use std::any::{Any, TypeId};
use std::fmt;
use std::rc::Rc;
use waft_embedder::{Offset, Size, TextBaseline};
use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
use waft_rendering::{
AnyBoxConstraints, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult,
DryLayoutFailure, PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject,
RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
RenderObjectWithLayoutCallbackData, RenderObjectWithLayoutCallbackMixin,
debug_checking_intrinsics,
};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
use crate::framework::{
AnyElement, BuildContext, BuildScope, BuildScopeCallback, Element, ElementData, KeyRef,
RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
Slot, Widget, WidgetKind, WidgetRef, downcast_widget,
};
use crate::view::View;
pub type LayoutWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef>;
pub struct LayoutBuilder {
pub key: Option<KeyRef>,
pub builder: LayoutWidgetBuilder,
}
impl LayoutBuilder {
pub fn new(
builder: impl Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef + 'static,
) -> LayoutBuilder {
LayoutBuilder {
key: None,
builder: Rc::new(builder),
}
}
pub fn key(mut self, key: KeyRef) -> LayoutBuilder {
self.key = Some(key);
self
}
pub fn into_widget(self) -> WidgetRef {
Rc::new(self)
}
pub fn update_should_rebuild(&self, old_widget: &LayoutBuilder) -> bool {
let _ = old_widget;
true
}
}
impl fmt::Debug for LayoutBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LayoutBuilder").finish_non_exhaustive()
}
}
impl Widget for LayoutBuilder {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
LayoutBuilderElement::new(app, this).as_element()
}
fn as_any(&self) -> &dyn Any {
self
}
fn widget_type(&self) -> TypeId {
TypeId::of::<LayoutBuilder>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
}
impl RenderObjectWidget for LayoutBuilder {
type RenderObject = RenderLayoutBuilder;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
RenderLayoutBuilder::new(app).as_object()
}
fn update_render_object(
&self,
_app: &mut App,
_context: BuildContext,
_render_object: RenderHandle<RenderLayoutBuilder>,
) {
}
}
pub struct LayoutBuilderElement {
element: ElementData,
render_object_element: RenderObjectElementData,
child: Option<AnyElement>,
build_scope: Option<Ref<BuildScope>>,
deferred_callback_scheduled: bool,
previous_layout_info: Option<AnyBoxConstraints>,
needs_build: bool,
}
impl LayoutBuilderElement {
fn new(app: &mut App, widget: WidgetRef) -> Handle<LayoutBuilderElement> {
debug_assert!(downcast_widget::<LayoutBuilder>(&*widget).is_some());
let this = app
.create(LayoutBuilderElement {
element: ElementData::new(widget),
render_object_element: RenderObjectElementData::default(),
child: None,
build_scope: None,
deferred_callback_scheduled: false,
previous_layout_info: None,
needs_build: true,
})
.into_tree_node(app);
let build_scope = BuildScope::new(
app,
Some(Listener::handle_method(this, Self::schedule_rebuild)),
);
app.get_mut(this).build_scope = Some(build_scope);
this
}
fn render_layout_builder(self: Handle<Self>, app: &App) -> RenderHandle<RenderLayoutBuilder> {
self.typed_render_object(app)
}
fn schedule_rebuild(self: Handle<Self>, app: &mut App) {
if app.get(self).deferred_callback_scheduled {
return;
}
let defer_mark_needs_layout = match SchedulerBinding::scheduler_phase(app) {
SchedulerPhase::Idle | SchedulerPhase::PostFrameCallbacks => true,
SchedulerPhase::TransientCallbacks
| SchedulerPhase::MidFrameMicrotasks
| SchedulerPhase::PersistentCallbacks => false,
};
if !defer_mark_needs_layout {
self.render_layout_builder(app)
.schedule_layout_callback(app);
return;
}
app.get_mut(self).deferred_callback_scheduled = true;
SchedulerBinding::schedule_frame_callback(
app,
FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
View::maybe_id_of(app, self.as_element()),
false,
true,
);
}
fn frame_callback(self: Handle<Self>, app: &mut App) {
app.get_mut(self).deferred_callback_scheduled = false;
if self.as_element().mounted(app) {
self.render_layout_builder(app)
.schedule_layout_callback(app);
}
}
fn rebuild_with_constraints(self: Handle<Self>, app: &mut App) {
let render_object = self.render_layout_builder(app);
let layout_info = render_object.layout_info(app);
let this = self.as_element();
let needs_callback = app.get(self).needs_build
|| Some(&layout_info) != app.get(self).previous_layout_info.as_ref();
let callback: Option<BuildScopeCallback> = needs_callback.then(|| {
Box::new(move |app: &mut App| {
debug_assert!(layout_info == render_object.layout_info(app));
let builder = Self::widget_of(this.widget(app)).builder.clone();
let built = builder(app, this, layout_info.clone());
let child = app.get(self).child;
let child = this.update_child(app, child, Some(built), None);
debug_assert!(child.is_some());
let state = app.get_mut(self);
state.child = child;
state.needs_build = false;
state.previous_layout_info = Some(layout_info);
}) as BuildScopeCallback
});
let owner = this.owner(app).expect("a laying-out element has an owner");
owner.build_scope(app, this, callback);
}
}
impl RenderObjectElementWidget for LayoutBuilderElement {
type Widget = LayoutBuilder;
fn widget_of(widget: &WidgetRef) -> &LayoutBuilder {
downcast_widget::<LayoutBuilder>(&**widget)
.expect("a LayoutBuilderElement holds its widget")
}
}
impl RenderObjectElement for LayoutBuilderElement {
fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
&app.get(self).render_object_element
}
fn render_object_element_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut RenderObjectElementData {
&mut app.get_mut(self).render_object_element
}
}
impl Element for LayoutBuilderElement {
crate::element_accessors!();
const IS_RENDER_OBJECT_ELEMENT: bool = true;
fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
self.render_object_element_data(app).render_object()
}
fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
None
}
fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
false
}
fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
app.get(self)
.build_scope
.handle()
.expect("created with the element")
}
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
if let Some(child) = app.get(self).child {
visitor(child);
}
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
debug_assert!(app.get(self).child == Some(child));
app.get_mut(self).child = None;
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
RenderObjectElement::mount(self, app, parent, new_slot); let render_object = self.render_layout_builder(app);
render_object.update_callback(
app,
Listener::handle_method(self, Self::rebuild_with_constraints),
);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
let old_widget = self.as_element().widget(app).clone();
debug_assert!(!Rc::ptr_eq(&old_widget, &new_widget));
RenderObjectElement::update(self, app, new_widget.clone());
let render_object = self.render_layout_builder(app);
render_object.update_callback(
app,
Listener::handle_method(self, Self::rebuild_with_constraints),
);
if Self::widget_of(&new_widget).update_should_rebuild(Self::widget_of(&old_widget)) {
app.get_mut(self).needs_build = true;
render_object.schedule_layout_callback(app);
}
}
fn mark_needs_build(self: Handle<Self>, app: &mut App) {
self.render_layout_builder(app)
.schedule_layout_callback(app);
app.get_mut(self).needs_build = true;
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
self.render_layout_builder(app)
.schedule_layout_callback(app);
app.get_mut(self).needs_build = true;
RenderObjectElement::perform_rebuild(self, app); }
fn deactivate(self: Handle<Self>, app: &mut App) {
RenderObjectElement::deactivate(self, app);
}
fn unmount(self: Handle<Self>, app: &mut App) {
let render_object = self.render_layout_builder(app);
render_object.set_callback(app, None);
RenderObjectElement::unmount(self, app);
}
fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
RenderObjectElement::update_parent_data(self, app, parent_data_element);
}
fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderObjectElement::update_slot(self, app, new_slot);
}
fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderObjectElement::attach_render_object(self, app, new_slot);
}
fn detach_render_object(self: Handle<Self>, app: &mut App) {
RenderObjectElement::detach_render_object(self, app);
}
fn insert_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
debug_assert!(slot.is_none());
let render_object = self.render_layout_builder(app);
render_object.set_child(app, Some(child.as_box().expect("a box child")));
}
fn move_render_object_child(
self: Handle<Self>,
_app: &mut App,
_child: AnyRenderObject,
_old_slot: Option<Slot>,
_new_slot: Option<Slot>,
) {
debug_assert!(false, "a layout builder has one child");
}
fn remove_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
_slot: Option<Slot>,
) {
let render_object = self.render_layout_builder(app);
debug_assert!(render_object.child(app).map(|current| current.as_object()) == Some(child));
render_object.set_child(app, None);
}
}
pub trait RenderAbstractLayoutBuilderMixin: RenderObjectWithLayoutCallbackMixin {
fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener>;
fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>);
fn update_callback(self: RenderHandle<Self>, app: &mut App, value: Listener) {
if self.callback(app).as_ref() == Some(&value) {
return;
}
self.set_callback(app, Some(value));
self.schedule_layout_callback(app);
}
fn layout_info(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
self.any_constraints(app)
}
}
pub struct RenderLayoutBuilder {
render_object: RenderObjectData,
render_box: RenderBoxData,
child: RenderObjectWithChildData<AnyRenderBox>,
layout_callback: RenderObjectWithLayoutCallbackData,
callback: Option<Listener>,
}
impl RenderLayoutBuilder {
pub fn new(app: &mut App) -> RenderHandle<RenderLayoutBuilder> {
RenderHandle::new_box(
app,
RenderLayoutBuilder {
render_object: RenderObjectData::default(),
render_box: RenderBoxData::default(),
child: RenderObjectWithChildData::default(),
layout_callback: RenderObjectWithLayoutCallbackData::default(),
callback: None,
},
)
}
}
impl RenderObjectWithChildMixin for RenderLayoutBuilder {
type ChildType = AnyRenderBox;
fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
&self.get(app).child
}
fn child_data_mut(
self: RenderHandle<Self>,
app: &mut App,
) -> &mut RenderObjectWithChildData<AnyRenderBox> {
&mut self.get_mut(app).child
}
}
impl RenderObjectWithLayoutCallbackMixin for RenderLayoutBuilder {
fn layout_callback_data(
self: RenderHandle<Self>,
app: &App,
) -> &RenderObjectWithLayoutCallbackData {
&self.get(app).layout_callback
}
fn layout_callback_data_mut(
self: RenderHandle<Self>,
app: &mut App,
) -> &mut RenderObjectWithLayoutCallbackData {
&mut self.get_mut(app).layout_callback
}
fn layout_callback(self: RenderHandle<Self>, app: &mut App) {
let callback = self
.get(app)
.callback
.clone()
.expect("a callback is set before layout");
callback.call(app);
}
}
impl RenderAbstractLayoutBuilderMixin for RenderLayoutBuilder {
fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener> {
self.get(app).callback.clone()
}
fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>) {
self.get_mut(app).callback = callback;
}
}
impl RenderObject for RenderLayoutBuilder {
waft_rendering::render_object_accessors!();
fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
let constraints = self.constraints(app);
self.run_layout_callback(app);
if let Some(child) = self.child(app) {
child.layout(app, constraints, true);
let size = constraints.constrain(child.size(app));
self.set_size(app, size);
} else {
self.set_size(app, constraints.biggest());
}
}
fn paint(
self: RenderHandle<Self>,
app: &mut App,
context: &mut PaintingContext,
offset: Offset,
) {
if let Some(child) = self.child(app) {
context.paint_child(app, child.as_object(), offset);
}
}
fn visit_children(
self: RenderHandle<Self>,
app: &App,
visitor: &mut dyn FnMut(AnyRenderObject),
) {
if let Some(child) = self.child(app) {
visitor(child.as_object());
}
}
}
impl RenderLayoutBuilder {
fn debug_throw_if_not_checking_intrinsics(self: RenderHandle<Self>) -> bool {
let _ = self;
debug_assert!(
debug_checking_intrinsics(),
"LayoutBuilder does not support returning intrinsic dimensions.\n\
Calculating the intrinsic dimensions would require running the layout callback \
speculatively, which might mutate the live render object tree."
);
true
}
}
impl RenderBox for RenderLayoutBuilder {
waft_rendering::render_box_accessors!();
fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
debug_assert!(self.debug_throw_if_not_checking_intrinsics());
0.0
}
fn compute_max_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
debug_assert!(self.debug_throw_if_not_checking_intrinsics());
0.0
}
fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
debug_assert!(self.debug_throw_if_not_checking_intrinsics());
0.0
}
fn compute_max_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
debug_assert!(self.debug_throw_if_not_checking_intrinsics());
0.0
}
fn compute_dry_layout(
self: RenderHandle<Self>,
_app: &mut App,
_constraints: BoxConstraints,
) -> Size {
self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
"Calculating the dry layout would require running the layout callback \
speculatively, which might mutate the live render object tree.",
));
Size::ZERO
}
fn compute_dry_baseline(
self: RenderHandle<Self>,
_app: &mut App,
_constraints: BoxConstraints,
_baseline: TextBaseline,
) -> Option<f64> {
self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
"Calculating the dry baseline would require running the layout callback \
speculatively, which might mutate the live render object tree.",
));
None
}
fn hit_test_children(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
self.child(app)
.is_some_and(|child| child.hit_test(app, result, position))
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use waft_foundation::AppCell;
use waft_embedder::{Size, TextDirection};
use super::*;
use crate::framework::IntoWidget;
use crate::test_harness::Harness;
use crate::widgets::basic::{Directionality, SizedBox};
type Seen = Rc<RefCell<Vec<BoxConstraints>>>;
fn builder(seen: &Seen) -> WidgetRef {
let seen = Rc::clone(seen);
LayoutBuilder::new(move |_app, _context, constraints| {
seen.borrow_mut().push(constraints.constraints());
SizedBox::square(Some(10.0)).into_widget()
})
.into_widget()
}
fn sized(width: f64, child: WidgetRef) -> WidgetRef {
SizedBox::new()
.width(width)
.height(50.0)
.child(child)
.into_widget()
}
#[test]
fn a_layout_builder_goes_wherever_a_widget_is_taken() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let seen: Seen = Rc::default();
let seen_in_builder = Rc::clone(&seen);
let focused = crate::widgets::focus_scope::Focus::new(LayoutBuilder::new(
move |_app, _context, constraints| {
seen_in_builder.borrow_mut().push(constraints.constraints());
SizedBox::square(Some(10.0)).into_widget()
},
));
let harness = Harness::mount(&mut app, focused.into_widget());
harness.pump(&mut app);
assert_eq!(seen.borrow().len(), 1, "the builder ran under the focus");
}
#[test]
fn the_builder_runs_at_layout_with_the_constraints_and_only_when_they_change() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let seen: Seen = Rc::default();
let harness = Harness::mount(&mut app, sized(100.0, builder(&seen)));
harness.pump(&mut app);
assert_eq!(
*seen.borrow(),
vec![BoxConstraints::tight(Size::new(100.0, 50.0))]
);
harness.pump(&mut app);
assert_eq!(seen.borrow().len(), 1);
harness.set_child(&mut app, sized(80.0, builder(&seen)));
harness.pump(&mut app);
assert_eq!(seen.borrow().len(), 2);
assert_eq!(
seen.borrow()[1],
BoxConstraints::tight(Size::new(80.0, 50.0))
);
}
#[derive(Debug)]
struct Inset(f64);
impl waft_rendering::BoxConstraintsExtension for Inset {
fn as_any(&self) -> &dyn Any {
self
}
fn eq_extension(&self, other: &dyn waft_rendering::BoxConstraintsExtension) -> bool {
other
.as_any()
.downcast_ref::<Inset>()
.is_some_and(|other| other.0 == self.0)
}
}
#[derive(Debug)]
struct InsetDelegate(f64);
impl waft_rendering::MultiChildLayoutDelegate for InsetDelegate {
fn perform_layout(
&self,
app: &mut App,
children: &mut waft_rendering::MultiChildLayoutChildren,
size: Size,
) {
children.layout_child(
app,
&child_id(),
AnyBoxConstraints::with_shared(BoxConstraints::loose(size), Rc::new(Inset(self.0))),
);
}
fn should_relayout(
&self,
old_delegate: &dyn waft_rendering::MultiChildLayoutDelegate,
) -> bool {
old_delegate
.as_any()
.downcast_ref::<InsetDelegate>()
.is_none_or(|old_delegate| old_delegate.0 != self.0)
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn child_id() -> waft_rendering::ChildLayoutId {
Rc::new(waft_foundation::ValueKey::new("child"))
}
#[test]
fn the_builder_gets_the_constraints_subclass_and_reruns_when_only_its_fields_change() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let seen = Rc::new(RefCell::new(Vec::new()));
let layout_builder = {
let seen = Rc::clone(&seen);
LayoutBuilder::new(move |_app, _context, constraints| {
seen.borrow_mut().push((
constraints.constraints(),
constraints.extension::<Inset>().map(|inset| inset.0),
));
SizedBox::square(Some(10.0)).into_widget()
})
.into_widget()
};
let layout = |inset: f64| {
sized(
100.0,
crate::widgets::basic::CustomMultiChildLayout::new(Rc::new(InsetDelegate(inset)))
.children([crate::widgets::basic::LayoutId::new(
child_id(),
layout_builder.clone(),
)
.into_widget()])
.into_widget(),
)
};
let loose = BoxConstraints::loose(Size::new(100.0, 50.0));
let harness = Harness::mount(&mut app, layout(1.0));
harness.pump(&mut app);
assert_eq!(*seen.borrow(), vec![(loose, Some(1.0))]);
harness.set_child(&mut app, layout(1.0));
harness.pump(&mut app);
assert_eq!(
seen.borrow().len(),
1,
"equal constraints, the same builder widget"
);
harness.set_child(&mut app, layout(2.0));
harness.pump(&mut app);
assert_eq!(
*seen.borrow(),
vec![(loose, Some(1.0)), (loose, Some(2.0))],
"only the subclass field changed"
);
}
#[test]
fn an_inherited_dependency_change_rebuilds_the_builder_during_layout() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let seen = Rc::new(RefCell::new(Vec::new()));
let dependent = {
let seen = Rc::clone(&seen);
LayoutBuilder::new(move |app, context, _constraints| {
seen.borrow_mut().push(Directionality::of(app, context));
SizedBox::square(Some(10.0)).into_widget()
})
.into_widget()
};
let under = |direction: TextDirection, child: WidgetRef| {
Directionality::new(direction, child).into_widget()
};
let harness = Harness::mount(&mut app, under(TextDirection::Ltr, dependent.clone()));
harness.pump(&mut app);
harness.set_child(&mut app, under(TextDirection::Rtl, dependent));
harness.pump(&mut app);
assert_eq!(*seen.borrow(), vec![TextDirection::Ltr, TextDirection::Rtl]);
}
}