1use std::any::Any;
7use std::rc::Rc;
8
9use waft_embedder::{Canvas, Matrix4, Offset, Size, TextBaseline};
10use waft_foundation::{
11 App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listenable,
12 Listener, MessageProperty,
13};
14use waft_painting::ClipContext;
15
16use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
17use crate::object::{
18 AnyRenderObject, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
19 RenderObjectWithChildMixin,
20};
21use crate::painting_context::PaintingContext;
22use crate::pipeline_owner::PipelineOwner;
23use crate::proxy_box::{RenderProxyBoxMixin, same_instance};
24
25pub trait CustomPainter: 'static {
64 fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
70 None
71 }
72
73 fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size);
94
95 fn should_repaint(&self, app: &App, old_delegate: &dyn CustomPainter) -> bool;
122
123 fn hit_test(&self, app: &App, position: Offset) -> Option<bool> {
137 let _ = (app, position);
138 None
139 }
140
141 fn as_any(&self) -> &dyn Any;
143}
144
145impl Listenable for dyn CustomPainter {
146 fn add_listener(&self, app: &mut App, listener: Listener) {
150 if let Some(repaint) = self.repaint() {
151 repaint.add_listener(app, listener);
152 }
153 }
154
155 fn remove_listener(&self, app: &mut App, listener: &Listener) {
158 if let Some(repaint) = self.repaint() {
159 repaint.remove_listener(app, listener);
160 }
161 }
162}
163
164pub struct RenderCustomPaint {
167 render_object: RenderObjectData,
168 render_box: RenderBoxData,
169 child: RenderObjectWithChildData<AnyRenderBox>,
170 painter: Option<Rc<dyn CustomPainter>>,
171 foreground_painter: Option<Rc<dyn CustomPainter>>,
172 preferred_size: Size,
173 is_complex: bool,
174 will_change: bool,
175}
176
177impl RenderCustomPaint {
178 pub fn new(
180 app: &mut App,
181 painter: Option<Rc<dyn CustomPainter>>,
182 foreground_painter: Option<Rc<dyn CustomPainter>>,
183 preferred_size: Size,
184 is_complex: bool,
185 will_change: bool,
186 child: Option<AnyRenderBox>,
187 ) -> RenderHandle<RenderCustomPaint> {
188 let this = RenderHandle::new_box(
189 app,
190 RenderCustomPaint {
191 render_object: RenderObjectData::new(),
192 render_box: RenderBoxData::new(),
193 child: RenderObjectWithChildData::new(),
194 painter,
195 foreground_painter,
196 preferred_size,
197 is_complex,
198 will_change,
199 },
200 );
201 this.set_child(app, child);
202 this
203 }
204
205 pub fn painter(self: RenderHandle<Self>, app: &App) -> Option<Rc<dyn CustomPainter>> {
209 self.get(app).painter.clone()
210 }
211
212 pub fn set_painter(
225 self: RenderHandle<Self>,
226 app: &mut App,
227 value: Option<Rc<dyn CustomPainter>>,
228 ) {
229 let old_painter = self.get(app).painter.clone();
230 if same_instance(old_painter.as_ref(), value.as_ref()) {
231 return;
232 }
233 self.get_mut(app).painter = value.clone();
234 self.did_update_painter(app, value.as_ref(), old_painter.as_ref());
235 }
236
237 pub fn foreground_painter(
241 self: RenderHandle<Self>,
242 app: &App,
243 ) -> Option<Rc<dyn CustomPainter>> {
244 self.get(app).foreground_painter.clone()
245 }
246
247 pub fn set_foreground_painter(
260 self: RenderHandle<Self>,
261 app: &mut App,
262 value: Option<Rc<dyn CustomPainter>>,
263 ) {
264 let old_painter = self.get(app).foreground_painter.clone();
265 if same_instance(old_painter.as_ref(), value.as_ref()) {
266 return;
267 }
268 self.get_mut(app).foreground_painter = value.clone();
269 self.did_update_painter(app, value.as_ref(), old_painter.as_ref());
270 }
271
272 fn did_update_painter(
273 self: RenderHandle<Self>,
274 app: &mut App,
275 new_painter: Option<&Rc<dyn CustomPainter>>,
276 old_painter: Option<&Rc<dyn CustomPainter>>,
277 ) {
278 let repaint = match (new_painter, old_painter) {
280 (None, old_painter) => {
281 debug_assert!(old_painter.is_some()); true
283 }
284 (Some(new_painter), Some(old_painter)) => {
285 new_painter.as_any().type_id() != old_painter.as_any().type_id()
286 || new_painter.should_repaint(app, &**old_painter)
287 }
288 (Some(_), None) => true,
289 };
290 if repaint {
291 self.mark_needs_paint(app);
292 }
293 if self.attached(app) {
294 if let Some(old_painter) = old_painter {
295 old_painter.remove_listener(app, &self.paint_listener());
296 }
297 if let Some(new_painter) = new_painter {
298 new_painter.add_listener(app, self.paint_listener());
299 }
300 }
301 }
303
304 fn paint_listener(self: RenderHandle<Self>) -> Listener {
306 Listener::handle_method(self.handle(), mark_needs_paint)
307 }
308
309 pub fn preferred_size(self: RenderHandle<Self>, app: &App) -> Size {
317 self.get(app).preferred_size
318 }
319
320 pub fn set_preferred_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
322 if self.preferred_size(app) == value {
323 return;
324 }
325 self.get_mut(app).preferred_size = value;
326 self.mark_needs_layout(app);
327 }
328
329 pub fn is_complex(self: RenderHandle<Self>, app: &App) -> bool {
337 self.get(app).is_complex
338 }
339
340 pub fn set_is_complex(self: RenderHandle<Self>, app: &mut App, value: bool) {
342 self.get_mut(app).is_complex = value;
343 }
344
345 pub fn will_change(self: RenderHandle<Self>, app: &App) -> bool {
353 self.get(app).will_change
354 }
355
356 pub fn set_will_change(self: RenderHandle<Self>, app: &mut App, value: bool) {
358 self.get_mut(app).will_change = value;
359 }
360
361 fn paint_with_painter(
362 self: RenderHandle<Self>,
363 app: &mut App,
364 canvas: &mut Canvas,
365 offset: Offset,
366 painter: &dyn CustomPainter,
367 ) {
368 canvas.save();
369 let debug_previous_canvas_save_count = canvas.save_count();
370 if offset != Offset::ZERO {
371 canvas.translate(offset.dx() as f32, offset.dy() as f32);
372 }
373 let size = self.size(app);
374 painter.paint(app, canvas, size);
375 debug_assert_eq!(
379 debug_previous_canvas_save_count,
380 canvas.save_count(),
381 "the custom painter had mismatching save and restore calls"
382 );
383 canvas.restore();
384 }
385
386 fn set_raster_cache_hints(self: RenderHandle<Self>, app: &App, context: &mut PaintingContext) {
387 if self.get(app).is_complex {
388 context.set_is_complex_hint();
389 }
390 if self.get(app).will_change {
391 context.set_will_change_hint();
392 }
393 }
394}
395
396fn mark_needs_paint(this: Handle<RenderCustomPaint>, app: &mut App) {
397 RenderHandle::from_handle(this).mark_needs_paint(app);
398}
399
400impl RenderObjectWithChildMixin for RenderCustomPaint {
401 type ChildType = AnyRenderBox;
402
403 fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
404 &self.get(app).child
405 }
406
407 fn child_data_mut(
408 self: RenderHandle<Self>,
409 app: &mut App,
410 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
411 &mut self.get_mut(app).child
412 }
413}
414
415impl RenderProxyBoxMixin for RenderCustomPaint {
416 fn compute_size_for_no_child(
417 self: RenderHandle<Self>,
418 app: &App,
419 constraints: BoxConstraints,
420 ) -> Size {
421 constraints.constrain(self.get(app).preferred_size)
422 }
423}
424
425fn painter_description(painter: &Option<Rc<dyn CustomPainter>>) -> String {
430 if painter.is_some() {
431 "Instance of 'CustomPainter'".to_string()
432 } else {
433 "null".to_string()
434 }
435}
436
437impl RenderObject for RenderCustomPaint {
438 crate::render_object_accessors!();
439
440 fn debug_fill_properties(
441 self: RenderHandle<Self>,
442 app: &App,
443 properties: &mut DiagnosticPropertiesBuilder,
444 ) {
445 let this = self.get(app);
446 properties.add(MessageProperty::new(
447 "painter",
448 painter_description(&this.painter),
449 ));
450 properties.add(
451 MessageProperty::new(
452 "foregroundPainter",
453 painter_description(&this.foreground_painter),
454 )
455 .with_level(if this.foreground_painter.is_some() {
456 DiagnosticLevel::Info
457 } else {
458 DiagnosticLevel::Fine
459 }),
460 );
461 properties.add(
462 DiagnosticsProperty::new("preferredSize", this.preferred_size)
463 .default_value(Some(Size::ZERO)),
464 );
465 properties
466 .add(DiagnosticsProperty::new("isComplex", this.is_complex).default_value(Some(false)));
467 properties.add(
468 DiagnosticsProperty::new("willChange", this.will_change).default_value(Some(false)),
469 );
470 }
471
472 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
473 if let Some(child) = self.child(app) {
474 child.as_object().attach(app, owner);
475 }
476 if let Some(painter) = self.painter(app) {
477 painter.add_listener(app, self.paint_listener());
478 }
479 if let Some(foreground_painter) = self.foreground_painter(app) {
480 foreground_painter.add_listener(app, self.paint_listener());
481 }
482 }
483
484 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
485 if let Some(painter) = self.painter(app) {
486 painter.remove_listener(app, &self.paint_listener());
487 }
488 if let Some(foreground_painter) = self.foreground_painter(app) {
489 foreground_painter.remove_listener(app, &self.paint_listener());
490 }
491 if let Some(child) = self.child(app) {
492 child.as_object().detach(app);
493 }
494 }
495
496 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
497 RenderProxyBoxMixin::perform_layout(self, app);
498 }
499
500 fn paint(
501 self: RenderHandle<Self>,
502 app: &mut App,
503 context: &mut PaintingContext,
504 offset: Offset,
505 ) {
506 if let Some(painter) = self.painter(app) {
507 self.paint_with_painter(app, context.canvas(), offset, &*painter);
508 self.set_raster_cache_hints(app, context);
509 }
510 RenderProxyBoxMixin::paint(self, app, context, offset);
511 if let Some(foreground_painter) = self.foreground_painter(app) {
512 self.paint_with_painter(app, context.canvas(), offset, &*foreground_painter);
513 self.set_raster_cache_hints(app, context);
514 }
515 }
516
517 fn visit_children(
518 self: RenderHandle<Self>,
519 app: &App,
520 visitor: &mut dyn FnMut(AnyRenderObject),
521 ) {
522 if let Some(child) = self.child(app) {
523 visitor(child.as_object());
524 }
525 }
526}
527
528impl RenderBox for RenderCustomPaint {
529 crate::render_box_accessors!();
530
531 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
532 RenderProxyBoxMixin::setup_parent_data(self, app, child);
533 }
534
535 fn apply_paint_transform(
536 self: RenderHandle<Self>,
537 app: &App,
538 child: AnyRenderObject,
539 transform: &mut Matrix4,
540 ) {
541 RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
542 }
543
544 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
545 if self.child(app).is_none() {
546 let width = self.preferred_size(app).width();
547 return if width.is_finite() { width } else { 0.0 };
548 }
549 RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
550 }
551
552 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
553 if self.child(app).is_none() {
554 let width = self.preferred_size(app).width();
555 return if width.is_finite() { width } else { 0.0 };
556 }
557 RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
558 }
559
560 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
561 if self.child(app).is_none() {
562 let height = self.preferred_size(app).height();
563 return if height.is_finite() { height } else { 0.0 };
564 }
565 RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
566 }
567
568 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
569 if self.child(app).is_none() {
570 let height = self.preferred_size(app).height();
571 return if height.is_finite() { height } else { 0.0 };
572 }
573 RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
574 }
575
576 fn compute_distance_to_actual_baseline(
577 self: RenderHandle<Self>,
578 app: &mut App,
579 baseline: TextBaseline,
580 ) -> Option<f64> {
581 RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
582 }
583
584 fn compute_dry_baseline(
585 self: RenderHandle<Self>,
586 app: &mut App,
587 constraints: BoxConstraints,
588 baseline: TextBaseline,
589 ) -> Option<f64> {
590 RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
591 }
592
593 fn compute_dry_layout(
594 self: RenderHandle<Self>,
595 app: &mut App,
596 constraints: BoxConstraints,
597 ) -> Size {
598 RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
599 }
600
601 fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
602 match &self.get(app).painter {
603 Some(painter) => painter.hit_test(app, position).unwrap_or(true),
604 None => false,
605 }
606 }
607
608 fn hit_test_children(
609 self: RenderHandle<Self>,
610 app: &mut App,
611 result: &mut BoxHitTestResult<'_>,
612 position: Offset,
613 ) -> bool {
614 if let Some(foreground_painter) = self.foreground_painter(app)
615 && foreground_painter.hit_test(app, position).unwrap_or(false)
616 {
617 return true;
618 }
619 RenderProxyBoxMixin::hit_test_children(self, app, result, position)
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use std::cell::Cell;
626 use waft_foundation::AppCell;
627
628 use waft_embedder::{Color, Paint, valo};
629 use waft_foundation::ValueNotifier;
630 use waft_gestures::HitTestResult;
631 use waft_painting::AlignmentGeometry;
632
633 use super::*;
634 use crate::box_::BoxHitTestResult;
635 use crate::object::AnyRenderObject;
636 use crate::testing::{EnginePhase, layout_with, painted_ops, pump_frame};
637
638 const RED: Color = Color::from_argb(255, 255, 0, 0);
639 const BLUE: Color = Color::from_argb(255, 0, 0, 255);
640 const GREEN: Color = Color::from_argb(255, 0, 255, 0);
641
642 struct Recorder {
645 color: Color,
646 paints: Rc<Cell<u32>>,
647 hit: Option<bool>,
648 repaint: Option<Rc<dyn Listenable>>,
649 should_repaint: bool,
650 }
651
652 impl Recorder {
653 fn new(color: Color) -> Recorder {
654 Recorder {
655 color,
656 paints: Rc::new(Cell::new(0)),
657 hit: None,
658 repaint: None,
659 should_repaint: false,
660 }
661 }
662 }
663
664 impl CustomPainter for Recorder {
665 fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
666 self.repaint.as_ref()
667 }
668
669 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
670 self.paints.set(self.paints.get() + 1);
671 canvas.draw_rect(
672 Offset::ZERO & size,
673 &Paint {
674 color: self.color.into(),
675 ..Paint::default()
676 },
677 );
678 }
679
680 fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
681 self.should_repaint
682 }
683
684 fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
685 self.hit
686 }
687
688 fn as_any(&self) -> &dyn Any {
689 self
690 }
691 }
692
693 fn drawn_colors(app: &mut App, render: AnyRenderObject) -> Vec<valo::Color> {
695 painted_ops(app, render)
696 .into_iter()
697 .filter_map(|op| match op {
698 valo::Op::DrawRect { paint, .. } => Some(paint.color),
699 _ => None,
700 })
701 .collect()
702 }
703
704 fn hit_test(app: &mut App, target: AnyRenderBox, position: Offset) -> (bool, usize) {
705 let mut result = HitTestResult::new();
706 let is_hit = target.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
707 (is_hit, result.path().len())
708 }
709
710 #[test]
711 fn both_painters_paint_around_the_child() {
712 let cell = AppCell::new();
713 let mut app = cell.borrow_mut();
714 let background = Rc::new(Recorder::new(RED));
715 let foreground = Rc::new(Recorder::new(BLUE));
716 let child = crate::proxy_box::RenderColoredBox::new(&mut app, GREEN, true, None);
717 let custom = RenderCustomPaint::new(
718 &mut app,
719 Some(background.clone()),
720 Some(foreground.clone()),
721 Size::ZERO,
722 false,
723 false,
724 Some(child.as_box()),
725 );
726 layout_with(
727 &mut app,
728 custom.as_box(),
729 None,
730 AlignmentGeometry::CENTER,
731 EnginePhase::Paint,
732 );
733
734 assert_eq!((background.paints.get(), foreground.paints.get()), (1, 1));
735 assert_eq!(
736 drawn_colors(&mut app, custom.as_object()),
737 [RED.into(), GREEN.into(), BLUE.into()],
738 "background, child, foreground"
739 );
740 }
741
742 #[test]
743 fn a_painter_repaints_when_its_repaint_listenable_notifies() {
744 let cell = AppCell::new();
745 let mut app = cell.borrow_mut();
746 let notifier = app.create(ValueNotifier::new(0));
747 let painter = Rc::new(Recorder {
748 repaint: Some(Rc::new(notifier.clone())),
749 ..Recorder::new(RED)
750 });
751 let custom = RenderCustomPaint::new(
752 &mut app,
753 Some(painter.clone()),
754 None,
755 Size::new(10.0, 10.0),
756 false,
757 false,
758 None,
759 );
760 layout_with(
761 &mut app,
762 custom.as_box(),
763 None,
764 AlignmentGeometry::CENTER,
765 EnginePhase::Paint,
766 );
767 assert_eq!(painter.paints.get(), 1);
768 assert!(!custom.as_object().debug_needs_paint(&app));
769
770 notifier.set_value(&mut app, 1);
771 assert!(custom.as_object().debug_needs_paint(&app));
772 pump_frame(&mut app, EnginePhase::Paint);
773 assert_eq!(painter.paints.get(), 2);
774 }
775
776 #[test]
778 fn replacing_the_painter_asks_it_whether_to_repaint() {
779 let cell = AppCell::new();
780 let mut app = cell.borrow_mut();
781 let notifier = app.create(ValueNotifier::new(0));
782 let painter = Rc::new(Recorder {
783 repaint: Some(Rc::new(notifier.clone())),
784 ..Recorder::new(RED)
785 });
786 let custom = RenderCustomPaint::new(
787 &mut app,
788 Some(painter.clone()),
789 None,
790 Size::new(10.0, 10.0),
791 false,
792 false,
793 None,
794 );
795 layout_with(
796 &mut app,
797 custom.as_box(),
798 None,
799 AlignmentGeometry::CENTER,
800 EnginePhase::Paint,
801 );
802
803 let quiet = Rc::new(Recorder::new(BLUE));
804 custom.set_painter(&mut app, Some(quiet.clone()));
805 assert!(
806 !custom.as_object().debug_needs_paint(&app),
807 "should_repaint is false"
808 );
809 notifier.set_value(&mut app, 1);
810 assert!(
811 !custom.as_object().debug_needs_paint(&app),
812 "the old painter's listenable was unsubscribed"
813 );
814
815 let eager = Rc::new(Recorder {
816 should_repaint: true,
817 ..Recorder::new(BLUE)
818 });
819 custom.set_painter(&mut app, Some(eager.clone()));
820 assert!(custom.as_object().debug_needs_paint(&app));
821 pump_frame(&mut app, EnginePhase::Paint);
822 assert_eq!((quiet.paints.get(), eager.paints.get()), (0, 1));
823
824 custom.set_painter(&mut app, None);
825 assert!(
826 custom.as_object().debug_needs_paint(&app),
827 "a removal repaints"
828 );
829 }
830
831 #[test]
832 fn preferred_size_is_used_without_a_child() {
833 let cell = AppCell::new();
834 let mut app = cell.borrow_mut();
835 let custom = RenderCustomPaint::new(
836 &mut app,
837 None,
838 None,
839 Size::new(20.0, 30.0),
840 false,
841 false,
842 None,
843 );
844 custom.layout(&mut app, BoxConstraints::new(), false);
845 assert_eq!(custom.size(&app), Size::new(20.0, 30.0));
846
847 custom.layout(
848 &mut app,
849 BoxConstraints::loose(Size::new(10.0, 10.0)),
850 false,
851 );
852 assert_eq!(
853 custom.size(&app),
854 Size::new(10.0, 10.0),
855 "the preferred size is constrained"
856 );
857 }
858
859 #[test]
860 fn a_child_sizes_the_custom_paint() {
861 let cell = AppCell::new();
862 let mut app = cell.borrow_mut();
863 let child = crate::proxy_box::RenderConstrainedBox::new(
864 &mut app,
865 BoxConstraints::tight(Size::new(40.0, 40.0)),
866 None,
867 );
868 let custom = RenderCustomPaint::new(
869 &mut app,
870 None,
871 None,
872 Size::new(20.0, 30.0),
873 false,
874 false,
875 Some(child.as_box()),
876 );
877 custom.layout(&mut app, BoxConstraints::new(), false);
878 assert_eq!(custom.size(&app), Size::new(40.0, 40.0));
879 }
880
881 #[test]
882 fn the_painters_answer_hit_tests() {
883 let cell = AppCell::new();
884 let mut app = cell.borrow_mut();
885 let background = Rc::new(Recorder::new(RED));
886 let custom = RenderCustomPaint::new(
887 &mut app,
888 Some(background),
889 None,
890 Size::new(100.0, 100.0),
891 false,
892 false,
893 None,
894 );
895 custom.layout(&mut app, BoxConstraints::new(), false);
896 assert_eq!(
897 hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
898 (true, 1),
899 "a background painter is hit by default"
900 );
901
902 let missing = Rc::new(Recorder {
903 hit: Some(false),
904 ..Recorder::new(RED)
905 });
906 custom.set_painter(&mut app, Some(missing));
907 assert_eq!(
908 hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
909 (false, 0)
910 );
911
912 custom.set_painter(&mut app, None);
913 assert_eq!(
914 hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
915 (false, 0),
916 "no painter, no hit"
917 );
918
919 let foreground = Rc::new(Recorder {
920 hit: Some(true),
921 ..Recorder::new(BLUE)
922 });
923 custom.set_foreground_painter(&mut app, Some(foreground));
924 assert_eq!(
925 hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
926 (true, 1),
927 "a foreground painter answers for the children"
928 );
929 }
930}