Skip to main content

strata_layout/
geometry.rs

1//! Geometry structures for CSS Box Model and subpixel layout snapping.
2
3use strata_primitives::geom::{EdgeInsets, Point as PrimPoint, Rect as PrimRect, Size as PrimSize};
4use strata_primitives::LayoutUnit;
5
6/// 2D Cartesian Coordinate Point.
7pub type Point = PrimPoint<f32>;
8
9/// 2D Size Dimensions.
10pub type Size = PrimSize<f32>;
11
12/// 2D Rectangle in floating point pixels.
13#[repr(C)]
14#[derive(Debug, Clone, Copy, PartialEq, Default)]
15pub struct Rect {
16    pub x: f32,
17    pub y: f32,
18    pub width: f32,
19    pub height: f32,
20}
21
22impl Rect {
23    #[inline(always)]
24    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
25        Self {
26            x,
27            y,
28            width,
29            height,
30        }
31    }
32
33    #[inline(always)]
34    pub const fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Self {
35        Self {
36            x,
37            y,
38            width,
39            height,
40        }
41    }
42
43    #[inline(always)]
44    pub const fn zero() -> Self {
45        Self {
46            x: 0.0,
47            y: 0.0,
48            width: 0.0,
49            height: 0.0,
50        }
51    }
52
53    #[inline(always)]
54    pub fn min_x(self) -> f32 {
55        self.x
56    }
57    #[inline(always)]
58    pub fn max_x(self) -> f32 {
59        self.x + self.width
60    }
61    #[inline(always)]
62    pub fn min_y(self) -> f32 {
63        self.y
64    }
65    #[inline(always)]
66    pub fn max_y(self) -> f32 {
67        self.y + self.height
68    }
69
70    /// Computes intersection with another rectangle if overlapping.
71    #[inline]
72    pub fn intersect(self, other: Self) -> Option<Self> {
73        let x0 = self.min_x().max(other.min_x());
74        let y0 = self.min_y().max(other.min_y());
75        let x1 = self.max_x().min(other.max_x());
76        let y1 = self.max_y().min(other.max_y());
77
78        if x1 > x0 && y1 > y0 {
79            Some(Self::new(x0, y0, x1 - x0, y1 - y0))
80        } else {
81            None
82        }
83    }
84
85    /// Returns true if this rectangle contains the given point (px, py).
86    #[inline]
87    pub fn contains_point(self, px: f32, py: f32) -> bool {
88        px >= self.min_x() && px <= self.max_x() && py >= self.min_y() && py <= self.max_y()
89    }
90
91    /// Returns true if this rectangle completely encloses `other`.
92    #[inline]
93    pub fn contains_rect(self, other: Self) -> bool {
94        if other.width <= 0.0 || other.height <= 0.0 {
95            return false;
96        }
97        other.min_x() >= self.min_x()
98            && other.max_x() <= self.max_x()
99            && other.min_y() >= self.min_y()
100            && other.max_y() <= self.max_y()
101    }
102
103    /// Chromium subpixel layout boundary snapping via `LayoutUnit` (1/64th px fixed point).
104    ///
105    /// Snaps bounding edges against global screen space, deriving width and height
106    /// as `snapped_max - snapped_min`. This guarantees adjacent sibling boxes and
107    /// deeply nested descendants snap seamlessly with zero hairline cracks or rounding drift.
108    pub fn snap_to_pixel(self) -> Self {
109        let x = if self.x.is_finite() {
110            self.x.clamp(-1e7, 1e7)
111        } else {
112            0.0
113        };
114        let y = if self.y.is_finite() {
115            self.y.clamp(-1e7, 1e7)
116        } else {
117            0.0
118        };
119        let w = if self.width.is_finite() {
120            self.width.clamp(0.0, 1e7)
121        } else {
122            0.0
123        };
124        let h = if self.height.is_finite() {
125            self.height.clamp(0.0, 1e7)
126        } else {
127            0.0
128        };
129
130        let snapped_x = LayoutUnit::from_f32(x).to_f32();
131        let snapped_y = LayoutUnit::from_f32(y).to_f32();
132        let snapped_max_x = LayoutUnit::from_f32(x + w).to_f32();
133        let snapped_max_y = LayoutUnit::from_f32(y + h).to_f32();
134
135        Self {
136            x: snapped_x,
137            y: snapped_y,
138            width: (snapped_max_x - snapped_x).max(0.0),
139            height: (snapped_max_y - snapped_y).max(0.0),
140        }
141    }
142
143    /// Snaps bounding edges against a device scale factor (e.g. 1.0 for 1x, 2.0 for Retina).
144    pub fn snap_to_scale(self, scale: f32) -> Self {
145        let s = if scale > 0.0 && scale.is_finite() {
146            scale
147        } else {
148            1.0
149        };
150        let x = if self.x.is_finite() {
151            self.x.clamp(-1e7, 1e7)
152        } else {
153            0.0
154        };
155        let y = if self.y.is_finite() {
156            self.y.clamp(-1e7, 1e7)
157        } else {
158            0.0
159        };
160        let w = if self.width.is_finite() {
161            self.width.clamp(0.0, 1e7)
162        } else {
163            0.0
164        };
165        let h = if self.height.is_finite() {
166            self.height.clamp(0.0, 1e7)
167        } else {
168            0.0
169        };
170
171        let snapped_x = (x * s).round() / s;
172        let snapped_y = (y * s).round() / s;
173        let snapped_max_x = ((x + w) * s).round() / s;
174        let snapped_max_y = ((y + h) * s).round() / s;
175
176        Self {
177            x: snapped_x,
178            y: snapped_y,
179            width: (snapped_max_x - snapped_x).max(0.0),
180            height: (snapped_max_y - snapped_y).max(0.0),
181        }
182    }
183
184    /// Returns true if all components of the rectangle are finite numbers.
185    #[inline(always)]
186    pub fn is_finite(&self) -> bool {
187        self.x.is_finite()
188            && self.y.is_finite()
189            && self.width.is_finite()
190            && self.height.is_finite()
191    }
192
193    /// Sanitizes all coordinates ensuring they are finite and clamped to valid layout limits.
194    pub fn sanitize(&mut self) {
195        if !self.x.is_finite() {
196            self.x = 0.0;
197        } else {
198            self.x = self.x.clamp(-1e7, 1e7);
199        }
200        if !self.y.is_finite() {
201            self.y = 0.0;
202        } else {
203            self.y = self.y.clamp(-1e7, 1e7);
204        }
205        if !self.width.is_finite() {
206            self.width = 0.0;
207        } else {
208            self.width = self.width.clamp(0.0, 1e7);
209        }
210        if !self.height.is_finite() {
211            self.height = 0.0;
212        } else {
213            self.height = self.height.clamp(0.0, 1e7);
214        }
215    }
216}
217
218impl From<PrimRect<f32>> for Rect {
219    fn from(r: PrimRect<f32>) -> Self {
220        Self {
221            x: r.origin.x,
222            y: r.origin.y,
223            width: r.size.width,
224            height: r.size.height,
225        }
226    }
227}
228
229impl From<Rect> for PrimRect<f32> {
230    fn from(r: Rect) -> Self {
231        PrimRect::from_xywh(r.x, r.y, r.width, r.height)
232    }
233}
234
235/// The concentric boxes and scroll metrics forming the CSS Box Model for an element.
236#[derive(Debug, Clone, Copy, PartialEq, Default)]
237pub struct LayoutGeometry {
238    /// Content box (where inner text and child elements reside).
239    pub content_box: Rect,
240    /// Padding box (content box expanded by padding insets).
241    pub padding_box: Rect,
242    /// Border box (padding box expanded by border widths).
243    /// This is the primary rectangle used for element rendering and layout bounds.
244    pub border_box: Rect,
245    /// Margin box (border box expanded by margin insets).
246    pub margin_box: Rect,
247    /// Total scrollable content extent (width, height) enclosing all overflowing children.
248    pub scroll_bounds: Size,
249    /// Current scroll offset (scroll_x, scroll_y).
250    pub scroll_offset: Point,
251    /// Whether element has scrollable overflow along (horizontal, vertical) axes.
252    pub has_scroll: (bool, bool),
253}
254
255impl LayoutGeometry {
256    /// Returns true if all concentric boxes contain strictly finite coordinates.
257    #[inline(always)]
258    pub fn is_finite(&self) -> bool {
259        self.content_box.is_finite()
260            && self.padding_box.is_finite()
261            && self.border_box.is_finite()
262            && self.margin_box.is_finite()
263    }
264
265    /// Sanitizes all concentric rectangles to strictly finite values.
266    pub fn sanitize(&mut self) {
267        self.content_box.sanitize();
268        self.padding_box.sanitize();
269        self.border_box.sanitize();
270        self.margin_box.sanitize();
271    }
272
273    /// Returns the maximum allowable scroll offset `(max_x, max_y)`.
274    #[inline(always)]
275    pub fn max_scroll(&self) -> Point {
276        Point::new(
277            (self.scroll_bounds.width - self.padding_box.width).max(0.0),
278            (self.scroll_bounds.height - self.padding_box.height).max(0.0),
279        )
280    }
281
282    /// Returns true if this element is an active scroll container.
283    #[inline(always)]
284    pub fn is_scroll_container(&self) -> bool {
285        self.has_scroll.0 || self.has_scroll.1
286    }
287
288    /// Clamps a candidate scroll offset to valid bounds `[0, max_scroll]`.
289    #[inline(always)]
290    pub fn clamp_scroll_offset(&self, offset: Point) -> Point {
291        let max = self.max_scroll();
292        Point::new(offset.x.clamp(0.0, max.x), offset.y.clamp(0.0, max.y))
293    }
294
295    /// Computes concentric boxes from a given border_box and padding/border/margin insets.
296    pub fn from_border_box(
297        border_box: Rect,
298        padding: EdgeInsets<f32>,
299        border: EdgeInsets<f32>,
300        margin: EdgeInsets<f32>,
301    ) -> Self {
302        let sanitize_edge = |e: EdgeInsets<f32>| -> EdgeInsets<f32> {
303            EdgeInsets {
304                top: if e.top.is_finite() {
305                    e.top.clamp(-1e7, 1e7)
306                } else {
307                    0.0
308                },
309                right: if e.right.is_finite() {
310                    e.right.clamp(-1e7, 1e7)
311                } else {
312                    0.0
313                },
314                bottom: if e.bottom.is_finite() {
315                    e.bottom.clamp(-1e7, 1e7)
316                } else {
317                    0.0
318                },
319                left: if e.left.is_finite() {
320                    e.left.clamp(-1e7, 1e7)
321                } else {
322                    0.0
323                },
324            }
325        };
326
327        let padding = sanitize_edge(padding);
328        let border = sanitize_edge(border);
329        let margin = sanitize_edge(margin);
330
331        let bx = if border_box.x.is_finite() {
332            border_box.x.clamp(-1e7, 1e7)
333        } else {
334            0.0
335        };
336        let by = if border_box.y.is_finite() {
337            border_box.y.clamp(-1e7, 1e7)
338        } else {
339            0.0
340        };
341        let bw = if border_box.width.is_finite() {
342            border_box.width.clamp(0.0, 1e7)
343        } else {
344            0.0
345        };
346        let bh = if border_box.height.is_finite() {
347            border_box.height.clamp(0.0, 1e7)
348        } else {
349            0.0
350        };
351        let border_box = Rect::new(bx, by, bw, bh);
352
353        let content_box = Rect::new(
354            border_box.x + border.left + padding.left,
355            border_box.y + border.top + padding.top,
356            (border_box.width - border.left - border.right - padding.left - padding.right)
357                .clamp(0.0, 1e7),
358            (border_box.height - border.top - border.bottom - padding.top - padding.bottom)
359                .clamp(0.0, 1e7),
360        );
361
362        let padding_box = Rect::new(
363            border_box.x + border.left,
364            border_box.y + border.top,
365            (border_box.width - border.left - border.right).clamp(0.0, 1e7),
366            (border_box.height - border.top - border.bottom).clamp(0.0, 1e7),
367        );
368
369        let margin_box = Rect::new(
370            border_box.x - margin.left,
371            border_box.y - margin.top,
372            (border_box.width + margin.left + margin.right).clamp(0.0, 1e7),
373            (border_box.height + margin.top + margin.bottom).clamp(0.0, 1e7),
374        );
375
376        let scroll_bounds = Size::new(content_box.width, content_box.height);
377        let scroll_offset = Point::ZERO;
378        let has_scroll = (false, false);
379
380        Self {
381            content_box,
382            padding_box,
383            border_box,
384            margin_box,
385            scroll_bounds,
386            scroll_offset,
387            has_scroll,
388        }
389    }
390
391    /// Computes concentric boxes while preserving the specified scroll offset.
392    pub fn from_border_box_with_scroll(
393        border_box: Rect,
394        padding: EdgeInsets<f32>,
395        border: EdgeInsets<f32>,
396        margin: EdgeInsets<f32>,
397        scroll_offset: Point,
398    ) -> Self {
399        let mut geom = Self::from_border_box(border_box, padding, border, margin);
400        geom.scroll_offset = scroll_offset;
401        geom
402    }
403
404    /// Translates all concentric rectangles by (dx, dy).
405    pub fn translate(&mut self, dx: f32, dy: f32) {
406        self.content_box.x += dx;
407        self.content_box.y += dy;
408        self.padding_box.x += dx;
409        self.padding_box.y += dy;
410        self.border_box.x += dx;
411        self.border_box.y += dy;
412        self.margin_box.x += dx;
413        self.margin_box.y += dy;
414    }
415
416    /// Snaps all concentric rectangles to Chromium subpixel coordinates.
417    pub fn snap_to_pixel(&mut self) {
418        let _prof = crate::prof::Scope::new(crate::prof::Slot::Geometry);
419        self.content_box = self.content_box.snap_to_pixel();
420        self.padding_box = self.padding_box.snap_to_pixel();
421        self.border_box = self.border_box.snap_to_pixel();
422        self.margin_box = self.margin_box.snap_to_pixel();
423    }
424
425    /// Snaps all concentric rectangles against a device scale factor.
426    pub fn snap_to_scale(&mut self, scale: f32) {
427        let _prof = crate::prof::Scope::new(crate::prof::Slot::Geometry);
428        self.content_box = self.content_box.snap_to_scale(scale);
429        self.padding_box = self.padding_box.snap_to_scale(scale);
430        self.border_box = self.border_box.snap_to_scale(scale);
431        self.margin_box = self.margin_box.snap_to_scale(scale);
432    }
433}