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 .iter()
361 .filter_map(|ws| ws.read(cx).database_id())
362 .collect();
363
364 let workspace = multi_workspace.workspace().clone();
365 workspace.update(cx, |workspace, cx| {
366 let Some(recent_projects) =
367 workspace.active_modal::<RecentProjects>(cx)
368 else {
369 let focus_handle = workspace.focus_handle(cx);
370 RecentProjects::open(
371 workspace,
372 create_new_window,
373 sibling_workspace_ids,
374 window,
375 focus_handle,
376 cx,
377 );
378 return;
379 };
380
381 recent_projects.update(cx, |recent_projects, cx| {
382 recent_projects
383 .picker
384 .update(cx, |picker, cx| picker.cycle_selection(window, cx))
385 });
386 });
387 })
388 .log_err();
389 });
390 }
391 None => {
392 with_active_or_new_workspace(cx, move |workspace, window, cx| {
393 let Some(recent_projects) = workspace.active_modal::<RecentProjects>(cx) else {
394 let focus_handle = workspace.focus_handle(cx);
395 RecentProjects::open(
396 workspace,
397 create_new_window,
398 HashSet::new(),
399 window,
400 focus_handle,
401 cx,
402 );
403 return;
404 };
405
406 recent_projects.update(cx, |recent_projects, cx| {
407 recent_projects
408 .picker
409 .update(cx, |picker, cx| picker.cycle_selection(window, cx))
410 });
411 });
412 }
413 }
414 });
415 cx.on_action(|open_remote: &OpenRemote, cx| {
416 let from_existing_connection = open_remote.from_existing_connection;
417 let create_new_window = open_remote.create_new_window;
418 with_active_or_new_workspace(cx, move |workspace, window, cx| {
419 if from_existing_connection {
420 cx.propagate();
421 return;
422 }
423 let handle = cx.entity().downgrade();
424 let fs = workspace.project().read(cx).fs().clone();
425 workspace.toggle_modal(window, cx, |window, cx| {
426 RemoteServerProjects::new(create_new_window, fs, window, handle, cx)
427 })
428 });
429 });
430
431 cx.observe_new(DisconnectedOverlay::register).detach();
432
433 cx.on_action(|_: &OpenDevContainer, cx| {
434 with_active_or_new_workspace(cx, move |workspace, window, cx| {
435 if !workspace.project().read(cx).is_local() {
436 cx.spawn_in(window, async move |_, cx| {
437 cx.prompt(
438 gpui::PromptLevel::Critical,
439 "Cannot open Dev Container from remote project",
440 None,
441 &["Ok"],
442 )
443 .await
444 .ok();
445 })
446 .detach();
447 return;
448 }
449
450 let fs = workspace.project().read(cx).fs().clone();
451 let configs = find_devcontainer_configs(workspace, cx);
452 let app_state = workspace.app_state().clone();
453 let dev_container_context = DevContainerContext::from_workspace(workspace, cx);
454 let handle = cx.entity().downgrade();
455 workspace.toggle_modal(window, cx, |window, cx| {
456 RemoteServerProjects::new_dev_container(
457 fs,
458 configs,
459 app_state,
460 dev_container_context,
461 window,
462 handle,
463 cx,
464 )
465 });
466 });
467 });
468
469 // Subscribe to worktree additions to suggest opening the project in a dev container
470 cx.observe_new(
471 |workspace: &mut Workspace, window: Option<&mut Window>, cx: &mut Context<Workspace>| {
472 let Some(window) = window else {
473 return;
474 };
475 cx.subscribe_in(
476 workspace.project(),
477 window,
478 move |_, project, event, window, cx| {
479 if let project::Event::WorktreeUpdatedEntries(worktree_id, updated_entries) =
480 event
481 {
482 dev_container_suggest::suggest_on_worktree_updated(
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 .iter()
1116 .find(|ws| ws.read(cx).database_id() == Some(workspace_id))
1117 .cloned();
1118 if let Some(workspace) = workspace {
1119 multi_workspace.activate(workspace, window, cx);
1120 }
1121 })
1122 .log_err();
1123 });
1124 }
1125 cx.emit(DismissEvent);
1126 }
1127 Some(ProjectPickerEntry::RecentProject(selected_match)) => {
1128 let Some(workspace) = self.workspace.upgrade() else {
1129 return;
1130 };
1131 let Some((
1132 candidate_workspace_id,
1133 candidate_workspace_location,
1134 candidate_workspace_paths,
1135 _,
1136 )) = self.workspaces.get(selected_match.candidate_id)
1137 else {
1138 return;
1139 };
1140
1141 let replace_current_window = self.create_new_window == secondary;
1142 let candidate_workspace_id = *candidate_workspace_id;
1143 let candidate_workspace_location = candidate_workspace_location.clone();
1144 let candidate_workspace_paths = candidate_workspace_paths.clone();
1145
1146 workspace.update(cx, |workspace, cx| {
1147 if workspace.database_id() == Some(candidate_workspace_id) {
1148 return;
1149 }
1150 match candidate_workspace_location {
1151 SerializedWorkspaceLocation::Local => {
1152 let paths = candidate_workspace_paths.paths().to_vec();
1153 if replace_current_window {
1154 if let Some(handle) =
1155 window.window_handle().downcast::<MultiWorkspace>()
1156 {
1157 cx.defer(move |cx| {
1158 if let Some(task) = handle
1159 .update(cx, |multi_workspace, window, cx| {
1160 multi_workspace.open_project(
1161 paths,
1162 OpenMode::Replace,
1163 window,
1164 cx,
1165 )
1166 })
1167 .log_err()
1168 {
1169 task.detach_and_log_err(cx);
1170 }
1171 });
1172 }
1173 return;
1174 } else {
1175 workspace
1176 .open_workspace_for_paths(
1177 OpenMode::NewWindow,
1178 paths,
1179 window,
1180 cx,
1181 )
1182 .detach_and_prompt_err(
1183 "Failed to open project",
1184 window,
1185 cx,
1186 |_, _, _| None,
1187 );
1188 }
1189 }
1190 SerializedWorkspaceLocation::Remote(mut connection) => {
1191 let app_state = workspace.app_state().clone();
1192 let replace_window = if replace_current_window {
1193 window.window_handle().downcast::<MultiWorkspace>()
1194 } else {
1195 None
1196 };
1197 let open_options = OpenOptions {
1198 requesting_window: replace_window,
1199 ..Default::default()
1200 };
1201 if let RemoteConnectionOptions::Ssh(connection) = &mut connection {
1202 RemoteSettings::get_global(cx)
1203 .fill_connection_options_from_settings(connection);
1204 };
1205 let paths = candidate_workspace_paths.paths().to_vec();
1206 cx.spawn_in(window, async move |_, cx| {
1207 open_remote_project(
1208 connection.clone(),
1209 paths,
1210 app_state,
1211 open_options,
1212 cx,
1213 )
1214 .await
1215 })
1216 .detach_and_prompt_err(
1217 "Failed to open project",
1218 window,
1219 cx,
1220 |_, _, _| None,
1221 );
1222 }
1223 }
1224 });
1225 cx.emit(DismissEvent);
1226 }
1227 _ => {}
1228 }
1229 }
1230
1231 fn dismissed(&mut self, _window: &mut Window, _: &mut Context<Picker<Self>>) {}
1232
1233 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
1234 let text = if self.workspaces.is_empty() && self.open_folders.is_empty() {
1235 "Recently opened projects will show up here".into()
1236 } else {
1237 "No matches".into()
1238 };
1239 Some(text)
1240 }
1241
1242 fn render_match(
1243 &self,
1244 ix: usize,
1245 selected: bool,
1246 window: &mut Window,
1247 cx: &mut Context<Picker<Self>>,
1248 ) -> Option<Self::ListItem> {
1249 match self.filtered_entries.get(ix)? {
1250 ProjectPickerEntry::Header(title) => Some(
1251 v_flex()
1252 .w_full()
1253 .gap_1()
1254 .when(ix > 0, |this| this.mt_1().child(Divider::horizontal()))
1255 .child(ListSubHeader::new(title.clone()).inset(true))
1256 .into_any_element(),
1257 ),
1258 ProjectPickerEntry::OpenFolder { index, positions } => {
1259 let folder = self.open_folders.get(*index)?;
1260 let name = folder.name.clone();
1261 let path = folder.path.compact();
1262 let branch = folder.branch.clone();
1263 let is_active = folder.is_active;
1264 let worktree_id = folder.worktree_id;
1265 let positions = positions.clone();
1266 let show_path = self.style == ProjectPickerStyle::Modal;
1267
1268 let secondary_actions = h_flex()
1269 .gap_1()
1270 .child(
1271 IconButton::new(("remove-folder", worktree_id.to_usize()), IconName::Close)
1272 .icon_size(IconSize::Small)
1273 .tooltip(Tooltip::text("Remove Folder from Workspace"))
1274 .on_click(cx.listener(move |picker, _, window, cx| {
1275 let Some(workspace) = picker.delegate.workspace.upgrade() else {
1276 return;
1277 };
1278 workspace.update(cx, |workspace, cx| {
1279 let project = workspace.project().clone();
1280 project.update(cx, |project, cx| {
1281 project.remove_worktree(worktree_id, cx);
1282 });
1283 });
1284 picker.delegate.open_folders =
1285 get_open_folders(workspace.read(cx), cx);
1286 let query = picker.query(cx);
1287 picker.update_matches(query, window, cx);
1288 })),
1289 )
1290 .into_any_element();
1291
1292 let icon = icon_for_remote_connection(self.project_connection_options.as_ref());
1293
1294 Some(
1295 ListItem::new(ix)
1296 .toggle_state(selected)
1297 .inset(true)
1298 .spacing(ListItemSpacing::Sparse)
1299 .child(
1300 h_flex()
1301 .id("open_folder_item")
1302 .gap_3()
1303 .flex_grow()
1304 .when(self.has_any_non_local_projects, |this| {
1305 this.child(Icon::new(icon).color(Color::Muted))
1306 })
1307 .child(
1308 v_flex()
1309 .child(
1310 h_flex()
1311 .gap_1()
1312 .child({
1313 let highlighted = HighlightedMatch {
1314 text: name.to_string(),
1315 highlight_positions: positions,
1316 color: Color::Default,
1317 };
1318 highlighted.render(window, cx)
1319 })
1320 .when_some(branch, |this, branch| {
1321 this.child(
1322 Label::new(branch).color(Color::Muted),
1323 )
1324 })
1325 .when(is_active, |this| {
1326 this.child(
1327 Icon::new(IconName::Check)
1328 .size(IconSize::Small)
1329 .color(Color::Accent),
1330 )
1331 }),
1332 )
1333 .when(show_path, |this| {
1334 this.child(
1335 Label::new(path.to_string_lossy().to_string())
1336 .size(LabelSize::Small)
1337 .color(Color::Muted),
1338 )
1339 }),
1340 )
1341 .when(!show_path, |this| {
1342 this.tooltip(Tooltip::text(path.to_string_lossy().to_string()))
1343 }),
1344 )
1345 .end_slot(secondary_actions)
1346 .show_end_slot_on_hover()
1347 .into_any_element(),
1348 )
1349 }
1350 ProjectPickerEntry::OpenProject(hit) => {
1351 let (workspace_id, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1352 let workspace_id = *workspace_id;
1353 let ordered_paths: Vec<_> = paths
1354 .ordered_paths()
1355 .map(|p| p.compact().to_string_lossy().to_string())
1356 .collect();
1357 let tooltip_path: SharedString = match &location {
1358 SerializedWorkspaceLocation::Remote(options) => {
1359 let host = options.display_name();
1360 if ordered_paths.len() == 1 {
1361 format!("{} ({})", ordered_paths[0], host).into()
1362 } else {
1363 format!("{}\n({})", ordered_paths.join("\n"), host).into()
1364 }
1365 }
1366 _ => ordered_paths.join("\n").into(),
1367 };
1368
1369 let mut path_start_offset = 0;
1370 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
1371 .ordered_paths()
1372 .map(|p| p.compact())
1373 .map(|path| {
1374 let highlighted_text =
1375 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
1376 path_start_offset += highlighted_text.1.text.len();
1377 highlighted_text
1378 })
1379 .unzip();
1380
1381 let prefix = match &location {
1382 SerializedWorkspaceLocation::Remote(options) => {
1383 Some(SharedString::from(options.display_name()))
1384 }
1385 _ => None,
1386 };
1387
1388 let highlighted_match = HighlightedMatchWithPaths {
1389 prefix,
1390 match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1391 paths,
1392 };
1393
1394 let icon = icon_for_remote_connection(match location {
1395 SerializedWorkspaceLocation::Local => None,
1396 SerializedWorkspaceLocation::Remote(options) => Some(options),
1397 });
1398
1399 let secondary_actions = h_flex()
1400 .gap_1()
1401 .child(
1402 IconButton::new("remove_open_project", IconName::Close)
1403 .icon_size(IconSize::Small)
1404 .tooltip(Tooltip::text("Remove Project from Window"))
1405 .on_click(cx.listener(move |picker, _, window, cx| {
1406 cx.stop_propagation();
1407 window.prevent_default();
1408 picker
1409 .delegate
1410 .remove_sibling_workspace(workspace_id, window, cx);
1411 let query = picker.query(cx);
1412 picker.update_matches(query, window, cx);
1413 })),
1414 )
1415 .into_any_element();
1416
1417 Some(
1418 ListItem::new(ix)
1419 .toggle_state(selected)
1420 .inset(true)
1421 .spacing(ListItemSpacing::Sparse)
1422 .child(
1423 h_flex()
1424 .id("open_project_info_container")
1425 .gap_3()
1426 .flex_grow()
1427 .when(self.has_any_non_local_projects, |this| {
1428 this.child(Icon::new(icon).color(Color::Muted))
1429 })
1430 .child({
1431 let mut highlighted = highlighted_match;
1432 if !self.render_paths {
1433 highlighted.paths.clear();
1434 }
1435 highlighted.render(window, cx)
1436 })
1437 .tooltip(Tooltip::text(tooltip_path)),
1438 )
1439 .end_slot(secondary_actions)
1440 .show_end_slot_on_hover()
1441 .into_any_element(),
1442 )
1443 }
1444 ProjectPickerEntry::RecentProject(hit) => {
1445 let (_, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1446 let is_local = matches!(location, SerializedWorkspaceLocation::Local);
1447 let paths_to_add = paths.paths().to_vec();
1448 let ordered_paths: Vec<_> = paths
1449 .ordered_paths()
1450 .map(|p| p.compact().to_string_lossy().to_string())
1451 .collect();
1452 let tooltip_path: SharedString = match &location {
1453 SerializedWorkspaceLocation::Remote(options) => {
1454 let host = options.display_name();
1455 if ordered_paths.len() == 1 {
1456 format!("{} ({})", ordered_paths[0], host).into()
1457 } else {
1458 format!("{}\n({})", ordered_paths.join("\n"), host).into()
1459 }
1460 }
1461 _ => ordered_paths.join("\n").into(),
1462 };
1463
1464 let mut path_start_offset = 0;
1465 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
1466 .ordered_paths()
1467 .map(|p| p.compact())
1468 .map(|path| {
1469 let highlighted_text =
1470 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
1471 path_start_offset += highlighted_text.1.text.len();
1472 highlighted_text
1473 })
1474 .unzip();
1475
1476 let prefix = match &location {
1477 SerializedWorkspaceLocation::Remote(options) => {
1478 Some(SharedString::from(options.display_name()))
1479 }
1480 _ => None,
1481 };
1482
1483 let highlighted_match = HighlightedMatchWithPaths {
1484 prefix,
1485 match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1486 paths,
1487 };
1488
1489 let focus_handle = self.focus_handle.clone();
1490
1491 let secondary_actions = h_flex()
1492 .gap_px()
1493 .when(is_local, |this| {
1494 this.child(
1495 IconButton::new("add_to_workspace", IconName::FolderPlus)
1496 .icon_size(IconSize::Small)
1497 .tooltip(Tooltip::text("Add Project to this Workspace"))
1498 .on_click({
1499 let paths_to_add = paths_to_add.clone();
1500 cx.listener(move |picker, _event, window, cx| {
1501 cx.stop_propagation();
1502 window.prevent_default();
1503 picker.delegate.add_project_to_workspace(
1504 paths_to_add.clone(),
1505 window,
1506 cx,
1507 );
1508 })
1509 }),
1510 )
1511 })
1512 .child(
1513 IconButton::new("open_new_window", IconName::ArrowUpRight)
1514 .icon_size(IconSize::XSmall)
1515 .tooltip({
1516 move |_, cx| {
1517 Tooltip::for_action_in(
1518 "Open Project in New Window",
1519 &menu::SecondaryConfirm,
1520 &focus_handle,
1521 cx,
1522 )
1523 }
1524 })
1525 .on_click(cx.listener(move |this, _event, window, cx| {
1526 cx.stop_propagation();
1527 window.prevent_default();
1528 this.delegate.set_selected_index(ix, window, cx);
1529 this.delegate.confirm(true, window, cx);
1530 })),
1531 )
1532 .child(
1533 IconButton::new("delete", IconName::Close)
1534 .icon_size(IconSize::Small)
1535 .tooltip(Tooltip::text("Delete from Recent Projects"))
1536 .on_click(cx.listener(move |this, _event, window, cx| {
1537 cx.stop_propagation();
1538 window.prevent_default();
1539 this.delegate.delete_recent_project(ix, window, cx)
1540 })),
1541 )
1542 .into_any_element();
1543
1544 let icon = icon_for_remote_connection(match location {
1545 SerializedWorkspaceLocation::Local => None,
1546 SerializedWorkspaceLocation::Remote(options) => Some(options),
1547 });
1548
1549 Some(
1550 ListItem::new(ix)
1551 .toggle_state(selected)
1552 .inset(true)
1553 .spacing(ListItemSpacing::Sparse)
1554 .child(
1555 h_flex()
1556 .id("project_info_container")
1557 .gap_3()
1558 .flex_grow()
1559 .when(self.has_any_non_local_projects, |this| {
1560 this.child(Icon::new(icon).color(Color::Muted))
1561 })
1562 .child({
1563 let mut highlighted = highlighted_match;
1564 if !self.render_paths {
1565 highlighted.paths.clear();
1566 }
1567 highlighted.render(window, cx)
1568 })
1569 .tooltip(Tooltip::text(tooltip_path)),
1570 )
1571 .end_slot(secondary_actions)
1572 .show_end_slot_on_hover()
1573 .into_any_element(),
1574 )
1575 }
1576 }
1577 }
1578
1579 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1580 let focus_handle = self.focus_handle.clone();
1581 let popover_style = matches!(self.style, ProjectPickerStyle::Popover);
1582 let is_already_open_entry = matches!(
1583 self.filtered_entries.get(self.selected_index),
1584 Some(ProjectPickerEntry::OpenFolder { .. } | ProjectPickerEntry::OpenProject(_))
1585 );
1586
1587 if popover_style {
1588 return Some(
1589 v_flex()
1590 .flex_1()
1591 .p_1p5()
1592 .gap_1()
1593 .border_t_1()
1594 .border_color(cx.theme().colors().border_variant)
1595 .child({
1596 let open_action = workspace::Open::default();
1597 Button::new("open_local_folder", "Open Local Project")
1598 .key_binding(KeyBinding::for_action_in(&open_action, &focus_handle, cx))
1599 .on_click(move |_, window, cx| {
1600 window.dispatch_action(open_action.boxed_clone(), cx)
1601 })
1602 })
1603 .child(
1604 Button::new("open_remote_folder", "Open Remote Project")
1605 .key_binding(KeyBinding::for_action(
1606 &OpenRemote {
1607 from_existing_connection: false,
1608 create_new_window: false,
1609 },
1610 cx,
1611 ))
1612 .on_click(|_, window, cx| {
1613 window.dispatch_action(
1614 OpenRemote {
1615 from_existing_connection: false,
1616 create_new_window: false,
1617 }
1618 .boxed_clone(),
1619 cx,
1620 )
1621 }),
1622 )
1623 .into_any(),
1624 );
1625 }
1626
1627 let selected_entry = self.filtered_entries.get(self.selected_index);
1628
1629 let secondary_footer_actions: Option<AnyElement> = match selected_entry {
1630 Some(ProjectPickerEntry::OpenFolder { .. } | ProjectPickerEntry::OpenProject(_)) => {
1631 let label = if matches!(selected_entry, Some(ProjectPickerEntry::OpenFolder { .. }))
1632 {
1633 "Remove Folder"
1634 } else {
1635 "Remove from Window"
1636 };
1637 Some(
1638 Button::new("remove_selected", label)
1639 .key_binding(KeyBinding::for_action_in(
1640 &RemoveSelected,
1641 &focus_handle,
1642 cx,
1643 ))
1644 .on_click(|_, window, cx| {
1645 window.dispatch_action(RemoveSelected.boxed_clone(), cx)
1646 })
1647 .into_any_element(),
1648 )
1649 }
1650 Some(ProjectPickerEntry::RecentProject(_)) => Some(
1651 Button::new("delete_recent", "Delete")
1652 .key_binding(KeyBinding::for_action_in(
1653 &RemoveSelected,
1654 &focus_handle,
1655 cx,
1656 ))
1657 .on_click(|_, window, cx| {
1658 window.dispatch_action(RemoveSelected.boxed_clone(), cx)
1659 })
1660 .into_any_element(),
1661 ),
1662 _ => None,
1663 };
1664
1665 Some(
1666 h_flex()
1667 .flex_1()
1668 .p_1p5()
1669 .gap_1()
1670 .justify_end()
1671 .border_t_1()
1672 .border_color(cx.theme().colors().border_variant)
1673 .when_some(secondary_footer_actions, |this, actions| {
1674 this.child(actions)
1675 })
1676 .map(|this| {
1677 if is_already_open_entry {
1678 this.child(
1679 Button::new("activate", "Activate")
1680 .key_binding(KeyBinding::for_action_in(
1681 &menu::Confirm,
1682 &focus_handle,
1683 cx,
1684 ))
1685 .on_click(|_, window, cx| {
1686 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1687 }),
1688 )
1689 } else {
1690 this.child(
1691 Button::new("open_new_window", "New Window")
1692 .key_binding(KeyBinding::for_action_in(
1693 &menu::SecondaryConfirm,
1694 &focus_handle,
1695 cx,
1696 ))
1697 .on_click(|_, window, cx| {
1698 window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
1699 }),
1700 )
1701 .child(
1702 Button::new("open_here", "Open")
1703 .key_binding(KeyBinding::for_action_in(
1704 &menu::Confirm,
1705 &focus_handle,
1706 cx,
1707 ))
1708 .on_click(|_, window, cx| {
1709 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1710 }),
1711 )
1712 }
1713 })
1714 .child(Divider::vertical())
1715 .child(
1716 PopoverMenu::new("actions-menu-popover")
1717 .with_handle(self.actions_menu_handle.clone())
1718 .anchor(gpui::Corner::BottomRight)
1719 .offset(gpui::Point {
1720 x: px(0.0),
1721 y: px(-2.0),
1722 })
1723 .trigger(
1724 Button::new("actions-trigger", "Actions")
1725 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1726 .key_binding(KeyBinding::for_action_in(
1727 &ToggleActionsMenu,
1728 &focus_handle,
1729 cx,
1730 )),
1731 )
1732 .menu({
1733 let focus_handle = focus_handle.clone();
1734 let show_add_to_workspace = match selected_entry {
1735 Some(ProjectPickerEntry::RecentProject(hit)) => self
1736 .workspaces
1737 .get(hit.candidate_id)
1738 .map(|(_, loc, ..)| {
1739 matches!(loc, SerializedWorkspaceLocation::Local)
1740 })
1741 .unwrap_or(false),
1742 _ => false,
1743 };
1744
1745 move |window, cx| {
1746 Some(ContextMenu::build(window, cx, {
1747 let focus_handle = focus_handle.clone();
1748 move |menu, _, _| {
1749 menu.context(focus_handle)
1750 .when(show_add_to_workspace, |menu| {
1751 menu.action(
1752 "Add to Workspace",
1753 AddToWorkspace.boxed_clone(),
1754 )
1755 .separator()
1756 })
1757 .action(
1758 "Open Local Project",
1759 workspace::Open::default().boxed_clone(),
1760 )
1761 .action(
1762 "Open Remote Project",
1763 OpenRemote {
1764 from_existing_connection: false,
1765 create_new_window: false,
1766 }
1767 .boxed_clone(),
1768 )
1769 }
1770 }))
1771 }
1772 }),
1773 )
1774 .into_any(),
1775 )
1776 }
1777}
1778
1779pub(crate) fn icon_for_remote_connection(options: Option<&RemoteConnectionOptions>) -> IconName {
1780 match options {
1781 None => IconName::Screen,
1782 Some(options) => match options {
1783 RemoteConnectionOptions::Ssh(_) => IconName::Server,
1784 RemoteConnectionOptions::Wsl(_) => IconName::Linux,
1785 RemoteConnectionOptions::Docker(_) => IconName::Box,
1786 #[cfg(any(test, feature = "test-support"))]
1787 RemoteConnectionOptions::Mock(_) => IconName::Server,
1788 },
1789 }
1790}
1791
1792// Compute the highlighted text for the name and path
1793pub(crate) fn highlights_for_path(
1794 path: &Path,
1795 match_positions: &Vec<usize>,
1796 path_start_offset: usize,
1797) -> (Option<HighlightedMatch>, HighlightedMatch) {
1798 let path_string = path.to_string_lossy();
1799 let path_text = path_string.to_string();
1800 let path_byte_len = path_text.len();
1801 // Get the subset of match highlight positions that line up with the given path.
1802 // Also adjusts them to start at the path start
1803 let path_positions = match_positions
1804 .iter()
1805 .copied()
1806 .skip_while(|position| *position < path_start_offset)
1807 .take_while(|position| *position < path_start_offset + path_byte_len)
1808 .map(|position| position - path_start_offset)
1809 .collect::<Vec<_>>();
1810
1811 // Again subset the highlight positions to just those that line up with the file_name
1812 // again adjusted to the start of the file_name
1813 let file_name_text_and_positions = path.file_name().map(|file_name| {
1814 let file_name_text = file_name.to_string_lossy().into_owned();
1815 let file_name_start_byte = path_byte_len - file_name_text.len();
1816 let highlight_positions = path_positions
1817 .iter()
1818 .copied()
1819 .skip_while(|position| *position < file_name_start_byte)
1820 .take_while(|position| *position < file_name_start_byte + file_name_text.len())
1821 .map(|position| position - file_name_start_byte)
1822 .collect::<Vec<_>>();
1823 HighlightedMatch {
1824 text: file_name_text,
1825 highlight_positions,
1826 color: Color::Default,
1827 }
1828 });
1829
1830 (
1831 file_name_text_and_positions,
1832 HighlightedMatch {
1833 text: path_text,
1834 highlight_positions: path_positions,
1835 color: Color::Default,
1836 },
1837 )
1838}
1839impl RecentProjectsDelegate {
1840 fn add_project_to_workspace(
1841 &mut self,
1842 paths: Vec<PathBuf>,
1843 window: &mut Window,
1844 cx: &mut Context<Picker<Self>>,
1845 ) {
1846 let Some(workspace) = self.workspace.upgrade() else {
1847 return;
1848 };
1849 let open_paths_task = workspace.update(cx, |workspace, cx| {
1850 workspace.open_paths(
1851 paths,
1852 OpenOptions {
1853 visible: Some(OpenVisible::All),
1854 ..Default::default()
1855 },
1856 None,
1857 window,
1858 cx,
1859 )
1860 });
1861 cx.spawn_in(window, async move |picker, cx| {
1862 let _result = open_paths_task.await;
1863 picker
1864 .update_in(cx, |picker, window, cx| {
1865 let Some(workspace) = picker.delegate.workspace.upgrade() else {
1866 return;
1867 };
1868 picker.delegate.open_folders = get_open_folders(workspace.read(cx), cx);
1869 let query = picker.query(cx);
1870 picker.update_matches(query, window, cx);
1871 })
1872 .ok();
1873 })
1874 .detach();
1875 }
1876
1877 fn delete_recent_project(
1878 &self,
1879 ix: usize,
1880 window: &mut Window,
1881 cx: &mut Context<Picker<Self>>,
1882 ) {
1883 if let Some(ProjectPickerEntry::RecentProject(selected_match)) =
1884 self.filtered_entries.get(ix)
1885 {
1886 let (workspace_id, _, _, _) = &self.workspaces[selected_match.candidate_id];
1887 let workspace_id = *workspace_id;
1888 let fs = self
1889 .workspace
1890 .upgrade()
1891 .map(|ws| ws.read(cx).app_state().fs.clone());
1892 let db = WorkspaceDb::global(cx);
1893 cx.spawn_in(window, async move |this, cx| {
1894 db.delete_workspace_by_id(workspace_id).await.log_err();
1895 let Some(fs) = fs else { return };
1896 let workspaces = db
1897 .recent_workspaces_on_disk(fs.as_ref())
1898 .await
1899 .unwrap_or_default();
1900 let workspaces =
1901 workspace::resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
1902 this.update_in(cx, move |picker, window, cx| {
1903 picker.delegate.set_workspaces(workspaces);
1904 picker
1905 .delegate
1906 .set_selected_index(ix.saturating_sub(1), window, cx);
1907 picker.delegate.reset_selected_match_index = false;
1908 picker.update_matches(picker.query(cx), window, cx);
1909 // After deleting a project, we want to update the history manager to reflect the change.
1910 // But we do not emit a update event when user opens a project, because it's handled in `workspace::load_workspace`.
1911 if let Some(history_manager) = HistoryManager::global(cx) {
1912 history_manager
1913 .update(cx, |this, cx| this.delete_history(workspace_id, cx));
1914 }
1915 })
1916 .ok();
1917 })
1918 .detach();
1919 }
1920 }
1921
1922 fn remove_sibling_workspace(
1923 &mut self,
1924 workspace_id: WorkspaceId,
1925 window: &mut Window,
1926 cx: &mut Context<Picker<Self>>,
1927 ) {
1928 if let Some(handle) = window.window_handle().downcast::<MultiWorkspace>() {
1929 cx.defer(move |cx| {
1930 handle
1931 .update(cx, |multi_workspace, window, cx| {
1932 let workspace = multi_workspace
1933 .workspaces()
1934 .iter()
1935 .find(|ws| ws.read(cx).database_id() == Some(workspace_id))
1936 .cloned();
1937 if let Some(workspace) = workspace {
1938 multi_workspace.remove(&workspace, window, cx);
1939 }
1940 })
1941 .log_err();
1942 });
1943 }
1944
1945 self.sibling_workspace_ids.remove(&workspace_id);
1946 }
1947
1948 fn is_current_workspace(
1949 &self,
1950 workspace_id: WorkspaceId,
1951 cx: &mut Context<Picker<Self>>,
1952 ) -> bool {
1953 if let Some(workspace) = self.workspace.upgrade() {
1954 let workspace = workspace.read(cx);
1955 if Some(workspace_id) == workspace.database_id() {
1956 return true;
1957 }
1958 }
1959
1960 false
1961 }
1962
1963 fn is_sibling_workspace(
1964 &self,
1965 workspace_id: WorkspaceId,
1966 cx: &mut Context<Picker<Self>>,
1967 ) -> bool {
1968 self.sibling_workspace_ids.contains(&workspace_id)
1969 && !self.is_current_workspace(workspace_id, cx)
1970 }
1971
1972 fn is_open_folder(&self, paths: &PathList) -> bool {
1973 if self.open_folders.is_empty() {
1974 return false;
1975 }
1976
1977 for workspace_path in paths.paths() {
1978 for open_folder in &self.open_folders {
1979 if workspace_path == &open_folder.path {
1980 return true;
1981 }
1982 }
1983 }
1984
1985 false
1986 }
1987
1988 fn is_valid_recent_candidate(
1989 &self,
1990 workspace_id: WorkspaceId,
1991 paths: &PathList,
1992 cx: &mut Context<Picker<Self>>,
1993 ) -> bool {
1994 !self.is_current_workspace(workspace_id, cx)
1995 && !self.is_sibling_workspace(workspace_id, cx)
1996 && !self.is_open_folder(paths)
1997 }
1998}
1999
2000#[cfg(test)]
2001mod tests {
2002 use std::path::PathBuf;
2003
2004 use editor::Editor;
2005 use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
2006
2007 use serde_json::json;
2008 use settings::SettingsStore;
2009 use util::path;
2010 use workspace::{AppState, open_paths};
2011
2012 use super::*;
2013
2014 #[gpui::test]
2015 async fn test_dirty_workspace_replaced_when_opening_recent_project(cx: &mut TestAppContext) {
2016 let app_state = init_test(cx);
2017
2018 cx.update(|cx| {
2019 SettingsStore::update_global(cx, |store, cx| {
2020 store.update_user_settings(cx, |settings| {
2021 settings
2022 .session
2023 .get_or_insert_default()
2024 .restore_unsaved_buffers = Some(false)
2025 });
2026 });
2027 });
2028
2029 app_state
2030 .fs
2031 .as_fake()
2032 .insert_tree(
2033 path!("/dir"),
2034 json!({
2035 "main.ts": "a"
2036 }),
2037 )
2038 .await;
2039 app_state
2040 .fs
2041 .as_fake()
2042 .insert_tree(path!("/test/path"), json!({}))
2043 .await;
2044 cx.update(|cx| {
2045 open_paths(
2046 &[PathBuf::from(path!("/dir/main.ts"))],
2047 app_state,
2048 workspace::OpenOptions::default(),
2049 cx,
2050 )
2051 })
2052 .await
2053 .unwrap();
2054 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2055
2056 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2057 multi_workspace
2058 .update(cx, |multi_workspace, _, cx| {
2059 assert!(!multi_workspace.workspace().read(cx).is_edited())
2060 })
2061 .unwrap();
2062
2063 let editor = multi_workspace
2064 .read_with(cx, |multi_workspace, cx| {
2065 multi_workspace
2066 .workspace()
2067 .read(cx)
2068 .active_item(cx)
2069 .unwrap()
2070 .downcast::<Editor>()
2071 .unwrap()
2072 })
2073 .unwrap();
2074 multi_workspace
2075 .update(cx, |_, window, cx| {
2076 editor.update(cx, |editor, cx| editor.insert("EDIT", window, cx));
2077 })
2078 .unwrap();
2079 multi_workspace
2080 .update(cx, |multi_workspace, _, cx| {
2081 assert!(
2082 multi_workspace.workspace().read(cx).is_edited(),
2083 "After inserting more text into the editor without saving, we should have a dirty project"
2084 )
2085 })
2086 .unwrap();
2087
2088 let recent_projects_picker = open_recent_projects(&multi_workspace, cx);
2089 multi_workspace
2090 .update(cx, |_, _, cx| {
2091 recent_projects_picker.update(cx, |picker, cx| {
2092 assert_eq!(picker.query(cx), "");
2093 let delegate = &mut picker.delegate;
2094 delegate.set_workspaces(vec![(
2095 WorkspaceId::default(),
2096 SerializedWorkspaceLocation::Local,
2097 PathList::new(&[path!("/test/path")]),
2098 Utc::now(),
2099 )]);
2100 delegate.filtered_entries =
2101 vec![ProjectPickerEntry::RecentProject(StringMatch {
2102 candidate_id: 0,
2103 score: 1.0,
2104 positions: Vec::new(),
2105 string: "fake candidate".to_string(),
2106 })];
2107 });
2108 })
2109 .unwrap();
2110
2111 assert!(
2112 !cx.has_pending_prompt(),
2113 "Should have no pending prompt on dirty project before opening the new recent project"
2114 );
2115 let dirty_workspace = multi_workspace
2116 .read_with(cx, |multi_workspace, _cx| {
2117 multi_workspace.workspace().clone()
2118 })
2119 .unwrap();
2120
2121 cx.dispatch_action(*multi_workspace, menu::Confirm);
2122 cx.run_until_parked();
2123
2124 // prepare_to_close triggers a save prompt for the dirty buffer.
2125 // Choose "Don't Save" (index 2) to discard and continue replacing.
2126 assert!(
2127 cx.has_pending_prompt(),
2128 "Should prompt to save dirty buffer before replacing workspace"
2129 );
2130 cx.simulate_prompt_answer("Don't Save");
2131 cx.run_until_parked();
2132
2133 multi_workspace
2134 .update(cx, |multi_workspace, _, cx| {
2135 assert!(
2136 multi_workspace
2137 .workspace()
2138 .read(cx)
2139 .active_modal::<RecentProjects>(cx)
2140 .is_none(),
2141 "Should remove the modal after selecting new recent project"
2142 );
2143
2144 assert!(
2145 !multi_workspace.workspaces().contains(&dirty_workspace),
2146 "The original dirty workspace should have been replaced"
2147 );
2148
2149 assert!(
2150 !multi_workspace.workspace().read(cx).is_edited(),
2151 "The active workspace should be the freshly opened one, not dirty"
2152 );
2153 })
2154 .unwrap();
2155 }
2156
2157 fn open_recent_projects(
2158 multi_workspace: &WindowHandle<MultiWorkspace>,
2159 cx: &mut TestAppContext,
2160 ) -> Entity<Picker<RecentProjectsDelegate>> {
2161 cx.dispatch_action(
2162 (*multi_workspace).into(),
2163 OpenRecent {
2164 create_new_window: false,
2165 },
2166 );
2167 multi_workspace
2168 .update(cx, |multi_workspace, _, cx| {
2169 multi_workspace
2170 .workspace()
2171 .read(cx)
2172 .active_modal::<RecentProjects>(cx)
2173 .unwrap()
2174 .read(cx)
2175 .picker
2176 .clone()
2177 })
2178 .unwrap()
2179 }
2180
2181 #[gpui::test]
2182 async fn test_open_dev_container_action_with_single_config(cx: &mut TestAppContext) {
2183 let app_state = init_test(cx);
2184
2185 app_state
2186 .fs
2187 .as_fake()
2188 .insert_tree(
2189 path!("/project"),
2190 json!({
2191 ".devcontainer": {
2192 "devcontainer.json": "{}"
2193 },
2194 "src": {
2195 "main.rs": "fn main() {}"
2196 }
2197 }),
2198 )
2199 .await;
2200
2201 // Open a file path (not a directory) so that the worktree root is a
2202 // file. This means `active_project_directory` returns `None`, which
2203 // causes `DevContainerContext::from_workspace` to return `None`,
2204 // preventing `open_dev_container` from spawning real I/O (docker
2205 // commands, shell environment loading) that is incompatible with the
2206 // test scheduler. The modal is still created and the re-entrancy
2207 // guard that this test validates is still exercised.
2208 cx.update(|cx| {
2209 open_paths(
2210 &[PathBuf::from(path!("/project/src/main.rs"))],
2211 app_state,
2212 workspace::OpenOptions::default(),
2213 cx,
2214 )
2215 })
2216 .await
2217 .unwrap();
2218
2219 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2220 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2221
2222 cx.run_until_parked();
2223
2224 // This dispatch triggers with_active_or_new_workspace -> MultiWorkspace::update
2225 // -> Workspace::update -> toggle_modal -> new_dev_container.
2226 // Before the fix, this panicked with "cannot read workspace::Workspace while
2227 // it is already being updated" because new_dev_container and open_dev_container
2228 // tried to read the Workspace entity through a WeakEntity handle while it was
2229 // already leased by the outer update.
2230 cx.dispatch_action(*multi_workspace, OpenDevContainer);
2231
2232 multi_workspace
2233 .update(cx, |multi_workspace, _, cx| {
2234 let modal = multi_workspace
2235 .workspace()
2236 .read(cx)
2237 .active_modal::<RemoteServerProjects>(cx);
2238 assert!(
2239 modal.is_some(),
2240 "Dev container modal should be open after dispatching OpenDevContainer"
2241 );
2242 })
2243 .unwrap();
2244 }
2245
2246 #[gpui::test]
2247 async fn test_open_dev_container_action_with_multiple_configs(cx: &mut TestAppContext) {
2248 let app_state = init_test(cx);
2249
2250 app_state
2251 .fs
2252 .as_fake()
2253 .insert_tree(
2254 path!("/project"),
2255 json!({
2256 ".devcontainer": {
2257 "rust": {
2258 "devcontainer.json": "{}"
2259 },
2260 "python": {
2261 "devcontainer.json": "{}"
2262 }
2263 },
2264 "src": {
2265 "main.rs": "fn main() {}"
2266 }
2267 }),
2268 )
2269 .await;
2270
2271 cx.update(|cx| {
2272 open_paths(
2273 &[PathBuf::from(path!("/project"))],
2274 app_state,
2275 workspace::OpenOptions::default(),
2276 cx,
2277 )
2278 })
2279 .await
2280 .unwrap();
2281
2282 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2283 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2284
2285 cx.run_until_parked();
2286
2287 cx.dispatch_action(*multi_workspace, OpenDevContainer);
2288
2289 multi_workspace
2290 .update(cx, |multi_workspace, _, cx| {
2291 let modal = multi_workspace
2292 .workspace()
2293 .read(cx)
2294 .active_modal::<RemoteServerProjects>(cx);
2295 assert!(
2296 modal.is_some(),
2297 "Dev container modal should be open after dispatching OpenDevContainer with multiple configs"
2298 );
2299 })
2300 .unwrap();
2301 }
2302
2303 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
2304 cx.update(|cx| {
2305 let state = AppState::test(cx);
2306 crate::init(cx);
2307 editor::init(cx);
2308 state
2309 })
2310 }
2311}