1use std::rc::Rc;
6
7use waft_embedder::{
8 Matrix4, Offset, Rect, SceneBuilder, Size, SystemUiOverlayStyle, TargetPlatform, View, ViewRef,
9};
10use waft_foundation::{App, Handle};
11use waft_gestures::{HitTestEntry, HitTestResult, HitTestTarget, PointerEvent};
12use waft_services::SystemChrome;
13
14use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
15use crate::layer::{ContainerLayer, ErasedLayer, OffsetLayerMixin, TransformLayer};
16use crate::object::{
17 AnyRenderObject, Constraints, RenderHandle, RenderObject, RenderObjectData, RenderObjectVTable,
18 resolve,
19};
20use crate::painting_context::PaintingContext;
21
22#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct ViewConfiguration {
25 pub logical_constraints: BoxConstraints,
27 pub physical_constraints: BoxConstraints,
29 pub device_pixel_ratio: f64,
31}
32
33impl ViewConfiguration {
34 pub const fn new(
38 physical_constraints: BoxConstraints,
39 logical_constraints: BoxConstraints,
40 device_pixel_ratio: f64,
41 ) -> ViewConfiguration {
42 ViewConfiguration {
43 logical_constraints,
44 physical_constraints,
45 device_pixel_ratio,
46 }
47 }
48
49 pub fn from_view(view: &dyn View) -> ViewConfiguration {
51 let metrics = view.metrics();
52 let physical_constraints =
53 BoxConstraints::from_view_constraints(metrics.physical_constraints);
54 let device_pixel_ratio = metrics.device_pixel_ratio;
55 ViewConfiguration {
56 logical_constraints: physical_constraints / device_pixel_ratio,
57 physical_constraints,
58 device_pixel_ratio,
59 }
60 }
61
62 pub fn to_matrix(&self) -> Matrix4 {
65 Matrix4::scale(
66 self.device_pixel_ratio as f32,
67 self.device_pixel_ratio as f32,
68 )
69 }
70
71 pub fn should_update_matrix(&self, old_configuration: &ViewConfiguration) -> bool {
74 old_configuration.device_pixel_ratio != self.device_pixel_ratio
75 }
76
77 pub fn to_physical_size(&self, logical_size: Size) -> Size {
79 self.physical_constraints
80 .constrain(logical_size * self.device_pixel_ratio)
81 }
82}
83
84impl Default for ViewConfiguration {
85 fn default() -> ViewConfiguration {
86 ViewConfiguration::new(
87 BoxConstraints::new().max_width(0.0).max_height(0.0),
88 BoxConstraints::new().max_width(0.0).max_height(0.0),
89 1.0,
90 )
91 }
92}
93
94pub struct RenderView {
103 render_object: RenderObjectData,
104 child: Option<AnyRenderBox>,
105 size: Size,
106 configuration: Option<ViewConfiguration>,
107 view: ViewRef,
108 root_transform: Option<Matrix4>,
109 needs_composite_frame: bool,
110 pub automatic_system_ui_adjustment: bool,
116}
117
118impl RenderView {
119 pub fn new(
126 app: &mut App,
127 child: Option<AnyRenderBox>,
128 configuration: Option<ViewConfiguration>,
129 view: ViewRef,
130 ) -> RenderHandle<RenderView> {
131 let this = crate::object::create(
132 app,
133 RenderView {
134 render_object: RenderObjectData::new(),
135 child: None,
136 size: Size::ZERO,
137 configuration: None,
138 view,
139 root_transform: None,
140 needs_composite_frame: false,
141 automatic_system_ui_adjustment: true,
142 },
143 );
144 let data = this.render_object_data_mut(app);
145 data.object_vtable = Some(&VTABLE);
146 data.was_repaint_boundary = true;
147 data.needs_compositing = true;
148 if let Some(configuration) = configuration {
149 this.set_configuration(app, configuration);
150 }
151 this.set_child(app, child);
152 this
153 }
154
155 pub fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
157 AnyRenderObject::from_vtable(self.id(), const { &VTABLE })
158 }
159
160 pub fn child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
162 self.get(app).child
163 }
164
165 pub fn set_child(self: RenderHandle<Self>, app: &mut App, value: Option<AnyRenderBox>) {
167 if let Some(old) = self.get(app).child {
168 self.as_object().drop_child(app, old.as_object());
169 }
170 self.get_mut(app).child = value;
171 if let Some(new) = value {
172 self.as_object().adopt_child(app, new.as_object());
173 }
174 }
175
176 pub fn size(self: RenderHandle<Self>, app: &App) -> Size {
178 self.get(app).size
179 }
180
181 pub fn configuration(self: RenderHandle<Self>, app: &App) -> ViewConfiguration {
193 self.get(app)
194 .configuration
195 .expect("RenderView has not been given a configuration yet")
196 }
197
198 pub fn set_configuration(self: RenderHandle<Self>, app: &mut App, value: ViewConfiguration) {
200 if self.get(app).configuration == Some(value) {
201 return;
202 }
203 let old_configuration = self.get(app).configuration;
204 self.get_mut(app).configuration = Some(value);
205 if self.get(app).root_transform.is_none() {
206 return;
208 }
209 if old_configuration.is_none_or(|old| value.should_update_matrix(&old)) {
210 let root_layer = self.update_matrices_and_create_new_root_layer(app);
211 self.as_object()
212 .replace_root_layer(app, root_layer.as_offset_layer());
213 }
214 debug_assert!(self.get(app).root_transform.is_some());
215 self.as_object().mark_needs_layout(app);
216 }
217
218 pub fn has_configuration(self: RenderHandle<Self>, app: &App) -> bool {
220 self.get(app).configuration.is_some()
221 }
222
223 pub fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
230 debug_assert!(
231 self.has_configuration(app),
232 "Constraints are not available because RenderView has not been given a configuration yet."
233 );
234 self.configuration(app).logical_constraints
235 }
236
237 pub fn flutter_view(self: RenderHandle<Self>, app: &App) -> ViewRef {
239 self.get(app).view.clone()
240 }
241
242 pub fn prepare_initial_frame(self: RenderHandle<Self>, app: &mut App) {
251 debug_assert!(
252 self.as_object().owner(app).is_some(),
253 "attach the RenderView to a PipelineOwner before calling prepare_initial_frame"
254 );
255 debug_assert!(
256 self.get(app).root_transform.is_none(),
257 "prepare_initial_frame must only be called once"
258 );
259 debug_assert!(
260 self.has_configuration(app),
261 "set a configuration before calling prepare_initial_frame"
262 );
263 self.as_object().schedule_initial_layout(app);
264 let root_layer = self.update_matrices_and_create_new_root_layer(app);
265 self.as_object()
266 .schedule_initial_paint(app, root_layer.as_container_layer());
267 debug_assert!(self.get(app).root_transform.is_some());
268 }
269
270 pub fn needs_composite_frame(self: RenderHandle<Self>, app: &App) -> bool {
274 self.get(app).needs_composite_frame
275 }
276
277 pub fn mark_needs_composite_frame(self: RenderHandle<Self>, app: &mut App) {
284 self.get_mut(app).needs_composite_frame = true;
285 }
286
287 fn update_matrices_and_create_new_root_layer(
288 self: RenderHandle<Self>,
289 app: &mut App,
290 ) -> Handle<TransformLayer> {
291 debug_assert!(self.has_configuration(app));
292 let root_transform = self.configuration(app).to_matrix();
293 self.get_mut(app).root_transform = Some(root_transform);
294 let root_layer = TransformLayer::new(app);
295 root_layer.set_transform(app, root_transform);
296 root_layer.attach(app, self.id());
297 debug_assert!(self.get(app).root_transform.is_some());
298 root_layer
299 }
300
301 pub fn hit_test(
310 self: RenderHandle<Self>,
311 app: &mut App,
312 result: &mut HitTestResult,
313 position: Offset,
314 ) -> bool {
315 if let Some(child) = self.child(app) {
316 child.hit_test(app, &mut BoxHitTestResult::wrap(result), position);
317 }
318 result.add(HitTestEntry::new(self));
319 true
320 }
321
322 pub fn composite_frame(self: RenderHandle<Self>, app: &mut App) {
326 debug_assert!(
327 self.has_configuration(app),
328 "set the RenderView configuration before calling composite_frame"
329 );
330 debug_assert!(
331 self.get(app).root_transform.is_some(),
332 "call prepare_initial_frame before calling composite_frame"
333 );
334 let layer = self
335 .as_object()
336 .layer(app)
337 .expect("call prepare_initial_frame before calling composite_frame");
338 let scene = layer.build_scene(app, SceneBuilder::new());
339 if self.get(app).automatic_system_ui_adjustment {
340 self.update_system_chrome(app);
341 }
342 debug_assert!(
343 self.configuration(app)
344 .logical_constraints
345 .is_satisfied_by(self.size(app))
346 );
347 self.get(app).view.present(std::sync::Arc::new(scene));
348 self.get_mut(app).needs_composite_frame = false;
349 }
350
351 fn update_system_chrome(self: RenderHandle<Self>, app: &mut App) {
377 let Some(layer) = self.as_object().layer(app) else {
378 return;
379 };
380 let bounds = self.paint_bounds(app);
381 let padding = self.get(app).view.metrics().padding;
382 let top = Offset::new(
384 bounds.center().dx(),
386 padding.top / 2.0,
389 );
390 let bottom = Offset::new(
392 bounds.center().dx(),
394 bounds.bottom - 1.0 - padding.bottom / 2.0,
400 );
401 let layer = layer.as_layer();
402 let upper = layer.find::<SystemUiOverlayStyle>(app, top);
403 let is_android = app.platform().target_platform() == TargetPlatform::Android;
405 let lower = is_android
406 .then(|| layer.find::<SystemUiOverlayStyle>(app, bottom))
407 .flatten();
408 let Some(style) = merged_overlay_style(upper, lower, is_android) else {
410 return;
411 };
412 let view = self.get(app).view.id();
413 SystemChrome::set_system_ui_overlay_style(app, view, &style);
414 }
415
416 pub fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
419 Offset::ZERO & (self.size(app) * self.configuration(app).device_pixel_ratio)
420 }
421}
422
423fn merged_overlay_style(
432 upper: Option<Rc<SystemUiOverlayStyle>>,
433 lower: Option<Rc<SystemUiOverlayStyle>>,
434 is_android: bool,
435) -> Option<SystemUiOverlayStyle> {
436 if let (Some(upper), Some(lower)) = (&upper, &lower) {
437 return Some(SystemUiOverlayStyle {
438 status_bar_brightness: upper.status_bar_brightness,
439 status_bar_icon_brightness: upper.status_bar_icon_brightness,
440 status_bar_color: upper.status_bar_color,
441 system_status_bar_contrast_enforced: upper.system_status_bar_contrast_enforced,
442 system_navigation_bar_color: lower.system_navigation_bar_color,
443 system_navigation_bar_divider_color: lower.system_navigation_bar_divider_color,
444 system_navigation_bar_icon_brightness: lower.system_navigation_bar_icon_brightness,
445 system_navigation_bar_contrast_enforced: lower.system_navigation_bar_contrast_enforced,
446 });
447 }
448 let defined = upper.or(lower)?;
449 if !is_android {
450 return Some(SystemUiOverlayStyle {
452 status_bar_brightness: defined.status_bar_brightness,
453 status_bar_icon_brightness: defined.status_bar_icon_brightness,
454 status_bar_color: defined.status_bar_color,
455 system_status_bar_contrast_enforced: defined.system_status_bar_contrast_enforced,
456 ..SystemUiOverlayStyle::new()
457 });
458 }
459 Some(*defined)
460}
461
462impl RenderObject for RenderView {
463 fn render_object_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectData {
464 &self.get(app).render_object
465 }
466
467 fn render_object_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderObjectData {
468 &mut self.get_mut(app).render_object
469 }
470
471 fn perform_resize(self: RenderHandle<Self>, _app: &mut App) {
472 panic!("RenderView is never sized by its parent");
473 }
474
475 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
476 debug_assert!(self.get(app).root_transform.is_some());
477 let constraints = self.constraints(app);
478 let sized_by_child = !constraints.is_tight();
479 let child = self.child(app);
480 if let Some(child) = child {
481 child.layout(app, constraints, sized_by_child);
482 }
483 let size = match child {
484 Some(child) if sized_by_child => child.size(app),
485 _ => constraints.smallest(),
486 };
487 self.get_mut(app).size = size;
488 debug_assert!(size.is_finite());
489 debug_assert!(constraints.is_satisfied_by(size));
490 }
491
492 fn visit_children(
493 self: RenderHandle<Self>,
494 app: &App,
495 visitor: &mut dyn FnMut(AnyRenderObject),
496 ) {
497 if let Some(child) = self.child(app) {
498 visitor(child.as_object());
499 }
500 }
501
502 fn apply_paint_transform(
503 self: RenderHandle<Self>,
504 app: &App,
505 child: AnyRenderObject,
506 transform: &mut Matrix4,
507 ) {
508 let root_transform = self
509 .get(app)
510 .root_transform
511 .as_ref()
512 .expect("the view has a configuration");
513 crate::object::multiply(transform, root_transform);
514 debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
515 }
516
517 fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
518 true
519 }
520
521 fn paint(
522 self: RenderHandle<Self>,
523 app: &mut App,
524 context: &mut PaintingContext,
525 offset: Offset,
526 ) {
527 if let Some(child) = self.child(app) {
528 context.paint_child(app, child.as_object(), offset);
529 }
530 }
531}
532
533impl HitTestTarget for RenderHandle<RenderView> {
535 fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
536}
537
538static VTABLE: RenderObjectVTable = RenderObjectVTable::of::<RenderView>(
540 |app, id, child| <RenderView as RenderObject>::setup_parent_data(resolve(id), app, child),
541 |app, id| RenderView::paint_bounds(resolve(id), app),
542 |app, id, child, transform| {
543 <RenderView as RenderObject>::apply_paint_transform(resolve(id), app, child, transform)
544 },
545 |app, id| <RenderView as RenderObject>::perform_resize(resolve(id), app),
546 |app, id| crate::object::RenderObjectBase::mark_needs_layout(resolve::<RenderView>(id), app),
547 None,
548 None,
549);
550
551#[cfg(test)]
552mod tests {
553 use std::cell::Cell;
554 use std::rc::Rc;
555 use waft_foundation::AppCell;
556
557 use waft_embedder::{ViewId, ViewMetrics};
558
559 use super::*;
560 use crate::box_::RenderBox;
561 use crate::layer::TransformLayer;
562 use crate::pipeline_owner::PipelineOwner;
563 use crate::proxy_box::RenderConstrainedBox;
564 use crate::shifted_box::RenderPadding;
565 use waft_embedder::ViewHost;
566 use waft_painting::EdgeInsetsGeometry;
567 use waft_test::TestViewHost;
568
569 struct TestView {
570 metrics: ViewMetrics,
571 presented: Rc<Cell<u32>>,
572 host: TestViewHost,
573 }
574
575 impl View for TestView {
576 fn id(&self) -> ViewId {
577 ViewId(0)
578 }
579
580 fn metrics(&self) -> ViewMetrics {
581 self.metrics
582 }
583
584 fn present(&self, _scene: std::sync::Arc<waft_embedder::Scene>) {
585 self.presented.set(self.presented.get() + 1);
586 }
587
588 fn host(&self) -> &dyn ViewHost {
589 &self.host
590 }
591 }
592
593 fn test_view(presented: &Rc<Cell<u32>>) -> ViewRef {
594 Rc::new(TestView {
595 metrics: ViewMetrics::default(),
596 presented: Rc::clone(presented),
597 host: TestViewHost::default(),
598 })
599 }
600
601 fn create_view_configuration(size: Size, device_pixel_ratio: f64) -> ViewConfiguration {
603 let constraints = BoxConstraints::tight(size);
604 ViewConfiguration::new(
605 constraints * device_pixel_ratio,
606 constraints,
607 device_pixel_ratio,
608 )
609 }
610
611 #[test]
613 fn view_configuration_equality() {
614 let a = create_view_configuration(Size::new(800.0, 600.0), 1.0);
615 let b = create_view_configuration(Size::new(800.0, 600.0), 1.0);
616 let c = create_view_configuration(Size::new(800.0, 600.0), 3.0);
617 assert_eq!(a, b);
618 assert_ne!(a, c);
619 }
620
621 #[test]
623 fn constraints_are_derived_from_configuration() {
624 let cell = AppCell::new();
625 let mut app = cell.borrow_mut();
626 let presented = Rc::new(Cell::new(0));
627 let view = RenderView::new(&mut app, None, None, test_view(&presented));
628 assert!(!view.has_configuration(&app));
629 let constraints = BoxConstraints::new()
630 .min_width(1.0)
631 .max_width(2.0)
632 .min_height(3.0)
633 .max_height(4.0);
634 view.set_configuration(
635 &mut app,
636 ViewConfiguration::new(constraints * 3.0, constraints, 3.0),
637 );
638 assert_eq!(view.constraints(&app), constraints);
639 }
640
641 #[test]
644 fn configuration_can_change_before_prepare_initial_frame() {
645 let cell = AppCell::new();
646 let mut app = cell.borrow_mut();
647 let presented = Rc::new(Cell::new(0));
648 let view = RenderView::new(&mut app, None, None, test_view(&presented));
649 view.set_configuration(
650 &mut app,
651 create_view_configuration(Size::new(100.0, 200.0), 3.0),
652 );
653 view.set_configuration(
654 &mut app,
655 create_view_configuration(Size::new(200.0, 300.0), 2.0),
656 );
657 let owner = PipelineOwner::new(&mut app, None, None);
658 owner.set_root_node(&mut app, Some(view.as_object()));
659 view.prepare_initial_frame(&mut app);
660 }
661
662 #[test]
665 fn does_not_replace_the_root_layer_unnecessarily() {
666 let cell = AppCell::new();
667 let mut app = cell.borrow_mut();
668 let presented = Rc::new(Cell::new(0));
669 let view = RenderView::new(
670 &mut app,
671 None,
672 Some(create_view_configuration(Size::new(100.0, 100.0), 1.0)),
673 test_view(&presented),
674 );
675 let owner = PipelineOwner::new(&mut app, None, None);
676 owner.set_root_node(&mut app, Some(view.as_object()));
677 view.prepare_initial_frame(&mut app);
678 owner.flush_layout(&mut app);
679 owner.flush_compositing_bits(&mut app);
680 owner.flush_paint(&mut app);
681 assert!(!view.as_object().debug_needs_paint(&app));
682
683 view.set_configuration(
684 &mut app,
685 create_view_configuration(Size::new(100.0, 1117.0), 1.0),
686 );
687 assert!(
688 !view.as_object().debug_needs_paint(&app),
689 "a resize keeps the root layer"
690 );
691
692 view.set_configuration(
693 &mut app,
694 create_view_configuration(Size::new(100.0, 1117.0), 5.0),
695 );
696 assert!(
697 view.as_object().debug_needs_paint(&app),
698 "a new ratio replaces it"
699 );
700 let layer = view.as_object().debug_layer(&app).expect("root layer");
701 let transform = app
702 .handle::<TransformLayer>(layer.id())
703 .expect("the root is a TransformLayer");
704 assert_eq!(transform.transform(&app), Some(Matrix4::scale(5.0, 5.0)));
705 }
706
707 #[test]
710 fn accounts_for_device_pixel_ratio_in_paint_bounds_and_presents() {
711 let cell = AppCell::new();
712 let mut app = cell.borrow_mut();
713 let presented = Rc::new(Cell::new(0));
714 let child =
715 RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
716 let view = RenderView::new(
717 &mut app,
718 Some(child.as_box()),
719 Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
720 test_view(&presented),
721 );
722 let owner = PipelineOwner::new(&mut app, None, None);
723 owner.set_root_node(&mut app, Some(view.as_object()));
724 view.prepare_initial_frame(&mut app);
725 owner.flush_layout(&mut app);
726 owner.flush_compositing_bits(&mut app);
727 owner.flush_paint(&mut app);
728 view.composite_frame(&mut app);
729
730 assert_eq!(view.size(&app), Size::new(800.0, 600.0));
731 assert_eq!(
732 view.paint_bounds(&app),
733 Offset::ZERO & Size::new(1600.0, 1200.0)
734 );
735 assert_eq!(presented.get(), 1);
736 }
737
738 #[test]
739 fn coordinates_convert_through_the_paint_transforms_below_the_view() {
740 let cell = AppCell::new();
741 let mut app = cell.borrow_mut();
742 let presented = Rc::new(Cell::new(0));
743 let child =
744 RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
745 let padding = RenderPadding::new(
746 &mut app,
747 EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
748 None,
749 Some(child.as_box()),
750 );
751 let view = RenderView::new(
752 &mut app,
753 Some(padding.as_box()),
754 Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
755 test_view(&presented),
756 );
757 let owner = PipelineOwner::new(&mut app, None, None);
758 owner.set_root_node(&mut app, Some(view.as_object()));
759 view.prepare_initial_frame(&mut app);
760 owner.flush_layout(&mut app);
761
762 let child = child.as_box();
764 assert_eq!(
765 child.local_to_global(&app, Offset::ZERO, None),
766 Offset::new(10.0, 20.0)
767 );
768 assert_eq!(
769 child.global_to_local(&app, Offset::new(15.0, 25.0), None),
770 Offset::new(5.0, 5.0)
771 );
772 assert_eq!(
773 child.local_to_global(&app, Offset::new(1.0, 1.0), Some(padding.as_object())),
774 Offset::new(11.0, 21.0)
775 );
776 assert_eq!(
777 padding.as_box().global_to_local(
778 &app,
779 Offset::new(10.0, 20.0),
780 Some(child.as_object())
781 ),
782 Offset::new(20.0, 40.0)
783 );
784 assert!(
785 child
786 .as_object()
787 .paint_bounds(&app)
788 .inflate(70.0)
789 .contains(child.global_to_local(&app, Offset::new(100.0, 100.0), None))
790 );
791 }
792
793 #[test]
794 fn a_proxy_box_adds_no_paint_transform() {
795 let cell = AppCell::new();
796 let mut app = cell.borrow_mut();
797 let presented = Rc::new(Cell::new(0));
798 let child =
799 RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
800 let proxy =
801 RenderConstrainedBox::new(&mut app, BoxConstraints::new(), Some(child.as_box()));
802 let padding = RenderPadding::new(
803 &mut app,
804 EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
805 None,
806 Some(proxy.as_box()),
807 );
808 let view = RenderView::new(
809 &mut app,
810 Some(padding.as_box()),
811 Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
812 test_view(&presented),
813 );
814 let owner = PipelineOwner::new(&mut app, None, None);
815 owner.set_root_node(&mut app, Some(view.as_object()));
816 view.prepare_initial_frame(&mut app);
817 owner.flush_layout(&mut app);
818
819 assert_eq!(
820 child.as_box().local_to_global(&app, Offset::ZERO, None),
821 Offset::new(10.0, 20.0)
822 );
823 assert_eq!(
824 child
825 .as_box()
826 .global_to_local(&app, Offset::new(15.0, 25.0), None),
827 Offset::new(5.0, 5.0)
828 );
829 }
830}