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