1use anyhow::Result;
2use fs::Fs;
3
4use gpui::{
5 AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
6 ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
7 actions, deferred, px,
8};
9pub use project::ProjectGroupKey;
10use project::{DisableAiSettings, Project};
11use release_channel::ReleaseChannel;
12use remote::RemoteConnectionOptions;
13use settings::Settings;
14pub use settings::SidebarSide;
15use std::future::Future;
16
17use std::path::PathBuf;
18use ui::prelude::*;
19use util::ResultExt;
20use util::path_list::PathList;
21use zed_actions::agents_sidebar::ToggleThreadSwitcher;
22
23use agent_settings::AgentSettings;
24use settings::SidebarDockPosition;
25use ui::{ContextMenu, right_click_menu};
26
27const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
28
29use crate::open_remote_project_with_existing_connection;
30use crate::{
31 CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
32 Panel, Workspace, WorkspaceId, client_side_decorations,
33 persistence::model::MultiWorkspaceState,
34};
35
36actions!(
37 multi_workspace,
38 [
39 /// Toggles the workspace switcher sidebar.
40 ToggleWorkspaceSidebar,
41 /// Closes the workspace sidebar.
42 CloseWorkspaceSidebar,
43 /// Moves focus to or from the workspace sidebar without closing it.
44 FocusWorkspaceSidebar,
45 /// Activates the next project in the sidebar.
46 NextProject,
47 /// Activates the previous project in the sidebar.
48 PreviousProject,
49 /// Activates the next thread in sidebar order.
50 NextThread,
51 /// Activates the previous thread in sidebar order.
52 PreviousThread,
53 /// Creates a new thread in the current workspace.
54 NewThread,
55 /// Moves the active project to a new window.
56 MoveProjectToNewWindow,
57 ]
58);
59
60#[derive(Default)]
61pub struct SidebarRenderState {
62 pub open: bool,
63 pub side: SidebarSide,
64}
65
66pub fn sidebar_side_context_menu(
67 id: impl Into<ElementId>,
68 cx: &App,
69) -> ui::RightClickMenu<ContextMenu> {
70 let current_position = AgentSettings::get_global(cx).sidebar_side;
71 right_click_menu(id).menu(move |window, cx| {
72 let fs = <dyn fs::Fs>::global(cx);
73 ContextMenu::build(window, cx, move |mut menu, _, _cx| {
74 let positions: [(SidebarDockPosition, &str); 2] = [
75 (SidebarDockPosition::Left, "Left"),
76 (SidebarDockPosition::Right, "Right"),
77 ];
78 for (position, label) in positions {
79 let fs = fs.clone();
80 menu = menu.toggleable_entry(
81 label,
82 position == current_position,
83 IconPosition::Start,
84 None,
85 move |_window, cx| {
86 let side = match position {
87 SidebarDockPosition::Left => "left",
88 SidebarDockPosition::Right => "right",
89 };
90 telemetry::event!("Sidebar Side Changed", side = side);
91 settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
92 settings
93 .agent
94 .get_or_insert_default()
95 .set_sidebar_side(position);
96 });
97 },
98 );
99 }
100 menu
101 })
102 })
103}
104
105pub enum MultiWorkspaceEvent {
106 ActiveWorkspaceChanged,
107 WorkspaceAdded(Entity<Workspace>),
108 WorkspaceRemoved(EntityId),
109 ProjectGroupsChanged,
110}
111
112pub enum SidebarEvent {
113 SerializeNeeded,
114}
115
116pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
117 fn width(&self, cx: &App) -> Pixels;
118 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
119 fn has_notifications(&self, cx: &App) -> bool;
120 fn side(&self, _cx: &App) -> SidebarSide;
121
122 fn is_threads_list_view_active(&self) -> bool {
123 true
124 }
125 /// Makes focus reset back to the search editor upon toggling the sidebar from outside
126 fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
127 /// Opens or cycles the thread switcher popup.
128 fn toggle_thread_switcher(
129 &mut self,
130 _select_last: bool,
131 _window: &mut Window,
132 _cx: &mut Context<Self>,
133 ) {
134 }
135
136 /// Activates the next or previous project.
137 fn cycle_project(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
138
139 /// Activates the next or previous thread in sidebar order.
140 fn cycle_thread(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
141
142 /// Return an opaque JSON blob of sidebar-specific state to persist.
143 fn serialized_state(&self, _cx: &App) -> Option<String> {
144 None
145 }
146
147 /// Restore sidebar state from a previously-serialized blob.
148 fn restore_serialized_state(
149 &mut self,
150 _state: &str,
151 _window: &mut Window,
152 _cx: &mut Context<Self>,
153 ) {
154 }
155}
156
157pub trait SidebarHandle: 'static + Send + Sync {
158 fn width(&self, cx: &App) -> Pixels;
159 fn set_width(&self, width: Option<Pixels>, cx: &mut App);
160 fn focus_handle(&self, cx: &App) -> FocusHandle;
161 fn focus(&self, window: &mut Window, cx: &mut App);
162 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
163 fn has_notifications(&self, cx: &App) -> bool;
164 fn to_any(&self) -> AnyView;
165 fn entity_id(&self) -> EntityId;
166 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
167 fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App);
168 fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App);
169
170 fn is_threads_list_view_active(&self, cx: &App) -> bool;
171
172 fn side(&self, cx: &App) -> SidebarSide;
173 fn serialized_state(&self, cx: &App) -> Option<String>;
174 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
175}
176
177#[derive(Clone)]
178pub struct DraggedSidebar;
179
180impl Render for DraggedSidebar {
181 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
182 gpui::Empty
183 }
184}
185
186impl<T: Sidebar> SidebarHandle for Entity<T> {
187 fn width(&self, cx: &App) -> Pixels {
188 self.read(cx).width(cx)
189 }
190
191 fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
192 self.update(cx, |this, cx| this.set_width(width, cx))
193 }
194
195 fn focus_handle(&self, cx: &App) -> FocusHandle {
196 self.read(cx).focus_handle(cx)
197 }
198
199 fn focus(&self, window: &mut Window, cx: &mut App) {
200 let handle = self.read(cx).focus_handle(cx);
201 window.focus(&handle, cx);
202 }
203
204 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
205 self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
206 }
207
208 fn has_notifications(&self, cx: &App) -> bool {
209 self.read(cx).has_notifications(cx)
210 }
211
212 fn to_any(&self) -> AnyView {
213 self.clone().into()
214 }
215
216 fn entity_id(&self) -> EntityId {
217 Entity::entity_id(self)
218 }
219
220 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
221 let entity = self.clone();
222 window.defer(cx, move |window, cx| {
223 entity.update(cx, |this, cx| {
224 this.toggle_thread_switcher(select_last, window, cx);
225 });
226 });
227 }
228
229 fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App) {
230 let entity = self.clone();
231 window.defer(cx, move |window, cx| {
232 entity.update(cx, |this, cx| {
233 this.cycle_project(forward, window, cx);
234 });
235 });
236 }
237
238 fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App) {
239 let entity = self.clone();
240 window.defer(cx, move |window, cx| {
241 entity.update(cx, |this, cx| {
242 this.cycle_thread(forward, window, cx);
243 });
244 });
245 }
246
247 fn is_threads_list_view_active(&self, cx: &App) -> bool {
248 self.read(cx).is_threads_list_view_active()
249 }
250
251 fn side(&self, cx: &App) -> SidebarSide {
252 self.read(cx).side(cx)
253 }
254
255 fn serialized_state(&self, cx: &App) -> Option<String> {
256 self.read(cx).serialized_state(cx)
257 }
258
259 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
260 self.update(cx, |this, cx| {
261 this.restore_serialized_state(state, window, cx)
262 })
263 }
264}
265
266#[derive(Clone)]
267pub struct ProjectGroup {
268 pub key: ProjectGroupKey,
269 pub workspaces: Vec<Entity<Workspace>>,
270 pub expanded: bool,
271}
272
273pub struct SerializedProjectGroupState {
274 pub key: ProjectGroupKey,
275 pub expanded: bool,
276}
277
278#[derive(Clone)]
279pub struct ProjectGroupState {
280 pub key: ProjectGroupKey,
281 pub expanded: bool,
282}
283
284pub struct MultiWorkspace {
285 window_id: WindowId,
286 retained_workspaces: Vec<Entity<Workspace>>,
287 project_groups: Vec<ProjectGroupState>,
288 active_workspace: Entity<Workspace>,
289 sidebar: Option<Box<dyn SidebarHandle>>,
290 sidebar_open: bool,
291 sidebar_overlay: Option<AnyView>,
292 pending_removal_tasks: Vec<Task<()>>,
293 _serialize_task: Option<Task<()>>,
294 _subscriptions: Vec<Subscription>,
295 previous_focus_handle: Option<FocusHandle>,
296}
297
298impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
299
300impl MultiWorkspace {
301 pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
302 self.sidebar
303 .as_ref()
304 .map_or(SidebarSide::Left, |s| s.side(cx))
305 }
306
307 pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
308 SidebarRenderState {
309 open: self.sidebar_open() && self.multi_workspace_enabled(cx),
310 side: self.sidebar_side(cx),
311 }
312 }
313
314 pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
315 let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
316 if let Some(task) = this._serialize_task.take() {
317 task.detach();
318 }
319 for task in std::mem::take(&mut this.pending_removal_tasks) {
320 task.detach();
321 }
322 });
323 let quit_subscription = cx.on_app_quit(Self::app_will_quit);
324 let settings_subscription = cx.observe_global_in::<settings::SettingsStore>(window, {
325 let mut previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
326 move |this, window, cx| {
327 if DisableAiSettings::get_global(cx).disable_ai != previous_disable_ai {
328 this.collapse_to_single_workspace(window, cx);
329 previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
330 }
331 }
332 });
333 Self::subscribe_to_workspace(&workspace, window, cx);
334 let weak_self = cx.weak_entity();
335 workspace.update(cx, |workspace, cx| {
336 workspace.set_multi_workspace(weak_self, cx);
337 });
338 Self {
339 window_id: window.window_handle().window_id(),
340 retained_workspaces: Vec::new(),
341 project_groups: Vec::new(),
342 active_workspace: workspace,
343 sidebar: None,
344 sidebar_open: false,
345 sidebar_overlay: None,
346 pending_removal_tasks: Vec::new(),
347 _serialize_task: None,
348 _subscriptions: vec![
349 release_subscription,
350 quit_subscription,
351 settings_subscription,
352 ],
353 previous_focus_handle: None,
354 }
355 }
356
357 pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
358 self._subscriptions
359 .push(cx.observe(&sidebar, |_this, _, cx| {
360 cx.notify();
361 }));
362 self._subscriptions
363 .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
364 SidebarEvent::SerializeNeeded => {
365 this.serialize(cx);
366 }
367 }));
368 self.sidebar = Some(Box::new(sidebar));
369 }
370
371 pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
372 self.sidebar.as_deref()
373 }
374
375 pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
376 self.sidebar_overlay = overlay;
377 cx.notify();
378 }
379
380 pub fn sidebar_open(&self) -> bool {
381 self.sidebar_open
382 }
383
384 pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
385 self.sidebar
386 .as_ref()
387 .map_or(false, |s| s.has_notifications(cx))
388 }
389
390 pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
391 self.sidebar
392 .as_ref()
393 .map_or(false, |s| s.is_threads_list_view_active(cx))
394 }
395
396 pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
397 !matches!(ReleaseChannel::try_global(cx), Some(ReleaseChannel::Stable))
398 && !DisableAiSettings::get_global(cx).disable_ai
399 }
400
401 pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
402 if !self.multi_workspace_enabled(cx) {
403 return;
404 }
405
406 if self.sidebar_open() {
407 self.close_sidebar(window, cx);
408 } else {
409 self.previous_focus_handle = window.focused(cx);
410 self.open_sidebar(cx);
411 if let Some(sidebar) = &self.sidebar {
412 sidebar.prepare_for_focus(window, cx);
413 sidebar.focus(window, cx);
414 }
415 }
416 }
417
418 pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
419 if !self.multi_workspace_enabled(cx) {
420 return;
421 }
422
423 if self.sidebar_open() {
424 self.close_sidebar(window, cx);
425 }
426 }
427
428 pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
429 if !self.multi_workspace_enabled(cx) {
430 return;
431 }
432
433 if self.sidebar_open() {
434 let sidebar_is_focused = self
435 .sidebar
436 .as_ref()
437 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
438
439 if sidebar_is_focused {
440 self.restore_previous_focus(false, window, cx);
441 } else {
442 self.previous_focus_handle = window.focused(cx);
443 if let Some(sidebar) = &self.sidebar {
444 sidebar.prepare_for_focus(window, cx);
445 sidebar.focus(window, cx);
446 }
447 }
448 } else {
449 self.previous_focus_handle = window.focused(cx);
450 self.open_sidebar(cx);
451 if let Some(sidebar) = &self.sidebar {
452 sidebar.prepare_for_focus(window, cx);
453 sidebar.focus(window, cx);
454 }
455 }
456 }
457
458 pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
459 let side = match self.sidebar_side(cx) {
460 SidebarSide::Left => "left",
461 SidebarSide::Right => "right",
462 };
463 telemetry::event!("Sidebar Toggled", action = "open", side = side);
464 self.apply_open_sidebar(cx);
465 }
466
467 /// Restores the sidebar to open state from persisted session data without
468 /// firing a telemetry event, since this is not a user-initiated action.
469 pub(crate) fn restore_open_sidebar(&mut self, cx: &mut Context<Self>) {
470 self.apply_open_sidebar(cx);
471 }
472
473 fn apply_open_sidebar(&mut self, cx: &mut Context<Self>) {
474 self.sidebar_open = true;
475 self.retain_active_workspace(cx);
476 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
477 for workspace in self.retained_workspaces.clone() {
478 workspace.update(cx, |workspace, _cx| {
479 workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
480 });
481 }
482 self.serialize(cx);
483 cx.notify();
484 }
485
486 pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
487 let side = match self.sidebar_side(cx) {
488 SidebarSide::Left => "left",
489 SidebarSide::Right => "right",
490 };
491 telemetry::event!("Sidebar Toggled", action = "close", side = side);
492 self.sidebar_open = false;
493 for workspace in self.retained_workspaces.clone() {
494 workspace.update(cx, |workspace, _cx| {
495 workspace.set_sidebar_focus_handle(None);
496 });
497 }
498 let sidebar_has_focus = self
499 .sidebar
500 .as_ref()
501 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
502 if sidebar_has_focus {
503 self.restore_previous_focus(true, window, cx);
504 } else {
505 self.previous_focus_handle.take();
506 }
507 self.serialize(cx);
508 cx.notify();
509 }
510
511 fn restore_previous_focus(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
512 let focus_handle = if clear {
513 self.previous_focus_handle.take()
514 } else {
515 self.previous_focus_handle.clone()
516 };
517
518 if let Some(previous_focus) = focus_handle {
519 previous_focus.focus(window, cx);
520 } else {
521 let pane = self.workspace().read(cx).active_pane().clone();
522 window.focus(&pane.read(cx).focus_handle(cx), cx);
523 }
524 }
525
526 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
527 cx.spawn_in(window, async move |this, cx| {
528 let workspaces = this.update(cx, |multi_workspace, _cx| {
529 multi_workspace.workspaces().cloned().collect::<Vec<_>>()
530 })?;
531
532 for workspace in workspaces {
533 let should_continue = workspace
534 .update_in(cx, |workspace, window, cx| {
535 workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
536 })?
537 .await?;
538 if !should_continue {
539 return anyhow::Ok(());
540 }
541 }
542
543 cx.update(|window, _cx| {
544 window.remove_window();
545 })?;
546
547 anyhow::Ok(())
548 })
549 .detach_and_log_err(cx);
550 }
551
552 fn subscribe_to_workspace(
553 workspace: &Entity<Workspace>,
554 window: &Window,
555 cx: &mut Context<Self>,
556 ) {
557 let project = workspace.read(cx).project().clone();
558 cx.subscribe_in(&project, window, {
559 let workspace = workspace.downgrade();
560 move |this, _project, event, _window, cx| match event {
561 project::Event::WorktreePathsChanged { old_worktree_paths } => {
562 if let Some(workspace) = workspace.upgrade() {
563 let host = workspace
564 .read(cx)
565 .project()
566 .read(cx)
567 .remote_connection_options(cx);
568 let old_key =
569 ProjectGroupKey::from_worktree_paths(old_worktree_paths, host);
570 this.handle_project_group_key_change(&workspace, &old_key, cx);
571 }
572 }
573 _ => {}
574 }
575 })
576 .detach();
577
578 cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
579 if let WorkspaceEvent::Activate = event {
580 this.activate(workspace.clone(), window, cx);
581 }
582 })
583 .detach();
584 }
585
586 fn handle_project_group_key_change(
587 &mut self,
588 workspace: &Entity<Workspace>,
589 old_key: &ProjectGroupKey,
590 cx: &mut Context<Self>,
591 ) {
592 if !self.is_workspace_retained(workspace) {
593 return;
594 }
595
596 let new_key = workspace.read(cx).project_group_key(cx);
597 if new_key.path_list().paths().is_empty() {
598 return;
599 }
600
601 // The Project already emitted WorktreePathsChanged which the
602 // sidebar handles for thread migration.
603 self.rekey_project_group(old_key, &new_key, cx);
604 self.serialize(cx);
605 cx.notify();
606 }
607
608 pub fn is_workspace_retained(&self, workspace: &Entity<Workspace>) -> bool {
609 self.retained_workspaces
610 .iter()
611 .any(|retained| retained == workspace)
612 }
613
614 pub fn active_workspace_is_retained(&self) -> bool {
615 self.is_workspace_retained(&self.active_workspace)
616 }
617
618 pub fn retained_workspaces(&self) -> &[Entity<Workspace>] {
619 &self.retained_workspaces
620 }
621
622 /// Ensures a project group exists for `key`, creating one if needed.
623 fn ensure_project_group_state(&mut self, key: ProjectGroupKey) {
624 if key.path_list().paths().is_empty() {
625 return;
626 }
627
628 if self.project_groups.iter().any(|group| group.key == key) {
629 return;
630 }
631
632 self.project_groups.insert(
633 0,
634 ProjectGroupState {
635 key,
636 expanded: true,
637 },
638 );
639 }
640
641 /// Transitions a project group from `old_key` to `new_key`.
642 ///
643 /// On collision (both keys have groups), the active workspace's
644 /// Re-keys a project group from `old_key` to `new_key`, handling
645 /// collisions. When two groups collide, the active workspace's
646 /// group always wins. Otherwise the old key's state is preserved
647 /// — it represents the group the user or system just acted on.
648 /// The losing group is removed, and the winner is re-keyed in
649 /// place to preserve sidebar order.
650 fn rekey_project_group(
651 &mut self,
652 old_key: &ProjectGroupKey,
653 new_key: &ProjectGroupKey,
654 cx: &App,
655 ) {
656 if old_key == new_key {
657 return;
658 }
659
660 if new_key.path_list().paths().is_empty() {
661 return;
662 }
663
664 let old_key_exists = self.project_groups.iter().any(|g| g.key == *old_key);
665 let new_key_exists = self.project_groups.iter().any(|g| g.key == *new_key);
666
667 if !old_key_exists {
668 self.ensure_project_group_state(new_key.clone());
669 return;
670 }
671
672 if new_key_exists {
673 let active_key = self.active_workspace.read(cx).project_group_key(cx);
674 if active_key == *new_key {
675 self.project_groups.retain(|g| g.key != *old_key);
676 } else {
677 self.project_groups.retain(|g| g.key != *new_key);
678 if let Some(group) = self.project_groups.iter_mut().find(|g| g.key == *old_key) {
679 group.key = new_key.clone();
680 }
681 }
682 } else {
683 if let Some(group) = self.project_groups.iter_mut().find(|g| g.key == *old_key) {
684 group.key = new_key.clone();
685 }
686 }
687
688 // If another retained workspace still has the old key (e.g. a
689 // linked worktree workspace), re-create the old group so it
690 // remains reachable in the sidebar.
691 let other_workspace_needs_old_key = self
692 .retained_workspaces
693 .iter()
694 .any(|ws| ws.read(cx).project_group_key(cx) == *old_key);
695 if other_workspace_needs_old_key {
696 self.ensure_project_group_state(old_key.clone());
697 }
698 }
699
700 pub(crate) fn retain_workspace(
701 &mut self,
702 workspace: Entity<Workspace>,
703 key: ProjectGroupKey,
704 cx: &mut Context<Self>,
705 ) {
706 self.ensure_project_group_state(key);
707 if self.is_workspace_retained(&workspace) {
708 return;
709 }
710
711 self.retained_workspaces.push(workspace.clone());
712 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
713 }
714
715 fn register_workspace(
716 &mut self,
717 workspace: &Entity<Workspace>,
718 window: &Window,
719 cx: &mut Context<Self>,
720 ) {
721 Self::subscribe_to_workspace(workspace, window, cx);
722 let weak_self = cx.weak_entity();
723 workspace.update(cx, |workspace, cx| {
724 workspace.set_multi_workspace(weak_self, cx);
725 });
726
727 let entity = cx.entity();
728 cx.defer({
729 let workspace = workspace.clone();
730 move |cx| {
731 entity.update(cx, |this, cx| {
732 this.sync_sidebar_to_workspace(&workspace, cx);
733 })
734 }
735 });
736 }
737
738 pub fn project_group_key_for_workspace(
739 &self,
740 workspace: &Entity<Workspace>,
741 cx: &App,
742 ) -> ProjectGroupKey {
743 workspace.read(cx).project_group_key(cx)
744 }
745
746 pub fn restore_project_groups(
747 &mut self,
748 groups: Vec<SerializedProjectGroupState>,
749 _cx: &mut Context<Self>,
750 ) {
751 let mut restored: Vec<ProjectGroupState> = Vec::new();
752 for SerializedProjectGroupState { key, expanded } in groups {
753 if key.path_list().paths().is_empty() {
754 continue;
755 }
756 if restored.iter().any(|group| group.key == key) {
757 continue;
758 }
759 restored.push(ProjectGroupState { key, expanded });
760 }
761 for existing in std::mem::take(&mut self.project_groups) {
762 if !restored.iter().any(|group| group.key == existing.key) {
763 restored.push(existing);
764 }
765 }
766 self.project_groups = restored;
767 }
768
769 pub fn project_group_keys(&self) -> Vec<ProjectGroupKey> {
770 self.project_groups
771 .iter()
772 .map(|group| group.key.clone())
773 .collect()
774 }
775
776 fn derived_project_groups(&self, cx: &App) -> Vec<ProjectGroup> {
777 self.project_groups
778 .iter()
779 .map(|group| ProjectGroup {
780 key: group.key.clone(),
781 workspaces: self
782 .retained_workspaces
783 .iter()
784 .filter(|workspace| workspace.read(cx).project_group_key(cx) == group.key)
785 .cloned()
786 .collect(),
787 expanded: group.expanded,
788 })
789 .collect()
790 }
791
792 pub fn project_groups(&self, cx: &App) -> Vec<ProjectGroup> {
793 self.derived_project_groups(cx)
794 }
795
796 pub fn group_state_by_key(&self, key: &ProjectGroupKey) -> Option<&ProjectGroupState> {
797 self.project_groups.iter().find(|group| group.key == *key)
798 }
799
800 pub fn group_state_by_key_mut(
801 &mut self,
802 key: &ProjectGroupKey,
803 ) -> Option<&mut ProjectGroupState> {
804 self.project_groups
805 .iter_mut()
806 .find(|group| group.key == *key)
807 }
808
809 pub fn set_all_groups_expanded(&mut self, expanded: bool) {
810 for group in &mut self.project_groups {
811 group.expanded = expanded;
812 }
813 }
814
815 pub fn workspaces_for_project_group(
816 &self,
817 key: &ProjectGroupKey,
818 cx: &App,
819 ) -> Option<Vec<Entity<Workspace>>> {
820 let has_group = self.project_groups.iter().any(|group| group.key == *key)
821 || self
822 .retained_workspaces
823 .iter()
824 .any(|workspace| workspace.read(cx).project_group_key(cx) == *key);
825
826 has_group.then(|| {
827 self.retained_workspaces
828 .iter()
829 .filter(|workspace| workspace.read(cx).project_group_key(cx) == *key)
830 .cloned()
831 .collect()
832 })
833 }
834
835 pub fn remove_project_group(
836 &mut self,
837 group_key: &ProjectGroupKey,
838 window: &mut Window,
839 cx: &mut Context<Self>,
840 ) -> Task<Result<bool>> {
841 let pos = self
842 .project_groups
843 .iter()
844 .position(|group| group.key == *group_key);
845 let workspaces = self
846 .workspaces_for_project_group(group_key, cx)
847 .unwrap_or_default();
848
849 // Compute the neighbor while the group is still in the list.
850 let neighbor_key = pos.and_then(|pos| {
851 self.project_groups
852 .get(pos + 1)
853 .or_else(|| pos.checked_sub(1).and_then(|i| self.project_groups.get(i)))
854 .map(|group| group.key.clone())
855 });
856
857 // Now remove the group.
858 self.project_groups.retain(|group| group.key != *group_key);
859 cx.emit(MultiWorkspaceEvent::ProjectGroupsChanged);
860
861 let excluded_workspaces = workspaces.clone();
862 self.remove(
863 workspaces,
864 move |this, window, cx| {
865 if let Some(neighbor_key) = neighbor_key {
866 return this.find_or_create_local_workspace(
867 neighbor_key.path_list().clone(),
868 Some(neighbor_key.clone()),
869 &excluded_workspaces,
870 None,
871 OpenMode::Activate,
872 window,
873 cx,
874 );
875 }
876
877 // No other project groups remain — create an empty workspace.
878 let app_state = this.workspace().read(cx).app_state().clone();
879 let project = Project::local(
880 app_state.client.clone(),
881 app_state.node_runtime.clone(),
882 app_state.user_store.clone(),
883 app_state.languages.clone(),
884 app_state.fs.clone(),
885 None,
886 project::LocalProjectFlags::default(),
887 cx,
888 );
889 let new_workspace =
890 cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
891 Task::ready(Ok(new_workspace))
892 },
893 window,
894 cx,
895 )
896 }
897
898 /// Goes through sqlite: serialize -> close -> open new window
899 /// This avoids issues with pending tasks having the wrong window
900 pub fn open_project_group_in_new_window(
901 &mut self,
902 key: &ProjectGroupKey,
903 window: &mut Window,
904 cx: &mut Context<Self>,
905 ) -> Task<Result<()>> {
906 let paths: Vec<PathBuf> = key.path_list().ordered_paths().cloned().collect();
907 if paths.is_empty() {
908 return Task::ready(Ok(()));
909 }
910
911 let app_state = self.workspace().read(cx).app_state().clone();
912
913 let workspaces: Vec<_> = self
914 .workspaces_for_project_group(key, cx)
915 .unwrap_or_default();
916 let mut serialization_tasks = Vec::new();
917 for workspace in &workspaces {
918 serialization_tasks.push(workspace.update(cx, |workspace, inner_cx| {
919 workspace.flush_serialization(window, inner_cx)
920 }));
921 }
922
923 let remove_task = self.remove_project_group(key, window, cx);
924
925 cx.spawn(async move |_this, cx| {
926 futures::future::join_all(serialization_tasks).await;
927
928 let removed = remove_task.await?;
929 if !removed {
930 return Ok(());
931 }
932
933 cx.update(|cx| {
934 Workspace::new_local(paths, app_state, None, None, None, OpenMode::NewWindow, cx)
935 })
936 .await?;
937
938 Ok(())
939 })
940 }
941
942 /// Finds an existing workspace whose root paths and host exactly match.
943 pub fn workspace_for_paths(
944 &self,
945 path_list: &PathList,
946 host: Option<&RemoteConnectionOptions>,
947 cx: &App,
948 ) -> Option<Entity<Workspace>> {
949 self.workspace_for_paths_excluding(path_list, host, &[], cx)
950 }
951
952 fn workspace_for_paths_excluding(
953 &self,
954 path_list: &PathList,
955 host: Option<&RemoteConnectionOptions>,
956 excluding: &[Entity<Workspace>],
957 cx: &App,
958 ) -> Option<Entity<Workspace>> {
959 for workspace in self.workspaces() {
960 if excluding.contains(workspace) {
961 continue;
962 }
963 let root_paths = PathList::new(&workspace.read(cx).root_paths(cx));
964 let key = workspace.read(cx).project_group_key(cx);
965 let host_matches = key.host().as_ref() == host;
966 let paths_match = root_paths == *path_list;
967 if host_matches && paths_match {
968 return Some(workspace.clone());
969 }
970 }
971
972 None
973 }
974
975 /// Finds an existing workspace whose paths match, or creates a new one.
976 ///
977 /// For local projects (`host` is `None`), this delegates to
978 /// [`Self::find_or_create_local_workspace`]. For remote projects, it
979 /// tries an exact path match and, if no existing workspace is found,
980 /// calls `connect_remote` to establish a connection and creates a new
981 /// remote workspace.
982 ///
983 /// The `connect_remote` closure is responsible for any user-facing
984 /// connection UI (e.g. password prompts). It receives the connection
985 /// options and should return a [`Task`] that resolves to the
986 /// [`RemoteClient`] session, or `None` if the connection was
987 /// cancelled.
988 pub fn find_or_create_workspace(
989 &mut self,
990 paths: PathList,
991 host: Option<RemoteConnectionOptions>,
992 provisional_project_group_key: Option<ProjectGroupKey>,
993 connect_remote: impl FnOnce(
994 RemoteConnectionOptions,
995 &mut Window,
996 &mut Context<Self>,
997 ) -> Task<Result<Option<Entity<remote::RemoteClient>>>>
998 + 'static,
999 excluding: &[Entity<Workspace>],
1000 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1001 open_mode: OpenMode,
1002 window: &mut Window,
1003 cx: &mut Context<Self>,
1004 ) -> Task<Result<Entity<Workspace>>> {
1005 if let Some(workspace) = self.workspace_for_paths(&paths, host.as_ref(), cx) {
1006 self.activate(workspace.clone(), window, cx);
1007 return Task::ready(Ok(workspace));
1008 }
1009
1010 let Some(connection_options) = host else {
1011 return self.find_or_create_local_workspace(
1012 paths,
1013 provisional_project_group_key,
1014 excluding,
1015 init,
1016 open_mode,
1017 window,
1018 cx,
1019 );
1020 };
1021
1022 let app_state = self.workspace().read(cx).app_state().clone();
1023 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
1024 let connect_task = connect_remote(connection_options.clone(), window, cx);
1025 let paths_vec = paths.paths().to_vec();
1026
1027 cx.spawn(async move |_this, cx| {
1028 let session = connect_task
1029 .await?
1030 .ok_or_else(|| anyhow::anyhow!("Remote connection was cancelled"))?;
1031
1032 let new_project = cx.update(|cx| {
1033 Project::remote(
1034 session,
1035 app_state.client.clone(),
1036 app_state.node_runtime.clone(),
1037 app_state.user_store.clone(),
1038 app_state.languages.clone(),
1039 app_state.fs.clone(),
1040 true,
1041 cx,
1042 )
1043 });
1044
1045 let window_handle =
1046 window_handle.ok_or_else(|| anyhow::anyhow!("Window is not a MultiWorkspace"))?;
1047
1048 open_remote_project_with_existing_connection(
1049 connection_options,
1050 new_project,
1051 paths_vec,
1052 app_state,
1053 window_handle,
1054 provisional_project_group_key,
1055 cx,
1056 )
1057 .await?;
1058
1059 window_handle.update(cx, |multi_workspace, window, cx| {
1060 let workspace = multi_workspace.workspace().clone();
1061 multi_workspace.add(workspace.clone(), window, cx);
1062 workspace
1063 })
1064 })
1065 }
1066
1067 /// Finds an existing workspace in this multi-workspace whose paths match,
1068 /// or creates a new one (deserializing its saved state from the database).
1069 /// Never searches other windows or matches workspaces with a superset of
1070 /// the requested paths.
1071 ///
1072 /// `excluding` lists workspaces that should be skipped during the search
1073 /// (e.g. workspaces that are about to be removed).
1074 pub fn find_or_create_local_workspace(
1075 &mut self,
1076 path_list: PathList,
1077 project_group: Option<ProjectGroupKey>,
1078 excluding: &[Entity<Workspace>],
1079 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1080 open_mode: OpenMode,
1081 window: &mut Window,
1082 cx: &mut Context<Self>,
1083 ) -> Task<Result<Entity<Workspace>>> {
1084 if let Some(workspace) = self.workspace_for_paths_excluding(&path_list, None, excluding, cx)
1085 {
1086 self.activate(workspace.clone(), window, cx);
1087 return Task::ready(Ok(workspace));
1088 }
1089
1090 let paths = path_list.paths().to_vec();
1091 let app_state = self.workspace().read(cx).app_state().clone();
1092 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
1093 let fs = <dyn Fs>::global(cx);
1094 let excluding = excluding.to_vec();
1095
1096 cx.spawn(async move |_this, cx| {
1097 let effective_path_list = if let Some(project_group) = project_group {
1098 let metadata_tasks: Vec<_> = paths
1099 .iter()
1100 .map(|path| fs.metadata(path.as_path()))
1101 .collect();
1102 let metadata_results = futures::future::join_all(metadata_tasks).await;
1103 // Only fall back when every path is definitely absent; real
1104 // filesystem errors should not be treated as "missing".
1105 let all_paths_missing = !paths.is_empty()
1106 && metadata_results
1107 .into_iter()
1108 // Ok(None) means the path is definitely absent
1109 .all(|result| matches!(result, Ok(None)));
1110
1111 if all_paths_missing {
1112 project_group.path_list().clone()
1113 } else {
1114 PathList::new(&paths)
1115 }
1116 } else {
1117 PathList::new(&paths)
1118 };
1119
1120 if let Some(requesting_window) = requesting_window
1121 && let Some(workspace) = requesting_window
1122 .update(cx, |multi_workspace, window, cx| {
1123 multi_workspace
1124 .workspace_for_paths_excluding(
1125 &effective_path_list,
1126 None,
1127 &excluding,
1128 cx,
1129 )
1130 .inspect(|workspace| {
1131 multi_workspace.activate(workspace.clone(), window, cx);
1132 })
1133 })
1134 .ok()
1135 .flatten()
1136 {
1137 return Ok(workspace);
1138 }
1139
1140 let result = cx
1141 .update(|cx| {
1142 Workspace::new_local(
1143 effective_path_list.paths().to_vec(),
1144 app_state,
1145 requesting_window,
1146 None,
1147 init,
1148 open_mode,
1149 cx,
1150 )
1151 })
1152 .await?;
1153 Ok(result.workspace)
1154 })
1155 }
1156
1157 pub fn workspace(&self) -> &Entity<Workspace> {
1158 &self.active_workspace
1159 }
1160
1161 pub fn workspaces(&self) -> impl Iterator<Item = &Entity<Workspace>> {
1162 let active_is_retained = self.is_workspace_retained(&self.active_workspace);
1163 self.retained_workspaces
1164 .iter()
1165 .chain(std::iter::once(&self.active_workspace).filter(move |_| !active_is_retained))
1166 }
1167
1168 /// Adds a workspace to this window as persistent without changing which
1169 /// workspace is active. Unlike `activate()`, this always inserts into the
1170 /// persistent list regardless of sidebar state — it's used for system-
1171 /// initiated additions like deserialization and worktree discovery.
1172 pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
1173 if self.is_workspace_retained(&workspace) {
1174 return;
1175 }
1176
1177 if workspace != self.active_workspace {
1178 self.register_workspace(&workspace, window, cx);
1179 }
1180
1181 let key = workspace.read(cx).project_group_key(cx);
1182 self.retain_workspace(workspace, key, cx);
1183 telemetry::event!(
1184 "Workspace Added",
1185 workspace_count = self.retained_workspaces.len()
1186 );
1187 cx.notify();
1188 }
1189
1190 /// Ensures the workspace is in the multiworkspace and makes it the active one.
1191 pub fn activate(
1192 &mut self,
1193 workspace: Entity<Workspace>,
1194 window: &mut Window,
1195 cx: &mut Context<Self>,
1196 ) {
1197 if self.workspace() == &workspace {
1198 self.focus_active_workspace(window, cx);
1199 return;
1200 }
1201
1202 let old_active_workspace = self.active_workspace.clone();
1203 let old_active_was_retained = self.active_workspace_is_retained();
1204 let workspace_was_retained = self.is_workspace_retained(&workspace);
1205
1206 if !workspace_was_retained {
1207 self.register_workspace(&workspace, window, cx);
1208
1209 if self.sidebar_open {
1210 let key = workspace.read(cx).project_group_key(cx);
1211 self.retain_workspace(workspace.clone(), key, cx);
1212 }
1213 }
1214
1215 self.active_workspace = workspace;
1216
1217 if !self.sidebar_open && !old_active_was_retained {
1218 self.detach_workspace(&old_active_workspace, cx);
1219 }
1220
1221 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1222 self.serialize(cx);
1223 self.focus_active_workspace(window, cx);
1224 cx.notify();
1225 }
1226
1227 /// Promotes the currently active workspace to persistent if it is
1228 /// transient, so it is retained across workspace switches even when
1229 /// the sidebar is closed. No-op if the workspace is already persistent.
1230 pub fn retain_active_workspace(&mut self, cx: &mut Context<Self>) {
1231 let workspace = self.active_workspace.clone();
1232 if self.is_workspace_retained(&workspace) {
1233 return;
1234 }
1235
1236 let key = workspace.read(cx).project_group_key(cx);
1237 self.retain_workspace(workspace, key, cx);
1238 self.serialize(cx);
1239 cx.notify();
1240 }
1241
1242 /// Collapses to a single workspace, discarding all groups.
1243 /// Used when multi-workspace is disabled (e.g. disable_ai).
1244 fn collapse_to_single_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1245 if self.sidebar_open {
1246 self.close_sidebar(window, cx);
1247 }
1248
1249 let active_workspace = self.active_workspace.clone();
1250 for workspace in self.retained_workspaces.clone() {
1251 if workspace != active_workspace {
1252 self.detach_workspace(&workspace, cx);
1253 }
1254 }
1255
1256 self.retained_workspaces.clear();
1257 self.project_groups.clear();
1258 cx.notify();
1259 }
1260
1261 /// Detaches a workspace: clears session state, DB binding, cached
1262 /// group key, and emits `WorkspaceRemoved`. The DB row is preserved
1263 /// so the workspace still appears in the recent-projects list.
1264 fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1265 self.retained_workspaces
1266 .retain(|retained| retained != workspace);
1267 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1268 workspace.update(cx, |workspace, _cx| {
1269 workspace.session_id.take();
1270 workspace._schedule_serialize_workspace.take();
1271 workspace._serialize_workspace_task.take();
1272 });
1273
1274 if let Some(workspace_id) = workspace.read(cx).database_id() {
1275 let db = crate::persistence::WorkspaceDb::global(cx);
1276 self.pending_removal_tasks.retain(|task| !task.is_ready());
1277 self.pending_removal_tasks
1278 .push(cx.background_spawn(async move {
1279 db.set_session_binding(workspace_id, None, None)
1280 .await
1281 .log_err();
1282 }));
1283 }
1284 }
1285
1286 fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1287 if self.sidebar_open() {
1288 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
1289 workspace.update(cx, |workspace, _| {
1290 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
1291 });
1292 }
1293 }
1294
1295 pub fn serialize(&mut self, cx: &mut Context<Self>) {
1296 self._serialize_task = Some(cx.spawn(async move |this, cx| {
1297 let Some((window_id, state)) = this
1298 .read_with(cx, |this, cx| {
1299 let state = MultiWorkspaceState {
1300 active_workspace_id: this.workspace().read(cx).database_id(),
1301 project_groups: this
1302 .project_groups
1303 .iter()
1304 .map(|group| {
1305 crate::persistence::model::SerializedProjectGroup::from_group(
1306 &group.key,
1307 group.expanded,
1308 )
1309 })
1310 .collect::<Vec<_>>(),
1311 sidebar_open: this.sidebar_open,
1312 sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
1313 };
1314 (this.window_id, state)
1315 })
1316 .ok()
1317 else {
1318 return;
1319 };
1320 let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
1321 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
1322 }));
1323 }
1324
1325 /// Returns the in-flight serialization task (if any) so the caller can
1326 /// await it. Used by the quit handler to ensure pending DB writes
1327 /// complete before the process exits.
1328 pub fn flush_serialization(&mut self) -> Task<()> {
1329 self._serialize_task.take().unwrap_or(Task::ready(()))
1330 }
1331
1332 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
1333 let mut tasks: Vec<Task<()>> = Vec::new();
1334 if let Some(task) = self._serialize_task.take() {
1335 tasks.push(task);
1336 }
1337 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
1338
1339 async move {
1340 futures::future::join_all(tasks).await;
1341 }
1342 }
1343
1344 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
1345 // If a dock panel is zoomed, focus it instead of the center pane.
1346 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
1347 // which closes the zoomed dock.
1348 let focus_handle = {
1349 let workspace = self.workspace().read(cx);
1350 let mut target = None;
1351 for dock in workspace.all_docks() {
1352 let dock = dock.read(cx);
1353 if dock.is_open() {
1354 if let Some(panel) = dock.active_panel() {
1355 if panel.is_zoomed(window, cx) {
1356 target = Some(panel.panel_focus_handle(cx));
1357 break;
1358 }
1359 }
1360 }
1361 }
1362 target.unwrap_or_else(|| {
1363 let pane = workspace.active_pane().clone();
1364 pane.read(cx).focus_handle(cx)
1365 })
1366 };
1367 window.focus(&focus_handle, cx);
1368 }
1369
1370 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
1371 self.workspace().read(cx).panel::<T>(cx)
1372 }
1373
1374 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
1375 self.workspace().read(cx).active_modal::<V>(cx)
1376 }
1377
1378 pub fn add_panel<T: Panel>(
1379 &mut self,
1380 panel: Entity<T>,
1381 window: &mut Window,
1382 cx: &mut Context<Self>,
1383 ) {
1384 self.workspace().update(cx, |workspace, cx| {
1385 workspace.add_panel(panel, window, cx);
1386 });
1387 }
1388
1389 pub fn focus_panel<T: Panel>(
1390 &mut self,
1391 window: &mut Window,
1392 cx: &mut Context<Self>,
1393 ) -> Option<Entity<T>> {
1394 self.workspace()
1395 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
1396 }
1397
1398 // used in a test
1399 pub fn toggle_modal<V: ModalView, B>(
1400 &mut self,
1401 window: &mut Window,
1402 cx: &mut Context<Self>,
1403 build: B,
1404 ) where
1405 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
1406 {
1407 self.workspace().update(cx, |workspace, cx| {
1408 workspace.toggle_modal(window, cx, build);
1409 });
1410 }
1411
1412 pub fn toggle_dock(
1413 &mut self,
1414 dock_side: DockPosition,
1415 window: &mut Window,
1416 cx: &mut Context<Self>,
1417 ) {
1418 self.workspace().update(cx, |workspace, cx| {
1419 workspace.toggle_dock(dock_side, window, cx);
1420 });
1421 }
1422
1423 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
1424 self.workspace().read(cx).active_item_as::<I>(cx)
1425 }
1426
1427 pub fn items_of_type<'a, T: Item>(
1428 &'a self,
1429 cx: &'a App,
1430 ) -> impl 'a + Iterator<Item = Entity<T>> {
1431 self.workspace().read(cx).items_of_type::<T>(cx)
1432 }
1433
1434 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
1435 self.workspace().read(cx).database_id()
1436 }
1437
1438 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
1439 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
1440 .into_iter()
1441 .filter(|task| !task.is_ready())
1442 .collect();
1443 tasks
1444 }
1445
1446 #[cfg(any(test, feature = "test-support"))]
1447 pub fn test_expand_all_groups(&mut self) {
1448 self.set_all_groups_expanded(true);
1449 }
1450
1451 #[cfg(any(test, feature = "test-support"))]
1452 pub fn assert_project_group_key_integrity(&self, cx: &App) -> anyhow::Result<()> {
1453 let mut retained_ids: collections::HashSet<EntityId> = Default::default();
1454 for workspace in &self.retained_workspaces {
1455 anyhow::ensure!(
1456 retained_ids.insert(workspace.entity_id()),
1457 "workspace {:?} is retained more than once",
1458 workspace.entity_id(),
1459 );
1460
1461 let live_key = workspace.read(cx).project_group_key(cx);
1462 anyhow::ensure!(
1463 self.project_groups
1464 .iter()
1465 .any(|group| group.key == live_key),
1466 "workspace {:?} has live key {:?} but no project-group metadata",
1467 workspace.entity_id(),
1468 live_key,
1469 );
1470 }
1471 Ok(())
1472 }
1473
1474 #[cfg(any(test, feature = "test-support"))]
1475 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
1476 self.workspace().update(cx, |workspace, _cx| {
1477 workspace.set_random_database_id();
1478 });
1479 }
1480
1481 #[cfg(any(test, feature = "test-support"))]
1482 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1483 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1484 Self::new(workspace, window, cx)
1485 }
1486
1487 #[cfg(any(test, feature = "test-support"))]
1488 pub fn test_add_workspace(
1489 &mut self,
1490 project: Entity<Project>,
1491 window: &mut Window,
1492 cx: &mut Context<Self>,
1493 ) -> Entity<Workspace> {
1494 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1495 self.activate(workspace.clone(), window, cx);
1496 workspace
1497 }
1498
1499 #[cfg(any(test, feature = "test-support"))]
1500 pub fn test_add_project_group(&mut self, group: ProjectGroup) {
1501 self.project_groups.push(ProjectGroupState {
1502 key: group.key,
1503 expanded: group.expanded,
1504 });
1505 }
1506
1507 #[cfg(any(test, feature = "test-support"))]
1508 pub fn create_test_workspace(
1509 &mut self,
1510 window: &mut Window,
1511 cx: &mut Context<Self>,
1512 ) -> Task<()> {
1513 let app_state = self.workspace().read(cx).app_state().clone();
1514 let project = Project::local(
1515 app_state.client.clone(),
1516 app_state.node_runtime.clone(),
1517 app_state.user_store.clone(),
1518 app_state.languages.clone(),
1519 app_state.fs.clone(),
1520 None,
1521 project::LocalProjectFlags::default(),
1522 cx,
1523 );
1524 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1525 self.activate(new_workspace.clone(), window, cx);
1526
1527 let weak_workspace = new_workspace.downgrade();
1528 let db = crate::persistence::WorkspaceDb::global(cx);
1529 cx.spawn_in(window, async move |this, cx| {
1530 let workspace_id = db.next_id().await.unwrap();
1531 let workspace = weak_workspace.upgrade().unwrap();
1532 let task: Task<()> = this
1533 .update_in(cx, |this, window, cx| {
1534 let session_id = workspace.read(cx).session_id();
1535 let window_id = window.window_handle().window_id().as_u64();
1536 workspace.update(cx, |workspace, _cx| {
1537 workspace.set_database_id(workspace_id);
1538 });
1539 this.serialize(cx);
1540 let db = db.clone();
1541 cx.background_spawn(async move {
1542 db.set_session_binding(workspace_id, session_id, Some(window_id))
1543 .await
1544 .log_err();
1545 })
1546 })
1547 .unwrap();
1548 task.await
1549 })
1550 }
1551
1552 /// Assigns random database IDs to all retained workspaces, flushes
1553 /// workspace serialization (SQLite) and multi-workspace state (KVP),
1554 /// and writes session bindings so the serialized data can be read
1555 /// back by `last_session_workspace_locations` +
1556 /// `read_serialized_multi_workspaces`.
1557 #[cfg(any(test, feature = "test-support"))]
1558 pub fn flush_all_serialization(
1559 &mut self,
1560 window: &mut Window,
1561 cx: &mut Context<Self>,
1562 ) -> Vec<Task<()>> {
1563 for workspace in self.workspaces() {
1564 workspace.update(cx, |ws, _cx| {
1565 if ws.database_id().is_none() {
1566 ws.set_random_database_id();
1567 }
1568 });
1569 }
1570
1571 let session_id = self.workspace().read(cx).session_id();
1572 let window_id_u64 = window.window_handle().window_id().as_u64();
1573
1574 let mut tasks: Vec<Task<()>> = Vec::new();
1575 for workspace in self.workspaces() {
1576 tasks.push(workspace.update(cx, |ws, cx| ws.flush_serialization(window, cx)));
1577 if let Some(db_id) = workspace.read(cx).database_id() {
1578 let db = crate::persistence::WorkspaceDb::global(cx);
1579 let session_id = session_id.clone();
1580 tasks.push(cx.background_spawn(async move {
1581 db.set_session_binding(db_id, session_id, Some(window_id_u64))
1582 .await
1583 .log_err();
1584 }));
1585 }
1586 }
1587 self.serialize(cx);
1588 tasks
1589 }
1590
1591 /// Removes one or more workspaces from this multi-workspace.
1592 ///
1593 /// If the active workspace is among those being removed,
1594 /// `fallback_workspace` is called **synchronously before the removal
1595 /// begins** to produce a `Task` that resolves to the workspace that
1596 /// should become active. The fallback must not be one of the
1597 /// workspaces being removed.
1598 ///
1599 /// Returns `true` if any workspaces were actually removed.
1600 pub fn remove(
1601 &mut self,
1602 workspaces: impl IntoIterator<Item = Entity<Workspace>>,
1603 fallback_workspace: impl FnOnce(
1604 &mut Self,
1605 &mut Window,
1606 &mut Context<Self>,
1607 ) -> Task<Result<Entity<Workspace>>>,
1608 window: &mut Window,
1609 cx: &mut Context<Self>,
1610 ) -> Task<Result<bool>> {
1611 let workspaces: Vec<_> = workspaces.into_iter().collect();
1612
1613 if workspaces.is_empty() {
1614 return Task::ready(Ok(false));
1615 }
1616
1617 let removing_active = workspaces.iter().any(|ws| ws == self.workspace());
1618 let original_active = self.workspace().clone();
1619
1620 let fallback_task = removing_active.then(|| fallback_workspace(self, window, cx));
1621
1622 cx.spawn_in(window, async move |this, cx| {
1623 // Prompt each workspace for unsaved changes. If any workspace
1624 // has dirty buffers, save_all_internal will emit Activate to
1625 // bring it into view before showing the save dialog.
1626 for workspace in &workspaces {
1627 let should_continue = workspace
1628 .update_in(cx, |workspace, window, cx| {
1629 workspace.save_all_internal(crate::SaveIntent::Close, window, cx)
1630 })?
1631 .await?;
1632
1633 if !should_continue {
1634 return Ok(false);
1635 }
1636 }
1637
1638 // If we're removing the active workspace, await the
1639 // fallback and switch to it before tearing anything down.
1640 // Otherwise restore the original active workspace in case
1641 // prompting switched away from it.
1642 if let Some(fallback_task) = fallback_task {
1643 let new_active = fallback_task.await?;
1644
1645 this.update_in(cx, |this, window, cx| {
1646 assert!(
1647 !workspaces.contains(&new_active),
1648 "fallback workspace must not be one of the workspaces being removed"
1649 );
1650 this.activate(new_active, window, cx);
1651 })?;
1652 } else {
1653 this.update_in(cx, |this, window, cx| {
1654 if *this.workspace() != original_active {
1655 this.activate(original_active, window, cx);
1656 }
1657 })?;
1658 }
1659
1660 // Actually remove the workspaces.
1661 this.update_in(cx, |this, _, cx| {
1662 let mut removed_any = false;
1663
1664 for workspace in &workspaces {
1665 let was_retained = this.is_workspace_retained(workspace);
1666 if was_retained {
1667 this.detach_workspace(workspace, cx);
1668 removed_any = true;
1669 }
1670 }
1671
1672 if removed_any {
1673 this.serialize(cx);
1674 cx.notify();
1675 }
1676
1677 Ok(removed_any)
1678 })?
1679 })
1680 }
1681
1682 pub fn open_project(
1683 &mut self,
1684 paths: Vec<PathBuf>,
1685 open_mode: OpenMode,
1686 window: &mut Window,
1687 cx: &mut Context<Self>,
1688 ) -> Task<Result<Entity<Workspace>>> {
1689 if self.multi_workspace_enabled(cx) {
1690 self.find_or_create_local_workspace(
1691 PathList::new(&paths),
1692 None,
1693 &[],
1694 None,
1695 OpenMode::Activate,
1696 window,
1697 cx,
1698 )
1699 } else {
1700 let workspace = self.workspace().clone();
1701 cx.spawn_in(window, async move |_this, cx| {
1702 let should_continue = workspace
1703 .update_in(cx, |workspace, window, cx| {
1704 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1705 })?
1706 .await?;
1707 if should_continue {
1708 workspace
1709 .update_in(cx, |workspace, window, cx| {
1710 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1711 })?
1712 .await
1713 } else {
1714 Ok(workspace)
1715 }
1716 })
1717 }
1718 }
1719}
1720
1721impl Render for MultiWorkspace {
1722 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1723 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1724 let sidebar_side = self.sidebar_side(cx);
1725 let sidebar_on_right = sidebar_side == SidebarSide::Right;
1726
1727 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1728 self.sidebar.as_ref().map(|sidebar_handle| {
1729 let weak = cx.weak_entity();
1730
1731 let sidebar_width = sidebar_handle.width(cx);
1732 let resize_handle = deferred(
1733 div()
1734 .id("sidebar-resize-handle")
1735 .absolute()
1736 .when(!sidebar_on_right, |el| {
1737 el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1738 })
1739 .when(sidebar_on_right, |el| {
1740 el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1741 })
1742 .top(px(0.))
1743 .h_full()
1744 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1745 .cursor_col_resize()
1746 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1747 cx.stop_propagation();
1748 cx.new(|_| dragged.clone())
1749 })
1750 .on_mouse_down(MouseButton::Left, |_, _, cx| {
1751 cx.stop_propagation();
1752 })
1753 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1754 if event.click_count == 2 {
1755 weak.update(cx, |this, cx| {
1756 if let Some(sidebar) = this.sidebar.as_mut() {
1757 sidebar.set_width(None, cx);
1758 }
1759 this.serialize(cx);
1760 })
1761 .ok();
1762 cx.stop_propagation();
1763 } else {
1764 weak.update(cx, |this, cx| {
1765 this.serialize(cx);
1766 })
1767 .ok();
1768 }
1769 })
1770 .occlude(),
1771 );
1772
1773 div()
1774 .id("sidebar-container")
1775 .relative()
1776 .h_full()
1777 .w(sidebar_width)
1778 .flex_shrink_0()
1779 .child(sidebar_handle.to_any())
1780 .child(resize_handle)
1781 .into_any_element()
1782 })
1783 } else {
1784 None
1785 };
1786
1787 let (left_sidebar, right_sidebar) = if sidebar_on_right {
1788 (None, sidebar)
1789 } else {
1790 (sidebar, None)
1791 };
1792
1793 let ui_font = theme_settings::setup_ui_font(window, cx);
1794 let text_color = cx.theme().colors().text;
1795
1796 let workspace = self.workspace().clone();
1797 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1798 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1799
1800 client_side_decorations(
1801 root.key_context(workspace_key_context)
1802 .relative()
1803 .size_full()
1804 .font(ui_font)
1805 .text_color(text_color)
1806 .on_action(cx.listener(Self::close_window))
1807 .when(self.multi_workspace_enabled(cx), |this| {
1808 this.on_action(cx.listener(
1809 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1810 this.toggle_sidebar(window, cx);
1811 },
1812 ))
1813 .on_action(cx.listener(
1814 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1815 this.close_sidebar_action(window, cx);
1816 },
1817 ))
1818 .on_action(cx.listener(
1819 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1820 this.focus_sidebar(window, cx);
1821 },
1822 ))
1823 .on_action(cx.listener(
1824 |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1825 if let Some(sidebar) = &this.sidebar {
1826 sidebar.toggle_thread_switcher(action.select_last, window, cx);
1827 }
1828 },
1829 ))
1830 .on_action(cx.listener(|this: &mut Self, _: &NextProject, window, cx| {
1831 if let Some(sidebar) = &this.sidebar {
1832 sidebar.cycle_project(true, window, cx);
1833 }
1834 }))
1835 .on_action(
1836 cx.listener(|this: &mut Self, _: &PreviousProject, window, cx| {
1837 if let Some(sidebar) = &this.sidebar {
1838 sidebar.cycle_project(false, window, cx);
1839 }
1840 }),
1841 )
1842 .on_action(cx.listener(|this: &mut Self, _: &NextThread, window, cx| {
1843 if let Some(sidebar) = &this.sidebar {
1844 sidebar.cycle_thread(true, window, cx);
1845 }
1846 }))
1847 .on_action(
1848 cx.listener(|this: &mut Self, _: &PreviousThread, window, cx| {
1849 if let Some(sidebar) = &this.sidebar {
1850 sidebar.cycle_thread(false, window, cx);
1851 }
1852 }),
1853 )
1854 .when(self.project_group_keys().len() >= 2, |el| {
1855 el.on_action(cx.listener(
1856 |this: &mut Self, _: &MoveProjectToNewWindow, window, cx| {
1857 let key =
1858 this.project_group_key_for_workspace(this.workspace(), cx);
1859 this.open_project_group_in_new_window(&key, window, cx)
1860 .detach_and_log_err(cx);
1861 },
1862 ))
1863 })
1864 })
1865 .when(
1866 self.sidebar_open() && self.multi_workspace_enabled(cx),
1867 |this| {
1868 this.on_drag_move(cx.listener(
1869 move |this: &mut Self,
1870 e: &DragMoveEvent<DraggedSidebar>,
1871 window,
1872 cx| {
1873 if let Some(sidebar) = &this.sidebar {
1874 let new_width = if sidebar_on_right {
1875 window.bounds().size.width - e.event.position.x
1876 } else {
1877 e.event.position.x
1878 };
1879 sidebar.set_width(Some(new_width), cx);
1880 }
1881 },
1882 ))
1883 },
1884 )
1885 .children(left_sidebar)
1886 .child(
1887 div()
1888 .flex()
1889 .flex_1()
1890 .size_full()
1891 .overflow_hidden()
1892 .child(self.workspace().clone()),
1893 )
1894 .children(right_sidebar)
1895 .child(self.workspace().read(cx).modal_layer.clone())
1896 .children(self.sidebar_overlay.as_ref().map(|view| {
1897 deferred(div().absolute().size_full().inset_0().occlude().child(
1898 v_flex().h(px(0.0)).top_20().items_center().child(
1899 h_flex().occlude().child(view.clone()).on_mouse_down(
1900 MouseButton::Left,
1901 |_, _, cx| {
1902 cx.stop_propagation();
1903 },
1904 ),
1905 ),
1906 ))
1907 .with_priority(2)
1908 })),
1909 window,
1910 cx,
1911 Tiling {
1912 left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1913 right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1914 ..Tiling::default()
1915 },
1916 )
1917 }
1918}