Skip to main content

gpui_component/dock/
mod.rs

1//! The gpui-component appearance for the dock.
2//!
3//! The layout tree, the persisted schema, the drag geometry, the active-panel
4//! state machine and the container entities all live in
5//! [`gpui_base::dock`]. This module is the skin over them: it re-exports the
6//! types a consumer needs, adds the presentation half of the panel traits
7//! (see [`panel`]), and implements base's two renderer traits.
8//!
9//! ```ignore
10//! let area = cx.new(|cx| {
11//!     DockArea::new("main", Some(1), window, cx).with_renderer(DockSkin::new(cx))
12//! });
13//! ```
14//!
15//! A [`DockArea`] built without [`DockSkin`] still docks, drags and persists —
16//! it simply draws no chrome at all.
17
18mod dock;
19mod invalid_panel;
20mod panel;
21mod tab_panel;
22#[cfg(test)]
23mod test_support;
24
25use std::{cell::Cell, rc::Rc};
26
27use gpui::{
28    App, AppContext as _, Context, Entity, EventEmitter, SharedString, WeakEntity, Window, actions,
29};
30
31/// The behavior half of the panel traits, which every panel implements
32/// alongside [`Panel`]. Exported under this name because `Panel` in this
33/// module is the presentation half that extends it.
34pub use gpui_base::dock::Panel as BasePanel;
35/// The object-safe counterpart of [`BasePanel`], for the same reason.
36pub use gpui_base::dock::PanelView as BasePanelView;
37/// Everything [`gpui_base::dock`] exports, so a consumer never has to depend
38/// on the foundation crate directly to write a skin or read a container's
39/// state. Kept in step with base's own list by
40/// `every_base_dock_export_is_reachable_from_here`.
41///
42/// Two names are handled elsewhere and one is deliberately absent:
43/// base's `Panel` and `PanelView` arrive as [`BasePanel`] and [`BasePanelView`]
44/// because this module's `Panel`/`PanelView` are the presentation halves that
45/// extend them, and base's `Dock` — a plain state struct holding one dock's
46/// open, collapsible, size and resizing flags — is not re-exported at all,
47/// because the name meant a panel container in every released version of this
48/// crate and handing it back with a different meaning is worse than dropping
49/// it. A skin reads a dock through [`DockContext`].
50pub use gpui_base::dock::{
51    AnyDrag, CLOSED_BOTTOM_STRIP, DockArea, DockAreaRenderer, DockAreaState, DockContext,
52    DockEvent, DockLayout, DockPlacement, DockSizing, DockState, DragPanel, DropIndicator,
53    DropPlaceholderBounds, DropTarget, EditResult, InsertTarget, NodeId, PaneNode, PaneRef,
54    PaneTree, PanelBuildContext, PanelBuilder, PanelEvent, PanelId, PanelInfo, PanelRegistry,
55    PanelSource, PanelState, RootKind, TabGroup, TabGroupConstraints, TabGroupContext,
56    TabGroupEvent, TabGroupRenderer, register_panel,
57};
58pub use panel::*;
59pub use tab_panel::DragPanelPreview;
60
61actions!(dock, [ToggleZoom, ClosePanel]);
62
63/// A dock that the user opened or closed with one of [`DockSkin`]'s controls:
64/// the collapse button in a tab bar, the strip of a collapsed bottom dock, or
65/// a resize handle dragged past the closed strip and released.
66///
67/// A [`DockArea`] drawn by [`DockSkin`] emits it after the dock has changed.
68/// [`DockArea::toggle_dock`] and the other dock setters do not, so an
69/// application can tell a user's toggle from one its own code made.
70pub struct DockToggleEvent {
71    placement: DockPlacement,
72    open: bool,
73}
74
75impl DockToggleEvent {
76    /// The dock that was toggled.
77    pub fn placement(&self) -> DockPlacement {
78        self.placement
79    }
80
81    /// Whether the dock is open now.
82    pub fn is_open(&self) -> bool {
83        self.open
84    }
85}
86
87impl EventEmitter<DockToggleEvent> for DockArea {}
88
89/// Toggle a dock on the user's behalf and report it with [`DockToggleEvent`].
90/// A dock that refuses to close emits nothing.
91pub(crate) fn toggle_dock_by_user(
92    area: &mut DockArea,
93    placement: DockPlacement,
94    window: &mut Window,
95    cx: &mut Context<DockArea>,
96) {
97    let was_open = area.is_dock_open(placement);
98    area.toggle_dock(placement, window, cx);
99    report_user_toggle(area, placement, was_open, cx);
100}
101
102/// Emit [`DockToggleEvent`] if a user action moved the dock away from
103/// `was_open`.
104pub(crate) fn report_user_toggle(
105    area: &DockArea,
106    placement: DockPlacement,
107    was_open: bool,
108    cx: &mut Context<DockArea>,
109) {
110    let open = area.is_dock_open(placement);
111    if open != was_open {
112        cx.emit(DockToggleEvent { placement, open });
113    }
114}
115
116pub(crate) fn init(cx: &mut App) {
117    // `gpui_base::dock::PanelRegistry::init` is crate-private, but the global
118    // it installs is not: `DockArea::new` and `register_panel` both create it
119    // on demand, and this keeps the old guarantee that it exists as soon as
120    // `gpui_component::init` has run.
121    if cx.try_global::<PanelRegistry>().is_none() {
122        cx.set_global(PanelRegistry::new());
123    }
124}
125
126/// What every part of the skin reads, and the dock area it belongs to.
127///
128/// The renderer is the only skin-owned object in the picture, so the settings
129/// the old `DockArea` carried — the panel style, whether dock collapse
130/// affordances are offered at all — live here. It is shared by reference with
131/// the per-container renderers, which are built once each and outlive any one
132/// frame.
133pub(crate) struct SkinShared {
134    area: WeakEntity<DockArea>,
135    panel_style: Cell<PanelStyle>,
136    toggle_button_visible: Cell<bool>,
137    close_button_visible: Cell<bool>,
138    collapsed_tab_bar_visible: Cell<bool>,
139    split_divider_line_visible: Cell<bool>,
140    /// The dock whose resize handle is being dragged, if any. Only one can be.
141    resizing_dock: Cell<Option<DockPlacement>>,
142    /// Whether that dock was open when the drag began, so the release can
143    /// tell whether the drag opened or closed it.
144    resize_started_open: Cell<bool>,
145}
146
147impl SkinShared {
148    pub(crate) fn area(&self) -> &WeakEntity<DockArea> {
149        &self.area
150    }
151
152    pub(crate) fn panel_style(&self) -> PanelStyle {
153        self.panel_style.get()
154    }
155
156    pub(crate) fn is_toggle_button_visible(&self) -> bool {
157        self.toggle_button_visible.get()
158    }
159
160    pub(crate) fn resizing_dock(&self) -> &Cell<Option<DockPlacement>> {
161        &self.resizing_dock
162    }
163
164    pub(crate) fn resize_started_open(&self) -> &Cell<bool> {
165        &self.resize_started_open
166    }
167
168    /// Redraw the area after a setting changed. The skin is not an entity, so
169    /// nothing else would notice.
170    fn notify(&self, cx: &mut App) {
171        _ = self.area.update(cx, |_, cx| cx.notify());
172    }
173}
174
175/// The gpui-component appearance for a [`DockArea`], and the handle its
176/// settings are changed through.
177///
178/// Install it at construction, where the area's own weak handle is available:
179///
180/// ```ignore
181/// let skin = DockSkin::new(cx);
182/// DockArea::new("main", None, window, cx).with_renderer(skin)
183/// ```
184///
185/// Keep the returned handle to change a setting later; it is an `Rc`, so a
186/// clone and the installed renderer are the same skin.
187pub struct DockSkin {
188    shared: Rc<SkinShared>,
189}
190
191impl DockSkin {
192    /// Build a [`DockArea`] wearing this appearance, together with the handle
193    /// its settings are changed through.
194    ///
195    /// The skin needs the area's own weak handle, so it can only be built
196    /// while the area is being constructed; this is that dance done once.
197    pub fn dock_area(
198        id: impl Into<SharedString>,
199        version: Option<usize>,
200        window: &mut Window,
201        cx: &mut App,
202    ) -> (Entity<DockArea>, Rc<Self>) {
203        let mut skin = None;
204        let area = cx.new(|cx| {
205            let this = Self::new(cx);
206            skin = Some(this.clone());
207            DockArea::new(id, version, window, cx).with_renderer(this)
208        });
209        // The closure above runs before `cx.new` returns.
210        (
211            area,
212            skin.expect("DockSkin::new ran inside the constructor"),
213        )
214    }
215
216    pub fn new(cx: &mut Context<DockArea>) -> Rc<Self> {
217        Rc::new(Self {
218            shared: Rc::new(SkinShared {
219                area: cx.weak_entity(),
220                panel_style: Cell::new(PanelStyle::default()),
221                toggle_button_visible: Cell::new(true),
222                close_button_visible: Cell::new(false),
223                collapsed_tab_bar_visible: Cell::new(true),
224                split_divider_line_visible: Cell::new(true),
225                resizing_dock: Cell::new(None),
226                resize_started_open: Cell::new(false),
227            }),
228        })
229    }
230
231    pub(crate) fn shared(&self) -> &Rc<SkinShared> {
232        &self.shared
233    }
234
235    /// Whether a single-panel tab group draws a plain title or a full tab bar.
236    pub fn panel_style(&self) -> PanelStyle {
237        self.shared.panel_style()
238    }
239
240    pub fn set_panel_style(&self, style: PanelStyle, cx: &mut App) {
241        self.shared.panel_style.set(style);
242        self.shared.notify(cx);
243    }
244
245    /// Whether tab bars offer the affordance that collapses a neighbouring
246    /// dock.
247    pub fn is_toggle_button_visible(&self) -> bool {
248        self.shared.is_toggle_button_visible()
249    }
250
251    pub fn set_toggle_button_visible(&self, visible: bool, cx: &mut App) {
252        self.shared.toggle_button_visible.set(visible);
253        self.shared.notify(cx);
254    }
255
256    /// Show close buttons on closable tabs. Hidden by default; a panel's
257    /// own close constraints still decide whether its button appears.
258    pub fn set_close_button_visible(&self, visible: bool, cx: &mut App) {
259        self.shared.close_button_visible.set(visible);
260        self.shared.notify(cx);
261    }
262
263    /// Whether a closed bottom dock keeps its tab bar as a strip to reopen it
264    /// from. Shown by default; hide it when the application offers its own
265    /// toggle, and a closed bottom dock then takes no space.
266    pub fn is_collapsed_tab_bar_visible(&self) -> bool {
267        self.shared.collapsed_tab_bar_visible.get()
268    }
269
270    pub fn set_collapsed_tab_bar_visible(&self, visible: bool, cx: &mut App) {
271        self.shared.collapsed_tab_bar_visible.set(visible);
272        self.shared.notify(cx);
273    }
274
275    /// Whether the divider between two split slots rests as a one-pixel line.
276    /// Shown by default. Hide it when the panels already sit apart; the
277    /// indicator still appears on hover and while dragging, and the hit area
278    /// is unchanged.
279    pub fn is_split_divider_line_visible(&self) -> bool {
280        self.shared.split_divider_line_visible.get()
281    }
282
283    pub fn set_split_divider_line_visible(&self, visible: bool, cx: &mut App) {
284        self.shared.split_divider_line_visible.set(visible);
285        self.shared.notify(cx);
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    /// Every name `gpui_base::dock` exports has to be reachable from
292    /// `gpui_component::dock`, or an application cannot write its own skin
293    /// without depending on the foundation crate directly.
294    ///
295    /// This reads both export lists rather than naming them, because the way
296    /// this went wrong was checking the list against a description of base
297    /// instead of against base itself: a hand-written list cannot notice a
298    /// name base gained after it was written; two names were missing when
299    /// this was added.
300    ///
301    /// The parse is deliberately crude — it takes the braces of each
302    /// `pub use ...::{..}` and the tail of each single-name `pub use a::b;` —
303    /// so a reformat of either file could trip it. That failure says "look at
304    /// the two lists", which is the right thing to do anyway.
305    fn exported_names(source: &str, prefix: &str) -> Vec<String> {
306        let mut names = Vec::new();
307        let mut rest = source;
308        while let Some(at) = rest.find(prefix) {
309            rest = &rest[at + prefix.len()..];
310            let Some(end) = rest.find(';') else { break };
311            let (item, tail) = rest.split_at(end);
312            rest = tail;
313            let item = item.trim();
314            let list = match (item.find('{'), item.rfind('}')) {
315                (Some(open), Some(close)) if open < close => &item[open + 1..close],
316                // `pub use a::b;` — the name is the last path segment.
317                _ => item.rsplit("::").next().unwrap_or(""),
318            };
319            names.extend(
320                list.split(',')
321                    .map(|name| name.split(" as ").next().unwrap_or("").trim().to_string())
322                    .filter(|name| !name.is_empty()),
323            );
324        }
325        names.sort();
326        names.dedup();
327        names
328    }
329
330    #[test]
331    fn every_base_dock_export_is_reachable_from_here() {
332        let base = include_str!("../../../base/src/dock/mod.rs");
333        let skin = include_str!("mod.rs");
334
335        let exported = exported_names(base, "pub use ");
336        assert!(
337            exported.len() > 30,
338            "the parse found only {} names in base's dock module, so it is \
339             reading the wrong thing rather than reporting the truth",
340            exported.len()
341        );
342
343        let reachable = exported_names(skin, "pub use gpui_base::dock::");
344        // `Panel` and `PanelView` are re-exported under other names because
345        // this module's own `Panel`/`PanelView` extend them; `Dock` is a
346        // documented omission. See the doc on the re-export block.
347        let renamed = ["Panel", "PanelView"];
348        let omitted = ["Dock"];
349
350        let missing: Vec<&String> = exported
351            .iter()
352            .filter(|name| {
353                !reachable.contains(name)
354                    && !renamed.contains(&name.as_str())
355                    && !omitted.contains(&name.as_str())
356            })
357            .collect();
358
359        assert!(
360            missing.is_empty(),
361            "gpui_base::dock exports these, and gpui_component::dock does not \
362             re-export them: {missing:?}. Add them to the list, or add the \
363             name to `omitted` with the reason on the re-export block."
364        );
365    }
366}