use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};
use std::cell::Cell;
use std::ops::{Add, Deref, DerefMut};
use std::rc::Rc;
use waft_embedder::{
Matrix4, Offset, Rect, Size, TextBaseline, ViewConstraints, clamp_double, lerp_double,
};
use waft_foundation::{App, Handle, HandleId};
use waft_gestures::{
HitTestEntry, HitTestResult, HitTestTarget, PointerEvent, remove_perspective_transform,
};
use waft_painting::EdgeInsetsGeometry;
use waft_painting::transform_point;
use crate::object::{
AnyRenderObject, Constraints, ContainerParentDataMixin, ContainerRenderObjectMixin, ParentData,
RenderHandle, RenderObject, RenderObjectVTable, create, debug_checking_intrinsics, resolve,
};
use crate::painting_context::PaintingContext;
use crate::pipeline_owner::PipelineOwner;
thread_local! {
static DEBUG_DOING_BASELINE: Cell<bool> = const { Cell::new(false) };
}
#[derive(Clone, Copy)]
pub struct BoxConstraints {
pub min_width: f64,
pub max_width: f64,
pub min_height: f64,
pub max_height: f64,
}
impl BoxConstraints {
pub const fn new() -> BoxConstraints {
BoxConstraints {
min_width: 0.0,
max_width: f64::INFINITY,
min_height: 0.0,
max_height: f64::INFINITY,
}
}
pub const fn min_width(mut self, value: f64) -> BoxConstraints {
self.min_width = value;
self
}
pub const fn max_width(mut self, value: f64) -> BoxConstraints {
self.max_width = value;
self
}
pub const fn min_height(mut self, value: f64) -> BoxConstraints {
self.min_height = value;
self
}
pub const fn max_height(mut self, value: f64) -> BoxConstraints {
self.max_height = value;
self
}
pub fn tight(size: Size) -> BoxConstraints {
BoxConstraints {
min_width: size.width(),
max_width: size.width(),
min_height: size.height(),
max_height: size.height(),
}
}
pub const fn tight_for(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
BoxConstraints {
min_width: match width {
Some(width) => width,
None => 0.0,
},
max_width: match width {
Some(width) => width,
None => f64::INFINITY,
},
min_height: match height {
Some(height) => height,
None => 0.0,
},
max_height: match height {
Some(height) => height,
None => f64::INFINITY,
},
}
}
pub const fn tight_for_finite(width: f64, height: f64) -> BoxConstraints {
BoxConstraints {
min_width: if width != f64::INFINITY { width } else { 0.0 },
max_width: if width != f64::INFINITY {
width
} else {
f64::INFINITY
},
min_height: if height != f64::INFINITY { height } else { 0.0 },
max_height: if height != f64::INFINITY {
height
} else {
f64::INFINITY
},
}
}
pub fn loose(size: Size) -> BoxConstraints {
BoxConstraints {
min_width: 0.0,
max_width: size.width(),
min_height: 0.0,
max_height: size.height(),
}
}
pub const fn expand(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
BoxConstraints {
min_width: match width {
Some(width) => width,
None => f64::INFINITY,
},
max_width: match width {
Some(width) => width,
None => f64::INFINITY,
},
min_height: match height {
Some(height) => height,
None => f64::INFINITY,
},
max_height: match height {
Some(height) => height,
None => f64::INFINITY,
},
}
}
pub const fn from_view_constraints(constraints: ViewConstraints) -> BoxConstraints {
BoxConstraints {
min_width: constraints.min_width,
max_width: constraints.max_width,
min_height: constraints.min_height,
max_height: constraints.max_height,
}
}
pub const fn copy_with(self) -> BoxConstraints {
self
}
pub fn deflate(self, edges: EdgeInsetsGeometry) -> BoxConstraints {
debug_assert!(self.debug_assert_is_valid(false));
let horizontal = edges.horizontal();
let vertical = edges.vertical();
let deflated_min_width = (self.min_width - horizontal).max(0.0);
let deflated_min_height = (self.min_height - vertical).max(0.0);
BoxConstraints {
min_width: deflated_min_width,
max_width: (self.max_width - horizontal).max(deflated_min_width),
min_height: deflated_min_height,
max_height: (self.max_height - vertical).max(deflated_min_height),
}
}
pub fn loosen(self) -> BoxConstraints {
debug_assert!(self.debug_assert_is_valid(false));
BoxConstraints {
min_width: 0.0,
max_width: self.max_width,
min_height: 0.0,
max_height: self.max_height,
}
}
pub fn enforce(self, constraints: BoxConstraints) -> BoxConstraints {
BoxConstraints {
min_width: clamp_double(self.min_width, constraints.min_width, constraints.max_width),
max_width: clamp_double(self.max_width, constraints.min_width, constraints.max_width),
min_height: clamp_double(
self.min_height,
constraints.min_height,
constraints.max_height,
),
max_height: clamp_double(
self.max_height,
constraints.min_height,
constraints.max_height,
),
}
}
pub fn tighten(self, width: Option<f64>, height: Option<f64>) -> BoxConstraints {
BoxConstraints {
min_width: match width {
Some(width) => clamp_double(width, self.min_width, self.max_width),
None => self.min_width,
},
max_width: match width {
Some(width) => clamp_double(width, self.min_width, self.max_width),
None => self.max_width,
},
min_height: match height {
Some(height) => clamp_double(height, self.min_height, self.max_height),
None => self.min_height,
},
max_height: match height {
Some(height) => clamp_double(height, self.min_height, self.max_height),
None => self.max_height,
},
}
}
pub const fn flipped(self) -> BoxConstraints {
BoxConstraints {
min_width: self.min_height,
max_width: self.max_height,
min_height: self.min_width,
max_height: self.max_width,
}
}
pub const fn width_constraints(self) -> BoxConstraints {
BoxConstraints {
min_width: self.min_width,
max_width: self.max_width,
min_height: 0.0,
max_height: f64::INFINITY,
}
}
pub const fn height_constraints(self) -> BoxConstraints {
BoxConstraints {
min_width: 0.0,
max_width: f64::INFINITY,
min_height: self.min_height,
max_height: self.max_height,
}
}
pub fn constrain_width(self, width: f64) -> f64 {
debug_assert!(self.debug_assert_is_valid(false));
clamp_double(width, self.min_width, self.max_width)
}
pub fn constrain_height(self, height: f64) -> f64 {
debug_assert!(self.debug_assert_is_valid(false));
clamp_double(height, self.min_height, self.max_height)
}
pub fn constrain(self, size: Size) -> Size {
Size::new(
self.constrain_width(size.width()),
self.constrain_height(size.height()),
)
}
pub fn constrain_dimensions(self, width: f64, height: f64) -> Size {
Size::new(self.constrain_width(width), self.constrain_height(height))
}
pub fn constrain_size_and_attempt_to_preserve_aspect_ratio(self, size: Size) -> Size {
if self.is_tight() {
return self.smallest();
}
if size.is_empty() {
return self.constrain(size);
}
let mut width = size.width();
let mut height = size.height();
let aspect_ratio = width / height;
if width > self.max_width {
width = self.max_width;
height = width / aspect_ratio;
}
if height > self.max_height {
height = self.max_height;
width = height * aspect_ratio;
}
if width < self.min_width {
width = self.min_width;
height = width / aspect_ratio;
}
if height < self.min_height {
height = self.min_height;
width = height * aspect_ratio;
}
Size::new(self.constrain_width(width), self.constrain_height(height))
}
pub fn biggest(self) -> Size {
Size::new(
self.constrain_width(f64::INFINITY),
self.constrain_height(f64::INFINITY),
)
}
pub fn smallest(self) -> Size {
Size::new(self.constrain_width(0.0), self.constrain_height(0.0))
}
pub fn has_tight_width(self) -> bool {
self.min_width >= self.max_width
}
pub fn has_tight_height(self) -> bool {
self.min_height >= self.max_height
}
pub fn has_bounded_width(self) -> bool {
self.max_width < f64::INFINITY
}
pub fn has_bounded_height(self) -> bool {
self.max_height < f64::INFINITY
}
pub fn has_infinite_width(self) -> bool {
self.min_width >= f64::INFINITY
}
pub fn has_infinite_height(self) -> bool {
self.min_height >= f64::INFINITY
}
pub fn is_satisfied_by(self, size: Size) -> bool {
debug_assert!(self.debug_assert_is_valid(false));
self.min_width <= size.width()
&& size.width() <= self.max_width
&& self.min_height <= size.height()
&& size.height() <= self.max_height
}
pub fn truncating_div(self, factor: f64) -> BoxConstraints {
BoxConstraints {
min_width: (self.min_width / factor).trunc(),
max_width: (self.max_width / factor).trunc(),
min_height: (self.min_height / factor).trunc(),
max_height: (self.max_height / factor).trunc(),
}
}
pub fn lerp(
a: Option<BoxConstraints>,
b: Option<BoxConstraints>,
t: f64,
) -> Option<BoxConstraints> {
if a == b {
return a;
}
let Some(a) = a else {
return Some((b.unwrap() * t).normalize());
};
let Some(b) = b else {
return Some((a * (1.0 - t)).normalize());
};
debug_assert!(a.debug_assert_is_valid(false));
debug_assert!(b.debug_assert_is_valid(false));
debug_assert!(
(a.min_width.is_finite() && b.min_width.is_finite())
|| (a.min_width == f64::INFINITY && b.min_width == f64::INFINITY),
"Cannot interpolate between finite constraints and unbounded constraints."
);
debug_assert!(
(a.max_width.is_finite() && b.max_width.is_finite())
|| (a.max_width == f64::INFINITY && b.max_width == f64::INFINITY),
"Cannot interpolate between finite constraints and unbounded constraints."
);
debug_assert!(
(a.min_height.is_finite() && b.min_height.is_finite())
|| (a.min_height == f64::INFINITY && b.min_height == f64::INFINITY),
"Cannot interpolate between finite constraints and unbounded constraints."
);
debug_assert!(
(a.max_height.is_finite() && b.max_height.is_finite())
|| (a.max_height == f64::INFINITY && b.max_height == f64::INFINITY),
"Cannot interpolate between finite constraints and unbounded constraints."
);
Some(
BoxConstraints {
min_width: if a.min_width.is_finite() {
lerp_double(Some(a.min_width), Some(b.min_width), t).unwrap()
} else {
f64::INFINITY
},
max_width: if a.max_width.is_finite() {
lerp_double(Some(a.max_width), Some(b.max_width), t).unwrap()
} else {
f64::INFINITY
},
min_height: if a.min_height.is_finite() {
lerp_double(Some(a.min_height), Some(b.min_height), t).unwrap()
} else {
f64::INFINITY
},
max_height: if a.max_height.is_finite() {
lerp_double(Some(a.max_height), Some(b.max_height), t).unwrap()
} else {
f64::INFINITY
},
}
.normalize(),
)
}
pub fn normalize(self) -> BoxConstraints {
if self.is_normalized() {
return self;
}
let min_width = if self.min_width >= 0.0 {
self.min_width
} else {
0.0
};
let min_height = if self.min_height >= 0.0 {
self.min_height
} else {
0.0
};
BoxConstraints {
min_width,
max_width: if min_width > self.max_width {
min_width
} else {
self.max_width
},
min_height,
max_height: if min_height > self.max_height {
min_height
} else {
self.max_height
},
}
}
}
impl Default for BoxConstraints {
fn default() -> BoxConstraints {
BoxConstraints::new()
}
}
impl Constraints for BoxConstraints {
fn is_tight(&self) -> bool {
self.has_tight_width() && self.has_tight_height()
}
fn is_normalized(&self) -> bool {
self.min_width >= 0.0
&& self.min_width <= self.max_width
&& self.min_height >= 0.0
&& self.min_height <= self.max_height
}
fn debug_assert_is_valid(&self, is_applied_constraint: bool) -> bool {
if cfg!(debug_assertions) {
assert!(
!self.min_width.is_nan()
&& !self.max_width.is_nan()
&& !self.min_height.is_nan()
&& !self.max_height.is_nan(),
"BoxConstraints has a NaN value."
);
assert!(
self.min_width >= 0.0,
"BoxConstraints has a negative minimum width."
);
assert!(
self.min_height >= 0.0,
"BoxConstraints has a negative minimum height."
);
assert!(
self.max_width >= self.min_width,
"BoxConstraints has non-normalized width constraints."
);
assert!(
self.max_height >= self.min_height,
"BoxConstraints has non-normalized height constraints."
);
if is_applied_constraint {
assert!(
self.min_width.is_finite(),
"BoxConstraints forces an infinite width."
);
assert!(
self.min_height.is_finite(),
"BoxConstraints forces an infinite height."
);
}
debug_assert!(self.is_normalized());
}
self.is_normalized()
}
}
impl std::ops::Mul<f64> for BoxConstraints {
type Output = BoxConstraints;
fn mul(self, factor: f64) -> BoxConstraints {
BoxConstraints {
min_width: self.min_width * factor,
max_width: self.max_width * factor,
min_height: self.min_height * factor,
max_height: self.max_height * factor,
}
}
}
impl std::ops::Div<f64> for BoxConstraints {
type Output = BoxConstraints;
fn div(self, factor: f64) -> BoxConstraints {
BoxConstraints {
min_width: self.min_width / factor,
max_width: self.max_width / factor,
min_height: self.min_height / factor,
max_height: self.max_height / factor,
}
}
}
impl std::ops::Rem<f64> for BoxConstraints {
type Output = BoxConstraints;
fn rem(self, value: f64) -> BoxConstraints {
BoxConstraints {
min_width: self.min_width % value,
max_width: self.max_width % value,
min_height: self.min_height % value,
max_height: self.max_height % value,
}
}
}
impl PartialEq for BoxConstraints {
fn eq(&self, other: &BoxConstraints) -> bool {
debug_assert!(self.debug_assert_is_valid(false));
debug_assert!(other.debug_assert_is_valid(false));
self.min_width == other.min_width
&& self.max_width == other.max_width
&& self.min_height == other.min_height
&& self.max_height == other.max_height
}
}
impl Eq for BoxConstraints {}
impl Hash for BoxConstraints {
fn hash<H: Hasher>(&self, state: &mut H) {
debug_assert!(self.debug_assert_is_valid(false));
self.min_width.to_bits().hash(state);
self.max_width.to_bits().hash(state);
self.min_height.to_bits().hash(state);
self.max_height.to_bits().hash(state);
}
}
impl Display for BoxConstraints {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let annotation = if self.is_normalized() {
""
} else {
"; NOT NORMALIZED"
};
if self.min_width == f64::INFINITY && self.min_height == f64::INFINITY {
return write!(f, "BoxConstraints(biggest{annotation})");
}
if self.min_width == 0.0
&& self.max_width == f64::INFINITY
&& self.min_height == 0.0
&& self.max_height == f64::INFINITY
{
return write!(f, "BoxConstraints(unconstrained{annotation})");
}
fn describe(min: f64, max: f64, dim: &str) -> String {
if min == max {
format!("{dim}={min:.1}")
} else {
format!("{min:.1}<={dim}<={max:.1}")
}
}
write!(
f,
"BoxConstraints({}, {}{annotation})",
describe(self.min_width, self.max_width, "w"),
describe(self.min_height, self.max_height, "h")
)
}
}
impl Debug for BoxConstraints {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(self, f)
}
}
pub trait BoxConstraintsExtension: Any {
fn as_any(&self) -> &dyn Any;
fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool;
}
#[derive(Clone)]
pub struct AnyBoxConstraints {
constraints: BoxConstraints,
extension: Option<Rc<dyn BoxConstraintsExtension>>,
}
impl AnyBoxConstraints {
pub const fn new(constraints: BoxConstraints) -> AnyBoxConstraints {
AnyBoxConstraints {
constraints,
extension: None,
}
}
pub fn with_shared(
constraints: BoxConstraints,
extension: Rc<dyn BoxConstraintsExtension>,
) -> AnyBoxConstraints {
AnyBoxConstraints {
constraints,
extension: Some(extension),
}
}
pub fn constraints(&self) -> BoxConstraints {
self.constraints
}
pub fn extension<T: BoxConstraintsExtension>(&self) -> Option<&T> {
self.extension
.as_ref()
.and_then(|extension| extension.as_any().downcast_ref::<T>())
}
pub fn has_extension(&self) -> bool {
self.extension.is_some()
}
}
impl Deref for AnyBoxConstraints {
type Target = BoxConstraints;
fn deref(&self) -> &BoxConstraints {
&self.constraints
}
}
impl From<BoxConstraints> for AnyBoxConstraints {
fn from(constraints: BoxConstraints) -> AnyBoxConstraints {
AnyBoxConstraints::new(constraints)
}
}
impl PartialEq for AnyBoxConstraints {
fn eq(&self, other: &AnyBoxConstraints) -> bool {
if self.constraints != other.constraints {
return false;
}
match (&self.extension, &other.extension) {
(None, None) => true,
(Some(mine), Some(theirs)) => mine.eq_extension(&**theirs),
_ => false,
}
}
}
impl PartialEq<BoxConstraints> for AnyBoxConstraints {
fn eq(&self, other: &BoxConstraints) -> bool {
self.extension.is_none() && self.constraints == *other
}
}
impl Debug for AnyBoxConstraints {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.constraints, f)
}
}
pub type BoxHitTest<'r> = dyn FnOnce(&mut BoxHitTestResult<'r>, Offset) -> bool;
pub struct BoxHitTestResult<'a>(&'a mut HitTestResult);
impl<'a> BoxHitTestResult<'a> {
pub fn wrap(result: &'a mut HitTestResult) -> BoxHitTestResult<'a> {
BoxHitTestResult(result)
}
pub fn add_with_paint_transform(
&mut self,
transform: Option<Matrix4>,
position: Offset,
hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
) -> bool {
let transform = match transform {
Some(transform) => match remove_perspective_transform(transform).invert() {
Some(inverted) => Some(inverted),
None => return false,
},
None => None,
};
self.add_with_raw_transform(transform, position, hit_test)
}
pub fn add_with_paint_offset(
&mut self,
offset: Option<Offset>,
position: Offset,
hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
) -> bool {
let transformed_position = match offset {
Some(offset) => position - offset,
None => position,
};
if let Some(offset) = offset {
self.0.push_offset(Offset::ZERO - offset);
}
let is_hit = hit_test(self, transformed_position);
if offset.is_some() {
self.0.pop_transform();
}
is_hit
}
pub fn add_with_raw_transform(
&mut self,
transform: Option<Matrix4>,
position: Offset,
hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
) -> bool {
let transformed_position = match transform {
Some(transform) => transform_point(&transform, position),
None => position,
};
if let Some(transform) = transform {
self.0.push_transform(transform);
}
let is_hit = hit_test(self, transformed_position);
if transform.is_some() {
self.0.pop_transform();
}
is_hit
}
pub fn add_with_out_of_band_position(
&mut self,
paint_offset: Option<Offset>,
paint_transform: Option<Matrix4>,
raw_transform: Option<Matrix4>,
hit_test: impl FnOnce(&mut BoxHitTestResult<'_>) -> bool,
) -> bool {
debug_assert_eq!(
[
paint_offset.is_some(),
paint_transform.is_some(),
raw_transform.is_some()
]
.iter()
.filter(|given| **given)
.count(),
1,
"Exactly one transform or offset argument must be provided."
);
if let Some(paint_offset) = paint_offset {
self.0.push_offset(Offset::ZERO - paint_offset);
} else if let Some(raw_transform) = raw_transform {
self.0.push_transform(raw_transform);
} else {
let paint_transform = paint_transform
.expect("checked")
.invert()
.expect("paint_transform must be invertible.");
self.0.push_transform(paint_transform);
}
let is_hit = hit_test(self);
self.0.pop_transform();
is_hit
}
}
impl Deref for BoxHitTestResult<'_> {
type Target = HitTestResult;
fn deref(&self) -> &HitTestResult {
self.0
}
}
impl DerefMut for BoxHitTestResult<'_> {
fn deref_mut(&mut self) -> &mut HitTestResult {
self.0
}
}
#[derive(Clone, Copy, Debug)]
pub struct BoxHitTestEntry {
target: AnyRenderBox,
local_position: Offset,
}
impl BoxHitTestEntry {
pub fn new(target: AnyRenderBox, local_position: Offset) -> BoxHitTestEntry {
BoxHitTestEntry {
target,
local_position,
}
}
pub fn target(&self) -> AnyRenderBox {
self.target
}
pub fn local_position(&self) -> Offset {
self.local_position
}
}
impl HitTestTarget for BoxHitTestEntry {
fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
self.target.handle_event(app, event, self);
}
fn arena_id(&self) -> Option<HandleId> {
Some(self.target.id)
}
}
impl From<BoxHitTestEntry> for HitTestEntry {
fn from(entry: BoxHitTestEntry) -> HitTestEntry {
HitTestEntry::new(entry)
}
}
#[derive(Clone, Copy, Debug)]
pub struct BoxParentData {
pub offset: Offset,
}
impl BoxParentData {
pub const fn new() -> BoxParentData {
BoxParentData {
offset: Offset::ZERO,
}
}
}
impl Default for BoxParentData {
fn default() -> BoxParentData {
BoxParentData::new()
}
}
impl ParentData for BoxParentData {
fn provide(&self, id: TypeId) -> Option<&dyn Any> {
(id == TypeId::of::<BoxParentData>()).then_some(self)
}
fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
(id == TypeId::of::<BoxParentData>()).then_some(self)
}
}
impl fmt::Display for BoxParentData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "offset={:?}", self.offset)
}
}
pub trait ContainerBoxParentData: ContainerParentDataMixin<ChildType = AnyRenderBox> {
fn box_parent_data(&self) -> &BoxParentData;
fn box_parent_data_mut(&mut self) -> &mut BoxParentData;
fn offset(&self) -> Offset {
self.box_parent_data().offset
}
fn set_offset(&mut self, value: Offset) {
self.box_parent_data_mut().offset = value;
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct BaselineOffset(pub Option<f64>);
impl BaselineOffset {
pub const NO_BASELINE: BaselineOffset = BaselineOffset(None);
pub fn offset(self) -> Option<f64> {
self.0
}
pub fn min_of(self, other: BaselineOffset) -> BaselineOffset {
match (self.0, other.0) {
(Some(lhs), Some(rhs)) => {
if lhs >= rhs {
other
} else {
self
}
}
(Some(_), None) => self,
(None, _) => other,
}
}
}
impl Add<f64> for BaselineOffset {
type Output = BaselineOffset;
fn add(self, offset: f64) -> BaselineOffset {
BaselineOffset(self.0.map(|value| value + offset))
}
}
#[derive(Clone, Copy, Debug)]
pub enum DryLayoutFailure<'a> {
Reason(&'a str),
Error(&'a str),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum IntrinsicDimension {
MinWidth,
MaxWidth,
MinHeight,
MaxHeight,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct DoubleKey(u64);
impl DoubleKey {
fn new(value: f64) -> DoubleKey {
DoubleKey(value.to_bits())
}
}
#[derive(Default)]
struct LayoutCacheStorage {
cached_intrinsic_dimensions: HashMap<(IntrinsicDimension, DoubleKey), f64>,
cached_dry_layout_sizes: HashMap<BoxConstraints, Size>,
cached_alphabetic_baseline: HashMap<BoxConstraints, BaselineOffset>,
cached_ideo_baseline: HashMap<BoxConstraints, BaselineOffset>,
}
impl LayoutCacheStorage {
fn clear(&mut self) -> bool {
let has_cache = !self.cached_dry_layout_sizes.is_empty()
|| !self.cached_intrinsic_dimensions.is_empty()
|| !self.cached_alphabetic_baseline.is_empty()
|| !self.cached_ideo_baseline.is_empty();
if has_cache {
self.cached_dry_layout_sizes.clear();
self.cached_intrinsic_dimensions.clear();
self.cached_alphabetic_baseline.clear();
self.cached_ideo_baseline.clear();
}
has_cache
}
fn baselines(
&mut self,
baseline: TextBaseline,
) -> &mut HashMap<BoxConstraints, BaselineOffset> {
match baseline {
TextBaseline::Alphabetic => &mut self.cached_alphabetic_baseline,
TextBaseline::Ideographic => &mut self.cached_ideo_baseline,
}
}
}
pub struct RenderBoxData {
pub(crate) size: Option<Size>,
pub(crate) constraints: Option<AnyBoxConstraints>,
layout_cache: LayoutCacheStorage,
debug_computing_this_dry_layout: bool,
debug_computing_this_dry_baseline: bool,
}
impl RenderBoxData {
pub fn new() -> RenderBoxData {
RenderBoxData {
size: None,
constraints: None,
layout_cache: LayoutCacheStorage::default(),
debug_computing_this_dry_layout: false,
debug_computing_this_dry_baseline: false,
}
}
pub fn constraints(&self) -> Option<BoxConstraints> {
self.constraints
.as_ref()
.map(AnyBoxConstraints::constraints)
}
}
impl Default for RenderBoxData {
fn default() -> RenderBoxData {
RenderBoxData::new()
}
}
#[macro_export]
macro_rules! render_box_accessors {
() => {
fn render_box_data(
self: $crate::RenderHandle<Self>,
app: &::waft_foundation::App,
) -> &$crate::RenderBoxData {
&self.get(app).render_box
}
fn render_box_data_mut(
self: $crate::RenderHandle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::RenderBoxData {
&mut self.get_mut(app).render_box
}
};
}
fn box_parent_data_of(app: &App, child: AnyRenderObject) -> &BoxParentData {
child
.parent_data(app)
.and_then(|parent_data| parent_data.part::<BoxParentData>())
.expect("parent data is not a BoxParentData")
}
pub trait RenderBoxContainerDefaultsMixin:
ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType: ContainerBoxParentData>
+ RenderBox
{
fn default_compute_distance_to_first_actual_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
debug_assert!(!self.as_object().debug_needs_layout(app));
let mut child = self.first_child(app);
while let Some(current) = child {
let child_parent_data = current
.as_object()
.parent_data_of::<Self::ParentDataType>(app);
let (offset, next_sibling) =
(child_parent_data.offset(), child_parent_data.next_sibling());
if let Some(result) = current.get_distance_to_actual_baseline(app, baseline) {
return Some(result + offset.dy());
}
child = next_sibling;
}
None
}
fn default_compute_distance_to_highest_actual_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
debug_assert!(!self.as_object().debug_needs_layout(app));
let mut min_baseline = BaselineOffset::NO_BASELINE;
let mut child = self.first_child(app);
while let Some(current) = child {
let child_parent_data = current
.as_object()
.parent_data_of::<Self::ParentDataType>(app);
let (offset, next_sibling) =
(child_parent_data.offset(), child_parent_data.next_sibling());
let candidate = BaselineOffset(current.get_distance_to_actual_baseline(app, baseline))
+ offset.dy();
min_baseline = min_baseline.min_of(candidate);
child = next_sibling;
}
min_baseline.offset()
}
fn default_hit_test_children(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
let mut child = self.last_child(app);
while let Some(current) = child {
let child_parent_data = current
.as_object()
.parent_data_of::<Self::ParentDataType>(app);
let (offset, previous_sibling) = (
child_parent_data.offset(),
child_parent_data.previous_sibling(),
);
let is_hit =
result.add_with_paint_offset(Some(offset), position, |result, transformed| {
debug_assert_eq!(transformed, position - offset);
current.hit_test(app, result, transformed)
});
if is_hit {
return true;
}
child = previous_sibling;
}
false
}
fn default_paint(
self: RenderHandle<Self>,
app: &mut App,
context: &mut PaintingContext,
offset: Offset,
) {
let mut child = self.first_child(app);
while let Some(current) = child {
let child_parent_data = current
.as_object()
.parent_data_of::<Self::ParentDataType>(app);
let (child_offset, next_sibling) =
(child_parent_data.offset(), child_parent_data.next_sibling());
context.paint_child(app, current.as_object(), child_offset + offset);
child = next_sibling;
}
}
}
pub trait RenderBox: RenderObject {
fn render_box_data(self: RenderHandle<Self>, app: &App) -> &RenderBoxData;
fn render_box_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderBoxData;
fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
self.render_box_data(app)
.constraints
.as_ref()
.map(AnyBoxConstraints::constraints)
.unwrap_or_else(|| {
panic!("A RenderObject does not have any constraints before it has been laid out.")
})
}
fn any_constraints(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
self.render_box_data(app)
.constraints
.clone()
.unwrap_or_else(|| {
panic!("A RenderObject does not have any constraints before it has been laid out.")
})
}
fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
if !child.parent_data_is::<BoxParentData>(app) {
child.set_parent_data(app, BoxParentData::new());
}
}
fn get_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
self.as_box().get_min_intrinsic_width(app, height)
}
fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
let _ = (self, app, height);
0.0
}
fn get_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
self.as_box().get_max_intrinsic_width(app, height)
}
fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
let _ = (self, app, height);
0.0
}
fn get_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
self.as_box().get_min_intrinsic_height(app, width)
}
fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
let _ = (self, app, width);
0.0
}
fn get_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
self.as_box().get_max_intrinsic_height(app, width)
}
fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
let _ = (self, app, width);
0.0
}
fn get_dry_layout(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
) -> Size {
self.as_box().get_dry_layout(app, constraints)
}
fn compute_dry_layout(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
) -> Size {
let _ = (app, constraints);
self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
"It does not implement RenderBox::compute_dry_layout.",
));
Size::ZERO
}
fn get_dry_baseline(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
) -> Option<f64> {
self.as_box().get_dry_baseline(app, constraints, baseline)
}
fn compute_dry_baseline(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
) -> Option<f64> {
let _ = (app, constraints, baseline);
self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
"It does not implement RenderBox::compute_dry_baseline.",
));
None
}
fn debug_cannot_compute_dry_layout(self: RenderHandle<Self>, failure: DryLayoutFailure<'_>) {
let _ = self;
if !cfg!(debug_assertions) || debug_checking_intrinsics() {
return;
}
match failure {
DryLayoutFailure::Reason(reason) => panic!(
"The {} class does not support dry layout. {reason}",
std::any::type_name::<Self>()
),
DryLayoutFailure::Error(error) => panic!("{error}"),
}
}
fn get_distance_to_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
only_real: bool,
) -> Option<f64> {
self.as_box()
.get_distance_to_baseline(app, baseline, only_real)
}
fn get_distance_to_actual_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
self.as_box().get_distance_to_actual_baseline(app, baseline)
}
fn compute_distance_to_actual_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
let _ = (self, app, baseline);
debug_assert!(
DEBUG_DOING_BASELINE.get(),
"Please see the documentation for compute_distance_to_actual_baseline for the \
required calling conventions of this method."
);
None
}
fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
RenderBoxBase::mark_needs_layout(self, app);
}
fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
RenderBoxBase::perform_resize(self, app);
}
fn size(self: RenderHandle<Self>, app: &App) -> Size {
self.as_box().size(app)
}
fn apply_paint_transform(
self: RenderHandle<Self>,
app: &App,
child: AnyRenderObject,
transform: &mut Matrix4,
) {
debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
let offset = box_parent_data_of(app, child).offset;
crate::object::translate(transform, offset.dx(), offset.dy());
}
fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
Offset::ZERO & self.size(app)
}
fn has_size(self: RenderHandle<Self>, app: &App) -> bool {
self.render_box_data(app).size.is_some()
}
fn handle_event(
self: RenderHandle<Self>,
app: &mut App,
event: &PointerEvent,
entry: &BoxHitTestEntry,
) {
let _ = (self, app, event, entry);
}
fn hit_test(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
RenderBoxBase::hit_test(self, app, result, position)
}
fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
let _ = self;
false
}
fn hit_test_children(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
let _ = (self, app, result, position);
false
}
fn set_size(self: RenderHandle<Self>, app: &mut App, size: Size) {
self.as_box().set_size(app, size)
}
fn layout(
self: RenderHandle<Self>,
app: &mut App,
constraints: impl Into<AnyBoxConstraints>,
parent_uses_size: bool,
) {
self.as_box().layout(app, constraints, parent_uses_size)
}
fn as_box(self: RenderHandle<Self>) -> AnyRenderBox {
AnyRenderBox {
id: self.id(),
vtable: const { &RenderBoxVTable::of::<Self>() },
}
}
fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
self.as_box().as_object()
}
fn adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
self.as_object().adopt_child(app, child)
}
fn drop_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
self.as_object().drop_child(app, child)
}
fn mark_needs_paint(self: RenderHandle<Self>, app: &mut App) {
self.as_object().mark_needs_paint(app)
}
fn mark_needs_composited_layer_update(self: RenderHandle<Self>, app: &mut App) {
self.as_object().mark_needs_composited_layer_update(app)
}
fn mark_needs_compositing_bits_update(self: RenderHandle<Self>, app: &mut App) {
self.as_object().mark_needs_compositing_bits_update(app)
}
fn schedule_initial_layout(self: RenderHandle<Self>, app: &mut App) {
self.as_object().schedule_initial_layout(app)
}
fn parent(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderObject> {
self.as_object().parent(app)
}
fn owner(self: RenderHandle<Self>, app: &App) -> Option<Handle<PipelineOwner>> {
self.as_object().owner(app)
}
fn attached(self: RenderHandle<Self>, app: &App) -> bool {
self.as_object().attached(app)
}
fn debug_needs_layout(self: RenderHandle<Self>, app: &App) -> bool {
self.as_object().debug_needs_layout(app)
}
}
pub trait RenderBoxBase: RenderBox {
fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
if self.render_box_data_mut(app).layout_cache.clear() && self.parent(app).is_some() {
self.as_object().mark_parent_needs_layout(app);
return;
}
crate::object::RenderObjectBase::mark_needs_layout(self, app);
}
fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
let constraints = RenderBox::constraints(self, app);
let size = RenderBox::compute_dry_layout(self, app, constraints);
debug_assert!(size.width().is_finite() && size.height().is_finite());
self.set_size(app, size);
}
fn hit_test(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
debug_assert!(
self.has_size(app),
"Cannot hit test a render box that has never been laid out: {self:?}"
);
if self.size(app).contains(position)
&& (RenderBox::hit_test_children(self, app, result, position)
|| RenderBox::hit_test_self(self, app, position))
{
result.add(BoxHitTestEntry::new(self.as_box(), position).into());
return true;
}
false
}
}
impl<T: RenderBox> RenderBoxBase for T {}
pub(crate) struct RenderBoxVTable {
pub object: RenderObjectVTable,
pub box_data: fn(&App, HandleId) -> &RenderBoxData,
pub box_data_mut: fn(&mut App, HandleId) -> &mut RenderBoxData,
pub hit_test: fn(&mut App, HandleId, &mut BoxHitTestResult<'_>, Offset) -> bool,
pub handle_event: fn(&mut App, HandleId, &PointerEvent, &BoxHitTestEntry),
pub compute_min_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
pub compute_max_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
pub compute_min_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
pub compute_max_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
pub compute_dry_layout: fn(&mut App, HandleId, BoxConstraints) -> Size,
pub compute_dry_baseline: fn(&mut App, HandleId, BoxConstraints, TextBaseline) -> Option<f64>,
pub compute_distance_to_actual_baseline: fn(&mut App, HandleId, TextBaseline) -> Option<f64>,
}
impl RenderBoxVTable {
const fn of<T: RenderBox>() -> RenderBoxVTable {
RenderBoxVTable {
object: RenderObjectVTable::of::<T>(
|app, id, child| <T as RenderBox>::setup_parent_data(resolve(id), app, child),
|app, id| T::paint_bounds(resolve(id), app),
|app, id, child, transform| {
<T as RenderBox>::apply_paint_transform(resolve(id), app, child, transform)
},
|app, id| <T as RenderBox>::perform_resize(resolve(id), app),
|app, id| <T as RenderBox>::mark_needs_layout(resolve(id), app),
Some(|| const { &RenderBoxVTable::of::<T>() }),
None,
),
box_data: |app, id| T::render_box_data(resolve(id), app),
box_data_mut: |app, id| T::render_box_data_mut(resolve(id), app),
hit_test: |app, id, result, position| T::hit_test(resolve(id), app, result, position),
handle_event: |app, id, event, entry| T::handle_event(resolve(id), app, event, entry),
compute_min_intrinsic_width: |app, id, height| {
T::compute_min_intrinsic_width(resolve(id), app, height)
},
compute_max_intrinsic_width: |app, id, height| {
T::compute_max_intrinsic_width(resolve(id), app, height)
},
compute_min_intrinsic_height: |app, id, width| {
T::compute_min_intrinsic_height(resolve(id), app, width)
},
compute_max_intrinsic_height: |app, id, width| {
T::compute_max_intrinsic_height(resolve(id), app, width)
},
compute_dry_layout: |app, id, constraints| {
T::compute_dry_layout(resolve(id), app, constraints)
},
compute_dry_baseline: |app, id, constraints, baseline| {
T::compute_dry_baseline(resolve(id), app, constraints, baseline)
},
compute_distance_to_actual_baseline: |app, id, baseline| {
T::compute_distance_to_actual_baseline(resolve(id), app, baseline)
},
}
}
}
impl<T: RenderBox> RenderHandle<T> {
pub fn new_box(app: &mut App, object: T) -> RenderHandle<T> {
let this = create(app, object);
let data = this.render_object_data_mut(app);
data.object_vtable = Some(&const { RenderBoxVTable::of::<T>() }.object);
let is_repaint_boundary = this.is_repaint_boundary(app);
let always_needs_compositing = this.always_needs_compositing(app);
let data = this.render_object_data_mut(app);
data.was_repaint_boundary = is_repaint_boundary;
data.needs_compositing = is_repaint_boundary || always_needs_compositing;
this
}
}
struct DebugDoingBaseline;
impl DebugDoingBaseline {
fn enter() -> DebugDoingBaseline {
DEBUG_DOING_BASELINE.set(cfg!(debug_assertions));
DebugDoingBaseline
}
}
impl Drop for DebugDoingBaseline {
fn drop(&mut self) {
DEBUG_DOING_BASELINE.set(false);
}
}
fn should_cache_intrinsics(this: AnyRenderBox, app: &App) -> bool {
debug_assert!(debug_checking_intrinsics() || !this.as_object().debug_doing_this_resize(app));
!cfg!(debug_assertions) || !debug_checking_intrinsics()
}
fn memoize_intrinsic(
this: AnyRenderBox,
app: &mut App,
dimension: IntrinsicDimension,
input: f64,
computer: fn(&mut App, HandleId, f64) -> f64,
) -> f64 {
if !should_cache_intrinsics(this, app) {
return computer(app, this.id, input);
}
let key = (dimension, DoubleKey::new(input));
if let Some(cached) = this.layout_cache(app).cached_intrinsic_dimensions.get(&key) {
return *cached;
}
let result = computer(app, this.id, input);
this.layout_cache_mut(app)
.cached_intrinsic_dimensions
.insert(key, result);
result
}
fn memoize_baseline(
this: AnyRenderBox,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
computer: impl FnOnce(AnyRenderBox, &mut App) -> BaselineOffset,
) -> BaselineOffset {
if !should_cache_intrinsics(this, app) {
return computer(this, app);
}
if let Some(cached) = this
.layout_cache_mut(app)
.baselines(baseline)
.get(&constraints)
{
return *cached;
}
let result = computer(this, app);
this.layout_cache_mut(app)
.baselines(baseline)
.insert(constraints, result);
result
}
#[derive(Clone, Copy)]
pub struct AnyRenderBox {
id: HandleId,
vtable: &'static RenderBoxVTable,
}
impl PartialEq for AnyRenderBox {
fn eq(&self, other: &AnyRenderBox) -> bool {
self.id == other.id
}
}
impl Eq for AnyRenderBox {}
impl std::hash::Hash for AnyRenderBox {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Debug for AnyRenderBox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AnyRenderBox({:?})", self.id)
}
}
impl AnyRenderBox {
pub(crate) fn from_vtable(id: HandleId, vtable: &'static RenderBoxVTable) -> AnyRenderBox {
AnyRenderBox { id, vtable }
}
pub fn has_size(self, app: &App) -> bool {
self.box_data(app).size.is_some()
}
pub fn as_object(self) -> AnyRenderObject {
AnyRenderObject::from_vtable(self.id, &self.vtable.object)
}
pub fn hit_test(
self,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
(self.vtable.hit_test)(app, self.id, result, position)
}
pub fn handle_event(self, app: &mut App, event: &PointerEvent, entry: &BoxHitTestEntry) {
(self.vtable.handle_event)(app, self.id, event, entry)
}
fn box_data(self, app: &App) -> &RenderBoxData {
(self.vtable.box_data)(app, self.id)
}
fn box_data_mut(self, app: &mut App) -> &mut RenderBoxData {
(self.vtable.box_data_mut)(app, self.id)
}
pub fn layout(
self,
app: &mut App,
constraints: impl Into<AnyBoxConstraints>,
parent_uses_size: bool,
) {
let constraints: AnyBoxConstraints = constraints.into();
debug_assert!(
!app.is_disposed(self.id),
"layout on a disposed render object"
);
debug_assert!(constraints.debug_assert_is_valid(true));
let same = self.box_data(app).constraints.as_ref() == Some(&constraints);
let tight = constraints.is_tight();
self.as_object()
.run_layout(app, parent_uses_size, tight, same, |app| {
self.box_data_mut(app).constraints = Some(constraints)
});
}
pub fn size(self, app: &App) -> Size {
self.box_data(app)
.size
.unwrap_or_else(|| panic!("RenderBox was not laid out: {self:?}"))
}
pub fn set_size(self, app: &mut App, size: Size) {
self.box_data_mut(app).size = Some(size);
}
pub fn constraints(self, app: &App) -> BoxConstraints {
self.box_data(app)
.constraints
.as_ref()
.map(AnyBoxConstraints::constraints)
.unwrap_or_else(|| {
panic!("A RenderObject does not have any constraints before it has been laid out.")
})
}
pub fn any_constraints(self, app: &App) -> AnyBoxConstraints {
self.box_data(app).constraints.clone().unwrap_or_else(|| {
panic!("A RenderObject does not have any constraints before it has been laid out.")
})
}
pub fn get_min_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
debug_assert!(
height >= 0.0,
"The height argument to get_min_intrinsic_width was negative. If you perform \
computations on another height before passing it to get_min_intrinsic_width, \
consider using f64::max or clamp_double to force the value into the valid range."
);
memoize_intrinsic(
self,
app,
IntrinsicDimension::MinWidth,
height,
self.vtable.compute_min_intrinsic_width,
)
}
pub fn get_max_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
debug_assert!(
height >= 0.0,
"The height argument to get_max_intrinsic_width was negative."
);
memoize_intrinsic(
self,
app,
IntrinsicDimension::MaxWidth,
height,
self.vtable.compute_max_intrinsic_width,
)
}
pub fn get_min_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
debug_assert!(
width >= 0.0,
"The width argument to get_min_intrinsic_height was negative."
);
memoize_intrinsic(
self,
app,
IntrinsicDimension::MinHeight,
width,
self.vtable.compute_min_intrinsic_height,
)
}
pub fn get_max_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
debug_assert!(
width >= 0.0,
"The width argument to get_max_intrinsic_height was negative."
);
memoize_intrinsic(
self,
app,
IntrinsicDimension::MaxHeight,
width,
self.vtable.compute_max_intrinsic_height,
)
}
pub fn get_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
if !should_cache_intrinsics(self, app) {
return self.compute_dry_layout(app, constraints);
}
if let Some(cached) = self
.layout_cache(app)
.cached_dry_layout_sizes
.get(&constraints)
{
return *cached;
}
let result = self.compute_dry_layout(app, constraints);
self.layout_cache_mut(app)
.cached_dry_layout_sizes
.insert(constraints, result);
result
}
fn compute_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
if cfg!(debug_assertions) {
assert!(!self.box_data(app).debug_computing_this_dry_layout);
self.box_data_mut(app).debug_computing_this_dry_layout = true;
}
let result = (self.vtable.compute_dry_layout)(app, self.id, constraints);
if cfg!(debug_assertions) {
self.box_data_mut(app).debug_computing_this_dry_layout = false;
}
result
}
pub fn get_dry_baseline(
self,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
) -> Option<f64> {
let baseline_offset = memoize_baseline(self, app, constraints, baseline, |this, app| {
this.compute_dry_baseline(app, constraints, baseline)
})
.offset();
if cfg!(debug_assertions) && !debug_checking_intrinsics() {
assert_eq!(
baseline_offset,
(self.vtable.compute_dry_baseline)(app, self.id, constraints, baseline)
);
}
baseline_offset
}
fn compute_dry_baseline(
self,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
) -> BaselineOffset {
if cfg!(debug_assertions) {
assert!(!self.box_data(app).debug_computing_this_dry_baseline);
self.box_data_mut(app).debug_computing_this_dry_baseline = true;
}
let result = BaselineOffset((self.vtable.compute_dry_baseline)(
app,
self.id,
constraints,
baseline,
));
if cfg!(debug_assertions) {
self.box_data_mut(app).debug_computing_this_dry_baseline = false;
}
result
}
pub fn get_distance_to_baseline(
self,
app: &mut App,
baseline: TextBaseline,
only_real: bool,
) -> Option<f64> {
debug_assert!(
!DEBUG_DOING_BASELINE.get(),
"Please see the documentation for compute_distance_to_actual_baseline for the \
required calling conventions of this method."
);
debug_assert!(!self.as_object().debug_needs_layout(app) || debug_checking_intrinsics());
let result = {
let _doing_baseline = DebugDoingBaseline::enter();
self.get_distance_to_actual_baseline(app, baseline)
};
match result {
None if !only_real => Some(self.size(app).height()),
result => result,
}
}
pub fn get_distance_to_actual_baseline(
self,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
debug_assert!(
DEBUG_DOING_BASELINE.get() || !cfg!(debug_assertions),
"Please see the documentation for compute_distance_to_actual_baseline for the \
required calling conventions of this method."
);
let constraints = self
.box_data(app)
.constraints
.as_ref()
.map(AnyBoxConstraints::constraints)
.expect("a RenderBox has constraints once it has been laid out");
memoize_baseline(self, app, constraints, baseline, |this, app| {
BaselineOffset((this.vtable.compute_distance_to_actual_baseline)(
app, this.id, baseline,
))
})
.offset()
}
fn layout_cache(self, app: &App) -> &LayoutCacheStorage {
&self.box_data(app).layout_cache
}
fn layout_cache_mut(self, app: &mut App) -> &mut LayoutCacheStorage {
&mut self.box_data_mut(app).layout_cache
}
pub fn box_parent_data(self, app: &App) -> &BoxParentData {
box_parent_data_of(app, self.as_object())
}
pub fn global_to_local(
self,
app: &App,
point: Offset,
ancestor: Option<AnyRenderObject>,
) -> Offset {
let transform = self.as_object().get_transform_to(app, ancestor);
let Some(transform) = transform.invert() else {
return Offset::ZERO;
};
let n = [0.0, 0.0, 1.0];
let i = crate::object::perspective_transform(&transform, [0.0, 0.0, 0.0]);
let d = subtract(
crate::object::perspective_transform(&transform, [0.0, 0.0, 1.0]),
i,
);
let s = crate::object::perspective_transform(&transform, [point.dx(), point.dy(), 0.0]);
let p = subtract(s, scale(d, dot(n, s) / dot(n, d)));
Offset::new(p[0], p[1])
}
pub fn local_to_global(
self,
app: &App,
point: Offset,
ancestor: Option<AnyRenderObject>,
) -> Offset {
waft_painting::transform_point(&self.as_object().get_transform_to(app, ancestor), point)
}
pub fn parent_data_of_mut<P: crate::object::ParentData + 'static>(
self,
app: &mut App,
) -> &mut P {
self.as_object().parent_data_of_mut(app)
}
pub fn parent_data_is<P: crate::object::ParentData + 'static>(self, app: &App) -> bool {
self.as_object().parent_data_is::<P>(app)
}
}
impl crate::object::ErasedRenderObject for AnyRenderBox {
fn as_object(self) -> AnyRenderObject {
AnyRenderBox::as_object(self)
}
fn from_object(object: AnyRenderObject) -> AnyRenderBox {
object
.as_box()
.expect("the render object is not a RenderBox")
}
}
impl From<AnyRenderBox> for AnyRenderObject {
fn from(box_: AnyRenderBox) -> AnyRenderObject {
box_.as_object()
}
}
fn subtract(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn scale(a: [f64; 3], factor: f64) -> [f64; 3] {
[a[0] * factor, a[1] * factor, a[2] * factor]
}
fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_string_marks_biggest_unconstrained_and_tight() {
assert!(
BoxConstraints::expand(None, None)
.to_string()
.contains("biggest")
);
assert!(BoxConstraints::new().to_string().contains("unconstrained"));
assert!(
BoxConstraints::tight_for(Some(50.0), None)
.to_string()
.contains("w=50")
);
}
#[test]
fn copy_with_replaces_fields() {
let constraints = BoxConstraints::new()
.min_width(3.0)
.max_width(7.0)
.min_height(11.0)
.max_height(17.0);
let copy = constraints.copy_with();
assert_eq!(copy, constraints);
let copy = constraints
.copy_with()
.min_width(13.0)
.max_width(17.0)
.min_height(111.0)
.max_height(117.0);
assert_eq!(copy.min_width, 13.0);
assert_eq!(copy.max_width, 17.0);
assert_eq!(copy.min_height, 111.0);
assert_eq!(copy.max_height, 117.0);
assert_ne!(copy, constraints);
let mut copy_hasher = std::collections::hash_map::DefaultHasher::new();
let mut original_hasher = std::collections::hash_map::DefaultHasher::new();
copy.hash(&mut copy_hasher);
constraints.hash(&mut original_hasher);
assert_ne!(copy_hasher.finish(), original_hasher.finish());
}
#[test]
fn operators() {
let constraints = BoxConstraints::new()
.min_width(3.0)
.max_width(7.0)
.min_height(11.0)
.max_height(17.0);
let copy = constraints * 2.0;
assert_eq!(copy.min_width, 6.0);
assert_eq!(copy.max_width, 14.0);
assert_eq!(copy.min_height, 22.0);
assert_eq!(copy.max_height, 34.0);
assert_eq!(copy / 2.0, constraints);
let copy = constraints.truncating_div(2.0);
assert_eq!(copy.min_width, 1.0);
assert_eq!(copy.max_width, 3.0);
assert_eq!(copy.min_height, 5.0);
assert_eq!(copy.max_height, 8.0);
let copy = constraints % 3.0;
assert_eq!(copy.min_width, 0.0);
assert_eq!(copy.max_width, 1.0);
assert_eq!(copy.min_height, 2.0);
assert_eq!(copy.max_height, 2.0);
}
#[test]
fn lerp_from_null_and_between() {
assert!(BoxConstraints::lerp(None, None, 0.5).is_none());
let constraints = BoxConstraints::new()
.min_width(3.0)
.max_width(7.0)
.min_height(11.0)
.max_height(17.0);
let copy = BoxConstraints::lerp(None, Some(constraints), 0.5).unwrap();
assert!((copy.min_width - 1.5).abs() < 1e-9);
assert!((copy.max_width - 3.5).abs() < 1e-9);
assert!((copy.min_height - 5.5).abs() < 1e-9);
assert!((copy.max_height - 8.5).abs() < 1e-9);
let copy = BoxConstraints::lerp(Some(constraints), None, 0.5).unwrap();
assert!((copy.min_width - 1.5).abs() < 1e-9);
let copy = BoxConstraints::lerp(
Some(
BoxConstraints::new()
.min_width(13.0)
.max_width(17.0)
.min_height(111.0)
.max_height(117.0),
),
Some(constraints),
0.2,
)
.unwrap();
assert!((copy.min_width - 11.0).abs() < 1e-9);
assert!((copy.max_width - 15.0).abs() < 1e-9);
assert!((copy.min_height - 91.0).abs() < 1e-9);
assert!((copy.max_height - 97.0).abs() < 1e-9);
}
#[test]
fn lerp_unbounded_axes() {
let constraints1 = BoxConstraints::new()
.min_width(f64::INFINITY)
.min_height(10.0)
.max_height(20.0);
let constraints2 = BoxConstraints::new()
.min_width(f64::INFINITY)
.min_height(20.0)
.max_height(30.0);
let constraints3 = BoxConstraints::new()
.min_width(f64::INFINITY)
.min_height(15.0)
.max_height(25.0);
assert_eq!(
BoxConstraints::lerp(Some(constraints1), Some(constraints2), 0.5),
Some(constraints3)
);
}
#[test]
fn lerp_overshoot_is_normalized() {
assert_eq!(
BoxConstraints::lerp(
Some(BoxConstraints::tight_for(None, Some(25.0))),
Some(BoxConstraints::tight_for(None, Some(0.0))),
1.2,
),
Some(BoxConstraints::tight_for(None, Some(0.0)))
);
let lerped = BoxConstraints::lerp(
Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
Some(BoxConstraints::new().max_width(100.0).max_height(100.0)),
-0.1,
)
.unwrap();
assert!(lerped.is_normalized());
assert_eq!(lerped, BoxConstraints::tight(Size::new(11.0, 11.0)));
}
#[test]
fn normalize_raises_inverted_max() {
let constraints = BoxConstraints::new()
.min_width(3.0)
.max_width(2.0)
.min_height(11.0)
.max_height(18.0);
let copy = constraints.normalize();
assert_eq!(copy.min_width, 3.0);
assert_eq!(copy.max_width, 3.0);
assert_eq!(copy.min_height, 11.0);
assert_eq!(copy.max_height, 18.0);
}
#[test]
fn from_view_constraints() {
let unconstrained = BoxConstraints::from_view_constraints(ViewConstraints::default());
assert_eq!(unconstrained, BoxConstraints::new());
let constraints =
BoxConstraints::from_view_constraints(ViewConstraints::new(1.0, 2.0, 3.0, 4.0));
assert_eq!(
constraints,
BoxConstraints::new()
.min_width(1.0)
.max_width(2.0)
.min_height(3.0)
.max_height(4.0)
);
}
#[test]
fn constrain_size_and_attempt_to_preserve_aspect_ratio_empty_size() {
let constraints = BoxConstraints::new()
.min_width(10.0)
.max_width(20.0)
.min_height(10.0)
.max_height(20.0);
let constrained =
constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(Size::new(15.0, 0.0));
assert_eq!(constrained, Size::new(15.0, 10.0));
}
}
#[cfg(test)]
mod hit_test_tests {
use waft_painting::force_to_point;
use super::*;
#[derive(Debug)]
struct DummyHitTestTarget;
impl HitTestTarget for DummyHitTestTarget {
fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
}
#[test]
fn wrapping_shares_the_path() {
let transform = Matrix4::translation(40.0, 150.0);
let mut wrapped = HitTestResult::new();
wrapped.push_transform(transform);
wrapped.add(HitTestEntry::new(DummyHitTestTarget));
assert_eq!(wrapped.path().len(), 1);
assert_eq!(wrapped.path()[0].transform(), Some(transform));
let mut wrapping = BoxHitTestResult::wrap(&mut wrapped);
wrapping.add(HitTestEntry::new(DummyHitTestTarget));
assert_eq!(wrapping.path().len(), 2);
assert_eq!(wrapping.path()[1].transform(), Some(transform));
wrapped.add(HitTestEntry::new(DummyHitTestTarget));
assert_eq!(wrapped.path().len(), 3);
assert_eq!(wrapped.path()[2].transform(), Some(transform));
}
#[test]
fn add_with_paint_transform() {
let mut base = HitTestResult::new();
let mut result = BoxHitTestResult::wrap(&mut base);
let mut positions = Vec::new();
let is_hit = result.add_with_paint_transform(None, Offset::ZERO, |_, position| {
positions.push(position);
true
});
assert!(is_hit);
assert_eq!(positions, [Offset::ZERO]);
positions.clear();
let is_hit = result.add_with_paint_transform(
Some(Matrix4::translation(20.0, 30.0)),
Offset::ZERO,
|_, position| {
positions.push(position);
true
},
);
assert!(is_hit);
assert_eq!(positions, [Offset::new(-20.0, -30.0)]);
positions.clear();
let position = Offset::new(3.0, 4.0);
let is_hit = result.add_with_paint_transform(None, position, |_, position| {
positions.push(position);
false
});
assert!(!is_hit);
assert_eq!(positions, [position]);
positions.clear();
let is_hit =
result.add_with_paint_transform(Some(Matrix4::IDENTITY), position, |_, position| {
positions.push(position);
true
});
assert!(is_hit);
assert_eq!(positions, [position]);
positions.clear();
let is_hit = result.add_with_paint_transform(
Some(Matrix4::translation(20.0, 30.0)),
position,
|_, position| {
positions.push(position);
true
},
);
assert!(is_hit);
assert_eq!(positions, [position - Offset::new(20.0, 30.0)]);
positions.clear();
let is_hit = result.add_with_paint_transform(
Some(force_to_point(position)), position,
|_, position| {
positions.push(position);
true
},
);
assert!(!is_hit);
assert!(positions.is_empty());
}
#[test]
fn a_hit_test_through_a_perspective_transform_lands_where_flutters_does() {
let angle = 0.5_f64;
let (cos, sin) = (angle.cos(), angle.sin());
let perspective = 0.001;
let mut storage = Matrix4::IDENTITY.to_flutter_array();
storage[0] = cos as f32;
storage[2] = -sin as f32;
storage[8] = sin as f32;
storage[10] = cos as f32;
storage[3] = (-perspective * sin) as f32;
storage[11] = (perspective * cos) as f32;
let transform = Matrix4::from_flutter_array(&storage);
let mut base = HitTestResult::new();
let mut result = BoxHitTestResult::wrap(&mut base);
let position = Offset::new(100.0, 50.0);
let mut landed = None;
let is_hit = result.add_with_paint_transform(Some(transform), position, |result, local| {
result.add(HitTestEntry::new(DummyHitTestTarget));
landed = Some(local);
true
});
assert!(is_hit);
let w = 1.0 + perspective * sin * position.dx() / cos;
let expected = Offset::new(position.dx() / cos / w, position.dy() / w);
let landed = landed.expect("the child was hit-tested");
assert!(
(landed.dx() - expected.dx()).abs() < 1e-3
&& (landed.dy() - expected.dy()).abs() < 1e-3,
"{landed:?} != {expected:?}"
);
}
#[test]
fn add_with_paint_offset() {
let mut base = HitTestResult::new();
let mut result = BoxHitTestResult::wrap(&mut base);
let mut positions = Vec::new();
let is_hit = result.add_with_paint_offset(None, Offset::ZERO, |_, position| {
positions.push(position);
true
});
assert!(is_hit);
assert_eq!(positions, [Offset::ZERO]);
positions.clear();
let is_hit = result.add_with_paint_offset(
Some(Offset::new(55.0, 32.0)),
Offset::ZERO,
|_, position| {
positions.push(position);
true
},
);
assert!(is_hit);
assert_eq!(positions, [Offset::new(-55.0, -32.0)]);
positions.clear();
let position = Offset::new(3.0, 4.0);
let is_hit = result.add_with_paint_offset(
Some(Offset::new(55.0, 32.0)),
position,
|result, position| {
result.add(HitTestEntry::new(DummyHitTestTarget));
positions.push(position);
true
},
);
assert!(is_hit);
assert_eq!(positions, [position - Offset::new(55.0, 32.0)]);
assert_eq!(
result.path()[0].transform(),
Some(Matrix4::translation(-55.0, -32.0)),
"the entry records the transform to the child"
);
}
#[test]
fn add_with_raw_transform() {
let mut base = HitTestResult::new();
let mut result = BoxHitTestResult::wrap(&mut base);
let mut positions = Vec::new();
let is_hit = result.add_with_raw_transform(
Some(Matrix4::translation(20.0, 30.0)),
Offset::ZERO,
|_, position| {
positions.push(position);
true
},
);
assert!(is_hit);
assert_eq!(positions, [Offset::new(20.0, 30.0)]);
positions.clear();
let position = Offset::new(3.0, 4.0);
let is_hit =
result.add_with_raw_transform(Some(Matrix4::IDENTITY), position, |_, position| {
positions.push(position);
true
});
assert!(is_hit);
assert_eq!(positions, [position]);
}
}
#[cfg(test)]
mod intrinsics_tests {
use std::cell::Cell;
use std::rc::Rc;
use waft_foundation::AppCell;
use super::*;
use crate::object::RenderObjectData;
struct CountingBox {
render_object: RenderObjectData,
render_box: RenderBoxData,
computations: Rc<Cell<u32>>,
}
impl RenderObject for CountingBox {
crate::render_object_accessors!();
fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
let size = self.constraints(app).smallest();
self.set_size(app, size);
}
}
impl RenderBox for CountingBox {
crate::render_box_accessors!();
fn compute_min_intrinsic_width(
self: RenderHandle<Self>,
app: &mut App,
height: f64,
) -> f64 {
let computations = self.get(app).computations.clone();
computations.set(computations.get() + 1);
100.0 + height
}
}
#[test]
fn the_intrinsic_cache_is_reused_and_cleared_by_mark_needs_layout() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let computations = Rc::new(Cell::new(0));
let box_ = RenderHandle::new_box(
&mut app,
CountingBox {
render_object: RenderObjectData::new(),
render_box: RenderBoxData::new(),
computations: computations.clone(),
},
);
assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
assert_eq!(computations.get(), 1);
assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
assert_eq!(computations.get(), 1, "the memoized value is reused");
assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 10.0), 110.0);
assert_eq!(computations.get(), 2, "another height is another entry");
RenderBox::mark_needs_layout(box_, &mut app);
assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
assert_eq!(computations.get(), 3, "mark_needs_layout cleared the cache");
}
#[test]
fn clearing_a_cached_intrinsic_marks_the_parent() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let computations = Rc::new(Cell::new(0));
let child = RenderHandle::new_box(
&mut app,
CountingBox {
render_object: RenderObjectData::new(),
render_box: RenderBoxData::new(),
computations,
},
);
let parent = crate::proxy_box::RenderConstrainedBox::new(
&mut app,
BoxConstraints::new(),
Some(child.as_box()),
);
parent.layout(&mut app, BoxConstraints::new().max_width(50.0), false);
assert!(!parent.debug_needs_layout(&app));
child.as_box().get_min_intrinsic_width(&mut app, 0.0);
RenderBox::mark_needs_layout(child, &mut app);
assert!(
parent.debug_needs_layout(&app),
"the parent read an intrinsic, so it has to lay out again"
);
}
}
#[cfg(test)]
mod any_box_constraints_tests {
use std::cell::Cell;
use std::rc::Rc;
use waft_foundation::{AppCell, ValueKey};
use super::*;
use crate::custom_layout::{
ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
MultiChildLayoutParentData, RenderCustomMultiChildLayoutBox,
};
use crate::object::RenderObjectData;
use crate::proxy_box::RenderOpacity;
#[derive(Debug)]
struct Inset(f64);
impl BoxConstraintsExtension for Inset {
fn as_any(&self) -> &dyn Any {
self
}
fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
other
.as_any()
.downcast_ref::<Inset>()
.is_some_and(|other| other.0 == self.0)
}
}
#[derive(Debug)]
struct Other(f64);
impl BoxConstraintsExtension for Other {
fn as_any(&self) -> &dyn Any {
self
}
fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
other
.as_any()
.downcast_ref::<Other>()
.is_some_and(|other| other.0 == self.0)
}
}
fn inset(constraints: BoxConstraints, inset: f64) -> AnyBoxConstraints {
AnyBoxConstraints::with_shared(constraints, Rc::new(Inset(inset)))
}
fn inset_of(constraints: &AnyBoxConstraints) -> Option<f64> {
constraints.extension::<Inset>().map(|inset| inset.0)
}
struct CountingLeaf {
render_object: RenderObjectData,
render_box: RenderBoxData,
layouts: Rc<Cell<u32>>,
}
impl RenderObject for CountingLeaf {
crate::render_object_accessors!();
fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
let layouts = Rc::clone(&self.get(app).layouts);
layouts.set(layouts.get() + 1);
let size = self.constraints(app).smallest();
self.set_size(app, size);
}
}
impl RenderBox for CountingLeaf {
crate::render_box_accessors!();
}
fn counting_leaf(app: &mut App, layouts: &Rc<Cell<u32>>) -> RenderHandle<CountingLeaf> {
RenderHandle::new_box(
app,
CountingLeaf {
render_object: RenderObjectData::new(),
render_box: RenderBoxData::new(),
layouts: Rc::clone(layouts),
},
)
}
fn child_id() -> ChildLayoutId {
Rc::new(ValueKey::new("child"))
}
#[derive(Debug)]
struct InsetDelegate;
impl MultiChildLayoutDelegate for InsetDelegate {
fn perform_layout(
&self,
app: &mut App,
children: &mut MultiChildLayoutChildren,
size: Size,
) {
children.layout_child(app, &child_id(), inset(BoxConstraints::loose(size), 3.0));
}
fn should_relayout(&self, _old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
false
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[test]
fn equality_includes_the_subclass_and_its_fields() {
let constraints = BoxConstraints::tight(Size::new(10.0, 20.0));
let plain = AnyBoxConstraints::new(constraints);
let converted: AnyBoxConstraints = constraints.into();
assert!(plain == converted);
assert!(plain == constraints);
assert!(
inset(constraints, 1.0) != plain,
"a plain value never equals a subclass instance, as Dart's runtimeType check"
);
assert!(inset(constraints, 1.0) != constraints);
assert!(inset(constraints, 1.0) == inset(constraints, 1.0));
assert!(inset(constraints, 1.0) != inset(constraints, 2.0));
assert!(
inset(constraints, 1.0)
!= AnyBoxConstraints::with_shared(constraints, Rc::new(Other(1.0)))
);
assert!(inset(constraints, 1.0) != inset(BoxConstraints::new(), 1.0));
}
#[test]
fn a_subclass_instance_derefs_to_its_value_and_answers_its_is_check() {
let constraints = BoxConstraints::new().max_width(30.0).max_height(40.0);
let extended = inset(constraints, 5.0);
assert_eq!(extended.constraints(), constraints);
assert_eq!(extended.max_width, 30.0);
assert_eq!(extended.loosen(), constraints.loosen());
assert!(extended.has_extension());
assert_eq!(inset_of(&extended), Some(5.0));
assert!(extended.extension::<Other>().is_none());
assert!(!AnyBoxConstraints::new(constraints).has_extension());
assert_eq!(format!("{extended:?}"), format!("{constraints:?}"));
}
#[test]
fn layout_lays_out_again_when_only_the_subclass_fields_change() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let layouts = Rc::new(Cell::new(0));
let leaf = counting_leaf(&mut app, &layouts);
let constraints = BoxConstraints::new().max_width(50.0).max_height(50.0);
leaf.layout(&mut app, inset(constraints, 1.0), false);
assert_eq!(layouts.get(), 1);
assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(1.0));
leaf.layout(&mut app, inset(constraints, 1.0), false);
assert_eq!(layouts.get(), 1, "equal constraints return early");
leaf.layout(&mut app, inset(constraints, 2.0), false);
assert_eq!(layouts.get(), 2, "only the inset changed");
assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(2.0));
leaf.layout(&mut app, constraints, false);
assert_eq!(
layouts.get(),
3,
"a plain value is not the subclass instance"
);
assert!(!leaf.any_constraints(&app).has_extension());
assert_eq!(leaf.constraints(&app), constraints);
}
#[test]
fn a_subclass_instance_reaches_the_child_a_layout_delegate_lays_out() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let layouts = Rc::new(Cell::new(0));
let leaf = counting_leaf(&mut app, &layouts);
let parent = RenderCustomMultiChildLayoutBox::new(&mut app, Rc::new(InsetDelegate));
parent.add(&mut app, leaf.as_box());
leaf.as_object()
.parent_data_of_mut::<MultiChildLayoutParentData>(&mut app)
.id = Some(child_id());
parent.layout(
&mut app,
BoxConstraints::tight(Size::new(100.0, 80.0)),
false,
);
assert_eq!(layouts.get(), 1);
let child_constraints = leaf.as_box().any_constraints(&app);
assert_eq!(inset_of(&child_constraints), Some(3.0));
assert_eq!(
leaf.as_box().constraints(&app),
BoxConstraints::loose(Size::new(100.0, 80.0))
);
}
#[test]
fn a_proxy_box_hands_its_child_the_plain_value() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let layouts = Rc::new(Cell::new(0));
let leaf = counting_leaf(&mut app, &layouts);
let proxy = RenderOpacity::new(&mut app, 1.0, Some(leaf.as_box()));
let constraints = BoxConstraints::new().max_width(60.0).max_height(70.0);
proxy.layout(&mut app, inset(constraints, 4.0), false);
assert_eq!(inset_of(&proxy.any_constraints(&app)), Some(4.0));
assert!(
!leaf.any_constraints(&app).has_extension(),
"the subclass instance rides one hop: the proxy passes its `constraints()` on"
);
assert_eq!(leaf.constraints(&app), constraints);
}
}