1use std::rc::Rc;
11
12use waft_foundation::{App, Handle, Listener, Retained, ValueChanged};
13
14use crate::layer::ErasedLayer;
15use crate::object::AnyRenderObject;
16use crate::painting_context::PaintingContext;
17use waft_foundation::Ref;
18
19pub trait PipelineManifold {
37 fn request_visual_update(&self, app: &mut App);
55}
56
57pub type FlushedPaintCallback = ValueChanged<bool>;
63
64pub struct PipelineOwner {
68 on_need_visual_update: Option<Listener>,
69 on_flushed_paint: Option<FlushedPaintCallback>,
74 manifold: Option<Rc<dyn PipelineManifold>>,
75 root_node: Option<AnyRenderObject>,
76 nodes_needing_layout: Vec<Retained<AnyRenderObject>>,
78 nodes_needing_compositing_bits_update: Vec<Retained<AnyRenderObject>>,
81 should_merge_dirty_nodes: bool,
82 debug_allow_mutations_to_dirty_subtrees: bool,
84 debug_doing_layout: bool,
85 debug_doing_child_layout: bool,
86 nodes_needing_paint: Vec<Retained<AnyRenderObject>>,
88 debug_doing_paint: bool,
89 children: Vec<Ref<PipelineOwner>>,
90 debug_parent: Option<Handle<PipelineOwner>>,
91}
92
93impl PipelineOwner {
94 pub fn new(
99 app: &mut App,
100 on_need_visual_update: Option<Listener>,
101 on_flushed_paint: Option<FlushedPaintCallback>,
102 ) -> Ref<PipelineOwner> {
103 app.create(PipelineOwner {
104 on_need_visual_update,
105 on_flushed_paint,
106 manifold: None,
107 root_node: None,
108 nodes_needing_layout: Vec::new(),
109 nodes_needing_compositing_bits_update: Vec::new(),
110 should_merge_dirty_nodes: false,
111 debug_allow_mutations_to_dirty_subtrees: false,
112 debug_doing_layout: false,
113 debug_doing_child_layout: false,
114 nodes_needing_paint: Vec::new(),
115 debug_doing_paint: false,
116 children: Vec::new(),
117 debug_parent: None,
118 })
119 }
120
121 pub fn request_visual_update(self: Handle<Self>, app: &mut App) {
127 if let Some(callback) = app.get(self).on_need_visual_update.clone() {
128 callback.call(app);
129 } else if let Some(manifold) = app.get(self).manifold.clone() {
130 manifold.request_visual_update(app);
131 }
132 }
133
134 pub fn root_node(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
136 app.get(self).root_node
137 }
138
139 pub fn set_root_node(self: Handle<Self>, app: &mut App, value: Option<AnyRenderObject>) {
141 let current = app.get(self).root_node;
142 if current == value {
143 return;
144 }
145 if let Some(old) = current {
146 old.detach(app);
147 }
148 app.get_mut(self).root_node = value;
149 if let Some(new) = value {
150 new.attach(app, self);
151 }
152 }
153
154 pub fn nodes_needing_layout(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
157 handles(&app.get(self).nodes_needing_layout)
158 }
159
160 pub(crate) fn add_node_needing_layout(
161 self: Handle<Self>,
162 app: &mut App,
163 node: AnyRenderObject,
164 ) {
165 let retained = Retained::keep(app, node);
166 app.get_mut(self).nodes_needing_layout.push(retained);
167 }
168
169 pub(crate) fn add_node_needing_compositing_bits_update(
170 self: Handle<Self>,
171 app: &mut App,
172 node: AnyRenderObject,
173 ) {
174 let retained = Retained::keep(app, node);
175 app.get_mut(self)
176 .nodes_needing_compositing_bits_update
177 .push(retained);
178 }
179
180 pub(crate) fn remove_node_needing_paint(
181 self: Handle<Self>,
182 app: &mut App,
183 node: AnyRenderObject,
184 ) {
185 app.get_mut(self)
186 .nodes_needing_paint
187 .retain(|candidate| *candidate != node);
188 }
189
190 pub fn debug_doing_layout(self: Handle<Self>, app: &App) -> bool {
194 if !cfg!(debug_assertions) {
195 return false;
196 }
197 app.get(self).debug_doing_layout
198 }
199
200 pub(crate) fn enable_mutations_to_dirty_subtrees(
204 self: Handle<Self>,
205 app: &mut App,
206 callback: impl FnOnce(&mut App),
207 ) {
208 debug_assert!(app.get(self).debug_doing_layout);
209 let old_state = app.get(self).debug_allow_mutations_to_dirty_subtrees;
210 if cfg!(debug_assertions) {
211 app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = true;
212 }
213 callback(app);
214 app.get_mut(self).should_merge_dirty_nodes = true;
215 if cfg!(debug_assertions) {
216 app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = old_state;
217 }
218 }
219
220 pub fn flush_layout(self: Handle<Self>, app: &mut App) {
222 if cfg!(debug_assertions) {
223 app.get_mut(self).debug_doing_layout = true;
224 }
225 while !app.get(self).nodes_needing_layout.is_empty() {
226 debug_assert!(!app.get(self).should_merge_dirty_nodes);
227 let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_layout);
228 dirty_nodes.sort_by_key(|node| node.depth(app));
229 let mut i = 0;
230 while i < dirty_nodes.len() {
231 if app.get(self).should_merge_dirty_nodes {
232 app.get_mut(self).should_merge_dirty_nodes = false;
233 if !app.get(self).nodes_needing_layout.is_empty() {
234 app.get_mut(self)
235 .nodes_needing_layout
236 .extend(dirty_nodes.drain(i..));
237 break;
238 }
239 }
240 let node = dirty_nodes[i].handle();
241 if node.needs_layout(app) && node.owner(app) == Some(self) {
242 node.layout_without_resize(app);
243 }
244 i += 1;
245 }
246 app.get_mut(self).should_merge_dirty_nodes = false;
247 }
248 if cfg!(debug_assertions) {
249 app.get_mut(self).debug_doing_child_layout = true;
250 }
251 let children: Vec<Handle<PipelineOwner>> = app
252 .get(self)
253 .children
254 .iter()
255 .map(|child| child.handle())
256 .collect();
257 for child in children {
258 child.flush_layout(app);
259 }
260 debug_assert!(
261 app.get(self).nodes_needing_layout.is_empty(),
262 "Child PipelineOwners must not dirty nodes in their parent."
263 );
264 app.get_mut(self).should_merge_dirty_nodes = false;
265 if cfg!(debug_assertions) {
266 app.get_mut(self).debug_doing_layout = false;
267 app.get_mut(self).debug_doing_child_layout = false;
268 }
269 }
270
271 pub fn flush_compositing_bits(self: Handle<Self>, app: &mut App) {
276 let mut dirty_nodes =
277 std::mem::take(&mut app.get_mut(self).nodes_needing_compositing_bits_update);
278 dirty_nodes.sort_by_key(|node| node.depth(app));
279 for node in dirty_nodes.iter().map(Retained::handle) {
280 if node.needs_compositing_bits_update(app) && node.owner(app) == Some(self) {
281 node.update_compositing_bits(app);
282 }
283 }
284 let children: Vec<Handle<PipelineOwner>> = app
285 .get(self)
286 .children
287 .iter()
288 .map(|child| child.handle())
289 .collect();
290 for child in children {
291 child.flush_compositing_bits(app);
292 }
293 debug_assert!(
294 app.get(self)
295 .nodes_needing_compositing_bits_update
296 .is_empty(),
297 "Child PipelineOwners must not dirty nodes in their parent."
298 );
299 }
300
301 pub fn nodes_needing_paint(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
304 handles(&app.get(self).nodes_needing_paint)
305 }
306
307 pub(crate) fn add_node_needing_paint(self: Handle<Self>, app: &mut App, node: AnyRenderObject) {
308 let retained = Retained::keep(app, node);
309 app.get_mut(self).nodes_needing_paint.push(retained);
310 }
311
312 pub fn debug_doing_paint(self: Handle<Self>, app: &App) -> bool {
316 app.get(self).debug_doing_paint
317 }
318
319 pub fn flush_paint(self: Handle<Self>, app: &mut App) {
328 if cfg!(debug_assertions) {
329 app.get_mut(self).debug_doing_paint = true;
330 }
331 let is_dirty = self.paint_dirty_nodes(app);
332 let children: Vec<Handle<PipelineOwner>> = app
333 .get(self)
334 .children
335 .iter()
336 .map(|child| child.handle())
337 .collect();
338 for child in children {
339 child.flush_paint(app);
340 }
341 self.did_flush_paint(app, is_dirty);
342 debug_assert!(
343 app.get(self).nodes_needing_paint.is_empty(),
344 "Child PipelineOwners must not dirty nodes in their parent."
345 );
346 if cfg!(debug_assertions) {
347 app.get_mut(self).debug_doing_paint = false;
348 }
349 }
350
351 pub fn flush_paint_without_children(self: Handle<Self>, app: &mut App) {
354 if cfg!(debug_assertions) {
355 app.get_mut(self).debug_doing_paint = true;
356 }
357 let is_dirty = self.paint_dirty_nodes(app);
358 self.did_flush_paint(app, is_dirty);
359 if cfg!(debug_assertions) {
360 app.get_mut(self).debug_doing_paint = false;
361 }
362 }
363
364 fn did_flush_paint(self: Handle<Self>, app: &mut App, is_dirty: bool) {
366 if let Some(on_flushed_paint) = app.get(self).on_flushed_paint.clone() {
367 on_flushed_paint(app, is_dirty);
368 }
369 }
370
371 fn paint_dirty_nodes(self: Handle<Self>, app: &mut App) -> bool {
374 let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_paint);
375 let is_dirty = !dirty_nodes.is_empty();
376 dirty_nodes.sort_by_key(|node| std::cmp::Reverse(node.depth(app)));
377 for node in dirty_nodes.iter().map(Retained::handle) {
378 if (node.needs_paint(app) || node.needs_composited_layer_update(app))
379 && node.owner(app) == Some(self)
380 {
381 debug_assert!(node.layer(app).is_some());
384 if node
385 .layer(app)
386 .is_some_and(|layer| layer.as_layer().attached(app))
387 {
388 debug_assert!(node.is_repaint_boundary(app));
389 if node.needs_paint(app) {
390 PaintingContext::repaint_composited_child(app, node);
391 } else {
392 PaintingContext::update_layer_properties(app, node);
393 }
394 } else {
395 node.skipped_painting_on_layer(app);
396 }
397 }
398 }
399 is_dirty
400 }
401
402 pub fn attach(self: Handle<Self>, app: &mut App, manifold: Rc<dyn PipelineManifold>) {
408 debug_assert!(app.get(self).manifold.is_none());
409 app.get_mut(self).manifold = Some(Rc::clone(&manifold));
410 let children: Vec<Handle<PipelineOwner>> = app
411 .get(self)
412 .children
413 .iter()
414 .map(|child| child.handle())
415 .collect();
416 for child in children {
417 child.attach(app, Rc::clone(&manifold));
418 }
419 }
420
421 pub fn detach(self: Handle<Self>, app: &mut App) {
427 debug_assert!(app.get(self).manifold.is_some());
428 app.get_mut(self).manifold = None;
429 let children: Vec<Handle<PipelineOwner>> = app
430 .get(self)
431 .children
432 .iter()
433 .map(|child| child.handle())
434 .collect();
435 for child in children {
436 child.detach(app);
437 }
438 }
439
440 pub fn adopt_child(self: Handle<Self>, app: &mut App, child: Ref<PipelineOwner>) {
442 debug_assert!(app.get(&child).debug_parent.is_none());
443 debug_assert!(!app.get(self).children.contains(&child));
444 debug_assert!(
445 !app.get(self).debug_doing_child_layout,
446 "Cannot modify child list after layout."
447 );
448 let kept = child;
449 let child = kept.handle();
450 app.get_mut(self).children.push(kept);
451 if cfg!(debug_assertions) {
452 app.get_mut(child).debug_parent = Some(self);
453 }
454 if let Some(manifold) = app.get(self).manifold.clone() {
455 child.attach(app, manifold);
456 }
457 }
458
459 pub fn drop_child(self: Handle<Self>, app: &mut App, child: Handle<PipelineOwner>) {
462 debug_assert_eq!(app.get(child).debug_parent, Some(self));
463 debug_assert!(app.get(self).children.iter().any(|kept| kept == child));
464 debug_assert!(
465 !app.get(self).debug_doing_child_layout,
466 "Cannot modify child list after layout."
467 );
468 let children = &mut app.get_mut(self).children;
469 let index = children
470 .iter()
471 .position(|candidate| candidate == child)
472 .expect("child was in the list");
473 children.remove(index);
474 if cfg!(debug_assertions) {
475 app.get_mut(child).debug_parent = None;
476 }
477 if app.get(self).manifold.is_some() {
478 child.detach(app);
479 }
480 }
481
482 pub fn visit_children(
484 self: Handle<Self>,
485 app: &App,
486 visitor: &mut dyn FnMut(Handle<PipelineOwner>),
487 ) {
488 for child in &app.get(self).children {
489 visitor(child.handle());
490 }
491 }
492}
493
494fn handles(retained: &[Retained<AnyRenderObject>]) -> Vec<AnyRenderObject> {
496 retained.iter().map(Retained::handle).collect()
497}
498
499#[cfg(test)]
500mod tests {
501 use std::cell::{Cell, RefCell};
502 use std::rc::Rc;
503
504 use waft_embedder::{Offset, Size};
505 use waft_foundation::{App, AppCell};
506
507 use super::*;
508 use crate::box_::{RenderBox, RenderBoxData};
509 use crate::layer::{ContainerLayer, OffsetLayer};
510 use crate::object::{RenderHandle, RenderObject, RenderObjectData};
511
512 struct TestLeaf {
513 render_object: RenderObjectData,
514 render_box: RenderBoxData,
515 on_layout: Option<Rc<dyn Fn()>>,
516 repaint_boundary: bool,
517 }
518
519 impl RenderObject for TestLeaf {
520 crate::render_object_accessors!();
521
522 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
523 if let Some(on_layout) = self.get(app).on_layout.clone() {
524 on_layout();
525 }
526 let size = self
527 .render_box_data(app)
528 .constraints
529 .as_ref()
530 .map(|constraints| constraints.smallest())
531 .unwrap_or(Size::ZERO);
532 self.set_size(app, size);
533 }
534
535 fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
536 self.get(app).repaint_boundary
537 }
538 }
539
540 impl RenderBox for TestLeaf {
541 crate::render_box_accessors!();
542 }
543
544 fn leaf(on_layout: Option<Rc<dyn Fn()>>) -> TestLeaf {
545 TestLeaf {
546 render_object: RenderObjectData::new(),
547 render_box: RenderBoxData::new(),
548 on_layout,
549 repaint_boundary: false,
550 }
551 }
552
553 #[test]
556 fn parent_pipeline_lays_out_before_child_pipeline() {
557 let cell = AppCell::new();
558 let mut app = cell.borrow_mut();
559 let log = Rc::new(RefCell::new(Vec::new()));
560
561 let root_log = Rc::clone(&log);
562 let root_node = RenderHandle::new_box(
563 &mut app,
564 leaf(Some(Rc::new(move || {
565 root_log.borrow_mut().push("layout parent")
566 }))),
567 );
568 let root = PipelineOwner::new(&mut app, None, None);
569 root.set_root_node(&mut app, Some(root_node.as_object()));
570 root_node.schedule_initial_layout(&mut app);
571
572 let child_log = Rc::clone(&log);
573 let child_node = RenderHandle::new_box(
574 &mut app,
575 leaf(Some(Rc::new(move || {
576 child_log.borrow_mut().push("layout child")
577 }))),
578 );
579 let child = PipelineOwner::new(&mut app, None, None);
580 child.set_root_node(&mut app, Some(child_node.as_object()));
581 child_node.schedule_initial_layout(&mut app);
582
583 root.adopt_child(&mut app, child);
584 root.flush_layout(&mut app);
585 assert_eq!(*log.borrow(), ["layout parent", "layout child"]);
586 }
587
588 #[test]
594 fn a_render_object_disposed_while_it_waits_for_a_pass_is_skipped_then_freed() {
595 type Wait = fn(&mut App, AnyRenderObject);
596 type Pass = fn(Handle<PipelineOwner>, &mut App);
597 let lists: [(&str, Wait, Pass); 3] = [
598 (
599 "layout",
600 |app, node| node.schedule_initial_layout(app),
601 PipelineOwner::flush_layout,
602 ),
603 (
604 "compositing bits",
605 |app, node| node.mark_needs_compositing_bits_update(app),
606 PipelineOwner::flush_compositing_bits,
607 ),
608 (
609 "paint",
610 |app, node| {
611 let root_layer = OffsetLayer::new(app, Offset::ZERO);
612 root_layer.as_layer().attach(app, node.id());
613 node.schedule_initial_paint(app, root_layer.as_container_layer());
614 },
615 PipelineOwner::flush_paint,
616 ),
617 ];
618 for (list, wait, pass) in lists {
619 let cell = AppCell::new();
620 let mut app = cell.borrow_mut();
621 let owner = PipelineOwner::new(&mut app, None, None);
622 let boundary = TestLeaf {
623 repaint_boundary: true,
624 ..leaf(None)
625 };
626 let node = RenderHandle::new_box(&mut app, boundary).as_object();
627 owner.set_root_node(&mut app, Some(node));
628 wait(&mut app, node);
629 owner.set_root_node(&mut app, None);
630 node.dispose(&mut app);
631 drop(app);
632 cell.checkpoint();
633
634 pass(owner.handle(), &mut cell.borrow_mut());
635 cell.checkpoint();
636
637 assert!(!cell.borrow().contains(node), "freed after the {list} pass");
638 }
639 }
640
641 #[test]
642 fn set_root_node_attaches_and_replacing_detaches() {
643 let cell = AppCell::new();
644 let mut app = cell.borrow_mut();
645 let owner = PipelineOwner::new(&mut app, None, None);
646 let first = RenderHandle::new_box(&mut app, leaf(None));
647 let second = RenderHandle::new_box(&mut app, leaf(None));
648 owner.set_root_node(&mut app, Some(first.as_object()));
649 assert!(first.attached(&app));
650 assert_eq!(first.owner(&app), Some(owner.handle()));
651
652 owner.set_root_node(&mut app, Some(second.as_object()));
653 assert!(!first.attached(&app));
654 assert!(second.attached(&app));
655 }
656
657 #[test]
658 fn schedule_initial_layout_then_flush() {
659 let cell = AppCell::new();
660 let mut app = cell.borrow_mut();
661 let owner = PipelineOwner::new(&mut app, None, None);
662 let node = RenderHandle::new_box(&mut app, leaf(None));
663 owner.set_root_node(&mut app, Some(node.as_object()));
664 node.schedule_initial_layout(&mut app);
665 assert!(node.debug_needs_layout(&app));
666 owner.flush_layout(&mut app);
667 assert!(!node.debug_needs_layout(&app));
668 assert_eq!(node.size(&app), Size::ZERO);
669 }
670
671 struct CountingManifold {
673 requests: Cell<u32>,
674 }
675
676 impl PipelineManifold for CountingManifold {
677 fn request_visual_update(&self, _app: &mut App) {
678 self.requests.set(self.requests.get() + 1);
679 }
680 }
681
682 #[test]
683 fn an_owner_without_a_callback_requests_visual_updates_through_its_manifold() {
684 let cell = AppCell::new();
685 let mut app = cell.borrow_mut();
686 let manifold = Rc::new(CountingManifold {
687 requests: Cell::new(0),
688 });
689 let root = PipelineOwner::new(&mut app, None, None);
690 let adopted_before = PipelineOwner::new(&mut app, None, None);
691 root.adopt_child(&mut app, adopted_before.clone());
692
693 adopted_before.request_visual_update(&mut app);
694 assert_eq!(
695 manifold.requests.get(),
696 0,
697 "unattached owners request nothing"
698 );
699
700 root.attach(&mut app, manifold.clone());
701 root.request_visual_update(&mut app);
702 adopted_before.request_visual_update(&mut app);
703 assert_eq!(
704 manifold.requests.get(),
705 2,
706 "attach reaches existing children"
707 );
708
709 let adopted_after = PipelineOwner::new(&mut app, None, None);
710 root.adopt_child(&mut app, adopted_after.clone());
711 adopted_after.request_visual_update(&mut app);
712 assert_eq!(manifold.requests.get(), 3, "adopt_child attaches the child");
713
714 root.drop_child(&mut app, adopted_after.handle());
715 adopted_after.request_visual_update(&mut app);
716 assert_eq!(manifold.requests.get(), 3, "drop_child detaches the child");
717
718 root.detach(&mut app);
719 adopted_before.request_visual_update(&mut app);
720 assert_eq!(manifold.requests.get(), 3, "detach reaches the children");
721 }
722
723 #[test]
724 fn a_callback_takes_precedence_over_the_manifold() {
725 let cell = AppCell::new();
726 let mut app = cell.borrow_mut();
727 let manifold = Rc::new(CountingManifold {
728 requests: Cell::new(0),
729 });
730 let callbacks = Rc::new(Cell::new(0));
731 let owner = PipelineOwner::new(
732 &mut app,
733 Some(Listener::new({
734 let callbacks = callbacks.clone();
735 move |_app| callbacks.set(callbacks.get() + 1)
736 })),
737 None,
738 );
739 owner.attach(&mut app, manifold.clone());
740 owner.request_visual_update(&mut app);
741 assert_eq!((callbacks.get(), manifold.requests.get()), (1, 0));
742 }
743}