1use std::ops::{Add, Sub};
4
5use kurbo::PathSeg;
6#[cfg(feature = "svg")]
7use tiny_skia::PathSegment;
8use tiny_skia::{Path, PathBuilder as TinyPathBuilder};
9use xxhash_rust::xxh3::Xxh3;
10
11use crate::{layout_unit::LayoutUnit, style::Affine};
12
13pub(crate) const LAYOUT_UNIT_EPSILON: f32 = 1.0 / 64.0;
18
19#[derive(Debug, Clone, Copy, PartialEq, Default)]
21pub struct Point<T> {
22 pub x: T,
24 pub y: T,
26}
27
28impl<T> Point<T> {
29 pub const fn new(x: T, y: T) -> Self {
31 Self { x, y }
32 }
33
34 pub(crate) fn all(value: T) -> Self
36 where
37 T: Copy,
38 {
39 Self { x: value, y: value }
40 }
41
42 pub fn map<R>(self, f: impl Fn(T) -> R) -> Point<R> {
44 Point {
45 x: f(self.x),
46 y: f(self.y),
47 }
48 }
49}
50
51impl Point<f32> {
52 pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
54}
55
56impl<U, T: Add<U>> Add<Point<U>> for Point<T> {
57 type Output = Point<<T as Add<U>>::Output>;
58
59 fn add(self, rhs: Point<U>) -> Self::Output {
60 Point {
61 x: self.x + rhs.x,
62 y: self.y + rhs.y,
63 }
64 }
65}
66
67impl<U, T: Sub<U>> Sub<Point<U>> for Point<T> {
68 type Output = Point<<T as Sub<U>>::Output>;
69
70 fn sub(self, rhs: Point<U>) -> Self::Output {
71 Point {
72 x: self.x - rhs.x,
73 y: self.y - rhs.y,
74 }
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Default)]
80pub struct Size<T> {
81 pub width: T,
83 pub height: T,
85}
86
87impl<T> Size<T> {
88 pub const fn new(width: T, height: T) -> Self {
90 Self { width, height }
91 }
92
93 pub(crate) fn all(value: T) -> Self
95 where
96 T: Copy,
97 {
98 Self {
99 width: value,
100 height: value,
101 }
102 }
103
104 pub fn map<R>(self, f: impl Fn(T) -> R) -> Size<R> {
106 Size {
107 width: f(self.width),
108 height: f(self.height),
109 }
110 }
111
112 pub fn zip_map<O, R>(self, other: Size<O>, f: impl Fn(T, O) -> R) -> Size<R> {
114 Size {
115 width: f(self.width, other.width),
116 height: f(self.height, other.height),
117 }
118 }
119}
120
121impl Size<f32> {
122 pub const ZERO: Self = Self {
124 width: 0.0,
125 height: 0.0,
126 };
127
128 pub fn has_area(self) -> bool {
130 self.width.is_finite() && self.height.is_finite() && self.width > 0.0 && self.height > 0.0
131 }
132
133 pub fn inset(self, inset: Rect<f32>) -> Self {
135 Size {
136 width: (self.width - inset.left - inset.right).max(0.0),
137 height: (self.height - inset.top - inset.bottom).max(0.0),
138 }
139 }
140}
141
142impl<U, T: Add<U>> Add<Size<U>> for Size<T> {
143 type Output = Size<<T as Add<U>>::Output>;
144
145 fn add(self, rhs: Size<U>) -> Self::Output {
146 Size {
147 width: self.width + rhs.width,
148 height: self.height + rhs.height,
149 }
150 }
151}
152
153impl<U, T: Sub<U>> Sub<Size<U>> for Size<T> {
154 type Output = Size<<T as Sub<U>>::Output>;
155
156 fn sub(self, rhs: Size<U>) -> Self::Output {
157 Size {
158 width: self.width - rhs.width,
159 height: self.height - rhs.height,
160 }
161 }
162}
163
164impl Size<Option<f32>> {
165 pub const NONE: Self = Self {
167 width: None,
168 height: None,
169 };
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Default)]
174pub struct Rect<T> {
175 pub left: T,
177 pub right: T,
179 pub top: T,
181 pub bottom: T,
183}
184
185impl<T> Rect<T> {
186 pub(crate) fn all(value: T) -> Self
188 where
189 T: Copy,
190 {
191 Self {
192 left: value,
193 right: value,
194 top: value,
195 bottom: value,
196 }
197 }
198
199 pub fn map<R>(self, f: impl Fn(T) -> R) -> Rect<R> {
201 Rect {
202 left: f(self.left),
203 right: f(self.right),
204 top: f(self.top),
205 bottom: f(self.bottom),
206 }
207 }
208}
209
210impl<T: Add<Output = T> + Copy> Rect<T> {
211 pub fn horizontal(self) -> T {
213 self.left + self.right
214 }
215
216 pub fn vertical(self) -> T {
218 self.top + self.bottom
219 }
220}
221
222impl Rect<f32> {
223 pub const ZERO: Self = Self {
225 left: 0.0,
226 right: 0.0,
227 top: 0.0,
228 bottom: 0.0,
229 };
230
231 pub fn top_left(self) -> Point<f32> {
233 Point {
234 x: self.left,
235 y: self.top,
236 }
237 }
238
239 pub(crate) fn saturating_sub(self, rhs: Self) -> Self {
241 Rect {
242 top: (self.top - rhs.top).max(0.0),
243 right: (self.right - rhs.right).max(0.0),
244 bottom: (self.bottom - rhs.bottom).max(0.0),
245 left: (self.left - rhs.left).max(0.0),
246 }
247 }
248}
249
250#[cfg(feature = "svg-raster")]
251impl Rect<f32> {
252 pub(crate) fn pixel_bounds(&self, transform: Affine) -> Option<Rect<i32>> {
255 let bounds = self.transformed(transform).filter(Self::has_area)?;
256 let (left, top) = (bounds.left.floor() as i32, bounds.top.floor() as i32);
257
258 Some(Rect {
259 left,
260 top,
261 right: left.checked_add((bounds.width().ceil() as i32).max(1))?,
262 bottom: top.checked_add((bounds.height().ceil() as i32).max(1))?,
263 })
264 }
265}
266
267#[cfg(feature = "svg-raster")]
268impl Rect<i32> {
269 pub(crate) fn from_size(x: i32, y: i32, width: u32, height: u32) -> Self {
271 Self {
272 left: x,
273 top: y,
274 right: x.saturating_add_unsigned(width),
275 bottom: y.saturating_add_unsigned(height),
276 }
277 }
278
279 pub(crate) fn width(&self) -> u32 {
280 self.right.abs_diff(self.left)
281 }
282
283 pub(crate) fn height(&self) -> u32 {
284 self.bottom.abs_diff(self.top)
285 }
286
287 pub(crate) fn intersection(&self, other: &Self) -> Option<Self> {
289 let rect = Self {
290 left: self.left.max(other.left),
291 top: self.top.max(other.top),
292 right: self.right.min(other.right),
293 bottom: self.bottom.min(other.bottom),
294 };
295
296 (rect.left < rect.right && rect.top < rect.bottom).then_some(rect)
297 }
298
299 pub(crate) fn translated(&self, dx: i32, dy: i32) -> Self {
301 Self {
302 left: self.left.saturating_add(dx),
303 top: self.top.saturating_add(dy),
304 right: self.right.saturating_add(dx),
305 bottom: self.bottom.saturating_add(dy),
306 }
307 }
308}
309
310#[cfg(feature = "svg")]
311impl Rect<f32> {
312 pub(crate) fn from_ltrb(left: f32, top: f32, right: f32, bottom: f32) -> Option<Self> {
314 let rect = Self {
315 left,
316 right,
317 top,
318 bottom,
319 };
320 let finite = [left, right, top, bottom, rect.width(), rect.height()]
321 .iter()
322 .all(|value| value.is_finite());
323
324 (finite && left <= right && top <= bottom).then_some(rect)
325 }
326
327 pub(crate) fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Option<Self> {
329 Self::from_ltrb(x, y, width + x, height + y)
330 }
331
332 pub(crate) fn positive_from_xywh(x: f32, y: f32, width: f32, height: f32) -> Option<Self> {
334 Self::from_xywh(x, y, width, height).filter(Self::has_area)
335 }
336
337 pub(crate) fn x(&self) -> f32 {
338 self.left
339 }
340
341 pub(crate) fn y(&self) -> f32 {
342 self.top
343 }
344
345 pub(crate) fn width(&self) -> f32 {
346 self.right - self.left
347 }
348
349 pub(crate) fn height(&self) -> f32 {
350 self.bottom - self.top
351 }
352
353 pub(crate) fn has_area(&self) -> bool {
355 self.left < self.right && self.top < self.bottom
356 }
357
358 pub(crate) fn union(&self, other: &Self) -> Self {
360 Self {
361 left: self.left.min(other.left),
362 right: self.right.max(other.right),
363 top: self.top.min(other.top),
364 bottom: self.bottom.max(other.bottom),
365 }
366 }
367
368 pub(crate) fn transformed(&self, transform: Affine) -> Option<Self> {
370 let (left, top, right, bottom) = transformed_rect_extents(
371 self.top_left(),
372 Size::new(self.width(), self.height()),
373 transform,
374 )?;
375
376 Self::from_ltrb(left, top, right, bottom)
377 }
378
379 pub(crate) fn to_bits(self) -> [u32; 4] {
381 [self.left, self.top, self.right, self.bottom].map(f32::to_bits)
382 }
383
384 pub(crate) fn in_bounding_box(&self, bbox: &Self) -> Option<Self> {
386 Self::positive_from_xywh(
387 self.x() * bbox.width() + bbox.x(),
388 self.y() * bbox.height() + bbox.y(),
389 self.width() * bbox.width(),
390 self.height() * bbox.height(),
391 )
392 }
393
394 pub(crate) fn unit_square_transform(&self) -> Affine {
396 Affine {
397 a: self.width(),
398 b: 0.0,
399 c: 0.0,
400 d: self.height(),
401 x: self.x(),
402 y: self.y(),
403 }
404 }
405}
406
407#[cfg(feature = "svg")]
408impl Size<f32> {
409 pub(crate) fn fitted_to(self, target: Self, expand: bool) -> Self {
412 let width = target.height * self.width / self.height;
413 let fits_height = if expand {
414 width <= target.width
415 } else {
416 width >= target.width
417 };
418
419 if fits_height {
420 Self::new(target.width, target.width * self.height / self.width)
421 } else {
422 Self::new(width, target.height)
423 }
424 }
425}
426
427#[derive(Debug, Clone, Copy, PartialEq, Default)]
429pub struct ComputedLayout {
430 pub location: Point<f32>,
432 pub size: Size<f32>,
434 pub border: Rect<f32>,
436 pub padding: Rect<f32>,
438}
439
440impl ComputedLayout {
441 pub fn new(location: Point<f32>, size: Size<f32>, border: Rect<f32>, padding: Rect<f32>) -> Self {
443 Self {
444 location,
445 size,
446 border,
447 padding,
448 }
449 }
450
451 pub fn content_box_width(&self) -> f32 {
453 self.size.width - self.padding.left - self.padding.right - self.border.left - self.border.right
454 }
455
456 pub fn content_box_height(&self) -> f32 {
458 self.size.height - self.padding.top - self.padding.bottom - self.border.top - self.border.bottom
459 }
460
461 pub fn padding_box_width(&self) -> f32 {
463 self.size.width - self.border.left - self.border.right
464 }
465
466 pub fn padding_box_height(&self) -> f32 {
468 self.size.height - self.border.top - self.border.bottom
469 }
470
471 pub fn content_box_size(&self) -> Size<f32> {
473 Size {
474 width: self.content_box_width(),
475 height: self.content_box_height(),
476 }
477 }
478
479 pub fn content_box_offset(&self) -> Point<f32> {
482 Point::new(
483 self.border.left + self.padding.left,
484 self.border.top + self.padding.top,
485 )
486 }
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub struct NodeId(usize);
492
493impl NodeId {
494 pub const ROOT: Self = Self(0);
496
497 pub(crate) const fn new(index: usize) -> Self {
499 Self(index)
500 }
501}
502
503impl From<NodeId> for usize {
504 fn from(id: NodeId) -> Self {
505 id.0
506 }
507}
508
509impl From<NodeId> for u64 {
510 fn from(id: NodeId) -> Self {
511 id.0 as u64
512 }
513}
514
515#[derive(Debug, Clone, Copy, PartialEq)]
517pub enum AvailableSpace {
518 Definite(f32),
520 MinContent,
522 MaxContent,
524}
525
526impl AvailableSpace {
527 pub(crate) fn definite(self) -> Option<LayoutUnit> {
529 match self {
530 Self::Definite(size) => Some(LayoutUnit::from_float(size)),
531 Self::MinContent | Self::MaxContent => None,
532 }
533 }
534}
535
536#[derive(Debug, Clone, Copy, PartialEq)]
538pub enum PathCommand {
539 MoveTo(Point<f32>),
541 LineTo(Point<f32>),
543 QuadTo(Point<f32>, Point<f32>),
545 CubicTo(Point<f32>, Point<f32>, Point<f32>),
547 Close,
549}
550
551impl PathCommand {
552 pub fn build_path(paths: &[Self]) -> Option<Path> {
554 let mut builder = TinyPathBuilder::new();
555
556 for command in paths {
557 match command {
558 Self::MoveTo(point) => builder.move_to(point.x, point.y),
559 Self::LineTo(point) => builder.line_to(point.x, point.y),
560 Self::QuadTo(p1, p2) => builder.quad_to(p1.x, p1.y, p2.x, p2.y),
561 Self::CubicTo(p1, p2, p3) => {
562 builder.cubic_to(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
563 }
564 Self::Close => builder.close(),
565 }
566 }
567
568 builder.finish()
569 }
570
571 #[cfg(feature = "svg")]
573 pub(crate) fn rectangle(x: f32, y: f32, width: f32, height: f32) -> Vec<Self> {
574 vec![
575 Self::MoveTo(Point::new(x, y)),
576 Self::LineTo(Point::new(x + width, y)),
577 Self::LineTo(Point::new(x + width, y + height)),
578 Self::LineTo(Point::new(x, y + height)),
579 Self::Close,
580 ]
581 }
582
583 #[cfg(feature = "svg")]
585 pub(crate) fn from_path(path: &Path) -> Vec<Self> {
586 let point = |point: tiny_skia::Point| Point::new(point.x, point.y);
587
588 path
589 .segments()
590 .map(|segment| match segment {
591 PathSegment::MoveTo(to) => Self::MoveTo(point(to)),
592 PathSegment::LineTo(to) => Self::LineTo(point(to)),
593 PathSegment::QuadTo(control, to) => Self::QuadTo(point(control), point(to)),
594 PathSegment::CubicTo(first, second, to) => {
595 Self::CubicTo(point(first), point(second), point(to))
596 }
597 PathSegment::Close => Self::Close,
598 })
599 .collect()
600 }
601
602 #[cfg(feature = "svg")]
604 pub(crate) fn normalize(paths: &[Self]) -> Option<NormalizedPath> {
605 let path = Self::build_path(paths)?;
606 let edges = |bounds: tiny_skia::Rect| Rect {
607 left: bounds.left(),
608 right: bounds.right(),
609 top: bounds.top(),
610 bottom: bounds.bottom(),
611 };
612
613 Some(NormalizedPath {
614 commands: Self::from_path(&path),
615 bounds: edges(path.compute_tight_bounds()?),
616 control_bounds: edges(path.bounds()),
617 })
618 }
619
620 pub fn digest(paths: &[Self]) -> u64 {
622 let mut h = Xxh3::new();
623 let point = |h: &mut Xxh3, p: &Point<f32>| {
624 h.update(&p.x.to_le_bytes());
625 h.update(&p.y.to_le_bytes());
626 };
627
628 for cmd in paths {
629 match cmd {
630 Self::MoveTo(p) => {
631 h.update(&[0u8]);
632 point(&mut h, p);
633 }
634 Self::LineTo(p) => {
635 h.update(&[1u8]);
636 point(&mut h, p);
637 }
638 Self::QuadTo(p1, p2) => {
639 h.update(&[2u8]);
640 point(&mut h, p1);
641 point(&mut h, p2);
642 }
643 Self::CubicTo(p1, p2, p3) => {
644 h.update(&[3u8]);
645 point(&mut h, p1);
646 point(&mut h, p2);
647 point(&mut h, p3);
648 }
649 Self::Close => {
650 h.update(&[4u8]);
651 }
652 }
653 }
654 h.digest()
655 }
656
657 #[cfg(feature = "svg")]
659 pub(crate) fn transformed(self, transform: Affine) -> Self {
660 self.map_points(|point| {
661 let (x, y) = transform.transform_point(point.x, point.y);
662
663 Point::new(x, y)
664 })
665 }
666
667 pub fn map_points(self, mut f: impl FnMut(Point<f32>) -> Point<f32>) -> Self {
669 match self {
670 Self::MoveTo(point) => Self::MoveTo(f(point)),
671 Self::LineTo(point) => Self::LineTo(f(point)),
672 Self::QuadTo(control, point) => Self::QuadTo(f(control), f(point)),
673 Self::CubicTo(control1, control2, point) => Self::CubicTo(f(control1), f(control2), f(point)),
674 Self::Close => Self::Close,
675 }
676 }
677}
678
679#[cfg(feature = "svg")]
681pub(crate) struct NormalizedPath {
682 pub(crate) commands: Vec<PathCommand>,
683 pub(crate) bounds: Rect<f32>,
685 pub(crate) control_bounds: Rect<f32>,
687}
688
689pub trait PathBuilder {
692 fn move_to(&mut self, point: (f32, f32));
694 fn line_to(&mut self, point: (f32, f32));
696 fn curve_to(&mut self, p1: (f32, f32), p2: (f32, f32), p3: (f32, f32));
698 fn close(&mut self);
700}
701
702impl PathBuilder for Vec<PathCommand> {
703 fn move_to(&mut self, point: (f32, f32)) {
704 self.push(PathCommand::MoveTo(Point::new(point.0, point.1)));
705 }
706
707 fn line_to(&mut self, point: (f32, f32)) {
708 self.push(PathCommand::LineTo(Point::new(point.0, point.1)));
709 }
710
711 fn curve_to(&mut self, p1: (f32, f32), p2: (f32, f32), p3: (f32, f32)) {
712 self.push(PathCommand::CubicTo(
713 Point::new(p1.0, p1.1),
714 Point::new(p2.0, p2.1),
715 Point::new(p3.0, p3.1),
716 ));
717 }
718
719 fn close(&mut self) {
720 self.push(PathCommand::Close);
721 }
722}
723
724pub fn transformed_rect_extents(
727 origin: Point<f32>,
728 size: Size<f32>,
729 transform: Affine,
730) -> Option<(f32, f32, f32, f32)> {
731 let corners = [
732 transform.transform_point(origin.x, origin.y),
733 transform.transform_point(origin.x + size.width, origin.y),
734 transform.transform_point(origin.x, origin.y + size.height),
735 transform.transform_point(origin.x + size.width, origin.y + size.height),
736 ];
737
738 let mut min_x = f32::INFINITY;
739 let mut min_y = f32::INFINITY;
740 let mut max_x = f32::NEG_INFINITY;
741 let mut max_y = f32::NEG_INFINITY;
742 for (x, y) in corners {
743 min_x = min_x.min(x);
744 min_y = min_y.min(y);
745 max_x = max_x.max(x);
746 max_y = max_y.max(y);
747 }
748
749 if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
750 return None;
751 }
752
753 Some((min_x, min_y, max_x, max_y))
754}
755
756#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
758pub struct Placement {
759 pub left: i32,
761 pub top: i32,
763 pub width: u32,
765 pub height: u32,
767}
768
769impl Placement {
770 pub fn right(self) -> i32 {
772 self.left + self.width as i32
773 }
774
775 pub fn bottom(self) -> i32 {
777 self.top + self.height as i32
778 }
779
780 pub fn from_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Option<Self> {
782 if left >= right || top >= bottom {
783 return None;
784 }
785
786 Some(Self {
787 left,
788 top,
789 width: (right - left) as u32,
790 height: (bottom - top) as u32,
791 })
792 }
793
794 pub fn translate(self, dx: i32, dy: i32) -> Self {
796 Self {
797 left: self.left + dx,
798 top: self.top + dy,
799 ..self
800 }
801 }
802
803 pub fn inflate(self, padding: i32) -> Option<Self> {
805 Self::from_bounds(
806 self.left - padding,
807 self.top - padding,
808 self.right() + padding,
809 self.bottom() + padding,
810 )
811 }
812
813 pub fn clamp_to(self, size: Size<u32>) -> Option<Self> {
815 Self::from_bounds(
816 self.left.clamp(0, size.width as i32),
817 self.top.clamp(0, size.height as i32),
818 self.right().clamp(0, size.width as i32),
819 self.bottom().clamp(0, size.height as i32),
820 )
821 }
822}
823
824const ARCLEN_PRECISION_LIMIT: f64 = 1.0 / (1u64 << 50) as f64;
829
830pub(crate) fn arclen_accuracy(segment: PathSeg, finest: f64, relative: f64) -> f64 {
834 let polygon = match segment {
835 PathSeg::Line(line) => line.p0.distance(line.p1),
836 PathSeg::Quad(quad) => quad.p0.distance(quad.p1) + quad.p1.distance(quad.p2),
837 PathSeg::Cubic(cubic) => {
838 cubic.p0.distance(cubic.p1) + cubic.p1.distance(cubic.p2) + cubic.p2.distance(cubic.p3)
839 }
840 };
841
842 (polygon * relative.max(ARCLEN_PRECISION_LIMIT)).max(finest)
843}