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