zng_view/
image_cache.rs

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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
use std::{fmt, mem, sync::Arc};

use image::ImageDecoder;
use webrender::api::{ImageDescriptor, ImageDescriptorFlags, ImageFormat};
use winit::{
    event_loop::ActiveEventLoop,
    window::{CustomCursor, Icon},
};
use zng_txt::{formatx, ToTxt, Txt};
use zng_unit::{Px, PxPoint, PxSize};
use zng_view_api::{
    image::{ImageDataFormat, ImageDownscale, ImageId, ImageLoadedData, ImageMaskMode, ImagePpi, ImageRequest},
    ipc::{IpcBytes, IpcBytesReceiver},
    Event,
};

use crate::{AppEvent, AppEventSender};
use rustc_hash::FxHashMap;

pub(crate) const ENCODERS: &[&str] = &[
    "png",
    "jpg",
    "jpeg",
    "webp",
    #[cfg(any(feature = "avif", zng_view_image_has_avif))]
    "avif",
    "gif",
    "ico",
    "bmp",
    "jfif",
    "exr",
    "hdr",
    "pnm",
    "qoi",
    "ff",
    "farbfeld",
];
pub(crate) const DECODERS: &[&str] = &[
    "png",
    "jpg",
    "jpeg",
    "webp",
    #[cfg(any(feature = "avif", zng_view_image_has_avif))]
    "avif",
    "gif",
    "ico",
    "bmp",
    "jfif",
    "exr",
    "pnm",
    "qoi",
    "ff",
    "farbfeld",
    "dds",
];

/// Decode and cache image resources.
pub(crate) struct ImageCache {
    app_sender: AppEventSender,
    images: FxHashMap<ImageId, Image>,
    image_id_gen: ImageId,
}
impl ImageCache {
    pub fn new(app_sender: AppEventSender) -> Self {
        Self {
            app_sender,
            images: FxHashMap::default(),
            image_id_gen: ImageId::first(),
        }
    }

    pub fn add(
        &mut self,
        ImageRequest {
            format,
            data,
            max_decoded_len,
            downscale,
            mask,
        }: ImageRequest<IpcBytes>,
    ) -> ImageId {
        let id = self.image_id_gen.incr();

        let app_sender = self.app_sender.clone();
        rayon::spawn(move || {
            let r = match format {
                ImageDataFormat::Bgra8 { size, ppi } => {
                    let expected_len = size.width.0 as usize * size.height.0 as usize * 4;
                    if data.len() != expected_len {
                        Err(formatx!(
                            "pixels.len() is not width * height * 4, expected {expected_len}, found {}",
                            data.len()
                        ))
                    } else if mask.is_some() {
                        let (pixels, size, _, is_opaque, _) = Self::convert_decoded(
                            image::DynamicImage::ImageLuma8(
                                image::ImageBuffer::from_raw(size.width.0 as _, size.height.0 as _, data.to_vec()).unwrap(),
                            ),
                            mask,
                        );
                        Ok((pixels, size, ppi, is_opaque, true))
                    } else {
                        let is_opaque = data.chunks_exact(4).all(|c| c[3] == 255);
                        Ok((data, size, ppi, is_opaque, false))
                    }
                }
                ImageDataFormat::A8 { size } => {
                    let expected_len = size.width.0 as usize * size.height.0 as usize;
                    if data.len() != expected_len {
                        Err(formatx!(
                            "pixels.len() is not width * height, expected {expected_len}, found {}",
                            data.len()
                        ))
                    } else if mask.is_none() {
                        let (pixels, size, _, is_opaque, _) = Self::convert_decoded(
                            image::DynamicImage::ImageLuma8(
                                image::ImageBuffer::from_raw(size.width.0 as _, size.height.0 as _, data.to_vec()).unwrap(),
                            ),
                            None,
                        );
                        Ok((pixels, size, None, is_opaque, false))
                    } else {
                        let is_opaque = data.iter().all(|&c| c == 255);
                        Ok((data, size, None, is_opaque, true))
                    }
                }
                fmt => match Self::get_format_and_size(&fmt, &data[..]) {
                    Ok((fmt, mut size, orientation)) => {
                        let decoded_len = size.width.0 as u64 * size.height.0 as u64 * 4;
                        if decoded_len > max_decoded_len {
                            Err(formatx!(
                                "image {size:?} needs to allocate {decoded_len} bytes, but max allowed size is {max_decoded_len} bytes",
                            ))
                        } else {
                            if let Some(d) = downscale {
                                size = d.resize_dimensions(size);
                            }
                            let _ = app_sender.send(AppEvent::Notify(Event::ImageMetadataLoaded {
                                image: id,
                                size,
                                ppi: None,
                                is_mask: false,
                            }));
                            match Self::image_decode(&data[..], fmt, downscale, orientation) {
                                Ok(img) => Ok(Self::convert_decoded(img, mask)),
                                Err(e) => Err(e.to_txt()),
                            }
                        }
                    }
                    Err(e) => Err(e),
                },
            };

            match r {
                Ok((pixels, size, ppi, is_opaque, is_mask)) => {
                    let _ = app_sender.send(AppEvent::ImageLoaded(ImageLoadedData {
                        id,
                        pixels,
                        size,
                        ppi,
                        is_opaque,
                        is_mask,
                    }));
                }
                Err(e) => {
                    let _ = app_sender.send(AppEvent::Notify(Event::ImageLoadError { image: id, error: e }));
                }
            }
        });

        id
    }

    pub fn add_pro(
        &mut self,
        ImageRequest {
            format,
            data,
            max_decoded_len,
            downscale,
            mask,
        }: ImageRequest<IpcBytesReceiver>,
    ) -> ImageId {
        let id = self.image_id_gen.incr();
        let app_sender = self.app_sender.clone();
        rayon::spawn(move || {
            // crate `images` does not do progressive decode.
            let mut full = vec![];
            let mut size = None;
            let mut ppi = None;
            let mut is_encoded = true;
            let mut orientation = image::metadata::Orientation::NoTransforms;

            let mut format = match format {
                ImageDataFormat::Bgra8 { size: s, ppi: p } => {
                    is_encoded = false;
                    size = Some(s);
                    ppi = p;
                    None
                }
                ImageDataFormat::A8 { size: s } => {
                    is_encoded = false;
                    size = Some(s);
                    None
                }
                ImageDataFormat::FileExtension(ext) => image::ImageFormat::from_extension(ext.as_str()),
                ImageDataFormat::MimeType(t) => t.strip_prefix("image/").and_then(image::ImageFormat::from_extension),
                ImageDataFormat::Unknown => None,
            };

            let mut pending = true;
            while pending {
                match data.recv() {
                    Ok(d) => {
                        pending = !d.is_empty();

                        full.extend(d);

                        if let Some(fmt) = format {
                            if size.is_none() {
                                if let Ok(mut d) = image::ImageReader::with_format(std::io::Cursor::new(&full), fmt).into_decoder() {
                                    use image::metadata::Orientation::*;

                                    let (mut w, mut h) = d.dimensions();
                                    orientation = d.orientation().unwrap_or(NoTransforms);

                                    if matches!(orientation, Rotate90 | Rotate270 | Rotate90FlipH | Rotate270FlipH) {
                                        mem::swap(&mut w, &mut h)
                                    }

                                    size = Some(PxSize::new(Px(w as i32), Px(h as i32)));
                                }

                                if let Some(s) = size {
                                    let decoded_len = s.width.0 as u64 * s.height.0 as u64 * 4;
                                    if decoded_len > max_decoded_len {
                                        let error = formatx!(
                                            "image {size:?} needs to allocate {decoded_len} bytes, but max allowed size is {max_decoded_len} bytes",
                                        );
                                        let _ = app_sender.send(AppEvent::Notify(Event::ImageLoadError { image: id, error }));
                                        return;
                                    }
                                }
                            }
                        } else if is_encoded {
                            format = image::guess_format(&full).ok();
                        }
                    }
                    Err(_) => {
                        // cancelled?
                        return;
                    }
                }
            }

            if let Some(fmt) = format {
                match Self::image_decode(&full[..], fmt, downscale, orientation) {
                    Ok(img) => {
                        let (pixels, size, ppi, is_opaque, is_mask) = Self::convert_decoded(img, mask);
                        let _ = app_sender.send(AppEvent::ImageLoaded(ImageLoadedData {
                            id,
                            pixels,
                            size,
                            ppi,
                            is_opaque,
                            is_mask,
                        }));
                    }
                    Err(e) => {
                        let _ = app_sender.send(AppEvent::Notify(Event::ImageLoadError {
                            image: id,
                            error: e.to_txt(),
                        }));
                    }
                }
            } else if !is_encoded {
                let pixels = IpcBytes::from_vec(full);
                let is_opaque = pixels.chunks_exact(4).all(|c| c[3] == 255);
                let _ = app_sender.send(AppEvent::ImageLoaded(ImageLoadedData {
                    id,
                    pixels,
                    size: size.unwrap(),
                    ppi,
                    is_opaque,
                    is_mask: false,
                }));
            } else {
                let _ = app_sender.send(AppEvent::Notify(Event::ImageLoadError {
                    image: id,
                    error: Txt::from_static("unknown format"),
                }));
            }
        });
        id
    }

    pub fn forget(&mut self, id: ImageId) {
        self.images.remove(&id);
    }

    pub fn get(&self, id: ImageId) -> Option<&Image> {
        self.images.get(&id)
    }

    /// Called after receive and decode completes correctly.
    pub(crate) fn loaded(&mut self, data: ImageLoadedData) {
        let mut flags = ImageDescriptorFlags::empty(); //ImageDescriptorFlags::ALLOW_MIPMAPS;
        if data.is_opaque {
            flags |= ImageDescriptorFlags::IS_OPAQUE
        }

        self.images.insert(
            data.id,
            Image(Arc::new(ImageData::RawData {
                size: data.size,
                pixels: data.pixels.clone(),
                descriptor: ImageDescriptor::new(
                    data.size.width.0,
                    data.size.height.0,
                    if data.is_mask { ImageFormat::R8 } else { ImageFormat::BGRA8 },
                    flags,
                ),
                ppi: data.ppi,
            })),
        );

        let _ = self.app_sender.send(AppEvent::Notify(Event::ImageLoaded(data)));
    }

    fn get_format_and_size(fmt: &ImageDataFormat, data: &[u8]) -> Result<(image::ImageFormat, PxSize, image::metadata::Orientation), Txt> {
        let fmt = match fmt {
            ImageDataFormat::FileExtension(ext) => image::ImageFormat::from_extension(ext.as_str()),
            ImageDataFormat::MimeType(t) => t.strip_prefix("image/").and_then(image::ImageFormat::from_extension),
            ImageDataFormat::Unknown => None,
            ImageDataFormat::Bgra8 { .. } => unreachable!(),
            ImageDataFormat::A8 { .. } => unreachable!(),
        };

        let reader = match fmt {
            Some(fmt) => image::ImageReader::with_format(std::io::Cursor::new(data), fmt),
            None => image::ImageReader::new(std::io::Cursor::new(data))
                .with_guessed_format()
                .map_err(|e| e.to_txt())?,
        };

        match reader.format() {
            Some(fmt) => {
                use image::metadata::Orientation::*;

                let mut decoder = reader.into_decoder().map_err(|e| e.to_string())?;
                let (mut w, mut h) = decoder.dimensions();
                let orientation = decoder.orientation().unwrap_or(NoTransforms);

                if matches!(orientation, Rotate90 | Rotate270 | Rotate90FlipH | Rotate270FlipH) {
                    mem::swap(&mut w, &mut h)
                }

                Ok((fmt, PxSize::new(Px(w as i32), Px(h as i32)), orientation))
            }
            None => Err(Txt::from_static("unknown format")),
        }
    }

    fn image_decode(
        buf: &[u8],
        format: image::ImageFormat,
        downscale: Option<ImageDownscale>,
        orientation: image::metadata::Orientation,
    ) -> image::ImageResult<image::DynamicImage> {
        let buf = std::io::Cursor::new(buf);

        let mut reader = image::ImageReader::new(buf);
        reader.set_format(format);
        reader.no_limits();
        let mut image = reader.decode()?;

        image.apply_orientation(orientation);

        if let Some(s) = downscale {
            let (img_w, img_h) = (image.width(), image.height());
            match s {
                ImageDownscale::Fit(s) => {
                    let w = img_w.min(s.width.0 as u32);
                    let h = img_h.min(s.height.0 as u32);
                    if w != img_w || h != img_h {
                        image = image.resize(w, h, image::imageops::FilterType::Triangle);
                    }
                }
                ImageDownscale::Fill(s) => {
                    let w = img_w.min(s.width.0 as u32);
                    let h = img_h.min(s.height.0 as u32);
                    if w != img_w && h != img_h {
                        image = image.resize_to_fill(w, h, image::imageops::FilterType::Triangle);
                    }
                }
            }
        }

        Ok(image)
    }

    fn convert_decoded(image: image::DynamicImage, mask: Option<ImageMaskMode>) -> RawLoadedImg {
        use image::DynamicImage::*;

        let mut is_opaque = true;

        let (size, pixels) = match image {
            ImageLuma8(img) => (
                img.dimensions(),
                if mask.is_some() {
                    let r = img.into_raw();
                    is_opaque = !r.iter().any(|&a| a < 255);
                    r
                } else {
                    img.into_raw().into_iter().flat_map(|l| [l, l, l, 255]).collect()
                },
            ),
            ImageLumaA8(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::A => img
                            .into_raw()
                            .chunks(2)
                            .map(|la| {
                                if la[1] < 255 {
                                    is_opaque = false;
                                }
                                la[1]
                            })
                            .collect(),
                        ImageMaskMode::B | ImageMaskMode::G | ImageMaskMode::R | ImageMaskMode::Luminance => img
                            .into_raw()
                            .chunks(2)
                            .map(|la| {
                                if la[0] < 255 {
                                    is_opaque = false;
                                }
                                la[0]
                            })
                            .collect(),
                    }
                } else {
                    img.into_raw()
                        .chunks(2)
                        .flat_map(|la| {
                            if la[1] < 255 {
                                is_opaque = false;
                                let l = la[0] as f32 * la[1] as f32 / 255.0;
                                let l = l as u8;
                                [l, l, l, la[1]]
                            } else {
                                let l = la[0];
                                [l, l, l, la[1]]
                            }
                        })
                        .collect()
                },
            ),
            ImageRgb8(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance | ImageMaskMode::A => img
                            .into_raw()
                            .chunks(3)
                            .map(|c| {
                                let c = luminance(c);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(3)
                                .map(|c| {
                                    let c = c[channel];
                                    if c < 255 {
                                        is_opaque = false;
                                    }
                                    c
                                })
                                .collect()
                        }
                    }
                } else {
                    img.into_raw().chunks(3).flat_map(|c| [c[2], c[1], c[0], 255]).collect()
                },
            ),
            ImageRgba8(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance => img
                            .into_raw()
                            .chunks(4)
                            .map(|c| {
                                let c = luminance(&c[..3]);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::A => 3,
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(4)
                                .map(|c| {
                                    let c = c[channel];
                                    if c < 255 {
                                        is_opaque = false;
                                    }
                                    c
                                })
                                .collect()
                        }
                    }
                } else {
                    let mut buf = img.into_raw();
                    buf.chunks_mut(4).for_each(|c| {
                        if c[3] < 255 {
                            is_opaque = false;
                            let a = c[3] as f32 / 255.0;
                            c[0..3].iter_mut().for_each(|c| *c = (*c as f32 * a) as u8);
                        }
                        c.swap(0, 2);
                    });
                    buf
                },
            ),
            ImageLuma16(img) => (
                img.dimensions(),
                if mask.is_some() {
                    img.into_raw()
                        .into_iter()
                        .map(|l| {
                            let l = (l as f32 / u16::MAX as f32 * 255.0) as u8;
                            if l < 255 {
                                is_opaque = false;
                            }
                            l
                        })
                        .collect()
                } else {
                    img.into_raw()
                        .into_iter()
                        .flat_map(|l| {
                            let l = (l as f32 / u16::MAX as f32 * 255.0) as u8;
                            [l, l, l, 255]
                        })
                        .collect()
                },
            ),
            ImageLumaA16(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::A => img
                            .into_raw()
                            .chunks(2)
                            .map(|la| {
                                if la[1] < u16::MAX {
                                    is_opaque = false;
                                }
                                let max = u16::MAX as f32;
                                let l = la[1] as f32 / max * 255.0;
                                l as u8
                            })
                            .collect(),
                        ImageMaskMode::B | ImageMaskMode::G | ImageMaskMode::R | ImageMaskMode::Luminance => img
                            .into_raw()
                            .chunks(2)
                            .map(|la| {
                                if la[0] < u16::MAX {
                                    is_opaque = false;
                                }
                                let max = u16::MAX as f32;
                                let l = la[0] as f32 / max * 255.0;
                                l as u8
                            })
                            .collect(),
                    }
                } else {
                    img.into_raw()
                        .chunks(2)
                        .flat_map(|la| {
                            let max = u16::MAX as f32;
                            let l = la[0] as f32 / max;
                            let a = la[1] as f32 / max * 255.0;

                            if la[1] < u16::MAX {
                                is_opaque = false;
                                let l = (l * a) as u8;
                                [l, l, l, a as u8]
                            } else {
                                let l = (l * 255.0) as u8;
                                [l, l, l, a as u8]
                            }
                        })
                        .collect()
                },
            ),
            ImageRgb16(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance | ImageMaskMode::A => img
                            .into_raw()
                            .chunks(3)
                            .map(|c| {
                                let c = luminance_16(c);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(3)
                                .map(|c| {
                                    let c = c[channel];
                                    if c < u16::MAX {
                                        is_opaque = false;
                                    }

                                    (c as f32 / u16::MAX as f32 * 255.0) as u8
                                })
                                .collect()
                        }
                    }
                } else {
                    img.into_raw()
                        .chunks(3)
                        .flat_map(|c| {
                            let to_u8 = 255.0 / u16::MAX as f32;
                            [
                                (c[2] as f32 * to_u8) as u8,
                                (c[1] as f32 * to_u8) as u8,
                                (c[0] as f32 * to_u8) as u8,
                                255,
                            ]
                        })
                        .collect()
                },
            ),
            ImageRgba16(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance => img
                            .into_raw()
                            .chunks(4)
                            .map(|c| {
                                let c = luminance_16(&c[..3]);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::A => 3,
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(4)
                                .map(|c| {
                                    let c = c[channel];
                                    if c < 255 {
                                        is_opaque = false;
                                    }
                                    (c as f32 / u16::MAX as f32 * 255.0) as u8
                                })
                                .collect()
                        }
                    }
                } else {
                    img.into_raw()
                        .chunks(4)
                        .flat_map(|c| {
                            if c[3] < u16::MAX {
                                is_opaque = false;
                                let max = u16::MAX as f32;
                                let a = c[3] as f32 / max * 255.0;
                                [
                                    (c[2] as f32 / max * a) as u8,
                                    (c[1] as f32 / max * a) as u8,
                                    (c[0] as f32 / max * a) as u8,
                                    a as u8,
                                ]
                            } else {
                                let to_u8 = 255.0 / u16::MAX as f32;
                                [
                                    (c[2] as f32 * to_u8) as u8,
                                    (c[1] as f32 * to_u8) as u8,
                                    (c[0] as f32 * to_u8) as u8,
                                    255,
                                ]
                            }
                        })
                        .collect()
                },
            ),
            ImageRgb32F(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance | ImageMaskMode::A => img
                            .into_raw()
                            .chunks(3)
                            .map(|c| {
                                let c = luminance_f32(c);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(3)
                                .map(|c| {
                                    let c = (c[channel] * 255.0) as u8;
                                    if c < 255 {
                                        is_opaque = false;
                                    }
                                    c
                                })
                                .collect()
                        }
                    }
                } else {
                    img.into_raw()
                        .chunks(3)
                        .flat_map(|c| [(c[2] * 255.0) as u8, (c[1] * 255.0) as u8, (c[0] * 255.0) as u8, 255])
                        .collect()
                },
            ),
            ImageRgba32F(img) => (
                img.dimensions(),
                if let Some(mask) = mask {
                    match mask {
                        ImageMaskMode::Luminance => img
                            .into_raw()
                            .chunks(4)
                            .map(|c| {
                                let c = luminance_f32(&c[..3]);
                                if c < 255 {
                                    is_opaque = false;
                                }
                                c
                            })
                            .collect(),
                        mask => {
                            let channel = match mask {
                                ImageMaskMode::A => 3,
                                ImageMaskMode::B => 2,
                                ImageMaskMode::G => 1,
                                ImageMaskMode::R => 0,
                                _ => unreachable!(),
                            };
                            img.into_raw()
                                .chunks(4)
                                .map(|c| {
                                    let c = (c[channel] * 255.0) as u8;
                                    if c < 255 {
                                        is_opaque = false;
                                    }
                                    c
                                })
                                .collect()
                        }
                    }
                } else {
                    img.into_raw()
                        .chunks(4)
                        .flat_map(|c| {
                            if c[3] < 1.0 {
                                is_opaque = false;
                                let a = c[3] * 255.0;
                                [(c[2] * a) as u8, (c[1] * a) as u8, (c[0] * a) as u8, a as u8]
                            } else {
                                [(c[2] * 255.0) as u8, (c[1] * 255.0) as u8, (c[0] * 255.0) as u8, 255]
                            }
                        })
                        .collect()
                },
            ),
            _ => unreachable!(),
        };

        (
            IpcBytes::from_vec(pixels),
            PxSize::new(Px(size.0 as i32), Px(size.1 as i32)),
            None,
            is_opaque,
            mask.is_some(), // is_mask
        )
    }

    pub fn encode(&self, id: ImageId, format: Txt) {
        if !ENCODERS.contains(&format.as_str()) {
            let error = formatx!("cannot encode `{id:?}` to `{format}`, unknown format");
            let _ = self
                .app_sender
                .send(AppEvent::Notify(Event::ImageEncodeError { image: id, format, error }));
            return;
        }

        if let Some(img) = self.get(id) {
            let fmt = image::ImageFormat::from_extension(format.as_str()).unwrap();
            debug_assert!(fmt.can_write());

            let img = img.clone();
            let sender = self.app_sender.clone();
            rayon::spawn(move || {
                let mut data = vec![];
                match img.encode(fmt, &mut data) {
                    Ok(_) => {
                        let _ = sender.send(AppEvent::Notify(Event::ImageEncoded {
                            image: id,
                            format,
                            data: IpcBytes::from_vec(data),
                        }));
                    }
                    Err(e) => {
                        let error = formatx!("failed to encode `{id:?}` to `{format}`, {e}");
                        let _ = sender.send(AppEvent::Notify(Event::ImageEncodeError { image: id, format, error }));
                    }
                }
            })
        } else {
            let error = formatx!("cannot encode `{id:?}` to `{format}`, image not found");
            let _ = self
                .app_sender
                .send(AppEvent::Notify(Event::ImageEncodeError { image: id, format, error }));
        }
    }

    pub(crate) fn on_low_memory(&mut self) {
        // app-process controls this cache
    }

    pub(crate) fn clear(&mut self) {
        self.images.clear();
    }
}

/// (pixels, size, ppi, is_opaque, is_mask)
type RawLoadedImg = (IpcBytes, PxSize, Option<ImagePpi>, bool, bool);
pub(crate) enum ImageData {
    RawData {
        size: PxSize,
        pixels: IpcBytes,
        descriptor: ImageDescriptor,
        ppi: Option<ImagePpi>,
    },
    NativeTexture {
        uv: webrender::api::units::TexelRect,
        texture: gleam::gl::GLuint,
    },
}
impl ImageData {
    pub fn is_opaque(&self) -> bool {
        match self {
            ImageData::RawData { descriptor, .. } => descriptor.flags.contains(ImageDescriptorFlags::IS_OPAQUE),
            ImageData::NativeTexture { .. } => false,
        }
    }

    pub fn is_mask(&self) -> bool {
        match self {
            ImageData::RawData { descriptor, .. } => descriptor.format == ImageFormat::R8,
            ImageData::NativeTexture { .. } => false,
        }
    }
}

#[derive(Clone)]
pub(crate) struct Image(Arc<ImageData>);
impl fmt::Debug for Image {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &*self.0 {
            ImageData::RawData {
                size,
                pixels,
                descriptor,
                ppi,
            } => f
                .debug_struct("Image")
                .field("size", size)
                .field("descriptor", descriptor)
                .field("ppi", ppi)
                .field("pixels", &format_args!("<{} shared bytes>", pixels.len()))
                .finish(),
            ImageData::NativeTexture { .. } => unreachable!(),
        }
    }
}
impl Image {
    pub fn descriptor(&self) -> ImageDescriptor {
        match &*self.0 {
            ImageData::RawData { descriptor, .. } => *descriptor,
            ImageData::NativeTexture { .. } => unreachable!(),
        }
    }

    /// Generate a window icon from the image.
    pub fn icon(&self) -> Option<Icon> {
        let (size, pixels) = match &*self.0 {
            ImageData::RawData { size, pixels, .. } => (size, pixels),
            ImageData::NativeTexture { .. } => unreachable!(),
        };

        let width = size.width.0 as u32;
        let height = size.height.0 as u32;
        if width == 0 || height == 0 || self.0.is_mask() {
            None
        } else {
            let r = if width > 255 || height > 255 {
                // resize to max 255
                let mut buf = pixels[..].to_vec();
                // BGRA to RGBA
                buf.chunks_exact_mut(4).for_each(|c| c.swap(0, 2));
                let img = image::ImageBuffer::from_raw(width, height, buf).unwrap();
                let img = image::DynamicImage::ImageRgba8(img);
                let img = img.resize(255, 255, image::imageops::FilterType::Lanczos3);

                use image::GenericImageView;
                let (width, height) = img.dimensions();
                let buf = img.into_rgba8().into_raw();
                winit::window::Icon::from_rgba(buf, width, height)
            } else {
                let mut buf = pixels[..].to_vec();
                // BGRA to RGBA
                buf.chunks_exact_mut(4).for_each(|c| c.swap(0, 2));
                winit::window::Icon::from_rgba(buf, width, height)
            };
            match r {
                Ok(i) => Some(i),
                Err(e) => {
                    tracing::error!("failed to convert image to custom icon, {e}");
                    None
                }
            }
        }
    }

    /// Generate a cursor from the image.
    pub fn cursor(&self, hotspot: PxPoint, event_loop: &ActiveEventLoop) -> Option<CustomCursor> {
        let (size, pixels) = match &*self.0 {
            ImageData::RawData { size, pixels, .. } => (size, pixels),
            ImageData::NativeTexture { .. } => unreachable!(),
        };

        let width: u16 = size.width.0.try_into().ok()?;
        let height: u16 = size.height.0.try_into().ok()?;
        let hotspot_x: u16 = hotspot.x.0.try_into().ok()?;
        let hotspot_y: u16 = hotspot.y.0.try_into().ok()?;

        if width == 0 || height == 0 || hotspot_x > width || hotspot_y > height || self.0.is_mask() {
            None
        } else {
            let mut buf = pixels[..].to_vec();
            // BGRA to RGBA
            buf.chunks_exact_mut(4).for_each(|c| c.swap(0, 2));
            match CustomCursor::from_rgba(buf, width, height, hotspot_x, hotspot_y) {
                Ok(c) => Some(event_loop.create_custom_cursor(c)),
                Err(e) => {
                    tracing::error!("failed to convert image to custom cursor, {e}");
                    None
                }
            }
        }
    }

    pub fn encode(&self, format: image::ImageFormat, buffer: &mut Vec<u8>) -> image::ImageResult<()> {
        let (size, pixels, ppi) = match &*self.0 {
            ImageData::RawData { size, pixels, ppi, .. } => (size, pixels, ppi),
            ImageData::NativeTexture { .. } => unreachable!(),
        };

        if size.width <= 0 || size.height <= 0 {
            return Err(image::ImageError::IoError(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "cannot encode zero sized image",
            )));
        }

        use image::*;

        if self.0.is_mask() {
            let width = size.width.0 as u32;
            let height = size.height.0 as u32;
            let is_opaque = self.0.is_opaque();
            let r8 = pixels[..].to_vec();

            let mut img = image::DynamicImage::ImageLuma8(image::ImageBuffer::from_raw(width, height, r8).unwrap());
            if is_opaque {
                img = image::DynamicImage::ImageRgb8(img.to_rgb8());
            }
            img.write_to(&mut std::io::Cursor::new(buffer), format)?;

            return Ok(());
        }

        // invert rows, `image` only supports top-to-bottom buffers.
        let mut buf = pixels[..].to_vec();
        // BGRA to RGBA
        buf.chunks_exact_mut(4).for_each(|c| c.swap(0, 2));
        let rgba = buf;

        let width = size.width.0 as u32;
        let height = size.height.0 as u32;
        let is_opaque = self.0.is_opaque();

        match format {
            ImageFormat::Jpeg => {
                let mut jpg = codecs::jpeg::JpegEncoder::new(buffer);
                if let Some(ppi) = ppi {
                    jpg.set_pixel_density(codecs::jpeg::PixelDensity {
                        density: (ppi.x as u16, ppi.y as u16),
                        unit: codecs::jpeg::PixelDensityUnit::Inches,
                    });
                }
                jpg.encode(&rgba, width, height, ColorType::Rgba8.into())?;
            }
            ImageFormat::Png => {
                let mut img = image::DynamicImage::ImageRgba8(image::ImageBuffer::from_raw(width, height, rgba).unwrap());
                if is_opaque {
                    img = image::DynamicImage::ImageRgb8(img.to_rgb8());
                }
                if let Some(ppi) = ppi {
                    let mut png_bytes = vec![];

                    img.write_to(&mut std::io::Cursor::new(&mut png_bytes), ImageFormat::Png)?;

                    let mut png = img_parts::png::Png::from_bytes(png_bytes.into()).unwrap();

                    let chunk_kind = *b"pHYs";
                    debug_assert!(png.chunk_by_type(chunk_kind).is_none());

                    use byteorder::*;
                    let mut chunk = Vec::with_capacity(4 * 2 + 1);

                    // ppi / inch_to_metric
                    let ppm_x = (ppi.x / 0.0254) as u32;
                    let ppm_y = (ppi.y / 0.0254) as u32;

                    chunk.write_u32::<BigEndian>(ppm_x).unwrap();
                    chunk.write_u32::<BigEndian>(ppm_y).unwrap();
                    chunk.write_u8(1).unwrap(); // metric

                    let chunk = img_parts::png::PngChunk::new(chunk_kind, chunk.into());
                    png.chunks_mut().insert(1, chunk);

                    png.encoder().write_to(buffer)?;
                } else {
                    img.write_to(&mut std::io::Cursor::new(buffer), ImageFormat::Png)?;
                }
            }
            _ => {
                // other formats that we don't with custom PPI meta.

                let mut img = image::DynamicImage::ImageRgba8(image::ImageBuffer::from_raw(width, height, rgba).unwrap());
                if is_opaque {
                    img = image::DynamicImage::ImageRgb8(img.to_rgb8());
                }
                img.write_to(&mut std::io::Cursor::new(buffer), format)?;
            }
        }

        Ok(())
    }

    #[allow(unused)]
    pub fn size(&self) -> PxSize {
        match &*self.0 {
            ImageData::RawData { size, .. } => *size,
            ImageData::NativeTexture { .. } => unreachable!(),
        }
    }

    #[allow(unused)]
    pub fn pixels(&self) -> &IpcBytes {
        match &*self.0 {
            ImageData::RawData { pixels, .. } => pixels,
            ImageData::NativeTexture { .. } => unreachable!(),
        }
    }
}

// Image data is provided to webrender directly from the BGRA8 shared memory.
// The `ExternalImageId` is the Arc pointer to ImageData.
mod external {
    use std::{collections::hash_map::Entry, sync::Arc};

    use rustc_hash::FxHashMap;
    use webrender::{
        api::{
            units::{ImageDirtyRect, TexelRect},
            DocumentId, ExternalImage, ExternalImageData, ExternalImageHandler, ExternalImageId, ExternalImageSource, ExternalImageType,
            ImageKey,
        },
        RenderApi,
    };
    use zng_view_api::image::ImageTextureId;

    use super::{Image, ImageData};

    /// Implements [`ExternalImageHandler`].
    ///
    /// # Safety
    ///
    /// This is only safe if use with [`ImageUseMap`].
    pub(crate) struct WrImageCache {
        locked: Vec<Arc<ImageData>>,
    }
    impl WrImageCache {
        pub fn new_boxed() -> Box<dyn ExternalImageHandler> {
            Box::new(WrImageCache { locked: vec![] })
        }
    }
    impl ExternalImageHandler for WrImageCache {
        fn lock(&mut self, key: ExternalImageId, _channel_index: u8) -> ExternalImage {
            // SAFETY: this is safe because the Arc is kept alive in `ImageUseMap`.
            let img = unsafe {
                let ptr = key.0 as *const ImageData;
                Arc::increment_strong_count(ptr);
                Arc::<ImageData>::from_raw(ptr)
            };

            self.locked.push(img); // keep alive in case the image is removed mid-use

            match &**self.locked.last().unwrap() {
                ImageData::RawData { pixels, .. } => {
                    ExternalImage {
                        uv: TexelRect::invalid(), // `RawData` does not use `uv`.
                        source: ExternalImageSource::RawData(&pixels[..]),
                    }
                }
                ImageData::NativeTexture { uv, texture: id } => ExternalImage {
                    uv: *uv,
                    source: ExternalImageSource::NativeTexture(*id),
                },
            }
        }

        fn unlock(&mut self, key: ExternalImageId, _channel_index: u8) {
            if let Some(i) = self.locked.iter().position(|d| ExternalImageId(Arc::as_ptr(d) as _) == key) {
                self.locked.swap_remove(i);
            } else {
                debug_assert!(false);
            }
        }
    }

    impl Image {
        fn external_id(&self) -> ExternalImageId {
            ExternalImageId(Arc::as_ptr(&self.0) as u64)
        }

        fn data(&self) -> webrender::api::ImageData {
            webrender::api::ImageData::External(ExternalImageData {
                id: self.external_id(),
                channel_index: 0,
                image_type: ExternalImageType::Buffer,
                normalized_uvs: false,
            })
        }
    }

    /// Track and manage images used in a renderer.
    ///
    /// The renderer must use [`WrImageCache`] as the external image source.
    #[derive(Default)]
    pub(crate) struct ImageUseMap {
        id_tex: FxHashMap<ExternalImageId, (ImageTextureId, Image)>,
        tex_id: FxHashMap<ImageTextureId, ExternalImageId>,
    }
    impl ImageUseMap {
        pub fn new_use(&mut self, image: &Image, document_id: DocumentId, api: &mut RenderApi) -> ImageTextureId {
            let id = image.external_id();
            match self.id_tex.entry(id) {
                Entry::Occupied(e) => e.get().0,
                Entry::Vacant(e) => {
                    let key = api.generate_image_key();
                    let tex_id = ImageTextureId::from_raw(key.1);
                    e.insert((tex_id, image.clone())); // keep the image Arc alive, we expect this in `WrImageCache`.
                    self.tex_id.insert(tex_id, id);

                    let mut txn = webrender::Transaction::new();
                    txn.add_image(key, image.descriptor(), image.data(), None);
                    api.send_transaction(document_id, txn);

                    tex_id
                }
            }
        }

        /// Returns if needs to update.
        pub fn update_use(&mut self, texture_id: ImageTextureId, image: &Image, document_id: DocumentId, api: &mut RenderApi) {
            if let Entry::Occupied(mut e) = self.tex_id.entry(texture_id) {
                let id = image.external_id();
                if *e.get() != id {
                    let prev_id = e.insert(id);
                    self.id_tex.remove(&prev_id).unwrap();
                    self.id_tex.insert(id, (texture_id, image.clone()));

                    let mut txn = webrender::Transaction::new();
                    txn.update_image(
                        ImageKey(api.get_namespace_id(), texture_id.get()),
                        image.descriptor(),
                        image.data(),
                        &ImageDirtyRect::All,
                    );
                    api.send_transaction(document_id, txn);
                }
            }
        }

        pub fn delete(&mut self, texture_id: ImageTextureId, document_id: DocumentId, api: &mut RenderApi) {
            if let Some(id) = self.tex_id.remove(&texture_id) {
                let _img = self.id_tex.remove(&id); // remove but keep alive until the transaction is done.
                let mut txn = webrender::Transaction::new();
                txn.delete_image(ImageKey(api.get_namespace_id(), texture_id.get()));
                api.send_transaction(document_id, txn);
            }
        }
    }
}
pub(crate) use external::{ImageUseMap, WrImageCache};

mod capture {
    use std::sync::Arc;

    use webrender::api::{ImageDescriptor, ImageDescriptorFlags, ImageFormat};
    use zng_txt::formatx;
    use zng_unit::{Factor, PxRect};
    use zng_view_api::{
        image::{ImageDataFormat, ImageId, ImageLoadedData, ImageMaskMode, ImagePpi, ImageRequest},
        ipc::IpcBytes,
        window::{FrameId, WindowId},
        Event,
    };

    use crate::{
        image_cache::{Image, ImageData},
        AppEvent,
    };

    use super::ImageCache;

    impl ImageCache {
        /// Create frame_image for an `Api::frame_image` request.
        pub fn frame_image(
            &mut self,
            gl: &dyn gleam::gl::Gl,
            rect: PxRect,
            window_id: WindowId,
            frame_id: FrameId,
            scale_factor: Factor,
            mask: Option<ImageMaskMode>,
        ) -> ImageId {
            if frame_id == FrameId::INVALID {
                let id = self.image_id_gen.incr();
                let _ = self.app_sender.send(AppEvent::Notify(Event::ImageLoadError {
                    image: id,
                    error: formatx!("no frame rendered in window `{window_id:?}`"),
                }));
                let _ = self.app_sender.send(AppEvent::Notify(Event::FrameImageReady {
                    window: window_id,
                    frame: frame_id,
                    image: id,
                    selection: rect,
                }));
                return id;
            }

            let data = self.frame_image_data(gl, rect, scale_factor, mask);

            let id = data.id;

            let _ = self.app_sender.send(AppEvent::ImageLoaded(data));
            let _ = self.app_sender.send(AppEvent::Notify(Event::FrameImageReady {
                window: window_id,
                frame: frame_id,
                image: id,
                selection: rect,
            }));

            id
        }

        /// Create frame_image for a capture request in the FrameRequest.
        pub fn frame_image_data(
            &mut self,
            gl: &dyn gleam::gl::Gl,
            rect: PxRect,
            scale_factor: Factor,
            mask: Option<ImageMaskMode>,
        ) -> ImageLoadedData {
            let data = self.frame_image_data_impl(gl, rect, scale_factor, mask);

            let flags = if data.is_opaque {
                ImageDescriptorFlags::IS_OPAQUE
            } else {
                ImageDescriptorFlags::empty()
            };

            self.images.insert(
                data.id,
                Image(Arc::new(ImageData::RawData {
                    size: data.size,
                    pixels: data.pixels.clone(),
                    descriptor: ImageDescriptor::new(
                        data.size.width.0,
                        data.size.height.0,
                        if data.is_mask { ImageFormat::R8 } else { ImageFormat::BGRA8 },
                        flags,
                    ),
                    ppi: data.ppi,
                })),
            );

            data
        }

        fn frame_image_data_impl(
            &mut self,
            gl: &dyn gleam::gl::Gl,
            rect: PxRect,
            scale_factor: Factor,
            mask: Option<ImageMaskMode>,
        ) -> ImageLoadedData {
            let format = match gl.get_type() {
                gleam::gl::GlType::Gl => gleam::gl::BGRA,
                gleam::gl::GlType::Gles => gleam::gl::RGBA,
            };
            let pixels_flipped = gl.read_pixels(
                rect.origin.x.0,
                rect.origin.y.0,
                rect.size.width.0,
                rect.size.height.0,
                format,
                gleam::gl::UNSIGNED_BYTE,
            );
            let mut buf = vec![0u8; pixels_flipped.len()];
            assert_eq!(rect.size.width.0 as usize * rect.size.height.0 as usize * 4, buf.len());
            let stride = 4 * rect.size.width.0 as usize;
            for (px, buf) in pixels_flipped.chunks_exact(stride).rev().zip(buf.chunks_exact_mut(stride)) {
                buf.copy_from_slice(px);
            }

            if let Some(mask) = mask {
                if format == gleam::gl::BGRA {
                    for bgra in buf.chunks_exact_mut(4) {
                        bgra.swap(0, 3);
                    }
                }
                let (pixels, size, ppi, is_opaque, is_mask) = Self::convert_decoded(
                    image::DynamicImage::ImageRgba8(
                        image::ImageBuffer::from_raw(rect.size.width.0 as u32, rect.size.height.0 as u32, buf).unwrap(),
                    ),
                    Some(mask),
                );

                let id = self.add(ImageRequest {
                    format: ImageDataFormat::A8 { size },
                    data: pixels.clone(),
                    max_decoded_len: u64::MAX,
                    downscale: None,
                    mask: Some(mask),
                });

                ImageLoadedData {
                    id,
                    size,
                    ppi,
                    is_opaque,
                    is_mask,
                    pixels,
                }
            } else {
                if format == gleam::gl::RGBA {
                    for rgba in buf.chunks_exact_mut(4) {
                        rgba.swap(0, 3);
                    }
                }

                let is_opaque = buf.chunks_exact(4).all(|bgra| bgra[3] == 255);

                let data = IpcBytes::from_vec(buf);
                let ppi = 96.0 * scale_factor.0;
                let ppi = Some(ImagePpi::splat(ppi));
                let size = rect.size;

                let id = self.add(ImageRequest {
                    format: ImageDataFormat::Bgra8 { size, ppi },
                    data: data.clone(),
                    max_decoded_len: u64::MAX,
                    downscale: None,
                    mask,
                });

                ImageLoadedData {
                    id,
                    size,
                    ppi,
                    is_opaque,
                    pixels: data,
                    is_mask: false,
                }
            }
        }
    }
}

fn luminance(rgb: &[u8]) -> u8 {
    let r = rgb[0] as f32 / 255.0;
    let g = rgb[1] as f32 / 255.0;
    let b = rgb[2] as f32 / 255.0;

    let l = r * 0.2126 + g * 0.7152 + b * 0.0722;
    (l * 255.0) as u8
}

fn luminance_16(rgb: &[u16]) -> u8 {
    let max = u16::MAX as f32;
    let r = rgb[0] as f32 / max;
    let g = rgb[1] as f32 / max;
    let b = rgb[2] as f32 / max;

    let l = r * 0.2126 + g * 0.7152 + b * 0.0722;
    (l * 255.0) as u8
}

fn luminance_f32(rgb: &[f32]) -> u8 {
    let r = rgb[0];
    let g = rgb[1];
    let b = rgb[2];

    let l = r * 0.2126 + g * 0.7152 + b * 0.0722;
    (l * 255.0) as u8
}