multi_workspace.rs

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