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