xengui 0.2.7

a retained-mode gui library in rust
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// SPDX-License-Identifier: Apache-2.0
use crate::{
    AnimationManager,
    BoxShadowCommand,
    DrawCommand,
    ImageCommand,
    LayoutContext,
    LayoutEngine,
    PaintContext,
    RectCommand,
    RenderBackend,
    RenderCache,
    SystemTheme,
    TriangleCommand,
    Widget,
};
use std::collections::HashSet;
use web_time::Instant;

/// Backend-agnostic frame orchestration: layout, paint-tree walk, command
/// batching and z-ordering. Every actual draw call is delegated to a
/// [`RenderBackend`] implementation.
pub struct FrameRenderer {
    render_cache: RenderCache,
    anim: AnimationManager,
    last_tick: Instant,
    force_layout: bool,
}

impl FrameRenderer {
    pub fn new() -> Self {
        Self {
            render_cache: RenderCache::new(),
            anim: AnimationManager::new(),
            last_tick: Instant::now(),
            force_layout: false,
        }
    }

    pub fn anim(&mut self) -> &mut AnimationManager {
        &mut self.anim
    }

    pub fn is_animating(&self) -> bool {
        self.anim.is_animating()
    }

    pub fn resize(&mut self) {
        self.force_layout = true;
    }

    pub fn render_frame(
        &mut self,
        tree: &mut [Box<dyn Widget>],
        backend: &mut dyn RenderBackend,
        theme: SystemTheme,
        scale_factor: f32,
        width: u32,
        height: u32
    ) {
        let now = Instant::now();
        let dt = now.duration_since(self.last_tick);
        self.last_tick = now;
        self.anim.tick(dt);

        let app_background = crate::current_theme().background;
        if !backend.begin_frame(app_background, width, height) {
            return;
        }

        let needs_full_layout =
            std::mem::take(&mut self.force_layout) ||
            tree_is_dirty(tree) ||
            self.anim
                .active_keys()
                .any(|k| {
                    k.property.affects_layout() || k.property == crate::AnimProperty::ScrollOffset
                });

        let mut layout_ctx = LayoutContext {
            text: backend.text_measurer(),
            anim: &mut self.anim,
            scale_factor,
        };

        if needs_full_layout {
            LayoutEngine::layout(
                tree,
                &mut layout_ctx,
                &mut self.render_cache,
                width as f32,
                height as f32
            );
        } else {
            LayoutEngine::cascade(tree, &mut layout_ctx);
        }

        let mut commands: Vec<(i32, DrawCommand)> = Vec::new();
        let mut focus_commands: Vec<RectCommand> = Vec::new();
        let mut top_commands: Vec<DrawCommand> = Vec::new();
        let mut live_keys: HashSet<String> = HashSet::new();

        for (i, node) in tree.iter().enumerate() {
            let segment = crate::path_segment(node.as_ref(), i);
            paint_recursive(
                node.as_ref(),
                &segment,
                &mut self.render_cache,
                &mut commands,
                &mut focus_commands,
                &mut top_commands,
                &mut live_keys,
                None,
                scale_factor,
                0
            );
        }
        self.render_cache.retain_keys(&live_keys);

        for node in tree.iter_mut() {
            reset_dirty_recursive(node.as_mut());
        }

        // Stable sort keeps original paint order for widgets sharing the
        // same z-index; only different values get reordered.
        commands.sort_by_key(|(z, _)| *z);

        #[derive(PartialEq, Clone, Copy)]
        enum RunKind {
            Rect,
            Triangle,
            Image,
            Text,
            BoxShadow,
        }

        let mut current_kind: Option<RunKind> = None;
        let mut rect_buf: Vec<RectCommand> = Vec::new();
        let mut tri_buf: Vec<TriangleCommand> = Vec::new();
        let mut img_buf: Vec<ImageCommand> = Vec::new();
        let mut shadow_buf: Vec<BoxShadowCommand> = Vec::new();

        macro_rules! flush_run {
            () => {
                match current_kind {
                    Some(RunKind::Rect) => backend.draw_rects(&rect_buf),
                    Some(RunKind::Triangle) => backend.draw_triangles(&tri_buf),
                    Some(RunKind::Image) => backend.draw_images(&img_buf),
                    Some(RunKind::BoxShadow) => backend.draw_box_shadows(&shadow_buf),
                    Some(RunKind::Text) => {
                        backend.flush_text();
                        let decorations = backend.take_text_decorations();
                        if !decorations.is_empty() {
                            backend.draw_rects(&decorations);
                        }
                    }
                    None => {}
                }
                rect_buf.clear();
                tri_buf.clear();
                img_buf.clear();
                shadow_buf.clear();
            };
        }

        // Draws each contiguous run of same-type commands in the order
        // z-index (then paint order) puts them in, instead of always
        // drawing every rect, then every triangle, then every image/text.
        for (_z, command) in commands {
            match command {
                DrawCommand::Text(cmd) => {
                    if current_kind != Some(RunKind::Text) {
                        flush_run!();
                        current_kind = Some(RunKind::Text);
                    }
                    backend.draw_text(theme, scale_factor, &cmd);
                }
                DrawCommand::Rect(cmd) => {
                    if current_kind != Some(RunKind::Rect) {
                        flush_run!();
                        current_kind = Some(RunKind::Rect);
                    }
                    rect_buf.push(cmd);
                }
                DrawCommand::Triangle(cmd) => {
                    if current_kind != Some(RunKind::Triangle) {
                        flush_run!();
                        current_kind = Some(RunKind::Triangle);
                    }
                    tri_buf.push(cmd);
                }
                DrawCommand::Image(cmd) => {
                    if current_kind != Some(RunKind::Image) {
                        flush_run!();
                        current_kind = Some(RunKind::Image);
                    }
                    img_buf.push(*cmd);
                }
                DrawCommand::BoxShadow(cmd) => {
                    if current_kind != Some(RunKind::BoxShadow) {
                        flush_run!();
                        current_kind = Some(RunKind::BoxShadow);
                    }
                    shadow_buf.push(cmd);
                }
            }
        }
        flush_run!();

        // Top layer: rendered strictly after the main pass, so a popup
        // here always sits above every other widget's content. Within the
        // top layer itself, commands still interleave by paint order
        // (rect/triangle/image/text) instead of being grouped by type.
        if !top_commands.is_empty() {
            let mut top_rect_buf: Vec<RectCommand> = Vec::new();
            let mut top_tri_buf: Vec<TriangleCommand> = Vec::new();
            let mut top_img_buf: Vec<ImageCommand> = Vec::new();
            let mut top_shadow_buf: Vec<BoxShadowCommand> = Vec::new();
            let mut top_kind: Option<RunKind> = None;

            macro_rules! flush_top_run {
                () => {
                    match top_kind {
                        Some(RunKind::Rect) => backend.draw_rects(&top_rect_buf),
                        Some(RunKind::Triangle) => backend.draw_triangles(&top_tri_buf),
                        Some(RunKind::Image) => backend.draw_images(&top_img_buf),
                        Some(RunKind::Text) => {
                            backend.flush_text();
                            let decorations = backend.take_text_decorations();
                            if !decorations.is_empty() {
                                backend.draw_rects(&decorations);
                            }
                        }
                        Some(RunKind::BoxShadow) => backend.draw_box_shadows(&top_shadow_buf),
                        None => {}
                    }
                    top_rect_buf.clear();
                    top_tri_buf.clear();
                    top_img_buf.clear();
                };
            }

            for command in top_commands {
                match command {
                    DrawCommand::Text(cmd) => {
                        if top_kind != Some(RunKind::Text) {
                            flush_top_run!();
                            top_kind = Some(RunKind::Text);
                        }
                        backend.draw_text(theme, scale_factor, &cmd);
                    }
                    DrawCommand::Rect(cmd) => {
                        if top_kind != Some(RunKind::Rect) {
                            flush_top_run!();
                            top_kind = Some(RunKind::Rect);
                        }
                        top_rect_buf.push(cmd);
                    }
                    DrawCommand::Triangle(cmd) => {
                        if top_kind != Some(RunKind::Triangle) {
                            flush_top_run!();
                            top_kind = Some(RunKind::Triangle);
                        }
                        top_tri_buf.push(cmd);
                    }
                    DrawCommand::Image(cmd) => {
                        if top_kind != Some(RunKind::Image) {
                            flush_top_run!();
                            top_kind = Some(RunKind::Image);
                        }
                        top_img_buf.push(*cmd);
                    }
                    DrawCommand::BoxShadow(cmd) => {
                        if current_kind != Some(RunKind::BoxShadow) {
                            flush_top_run!();
                            current_kind = Some(RunKind::BoxShadow);
                        }
                        top_shadow_buf.push(cmd);
                    }
                }
            }
            flush_top_run!();
        }

        // Focus rings paint last, above everything else including the top
        // layer. All text (main pass and top layer) is already flushed to
        // the GPU by this point via the per-run flush_text() calls above.
        if !focus_commands.is_empty() {
            backend.draw_rects(&focus_commands);
        }

        backend.end_frame();
    }
}

impl Default for FrameRenderer {
    fn default() -> Self {
        Self::new()
    }
}

#[allow(clippy::too_many_arguments)]
fn paint_recursive(
    widget: &dyn Widget,
    path: &str,
    cache: &mut RenderCache,
    commands: &mut Vec<(i32, DrawCommand)>,
    focus_commands: &mut Vec<RectCommand>,
    top_commands: &mut Vec<DrawCommand>,
    live_keys: &mut HashSet<String>,
    clip_rect: Option<(f32, f32, f32, f32)>,
    scale_factor: f32,
    parent_z_index: i32
) {
    let layout_box = *widget.layout_box();

    if let Some((cx, cy, cw, ch)) = clip_rect {
        let visible =
            layout_box.x < cx + cw &&
            layout_box.x + layout_box.width > cx &&
            layout_box.y < cy + ch &&
            layout_box.y + layout_box.height > cy;
        if !visible {
            return;
        }
    }

    live_keys.insert(path.to_string());

    // Inherits the nearest ancestor's z_index when this widget doesn't set
    // its own, so a header's children stack above/below other siblings the
    // same way the header itself does, instead of resetting to 0.
    let z_index = widget.computed_style().z_index.unwrap_or(parent_z_index);

    let own_commands: Vec<DrawCommand> = match cache.try_reuse(path, layout_box, widget.is_dirty()) {
        Some(cached) => cached.to_vec(),
        None => {
            let mut local = Vec::new();
            {
                let mut paint_ctx = PaintContext::new(&mut local, scale_factor);
                widget.paint(&mut paint_ctx);
            }
            cache.store(path, layout_box, local.clone());
            local
        }
    };

    for mut command in own_commands {
        apply_clip(&mut command, clip_rect);
        commands.push((z_index, command));
    }

    let child_clip = match widget.clip_children() {
        Some(rect) => Some(clip_intersect(clip_rect, rect)),
        None => clip_rect,
    };

    for (i, child) in widget.children().iter().enumerate() {
        let segment = crate::path_segment(child.as_ref(), i);
        paint_recursive(
            child.as_ref(),
            &format!("{path}.{segment}"),
            cache,
            commands,
            focus_commands,
            top_commands,
            live_keys,
            child_clip,
            scale_factor,
            z_index
        );
    }

    let mut overlay = Vec::new();
    {
        let mut paint_ctx = PaintContext::new(&mut overlay, scale_factor);
        widget.paint_overlay(&mut paint_ctx);
    }
    for mut command in overlay {
        apply_clip(&mut command, clip_rect);
        // Overlay content (e.g. a View's scrollbar) is UI chrome for
        // interacting with this widget's own children, so it must stay
        // reachable above them regardless of any child's own z_index -
        // pushed into top_commands instead of the sortable z_index stream.
        top_commands.push(command);
    }

    let mut top_local = Vec::new();
    {
        let mut paint_ctx = PaintContext::new(&mut top_local, scale_factor);
        widget.paint_top(&mut paint_ctx);
    }
    for mut command in top_local {
        apply_clip(&mut command, clip_rect);
        top_commands.push(command);
    }

    let mut focus_local = Vec::new();
    {
        let mut paint_ctx = PaintContext::new(&mut focus_local, scale_factor);
        widget.paint_focus(&mut paint_ctx);
    }
    for mut command in focus_local {
        apply_clip(&mut command, clip_rect);
        if let DrawCommand::Rect(rect_cmd) = command {
            focus_commands.push(rect_cmd);
        }
    }
}

fn clip_intersect(
    existing: Option<(f32, f32, f32, f32)>,
    ancestor: (f32, f32, f32, f32)
) -> (f32, f32, f32, f32) {
    let Some((ex, ey, ew, eh)) = existing else {
        return ancestor;
    };
    let (ax, ay, aw, ah) = ancestor;
    let x0 = ex.max(ax);
    let y0 = ey.max(ay);
    let x1 = (ex + ew).min(ax + aw);
    let y1 = (ey + eh).min(ay + ah);
    (x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
}

fn apply_clip(command: &mut DrawCommand, clip_rect: Option<(f32, f32, f32, f32)>) {
    let Some(ancestor_clip) = clip_rect else {
        return;
    };
    let target = match command {
        DrawCommand::Rect(cmd) => &mut cmd.clip_rect,
        DrawCommand::Image(cmd) => &mut cmd.clip_rect,
        DrawCommand::Text(cmd) => &mut cmd.clip_rect,
        DrawCommand::Triangle(cmd) => &mut cmd.clip_rect,
        DrawCommand::BoxShadow(cmd) => &mut cmd.clip_rect,
    };
    *target = Some(clip_intersect(*target, ancestor_clip));
}

fn reset_dirty_recursive(widget: &mut dyn Widget) {
    widget.set_dirty(false);
    if let Some(children) = widget.children_mut() {
        for child in children.iter_mut() {
            reset_dirty_recursive(child.as_mut());
        }
    }
}

fn tree_is_dirty(tree: &[Box<dyn Widget>]) -> bool {
    tree.iter().any(|w| widget_dirty_recursive(w.as_ref()))
}

fn widget_dirty_recursive(widget: &dyn Widget) -> bool {
    widget.is_dirty() ||
        widget
            .children()
            .iter()
            .any(|c| widget_dirty_recursive(c.as_ref()))
}