1use anyhow::Result;
2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
3use gpui::PathPromptOptions;
4use gpui::{
5 AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
6 ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
7 actions, deferred, px,
8};
9#[cfg(any(test, feature = "test-support"))]
10use project::Project;
11use project::{DirectoryLister, DisableAiSettings, ProjectGroupKey};
12use settings::Settings;
13pub use settings::SidebarSide;
14use std::future::Future;
15use std::path::Path;
16use std::path::PathBuf;
17use std::sync::Arc;
18use ui::prelude::*;
19use util::ResultExt;
20use util::path_list::PathList;
21use zed_actions::agents_sidebar::{MoveWorkspaceToNewWindow, 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::AppState;
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 /// Switches to the next workspace.
46 NextWorkspace,
47 /// Switches to the previous workspace.
48 PreviousWorkspace,
49 ]
50);
51
52#[derive(Default)]
53pub struct SidebarRenderState {
54 pub open: bool,
55 pub side: SidebarSide,
56}
57
58pub fn sidebar_side_context_menu(
59 id: impl Into<ElementId>,
60 cx: &App,
61) -> ui::RightClickMenu<ContextMenu> {
62 let current_position = AgentSettings::get_global(cx).sidebar_side;
63 right_click_menu(id).menu(move |window, cx| {
64 let fs = <dyn fs::Fs>::global(cx);
65 ContextMenu::build(window, cx, move |mut menu, _, _cx| {
66 let positions: [(SidebarDockPosition, &str); 2] = [
67 (SidebarDockPosition::Left, "Left"),
68 (SidebarDockPosition::Right, "Right"),
69 ];
70 for (position, label) in positions {
71 let fs = fs.clone();
72 menu = menu.toggleable_entry(
73 label,
74 position == current_position,
75 IconPosition::Start,
76 None,
77 move |_window, cx| {
78 settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
79 settings
80 .agent
81 .get_or_insert_default()
82 .set_sidebar_side(position);
83 });
84 },
85 );
86 }
87 menu
88 })
89 })
90}
91
92pub enum MultiWorkspaceEvent {
93 ActiveWorkspaceChanged,
94 WorkspaceAdded(Entity<Workspace>),
95 WorkspaceRemoved(EntityId),
96}
97
98pub enum SidebarEvent {
99 SerializeNeeded,
100}
101
102pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
103 fn width(&self, cx: &App) -> Pixels;
104 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
105 fn has_notifications(&self, cx: &App) -> bool;
106 fn side(&self, _cx: &App) -> SidebarSide;
107
108 fn is_threads_list_view_active(&self) -> bool {
109 true
110 }
111 /// Makes focus reset back to the search editor upon toggling the sidebar from outside
112 fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
113 /// Opens or cycles the thread switcher popup.
114 fn toggle_thread_switcher(
115 &mut self,
116 _select_last: bool,
117 _window: &mut Window,
118 _cx: &mut Context<Self>,
119 ) {
120 }
121
122 /// Return an opaque JSON blob of sidebar-specific state to persist.
123 fn serialized_state(&self, _cx: &App) -> Option<String> {
124 None
125 }
126
127 /// Restore sidebar state from a previously-serialized blob.
128 fn restore_serialized_state(
129 &mut self,
130 _state: &str,
131 _window: &mut Window,
132 _cx: &mut Context<Self>,
133 ) {
134 }
135}
136
137pub trait SidebarHandle: 'static + Send + Sync {
138 fn width(&self, cx: &App) -> Pixels;
139 fn set_width(&self, width: Option<Pixels>, cx: &mut App);
140 fn focus_handle(&self, cx: &App) -> FocusHandle;
141 fn focus(&self, window: &mut Window, cx: &mut App);
142 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
143 fn has_notifications(&self, cx: &App) -> bool;
144 fn to_any(&self) -> AnyView;
145 fn entity_id(&self) -> EntityId;
146 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
147
148 fn is_threads_list_view_active(&self, cx: &App) -> bool;
149
150 fn side(&self, cx: &App) -> SidebarSide;
151 fn serialized_state(&self, cx: &App) -> Option<String>;
152 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
153}
154
155#[derive(Clone)]
156pub struct DraggedSidebar;
157
158impl Render for DraggedSidebar {
159 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
160 gpui::Empty
161 }
162}
163
164impl<T: Sidebar> SidebarHandle for Entity<T> {
165 fn width(&self, cx: &App) -> Pixels {
166 self.read(cx).width(cx)
167 }
168
169 fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
170 self.update(cx, |this, cx| this.set_width(width, cx))
171 }
172
173 fn focus_handle(&self, cx: &App) -> FocusHandle {
174 self.read(cx).focus_handle(cx)
175 }
176
177 fn focus(&self, window: &mut Window, cx: &mut App) {
178 let handle = self.read(cx).focus_handle(cx);
179 window.focus(&handle, cx);
180 }
181
182 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
183 self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
184 }
185
186 fn has_notifications(&self, cx: &App) -> bool {
187 self.read(cx).has_notifications(cx)
188 }
189
190 fn to_any(&self) -> AnyView {
191 self.clone().into()
192 }
193
194 fn entity_id(&self) -> EntityId {
195 Entity::entity_id(self)
196 }
197
198 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
199 let entity = self.clone();
200 window.defer(cx, move |window, cx| {
201 entity.update(cx, |this, cx| {
202 this.toggle_thread_switcher(select_last, window, cx);
203 });
204 });
205 }
206
207 fn is_threads_list_view_active(&self, cx: &App) -> bool {
208 self.read(cx).is_threads_list_view_active()
209 }
210
211 fn side(&self, cx: &App) -> SidebarSide {
212 self.read(cx).side(cx)
213 }
214
215 fn serialized_state(&self, cx: &App) -> Option<String> {
216 self.read(cx).serialized_state(cx)
217 }
218
219 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
220 self.update(cx, |this, cx| {
221 this.restore_serialized_state(state, window, cx)
222 })
223 }
224}
225
226pub struct MultiWorkspace {
227 window_id: WindowId,
228 workspaces: Vec<Entity<Workspace>>,
229 active_workspace_index: usize,
230 project_group_keys: Vec<ProjectGroupKey>,
231 sidebar: Option<Box<dyn SidebarHandle>>,
232 sidebar_open: bool,
233 sidebar_overlay: Option<AnyView>,
234 pending_removal_tasks: Vec<Task<()>>,
235 _serialize_task: Option<Task<()>>,
236 _subscriptions: Vec<Subscription>,
237}
238
239impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
240
241impl MultiWorkspace {
242 pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
243 self.sidebar
244 .as_ref()
245 .map_or(SidebarSide::Left, |s| s.side(cx))
246 }
247
248 pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
249 SidebarRenderState {
250 open: self.sidebar_open() && self.multi_workspace_enabled(cx),
251 side: self.sidebar_side(cx),
252 }
253 }
254
255 pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
256 let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
257 if let Some(task) = this._serialize_task.take() {
258 task.detach();
259 }
260 for task in std::mem::take(&mut this.pending_removal_tasks) {
261 task.detach();
262 }
263 });
264 let quit_subscription = cx.on_app_quit(Self::app_will_quit);
265 let settings_subscription =
266 cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
267 if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
268 this.close_sidebar(window, cx);
269 }
270 });
271 Self::subscribe_to_workspace(&workspace, window, cx);
272 let weak_self = cx.weak_entity();
273 workspace.update(cx, |workspace, cx| {
274 workspace.set_multi_workspace(weak_self, cx);
275 });
276 Self {
277 window_id: window.window_handle().window_id(),
278 project_group_keys: vec![workspace.read(cx).project_group_key(cx)],
279 workspaces: vec![workspace],
280 active_workspace_index: 0,
281 sidebar: None,
282 sidebar_open: false,
283 sidebar_overlay: None,
284 pending_removal_tasks: Vec::new(),
285 _serialize_task: None,
286 _subscriptions: vec![
287 release_subscription,
288 quit_subscription,
289 settings_subscription,
290 ],
291 }
292 }
293
294 pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
295 self._subscriptions
296 .push(cx.observe(&sidebar, |_this, _, cx| {
297 cx.notify();
298 }));
299 self._subscriptions
300 .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
301 SidebarEvent::SerializeNeeded => {
302 this.serialize(cx);
303 }
304 }));
305 self.sidebar = Some(Box::new(sidebar));
306 }
307
308 pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
309 self.sidebar.as_deref()
310 }
311
312 pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
313 self.sidebar_overlay = overlay;
314 cx.notify();
315 }
316
317 pub fn sidebar_open(&self) -> bool {
318 self.sidebar_open
319 }
320
321 pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
322 self.sidebar
323 .as_ref()
324 .map_or(false, |s| s.has_notifications(cx))
325 }
326
327 pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
328 self.sidebar
329 .as_ref()
330 .map_or(false, |s| s.is_threads_list_view_active(cx))
331 }
332
333 pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
334 cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
335 }
336
337 pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
338 if !self.multi_workspace_enabled(cx) {
339 return;
340 }
341
342 if self.sidebar_open {
343 self.close_sidebar(window, cx);
344 } else {
345 self.open_sidebar(cx);
346 if let Some(sidebar) = &self.sidebar {
347 sidebar.prepare_for_focus(window, cx);
348 sidebar.focus(window, cx);
349 }
350 }
351 }
352
353 pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
354 if !self.multi_workspace_enabled(cx) {
355 return;
356 }
357
358 if self.sidebar_open {
359 self.close_sidebar(window, cx);
360 }
361 }
362
363 pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
364 if !self.multi_workspace_enabled(cx) {
365 return;
366 }
367
368 if self.sidebar_open {
369 let sidebar_is_focused = self
370 .sidebar
371 .as_ref()
372 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
373
374 if sidebar_is_focused {
375 let pane = self.workspace().read(cx).active_pane().clone();
376 let pane_focus = pane.read(cx).focus_handle(cx);
377 window.focus(&pane_focus, cx);
378 } else if let Some(sidebar) = &self.sidebar {
379 sidebar.prepare_for_focus(window, cx);
380 sidebar.focus(window, cx);
381 }
382 } else {
383 self.open_sidebar(cx);
384 if let Some(sidebar) = &self.sidebar {
385 sidebar.prepare_for_focus(window, cx);
386 sidebar.focus(window, cx);
387 }
388 }
389 }
390
391 pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
392 self.sidebar_open = true;
393 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
394 for workspace in &self.workspaces {
395 workspace.update(cx, |workspace, _cx| {
396 workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
397 });
398 }
399 self.serialize(cx);
400 cx.notify();
401 }
402
403 pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
404 self.sidebar_open = false;
405 for workspace in &self.workspaces {
406 workspace.update(cx, |workspace, _cx| {
407 workspace.set_sidebar_focus_handle(None);
408 });
409 }
410 let pane = self.workspace().read(cx).active_pane().clone();
411 let pane_focus = pane.read(cx).focus_handle(cx);
412 window.focus(&pane_focus, cx);
413 self.serialize(cx);
414 cx.notify();
415 }
416
417 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
418 cx.spawn_in(window, async move |this, cx| {
419 let workspaces = this.update(cx, |multi_workspace, _cx| {
420 multi_workspace.workspaces().to_vec()
421 })?;
422
423 for workspace in workspaces {
424 let should_continue = workspace
425 .update_in(cx, |workspace, window, cx| {
426 workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
427 })?
428 .await?;
429 if !should_continue {
430 return anyhow::Ok(());
431 }
432 }
433
434 cx.update(|window, _cx| {
435 window.remove_window();
436 })?;
437
438 anyhow::Ok(())
439 })
440 .detach_and_log_err(cx);
441 }
442
443 fn subscribe_to_workspace(
444 workspace: &Entity<Workspace>,
445 window: &Window,
446 cx: &mut Context<Self>,
447 ) {
448 let project = workspace.read(cx).project().clone();
449 cx.subscribe_in(&project, window, {
450 let workspace = workspace.downgrade();
451 move |this, _project, event, _window, cx| match event {
452 project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
453 if let Some(workspace) = workspace.upgrade() {
454 this.add_project_group_key(workspace.read(cx).project_group_key(cx));
455 }
456 }
457 _ => {}
458 }
459 })
460 .detach();
461
462 cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
463 if let WorkspaceEvent::Activate = event {
464 this.activate(workspace.clone(), window, cx);
465 }
466 })
467 .detach();
468 }
469
470 pub fn add_project_group_key(&mut self, project_group_key: ProjectGroupKey) {
471 if self.project_group_keys.contains(&project_group_key) {
472 return;
473 }
474 self.project_group_keys.push(project_group_key);
475 }
476
477 pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
478 self.project_group_keys.iter()
479 }
480
481 /// Returns the project groups, ordered by most recently added.
482 pub fn project_groups(
483 &self,
484 cx: &App,
485 ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
486 let mut groups = self
487 .project_group_keys
488 .iter()
489 .rev()
490 .map(|key| (key.clone(), Vec::new()))
491 .collect::<Vec<_>>();
492 for workspace in &self.workspaces {
493 let key = workspace.read(cx).project_group_key(cx);
494 if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
495 workspaces.push(workspace.clone());
496 }
497 }
498 groups.into_iter()
499 }
500
501 pub fn workspaces_for_project_group(
502 &self,
503 project_group_key: &ProjectGroupKey,
504 cx: &App,
505 ) -> impl Iterator<Item = &Entity<Workspace>> {
506 self.workspaces
507 .iter()
508 .filter(move |ws| ws.read(cx).project_group_key(cx) == *project_group_key)
509 }
510
511 pub fn remove_folder_from_project_group(
512 &mut self,
513 project_group_key: &ProjectGroupKey,
514 path: &Path,
515 cx: &mut Context<Self>,
516 ) {
517 let new_path_list = project_group_key.path_list().without_path(path);
518 if new_path_list.is_empty() {
519 return;
520 }
521
522 let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
523
524 let workspaces: Vec<_> = self
525 .workspaces_for_project_group(project_group_key, cx)
526 .cloned()
527 .collect();
528
529 self.add_project_group_key(new_key);
530
531 for workspace in workspaces {
532 let project = workspace.read(cx).project().clone();
533 project.update(cx, |project, cx| {
534 project.remove_worktree_for_main_worktree_path(path, cx);
535 });
536 }
537
538 self.serialize(cx);
539 cx.notify();
540 }
541
542 pub fn prompt_to_add_folders_to_project_group(
543 &mut self,
544 key: &ProjectGroupKey,
545 window: &mut Window,
546 cx: &mut Context<Self>,
547 ) {
548 let paths = self.workspace().update(cx, |workspace, cx| {
549 workspace.prompt_for_open_path(
550 PathPromptOptions {
551 files: false,
552 directories: true,
553 multiple: true,
554 prompt: None,
555 },
556 DirectoryLister::Project(workspace.project().clone()),
557 window,
558 cx,
559 )
560 });
561
562 let key = key.clone();
563 cx.spawn_in(window, async move |this, cx| {
564 if let Some(new_paths) = paths.await.ok().flatten() {
565 if !new_paths.is_empty() {
566 this.update(cx, |multi_workspace, cx| {
567 multi_workspace.add_folders_to_project_group(&key, new_paths, cx);
568 })?;
569 }
570 }
571 anyhow::Ok(())
572 })
573 .detach_and_log_err(cx);
574 }
575
576 pub fn add_folders_to_project_group(
577 &mut self,
578 project_group_key: &ProjectGroupKey,
579 new_paths: Vec<PathBuf>,
580 cx: &mut Context<Self>,
581 ) {
582 let mut all_paths: Vec<PathBuf> = project_group_key.path_list().paths().to_vec();
583 all_paths.extend(new_paths.iter().cloned());
584 let new_path_list = PathList::new(&all_paths);
585 let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
586
587 let workspaces: Vec<_> = self
588 .workspaces_for_project_group(project_group_key, cx)
589 .cloned()
590 .collect();
591
592 self.add_project_group_key(new_key);
593
594 for workspace in workspaces {
595 let project = workspace.read(cx).project().clone();
596 for path in &new_paths {
597 project
598 .update(cx, |project, cx| {
599 project.find_or_create_worktree(path, true, cx)
600 })
601 .detach_and_log_err(cx);
602 }
603 }
604
605 self.serialize(cx);
606 cx.notify();
607 }
608
609 pub fn remove_project_group(
610 &mut self,
611 key: &ProjectGroupKey,
612 window: &mut Window,
613 cx: &mut Context<Self>,
614 ) {
615 self.project_group_keys.retain(|k| k != key);
616
617 let workspaces: Vec<_> = self
618 .workspaces_for_project_group(key, cx)
619 .cloned()
620 .collect();
621 for workspace in workspaces {
622 self.remove(&workspace, window, cx);
623 }
624
625 self.serialize(cx);
626 cx.notify();
627 }
628
629 /// Finds an existing workspace in this multi-workspace whose paths match,
630 /// or creates a new one (deserializing its saved state from the database).
631 /// Never searches other windows or matches workspaces with a superset of
632 /// the requested paths.
633 pub fn find_or_create_local_workspace(
634 &mut self,
635 path_list: PathList,
636 window: &mut Window,
637 cx: &mut Context<Self>,
638 ) -> Task<Result<Entity<Workspace>>> {
639 if let Some(workspace) = self
640 .workspaces
641 .iter()
642 .find(|ws| ws.read(cx).project_group_key(cx).path_list() == &path_list)
643 .cloned()
644 {
645 self.activate(workspace.clone(), window, cx);
646 return Task::ready(Ok(workspace));
647 }
648
649 let paths = path_list.paths().to_vec();
650 let app_state = self.workspace().read(cx).app_state().clone();
651 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
652
653 cx.spawn(async move |_this, cx| {
654 let result = cx
655 .update(|cx| {
656 Workspace::new_local(
657 paths,
658 app_state,
659 requesting_window,
660 None,
661 None,
662 OpenMode::Activate,
663 cx,
664 )
665 })
666 .await?;
667 Ok(result.workspace)
668 })
669 }
670
671 pub fn workspace(&self) -> &Entity<Workspace> {
672 &self.workspaces[self.active_workspace_index]
673 }
674
675 pub fn workspaces(&self) -> &[Entity<Workspace>] {
676 &self.workspaces
677 }
678
679 pub fn active_workspace_index(&self) -> usize {
680 self.active_workspace_index
681 }
682
683 /// Adds a workspace to this window without changing which workspace is
684 /// active.
685 pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
686 if !self.multi_workspace_enabled(cx) {
687 self.set_single_workspace(workspace, cx);
688 return;
689 }
690
691 self.insert_workspace(workspace, window, cx);
692 }
693
694 /// Ensures the workspace is in the multiworkspace and makes it the active one.
695 pub fn activate(
696 &mut self,
697 workspace: Entity<Workspace>,
698 window: &mut Window,
699 cx: &mut Context<Self>,
700 ) {
701 if !self.multi_workspace_enabled(cx) {
702 self.set_single_workspace(workspace, cx);
703 return;
704 }
705
706 let index = self.insert_workspace(workspace, &*window, cx);
707 let changed = self.active_workspace_index != index;
708 self.active_workspace_index = index;
709 if changed {
710 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
711 self.serialize(cx);
712 }
713 self.focus_active_workspace(window, cx);
714 cx.notify();
715 }
716
717 fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
718 self.workspaces[0] = workspace;
719 self.active_workspace_index = 0;
720 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
721 cx.notify();
722 }
723
724 /// Inserts a workspace into the list if not already present. Returns the
725 /// index of the workspace (existing or newly inserted). Does not change
726 /// the active workspace index.
727 fn insert_workspace(
728 &mut self,
729 workspace: Entity<Workspace>,
730 window: &Window,
731 cx: &mut Context<Self>,
732 ) -> usize {
733 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
734 index
735 } else {
736 let project_group_key = workspace.read(cx).project().read(cx).project_group_key(cx);
737
738 Self::subscribe_to_workspace(&workspace, window, cx);
739 self.sync_sidebar_to_workspace(&workspace, cx);
740 let weak_self = cx.weak_entity();
741 workspace.update(cx, |workspace, cx| {
742 workspace.set_multi_workspace(weak_self, cx);
743 });
744
745 self.add_project_group_key(project_group_key);
746 self.workspaces.push(workspace.clone());
747 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
748 cx.notify();
749 self.workspaces.len() - 1
750 }
751 }
752
753 /// Clears session state and DB binding for a workspace that is being
754 /// removed or replaced. The DB row is preserved so the workspace still
755 /// appears in the recent-projects list.
756 fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
757 workspace.update(cx, |workspace, _cx| {
758 workspace.session_id.take();
759 workspace._schedule_serialize_workspace.take();
760 workspace._serialize_workspace_task.take();
761 });
762
763 if let Some(workspace_id) = workspace.read(cx).database_id() {
764 let db = crate::persistence::WorkspaceDb::global(cx);
765 self.pending_removal_tasks.retain(|task| !task.is_ready());
766 self.pending_removal_tasks
767 .push(cx.background_spawn(async move {
768 db.set_session_binding(workspace_id, None, None)
769 .await
770 .log_err();
771 }));
772 }
773 }
774
775 fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
776 if self.sidebar_open {
777 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
778 workspace.update(cx, |workspace, _| {
779 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
780 });
781 }
782 }
783
784 fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
785 let count = self.workspaces.len() as isize;
786 if count <= 1 {
787 return;
788 }
789 let current = self.active_workspace_index as isize;
790 let next = ((current + delta).rem_euclid(count)) as usize;
791 let workspace = self.workspaces[next].clone();
792 self.activate(workspace, window, cx);
793 }
794
795 fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
796 self.cycle_workspace(1, window, cx);
797 }
798
799 fn previous_workspace(
800 &mut self,
801 _: &PreviousWorkspace,
802 window: &mut Window,
803 cx: &mut Context<Self>,
804 ) {
805 self.cycle_workspace(-1, window, cx);
806 }
807
808 pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
809 self._serialize_task = Some(cx.spawn(async move |this, cx| {
810 let Some((window_id, state)) = this
811 .read_with(cx, |this, cx| {
812 let state = MultiWorkspaceState {
813 active_workspace_id: this.workspace().read(cx).database_id(),
814 project_group_keys: this
815 .project_group_keys()
816 .cloned()
817 .map(Into::into)
818 .collect::<Vec<_>>(),
819 sidebar_open: this.sidebar_open,
820 sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
821 };
822 (this.window_id, state)
823 })
824 .ok()
825 else {
826 return;
827 };
828 let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
829 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
830 }));
831 }
832
833 /// Returns the in-flight serialization task (if any) so the caller can
834 /// await it. Used by the quit handler to ensure pending DB writes
835 /// complete before the process exits.
836 pub fn flush_serialization(&mut self) -> Task<()> {
837 self._serialize_task.take().unwrap_or(Task::ready(()))
838 }
839
840 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
841 let mut tasks: Vec<Task<()>> = Vec::new();
842 if let Some(task) = self._serialize_task.take() {
843 tasks.push(task);
844 }
845 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
846
847 async move {
848 futures::future::join_all(tasks).await;
849 }
850 }
851
852 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
853 // If a dock panel is zoomed, focus it instead of the center pane.
854 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
855 // which closes the zoomed dock.
856 let focus_handle = {
857 let workspace = self.workspace().read(cx);
858 let mut target = None;
859 for dock in workspace.all_docks() {
860 let dock = dock.read(cx);
861 if dock.is_open() {
862 if let Some(panel) = dock.active_panel() {
863 if panel.is_zoomed(window, cx) {
864 target = Some(panel.panel_focus_handle(cx));
865 break;
866 }
867 }
868 }
869 }
870 target.unwrap_or_else(|| {
871 let pane = workspace.active_pane().clone();
872 pane.read(cx).focus_handle(cx)
873 })
874 };
875 window.focus(&focus_handle, cx);
876 }
877
878 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
879 self.workspace().read(cx).panel::<T>(cx)
880 }
881
882 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
883 self.workspace().read(cx).active_modal::<V>(cx)
884 }
885
886 pub fn add_panel<T: Panel>(
887 &mut self,
888 panel: Entity<T>,
889 window: &mut Window,
890 cx: &mut Context<Self>,
891 ) {
892 self.workspace().update(cx, |workspace, cx| {
893 workspace.add_panel(panel, window, cx);
894 });
895 }
896
897 pub fn focus_panel<T: Panel>(
898 &mut self,
899 window: &mut Window,
900 cx: &mut Context<Self>,
901 ) -> Option<Entity<T>> {
902 self.workspace()
903 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
904 }
905
906 // used in a test
907 pub fn toggle_modal<V: ModalView, B>(
908 &mut self,
909 window: &mut Window,
910 cx: &mut Context<Self>,
911 build: B,
912 ) where
913 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
914 {
915 self.workspace().update(cx, |workspace, cx| {
916 workspace.toggle_modal(window, cx, build);
917 });
918 }
919
920 pub fn toggle_dock(
921 &mut self,
922 dock_side: DockPosition,
923 window: &mut Window,
924 cx: &mut Context<Self>,
925 ) {
926 self.workspace().update(cx, |workspace, cx| {
927 workspace.toggle_dock(dock_side, window, cx);
928 });
929 }
930
931 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
932 self.workspace().read(cx).active_item_as::<I>(cx)
933 }
934
935 pub fn items_of_type<'a, T: Item>(
936 &'a self,
937 cx: &'a App,
938 ) -> impl 'a + Iterator<Item = Entity<T>> {
939 self.workspace().read(cx).items_of_type::<T>(cx)
940 }
941
942 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
943 self.workspace().read(cx).database_id()
944 }
945
946 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
947 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
948 .into_iter()
949 .filter(|task| !task.is_ready())
950 .collect();
951 tasks
952 }
953
954 #[cfg(any(test, feature = "test-support"))]
955 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
956 self.workspace().update(cx, |workspace, _cx| {
957 workspace.set_random_database_id();
958 });
959 }
960
961 #[cfg(any(test, feature = "test-support"))]
962 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
963 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
964 Self::new(workspace, window, cx)
965 }
966
967 #[cfg(any(test, feature = "test-support"))]
968 pub fn test_add_workspace(
969 &mut self,
970 project: Entity<Project>,
971 window: &mut Window,
972 cx: &mut Context<Self>,
973 ) -> Entity<Workspace> {
974 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
975 self.activate(workspace.clone(), window, cx);
976 workspace
977 }
978
979 #[cfg(any(test, feature = "test-support"))]
980 pub fn create_test_workspace(
981 &mut self,
982 window: &mut Window,
983 cx: &mut Context<Self>,
984 ) -> Task<()> {
985 let app_state = self.workspace().read(cx).app_state().clone();
986 let project = Project::local(
987 app_state.client.clone(),
988 app_state.node_runtime.clone(),
989 app_state.user_store.clone(),
990 app_state.languages.clone(),
991 app_state.fs.clone(),
992 None,
993 project::LocalProjectFlags::default(),
994 cx,
995 );
996 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
997 self.activate(new_workspace.clone(), window, cx);
998
999 let weak_workspace = new_workspace.downgrade();
1000 let db = crate::persistence::WorkspaceDb::global(cx);
1001 cx.spawn_in(window, async move |this, cx| {
1002 let workspace_id = db.next_id().await.unwrap();
1003 let workspace = weak_workspace.upgrade().unwrap();
1004 let task: Task<()> = this
1005 .update_in(cx, |this, window, cx| {
1006 let session_id = workspace.read(cx).session_id();
1007 let window_id = window.window_handle().window_id().as_u64();
1008 workspace.update(cx, |workspace, _cx| {
1009 workspace.set_database_id(workspace_id);
1010 });
1011 this.serialize(cx);
1012 let db = db.clone();
1013 cx.background_spawn(async move {
1014 db.set_session_binding(workspace_id, session_id, Some(window_id))
1015 .await
1016 .log_err();
1017 })
1018 })
1019 .unwrap();
1020 task.await
1021 })
1022 }
1023
1024 pub fn remove(
1025 &mut self,
1026 workspace: &Entity<Workspace>,
1027 window: &mut Window,
1028 cx: &mut Context<Self>,
1029 ) -> bool {
1030 let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
1031 return false;
1032 };
1033 if self.workspaces.len() <= 1 {
1034 return false;
1035 }
1036
1037 let removed_workspace = self.workspaces.remove(index);
1038
1039 if self.active_workspace_index >= self.workspaces.len() {
1040 self.active_workspace_index = self.workspaces.len() - 1;
1041 } else if self.active_workspace_index > index {
1042 self.active_workspace_index -= 1;
1043 }
1044
1045 self.detach_workspace(&removed_workspace, cx);
1046
1047 self.serialize(cx);
1048 self.focus_active_workspace(window, cx);
1049 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
1050 removed_workspace.entity_id(),
1051 ));
1052 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1053 cx.notify();
1054
1055 true
1056 }
1057
1058 pub fn move_workspace_to_new_window(
1059 &mut self,
1060 workspace: &Entity<Workspace>,
1061 window: &mut Window,
1062 cx: &mut Context<Self>,
1063 ) {
1064 let workspace = workspace.clone();
1065 if !self.remove(&workspace, window, cx) {
1066 return;
1067 }
1068
1069 let app_state: Arc<AppState> = workspace.read(cx).app_state().clone();
1070
1071 cx.defer(move |cx| {
1072 let options = (app_state.build_window_options)(None, cx);
1073
1074 let Ok(window) = cx.open_window(options, |window, cx| {
1075 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1076 }) else {
1077 return;
1078 };
1079
1080 let _ = window.update(cx, |_, window, _| {
1081 window.activate_window();
1082 });
1083 });
1084 }
1085
1086 pub fn move_project_group_to_new_window(
1087 &mut self,
1088 key: &ProjectGroupKey,
1089 window: &mut Window,
1090 cx: &mut Context<Self>,
1091 ) {
1092 let workspaces: Vec<_> = self
1093 .workspaces_for_project_group(key, cx)
1094 .cloned()
1095 .collect();
1096 if workspaces.is_empty() {
1097 return;
1098 }
1099
1100 self.project_group_keys.retain(|k| k != key);
1101
1102 let mut removed = Vec::new();
1103 for workspace in &workspaces {
1104 if self.remove(workspace, window, cx) {
1105 removed.push(workspace.clone());
1106 }
1107 }
1108
1109 if removed.is_empty() {
1110 return;
1111 }
1112
1113 let app_state = removed[0].read(cx).app_state().clone();
1114
1115 cx.defer(move |cx| {
1116 let options = (app_state.build_window_options)(None, cx);
1117
1118 let first = removed[0].clone();
1119 let rest = removed[1..].to_vec();
1120
1121 let Ok(new_window) = cx.open_window(options, |window, cx| {
1122 cx.new(|cx| MultiWorkspace::new(first, window, cx))
1123 }) else {
1124 return;
1125 };
1126
1127 new_window
1128 .update(cx, |mw, window, cx| {
1129 for workspace in rest {
1130 mw.activate(workspace, window, cx);
1131 }
1132 window.activate_window();
1133 })
1134 .log_err();
1135 });
1136 }
1137
1138 fn move_active_workspace_to_new_window(
1139 &mut self,
1140 _: &MoveWorkspaceToNewWindow,
1141 window: &mut Window,
1142 cx: &mut Context<Self>,
1143 ) {
1144 let workspace = self.workspace().clone();
1145 self.move_workspace_to_new_window(&workspace, window, cx);
1146 }
1147
1148 pub fn open_project(
1149 &mut self,
1150 paths: Vec<PathBuf>,
1151 open_mode: OpenMode,
1152 window: &mut Window,
1153 cx: &mut Context<Self>,
1154 ) -> Task<Result<Entity<Workspace>>> {
1155 if self.multi_workspace_enabled(cx) {
1156 self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1157 } else {
1158 let workspace = self.workspace().clone();
1159 cx.spawn_in(window, async move |_this, cx| {
1160 let should_continue = workspace
1161 .update_in(cx, |workspace, window, cx| {
1162 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1163 })?
1164 .await?;
1165 if should_continue {
1166 workspace
1167 .update_in(cx, |workspace, window, cx| {
1168 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1169 })?
1170 .await
1171 } else {
1172 Ok(workspace)
1173 }
1174 })
1175 }
1176 }
1177}
1178
1179impl Render for MultiWorkspace {
1180 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1181 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1182 let sidebar_side = self.sidebar_side(cx);
1183 let sidebar_on_right = sidebar_side == SidebarSide::Right;
1184
1185 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1186 self.sidebar.as_ref().map(|sidebar_handle| {
1187 let weak = cx.weak_entity();
1188
1189 let sidebar_width = sidebar_handle.width(cx);
1190 let resize_handle = deferred(
1191 div()
1192 .id("sidebar-resize-handle")
1193 .absolute()
1194 .when(!sidebar_on_right, |el| {
1195 el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1196 })
1197 .when(sidebar_on_right, |el| {
1198 el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1199 })
1200 .top(px(0.))
1201 .h_full()
1202 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1203 .cursor_col_resize()
1204 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1205 cx.stop_propagation();
1206 cx.new(|_| dragged.clone())
1207 })
1208 .on_mouse_down(MouseButton::Left, |_, _, cx| {
1209 cx.stop_propagation();
1210 })
1211 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1212 if event.click_count == 2 {
1213 weak.update(cx, |this, cx| {
1214 if let Some(sidebar) = this.sidebar.as_mut() {
1215 sidebar.set_width(None, cx);
1216 }
1217 this.serialize(cx);
1218 })
1219 .ok();
1220 cx.stop_propagation();
1221 } else {
1222 weak.update(cx, |this, cx| {
1223 this.serialize(cx);
1224 })
1225 .ok();
1226 }
1227 })
1228 .occlude(),
1229 );
1230
1231 div()
1232 .id("sidebar-container")
1233 .relative()
1234 .h_full()
1235 .w(sidebar_width)
1236 .flex_shrink_0()
1237 .child(sidebar_handle.to_any())
1238 .child(resize_handle)
1239 .into_any_element()
1240 })
1241 } else {
1242 None
1243 };
1244
1245 let (left_sidebar, right_sidebar) = if sidebar_on_right {
1246 (None, sidebar)
1247 } else {
1248 (sidebar, None)
1249 };
1250
1251 let ui_font = theme_settings::setup_ui_font(window, cx);
1252 let text_color = cx.theme().colors().text;
1253
1254 let workspace = self.workspace().clone();
1255 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1256 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1257
1258 client_side_decorations(
1259 root.key_context(workspace_key_context)
1260 .relative()
1261 .size_full()
1262 .font(ui_font)
1263 .text_color(text_color)
1264 .on_action(cx.listener(Self::close_window))
1265 .when(self.multi_workspace_enabled(cx), |this| {
1266 this.on_action(cx.listener(
1267 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1268 this.toggle_sidebar(window, cx);
1269 },
1270 ))
1271 .on_action(cx.listener(
1272 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1273 this.close_sidebar_action(window, cx);
1274 },
1275 ))
1276 .on_action(cx.listener(
1277 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1278 this.focus_sidebar(window, cx);
1279 },
1280 ))
1281 .on_action(cx.listener(Self::next_workspace))
1282 .on_action(cx.listener(Self::previous_workspace))
1283 .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1284 .on_action(cx.listener(
1285 |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1286 if let Some(sidebar) = &this.sidebar {
1287 sidebar.toggle_thread_switcher(action.select_last, window, cx);
1288 }
1289 },
1290 ))
1291 })
1292 .when(
1293 self.sidebar_open() && self.multi_workspace_enabled(cx),
1294 |this| {
1295 this.on_drag_move(cx.listener(
1296 move |this: &mut Self,
1297 e: &DragMoveEvent<DraggedSidebar>,
1298 window,
1299 cx| {
1300 if let Some(sidebar) = &this.sidebar {
1301 let new_width = if sidebar_on_right {
1302 window.bounds().size.width - e.event.position.x
1303 } else {
1304 e.event.position.x
1305 };
1306 sidebar.set_width(Some(new_width), cx);
1307 }
1308 },
1309 ))
1310 },
1311 )
1312 .children(left_sidebar)
1313 .child(
1314 div()
1315 .flex()
1316 .flex_1()
1317 .size_full()
1318 .overflow_hidden()
1319 .child(self.workspace().clone()),
1320 )
1321 .children(right_sidebar)
1322 .child(self.workspace().read(cx).modal_layer.clone())
1323 .children(self.sidebar_overlay.as_ref().map(|view| {
1324 deferred(div().absolute().size_full().inset_0().occlude().child(
1325 v_flex().h(px(0.0)).top_20().items_center().child(
1326 h_flex().occlude().child(view.clone()).on_mouse_down(
1327 MouseButton::Left,
1328 |_, _, cx| {
1329 cx.stop_propagation();
1330 },
1331 ),
1332 ),
1333 ))
1334 .with_priority(2)
1335 })),
1336 window,
1337 cx,
1338 Tiling {
1339 left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1340 right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1341 ..Tiling::default()
1342 },
1343 )
1344 }
1345}