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