Skip to main content

gpui_component/dock/
dock.rs

1//! The gpui-component appearance for the dock area: the outer frame, the
2//! split frames, and one dock's chrome.
3
4use std::{rc::Rc, sync::Arc};
5
6use gpui::{
7    AnyElement, App, AppContext as _, Axis, Context, Div, Element, Empty, InteractiveElement as _,
8    IntoElement, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Render, Stateful, Style,
9    Styled as _, Window, div, px,
10};
11use gpui_base::{
12    HandleEdge, ResizeHandleContext,
13    dock::{
14        CLOSED_BOTTOM_STRIP, DockAreaRenderer, DockContext, DockEvent, DockPlacement, NodeId,
15        PanelState, PanelView, TabGroupRenderer,
16    },
17};
18
19use crate::{
20    ActiveTheme as _,
21    dock::{
22        DockSkin, SkinShared, invalid_panel::InvalidPanel, panel_handle, report_user_toggle,
23        tab_panel::TabGroupSkin,
24    },
25    resizable::render_resize_handle_with,
26    resize_handle,
27};
28
29/// The payload a dock's resize handle drags. It draws nothing: the handle
30/// itself is the affordance.
31#[derive(Clone)]
32struct ResizePanel;
33
34impl Render for ResizePanel {
35    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
36        Empty
37    }
38}
39
40impl DockAreaRenderer for DockSkin {
41    fn closed_dock_extent(&self, placement: DockPlacement) -> Pixels {
42        match placement {
43            DockPlacement::Bottom if self.shared().collapsed_tab_bar_visible.get() => {
44                CLOSED_BOTTOM_STRIP
45            }
46            _ => px(0.),
47        }
48    }
49
50    // The row, the fill and the clip are base's now -- applied around whatever
51    // these return -- so a skin that has no appearance to add returns a bare
52    // frame and still gets a dock area the right shape.
53    fn frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
54        div().id("dock-area")
55    }
56
57    fn center_frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
58        div().id("dock-area-center")
59    }
60
61    fn render_split_handle(
62        &self,
63        handle: &ResizeHandleContext,
64        window: &mut Window,
65        cx: &mut App,
66    ) -> Option<AnyElement> {
67        let line = self.shared().split_divider_line_visible.get();
68        Some(render_resize_handle_with(handle, line, window, cx))
69    }
70
71    fn split_frame(&self, node: NodeId, _: Axis, _: &mut Window, cx: &mut App) -> Stateful<Div> {
72        // The size is base's; the background is this skin's, and is the only
73        // reason this hook is implemented at all.
74        div()
75            .id(("dock-split-frame", node.as_u64()))
76            .bg(cx.theme().tokens.tab_bar)
77    }
78
79    fn render_dock(
80        &self,
81        dock: &DockContext,
82        content: AnyElement,
83        window: &mut Window,
84        cx: &mut App,
85    ) -> AnyElement {
86        // No box here any more. A dock's extent is structural, so
87        // `DockArea::render_dock` applies it around whatever this returns --
88        // which also means a renderer that draws no chrome still gets a dock
89        // the right shape. This adds the edge you drag and nothing else.
90        div()
91            .flex()
92            .size_full()
93            .relative()
94            .child(content)
95            .child(self.render_resize_handle(dock, window, cx))
96            .child(DockResizeTracker {
97                dock: dock.clone(),
98                shared: self.shared().clone(),
99            })
100            .into_any_element()
101    }
102
103    /// The "unknown panel" message the old `InvalidPanel` drew.
104    ///
105    /// It answers `dump` with the state it was handed, so a layout written by
106    /// a build that knows the panel survives a load and save here.
107    fn build_placeholder(
108        &self,
109        state: &PanelState,
110        _: &mut Window,
111        cx: &mut App,
112    ) -> Option<Arc<dyn PanelView>> {
113        let state = state.clone();
114        Some(panel_handle(cx.new(|cx| InvalidPanel::new(state, cx))))
115    }
116
117    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
118        Rc::new(TabGroupSkin::new(self.shared().clone()))
119    }
120}
121
122impl DockSkin {
123    fn render_resize_handle(
124        &self,
125        dock: &DockContext,
126        _: &mut Window,
127        cx: &mut App,
128    ) -> impl IntoElement {
129        let placement = dock.placement();
130        let physical = placement.physical(gpui_base::LayoutDirection::global(cx));
131        let open = dock.is_open();
132        let shared = self.shared().clone();
133
134        // One id per placement: the docks all render under the same stateful
135        // ancestor, so a shared literal would collapse the handles into one
136        // GlobalElementId and GPUI would silently share their element state —
137        // a press on the left handle then starts the right handle's drag.
138        let id = match placement {
139            DockPlacement::Left => "resize-handle-left",
140            DockPlacement::Right => "resize-handle-right",
141            DockPlacement::Bottom => "resize-handle-bottom",
142            DockPlacement::Center => "resize-handle-center",
143        };
144
145        // Every dock's handle lives inside the dock, because `dock_frame` clips
146        // to the dock's box. The left dock hugs its trailing edge; the right
147        // and bottom docks hug their leading one.
148        let edge = match physical {
149            DockPlacement::Left => HandleEdge::Trailing,
150            _ => HandleEdge::Leading,
151        };
152
153        resize_handle(id, placement.axis()).inside(edge).on_drag(
154            ResizePanel,
155            move |info, _, _, cx| {
156                cx.stop_propagation();
157                shared.resizing_dock().set(Some(placement));
158                shared.resize_started_open().set(open);
159                cx.new(|_| info.clone())
160            },
161        )
162    }
163}
164
165/// Turns the window's mouse stream into dock resizing.
166///
167/// A resize is driven by pointer moves that land anywhere in the window, not
168/// only on the handle, so it cannot be expressed as a listener on the handle
169/// itself. This element paints nothing and exists for its `paint` hook, which
170/// is the only place a window-level mouse listener can be registered — which
171/// is why it stays in the skin rather than moving into base: it is a
172/// paint-order concern of this appearance.
173struct DockResizeTracker {
174    dock: DockContext,
175    shared: Rc<SkinShared>,
176}
177
178impl Element for DockResizeTracker {
179    type RequestLayoutState = ();
180    type PrepaintState = ();
181
182    fn id(&self) -> Option<gpui::ElementId> {
183        None
184    }
185
186    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
187        None
188    }
189
190    fn request_layout(
191        &mut self,
192        _: Option<&gpui::GlobalElementId>,
193        _: Option<&gpui::InspectorElementId>,
194        window: &mut Window,
195        cx: &mut App,
196    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
197        (window.request_layout(Style::default(), None, cx), ())
198    }
199
200    fn prepaint(
201        &mut self,
202        _: Option<&gpui::GlobalElementId>,
203        _: Option<&gpui::InspectorElementId>,
204        _: gpui::Bounds<Pixels>,
205        _: &mut Self::RequestLayoutState,
206        _: &mut Window,
207        _: &mut App,
208    ) -> Self::PrepaintState {
209    }
210
211    fn paint(
212        &mut self,
213        _: Option<&gpui::GlobalElementId>,
214        _: Option<&gpui::InspectorElementId>,
215        _: gpui::Bounds<Pixels>,
216        _: &mut Self::RequestLayoutState,
217        _: &mut Self::PrepaintState,
218        window: &mut Window,
219        _: &mut App,
220    ) {
221        let placement = self.dock.placement();
222
223        window.on_mouse_event({
224            let dock = self.dock.clone();
225            let shared = self.shared.clone();
226            move |event: &MouseMoveEvent, phase, window, cx| {
227                if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
228                    return;
229                }
230                // Base opens, closes and sizes the dock from the pointer, so a
231                // drag that started on a closed dock reopens it too.
232                dock.resize_to(event.position, window, cx);
233            }
234        });
235
236        window.on_mouse_event({
237            let dock = self.dock.clone();
238            let shared = self.shared.clone();
239            move |_: &MouseUpEvent, phase, window, cx| {
240                if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
241                    return;
242                }
243                shared.resizing_dock().set(None);
244                dock.end_resize(window, cx);
245                let was_open = shared.resize_started_open().get();
246                // The size lives on the dock, not in the layout tree, so
247                // nothing else tells a subscriber to persist it.
248                _ = shared.area().update(cx, |area, cx| {
249                    cx.emit(DockEvent::LayoutChanged);
250                    report_user_toggle(area, placement, was_open, cx);
251                });
252            }
253        });
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use std::rc::Rc;
260
261    use gpui::{
262        App, Entity, IntoElement as _, Modifiers, MouseButton, TestAppContext, VisualTestContext,
263        Window, point, px, size,
264    };
265
266    use std::cell::Cell;
267
268    use gpui_base::dock::DockAreaRenderer;
269
270    use gpui_base::PANEL_MIN_SIZE;
271
272    use crate::dock::{
273        CLOSED_BOTTOM_STRIP, DockArea, DockLayout, DockPlacement, DockSkin,
274        test_support::{MeasuredProbe, SizedProbe},
275    };
276
277    /// A renderer that draws no chrome at all: every hook at its trait default.
278    ///
279    /// This is the position every renderer that is not `DockSkin` starts from,
280    /// including the one gpui-shell installs so a script can draw the chrome
281    /// itself, and the shape of what it gets is base's promise.
282    struct ChromelessDockSkin;
283
284    impl DockAreaRenderer for ChromelessDockSkin {
285        fn tab_group_renderer(&self) -> Rc<dyn gpui_base::dock::TabGroupRenderer> {
286            Rc::new(ChromelessTabs)
287        }
288    }
289
290    struct ChromelessTabs;
291    impl gpui_base::dock::TabGroupRenderer for ChromelessTabs {
292        // The one hook with no default, because a group with no tab bar has no
293        // way to choose between its panels. Drawn as nothing, so the height it
294        // leaves the content is the whole group.
295        fn render_tab_bar(
296            &self,
297            _: &gpui_base::dock::TabGroupContext,
298            _: &mut Window,
299            _: &mut App,
300        ) -> gpui::AnyElement {
301            gpui::Empty.into_any_element()
302        }
303    }
304
305    /// A dock's box is base's, not its renderer's.
306    ///
307    /// This is the regression. The extent lived in `DockSkin::render_dock`, so
308    /// it was reachable only through that one renderer, and `render_dock`'s
309    /// trait default hands the content straight back. A dock that never states
310    /// its extent is not a column beside the centre: it takes whatever the row
311    /// gives it and the panes inside shrink to their content. Nothing failed,
312    /// and nothing said why.
313    #[gpui::test]
314    fn a_dock_is_its_own_width_under_a_renderer_that_draws_no_chrome(cx: &mut TestAppContext) {
315        cx.update(|cx| crate::init(cx));
316        let measured = Rc::new(Cell::new(gpui::Size::default()));
317        let probe = measured.clone();
318        let centre = Rc::new(Cell::new(gpui::Size::default()));
319        let centre_probe = centre.clone();
320        let (area, cx) = cx.add_window_view(|window, cx| {
321            DockArea::new("test", None, window, cx).with_renderer(Rc::new(ChromelessDockSkin))
322        });
323        cx.simulate_resize(size(px(800.), px(600.)));
324        cx.update(|window, cx| {
325            area.update(cx, |area, cx| {
326                area.set_center(
327                    DockLayout::tabs().panel(SizedProbe::new(centre_probe, cx)),
328                    window,
329                    cx,
330                );
331                area.set_dock(
332                    DockPlacement::Right,
333                    DockLayout::tabs().panel(SizedProbe::new(probe, cx)),
334                    window,
335                    cx,
336                );
337                area.set_dock_size(DockPlacement::Right, px(200.), window, cx);
338            });
339        });
340        cx.run_until_parked();
341        cx.update(|window, cx| {
342            area.update(cx, |area, cx| {
343                if !area.is_dock_open(DockPlacement::Right) {
344                    area.toggle_dock(DockPlacement::Right, window, cx);
345                }
346            });
347        });
348        cx.run_until_parked();
349        cx.update(|window, cx| window.draw(cx).clear(cx));
350
351        let dock = measured.get().width;
352        assert_eq!(
353            dock,
354            px(200.),
355            "the right dock has to be its own width, not the area's: got {dock:?}"
356        );
357        // The other half of the same fault: a dock area that is not a row puts
358        // the centre above the dock at the area's full width instead of beside
359        // it at what the dock leaves.
360        let middle = centre.get().width;
361        assert_eq!(
362            middle,
363            px(600.),
364            "the centre has to be what the docks leave: got {middle:?}"
365        );
366        // This renderer draws no tab bar, so a group that fills its slot leaves
367        // its panel the whole 600. A tab group frame without a column and a
368        // fill gives it nothing: the panel is positioned absolutely inside the
369        // content region and contributes no height of its own, so the region
370        // resolves to zero and the group is a strip of tabs.
371        let tall = centre.get().height;
372        assert_eq!(
373            tall,
374            px(600.),
375            "a group has to fill its slot, or its panel gets no height: got {tall:?}"
376        );
377    }
378
379    fn area_with_side_docks(cx: &mut TestAppContext) -> (Entity<DockArea>, &mut VisualTestContext) {
380        cx.update(|cx| crate::init(cx));
381        let (area, cx) = cx.add_window_view(|window, cx| {
382            DockArea::new("test", None, window, cx).with_renderer(DockSkin::new(cx))
383        });
384        cx.simulate_resize(size(px(800.), px(600.)));
385        cx.update(|window, cx| {
386            area.update(cx, |area, cx| {
387                area.set_center(
388                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
389                    window,
390                    cx,
391                );
392                area.set_dock(
393                    DockPlacement::Left,
394                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
395                    window,
396                    cx,
397                );
398                area.set_dock(
399                    DockPlacement::Right,
400                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
401                    window,
402                    cx,
403                );
404            });
405        });
406        cx.run_until_parked();
407        (area, cx)
408    }
409
410    /// Every dock's handle once shared the literal element id
411    /// `"resize-handle"`, so GPUI silently handed them one element state —
412    /// including the pending-mouse-down that starts a drag. Pressing the left
413    /// handle then let the right dock's drag listener (painted later, so
414    /// dispatched first) claim the drag, and one pixel of movement threw the
415    /// right dock to nearly the full area width.
416    #[gpui::test]
417    fn dragging_the_left_handle_resizes_only_the_left_dock(cx: &mut TestAppContext) {
418        let (area, cx) = area_with_side_docks(cx);
419        cx.update(|window, cx| window.draw(cx).clear(cx));
420
421        // The left dock is 200px wide, so its handle sits at x ∈ [198, 199).
422        cx.simulate_mouse_down(
423            point(px(198.5), px(300.)),
424            MouseButton::Left,
425            Modifiers::none(),
426        );
427        // Past the drag threshold: the drag starts and claims a dock.
428        cx.simulate_mouse_move(
429            point(px(204.), px(300.)),
430            MouseButton::Left,
431            Modifiers::none(),
432        );
433        // The move the claimed dock resizes to.
434        cx.simulate_mouse_move(
435            point(px(240.), px(300.)),
436            MouseButton::Left,
437            Modifiers::none(),
438        );
439        cx.simulate_mouse_up(
440            point(px(240.), px(300.)),
441            MouseButton::Left,
442            Modifiers::none(),
443        );
444        cx.run_until_parked();
445
446        let (left, right) = cx.update(|_, cx| {
447            let area = area.read(cx);
448            (
449                area.dock_size(DockPlacement::Left),
450                area.dock_size(DockPlacement::Right),
451            )
452        });
453        assert_eq!(
454            right,
455            Some(px(200.)),
456            "the right dock must not move when the left handle is dragged"
457        );
458        assert_eq!(left, Some(px(240.)), "the left dock follows the pointer");
459    }
460    #[gpui::test]
461    fn dragging_the_bottom_dock_closed_and_open_reports_each_toggle(cx: &mut TestAppContext) {
462        cx.update(|cx| crate::init(cx));
463        let (area, cx) = cx.add_window_view(|window, cx| {
464            DockArea::new("test", None, window, cx).with_renderer(DockSkin::new(cx))
465        });
466        cx.simulate_resize(size(px(800.), px(600.)));
467        let events = Rc::new(std::cell::RefCell::new(Vec::new()));
468        cx.update(|window, cx| {
469            area.update(cx, |area, cx| {
470                area.set_center(
471                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
472                    window,
473                    cx,
474                );
475                area.set_dock(
476                    DockPlacement::Bottom,
477                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
478                    window,
479                    cx,
480                );
481                area.set_dock_size(DockPlacement::Bottom, px(200.), window, cx);
482            });
483            let events = events.clone();
484            cx.subscribe(&area, move |_, event: &crate::dock::DockToggleEvent, _| {
485                events
486                    .borrow_mut()
487                    .push((event.placement(), event.is_open()));
488            })
489            .detach();
490        });
491        cx.run_until_parked();
492
493        let drag = |cx: &mut VisualTestContext, ys: &[f32]| {
494            cx.update(|window, cx| window.draw(cx).clear(cx));
495            let (first, rest) = ys.split_first().unwrap();
496            cx.simulate_mouse_down(
497                point(px(400.), px(*first)),
498                MouseButton::Left,
499                Modifiers::none(),
500            );
501            for y in rest {
502                cx.simulate_mouse_move(
503                    point(px(400.), px(*y)),
504                    MouseButton::Left,
505                    Modifiers::none(),
506                );
507            }
508            cx.simulate_mouse_up(
509                point(px(400.), px(*ys.last().unwrap())),
510                MouseButton::Left,
511                Modifiers::none(),
512            );
513            cx.run_until_parked();
514        };
515
516        // A resize that keeps the dock open is not a toggle.
517        drag(cx, &[400.5, 380., 350.]);
518        assert!(events.borrow().is_empty(), "a plain resize is not reported");
519
520        // Same handle, same strip geometry as the snapping test below.
521        drag(cx, &[350.5, 356., 580., 540.]);
522        drag(cx, &[571.5, 565., 520.]);
523        assert_eq!(
524            *events.borrow(),
525            vec![
526                (DockPlacement::Bottom, false),
527                (DockPlacement::Bottom, true)
528            ]
529        );
530    }
531
532    #[gpui::test]
533    fn dragging_the_bottom_handle_below_the_minimum_snaps_to_the_nearer_end(
534        cx: &mut TestAppContext,
535    ) {
536        cx.update(|cx| crate::init(cx));
537        let (area, cx) = cx.add_window_view(|window, cx| {
538            DockArea::new("test", None, window, cx).with_renderer(DockSkin::new(cx))
539        });
540        cx.simulate_resize(size(px(800.), px(600.)));
541        cx.update(|window, cx| {
542            area.update(cx, |area, cx| {
543                area.set_center(
544                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
545                    window,
546                    cx,
547                );
548                area.set_dock(
549                    DockPlacement::Bottom,
550                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
551                    window,
552                    cx,
553                );
554                area.set_dock_size(DockPlacement::Bottom, px(200.), window, cx);
555            });
556        });
557        cx.run_until_parked();
558
559        let drag = |cx: &mut VisualTestContext, ys: &[f32]| {
560            cx.update(|window, cx| window.draw(cx).clear(cx));
561            let (first, rest) = ys.split_first().unwrap();
562            cx.simulate_mouse_down(
563                point(px(400.), px(*first)),
564                MouseButton::Left,
565                Modifiers::none(),
566            );
567            for y in rest {
568                cx.simulate_mouse_move(
569                    point(px(400.), px(*y)),
570                    MouseButton::Left,
571                    Modifiers::none(),
572                );
573            }
574            cx.simulate_mouse_up(
575                point(px(400.), px(*ys.last().unwrap())),
576                MouseButton::Left,
577                Modifiers::none(),
578            );
579            cx.run_until_parked();
580        };
581        let bottom = |cx: &mut VisualTestContext| {
582            cx.update(|_, cx| {
583                let area = area.read(cx);
584                (
585                    area.is_dock_open(DockPlacement::Bottom),
586                    area.dock_size(DockPlacement::Bottom),
587                )
588            })
589        };
590
591        // From the 200px dock's handle at y ∈ [400, 401), through the closed
592        // strip and back, released 60px tall: nearer the strip than the
593        // minimum, so it closes.
594        drag(cx, &[400.5, 406., 580., 540.]);
595        assert!(!bottom(cx).0, "released nearer the strip, the dock closes");
596
597        // From the closed strip's handle at y ∈ [571, 572), released 80px
598        // tall: nearer the minimum, so it opens at the minimum.
599        drag(cx, &[571.5, 565., 520.]);
600        assert_eq!(
601            bottom(cx),
602            (true, Some(PANEL_MIN_SIZE)),
603            "released nearer the minimum, the dock opens at the minimum"
604        );
605    }
606
607    /// #3856: an application with its own toggle hides the collapsed tab bar,
608    /// and a closed bottom dock then gives the centre its whole height.
609    #[gpui::test]
610    fn a_closed_bottom_dock_takes_no_space_without_its_tab_bar(cx: &mut TestAppContext) {
611        cx.update(|cx| crate::init(cx));
612        let mut skin = None;
613        let (area, cx) = cx.add_window_view(|window, cx| {
614            let this = DockSkin::new(cx);
615            skin = Some(this.clone());
616            DockArea::new("test", None, window, cx).with_renderer(this)
617        });
618        let skin = skin.unwrap();
619        cx.simulate_resize(size(px(800.), px(600.)));
620        let center = Rc::new(std::cell::Cell::new(px(0.)));
621        cx.update(|window, cx| {
622            area.update(cx, |area, cx| {
623                area.set_center(
624                    DockLayout::tabs().panel(MeasuredProbe::new(center.clone(), cx)),
625                    window,
626                    cx,
627                );
628                area.set_dock(
629                    DockPlacement::Bottom,
630                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
631                    window,
632                    cx,
633                );
634                area.toggle_dock(DockPlacement::Bottom, window, cx);
635            });
636        });
637        let draw = |cx: &mut VisualTestContext| {
638            cx.run_until_parked();
639            cx.update(|window, cx| window.draw(cx).clear(cx));
640        };
641        draw(cx);
642        assert!(!cx.update(|_, cx| area.read(cx).is_dock_open(DockPlacement::Bottom)));
643        let with_strip = center.get();
644
645        assert!(skin.is_collapsed_tab_bar_visible());
646        cx.update(|_, cx| skin.set_collapsed_tab_bar_visible(false, cx));
647        draw(cx);
648        assert_eq!(center.get() - with_strip, CLOSED_BOTTOM_STRIP);
649    }
650}