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};
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}={min:.1}")
662 } else {
663 format!("{min:.1}<={dim}<={max:.1}")
664 }
665 }
666 write!(
667 f,
668 "BoxConstraints({}, {}{annotation})",
669 describe(self.min_width, self.max_width, "w"),
670 describe(self.min_height, self.max_height, "h")
671 )
672 }
673}
674
675impl Debug for BoxConstraints {
676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 Display::fmt(self, f)
678 }
679}
680
681pub trait BoxConstraintsExtension: Any {
689 fn as_any(&self) -> &dyn Any;
691
692 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool;
696}
697
698#[derive(Clone)]
715pub struct AnyBoxConstraints {
716 constraints: BoxConstraints,
717 extension: Option<Rc<dyn BoxConstraintsExtension>>,
718}
719
720impl AnyBoxConstraints {
721 pub const fn new(constraints: BoxConstraints) -> AnyBoxConstraints {
723 AnyBoxConstraints {
724 constraints,
725 extension: None,
726 }
727 }
728
729 pub fn with_shared(
731 constraints: BoxConstraints,
732 extension: Rc<dyn BoxConstraintsExtension>,
733 ) -> AnyBoxConstraints {
734 AnyBoxConstraints {
735 constraints,
736 extension: Some(extension),
737 }
738 }
739
740 pub fn constraints(&self) -> BoxConstraints {
742 self.constraints
743 }
744
745 pub fn extension<T: BoxConstraintsExtension>(&self) -> Option<&T> {
747 self.extension
748 .as_ref()
749 .and_then(|extension| extension.as_any().downcast_ref::<T>())
750 }
751
752 pub fn has_extension(&self) -> bool {
754 self.extension.is_some()
755 }
756}
757
758impl Deref for AnyBoxConstraints {
759 type Target = BoxConstraints;
760
761 fn deref(&self) -> &BoxConstraints {
762 &self.constraints
763 }
764}
765
766impl From<BoxConstraints> for AnyBoxConstraints {
767 fn from(constraints: BoxConstraints) -> AnyBoxConstraints {
768 AnyBoxConstraints::new(constraints)
769 }
770}
771
772impl PartialEq for AnyBoxConstraints {
773 fn eq(&self, other: &AnyBoxConstraints) -> bool {
774 if self.constraints != other.constraints {
775 return false;
776 }
777 match (&self.extension, &other.extension) {
778 (None, None) => true,
779 (Some(mine), Some(theirs)) => mine.eq_extension(&**theirs),
780 _ => false,
781 }
782 }
783}
784
785impl PartialEq<BoxConstraints> for AnyBoxConstraints {
786 fn eq(&self, other: &BoxConstraints) -> bool {
787 self.extension.is_none() && self.constraints == *other
788 }
789}
790
791impl Debug for AnyBoxConstraints {
793 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794 Debug::fmt(&self.constraints, f)
795 }
796}
797
798pub type BoxHitTest<'r> = dyn FnOnce(&mut BoxHitTestResult<'r>, Offset) -> bool;
803
804pub struct BoxHitTestResult<'a>(&'a mut HitTestResult);
809
810impl<'a> BoxHitTestResult<'a> {
811 pub fn wrap(result: &'a mut HitTestResult) -> BoxHitTestResult<'a> {
813 BoxHitTestResult(result)
814 }
815
816 pub fn add_with_paint_transform(
831 &mut self,
832 transform: Option<Matrix4>,
833 position: Offset,
834 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
835 ) -> bool {
836 let transform = match transform {
837 Some(transform) => match remove_perspective_transform(transform).invert() {
838 Some(inverted) => Some(inverted),
839 None => return false,
841 },
842 None => None,
843 };
844 self.add_with_raw_transform(transform, position, hit_test)
845 }
846
847 pub fn add_with_paint_offset(
852 &mut self,
853 offset: Option<Offset>,
854 position: Offset,
855 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
856 ) -> bool {
857 let transformed_position = match offset {
858 Some(offset) => position - offset,
859 None => position,
860 };
861 if let Some(offset) = offset {
862 self.0.push_offset(Offset::ZERO - offset);
863 }
864 let is_hit = hit_test(self, transformed_position);
865 if offset.is_some() {
866 self.0.pop_transform();
867 }
868 is_hit
869 }
870
871 pub fn add_with_raw_transform(
878 &mut self,
879 transform: Option<Matrix4>,
880 position: Offset,
881 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
882 ) -> bool {
883 let transformed_position = match transform {
884 Some(transform) => transform_point(&transform, position),
885 None => position,
886 };
887 if let Some(transform) = transform {
888 self.0.push_transform(transform);
889 }
890 let is_hit = hit_test(self, transformed_position);
891 if transform.is_some() {
892 self.0.pop_transform();
893 }
894 is_hit
895 }
896
897 pub fn add_with_out_of_band_position(
902 &mut self,
903 paint_offset: Option<Offset>,
904 paint_transform: Option<Matrix4>,
905 raw_transform: Option<Matrix4>,
906 hit_test: impl FnOnce(&mut BoxHitTestResult<'_>) -> bool,
907 ) -> bool {
908 debug_assert_eq!(
909 [
910 paint_offset.is_some(),
911 paint_transform.is_some(),
912 raw_transform.is_some()
913 ]
914 .iter()
915 .filter(|given| **given)
916 .count(),
917 1,
918 "Exactly one transform or offset argument must be provided."
919 );
920 if let Some(paint_offset) = paint_offset {
921 self.0.push_offset(Offset::ZERO - paint_offset);
922 } else if let Some(raw_transform) = raw_transform {
923 self.0.push_transform(raw_transform);
924 } else {
925 let paint_transform = paint_transform
926 .expect("checked")
927 .invert()
928 .expect("paint_transform must be invertible.");
929 self.0.push_transform(paint_transform);
930 }
931 let is_hit = hit_test(self);
932 self.0.pop_transform();
933 is_hit
934 }
935}
936
937impl Deref for BoxHitTestResult<'_> {
938 type Target = HitTestResult;
939
940 fn deref(&self) -> &HitTestResult {
941 self.0
942 }
943}
944
945impl DerefMut for BoxHitTestResult<'_> {
946 fn deref_mut(&mut self) -> &mut HitTestResult {
947 self.0
948 }
949}
950
951#[derive(Clone, Copy, Debug)]
957pub struct BoxHitTestEntry {
958 target: AnyRenderBox,
959 local_position: Offset,
960}
961
962impl BoxHitTestEntry {
963 pub fn new(target: AnyRenderBox, local_position: Offset) -> BoxHitTestEntry {
965 BoxHitTestEntry {
966 target,
967 local_position,
968 }
969 }
970
971 pub fn target(&self) -> AnyRenderBox {
973 self.target
974 }
975
976 pub fn local_position(&self) -> Offset {
978 self.local_position
979 }
980}
981
982impl HitTestTarget for BoxHitTestEntry {
983 fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
984 self.target.handle_event(app, event, self);
985 }
986
987 fn arena_id(&self) -> Option<HandleId> {
988 Some(self.target.id)
989 }
990}
991
992impl From<BoxHitTestEntry> for HitTestEntry {
993 fn from(entry: BoxHitTestEntry) -> HitTestEntry {
994 HitTestEntry::new(entry)
995 }
996}
997
998#[derive(Clone, Copy, Debug)]
1000pub struct BoxParentData {
1001 pub offset: Offset,
1003}
1004
1005impl BoxParentData {
1006 pub const fn new() -> BoxParentData {
1008 BoxParentData {
1009 offset: Offset::ZERO,
1010 }
1011 }
1012}
1013
1014impl Default for BoxParentData {
1015 fn default() -> BoxParentData {
1016 BoxParentData::new()
1017 }
1018}
1019
1020impl ParentData for BoxParentData {
1021 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1022 (id == TypeId::of::<BoxParentData>()).then_some(self)
1023 }
1024
1025 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1026 (id == TypeId::of::<BoxParentData>()).then_some(self)
1027 }
1028}
1029
1030impl fmt::Display for BoxParentData {
1031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1032 write!(f, "offset={:?}", self.offset)
1033 }
1034}
1035
1036pub trait ContainerBoxParentData: ContainerParentDataMixin<ChildType = AnyRenderBox> {
1042 fn box_parent_data(&self) -> &BoxParentData;
1047
1048 fn box_parent_data_mut(&mut self) -> &mut BoxParentData;
1050
1051 fn offset(&self) -> Offset {
1053 self.box_parent_data().offset
1054 }
1055
1056 fn set_offset(&mut self, value: Offset) {
1058 self.box_parent_data_mut().offset = value;
1059 }
1060}
1061
1062#[derive(Clone, Copy, PartialEq, Debug)]
1064pub struct BaselineOffset(pub Option<f64>);
1065
1066impl BaselineOffset {
1067 pub const NO_BASELINE: BaselineOffset = BaselineOffset(None);
1073
1074 pub fn offset(self) -> Option<f64> {
1076 self.0
1077 }
1078
1079 pub fn min_of(self, other: BaselineOffset) -> BaselineOffset {
1086 match (self.0, other.0) {
1087 (Some(lhs), Some(rhs)) => {
1088 if lhs >= rhs {
1089 other
1090 } else {
1091 self
1092 }
1093 }
1094 (Some(_), None) => self,
1095 (None, _) => other,
1096 }
1097 }
1098}
1099
1100impl Add<f64> for BaselineOffset {
1101 type Output = BaselineOffset;
1102
1103 fn add(self, offset: f64) -> BaselineOffset {
1106 BaselineOffset(self.0.map(|value| value + offset))
1107 }
1108}
1109
1110#[derive(Clone, Copy, Debug)]
1115pub enum DryLayoutFailure<'a> {
1116 Reason(&'a str),
1118
1119 Error(&'a str),
1121}
1122
1123#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1126enum IntrinsicDimension {
1127 MinWidth,
1128 MaxWidth,
1129 MinHeight,
1130 MaxHeight,
1131}
1132
1133#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1135struct DoubleKey(u64);
1136
1137impl DoubleKey {
1138 fn new(value: f64) -> DoubleKey {
1139 DoubleKey(value.to_bits())
1140 }
1141}
1142
1143#[derive(Default)]
1150struct LayoutCacheStorage {
1151 cached_intrinsic_dimensions: HashMap<(IntrinsicDimension, DoubleKey), f64>,
1152 cached_dry_layout_sizes: HashMap<BoxConstraints, Size>,
1153 cached_alphabetic_baseline: HashMap<BoxConstraints, BaselineOffset>,
1154 cached_ideo_baseline: HashMap<BoxConstraints, BaselineOffset>,
1155}
1156
1157impl LayoutCacheStorage {
1158 fn clear(&mut self) -> bool {
1160 let has_cache = !self.cached_dry_layout_sizes.is_empty()
1161 || !self.cached_intrinsic_dimensions.is_empty()
1162 || !self.cached_alphabetic_baseline.is_empty()
1163 || !self.cached_ideo_baseline.is_empty();
1164 if has_cache {
1165 self.cached_dry_layout_sizes.clear();
1166 self.cached_intrinsic_dimensions.clear();
1167 self.cached_alphabetic_baseline.clear();
1168 self.cached_ideo_baseline.clear();
1169 }
1170 has_cache
1171 }
1172
1173 fn baselines(
1174 &mut self,
1175 baseline: TextBaseline,
1176 ) -> &mut HashMap<BoxConstraints, BaselineOffset> {
1177 match baseline {
1178 TextBaseline::Alphabetic => &mut self.cached_alphabetic_baseline,
1179 TextBaseline::Ideographic => &mut self.cached_ideo_baseline,
1180 }
1181 }
1182}
1183
1184pub struct RenderBoxData {
1186 pub(crate) size: Option<Size>,
1187 pub(crate) constraints: Option<AnyBoxConstraints>,
1188 layout_cache: LayoutCacheStorage,
1189 debug_computing_this_dry_layout: bool,
1190 debug_computing_this_dry_baseline: bool,
1191}
1192
1193impl RenderBoxData {
1194 pub fn new() -> RenderBoxData {
1196 RenderBoxData {
1197 size: None,
1198 constraints: None,
1199 layout_cache: LayoutCacheStorage::default(),
1200 debug_computing_this_dry_layout: false,
1201 debug_computing_this_dry_baseline: false,
1202 }
1203 }
1204
1205 pub fn constraints(&self) -> Option<BoxConstraints> {
1208 self.constraints
1209 .as_ref()
1210 .map(AnyBoxConstraints::constraints)
1211 }
1212}
1213
1214impl Default for RenderBoxData {
1215 fn default() -> RenderBoxData {
1216 RenderBoxData::new()
1217 }
1218}
1219
1220#[macro_export]
1222macro_rules! render_box_accessors {
1223 () => {
1224 fn render_box_data(
1225 self: $crate::RenderHandle<Self>,
1226 app: &::waft_foundation::App,
1227 ) -> &$crate::RenderBoxData {
1228 &self.get(app).render_box
1229 }
1230 fn render_box_data_mut(
1231 self: $crate::RenderHandle<Self>,
1232 app: &mut ::waft_foundation::App,
1233 ) -> &mut $crate::RenderBoxData {
1234 &mut self.get_mut(app).render_box
1235 }
1236 };
1237}
1238
1239fn box_parent_data_of(app: &App, child: AnyRenderObject) -> &BoxParentData {
1245 child
1246 .parent_data(app)
1247 .and_then(|parent_data| parent_data.part::<BoxParentData>())
1248 .expect("parent data is not a BoxParentData")
1249}
1250
1251pub trait RenderBoxContainerDefaultsMixin:
1259 ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType: ContainerBoxParentData>
1260 + RenderBox
1261{
1262 fn default_compute_distance_to_first_actual_baseline(
1267 self: RenderHandle<Self>,
1268 app: &mut App,
1269 baseline: TextBaseline,
1270 ) -> Option<f64> {
1271 debug_assert!(!self.as_object().debug_needs_layout(app));
1272 let mut child = self.first_child(app);
1273 while let Some(current) = child {
1274 let child_parent_data = current
1275 .as_object()
1276 .parent_data_of::<Self::ParentDataType>(app);
1277 let (offset, next_sibling) =
1278 (child_parent_data.offset(), child_parent_data.next_sibling());
1279 if let Some(result) = current.get_distance_to_actual_baseline(app, baseline) {
1280 return Some(result + offset.dy());
1281 }
1282 child = next_sibling;
1283 }
1284 None
1285 }
1286
1287 fn default_compute_distance_to_highest_actual_baseline(
1292 self: RenderHandle<Self>,
1293 app: &mut App,
1294 baseline: TextBaseline,
1295 ) -> Option<f64> {
1296 debug_assert!(!self.as_object().debug_needs_layout(app));
1297 let mut min_baseline = BaselineOffset::NO_BASELINE;
1298 let mut child = self.first_child(app);
1299 while let Some(current) = child {
1300 let child_parent_data = current
1301 .as_object()
1302 .parent_data_of::<Self::ParentDataType>(app);
1303 let (offset, next_sibling) =
1304 (child_parent_data.offset(), child_parent_data.next_sibling());
1305 let candidate = BaselineOffset(current.get_distance_to_actual_baseline(app, baseline))
1306 + offset.dy();
1307 min_baseline = min_baseline.min_of(candidate);
1308 child = next_sibling;
1309 }
1310 min_baseline.offset()
1311 }
1312
1313 fn default_hit_test_children(
1323 self: RenderHandle<Self>,
1324 app: &mut App,
1325 result: &mut BoxHitTestResult<'_>,
1326 position: Offset,
1327 ) -> bool {
1328 let mut child = self.last_child(app);
1329 while let Some(current) = child {
1330 let child_parent_data = current
1332 .as_object()
1333 .parent_data_of::<Self::ParentDataType>(app);
1334 let (offset, previous_sibling) = (
1335 child_parent_data.offset(),
1336 child_parent_data.previous_sibling(),
1337 );
1338 let is_hit =
1339 result.add_with_paint_offset(Some(offset), position, |result, transformed| {
1340 debug_assert_eq!(transformed, position - offset);
1341 current.hit_test(app, result, transformed)
1342 });
1343 if is_hit {
1344 return true;
1345 }
1346 child = previous_sibling;
1347 }
1348 false
1349 }
1350
1351 fn default_paint(
1358 self: RenderHandle<Self>,
1359 app: &mut App,
1360 context: &mut PaintingContext,
1361 offset: Offset,
1362 ) {
1363 let mut child = self.first_child(app);
1364 while let Some(current) = child {
1365 let child_parent_data = current
1366 .as_object()
1367 .parent_data_of::<Self::ParentDataType>(app);
1368 let (child_offset, next_sibling) =
1369 (child_parent_data.offset(), child_parent_data.next_sibling());
1370 context.paint_child(app, current.as_object(), child_offset + offset);
1371 child = next_sibling;
1372 }
1373 }
1374}
1375
1376pub trait RenderBox: RenderObject {
1382 fn render_box_data(self: RenderHandle<Self>, app: &App) -> &RenderBoxData;
1384
1385 fn render_box_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderBoxData;
1387
1388 fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
1394 self.render_box_data(app)
1395 .constraints
1396 .as_ref()
1397 .map(AnyBoxConstraints::constraints)
1398 .unwrap_or_else(|| {
1399 panic!("A RenderObject does not have any constraints before it has been laid out.")
1400 })
1401 }
1402
1403 fn any_constraints(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
1411 self.render_box_data(app)
1412 .constraints
1413 .clone()
1414 .unwrap_or_else(|| {
1415 panic!("A RenderObject does not have any constraints before it has been laid out.")
1416 })
1417 }
1418
1419 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1423 if !child.parent_data_is::<BoxParentData>(app) {
1424 child.set_parent_data(app, BoxParentData::new());
1425 }
1426 }
1427
1428 fn get_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1430 self.as_box().get_min_intrinsic_width(app, height)
1431 }
1432
1433 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1478 let _ = (self, app, height);
1479 0.0
1480 }
1481
1482 fn get_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1484 self.as_box().get_max_intrinsic_width(app, height)
1485 }
1486
1487 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1508 let _ = (self, app, height);
1509 0.0
1510 }
1511
1512 fn get_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1514 self.as_box().get_min_intrinsic_height(app, width)
1515 }
1516
1517 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1534 let _ = (self, app, width);
1535 0.0
1536 }
1537
1538 fn get_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1540 self.as_box().get_max_intrinsic_height(app, width)
1541 }
1542
1543 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1560 let _ = (self, app, width);
1561 0.0
1562 }
1563
1564 fn get_dry_layout(
1566 self: RenderHandle<Self>,
1567 app: &mut App,
1568 constraints: BoxConstraints,
1569 ) -> Size {
1570 self.as_box().get_dry_layout(app, constraints)
1571 }
1572
1573 fn compute_dry_layout(
1598 self: RenderHandle<Self>,
1599 app: &mut App,
1600 constraints: BoxConstraints,
1601 ) -> Size {
1602 let _ = (app, constraints);
1603 self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1604 "It does not implement RenderBox::compute_dry_layout.",
1605 ));
1606 Size::ZERO
1607 }
1608
1609 fn get_dry_baseline(
1611 self: RenderHandle<Self>,
1612 app: &mut App,
1613 constraints: BoxConstraints,
1614 baseline: TextBaseline,
1615 ) -> Option<f64> {
1616 self.as_box().get_dry_baseline(app, constraints, baseline)
1617 }
1618
1619 fn compute_dry_baseline(
1643 self: RenderHandle<Self>,
1644 app: &mut App,
1645 constraints: BoxConstraints,
1646 baseline: TextBaseline,
1647 ) -> Option<f64> {
1648 let _ = (app, constraints, baseline);
1649 self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1650 "It does not implement RenderBox::compute_dry_baseline.",
1651 ));
1652 None
1653 }
1654
1655 fn debug_cannot_compute_dry_layout(self: RenderHandle<Self>, failure: DryLayoutFailure<'_>) {
1663 let _ = self;
1664 if !cfg!(debug_assertions) || debug_checking_intrinsics() {
1665 return;
1666 }
1667 match failure {
1668 DryLayoutFailure::Reason(reason) => panic!(
1669 "The {} class does not support dry layout. {reason}",
1670 std::any::type_name::<Self>()
1671 ),
1672 DryLayoutFailure::Error(error) => panic!("{error}"),
1673 }
1674 }
1675
1676 fn get_distance_to_baseline(
1678 self: RenderHandle<Self>,
1679 app: &mut App,
1680 baseline: TextBaseline,
1681 only_real: bool,
1682 ) -> Option<f64> {
1683 self.as_box()
1684 .get_distance_to_baseline(app, baseline, only_real)
1685 }
1686
1687 fn get_distance_to_actual_baseline(
1689 self: RenderHandle<Self>,
1690 app: &mut App,
1691 baseline: TextBaseline,
1692 ) -> Option<f64> {
1693 self.as_box().get_distance_to_actual_baseline(app, baseline)
1694 }
1695
1696 fn compute_distance_to_actual_baseline(
1716 self: RenderHandle<Self>,
1717 app: &mut App,
1718 baseline: TextBaseline,
1719 ) -> Option<f64> {
1720 let _ = (self, app, baseline);
1721 debug_assert!(
1722 DEBUG_DOING_BASELINE.get(),
1723 "Please see the documentation for compute_distance_to_actual_baseline for the \
1724 required calling conventions of this method."
1725 );
1726 None
1727 }
1728
1729 fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1735 RenderBoxBase::mark_needs_layout(self, app);
1736 }
1737
1738 fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1745 RenderBoxBase::perform_resize(self, app);
1746 }
1747
1748 fn size(self: RenderHandle<Self>, app: &App) -> Size {
1750 self.as_box().size(app)
1751 }
1752
1753 fn apply_paint_transform(
1763 self: RenderHandle<Self>,
1764 app: &App,
1765 child: AnyRenderObject,
1766 transform: &mut Matrix4,
1767 ) {
1768 debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
1769 let offset = box_parent_data_of(app, child).offset;
1772 crate::object::translate(transform, offset.dx(), offset.dy());
1773 }
1774
1775 fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
1777 Offset::ZERO & self.size(app)
1778 }
1779
1780 fn has_size(self: RenderHandle<Self>, app: &App) -> bool {
1782 self.render_box_data(app).size.is_some()
1783 }
1784
1785 fn handle_event(
1791 self: RenderHandle<Self>,
1792 app: &mut App,
1793 event: &PointerEvent,
1794 entry: &BoxHitTestEntry,
1795 ) {
1796 let _ = (self, app, event, entry);
1797 }
1798
1799 fn hit_test(
1814 self: RenderHandle<Self>,
1815 app: &mut App,
1816 result: &mut BoxHitTestResult<'_>,
1817 position: Offset,
1818 ) -> bool {
1819 RenderBoxBase::hit_test(self, app, result, position)
1820 }
1821
1822 fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1827 let _ = self;
1828 false
1829 }
1830
1831 fn hit_test_children(
1836 self: RenderHandle<Self>,
1837 app: &mut App,
1838 result: &mut BoxHitTestResult<'_>,
1839 position: Offset,
1840 ) -> bool {
1841 let _ = (self, app, result, position);
1842 false
1843 }
1844
1845 fn set_size(self: RenderHandle<Self>, app: &mut App, size: Size) {
1848 self.as_box().set_size(app, size)
1849 }
1850
1851 fn layout(
1853 self: RenderHandle<Self>,
1854 app: &mut App,
1855 constraints: impl Into<AnyBoxConstraints>,
1856 parent_uses_size: bool,
1857 ) {
1858 self.as_box().layout(app, constraints, parent_uses_size)
1859 }
1860
1861 fn as_box(self: RenderHandle<Self>) -> AnyRenderBox {
1863 AnyRenderBox {
1864 id: self.id(),
1865 vtable: const { &RenderBoxVTable::of::<Self>() },
1866 }
1867 }
1868
1869 fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
1871 self.as_box().as_object()
1872 }
1873
1874 fn adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1876 self.as_object().adopt_child(app, child)
1877 }
1878
1879 fn drop_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1881 self.as_object().drop_child(app, child)
1882 }
1883
1884 fn mark_needs_paint(self: RenderHandle<Self>, app: &mut App) {
1886 self.as_object().mark_needs_paint(app)
1887 }
1888
1889 fn mark_needs_composited_layer_update(self: RenderHandle<Self>, app: &mut App) {
1891 self.as_object().mark_needs_composited_layer_update(app)
1892 }
1893
1894 fn mark_needs_compositing_bits_update(self: RenderHandle<Self>, app: &mut App) {
1896 self.as_object().mark_needs_compositing_bits_update(app)
1897 }
1898
1899 fn schedule_initial_layout(self: RenderHandle<Self>, app: &mut App) {
1901 self.as_object().schedule_initial_layout(app)
1902 }
1903
1904 fn parent(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderObject> {
1906 self.as_object().parent(app)
1907 }
1908
1909 fn owner(self: RenderHandle<Self>, app: &App) -> Option<Handle<PipelineOwner>> {
1911 self.as_object().owner(app)
1912 }
1913
1914 fn attached(self: RenderHandle<Self>, app: &App) -> bool {
1916 self.as_object().attached(app)
1917 }
1918
1919 fn debug_needs_layout(self: RenderHandle<Self>, app: &App) -> bool {
1921 self.as_object().debug_needs_layout(app)
1922 }
1923}
1924
1925pub trait RenderBoxBase: RenderBox {
1932 fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1934 if self.render_box_data_mut(app).layout_cache.clear() && self.parent(app).is_some() {
1947 self.as_object().mark_parent_needs_layout(app);
1948 return;
1949 }
1950 crate::object::RenderObjectBase::mark_needs_layout(self, app);
1951 }
1952
1953 fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1955 let constraints = RenderBox::constraints(self, app);
1957 let size = RenderBox::compute_dry_layout(self, app, constraints);
1958 debug_assert!(size.width().is_finite() && size.height().is_finite());
1959 self.set_size(app, size);
1960 }
1961
1962 fn hit_test(
1964 self: RenderHandle<Self>,
1965 app: &mut App,
1966 result: &mut BoxHitTestResult<'_>,
1967 position: Offset,
1968 ) -> bool {
1969 debug_assert!(
1970 self.has_size(app),
1971 "Cannot hit test a render box that has never been laid out: {self:?}"
1972 );
1973 if self.size(app).contains(position)
1974 && (RenderBox::hit_test_children(self, app, result, position)
1975 || RenderBox::hit_test_self(self, app, position))
1976 {
1977 result.add(BoxHitTestEntry::new(self.as_box(), position).into());
1978 return true;
1979 }
1980 false
1981 }
1982}
1983
1984impl<T: RenderBox> RenderBoxBase for T {}
1985
1986pub(crate) struct RenderBoxVTable {
1988 pub object: RenderObjectVTable,
1989 pub box_data: fn(&App, HandleId) -> &RenderBoxData,
1990 pub box_data_mut: fn(&mut App, HandleId) -> &mut RenderBoxData,
1991 pub hit_test: fn(&mut App, HandleId, &mut BoxHitTestResult<'_>, Offset) -> bool,
1992 pub handle_event: fn(&mut App, HandleId, &PointerEvent, &BoxHitTestEntry),
1993 pub compute_min_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1994 pub compute_max_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1995 pub compute_min_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
1996 pub compute_max_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
1997 pub compute_dry_layout: fn(&mut App, HandleId, BoxConstraints) -> Size,
1998 pub compute_dry_baseline: fn(&mut App, HandleId, BoxConstraints, TextBaseline) -> Option<f64>,
1999 pub compute_distance_to_actual_baseline: fn(&mut App, HandleId, TextBaseline) -> Option<f64>,
2000}
2001
2002impl RenderBoxVTable {
2003 const fn of<T: RenderBox>() -> RenderBoxVTable {
2004 RenderBoxVTable {
2005 object: RenderObjectVTable::of::<T>(
2006 |app, id, child| <T as RenderBox>::setup_parent_data(resolve(id), app, child),
2007 |app, id| T::paint_bounds(resolve(id), app),
2008 |app, id, child, transform| {
2009 <T as RenderBox>::apply_paint_transform(resolve(id), app, child, transform)
2010 },
2011 |app, id| <T as RenderBox>::perform_resize(resolve(id), app),
2012 |app, id| <T as RenderBox>::mark_needs_layout(resolve(id), app),
2013 Some(|| const { &RenderBoxVTable::of::<T>() }),
2014 None,
2015 ),
2016 box_data: |app, id| T::render_box_data(resolve(id), app),
2017 box_data_mut: |app, id| T::render_box_data_mut(resolve(id), app),
2018 hit_test: |app, id, result, position| T::hit_test(resolve(id), app, result, position),
2019 handle_event: |app, id, event, entry| T::handle_event(resolve(id), app, event, entry),
2020 compute_min_intrinsic_width: |app, id, height| {
2021 T::compute_min_intrinsic_width(resolve(id), app, height)
2022 },
2023 compute_max_intrinsic_width: |app, id, height| {
2024 T::compute_max_intrinsic_width(resolve(id), app, height)
2025 },
2026 compute_min_intrinsic_height: |app, id, width| {
2027 T::compute_min_intrinsic_height(resolve(id), app, width)
2028 },
2029 compute_max_intrinsic_height: |app, id, width| {
2030 T::compute_max_intrinsic_height(resolve(id), app, width)
2031 },
2032 compute_dry_layout: |app, id, constraints| {
2033 T::compute_dry_layout(resolve(id), app, constraints)
2034 },
2035 compute_dry_baseline: |app, id, constraints, baseline| {
2036 T::compute_dry_baseline(resolve(id), app, constraints, baseline)
2037 },
2038 compute_distance_to_actual_baseline: |app, id, baseline| {
2039 T::compute_distance_to_actual_baseline(resolve(id), app, baseline)
2040 },
2041 }
2042 }
2043}
2044
2045impl<T: RenderBox> RenderHandle<T> {
2046 pub fn new_box(app: &mut App, object: T) -> RenderHandle<T> {
2048 let this = create(app, object);
2049 let data = this.render_object_data_mut(app);
2050 data.object_vtable = Some(&const { RenderBoxVTable::of::<T>() }.object);
2051 let is_repaint_boundary = this.is_repaint_boundary(app);
2055 let always_needs_compositing = this.always_needs_compositing(app);
2056 let data = this.render_object_data_mut(app);
2057 data.was_repaint_boundary = is_repaint_boundary;
2058 data.needs_compositing = is_repaint_boundary || always_needs_compositing;
2059 this
2060 }
2061}
2062
2063struct DebugDoingBaseline;
2065
2066impl DebugDoingBaseline {
2067 fn enter() -> DebugDoingBaseline {
2068 DEBUG_DOING_BASELINE.set(cfg!(debug_assertions));
2069 DebugDoingBaseline
2070 }
2071}
2072
2073impl Drop for DebugDoingBaseline {
2074 fn drop(&mut self) {
2075 DEBUG_DOING_BASELINE.set(false);
2076 }
2077}
2078
2079fn should_cache_intrinsics(this: AnyRenderBox, app: &App) -> bool {
2081 debug_assert!(debug_checking_intrinsics() || !this.as_object().debug_doing_this_resize(app));
2083 !cfg!(debug_assertions) || !debug_checking_intrinsics()
2085}
2086
2087fn memoize_intrinsic(
2089 this: AnyRenderBox,
2090 app: &mut App,
2091 dimension: IntrinsicDimension,
2092 input: f64,
2093 computer: fn(&mut App, HandleId, f64) -> f64,
2094) -> f64 {
2095 if !should_cache_intrinsics(this, app) {
2096 return computer(app, this.id, input);
2097 }
2098 let key = (dimension, DoubleKey::new(input));
2099 if let Some(cached) = this.layout_cache(app).cached_intrinsic_dimensions.get(&key) {
2100 return *cached;
2101 }
2102 let result = computer(app, this.id, input);
2103 this.layout_cache_mut(app)
2104 .cached_intrinsic_dimensions
2105 .insert(key, result);
2106 result
2107}
2108
2109fn memoize_baseline(
2111 this: AnyRenderBox,
2112 app: &mut App,
2113 constraints: BoxConstraints,
2114 baseline: TextBaseline,
2115 computer: impl FnOnce(AnyRenderBox, &mut App) -> BaselineOffset,
2116) -> BaselineOffset {
2117 if !should_cache_intrinsics(this, app) {
2118 return computer(this, app);
2119 }
2120 if let Some(cached) = this
2121 .layout_cache_mut(app)
2122 .baselines(baseline)
2123 .get(&constraints)
2124 {
2125 return *cached;
2126 }
2127 let result = computer(this, app);
2128 this.layout_cache_mut(app)
2129 .baselines(baseline)
2130 .insert(constraints, result);
2131 result
2132}
2133
2134#[derive(Clone, Copy)]
2136pub struct AnyRenderBox {
2137 id: HandleId,
2138 vtable: &'static RenderBoxVTable,
2139}
2140
2141impl PartialEq for AnyRenderBox {
2142 fn eq(&self, other: &AnyRenderBox) -> bool {
2143 self.id == other.id
2144 }
2145}
2146
2147impl Eq for AnyRenderBox {}
2148
2149impl std::hash::Hash for AnyRenderBox {
2150 fn hash<H: Hasher>(&self, state: &mut H) {
2151 self.id.hash(state);
2152 }
2153}
2154
2155impl Debug for AnyRenderBox {
2156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2157 write!(f, "AnyRenderBox({:?})", self.id)
2158 }
2159}
2160
2161impl AnyRenderBox {
2162 pub(crate) fn from_vtable(id: HandleId, vtable: &'static RenderBoxVTable) -> AnyRenderBox {
2163 AnyRenderBox { id, vtable }
2164 }
2165
2166 pub fn has_size(self, app: &App) -> bool {
2169 self.box_data(app).size.is_some()
2170 }
2171
2172 pub fn as_object(self) -> AnyRenderObject {
2173 AnyRenderObject::from_vtable(self.id, &self.vtable.object)
2174 }
2175
2176 pub fn hit_test(
2178 self,
2179 app: &mut App,
2180 result: &mut BoxHitTestResult<'_>,
2181 position: Offset,
2182 ) -> bool {
2183 (self.vtable.hit_test)(app, self.id, result, position)
2184 }
2185
2186 pub fn handle_event(self, app: &mut App, event: &PointerEvent, entry: &BoxHitTestEntry) {
2188 (self.vtable.handle_event)(app, self.id, event, entry)
2189 }
2190
2191 fn box_data(self, app: &App) -> &RenderBoxData {
2192 (self.vtable.box_data)(app, self.id)
2193 }
2194
2195 fn box_data_mut(self, app: &mut App) -> &mut RenderBoxData {
2196 (self.vtable.box_data_mut)(app, self.id)
2197 }
2198
2199 pub fn layout(
2205 self,
2206 app: &mut App,
2207 constraints: impl Into<AnyBoxConstraints>,
2208 parent_uses_size: bool,
2209 ) {
2210 let constraints: AnyBoxConstraints = constraints.into();
2211 debug_assert!(
2212 !app.is_disposed(self.id),
2213 "layout on a disposed render object"
2214 );
2215 debug_assert!(constraints.debug_assert_is_valid(true));
2216 let same = self.box_data(app).constraints.as_ref() == Some(&constraints);
2217 let tight = constraints.is_tight();
2218 self.as_object()
2219 .run_layout(app, parent_uses_size, tight, same, |app| {
2220 self.box_data_mut(app).constraints = Some(constraints)
2221 });
2222 }
2223
2224 pub fn size(self, app: &App) -> Size {
2230 self.box_data(app)
2231 .size
2232 .unwrap_or_else(|| panic!("RenderBox was not laid out: {self:?}"))
2233 }
2234
2235 pub fn set_size(self, app: &mut App, size: Size) {
2237 self.box_data_mut(app).size = Some(size);
2238 }
2239
2240 pub fn constraints(self, app: &App) -> BoxConstraints {
2246 self.box_data(app)
2247 .constraints
2248 .as_ref()
2249 .map(AnyBoxConstraints::constraints)
2250 .unwrap_or_else(|| {
2251 panic!("A RenderObject does not have any constraints before it has been laid out.")
2252 })
2253 }
2254
2255 pub fn any_constraints(self, app: &App) -> AnyBoxConstraints {
2257 self.box_data(app).constraints.clone().unwrap_or_else(|| {
2258 panic!("A RenderObject does not have any constraints before it has been laid out.")
2259 })
2260 }
2261
2262 pub fn get_min_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2278 debug_assert!(
2279 height >= 0.0,
2280 "The height argument to get_min_intrinsic_width was negative. If you perform \
2281 computations on another height before passing it to get_min_intrinsic_width, \
2282 consider using f64::max or clamp_double to force the value into the valid range."
2283 );
2284 memoize_intrinsic(
2285 self,
2286 app,
2287 IntrinsicDimension::MinWidth,
2288 height,
2289 self.vtable.compute_min_intrinsic_width,
2290 )
2291 }
2292
2293 pub fn get_max_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2300 debug_assert!(
2301 height >= 0.0,
2302 "The height argument to get_max_intrinsic_width was negative."
2303 );
2304 memoize_intrinsic(
2305 self,
2306 app,
2307 IntrinsicDimension::MaxWidth,
2308 height,
2309 self.vtable.compute_max_intrinsic_width,
2310 )
2311 }
2312
2313 pub fn get_min_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2319 debug_assert!(
2320 width >= 0.0,
2321 "The width argument to get_min_intrinsic_height was negative."
2322 );
2323 memoize_intrinsic(
2324 self,
2325 app,
2326 IntrinsicDimension::MinHeight,
2327 width,
2328 self.vtable.compute_min_intrinsic_height,
2329 )
2330 }
2331
2332 pub fn get_max_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2339 debug_assert!(
2340 width >= 0.0,
2341 "The width argument to get_max_intrinsic_height was negative."
2342 );
2343 memoize_intrinsic(
2344 self,
2345 app,
2346 IntrinsicDimension::MaxHeight,
2347 width,
2348 self.vtable.compute_max_intrinsic_height,
2349 )
2350 }
2351
2352 pub fn get_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2370 if !should_cache_intrinsics(self, app) {
2371 return self.compute_dry_layout(app, constraints);
2372 }
2373 if let Some(cached) = self
2374 .layout_cache(app)
2375 .cached_dry_layout_sizes
2376 .get(&constraints)
2377 {
2378 return *cached;
2379 }
2380 let result = self.compute_dry_layout(app, constraints);
2381 self.layout_cache_mut(app)
2382 .cached_dry_layout_sizes
2383 .insert(constraints, result);
2384 result
2385 }
2386
2387 fn compute_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2389 if cfg!(debug_assertions) {
2390 assert!(!self.box_data(app).debug_computing_this_dry_layout);
2391 self.box_data_mut(app).debug_computing_this_dry_layout = true;
2392 }
2393 let result = (self.vtable.compute_dry_layout)(app, self.id, constraints);
2394 if cfg!(debug_assertions) {
2395 self.box_data_mut(app).debug_computing_this_dry_layout = false;
2396 }
2397 result
2398 }
2399
2400 pub fn get_dry_baseline(
2416 self,
2417 app: &mut App,
2418 constraints: BoxConstraints,
2419 baseline: TextBaseline,
2420 ) -> Option<f64> {
2421 let baseline_offset = memoize_baseline(self, app, constraints, baseline, |this, app| {
2422 this.compute_dry_baseline(app, constraints, baseline)
2423 })
2424 .offset();
2425 if cfg!(debug_assertions) && !debug_checking_intrinsics() {
2430 assert_eq!(
2431 baseline_offset,
2432 (self.vtable.compute_dry_baseline)(app, self.id, constraints, baseline)
2433 );
2434 }
2435 baseline_offset
2436 }
2437
2438 fn compute_dry_baseline(
2440 self,
2441 app: &mut App,
2442 constraints: BoxConstraints,
2443 baseline: TextBaseline,
2444 ) -> BaselineOffset {
2445 if cfg!(debug_assertions) {
2446 assert!(!self.box_data(app).debug_computing_this_dry_baseline);
2447 self.box_data_mut(app).debug_computing_this_dry_baseline = true;
2448 }
2449 let result = BaselineOffset((self.vtable.compute_dry_baseline)(
2450 app,
2451 self.id,
2452 constraints,
2453 baseline,
2454 ));
2455 if cfg!(debug_assertions) {
2456 self.box_data_mut(app).debug_computing_this_dry_baseline = false;
2457 }
2458 result
2459 }
2460
2461 pub fn get_distance_to_baseline(
2477 self,
2478 app: &mut App,
2479 baseline: TextBaseline,
2480 only_real: bool,
2481 ) -> Option<f64> {
2482 debug_assert!(
2483 !DEBUG_DOING_BASELINE.get(),
2484 "Please see the documentation for compute_distance_to_actual_baseline for the \
2485 required calling conventions of this method."
2486 );
2487 debug_assert!(!self.as_object().debug_needs_layout(app) || debug_checking_intrinsics());
2488 let result = {
2489 let _doing_baseline = DebugDoingBaseline::enter();
2490 self.get_distance_to_actual_baseline(app, baseline)
2491 };
2492 match result {
2493 None if !only_real => Some(self.size(app).height()),
2494 result => result,
2495 }
2496 }
2497
2498 pub fn get_distance_to_actual_baseline(
2504 self,
2505 app: &mut App,
2506 baseline: TextBaseline,
2507 ) -> Option<f64> {
2508 debug_assert!(
2509 DEBUG_DOING_BASELINE.get() || !cfg!(debug_assertions),
2510 "Please see the documentation for compute_distance_to_actual_baseline for the \
2511 required calling conventions of this method."
2512 );
2513 let constraints = self
2514 .box_data(app)
2515 .constraints
2516 .as_ref()
2517 .map(AnyBoxConstraints::constraints)
2518 .expect("a RenderBox has constraints once it has been laid out");
2519 memoize_baseline(self, app, constraints, baseline, |this, app| {
2520 BaselineOffset((this.vtable.compute_distance_to_actual_baseline)(
2521 app, this.id, baseline,
2522 ))
2523 })
2524 .offset()
2525 }
2526
2527 fn layout_cache(self, app: &App) -> &LayoutCacheStorage {
2528 &self.box_data(app).layout_cache
2529 }
2530
2531 fn layout_cache_mut(self, app: &mut App) -> &mut LayoutCacheStorage {
2532 &mut self.box_data_mut(app).layout_cache
2533 }
2534
2535 pub fn box_parent_data(self, app: &App) -> &BoxParentData {
2540 box_parent_data_of(app, self.as_object())
2541 }
2542
2543 pub fn global_to_local(
2558 self,
2559 app: &App,
2560 point: Offset,
2561 ancestor: Option<AnyRenderObject>,
2562 ) -> Offset {
2563 let transform = self.as_object().get_transform_to(app, ancestor);
2578 let Some(transform) = transform.invert() else {
2579 return Offset::ZERO;
2580 };
2581
2582 let n = [0.0, 0.0, 1.0];
2585 let i = crate::object::perspective_transform(&transform, [0.0, 0.0, 0.0]);
2586 let d = subtract(
2587 crate::object::perspective_transform(&transform, [0.0, 0.0, 1.0]),
2588 i,
2589 );
2590 let s = crate::object::perspective_transform(&transform, [point.dx(), point.dy(), 0.0]);
2591 let p = subtract(s, scale(d, dot(n, s) / dot(n, d)));
2593 Offset::new(p[0], p[1])
2594 }
2595
2596 pub fn local_to_global(
2607 self,
2608 app: &App,
2609 point: Offset,
2610 ancestor: Option<AnyRenderObject>,
2611 ) -> Offset {
2612 waft_painting::transform_point(&self.as_object().get_transform_to(app, ancestor), point)
2613 }
2614
2615 pub fn parent_data_of_mut<P: crate::object::ParentData + 'static>(
2617 self,
2618 app: &mut App,
2619 ) -> &mut P {
2620 self.as_object().parent_data_of_mut(app)
2621 }
2622
2623 pub fn parent_data_is<P: crate::object::ParentData + 'static>(self, app: &App) -> bool {
2625 self.as_object().parent_data_is::<P>(app)
2626 }
2627}
2628
2629impl crate::object::ErasedRenderObject for AnyRenderBox {
2630 fn as_object(self) -> AnyRenderObject {
2631 AnyRenderBox::as_object(self)
2632 }
2633
2634 fn from_object(object: AnyRenderObject) -> AnyRenderBox {
2635 object
2636 .as_box()
2637 .expect("the render object is not a RenderBox")
2638 }
2639}
2640
2641impl From<AnyRenderBox> for AnyRenderObject {
2642 fn from(box_: AnyRenderBox) -> AnyRenderObject {
2643 box_.as_object()
2644 }
2645}
2646
2647fn subtract(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
2648 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
2649}
2650
2651fn scale(a: [f64; 3], factor: f64) -> [f64; 3] {
2652 [a[0] * factor, a[1] * factor, a[2] * factor]
2653}
2654
2655fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
2656 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
2657}
2658
2659#[cfg(test)]
2660mod tests {
2661 use super::*;
2662
2663 #[test]
2664 fn to_string_marks_biggest_unconstrained_and_tight() {
2665 assert!(
2666 BoxConstraints::expand(None, None)
2667 .to_string()
2668 .contains("biggest")
2669 );
2670 assert!(BoxConstraints::new().to_string().contains("unconstrained"));
2671 assert!(
2672 BoxConstraints::tight_for(Some(50.0), None)
2673 .to_string()
2674 .contains("w=50")
2675 );
2676 }
2677
2678 #[test]
2679 fn copy_with_replaces_fields() {
2680 let constraints = BoxConstraints::new()
2681 .min_width(3.0)
2682 .max_width(7.0)
2683 .min_height(11.0)
2684 .max_height(17.0);
2685 let copy = constraints.copy_with();
2686 assert_eq!(copy, constraints);
2687 let copy = constraints
2688 .copy_with()
2689 .min_width(13.0)
2690 .max_width(17.0)
2691 .min_height(111.0)
2692 .max_height(117.0);
2693 assert_eq!(copy.min_width, 13.0);
2694 assert_eq!(copy.max_width, 17.0);
2695 assert_eq!(copy.min_height, 111.0);
2696 assert_eq!(copy.max_height, 117.0);
2697 assert_ne!(copy, constraints);
2698 let mut copy_hasher = std::collections::hash_map::DefaultHasher::new();
2699 let mut original_hasher = std::collections::hash_map::DefaultHasher::new();
2700 copy.hash(&mut copy_hasher);
2701 constraints.hash(&mut original_hasher);
2702 assert_ne!(copy_hasher.finish(), original_hasher.finish());
2703 }
2704
2705 #[test]
2706 fn operators() {
2707 let constraints = BoxConstraints::new()
2708 .min_width(3.0)
2709 .max_width(7.0)
2710 .min_height(11.0)
2711 .max_height(17.0);
2712 let copy = constraints * 2.0;
2713 assert_eq!(copy.min_width, 6.0);
2714 assert_eq!(copy.max_width, 14.0);
2715 assert_eq!(copy.min_height, 22.0);
2716 assert_eq!(copy.max_height, 34.0);
2717 assert_eq!(copy / 2.0, constraints);
2718 let copy = constraints.truncating_div(2.0);
2719 assert_eq!(copy.min_width, 1.0);
2720 assert_eq!(copy.max_width, 3.0);
2721 assert_eq!(copy.min_height, 5.0);
2722 assert_eq!(copy.max_height, 8.0);
2723 let copy = constraints % 3.0;
2724 assert_eq!(copy.min_width, 0.0);
2725 assert_eq!(copy.max_width, 1.0);
2726 assert_eq!(copy.min_height, 2.0);
2727 assert_eq!(copy.max_height, 2.0);
2728 }
2729
2730 #[test]
2731 fn lerp_from_null_and_between() {
2732 assert!(BoxConstraints::lerp(None, None, 0.5).is_none());
2733 let constraints = BoxConstraints::new()
2734 .min_width(3.0)
2735 .max_width(7.0)
2736 .min_height(11.0)
2737 .max_height(17.0);
2738 let copy = BoxConstraints::lerp(None, Some(constraints), 0.5).unwrap();
2739 assert!((copy.min_width - 1.5).abs() < 1e-9);
2740 assert!((copy.max_width - 3.5).abs() < 1e-9);
2741 assert!((copy.min_height - 5.5).abs() < 1e-9);
2742 assert!((copy.max_height - 8.5).abs() < 1e-9);
2743 let copy = BoxConstraints::lerp(Some(constraints), None, 0.5).unwrap();
2744 assert!((copy.min_width - 1.5).abs() < 1e-9);
2745 let copy = BoxConstraints::lerp(
2746 Some(
2747 BoxConstraints::new()
2748 .min_width(13.0)
2749 .max_width(17.0)
2750 .min_height(111.0)
2751 .max_height(117.0),
2752 ),
2753 Some(constraints),
2754 0.2,
2755 )
2756 .unwrap();
2757 assert!((copy.min_width - 11.0).abs() < 1e-9);
2758 assert!((copy.max_width - 15.0).abs() < 1e-9);
2759 assert!((copy.min_height - 91.0).abs() < 1e-9);
2760 assert!((copy.max_height - 97.0).abs() < 1e-9);
2761 }
2762
2763 #[test]
2764 fn lerp_unbounded_axes() {
2765 let constraints1 = BoxConstraints::new()
2766 .min_width(f64::INFINITY)
2767 .min_height(10.0)
2768 .max_height(20.0);
2769 let constraints2 = BoxConstraints::new()
2770 .min_width(f64::INFINITY)
2771 .min_height(20.0)
2772 .max_height(30.0);
2773 let constraints3 = BoxConstraints::new()
2774 .min_width(f64::INFINITY)
2775 .min_height(15.0)
2776 .max_height(25.0);
2777 assert_eq!(
2778 BoxConstraints::lerp(Some(constraints1), Some(constraints2), 0.5),
2779 Some(constraints3)
2780 );
2781 }
2782
2783 #[test]
2784 fn lerp_overshoot_is_normalized() {
2785 assert_eq!(
2786 BoxConstraints::lerp(
2787 Some(BoxConstraints::tight_for(None, Some(25.0))),
2788 Some(BoxConstraints::tight_for(None, Some(0.0))),
2789 1.2,
2790 ),
2791 Some(BoxConstraints::tight_for(None, Some(0.0)))
2792 );
2793 let lerped = BoxConstraints::lerp(
2794 Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
2795 Some(BoxConstraints::new().max_width(100.0).max_height(100.0)),
2796 -0.1,
2797 )
2798 .unwrap();
2799 assert!(lerped.is_normalized());
2800 assert_eq!(lerped, BoxConstraints::tight(Size::new(11.0, 11.0)));
2801 }
2802
2803 #[test]
2804 fn normalize_raises_inverted_max() {
2805 let constraints = BoxConstraints::new()
2806 .min_width(3.0)
2807 .max_width(2.0)
2808 .min_height(11.0)
2809 .max_height(18.0);
2810 let copy = constraints.normalize();
2811 assert_eq!(copy.min_width, 3.0);
2812 assert_eq!(copy.max_width, 3.0);
2813 assert_eq!(copy.min_height, 11.0);
2814 assert_eq!(copy.max_height, 18.0);
2815 }
2816
2817 #[test]
2818 fn from_view_constraints() {
2819 let unconstrained = BoxConstraints::from_view_constraints(ViewConstraints::default());
2820 assert_eq!(unconstrained, BoxConstraints::new());
2821 let constraints =
2822 BoxConstraints::from_view_constraints(ViewConstraints::new(1.0, 2.0, 3.0, 4.0));
2823 assert_eq!(
2824 constraints,
2825 BoxConstraints::new()
2826 .min_width(1.0)
2827 .max_width(2.0)
2828 .min_height(3.0)
2829 .max_height(4.0)
2830 );
2831 }
2832
2833 #[test]
2834 fn constrain_size_and_attempt_to_preserve_aspect_ratio_empty_size() {
2835 let constraints = BoxConstraints::new()
2836 .min_width(10.0)
2837 .max_width(20.0)
2838 .min_height(10.0)
2839 .max_height(20.0);
2840 let constrained =
2841 constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(Size::new(15.0, 0.0));
2842 assert_eq!(constrained, Size::new(15.0, 10.0));
2843 }
2844}
2845
2846#[cfg(test)]
2847mod hit_test_tests {
2848 use waft_painting::force_to_point;
2849
2850 use super::*;
2851
2852 #[derive(Debug)]
2853 struct DummyHitTestTarget;
2854
2855 impl HitTestTarget for DummyHitTestTarget {
2856 fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
2857 }
2858
2859 #[test]
2861 fn wrapping_shares_the_path() {
2862 let transform = Matrix4::translation(40.0, 150.0);
2863 let mut wrapped = HitTestResult::new();
2864 wrapped.push_transform(transform);
2865 wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2866 assert_eq!(wrapped.path().len(), 1);
2867 assert_eq!(wrapped.path()[0].transform(), Some(transform));
2868
2869 let mut wrapping = BoxHitTestResult::wrap(&mut wrapped);
2870 wrapping.add(HitTestEntry::new(DummyHitTestTarget));
2871 assert_eq!(wrapping.path().len(), 2);
2872 assert_eq!(wrapping.path()[1].transform(), Some(transform));
2873
2874 wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2875 assert_eq!(wrapped.path().len(), 3);
2876 assert_eq!(wrapped.path()[2].transform(), Some(transform));
2877 }
2878
2879 #[test]
2881 fn add_with_paint_transform() {
2882 let mut base = HitTestResult::new();
2883 let mut result = BoxHitTestResult::wrap(&mut base);
2884 let mut positions = Vec::new();
2885
2886 let is_hit = result.add_with_paint_transform(None, Offset::ZERO, |_, position| {
2887 positions.push(position);
2888 true
2889 });
2890 assert!(is_hit);
2891 assert_eq!(positions, [Offset::ZERO]);
2892 positions.clear();
2893
2894 let is_hit = result.add_with_paint_transform(
2895 Some(Matrix4::translation(20.0, 30.0)),
2896 Offset::ZERO,
2897 |_, position| {
2898 positions.push(position);
2899 true
2900 },
2901 );
2902 assert!(is_hit);
2903 assert_eq!(positions, [Offset::new(-20.0, -30.0)]);
2904 positions.clear();
2905
2906 let position = Offset::new(3.0, 4.0);
2907 let is_hit = result.add_with_paint_transform(None, position, |_, position| {
2908 positions.push(position);
2909 false
2910 });
2911 assert!(!is_hit);
2912 assert_eq!(positions, [position]);
2913 positions.clear();
2914
2915 let is_hit =
2916 result.add_with_paint_transform(Some(Matrix4::IDENTITY), position, |_, position| {
2917 positions.push(position);
2918 true
2919 });
2920 assert!(is_hit);
2921 assert_eq!(positions, [position]);
2922 positions.clear();
2923
2924 let is_hit = result.add_with_paint_transform(
2925 Some(Matrix4::translation(20.0, 30.0)),
2926 position,
2927 |_, position| {
2928 positions.push(position);
2929 true
2930 },
2931 );
2932 assert!(is_hit);
2933 assert_eq!(positions, [position - Offset::new(20.0, 30.0)]);
2934 positions.clear();
2935
2936 let is_hit = result.add_with_paint_transform(
2937 Some(force_to_point(position)), position,
2939 |_, position| {
2940 positions.push(position);
2941 true
2942 },
2943 );
2944 assert!(!is_hit);
2945 assert!(positions.is_empty());
2946 }
2947
2948 #[test]
2953 fn a_hit_test_through_a_perspective_transform_lands_where_flutters_does() {
2954 let angle = 0.5_f64;
2955 let (cos, sin) = (angle.cos(), angle.sin());
2956 let perspective = 0.001;
2957 let mut storage = Matrix4::IDENTITY.to_flutter_array();
2958 storage[0] = cos as f32;
2959 storage[2] = -sin as f32;
2960 storage[8] = sin as f32;
2961 storage[10] = cos as f32;
2962 storage[3] = (-perspective * sin) as f32;
2964 storage[11] = (perspective * cos) as f32;
2965 let transform = Matrix4::from_flutter_array(&storage);
2966
2967 let mut base = HitTestResult::new();
2968 let mut result = BoxHitTestResult::wrap(&mut base);
2969 let position = Offset::new(100.0, 50.0);
2970 let mut landed = None;
2971 let is_hit = result.add_with_paint_transform(Some(transform), position, |result, local| {
2972 result.add(HitTestEntry::new(DummyHitTestTarget));
2973 landed = Some(local);
2974 true
2975 });
2976 assert!(is_hit);
2977
2978 let w = 1.0 + perspective * sin * position.dx() / cos;
2981 let expected = Offset::new(position.dx() / cos / w, position.dy() / w);
2982 let landed = landed.expect("the child was hit-tested");
2983 assert!(
2984 (landed.dx() - expected.dx()).abs() < 1e-3
2985 && (landed.dy() - expected.dy()).abs() < 1e-3,
2986 "{landed:?} != {expected:?}"
2987 );
2988 }
2989
2990 #[test]
2992 fn add_with_paint_offset() {
2993 let mut base = HitTestResult::new();
2994 let mut result = BoxHitTestResult::wrap(&mut base);
2995 let mut positions = Vec::new();
2996
2997 let is_hit = result.add_with_paint_offset(None, Offset::ZERO, |_, position| {
2998 positions.push(position);
2999 true
3000 });
3001 assert!(is_hit);
3002 assert_eq!(positions, [Offset::ZERO]);
3003 positions.clear();
3004
3005 let is_hit = result.add_with_paint_offset(
3006 Some(Offset::new(55.0, 32.0)),
3007 Offset::ZERO,
3008 |_, position| {
3009 positions.push(position);
3010 true
3011 },
3012 );
3013 assert!(is_hit);
3014 assert_eq!(positions, [Offset::new(-55.0, -32.0)]);
3015 positions.clear();
3016
3017 let position = Offset::new(3.0, 4.0);
3018 let is_hit = result.add_with_paint_offset(
3019 Some(Offset::new(55.0, 32.0)),
3020 position,
3021 |result, position| {
3022 result.add(HitTestEntry::new(DummyHitTestTarget));
3023 positions.push(position);
3024 true
3025 },
3026 );
3027 assert!(is_hit);
3028 assert_eq!(positions, [position - Offset::new(55.0, 32.0)]);
3029 assert_eq!(
3030 result.path()[0].transform(),
3031 Some(Matrix4::translation(-55.0, -32.0)),
3032 "the entry records the transform to the child"
3033 );
3034 }
3035
3036 #[test]
3038 fn add_with_raw_transform() {
3039 let mut base = HitTestResult::new();
3040 let mut result = BoxHitTestResult::wrap(&mut base);
3041 let mut positions = Vec::new();
3042
3043 let is_hit = result.add_with_raw_transform(
3044 Some(Matrix4::translation(20.0, 30.0)),
3045 Offset::ZERO,
3046 |_, position| {
3047 positions.push(position);
3048 true
3049 },
3050 );
3051 assert!(is_hit);
3052 assert_eq!(positions, [Offset::new(20.0, 30.0)]);
3053 positions.clear();
3054
3055 let position = Offset::new(3.0, 4.0);
3056 let is_hit =
3057 result.add_with_raw_transform(Some(Matrix4::IDENTITY), position, |_, position| {
3058 positions.push(position);
3059 true
3060 });
3061 assert!(is_hit);
3062 assert_eq!(positions, [position]);
3063 }
3064}
3065
3066#[cfg(test)]
3067mod intrinsics_tests {
3068 use std::cell::Cell;
3069 use std::rc::Rc;
3070 use waft_foundation::AppCell;
3071
3072 use super::*;
3073 use crate::object::RenderObjectData;
3074
3075 struct CountingBox {
3078 render_object: RenderObjectData,
3079 render_box: RenderBoxData,
3080 computations: Rc<Cell<u32>>,
3081 }
3082
3083 impl RenderObject for CountingBox {
3084 crate::render_object_accessors!();
3085
3086 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3087 let size = self.constraints(app).smallest();
3088 self.set_size(app, size);
3089 }
3090 }
3091
3092 impl RenderBox for CountingBox {
3093 crate::render_box_accessors!();
3094
3095 fn compute_min_intrinsic_width(
3096 self: RenderHandle<Self>,
3097 app: &mut App,
3098 height: f64,
3099 ) -> f64 {
3100 let computations = self.get(app).computations.clone();
3101 computations.set(computations.get() + 1);
3102 100.0 + height
3103 }
3104 }
3105
3106 #[test]
3109 fn the_intrinsic_cache_is_reused_and_cleared_by_mark_needs_layout() {
3110 let cell = AppCell::new();
3111 let mut app = cell.borrow_mut();
3112 let computations = Rc::new(Cell::new(0));
3113 let box_ = RenderHandle::new_box(
3114 &mut app,
3115 CountingBox {
3116 render_object: RenderObjectData::new(),
3117 render_box: RenderBoxData::new(),
3118 computations: computations.clone(),
3119 },
3120 );
3121
3122 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3123 assert_eq!(computations.get(), 1);
3124
3125 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3126 assert_eq!(computations.get(), 1, "the memoized value is reused");
3127
3128 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 10.0), 110.0);
3129 assert_eq!(computations.get(), 2, "another height is another entry");
3130
3131 RenderBox::mark_needs_layout(box_, &mut app);
3132 assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3133 assert_eq!(computations.get(), 3, "mark_needs_layout cleared the cache");
3134 }
3135
3136 #[test]
3139 fn clearing_a_cached_intrinsic_marks_the_parent() {
3140 let cell = AppCell::new();
3141 let mut app = cell.borrow_mut();
3142 let computations = Rc::new(Cell::new(0));
3143 let child = RenderHandle::new_box(
3144 &mut app,
3145 CountingBox {
3146 render_object: RenderObjectData::new(),
3147 render_box: RenderBoxData::new(),
3148 computations,
3149 },
3150 );
3151 let parent = crate::proxy_box::RenderConstrainedBox::new(
3152 &mut app,
3153 BoxConstraints::new(),
3154 Some(child.as_box()),
3155 );
3156 parent.layout(&mut app, BoxConstraints::new().max_width(50.0), false);
3157 assert!(!parent.debug_needs_layout(&app));
3158
3159 child.as_box().get_min_intrinsic_width(&mut app, 0.0);
3160 RenderBox::mark_needs_layout(child, &mut app);
3161 assert!(
3162 parent.debug_needs_layout(&app),
3163 "the parent read an intrinsic, so it has to lay out again"
3164 );
3165 }
3166}
3167
3168#[cfg(test)]
3169mod any_box_constraints_tests {
3170 use std::cell::Cell;
3171 use std::rc::Rc;
3172 use waft_foundation::{AppCell, ValueKey};
3173
3174 use super::*;
3175 use crate::custom_layout::{
3176 ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
3177 MultiChildLayoutParentData, RenderCustomMultiChildLayoutBox,
3178 };
3179 use crate::object::RenderObjectData;
3180 use crate::proxy_box::RenderOpacity;
3181
3182 #[derive(Debug)]
3184 struct Inset(f64);
3185
3186 impl BoxConstraintsExtension for Inset {
3187 fn as_any(&self) -> &dyn Any {
3188 self
3189 }
3190
3191 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3192 other
3193 .as_any()
3194 .downcast_ref::<Inset>()
3195 .is_some_and(|other| other.0 == self.0)
3196 }
3197 }
3198
3199 #[derive(Debug)]
3201 struct Other(f64);
3202
3203 impl BoxConstraintsExtension for Other {
3204 fn as_any(&self) -> &dyn Any {
3205 self
3206 }
3207
3208 fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3209 other
3210 .as_any()
3211 .downcast_ref::<Other>()
3212 .is_some_and(|other| other.0 == self.0)
3213 }
3214 }
3215
3216 fn inset(constraints: BoxConstraints, inset: f64) -> AnyBoxConstraints {
3217 AnyBoxConstraints::with_shared(constraints, Rc::new(Inset(inset)))
3218 }
3219
3220 fn inset_of(constraints: &AnyBoxConstraints) -> Option<f64> {
3221 constraints.extension::<Inset>().map(|inset| inset.0)
3222 }
3223
3224 struct CountingLeaf {
3226 render_object: RenderObjectData,
3227 render_box: RenderBoxData,
3228 layouts: Rc<Cell<u32>>,
3229 }
3230
3231 impl RenderObject for CountingLeaf {
3232 crate::render_object_accessors!();
3233
3234 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3235 let layouts = Rc::clone(&self.get(app).layouts);
3236 layouts.set(layouts.get() + 1);
3237 let size = self.constraints(app).smallest();
3238 self.set_size(app, size);
3239 }
3240 }
3241
3242 impl RenderBox for CountingLeaf {
3243 crate::render_box_accessors!();
3244 }
3245
3246 fn counting_leaf(app: &mut App, layouts: &Rc<Cell<u32>>) -> RenderHandle<CountingLeaf> {
3247 RenderHandle::new_box(
3248 app,
3249 CountingLeaf {
3250 render_object: RenderObjectData::new(),
3251 render_box: RenderBoxData::new(),
3252 layouts: Rc::clone(layouts),
3253 },
3254 )
3255 }
3256
3257 fn child_id() -> ChildLayoutId {
3258 Rc::new(ValueKey::new("child"))
3259 }
3260
3261 #[derive(Debug)]
3264 struct InsetDelegate;
3265
3266 impl MultiChildLayoutDelegate for InsetDelegate {
3267 fn perform_layout(
3268 &self,
3269 app: &mut App,
3270 children: &mut MultiChildLayoutChildren,
3271 size: Size,
3272 ) {
3273 children.layout_child(app, &child_id(), inset(BoxConstraints::loose(size), 3.0));
3274 }
3275
3276 fn should_relayout(&self, _old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
3277 false
3278 }
3279
3280 fn as_any(&self) -> &dyn Any {
3281 self
3282 }
3283 }
3284
3285 #[test]
3286 fn equality_includes_the_subclass_and_its_fields() {
3287 let constraints = BoxConstraints::tight(Size::new(10.0, 20.0));
3288 let plain = AnyBoxConstraints::new(constraints);
3289 let converted: AnyBoxConstraints = constraints.into();
3290 assert!(plain == converted);
3291 assert!(plain == constraints);
3292
3293 assert!(
3294 inset(constraints, 1.0) != plain,
3295 "a plain value never equals a subclass instance, as Dart's runtimeType check"
3296 );
3297 assert!(inset(constraints, 1.0) != constraints);
3298 assert!(inset(constraints, 1.0) == inset(constraints, 1.0));
3299 assert!(inset(constraints, 1.0) != inset(constraints, 2.0));
3300 assert!(
3301 inset(constraints, 1.0)
3302 != AnyBoxConstraints::with_shared(constraints, Rc::new(Other(1.0)))
3303 );
3304 assert!(inset(constraints, 1.0) != inset(BoxConstraints::new(), 1.0));
3305 }
3306
3307 #[test]
3308 fn a_subclass_instance_derefs_to_its_value_and_answers_its_is_check() {
3309 let constraints = BoxConstraints::new().max_width(30.0).max_height(40.0);
3310 let extended = inset(constraints, 5.0);
3311 assert_eq!(extended.constraints(), constraints);
3312 assert_eq!(extended.max_width, 30.0);
3313 assert_eq!(extended.loosen(), constraints.loosen());
3314 assert!(extended.has_extension());
3315 assert_eq!(inset_of(&extended), Some(5.0));
3316 assert!(extended.extension::<Other>().is_none());
3317 assert!(!AnyBoxConstraints::new(constraints).has_extension());
3318 assert_eq!(format!("{extended:?}"), format!("{constraints:?}"));
3319 }
3320
3321 #[test]
3322 fn layout_lays_out_again_when_only_the_subclass_fields_change() {
3323 let cell = AppCell::new();
3324 let mut app = cell.borrow_mut();
3325 let layouts = Rc::new(Cell::new(0));
3326 let leaf = counting_leaf(&mut app, &layouts);
3327 let constraints = BoxConstraints::new().max_width(50.0).max_height(50.0);
3328
3329 leaf.layout(&mut app, inset(constraints, 1.0), false);
3330 assert_eq!(layouts.get(), 1);
3331 assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(1.0));
3332
3333 leaf.layout(&mut app, inset(constraints, 1.0), false);
3334 assert_eq!(layouts.get(), 1, "equal constraints return early");
3335
3336 leaf.layout(&mut app, inset(constraints, 2.0), false);
3337 assert_eq!(layouts.get(), 2, "only the inset changed");
3338 assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(2.0));
3339
3340 leaf.layout(&mut app, constraints, false);
3341 assert_eq!(
3342 layouts.get(),
3343 3,
3344 "a plain value is not the subclass instance"
3345 );
3346 assert!(!leaf.any_constraints(&app).has_extension());
3347 assert_eq!(leaf.constraints(&app), constraints);
3348 }
3349
3350 #[test]
3351 fn a_subclass_instance_reaches_the_child_a_layout_delegate_lays_out() {
3352 let cell = AppCell::new();
3353 let mut app = cell.borrow_mut();
3354 let layouts = Rc::new(Cell::new(0));
3355 let leaf = counting_leaf(&mut app, &layouts);
3356 let parent = RenderCustomMultiChildLayoutBox::new(&mut app, Rc::new(InsetDelegate));
3357 parent.add(&mut app, leaf.as_box());
3358 leaf.as_object()
3359 .parent_data_of_mut::<MultiChildLayoutParentData>(&mut app)
3360 .id = Some(child_id());
3361
3362 parent.layout(
3363 &mut app,
3364 BoxConstraints::tight(Size::new(100.0, 80.0)),
3365 false,
3366 );
3367 assert_eq!(layouts.get(), 1);
3368 let child_constraints = leaf.as_box().any_constraints(&app);
3369 assert_eq!(inset_of(&child_constraints), Some(3.0));
3370 assert_eq!(
3371 leaf.as_box().constraints(&app),
3372 BoxConstraints::loose(Size::new(100.0, 80.0))
3373 );
3374 }
3375
3376 #[test]
3377 fn a_proxy_box_hands_its_child_the_plain_value() {
3378 let cell = AppCell::new();
3379 let mut app = cell.borrow_mut();
3380 let layouts = Rc::new(Cell::new(0));
3381 let leaf = counting_leaf(&mut app, &layouts);
3382 let proxy = RenderOpacity::new(&mut app, 1.0, Some(leaf.as_box()));
3383 let constraints = BoxConstraints::new().max_width(60.0).max_height(70.0);
3384
3385 proxy.layout(&mut app, inset(constraints, 4.0), false);
3386 assert_eq!(inset_of(&proxy.any_constraints(&app)), Some(4.0));
3387 assert!(
3388 !leaf.any_constraints(&app).has_extension(),
3389 "the subclass instance rides one hop: the proxy passes its `constraints()` on"
3390 );
3391 assert_eq!(leaf.constraints(&app), constraints);
3392 }
3393}