xengui 0.2.5

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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// SPDX-License-Identifier: Apache-2.0
use crate::{
    AnimationManager,
    DrawCommand,
    ImageCommand,
    ImagePipeline,
    LayoutContext,
    LayoutEngine,
    PaintContext,
    RectCommand,
    RectPipeline,
    RenderCache,
    TextCommand,
    TextPipeline,
    TriangleCommand,
    TrianglePipeline,
    Widget,
};
use std::{ collections::HashSet, sync::Arc };
use winit::window::Window;
use web_time::Instant;

pub struct XenRenderer {
    pub window: Arc<Window>,
    pub surface: wgpu::Surface<'static>,
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    pub staging_belt: wgpu::util::StagingBelt,
    pub config: wgpu::SurfaceConfiguration,
    pub text_pipeline: TextPipeline,
    pub rect_pipeline: RectPipeline,
    pub triangle_pipeline: TrianglePipeline,
    pub image_pipeline: ImagePipeline,
    pub render_cache: RenderCache,
    pub anim: AnimationManager,
    last_tick: Instant,
}

impl XenRenderer {
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new(window: Arc<Window>, user_fonts: Vec<(String, Vec<u8>)>) -> Result<Self, String> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: if cfg!(target_os = "windows") {
                wgpu::Backends::DX12
            } else if cfg!(target_os = "macos") {
                wgpu::Backends::METAL
            } else if cfg!(target_os = "linux") {
                wgpu::Backends::VULKAN
            } else {
                wgpu::Backends::PRIMARY
            },
            flags: wgpu::InstanceFlags::default(),
            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
            backend_options: wgpu::BackendOptions::default(),
            display: None,
        });

        let surface = instance
            .create_surface(window.clone())
            .map_err(|e| format!("Cannot create surface: {}", e))?;

        let adapter = pollster
            ::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
            .expect("Cannot find a compatible adapter");

        let (device, queue) = pollster
            ::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
            .map_err(|e| format!("Cannot start GPU (device): {}", e))?;

        Self::init_common(window, surface, adapter, device, queue, user_fonts)
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn new(
        window: Arc<Window>,
        user_fonts: Vec<(String, Vec<u8>)>
    ) -> Result<Self, String> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            flags: wgpu::InstanceFlags::default(),
            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
            backend_options: wgpu::BackendOptions::default(),
            display: None,
        });

        let surface = instance
            .create_surface(window.clone())
            .map_err(|e| format!("Cannot create surface: {}", e))?;

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions::default()).await
            .expect("Cannot find a compatible adapter");

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor::default()).await
            .map_err(|e| format!("Cannot start GPU (device): {}", e))?;

        Self::init_common(window, surface, adapter, device, queue, user_fonts)
    }

    fn init_common(
        window: Arc<Window>,
        surface: wgpu::Surface<'static>,
        adapter: wgpu::Adapter,
        device: wgpu::Device,
        queue: wgpu::Queue,
        user_fonts: Vec<(String, Vec<u8>)>
    ) -> Result<Self, String> {
        let surface_caps = surface.get_capabilities(&adapter);
        let surface_format = surface_caps.formats
            .iter()
            .copied()
            .find(|f| {
                f == &wgpu::TextureFormat::Bgra8Unorm || f == &wgpu::TextureFormat::Rgba8Unorm
            })
            .unwrap_or(surface_caps.formats[0]);

        let text_pipeline = TextPipeline::new(&device, &queue, surface_format, user_fonts)?;
        let rect_pipeline = RectPipeline::new(&device, surface_format);
        let triangle_pipeline = TrianglePipeline::new(&device, surface_format);
        let image_pipeline = ImagePipeline::new(&device, surface_format);

        let alpha_mode = surface_caps.alpha_modes
            .iter()
            .copied()
            .find(|&a| {
                a == wgpu::CompositeAlphaMode::PreMultiplied ||
                    a == wgpu::CompositeAlphaMode::PostMultiplied
            })
            .unwrap_or(wgpu::CompositeAlphaMode::Auto);

        // Prevent zero-sized texture allocations on web target by defaulting to at least 1px
        let width = window.inner_size().width.max(1);
        let height = window.inner_size().height.max(1);

        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width,
            height,
            present_mode: wgpu::PresentMode::Fifo,
            desired_maximum_frame_latency: 2,
            alpha_mode,
            view_formats: vec![],
            color_space: wgpu::SurfaceColorSpace::Auto,
        };
        surface.configure(&device, &config);

        let staging_belt = wgpu::util::StagingBelt::new(device.clone(), 1024 * 1024);

        Ok(Self {
            window,
            surface,
            device,
            queue,
            staging_belt,
            config,
            text_pipeline,
            rect_pipeline,
            triangle_pipeline,
            image_pipeline,
            render_cache: RenderCache::new(),
            anim: AnimationManager::new(),
            last_tick: Instant::now(),
        })
    }

    pub fn render_frame(
        &mut self,
        tree: &mut [Box<dyn Widget>],
        theme: &Option<winit::window::Theme>
    ) {
        let now = Instant::now();
        let dt = now.duration_since(self.last_tick);
        self.last_tick = now;
        self.anim.tick(dt);

        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(surface_texture) => surface_texture,
            wgpu::CurrentSurfaceTexture::Suboptimal(surface_texture) => surface_texture,
            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
                log::warn!("Surface lost/outdated, reconfiguring.");
                self.surface.configure(&self.device, &self.config);
                return;
            }
            wgpu::CurrentSurfaceTexture::Timeout => {
                log::debug!("Surface timeout, skipping frame.");
                return;
            }
            wgpu::CurrentSurfaceTexture::Occluded => {
                log::debug!("Surface occluded, skipping frame.");
                return;
            }
            wgpu::CurrentSurfaceTexture::Validation => {
                log::warn!("Surface validation error, skipping frame.");
                return;
            }
            #[allow(unreachable_patterns)]
            _ => {
                log::warn!("Unhandled surface texture state, skipping frame.");
                return;
            }
        };
        let view = frame.texture.create_view(&Default::default());
        let mut encoder = self.device.create_command_encoder(&Default::default());
        {
            // uses the app's own active theme
            let app_background = crate::current_theme().background;
            let background_color = wgpu::Color {
                r: app_background.r() as f64,
                g: app_background.g() as f64,
                b: app_background.b() as f64,
                a: app_background.a() as f64,
            };

            let mut render_pass = encoder.begin_render_pass(
                &(wgpu::RenderPassDescriptor {
                    label: Some("Render Pass"),
                    color_attachments: &[
                        Some(wgpu::RenderPassColorAttachment {
                            view: &view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(background_color),
                                store: wgpu::StoreOp::Store,
                            },
                            depth_slice: None,
                        }),
                    ],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                })
            );

            let mut layout_ctx = LayoutContext {
                text: &mut self.text_pipeline,
                anim: &mut self.anim,
                scale_factor: self.window.scale_factor() as f32,
            };

            LayoutEngine::layout(
                tree,
                &mut layout_ctx,
                &mut self.render_cache,
                self.config.width as f32,
                self.config.height as f32
            );

            let mut commands: Vec<(i32, DrawCommand)> = Vec::new();
            let mut focus_commands: Vec<RectCommand> = 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 live_keys,
                    None
                );
            }
            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,
            }

            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 text_cmds: Vec<TextCommand> = Vec::new();

            macro_rules! flush_run {
                () => {
                    match current_kind {
                        Some(RunKind::Rect) => {
                            self.rect_pipeline.draw_batch(
                                &self.device,
                                &self.queue,
                                &mut render_pass,
                                self.config.width,
                                self.config.height,
                                &rect_buf
                            );
                        }
                        Some(RunKind::Triangle) => {
                            self.triangle_pipeline.draw_batch(
                                &self.device,
                                &self.queue,
                                &mut render_pass,
                                self.config.width,
                                self.config.height,
                                &tri_buf
                            );
                        }
                        Some(RunKind::Image) => {
                            self.image_pipeline.draw_batch(
                                &self.device,
                                &self.queue,
                                &mut render_pass,
                                self.config.width,
                                self.config.height,
                                &img_buf
                            );
                        }
                        None => {}
                    }
                    rect_buf.clear();
                    tri_buf.clear();
                    img_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.
            for (_, command) in commands {
                match command {
                    DrawCommand::Text(cmd) => {
                        text_cmds.push(*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);
                    }
                }
            }
            flush_run!();

            let resolved_theme = theme.unwrap_or(winit::window::Theme::Dark);
            for cmd in &text_cmds {
                self.text_pipeline.draw(self.window.scale_factor() as f32, resolved_theme, cmd);
            }

            // Underline/strike/overline quads produced while queueing text
            // above; drawn once, after every layer, instead of being
            // folded back into an already-drawn rect batch.
            let decorations = self.text_pipeline.take_decorations();
            if !decorations.is_empty() {
                self.rect_pipeline.draw_batch(
                    &self.device,
                    &self.queue,
                    &mut render_pass,
                    self.config.width,
                    self.config.height,
                    &decorations
                );
            }

            drop(render_pass);

            const MAX_TEXT_FLUSH_RETRIES: u32 = 3;

            let mut attempts = 0;
            loop {
                match
                    self.text_pipeline.flush(
                        &self.device,
                        &self.queue,
                        &mut encoder,
                        &view,
                        frame.texture.width(),
                        frame.texture.height()
                    )
                {
                    Ok(()) => {
                        break;
                    }
                    Err(e) if attempts < MAX_TEXT_FLUSH_RETRIES => {
                        attempts += 1;
                        log::warn!(
                            "Text cache resize, retrying flush ({attempts}/{MAX_TEXT_FLUSH_RETRIES}): {e}"
                        );
                        for cmd in &text_cmds {
                            self.text_pipeline.draw(
                                self.window.scale_factor() as f32,
                                resolved_theme,
                                cmd
                            );
                        }
                    }
                    Err(e) => {
                        log::error!("Text drawing failed permanently, skipping frame: {e}");
                        return;
                    }
                }
            }

            // Drawn in its own pass, after text, so the focus ring is
            // always visible above absolutely everything else in the frame.
            if !focus_commands.is_empty() {
                let mut focus_pass = encoder.begin_render_pass(
                    &(wgpu::RenderPassDescriptor {
                        label: Some("Focus Ring Pass"),
                        color_attachments: &[
                            Some(wgpu::RenderPassColorAttachment {
                                view: &view,
                                resolve_target: None,
                                ops: wgpu::Operations {
                                    load: wgpu::LoadOp::Load,
                                    store: wgpu::StoreOp::Store,
                                },
                                depth_slice: None,
                            }),
                        ],
                        depth_stencil_attachment: None,
                        timestamp_writes: None,
                        occlusion_query_set: None,
                        multiview_mask: None,
                    })
                );
                self.rect_pipeline.draw_batch(
                    &self.device,
                    &self.queue,
                    &mut focus_pass,
                    self.config.width,
                    self.config.height,
                    &focus_commands
                );
            }
        }

        // finish buffers
        self.staging_belt.finish();
        // complete pipeline and presentate
        self.queue.submit(Some(encoder.finish()));
        self.queue.present(frame);
        self.staging_belt.recall();
    }

    pub fn resize(
        &mut self,
        tree: &mut [Box<dyn Widget>],
        theme: &Option<winit::window::Theme>,
        size: winit::dpi::PhysicalSize<u32>
    ) {
        if size.width == self.config.width && size.height == self.config.height {
            return;
        }
        if size.width > 0 && size.height > 0 {
            self.config.width = size.width.max(1);
            self.config.height = size.height.max(1);
            self.surface.configure(&self.device, &self.config);
            for node in tree.iter_mut() {
                set_dirty_recursive(node.as_mut());
            }
            self.render_frame(tree, theme);
        }
    }
}

fn paint_recursive(
    widget: &dyn Widget,
    path: &str,
    cache: &mut RenderCache,
    commands: &mut Vec<(i32, DrawCommand)>,
    focus_commands: &mut Vec<RectCommand>,
    live_keys: &mut HashSet<String>,
    clip_rect: Option<(f32, f32, f32, f32)>
) {
    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());

    let z_index = widget.computed_style().z_index.unwrap_or(0);

    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);
                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,
            live_keys,
            child_clip
        );
    }

    // Painted after every descendant so overlays (scrollbar thumbs, etc.)
    // stay on top of this widget's own subtree; never cached since it
    // depends on live interaction state.
    let mut overlay = Vec::new();
    {
        let mut paint_ctx = PaintContext::new(&mut overlay);
        widget.paint_overlay(&mut paint_ctx);
    }
    for mut command in overlay {
        apply_clip(&mut command, clip_rect);
        commands.push((z_index, command));
    }

    // Collected separately from normal content so it can be drawn in its
    // own pass, above absolutely everything, regardless of z-index or
    // tree position; never cached since it depends on live focus state.
    let mut focus_local = Vec::new();
    {
        let mut paint_ctx = PaintContext::new(&mut focus_local);
        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,
    };
    *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 set_dirty_recursive(widget: &mut dyn Widget) {
    widget.set_dirty(true);
    if let Some(children) = widget.children_mut() {
        for child in children.iter_mut() {
            set_dirty_recursive(child.as_mut());
        }
    }
}