Skip to main content

gpui_base/dock/
tiles_geometry.rs

1//! Pure arithmetic for the tiles canvas: magnetic snapping, boundary
2//! constraints, resize math, and grid rounding, plus the undo/redo history
3//! record for a tile change.
4//!
5//! This module decides *where* a tile lands. It draws nothing: the tile
6//! frame, the drag-bar chrome, and the resize-handle visuals are appearance
7//! and live in `crates/ui`.
8
9use gpui::{Bounds, EntityId, Pixels, Point, Size, px, size};
10
11use crate::history::HistoryItem;
12
13/// A tile smaller than this on either axis cannot be usefully manipulated.
14/// This is behavior, not presentation: it bounds what resize/drag arithmetic
15/// will produce.
16pub const MINIMUM_SIZE: Size<Pixels> = size(px(100.), px(100.));
17
18/// Height of the tile's drag bar. This is hit-target geometry the skin must
19/// agree with when it paints the drag bar, not a visual constant, so it
20/// lives here rather than in `crates/ui`.
21pub const DRAG_BAR_HEIGHT: Pixels = px(30.);
22
23/// Size of the resize-handle hit target at a tile's corner/edge. Same
24/// reasoning as [`DRAG_BAR_HEIGHT`].
25pub const HANDLE_SIZE: Pixels = px(5.0);
26
27/// A recorded change to one tile's bounds or z-order, for undo/redo.
28///
29/// Exactly one of the bounds pair or the order pair is populated per change,
30/// mirroring the two ways a tile can be edited (move/resize vs. reorder).
31#[derive(Clone, PartialEq, Debug)]
32pub struct TileChange {
33    tile_id: EntityId,
34    old_bounds: Option<Bounds<Pixels>>,
35    new_bounds: Option<Bounds<Pixels>>,
36    version: usize,
37}
38
39impl TileChange {
40    /// A change record for a tile whose bounds moved or resized.
41    pub fn bounds_change(
42        tile_id: EntityId,
43        old_bounds: Bounds<Pixels>,
44        new_bounds: Bounds<Pixels>,
45    ) -> Self {
46        Self {
47            tile_id,
48            old_bounds: Some(old_bounds),
49            new_bounds: Some(new_bounds),
50            version: 0,
51        }
52    }
53
54    pub fn tile_id(&self) -> EntityId {
55        self.tile_id
56    }
57
58    pub fn old_bounds(&self) -> Option<Bounds<Pixels>> {
59        self.old_bounds
60    }
61
62    pub fn new_bounds(&self) -> Option<Bounds<Pixels>> {
63        self.new_bounds
64    }
65}
66
67impl HistoryItem for TileChange {
68    fn version(&self) -> usize {
69        self.version
70    }
71
72    fn set_version(&mut self, version: usize) {
73        self.version = version;
74    }
75}
76
77/// Which edge (or corner) of a tile a resize drag is manipulating.
78#[derive(Clone, Copy, PartialEq, Eq, Debug)]
79pub enum ResizeSide {
80    Left,
81    Right,
82    Top,
83    Bottom,
84    BottomRight,
85}
86
87/// In-flight state for a resize drag: which side is moving, and the pointer
88/// position and tile bounds recorded at the last processed move event.
89#[derive(Clone, Copy, Debug)]
90pub struct ResizeDrag {
91    side: ResizeSide,
92    last_position: Point<Pixels>,
93    last_bounds: Bounds<Pixels>,
94}
95
96impl ResizeDrag {
97    pub fn new(
98        side: ResizeSide,
99        last_position: Point<Pixels>,
100        last_bounds: Bounds<Pixels>,
101    ) -> Self {
102        Self {
103            side,
104            last_position,
105            last_bounds,
106        }
107    }
108
109    pub fn side(&self) -> ResizeSide {
110        self.side
111    }
112
113    pub fn last_bounds(&self) -> Bounds<Pixels> {
114        self.last_bounds
115    }
116
117    pub fn with_last_position(mut self, last_position: Point<Pixels>) -> Self {
118        self.last_position = last_position;
119        self
120    }
121
122    pub fn with_last_bounds(mut self, last_bounds: Bounds<Pixels>) -> Self {
123        self.last_bounds = last_bounds;
124        self
125    }
126}
127
128/// Snap `edge` to the nearest value in `candidates` whose distance is strictly
129/// below `threshold`. Returns `None` when nothing is close enough.
130pub fn snap_edge(edge: Pixels, candidates: &[Pixels], threshold: Pixels) -> Option<Pixels> {
131    let mut best: Option<Pixels> = None;
132    let mut best_dist = threshold;
133    for &candidate in candidates {
134        let dist = (edge - candidate).abs();
135        if dist < best_dist {
136            best_dist = dist;
137            best = Some(candidate);
138        }
139    }
140    best
141}
142
143/// Compute the final bounds for a resize, applying magnetic edge snapping to
144/// neighboring panels and falling back to grid rounding when no neighbor edge
145/// is within `grid_size`.
146///
147/// Which edges move is inferred from the provided `Option`s, mirroring the
148/// original `Tiles::resize`:
149/// - `new_x` set                  => left edge moves (right edge pinned)
150/// - `new_width` set, `new_x` not => right edge moves (left edge pinned)
151/// - `new_y` set                  => top edge moves (bottom edge pinned)
152/// - `new_height` set, `new_y` not => bottom edge moves (top edge pinned)
153pub fn compute_resized_bounds(
154    previous: Bounds<Pixels>,
155    new_x: Option<Pixels>,
156    new_y: Option<Pixels>,
157    new_width: Option<Pixels>,
158    new_height: Option<Pixels>,
159    other_bounds: &[Bounds<Pixels>],
160    grid_size: Pixels,
161) -> Bounds<Pixels> {
162    // Candidate snap edges from neighbouring panels.
163    let mut x_edges = Vec::with_capacity(other_bounds.len() * 2);
164    let mut y_edges = Vec::with_capacity(other_bounds.len() * 2);
165    for bounds in other_bounds {
166        x_edges.push(bounds.left());
167        x_edges.push(bounds.right());
168        y_edges.push(bounds.top());
169        y_edges.push(bounds.bottom());
170    }
171
172    let prev_right = previous.origin.x + previous.size.width;
173    let prev_bottom = previous.origin.y + previous.size.height;
174
175    // --- X axis ---
176    let (final_x, final_width) = if let Some(x) = new_x {
177        // Left edge moving; right edge pinned. Canvas-left (0) is also a target.
178        let raw_left = x.max(px(0.));
179        let mut candidates = x_edges.clone();
180        candidates.push(px(0.));
181        let snapped_left = snap_edge(raw_left, &candidates, grid_size)
182            .unwrap_or_else(|| round_to_grid(raw_left, grid_size));
183        let width = (prev_right - snapped_left).max(MINIMUM_SIZE.width);
184        (snapped_left, width)
185    } else if let Some(width) = new_width {
186        // Right edge moving; left edge pinned.
187        let raw_right = previous.origin.x + width;
188        let snapped_right = snap_edge(raw_right, &x_edges, grid_size)
189            .unwrap_or_else(|| round_to_grid(raw_right, grid_size));
190        let width = (snapped_right - previous.origin.x).max(MINIMUM_SIZE.width);
191        (previous.origin.x, width)
192    } else {
193        (previous.origin.x, previous.size.width)
194    };
195
196    // --- Y axis ---
197    let (final_y, final_height) = if let Some(y) = new_y {
198        // Top edge moving; bottom edge pinned. Canvas-top (0) is also a target.
199        let raw_top = y.max(px(0.));
200        let mut candidates = y_edges.clone();
201        candidates.push(px(0.));
202        let snapped_top = snap_edge(raw_top, &candidates, grid_size)
203            .unwrap_or_else(|| round_to_grid(raw_top, grid_size));
204        let height = (prev_bottom - snapped_top).max(MINIMUM_SIZE.height);
205        (snapped_top, height)
206    } else if let Some(height) = new_height {
207        // Bottom edge moving; top edge pinned.
208        let raw_bottom = previous.origin.y + height;
209        let snapped_bottom = snap_edge(raw_bottom, &y_edges, grid_size)
210            .unwrap_or_else(|| round_to_grid(raw_bottom, grid_size));
211        let height = (snapped_bottom - previous.origin.y).max(MINIMUM_SIZE.height);
212        (previous.origin.y, height)
213    } else {
214        (previous.origin.y, previous.size.height)
215    };
216
217    Bounds {
218        origin: Point {
219            x: final_x,
220            y: final_y,
221        },
222        size: Size {
223            width: final_width,
224            height: final_height,
225        },
226    }
227}
228
229/// Round `value` to the nearest multiple of `grid_size`.
230///
231/// This is the original `round_to_nearest_ten_with` (already grid-size
232/// parameterized, not `cx`-dependent), renamed to match the split described
233/// below and exposed directly rather than duplicated under two names.
234///
235/// The original `round_to_nearest_ten` and `round_point_to_nearest_ten` read
236/// the grid size off the theme via `cx`; base cannot see a theme, so the
237/// skin reads the grid size and passes it in here instead.
238pub fn round_to_grid(value: Pixels, grid_size: Pixels) -> Pixels {
239    (value / grid_size).round() * grid_size
240}
241
242/// Calculate the magnetic snap position for a tile being dragged.
243///
244/// `moving` is the tile's candidate bounds (already translated by the drag
245/// delta, before snapping). `others` are the bounds of every other tile in
246/// the same canvas. The returned point keeps `moving.origin`'s coordinate on
247/// any axis that did not snap, so the result can be assigned directly as the
248/// tile's new origin.
249pub fn magnetic_snap(
250    moving: Bounds<Pixels>,
251    others: &[Bounds<Pixels>],
252    threshold: Pixels,
253) -> Point<Pixels> {
254    // Only check nearby panels
255    let search_bounds = Bounds {
256        origin: Point {
257            x: moving.left() - threshold,
258            y: moving.top() - threshold,
259        },
260        size: Size {
261            width: moving.size.width + threshold * 2.0,
262            height: moving.size.height + threshold * 2.0,
263        },
264    };
265
266    let mut snap_x: Option<Pixels> = None;
267    let mut snap_y: Option<Pixels> = None;
268    let mut min_x_dist = threshold;
269    let mut min_y_dist = threshold;
270
271    // Pre-calculate dragging bounds edges to avoid repeated method calls
272    let drag_left = moving.left();
273    let drag_right = moving.right();
274    let drag_top = moving.top();
275    let drag_bottom = moving.bottom();
276    let drag_width = moving.size.width;
277    let drag_height = moving.size.height;
278
279    // Check for edge snapping first (top and left boundaries)
280    let edge_snap_pos = px(0.);
281
282    // Snap to top edge
283    let top_dist = drag_top.abs();
284    if top_dist < threshold {
285        snap_y = Some(edge_snap_pos);
286        min_y_dist = top_dist;
287    }
288
289    // Snap to left edge
290    let left_dist = drag_left.abs();
291    if left_dist < threshold {
292        snap_x = Some(edge_snap_pos);
293        min_x_dist = left_dist;
294    }
295
296    // If both edges are snapped, skip the neighbor search entirely.
297    if snap_x.is_none() || snap_y.is_none() {
298        for other in others {
299            if snap_x.is_some() && snap_y.is_some() {
300                break;
301            }
302
303            // Pre-calculate other bounds edges
304            let other_left = other.left();
305            let other_right = other.right();
306            let other_top = other.top();
307            let other_bottom = other.bottom();
308
309            // Skip panels that are far away
310            if other_right < search_bounds.left()
311                || other_left > search_bounds.right()
312                || other_bottom < search_bounds.top()
313                || other_top > search_bounds.bottom()
314            {
315                continue;
316            }
317
318            // Horizontal snapping (X axis) - find closest snap point
319            if snap_x.is_none() {
320                let candidates = [
321                    ((drag_left - other_left).abs(), other_left),
322                    ((drag_left - other_right).abs(), other_right),
323                    ((drag_right - other_left).abs(), other_left - drag_width),
324                    ((drag_right - other_right).abs(), other_right - drag_width),
325                ];
326
327                for (dist, snap_pos) in candidates {
328                    if dist < min_x_dist {
329                        min_x_dist = dist;
330                        snap_x = Some(snap_pos);
331                    }
332                }
333            }
334
335            // Vertical snapping (Y axis) - find closest snap point
336            if snap_y.is_none() {
337                let candidates = [
338                    ((drag_top - other_top).abs(), other_top),
339                    ((drag_top - other_bottom).abs(), other_bottom),
340                    ((drag_bottom - other_top).abs(), other_top - drag_height),
341                    (
342                        (drag_bottom - other_bottom).abs(),
343                        other_bottom - drag_height,
344                    ),
345                ];
346
347                for (dist, snap_pos) in candidates {
348                    if dist < min_y_dist {
349                        min_y_dist = dist;
350                        snap_y = Some(snap_pos);
351                    }
352                }
353            }
354        }
355    }
356
357    Point {
358        x: snap_x.unwrap_or(moving.origin.x),
359        y: snap_y.unwrap_or(moving.origin.y),
360    }
361}
362
363/// Clamp a dragged tile's origin to the canvas boundary.
364///
365/// The top is a hard boundary (a tile's top can never go negative), and at
366/// most `dragging_width - 64px` of the tile may hang off the left edge,
367/// keeping 64px of it visible. There is no boundary on the right or bottom:
368/// the canvas scrolls.
369///
370/// `dragging_width` is the width of the tile being dragged, not a canvas
371/// size — the original `Tiles::apply_boundary_constraints` reads it from
372/// `self.dragging_initial_bounds.size.width`, the entity's own drag-tracking
373/// state, not a container/tile-list argument.
374pub fn apply_boundary_constraints(origin: Point<Pixels>, dragging_width: Pixels) -> Point<Pixels> {
375    let mut origin = origin;
376
377    // Top boundary
378    if origin.y < px(0.) {
379        origin.y = px(0.);
380    }
381
382    // Left boundary (allow partial off-screen but keep 64px visible)
383    let min_left = -dragging_width + px(64.);
384    if origin.x < min_left {
385        origin.x = min_left;
386    }
387
388    origin
389}
390
391/// The scrollable extent a set of tiles occupies, measured from the canvas
392/// origin.
393///
394/// Reproduces the fold the old `Tiles::render` did before handing the result
395/// to its scrollbar: the union runs from `min(0, left)` to `max(0, right)` on
396/// each axis, so a canvas whose tiles all sit at positive coordinates reports
397/// the far edge, and one with a tile dragged past the origin reports the
398/// distance across both.
399pub fn content_size(tiles: &[Bounds<Pixels>]) -> Size<Pixels> {
400    let mut left = px(0.);
401    let mut top = px(0.);
402    let mut right = px(0.);
403    let mut bottom = px(0.);
404    for bounds in tiles {
405        left = left.min(bounds.left());
406        top = top.min(bounds.top());
407        right = right.max(bounds.right());
408        bottom = bottom.max(bounds.bottom());
409    }
410    size(right - left, bottom - top)
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    fn b(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
418        Bounds {
419            origin: Point { x: px(x), y: px(y) },
420            size: Size {
421                width: px(w),
422                height: px(h),
423            },
424        }
425    }
426
427    #[test]
428    fn test_snap_edge_within_threshold() {
429        // 102 is 2px from 100 (< 8) -> snaps to 100.
430        assert_eq!(
431            snap_edge(px(102.), &[px(100.), px(300.)], px(8.)),
432            Some(px(100.))
433        );
434    }
435
436    #[test]
437    fn test_snap_edge_outside_threshold() {
438        // 120 is 20px from nearest candidate (>= 8) -> no snap.
439        assert_eq!(snap_edge(px(120.), &[px(100.), px(300.)], px(8.)), None);
440    }
441
442    #[test]
443    fn test_snap_edge_picks_nearest() {
444        // 303 is 3px from 300 and 5px from 308 -> picks 300.
445        assert_eq!(
446            snap_edge(px(303.), &[px(308.), px(300.)], px(8.)),
447            Some(px(300.))
448        );
449    }
450
451    #[test]
452    fn test_snap_edge_empty_candidates() {
453        assert_eq!(snap_edge(px(50.), &[], px(8.)), None);
454    }
455
456    #[test]
457    fn test_resize_right_edge_snaps_to_neighbor_left() {
458        // Panel A: x=0 w=196 (right edge 196). Neighbour B starts at x=200.
459        // Dragging right edge to 197 should snap right edge to 200 -> width 200.
460        let prev = b(0., 0., 196., 100.);
461        let neighbor = b(200., 0., 100., 100.);
462        let out =
463            compute_resized_bounds(prev, None, None, Some(px(197.)), None, &[neighbor], px(8.));
464        assert_eq!(out.origin.x, px(0.));
465        assert_eq!(out.size.width, px(200.));
466    }
467
468    #[test]
469    fn test_resize_bottom_edge_snaps_to_neighbor_top() {
470        let prev = b(0., 0., 100., 196.);
471        let neighbor = b(0., 200., 100., 100.);
472        let out =
473            compute_resized_bounds(prev, None, None, None, Some(px(197.)), &[neighbor], px(8.));
474        assert_eq!(out.origin.y, px(0.));
475        assert_eq!(out.size.height, px(200.));
476    }
477
478    #[test]
479    fn test_resize_left_edge_snaps_and_pins_right() {
480        // Panel: x=200 w=100 (right edge 300). Neighbour right edge at 100.
481        // Drag left edge to 103 -> snaps to 100 -> width = 300 - 100 = 200.
482        let prev = b(200., 0., 100., 100.);
483        let neighbor = b(0., 0., 100., 100.);
484        let out = compute_resized_bounds(
485            prev,
486            Some(px(103.)),
487            None,
488            Some(px(197.)),
489            None,
490            &[neighbor],
491            px(8.),
492        );
493        assert_eq!(out.origin.x, px(100.));
494        assert_eq!(out.size.width, px(200.));
495    }
496
497    #[test]
498    fn test_resize_corner_snaps_both_edges() {
499        // Right edge -> neighbour-right at 300; bottom edge -> neighbour-bottom at 250.
500        let prev = b(0., 0., 196., 196.);
501        let right_neighbor = b(100., 0., 200., 100.); // right edge = 300
502        let bottom_neighbor = b(0., 100., 100., 150.); // bottom edge = 250
503        let out = compute_resized_bounds(
504            prev,
505            None,
506            None,
507            Some(px(298.)),
508            Some(px(248.)),
509            &[right_neighbor, bottom_neighbor],
510            px(8.),
511        );
512        assert_eq!(out.size.width, px(300.));
513        assert_eq!(out.size.height, px(250.));
514    }
515
516    #[test]
517    fn test_resize_grid_rounds_when_no_neighbor_close() {
518        // No neighbours; raw right edge 153 -> grid round to 152 (nearest multiple of 8).
519        let prev = b(0., 0., 100., 100.);
520        let out = compute_resized_bounds(prev, None, None, Some(px(153.)), None, &[], px(8.));
521        assert_eq!(out.size.width, px(152.));
522    }
523
524    #[test]
525    fn test_resize_respects_minimum_size() {
526        let prev = b(0., 0., 100., 100.);
527        let out = compute_resized_bounds(prev, None, None, Some(px(10.)), None, &[], px(8.));
528        assert_eq!(out.size.width, MINIMUM_SIZE.width);
529    }
530
531    #[test]
532    fn content_size_spans_from_the_origin_to_the_far_edge() {
533        assert_eq!(
534            content_size(&[b(20., 20., 380., 280.), b(420., 20., 380., 280.)]),
535            size(px(800.), px(300.)),
536            "the extent runs from the canvas origin, not from the first tile"
537        );
538        assert_eq!(
539            content_size(&[]),
540            size(px(0.), px(0.)),
541            "an empty canvas scrolls nowhere"
542        );
543        assert_eq!(
544            content_size(&[b(-40., -10., 100., 100.)]),
545            size(px(100.), px(100.)),
546            "a tile dragged past the origin still reports the distance across it"
547        );
548    }
549
550    #[test]
551    fn test_resize_no_change_returns_previous_geometry() {
552        let prev = b(0., 0., 100., 100.);
553        let out = compute_resized_bounds(prev, None, None, None, None, &[], px(8.));
554        assert_eq!(out.origin.x, px(0.));
555        assert_eq!(out.origin.y, px(0.));
556        assert_eq!(out.size.width, px(100.));
557        assert_eq!(out.size.height, px(100.));
558    }
559}