Skip to main content

waft_winui/primitives/
size_observer.rs

1//! Reports layout size changes after the frame so controls can safely update state.
2
3use std::{fmt, rc::Rc};
4use waft_embedder::{Matrix4, Offset, Size, TextBaseline};
5use waft_foundation::{App, Handle};
6use waft_rendering::{
7    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, PaintingContext,
8    PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
9    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
10};
11use waft_scheduler::{FrameCallback, SchedulerBinding};
12use waft_widgets::*;
13
14/// Receives the previous and current child size after layout; the first previous size is zero.
15pub type SizeChangedCallback = Rc<dyn Fn(&mut App, Size, Size)>;
16
17/// A transparent layout proxy. Multiple layouts in one frame report only the final size.
18/// The first report uses `Size::ZERO` as the previous size.
19pub struct SizeObserver {
20    /// Identifies this observer across parent rebuilds.
21    pub key: Option<KeyRef>,
22    /// The child whose laid-out size is observed without changing its constraints.
23    pub child: WidgetRef,
24    /// Receives coalesced size changes after the frame, while the render object remains attached.
25    pub on_changed: SizeChangedCallback,
26}
27
28impl SizeObserver {
29    /// Creates a layout observer with a child and a size-change callback.
30    #[cfg_attr(debug_assertions, track_caller)]
31    pub fn new<K>(child: impl IntoWidget<K>, on_changed: SizeChangedCallback) -> Self {
32        Self {
33            key: None,
34            child: child.into_widget(),
35            on_changed,
36        }
37    }
38
39    /// Sets the widget identity.
40    pub fn key(mut self, key: KeyRef) -> Self {
41        self.key = Some(key);
42        self
43    }
44}
45
46impl fmt::Debug for SizeObserver {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("SizeObserver")
49            .field("key", &self.key)
50            .finish_non_exhaustive()
51    }
52}
53
54impl RenderObjectWidget for SizeObserver {
55    type RenderObject = RenderSizeObserver;
56
57    fn key(&self) -> Option<&KeyRef> {
58        self.key.as_ref()
59    }
60
61    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
62        RenderHandle::new_box(
63            app,
64            RenderSizeObserver {
65                render_object: RenderObjectData::new(),
66                render_box: RenderBoxData::new(),
67                child: RenderObjectWithChildData::new(),
68                on_changed: self.on_changed.clone(),
69                observed: Size::ZERO,
70                reported: Size::ZERO,
71                pending: false,
72                epoch: 0,
73            },
74        )
75        .as_object()
76    }
77
78    fn update_render_object(
79        &self,
80        app: &mut App,
81        _context: BuildContext,
82        render_object: RenderHandle<RenderSizeObserver>,
83    ) {
84        render_object.get_mut(app).on_changed = self.on_changed.clone();
85    }
86}
87
88impl SingleChildRenderObjectWidget for SizeObserver {
89    fn child(&self) -> Option<&WidgetRef> {
90        Some(&self.child)
91    }
92}
93
94/// A layout proxy that schedules size notifications without mutating the tree during layout.
95pub struct RenderSizeObserver {
96    render_object: RenderObjectData,
97    render_box: RenderBoxData,
98    child: RenderObjectWithChildData<AnyRenderBox>,
99    on_changed: SizeChangedCallback,
100    /// The last size produced by layout, which may not yet have been reported.
101    observed: Size,
102    /// The size delivered by the most recent callback.
103    reported: Size,
104    /// Whether this attachment already has a queued post-frame callback.
105    pending: bool,
106    /// Invalidates queued callbacks when this render object detaches.
107    epoch: u64,
108}
109
110impl RenderSizeObserver {
111    /// Queues one notification per frame and discards callbacks from an earlier attachment.
112    fn schedule_report(self: RenderHandle<Self>, app: &mut App) {
113        if self.get(app).pending || self.get(app).observed == self.get(app).reported {
114            return;
115        }
116        self.get_mut(app).pending = true;
117        let epoch = self.get(app).epoch;
118        SchedulerBinding::add_post_frame_callback(
119            app,
120            FrameCallback::new(move |app, _| {
121                if !app.contains(self.handle()) || app.is_disposed(self.handle()) {
122                    return;
123                }
124                if self.get(app).epoch != epoch || !self.as_object().attached(app) {
125                    return;
126                }
127                self.get_mut(app).pending = false;
128                let old = self.get(app).reported;
129                let new = self.get(app).observed;
130                if old == new {
131                    return;
132                }
133                self.get_mut(app).reported = new;
134                let callback = self.get(app).on_changed.clone();
135                callback(app, old, new);
136            }),
137            // Queued during layout, which every view of a frame shares: this frame's end runs it.
138            None,
139        );
140    }
141}
142
143impl RenderObjectWithChildMixin for RenderSizeObserver {
144    type ChildType = AnyRenderBox;
145
146    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
147        &self.get(app).child
148    }
149
150    fn child_data_mut(
151        self: RenderHandle<Self>,
152        app: &mut App,
153    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
154        &mut self.get_mut(app).child
155    }
156}
157
158impl RenderProxyBoxMixin for RenderSizeObserver {}
159
160impl RenderObject for RenderSizeObserver {
161    waft_rendering::render_object_accessors!();
162
163    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
164        RenderProxyBoxMixin::perform_layout(self, app);
165        self.get_mut(app).observed = self.as_box().size(app);
166        self.schedule_report(app);
167    }
168
169    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
170        if let Some(child) = self.child(app) {
171            child.as_object().attach(app, owner);
172        }
173        self.schedule_report(app);
174    }
175
176    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
177        self.get_mut(app).epoch += 1;
178        self.get_mut(app).pending = false;
179        if let Some(child) = self.child(app) {
180            child.as_object().detach(app);
181        }
182    }
183
184    fn paint(
185        self: RenderHandle<Self>,
186        app: &mut App,
187        context: &mut PaintingContext,
188        offset: Offset,
189    ) {
190        RenderProxyBoxMixin::paint(self, app, context, offset);
191    }
192
193    fn visit_children(
194        self: RenderHandle<Self>,
195        app: &App,
196        visitor: &mut dyn FnMut(AnyRenderObject),
197    ) {
198        if let Some(child) = self.child(app) {
199            visitor(child.as_object());
200        }
201    }
202}
203
204impl RenderBox for RenderSizeObserver {
205    waft_rendering::render_box_accessors!();
206
207    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
208        RenderProxyBoxMixin::setup_parent_data(self, app, child);
209    }
210
211    fn apply_paint_transform(
212        self: RenderHandle<Self>,
213        app: &App,
214        child: AnyRenderObject,
215        transform: &mut Matrix4,
216    ) {
217        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
218    }
219
220    fn hit_test_children(
221        self: RenderHandle<Self>,
222        app: &mut App,
223        result: &mut BoxHitTestResult<'_>,
224        position: Offset,
225    ) -> bool {
226        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
227    }
228
229    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
230        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
231    }
232
233    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
234        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
235    }
236
237    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
238        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
239    }
240
241    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
242        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
243    }
244
245    fn compute_distance_to_actual_baseline(
246        self: RenderHandle<Self>,
247        app: &mut App,
248        baseline: TextBaseline,
249    ) -> Option<f64> {
250        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
251    }
252
253    fn compute_dry_baseline(
254        self: RenderHandle<Self>,
255        app: &mut App,
256        constraints: BoxConstraints,
257        baseline: TextBaseline,
258    ) -> Option<f64> {
259        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
260    }
261
262    fn compute_dry_layout(
263        self: RenderHandle<Self>,
264        app: &mut App,
265        constraints: BoxConstraints,
266    ) -> Size {
267        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
268    }
269}