Skip to main content

cranpose_render_common/
lib.rs

1//! Common rendering contracts shared between renderer backends.
2
3pub mod bounded_lru_cache;
4pub mod debug_toggles;
5pub mod dev_overlay;
6mod direct_mapped_cache;
7
8/// The frame background every renderer clears to (linear values; sRGB
9/// surfaces display this as rgb(75, 75, 86)). One definition so backends
10/// cannot drift.
11pub const FRAME_CLEAR_COLOR: [f32; 4] = [18.0 / 255.0, 18.0 / 255.0, 24.0 / 255.0, 1.0];
12pub mod brush_sampling;
13pub mod font_layout;
14pub mod font_source;
15mod font_tracking;
16pub mod geometry;
17pub mod gpos_kerning;
18pub mod graph;
19mod graph_hash;
20pub mod graph_scene;
21pub mod hit_graph;
22pub mod image_compare;
23pub mod layer_composition;
24pub mod layer_shadow;
25pub mod layer_transform;
26pub mod primitive_emit;
27pub mod raster_cache;
28pub mod render_contract;
29pub mod scene_builder;
30pub mod shape_sdf;
31pub mod software_text_raster;
32pub mod style_shared;
33mod text_cache_key;
34pub mod text_hyphenation;
35pub mod text_measure;
36
37#[cfg(test)]
38#[path = "tests/pointer_slices.rs"]
39mod pointer_slices;
40
41use cranpose_core::{MemoryApplier, collections::map::HashSet};
42use cranpose_foundation::nodes::input::PointerEvent;
43use cranpose_ui::LayoutTree;
44pub use cranpose_ui_graphics::Brush;
45use cranpose_ui_graphics::Size;
46
47/// Trait implemented by hit-test targets stored inside a [`RenderScene`].
48pub trait HitTestTarget {
49    /// Dispatches a pointer event to this target's handlers.
50    fn dispatch(&self, event: PointerEvent);
51
52    /// Dispatches a pointer event using the current live node state when available.
53    ///
54    /// Render-scene hit targets may cache closures from an older scene build. Pointer
55    /// dispatch goes through this hook so implementations can resolve fresh handlers
56    /// from the current applier while still using the target's geometry snapshot.
57    fn dispatch_with_applier(&self, _applier: &mut MemoryApplier, event: PointerEvent) {
58        self.dispatch(event);
59    }
60
61    /// Returns the NodeId associated with this hit target.
62    /// Used by HitPathTracker to cache stable identity instead of geometry.
63    fn node_id(&self) -> cranpose_core::NodeId;
64
65    /// The pointer's appearance while it hovers this target, when the target
66    /// names one.
67    ///
68    /// The shell asks the hit list top-down and applies the first answer, so
69    /// the innermost region under the pointer decides the cursor.
70    fn pointer_icon(&self) -> Option<cranpose_ui_graphics::PointerIcon> {
71        None
72    }
73
74    /// Returns the node capture path that should stay attached to this target's gesture.
75    ///
76    /// The default is just this target's own node. Renderers can override this to
77    /// include stable ancestor pointer-input nodes that must continue receiving
78    /// Move/Up/Cancel even if the original descendant target is recycled.
79    fn capture_path(&self) -> Vec<cranpose_core::NodeId> {
80        vec![self.node_id()]
81    }
82}
83
84/// Trait describing the minimal surface area required by the application
85/// shell to process pointer events and refresh the frame graph.
86pub trait RenderScene {
87    type HitTarget: HitTestTarget + Clone;
88
89    fn clear(&mut self);
90
91    /// Performs hit testing at the given coordinates.
92    /// Returns hit targets ordered by z-index (top-to-bottom).
93    fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget>;
94
95    /// The one target a press reaches when it misses every target but lands
96    /// inside a small target grown to the minimum touch size: the nearest such
97    /// target, and none when the point is outside every grown target.
98    fn hit_test_near(&self, _x: f32, _y: f32) -> Option<Self::HitTarget> {
99        None
100    }
101
102    /// Returns NodeIds of all hit regions at the given coordinates.
103    /// This is a convenience method equivalent to `hit_test().map(|h| h.node_id())`.
104    fn hit_test_nodes(&self, x: f32, y: f32) -> Vec<cranpose_core::NodeId> {
105        self.hit_test(x, y)
106            .into_iter()
107            .map(|h| h.node_id())
108            .collect()
109    }
110
111    /// Finds a hit target by NodeId with fresh geometry from the current scene.
112    ///
113    /// This is the key method for HitPathTracker-style gesture handling:
114    /// - On PointerDown, we cache NodeIds (not geometry)
115    /// - On Move/Up/Cancel, we call this to get fresh HitTarget with current geometry
116    /// - Handler closures are preserved (same Rc), so internal state survives
117    ///
118    /// Returns None if the node no longer exists in the scene (e.g., removed during gesture).
119    fn find_target(&self, node_id: cranpose_core::NodeId) -> Option<Self::HitTarget>;
120
121    /// Replaces the set with retained visual observation owners, preserving its capacity.
122    /// Returns whether the scene provides this information.
123    fn collect_retained_visual_observation_nodes(
124        &self,
125        nodes: &mut HashSet<cranpose_core::NodeId>,
126    ) -> bool {
127        nodes.clear();
128        false
129    }
130}
131
132/// Abstraction implemented by concrete renderer backends.
133pub trait Renderer {
134    type Scene: RenderScene;
135    type Error;
136
137    /// Installs renderer-provided app services into the target AppContext.
138    ///
139    /// AppShell calls this before the first composition pass.
140    /// Renderers that provide text measurement or other per-app services should install
141    /// them here rather than as constructor side effects.
142    fn attach_app_context_services(&mut self, _app_context: &cranpose_ui::AppContext) {}
143
144    fn scene(&self) -> &Self::Scene;
145    fn scene_mut(&mut self) -> &mut Self::Scene;
146
147    fn rebuild_scene(
148        &mut self,
149        layout_tree: &LayoutTree,
150        viewport: Size,
151    ) -> Result<(), Self::Error>;
152
153    /// Rebuilds the scene by traversing the LayoutNode tree directly via Applier.
154    ///
155    /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
156    /// Implementors must read layout state from LayoutNode.layout_state() directly.
157    fn rebuild_scene_from_applier(
158        &mut self,
159        applier: &mut cranpose_core::MemoryApplier,
160        root: cranpose_core::NodeId,
161        viewport: Size,
162    ) -> Result<(), Self::Error>;
163
164    fn update_scene_from_applier(
165        &mut self,
166        applier: &mut cranpose_core::MemoryApplier,
167        root: cranpose_core::NodeId,
168        viewport: Size,
169        dirty_nodes: &[cranpose_core::NodeId],
170    ) -> Result<(), Self::Error> {
171        let _ = dirty_nodes;
172        self.rebuild_scene_from_applier(applier, root, viewport)
173    }
174
175    fn update_visual_scene_from_applier(
176        &mut self,
177        applier: &mut cranpose_core::MemoryApplier,
178        root: cranpose_core::NodeId,
179        viewport: Size,
180        dirty_nodes: &[cranpose_core::NodeId],
181    ) -> Result<(), Self::Error> {
182        self.update_scene_from_applier(applier, root, viewport, dirty_nodes)
183    }
184
185    /// Draw a development overlay (e.g., FPS counter) on top of the scene.
186    ///
187    /// This is called after rebuild_scene when dev options are enabled.
188    /// The text is drawn directly by the renderer without affecting composition.
189    ///
190    /// Default implementation does nothing.
191    fn draw_dev_overlay(&mut self, _text: &str, _viewport: Size) {}
192
193    /// Replaces the developer inspector graph outside the application scene.
194    ///
195    /// Passing `None` removes the inspector. Its primitives must not participate
196    /// in application hit testing, layout, or accessibility.
197    fn set_inspector_overlay(&mut self, _graph: Option<graph::RenderGraph>) {}
198
199    /// Returns whether renderer-side cache materialization needs a visible follow-up frame.
200    fn needs_frame_warmup(&self) -> bool {
201        false
202    }
203}