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::{App, AppContext as _, Context, Entity, SharedString, WeakEntity, Window, actions};
28
29/// The behavior half of the panel traits, which every panel implements
30/// alongside [`Panel`]. Exported under this name because `Panel` in this
31/// module is the presentation half that extends it.
32pub use gpui_base::dock::Panel as BasePanel;
33/// The object-safe counterpart of [`BasePanel`], for the same reason.
34pub use gpui_base::dock::PanelView as BasePanelView;
35/// Everything [`gpui_base::dock`] exports, so a consumer never has to depend
36/// on the foundation crate directly to write a skin or read a container's
37/// state. Kept in step with base's own list by
38/// `every_base_dock_export_is_reachable_from_here`.
39///
40/// Two names are handled elsewhere and one is deliberately absent:
41/// base's `Panel` and `PanelView` arrive as [`BasePanel`] and [`BasePanelView`]
42/// because this module's `Panel`/`PanelView` are the presentation halves that
43/// extend them, and base's `Dock` — a plain state struct holding one dock's
44/// open, collapsible, size and resizing flags — is not re-exported at all,
45/// because the name meant a panel container in every released version of this
46/// crate and handing it back with a different meaning is worse than dropping
47/// it. A skin reads a dock through [`DockContext`].
48pub use gpui_base::dock::{
49    AnyDrag, DockArea, DockAreaRenderer, DockAreaState, DockContext, DockEvent, DockLayout,
50    DockPlacement, DockSizing, DockState, DragPanel, DropIndicator, DropPlaceholderBounds,
51    DropTarget, EditResult, InsertTarget, NodeId, PaneNode, PaneRef, PaneTree, PanelBuildContext,
52    PanelBuilder, PanelEvent, PanelId, PanelInfo, PanelRegistry, PanelSource, PanelState, RootKind,
53    TabGroup, TabGroupConstraints, TabGroupContext, TabGroupEvent, TabGroupRenderer,
54    register_panel,
55};
56pub use panel::*;
57pub use tab_panel::DragPanelPreview;
58
59actions!(dock, [ToggleZoom, ClosePanel]);
60
61pub(crate) fn init(cx: &mut App) {
62    // `gpui_base::dock::PanelRegistry::init` is crate-private, but the global
63    // it installs is not: `DockArea::new` and `register_panel` both create it
64    // on demand, and this keeps the old guarantee that it exists as soon as
65    // `gpui_component::init` has run.
66    if cx.try_global::<PanelRegistry>().is_none() {
67        cx.set_global(PanelRegistry::new());
68    }
69}
70
71/// What every part of the skin reads, and the dock area it belongs to.
72///
73/// The renderer is the only skin-owned object in the picture, so the settings
74/// the old `DockArea` carried — the panel style, whether dock collapse
75/// affordances are offered at all — live here. It is shared by reference with
76/// the per-container renderers, which are built once each and outlive any one
77/// frame.
78pub(crate) struct SkinShared {
79    area: WeakEntity<DockArea>,
80    panel_style: Cell<PanelStyle>,
81    toggle_button_visible: Cell<bool>,
82    /// The dock whose resize handle is being dragged, if any. Only one can be.
83    resizing_dock: Cell<Option<DockPlacement>>,
84}
85
86impl SkinShared {
87    pub(crate) fn area(&self) -> &WeakEntity<DockArea> {
88        &self.area
89    }
90
91    pub(crate) fn panel_style(&self) -> PanelStyle {
92        self.panel_style.get()
93    }
94
95    pub(crate) fn is_toggle_button_visible(&self) -> bool {
96        self.toggle_button_visible.get()
97    }
98
99    pub(crate) fn resizing_dock(&self) -> &Cell<Option<DockPlacement>> {
100        &self.resizing_dock
101    }
102
103    /// Redraw the area after a setting changed. The skin is not an entity, so
104    /// nothing else would notice.
105    fn notify(&self, cx: &mut App) {
106        _ = self.area.update(cx, |_, cx| cx.notify());
107    }
108}
109
110/// The gpui-component appearance for a [`DockArea`], and the handle its
111/// settings are changed through.
112///
113/// Install it at construction, where the area's own weak handle is available:
114///
115/// ```ignore
116/// let skin = DockSkin::new(cx);
117/// DockArea::new("main", None, window, cx).with_renderer(skin)
118/// ```
119///
120/// Keep the returned handle to change a setting later; it is an `Rc`, so a
121/// clone and the installed renderer are the same skin.
122pub struct DockSkin {
123    shared: Rc<SkinShared>,
124}
125
126impl DockSkin {
127    /// Build a [`DockArea`] wearing this appearance, together with the handle
128    /// its settings are changed through.
129    ///
130    /// The skin needs the area's own weak handle, so it can only be built
131    /// while the area is being constructed; this is that dance done once.
132    pub fn dock_area(
133        id: impl Into<SharedString>,
134        version: Option<usize>,
135        window: &mut Window,
136        cx: &mut App,
137    ) -> (Entity<DockArea>, Rc<Self>) {
138        let mut skin = None;
139        let area = cx.new(|cx| {
140            let this = Self::new(cx);
141            skin = Some(this.clone());
142            DockArea::new(id, version, window, cx).with_renderer(this)
143        });
144        // The closure above runs before `cx.new` returns.
145        (
146            area,
147            skin.expect("DockSkin::new ran inside the constructor"),
148        )
149    }
150
151    pub fn new(cx: &mut Context<DockArea>) -> Rc<Self> {
152        Rc::new(Self {
153            shared: Rc::new(SkinShared {
154                area: cx.weak_entity(),
155                panel_style: Cell::new(PanelStyle::default()),
156                toggle_button_visible: Cell::new(true),
157                resizing_dock: Cell::new(None),
158            }),
159        })
160    }
161
162    pub(crate) fn shared(&self) -> &Rc<SkinShared> {
163        &self.shared
164    }
165
166    /// Whether a single-panel tab group draws a plain title or a full tab bar.
167    pub fn panel_style(&self) -> PanelStyle {
168        self.shared.panel_style()
169    }
170
171    pub fn set_panel_style(&self, style: PanelStyle, cx: &mut App) {
172        self.shared.panel_style.set(style);
173        self.shared.notify(cx);
174    }
175
176    /// Whether tab bars offer the affordance that collapses a neighbouring
177    /// dock.
178    pub fn is_toggle_button_visible(&self) -> bool {
179        self.shared.is_toggle_button_visible()
180    }
181
182    pub fn set_toggle_button_visible(&self, visible: bool, cx: &mut App) {
183        self.shared.toggle_button_visible.set(visible);
184        self.shared.notify(cx);
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    /// Every name `gpui_base::dock` exports has to be reachable from
191    /// `gpui_component::dock`, or an application cannot write its own skin
192    /// without depending on the foundation crate directly.
193    ///
194    /// This reads both export lists rather than naming them, because the way
195    /// this went wrong was checking the list against a description of base
196    /// instead of against base itself: a hand-written list cannot notice a
197    /// name base gained after it was written; two names were missing when
198    /// this was added.
199    ///
200    /// The parse is deliberately crude — it takes the braces of each
201    /// `pub use ...::{..}` and the tail of each single-name `pub use a::b;` —
202    /// so a reformat of either file could trip it. That failure says "look at
203    /// the two lists", which is the right thing to do anyway.
204    fn exported_names(source: &str, prefix: &str) -> Vec<String> {
205        let mut names = Vec::new();
206        let mut rest = source;
207        while let Some(at) = rest.find(prefix) {
208            rest = &rest[at + prefix.len()..];
209            let Some(end) = rest.find(';') else { break };
210            let (item, tail) = rest.split_at(end);
211            rest = tail;
212            let item = item.trim();
213            let list = match (item.find('{'), item.rfind('}')) {
214                (Some(open), Some(close)) if open < close => &item[open + 1..close],
215                // `pub use a::b;` — the name is the last path segment.
216                _ => item.rsplit("::").next().unwrap_or(""),
217            };
218            names.extend(
219                list.split(',')
220                    .map(|name| name.split(" as ").next().unwrap_or("").trim().to_string())
221                    .filter(|name| !name.is_empty()),
222            );
223        }
224        names.sort();
225        names.dedup();
226        names
227    }
228
229    #[test]
230    fn every_base_dock_export_is_reachable_from_here() {
231        let base = include_str!("../../../base/src/dock/mod.rs");
232        let skin = include_str!("mod.rs");
233
234        let exported = exported_names(base, "pub use ");
235        assert!(
236            exported.len() > 30,
237            "the parse found only {} names in base's dock module, so it is \
238             reading the wrong thing rather than reporting the truth",
239            exported.len()
240        );
241
242        let reachable = exported_names(skin, "pub use gpui_base::dock::");
243        // `Panel` and `PanelView` are re-exported under other names because
244        // this module's own `Panel`/`PanelView` extend them; `Dock` is a
245        // documented omission. See the doc on the re-export block.
246        let renamed = ["Panel", "PanelView"];
247        let omitted = ["Dock"];
248
249        let missing: Vec<&String> = exported
250            .iter()
251            .filter(|name| {
252                !reachable.contains(name)
253                    && !renamed.contains(&name.as_str())
254                    && !omitted.contains(&name.as_str())
255            })
256            .collect();
257
258        assert!(
259            missing.is_empty(),
260            "gpui_base::dock exports these, and gpui_component::dock does not \
261             re-export them: {missing:?}. Add them to the list, or add the \
262             name to `omitted` with the reason on the re-export block."
263        );
264    }
265}