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