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 z_order_changes: RefCell<DirtyNodeSet>,
45 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 font_scale_identity: Cell<bool>,
57 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 pub(crate) measure_reads: Rc<cranpose_core::internal::NodeReads>,
69 text: crate::text::measure::TextService,
70 layout_frame_arena: RefCell<crate::layout::FrameLayoutArena>,
71 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#[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 #[doc(hidden)]
221 pub fn pending_mouse_moves(&self) -> usize {
222 self.mouse_input.len()
223 }
224
225 #[doc(hidden)]
227 pub fn take_mouse_move(&self) -> Option<crate::mouse_input::MouseMoveRequest> {
228 self.mouse_input.take()
229 }
230
231 pub(crate) fn claim_pointer(&self, node: NodeId) {
234 self.pointer_claim.set(Some(node));
235 }
236
237 #[doc(hidden)]
239 pub fn take_pointer_claim(&self) -> Option<NodeId> {
240 self.pointer_claim.take()
241 }
242
243 pub fn window_roots(&self) -> &crate::modifier::WindowRootRegistry {
245 &self.window_roots
246 }
247
248 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 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 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 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 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 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 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 pub fn dismissable_popup_open(&self) -> bool {
392 self.hosted_popups.dismissable_open(false)
393 }
394
395 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 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 pub fn keep_retained_redraw_node(&self, node_id: NodeId) {
414 self.state.retained_redraws.borrow_mut().push(node_id);
415 }
416
417 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 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 pub fn has_pending_layout_repasses(&self) -> bool {
439 self.state.layout_repasses.borrow_mut().has_pending_repass()
440 }
441
442 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 pub fn has_pending_measure_repasses(&self) -> bool {
453 self.state
454 .measure_repasses
455 .borrow_mut()
456 .has_pending_repass()
457 }
458
459 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 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 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 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 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 pub(crate) fn placement_pass(&self) -> &crate::widgets::nodes::PlacementPass {
518 &self.placement_pass
519 }
520
521 pub fn take_layout_invalidation(&self) -> bool {
524 self.state.layout_invalidated.replace(false)
525 }
526
527 pub fn start_text_frame(&self) {
532 self.text.owe_pass();
533 }
534
535 pub fn take_render_invalidation(&self) -> bool {
538 self.state.render_invalidated.replace(false)
539 }
540
541 pub fn take_pointer_invalidation(&self) -> bool {
544 self.state.pointer_invalidated.replace(false)
545 }
546
547 pub fn take_focus_invalidation(&self) -> bool {
550 self.state.focus_invalidated.replace(false)
551 }
552
553 pub fn clear_transient_scroll_motion_contexts(&self) {
556 self.scroll_motion_contexts.clear_transient_after_frame();
557 }
558
559 pub fn has_pending_pointer_repasses(&self) -> bool {
562 self.pointer_dispatch.has_pending()
563 }
564
565 pub fn has_pending_focus_invalidations(&self) -> bool {
568 self.focus_dispatch.invalidations.has_pending()
569 }
570
571 pub fn active_focus_target(&self) -> Option<NodeId> {
574 self.focus_dispatch.active_focus_target()
575 }
576
577 pub fn has_pending_semantics_invalidations(&self) -> bool {
581 self.semantics_dispatch.has_pending()
582 }
583
584 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 pub fn tick_cursor_blink(&self) -> bool {
599 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
763pub(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#[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
987pub 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
1026pub(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
1034pub fn has_pending_draw_repasses() -> bool {
1036 with_render_state(|state| state.draw_repasses.borrow_mut().has_pending_repass())
1037}
1038
1039pub fn take_draw_repass_nodes() -> Vec<NodeId> {
1041 with_render_state(|state| state.draw_repasses.borrow_mut().take_dirty_nodes())
1042}
1043
1044pub 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
1058pub 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
1068pub 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#[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#[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
1092pub fn has_pending_layout_repasses() -> bool {
1094 require_current_app_context("render state access").has_pending_layout_repasses()
1095}
1096
1097pub fn pending_layout_repass_nodes_snapshot() -> Vec<NodeId> {
1099 require_current_app_context("render state access").pending_layout_repass_nodes_snapshot()
1100}
1101
1102pub fn take_layout_repass_nodes() -> Vec<NodeId> {
1106 require_current_app_context("render state access").take_layout_repass_nodes()
1107}
1108
1109pub 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
1124pub fn has_pending_measure_repasses() -> bool {
1126 require_current_app_context("render state access").has_pending_measure_repasses()
1127}
1128
1129pub fn pending_measure_repass_nodes_snapshot() -> Vec<NodeId> {
1138 require_current_app_context("render state access").pending_measure_repass_nodes_snapshot()
1139}
1140
1141pub 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
1157pub fn take_geometry_scene_nodes() -> GeometrySceneNodes {
1163 let mut nodes = GeometrySceneNodes::default();
1164 take_geometry_scene_nodes_into(&mut nodes);
1165 nodes
1166}
1167
1168pub 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
1182pub fn request_render_invalidation() {
1184 with_render_state(|state| state.render_invalidated.set(true));
1185}
1186
1187pub fn take_render_invalidation() -> bool {
1189 require_current_app_context("render state access").take_render_invalidation()
1190}
1191
1192pub fn peek_render_invalidation() -> bool {
1194 with_render_state(|state| state.render_invalidated.get())
1195}
1196
1197pub fn request_pointer_invalidation() {
1199 with_render_state(|state| state.pointer_invalidated.set(true));
1200}
1201
1202pub fn take_pointer_invalidation() -> bool {
1204 require_current_app_context("render state access").take_pointer_invalidation()
1205}
1206
1207pub fn peek_pointer_invalidation() -> bool {
1209 with_render_state(|state| state.pointer_invalidated.get())
1210}
1211
1212pub fn request_focus_invalidation() {
1214 with_render_state(|state| state.focus_invalidated.set(true));
1215}
1216
1217pub fn take_focus_invalidation() -> bool {
1219 require_current_app_context("render state access").take_focus_invalidation()
1220}
1221
1222pub fn peek_focus_invalidation() -> bool {
1224 with_render_state(|state| state.focus_invalidated.get())
1225}
1226
1227pub fn request_layout_invalidation() {
1254 with_render_state(|state| state.layout_invalidated.set(true));
1255}
1256
1257pub fn take_layout_invalidation() -> bool {
1259 require_current_app_context("render state access").take_layout_invalidation()
1260}
1261
1262pub 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;