cranpose-ui 0.1.84

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use crate::layout::{LayoutBox, LayoutNodeData, LayoutTree};
use crate::modifier::{DrawCommand as ModifierDrawCommand, Point, Rect, Size};
use crate::widgets::LayoutNode;
use cranpose_core::{MemoryApplier, NodeId};
use cranpose_ui_graphics::DrawPrimitive;

/// Layer that a paint operation targets within the rendering pipeline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaintLayer {
    Behind,
    Content,
    Overlay,
}

/// A rendered operation emitted by the headless renderer.
#[derive(Clone, Debug, PartialEq)]
pub enum RenderOp {
    Primitive {
        node_id: NodeId,
        layer: PaintLayer,
        primitive: DrawPrimitive,
    },
    Text {
        node_id: NodeId,
        rect: Rect,
        value: String,
    },
}

/// A collection of render operations for a composed scene.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RecordedRenderScene {
    operations: Vec<RenderOp>,
}

impl RecordedRenderScene {
    pub fn new(operations: Vec<RenderOp>) -> Self {
        Self { operations }
    }

    /// Returns a slice of recorded render operations in submission order.
    pub fn operations(&self) -> &[RenderOp] {
        &self.operations
    }

    /// Consumes the scene and yields the owned operations.
    pub fn into_operations(self) -> Vec<RenderOp> {
        self.operations
    }

    /// Returns an iterator over primitives that target the provided paint layer.
    pub fn primitives_for(&self, layer: PaintLayer) -> impl Iterator<Item = &DrawPrimitive> {
        self.operations.iter().filter_map(move |op| match op {
            RenderOp::Primitive {
                layer: op_layer,
                primitive,
                ..
            } if *op_layer == layer => Some(primitive),
            _ => None,
        })
    }
}

/// A lightweight renderer that walks the layout tree and materialises paint commands.
#[derive(Default)]
pub struct HeadlessRenderer;

impl HeadlessRenderer {
    pub fn new() -> Self {
        Self
    }

    pub fn render(&self, tree: &LayoutTree) -> RecordedRenderScene {
        let mut operations = Vec::new();
        self.render_box(tree.root(), &mut operations);
        RecordedRenderScene::new(operations)
    }

    #[allow(clippy::only_used_in_recursion)]
    fn render_box(&self, layout: &LayoutBox, operations: &mut Vec<RenderOp>) {
        let rect = layout.rect;
        let (mut behind, mut overlay) = evaluate_modifier(layout.node_id, &layout.node_data, rect);

        operations.append(&mut behind);

        // Render text content if present in modifier slices.
        // This follows Jetpack Compose's pattern where text is a modifier node capability
        // (TextModifierNode implements LayoutModifierNode + DrawModifierNode + SemanticsNode)
        if let Some(text) = layout.node_data.modifier_slices().text_content() {
            operations.push(RenderOp::Text {
                node_id: layout.node_id,
                rect,
                value: text.to_string(),
            });
        }

        // Render children
        for child in &layout.children {
            self.render_box(child, operations);
        }

        operations.append(&mut overlay);
    }
}

fn evaluate_modifier(
    node_id: NodeId,
    data: &LayoutNodeData,
    rect: Rect,
) -> (Vec<RenderOp>, Vec<RenderOp>) {
    let size = Size {
        width: rect.width,
        height: rect.height,
    };

    let behind = collect_primitives_from_commands(
        node_id,
        rect,
        size,
        data.modifier_slices().draw_commands(),
        PaintLayer::Behind,
    );
    let overlay = collect_primitives_from_commands(
        node_id,
        rect,
        size,
        data.modifier_slices().draw_commands(),
        PaintLayer::Overlay,
    );
    (behind, overlay)
}

fn collect_primitives_from_commands(
    node_id: NodeId,
    rect: Rect,
    size: Size,
    commands: &[ModifierDrawCommand],
    layer: PaintLayer,
) -> Vec<RenderOp> {
    let split_with_content = |primitives: Vec<DrawPrimitive>, layer| {
        let Some(last_content_idx) = primitives
            .iter()
            .rposition(|primitive| matches!(primitive, DrawPrimitive::Content))
        else {
            return if layer == PaintLayer::Overlay {
                primitives
                    .into_iter()
                    .filter(|primitive| !matches!(primitive, DrawPrimitive::Content))
                    .collect()
            } else {
                Vec::new()
            };
        };

        primitives
            .into_iter()
            .enumerate()
            .filter_map(|(index, primitive)| {
                if matches!(primitive, DrawPrimitive::Content) {
                    return None;
                }
                let is_before = index < last_content_idx;
                match layer {
                    PaintLayer::Behind if is_before => Some(primitive),
                    PaintLayer::Overlay if !is_before => Some(primitive),
                    _ => None,
                }
            })
            .collect()
    };

    let run = |func: &crate::draw::DrawCommandFn| {
        use cranpose_ui_graphics::DrawScope as _;
        let mut scope = crate::draw::command_draw_scope(size);
        func(&mut scope);
        scope.into_primitives()
    };
    let mut ops = Vec::new();
    for command in commands {
        let primitives = match (layer, command) {
            (PaintLayer::Behind, ModifierDrawCommand::Behind(func)) => run(func)
                .into_iter()
                .filter(|primitive| !matches!(primitive, DrawPrimitive::Content))
                .collect(),
            (PaintLayer::Overlay, ModifierDrawCommand::Overlay(func)) => run(func)
                .into_iter()
                .filter(|primitive| !matches!(primitive, DrawPrimitive::Content))
                .collect(),
            (PaintLayer::Behind | PaintLayer::Overlay, ModifierDrawCommand::WithContent(func)) => {
                split_with_content(run(func), layer)
            }
            _ => Vec::new(),
        };
        for primitive in primitives {
            ops.push(RenderOp::Primitive {
                node_id,
                layer,
                primitive: translate_primitive(primitive, rect.x, rect.y),
            });
        }
    }
    ops
}

fn translate_primitive(primitive: DrawPrimitive, dx: f32, dy: f32) -> DrawPrimitive {
    match primitive {
        DrawPrimitive::Content => DrawPrimitive::Content,
        DrawPrimitive::Blend {
            primitive,
            blend_mode,
        } => DrawPrimitive::Blend {
            primitive: Box::new(translate_primitive(*primitive, dx, dy)),
            blend_mode,
        },
        DrawPrimitive::Rect {
            rect,
            brush,
            stroke,
        } => DrawPrimitive::Rect {
            rect: rect.translate(dx, dy),
            brush,
            stroke,
        },
        DrawPrimitive::RoundRect {
            rect,
            brush,
            radii,
            stroke,
        } => DrawPrimitive::RoundRect {
            rect: rect.translate(dx, dy),
            brush,
            radii,
            stroke,
        },
        DrawPrimitive::Arc {
            rect,
            brush,
            center,
            radius,
            start_angle,
            sweep_angle,
            stroke,
            inner_radius,
        } => DrawPrimitive::Arc {
            rect: rect.translate(dx, dy),
            brush,
            // The arc center lives in the same local space as `rect`, so it
            // must move with it — translating only the bounding box would
            // silently shear the arc out of its box.
            center: Point::new(center.x + dx, center.y + dy),
            radius,
            start_angle,
            sweep_angle,
            stroke,
            inner_radius,
        },
        DrawPrimitive::Image {
            rect,
            image,
            alpha,
            color_filter,
            sampling,
            src_rect,
        } => DrawPrimitive::Image {
            rect: rect.translate(dx, dy),
            image,
            alpha,
            color_filter,
            sampling,
            src_rect,
        },
        DrawPrimitive::Text(mut text) => {
            text.rect = text.rect.translate(dx, dy);
            DrawPrimitive::Text(text)
        }
        DrawPrimitive::Shadow(shadow) => {
            use cranpose_ui_graphics::ShadowPrimitive;
            DrawPrimitive::Shadow(match shadow {
                ShadowPrimitive::Drop {
                    shape,
                    cutout,
                    blur_radius,
                    blend_mode,
                } => ShadowPrimitive::Drop {
                    shape: Box::new(translate_primitive(*shape, dx, dy)),
                    cutout: cutout.map(|cutout| Box::new(translate_primitive(*cutout, dx, dy))),
                    blur_radius,
                    blend_mode,
                },
                ShadowPrimitive::Inner {
                    fill,
                    cutout,
                    blur_radius,
                    blend_mode,
                    clip_rect,
                } => ShadowPrimitive::Inner {
                    fill: Box::new(translate_primitive(*fill, dx, dy)),
                    cutout: Box::new(translate_primitive(*cutout, dx, dy)),
                    blur_radius,
                    blend_mode,
                    clip_rect: clip_rect.translate(dx, dy),
                },
            })
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Direct Applier Rendering (new architecture)
// ═══════════════════════════════════════════════════════════════════════════

impl HeadlessRenderer {
    /// Renders the scene by traversing LayoutNodes directly via the Applier.
    /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
    pub fn render_from_applier(
        &self,
        applier: &mut MemoryApplier,
        root: NodeId,
    ) -> RecordedRenderScene {
        let mut operations = Vec::new();
        self.render_node_from_applier(applier, root, Point::default(), &mut operations);
        RecordedRenderScene::new(operations)
    }

    #[allow(clippy::only_used_in_recursion)]
    fn render_node_from_applier(
        &self,
        applier: &mut MemoryApplier,
        node_id: NodeId,
        parent_offset: Point,
        operations: &mut Vec<RenderOp>,
    ) {
        // Read layout state and node data from LayoutNode
        let node_data = match applier.with_node::<LayoutNode, _>(node_id, |node| {
            let state = node.layout_state();
            let modifier_slices = node.modifier_slices_snapshot();
            let children: Vec<NodeId> = node.children.clone();
            (state, modifier_slices, children)
        }) {
            Ok(data) => data,
            Err(_) => return, // Node not found or type mismatch
        };

        let (layout_state, modifier_slices, children) = node_data;

        // Skip nodes that weren't placed
        if !layout_state.is_placed {
            return;
        }

        // Calculate absolute position
        let abs_x = parent_offset.x + layout_state.position.x;
        let abs_y = parent_offset.y + layout_state.position.y;

        let rect = Rect {
            x: abs_x,
            y: abs_y,
            width: layout_state.size.width,
            height: layout_state.size.height,
        };

        let size = Size {
            width: rect.width,
            height: rect.height,
        };

        // Collect draw commands from modifier slices
        let mut behind = Vec::new();
        let mut overlay = Vec::new();
        behind.extend(collect_primitives_from_commands(
            node_id,
            rect,
            size,
            modifier_slices.draw_commands(),
            PaintLayer::Behind,
        ));
        overlay.extend(collect_primitives_from_commands(
            node_id,
            rect,
            size,
            modifier_slices.draw_commands(),
            PaintLayer::Overlay,
        ));

        operations.append(&mut behind);

        // Render text content if present
        if let Some(text) = modifier_slices.text_content() {
            operations.push(RenderOp::Text {
                node_id,
                rect,
                value: text.to_string(),
            });
        }

        // Calculate content offset for children (includes node position + content_offset from padding etc.)
        let child_offset = Point {
            x: abs_x + layout_state.content_offset.x,
            y: abs_y + layout_state.content_offset.y,
        };

        // Render children
        for child_id in children {
            self.render_node_from_applier(applier, child_id, child_offset, operations);
        }

        operations.append(&mut overlay);
    }
}

#[cfg(test)]
#[path = "tests/renderer_tests.rs"]
mod tests;