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