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 /// The dock whose resize handle is being dragged, if any. Only one can be.
140 resizing_dock: Cell<Option<DockPlacement>>,
141 /// Whether that dock was open when the drag began, so the release can
142 /// tell whether the drag opened or closed it.
143 resize_started_open: Cell<bool>,
144}
145
146impl SkinShared {
147 pub(crate) fn area(&self) -> &WeakEntity<DockArea> {
148 &self.area
149 }
150
151 pub(crate) fn panel_style(&self) -> PanelStyle {
152 self.panel_style.get()
153 }
154
155 pub(crate) fn is_toggle_button_visible(&self) -> bool {
156 self.toggle_button_visible.get()
157 }
158
159 pub(crate) fn resizing_dock(&self) -> &Cell<Option<DockPlacement>> {
160 &self.resizing_dock
161 }
162
163 pub(crate) fn resize_started_open(&self) -> &Cell<bool> {
164 &self.resize_started_open
165 }
166
167 /// Redraw the area after a setting changed. The skin is not an entity, so
168 /// nothing else would notice.
169 fn notify(&self, cx: &mut App) {
170 _ = self.area.update(cx, |_, cx| cx.notify());
171 }
172}
173
174/// The gpui-component appearance for a [`DockArea`], and the handle its
175/// settings are changed through.
176///
177/// Install it at construction, where the area's own weak handle is available:
178///
179/// ```ignore
180/// let skin = DockSkin::new(cx);
181/// DockArea::new("main", None, window, cx).with_renderer(skin)
182/// ```
183///
184/// Keep the returned handle to change a setting later; it is an `Rc`, so a
185/// clone and the installed renderer are the same skin.
186pub struct DockSkin {
187 shared: Rc<SkinShared>,
188}
189
190impl DockSkin {
191 /// Build a [`DockArea`] wearing this appearance, together with the handle
192 /// its settings are changed through.
193 ///
194 /// The skin needs the area's own weak handle, so it can only be built
195 /// while the area is being constructed; this is that dance done once.
196 pub fn dock_area(
197 id: impl Into<SharedString>,
198 version: Option<usize>,
199 window: &mut Window,
200 cx: &mut App,
201 ) -> (Entity<DockArea>, Rc<Self>) {
202 let mut skin = None;
203 let area = cx.new(|cx| {
204 let this = Self::new(cx);
205 skin = Some(this.clone());
206 DockArea::new(id, version, window, cx).with_renderer(this)
207 });
208 // The closure above runs before `cx.new` returns.
209 (
210 area,
211 skin.expect("DockSkin::new ran inside the constructor"),
212 )
213 }
214
215 pub fn new(cx: &mut Context<DockArea>) -> Rc<Self> {
216 Rc::new(Self {
217 shared: Rc::new(SkinShared {
218 area: cx.weak_entity(),
219 panel_style: Cell::new(PanelStyle::default()),
220 toggle_button_visible: Cell::new(true),
221 close_button_visible: Cell::new(false),
222 collapsed_tab_bar_visible: Cell::new(true),
223 resizing_dock: Cell::new(None),
224 resize_started_open: Cell::new(false),
225 }),
226 })
227 }
228
229 pub(crate) fn shared(&self) -> &Rc<SkinShared> {
230 &self.shared
231 }
232
233 /// Whether a single-panel tab group draws a plain title or a full tab bar.
234 pub fn panel_style(&self) -> PanelStyle {
235 self.shared.panel_style()
236 }
237
238 pub fn set_panel_style(&self, style: PanelStyle, cx: &mut App) {
239 self.shared.panel_style.set(style);
240 self.shared.notify(cx);
241 }
242
243 /// Whether tab bars offer the affordance that collapses a neighbouring
244 /// dock.
245 pub fn is_toggle_button_visible(&self) -> bool {
246 self.shared.is_toggle_button_visible()
247 }
248
249 pub fn set_toggle_button_visible(&self, visible: bool, cx: &mut App) {
250 self.shared.toggle_button_visible.set(visible);
251 self.shared.notify(cx);
252 }
253
254 /// Show close buttons on closable tabs. Hidden by default; a panel's
255 /// own close constraints still decide whether its button appears.
256 pub fn set_close_button_visible(&self, visible: bool, cx: &mut App) {
257 self.shared.close_button_visible.set(visible);
258 self.shared.notify(cx);
259 }
260
261 /// Whether a closed bottom dock keeps its tab bar as a strip to reopen it
262 /// from. Shown by default; hide it when the application offers its own
263 /// toggle, and a closed bottom dock then takes no space.
264 pub fn is_collapsed_tab_bar_visible(&self) -> bool {
265 self.shared.collapsed_tab_bar_visible.get()
266 }
267
268 pub fn set_collapsed_tab_bar_visible(&self, visible: bool, cx: &mut App) {
269 self.shared.collapsed_tab_bar_visible.set(visible);
270 self.shared.notify(cx);
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 /// Every name `gpui_base::dock` exports has to be reachable from
277 /// `gpui_component::dock`, or an application cannot write its own skin
278 /// without depending on the foundation crate directly.
279 ///
280 /// This reads both export lists rather than naming them, because the way
281 /// this went wrong was checking the list against a description of base
282 /// instead of against base itself: a hand-written list cannot notice a
283 /// name base gained after it was written; two names were missing when
284 /// this was added.
285 ///
286 /// The parse is deliberately crude — it takes the braces of each
287 /// `pub use ...::{..}` and the tail of each single-name `pub use a::b;` —
288 /// so a reformat of either file could trip it. That failure says "look at
289 /// the two lists", which is the right thing to do anyway.
290 fn exported_names(source: &str, prefix: &str) -> Vec<String> {
291 let mut names = Vec::new();
292 let mut rest = source;
293 while let Some(at) = rest.find(prefix) {
294 rest = &rest[at + prefix.len()..];
295 let Some(end) = rest.find(';') else { break };
296 let (item, tail) = rest.split_at(end);
297 rest = tail;
298 let item = item.trim();
299 let list = match (item.find('{'), item.rfind('}')) {
300 (Some(open), Some(close)) if open < close => &item[open + 1..close],
301 // `pub use a::b;` — the name is the last path segment.
302 _ => item.rsplit("::").next().unwrap_or(""),
303 };
304 names.extend(
305 list.split(',')
306 .map(|name| name.split(" as ").next().unwrap_or("").trim().to_string())
307 .filter(|name| !name.is_empty()),
308 );
309 }
310 names.sort();
311 names.dedup();
312 names
313 }
314
315 #[test]
316 fn every_base_dock_export_is_reachable_from_here() {
317 let base = include_str!("../../../base/src/dock/mod.rs");
318 let skin = include_str!("mod.rs");
319
320 let exported = exported_names(base, "pub use ");
321 assert!(
322 exported.len() > 30,
323 "the parse found only {} names in base's dock module, so it is \
324 reading the wrong thing rather than reporting the truth",
325 exported.len()
326 );
327
328 let reachable = exported_names(skin, "pub use gpui_base::dock::");
329 // `Panel` and `PanelView` are re-exported under other names because
330 // this module's own `Panel`/`PanelView` extend them; `Dock` is a
331 // documented omission. See the doc on the re-export block.
332 let renamed = ["Panel", "PanelView"];
333 let omitted = ["Dock"];
334
335 let missing: Vec<&String> = exported
336 .iter()
337 .filter(|name| {
338 !reachable.contains(name)
339 && !renamed.contains(&name.as_str())
340 && !omitted.contains(&name.as_str())
341 })
342 .collect();
343
344 assert!(
345 missing.is_empty(),
346 "gpui_base::dock exports these, and gpui_component::dock does not \
347 re-export them: {missing:?}. Add them to the list, or add the \
348 name to `omitted` with the reason on the re-export block."
349 );
350 }
351}