1use std::rc::Rc;
6
7use waft_foundation::{App, Handle, Listener, ValueChanged};
8
9use crate::layer::ErasedLayer;
10use crate::object::AnyRenderObject;
11use crate::painting_context::PaintingContext;
12use waft_foundation::Ref;
13
14pub trait PipelineManifold {
32 fn request_visual_update(&self, app: &mut App);
50}
51
52pub type FlushedPaintCallback = ValueChanged<bool>;
58
59pub struct PipelineOwner {
63 on_need_visual_update: Option<Listener>,
64 on_flushed_paint: Option<FlushedPaintCallback>,
69 manifold: Option<Rc<dyn PipelineManifold>>,
70 root_node: Option<AnyRenderObject>,
71 nodes_needing_layout: Vec<AnyRenderObject>,
72 nodes_needing_compositing_bits_update: Vec<AnyRenderObject>,
73 should_merge_dirty_nodes: bool,
74 debug_allow_mutations_to_dirty_subtrees: bool,
76 debug_doing_layout: bool,
77 debug_doing_child_layout: bool,
78 nodes_needing_paint: Vec<AnyRenderObject>,
79 debug_doing_paint: bool,
80 children: Vec<Ref<PipelineOwner>>,
81 debug_parent: Option<Handle<PipelineOwner>>,
82}
83
84impl PipelineOwner {
85 pub fn new(
90 app: &mut App,
91 on_need_visual_update: Option<Listener>,
92 on_flushed_paint: Option<FlushedPaintCallback>,
93 ) -> Ref<PipelineOwner> {
94 app.create(PipelineOwner {
95 on_need_visual_update,
96 on_flushed_paint,
97 manifold: None,
98 root_node: None,
99 nodes_needing_layout: Vec::new(),
100 nodes_needing_compositing_bits_update: Vec::new(),
101 should_merge_dirty_nodes: false,
102 debug_allow_mutations_to_dirty_subtrees: false,
103 debug_doing_layout: false,
104 debug_doing_child_layout: false,
105 nodes_needing_paint: Vec::new(),
106 debug_doing_paint: false,
107 children: Vec::new(),
108 debug_parent: None,
109 })
110 }
111
112 pub fn request_visual_update(self: Handle<Self>, app: &mut App) {
118 if let Some(callback) = app.get(self).on_need_visual_update.clone() {
119 callback.call(app);
120 } else if let Some(manifold) = app.get(self).manifold.clone() {
121 manifold.request_visual_update(app);
122 }
123 }
124
125 pub fn root_node(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
127 app.get(self).root_node
128 }
129
130 pub fn set_root_node(self: Handle<Self>, app: &mut App, value: Option<AnyRenderObject>) {
132 let current = app.get(self).root_node;
133 if current == value {
134 return;
135 }
136 if let Some(old) = current {
137 old.detach(app);
138 }
139 app.get_mut(self).root_node = value;
140 if let Some(new) = value {
141 new.attach(app, self);
142 }
143 }
144
145 pub fn nodes_needing_layout(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
148 app.get(self).nodes_needing_layout.clone()
149 }
150
151 pub(crate) fn add_node_needing_layout(
152 self: Handle<Self>,
153 app: &mut App,
154 node: AnyRenderObject,
155 ) {
156 app.get_mut(self).nodes_needing_layout.push(node);
157 }
158
159 pub(crate) fn add_node_needing_compositing_bits_update(
160 self: Handle<Self>,
161 app: &mut App,
162 node: AnyRenderObject,
163 ) {
164 app.get_mut(self)
165 .nodes_needing_compositing_bits_update
166 .push(node);
167 }
168
169 pub(crate) fn remove_node_needing_paint(
170 self: Handle<Self>,
171 app: &mut App,
172 node: AnyRenderObject,
173 ) {
174 app.get_mut(self)
175 .nodes_needing_paint
176 .retain(|candidate| *candidate != node);
177 }
178
179 pub fn debug_doing_layout(self: Handle<Self>, app: &App) -> bool {
183 if !cfg!(debug_assertions) {
184 return false;
185 }
186 app.get(self).debug_doing_layout
187 }
188
189 pub(crate) fn enable_mutations_to_dirty_subtrees(
193 self: Handle<Self>,
194 app: &mut App,
195 callback: impl FnOnce(&mut App),
196 ) {
197 debug_assert!(app.get(self).debug_doing_layout);
198 let old_state = app.get(self).debug_allow_mutations_to_dirty_subtrees;
199 if cfg!(debug_assertions) {
200 app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = true;
201 }
202 callback(app);
203 app.get_mut(self).should_merge_dirty_nodes = true;
204 if cfg!(debug_assertions) {
205 app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = old_state;
206 }
207 }
208
209 pub fn flush_layout(self: Handle<Self>, app: &mut App) {
211 if cfg!(debug_assertions) {
212 app.get_mut(self).debug_doing_layout = true;
213 }
214 while !app.get(self).nodes_needing_layout.is_empty() {
215 debug_assert!(!app.get(self).should_merge_dirty_nodes);
216 let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_layout);
217 dirty_nodes.sort_by_key(|node| node.depth(app));
218 let mut i = 0;
219 while i < dirty_nodes.len() {
220 if app.get(self).should_merge_dirty_nodes {
221 app.get_mut(self).should_merge_dirty_nodes = false;
222 if !app.get(self).nodes_needing_layout.is_empty() {
223 app.get_mut(self)
224 .nodes_needing_layout
225 .extend(dirty_nodes.drain(i..));
226 break;
227 }
228 }
229 let node = dirty_nodes[i];
230 if node.needs_layout(app) && node.owner(app) == Some(self) {
231 node.layout_without_resize(app);
232 }
233 i += 1;
234 }
235 app.get_mut(self).should_merge_dirty_nodes = false;
236 }
237 if cfg!(debug_assertions) {
238 app.get_mut(self).debug_doing_child_layout = true;
239 }
240 let children: Vec<Handle<PipelineOwner>> = app
241 .get(self)
242 .children
243 .iter()
244 .map(|child| child.handle())
245 .collect();
246 for child in children {
247 child.flush_layout(app);
248 }
249 debug_assert!(
250 app.get(self).nodes_needing_layout.is_empty(),
251 "Child PipelineOwners must not dirty nodes in their parent."
252 );
253 app.get_mut(self).should_merge_dirty_nodes = false;
254 if cfg!(debug_assertions) {
255 app.get_mut(self).debug_doing_layout = false;
256 app.get_mut(self).debug_doing_child_layout = false;
257 }
258 }
259
260 pub fn flush_compositing_bits(self: Handle<Self>, app: &mut App) {
265 let mut dirty_nodes =
266 std::mem::take(&mut app.get_mut(self).nodes_needing_compositing_bits_update);
267 dirty_nodes.sort_by_key(|node| node.depth(app));
268 for node in dirty_nodes {
269 if node.needs_compositing_bits_update(app) && node.owner(app) == Some(self) {
270 node.update_compositing_bits(app);
271 }
272 }
273 let children: Vec<Handle<PipelineOwner>> = app
274 .get(self)
275 .children
276 .iter()
277 .map(|child| child.handle())
278 .collect();
279 for child in children {
280 child.flush_compositing_bits(app);
281 }
282 debug_assert!(
283 app.get(self)
284 .nodes_needing_compositing_bits_update
285 .is_empty(),
286 "Child PipelineOwners must not dirty nodes in their parent."
287 );
288 }
289
290 pub fn nodes_needing_paint(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
293 app.get(self).nodes_needing_paint.clone()
294 }
295
296 pub(crate) fn add_node_needing_paint(self: Handle<Self>, app: &mut App, node: AnyRenderObject) {
297 app.get_mut(self).nodes_needing_paint.push(node);
298 }
299
300 pub fn debug_doing_paint(self: Handle<Self>, app: &App) -> bool {
304 app.get(self).debug_doing_paint
305 }
306
307 pub fn flush_paint(self: Handle<Self>, app: &mut App) {
316 if cfg!(debug_assertions) {
317 app.get_mut(self).debug_doing_paint = true;
318 }
319 let is_dirty = self.paint_dirty_nodes(app);
320 let children: Vec<Handle<PipelineOwner>> = app
321 .get(self)
322 .children
323 .iter()
324 .map(|child| child.handle())
325 .collect();
326 for child in children {
327 child.flush_paint(app);
328 }
329 self.did_flush_paint(app, is_dirty);
330 debug_assert!(
331 app.get(self).nodes_needing_paint.is_empty(),
332 "Child PipelineOwners must not dirty nodes in their parent."
333 );
334 if cfg!(debug_assertions) {
335 app.get_mut(self).debug_doing_paint = false;
336 }
337 }
338
339 pub fn flush_paint_without_children(self: Handle<Self>, app: &mut App) {
342 if cfg!(debug_assertions) {
343 app.get_mut(self).debug_doing_paint = true;
344 }
345 let is_dirty = self.paint_dirty_nodes(app);
346 self.did_flush_paint(app, is_dirty);
347 if cfg!(debug_assertions) {
348 app.get_mut(self).debug_doing_paint = false;
349 }
350 }
351
352 fn did_flush_paint(self: Handle<Self>, app: &mut App, is_dirty: bool) {
354 if let Some(on_flushed_paint) = app.get(self).on_flushed_paint.clone() {
355 on_flushed_paint(app, is_dirty);
356 }
357 }
358
359 fn paint_dirty_nodes(self: Handle<Self>, app: &mut App) -> bool {
362 let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_paint);
363 let is_dirty = !dirty_nodes.is_empty();
364 dirty_nodes.sort_by_key(|node| std::cmp::Reverse(node.depth(app)));
365 for node in dirty_nodes {
366 debug_assert!(node.layer(app).is_some() || !cfg!(debug_assertions));
367 if (node.needs_paint(app) || node.needs_composited_layer_update(app))
368 && node.owner(app) == Some(self)
369 {
370 if node
371 .layer(app)
372 .is_some_and(|layer| layer.as_layer().attached(app))
373 {
374 debug_assert!(node.is_repaint_boundary(app));
375 if node.needs_paint(app) {
376 PaintingContext::repaint_composited_child(app, node);
377 } else {
378 PaintingContext::update_layer_properties(app, node);
379 }
380 } else {
381 node.skipped_painting_on_layer(app);
382 }
383 }
384 }
385 is_dirty
386 }
387
388 pub fn attach(self: Handle<Self>, app: &mut App, manifold: Rc<dyn PipelineManifold>) {
394 debug_assert!(app.get(self).manifold.is_none());
395 app.get_mut(self).manifold = Some(Rc::clone(&manifold));
396 let children: Vec<Handle<PipelineOwner>> = app
397 .get(self)
398 .children
399 .iter()
400 .map(|child| child.handle())
401 .collect();
402 for child in children {
403 child.attach(app, Rc::clone(&manifold));
404 }
405 }
406
407 pub fn detach(self: Handle<Self>, app: &mut App) {
413 debug_assert!(app.get(self).manifold.is_some());
414 app.get_mut(self).manifold = None;
415 let children: Vec<Handle<PipelineOwner>> = app
416 .get(self)
417 .children
418 .iter()
419 .map(|child| child.handle())
420 .collect();
421 for child in children {
422 child.detach(app);
423 }
424 }
425
426 pub fn adopt_child(self: Handle<Self>, app: &mut App, child: Ref<PipelineOwner>) {
428 debug_assert!(app.get(&child).debug_parent.is_none());
429 debug_assert!(!app.get(self).children.contains(&child));
430 debug_assert!(
431 !app.get(self).debug_doing_child_layout,
432 "Cannot modify child list after layout."
433 );
434 let kept = child;
435 let child = kept.handle();
436 app.get_mut(self).children.push(kept);
437 if cfg!(debug_assertions) {
438 app.get_mut(child).debug_parent = Some(self);
439 }
440 if let Some(manifold) = app.get(self).manifold.clone() {
441 child.attach(app, manifold);
442 }
443 }
444
445 pub fn drop_child(self: Handle<Self>, app: &mut App, child: Handle<PipelineOwner>) {
448 debug_assert_eq!(app.get(child).debug_parent, Some(self));
449 debug_assert!(app.get(self).children.iter().any(|kept| kept == child));
450 debug_assert!(
451 !app.get(self).debug_doing_child_layout,
452 "Cannot modify child list after layout."
453 );
454 let children = &mut app.get_mut(self).children;
455 let index = children
456 .iter()
457 .position(|candidate| candidate == child)
458 .expect("child was in the list");
459 children.remove(index);
460 if cfg!(debug_assertions) {
461 app.get_mut(child).debug_parent = None;
462 }
463 if app.get(self).manifold.is_some() {
464 child.detach(app);
465 }
466 }
467
468 pub fn visit_children(
470 self: Handle<Self>,
471 app: &App,
472 visitor: &mut dyn FnMut(Handle<PipelineOwner>),
473 ) {
474 for child in &app.get(self).children {
475 visitor(child.handle());
476 }
477 }
478}
479
480#[cfg(test)]
481mod tests {
482 use std::cell::{Cell, RefCell};
483 use std::rc::Rc;
484
485 use waft_embedder::Size;
486 use waft_foundation::{App, AppCell};
487
488 use super::*;
489 use crate::box_::{RenderBox, RenderBoxData};
490 use crate::object::{RenderHandle, RenderObject, RenderObjectData};
491
492 struct TestLeaf {
493 render_object: RenderObjectData,
494 render_box: RenderBoxData,
495 on_layout: Option<Rc<dyn Fn()>>,
496 }
497
498 impl RenderObject for TestLeaf {
499 crate::render_object_accessors!();
500
501 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
502 if let Some(on_layout) = self.get(app).on_layout.clone() {
503 on_layout();
504 }
505 let size = self
506 .render_box_data(app)
507 .constraints
508 .as_ref()
509 .map(|constraints| constraints.smallest())
510 .unwrap_or(Size::ZERO);
511 self.set_size(app, size);
512 }
513 }
514
515 impl RenderBox for TestLeaf {
516 crate::render_box_accessors!();
517 }
518
519 fn leaf(on_layout: Option<Rc<dyn Fn()>>) -> TestLeaf {
520 TestLeaf {
521 render_object: RenderObjectData::new(),
522 render_box: RenderBoxData::new(),
523 on_layout,
524 }
525 }
526
527 #[test]
530 fn parent_pipeline_lays_out_before_child_pipeline() {
531 let cell = AppCell::new();
532 let mut app = cell.borrow_mut();
533 let log = Rc::new(RefCell::new(Vec::new()));
534
535 let root_log = Rc::clone(&log);
536 let root_node = RenderHandle::new_box(
537 &mut app,
538 leaf(Some(Rc::new(move || {
539 root_log.borrow_mut().push("layout parent")
540 }))),
541 );
542 let root = PipelineOwner::new(&mut app, None, None);
543 root.set_root_node(&mut app, Some(root_node.as_object()));
544 root_node.schedule_initial_layout(&mut app);
545
546 let child_log = Rc::clone(&log);
547 let child_node = RenderHandle::new_box(
548 &mut app,
549 leaf(Some(Rc::new(move || {
550 child_log.borrow_mut().push("layout child")
551 }))),
552 );
553 let child = PipelineOwner::new(&mut app, None, None);
554 child.set_root_node(&mut app, Some(child_node.as_object()));
555 child_node.schedule_initial_layout(&mut app);
556
557 root.adopt_child(&mut app, child);
558 root.flush_layout(&mut app);
559 assert_eq!(*log.borrow(), ["layout parent", "layout child"]);
560 }
561
562 #[test]
563 fn set_root_node_attaches_and_replacing_detaches() {
564 let cell = AppCell::new();
565 let mut app = cell.borrow_mut();
566 let owner = PipelineOwner::new(&mut app, None, None);
567 let first = RenderHandle::new_box(&mut app, leaf(None));
568 let second = RenderHandle::new_box(&mut app, leaf(None));
569 owner.set_root_node(&mut app, Some(first.as_object()));
570 assert!(first.attached(&app));
571 assert_eq!(first.owner(&app), Some(owner.handle()));
572
573 owner.set_root_node(&mut app, Some(second.as_object()));
574 assert!(!first.attached(&app));
575 assert!(second.attached(&app));
576 }
577
578 #[test]
579 fn schedule_initial_layout_then_flush() {
580 let cell = AppCell::new();
581 let mut app = cell.borrow_mut();
582 let owner = PipelineOwner::new(&mut app, None, None);
583 let node = RenderHandle::new_box(&mut app, leaf(None));
584 owner.set_root_node(&mut app, Some(node.as_object()));
585 node.schedule_initial_layout(&mut app);
586 assert!(node.debug_needs_layout(&app));
587 owner.flush_layout(&mut app);
588 assert!(!node.debug_needs_layout(&app));
589 assert_eq!(node.size(&app), Size::ZERO);
590 }
591
592 struct CountingManifold {
594 requests: Cell<u32>,
595 }
596
597 impl PipelineManifold for CountingManifold {
598 fn request_visual_update(&self, _app: &mut App) {
599 self.requests.set(self.requests.get() + 1);
600 }
601 }
602
603 #[test]
604 fn an_owner_without_a_callback_requests_visual_updates_through_its_manifold() {
605 let cell = AppCell::new();
606 let mut app = cell.borrow_mut();
607 let manifold = Rc::new(CountingManifold {
608 requests: Cell::new(0),
609 });
610 let root = PipelineOwner::new(&mut app, None, None);
611 let adopted_before = PipelineOwner::new(&mut app, None, None);
612 root.adopt_child(&mut app, adopted_before.clone());
613
614 adopted_before.request_visual_update(&mut app);
615 assert_eq!(
616 manifold.requests.get(),
617 0,
618 "unattached owners request nothing"
619 );
620
621 root.attach(&mut app, manifold.clone());
622 root.request_visual_update(&mut app);
623 adopted_before.request_visual_update(&mut app);
624 assert_eq!(
625 manifold.requests.get(),
626 2,
627 "attach reaches existing children"
628 );
629
630 let adopted_after = PipelineOwner::new(&mut app, None, None);
631 root.adopt_child(&mut app, adopted_after.clone());
632 adopted_after.request_visual_update(&mut app);
633 assert_eq!(manifold.requests.get(), 3, "adopt_child attaches the child");
634
635 root.drop_child(&mut app, adopted_after.handle());
636 adopted_after.request_visual_update(&mut app);
637 assert_eq!(manifold.requests.get(), 3, "drop_child detaches the child");
638
639 root.detach(&mut app);
640 adopted_before.request_visual_update(&mut app);
641 assert_eq!(manifold.requests.get(), 3, "detach reaches the children");
642 }
643
644 #[test]
645 fn a_callback_takes_precedence_over_the_manifold() {
646 let cell = AppCell::new();
647 let mut app = cell.borrow_mut();
648 let manifold = Rc::new(CountingManifold {
649 requests: Cell::new(0),
650 });
651 let callbacks = Rc::new(Cell::new(0));
652 let owner = PipelineOwner::new(
653 &mut app,
654 Some(Listener::new({
655 let callbacks = callbacks.clone();
656 move |_app| callbacks.set(callbacks.get() + 1)
657 })),
658 None,
659 );
660 owner.attach(&mut app, manifold.clone());
661 owner.request_visual_update(&mut app);
662 assert_eq!((callbacks.get(), manifold.requests.get()), (1, 0));
663 }
664}