quickgui 0.1.1

A damage-driven, GPU-accelerated desktop GUI foundation
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
use super::*;

impl TextSystem {
    pub(super) fn new(
        device: &Device,
        queue: &Queue,
        format: TextureFormat,
        font_system: SharedFontSystem,
        shared_cache: Option<&Cache>,
    ) -> Self {
        let swash_cache = SwashCache::new();
        let cache = shared_cache.cloned().unwrap_or_else(|| Cache::new(device));
        let viewport = Viewport::new(device, &cache);
        let mut atlas = TextAtlas::new(device, queue, &cache, format);
        let renderer = TextRenderer::new(&mut atlas, device, MultisampleState::default(), None);
        Self {
            font_system,
            cache,
            swash_cache,
            viewport,
            atlas,
            renderers: vec![renderer],
            buffers: HashMap::with_capacity(512),
            shared_buffers: HashMap::with_capacity(512),
            colors: HashMap::with_capacity(MAX_RETAINED_TEXT_COLORS),
            seen: HashSet::with_capacity(128),
            visible: Vec::with_capacity(128),
            batches: Vec::with_capacity(16),
            layer_batches: Vec::with_capacity(4),
            eviction_keys: Vec::new(),
            shared_eviction_keys: Vec::new(),
            frame: 0,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn prepare(
        &mut self,
        device: &Device,
        queue: &Queue,
        scene: &Scene,
        viewport_rect: Rect,
        physical_width: u32,
        physical_height: u32,
        scale: f32,
    ) -> Result<(usize, usize, usize), RendererError> {
        self.frame = self.frame.wrapping_add(1);
        self.seen.clear();
        self.visible.clear();
        self.batches.clear();
        self.layer_batches.clear();
        let mut text_count = 0;
        let mut reshaped = 0;

        for layer in scene.paint_layers() {
            let start = self.visible.len();
            for item in layer.paint() {
                let PrimitiveRef::Text(index) = item.primitive else {
                    continue;
                };
                let run = &layer.text_runs()[index];
                let clip = run.clip.unwrap_or(viewport_rect);
                let Some(clip) = clip.intersection(viewport_rect) else {
                    continue;
                };
                if !run.bounds.intersects(clip) {
                    continue;
                }
                if !self.seen.insert(run.id) {
                    return Err(RendererError::DuplicateTextId(run.id));
                }
                text_count += 1;
                let color_key = [
                    run.style.color.r.to_bits(),
                    run.style.color.g.to_bits(),
                    run.style.color.b.to_bits(),
                    run.style.color.a.to_bits(),
                ];
                let color = if let Some(color) = self.colors.get(&color_key) {
                    *color
                } else {
                    if self.colors.len() >= MAX_RETAINED_TEXT_COLORS {
                        self.colors.clear();
                    }
                    let rgba = run.style.color.to_srgba8();
                    let color = glyphon::Color::rgba(rgba[0], rgba[1], rgba[2], rgba[3]);
                    self.colors.insert(color_key, color);
                    color
                };
                let bounds = physical_text_bounds(clip, scale);
                let left = run.bounds.x * scale;
                let top = run.bounds.y * scale;
                let run_reshaped = if run.highlights.is_none()
                    && should_fragment_basic_text(&run.content, &run.style)
                {
                    let mut fragment_left = left;
                    let mut fragment_reshaped = false;
                    for fragment in BasicTextFragments::new(&run.content) {
                        let content = Arc::<str>::from(fragment);
                        let (buffer, _projection, was_reshaped) = self
                            .update_shared_text_entry(content, &run.style, None, scale, self.frame);
                        let width = text_buffer_width(&buffer);
                        self.visible.push(VisibleText {
                            order: item.order,
                            buffer,
                            left: fragment_left,
                            top,
                            bounds,
                            color,
                            opacity: run.opacity,
                        });
                        fragment_left += width;
                        fragment_reshaped |= was_reshaped;
                    }
                    fragment_reshaped
                } else {
                    let was_reshaped = self.update_text_entry(
                        run.id,
                        &run.content,
                        &run.style,
                        run.highlights.as_ref(),
                        Some(run.bounds.width),
                        scale,
                        self.frame,
                    );
                    self.visible.push(VisibleText {
                        order: item.order,
                        buffer: Arc::clone(&self.buffers[&run.id].buffer),
                        left,
                        top,
                        bounds,
                        color,
                        opacity: run.opacity,
                    });
                    was_reshaped
                };
                if run_reshaped {
                    reshaped += 1;
                }
            }
            self.visible[start..].sort_unstable_by_key(|text| text.order);
            let batch_start = self.batches.len();
            let mut visible_start = start;
            while visible_start < self.visible.len() {
                let order = self.visible[visible_start].order;
                let visible_end = self.visible[visible_start..]
                    .iter()
                    .position(|text| text.order != order)
                    .map_or(self.visible.len(), |offset| visible_start + offset);
                self.batches.push(TextBatch {
                    order,
                    visible: visible_start..visible_end,
                    renderer: self.batches.len(),
                });
                visible_start = visible_end;
            }
            self.layer_batches.push(batch_start..self.batches.len());
        }

        self.viewport.update(
            queue,
            Resolution {
                width: physical_width,
                height: physical_height,
            },
        );

        let draw_calls = self.batches.len();
        while self.renderers.len() < draw_calls.max(1) {
            self.renderers.push(TextRenderer::new(
                &mut self.atlas,
                device,
                MultisampleState::default(),
                None,
            ));
        }

        let font_system = self.font_system.clone();
        let Self {
            swash_cache,
            viewport,
            atlas,
            renderers,
            visible,
            batches,
            ..
        } = self;
        let mut font_system = font_system.borrow_mut();
        for batch in batches.iter() {
            let areas = visible[batch.visible.clone()].iter().map(|item| TextArea {
                buffer: item.buffer.as_ref(),
                left: item.left,
                top: item.top,
                scale: 1.0,
                bounds: item.bounds,
                default_color: item.color,
                opacity: item.opacity,
                custom_glyphs: &[],
            });
            renderers[batch.renderer].prepare(
                device,
                queue,
                &mut font_system,
                atlas,
                viewport,
                areas,
                swash_cache,
            )?;
        }
        Ok((text_count, reshaped, draw_calls))
    }

    pub(super) fn measure(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        max_width: Option<f32>,
        scale: f32,
    ) -> Size {
        let width = canonical_text_width(
            style.wrap,
            style.align,
            style.text_overflow.is_some(),
            max_width,
        );
        let next_frame = self.frame.wrapping_add(1);
        self.update_text_entry(id, content, style, highlights, width, scale, next_frame);
        let buffer = &self.buffers[&id].buffer;
        let mut measured_width = 0.0_f32;
        let mut measured_height = 0.0_f32;
        for run in buffer
            .layout_runs()
            .take(style.line_clamp.unwrap_or(usize::MAX))
        {
            measured_width = measured_width.max(run.line_w);
            measured_height = measured_height.max(run.line_top + run.line_height);
        }
        if measured_height == 0.0 {
            measured_height = style.line_height * scale;
        }
        // Cosmic Text's unbounded `line_w` can land exactly on its later wrapping threshold.
        // Reserve one physical pixel so an intrinsically sized single line does not reflow only
        // after Taffy feeds that measured width back into the paint layout.
        let measured_width = (measured_width.ceil() + 1.0) / scale;
        let measured_width = match width {
            Some(width) => measured_width.min(width),
            None => measured_width,
        };
        Size::new(measured_width, measured_height.ceil() / scale)
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn caret_position(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        width: f32,
        scale: f32,
        index: usize,
    ) -> Point {
        let next_frame = self.frame.wrapping_add(1);
        self.update_text_entry(
            id,
            content,
            style,
            highlights,
            Some(width),
            scale,
            next_frame,
        );
        let entry = &self.buffers[&id];
        let display_index = entry.projection.original_to_display(index);
        let cursor = text_cursor_for_byte_index(&entry.projection.content, display_index);
        entry
            .buffer
            .cursor_position(&cursor)
            .map(|(x, y)| Point::new(x / scale, y / scale))
            .unwrap_or(Point::ZERO)
    }

    pub(super) fn index_for_point(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        hit: TextHitTest,
    ) -> usize {
        let next_frame = self.frame.wrapping_add(1);
        self.update_text_entry(
            id,
            content,
            style,
            highlights,
            Some(hit.width),
            hit.scale,
            next_frame,
        );
        let entry = &self.buffers[&id];
        entry
            .buffer
            .hit(
                hit.point.x.max(0.0) * hit.scale,
                hit.point.y.max(0.0) * hit.scale,
            )
            .map(|cursor| byte_index_for_text_cursor(&entry.projection.content, cursor))
            .map(|index| entry.projection.display_to_original(index))
            .unwrap_or(content.len())
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn selection_rects(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        width: f32,
        scale: f32,
        visible_y: Range<f32>,
        start: usize,
        end: usize,
    ) -> Vec<Rect> {
        let next_frame = self.frame.wrapping_add(1);
        self.update_text_entry(
            id,
            content,
            style,
            highlights,
            Some(width),
            scale,
            next_frame,
        );
        let entry = &self.buffers[&id];
        let display_ranges = entry.projection.display_ranges_for_original(start..end);
        let mut rectangles = Vec::new();
        for display_range in display_ranges {
            let start = text_cursor_for_byte_index(&entry.projection.content, display_range.start);
            let end = text_cursor_for_byte_index(&entry.projection.content, display_range.end);
            for run in entry
                .buffer
                .layout_runs()
                .take(style.line_clamp.unwrap_or(usize::MAX))
            {
                let top = run.line_top / scale;
                let bottom = top + run.line_height / scale;
                if top >= visible_y.end || bottom <= visible_y.start {
                    continue;
                }
                let line_top = run.line_top;
                rectangles.extend(text_selection_spans(&run, start, end).into_iter().map(
                    |(x, width)| {
                        Rect::new(
                            x / scale,
                            line_top / scale,
                            width / scale,
                            run.line_height / scale,
                        )
                    },
                ));
            }
        }
        rectangles
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn text_geometry(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        width: f32,
        scale: f32,
        visible_y: Range<f32>,
    ) -> StyledTextGeometry {
        let next_frame = self.frame.wrapping_add(1);
        self.update_text_entry(
            id,
            content,
            style,
            highlights,
            Some(width),
            scale,
            next_frame,
        );
        let entry = &self.buffers[&id];
        collect_styled_text_geometry(
            entry.buffer.as_ref(),
            entry.projection.highlights.as_deref().unwrap_or_default(),
            style,
            scale,
            visible_y,
            style.line_clamp,
        )
    }

    pub(super) fn render_order<'pass>(
        &'pass self,
        pass: &mut wgpu::RenderPass<'pass>,
        layer: usize,
        order: u32,
    ) -> Result<(), RendererError> {
        let Some(batches) = self.layer_batches.get(layer) else {
            return Ok(());
        };
        let Some(batch) = self.batches[batches.clone()]
            .iter()
            .find(|batch| batch.order == order)
        else {
            return Ok(());
        };
        self.renderers[batch.renderer].render(&self.atlas, &self.viewport, pass)?;
        Ok(())
    }

    pub(super) fn finish_frame(&mut self) {
        // Glyphon's prepared renderers own all GPU state needed after command submission. Drop
        // the temporary CPU-buffer references now instead of retaining them until the next
        // `prepare`, which both lowers idle memory ownership and lets a stable text id reclaim its
        // uniquely cached Buffer for width-only reflow during the following layout pass.
        self.visible.clear();
        self.atlas.trim();
        if self.renderers.len() > MAX_RETAINED_TEXT_RENDERERS {
            self.renderers.truncate(MAX_RETAINED_TEXT_RENDERERS);
        }
        let oldest_allowed = self.frame.saturating_sub(TEXT_RETENTION_FRAMES);
        self.eviction_keys.clear();
        self.eviction_keys.extend(
            self.buffers
                .iter()
                .filter_map(|(id, entry)| (entry.last_used_frame < oldest_allowed).then_some(*id)),
        );
        for id in self.eviction_keys.drain(..) {
            self.buffers.remove(&id);
        }

        if self.buffers.len() > MAX_RETAINED_TEXT_AREAS {
            let mut by_age: Vec<_> = self
                .buffers
                .iter()
                .map(|(id, entry)| (*id, entry.last_used_frame))
                .collect();
            by_age.sort_unstable_by_key(|(_, age)| *age);
            let remove_count = self.buffers.len() - MAX_RETAINED_TEXT_AREAS;
            for (id, _) in by_age.into_iter().take(remove_count) {
                self.buffers.remove(&id);
            }
        }

        self.shared_eviction_keys.clear();
        self.shared_eviction_keys.extend(
            self.shared_buffers
                .iter()
                .filter(|(_, entry)| entry.last_used_frame < oldest_allowed)
                .map(|(key, _)| key.clone()),
        );
        for key in self.shared_eviction_keys.drain(..) {
            self.shared_buffers.remove(&key);
        }

        if self.shared_buffers.len() > MAX_RETAINED_TEXT_LAYOUTS {
            let mut by_age: Vec<_> = self
                .shared_buffers
                .iter()
                .map(|(key, entry)| (key.clone(), entry.last_used_frame))
                .collect();
            by_age.sort_unstable_by_key(|(_, age)| *age);
            let remove_count = self.shared_buffers.len() - MAX_RETAINED_TEXT_LAYOUTS;
            for (key, _) in by_age.into_iter().take(remove_count) {
                self.shared_buffers.remove(&key);
            }
        }
    }

    pub(super) fn retained_counts(&self) -> (usize, usize, usize) {
        (
            self.buffers.len(),
            self.shared_buffers.len(),
            self.renderers.len(),
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn update_text_entry(
        &mut self,
        id: TextId,
        content: &Arc<str>,
        style: &TextStyle,
        highlights: Option<&Arc<[TextHighlight]>>,
        width: Option<f32>,
        scale: f32,
        frame: u64,
    ) -> bool {
        // Left-aligned unwrapped glyph layout is independent of paint bounds. Other alignments need
        // the assigned width so shaping, hit testing, selection, and rendering share exact x data.
        let width = canonical_text_width(
            style.wrap,
            style.align,
            style.text_overflow.is_some(),
            width,
        );
        let key = TextLayoutKey {
            content: content.clone(),
            highlights: highlights.cloned(),
            width,
            font_size: style.font_size,
            line_height: style.line_height,
            monospace_width: style.monospace_width,
            family: style.family.clone(),
            features: style.features.clone(),
            fallbacks: normalize_fallbacks(style.fallbacks.clone()),
            weight: style.weight,
            font_style: style.font_style,
            font_thicken: style.font_thicken,
            underline: style.underline,
            underline_color: style.underline_color,
            underline_wavy: style.underline_wavy,
            underline_thickness: style.underline_thickness,
            strikethrough: style.strikethrough,
            strikethrough_color: style.strikethrough_color,
            align: style.align,
            wrap: style.wrap,
            text_overflow: style.text_overflow.clone(),
            line_clamp: style.line_clamp,
            shaping: style.shaping,
            scale,
        };

        if let Some(buffer) = self.buffers.get_mut(&id).and_then(|entry| {
            entry.last_used_frame = frame;
            (entry.key == key).then(|| Arc::clone(&entry.buffer))
        }) {
            self.shared_buffers
                .entry(key)
                .and_modify(|entry| entry.last_used_frame = frame)
                .or_insert(SharedTextEntry {
                    buffer,
                    projection: Arc::clone(&self.buffers[&id].projection),
                    last_used_frame: frame,
                });
            return false;
        }

        let previous = self.buffers.remove(&id);

        // Prefer a layout already shared by another text id or retained from a recent frame.
        if let Some(entry) = self.shared_buffers.get_mut(&key) {
            entry.last_used_frame = frame;
            self.buffers.insert(
                id,
                TextEntry {
                    key,
                    buffer: Arc::clone(&entry.buffer),
                    projection: Arc::clone(&entry.projection),
                    last_used_frame: frame,
                },
            );
            return false;
        }

        // A stable text id commonly changes only its width while a window is being resized. The
        // per-id entry and shared-layout entry are normally the only owners after `finish_frame`.
        // Reclaim that Buffer and ask Cosmic Text for a relayout; its shaped line cache remains
        // intact. If another id genuinely shares the old layout, keep it immutable and fall back
        // to the normal shared/new-buffer path.
        let reusable = previous.and_then(|entry| {
            let shared = self.shared_buffers.get(&entry.key)?;
            if !Arc::ptr_eq(&entry.buffer, &shared.buffer) || Arc::strong_count(&entry.buffer) != 2
            {
                return None;
            }
            self.shared_buffers.remove(&entry.key);
            if entry.key.same_except_width(&key) {
                Arc::try_unwrap(entry.buffer)
                    .ok()
                    .map(|buffer| (buffer, entry.projection))
            } else {
                // A stable id with a projected/truncated layout cannot reflow the shortened
                // buffer, but its superseded width must not linger for the retention window.
                // Removing the sole shared owner drops that CPU buffer immediately while layouts
                // genuinely shared by another id remain cached.
                None
            }
        });

        let (buffer, projection, reshaped) = if let Some((mut buffer, projection)) = reusable {
            let mut font_system = self.font_system.borrow_mut();
            reflow_text_buffer(&mut buffer, &mut font_system, key.width, scale);
            drop(font_system);
            let buffer = Arc::new(buffer);
            self.shared_buffers.insert(
                key.clone(),
                SharedTextEntry {
                    buffer: Arc::clone(&buffer),
                    projection: Arc::clone(&projection),
                    last_used_frame: frame,
                },
            );
            (buffer, projection, true)
        } else {
            self.update_shared_text_entry_for_key(key.clone(), style, scale, frame)
        };
        self.buffers.insert(
            id,
            TextEntry {
                key,
                buffer,
                projection,
                last_used_frame: frame,
            },
        );
        reshaped
    }

    pub(super) fn update_shared_text_entry(
        &mut self,
        content: Arc<str>,
        style: &TextStyle,
        width: Option<f32>,
        scale: f32,
        frame: u64,
    ) -> (Arc<Buffer>, Arc<ProjectedText>, bool) {
        let key = TextLayoutKey {
            content,
            highlights: None,
            width: canonical_text_width(
                style.wrap,
                style.align,
                style.text_overflow.is_some(),
                width,
            ),
            font_size: style.font_size,
            line_height: style.line_height,
            monospace_width: style.monospace_width,
            family: style.family.clone(),
            features: style.features.clone(),
            fallbacks: normalize_fallbacks(style.fallbacks.clone()),
            weight: style.weight,
            font_style: style.font_style,
            font_thicken: style.font_thicken,
            underline: style.underline,
            underline_color: style.underline_color,
            underline_wavy: style.underline_wavy,
            underline_thickness: style.underline_thickness,
            strikethrough: style.strikethrough,
            strikethrough_color: style.strikethrough_color,
            align: style.align,
            wrap: style.wrap,
            text_overflow: style.text_overflow.clone(),
            line_clamp: style.line_clamp,
            shaping: style.shaping,
            scale,
        };
        self.update_shared_text_entry_for_key(key, style, scale, frame)
    }

    pub(super) fn update_shared_text_entry_for_key(
        &mut self,
        key: TextLayoutKey,
        style: &TextStyle,
        scale: f32,
        frame: u64,
    ) -> (Arc<Buffer>, Arc<ProjectedText>, bool) {
        if let Some(entry) = self.shared_buffers.get_mut(&key) {
            entry.last_used_frame = frame;
            (
                Arc::clone(&entry.buffer),
                Arc::clone(&entry.projection),
                false,
            )
        } else {
            let (buffer, projection) = {
                let mut font_system = self.font_system.borrow_mut();
                let (projection, buffer) = prepare_text_buffer(
                    &mut font_system,
                    &key.content,
                    key.highlights.as_ref(),
                    style,
                    key.width,
                    scale,
                );
                (Arc::new(buffer), Arc::new(projection))
            };
            self.shared_buffers.insert(
                key.clone(),
                SharedTextEntry {
                    buffer: Arc::clone(&buffer),
                    projection: Arc::clone(&projection),
                    last_used_frame: frame,
                },
            );
            (buffer, projection, true)
        }
    }
}