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, actions,
  6    deferred, px,
  7};
  8use project::Project;
  9use std::path::PathBuf;
 10use ui::prelude::*;
 11
 12const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
 13
 14use crate::{
 15    DockPosition, Item, ModalView, Panel, Workspace, WorkspaceId, client_side_decorations,
 16};
 17
 18actions!(
 19    multi_workspace,
 20    [
 21        /// Creates a new workspace within the current window.
 22        NewWorkspaceInWindow,
 23        /// Switches to the next workspace within the current window.
 24        NextWorkspaceInWindow,
 25        /// Switches to the previous workspace within the current window.
 26        PreviousWorkspaceInWindow,
 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 SidebarEvent {
 35    Open,
 36    Close,
 37}
 38
 39pub trait Sidebar: EventEmitter<SidebarEvent> + Focusable + Render + Sized {
 40    fn width(&self, cx: &App) -> Pixels;
 41    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 42    fn has_notifications(&self, cx: &App) -> bool;
 43}
 44
 45pub trait SidebarHandle: 'static + Send + Sync {
 46    fn width(&self, cx: &App) -> Pixels;
 47    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 48    fn focus_handle(&self, cx: &App) -> FocusHandle;
 49    fn focus(&self, window: &mut Window, cx: &mut App);
 50    fn has_notifications(&self, cx: &App) -> bool;
 51    fn to_any(&self) -> AnyView;
 52    fn entity_id(&self) -> EntityId;
 53}
 54
 55#[derive(Clone)]
 56pub struct DraggedSidebar;
 57
 58impl Render for DraggedSidebar {
 59    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 60        gpui::Empty
 61    }
 62}
 63
 64impl<T: Sidebar> SidebarHandle for Entity<T> {
 65    fn width(&self, cx: &App) -> Pixels {
 66        self.read(cx).width(cx)
 67    }
 68
 69    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 70        self.update(cx, |this, cx| this.set_width(width, cx))
 71    }
 72
 73    fn focus_handle(&self, cx: &App) -> FocusHandle {
 74        self.read(cx).focus_handle(cx)
 75    }
 76
 77    fn focus(&self, window: &mut Window, cx: &mut App) {
 78        let handle = self.read(cx).focus_handle(cx);
 79        window.focus(&handle, cx);
 80    }
 81
 82    fn has_notifications(&self, cx: &App) -> bool {
 83        self.read(cx).has_notifications(cx)
 84    }
 85
 86    fn to_any(&self) -> AnyView {
 87        self.clone().into()
 88    }
 89
 90    fn entity_id(&self) -> EntityId {
 91        Entity::entity_id(self)
 92    }
 93}
 94
 95pub struct MultiWorkspace {
 96    workspaces: Vec<Entity<Workspace>>,
 97    active_workspace_index: usize,
 98    sidebar: Option<Box<dyn SidebarHandle>>,
 99    sidebar_open: bool,
100    _sidebar_subscription: Option<Subscription>,
101}
102
103impl MultiWorkspace {
104    pub fn new(workspace: Entity<Workspace>, _cx: &mut Context<Self>) -> Self {
105        Self {
106            workspaces: vec![workspace],
107            active_workspace_index: 0,
108            sidebar: None,
109            sidebar_open: false,
110            _sidebar_subscription: None,
111        }
112    }
113
114    pub fn register_sidebar<T: Sidebar>(
115        &mut self,
116        sidebar: Entity<T>,
117        window: &mut Window,
118        cx: &mut Context<Self>,
119    ) {
120        let subscription =
121            cx.subscribe_in(&sidebar, window, |this, _, event, window, cx| match event {
122                SidebarEvent::Open => this.toggle_sidebar(window, cx),
123                SidebarEvent::Close => {
124                    this.close_sidebar(window, cx);
125                }
126            });
127        self.sidebar = Some(Box::new(sidebar));
128        self._sidebar_subscription = Some(subscription);
129    }
130
131    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
132        self.sidebar.as_deref()
133    }
134
135    pub fn sidebar_open(&self) -> bool {
136        self.sidebar_open && self.sidebar.is_some()
137    }
138
139    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
140        self.sidebar
141            .as_ref()
142            .map_or(false, |s| s.has_notifications(cx))
143    }
144
145    pub(crate) fn multi_workspace_enabled(&self, cx: &App) -> bool {
146        cx.has_flag::<AgentV2FeatureFlag>()
147    }
148
149    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
150        if !self.multi_workspace_enabled(cx) {
151            return;
152        }
153
154        if self.sidebar_open {
155            self.close_sidebar(window, cx);
156        } else {
157            self.open_sidebar(window, cx);
158            if let Some(sidebar) = &self.sidebar {
159                sidebar.focus(window, cx);
160            }
161        }
162    }
163
164    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
165        if !self.multi_workspace_enabled(cx) {
166            return;
167        }
168
169        if self.sidebar_open {
170            let sidebar_is_focused = self
171                .sidebar
172                .as_ref()
173                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
174
175            if sidebar_is_focused {
176                let pane = self.workspace().read(cx).active_pane().clone();
177                let pane_focus = pane.read(cx).focus_handle(cx);
178                window.focus(&pane_focus, cx);
179            } else if let Some(sidebar) = &self.sidebar {
180                sidebar.focus(window, cx);
181            }
182        } else {
183            self.open_sidebar(window, cx);
184            if let Some(sidebar) = &self.sidebar {
185                sidebar.focus(window, cx);
186            }
187        }
188    }
189
190    pub fn open_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
191        self.sidebar_open = true;
192        for workspace in &self.workspaces {
193            workspace.update(cx, |workspace, cx| {
194                workspace.set_workspace_sidebar_open(true, cx);
195            });
196        }
197        self.serialize(window, cx);
198        cx.notify();
199    }
200
201    fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
202        self.sidebar_open = false;
203        for workspace in &self.workspaces {
204            workspace.update(cx, |workspace, cx| {
205                workspace.set_workspace_sidebar_open(false, cx);
206            });
207        }
208        let pane = self.workspace().read(cx).active_pane().clone();
209        let pane_focus = pane.read(cx).focus_handle(cx);
210        window.focus(&pane_focus, cx);
211        self.serialize(window, cx);
212        cx.notify();
213    }
214
215    pub fn is_sidebar_open(&self) -> bool {
216        self.sidebar_open
217    }
218
219    pub fn workspace(&self) -> &Entity<Workspace> {
220        &self.workspaces[self.active_workspace_index]
221    }
222
223    pub fn workspaces(&self) -> &[Entity<Workspace>] {
224        &self.workspaces
225    }
226
227    pub fn active_workspace_index(&self) -> usize {
228        self.active_workspace_index
229    }
230
231    pub fn activate(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
232        if !self.multi_workspace_enabled(cx) {
233            self.workspaces[0] = workspace;
234            self.active_workspace_index = 0;
235            cx.notify();
236            return;
237        }
238
239        let index = self.add_workspace(workspace, cx);
240        if self.active_workspace_index != index {
241            self.active_workspace_index = index;
242            cx.notify();
243        }
244    }
245
246    /// Adds a workspace to this window without changing which workspace is active.
247    /// Returns the index of the workspace (existing or newly inserted).
248    pub fn add_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
249        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
250            index
251        } else {
252            if self.sidebar_open {
253                workspace.update(cx, |workspace, cx| {
254                    workspace.set_workspace_sidebar_open(true, cx);
255                });
256            }
257            self.workspaces.push(workspace);
258            cx.notify();
259            self.workspaces.len() - 1
260        }
261    }
262
263    pub fn activate_index(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
264        debug_assert!(
265            index < self.workspaces.len(),
266            "workspace index out of bounds"
267        );
268        self.active_workspace_index = index;
269        self.serialize(window, cx);
270        self.focus_active_workspace(window, cx);
271        cx.notify();
272    }
273
274    pub fn activate_next_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
275        if self.workspaces.len() > 1 {
276            let next_index = (self.active_workspace_index + 1) % self.workspaces.len();
277            self.activate_index(next_index, window, cx);
278        }
279    }
280
281    pub fn activate_previous_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
282        if self.workspaces.len() > 1 {
283            let prev_index = if self.active_workspace_index == 0 {
284                self.workspaces.len() - 1
285            } else {
286                self.active_workspace_index - 1
287            };
288            self.activate_index(prev_index, window, cx);
289        }
290    }
291
292    fn serialize(&self, window: &mut Window, cx: &mut App) {
293        let window_id = window.window_handle().window_id();
294        let state = crate::persistence::model::MultiWorkspaceState {
295            active_workspace_id: self.workspace().read(cx).database_id(),
296            sidebar_open: self.sidebar_open,
297        };
298        cx.background_spawn(async move {
299            crate::persistence::write_multi_workspace_state(window_id, state).await;
300        })
301        .detach();
302    }
303
304    fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
305        let pane = self.workspace().read(cx).active_pane().clone();
306        let focus_handle = pane.read(cx).focus_handle(cx);
307        window.focus(&focus_handle, cx);
308    }
309
310    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
311        self.workspace().read(cx).panel::<T>(cx)
312    }
313
314    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
315        self.workspace().read(cx).active_modal::<V>(cx)
316    }
317
318    pub fn add_panel<T: Panel>(
319        &mut self,
320        panel: Entity<T>,
321        window: &mut Window,
322        cx: &mut Context<Self>,
323    ) {
324        self.workspace().update(cx, |workspace, cx| {
325            workspace.add_panel(panel, window, cx);
326        });
327    }
328
329    pub fn focus_panel<T: Panel>(
330        &mut self,
331        window: &mut Window,
332        cx: &mut Context<Self>,
333    ) -> Option<Entity<T>> {
334        self.workspace()
335            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
336    }
337
338    pub fn toggle_modal<V: ModalView, B>(
339        &mut self,
340        window: &mut Window,
341        cx: &mut Context<Self>,
342        build: B,
343    ) where
344        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
345    {
346        self.workspace().update(cx, |workspace, cx| {
347            workspace.toggle_modal(window, cx, build);
348        });
349    }
350
351    pub fn toggle_dock(
352        &mut self,
353        dock_side: DockPosition,
354        window: &mut Window,
355        cx: &mut Context<Self>,
356    ) {
357        self.workspace().update(cx, |workspace, cx| {
358            workspace.toggle_dock(dock_side, window, cx);
359        });
360    }
361
362    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
363        self.workspace().read(cx).active_item_as::<I>(cx)
364    }
365
366    pub fn items_of_type<'a, T: Item>(
367        &'a self,
368        cx: &'a App,
369    ) -> impl 'a + Iterator<Item = Entity<T>> {
370        self.workspace().read(cx).items_of_type::<T>(cx)
371    }
372
373    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
374        self.workspace().read(cx).database_id()
375    }
376
377    #[cfg(any(test, feature = "test-support"))]
378    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
379        self.workspace().update(cx, |workspace, _cx| {
380            workspace.set_random_database_id();
381        });
382    }
383
384    #[cfg(any(test, feature = "test-support"))]
385    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
386        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
387        Self::new(workspace, cx)
388    }
389
390    #[cfg(any(test, feature = "test-support"))]
391    pub fn test_add_workspace(
392        &mut self,
393        project: Entity<Project>,
394        window: &mut Window,
395        cx: &mut Context<Self>,
396    ) -> Entity<Workspace> {
397        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
398        self.activate(workspace.clone(), cx);
399        workspace
400    }
401
402    pub fn create_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
403        if !self.multi_workspace_enabled(cx) {
404            return;
405        }
406        let app_state = self.workspace().read(cx).app_state().clone();
407        let project = Project::local(
408            app_state.client.clone(),
409            app_state.node_runtime.clone(),
410            app_state.user_store.clone(),
411            app_state.languages.clone(),
412            app_state.fs.clone(),
413            None,
414            project::LocalProjectFlags::default(),
415            cx,
416        );
417        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
418        self.activate(new_workspace, cx);
419        self.focus_active_workspace(window, cx);
420    }
421
422    pub fn remove_workspace(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
423        if self.workspaces.len() <= 1 || index >= self.workspaces.len() {
424            return;
425        }
426
427        self.workspaces.remove(index);
428
429        if self.active_workspace_index >= self.workspaces.len() {
430            self.active_workspace_index = self.workspaces.len() - 1;
431        } else if self.active_workspace_index > index {
432            self.active_workspace_index -= 1;
433        }
434
435        self.focus_active_workspace(window, cx);
436        cx.notify();
437    }
438
439    pub fn open_project(
440        &mut self,
441        paths: Vec<PathBuf>,
442        window: &mut Window,
443        cx: &mut Context<Self>,
444    ) -> Task<Result<()>> {
445        let workspace = self.workspace().clone();
446
447        if self.multi_workspace_enabled(cx) {
448            workspace.update(cx, |workspace, cx| {
449                workspace.open_workspace_for_paths(true, paths, window, cx)
450            })
451        } else {
452            cx.spawn_in(window, async move |_this, cx| {
453                let should_continue = workspace
454                    .update_in(cx, |workspace, window, cx| {
455                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
456                    })?
457                    .await?;
458                if should_continue {
459                    workspace
460                        .update_in(cx, |workspace, window, cx| {
461                            workspace.open_workspace_for_paths(true, paths, window, cx)
462                        })?
463                        .await
464                } else {
465                    Ok(())
466                }
467            })
468        }
469    }
470}
471
472impl Render for MultiWorkspace {
473    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
474        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
475
476        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open {
477            self.sidebar.as_ref().map(|sidebar_handle| {
478                let weak = cx.weak_entity();
479
480                let sidebar_width = sidebar_handle.width(cx);
481                let resize_handle = deferred(
482                    div()
483                        .id("sidebar-resize-handle")
484                        .absolute()
485                        .right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
486                        .top(px(0.))
487                        .h_full()
488                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
489                        .cursor_col_resize()
490                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
491                            cx.stop_propagation();
492                            cx.new(|_| dragged.clone())
493                        })
494                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
495                            cx.stop_propagation();
496                        })
497                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
498                            if event.click_count == 2 {
499                                weak.update(cx, |this, cx| {
500                                    if let Some(sidebar) = this.sidebar.as_mut() {
501                                        sidebar.set_width(None, cx);
502                                    }
503                                })
504                                .ok();
505                                cx.stop_propagation();
506                            }
507                        })
508                        .occlude(),
509                );
510
511                div()
512                    .id("sidebar-container")
513                    .relative()
514                    .h_full()
515                    .w(sidebar_width)
516                    .flex_shrink_0()
517                    .child(sidebar_handle.to_any())
518                    .child(resize_handle)
519                    .into_any_element()
520            })
521        } else {
522            None
523        };
524
525        client_side_decorations(
526            h_flex()
527                .key_context("Workspace")
528                .size_full()
529                .on_action(
530                    cx.listener(|this: &mut Self, _: &NewWorkspaceInWindow, window, cx| {
531                        this.create_workspace(window, cx);
532                    }),
533                )
534                .on_action(
535                    cx.listener(|this: &mut Self, _: &NextWorkspaceInWindow, window, cx| {
536                        this.activate_next_workspace(window, cx);
537                    }),
538                )
539                .on_action(cx.listener(
540                    |this: &mut Self, _: &PreviousWorkspaceInWindow, window, cx| {
541                        this.activate_previous_workspace(window, cx);
542                    },
543                ))
544                .on_action(cx.listener(
545                    |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
546                        this.toggle_sidebar(window, cx);
547                    },
548                ))
549                .on_action(
550                    cx.listener(|this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
551                        this.focus_sidebar(window, cx);
552                    }),
553                )
554                .when(
555                    self.sidebar_open() && self.multi_workspace_enabled(cx),
556                    |this| {
557                        this.on_drag_move(cx.listener(
558                            |this: &mut Self, e: &DragMoveEvent<DraggedSidebar>, _window, cx| {
559                                if let Some(sidebar) = &this.sidebar {
560                                    let new_width = e.event.position.x;
561                                    sidebar.set_width(Some(new_width), cx);
562                                }
563                            },
564                        ))
565                        .children(sidebar)
566                    },
567                )
568                .child(
569                    div()
570                        .flex()
571                        .flex_1()
572                        .size_full()
573                        .overflow_hidden()
574                        .child(self.workspace().clone()),
575                ),
576            window,
577            cx,
578            Tiling {
579                left: multi_workspace_enabled && self.sidebar_open,
580                ..Tiling::default()
581            },
582        )
583    }
584}