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