rust_widgets 1.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
//! Image format enumeration and pixel-data containers.
//!
//! # Format support matrix (truthful)
//!
//! The [`ImageFormat`] enum is a format identifier list; it does **not** imply
//! that this crate ships a codec for every variant. Actual codec status:
//!
//! - **Decoded & encoded**: PNG, JPEG, BMP, QOI, Farbfeld, PNM (P5/P6).
//! - **Encoded only** (decoding returns `Err`): GIF, TIFF, SVG/SVGZ.
//! - **Neither** (detected by magic bytes; `decode` returns
//!   `Err("... not implemented ...")`): WebP, AVIF, ICO.
//!
//! Decoders never return fabricated placeholder pixels.

/// Image format identifier.
///
/// See the module docs for which formats are actually decodable/encodable
/// in this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ImageFormat {
    /// Unknown/unrecognized format.
    #[default]
    Unknown,
    /// Raw RGBA pixel data (8 bits per channel).
    Rgba8,
    /// Raw RGB pixel data (8 bits per channel).
    Rgb8,
    /// Portable Network Graphics.
    Png,
    /// Joint Photographic Experts Group.
    Jpeg,
    /// Bitmap.
    Bmp,
    /// Graphics Interchange Format (static and animated).
    Gif,
    /// WebP (both lossy and lossless).
    WebP,
    /// Tagged Image File Format.
    Tiff,
    /// AV1 Image File Format.
    Avif,
    /// ICO (Windows icon).
    Ico,
    /// Netpbm (PBM/PGM/PPM/PAM).
    Pnm,
    /// Quite OK Image format.
    Qoi,
    /// Farbfeld (lossless image format).
    Farbfeld,
    /// Scalable Vector Graphics.
    Svg,
    /// Compressed SVG (.svgz).
    Svgz,
}

impl ImageFormat {
    /// Returns the MIME type string for this format.
    pub fn mime_type(&self) -> &'static str {
        match self {
            ImageFormat::Unknown => "application/octet-stream",
            ImageFormat::Rgba8 => "image/x-rgba",
            ImageFormat::Rgb8 => "image/x-rgb",
            ImageFormat::Png => "image/png",
            ImageFormat::Jpeg => "image/jpeg",
            ImageFormat::Bmp => "image/bmp",
            ImageFormat::Gif => "image/gif",
            ImageFormat::WebP => "image/webp",
            ImageFormat::Tiff => "image/tiff",
            ImageFormat::Avif => "image/avif",
            ImageFormat::Ico => "image/x-icon",
            ImageFormat::Pnm => "image/x-portable-anymap",
            ImageFormat::Qoi => "image/x-qoi",
            ImageFormat::Farbfeld => "image/x-farbfeld",
            ImageFormat::Svg => "image/svg+xml",
            ImageFormat::Svgz => "image/svg+xml-compressed",
        }
    }

    /// Returns the common file extension (without dot) for this format.
    pub fn extension(&self) -> &'static str {
        match self {
            ImageFormat::Unknown => "bin",
            ImageFormat::Rgba8 => "rgba",
            ImageFormat::Rgb8 => "rgb",
            ImageFormat::Png => "png",
            ImageFormat::Jpeg => "jpg",
            ImageFormat::Bmp => "bmp",
            ImageFormat::Gif => "gif",
            ImageFormat::WebP => "webp",
            ImageFormat::Tiff => "tiff",
            ImageFormat::Avif => "avif",
            ImageFormat::Ico => "ico",
            ImageFormat::Pnm => "pnm",
            ImageFormat::Qoi => "qoi",
            ImageFormat::Farbfeld => "ff",
            ImageFormat::Svg => "svg",
            ImageFormat::Svgz => "svgz",
        }
    }

    /// Returns true if this format supports animation (multiple frames).
    pub fn supports_animation(&self) -> bool {
        matches!(self, ImageFormat::Gif | ImageFormat::WebP | ImageFormat::Avif | ImageFormat::Png)
    }

    /// Returns true if this format supports lossy compression.
    pub fn supports_lossy(&self) -> bool {
        matches!(self, ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Avif)
    }

    /// Returns true if this format supports transparency/alpha channel.
    pub fn supports_alpha(&self) -> bool {
        !matches!(self, ImageFormat::Jpeg | ImageFormat::Bmp | ImageFormat::Pnm | ImageFormat::Rgb8)
    }

    /// Returns true if this is a vector format (SVG/SVGZ).
    pub fn is_vector(&self) -> bool {
        matches!(self, ImageFormat::Svg | ImageFormat::Svgz)
    }
}

/// Pixel data representation variants.
#[derive(Debug, Clone, PartialEq)]
pub enum ImageData {
    /// 8-bit RGBA pixels (4 bytes per pixel).
    Rgba8(Vec<u8>),
    /// 8-bit RGB pixels (3 bytes per pixel).
    Rgb8(Vec<u8>),
    /// 8-bit grayscale (1 byte per pixel).
    Grayscale8(Vec<u8>),
    /// 16-bit grayscale (2 bytes per pixel, big-endian).
    Grayscale16(Vec<u8>),
    /// 16-bit RGBA pixels (8 bytes per pixel, big-endian per channel).
    Rgba16(Vec<u8>),
    /// 16-bit RGB pixels (6 bytes per pixel, big-endian per channel).
    Rgb16(Vec<u8>),
}

impl ImageData {
    /// Returns the raw pixel bytes.
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            ImageData::Rgba8(d) => d,
            ImageData::Rgb8(d) => d,
            ImageData::Grayscale8(d) => d,
            ImageData::Grayscale16(d) => d,
            ImageData::Rgba16(d) => d,
            ImageData::Rgb16(d) => d,
        }
    }

    /// Consumes self and returns the raw pixel bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        match self {
            ImageData::Rgba8(d) => d,
            ImageData::Rgb8(d) => d,
            ImageData::Grayscale8(d) => d,
            ImageData::Grayscale16(d) => d,
            ImageData::Rgba16(d) => d,
            ImageData::Rgb16(d) => d,
        }
    }

    /// Returns the number of bytes per pixel.
    pub fn bytes_per_pixel(&self) -> usize {
        match self {
            ImageData::Rgba8(_) => 4,
            ImageData::Rgb8(_) => 3,
            ImageData::Grayscale8(_) => 1,
            ImageData::Grayscale16(_) => 2,
            ImageData::Rgba16(_) => 8,
            ImageData::Rgb16(_) => 6,
        }
    }

    /// Returns the number of channels.
    pub fn channels(&self) -> usize {
        match self {
            ImageData::Rgba8(_) | ImageData::Rgba16(_) => 4,
            ImageData::Rgb8(_) | ImageData::Rgb16(_) => 3,
            ImageData::Grayscale8(_) | ImageData::Grayscale16(_) => 1,
        }
    }

    /// Converts to RGBA8 if not already. Returns self if already RGBA8.
    pub fn to_rgba8(&self, width: u32, height: u32) -> ImageData {
        if matches!(self, ImageData::Rgba8(_)) {
            return self.clone();
        }
        let total = (width * height) as usize;
        match self {
            ImageData::Rgb8(d) => {
                let mut rgba = Vec::with_capacity(total * 4);
                for chunk in d.chunks(3) {
                    rgba.push(chunk[0]);
                    rgba.push(chunk[1]);
                    rgba.push(chunk[2]);
                    rgba.push(255);
                }
                ImageData::Rgba8(rgba)
            }
            ImageData::Grayscale8(d) => {
                let mut rgba = Vec::with_capacity(total * 4);
                for &g in d {
                    rgba.push(g);
                    rgba.push(g);
                    rgba.push(g);
                    rgba.push(255);
                }
                ImageData::Rgba8(rgba)
            }
            ImageData::Grayscale16(d) => {
                let mut rgba = Vec::with_capacity(total * 4);
                for chunk in d.chunks(2) {
                    let g = (u16::from_be_bytes([chunk[0], chunk[1]]) >> 8) as u8;
                    rgba.push(g);
                    rgba.push(g);
                    rgba.push(g);
                    rgba.push(255);
                }
                ImageData::Rgba8(rgba)
            }
            ImageData::Rgba16(d) => {
                let mut rgba = Vec::with_capacity(total * 4);
                for chunk in d.chunks(8) {
                    rgba.push((u16::from_be_bytes([chunk[0], chunk[1]]) >> 8) as u8);
                    rgba.push((u16::from_be_bytes([chunk[2], chunk[3]]) >> 8) as u8);
                    rgba.push((u16::from_be_bytes([chunk[4], chunk[5]]) >> 8) as u8);
                    rgba.push((u16::from_be_bytes([chunk[6], chunk[7]]) >> 8) as u8);
                }
                ImageData::Rgba8(rgba)
            }
            ImageData::Rgb16(d) => {
                let mut rgba = Vec::with_capacity(total * 4);
                for chunk in d.chunks(6) {
                    rgba.push((u16::from_be_bytes([chunk[0], chunk[1]]) >> 8) as u8);
                    rgba.push((u16::from_be_bytes([chunk[2], chunk[3]]) >> 8) as u8);
                    rgba.push((u16::from_be_bytes([chunk[4], chunk[5]]) >> 8) as u8);
                    rgba.push(255);
                }
                ImageData::Rgba8(rgba)
            }
            ImageData::Rgba8(_) => unreachable!(), // Caught by matches! check above
        }
    }
}

/// EXIF data extracted from image files.
#[derive(Debug, Clone, Default)]
pub struct ExifData {
    /// Camera make.
    pub make: String,
    /// Camera model.
    pub model: String,
    /// ISO speed rating.
    pub iso: Option<u32>,
    /// Focal length in millimeters.
    pub focal_length: Option<f64>,
    /// Aperture (F-number).
    pub aperture: Option<f64>,
    /// Exposure time in seconds.
    pub exposure_time: Option<f64>,
    /// Original date/time.
    pub date_time: Option<String>,
    /// GPS latitude in decimal degrees.
    pub gps_latitude: Option<f64>,
    /// GPS longitude in decimal degrees.
    pub gps_longitude: Option<f64>,
    /// Image width from EXIF.
    pub exif_width: Option<u32>,
    /// Image height from EXIF.
    pub exif_height: Option<u32>,
    /// Orientation (1 = normal, 3 = 180 rotated, 6 = 90 CW, 8 = 90 CCW).
    pub orientation: Option<u8>,
}

/// Parsed color space information.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorSpace {
    /// sRGB (default).
    #[default]
    Srgb,
    /// Adobe RGB.
    AdobeRgb,
    /// Linear RGB.
    LinearRgb,
    /// ProPhoto RGB.
    ProPhotoRgb,
    /// Display P3.
    DisplayP3,
    /// Grayscale.
    Grayscale,
    /// CMYK.
    Cmyk,
    /// Unknown color space.
    Unknown,
}

/// Decoded image with metadata.
#[derive(Debug, Clone)]
pub struct DecodedImage {
    /// The image format as detected.
    pub format: ImageFormat,
    /// Pixel data.
    pub data: ImageData,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// EXIF metadata (if available).
    pub exif: ExifData,
    /// Color space information.
    pub color_space: ColorSpace,
}

impl DecodedImage {
    /// Create a new decoded image.
    pub fn new(format: ImageFormat, data: ImageData, width: u32, height: u32) -> Self {
        Self {
            format,
            data,
            width,
            height,
            exif: ExifData::default(),
            color_space: ColorSpace::Srgb,
        }
    }

    /// Returns the total number of pixels.
    pub fn pixel_count(&self) -> u64 {
        self.width as u64 * self.height as u64
    }

    /// Returns a reference to the RGBA8 pixel data, converting if needed.
    pub fn as_rgba8(&self) -> ImageData {
        self.data.to_rgba8(self.width, self.height)
    }
}

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

    #[test]
    fn image_format_mime_types() {
        assert_eq!(ImageFormat::Png.mime_type(), "image/png");
        assert_eq!(ImageFormat::Jpeg.mime_type(), "image/jpeg");
        assert_eq!(ImageFormat::Gif.mime_type(), "image/gif");
        assert_eq!(ImageFormat::Svg.mime_type(), "image/svg+xml");
        assert_eq!(ImageFormat::Svgz.mime_type(), "image/svg+xml-compressed");
    }

    #[test]
    fn image_format_extensions() {
        assert_eq!(ImageFormat::Png.extension(), "png");
        assert_eq!(ImageFormat::WebP.extension(), "webp");
        assert_eq!(ImageFormat::Avif.extension(), "avif");
        assert_eq!(ImageFormat::Ico.extension(), "ico");
        assert_eq!(ImageFormat::Farbfeld.extension(), "ff");
    }

    #[test]
    fn image_format_supports_checks() {
        assert!(ImageFormat::Png.supports_animation());
        assert!(!ImageFormat::Jpeg.supports_animation());
        assert!(ImageFormat::Jpeg.supports_lossy());
        assert!(!ImageFormat::Png.supports_lossy());
        assert!(ImageFormat::Png.supports_alpha());
        assert!(!ImageFormat::Jpeg.supports_alpha());
        assert!(ImageFormat::Svg.is_vector());
        assert!(ImageFormat::Svgz.is_vector());
        assert!(!ImageFormat::Png.is_vector());
    }

    #[test]
    fn image_data_rgb8_to_rgba8() {
        let rgb = ImageData::Rgb8(vec![255, 0, 0, 0, 255, 0]);
        let rgba = rgb.to_rgba8(2, 1);
        if let ImageData::Rgba8(d) = rgba {
            assert_eq!(d.len(), 8);
            assert_eq!(&d[0..4], &[255, 0, 0, 255]);
            assert_eq!(&d[4..8], &[0, 255, 0, 255]);
        } else {
            panic!("Expected Rgba8");
        }
    }

    #[test]
    fn image_data_grayscale8_to_rgba8() {
        let g = ImageData::Grayscale8(vec![128, 64]);
        let rgba = g.to_rgba8(2, 1);
        if let ImageData::Rgba8(d) = rgba {
            assert_eq!(&d[0..4], &[128, 128, 128, 255]);
            assert_eq!(&d[4..8], &[64, 64, 64, 255]);
        } else {
            panic!("Expected Rgba8");
        }
    }

    #[test]
    fn decoded_image_pixel_count() {
        let img = DecodedImage::new(ImageFormat::Rgba8, ImageData::Rgba8(vec![0; 400]), 20, 20);
        assert_eq!(img.pixel_count(), 400);
    }

    #[test]
    fn image_data_bytes_per_pixel() {
        assert_eq!(ImageData::Rgba8(vec![]).bytes_per_pixel(), 4);
        assert_eq!(ImageData::Rgb8(vec![]).bytes_per_pixel(), 3);
        assert_eq!(ImageData::Grayscale8(vec![]).bytes_per_pixel(), 1);
        assert_eq!(ImageData::Grayscale16(vec![]).bytes_per_pixel(), 2);
    }
}