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