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