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;
9#[cfg(any(test, feature = "test-support"))]
10use project::Project;
11use settings::Settings;
12use std::future::Future;
13use std::path::PathBuf;
14use std::sync::Arc;
15use ui::prelude::*;
16use util::ResultExt;
17use zed_actions::agents_sidebar::MoveWorkspaceToNewWindow;
18
19const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
20
21use crate::{
22 CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, Panel,
23 Workspace, WorkspaceId, client_side_decorations,
24};
25
26actions!(
27 multi_workspace,
28 [
29 /// Toggles the workspace switcher sidebar.
30 ToggleWorkspaceSidebar,
31 /// Closes the workspace sidebar.
32 CloseWorkspaceSidebar,
33 /// Moves focus to or from the workspace sidebar without closing it.
34 FocusWorkspaceSidebar,
35 /// Switches to the next workspace.
36 NextWorkspace,
37 /// Switches to the previous workspace.
38 PreviousWorkspace,
39 ]
40);
41
42pub enum MultiWorkspaceEvent {
43 ActiveWorkspaceChanged,
44 WorkspaceAdded(Entity<Workspace>),
45 WorkspaceRemoved(EntityId),
46}
47
48pub trait Sidebar: Focusable + Render + Sized {
49 fn width(&self, cx: &App) -> Pixels;
50 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
51 fn has_notifications(&self, cx: &App) -> bool;
52
53 fn is_threads_list_view_active(&self) -> bool {
54 true
55 }
56 /// Makes focus reset bac to the search editor upon toggling the sidebar from outside
57 fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
58}
59
60pub trait SidebarHandle: 'static + Send + Sync {
61 fn width(&self, cx: &App) -> Pixels;
62 fn set_width(&self, width: Option<Pixels>, cx: &mut App);
63 fn focus_handle(&self, cx: &App) -> FocusHandle;
64 fn focus(&self, window: &mut Window, cx: &mut App);
65 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
66 fn has_notifications(&self, cx: &App) -> bool;
67 fn to_any(&self) -> AnyView;
68 fn entity_id(&self) -> EntityId;
69
70 fn is_threads_list_view_active(&self, cx: &App) -> bool;
71}
72
73#[derive(Clone)]
74pub struct DraggedSidebar;
75
76impl Render for DraggedSidebar {
77 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
78 gpui::Empty
79 }
80}
81
82impl<T: Sidebar> SidebarHandle for Entity<T> {
83 fn width(&self, cx: &App) -> Pixels {
84 self.read(cx).width(cx)
85 }
86
87 fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
88 self.update(cx, |this, cx| this.set_width(width, cx))
89 }
90
91 fn focus_handle(&self, cx: &App) -> FocusHandle {
92 self.read(cx).focus_handle(cx)
93 }
94
95 fn focus(&self, window: &mut Window, cx: &mut App) {
96 let handle = self.read(cx).focus_handle(cx);
97 window.focus(&handle, cx);
98 }
99
100 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
101 self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
102 }
103
104 fn has_notifications(&self, cx: &App) -> bool {
105 self.read(cx).has_notifications(cx)
106 }
107
108 fn to_any(&self) -> AnyView {
109 self.clone().into()
110 }
111
112 fn entity_id(&self) -> EntityId {
113 Entity::entity_id(self)
114 }
115
116 fn is_threads_list_view_active(&self, cx: &App) -> bool {
117 self.read(cx).is_threads_list_view_active()
118 }
119}
120
121pub struct MultiWorkspace {
122 window_id: WindowId,
123 workspaces: Vec<Entity<Workspace>>,
124 active_workspace_index: usize,
125 sidebar: Option<Box<dyn SidebarHandle>>,
126 sidebar_open: bool,
127 pending_removal_tasks: Vec<Task<()>>,
128 _serialize_task: Option<Task<()>>,
129 _subscriptions: Vec<Subscription>,
130}
131
132impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
133
134impl MultiWorkspace {
135 pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
136 let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
137 if let Some(task) = this._serialize_task.take() {
138 task.detach();
139 }
140 for task in std::mem::take(&mut this.pending_removal_tasks) {
141 task.detach();
142 }
143 });
144 let quit_subscription = cx.on_app_quit(Self::app_will_quit);
145 let settings_subscription =
146 cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
147 if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
148 this.close_sidebar(window, cx);
149 }
150 });
151 Self::subscribe_to_workspace(&workspace, cx);
152 Self {
153 window_id: window.window_handle().window_id(),
154 workspaces: vec![workspace],
155 active_workspace_index: 0,
156 sidebar: None,
157 sidebar_open: false,
158 pending_removal_tasks: Vec::new(),
159 _serialize_task: None,
160 _subscriptions: vec![
161 release_subscription,
162 quit_subscription,
163 settings_subscription,
164 ],
165 }
166 }
167
168 pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
169 self._subscriptions
170 .push(cx.observe(&sidebar, |this, _, cx| {
171 let has_notifications = this.sidebar_has_notifications(cx);
172 let is_open = this.sidebar_open;
173 let show_toggle = this.multi_workspace_enabled(cx);
174 for workspace in &this.workspaces {
175 workspace.update(cx, |workspace, cx| {
176 workspace.set_workspace_sidebar_open(
177 is_open,
178 has_notifications,
179 show_toggle,
180 cx,
181 );
182 });
183 }
184 }));
185 self.sidebar = Some(Box::new(sidebar));
186 }
187
188 pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
189 self.sidebar.as_deref()
190 }
191
192 pub fn sidebar_open(&self) -> bool {
193 self.sidebar_open
194 }
195
196 pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
197 self.sidebar
198 .as_ref()
199 .map_or(false, |s| s.has_notifications(cx))
200 }
201
202 pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
203 self.sidebar
204 .as_ref()
205 .map_or(false, |s| s.is_threads_list_view_active(cx))
206 }
207
208 pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
209 cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
210 }
211
212 pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
213 if !self.multi_workspace_enabled(cx) {
214 return;
215 }
216
217 if self.sidebar_open {
218 self.close_sidebar(window, cx);
219 } else {
220 self.open_sidebar(cx);
221 if let Some(sidebar) = &self.sidebar {
222 sidebar.prepare_for_focus(window, cx);
223 sidebar.focus(window, cx);
224 }
225 }
226 }
227
228 pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
229 if !self.multi_workspace_enabled(cx) {
230 return;
231 }
232
233 if self.sidebar_open {
234 self.close_sidebar(window, cx);
235 }
236 }
237
238 pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
239 if !self.multi_workspace_enabled(cx) {
240 return;
241 }
242
243 if self.sidebar_open {
244 let sidebar_is_focused = self
245 .sidebar
246 .as_ref()
247 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
248
249 if sidebar_is_focused {
250 let pane = self.workspace().read(cx).active_pane().clone();
251 let pane_focus = pane.read(cx).focus_handle(cx);
252 window.focus(&pane_focus, cx);
253 } else if let Some(sidebar) = &self.sidebar {
254 sidebar.prepare_for_focus(window, cx);
255 sidebar.focus(window, cx);
256 }
257 } else {
258 self.open_sidebar(cx);
259 if let Some(sidebar) = &self.sidebar {
260 sidebar.prepare_for_focus(window, cx);
261 sidebar.focus(window, cx);
262 }
263 }
264 }
265
266 pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
267 self.sidebar_open = true;
268 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
269 let has_notifications = self.sidebar_has_notifications(cx);
270 let show_toggle = self.multi_workspace_enabled(cx);
271 for workspace in &self.workspaces {
272 workspace.update(cx, |workspace, cx| {
273 workspace.set_workspace_sidebar_open(true, has_notifications, show_toggle, cx);
274 workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
275 });
276 }
277 self.serialize(cx);
278 cx.notify();
279 }
280
281 pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
282 self.sidebar_open = false;
283 let has_notifications = self.sidebar_has_notifications(cx);
284 let show_toggle = self.multi_workspace_enabled(cx);
285 for workspace in &self.workspaces {
286 workspace.update(cx, |workspace, cx| {
287 workspace.set_workspace_sidebar_open(false, has_notifications, show_toggle, cx);
288 workspace.set_sidebar_focus_handle(None);
289 });
290 }
291 let pane = self.workspace().read(cx).active_pane().clone();
292 let pane_focus = pane.read(cx).focus_handle(cx);
293 window.focus(&pane_focus, cx);
294 self.serialize(cx);
295 cx.notify();
296 }
297
298 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
299 cx.spawn_in(window, async move |this, cx| {
300 let workspaces = this.update(cx, |multi_workspace, _cx| {
301 multi_workspace.workspaces().to_vec()
302 })?;
303
304 for workspace in workspaces {
305 let should_continue = workspace
306 .update_in(cx, |workspace, window, cx| {
307 workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
308 })?
309 .await?;
310 if !should_continue {
311 return anyhow::Ok(());
312 }
313 }
314
315 cx.update(|window, _cx| {
316 window.remove_window();
317 })?;
318
319 anyhow::Ok(())
320 })
321 .detach_and_log_err(cx);
322 }
323
324 fn subscribe_to_workspace(workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
325 cx.subscribe(workspace, |this, workspace, event, cx| {
326 if let WorkspaceEvent::Activate = event {
327 this.activate(workspace, cx);
328 }
329 })
330 .detach();
331 }
332
333 pub fn workspace(&self) -> &Entity<Workspace> {
334 &self.workspaces[self.active_workspace_index]
335 }
336
337 pub fn workspaces(&self) -> &[Entity<Workspace>] {
338 &self.workspaces
339 }
340
341 pub fn active_workspace_index(&self) -> usize {
342 self.active_workspace_index
343 }
344
345 pub fn activate(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
346 if !self.multi_workspace_enabled(cx) {
347 self.workspaces[0] = workspace;
348 self.active_workspace_index = 0;
349 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
350 cx.notify();
351 return;
352 }
353
354 let old_index = self.active_workspace_index;
355 let new_index = self.set_active_workspace(workspace, cx);
356 if old_index != new_index {
357 self.serialize(cx);
358 }
359 }
360
361 fn set_active_workspace(
362 &mut self,
363 workspace: Entity<Workspace>,
364 cx: &mut Context<Self>,
365 ) -> usize {
366 let index = self.add_workspace(workspace, cx);
367 let changed = self.active_workspace_index != index;
368 self.active_workspace_index = index;
369 if changed {
370 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
371 }
372 cx.notify();
373 index
374 }
375
376 /// Adds a workspace to this window without changing which workspace is active.
377 /// Returns the index of the workspace (existing or newly inserted).
378 pub fn add_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
379 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
380 index
381 } else {
382 if self.sidebar_open {
383 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
384 let has_notifications = self.sidebar_has_notifications(cx);
385 let show_toggle = self.multi_workspace_enabled(cx);
386 workspace.update(cx, |workspace, cx| {
387 workspace.set_workspace_sidebar_open(true, has_notifications, show_toggle, cx);
388 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
389 });
390 }
391 Self::subscribe_to_workspace(&workspace, cx);
392 self.workspaces.push(workspace.clone());
393 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
394 cx.notify();
395 self.workspaces.len() - 1
396 }
397 }
398
399 pub fn activate_index(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
400 debug_assert!(
401 index < self.workspaces.len(),
402 "workspace index out of bounds"
403 );
404 let changed = self.active_workspace_index != index;
405 self.active_workspace_index = index;
406 self.serialize(cx);
407 self.focus_active_workspace(window, cx);
408 if changed {
409 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
410 }
411 cx.notify();
412 }
413
414 fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
415 let count = self.workspaces.len() as isize;
416 if count <= 1 {
417 return;
418 }
419 let current = self.active_workspace_index as isize;
420 let next = ((current + delta).rem_euclid(count)) as usize;
421 self.activate_index(next, window, cx);
422 }
423
424 fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
425 self.cycle_workspace(1, window, cx);
426 }
427
428 fn previous_workspace(
429 &mut self,
430 _: &PreviousWorkspace,
431 window: &mut Window,
432 cx: &mut Context<Self>,
433 ) {
434 self.cycle_workspace(-1, window, cx);
435 }
436
437 fn serialize(&mut self, cx: &mut App) {
438 let window_id = self.window_id;
439 let state = crate::persistence::model::MultiWorkspaceState {
440 active_workspace_id: self.workspace().read(cx).database_id(),
441 sidebar_open: self.sidebar_open,
442 };
443 let kvp = db::kvp::KeyValueStore::global(cx);
444 self._serialize_task = Some(cx.background_spawn(async move {
445 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
446 }));
447 }
448
449 /// Returns the in-flight serialization task (if any) so the caller can
450 /// await it. Used by the quit handler to ensure pending DB writes
451 /// complete before the process exits.
452 pub fn flush_serialization(&mut self) -> Task<()> {
453 self._serialize_task.take().unwrap_or(Task::ready(()))
454 }
455
456 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
457 let mut tasks: Vec<Task<()>> = Vec::new();
458 if let Some(task) = self._serialize_task.take() {
459 tasks.push(task);
460 }
461 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
462
463 async move {
464 futures::future::join_all(tasks).await;
465 }
466 }
467
468 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
469 // If a dock panel is zoomed, focus it instead of the center pane.
470 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
471 // which closes the zoomed dock.
472 let focus_handle = {
473 let workspace = self.workspace().read(cx);
474 let mut target = None;
475 for dock in workspace.all_docks() {
476 let dock = dock.read(cx);
477 if dock.is_open() {
478 if let Some(panel) = dock.active_panel() {
479 if panel.is_zoomed(window, cx) {
480 target = Some(panel.panel_focus_handle(cx));
481 break;
482 }
483 }
484 }
485 }
486 target.unwrap_or_else(|| {
487 let pane = workspace.active_pane().clone();
488 pane.read(cx).focus_handle(cx)
489 })
490 };
491 window.focus(&focus_handle, cx);
492 }
493
494 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
495 self.workspace().read(cx).panel::<T>(cx)
496 }
497
498 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
499 self.workspace().read(cx).active_modal::<V>(cx)
500 }
501
502 pub fn add_panel<T: Panel>(
503 &mut self,
504 panel: Entity<T>,
505 window: &mut Window,
506 cx: &mut Context<Self>,
507 ) {
508 self.workspace().update(cx, |workspace, cx| {
509 workspace.add_panel(panel, window, cx);
510 });
511 }
512
513 pub fn focus_panel<T: Panel>(
514 &mut self,
515 window: &mut Window,
516 cx: &mut Context<Self>,
517 ) -> Option<Entity<T>> {
518 self.workspace()
519 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
520 }
521
522 // used in a test
523 pub fn toggle_modal<V: ModalView, B>(
524 &mut self,
525 window: &mut Window,
526 cx: &mut Context<Self>,
527 build: B,
528 ) where
529 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
530 {
531 self.workspace().update(cx, |workspace, cx| {
532 workspace.toggle_modal(window, cx, build);
533 });
534 }
535
536 pub fn toggle_dock(
537 &mut self,
538 dock_side: DockPosition,
539 window: &mut Window,
540 cx: &mut Context<Self>,
541 ) {
542 self.workspace().update(cx, |workspace, cx| {
543 workspace.toggle_dock(dock_side, window, cx);
544 });
545 }
546
547 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
548 self.workspace().read(cx).active_item_as::<I>(cx)
549 }
550
551 pub fn items_of_type<'a, T: Item>(
552 &'a self,
553 cx: &'a App,
554 ) -> impl 'a + Iterator<Item = Entity<T>> {
555 self.workspace().read(cx).items_of_type::<T>(cx)
556 }
557
558 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
559 self.workspace().read(cx).database_id()
560 }
561
562 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
563 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
564 .into_iter()
565 .filter(|task| !task.is_ready())
566 .collect();
567 tasks
568 }
569
570 #[cfg(any(test, feature = "test-support"))]
571 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
572 self.workspace().update(cx, |workspace, _cx| {
573 workspace.set_random_database_id();
574 });
575 }
576
577 #[cfg(any(test, feature = "test-support"))]
578 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
579 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
580 Self::new(workspace, window, cx)
581 }
582
583 #[cfg(any(test, feature = "test-support"))]
584 pub fn test_add_workspace(
585 &mut self,
586 project: Entity<Project>,
587 window: &mut Window,
588 cx: &mut Context<Self>,
589 ) -> Entity<Workspace> {
590 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
591 self.activate(workspace.clone(), cx);
592 workspace
593 }
594
595 #[cfg(any(test, feature = "test-support"))]
596 pub fn create_test_workspace(
597 &mut self,
598 window: &mut Window,
599 cx: &mut Context<Self>,
600 ) -> Task<()> {
601 let app_state = self.workspace().read(cx).app_state().clone();
602 let project = Project::local(
603 app_state.client.clone(),
604 app_state.node_runtime.clone(),
605 app_state.user_store.clone(),
606 app_state.languages.clone(),
607 app_state.fs.clone(),
608 None,
609 project::LocalProjectFlags::default(),
610 cx,
611 );
612 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
613 self.set_active_workspace(new_workspace.clone(), cx);
614 self.focus_active_workspace(window, cx);
615
616 let weak_workspace = new_workspace.downgrade();
617 let db = crate::persistence::WorkspaceDb::global(cx);
618 cx.spawn_in(window, async move |this, cx| {
619 let workspace_id = db.next_id().await.unwrap();
620 let workspace = weak_workspace.upgrade().unwrap();
621 let task: Task<()> = this
622 .update_in(cx, |this, window, cx| {
623 let session_id = workspace.read(cx).session_id();
624 let window_id = window.window_handle().window_id().as_u64();
625 workspace.update(cx, |workspace, _cx| {
626 workspace.set_database_id(workspace_id);
627 });
628 this.serialize(cx);
629 let db = db.clone();
630 cx.background_spawn(async move {
631 db.set_session_binding(workspace_id, session_id, Some(window_id))
632 .await
633 .log_err();
634 })
635 })
636 .unwrap();
637 task.await
638 })
639 }
640
641 pub fn remove_workspace(
642 &mut self,
643 index: usize,
644 window: &mut Window,
645 cx: &mut Context<Self>,
646 ) -> Option<Entity<Workspace>> {
647 if self.workspaces.len() <= 1 || index >= self.workspaces.len() {
648 return None;
649 }
650
651 let removed_workspace = self.workspaces.remove(index);
652
653 if self.active_workspace_index >= self.workspaces.len() {
654 self.active_workspace_index = self.workspaces.len() - 1;
655 } else if self.active_workspace_index > index {
656 self.active_workspace_index -= 1;
657 }
658
659 // Clear session_id and cancel any in-flight serialization on the
660 // removed workspace. Without this, a pending throttle timer from
661 // `serialize_workspace` could fire and write the old session_id
662 // back to the DB, resurrecting the workspace on next launch.
663 removed_workspace.update(cx, |workspace, _cx| {
664 workspace.session_id.take();
665 workspace._schedule_serialize_workspace.take();
666 workspace._serialize_workspace_task.take();
667 });
668
669 if let Some(workspace_id) = removed_workspace.read(cx).database_id() {
670 let db = crate::persistence::WorkspaceDb::global(cx);
671 self.pending_removal_tasks.retain(|task| !task.is_ready());
672 self.pending_removal_tasks
673 .push(cx.background_spawn(async move {
674 // Clear the session binding instead of deleting the row so
675 // the workspace still appears in the recent-projects list.
676 db.set_session_binding(workspace_id, None, None)
677 .await
678 .log_err();
679 }));
680 }
681
682 self.serialize(cx);
683 self.focus_active_workspace(window, cx);
684 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
685 removed_workspace.entity_id(),
686 ));
687 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
688 cx.notify();
689
690 Some(removed_workspace)
691 }
692
693 pub fn move_workspace_to_new_window(
694 &mut self,
695 index: usize,
696 window: &mut Window,
697 cx: &mut Context<Self>,
698 ) {
699 if self.workspaces.len() <= 1 || index >= self.workspaces.len() {
700 return;
701 }
702
703 let Some(workspace) = self.remove_workspace(index, window, cx) else {
704 return;
705 };
706
707 let app_state: Arc<crate::AppState> = workspace.read(cx).app_state().clone();
708
709 cx.defer(move |cx| {
710 let options = (app_state.build_window_options)(None, cx);
711
712 let Ok(window) = cx.open_window(options, |window, cx| {
713 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
714 }) else {
715 return;
716 };
717
718 let _ = window.update(cx, |_, window, _| {
719 window.activate_window();
720 });
721 });
722 }
723
724 fn move_active_workspace_to_new_window(
725 &mut self,
726 _: &MoveWorkspaceToNewWindow,
727 window: &mut Window,
728 cx: &mut Context<Self>,
729 ) {
730 let index = self.active_workspace_index;
731 self.move_workspace_to_new_window(index, window, cx);
732 }
733
734 pub fn open_project(
735 &mut self,
736 paths: Vec<PathBuf>,
737 window: &mut Window,
738 cx: &mut Context<Self>,
739 ) -> Task<Result<Entity<Workspace>>> {
740 let workspace = self.workspace().clone();
741
742 if self.multi_workspace_enabled(cx) {
743 workspace.update(cx, |workspace, cx| {
744 workspace.open_workspace_for_paths(true, paths, window, cx)
745 })
746 } else {
747 cx.spawn_in(window, async move |_this, cx| {
748 let should_continue = workspace
749 .update_in(cx, |workspace, window, cx| {
750 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
751 })?
752 .await?;
753 if should_continue {
754 workspace
755 .update_in(cx, |workspace, window, cx| {
756 workspace.open_workspace_for_paths(true, paths, window, cx)
757 })?
758 .await
759 } else {
760 Ok(workspace)
761 }
762 })
763 }
764 }
765}
766
767impl Render for MultiWorkspace {
768 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
769 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
770
771 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
772 self.sidebar.as_ref().map(|sidebar_handle| {
773 let weak = cx.weak_entity();
774
775 let sidebar_width = sidebar_handle.width(cx);
776 let resize_handle = deferred(
777 div()
778 .id("sidebar-resize-handle")
779 .absolute()
780 .right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
781 .top(px(0.))
782 .h_full()
783 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
784 .cursor_col_resize()
785 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
786 cx.stop_propagation();
787 cx.new(|_| dragged.clone())
788 })
789 .on_mouse_down(MouseButton::Left, |_, _, cx| {
790 cx.stop_propagation();
791 })
792 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
793 if event.click_count == 2 {
794 weak.update(cx, |this, cx| {
795 if let Some(sidebar) = this.sidebar.as_mut() {
796 sidebar.set_width(None, cx);
797 }
798 })
799 .ok();
800 cx.stop_propagation();
801 }
802 })
803 .occlude(),
804 );
805
806 div()
807 .id("sidebar-container")
808 .relative()
809 .h_full()
810 .w(sidebar_width)
811 .flex_shrink_0()
812 .child(sidebar_handle.to_any())
813 .child(resize_handle)
814 .into_any_element()
815 })
816 } else {
817 None
818 };
819
820 let ui_font = theme::setup_ui_font(window, cx);
821 let text_color = cx.theme().colors().text;
822
823 let workspace = self.workspace().clone();
824 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
825 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
826
827 client_side_decorations(
828 root.key_context(workspace_key_context)
829 .relative()
830 .size_full()
831 .font(ui_font)
832 .text_color(text_color)
833 .on_action(cx.listener(Self::close_window))
834 .when(self.multi_workspace_enabled(cx), |this| {
835 this.on_action(cx.listener(
836 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
837 this.toggle_sidebar(window, cx);
838 },
839 ))
840 .on_action(cx.listener(
841 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
842 this.close_sidebar_action(window, cx);
843 },
844 ))
845 .on_action(cx.listener(
846 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
847 this.focus_sidebar(window, cx);
848 },
849 ))
850 .on_action(cx.listener(Self::next_workspace))
851 .on_action(cx.listener(Self::previous_workspace))
852 .on_action(cx.listener(Self::move_active_workspace_to_new_window))
853 })
854 .when(
855 self.sidebar_open() && self.multi_workspace_enabled(cx),
856 |this| {
857 this.on_drag_move(cx.listener(
858 |this: &mut Self, e: &DragMoveEvent<DraggedSidebar>, _window, cx| {
859 if let Some(sidebar) = &this.sidebar {
860 let new_width = e.event.position.x;
861 sidebar.set_width(Some(new_width), cx);
862 }
863 },
864 ))
865 .children(sidebar)
866 },
867 )
868 .child(
869 div()
870 .flex()
871 .flex_1()
872 .size_full()
873 .overflow_hidden()
874 .child(self.workspace().clone()),
875 )
876 .child(self.workspace().read(cx).modal_layer.clone()),
877 window,
878 cx,
879 Tiling {
880 left: multi_workspace_enabled && self.sidebar_open(),
881 ..Tiling::default()
882 },
883 )
884 }
885}
886
887#[cfg(test)]
888mod tests {
889 use super::*;
890 use fs::FakeFs;
891 use gpui::TestAppContext;
892 use settings::SettingsStore;
893
894 fn init_test(cx: &mut TestAppContext) {
895 cx.update(|cx| {
896 let settings_store = SettingsStore::test(cx);
897 cx.set_global(settings_store);
898 theme::init(theme::LoadThemes::JustBase, cx);
899 DisableAiSettings::register(cx);
900 cx.update_flags(false, vec!["agent-v2".into()]);
901 });
902 }
903
904 #[gpui::test]
905 async fn test_sidebar_disabled_when_disable_ai_is_enabled(cx: &mut TestAppContext) {
906 init_test(cx);
907 let fs = FakeFs::new(cx.executor());
908 let project = Project::test(fs, [], cx).await;
909
910 let (multi_workspace, cx) =
911 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
912
913 multi_workspace.read_with(cx, |mw, cx| {
914 assert!(mw.multi_workspace_enabled(cx));
915 });
916
917 multi_workspace.update_in(cx, |mw, _window, cx| {
918 mw.open_sidebar(cx);
919 assert!(mw.sidebar_open());
920 });
921
922 cx.update(|_window, cx| {
923 DisableAiSettings::override_global(DisableAiSettings { disable_ai: true }, cx);
924 });
925 cx.run_until_parked();
926
927 multi_workspace.read_with(cx, |mw, cx| {
928 assert!(
929 !mw.sidebar_open(),
930 "Sidebar should be closed when disable_ai is true"
931 );
932 assert!(
933 !mw.multi_workspace_enabled(cx),
934 "Multi-workspace should be disabled when disable_ai is true"
935 );
936 });
937
938 multi_workspace.update_in(cx, |mw, window, cx| {
939 mw.toggle_sidebar(window, cx);
940 });
941 multi_workspace.read_with(cx, |mw, _cx| {
942 assert!(
943 !mw.sidebar_open(),
944 "Sidebar should remain closed when toggled with disable_ai true"
945 );
946 });
947
948 cx.update(|_window, cx| {
949 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
950 });
951 cx.run_until_parked();
952
953 multi_workspace.read_with(cx, |mw, cx| {
954 assert!(
955 mw.multi_workspace_enabled(cx),
956 "Multi-workspace should be enabled after re-enabling AI"
957 );
958 assert!(
959 !mw.sidebar_open(),
960 "Sidebar should still be closed after re-enabling AI (not auto-opened)"
961 );
962 });
963
964 multi_workspace.update_in(cx, |mw, window, cx| {
965 mw.toggle_sidebar(window, cx);
966 });
967 multi_workspace.read_with(cx, |mw, _cx| {
968 assert!(
969 mw.sidebar_open(),
970 "Sidebar should open when toggled after re-enabling AI"
971 );
972 });
973 }
974}