Skip to main content

cranpose_render_common/
lib.rs

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