Skip to main content

cranpose_ui/
render_state.rs

1#[cfg(test)]
2use std::sync::{Mutex, OnceLock};
3use std::{
4    cell::{Cell, RefCell},
5    rc::{Rc, Weak},
6    sync::Arc,
7};
8
9use cranpose_core::{MemoryApplier, NodeId, PackedU64, RuntimeHandle, SnapshotStateObserver};
10
11pub(crate) type ModifierChainTraceCallback =
12    dyn Fn(&[crate::modifier::ModifierChainInspectorNode]) + Send + Sync + 'static;
13mod dirty_node_set;
14mod display_scale;
15mod draw_observation;
16mod geometry_scene_nodes;
17pub(crate) mod measure_reads;
18mod noted_scene_nodes;
19
20use dirty_node_set::DirtyNodeSet;
21use display_scale::normalize_density;
22pub use display_scale::{
23    MAX_FONT_SCALE, MIN_FONT_SCALE, current_density, current_font_scale, current_font_scale_curve,
24    scale_sp, set_density, set_font_scale, set_font_scale_curve,
25};
26pub(crate) use display_scale::{current_host_density, text_layout_stamp};
27use draw_observation::new_draw_observer;
28pub(crate) use draw_observation::{
29    DrawObservationScope, clear_draw_observations_for_node, observe_draw_reads,
30};
31pub use draw_observation::{prune_draw_observations_to_nodes, request_current_draw_redraw};
32pub use geometry_scene_nodes::{GeometrySceneNodes, MovedSceneNode};
33use noted_scene_nodes::NotedSceneNodes;
34
35struct RenderState {
36    layout_repasses: RefCell<DirtyNodeSet>,
37    measure_repasses: RefCell<DirtyNodeSet>,
38    draw_repasses: RefCell<DirtyNodeSet>,
39    layer_property_repasses: RefCell<DirtyNodeSet>,
40    modifier_slice_repasses: RefCell<DirtyNodeSet>,
41    geometry_scene_nodes: RefCell<NotedSceneNodes<NodeId>>,
42    moved_scene_nodes: RefCell<NotedSceneNodes<MovedSceneNode>>,
43    /// Nodes whose z index changed: their parents' layers hold the order.
44    z_order_changes: RefCell<DirtyNodeSet>,
45    /// Nodes whose redraw flag was set before they had an id, so no draw
46    /// repass names them: each surface's frame takes those under its root.
47    retained_redraws: RefCell<Vec<NodeId>>,
48    render_invalidated: Cell<bool>,
49    pointer_invalidated: Cell<bool>,
50    focus_invalidated: Cell<bool>,
51    layout_invalidated: Cell<bool>,
52    density_bits: Cell<u32>,
53    font_scale: Cell<crate::font_scale::FontScaleCurve>,
54    /// Whether `font_scale` leaves every size as it is, read by every text
55    /// measured instead of the curve.
56    font_scale_identity: Cell<bool>,
57    /// `font_scale`'s fingerprint, computed when the curve is set.
58    font_scale_fingerprint: Cell<u32>,
59}
60
61#[doc(hidden)]
62pub struct AppContext {
63    id: AppContextId,
64    self_weak: RefCell<Weak<Self>>,
65    state: RenderState,
66    draw_observer: SnapshotStateObserver,
67    // What each node's last measure read: a change measures the node again.
68    pub(crate) measure_reads: Rc<cranpose_core::internal::NodeReads>,
69    text: crate::text::measure::TextService,
70    layout_frame_arena: RefCell<crate::layout::FrameLayoutArena>,
71    /// The host the next layout pass lends its applier to; `None` while a
72    /// pass has it.
73    layout_host: RefCell<Option<crate::layout::LayoutHost>>,
74    layout_cache_epoch: Cell<u64>,
75    layout_cache_floor: Cell<u64>,
76    last_fling_velocity_bits: Cell<u32>,
77    scroll_motion_contexts: crate::scroll::ScrollMotionContextStore,
78    lazy_prefetch: crate::lazy_prefetch::LazyPrefetchState,
79    layout_node_registry: crate::widgets::nodes::LayoutNodeRegistryState,
80    pointer_dispatch: crate::dirty_node_queue::DirtyNodeQueue,
81    mouse_input: crate::mouse_input::MouseInputQueue,
82    pointer_claim: Cell<Option<NodeId>>,
83    focus_dispatch: crate::focus_dispatch::FocusInvalidationState,
84    modal: crate::modal::ModalState,
85    modal_nodes: crate::modal_nodes::ModalNodes,
86    semantics_layout: crate::semantics_layout_log::SemanticsLayoutLog,
87    hosted_popups: crate::widgets::popup::HostedPopupRegistries,
88    pub(crate) semantics_dispatch: crate::dirty_node_queue::DirtyNodeQueue,
89    pub(crate) cursor_animation: crate::cursor_animation::CursorAnimationState,
90    pub(crate) text_field_focus: crate::text_field_focus::TextFieldFocusState,
91    pub(crate) text_input_session: crate::text_input_session::PlatformTextInputState,
92    clipboard_session: crate::clipboard_session::ClipboardSessionState,
93    pointer_icon: crate::pointer_icon_session::PointerIconState,
94    pointer_input_tasks: crate::modifier::pointer_input::PointerInputTaskRegistry,
95    modifier_chain_trace: RefCell<Option<Arc<ModifierChainTraceCallback>>>,
96    window_roots: crate::modifier::WindowRootRegistry,
97    drag_and_drop: crate::modifier::DragAndDropState,
98    placement_pass: crate::widgets::nodes::PlacementPass,
99    memory_headroom: Cell<crate::MemoryHeadroom>,
100}
101
102/// Nonzero, so that an absent one takes no more room than one: every
103/// layout node keeps the id of the context it registered with.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
105pub(crate) struct AppContextId(std::num::NonZeroU32);
106
107impl RenderState {
108    fn new_with_density(density: f32) -> Self {
109        Self {
110            layout_repasses: RefCell::new(DirtyNodeSet::new()),
111            measure_repasses: RefCell::new(DirtyNodeSet::new()),
112            draw_repasses: RefCell::new(DirtyNodeSet::new()),
113            layer_property_repasses: RefCell::new(DirtyNodeSet::new()),
114            modifier_slice_repasses: RefCell::new(DirtyNodeSet::new()),
115            geometry_scene_nodes: RefCell::new(NotedSceneNodes::new()),
116            moved_scene_nodes: RefCell::new(NotedSceneNodes::new()),
117            z_order_changes: RefCell::new(DirtyNodeSet::new()),
118            retained_redraws: RefCell::new(Vec::new()),
119            render_invalidated: Cell::new(false),
120            pointer_invalidated: Cell::new(false),
121            focus_invalidated: Cell::new(false),
122            layout_invalidated: Cell::new(false),
123            density_bits: Cell::new(normalize_density(density).to_bits()),
124            font_scale: Cell::new(crate::font_scale::FontScaleCurve::linear(1.0)),
125            font_scale_identity: Cell::new(true),
126            font_scale_fingerprint: Cell::new(
127                crate::font_scale::FontScaleCurve::linear(1.0).fingerprint(),
128            ),
129        }
130    }
131}
132
133fn next_app_context_id() -> AppContextId {
134    crate::thread_state::cells(|cells| {
135        let next = &cells.next_app_context_id;
136        let id = next.get();
137        next.set(id.checked_add(1).unwrap_or(std::num::NonZeroU32::MIN));
138        AppContextId(id)
139    })
140}
141
142#[doc(hidden)]
143pub struct AppContextScope;
144
145impl Drop for AppContextScope {
146    fn drop(&mut self) {
147        crate::thread_state::try_with(|state| {
148            state.app_context_stack.borrow_mut().pop();
149        });
150    }
151}
152
153impl AppContext {
154    pub fn new() -> Rc<Self> {
155        Self::new_with_density(1.0, None)
156    }
157
158    pub fn new_with_density(density: f32, runtime: Option<RuntimeHandle>) -> Rc<Self> {
159        let id = next_app_context_id();
160        let context = Rc::new(Self {
161            id,
162            self_weak: RefCell::new(Weak::new()),
163            state: RenderState::new_with_density(density),
164            draw_observer: new_draw_observer(runtime),
165            measure_reads: measure_reads::new(id),
166            text: crate::text::measure::TextService::new(),
167            layout_frame_arena: RefCell::new(crate::layout::FrameLayoutArena::default()),
168            layout_host: RefCell::new(None),
169            layout_cache_epoch: Cell::new(1),
170            layout_cache_floor: Cell::new(0),
171            last_fling_velocity_bits: Cell::new(0.0f32.to_bits()),
172            scroll_motion_contexts: crate::scroll::ScrollMotionContextStore::new(),
173            lazy_prefetch: crate::lazy_prefetch::LazyPrefetchState::new(),
174            layout_node_registry: crate::widgets::nodes::LayoutNodeRegistryState::new(),
175            pointer_dispatch: crate::dirty_node_queue::DirtyNodeQueue::new(),
176            mouse_input: crate::mouse_input::MouseInputQueue::default(),
177            pointer_claim: Cell::new(None),
178            focus_dispatch: crate::focus_dispatch::FocusInvalidationState::new(),
179            modal: crate::modal::ModalState::new(),
180            modal_nodes: crate::modal_nodes::ModalNodes::default(),
181            semantics_layout: crate::semantics_layout_log::SemanticsLayoutLog::default(),
182            hosted_popups: crate::widgets::popup::HostedPopupRegistries::default(),
183            semantics_dispatch: crate::dirty_node_queue::DirtyNodeQueue::new(),
184            cursor_animation: crate::cursor_animation::CursorAnimationState::new(),
185            text_field_focus: crate::text_field_focus::TextFieldFocusState::new(),
186            text_input_session: crate::text_input_session::PlatformTextInputState::new(),
187            clipboard_session: crate::clipboard_session::ClipboardSessionState::new(),
188            pointer_icon: crate::pointer_icon_session::PointerIconState::new(),
189            pointer_input_tasks: crate::modifier::pointer_input::PointerInputTaskRegistry::new(),
190            modifier_chain_trace: RefCell::new(None),
191            window_roots: crate::modifier::WindowRootRegistry::default(),
192            drag_and_drop: crate::modifier::DragAndDropState::default(),
193            placement_pass: crate::widgets::nodes::PlacementPass::new(),
194            memory_headroom: Cell::new(crate::MemoryHeadroom::Ample),
195        });
196        *context.self_weak.borrow_mut() = Rc::downgrade(&context);
197        crate::thread_state::with(|state| {
198            state
199                .app_contexts
200                .borrow_mut()
201                .insert(context.id, Rc::downgrade(&context));
202        });
203        context
204    }
205
206    pub fn enter<R>(self: &Rc<Self>, block: impl FnOnce() -> R) -> R {
207        let _scope = self.enter_scope();
208        block()
209    }
210
211    pub(crate) fn id(&self) -> AppContextId {
212        self.id
213    }
214
215    pub(crate) fn mouse_input(&self) -> &crate::mouse_input::MouseInputQueue {
216        &self.mouse_input
217    }
218
219    /// Number of coalesced mouse movements waiting for host dispatch.
220    #[doc(hidden)]
221    pub fn pending_mouse_moves(&self) -> usize {
222        self.mouse_input.len()
223    }
224
225    /// Takes the oldest queued mouse movement, retaining the queue's storage.
226    #[doc(hidden)]
227    pub fn take_mouse_move(&self) -> Option<crate::mouse_input::MouseMoveRequest> {
228        self.mouse_input.take()
229    }
230
231    /// Asks the shell to give the rest of the held press to `node` alone: the
232    /// other targets under the press see it cancelled.
233    pub(crate) fn claim_pointer(&self, node: NodeId) {
234        self.pointer_claim.set(Some(node));
235    }
236
237    /// Takes the node that claimed the held press since the last call.
238    #[doc(hidden)]
239    pub fn take_pointer_claim(&self) -> Option<NodeId> {
240        self.pointer_claim.take()
241    }
242
243    /// The window roots attached in this context.
244    pub fn window_roots(&self) -> &crate::modifier::WindowRootRegistry {
245        &self.window_roots
246    }
247
248    /// The drag and drop transfer and targets of this context.
249    pub fn drag_and_drop(&self) -> &crate::modifier::DragAndDropState {
250        &self.drag_and_drop
251    }
252
253    #[doc(hidden)]
254    pub fn enter_scope(self: &Rc<Self>) -> AppContextScope {
255        crate::thread_state::with(|state| {
256            state
257                .app_context_stack
258                .borrow_mut()
259                .push(Rc::downgrade(self));
260        });
261        AppContextScope
262    }
263
264    /// Lays this app's text out with `fonts` from now on.
265    pub fn set_text_fonts(&self, fonts: cranpose_text::FontFamilyResolver) {
266        self.text.set_fonts(fonts);
267        self.invalidate_layout_caches();
268        self.state.layout_invalidated.set(true);
269        self.state.render_invalidated.set(true);
270    }
271
272    fn invalidate_layout_caches(&self) {
273        let floor = self.layout_cache_epoch.get() + 1;
274        self.layout_cache_epoch.set(floor);
275        self.layout_cache_floor.set(floor);
276    }
277
278    #[doc(hidden)]
279    pub fn downgrade(&self) -> Weak<Self> {
280        self.self_weak.borrow().clone()
281    }
282
283    // What a layout pass takes from its app context. A pass looks the
284    // context up once and asks it directly: each lookup reads a thread-local,
285    // which on ESP-IDF goes through a pthread key.
286
287    /// Tells the text service, and its measurer, a layout pass starts.
288    pub(crate) fn begin_text_layout_pass(&self) {
289        self.text.begin_layout_pass();
290    }
291
292    pub(crate) fn take_layout_frame_arena(&self) -> crate::layout::FrameLayoutArena {
293        std::mem::take(&mut *self.layout_frame_arena.borrow_mut())
294    }
295
296    pub(crate) fn replace_layout_frame_arena(&self, arena: crate::layout::FrameLayoutArena) {
297        *self.layout_frame_arena.borrow_mut() = arena;
298    }
299
300    /// The host for a layout pass: the one the last pass gave back, or a new
301    /// one when a pass is still running or none ran yet.
302    pub(crate) fn take_layout_host(&self) -> crate::layout::LayoutHost {
303        self.layout_host.borrow_mut().take().unwrap_or_default()
304    }
305
306    pub(crate) fn replace_layout_host(&self, host: crate::layout::LayoutHost) {
307        *self.layout_host.borrow_mut() = Some(host);
308    }
309
310    pub(crate) fn next_layout_cache_epoch(&self) -> u64 {
311        let epoch = self.layout_cache_epoch.get();
312        self.layout_cache_epoch.set(epoch + 1);
313        epoch
314    }
315
316    pub(crate) fn layout_cache_floor(&self) -> u64 {
317        self.layout_cache_floor.get()
318    }
319
320    pub(crate) fn current_layout_cache_epoch(&self) -> u64 {
321        self.layout_cache_epoch.get()
322    }
323
324    pub(crate) fn take_modifier_slice_repass_nodes(&self) -> Vec<NodeId> {
325        self.state
326            .modifier_slice_repasses
327            .borrow_mut()
328            .take_dirty_nodes()
329    }
330
331    pub(crate) fn take_measure_repass_nodes(&self) -> Vec<NodeId> {
332        self.state.measure_repasses.borrow_mut().take_dirty_nodes()
333    }
334
335    pub(crate) fn take_layout_repass_nodes(&self) -> Vec<NodeId> {
336        self.state.layout_repasses.borrow_mut().take_dirty_nodes()
337    }
338
339    pub(crate) fn lazy_prefetch(&self) -> &crate::lazy_prefetch::LazyPrefetchState {
340        &self.lazy_prefetch
341    }
342
343    pub(crate) fn memory_headroom(&self) -> crate::MemoryHeadroom {
344        self.memory_headroom.get()
345    }
346
347    pub(crate) fn set_memory_headroom(&self, headroom: crate::MemoryHeadroom) {
348        self.memory_headroom.set(headroom);
349    }
350
351    /// Whether the next frame has work in this context: a render, pointer,
352    /// focus or layout invalidation, or a layout, measure or layer-property
353    /// repass. Reads the context directly, without looking up the current
354    /// one.
355    pub fn has_pending_frame_work(&self) -> bool {
356        let state = &self.state;
357        state.render_invalidated.get()
358            || state.pointer_invalidated.get()
359            || state.focus_invalidated.get()
360            || state.layout_invalidated.get()
361            || state.layout_repasses.borrow_mut().has_pending_repass()
362            || state.measure_repasses.borrow_mut().has_pending_repass()
363            || state
364                .layer_property_repasses
365                .borrow_mut()
366                .has_pending_repass()
367    }
368
369    /// [`Self::has_pending_frame_work`], or a pending draw or pointer repass
370    /// or focus invalidation.
371    pub fn has_stale_work(&self) -> bool {
372        self.has_pending_frame_work()
373            || self.state.draw_repasses.borrow_mut().has_pending_repass()
374            || self.pointer_dispatch.has_pending()
375            || self.focus_dispatch.invalidations.has_pending()
376    }
377
378    /// Whether a modal node may be live in this context.
379    ///
380    /// While `count` holds, the context keeps its modal nodes: the first call
381    /// reads every node of `applier` once, and later calls read only the nodes
382    /// whose semantics changed since. Without `count` nothing is kept and the
383    /// answer is always `true`, leaving the caller to walk.
384    pub fn modal_node_may_be_live(&self, applier: &mut MemoryApplier, count: bool) -> bool {
385        self.modal_nodes.may_be_live(applier, count)
386    }
387
388    /// Whether a dismissable popup is open on one of this context's hosts.
389    /// Unlike [`crate::dismissable_popup_open`], a composable that asks does
390    /// not recompose when popups open or close.
391    pub fn dismissable_popup_open(&self) -> bool {
392        self.hosted_popups.dismissable_open(false)
393    }
394
395    /// Moves the nodes waiting for a draw repass into `output`, as
396    /// [`take_draw_repass_nodes_into`] does in the current context.
397    pub fn take_draw_repass_nodes_into(&self, output: &mut Vec<NodeId>) {
398        self.state
399            .draw_repasses
400            .borrow_mut()
401            .take_dirty_nodes_into(output);
402    }
403
404    /// Moves into `output` the nodes whose redraw flag was set before they
405    /// had an id, for a surface's frame to take those under its root.
406    pub fn take_retained_redraw_nodes_into(&self, output: &mut Vec<NodeId>) {
407        output.append(&mut self.state.retained_redraws.borrow_mut());
408    }
409
410    /// Gives back a node [`Self::take_retained_redraw_nodes_into`] moved out
411    /// that the surface did not take: one under another window root or not
412    /// attached yet.
413    pub fn keep_retained_redraw_node(&self, node_id: NodeId) {
414        self.state.retained_redraws.borrow_mut().push(node_id);
415    }
416
417    /// Appends the nodes whose z index changed since the last call to
418    /// `output`, as [`append_z_order_changes`] does in the current context.
419    pub fn append_z_order_changes(&self, output: &mut Vec<NodeId>) {
420        let mut changes = self.state.z_order_changes.borrow_mut();
421        if !changes.dirty_nodes.is_empty() {
422            output.extend(changes.dirty_nodes.drain());
423        }
424    }
425
426    /// Moves the nodes waiting for a graphics-layer property update into
427    /// `output`, as [`take_layer_property_repass_nodes_into`] does in the
428    /// current context.
429    pub fn take_layer_property_repass_nodes_into(&self, output: &mut Vec<NodeId>) {
430        self.state
431            .layer_property_repasses
432            .borrow_mut()
433            .take_dirty_nodes_into(output);
434    }
435
436    /// Whether a layout repass waits, as [`has_pending_layout_repasses`]
437    /// says in the current context.
438    pub fn has_pending_layout_repasses(&self) -> bool {
439        self.state.layout_repasses.borrow_mut().has_pending_repass()
440    }
441
442    /// The nodes waiting for a layout repass, which stay waiting.
443    pub fn pending_layout_repass_nodes_snapshot(&self) -> Vec<NodeId> {
444        self.state
445            .layout_repasses
446            .borrow_mut()
447            .dirty_nodes_snapshot()
448    }
449
450    /// Whether a measure repass waits, as [`has_pending_measure_repasses`]
451    /// says in the current context.
452    pub fn has_pending_measure_repasses(&self) -> bool {
453        self.state
454            .measure_repasses
455            .borrow_mut()
456            .has_pending_repass()
457    }
458
459    /// The nodes waiting for a measure repass, which stay waiting.
460    pub fn pending_measure_repass_nodes_snapshot(&self) -> Vec<NodeId> {
461        self.state
462            .measure_repasses
463            .borrow_mut()
464            .dirty_nodes_snapshot()
465    }
466
467    /// Moves the nodes whose geometry the last layout pass changed into
468    /// `output`, as [`take_geometry_scene_nodes_into`] does in the current
469    /// context.
470    pub fn take_geometry_scene_nodes_into(&self, output: &mut GeometrySceneNodes) {
471        self.state
472            .geometry_scene_nodes
473            .borrow_mut()
474            .take_into(&mut output.reshaped);
475        self.state
476            .moved_scene_nodes
477            .borrow_mut()
478            .take_into(&mut output.moved);
479    }
480
481    /// Notes that the layout pass changed `node_id`'s geometry. A node
482    /// whose layout state is at hand notes it with
483    /// [`Self::note_geometry_scene_node`] instead, once a take.
484    pub(crate) fn record_geometry_scene_node(&self, node_id: NodeId) {
485        self.state.geometry_scene_nodes.borrow_mut().push(node_id);
486    }
487
488    /// Notes that the layout pass changed `node_id`'s geometry. `noted_in`
489    /// is the node's own record of the take it was last noted in.
490    pub(crate) fn note_geometry_scene_node(&self, node_id: NodeId, noted_in: &mut PackedU64) {
491        self.state
492            .geometry_scene_nodes
493            .borrow_mut()
494            .note(node_id, noted_in);
495    }
496
497    /// Notes that the layout pass moved `node_id`, which `placer` placed, and
498    /// changed nothing else of it, so the scene can keep what it drew for the
499    /// node. `noted_in` is the node's own record of the take it was last
500    /// noted in.
501    pub(crate) fn record_moved_scene_node(
502        &self,
503        node_id: NodeId,
504        placer: Option<NodeId>,
505        noted_in: &mut PackedU64,
506    ) {
507        self.state.moved_scene_nodes.borrow_mut().note(
508            MovedSceneNode {
509                node: node_id,
510                placer,
511            },
512            noted_in,
513        );
514    }
515
516    /// The placement bookkeeping of this context's running layout pass.
517    pub(crate) fn placement_pass(&self) -> &crate::widgets::nodes::PlacementPass {
518        &self.placement_pass
519    }
520
521    /// Takes the pending layout invalidation, as [`take_layout_invalidation`]
522    /// does in the current context.
523    pub fn take_layout_invalidation(&self) -> bool {
524        self.state.layout_invalidated.replace(false)
525    }
526
527    /// Starts a frame for the text caches. The first text measured in it
528    /// outside a layout pass, as a draw scope measures its labels, begins a
529    /// pass of the caches, so a text that a frame only draws ages out as a
530    /// laid-out one does.
531    pub fn start_text_frame(&self) {
532        self.text.owe_pass();
533    }
534
535    /// Takes the pending render invalidation, as [`take_render_invalidation`]
536    /// does in the current context.
537    pub fn take_render_invalidation(&self) -> bool {
538        self.state.render_invalidated.replace(false)
539    }
540
541    /// Takes the pending pointer invalidation, as
542    /// [`take_pointer_invalidation`] does in the current context.
543    pub fn take_pointer_invalidation(&self) -> bool {
544        self.state.pointer_invalidated.replace(false)
545    }
546
547    /// Takes the pending focus invalidation, as [`take_focus_invalidation`]
548    /// does in the current context.
549    pub fn take_focus_invalidation(&self) -> bool {
550        self.state.focus_invalidated.replace(false)
551    }
552
553    /// Ends the frame for the transient scroll motion contexts, as
554    /// [`clear_transient_scroll_motion_contexts`] does in the current context.
555    pub fn clear_transient_scroll_motion_contexts(&self) {
556        self.scroll_motion_contexts.clear_transient_after_frame();
557    }
558
559    /// Whether a pointer repass waits, as
560    /// [`crate::has_pending_pointer_repasses`] says in the current context.
561    pub fn has_pending_pointer_repasses(&self) -> bool {
562        self.pointer_dispatch.has_pending()
563    }
564
565    /// Whether a focus invalidation waits, as
566    /// [`crate::has_pending_focus_invalidations`] says in the current context.
567    pub fn has_pending_focus_invalidations(&self) -> bool {
568        self.focus_dispatch.invalidations.has_pending()
569    }
570
571    /// The node holding focus, as [`crate::active_focus_target`] says in the
572    /// current context.
573    pub fn active_focus_target(&self) -> Option<NodeId> {
574        self.focus_dispatch.active_focus_target()
575    }
576
577    /// Whether a semantics invalidation waits, as
578    /// [`has_pending_semantics_invalidations`](crate::has_pending_semantics_invalidations)
579    /// says in the current context.
580    pub fn has_pending_semantics_invalidations(&self) -> bool {
581        self.semantics_dispatch.has_pending()
582    }
583
584    /// Whether a text field holds focus, as
585    /// [`has_focused_field`](crate::has_focused_field) says in the current
586    /// context; without one, the keyboard the framework asked for goes away.
587    pub fn has_focused_field(&self) -> bool {
588        let has_focus = self.text_field_focus.has_focused_field();
589        if !has_focus {
590            self.text_input_session.notify_focus_lost();
591        }
592        has_focus
593    }
594
595    /// Advances the cursor blink, as
596    /// [`tick_cursor_blink`](crate::tick_cursor_blink) does in the current
597    /// context.
598    pub fn tick_cursor_blink(&self) -> bool {
599        // Without a focused field no caret blinks, and the clock is not read.
600        self.cursor_animation.next_blink_time().is_some()
601            && self.cursor_animation.tick_blink(web_time::Instant::now())
602    }
603}
604
605impl Drop for AppContext {
606    fn drop(&mut self) {
607        let id = self.id;
608        crate::thread_state::try_with(|state| {
609            state.app_contexts.borrow_mut().remove(&id);
610        });
611    }
612}
613
614fn app_context_by_id(id: AppContextId) -> Option<Rc<AppContext>> {
615    crate::thread_state::try_with(|state| {
616        let contexts = &state.app_contexts;
617        let context = contexts.borrow().get(&id).cloned()?;
618        let Some(context) = context.upgrade() else {
619            contexts.borrow_mut().remove(&id);
620            return None;
621        };
622        Some(context)
623    })
624    .flatten()
625}
626
627#[cfg(test)]
628fn app_context_registry_entry_count() -> usize {
629    crate::thread_state::try_with(|state| state.app_contexts.borrow().len()).unwrap_or_default()
630}
631
632pub(crate) fn with_app_context_by_id<R>(
633    id: AppContextId,
634    f: impl FnOnce(&Rc<AppContext>) -> R,
635) -> Option<R> {
636    app_context_by_id(id).map(|context| f(&context))
637}
638
639pub(crate) fn current_app_context_id() -> AppContextId {
640    require_current_app_context("app context identity access").id
641}
642
643pub(crate) fn with_layout_node_registry_by_app_context<R>(
644    id: AppContextId,
645    f: impl FnOnce(&crate::widgets::nodes::LayoutNodeRegistryState) -> R,
646) -> Option<R> {
647    with_app_context_by_id(id, |context| f(&context.layout_node_registry))
648}
649
650pub(crate) fn enter_app_context_by_id<R>(id: AppContextId, f: impl FnOnce() -> R) -> Option<R> {
651    with_app_context_by_id(id, |context| context.enter(f))
652}
653
654pub(crate) fn current_app_context() -> Option<Rc<AppContext>> {
655    crate::thread_state::try_with(|state| {
656        let mut stack = state.app_context_stack.borrow_mut();
657        loop {
658            let context = stack.last()?;
659            if let Some(context) = context.upgrade() {
660                return Some(context);
661            }
662            stack.pop();
663        }
664    })
665    .flatten()
666}
667
668#[doc(hidden)]
669pub fn has_current_app_context() -> bool {
670    current_app_context().is_some()
671}
672
673pub(crate) fn require_current_app_context(operation: &str) -> Rc<AppContext> {
674    if let Some(context) = current_app_context() {
675        return context;
676    }
677    require_current_app_context_without_scope(operation)
678}
679
680fn require_current_app_context_without_scope(operation: &str) -> Rc<AppContext> {
681    panic!("{operation} requires an active AppContext")
682}
683
684fn with_render_state<R>(f: impl FnOnce(&RenderState) -> R) -> R {
685    let context = require_current_app_context("render state access");
686    f(&context.state)
687}
688
689pub(crate) fn with_text_service<R>(f: impl FnOnce(&crate::text::measure::TextService) -> R) -> R {
690    let context = require_current_app_context("text service access");
691    context.text.pay_owed_pass();
692    f(&context.text)
693}
694
695pub(crate) fn set_modifier_chain_trace(callback: Arc<ModifierChainTraceCallback>) -> AppContextId {
696    let context = require_current_app_context("modifier chain trace installation");
697    *context.modifier_chain_trace.borrow_mut() = Some(callback);
698    context.id
699}
700
701pub(crate) fn clear_modifier_chain_trace(context_id: AppContextId) {
702    let _ = with_app_context_by_id(context_id, |context| {
703        *context.modifier_chain_trace.borrow_mut() = None;
704    });
705}
706
707pub(crate) fn emit_modifier_chain_trace(nodes: &[crate::modifier::ModifierChainInspectorNode]) {
708    let Some(context) = current_app_context() else {
709        return;
710    };
711    let callback = context.modifier_chain_trace.borrow().clone();
712    if let Some(callback) = callback {
713        callback(nodes);
714    }
715}
716
717pub(crate) fn invalidate_layout_cache_epoch() {
718    require_current_app_context("layout cache epoch access").invalidate_layout_caches();
719}
720
721pub(crate) fn record_last_fling_velocity(velocity: f32) {
722    if let Some(context) = current_app_context() {
723        context.last_fling_velocity_bits.set(velocity.to_bits());
724    }
725}
726
727#[doc(hidden)]
728pub fn debug_last_fling_velocity() -> f32 {
729    let context = require_current_app_context("fling velocity diagnostics access");
730    f32::from_bits(context.last_fling_velocity_bits.get())
731}
732
733#[doc(hidden)]
734pub fn debug_reset_last_fling_velocity() {
735    let context = require_current_app_context("fling velocity diagnostics access");
736    context.last_fling_velocity_bits.set(0.0f32.to_bits());
737}
738
739pub(crate) fn with_scroll_motion_context_store<R>(
740    f: impl FnOnce(&crate::scroll::ScrollMotionContextStore) -> R,
741) -> R {
742    let context = require_current_app_context("scroll motion context access");
743    f(&context.scroll_motion_contexts)
744}
745
746#[doc(hidden)]
747pub fn clear_transient_scroll_motion_contexts() {
748    if let Some(context) = current_app_context() {
749        context.clear_transient_scroll_motion_contexts();
750    }
751}
752
753#[cfg(test)]
754pub(crate) fn layout_frame_arena_placement_scratch_count() -> usize {
755    let context = require_current_app_context("layout frame arena access");
756
757    context
758        .layout_frame_arena
759        .borrow()
760        .available_placement_scratch_count()
761}
762
763/// Runs `f` on the current app context's layout node registry and returns
764/// that context's id.
765pub(crate) fn with_current_layout_node_registry(
766    f: impl FnOnce(&crate::widgets::nodes::LayoutNodeRegistryState),
767) -> AppContextId {
768    let context = require_current_app_context("layout node registry access");
769    f(&context.layout_node_registry);
770    context.id
771}
772
773pub(crate) fn with_layout_node_registry<R>(
774    f: impl FnOnce(&crate::widgets::nodes::LayoutNodeRegistryState) -> R,
775) -> R {
776    let context = require_current_app_context("layout node registry access");
777    f(&context.layout_node_registry)
778}
779
780pub(crate) fn with_pointer_dispatch<R>(
781    f: impl FnOnce(&crate::dirty_node_queue::DirtyNodeQueue) -> R,
782) -> R {
783    let context = require_current_app_context("pointer dispatch access");
784    f(&context.pointer_dispatch)
785}
786
787pub(crate) fn with_focus_dispatch<R>(
788    f: impl FnOnce(&crate::focus_dispatch::FocusInvalidationState) -> R,
789) -> R {
790    let context = require_current_app_context("focus dispatch access");
791    f(&context.focus_dispatch)
792}
793
794pub(crate) fn with_focus_dispatch_by_app_context<R>(
795    id: AppContextId,
796    f: impl FnOnce(&crate::focus_dispatch::FocusInvalidationState) -> R,
797) -> Option<R> {
798    with_app_context_by_id(id, |context| context.enter(|| f(&context.focus_dispatch)))
799}
800
801pub(crate) fn with_modal_state<R>(f: impl FnOnce(&crate::modal::ModalState) -> R) -> R {
802    let context = require_current_app_context("modal state access");
803    f(&context.modal)
804}
805
806pub(crate) fn with_current_modal_nodes<R>(
807    f: impl FnOnce(&crate::modal_nodes::ModalNodes) -> R,
808) -> Option<R> {
809    current_app_context().map(|context| f(&context.modal_nodes))
810}
811
812pub(crate) fn with_current_semantics_layout_log<R>(
813    f: impl FnOnce(&crate::semantics_layout_log::SemanticsLayoutLog) -> R,
814) -> Option<R> {
815    current_app_context().map(|context| f(&context.semantics_layout))
816}
817
818pub(crate) fn with_hosted_popup_registries<R>(
819    f: impl FnOnce(&crate::widgets::popup::HostedPopupRegistries) -> R,
820) -> R {
821    let context = require_current_app_context("hosted popup registries access");
822    f(&context.hosted_popups)
823}
824
825pub(crate) fn with_semantics_dispatch<R>(
826    f: impl FnOnce(&crate::dirty_node_queue::DirtyNodeQueue) -> R,
827) -> R {
828    let context = require_current_app_context("semantics dispatch access");
829    f(&context.semantics_dispatch)
830}
831
832pub(crate) fn with_semantics_dispatch_by_app_context(
833    id: AppContextId,
834    f: impl FnOnce(&crate::dirty_node_queue::DirtyNodeQueue),
835) {
836    with_app_context_by_id(id, |context| f(&context.semantics_dispatch));
837}
838
839pub(crate) fn current_app_context_id_opt() -> Option<AppContextId> {
840    current_app_context().map(|context| context.id)
841}
842
843pub(crate) fn with_cursor_animation<R>(
844    f: impl FnOnce(&crate::cursor_animation::CursorAnimationState) -> R,
845) -> R {
846    let context = require_current_app_context("cursor animation access");
847    f(&context.cursor_animation)
848}
849
850pub(crate) fn with_text_field_focus<R>(
851    f: impl FnOnce(&crate::text_field_focus::TextFieldFocusState) -> R,
852) -> R {
853    let context = require_current_app_context("text field focus access");
854    f(&context.text_field_focus)
855}
856
857pub(crate) fn with_text_input_session<R>(
858    f: impl FnOnce(&crate::text_input_session::PlatformTextInputState) -> R,
859) -> R {
860    let context = require_current_app_context("platform text input session access");
861    f(&context.text_input_session)
862}
863
864pub(crate) fn with_clipboard_session<R>(
865    f: impl FnOnce(&crate::clipboard_session::ClipboardSessionState) -> R,
866) -> R {
867    let context = require_current_app_context("clipboard session access");
868    f(&context.clipboard_session)
869}
870
871pub(crate) fn with_pointer_icon_session<R>(
872    f: impl FnOnce(&crate::pointer_icon_session::PointerIconState) -> R,
873) -> R {
874    let context = require_current_app_context("pointer icon session access");
875    f(&context.pointer_icon)
876}
877
878pub(crate) fn register_pointer_input_task(
879    task_id: u64,
880    task: Rc<crate::modifier::pointer_input::PointerInputTaskInner>,
881) -> crate::modifier::pointer_input::PointerInputTaskOwner {
882    let context = require_current_app_context("pointer input task registration");
883    context.pointer_input_tasks.insert(task_id, task);
884    crate::modifier::pointer_input::PointerInputTaskOwner::App(context.id)
885}
886
887pub(crate) fn remove_pointer_input_task(
888    owner: crate::modifier::pointer_input::PointerInputTaskOwner,
889    task_id: u64,
890) {
891    match owner {
892        crate::modifier::pointer_input::PointerInputTaskOwner::App(context_id) => {
893            let _ = with_app_context_by_id(context_id, |context| {
894                context.pointer_input_tasks.remove(task_id);
895            });
896        }
897    }
898}
899
900pub(crate) fn request_pointer_input_task_poll(
901    owner: crate::modifier::pointer_input::PointerInputTaskOwner,
902    task_id: u64,
903) {
904    match owner {
905        crate::modifier::pointer_input::PointerInputTaskOwner::App(context_id) => {
906            let _ = with_app_context_by_id(context_id, |context| {
907                context.enter(|| {
908                    context.pointer_input_tasks.request_poll(task_id, owner);
909                });
910            });
911        }
912    }
913}
914
915fn with_draw_observer<R>(f: impl FnOnce(&SnapshotStateObserver) -> R) -> R {
916    let context = require_current_app_context("draw observer access");
917    f(&context.draw_observer)
918}
919
920/// Schedules a layout repass for a specific node.
921///
922/// **This is the preferred way to invalidate layout for local changes** (e.g., scroll, single-node mutations).
923///
924/// The app shell will call `take_layout_repass_nodes()` and bubble dirty flags up the tree
925/// via `bubble_layout_dirty`. This gives you **O(subtree) performance** - only the affected
926/// subtree is remeasured, and layout caches for other parts of the app remain valid.
927///
928/// A scoped repass never invalidates the whole tree, and it never cancels a global
929/// invalidation requested for the same frame.
930///
931/// # For Global Invalidation
932///
933/// For rare global events (window resize, global scale changes), use `request_layout_invalidation()` instead.
934#[track_caller]
935pub fn schedule_layout_repass(node_id: NodeId) {
936    if layout_repass_schedule_diagnostics_enabled_for(node_id) {
937        let caller = std::panic::Location::caller();
938        log::warn!(
939            "[layout-repass-schedule] node={} caller={}:{}:{}",
940            node_id,
941            caller.file(),
942            caller.line(),
943            caller.column()
944        );
945    }
946    with_render_state(|state| {
947        state.layout_repasses.borrow_mut().schedule_repass(node_id);
948    });
949    request_render_invalidation();
950}
951
952#[derive(Clone, Copy)]
953enum LayoutRepassScheduleDiag {
954    Disabled,
955    All,
956    Node(NodeId),
957}
958
959fn layout_repass_schedule_diagnostics_enabled_for(node_id: NodeId) -> bool {
960    let mode = cranpose_core::DIAGNOSTICS
961        .layout_repass_schedule_diag
962        .with(|value| match value {
963            None => LayoutRepassScheduleDiag::Disabled,
964            Some("all") => LayoutRepassScheduleDiag::All,
965            Some(value) => value.parse::<NodeId>().map_or(
966                LayoutRepassScheduleDiag::Disabled,
967                LayoutRepassScheduleDiag::Node,
968            ),
969        });
970    match mode {
971        LayoutRepassScheduleDiag::Disabled => false,
972        LayoutRepassScheduleDiag::All => true,
973        LayoutRepassScheduleDiag::Node(target) => target == node_id,
974    }
975}
976
977pub(crate) fn schedule_modifier_slices_repass(node_id: NodeId) {
978    with_render_state(|state| {
979        state
980            .modifier_slice_repasses
981            .borrow_mut()
982            .schedule_repass(node_id);
983    });
984    schedule_draw_repass(node_id);
985}
986
987/// Schedules a draw-only repass for a specific node.
988///
989/// This ensures draw/pointer data stays in sync when modifier updates do not
990/// require a layout pass (e.g., draw-only modifier changes).
991pub fn schedule_draw_repass(node_id: NodeId) {
992    let context = require_current_app_context("render state access");
993    schedule_draw_repass_in_context(&context, node_id);
994}
995
996fn schedule_draw_repass_for_app_context(context_id: AppContextId, node_id: NodeId) {
997    let _ = with_app_context_by_id(context_id, |context| {
998        schedule_draw_repass_in_context(context, node_id);
999    });
1000}
1001
1002fn schedule_draw_repass_in_context(context: &AppContext, node_id: NodeId) {
1003    context
1004        .state
1005        .draw_repasses
1006        .borrow_mut()
1007        .schedule_repass(node_id);
1008    context.state.render_invalidated.set(true);
1009}
1010
1011fn schedule_layer_property_repass_for_app_context(context_id: AppContextId, node_id: NodeId) {
1012    let _ = with_app_context_by_id(context_id, |context| {
1013        schedule_layer_property_repass_in_context(context, node_id);
1014    });
1015}
1016
1017fn schedule_layer_property_repass_in_context(context: &AppContext, node_id: NodeId) {
1018    context
1019        .state
1020        .layer_property_repasses
1021        .borrow_mut()
1022        .schedule_repass(node_id);
1023    context.state.render_invalidated.set(true);
1024}
1025
1026/// Notes `node_id`, whose redraw flag was set before it had an id, in the
1027/// current context: no draw repass names it, so a surface's frame takes it.
1028pub(crate) fn note_retained_redraw(node_id: NodeId) {
1029    if let Some(context) = current_app_context() {
1030        context.keep_retained_redraw_node(node_id);
1031    }
1032}
1033
1034/// Returns true if any draw repasses are pending.
1035pub fn has_pending_draw_repasses() -> bool {
1036    with_render_state(|state| state.draw_repasses.borrow_mut().has_pending_repass())
1037}
1038
1039/// Takes all pending draw repass node IDs.
1040pub fn take_draw_repass_nodes() -> Vec<NodeId> {
1041    with_render_state(|state| state.draw_repasses.borrow_mut().take_dirty_nodes())
1042}
1043
1044/// Takes pending draw repasses into reusable caller-owned storage.
1045///
1046/// ```
1047/// let context = cranpose_ui::AppContext::new();
1048/// context.enter(|| {
1049///     let mut nodes = Vec::new();
1050///     cranpose_ui::take_draw_repass_nodes_into(&mut nodes);
1051///     assert!(nodes.is_empty());
1052/// });
1053/// ```
1054pub fn take_draw_repass_nodes_into(output: &mut Vec<NodeId>) {
1055    require_current_app_context("render state access").take_draw_repass_nodes_into(output);
1056}
1057
1058/// Records that `node_id`'s z index changed. The frame rebuilds the layer of
1059/// its parent, which holds the order the parent's children draw and take
1060/// taps in.
1061pub fn schedule_z_order_change(node_id: NodeId) {
1062    with_render_state(|state| {
1063        state.z_order_changes.borrow_mut().schedule_repass(node_id);
1064        state.render_invalidated.set(true);
1065    });
1066}
1067
1068/// Appends the nodes whose z index changed since the last call to `output`,
1069/// after what it already holds.
1070pub fn append_z_order_changes(output: &mut Vec<NodeId>) {
1071    require_current_app_context("render state access").append_z_order_changes(output);
1072}
1073
1074/// Returns true if graphics-layer property updates are pending.
1075#[doc(hidden)]
1076pub fn has_pending_layer_property_repasses() -> bool {
1077    with_render_state(|state| {
1078        state
1079            .layer_property_repasses
1080            .borrow_mut()
1081            .has_pending_repass()
1082    })
1083}
1084
1085/// Takes pending graphics-layer property updates into reusable storage.
1086#[doc(hidden)]
1087pub fn take_layer_property_repass_nodes_into(output: &mut Vec<NodeId>) {
1088    require_current_app_context("render state access")
1089        .take_layer_property_repass_nodes_into(output);
1090}
1091
1092/// Returns true if any layout repasses are pending.
1093pub fn has_pending_layout_repasses() -> bool {
1094    require_current_app_context("render state access").has_pending_layout_repasses()
1095}
1096
1097/// Returns a stable snapshot of pending layout repass node IDs without consuming them.
1098pub fn pending_layout_repass_nodes_snapshot() -> Vec<NodeId> {
1099    require_current_app_context("render state access").pending_layout_repass_nodes_snapshot()
1100}
1101
1102/// Takes all pending layout repass node IDs.
1103///
1104/// The caller should iterate over these and call `bubble_layout_dirty` for each.
1105pub fn take_layout_repass_nodes() -> Vec<NodeId> {
1106    require_current_app_context("render state access").take_layout_repass_nodes()
1107}
1108
1109/// Schedules a scoped re-*measure* of `node_id` on the next frame.
1110///
1111/// Like [`schedule_layout_repass`], but processing bubbles *measure* dirtiness
1112/// (not just layout/placement) up the tree, so the node and its ancestors are
1113/// re-measured. Use this when a node's own measured size changes off a frame
1114/// callback (e.g. a row collapsing after a swipe dismiss): a plain layout
1115/// repass would leave the node's `needs_measure` flag unset, and an enclosing
1116/// `LazyColumn` would reuse its cached, full-height item slot.
1117pub fn schedule_measure_repass(node_id: NodeId) {
1118    with_render_state(|state| {
1119        state.measure_repasses.borrow_mut().schedule_repass(node_id);
1120    });
1121    request_render_invalidation();
1122}
1123
1124/// Returns true if any measure repasses are pending.
1125pub fn has_pending_measure_repasses() -> bool {
1126    require_current_app_context("render state access").has_pending_measure_repasses()
1127}
1128
1129/// Returns a stable snapshot of pending measure repass node IDs without
1130/// consuming them.
1131///
1132/// The layout pass takes these ids to bubble measure dirtiness; the scene phase
1133/// needs the same ids *before* that happens, to scope its graph update to the
1134/// subtree that moved. Without the snapshot a measure repass reaches the scene
1135/// phase as "something changed, but nothing says where", which is
1136/// indistinguishable from a full invalidation.
1137pub fn pending_measure_repass_nodes_snapshot() -> Vec<NodeId> {
1138    require_current_app_context("render state access").pending_measure_repass_nodes_snapshot()
1139}
1140
1141/// Takes all pending measure repass node IDs.
1142///
1143/// The caller should iterate over these and call `bubble_measure_dirty` for each.
1144pub fn take_measure_repass_nodes() -> Vec<NodeId> {
1145    require_current_app_context("render state access").take_measure_repass_nodes()
1146}
1147
1148#[cfg(any(test, feature = "test-helpers"))]
1149pub(crate) fn take_modifier_slice_repass_nodes() -> Vec<NodeId> {
1150    require_current_app_context("render state access").take_modifier_slice_repass_nodes()
1151}
1152
1153pub(crate) fn record_geometry_scene_node(node_id: NodeId) {
1154    require_current_app_context("render state access").record_geometry_scene_node(node_id);
1155}
1156
1157/// Takes the nodes whose geometry the last layout pass actually changed.
1158///
1159/// The scene phase merges these into its scoped update scope. Consuming them
1160/// is mandatory whenever layout ran: geometry recorded by one pass is
1161/// meaningless to the next.
1162pub fn take_geometry_scene_nodes() -> GeometrySceneNodes {
1163    let mut nodes = GeometrySceneNodes::default();
1164    take_geometry_scene_nodes_into(&mut nodes);
1165    nodes
1166}
1167
1168/// Takes changed geometry nodes into reusable caller-owned storage.
1169///
1170/// ```
1171/// let context = cranpose_ui::AppContext::new();
1172/// context.enter(|| {
1173///     let mut nodes = cranpose_ui::GeometrySceneNodes::default();
1174///     cranpose_ui::take_geometry_scene_nodes_into(&mut nodes);
1175///     assert!(nodes.is_empty());
1176/// });
1177/// ```
1178pub fn take_geometry_scene_nodes_into(output: &mut GeometrySceneNodes) {
1179    require_current_app_context("render state access").take_geometry_scene_nodes_into(output);
1180}
1181
1182/// Requests that the renderer rebuild the current scene.
1183pub fn request_render_invalidation() {
1184    with_render_state(|state| state.render_invalidated.set(true));
1185}
1186
1187/// Returns true if a render invalidation was pending and clears the flag.
1188pub fn take_render_invalidation() -> bool {
1189    require_current_app_context("render state access").take_render_invalidation()
1190}
1191
1192/// Returns true if a render invalidation is pending without clearing it.
1193pub fn peek_render_invalidation() -> bool {
1194    with_render_state(|state| state.render_invalidated.get())
1195}
1196
1197/// Requests a new pointer-input pass without touching layout or draw dirties.
1198pub fn request_pointer_invalidation() {
1199    with_render_state(|state| state.pointer_invalidated.set(true));
1200}
1201
1202/// Returns true if a pointer invalidation was pending and clears the flag.
1203pub fn take_pointer_invalidation() -> bool {
1204    require_current_app_context("render state access").take_pointer_invalidation()
1205}
1206
1207/// Returns true if a pointer invalidation is pending without clearing it.
1208pub fn peek_pointer_invalidation() -> bool {
1209    with_render_state(|state| state.pointer_invalidated.get())
1210}
1211
1212/// Requests a focus recomposition without affecting layout/draw dirties.
1213pub fn request_focus_invalidation() {
1214    with_render_state(|state| state.focus_invalidated.set(true));
1215}
1216
1217/// Returns true if a focus invalidation was pending and clears the flag.
1218pub fn take_focus_invalidation() -> bool {
1219    require_current_app_context("render state access").take_focus_invalidation()
1220}
1221
1222/// Returns true if a focus invalidation is pending without clearing it.
1223pub fn peek_focus_invalidation() -> bool {
1224    with_render_state(|state| state.focus_invalidated.get())
1225}
1226
1227/// Requests a **global** layout re-run.
1228///
1229/// # ⚠️ WARNING: Extremely Expensive - O(entire app size)
1230///
1231/// This triggers internal cache invalidation that forces **every node** in the app
1232/// to re-measure, even if nothing changed. This is a performance footgun!
1233///
1234/// ## Valid Use Cases (rare!)
1235///
1236/// Only use this for **true global changes** that affect layout computation everywhere:
1237/// - Window/viewport resize
1238/// - Global font scale or density changes
1239/// - System-wide theme changes that affect layout
1240/// - Debug toggles that change layout behavior globally
1241///
1242/// ## For Local Changes - DO NOT USE THIS
1243///
1244/// **If you're invalidating layout for scroll, a single widget update, or any local change,
1245/// you MUST use the scoped repass mechanism instead:**
1246///
1247/// ```text
1248/// cranpose_ui::schedule_layout_repass(node_id);
1249/// ```
1250///
1251/// Scoped repasses give you O(subtree) performance instead of O(app), and they don't
1252/// invalidate caches across the entire app.
1253pub fn request_layout_invalidation() {
1254    with_render_state(|state| state.layout_invalidated.set(true));
1255}
1256
1257/// Returns true if a layout invalidation was pending and clears the flag.
1258pub fn take_layout_invalidation() -> bool {
1259    require_current_app_context("render state access").take_layout_invalidation()
1260}
1261
1262/// Returns true if a layout invalidation is pending without clearing it.
1263pub fn peek_layout_invalidation() -> bool {
1264    with_render_state(|state| state.layout_invalidated.get())
1265}
1266
1267#[cfg(any(test, feature = "test-helpers"))]
1268#[doc(hidden)]
1269pub fn reset_render_state_for_tests() {
1270    let _ = take_draw_repass_nodes();
1271    let mut layer_nodes = Vec::new();
1272    take_layer_property_repass_nodes_into(&mut layer_nodes);
1273    let _ = take_layout_repass_nodes();
1274    let _ = take_modifier_slice_repass_nodes();
1275    append_z_order_changes(&mut layer_nodes);
1276    let _ = take_render_invalidation();
1277    let _ = take_pointer_invalidation();
1278    let _ = take_focus_invalidation();
1279    let _ = take_layout_invalidation();
1280    debug_reset_last_fling_velocity();
1281    set_density(1.0);
1282    set_font_scale(1.0);
1283    let _ = take_layout_invalidation();
1284}
1285
1286#[cfg(test)]
1287pub(crate) struct TestAppContextScope {
1288    _scope: AppContextScope,
1289    _context: Rc<AppContext>,
1290}
1291
1292#[cfg(test)]
1293pub(crate) fn app_context_test_scope() -> TestAppContextScope {
1294    let context = AppContext::new();
1295    let scope = context.enter_scope();
1296    context.enter(reset_render_state_for_tests);
1297    TestAppContextScope {
1298        _scope: scope,
1299        _context: context,
1300    }
1301}
1302
1303#[cfg(test)]
1304pub(crate) struct RenderStateTestGuard {
1305    _app_scope: TestAppContextScope,
1306    _lock: std::sync::MutexGuard<'static, ()>,
1307}
1308
1309#[cfg(test)]
1310pub(crate) fn render_state_test_guard() -> RenderStateTestGuard {
1311    static TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1312    let lock = match TEST_LOCK.get_or_init(|| Mutex::new(())).lock() {
1313        Ok(guard) => guard,
1314        Err(poisoned) => poisoned.into_inner(),
1315    };
1316    RenderStateTestGuard {
1317        _app_scope: app_context_test_scope(),
1318        _lock: lock,
1319    }
1320}
1321
1322#[cfg(test)]
1323#[path = "tests/render_state_tests.rs"]
1324mod tests;