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