Skip to main content

cranpose_render_common/
lib.rs

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