guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! Textured quad rendering for images with transform support.
//!
//! This module renders images as textured quads with full transform support
//! (rotation, scale, translate). Textures are cached for performance.

use std::borrow::Cow;
use std::cell::Cell;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};

use rustc_hash::FxHashMap;
use wgpu::{
    BindGroup, Device, Extent3d, Queue, RenderPass, Texture, TextureDimension, TextureFormat,
    TextureUsages,
};

use super::commands::DrawCommand;
use super::constants::SVG_QUALITY_MULTIPLIER;
use super::flatten::FlattenedCommand;
use super::image_atlas::{AtlasEntry, ImageAtlas};
use super::textured_quad::{QuadDraw, TexturedQuadPipeline};
use super::textured_vertex::{NO_TINT, QuadClip, TexturedVertex};
use crate::image_decode::{DecodeKey, DecodedImage, Extent, SampledBytes};
use crate::render_stats::Pipeline;
use crate::widgets::Color;
use crate::widgets::Rect;
use crate::widgets::image::{ContentFit, ImageSource};

/// A prepared image quad ready for rendering: the texture it samples, and
/// where its corners are among the frame's quads.
pub struct PreparedImageQuad {
    texture: Rc<CachedTexture>,
    quad: u32,
}

impl QuadDraw for PreparedImageQuad {
    fn bind_group(&self) -> &Rc<BindGroup> {
        &self.texture.bind_group
    }

    fn quad(&self) -> u32 {
        self.quad
    }
}

/// Where a cached image's texels live.
enum Backing {
    /// A texture of its own: an image larger than an atlas page takes.
    Own(Texture),
    /// A place on a shared page, given back when this is dropped.
    Atlas(AtlasEntry),
}

/// Cached texture data.
struct CachedTexture {
    backing: Backing,
    /// The bind group it is drawn through: its own texture's, or its page's.
    /// Made with the texture or the page and kept with it, so drawing it again
    /// makes nothing, and every image on one page draws through the same one.
    bind_group: Rc<BindGroup>,
    /// Its texels within that texture, `[x, y, width, height]` in texture
    /// coordinates — all of it, for a texture of its own.
    uv_rect: [f32; 4],
    /// Original intrinsic dimensions
    intrinsic_width: f32,
    intrinsic_height: f32,
    /// When a frame last drew it. A `Cell` because the frame that draws it
    /// holds it through an `Rc` already.
    last_used: Cell<Instant>,
    /// The source and raster it was uploaded from, whose pixels went with the
    /// upload: the decode cache is told when this texture goes.
    decoded_from: Option<(DecodeKey, Extent)>,
}

impl CachedTexture {
    /// What it costs on the GPU, counted against the cache's budget.
    fn bytes(&self) -> usize {
        match &self.backing {
            Backing::Own(texture) => texture_bytes(texture),
            Backing::Atlas(entry) => entry.bytes(),
        }
    }
}

impl Drop for CachedTexture {
    fn drop(&mut self) {
        if let Some((key, extent)) = self.decoded_from.take() {
            crate::image_decode::texture_evicted(key, extent);
        }
    }
}

/// Cache key for image textures: the source, and which of its rasters.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CacheKey {
    source: SourceKey,
    extent: Extent,
}

/// Which source a texture is of.
///
/// A source that decodes is its decode entry: `DecodeKey` settled whether two
/// sources are one when the entry was made, so finding its texture reads none
/// of its bytes. Raw pixels have no entry and are their own buffer.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum SourceKey {
    Decoded(DecodedImage),
    Rgba(RgbaKey),
}

impl SourceKey {
    /// `None` for a source that decodes and has no entry to name it by.
    fn of(source: &ImageSource, decoded: Option<&DecodedImage>) -> Option<Self> {
        match source {
            ImageSource::Rgba {
                width,
                height,
                pixels,
            } => Some(Self::Rgba(RgbaKey {
                width: *width,
                height: *height,
                pixels: SampledBytes(pixels.clone()),
            })),
            _ => decoded.cloned().map(Self::Decoded),
        }
    }

    /// Whether nothing but this key holds the source, so no image can draw it
    /// again. Only raw pixels can be orphaned: a decode entry outlives every
    /// texture of it.
    fn orphaned(&self) -> bool {
        matches!(self, Self::Rgba(key) if Arc::strong_count(&key.pixels.0) == 1)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct RgbaKey {
    width: u32,
    height: u32,
    pixels: SampledBytes,
}

/// The pixel size to rasterize an SVG of `intrinsic` size at.
///
/// With a `target` — the box it is shown in, in logical pixels — the raster
/// is fitted to that box, preserving aspect ratio, rather than to the SVG's
/// intrinsic size: a 16px weather icon with a 104px viewBox costs a 16px
/// raster, not a 104px one, which is both faster and sharper. `scale` carries
/// transform scale, HiDPI factor and the quality multiplier.
///
/// Both are quantized first — the scale to quarters, the box to whole pixels —
/// so a scale animation asks for a raster per step rather than per frame.
fn svg_extent(
    (width, height): (f32, f32),
    scale: f32,
    target: Option<(f32, f32)>,
    limit: u32,
) -> Option<(u32, u32)> {
    let scale = (scale * 4.0).round() / 4.0;
    let scale = match target {
        Some((tw, th)) if tw >= 1.0 && th >= 1.0 => {
            scale * (tw.round() / width).min(th.round() / height)
        }
        _ => scale,
    };
    let scale = scale.min(limit as f32 / width.max(height));
    let extent = ((width * scale).ceil(), (height * scale).ceil());
    (extent.0 >= 1.0 && extent.1 >= 1.0)
        .then_some(((extent.0 as u32).min(limit), (extent.1 as u32).min(limit)))
}

/// Fit premultiplied pixels within the texture limit.
fn resized_raster(width: u32, height: u32, rgba: &[u8], limit: u32) -> Option<(u32, u32, Vec<u8>)> {
    let source = image::ImageBuffer::<image::Rgba<u8>, _>::from_raw(width, height, rgba)?;
    let longest = width.max(height) as u64;
    if longest == 0 || limit == 0 {
        return None;
    }
    let new_width = ((width as u64 * limit as u64 + longest / 2) / longest).max(1) as u32;
    let new_height = ((height as u64 * limit as u64 + longest / 2) / longest).max(1) as u32;
    let pixels = image::imageops::resize(
        &source,
        new_width,
        new_height,
        image::imageops::FilterType::Triangle,
    );
    Some((new_width, new_height, pixels.into_raw()))
}

fn raster_upload_pixels(
    width: u32,
    height: u32,
    rgba: &[u8],
    limit: u32,
) -> Option<(u32, u32, Cow<'_, [u8]>)> {
    if width == 0 || height == 0 {
        return None;
    }
    if width > limit || height > limit {
        let Some((w, h, pixels)) = resized_raster(width, height, rgba, limit) else {
            log::warn!("Failed to resize image {width}x{height} to texture limit {limit}");
            return None;
        };
        log::warn!("Resized image {width}x{height} to {w}x{h} for texture limit {limit}");
        Some((w, h, Cow::Owned(pixels)))
    } else {
        Some((width, height, Cow::Borrowed(rgba)))
    }
}

/// A texture of its own, for an image too large for an atlas page.
///
/// `Rgba8Unorm`, like the pages, so colours pass through without an sRGB
/// conversion.
fn own_texture(device: &Device, queue: &Queue, width: u32, height: u32, rgba: &[u8]) -> Texture {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("Image Texture"),
        size: Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: TextureDimension::D2,
        format: TextureFormat::Rgba8Unorm,
        usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        rgba,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(4 * width),
            rows_per_image: Some(height),
        },
        Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
    );
    texture
}

/// Renderer for images as textured quads.
pub struct ImageQuadRenderer {
    /// Pipeline, layout, sampler and index buffer — shared with the text
    /// renderer, which draws the same quad from a different texture.
    quad: TexturedQuadPipeline,

    /// The pages small images are packed onto.
    atlas: ImageAtlas,
    // Texture cache
    texture_cache: FxHashMap<CacheKey, Rc<CachedTexture>>,
    texture_limit: u32,
    /// The size of the raster each SVG source was last drawn from: what is
    /// drawn, stretched, while a new size is on its way.
    last_svg_raster: FxHashMap<DecodedImage, Extent>,
    /// When the frame being prepared started: what a texture drawn in it is
    /// stamped with.
    frame_started: Instant,
    /// The sum of every cached texture's `bytes`.
    cached_bytes: usize,
}

/// What a quad's vertices carry for its opacity and its tint. A tint's own
/// alpha fades the image as an opacity would.
fn opacity_and_tint(opacity: f32, tint: Option<Color>) -> (f32, [f32; 4]) {
    match tint {
        Some(c) => (opacity * c.a, [c.r, c.g, c.b, 1.0]),
        None => (opacity, NO_TINT),
    }
}

/// How long a texture no frame has drawn is kept once the cache is past its
/// budget. One drawn more recently is never evicted — the cache grows past its
/// budget instead — because a raster texture's pixels went with its upload: an
/// image still in view whose texture was evicted is blank until it is decoded
/// again, and evicting it every frame would decode it every frame.
const KEEP_UNUSED: Duration = Duration::from_secs(1);

/// The bytes `texture` holds on the GPU, every mip level of it.
fn texture_bytes(texture: &Texture) -> usize {
    let size = texture.size();
    let texel = texture.format().block_copy_size(None).unwrap_or(4) as usize;
    (0..texture.mip_level_count())
        .map(|level| {
            let width = (size.width >> level).max(1) as usize;
            let height = (size.height >> level).max(1) as usize;
            width * height * texel
        })
        .sum()
}

impl ImageQuadRenderer {
    pub fn new(
        device: &Device,
        format: TextureFormat,
        clip_records: &wgpu::BindGroupLayout,
    ) -> Self {
        Self {
            quad: TexturedQuadPipeline::new(device, format, clip_records, "ImageQuad"),
            atlas: ImageAtlas::default(),
            texture_cache: FxHashMap::default(),
            texture_limit: device.limits().max_texture_dimension_2d,
            last_svg_raster: FxHashMap::default(),
            frame_started: Instant::now(),
            cached_bytes: 0,
        }
    }

    /// Update screen dimensions for NDC conversion.
    pub fn set_screen_size(&mut self, width: f32, height: f32) {
        self.quad.set_screen_size(width, height);
    }

    /// Begin a new frame: what a texture drawn in it is stamped with.
    pub fn begin_frame(&mut self) {
        self.frame_started = Instant::now();
        self.quad.begin_frame();
    }

    /// Write this frame's image quads to the GPU, once they are all prepared.
    pub fn upload(&mut self, device: &Device, queue: &Queue) {
        self.quad.upload(device, queue);
    }

    /// Bring the cache back under `budget` bytes, once the frame has drawn
    /// what it draws.
    ///
    /// After the frame rather than before it, so every texture this frame drew
    /// is stamped as drawn now: before it, a surface that sat idle for longer
    /// than [`KEEP_UNUSED`] would have its own images evicted by the frame
    /// about to draw them.
    pub fn trim(&mut self, budget: usize) {
        // Before the budget is looked at: a page empties when the last frame's
        // quads let go of what was evicted from it, which is not this call.
        self.atlas.drop_empty_pages();
        // Under the budget too: the key holds the pixels, and would keep a
        // buffer the application let go for as long as its texture stayed.
        self.texture_cache.retain(|key, texture| {
            let orphaned = key.source.orphaned();
            if orphaned {
                self.cached_bytes -= texture.bytes();
            }
            !orphaned
        });
        if self.cached_bytes <= budget {
            return;
        }
        let mut idle: Vec<(Instant, CacheKey)> = self
            .texture_cache
            .iter()
            .filter(|(_, texture)| {
                self.frame_started
                    .saturating_duration_since(texture.last_used.get())
                    > KEEP_UNUSED
            })
            .map(|(key, texture)| (texture.last_used.get(), key.clone()))
            .collect();
        idle.sort_unstable_by_key(|(last_used, _)| *last_used);
        for (_, key) in idle {
            if self.cached_bytes <= budget {
                break;
            }
            if let Some(texture) = self.texture_cache.remove(&key) {
                self.cached_bytes -= texture.bytes();
                if let SourceKey::Decoded(decoded) = &key.source
                    && self.last_svg_raster.get(decoded) == Some(&key.extent)
                {
                    self.last_svg_raster.remove(decoded);
                }
            }
        }
    }

    /// How many textures are cached.
    #[cfg(feature = "testing")]
    pub(crate) fn texture_count(&self) -> usize {
        self.texture_cache.len()
    }

    /// Drop every texture, as eviction does, and say so as eviction does.
    #[cfg(feature = "testing")]
    pub(crate) fn forget_textures(&mut self) {
        self.texture_cache.clear();
        self.last_svg_raster.clear();
        self.cached_bytes = 0;
    }

    /// How many atlas pages there are.
    #[cfg(feature = "testing")]
    pub(crate) fn atlas_pages(&self) -> usize {
        self.atlas.pages()
    }

    /// Get or create a cached texture for the given source.
    ///
    /// `svg_target` is the widget rect the SVG will be displayed in (logical
    /// pixels), which its raster is sized to — see [`svg_extent`]. `None`
    /// (ContentFit::None) keeps the intrinsic size, which is what that fit
    /// mode displays.
    ///
    /// An SVG with no raster of that size yet draws one now if it is small;
    /// a larger one is asked of the worker, and is drawn from the raster it
    /// was last drawn from until the new one lands.
    fn get_or_create_texture(
        &mut self,
        device: &Device,
        queue: &Queue,
        source: &ImageSource,
        render_scale: f32,
        svg_target: Option<(f32, f32)>,
        decoded: Option<&DecodedImage>,
    ) -> Option<Rc<CachedTexture>> {
        let extent = match decoded.and_then(DecodedImage::svg_size) {
            Some(size) => Some(svg_extent(
                size,
                render_scale,
                svg_target,
                self.texture_limit,
            )?),
            None => None,
        };
        let key = CacheKey {
            source: SourceKey::of(source, decoded)?,
            extent,
        };
        let texture = match self.texture_cache.get_key_value(&key) {
            Some((cached_key, cached)) => {
                let cached = cached.clone();
                // Equal pixels in a new buffer, and nothing else holds the old
                // one: keyed by the new one from now on, so the next lookup is
                // settled by the pointer and `trim` keeps a texture still drawn.
                if cached_key.source.orphaned() {
                    self.texture_cache.remove(&key);
                    self.texture_cache.insert(key.clone(), cached.clone());
                }
                Some(cached)
            }
            None => self.load_texture(device, queue, source, key.clone(), decoded),
        };
        let svg = extent.and(decoded);
        let texture = match texture {
            Some(texture) => {
                if let Some(svg) = svg
                    && self.last_svg_raster.get(svg) != Some(&extent)
                {
                    self.last_svg_raster.insert(svg.clone(), extent);
                }
                texture
            }
            None => {
                let last = svg
                    .and_then(|svg| self.last_svg_raster.get(svg))
                    .and_then(|&extent| {
                        self.texture_cache.get(&CacheKey {
                            source: key.source.clone(),
                            extent,
                        })
                    });
                match (last, decoded) {
                    (Some(last), _) => last.clone(),
                    (None, Some(decoded)) if extent.is_some() => {
                        decoded.drew_nothing();
                        return None;
                    }
                    (None, _) => return None,
                }
            }
        };
        texture.last_used.set(self.frame_started);
        Some(texture)
    }

    /// Upload a texture to the GPU, and cache it under `key`.
    ///
    /// A raster `Path` or `Bytes` source arrives already decoded and an SVG
    /// already rasterized — the worker in `image_decode` did that off the
    /// frame. Oversized rasters are resized here before upload. Taking the
    /// pixels for upload drops them from the cache. A raster source whose
    /// pixels were already taken has none left: this draws nothing and reports
    /// the texture missing, which sends the source back to the worker. An SVG
    /// with none of this size rasterizes them here if they are few, and asks
    /// the worker for them if not. Decoding a raster image or rasterizing a
    /// large SVG here instead is the stall that module exists to remove.
    fn load_texture(
        &mut self,
        device: &Device,
        queue: &Queue,
        source: &ImageSource,
        key: CacheKey,
        decoded: Option<&DecodedImage>,
    ) -> Option<Rc<CachedTexture>> {
        let mut texture = match source {
            ImageSource::Path(_) | ImageSource::Bytes(_) => {
                let Some(pixels) = decoded.and_then(DecodedImage::take) else {
                    crate::image_decode::texture_missing(source);
                    return None;
                };
                match self.upload_raster(device, queue, pixels.width, pixels.height, &pixels.rgba) {
                    Some(texture) => texture,
                    None => {
                        decoded?.upload_failed();
                        return None;
                    }
                }
            }
            ImageSource::Rgba {
                width,
                height,
                pixels,
            } => {
                let expected = (*width as usize)
                    .checked_mul(*height as usize)
                    .and_then(|v| v.checked_mul(4));
                if Some(pixels.len()) != expected {
                    log::warn!(
                        "Rgba image source size mismatch: {}x{} expects {:?} bytes, got {}",
                        width,
                        height,
                        expected,
                        pixels.len()
                    );
                    return None;
                }
                // Raw pixels are straight; the pipeline takes them
                // premultiplied.
                let pixels = crate::image_decode::premultiplied(pixels);
                self.upload_raster(device, queue, *width, *height, &pixels)?
            }
            ImageSource::SvgPath(_) | ImageSource::SvgBytes(_) => {
                let decoded = decoded?;
                let pixels = decoded.take_or_rasterize(key.extent)?;
                self.store(
                    device,
                    queue,
                    pixels.width,
                    pixels.height,
                    &pixels.rgba,
                    decoded.svg_size()?,
                )?
            }
        };
        texture.decoded_from = decoded.map(|decoded| (decoded.key().clone(), key.extent));

        let cached = Rc::new(texture);
        self.cached_bytes += cached.bytes();
        self.texture_cache.insert(key, cached.clone());
        Some(cached)
    }

    /// Upload raw RGBA8 pixel data to GPU.
    fn upload_raster(
        &mut self,
        device: &Device,
        queue: &Queue,
        width: u32,
        height: u32,
        rgba: &[u8],
    ) -> Option<CachedTexture> {
        let (upload_width, upload_height, rgba) =
            raster_upload_pixels(width, height, rgba, self.texture_limit)?;
        self.store(
            device,
            queue,
            upload_width,
            upload_height,
            &rgba,
            (width as f32, height as f32),
        )
    }

    /// Put `rgba`, `width` by `height` texels, where it will be drawn from: on
    /// an atlas page if it is small enough for one, in a texture of its own if
    /// not. `intrinsic` is the size the image lays out at, which for an SVG is
    /// not the size it was rasterized at.
    fn store(
        &mut self,
        device: &Device,
        queue: &Queue,
        width: u32,
        height: u32,
        rgba: &[u8],
        (intrinsic_width, intrinsic_height): (f32, f32),
    ) -> Option<CachedTexture> {
        let (backing, bind_group, uv_rect) = match self
            .atlas
            .insert(device, queue, &self.quad, width, height, rgba)
        {
            Some((entry, uv_rect)) => {
                let bind_group = entry.bind_group().clone();
                (Backing::Atlas(entry), bind_group, uv_rect)
            }
            None => {
                let texture = own_texture(device, queue, width, height, rgba);
                let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
                let bind_group = self
                    .quad
                    .bind_texture(device, &view, "ImageQuad Bind Group");
                (Backing::Own(texture), bind_group, [0.0, 0.0, 1.0, 1.0])
            }
        };
        Some(CachedTexture {
            backing,
            bind_group,
            uv_rect,
            intrinsic_width,
            intrinsic_height,
            last_used: Cell::new(self.frame_started),
            decoded_from: None,
        })
    }

    /// Prepare image commands for rendering, appending them to `out`.
    ///
    /// The caller's buffer rather than one of ours: every group's quads end up
    /// in the same frame-long `Vec` addressed by range, so a `Vec` returned
    /// here would be allocated per group only to be drained into that one.
    pub fn prepare(
        &mut self,
        device: &Device,
        queue: &Queue,
        commands: &[FlattenedCommand],
        scale_factor: f32,
        out: &mut Vec<PreparedImageQuad>,
    ) {
        out.extend(
            commands
                .iter()
                .filter_map(|cmd| self.prepare_single(device, queue, cmd, scale_factor)),
        );
    }

    /// Prepare a single image command.
    fn prepare_single(
        &mut self,
        device: &Device,
        queue: &Queue,
        cmd: &FlattenedCommand,
        scale_factor: f32,
    ) -> Option<PreparedImageQuad> {
        let (source, decoded, rect, content_fit, tint) = match &*cmd.command {
            DrawCommand::Image {
                source,
                decoded,
                rect,
                content_fit,
                tint,
            } => (source, decoded, rect, content_fit, tint),
            _ => return None,
        };

        // Extract scale from transform for SVG quality
        let transform_scale = cmd.world_transform.extract_scale().max(1.0);

        // Rasterize SVGs at the size they are displayed at; ContentFit::None
        // shows the image at intrinsic size, so no target there.
        let svg_target = (*content_fit != ContentFit::None).then_some((rect.width, rect.height));

        // Get or create the texture
        // An SVG is rasterised at the scale it is shown at; a raster image is
        // uploaded at its own size.
        let render_scale = if source.is_svg() {
            transform_scale * scale_factor * SVG_QUALITY_MULTIPLIER
        } else {
            1.0
        };

        let cached = self.get_or_create_texture(
            device,
            queue,
            source,
            render_scale,
            svg_target,
            decoded.as_ref(),
        )?;

        // Calculate display rect and UV coordinates based on content fit
        let (display_rect, (u_min, v_min, u_max, v_max)) = self.calculate_display_rect_and_uv(
            rect,
            cached.intrinsic_width,
            cached.intrinsic_height,
            *content_fit,
        );
        // From the image's own coordinates to the texture it is drawn from,
        // which for one on an atlas page is a corner of the page.
        let [x, y, width, height] = cached.uv_rect;
        let uv = (
            x + u_min * width,
            y + v_min * height,
            x + u_max * width,
            y + v_max * height,
        );

        // An image is cut in the clip's own space, so a turned clip cuts the
        // turned shape.
        let clip = cmd.clip().map_or(QuadClip::NONE, |clip| {
            QuadClip::resolved(&clip, scale_factor)
        });

        let corners = self.compute_vertices(
            &display_rect,
            &cmd.world_transform,
            uv,
            scale_factor,
            clip,
            opacity_and_tint(cmd.opacity, *tint),
        );

        Some(PreparedImageQuad {
            quad: self.quad.push(corners),
            texture: cached,
        })
    }

    /// Calculate the display rect and UV coordinates based on content fit.
    fn calculate_display_rect_and_uv(
        &self,
        rect: &Rect,
        intrinsic_width: f32,
        intrinsic_height: f32,
        content_fit: ContentFit,
    ) -> (Rect, (f32, f32, f32, f32)) {
        let img_width = intrinsic_width;
        let img_height = intrinsic_height;
        let img_aspect = img_width / img_height;
        let widget_aspect = rect.width / rect.height;

        match content_fit {
            ContentFit::Fill => {
                // Stretch to fill - use full rect and full UV
                (*rect, (0.0, 0.0, 1.0, 1.0))
            }
            ContentFit::Contain => {
                // Fit within bounds, preserving aspect ratio (letterbox/pillarbox)
                let (scaled_w, scaled_h) = if widget_aspect > img_aspect {
                    // Widget is wider - fit to height, center horizontally
                    (rect.height * img_aspect, rect.height)
                } else {
                    // Widget is taller - fit to width, center vertically
                    (rect.width, rect.width / img_aspect)
                };
                let offset_x = (rect.width - scaled_w) / 2.0;
                let offset_y = (rect.height - scaled_h) / 2.0;
                (
                    Rect::new(rect.x + offset_x, rect.y + offset_y, scaled_w, scaled_h),
                    (0.0, 0.0, 1.0, 1.0),
                )
            }
            ContentFit::Cover => {
                // Cover bounds, cropping as needed (adjust UV to crop)
                let (u_min, v_min, u_max, v_max) = if widget_aspect > img_aspect {
                    // Widget is wider - crop top/bottom
                    let visible_height = img_aspect / widget_aspect;
                    let v_offset = (1.0 - visible_height) / 2.0;
                    (0.0, v_offset, 1.0, v_offset + visible_height)
                } else {
                    // Widget is taller - crop left/right
                    let visible_width = widget_aspect / img_aspect;
                    let u_offset = (1.0 - visible_width) / 2.0;
                    (u_offset, 0.0, u_offset + visible_width, 1.0)
                };
                (*rect, (u_min, v_min, u_max, v_max))
            }
            ContentFit::None => {
                // Use intrinsic size, centered in widget
                let offset_x = (rect.width - img_width) / 2.0;
                let offset_y = (rect.height - img_height) / 2.0;
                (
                    Rect::new(rect.x + offset_x, rect.y + offset_y, img_width, img_height),
                    (0.0, 0.0, 1.0, 1.0),
                )
            }
        }
    }

    /// Compute vertex positions by applying world transform to local corners.
    fn compute_vertices(
        &self,
        rect: &Rect,
        world_transform: &crate::transform::Transform,
        uv: (f32, f32, f32, f32),
        scale_factor: f32,
        clip: QuadClip,
        (opacity, tint): (f32, [f32; 4]),
    ) -> [TexturedVertex; 4] {
        // Get local rect corners
        let local_corners = [
            (rect.x, rect.y),                            // top-left
            (rect.x + rect.width, rect.y),               // top-right
            (rect.x, rect.y + rect.height),              // bottom-left
            (rect.x + rect.width, rect.y + rect.height), // bottom-right
        ];

        // Apply world_transform to get screen coordinates (in logical pixels)
        // Then multiply by scale_factor to get physical pixels
        let screen_corners: [(f32, f32); 4] = [
            {
                let (sx, sy) =
                    world_transform.transform_point(local_corners[0].0, local_corners[0].1);
                (sx * scale_factor, sy * scale_factor)
            },
            {
                let (sx, sy) =
                    world_transform.transform_point(local_corners[1].0, local_corners[1].1);
                (sx * scale_factor, sy * scale_factor)
            },
            {
                let (sx, sy) =
                    world_transform.transform_point(local_corners[2].0, local_corners[2].1);
                (sx * scale_factor, sy * scale_factor)
            },
            {
                let (sx, sy) =
                    world_transform.transform_point(local_corners[3].0, local_corners[3].1);
                (sx * scale_factor, sy * scale_factor)
            },
        ];

        let (u_min, v_min, u_max, v_max) = uv;
        let uvs = [
            [u_min, v_min],
            [u_max, v_min],
            [u_min, v_max],
            [u_max, v_max],
        ];

        std::array::from_fn(|i| {
            let (x, y) = screen_corners[i];
            TexturedVertex::corner(self.quad.to_ndc(x, y), uvs[i], (x, y), &clip, opacity, tint)
        })
    }

    /// Render the prepared image quads.
    pub fn render<'a>(
        &'a self,
        render_pass: &mut RenderPass<'a>,
        quads: &'a [PreparedImageQuad],
        clip_records: &'a wgpu::BindGroup,
    ) {
        self.quad
            .draw(render_pass, quads, clip_records, Pipeline::Images);
    }
}

#[cfg(test)]
mod limit_tests {
    use super::*;

    #[test]
    fn supported_raster_uploads_borrow_the_original_pixels() {
        for (width, height) in [(7, 1), (1, 7), (8, 1), (1, 8), (8, 8)] {
            let pixels = vec![255; (width * height * 4) as usize];
            let (w, h, upload) = raster_upload_pixels(width, height, &pixels, 8).unwrap();
            assert_eq!((w, h), (width, height));
            assert!(
                matches!(upload, Cow::Borrowed(_)),
                "copied {width}x{height}"
            );
            assert_eq!(upload.as_ptr(), pixels.as_ptr());
        }
    }

    #[test]
    fn oversized_raster_uploads_own_only_the_resized_pixels() {
        for (width, height) in [(9, 1), (1, 9), (9, 9)] {
            let pixels = vec![255; (width * height * 4) as usize];
            let (w, h, upload) = raster_upload_pixels(width, height, &pixels, 8).unwrap();
            assert_eq!((w, h), (width.min(8), height.min(8)));
            assert!(matches!(upload, Cow::Owned(_)));
            assert_eq!(upload.as_ref(), vec![255; (w * h * 4) as usize]);
        }
        assert!(raster_upload_pixels(0, 1, &[], 8).is_none());
        assert!(raster_upload_pixels(1, 0, &[], 8).is_none());
        assert!(raster_upload_pixels(9, 1, &[0; 4], 8).is_none());
        assert!(raster_upload_pixels(1, 1, &[0; 4], 0).is_none());
    }

    #[test]
    fn svg_raster_extents_fit_both_axes() {
        for ((width, height), expected) in [
            ((8193.0, 1.0), (8192, 1)),
            ((1.0, 8193.0), (1, 8192)),
            ((12000.0, 6000.0), (8192, 4096)),
            ((6000.0, 12000.0), (4096, 8192)),
        ] {
            assert_eq!(svg_extent((width, height), 2.0, None, 8192), Some(expected));
        }
        assert_eq!(svg_extent((20.0, 10.0), 2.0, None, 8192), Some((40, 20)));
        assert_eq!(
            svg_extent((8193.0, 1.0), 2.0, Some((20.0, 20.0)), 8192),
            Some((40, 1))
        );
        assert_eq!(svg_extent((0.0, 10.0), 2.0, None, 8192), None);
        assert_eq!(svg_extent((10.0, 0.0), 2.0, None, 8192), None);
        assert_eq!(svg_extent((20.0, 10.0), 0.0, None, 8192), None);
    }

    #[test]
    fn raster_resize_preserves_aspect_ratio_and_premultiplied_color() {
        for (width, height, expected) in [
            (12, 6, (8, 4)),
            (6, 12, (4, 8)),
            (12, 1, (8, 1)),
            (1, 12, (1, 8)),
        ] {
            let pixels = [128, 0, 0, 128].repeat((width * height) as usize);
            let (w, h, resized) = resized_raster(width, height, &pixels, 8).unwrap();
            assert_eq!((w, h), expected);
            assert_eq!(resized.len(), (w * h * 4) as usize);
            assert!(
                resized
                    .as_chunks::<4>()
                    .0
                    .iter()
                    .all(|pixel| *pixel == [128, 0, 0, 128])
            );
        }
    }

    #[test]
    fn raster_resize_rounds_nonintegral_dimensions_to_the_nearest_texel() {
        for (width, height, limit, expected) in [
            (9, 2, 8, (8, 2)),
            (2, 9, 8, (2, 8)),
            (9, 3, 8, (8, 3)),
            (3, 9, 8, (3, 8)),
            (5, 2, 3, (3, 1)),
            (2, 5, 3, (1, 3)),
            (6, 3, 3, (3, 2)),
            (3, 6, 3, (2, 3)),
        ] {
            let pixels = [255; 4].repeat((width * height) as usize);
            let (w, h, _) = resized_raster(width, height, &pixels, limit).unwrap();
            assert_eq!((w, h), expected);
        }
    }

    #[test]
    fn raster_resize_keeps_distinct_nearly_unscaled_rows_and_columns() {
        for (width, height, expected) in [(9, 2, (8, 2)), (2, 9, (2, 8))] {
            let mut pixels = Vec::new();
            for y in 0..height {
                for x in 0..width {
                    pixels.extend_from_slice(
                        if (height == 2 && y == 0) || (width == 2 && x == 0) {
                            &[255, 0, 0, 255]
                        } else {
                            &[0, 0, 255, 255]
                        },
                    );
                }
            }
            let (w, h, resized) = resized_raster(width, height, &pixels, 8).unwrap();
            assert_eq!((w, h), expected);
            for y in 0..h {
                for x in 0..w {
                    let offset = ((y * w + x) * 4) as usize;
                    let expected = if (h == 2 && y == 0) || (w == 2 && x == 0) {
                        [255, 0, 0, 255]
                    } else {
                        [0, 0, 255, 255]
                    };
                    assert_eq!(&resized[offset..offset + 4], &expected);
                }
            }
        }
    }

    #[test]
    fn raster_shrinking_keeps_thin_lines_between_sample_centers() {
        for (width, height) in [(40, 1), (1, 40)] {
            let mut pixels = Vec::new();
            for y in 0..height {
                for x in 0..width {
                    pixels.extend_from_slice(if (x + y) % 5 == 0 {
                        &[128, 0, 0, 128]
                    } else {
                        &[0, 0, 0, 0]
                    });
                }
            }
            let (_, _, resized) = resized_raster(width, height, &pixels, 8).unwrap();
            // One translucent line in every five texels must still contribute.
            for pixel in resized.as_chunks::<4>().0 {
                assert!((16..=36).contains(&pixel[0]), "lost line: {pixel:?}");
                assert_eq!(*pixel, [pixel[0], 0, 0, pixel[0]]);
            }
        }
    }

    #[test]
    fn raster_resize_filters_both_axes_in_premultiplied_space() {
        let pixels = [
            128, 0, 0, 128, 0, 128, 0, 128, 0, 0, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 64, 0,
            0, 64, 0, 64, 0, 64, 0, 0, 64, 64,
        ];
        let (width, height, resized) = resized_raster(4, 2, &pixels, 2).unwrap();
        assert_eq!((width, height), (2, 1));
        // Horizontal weights are [3, 3, 1]/7 and [1, 3, 3]/7;
        // both rows contribute equally before rounding to bytes.
        assert_eq!(resized, [41, 32, 9, 82, 32, 50, 69, 96]);
    }

    #[test]
    fn an_unresizable_raster_returns_no_pixels() {
        assert!(resized_raster(12, 1, &[0; 4], 8).is_none());
        assert!(resized_raster(12, 1, &[0; 48], 0).is_none());
        assert!(resized_raster(0, 0, &[], 8).is_none());
    }

    #[test]
    fn raster_uploads_below_the_limit_keep_their_texel_dimensions() {
        let Some(gpu) = crate::or_skip(crate::renderer::GpuContext::try_new()) else {
            return;
        };
        let mut renderer = ImageQuadRenderer::new(
            &gpu.device,
            TextureFormat::Rgba8Unorm,
            super::super::clip_records::ClipRecords::new(&gpu.device).layout(),
        );
        let limit = gpu.device.limits().max_texture_dimension_2d;
        for (width, height) in [(limit - 1, 1), (1, limit - 1)] {
            let pixels = vec![255; (width * height * 4) as usize];
            let texture = renderer
                .upload_raster(&gpu.device, &gpu.queue, width, height, &pixels)
                .unwrap();
            let Backing::Own(texture) = &texture.backing else {
                panic!("a near-limit image has its own texture");
            };
            assert_eq!((texture.width(), texture.height()), (width, height));
        }
    }
}