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