1use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::fmt::{self, Debug, Display};
10use std::hash::{Hash, Hasher};
11
12use std::cell::Cell;
13use std::ops::{Add, Deref, DerefMut};
14use std::rc::Rc;
15
16use waft_embedder::{
17 Matrix4, Offset, Rect, Size, TextBaseline, ViewConstraints, clamp_double, lerp_double,
18};
19use waft_foundation::{App, Handle, HandleId, debug_format_double};
20use waft_gestures::{
21 HitTestEntry, HitTestResult, HitTestTarget, PointerEvent, remove_perspective_transform,
22};
23use waft_painting::EdgeInsetsGeometry;
24use waft_painting::transform_point;
25
26use crate::object::{
27 AnyRenderObject, Constraints, ContainerParentDataMixin, ContainerRenderObjectMixin, ParentData,
28 RenderHandle, RenderObject, RenderObjectVTable, create, debug_checking_intrinsics, resolve,
29};
30use crate::painting_context::PaintingContext;
31use crate::pipeline_owner::PipelineOwner;
32
33thread_local! {
34 static DEBUG_DOING_BASELINE: Cell<bool> = const { Cell::new(false) };
35}
36
37#[derive(Clone, Copy)]
45pub struct BoxConstraints {
46 pub min_width: f64,
48 pub max_width: f64,
52 pub min_height: f64,
54 pub max_height: f64,
58}
59
60impl BoxConstraints {
61 pub const fn new() -> BoxConstraints {
63 BoxConstraints {
64 min_width: 0.0,
65 max_width: f64::INFINITY,
66 min_height: 0.0,
67 max_height: f64::INFINITY,
68 }
69 }
70
71 pub const fn min_width(mut self, value: f64) -> BoxConstraints {
73 self.min_width = value;
74 self
75 }
76
77 pub const fn max_width(mut self, value: f64) -> BoxConstraints {
79 self.max_width = value;
80 self
81 }
82
83 pub const fn min_height(mut self, value: f64) -> BoxConstraints {
85 self.min_height = value;
86 self
87 }
88
89 pub const fn max_height(mut self, value: f64) -> BoxConstraints {
91 self.max_height = value;
92 self
93 }
94
95 pub fn tight(size: Size) -> BoxConstraints {
97 BoxConstraints {
98 min_width: size.width(),
99 max_width: size.width(),
100 min_height: size.height(),
101 max_height: size.height(),
102 }
103 }
104
105 pub const fn tight_for(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
107 BoxConstraints {
108 min_width: match width {
109 Some(width) => width,
110 None => 0.0,
111 },
112 max_width: match width {
113 Some(width) => width,
114 None => f64::INFINITY,
115 },
116 min_height: match height {
117 Some(height) => height,
118 None => 0.0,
119 },
120 max_height: match height {
121 Some(height) => height,
122 None => f64::INFINITY,
123 },
124 }
125 }
126
127 pub const fn tight_for_finite(width: f64, height: f64) -> BoxConstraints {
130 BoxConstraints {
131 min_width: if width != f64::INFINITY { width } else { 0.0 },
132 max_width: if width != f64::INFINITY {
133 width
134 } else {
135 f64::INFINITY
136 },
137 min_height: if height != f64::INFINITY { height } else { 0.0 },
138 max_height: if height != f64::INFINITY {
139 height
140 } else {
141 f64::INFINITY
142 },
143 }
144 }
145
146 pub fn loose(size: Size) -> BoxConstraints {
148 BoxConstraints {
149 min_width: 0.0,
150 max_width: size.width(),
151 min_height: 0.0,
152 max_height: size.height(),
153 }
154 }
155
156 pub const fn expand(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
158 BoxConstraints {
159 min_width: match width {
160 Some(width) => width,
161 None => f64::INFINITY,
162 },
163 max_width: match width {
164 Some(width) => width,
165 None => f64::INFINITY,
166 },
167 min_height: match height {
168 Some(height) => height,
169 None => f64::INFINITY,
170 },
171 max_height: match height {
172 Some(height) => height,
173 None => f64::INFINITY,
174 },
175 }
176 }
177
178 pub const fn from_view_constraints(constraints: ViewConstraints) -> BoxConstraints {
180 BoxConstraints {
181 min_width: constraints.min_width,
182 max_width: constraints.max_width,
183 min_height: constraints.min_height,
184 max_height: constraints.max_height,
185 }
186 }
187
188 pub const fn copy_with(self) -> BoxConstraints {
190 self
191 }
192
193 pub fn deflate(self, edges: EdgeInsetsGeometry) -> BoxConstraints {
195 debug_assert!(self.debug_assert_is_valid(false));
196 let horizontal = edges.horizontal();
197 let vertical = edges.vertical();
198 let deflated_min_width = (self.min_width - horizontal).max(0.0);
199 let deflated_min_height = (self.min_height - vertical).max(0.0);
200 BoxConstraints {
201 min_width: deflated_min_width,
202 max_width: (self.max_width - horizontal).max(deflated_min_width),
203 min_height: deflated_min_height,
204 max_height: (self.max_height - vertical).max(deflated_min_height),
205 }
206 }
207
208 pub fn loosen(self) -> BoxConstraints {
210 debug_assert!(self.debug_assert_is_valid(false));
211 BoxConstraints {
212 min_width: 0.0,
213 max_width: self.max_width,
214 min_height: 0.0,
215 max_height: self.max_height,
216 }
217 }
218
219 pub fn enforce(self, constraints: BoxConstraints) -> BoxConstraints {
222 BoxConstraints {
223 min_width: clamp_double(self.min_width, constraints.min_width, constraints.max_width),
224 max_width: clamp_double(self.max_width, constraints.min_width, constraints.max_width),
225 min_height: clamp_double(
226 self.min_height,
227 constraints.min_height,
228 constraints.max_height,
229 ),
230 max_height: clamp_double(
231 self.max_height,
232 constraints.min_height,
233 constraints.max_height,
234 ),
235 }
236 }
237
238 pub fn tighten(self, width: Option<f64>, height: Option<f64>) -> BoxConstraints {
242 BoxConstraints {
243 min_width: match width {
244 Some(width) => clamp_double(width, self.min_width, self.max_width),
245 None => self.min_width,
246 },
247 max_width: match width {
248 Some(width) => clamp_double(width, self.min_width, self.max_width),
249 None => self.max_width,
250 },
251 min_height: match height {
252 Some(height) => clamp_double(height, self.min_height, self.max_height),
253 None => self.min_height,
254 },
255 max_height: match height {
256 Some(height) => clamp_double(height, self.min_height, self.max_height),
257 None => self.max_height,
258 },
259 }
260 }
261
262 pub const fn flipped(self) -> BoxConstraints {
264 BoxConstraints {
265 min_width: self.min_height,
266 max_width: self.max_height,
267 min_height: self.min_width,
268 max_height: self.max_width,
269 }
270 }
271
272 pub const fn width_constraints(self) -> BoxConstraints {
275 BoxConstraints {
276 min_width: self.min_width,
277 max_width: self.max_width,
278 min_height: 0.0,
279 max_height: f64::INFINITY,
280 }
281 }
282
283 pub const fn height_constraints(self) -> BoxConstraints {
286 BoxConstraints {
287 min_width: 0.0,
288 max_width: f64::INFINITY,
289 min_height: self.min_height,
290 max_height: self.max_height,
291 }
292 }
293
294 pub fn constrain_width(self, width: f64) -> f64 {
297 debug_assert!(self.debug_assert_is_valid(false));
298 clamp_double(width, self.min_width, self.max_width)
299 }
300
301 pub fn constrain_height(self, height: f64) -> f64 {
304 debug_assert!(self.debug_assert_is_valid(false));
305 clamp_double(height, self.min_height, self.max_height)
306 }
307
308 pub fn constrain(self, size: Size) -> Size {
311 Size::new(
312 self.constrain_width(size.width()),
313 self.constrain_height(size.height()),
314 )
315 }
316
317 pub fn constrain_dimensions(self, width: f64, height: f64) -> Size {
320 Size::new(self.constrain_width(width), self.constrain_height(height))
321 }
322
323 pub fn constrain_size_and_attempt_to_preserve_aspect_ratio(self, size: Size) -> Size {
331 if self.is_tight() {
332 return self.smallest();
333 }
334 if size.is_empty() {
335 return self.constrain(size);
336 }
337 let mut width = size.width();
338 let mut height = size.height();
339 let aspect_ratio = width / height;
340 if width > self.max_width {
341 width = self.max_width;
342 height = width / aspect_ratio;
343 }
344 if height > self.max_height {
345 height = self.max_height;
346 width = height * aspect_ratio;
347 }
348 if width < self.min_width {
349 width = self.min_width;
350 height = width / aspect_ratio;
351 }
352 if height < self.min_height {
353 height = self.min_height;
354 width = height * aspect_ratio;
355 }
356 Size::new(self.constrain_width(width), self.constrain_height(height))
357 }
358
359 pub fn biggest(self) -> Size {
361 Size::new(
362 self.constrain_width(f64::INFINITY),
363 self.constrain_height(f64::INFINITY),
364 )
365 }
366
367 pub fn smallest(self) -> Size {
369 Size::new(self.constrain_width(0.0), self.constrain_height(0.0))
370 }
371
372 pub fn has_tight_width(self) -> bool {
374 self.min_width >= self.max_width
375 }
376
377 pub fn has_tight_height(self) -> bool {
379 self.min_height >= self.max_height
380 }
381
382 pub fn has_bounded_width(self) -> bool {
384 self.max_width < f64::INFINITY
385 }
386
387 pub fn has_bounded_height(self) -> bool {
389 self.max_height < f64::INFINITY
390 }
391
392 pub fn has_infinite_width(self) -> bool {
394 self.min_width >= f64::INFINITY
395 }
396
397 pub fn has_infinite_height(self) -> bool {
399 self.min_height >= f64::INFINITY
400 }
401
402 pub fn is_satisfied_by(self, size: Size) -> bool {
404 debug_assert!(self.debug_assert_is_valid(false));
405 self.min_width <= size.width()
406 && size.width() <= self.max_width
407 && self.min_height <= size.height()
408 && size.height() <= self.max_height
409 }
410
411 pub fn truncating_div(self, factor: f64) -> BoxConstraints {
414 BoxConstraints {
415 min_width: (self.min_width / factor).trunc(),
416 max_width: (self.max_width / factor).trunc(),
417 min_height: (self.min_height / factor).trunc(),
418 max_height: (self.max_height / factor).trunc(),
419 }
420 }
421
422 pub fn lerp(
427 a: Option<BoxConstraints>,
428 b: Option<BoxConstraints>,
429 t: f64,
430 ) -> Option<BoxConstraints> {
431 if a == b {
432 return a;
433 }
434 let Some(a) = a else {
435 return Some((b.unwrap() * t).normalize());
436 };
437 let Some(b) = b else {
438 return Some((a * (1.0 - t)).normalize());
439 };
440 debug_assert!(a.debug_assert_is_valid(false));
441 debug_assert!(b.debug_assert_is_valid(false));
442 debug_assert!(
443 (a.min_width.is_finite() && b.min_width.is_finite())
444 || (a.min_width == f64::INFINITY && b.min_width == f64::INFINITY),
445 "Cannot interpolate between finite constraints and unbounded constraints."
446 );
447 debug_assert!(
448 (a.max_width.is_finite() && b.max_width.is_finite())
449 || (a.max_width == f64::INFINITY && b.max_width == f64::INFINITY),
450 "Cannot interpolate between finite constraints and unbounded constraints."
451 );
452 debug_assert!(
453 (a.min_height.is_finite() && b.min_height.is_finite())
454 || (a.min_height == f64::INFINITY && b.min_height == f64::INFINITY),
455 "Cannot interpolate between finite constraints and unbounded constraints."
456 );
457 debug_assert!(
458 (a.max_height.is_finite() && b.max_height.is_finite())
459 || (a.max_height == f64::INFINITY && b.max_height == f64::INFINITY),
460 "Cannot interpolate between finite constraints and unbounded constraints."
461 );
462 Some(
463 BoxConstraints {
464 min_width: if a.min_width.is_finite() {
465 lerp_double(Some(a.min_width), Some(b.min_width), t).unwrap()
466 } else {
467 f64::INFINITY
468 },
469 max_width: if a.max_width.is_finite() {
470 lerp_double(Some(a.max_width), Some(b.max_width), t).unwrap()
471 } else {
472 f64::INFINITY
473 },
474 min_height: if a.min_height.is_finite() {
475 lerp_double(Some(a.min_height), Some(b.min_height), t).unwrap()
476 } else {
477 f64::INFINITY
478 },
479 max_height: if a.max_height.is_finite() {
480 lerp_double(Some(a.max_height), Some(b.max_height), t).unwrap()
481 } else {
482 f64::INFINITY
483 },
484 }
485 .normalize(),
486 )
487 }
488
489 pub fn normalize(self) -> BoxConstraints {
491 if self.is_normalized() {
492 return self;
493 }
494 let min_width = if self.min_width >= 0.0 {
495 self.min_width
496 } else {
497 0.0
498 };
499 let min_height = if self.min_height >= 0.0 {
500 self.min_height
501 } else {
502 0.0
503 };
504 BoxConstraints {
505 min_width,
506 max_width: if min_width > self.max_width {
507 min_width
508 } else {
509 self.max_width
510 },
511 min_height,
512 max_height: if min_height > self.max_height {
513 min_height
514 } else {
515 self.max_height
516 },
517 }
518 }
519}
520
521impl Default for BoxConstraints {
522 fn default() -> BoxConstraints {
523 BoxConstraints::new()
524 }
525}
526
527impl Constraints for BoxConstraints {
528 fn is_tight(&self) -> bool {
529 self.has_tight_width() && self.has_tight_height()
530 }
531
532 fn is_normalized(&self) -> bool {
533 self.min_width >= 0.0
534 && self.min_width <= self.max_width
535 && self.min_height >= 0.0
536 && self.min_height <= self.max_height
537 }
538
539 fn debug_assert_is_valid(&self, is_applied_constraint: bool) -> bool {
540 if cfg!(debug_assertions) {
541 assert!(
542 !self.min_width.is_nan()
543 && !self.max_width.is_nan()
544 && !self.min_height.is_nan()
545 && !self.max_height.is_nan(),
546 "BoxConstraints has a NaN value."
547 );
548 assert!(
549 self.min_width >= 0.0,
550 "BoxConstraints has a negative minimum width."
551 );
552 assert!(
553 self.min_height >= 0.0,
554 "BoxConstraints has a negative minimum height."
555 );
556 assert!(
557 self.max_width >= self.min_width,
558 "BoxConstraints has non-normalized width constraints."
559 );
560 assert!(
561 self.max_height >= self.min_height,
562 "BoxConstraints has non-normalized height constraints."
563 );
564 if is_applied_constraint {
565 assert!(
566 self.min_width.is_finite(),
567 "BoxConstraints forces an infinite width."
568 );
569 assert!(
570 self.min_height.is_finite(),
571 "BoxConstraints forces an infinite height."
572 );
573 }
574 debug_assert!(self.is_normalized());
575 }
576 self.is_normalized()
577 }
578}
579
580impl std::ops::Mul<f64> for BoxConstraints {
581 type Output = BoxConstraints;
582
583 fn mul(self, factor: f64) -> BoxConstraints {
584 BoxConstraints {
585 min_width: self.min_width * factor,
586 max_width: self.max_width * factor,
587 min_height: self.min_height * factor,
588 max_height: self.max_height * factor,
589 }
590 }
591}
592
593impl std::ops::Div<f64> for BoxConstraints {
594 type Output = BoxConstraints;
595
596 fn div(self, factor: f64) -> BoxConstraints {
597 BoxConstraints {
598 min_width: self.min_width / factor,
599 max_width: self.max_width / factor,
600 min_height: self.min_height / factor,
601 max_height: self.max_height / factor,
602 }
603 }
604}
605
606impl std::ops::Rem<f64> for BoxConstraints {
607 type Output = BoxConstraints;
608
609 fn rem(self, value: f64) -> BoxConstraints {
610 BoxConstraints {
611 min_width: self.min_width % value,
612 max_width: self.max_width % value,
613 min_height: self.min_height % value,
614 max_height: self.max_height % value,
615 }
616 }
617}
618
619impl PartialEq for BoxConstraints {
620 fn eq(&self, other: &BoxConstraints) -> bool {
621 debug_assert!(self.debug_assert_is_valid(false));
622 debug_assert!(other.debug_assert_is_valid(false));
623 self.min_width == other.min_width
624 && self.max_width == other.max_width
625 && self.min_height == other.min_height
626 && self.max_height == other.max_height
627 }
628}
629
630impl Eq for BoxConstraints {}
631
632impl Hash for BoxConstraints {
633 fn hash<H: Hasher>(&self, state: &mut H) {
634 debug_assert!(self.debug_assert_is_valid(false));
635 self.min_width.to_bits().hash(state);
636 self.max_width.to_bits().hash(state);
637 self.min_height.to_bits().hash(state);
638 self.max_height.to_bits().hash(state);
639 }
640}
641
642impl Display for BoxConstraints {
643 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644 let annotation = if self.is_normalized() {
645 ""
646 } else {
647 "; NOT NORMALIZED"
648 };
649 if self.min_width == f64::INFINITY && self.min_height == f64::INFINITY {
650 return write!(f, "BoxConstraints(biggest{annotation})");
651 }
652 if self.min_width == 0.0
653 && self.max_width == f64::INFINITY
654 && self.min_height == 0.0
655 && self.max_height == f64::INFINITY
656 {
657 return write!(f, "BoxConstraints(unconstrained{annotation})");
658 }
659 fn describe(min: f64, max: f64, dim: &str) -> String {
660 if min == max {
661 format!("{dim}={}", debug_format_double(Some(min)))
662 } else {
663 format!(
664 "{}<={dim}<={}",
665 debug_format_double(Some(min)),
666 debug_format_double(Some(max))
667 )
668 }
669 }
670 write!(
671 f,
672 "BoxConstraints({}, {}{annotation})",
673 describe(self.min_width, self.max_width, "w"),
674 describe(self.min_height, self.max_height, "h")
675 )
676 }
677}
678
679impl Debug for BoxConstraints {
680 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681 Display::fmt(self, f)
682 }
683}
684
685pub trait BoxConstraintsExtension: Any {
693 fn as_any(&self) -> &dyn Any;
695
696 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool;
700}
701
702#[derive(Clone)]
719pub struct AnyBoxConstraints {
720 constraints: BoxConstraints,
721 extension: Option<Rc<dyn BoxConstraintsExtension>>,
722}
723
724impl AnyBoxConstraints {
725 pub const fn new(constraints: BoxConstraints) -> AnyBoxConstraints {
727 AnyBoxConstraints {
728 constraints,
729 extension: None,
730 }
731 }
732
733 pub fn with_shared(
735 constraints: BoxConstraints,
736 extension: Rc<dyn BoxConstraintsExtension>,
737 ) -> AnyBoxConstraints {
738 AnyBoxConstraints {
739 constraints,
740 extension: Some(extension),
741 }
742 }
743
744 pub fn constraints(&self) -> BoxConstraints {
746 self.constraints
747 }
748
749 pub fn extension<T: BoxConstraintsExtension>(&self) -> Option<&T> {
751 self.extension
752 .as_ref()
753 .and_then(|extension| extension.as_any().downcast_ref::<T>())
754 }
755
756 pub fn has_extension(&self) -> bool {
758 self.extension.is_some()
759 }
760}
761
762impl Deref for AnyBoxConstraints {
763 type Target = BoxConstraints;
764
765 fn deref(&self) -> &BoxConstraints {
766 &self.constraints
767 }
768}
769
770impl From<BoxConstraints> for AnyBoxConstraints {
771 fn from(constraints: BoxConstraints) -> AnyBoxConstraints {
772 AnyBoxConstraints::new(constraints)
773 }
774}
775
776impl PartialEq for AnyBoxConstraints {
777 fn eq(&self, other: &AnyBoxConstraints) -> bool {
778 if self.constraints != other.constraints {
779 return false;
780 }
781 match (&self.extension, &other.extension) {
782 (None, None) => true,
783 (Some(mine), Some(theirs)) => mine.eq_extension(&**theirs),
784 _ => false,
785 }
786 }
787}
788
789impl PartialEq<BoxConstraints> for AnyBoxConstraints {
790 fn eq(&self, other: &BoxConstraints) -> bool {
791 self.extension.is_none() && self.constraints == *other
792 }
793}
794
795impl Debug for AnyBoxConstraints {
797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798 Debug::fmt(&self.constraints, f)
799 }
800}
801
802pub type BoxHitTest<'r> = dyn FnOnce(&mut BoxHitTestResult<'r>, Offset) -> bool;
807
808pub struct BoxHitTestResult<'a>(&'a mut HitTestResult);
813
814impl<'a> BoxHitTestResult<'a> {
815 pub fn wrap(result: &'a mut HitTestResult) -> BoxHitTestResult<'a> {
817 BoxHitTestResult(result)
818 }
819
820 pub fn add_with_paint_transform(
835 &mut self,
836 transform: Option<Matrix4>,
837 position: Offset,
838 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
839 ) -> bool {
840 let transform = match transform {
841 Some(transform) => match remove_perspective_transform(transform).invert() {
842 Some(inverted) => Some(inverted),
843 None => return false,
845 },
846 None => None,
847 };
848 self.add_with_raw_transform(transform, position, hit_test)
849 }
850
851 pub fn add_with_paint_offset(
856 &mut self,
857 offset: Option<Offset>,
858 position: Offset,
859 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
860 ) -> bool {
861 let transformed_position = match offset {
862 Some(offset) => position - offset,
863 None => position,
864 };
865 if let Some(offset) = offset {
866 self.0.push_offset(Offset::ZERO - offset);
867 }
868 let is_hit = hit_test(self, transformed_position);
869 if offset.is_some() {
870 self.0.pop_transform();
871 }
872 is_hit
873 }
874
875 pub fn add_with_raw_transform(
882 &mut self,
883 transform: Option<Matrix4>,
884 position: Offset,
885 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
886 ) -> bool {
887 let transformed_position = match transform {
888 Some(transform) => transform_point(&transform, position),
889 None => position,
890 };
891 if let Some(transform) = transform {
892 self.0.push_transform(transform);
893 }
894 let is_hit = hit_test(self, transformed_position);
895 if transform.is_some() {
896 self.0.pop_transform();
897 }
898 is_hit
899 }
900
901 pub fn add_with_out_of_band_position(
906 &mut self,
907 paint_offset: Option<Offset>,
908 paint_transform: Option<Matrix4>,
909 raw_transform: Option<Matrix4>,
910 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>) -> bool,
911 ) -> bool {
912 debug_assert_eq!(
913 [
914 paint_offset.is_some(),
915 paint_transform.is_some(),
916 raw_transform.is_some()
917 ]
918 .iter()
919 .filter(|given| **given)
920 .count(),
921 1,
922 "Exactly one transform or offset argument must be provided."
923 );
924 if let Some(paint_offset) = paint_offset {
925 self.0.push_offset(Offset::ZERO - paint_offset);
926 } else if let Some(raw_transform) = raw_transform {
927 self.0.push_transform(raw_transform);
928 } else {
929 let paint_transform = paint_transform
930 .expect("checked")
931 .invert()
932 .expect("paint_transform must be invertible.");
933 self.0.push_transform(paint_transform);
934 }
935 let is_hit = hit_test(self);
936 self.0.pop_transform();
937 is_hit
938 }
939}
940
941impl Deref for BoxHitTestResult<'_> {
942 type Target = HitTestResult;
943
944 fn deref(&self) -> &HitTestResult {
945 self.0
946 }
947}
948
949impl DerefMut for BoxHitTestResult<'_> {
950 fn deref_mut(&mut self) -> &mut HitTestResult {
951 self.0
952 }
953}
954
955#[derive(Clone, Copy, Debug)]
961pub struct BoxHitTestEntry {
962 target: AnyRenderBox,
963 local_position: Offset,
964}
965
966impl BoxHitTestEntry {
967 pub fn new(target: AnyRenderBox, local_position: Offset) -> BoxHitTestEntry {
969 BoxHitTestEntry {
970 target,
971 local_position,
972 }
973 }
974
975 pub fn target(&self) -> AnyRenderBox {
977 self.target
978 }
979
980 pub fn local_position(&self) -> Offset {
982 self.local_position
983 }
984}
985
986impl HitTestTarget for BoxHitTestEntry {
987 fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
988 self.target.handle_event(app, event, self);
989 }
990
991 fn arena_id(&self) -> Option<HandleId> {
992 Some(self.target.id)
993 }
994}
995
996impl From<BoxHitTestEntry> for HitTestEntry {
997 fn from(entry: BoxHitTestEntry) -> HitTestEntry {
998 HitTestEntry::new(entry)
999 }
1000}
1001
1002#[derive(Clone, Copy, Debug)]
1004pub struct BoxParentData {
1005 pub offset: Offset,
1007}
1008
1009impl BoxParentData {
1010 pub const fn new() -> BoxParentData {
1012 BoxParentData {
1013 offset: Offset::ZERO,
1014 }
1015 }
1016}
1017
1018impl Default for BoxParentData {
1019 fn default() -> BoxParentData {
1020 BoxParentData::new()
1021 }
1022}
1023
1024impl ParentData for BoxParentData {
1025 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1026 (id == TypeId::of::<BoxParentData>()).then_some(self)
1027 }
1028
1029 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1030 (id == TypeId::of::<BoxParentData>()).then_some(self)
1031 }
1032}
1033
1034impl fmt::Display for BoxParentData {
1035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 write!(f, "offset={}", self.offset)
1037 }
1038}
1039
1040pub trait ContainerBoxParentData: ContainerParentDataMixin<ChildType = AnyRenderBox> {
1046 fn box_parent_data(&self) -> &BoxParentData;
1051
1052 fn box_parent_data_mut(&mut self) -> &mut BoxParentData;
1054
1055 fn offset(&self) -> Offset {
1057 self.box_parent_data().offset
1058 }
1059
1060 fn set_offset(&mut self, value: Offset) {
1062 self.box_parent_data_mut().offset = value;
1063 }
1064}
1065
1066#[derive(Clone, Copy, PartialEq, Debug)]
1068pub struct BaselineOffset(pub Option<f64>);
1069
1070impl BaselineOffset {
1071 pub const NO_BASELINE: BaselineOffset = BaselineOffset(None);
1077
1078 pub fn offset(self) -> Option<f64> {
1080 self.0
1081 }
1082
1083 pub fn min_of(self, other: BaselineOffset) -> BaselineOffset {
1090 match (self.0, other.0) {
1091 (Some(lhs), Some(rhs)) => {
1092 if lhs >= rhs {
1093 other
1094 } else {
1095 self
1096 }
1097 }
1098 (Some(_), None) => self,
1099 (None, _) => other,
1100 }
1101 }
1102}
1103
1104impl Add<f64> for BaselineOffset {
1105 type Output = BaselineOffset;
1106
1107 fn add(self, offset: f64) -> BaselineOffset {
1110 BaselineOffset(self.0.map(|value| value + offset))
1111 }
1112}
1113
1114#[derive(Clone, Copy, Debug)]
1119pub enum DryLayoutFailure<'a> {
1120 Reason(&'a str),
1122
1123 Error(&'a str),
1125}
1126
1127#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1130enum IntrinsicDimension {
1131 MinWidth,
1132 MaxWidth,
1133 MinHeight,
1134 MaxHeight,
1135}
1136
1137#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1139struct DoubleKey(u64);
1140
1141impl DoubleKey {
1142 fn new(value: f64) -> DoubleKey {
1143 DoubleKey(value.to_bits())
1144 }
1145}
1146
1147#[derive(Default)]
1154struct LayoutCacheStorage {
1155 cached_intrinsic_dimensions: HashMap<(IntrinsicDimension, DoubleKey), f64>,
1156 cached_dry_layout_sizes: HashMap<BoxConstraints, Size>,
1157 cached_alphabetic_baseline: HashMap<BoxConstraints, BaselineOffset>,
1158 cached_ideo_baseline: HashMap<BoxConstraints, BaselineOffset>,
1159}
1160
1161impl LayoutCacheStorage {
1162 fn clear(&mut self) -> bool {
1164 let has_cache = !self.cached_dry_layout_sizes.is_empty()
1165 || !self.cached_intrinsic_dimensions.is_empty()
1166 || !self.cached_alphabetic_baseline.is_empty()
1167 || !self.cached_ideo_baseline.is_empty();
1168 if has_cache {
1169 self.cached_dry_layout_sizes.clear();
1170 self.cached_intrinsic_dimensions.clear();
1171 self.cached_alphabetic_baseline.clear();
1172 self.cached_ideo_baseline.clear();
1173 }
1174 has_cache
1175 }
1176
1177 fn baselines(
1178 &mut self,
1179 baseline: TextBaseline,
1180 ) -> &mut HashMap<BoxConstraints, BaselineOffset> {
1181 match baseline {
1182 TextBaseline::Alphabetic => &mut self.cached_alphabetic_baseline,
1183 TextBaseline::Ideographic => &mut self.cached_ideo_baseline,
1184 }
1185 }
1186}
1187
1188pub struct RenderBoxData {
1190 pub(crate) size: Option<Size>,
1191 pub(crate) constraints: Option<AnyBoxConstraints>,
1192 layout_cache: LayoutCacheStorage,
1193 debug_computing_this_dry_layout: bool,
1194 debug_computing_this_dry_baseline: bool,
1195}
1196
1197impl RenderBoxData {
1198 pub fn new() -> RenderBoxData {
1200 RenderBoxData {
1201 size: None,
1202 constraints: None,
1203 layout_cache: LayoutCacheStorage::default(),
1204 debug_computing_this_dry_layout: false,
1205 debug_computing_this_dry_baseline: false,
1206 }
1207 }
1208
1209 pub fn constraints(&self) -> Option<BoxConstraints> {
1212 self.constraints
1213 .as_ref()
1214 .map(AnyBoxConstraints::constraints)
1215 }
1216}
1217
1218impl Default for RenderBoxData {
1219 fn default() -> RenderBoxData {
1220 RenderBoxData::new()
1221 }
1222}
1223
1224#[macro_export]
1226macro_rules! render_box_accessors {
1227 () => {
1228 fn render_box_data(
1229 self: $crate::RenderHandle<Self>,
1230 app: &::waft_foundation::App,
1231 ) -> &$crate::RenderBoxData {
1232 &self.get(app).render_box
1233 }
1234 fn render_box_data_mut(
1235 self: $crate::RenderHandle<Self>,
1236 app: &mut ::waft_foundation::App,
1237 ) -> &mut $crate::RenderBoxData {
1238 &mut self.get_mut(app).render_box
1239 }
1240 };
1241}
1242
1243fn box_parent_data_of(app: &App, child: AnyRenderObject) -> &BoxParentData {
1249 child
1250 .parent_data(app)
1251 .and_then(|parent_data| parent_data.part::<BoxParentData>())
1252 .expect("parent data is not a BoxParentData")
1253}
1254
1255pub trait RenderBoxContainerDefaultsMixin:
1263 ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType: ContainerBoxParentData>
1264 + RenderBox
1265{
1266 fn default_compute_distance_to_first_actual_baseline(
1271 self: RenderHandle<Self>,
1272 app: &mut App,
1273 baseline: TextBaseline,
1274 ) -> Option<f64> {
1275 debug_assert!(!self.as_object().debug_needs_layout(app));
1276 let mut child = self.first_child(app);
1277 while let Some(current) = child {
1278 let child_parent_data = current
1279 .as_object()
1280 .parent_data_of::<Self::ParentDataType>(app);
1281 let (offset, next_sibling) =
1282 (child_parent_data.offset(), child_parent_data.next_sibling());
1283 if let Some(result) = current.get_distance_to_actual_baseline(app, baseline) {
1284 return Some(result + offset.dy());
1285 }
1286 child = next_sibling;
1287 }
1288 None
1289 }
1290
1291 fn default_compute_distance_to_highest_actual_baseline(
1296 self: RenderHandle<Self>,
1297 app: &mut App,
1298 baseline: TextBaseline,
1299 ) -> Option<f64> {
1300 debug_assert!(!self.as_object().debug_needs_layout(app));
1301 let mut min_baseline = BaselineOffset::NO_BASELINE;
1302 let mut child = self.first_child(app);
1303 while let Some(current) = child {
1304 let child_parent_data = current
1305 .as_object()
1306 .parent_data_of::<Self::ParentDataType>(app);
1307 let (offset, next_sibling) =
1308 (child_parent_data.offset(), child_parent_data.next_sibling());
1309 let candidate = BaselineOffset(current.get_distance_to_actual_baseline(app, baseline))
1310 + offset.dy();
1311 min_baseline = min_baseline.min_of(candidate);
1312 child = next_sibling;
1313 }
1314 min_baseline.offset()
1315 }
1316
1317 fn default_hit_test_children(
1327 self: RenderHandle<Self>,
1328 app: &mut App,
1329 result: &mut BoxHitTestResult<'_>,
1330 position: Offset,
1331 ) -> bool {
1332 let mut child = self.last_child(app);
1333 while let Some(current) = child {
1334 let child_parent_data = current
1336 .as_object()
1337 .parent_data_of::<Self::ParentDataType>(app);
1338 let (offset, previous_sibling) = (
1339 child_parent_data.offset(),
1340 child_parent_data.previous_sibling(),
1341 );
1342 let is_hit =
1343 result.add_with_paint_offset(Some(offset), position, |result, transformed| {
1344 debug_assert_eq!(transformed, position - offset);
1345 current.hit_test(app, result, transformed)
1346 });
1347 if is_hit {
1348 return true;
1349 }
1350 child = previous_sibling;
1351 }
1352 false
1353 }
1354
1355 fn default_paint(
1362 self: RenderHandle<Self>,
1363 app: &mut App,
1364 context: &mut PaintingContext,
1365 offset: Offset,
1366 ) {
1367 let mut child = self.first_child(app);
1368 while let Some(current) = child {
1369 let child_parent_data = current
1370 .as_object()
1371 .parent_data_of::<Self::ParentDataType>(app);
1372 let (child_offset, next_sibling) =
1373 (child_parent_data.offset(), child_parent_data.next_sibling());
1374 context.paint_child(app, current.as_object(), child_offset + offset);
1375 child = next_sibling;
1376 }
1377 }
1378}
1379
1380pub trait RenderBox: RenderObject {
1386 fn render_box_data(self: RenderHandle<Self>, app: &App) -> &RenderBoxData;
1388
1389 fn render_box_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderBoxData;
1391
1392 fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
1398 self.render_box_data(app)
1399 .constraints
1400 .as_ref()
1401 .map(AnyBoxConstraints::constraints)
1402 .unwrap_or_else(|| {
1403 panic!("A RenderObject does not have any constraints before it has been laid out.")
1404 })
1405 }
1406
1407 fn any_constraints(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
1415 self.render_box_data(app)
1416 .constraints
1417 .clone()
1418 .unwrap_or_else(|| {
1419 panic!("A RenderObject does not have any constraints before it has been laid out.")
1420 })
1421 }
1422
1423 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1427 if !child.parent_data_is::<BoxParentData>(app) {
1428 child.set_parent_data(app, BoxParentData::new());
1429 }
1430 }
1431
1432 fn get_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1434 self.as_box().get_min_intrinsic_width(app, height)
1435 }
1436
1437 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1482 let _ = (self, app, height);
1483 0.0
1484 }
1485
1486 fn get_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1488 self.as_box().get_max_intrinsic_width(app, height)
1489 }
1490
1491 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1512 let _ = (self, app, height);
1513 0.0
1514 }
1515
1516 fn get_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1518 self.as_box().get_min_intrinsic_height(app, width)
1519 }
1520
1521 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1538 let _ = (self, app, width);
1539 0.0
1540 }
1541
1542 fn get_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1544 self.as_box().get_max_intrinsic_height(app, width)
1545 }
1546
1547 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1564 let _ = (self, app, width);
1565 0.0
1566 }
1567
1568 fn get_dry_layout(
1570 self: RenderHandle<Self>,
1571 app: &mut App,
1572 constraints: BoxConstraints,
1573 ) -> Size {
1574 self.as_box().get_dry_layout(app, constraints)
1575 }
1576
1577 fn compute_dry_layout(
1602 self: RenderHandle<Self>,
1603 app: &mut App,
1604 constraints: BoxConstraints,
1605 ) -> Size {
1606 let _ = (app, constraints);
1607 self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1608 "It does not implement RenderBox::compute_dry_layout.",
1609 ));
1610 Size::ZERO
1611 }
1612
1613 fn get_dry_baseline(
1615 self: RenderHandle<Self>,
1616 app: &mut App,
1617 constraints: BoxConstraints,
1618 baseline: TextBaseline,
1619 ) -> Option<f64> {
1620 self.as_box().get_dry_baseline(app, constraints, baseline)
1621 }
1622
1623 fn compute_dry_baseline(
1647 self: RenderHandle<Self>,
1648 app: &mut App,
1649 constraints: BoxConstraints,
1650 baseline: TextBaseline,
1651 ) -> Option<f64> {
1652 let _ = (app, constraints, baseline);
1653 self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1654 "It does not implement RenderBox::compute_dry_baseline.",
1655 ));
1656 None
1657 }
1658
1659 fn debug_cannot_compute_dry_layout(self: RenderHandle<Self>, failure: DryLayoutFailure<'_>) {
1667 let _ = self;
1668 if !cfg!(debug_assertions) || debug_checking_intrinsics() {
1669 return;
1670 }
1671 match failure {
1672 DryLayoutFailure::Reason(reason) => panic!(
1673 "The {} class does not support dry layout. {reason}",
1674 std::any::type_name::<Self>()
1675 ),
1676 DryLayoutFailure::Error(error) => panic!("{error}"),
1677 }
1678 }
1679
1680 fn get_distance_to_baseline(
1682 self: RenderHandle<Self>,
1683 app: &mut App,
1684 baseline: TextBaseline,
1685 only_real: bool,
1686 ) -> Option<f64> {
1687 self.as_box()
1688 .get_distance_to_baseline(app, baseline, only_real)
1689 }
1690
1691 fn get_distance_to_actual_baseline(
1693 self: RenderHandle<Self>,
1694 app: &mut App,
1695 baseline: TextBaseline,
1696 ) -> Option<f64> {
1697 self.as_box().get_distance_to_actual_baseline(app, baseline)
1698 }
1699
1700 fn compute_distance_to_actual_baseline(
1720 self: RenderHandle<Self>,
1721 app: &mut App,
1722 baseline: TextBaseline,
1723 ) -> Option<f64> {
1724 let _ = (self, app, baseline);
1725 debug_assert!(
1726 DEBUG_DOING_BASELINE.get(),
1727 "Please see the documentation for compute_distance_to_actual_baseline for the \
1728 required calling conventions of this method."
1729 );
1730 None
1731 }
1732
1733 fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1739 RenderBoxBase::mark_needs_layout(self, app);
1740 }
1741
1742 fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1749 RenderBoxBase::perform_resize(self, app);
1750 }
1751
1752 fn size(self: RenderHandle<Self>, app: &App) -> Size {
1754 self.as_box().size(app)
1755 }
1756
1757 fn apply_paint_transform(
1767 self: RenderHandle<Self>,
1768 app: &App,
1769 child: AnyRenderObject,
1770 transform: &mut Matrix4,
1771 ) {
1772 debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
1773 let offset = box_parent_data_of(app, child).offset;
1776 crate::object::translate(transform, offset.dx(), offset.dy());
1777 }
1778
1779 fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
1781 Offset::ZERO & self.size(app)
1782 }
1783
1784 fn has_size(self: RenderHandle<Self>, app: &App) -> bool {
1786 self.render_box_data(app).size.is_some()
1787 }
1788
1789 fn handle_event(
1795 self: RenderHandle<Self>,
1796 app: &mut App,
1797 event: &PointerEvent,
1798 entry: &BoxHitTestEntry,
1799 ) {
1800 let _ = (self, app, event, entry);
1801 }
1802
1803 fn hit_test(
1818 self: RenderHandle<Self>,
1819 app: &mut App,
1820 result: &mut BoxHitTestResult<'_>,
1821 position: Offset,
1822 ) -> bool {
1823 RenderBoxBase::hit_test(self, app, result, position)
1824 }
1825
1826 fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1831 let _ = self;
1832 false
1833 }
1834
1835 fn hit_test_children(
1840 self: RenderHandle<Self>,
1841 app: &mut App,
1842 result: &mut BoxHitTestResult<'_>,
1843 position: Offset,
1844 ) -> bool {
1845 let _ = (self, app, result, position);
1846 false
1847 }
1848
1849 fn set_size(self: RenderHandle<Self>, app: &mut App, size: Size) {
1852 self.as_box().set_size(app, size)
1853 }
1854
1855 fn layout(
1857 self: RenderHandle<Self>,
1858 app: &mut App,
1859 constraints: impl Into<AnyBoxConstraints>,
1860 parent_uses_size: bool,
1861 ) {
1862 self.as_box().layout(app, constraints, parent_uses_size)
1863 }
1864
1865 fn as_box(self: RenderHandle<Self>) -> AnyRenderBox {
1867 AnyRenderBox {
1868 id: self.id(),
1869 vtable: const { &RenderBoxVTable::of::<Self>() },
1870 }
1871 }
1872
1873 fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
1875 self.as_box().as_object()
1876 }
1877
1878 fn adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1880 self.as_object().adopt_child(app, child)
1881 }
1882
1883 fn drop_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1885 self.as_object().drop_child(app, child)
1886 }
1887
1888 fn mark_needs_paint(self: RenderHandle<Self>, app: &mut App) {
1890 self.as_object().mark_needs_paint(app)
1891 }
1892
1893 fn mark_needs_composited_layer_update(self: RenderHandle<Self>, app: &mut App) {
1895 self.as_object().mark_needs_composited_layer_update(app)
1896 }
1897
1898 fn mark_needs_compositing_bits_update(self: RenderHandle<Self>, app: &mut App) {
1900 self.as_object().mark_needs_compositing_bits_update(app)
1901 }
1902
1903 fn schedule_initial_layout(self: RenderHandle<Self>, app: &mut App) {
1905 self.as_object().schedule_initial_layout(app)
1906 }
1907
1908 fn parent(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderObject> {
1910 self.as_object().parent(app)
1911 }
1912
1913 fn owner(self: RenderHandle<Self>, app: &App) -> Option<Handle<PipelineOwner>> {
1915 self.as_object().owner(app)
1916 }
1917
1918 fn attached(self: RenderHandle<Self>, app: &App) -> bool {
1920 self.as_object().attached(app)
1921 }
1922
1923 fn debug_needs_layout(self: RenderHandle<Self>, app: &App) -> bool {
1925 self.as_object().debug_needs_layout(app)
1926 }
1927}
1928
1929pub trait RenderBoxBase: RenderBox {
1936 fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1938 if self.render_box_data_mut(app).layout_cache.clear() && self.parent(app).is_some() {
1951 self.as_object().mark_parent_needs_layout(app);
1952 return;
1953 }
1954 crate::object::RenderObjectBase::mark_needs_layout(self, app);
1955 }
1956
1957 fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1959 let constraints = RenderBox::constraints(self, app);
1961 let size = RenderBox::compute_dry_layout(self, app, constraints);
1962 debug_assert!(size.width().is_finite() && size.height().is_finite());
1963 self.set_size(app, size);
1964 }
1965
1966 fn hit_test(
1968 self: RenderHandle<Self>,
1969 app: &mut App,
1970 result: &mut BoxHitTestResult<'_>,
1971 position: Offset,
1972 ) -> bool {
1973 debug_assert!(
1974 self.has_size(app),
1975 "Cannot hit test a render box that has never been laid out: {self:?}"
1976 );
1977 if self.size(app).contains(position)
1978 && (RenderBox::hit_test_children(self, app, result, position)
1979 || RenderBox::hit_test_self(self, app, position))
1980 {
1981 result.add(BoxHitTestEntry::new(self.as_box(), position).into());
1982 return true;
1983 }
1984 false
1985 }
1986}
1987
1988impl<T: RenderBox> RenderBoxBase for T {}
1989
1990pub(crate) struct RenderBoxVTable {
1992 pub object: RenderObjectVTable,
1993 pub box_data: fn(&App, HandleId) -> &RenderBoxData,
1994 pub box_data_mut: fn(&mut App, HandleId) -> &mut RenderBoxData,
1995 pub hit_test: fn(&mut App, HandleId, &mut BoxHitTestResult<'_>, Offset) -> bool,
1996 pub handle_event: fn(&mut App, HandleId, &PointerEvent, &BoxHitTestEntry),
1997 pub compute_min_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1998 pub compute_max_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1999 pub compute_min_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
2000 pub compute_max_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
2001 pub compute_dry_layout: fn(&mut App, HandleId, BoxConstraints) -> Size,
2002 pub compute_dry_baseline: fn(&mut App, HandleId, BoxConstraints, TextBaseline) -> Option<f64>,
2003 pub compute_distance_to_actual_baseline: fn(&mut App, HandleId, TextBaseline) -> Option<f64>,
2004}
2005
2006impl RenderBoxVTable {
2007 const fn of<T: RenderBox>() -> RenderBoxVTable {
2008 RenderBoxVTable {
2009 object: RenderObjectVTable::of::<T>(
2010 |app, id, child| <T as RenderBox>::setup_parent_data(resolve(id), app, child),
2011 |app, id| T::paint_bounds(resolve(id), app),
2012 |app, id, child, transform| {
2013 <T as RenderBox>::apply_paint_transform(resolve(id), app, child, transform)
2014 },
2015 |app, id| <T as RenderBox>::perform_resize(resolve(id), app),
2016 |app, id| <T as RenderBox>::mark_needs_layout(resolve(id), app),
2017 Some(|| const { &RenderBoxVTable::of::<T>() }),
2018 None,
2019 ),
2020 box_data: |app, id| T::render_box_data(resolve(id), app),
2021 box_data_mut: |app, id| T::render_box_data_mut(resolve(id), app),
2022 hit_test: |app, id, result, position| T::hit_test(resolve(id), app, result, position),
2023 handle_event: |app, id, event, entry| T::handle_event(resolve(id), app, event, entry),
2024 compute_min_intrinsic_width: |app, id, height| {
2025 T::compute_min_intrinsic_width(resolve(id), app, height)
2026 },
2027 compute_max_intrinsic_width: |app, id, height| {
2028 T::compute_max_intrinsic_width(resolve(id), app, height)
2029 },
2030 compute_min_intrinsic_height: |app, id, width| {
2031 T::compute_min_intrinsic_height(resolve(id), app, width)
2032 },
2033 compute_max_intrinsic_height: |app, id, width| {
2034 T::compute_max_intrinsic_height(resolve(id), app, width)
2035 },
2036 compute_dry_layout: |app, id, constraints| {
2037 T::compute_dry_layout(resolve(id), app, constraints)
2038 },
2039 compute_dry_baseline: |app, id, constraints, baseline| {
2040 T::compute_dry_baseline(resolve(id), app, constraints, baseline)
2041 },
2042 compute_distance_to_actual_baseline: |app, id, baseline| {
2043 T::compute_distance_to_actual_baseline(resolve(id), app, baseline)
2044 },
2045 }
2046 }
2047}
2048
2049impl<T: RenderBox> RenderHandle<T> {
2050 pub fn new_box(app: &mut App, object: T) -> RenderHandle<T> {
2052 let this = create(app, object);
2053 let data = this.render_object_data_mut(app);
2054 data.object_vtable = Some(&const { RenderBoxVTable::of::<T>() }.object);
2055 let is_repaint_boundary = this.is_repaint_boundary(app);
2059 let always_needs_compositing = this.always_needs_compositing(app);
2060 let data = this.render_object_data_mut(app);
2061 data.was_repaint_boundary = is_repaint_boundary;
2062 data.needs_compositing = is_repaint_boundary || always_needs_compositing;
2063 this
2064 }
2065}
2066
2067struct DebugDoingBaseline;
2069
2070impl DebugDoingBaseline {
2071 fn enter() -> DebugDoingBaseline {
2072 DEBUG_DOING_BASELINE.set(cfg!(debug_assertions));
2073 DebugDoingBaseline
2074 }
2075}
2076
2077impl Drop for DebugDoingBaseline {
2078 fn drop(&mut self) {
2079 DEBUG_DOING_BASELINE.set(false);
2080 }
2081}
2082
2083fn should_cache_intrinsics(this: AnyRenderBox, app: &App) -> bool {
2085 debug_assert!(debug_checking_intrinsics() || !this.as_object().debug_doing_this_resize(app));
2087 !cfg!(debug_assertions) || !debug_checking_intrinsics()
2089}
2090
2091fn memoize_intrinsic(
2093 this: AnyRenderBox,
2094 app: &mut App,
2095 dimension: IntrinsicDimension,
2096 input: f64,
2097 computer: fn(&mut App, HandleId, f64) -> f64,
2098) -> f64 {
2099 if !should_cache_intrinsics(this, app) {
2100 return computer(app, this.id, input);
2101 }
2102 let key = (dimension, DoubleKey::new(input));
2103 if let Some(cached) = this.layout_cache(app).cached_intrinsic_dimensions.get(&key) {
2104 return *cached;
2105 }
2106 let result = computer(app, this.id, input);
2107 this.layout_cache_mut(app)
2108 .cached_intrinsic_dimensions
2109 .insert(key, result);
2110 result
2111}
2112
2113fn memoize_baseline(
2115 this: AnyRenderBox,
2116 app: &mut App,
2117 constraints: BoxConstraints,
2118 baseline: TextBaseline,
2119 computer: impl FnOnce(AnyRenderBox, &mut App) -> BaselineOffset,
2120) -> BaselineOffset {
2121 if !should_cache_intrinsics(this, app) {
2122 return computer(this, app);
2123 }
2124 if let Some(cached) = this
2125 .layout_cache_mut(app)
2126 .baselines(baseline)
2127 .get(&constraints)
2128 {
2129 return *cached;
2130 }
2131 let result = computer(this, app);
2132 this.layout_cache_mut(app)
2133 .baselines(baseline)
2134 .insert(constraints, result);
2135 result
2136}
2137
2138#[derive(Clone, Copy)]
2140pub struct AnyRenderBox {
2141 id: HandleId,
2142 vtable: &'static RenderBoxVTable,
2143}
2144
2145impl PartialEq for AnyRenderBox {
2146 fn eq(&self, other: &AnyRenderBox) -> bool {
2147 self.id == other.id
2148 }
2149}
2150
2151impl Eq for AnyRenderBox {}
2152
2153impl std::hash::Hash for AnyRenderBox {
2154 fn hash<H: Hasher>(&self, state: &mut H) {
2155 self.id.hash(state);
2156 }
2157}
2158
2159impl Debug for AnyRenderBox {
2160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2161 write!(f, "AnyRenderBox({:?})", self.id)
2162 }
2163}
2164
2165impl AnyRenderBox {
2166 pub(crate) fn from_vtable(id: HandleId, vtable: &'static RenderBoxVTable) -> AnyRenderBox {
2167 AnyRenderBox { id, vtable }
2168 }
2169
2170 pub fn has_size(self, app: &App) -> bool {
2173 self.box_data(app).size.is_some()
2174 }
2175
2176 pub fn as_object(self) -> AnyRenderObject {
2177 AnyRenderObject::from_vtable(self.id, &self.vtable.object)
2178 }
2179
2180 pub fn hit_test(
2182 self,
2183 app: &mut App,
2184 result: &mut BoxHitTestResult<'_>,
2185 position: Offset,
2186 ) -> bool {
2187 (self.vtable.hit_test)(app, self.id, result, position)
2188 }
2189
2190 pub fn handle_event(self, app: &mut App, event: &PointerEvent, entry: &BoxHitTestEntry) {
2192 (self.vtable.handle_event)(app, self.id, event, entry)
2193 }
2194
2195 pub(crate) fn box_data(self, app: &App) -> &RenderBoxData {
2196 (self.vtable.box_data)(app, self.id)
2197 }
2198
2199 fn box_data_mut(self, app: &mut App) -> &mut RenderBoxData {
2200 (self.vtable.box_data_mut)(app, self.id)
2201 }
2202
2203 pub fn layout(
2209 self,
2210 app: &mut App,
2211 constraints: impl Into<AnyBoxConstraints>,
2212 parent_uses_size: bool,
2213 ) {
2214 let constraints: AnyBoxConstraints = constraints.into();
2215 debug_assert!(
2216 !app.is_disposed(self.id),
2217 "layout on a disposed render object"
2218 );
2219 debug_assert!(constraints.debug_assert_is_valid(true));
2220 let same = self.box_data(app).constraints.as_ref() == Some(&constraints);
2221 let tight = constraints.is_tight();
2222 self.as_object()
2223 .run_layout(app, parent_uses_size, tight, same, |app| {
2224 self.box_data_mut(app).constraints = Some(constraints)
2225 });
2226 }
2227
2228 pub fn size(self, app: &App) -> Size {
2234 self.box_data(app)
2235 .size
2236 .unwrap_or_else(|| panic!("RenderBox was not laid out: {self:?}"))
2237 }
2238
2239 pub fn set_size(self, app: &mut App, size: Size) {
2241 self.box_data_mut(app).size = Some(size);
2242 }
2243
2244 pub fn constraints(self, app: &App) -> BoxConstraints {
2250 self.box_data(app)
2251 .constraints
2252 .as_ref()
2253 .map(AnyBoxConstraints::constraints)
2254 .unwrap_or_else(|| {
2255 panic!("A RenderObject does not have any constraints before it has been laid out.")
2256 })
2257 }
2258
2259 pub fn any_constraints(self, app: &App) -> AnyBoxConstraints {
2261 self.box_data(app).constraints.clone().unwrap_or_else(|| {
2262 panic!("A RenderObject does not have any constraints before it has been laid out.")
2263 })
2264 }
2265
2266 pub fn get_min_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2282 debug_assert!(
2283 height >= 0.0,
2284 "The height argument to get_min_intrinsic_width was negative. If you perform \
2285 computations on another height before passing it to get_min_intrinsic_width, \
2286 consider using f64::max or clamp_double to force the value into the valid range."
2287 );
2288 memoize_intrinsic(
2289 self,
2290 app,
2291 IntrinsicDimension::MinWidth,
2292 height,
2293 self.vtable.compute_min_intrinsic_width,
2294 )
2295 }
2296
2297 pub fn get_max_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2304 debug_assert!(
2305 height >= 0.0,
2306 "The height argument to get_max_intrinsic_width was negative."
2307 );
2308 memoize_intrinsic(
2309 self,
2310 app,
2311 IntrinsicDimension::MaxWidth,
2312 height,
2313 self.vtable.compute_max_intrinsic_width,
2314 )
2315 }
2316
2317 pub fn get_min_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2323 debug_assert!(
2324 width >= 0.0,
2325 "The width argument to get_min_intrinsic_height was negative."
2326 );
2327 memoize_intrinsic(
2328 self,
2329 app,
2330 IntrinsicDimension::MinHeight,
2331 width,
2332 self.vtable.compute_min_intrinsic_height,
2333 )
2334 }
2335
2336 pub fn get_max_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2343 debug_assert!(
2344 width >= 0.0,
2345 "The width argument to get_max_intrinsic_height was negative."
2346 );
2347 memoize_intrinsic(
2348 self,
2349 app,
2350 IntrinsicDimension::MaxHeight,
2351 width,
2352 self.vtable.compute_max_intrinsic_height,
2353 )
2354 }
2355
2356 pub fn get_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2374 if !should_cache_intrinsics(self, app) {
2375 return self.compute_dry_layout(app, constraints);
2376 }
2377 if let Some(cached) = self
2378 .layout_cache(app)
2379 .cached_dry_layout_sizes
2380 .get(&constraints)
2381 {
2382 return *cached;
2383 }
2384 let result = self.compute_dry_layout(app, constraints);
2385 self.layout_cache_mut(app)
2386 .cached_dry_layout_sizes
2387 .insert(constraints, result);
2388 result
2389 }
2390
2391 fn compute_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2393 if cfg!(debug_assertions) {
2394 assert!(!self.box_data(app).debug_computing_this_dry_layout);
2395 self.box_data_mut(app).debug_computing_this_dry_layout = true;
2396 }
2397 let result = (self.vtable.compute_dry_layout)(app, self.id, constraints);
2398 if cfg!(debug_assertions) {
2399 self.box_data_mut(app).debug_computing_this_dry_layout = false;
2400 }
2401 result
2402 }
2403
2404 pub fn get_dry_baseline(
2420 self,
2421 app: &mut App,
2422 constraints: BoxConstraints,
2423 baseline: TextBaseline,
2424 ) -> Option<f64> {
2425 let baseline_offset = memoize_baseline(self, app, constraints, baseline, |this, app| {
2426 this.compute_dry_baseline(app, constraints, baseline)
2427 })
2428 .offset();
2429 if cfg!(debug_assertions) && !debug_checking_intrinsics() {
2434 assert_eq!(
2435 baseline_offset,
2436 (self.vtable.compute_dry_baseline)(app, self.id, constraints, baseline)
2437 );
2438 }
2439 baseline_offset
2440 }
2441
2442 fn compute_dry_baseline(
2444 self,
2445 app: &mut App,
2446 constraints: BoxConstraints,
2447 baseline: TextBaseline,
2448 ) -> BaselineOffset {
2449 if cfg!(debug_assertions) {
2450 assert!(!self.box_data(app).debug_computing_this_dry_baseline);
2451 self.box_data_mut(app).debug_computing_this_dry_baseline = true;
2452 }
2453 let result = BaselineOffset((self.vtable.compute_dry_baseline)(
2454 app,
2455 self.id,
2456 constraints,
2457 baseline,
2458 ));
2459 if cfg!(debug_assertions) {
2460 self.box_data_mut(app).debug_computing_this_dry_baseline = false;
2461 }
2462 result
2463 }
2464
2465 pub fn get_distance_to_baseline(
2481 self,
2482 app: &mut App,
2483 baseline: TextBaseline,
2484 only_real: bool,
2485 ) -> Option<f64> {
2486 debug_assert!(
2487 !DEBUG_DOING_BASELINE.get(),
2488 "Please see the documentation for compute_distance_to_actual_baseline for the \
2489 required calling conventions of this method."
2490 );
2491 debug_assert!(!self.as_object().debug_needs_layout(app) || debug_checking_intrinsics());
2492 let result = {
2493 let _doing_baseline = DebugDoingBaseline::enter();
2494 self.get_distance_to_actual_baseline(app, baseline)
2495 };
2496 match result {
2497 None if !only_real => Some(self.size(app).height()),
2498 result => result,
2499 }
2500 }
2501
2502 pub fn get_distance_to_actual_baseline(
2508 self,
2509 app: &mut App,
2510 baseline: TextBaseline,
2511 ) -> Option<f64> {
2512 debug_assert!(
2513 DEBUG_DOING_BASELINE.get() || !cfg!(debug_assertions),
2514 "Please see the documentation for compute_distance_to_actual_baseline for the \
2515 required calling conventions of this method."
2516 );
2517 let constraints = self
2518 .box_data(app)
2519 .constraints
2520 .as_ref()
2521 .map(AnyBoxConstraints::constraints)
2522 .expect("a RenderBox has constraints once it has been laid out");
2523 memoize_baseline(self, app, constraints, baseline, |this, app| {
2524 BaselineOffset((this.vtable.compute_distance_to_actual_baseline)(
2525 app, this.id, baseline,
2526 ))
2527 })
2528 .offset()
2529 }
2530
2531 fn layout_cache(self, app: &App) -> &LayoutCacheStorage {
2532 &self.box_data(app).layout_cache
2533 }
2534
2535 fn layout_cache_mut(self, app: &mut App) -> &mut LayoutCacheStorage {
2536 &mut self.box_data_mut(app).layout_cache
2537 }
2538
2539 pub fn box_parent_data(self, app: &App) -> &BoxParentData {
2544 box_parent_data_of(app, self.as_object())
2545 }
2546
2547 pub fn global_to_local(
2562 self,
2563 app: &App,
2564 point: Offset,
2565 ancestor: Option<AnyRenderObject>,
2566 ) -> Offset {
2567 let transform = self.as_object().get_transform_to(app, ancestor);
2582 let Some(transform) = transform.invert() else {
2583 return Offset::ZERO;
2584 };
2585
2586 let n = [0.0, 0.0, 1.0];
2589 let i = crate::object::perspective_transform(&transform, [0.0, 0.0, 0.0]);
2590 let d = subtract(
2591 crate::object::perspective_transform(&transform, [0.0, 0.0, 1.0]),
2592 i,
2593 );
2594 let s = crate::object::perspective_transform(&transform, [point.dx(), point.dy(), 0.0]);
2595 let p = subtract(s, scale(d, dot(n, s) / dot(n, d)));
2597 Offset::new(p[0], p[1])
2598 }
2599
2600 pub fn local_to_global(
2611 self,
2612 app: &App,
2613 point: Offset,
2614 ancestor: Option<AnyRenderObject>,
2615 ) -> Offset {
2616 waft_painting::transform_point(&self.as_object().get_transform_to(app, ancestor), point)
2617 }
2618
2619 pub fn parent_data_of_mut<P: crate::object::ParentData + 'static>(
2621 self,
2622 app: &mut App,
2623 ) -> &mut P {
2624 self.as_object().parent_data_of_mut(app)
2625 }
2626
2627 pub fn parent_data_is<P: crate::object::ParentData + 'static>(self, app: &App) -> bool {
2629 self.as_object().parent_data_is::<P>(app)
2630 }
2631}
2632
2633impl crate::object::ErasedRenderObject for AnyRenderBox {
2634 fn as_object(self) -> AnyRenderObject {
2635 AnyRenderBox::as_object(self)
2636 }
2637
2638 fn from_object(object: AnyRenderObject) -> AnyRenderBox {
2639 object
2640 .as_box()
2641 .expect("the render object is not a RenderBox")
2642 }
2643}
2644
2645impl From<AnyRenderBox> for AnyRenderObject {
2646 fn from(box_: AnyRenderBox) -> AnyRenderObject {
2647 box_.as_object()
2648 }
2649}
2650
2651fn subtract(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
2652 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
2653}
2654
2655fn scale(a: [f64; 3], factor: f64) -> [f64; 3] {
2656 [a[0] * factor, a[1] * factor, a[2] * factor]
2657}
2658
2659fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
2660 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
2661}
2662
2663#[cfg(test)]
2664mod tests {
2665 use super::*;
2666
2667 #[test]
2668 fn to_string_marks_biggest_unconstrained_and_tight() {
2669 assert!(
2670 BoxConstraints::expand(None, None)
2671 .to_string()
2672 .contains("biggest")
2673 );
2674 assert!(BoxConstraints::new().to_string().contains("unconstrained"));
2675 assert!(
2676 BoxConstraints::tight_for(Some(50.0), None)
2677 .to_string()
2678 .contains("w=50")
2679 );
2680 }
2681
2682 #[test]
2683 fn copy_with_replaces_fields() {
2684 let constraints = BoxConstraints::new()
2685 .min_width(3.0)
2686 .max_width(7.0)
2687 .min_height(11.0)
2688 .max_height(17.0);
2689 let copy = constraints.copy_with();
2690 assert_eq!(copy, constraints);
2691 let copy = constraints
2692 .copy_with()
2693 .min_width(13.0)
2694 .max_width(17.0)
2695 .min_height(111.0)
2696 .max_height(117.0);
2697 assert_eq!(copy.min_width, 13.0);
2698 assert_eq!(copy.max_width, 17.0);
2699 assert_eq!(copy.min_height, 111.0);
2700 assert_eq!(copy.max_height, 117.0);
2701 assert_ne!(copy, constraints);
2702 let mut copy_hasher = std::collections::hash_map::DefaultHasher::new();
2703 let mut original_hasher = std::collections::hash_map::DefaultHasher::new();
2704 copy.hash(&mut copy_hasher);
2705 constraints.hash(&mut original_hasher);
2706 assert_ne!(copy_hasher.finish(), original_hasher.finish());
2707 }
2708
2709 #[test]
2710 fn operators() {
2711 let constraints = BoxConstraints::new()
2712 .min_width(3.0)
2713 .max_width(7.0)
2714 .min_height(11.0)
2715 .max_height(17.0);
2716 let copy = constraints * 2.0;
2717 assert_eq!(copy.min_width, 6.0);
2718 assert_eq!(copy.max_width, 14.0);
2719 assert_eq!(copy.min_height, 22.0);
2720 assert_eq!(copy.max_height, 34.0);
2721 assert_eq!(copy / 2.0, constraints);
2722 let copy = constraints.truncating_div(2.0);
2723 assert_eq!(copy.min_width, 1.0);
2724 assert_eq!(copy.max_width, 3.0);
2725 assert_eq!(copy.min_height, 5.0);
2726 assert_eq!(copy.max_height, 8.0);
2727 let copy = constraints % 3.0;
2728 assert_eq!(copy.min_width, 0.0);
2729 assert_eq!(copy.max_width, 1.0);
2730 assert_eq!(copy.min_height, 2.0);
2731 assert_eq!(copy.max_height, 2.0);
2732 }
2733
2734 #[test]
2735 fn lerp_from_null_and_between() {
2736 assert!(BoxConstraints::lerp(None, None, 0.5).is_none());
2737 let constraints = BoxConstraints::new()
2738 .min_width(3.0)
2739 .max_width(7.0)
2740 .min_height(11.0)
2741 .max_height(17.0);
2742 let copy = BoxConstraints::lerp(None, Some(constraints), 0.5).unwrap();
2743 assert!((copy.min_width - 1.5).abs() < 1e-9);
2744 assert!((copy.max_width - 3.5).abs() < 1e-9);
2745 assert!((copy.min_height - 5.5).abs() < 1e-9);
2746 assert!((copy.max_height - 8.5).abs() < 1e-9);
2747 let copy = BoxConstraints::lerp(Some(constraints), None, 0.5).unwrap();
2748 assert!((copy.min_width - 1.5).abs() < 1e-9);
2749 let copy = BoxConstraints::lerp(
2750 Some(
2751 BoxConstraints::new()
2752 .min_width(13.0)
2753 .max_width(17.0)
2754 .min_height(111.0)
2755 .max_height(117.0),
2756 ),
2757 Some(constraints),
2758 0.2,
2759 )
2760 .unwrap();
2761 assert!((copy.min_width - 11.0).abs() < 1e-9);
2762 assert!((copy.max_width - 15.0).abs() < 1e-9);
2763 assert!((copy.min_height - 91.0).abs() < 1e-9);
2764 assert!((copy.max_height - 97.0).abs() < 1e-9);
2765 }
2766
2767 #[test]
2768 fn lerp_unbounded_axes() {
2769 let constraints1 = BoxConstraints::new()
2770 .min_width(f64::INFINITY)
2771 .min_height(10.0)
2772 .max_height(20.0);
2773 let constraints2 = BoxConstraints::new()
2774 .min_width(f64::INFINITY)
2775 .min_height(20.0)
2776 .max_height(30.0);
2777 let constraints3 = BoxConstraints::new()
2778 .min_width(f64::INFINITY)
2779 .min_height(15.0)
2780 .max_height(25.0);
2781 assert_eq!(
2782 BoxConstraints::lerp(Some(constraints1), Some(constraints2), 0.5),
2783 Some(constraints3)
2784 );
2785 }
2786
2787 #[test]
2788 fn lerp_overshoot_is_normalized() {
2789 assert_eq!(
2790 BoxConstraints::lerp(
2791 Some(BoxConstraints::tight_for(None, Some(25.0))),
2792 Some(BoxConstraints::tight_for(None, Some(0.0))),
2793 1.2,
2794 ),
2795 Some(BoxConstraints::tight_for(None, Some(0.0)))
2796 );
2797 let lerped = BoxConstraints::lerp(
2798 Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
2799 Some(BoxConstraints::new().max_width(100.0).max_height(100.0)),
2800 -0.1,
2801 )
2802 .unwrap();
2803 assert!(lerped.is_normalized());
2804 assert_eq!(lerped, BoxConstraints::tight(Size::new(11.0, 11.0)));
2805 }
2806
2807 #[test]
2808 fn normalize_raises_inverted_max() {
2809 let constraints = BoxConstraints::new()
2810 .min_width(3.0)
2811 .max_width(2.0)
2812 .min_height(11.0)
2813 .max_height(18.0);
2814 let copy = constraints.normalize();
2815 assert_eq!(copy.min_width, 3.0);
2816 assert_eq!(copy.max_width, 3.0);
2817 assert_eq!(copy.min_height, 11.0);
2818 assert_eq!(copy.max_height, 18.0);
2819 }
2820
2821 #[test]
2822 fn from_view_constraints() {
2823 let unconstrained = BoxConstraints::from_view_constraints(ViewConstraints::default());
2824 assert_eq!(unconstrained, BoxConstraints::new());
2825 let constraints =
2826 BoxConstraints::from_view_constraints(ViewConstraints::new(1.0, 2.0, 3.0, 4.0));
2827 assert_eq!(
2828 constraints,
2829 BoxConstraints::new()
2830 .min_width(1.0)
2831 .max_width(2.0)
2832 .min_height(3.0)
2833 .max_height(4.0)
2834 );
2835 }
2836
2837 #[test]
2838 fn constrain_size_and_attempt_to_preserve_aspect_ratio_empty_size() {
2839 let constraints = BoxConstraints::new()
2840 .min_width(10.0)
2841 .max_width(20.0)
2842 .min_height(10.0)
2843 .max_height(20.0);
2844 let constrained =
2845 constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(Size::new(15.0, 0.0));
2846 assert_eq!(constrained, Size::new(15.0, 10.0));
2847 }
2848}
2849
2850#[cfg(test)]
2851mod hit_test_tests {
2852 use waft_painting::force_to_point;
2853
2854 use super::*;
2855
2856 #[derive(Debug)]
2857 struct DummyHitTestTarget;
2858
2859 impl HitTestTarget for DummyHitTestTarget {
2860 fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
2861 }
2862
2863 #[test]
2865 fn wrapping_shares_the_path() {
2866 let transform = Matrix4::translation(40.0, 150.0);
2867 let mut wrapped = HitTestResult::new();
2868 wrapped.push_transform(transform);
2869 wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2870 assert_eq!(wrapped.path().len(), 1);
2871 assert_eq!(wrapped.path()[0].transform(), Some(transform));
2872
2873 let mut wrapping = BoxHitTestResult::wrap(&mut wrapped);
2874 wrapping.add(HitTestEntry::new(DummyHitTestTarget));
2875 assert_eq!(wrapping.path().len(), 2);
2876 assert_eq!(wrapping.path()[1].transform(), Some(transform));
2877
2878 wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2879 assert_eq!(wrapped.path().len(), 3);
2880 assert_eq!(wrapped.path()[2].transform(), Some(transform));
2881 }
2882
2883 #[test]
2885 fn add_with_paint_transform() {
2886 let mut base = HitTestResult::new();
2887 let mut result = BoxHitTestResult::wrap(&mut base);
2888 let mut positions = Vec::new();
2889
2890 let is_hit = result.add_with_paint_transform(None, Offset::ZERO, |_, position| {
2891 positions.push(position);
2892 true
2893 });
2894 assert!(is_hit);
2895 assert_eq!(positions, [Offset::ZERO]);
2896 positions.clear();
2897
2898 let is_hit = result.add_with_paint_transform(
2899 Some(Matrix4::translation(20.0, 30.0)),
2900 Offset::ZERO,
2901 |_, position| {
2902 positions.push(position);
2903 true
2904 },
2905 );
2906 assert!(is_hit);
2907 assert_eq!(positions, [Offset::new(-20.0, -30.0)]);
2908 positions.clear();
2909
2910 let position = Offset::new(3.0, 4.0);
2911 let is_hit = result.add_with_paint_transform(None, position, |_, position| {
2912 positions.push(position);
2913 false
2914 });
2915 assert!(!is_hit);
2916 assert_eq!(positions, [position]);
2917 positions.clear();
2918
2919 let is_hit =
2920 result.add_with_paint_transform(Some(Matrix4::IDENTITY), position, |_, position| {
2921 positions.push(position);
2922 true
2923 });
2924 assert!(is_hit);
2925 assert_eq!(positions, [position]);
2926 positions.clear();
2927
2928 let is_hit = result.add_with_paint_transform(
2929 Some(Matrix4::translation(20.0, 30.0)),
2930 position,
2931 |_, position| {
2932 positions.push(position);
2933 true
2934 },
2935 );
2936 assert!(is_hit);
2937 assert_eq!(positions, [position - Offset::new(20.0, 30.0)]);
2938 positions.clear();
2939
2940 let is_hit = result.add_with_paint_transform(
2941 Some(force_to_point(position)), position,
2943 |_, position| {
2944 positions.push(position);
2945 true
2946 },
2947 );
2948 assert!(!is_hit);
2949 assert!(positions.is_empty());
2950 }
2951
2952 #[test]
2957 fn a_hit_test_through_a_perspective_transform_lands_where_flutters_does() {
2958 let angle = 0.5_f64;
2959 let (cos, sin) = (angle.cos(), angle.sin());
2960 let perspective = 0.001;
2961 let mut storage = Matrix4::IDENTITY.to_flutter_array();
2962 storage[0] = cos as f32;
2963 storage[2] = -sin as f32;
2964 storage[8] = sin as f32;
2965 storage[10] = cos as f32;
2966 storage[3] = (-perspective * sin) as f32;
2968 storage[11] = (perspective * cos) as f32;
2969 let transform = Matrix4::from_flutter_array(&storage);
2970
2971 let mut base = HitTestResult::new();
2972 let mut result = BoxHitTestResult::wrap(&mut base);
2973 let position = Offset::new(100.0, 50.0);
2974 let mut landed = None;
2975 let is_hit = result.add_with_paint_transform(Some(transform), position, |result, local| {
2976 result.add(HitTestEntry::new(DummyHitTestTarget));
2977 landed = Some(local);
2978 true
2979 });
2980 assert!(is_hit);
2981
2982 let w = 1.0 + perspective * sin * position.dx() / cos;
2985 let expected = Offset::new(position.dx() / cos / w, position.dy() / w);
2986 let landed = landed.expect("the child was hit-tested");
2987 assert!(
2988 (landed.dx() - expected.dx()).abs() < 1e-3
2989 && (landed.dy() - expected.dy()).abs() < 1e-3,
2990 "{landed:?} != {expected:?}"
2991 );
2992 }
2993
2994 #[test]
2996 fn add_with_paint_offset() {
2997 let mut base = HitTestResult::new();
2998 let mut result = BoxHitTestResult::wrap(&mut base);
2999 let mut positions = Vec::new();
3000
3001 let is_hit = result.add_with_paint_offset(None, Offset::ZERO, |_, position| {
3002 positions.push(position);
3003 true
3004 });
3005 assert!(is_hit);
3006 assert_eq!(positions, [Offset::ZERO]);
3007 positions.clear();
3008
3009 let is_hit = result.add_with_paint_offset(
3010 Some(Offset::new(55.0, 32.0)),
3011 Offset::ZERO,
3012 |_, position| {
3013 positions.push(position);
3014 true
3015 },
3016 );
3017 assert!(is_hit);
3018 assert_eq!(positions, [Offset::new(-55.0, -32.0)]);
3019 positions.clear();
3020
3021 let position = Offset::new(3.0, 4.0);
3022 let is_hit = result.add_with_paint_offset(
3023 Some(Offset::new(55.0, 32.0)),
3024 position,
3025 |result, position| {
3026 result.add(HitTestEntry::new(DummyHitTestTarget));
3027 positions.push(position);
3028 true
3029 },
3030 );
3031 assert!(is_hit);
3032 assert_eq!(positions, [position - Offset::new(55.0, 32.0)]);
3033 assert_eq!(
3034 result.path()[0].transform(),
3035 Some(Matrix4::translation(-55.0, -32.0)),
3036 "the entry records the transform to the child"
3037 );
3038 }
3039
3040 #[test]
3042 fn add_with_raw_transform() {
3043 let mut base = HitTestResult::new();
3044 let mut result = BoxHitTestResult::wrap(&mut base);
3045 let mut positions = Vec::new();
3046
3047 let is_hit = result.add_with_raw_transform(
3048 Some(Matrix4::translation(20.0, 30.0)),
3049 Offset::ZERO,
3050 |_, position| {
3051 positions.push(position);
3052 true
3053 },
3054 );
3055 assert!(is_hit);
3056 assert_eq!(positions, [Offset::new(20.0, 30.0)]);
3057 positions.clear();
3058
3059 let position = Offset::new(3.0, 4.0);
3060 let is_hit =
3061 result.add_with_raw_transform(Some(Matrix4::IDENTITY), position, |_, position| {
3062 positions.push(position);
3063 true
3064 });
3065 assert!(is_hit);
3066 assert_eq!(positions, [position]);
3067 }
3068}
3069
3070#[cfg(test)]
3071mod intrinsics_tests {
3072 use std::cell::Cell;
3073 use std::rc::Rc;
3074 use waft_foundation::AppCell;
3075
3076 use super::*;
3077 use crate::object::RenderObjectData;
3078
3079 struct CountingBox {
3082 render_object: RenderObjectData,
3083 render_box: RenderBoxData,
3084 computations: Rc<Cell<u32>>,
3085 }
3086
3087 impl RenderObject for CountingBox {
3088 crate::render_object_accessors!();
3089
3090 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3091 let size = self.constraints(app).smallest();
3092 self.set_size(app, size);
3093 }
3094 }
3095
3096 impl RenderBox for CountingBox {
3097 crate::render_box_accessors!();
3098
3099 fn compute_min_intrinsic_width(
3100 self: RenderHandle<Self>,
3101 app: &mut App,
3102 height: f64,
3103 ) -> f64 {
3104 let computations = self.get(app).computations.clone();
3105 computations.set(computations.get() + 1);
3106 100.0 + height
3107 }
3108 }
3109
3110 #[test]
3113 fn the_intrinsic_cache_is_reused_and_cleared_by_mark_needs_layout() {
3114 let cell = AppCell::new();
3115 let mut app = cell.borrow_mut();
3116 let computations = Rc::new(Cell::new(0));
3117 let box_ = RenderHandle::new_box(
3118 &mut app,
3119 CountingBox {
3120 render_object: RenderObjectData::new(),
3121 render_box: RenderBoxData::new(),
3122 computations: computations.clone(),
3123 },
3124 );
3125
3126 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3127 assert_eq!(computations.get(), 1);
3128
3129 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3130 assert_eq!(computations.get(), 1, "the memoized value is reused");
3131
3132 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 10.0), 110.0);
3133 assert_eq!(computations.get(), 2, "another height is another entry");
3134
3135 RenderBox::mark_needs_layout(box_, &mut app);
3136 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3137 assert_eq!(computations.get(), 3, "mark_needs_layout cleared the cache");
3138 }
3139
3140 #[test]
3143 fn clearing_a_cached_intrinsic_marks_the_parent() {
3144 let cell = AppCell::new();
3145 let mut app = cell.borrow_mut();
3146 let computations = Rc::new(Cell::new(0));
3147 let child = RenderHandle::new_box(
3148 &mut app,
3149 CountingBox {
3150 render_object: RenderObjectData::new(),
3151 render_box: RenderBoxData::new(),
3152 computations,
3153 },
3154 );
3155 let parent = crate::proxy_box::RenderConstrainedBox::new(
3156 &mut app,
3157 BoxConstraints::new(),
3158 Some(child.as_box()),
3159 );
3160 parent.layout(&mut app, BoxConstraints::new().max_width(50.0), false);
3161 assert!(!parent.debug_needs_layout(&app));
3162
3163 child.as_box().get_min_intrinsic_width(&mut app, 0.0);
3164 RenderBox::mark_needs_layout(child, &mut app);
3165 assert!(
3166 parent.debug_needs_layout(&app),
3167 "the parent read an intrinsic, so it has to lay out again"
3168 );
3169 }
3170}
3171
3172#[cfg(test)]
3173mod any_box_constraints_tests {
3174 use std::cell::Cell;
3175 use std::rc::Rc;
3176 use waft_foundation::{AppCell, ValueKey};
3177
3178 use super::*;
3179 use crate::custom_layout::{
3180 ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
3181 MultiChildLayoutParentData, RenderCustomMultiChildLayoutBox,
3182 };
3183 use crate::object::RenderObjectData;
3184 use crate::proxy_box::RenderOpacity;
3185
3186 #[derive(Debug)]
3188 struct Inset(f64);
3189
3190 impl BoxConstraintsExtension for Inset {
3191 fn as_any(&self) -> &dyn Any {
3192 self
3193 }
3194
3195 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3196 other
3197 .as_any()
3198 .downcast_ref::<Inset>()
3199 .is_some_and(|other| other.0 == self.0)
3200 }
3201 }
3202
3203 #[derive(Debug)]
3205 struct Other(f64);
3206
3207 impl BoxConstraintsExtension for Other {
3208 fn as_any(&self) -> &dyn Any {
3209 self
3210 }
3211
3212 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3213 other
3214 .as_any()
3215 .downcast_ref::<Other>()
3216 .is_some_and(|other| other.0 == self.0)
3217 }
3218 }
3219
3220 fn inset(constraints: BoxConstraints, inset: f64) -> AnyBoxConstraints {
3221 AnyBoxConstraints::with_shared(constraints, Rc::new(Inset(inset)))
3222 }
3223
3224 fn inset_of(constraints: &AnyBoxConstraints) -> Option<f64> {
3225 constraints.extension::<Inset>().map(|inset| inset.0)
3226 }
3227
3228 struct CountingLeaf {
3230 render_object: RenderObjectData,
3231 render_box: RenderBoxData,
3232 layouts: Rc<Cell<u32>>,
3233 }
3234
3235 impl RenderObject for CountingLeaf {
3236 crate::render_object_accessors!();
3237
3238 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3239 let layouts = Rc::clone(&self.get(app).layouts);
3240 layouts.set(layouts.get() + 1);
3241 let size = self.constraints(app).smallest();
3242 self.set_size(app, size);
3243 }
3244 }
3245
3246 impl RenderBox for CountingLeaf {
3247 crate::render_box_accessors!();
3248 }
3249
3250 fn counting_leaf(app: &mut App, layouts: &Rc<Cell<u32>>) -> RenderHandle<CountingLeaf> {
3251 RenderHandle::new_box(
3252 app,
3253 CountingLeaf {
3254 render_object: RenderObjectData::new(),
3255 render_box: RenderBoxData::new(),
3256 layouts: Rc::clone(layouts),
3257 },
3258 )
3259 }
3260
3261 fn child_id() -> ChildLayoutId {
3262 Rc::new(ValueKey::new("child"))
3263 }
3264
3265 #[derive(Debug)]
3268 struct InsetDelegate;
3269
3270 impl MultiChildLayoutDelegate for InsetDelegate {
3271 fn perform_layout(
3272 &self,
3273 app: &mut App,
3274 children: &mut MultiChildLayoutChildren,
3275 size: Size,
3276 ) {
3277 children.layout_child(app, &child_id(), inset(BoxConstraints::loose(size), 3.0));
3278 }
3279
3280 fn should_relayout(&self, _old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
3281 false
3282 }
3283
3284 fn as_any(&self) -> &dyn Any {
3285 self
3286 }
3287 }
3288
3289 #[test]
3290 fn equality_includes_the_subclass_and_its_fields() {
3291 let constraints = BoxConstraints::tight(Size::new(10.0, 20.0));
3292 let plain = AnyBoxConstraints::new(constraints);
3293 let converted: AnyBoxConstraints = constraints.into();
3294 assert!(plain == converted);
3295 assert!(plain == constraints);
3296
3297 assert!(
3298 inset(constraints, 1.0) != plain,
3299 "a plain value never equals a subclass instance, as Dart's runtimeType check"
3300 );
3301 assert!(inset(constraints, 1.0) != constraints);
3302 assert!(inset(constraints, 1.0) == inset(constraints, 1.0));
3303 assert!(inset(constraints, 1.0) != inset(constraints, 2.0));
3304 assert!(
3305 inset(constraints, 1.0)
3306 != AnyBoxConstraints::with_shared(constraints, Rc::new(Other(1.0)))
3307 );
3308 assert!(inset(constraints, 1.0) != inset(BoxConstraints::new(), 1.0));
3309 }
3310
3311 #[test]
3312 fn a_subclass_instance_derefs_to_its_value_and_answers_its_is_check() {
3313 let constraints = BoxConstraints::new().max_width(30.0).max_height(40.0);
3314 let extended = inset(constraints, 5.0);
3315 assert_eq!(extended.constraints(), constraints);
3316 assert_eq!(extended.max_width, 30.0);
3317 assert_eq!(extended.loosen(), constraints.loosen());
3318 assert!(extended.has_extension());
3319 assert_eq!(inset_of(&extended), Some(5.0));
3320 assert!(extended.extension::<Other>().is_none());
3321 assert!(!AnyBoxConstraints::new(constraints).has_extension());
3322 assert_eq!(format!("{extended:?}"), format!("{constraints:?}"));
3323 }
3324
3325 #[test]
3326 fn layout_lays_out_again_when_only_the_subclass_fields_change() {
3327 let cell = AppCell::new();
3328 let mut app = cell.borrow_mut();
3329 let layouts = Rc::new(Cell::new(0));
3330 let leaf = counting_leaf(&mut app, &layouts);
3331 let constraints = BoxConstraints::new().max_width(50.0).max_height(50.0);
3332
3333 leaf.layout(&mut app, inset(constraints, 1.0), false);
3334 assert_eq!(layouts.get(), 1);
3335 assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(1.0));
3336
3337 leaf.layout(&mut app, inset(constraints, 1.0), false);
3338 assert_eq!(layouts.get(), 1, "equal constraints return early");
3339
3340 leaf.layout(&mut app, inset(constraints, 2.0), false);
3341 assert_eq!(layouts.get(), 2, "only the inset changed");
3342 assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(2.0));
3343
3344 leaf.layout(&mut app, constraints, false);
3345 assert_eq!(
3346 layouts.get(),
3347 3,
3348 "a plain value is not the subclass instance"
3349 );
3350 assert!(!leaf.any_constraints(&app).has_extension());
3351 assert_eq!(leaf.constraints(&app), constraints);
3352 }
3353
3354 #[test]
3355 fn a_subclass_instance_reaches_the_child_a_layout_delegate_lays_out() {
3356 let cell = AppCell::new();
3357 let mut app = cell.borrow_mut();
3358 let layouts = Rc::new(Cell::new(0));
3359 let leaf = counting_leaf(&mut app, &layouts);
3360 let parent = RenderCustomMultiChildLayoutBox::new(&mut app, Rc::new(InsetDelegate));
3361 parent.add(&mut app, leaf.as_box());
3362 leaf.as_object()
3363 .parent_data_of_mut::<MultiChildLayoutParentData>(&mut app)
3364 .id = Some(child_id());
3365
3366 parent.layout(
3367 &mut app,
3368 BoxConstraints::tight(Size::new(100.0, 80.0)),
3369 false,
3370 );
3371 assert_eq!(layouts.get(), 1);
3372 let child_constraints = leaf.as_box().any_constraints(&app);
3373 assert_eq!(inset_of(&child_constraints), Some(3.0));
3374 assert_eq!(
3375 leaf.as_box().constraints(&app),
3376 BoxConstraints::loose(Size::new(100.0, 80.0))
3377 );
3378 }
3379
3380 #[test]
3381 fn a_proxy_box_hands_its_child_the_plain_value() {
3382 let cell = AppCell::new();
3383 let mut app = cell.borrow_mut();
3384 let layouts = Rc::new(Cell::new(0));
3385 let leaf = counting_leaf(&mut app, &layouts);
3386 let proxy = RenderOpacity::new(&mut app, 1.0, Some(leaf.as_box()));
3387 let constraints = BoxConstraints::new().max_width(60.0).max_height(70.0);
3388
3389 proxy.layout(&mut app, inset(constraints, 4.0), false);
3390 assert_eq!(inset_of(&proxy.any_constraints(&app)), Some(4.0));
3391 assert!(
3392 !leaf.any_constraints(&app).has_extension(),
3393 "the subclass instance rides one hop: the proxy passes its `constraints()` on"
3394 );
3395 assert_eq!(leaf.constraints(&app), constraints);
3396 }
3397}