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