Skip to main content

gpui_base/dock/
tiles_state.rs

1//! A tiles canvas's behavior, with no appearance of its own.
2
3use std::{rc::Rc, sync::Arc};
4
5use gpui::{
6    AnyElement, App, Bounds, Context, Div, Empty, EntityId, EventEmitter, FocusHandle, Focusable,
7    InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Point, Render, Size,
8    Stateful, Styled as _, WeakEntity, Window, div, prelude::FluentBuilder as _, px,
9};
10
11use crate::history::History;
12
13use super::{
14    drag::AnyDrag,
15    layout::{NodeId, PanelId},
16    panel::PanelView,
17    tiles_geometry::{
18        MINIMUM_SIZE, ResizeDrag, ResizeSide, TileChange, apply_boundary_constraints,
19        compute_resized_bounds, content_size, magnetic_snap,
20    },
21};
22
23/// What a tiles canvas cannot carry out on its own.
24///
25/// The canvas mirrors one `Tiles` node but does not own the tree that node
26/// lives in, so — exactly as with [`TabGroupEvent`](super::TabGroupEvent) —
27/// every outcome is reported as an intent and applied by the container
28/// through `PaneTree::set_tile_bounds` / `PaneTree::bring_to_front`.
29#[non_exhaustive]
30pub enum TilesEvent {
31    /// A tile finished moving or resizing at `bounds`.
32    BoundsChanged {
33        panel: PanelId,
34        bounds: Bounds<Pixels>,
35    },
36    /// A tile was interacted with and should stack above its peers.
37    BringToFront { panel: PanelId },
38    /// The user asked to close `panel`, dismissing its tile.
39    ClosePanel { panel: PanelId },
40    /// A host-owned drag landed on the canvas. The canvas has free
41    /// coordinates, so the host reads the landing position itself.
42    DragDrop { item: AnyDrag },
43    /// One tile asked to fill the whole dock. The container installs the
44    /// *canvas* as its zoomed view, and the canvas draws that one tile with
45    /// its chrome — which is where the control that zooms back out lives.
46    ZoomIn { panel: PanelId },
47    /// The zoomed tile gave the dock back.
48    ZoomOut,
49}
50
51/// One tile, mirrored from a `Tiles` node.
52#[derive(Clone)]
53struct Tile {
54    panel: Arc<dyn PanelView>,
55    id: PanelId,
56    bounds: Bounds<Pixels>,
57    z_index: usize,
58}
59
60/// An in-flight move: which tile, and where the pointer and the tile were
61/// when it started.
62#[derive(Clone, Copy)]
63struct TileMove {
64    panel: PanelId,
65    initial_pointer: Point<Pixels>,
66    initial_bounds: Bounds<Pixels>,
67}
68
69/// An in-flight resize: which tile, and the geometry module's own drag record.
70#[derive(Clone, Copy)]
71struct TileResize {
72    panel: PanelId,
73    initial_bounds: Bounds<Pixels>,
74    drag: ResizeDrag,
75}
76
77/// A tiles canvas's behavior, with no appearance of its own.
78///
79/// It owns the tile list mirrored from the layout tree, the in-flight move and
80/// resize state, and the undo stack. Everything visible is produced by the
81/// [`TilesRenderer`] the host installs.
82pub struct TilesState {
83    node: NodeId,
84    /// Handed to the callbacks in [`TileContext`], which are built from a
85    /// plain `&App` and so cannot ask for it.
86    this: WeakEntity<Self>,
87    tiles: Vec<Tile>,
88    focus_handle: FocusHandle,
89    /// The tile filling the whole dock, if one is. Driven by the container
90    /// through [`Self::set_zoomed`], so the canvas and the container name the
91    /// same tile or neither does.
92    zoomed: Option<PanelId>,
93    moving: Option<TileMove>,
94    resizing: Option<TileResize>,
95    history: History<TileChange>,
96    renderer: Rc<dyn TilesRenderer>,
97}
98
99impl TilesState {
100    /// Only a container builds canvases: a canvas is the entity mirror of one
101    /// `Tiles` node, created when that node first appears in the tree.
102    pub(crate) fn new(node: NodeId, _window: &mut Window, cx: &mut Context<Self>) -> Self {
103        Self {
104            node,
105            this: cx.weak_entity(),
106            tiles: Vec::new(),
107            focus_handle: cx.focus_handle(),
108            zoomed: None,
109            moving: None,
110            resizing: None,
111            history: History::new().group_interval(std::time::Duration::from_millis(100)),
112            renderer: Rc::new(BareTiles),
113        }
114    }
115
116    pub fn with_renderer(mut self, renderer: Rc<dyn TilesRenderer>) -> Self {
117        self.renderer = renderer;
118        self
119    }
120
121    /// The `Tiles` node this canvas mirrors.
122    pub fn node(&self) -> NodeId {
123        self.node
124    }
125
126    /// Every tile, in stacking order (lowest first).
127    pub fn tiles(&self, cx: &App) -> Vec<TileContext> {
128        let mut order: Vec<usize> = (0..self.tiles.len()).collect();
129        order.sort_by_key(|ix| (self.tiles[*ix].z_index, *ix));
130        order
131            .into_iter()
132            .map(|ix| self.tile_context(ix, cx))
133            .collect()
134    }
135
136    /// Mirror one `Tiles` node's membership and geometry into this canvas.
137    pub(crate) fn sync_from_tree(
138        &mut self,
139        tiles: Vec<(Arc<dyn PanelView>, Bounds<Pixels>, usize)>,
140        cx: &mut Context<Self>,
141    ) {
142        self.tiles = tiles
143            .into_iter()
144            .map(|(panel, bounds, z_index)| Tile {
145                id: panel.panel_id(cx),
146                panel,
147                bounds,
148                z_index,
149            })
150            .collect();
151        // A tile that left the canvas must not be resurrected by an in-flight
152        // gesture that outlived it.
153        if self
154            .moving
155            .is_some_and(|drag| self.index_of(drag.panel).is_none())
156        {
157            self.moving = None;
158        }
159        if self
160            .resizing
161            .is_some_and(|drag| self.index_of(drag.panel).is_none())
162        {
163            self.resizing = None;
164        }
165        cx.notify();
166    }
167
168    /// The tile filling the whole dock, if one is.
169    pub fn zoomed_tile(&self) -> Option<PanelId> {
170        self.zoomed
171    }
172
173    /// Flip one tile's zoom.
174    pub fn toggle_zoom(&mut self, panel: PanelId, window: &mut Window, cx: &mut Context<Self>) {
175        let zoomed = (self.zoomed != Some(panel)).then_some(panel);
176        self.set_zoomed(zoomed, window, cx);
177    }
178
179    /// Zoom one tile in, or zoom out with `None`: the flag changes, the panel
180    /// is told, and the container is asked to install or clear the zoomed
181    /// view.
182    ///
183    /// The container drives this too when it clears a zoom from outside, so
184    /// the canvas cannot be left naming a tile the container is not showing.
185    ///
186    /// Zooming *in* is refused, leaving the flag alone, for a tile that is not
187    /// on this canvas or whose panel is not zoomable. Zooming *out* is never
188    /// refused: a tile that became unzoomable while zoomed still has to be
189    /// able to give the dock back.
190    pub(crate) fn set_zoomed(
191        &mut self,
192        zoomed: Option<PanelId>,
193        window: &mut Window,
194        cx: &mut Context<Self>,
195    ) {
196        if self.zoomed == zoomed {
197            return;
198        }
199        // The outgoing tile hears about it as well as the incoming one, so a
200        // zoom moved straight from one tile to another leaves neither panel
201        // believing it still fills the dock.
202        let outgoing = self.zoomed.and_then(|panel| self.panel_view(panel));
203        let incoming = zoomed.and_then(|panel| self.panel_view(panel));
204        if zoomed.is_some() && !incoming.as_ref().is_some_and(|panel| panel.zoomable(cx)) {
205            return;
206        }
207
208        self.zoomed = zoomed;
209        cx.emit(match zoomed {
210            Some(panel) => TilesEvent::ZoomIn { panel },
211            None => TilesEvent::ZoomOut,
212        });
213
214        // Delivered outside this update so a `set_zoomed` handler may call
215        // back into the canvas.
216        cx.spawn_in(window, async move |_, cx| {
217            _ = cx.update(|window, cx| {
218                if let Some(panel) = outgoing {
219                    panel.set_zoomed(false, window, cx);
220                }
221                if let Some(panel) = incoming {
222                    panel.set_zoomed(true, window, cx);
223                }
224            });
225        })
226        .detach();
227        cx.notify();
228    }
229
230    /// Undo the most recent group of tile changes.
231    pub fn undo(&mut self, cx: &mut Context<Self>) {
232        let Some(changes) = self.history.undo() else {
233            return;
234        };
235        for change in changes {
236            if let (Some(panel), Some(bounds)) =
237                (self.panel_of(change.tile_id()), change.old_bounds())
238            {
239                cx.emit(TilesEvent::BoundsChanged { panel, bounds });
240            }
241        }
242        cx.notify();
243    }
244
245    /// Redo the most recently undone group of tile changes.
246    pub fn redo(&mut self, cx: &mut Context<Self>) {
247        let Some(changes) = self.history.redo() else {
248            return;
249        };
250        for change in changes {
251            if let (Some(panel), Some(bounds)) =
252                (self.panel_of(change.tile_id()), change.new_bounds())
253            {
254                cx.emit(TilesEvent::BoundsChanged { panel, bounds });
255            }
256        }
257        cx.notify();
258    }
259}
260
261impl TilesState {
262    fn index_of(&self, panel: PanelId) -> Option<usize> {
263        self.tiles.iter().position(|tile| tile.id == panel)
264    }
265
266    fn bounds_of(&self, panel: PanelId) -> Option<Bounds<Pixels>> {
267        self.index_of(panel).map(|ix| self.tiles[ix].bounds)
268    }
269
270    fn panel_view(&self, panel: PanelId) -> Option<Arc<dyn PanelView>> {
271        self.index_of(panel).map(|ix| self.tiles[ix].panel.clone())
272    }
273
274    /// The panel behind a history record's `EntityId`.
275    fn panel_of(&self, entity: EntityId) -> Option<PanelId> {
276        self.tiles
277            .iter()
278            .find(|tile| tile.panel.view().entity_id() == entity)
279            .map(|tile| tile.id)
280    }
281
282    /// Every other tile's bounds, which is what the snapping arithmetic
283    /// measures against.
284    fn other_bounds(&self, panel: PanelId) -> Vec<Bounds<Pixels>> {
285        self.tiles
286            .iter()
287            .filter(|tile| tile.id != panel)
288            .map(|tile| tile.bounds)
289            .collect()
290    }
291
292    fn grid_size(&self, cx: &App) -> Pixels {
293        self.renderer.grid_size(cx)
294    }
295
296    fn begin_move(&mut self, panel: PanelId, pointer: Point<Pixels>, cx: &mut Context<Self>) {
297        // A zoomed tile fills the dock rather than sitting at its stored
298        // bounds, so there is nothing for a move to mean — the same reason a
299        // zoomed tab group reports itself locked.
300        if self.zoomed.is_some() {
301            return;
302        }
303        let Some(initial_bounds) = self.bounds_of(panel) else {
304            return;
305        };
306        self.moving = Some(TileMove {
307            panel,
308            initial_pointer: pointer,
309            initial_bounds,
310        });
311        cx.emit(TilesEvent::BringToFront { panel });
312        cx.notify();
313    }
314
315    fn move_to(&mut self, pointer: Point<Pixels>, cx: &mut Context<Self>) {
316        let Some(drag) = self.moving else {
317            return;
318        };
319        let delta = pointer - drag.initial_pointer;
320        let candidate = Bounds {
321            origin: apply_boundary_constraints(
322                drag.initial_bounds.origin + delta,
323                drag.initial_bounds.size.width,
324            ),
325            size: drag.initial_bounds.size,
326        };
327        let origin = magnetic_snap(
328            candidate,
329            &self.other_bounds(drag.panel),
330            self.grid_size(cx),
331        );
332
333        self.apply_bounds(
334            drag.panel,
335            Bounds {
336                origin,
337                size: drag.initial_bounds.size,
338            },
339            cx,
340        );
341    }
342
343    fn end_move(&mut self, cx: &mut Context<Self>) {
344        let Some(drag) = self.moving.take() else {
345            return;
346        };
347        self.record(drag.panel, drag.initial_bounds, cx);
348    }
349
350    fn begin_resize(
351        &mut self,
352        panel: PanelId,
353        side: ResizeSide,
354        pointer: Point<Pixels>,
355        cx: &mut Context<Self>,
356    ) {
357        if self.zoomed.is_some() {
358            return;
359        }
360        let Some(initial_bounds) = self.bounds_of(panel) else {
361            return;
362        };
363        self.resizing = Some(TileResize {
364            panel,
365            initial_bounds,
366            drag: ResizeDrag::new(side, pointer, initial_bounds),
367        });
368        cx.emit(TilesEvent::BringToFront { panel });
369        cx.notify();
370    }
371
372    fn resize_to(&mut self, pointer: Point<Pixels>, cx: &mut Context<Self>) {
373        let Some(resize) = self.resizing else {
374            return;
375        };
376        let previous = resize.drag.last_bounds();
377        let (new_x, new_y, new_width, new_height) = match resize.drag.side() {
378            ResizeSide::Left => (Some(pointer.x), None, None, None),
379            ResizeSide::Right => (
380                None,
381                None,
382                Some((pointer.x - previous.origin.x).max(MINIMUM_SIZE.width)),
383                None,
384            ),
385            ResizeSide::Top => (None, Some(pointer.y), None, None),
386            ResizeSide::Bottom => (
387                None,
388                None,
389                None,
390                Some((pointer.y - previous.origin.y).max(MINIMUM_SIZE.height)),
391            ),
392            ResizeSide::BottomRight => (
393                None,
394                None,
395                Some((pointer.x - previous.origin.x).max(MINIMUM_SIZE.width)),
396                Some((pointer.y - previous.origin.y).max(MINIMUM_SIZE.height)),
397            ),
398        };
399
400        let bounds = compute_resized_bounds(
401            previous,
402            new_x,
403            new_y,
404            new_width,
405            new_height,
406            &self.other_bounds(resize.panel),
407            self.grid_size(cx),
408        );
409
410        self.resizing = Some(TileResize {
411            drag: resize
412                .drag
413                .with_last_position(pointer)
414                .with_last_bounds(bounds),
415            ..resize
416        });
417        self.apply_bounds(resize.panel, bounds, cx);
418    }
419
420    fn end_resize(&mut self, cx: &mut Context<Self>) {
421        let Some(resize) = self.resizing.take() else {
422            return;
423        };
424        self.record(resize.panel, resize.initial_bounds, cx);
425    }
426
427    /// Show the new geometry immediately and report it, so the container's
428    /// tree and this mirror never disagree for a frame.
429    fn apply_bounds(&mut self, panel: PanelId, bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
430        let Some(ix) = self.index_of(panel) else {
431            return;
432        };
433        if self.tiles[ix].bounds == bounds {
434            return;
435        }
436        self.tiles[ix].bounds = bounds;
437        cx.emit(TilesEvent::BoundsChanged { panel, bounds });
438        cx.notify();
439    }
440
441    /// Push one completed gesture onto the undo stack.
442    fn record(&mut self, panel: PanelId, old_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
443        let Some(ix) = self.index_of(panel) else {
444            return;
445        };
446        let tile = &self.tiles[ix];
447        if tile.bounds == old_bounds {
448            return;
449        }
450        self.history.push(TileChange::bounds_change(
451            tile.panel.view().entity_id(),
452            old_bounds,
453            tile.bounds,
454        ));
455        cx.notify();
456    }
457
458    /// Ask the container to close `panel`. Nothing happens for a tile that
459    /// is not on this canvas, or for a panel that refuses to close.
460    fn close_tile(&mut self, panel: PanelId, cx: &mut Context<Self>) {
461        let closable = self
462            .tiles
463            .iter()
464            .any(|tile| tile.id == panel && tile.panel.closable(cx));
465        if !closable {
466            return;
467        }
468        cx.emit(TilesEvent::ClosePanel { panel });
469        cx.notify();
470    }
471
472    fn tile_context(&self, ix: usize, cx: &App) -> TileContext {
473        let tile = &self.tiles[ix];
474        let panel = tile.id;
475        let canvas = self.this.clone();
476
477        TileContext {
478            node: self.node,
479            panel: tile.panel.clone(),
480            id: panel,
481            bounds: tile.bounds,
482            z_index: tile.z_index,
483            moving: self.moving.is_some_and(|drag| drag.panel == panel),
484            resizing: self.resizing.is_some_and(|drag| drag.panel == panel),
485            closable: tile.panel.closable(cx),
486            zoomed: self.zoomed == Some(panel),
487            zoomable: tile.panel.zoomable(cx),
488            on_begin_move: {
489                let canvas = canvas.clone();
490                Rc::new(move |pointer, _, cx| {
491                    _ = canvas.update(cx, |canvas, cx| canvas.begin_move(panel, pointer, cx));
492                })
493            },
494            on_move_to: {
495                let canvas = canvas.clone();
496                Rc::new(move |pointer, _, cx| {
497                    _ = canvas.update(cx, |canvas, cx| canvas.move_to(pointer, cx));
498                })
499            },
500            on_end_move: {
501                let canvas = canvas.clone();
502                Rc::new(move |_, cx| {
503                    _ = canvas.update(cx, |canvas, cx| canvas.end_move(cx));
504                })
505            },
506            on_begin_resize: {
507                let canvas = canvas.clone();
508                Rc::new(move |side, pointer, _, cx| {
509                    _ = canvas.update(cx, |canvas, cx| {
510                        canvas.begin_resize(panel, side, pointer, cx)
511                    });
512                })
513            },
514            on_resize_to: {
515                let canvas = canvas.clone();
516                Rc::new(move |pointer, _, cx| {
517                    _ = canvas.update(cx, |canvas, cx| canvas.resize_to(pointer, cx));
518                })
519            },
520            on_end_resize: {
521                let canvas = canvas.clone();
522                Rc::new(move |_, cx| {
523                    _ = canvas.update(cx, |canvas, cx| canvas.end_resize(cx));
524                })
525            },
526            on_bring_to_front: {
527                let canvas = canvas.clone();
528                Rc::new(move |_, cx| {
529                    _ = canvas.update(cx, |_, cx| {
530                        cx.emit(TilesEvent::BringToFront { panel });
531                    });
532                })
533            },
534            on_toggle_zoom: {
535                let canvas = canvas.clone();
536                Rc::new(move |window, cx| {
537                    _ = canvas.update(cx, |canvas, cx| canvas.toggle_zoom(panel, window, cx));
538                })
539            },
540            on_close: Rc::new(move |_, cx| {
541                _ = canvas.update(cx, |canvas, cx| canvas.close_tile(panel, cx));
542            }),
543        }
544    }
545}
546
547impl EventEmitter<TilesEvent> for TilesState {}
548
549impl Focusable for TilesState {
550    fn focus_handle(&self, _: &App) -> FocusHandle {
551        self.focus_handle.clone()
552    }
553}
554
555impl Render for TilesState {
556    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
557        let renderer = self.renderer.clone();
558        let focus_handle = self.focus_handle.clone();
559        // A zoomed tile fills the dock on its own, so the tiles beside it are
560        // not drawn — just as the rest of the dock is not drawn behind it.
561        // A zoom naming a tile that has since left the canvas draws the
562        // canvas whole rather than nothing at all.
563        let zoomed = self.zoomed.filter(|panel| self.index_of(*panel).is_some());
564        let tiles: Vec<TileContext> = self
565            .tiles(cx)
566            .into_iter()
567            .filter(|tile| zoomed.is_none_or(|panel| tile.id == panel))
568            .collect();
569        // Every tile, not the drawn subset: an overlay scrollbar measures the
570        // whole canvas.
571        let content = content_size(
572            &self
573                .tiles
574                .iter()
575                .map(|tile| tile.bounds)
576                .collect::<Vec<_>>(),
577        );
578
579        renderer
580            .frame(window, cx)
581            .track_focus(&focus_handle)
582            .on_drop(cx.listener(|_, item: &AnyDrag, _, cx| {
583                cx.emit(TilesEvent::DragDrop { item: item.clone() });
584            }))
585            .children(
586                tiles
587                    .into_iter()
588                    .map(|tile| {
589                        renderer
590                            .tile_frame(&tile, window, cx)
591                            // The only positioning base installs anywhere in
592                            // the dock. A tiles canvas *is* "panels at stored
593                            // coordinates": drawing one somewhere other than
594                            // its own bounds would not be a different skin,
595                            // it would be a different data structure. A
596                            // zoomed tile is the exception — it is no longer
597                            // at its coordinates, and how it fills the dock
598                            // is the skin's to decide.
599                            .when(!tile.zoomed, |this| {
600                                this.absolute()
601                                    .left(tile.bounds.origin.x)
602                                    .top(tile.bounds.origin.y)
603                                    .w(tile.bounds.size.width)
604                                    .h(tile.bounds.size.height)
605                            })
606                            .child(renderer.render_drag_bar(&tile, window, cx))
607                            .child(
608                                renderer
609                                    .panel_frame(&tile, window, cx)
610                                    .child(tile.panel.view()),
611                            )
612                            // Nothing to resize against while zoomed, and the
613                            // canvas refuses the gesture anyway.
614                            .when(!tile.zoomed, |this| {
615                                this.child(renderer.render_resize_handles(&tile, window, cx))
616                            })
617                    })
618                    .collect::<Vec<_>>(),
619            )
620            // Last, so it paints and hit-tests above every tile. A zoomed
621            // canvas draws one tile filling the dock, so there is no canvas
622            // for an overlay to sit over.
623            .when(zoomed.is_none(), |this| {
624                this.children(renderer.render_overlay(content, window, cx))
625            })
626    }
627}
628
629type MovePointerHandler = Rc<dyn Fn(Point<Pixels>, &mut Window, &mut App)>;
630type ResizeStartHandler = Rc<dyn Fn(ResizeSide, Point<Pixels>, &mut Window, &mut App)>;
631type GestureEndHandler = Rc<dyn Fn(&mut Window, &mut App)>;
632
633/// What a skin needs to draw one tile, and the callbacks it invokes rather
634/// than reimplementing the snapping and resize arithmetic.
635#[derive(Clone)]
636pub struct TileContext {
637    node: NodeId,
638    panel: Arc<dyn PanelView>,
639    id: PanelId,
640    bounds: Bounds<Pixels>,
641    z_index: usize,
642    moving: bool,
643    resizing: bool,
644    closable: bool,
645    zoomed: bool,
646    zoomable: bool,
647    on_begin_move: MovePointerHandler,
648    on_move_to: MovePointerHandler,
649    on_end_move: GestureEndHandler,
650    on_begin_resize: ResizeStartHandler,
651    on_resize_to: MovePointerHandler,
652    on_end_resize: GestureEndHandler,
653    on_bring_to_front: GestureEndHandler,
654    on_toggle_zoom: GestureEndHandler,
655    on_close: GestureEndHandler,
656}
657
658impl TileContext {
659    /// The `Tiles` node this tile belongs to, for a skin that needs to name
660    /// the canvas in a drag payload or a drop target.
661    pub fn node(&self) -> NodeId {
662        self.node
663    }
664
665    pub fn panel(&self) -> &Arc<dyn PanelView> {
666        &self.panel
667    }
668
669    pub fn panel_id(&self) -> PanelId {
670        self.id
671    }
672
673    pub fn bounds(&self) -> Bounds<Pixels> {
674        self.bounds
675    }
676
677    pub fn z_index(&self) -> usize {
678        self.z_index
679    }
680
681    pub fn is_moving(&self) -> bool {
682        self.moving
683    }
684
685    pub fn is_resizing(&self) -> bool {
686        self.resizing
687    }
688
689    pub fn is_closable(&self) -> bool {
690        self.closable
691    }
692
693    /// Whether this tile is the one filling the whole dock.
694    ///
695    /// A zoomed tile is drawn without its stored bounds and takes no move or
696    /// resize gesture, so a skin should offer the way back out here rather
697    /// than the affordances of a tile that can still be dragged.
698    pub fn is_zoomed(&self) -> bool {
699        self.zoomed
700    }
701
702    /// Whether this tile's panel allows zooming at all. Where the zoom
703    /// control appears is the skin's decision; whether there is one to offer
704    /// is not.
705    pub fn is_zoomable(&self) -> bool {
706        self.zoomable
707    }
708
709    /// Pointer positions are in window coordinates: every gesture is resolved
710    /// against the position the gesture started at, so the skin never has to
711    /// convert into canvas space.
712    pub fn begin_move(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
713        (self.on_begin_move)(pointer, window, cx);
714    }
715
716    pub fn move_to(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
717        (self.on_move_to)(pointer, window, cx);
718    }
719
720    pub fn end_move(&self, window: &mut Window, cx: &mut App) {
721        (self.on_end_move)(window, cx);
722    }
723
724    pub fn begin_resize(
725        &self,
726        side: ResizeSide,
727        pointer: Point<Pixels>,
728        window: &mut Window,
729        cx: &mut App,
730    ) {
731        (self.on_begin_resize)(side, pointer, window, cx);
732    }
733
734    pub fn resize_to(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
735        (self.on_resize_to)(pointer, window, cx);
736    }
737
738    pub fn end_resize(&self, window: &mut Window, cx: &mut App) {
739        (self.on_end_resize)(window, cx);
740    }
741
742    pub fn bring_to_front(&self, window: &mut Window, cx: &mut App) {
743        (self.on_bring_to_front)(window, cx);
744    }
745
746    /// Flip this tile between filling the whole dock and sitting at its
747    /// stored bounds.
748    ///
749    /// Zooming *in* is refused when [`Self::is_zoomable`] is false, so a skin
750    /// that offers a Zoom control should gate it on that. Zooming out is
751    /// never refused.
752    pub fn toggle_zoom(&self, window: &mut Window, cx: &mut App) {
753        (self.on_toggle_zoom)(window, cx);
754    }
755
756    /// Dismiss this tile. Refused when [`Self::is_closable`] is false, so a
757    /// skin that offers a Close control should gate it on that.
758    pub fn close(&self, window: &mut Window, cx: &mut App) {
759        (self.on_close)(window, cx);
760    }
761}
762
763/// Appearance for a tiles canvas. Base draws none of it.
764///
765/// Like [`TabGroupRenderer`](super::TabGroupRenderer), the frame hooks return
766/// the element itself rather than wrapping one: base attaches focus and drop
767/// handling to the canvas frame and the stored bounds to the tile frame, so a
768/// wrapper would put the hit area and the painted area on different elements.
769/// That is also why there is no `wrap_canvas` hook — it would be exactly the
770/// wrapper the `TabGroupRenderer` review ruled out.
771#[allow(unused_variables)]
772pub trait TilesRenderer: 'static {
773    /// The canvas frame, which base tracks focus and drop handling on.
774    fn frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
775        div().id("tiles")
776    }
777
778    /// One tile's frame, which base positions at the tile's stored bounds.
779    fn tile_frame(&self, tile: &TileContext, window: &mut Window, cx: &mut App) -> Stateful<Div> {
780        div().id("tile")
781    }
782
783    /// The strip the tile is dragged by. Its height is
784    /// [`DRAG_BAR_HEIGHT`](super::DRAG_BAR_HEIGHT), which base's snapping
785    /// arithmetic and the skin must agree on.
786    fn render_drag_bar(&self, tile: &TileContext, window: &mut Window, cx: &mut App) -> AnyElement;
787
788    /// The tile's resize affordances. Their hit size is
789    /// [`HANDLE_SIZE`](super::HANDLE_SIZE).
790    fn render_resize_handles(
791        &self,
792        tile: &TileContext,
793        window: &mut Window,
794        cx: &mut App,
795    ) -> AnyElement {
796        Empty.into_any_element()
797    }
798
799    /// The frame around one tile's panel view.
800    ///
801    /// A wrapper, unlike the other frame hooks, and for the same reason
802    /// [`DockAreaRenderer::split_frame`](super::DockAreaRenderer::split_frame)
803    /// is one: base attaches nothing to it, so there is no hit area to keep
804    /// together with the painted area. It exists because base draws the panel
805    /// as an ordinary child of the tile frame, and a panel that does not size
806    /// itself would otherwise have no size at all — the old canvas wrapped it
807    /// in `h_flex().overflow_hidden().size_full()`, and nothing else can put
808    /// that back.
809    fn panel_frame(&self, tile: &TileContext, window: &mut Window, cx: &mut App) -> Stateful<Div> {
810        div().id(("tile-panel", tile.panel_id().as_u64()))
811    }
812
813    /// An element drawn above every tile — a scrollbar, a drop hint.
814    ///
815    /// Rendered last, so it paints and hit-tests above the tiles. That
816    /// ordering is the whole point: the canvas frame is the scroll container,
817    /// so an overlay placed with the frame's own children would sit beneath
818    /// every tile. Not called while a tile is zoomed, because then the canvas
819    /// is one tile filling the dock rather than a canvas.
820    ///
821    /// `content` is the scrollable extent of every tile measured from the
822    /// canvas origin, which a scrollbar needs and a hook holding only
823    /// `&mut App` could not work out.
824    fn render_overlay(
825        &self,
826        content: Size<Pixels>,
827        window: &mut Window,
828        cx: &mut App,
829    ) -> Option<AnyElement> {
830        None
831    }
832
833    /// The grid a tile snaps to when no neighbouring edge is close enough.
834    ///
835    /// The old canvas read this off the theme, which base cannot see; the
836    /// default is the ten-pixel grid the original rounded to.
837    fn grid_size(&self, cx: &App) -> Pixels {
838        px(10.)
839    }
840}
841
842/// The renderer a canvas starts with: the tiles and nothing else.
843pub(crate) struct BareTiles;
844
845impl TilesRenderer for BareTiles {
846    fn render_drag_bar(&self, _: &TileContext, _: &mut Window, _: &mut App) -> AnyElement {
847        Empty.into_any_element()
848    }
849}
850
851#[cfg(test)]
852mod tests {
853    use std::{cell::RefCell, rc::Rc};
854
855    use gpui::{Bounds, Entity, TestAppContext, VisualTestContext, point, size};
856
857    use super::*;
858    use crate::ElementExt as _;
859    use crate::dock::{
860        DockArea, DockAreaRenderer, DockLayout, TabGroupRenderer, test_support::TestPanel,
861    };
862
863    /// What each hook drew, in the order the frame prepainted it.
864    ///
865    /// Prepaint order, not call order: the overlay has to be *below the tiles
866    /// in the element tree*, and a renderer that computed it early and added
867    /// it late would still be called first. Prepaint walks the tree, so this
868    /// records the property that matters.
869    #[derive(Default)]
870    struct DrawOrder {
871        painted: Vec<&'static str>,
872        content: Option<Size<Pixels>>,
873        /// The contexts the drag bar was handed, so a test can drive a tile
874        /// through the same seam a skin would.
875        tiles: Vec<TileContext>,
876    }
877
878    struct OrderRecorder {
879        order: Rc<RefCell<DrawOrder>>,
880    }
881
882    impl TilesRenderer for OrderRecorder {
883        fn render_drag_bar(&self, tile: &TileContext, _: &mut Window, _: &mut App) -> AnyElement {
884            self.order.borrow_mut().tiles.push(tile.clone());
885            Empty.into_any_element()
886        }
887
888        fn panel_frame(&self, tile: &TileContext, _: &mut Window, _: &mut App) -> Stateful<Div> {
889            let order = self.order.clone();
890            div()
891                .id(("tile", tile.panel_id().as_u64()))
892                .on_prepaint(move |_, _, _| order.borrow_mut().painted.push("tile"))
893        }
894
895        fn render_overlay(
896            &self,
897            content: Size<Pixels>,
898            _: &mut Window,
899            _: &mut App,
900        ) -> Option<AnyElement> {
901            let order = self.order.clone();
902            Some(
903                div()
904                    .on_prepaint(move |_, _, _| {
905                        let mut order = order.borrow_mut();
906                        order.painted.push("overlay");
907                        order.content = Some(content);
908                    })
909                    .into_any_element(),
910            )
911        }
912    }
913
914    impl TabGroupRenderer for OrderRecorder {
915        fn render_tab_bar(
916            &self,
917            _: &super::super::TabGroupContext,
918            _: &mut Window,
919            _: &mut App,
920        ) -> AnyElement {
921            Empty.into_any_element()
922        }
923    }
924
925    impl DockAreaRenderer for OrderRecorder {
926        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
927            Rc::new(OrderRecorder {
928                order: self.order.clone(),
929            })
930        }
931
932        fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
933            Rc::new(OrderRecorder {
934                order: self.order.clone(),
935            })
936        }
937    }
938
939    fn setup_order(
940        cx: &mut TestAppContext,
941    ) -> (
942        Entity<DockArea>,
943        Rc<RefCell<DrawOrder>>,
944        &mut VisualTestContext,
945    ) {
946        cx.update(|cx| {
947            let _ = crate::Theme::global_mut(cx);
948        });
949        let order: Rc<RefCell<DrawOrder>> = Rc::default();
950        let renderer = Rc::new(OrderRecorder {
951            order: order.clone(),
952        });
953        let (area, cx) = cx.add_window_view(|window, cx| {
954            DockArea::new("tiles-order", None, window, cx).with_renderer(renderer)
955        });
956        (area, order, cx)
957    }
958
959    /// The canvas overlay is drawn after every tile.
960    ///
961    /// This is the whole reason the hook exists rather than the skin adding a
962    /// scrollbar to the canvas frame: the frame is the scroll container, and
963    /// base appends the tiles to whatever it carries, so anything placed there
964    /// paints and hit-tests underneath every tile. Move
965    /// `children(render_overlay(..))` above `children(tiles)` in
966    /// `TilesState::render` and this fails.
967    #[gpui::test]
968    fn the_canvas_overlay_is_drawn_after_every_tile(cx: &mut TestAppContext) {
969        let (area, order, cx) = setup_order(cx);
970
971        cx.update(|window, cx| {
972            let first = TestPanel::new("First", cx);
973            let second = TestPanel::new("Second", cx);
974            let layout = DockLayout::tiles()
975                .tile(
976                    first,
977                    Bounds {
978                        origin: point(px(20.), px(20.)),
979                        size: size(px(100.), px(80.)),
980                    },
981                )
982                .tile(
983                    second,
984                    Bounds {
985                        origin: point(px(140.), px(20.)),
986                        size: size(px(100.), px(80.)),
987                    },
988                );
989            area.update(cx, |area, cx| area.set_center(layout, window, cx));
990        });
991        cx.run_until_parked();
992        order.borrow_mut().painted.clear();
993        cx.update(|window, cx| window.draw(cx).clear(cx));
994
995        assert_eq!(
996            order.borrow().painted,
997            vec!["tile", "tile", "overlay"],
998            "the overlay must come after every tile, or it paints beneath them"
999        );
1000
1001        // And it is handed the whole canvas, not the tile it happens to sit
1002        // over: 20..240 across and 20..100 down, measured from the origin.
1003        assert_eq!(
1004            order.borrow().content,
1005            Some(size(px(240.), px(100.))),
1006            "the overlay is given the canvas's scrollable extent"
1007        );
1008    }
1009
1010    /// A zoomed tile fills the dock, so there is no canvas to overlay.
1011    #[gpui::test]
1012    fn a_zoomed_canvas_draws_no_overlay(cx: &mut TestAppContext) {
1013        let (area, order, cx) = setup_order(cx);
1014
1015        let panel = cx.update(|window, cx| {
1016            let panel = TestPanel::new("Only", cx);
1017            let layout = DockLayout::tiles().tile(
1018                panel.clone(),
1019                Bounds {
1020                    origin: point(px(20.), px(20.)),
1021                    size: size(px(100.), px(80.)),
1022                },
1023            );
1024            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1025            panel
1026        });
1027        cx.run_until_parked();
1028
1029        // Zoomed through the seam a skin uses, not a back door.
1030        cx.update(|window, cx| window.draw(cx).clear(cx));
1031        let tile = order.borrow().tiles.last().cloned().expect("the tile drew");
1032        cx.update(|window, cx| tile.toggle_zoom(window, cx));
1033        cx.run_until_parked();
1034        assert_eq!(
1035            cx.read(|cx| area.read(cx).zoomed_tile()),
1036            Some(PanelId::from(panel.entity_id())),
1037            "the tile is the one filling the dock"
1038        );
1039        order.borrow_mut().painted.clear();
1040        cx.update(|window, cx| window.draw(cx).clear(cx));
1041
1042        assert_eq!(
1043            order.borrow().painted,
1044            vec!["tile"],
1045            "a zoomed tile fills the dock, so no overlay is drawn over it"
1046        );
1047    }
1048}