f-office-paint 0.3.0

Display list: the contract between layout and output.
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
//! The headers of PNG and JPEG files: the pixel size, and the resolution when the file gives
//! one. PNG: ISO/IEC 15948, 11.2.2 `IHDR` and 11.3.5.3 `pHYs`, which comes before the first
//! `IDAT` chunk, and the palette's class from `IHDR`, 11.2.3 `PLTE` and 11.3.2.1 `tRNS`, which
//! also come before it. JPEG: ITU-T T.81, B.2.2, the frame header after the segments before it,
//! and the density of a JFIF `APP0` segment among them (JPEG File Interchange Format 1.02).

use crate::PaletteClass;

/// The length in which a density counts its pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DensityUnit {
    /// Pixels per inch.
    Inch,
    /// Pixels per centimeter.
    Centimeter,
    /// Pixels per meter.
    Meter,
}

/// What the header of an image file gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageHeader {
    /// The width and the height, in pixels.
    pub pixels: (usize, usize),
    /// The pixels in one unit of the width and of the height, both more than zero, and the
    /// unit, when the file gives them.
    pub density: Option<(u32, u32, DensityUnit)>,
}

/// The type of the PNG chunk of the header, which comes first.
const IHDR: &[u8] = b"IHDR";

/// The type of the PNG chunk of the density.
const PHYS: &[u8] = b"pHYs";

/// The type of the PNG chunk of the palette.
const PLTE: &[u8] = b"PLTE";

/// The type of the PNG chunk of the transparency.
const TRNS: &[u8] = b"tRNS";

/// The PNG color type of a palette.
const PNG_PALETTE: u8 = 3;

/// The PNG color types with an alpha sample: gray with an alpha (4) and RGB with an alpha (6).
const PNG_ALPHA_TYPES: [u8; 2] = [4, 6];

/// The types of the PNG chunks after which no density comes.
const PNG_DATA: [&[u8]; 2] = [b"IDAT", b"IEND"];

/// The unit of a PNG density in meters.
const PNG_METER: u8 = 1;

/// The JPEG marker of an application segment of type 0, which a JFIF file starts with.
const APP0: u8 = 0xe0;

/// The identifier at the start of a JFIF `APP0` segment.
const JFIF: &[u8] = b"JFIF\0";

/// The pixel size `(width, height)` from a GIF logical screen descriptor (GIF87a/GIF89a, bytes
/// 6..10 little-endian).
#[must_use]
pub fn gif_pixels(data: &[u8]) -> Option<(usize, usize)> {
    let head = data.get(6..10)?;
    let w = u16::from_le_bytes([*head.first()?, *head.get(1)?]);
    let h = u16::from_le_bytes([*head.get(2)?, *head.get(3)?]);
    (w > 0 && h > 0).then_some((usize::from(w), usize::from(h)))
}

/// The pixel size `(width, height)` from a Windows BMP DIB header (`BITMAPINFOHEADER`, bytes
/// 18..26 little-endian signed 32-bit integers).
#[must_use]
pub fn bmp_pixels(data: &[u8]) -> Option<(usize, usize)> {
    let w_bytes: [u8; 4] = data.get(18..22)?.try_into().ok()?;
    let h_bytes: [u8; 4] = data.get(22..26)?.try_into().ok()?;
    let w = usize::try_from(i32::from_le_bytes(w_bytes)).ok()?;
    let h = usize::try_from(i32::from_le_bytes(h_bytes).unsigned_abs()).ok()?;
    (w > 0 && h > 0).then_some((w, h))
}

/// The header of the PNG file `data`.
#[must_use]
pub fn png_header(data: &[u8]) -> Option<ImageHeader> {
    (data.get(12..16) == Some(IHDR)).then_some(())?;
    let pixels = (
        usize::try_from(be32(data, 16)?).ok()?,
        usize::try_from(be32(data, 20)?).ok()?,
    );
    Some(ImageHeader {
        pixels,
        density: png_density(data),
    })
}

/// The density of the `pHYs` chunk of the PNG file `data`: none when the walk of the chunks
/// reaches the data first or breaks off, or when the chunk gives no unit.
fn png_density(data: &[u8]) -> Option<(u32, u32, DensityUnit)> {
    let (_, body) = png_chunks(data).find(|(kind, _)| *kind == PHYS)?;
    let (x, y) = (be32(body, 0)?, be32(body, 4)?);
    (body.get(8) == Some(&PNG_METER) && x > 0 && y > 0).then_some((x, y, DensityUnit::Meter))
}

/// The class of the palette of the PNG file `data` ([`PaletteClass`]): none for another color
/// type, a palette with a `tRNS` chunk, a palette of 2 bits, a palette of more than 1 bit whose
/// entries are all gray, or a file whose `PLTE` chunk the walk of the chunks does not reach
/// before the data.
#[must_use]
pub fn png_palette_class(data: &[u8]) -> Option<PaletteClass> {
    (png_color_type(data) == Some(PNG_PALETTE)).then_some(())?;
    let mut palette = None;
    for (kind, body) in png_chunks(data) {
        if kind == TRNS {
            return None;
        }
        if kind == PLTE {
            palette = Some(body);
        }
    }
    let gray = palette?
        .chunks(3)
        .all(|entry| matches!(entry, [red, green, blue] if red == green && green == blue));
    match (data.get(24)?, gray) {
        (1, _) => Some(PaletteClass::OneBit),
        (4, false) => Some(PaletteClass::FourBitColor),
        (8, false) => Some(PaletteClass::EightBitColor),
        _ => None,
    }
}

/// The color type of the PNG file `data` from its header chunk (ISO/IEC 15948, 11.2.2): 0 gray,
/// 2 RGB, 3 a palette, 4 gray with an alpha, 6 RGB with an alpha; `None` when the file has no
/// header chunk in its place.
#[must_use]
pub fn png_color_type(data: &[u8]) -> Option<u8> {
    (data.get(12..16) == Some(IHDR)).then_some(())?;
    data.get(25).copied()
}

/// Whether the PNG file `data` can make pixels clear or partly clear: its color type has an
/// alpha sample (ISO/IEC 15948, 11.2.2), or a `tRNS` chunk comes before its data (11.3.2.1);
/// `None` when the file has no header chunk in its place.
#[must_use]
pub fn png_can_be_clear(data: &[u8]) -> Option<bool> {
    let color_type = png_color_type(data)?;
    Some(PNG_ALPHA_TYPES.contains(&color_type) || png_chunks(data).any(|(kind, _)| kind == TRNS))
}

/// Whether `data` holds every PNG metadata chunk before the first `IDAT` or `IEND` chunk.
///
/// Use this before trusting [`png_header`], [`png_palette_class`], or [`png_can_be_clear`] on a
/// truncated prefix of a lazy PNG image: if a large chunk (such as `iCCP`) pushes `pHYs`, `PLTE`,
/// or `tRNS` past the prefix, this returns `false` so callers fall back to loading full bytes.
#[must_use]
pub fn png_header_complete(data: &[u8]) -> bool {
    let mut at = 8_usize;
    loop {
        let Some(length) = be32(data, at).and_then(|v| usize::try_from(v).ok()) else {
            return false;
        };
        let Some(kind_end) = at.checked_add(8) else {
            return false;
        };
        let Some(kind) = data.get(at + 4..kind_end) else {
            return false;
        };
        if PNG_DATA.contains(&kind) {
            return true;
        }
        let Some(next) = kind_end.checked_add(length).and_then(|e| e.checked_add(4)) else {
            return false;
        };
        if next > data.len() {
            return false;
        }
        at = next;
    }
}

/// The chunks of the PNG file `data` after its header chunk's place and before its first data
/// chunk, each as its type and its body, until the walk reaches the data or breaks off.
fn png_chunks(data: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
    let mut at = Some(8_usize);
    std::iter::from_fn(move || {
        let start = at.take()?;
        let length = usize::try_from(be32(data, start)?).ok()?;
        let kind = data.get(start.checked_add(4)?..start.checked_add(8)?)?;
        if PNG_DATA.contains(&kind) {
            return None;
        }
        let first = start.checked_add(8)?;
        let end = first.checked_add(length)?;
        let body = data.get(first..end)?;
        at = end.checked_add(4);
        Some((kind, body))
    })
}

/// The header of the JPEG file `data`.
#[must_use]
pub fn jpeg_header(data: &[u8]) -> Option<ImageHeader> {
    let mut density = None;
    let mut at = 2;
    loop {
        let (&mark, &kind) = (data.get(at)?, data.get(at + 1)?);
        if mark != 0xff {
            return None;
        }
        let frame = matches!(kind, 0xc0..=0xcf) && !matches!(kind, 0xc4 | 0xc8 | 0xcc);
        if frame {
            let pixels = (
                usize::from(be16(data, at + 7)?),
                usize::from(be16(data, at + 5)?),
            );
            return Some(ImageHeader { pixels, density });
        }
        let length = usize::from(be16(data, at + 2)?);
        if kind == APP0
            && let Some(segment) = data.get(at + 4..at + 2 + length)
        {
            density = jfif_density(segment).or(density);
        }
        at += 2 + length;
    }
}

/// The density of the JFIF `APP0` segment `segment`, after its length: none for another
/// segment, and for a density that gives only the aspect of a pixel.
fn jfif_density(segment: &[u8]) -> Option<(u32, u32, DensityUnit)> {
    if !segment.starts_with(JFIF) {
        return None;
    }
    let unit = match segment.get(7)? {
        1 => DensityUnit::Inch,
        2 => DensityUnit::Centimeter,
        _ => return None,
    };
    let (x, y) = (u32::from(be16(segment, 8)?), u32::from(be16(segment, 10)?));
    (x > 0 && y > 0).then_some((x, y, unit))
}

/// The big-endian 32-bit number at `at` of `data`.
fn be32(data: &[u8], at: usize) -> Option<u32> {
    let bytes: [u8; 4] = data.get(at..at.checked_add(4)?)?.try_into().ok()?;
    Some(u32::from_be_bytes(bytes))
}

/// The big-endian 16-bit number at `at` of `data`.
fn be16(data: &[u8], at: usize) -> Option<u16> {
    Some(u16::from_be_bytes([
        *data.get(at)?,
        *data.get(at.checked_add(1)?)?,
    ]))
}

#[cfg(test)]
mod tests {
    use crate::PaletteClass;

    use super::{DensityUnit, jpeg_header, png_can_be_clear, png_header, png_palette_class};

    /// A PNG file's signature and chunks, each with a CRC of zeros, which the reader does not
    /// check.
    fn png(chunks: &[(&[u8], Vec<u8>)]) -> Vec<u8> {
        let mut file = b"\x89PNG\r\n\x1a\n".to_vec();
        for (kind, body) in chunks {
            let length = u32::try_from(body.len()).unwrap();
            file.extend_from_slice(&length.to_be_bytes());
            file.extend_from_slice(kind);
            file.extend_from_slice(body);
            file.extend_from_slice(&[0; 4]);
        }
        file
    }

    fn ihdr(width: u32, height: u32) -> Vec<u8> {
        let mut body = width.to_be_bytes().to_vec();
        body.extend_from_slice(&height.to_be_bytes());
        body.extend_from_slice(&[8, 2, 0, 0, 0]);
        body
    }

    /// A header chunk of a palette of `depth` bits.
    fn palette_ihdr(depth: u8) -> Vec<u8> {
        let mut body = ihdr(4, 4);
        body[8..10].copy_from_slice(&[depth, 3]);
        body
    }

    /// The class of a palette PNG of `depth` bits with the entries `entries`, its `tRNS`
    /// chunk when `clear`, and its chunks before and after the data.
    fn class(depth: u8, entries: &[u8], clear: bool) -> Option<PaletteClass> {
        let mut chunks = vec![
            (&b"IHDR"[..], palette_ihdr(depth)),
            (b"PLTE", entries.to_vec()),
        ];
        if clear {
            chunks.push((b"tRNS", vec![255]));
        }
        chunks.push((b"IDAT", vec![0]));
        png_palette_class(&png(&chunks))
    }

    #[test]
    fn png_palette_class_from_its_depth_its_entries_and_its_transparency() {
        let (gray, color) = (&[0, 0, 0, 255, 255, 255][..], &[0, 0, 0, 40, 90, 170][..]);
        let (one, four, eight) = (
            Some(PaletteClass::OneBit),
            Some(PaletteClass::FourBitColor),
            Some(PaletteClass::EightBitColor),
        );
        // Each case: bits, entries, a tRNS chunk, and the class. Any tRNS chunk takes the
        // class away, also one of an opaque entry.
        let cases = [
            (1, gray, false, one),
            (1, color, false, one),
            (2, color, false, None),
            (4, color, false, four),
            (4, gray, false, None),
            (8, color, false, eight),
            (8, gray, false, None),
            (1, gray, true, None),
            (8, color, true, None),
        ];
        for (depth, entries, clear, expected) in cases {
            assert_eq!(class(depth, entries, clear), expected);
        }
    }

    #[test]
    fn png_palette_class_needs_a_palette_before_the_data() {
        let rgb = png(&[(b"IHDR", ihdr(4, 4)), (b"IDAT", vec![0])]);
        assert_eq!(png_palette_class(&rgb), None);
        let color = vec![0, 0, 0, 40, 90, 170];
        let late = png(&[
            (b"IHDR", palette_ihdr(8)),
            (b"IDAT", vec![0]),
            (b"PLTE", color.clone()),
        ]);
        assert_eq!(png_palette_class(&late), None);
        // A tRNS chunk after the data does not count.
        let after = png(&[
            (b"IHDR", palette_ihdr(8)),
            (b"PLTE", color),
            (b"IDAT", vec![0]),
            (b"tRNS", vec![0]),
        ]);
        assert_eq!(png_palette_class(&after), Some(PaletteClass::EightBitColor));
    }

    /// Whether a PNG file of the color type `color_type` can be clear, with a transparency
    /// chunk before its data (`Some(true)`), after it (`Some(false)`) or none.
    fn typed_can_be_clear(color_type: u8, transparency: Option<bool>) -> Option<bool> {
        let mut header = ihdr(4, 4);
        header[9] = color_type;
        let mut chunks = vec![(&b"IHDR"[..], header)];
        if transparency == Some(true) {
            chunks.push((b"tRNS", vec![0, 0]));
        }
        chunks.push((b"IDAT", vec![0]));
        if transparency == Some(false) {
            chunks.push((b"tRNS", vec![0, 0]));
        }
        png_can_be_clear(&png(&chunks))
    }

    #[test]
    fn png_can_be_clear_by_its_alpha_sample_or_a_transparency_chunk_before_the_data() {
        // The color type, the place of a transparency chunk, and whether the file can be clear;
        // a transparency chunk after the data does not count.
        let cases = [
            (2, None, true),
            (0, None, true),
            (3, None, true),
            (6, None, false),
            (4, None, false),
            (2, Some(true), false),
            (3, Some(true), false),
            (2, Some(false), true),
        ];
        for (color_type, transparency, opaque) in cases {
            assert_eq!(
                typed_can_be_clear(color_type, transparency),
                Some(!opaque),
                "{color_type} {transparency:?}"
            );
        }
        assert_eq!(png_can_be_clear(b"not a png"), None);
    }

    fn phys(x: u32, y: u32, unit: u8) -> Vec<u8> {
        let mut body = x.to_be_bytes().to_vec();
        body.extend_from_slice(&y.to_be_bytes());
        body.push(unit);
        body
    }

    #[test]
    fn png_gives_its_pixels_and_its_density_before_the_data() {
        let file = png(&[
            (b"IHDR", ihdr(300, 200)),
            (b"tEXt", b"a".to_vec()),
            (b"pHYs", phys(3_780, 2_835, 1)),
            (b"IDAT", Vec::new()),
        ]);
        let header = png_header(&file).unwrap();
        assert_eq!(header.pixels, (300, 200));
        assert_eq!(header.density, Some((3_780, 2_835, DensityUnit::Meter)));
    }

    #[test]
    fn png_density_after_the_data_or_without_a_unit_counts_as_none() {
        let late = png(&[
            (b"IHDR", ihdr(3, 2)),
            (b"IDAT", Vec::new()),
            (b"pHYs", phys(3_780, 3_780, 1)),
        ]);
        assert_eq!(png_header(&late).unwrap().density, None);
        let aspect = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(1, 2, 0))]);
        assert_eq!(png_header(&aspect).unwrap().density, None);
        let zero = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(0, 3_780, 1))]);
        assert_eq!(png_header(&zero).unwrap().density, None);
        let mut cut = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(3_780, 3_780, 1))]);
        cut.truncate(cut.len() - 8);
        assert_eq!(png_header(&cut).unwrap().pixels, (3, 2));
        assert_eq!(png_header(&cut).unwrap().density, None);
    }

    #[test]
    fn png_without_its_header_chunk_first_has_no_header() {
        let file = png(&[(b"pHYs", phys(1, 1, 1)), (b"IHDR", ihdr(3, 2))]);
        assert_eq!(png_header(&file), None);
    }

    /// A JPEG file's start, an `APP0` segment with `app0`, and a baseline frame header of
    /// `width` by `height` pixels.
    fn jpeg(app0: &[u8], width: u16, height: u16) -> Vec<u8> {
        let mut file = vec![0xff, 0xd8, 0xff, 0xe0];
        file.extend_from_slice(&u16::try_from(app0.len() + 2).unwrap().to_be_bytes());
        file.extend_from_slice(app0);
        file.extend_from_slice(&[0xff, 0xc0, 0, 11, 8]);
        file.extend_from_slice(&height.to_be_bytes());
        file.extend_from_slice(&width.to_be_bytes());
        file.extend_from_slice(&[1, 1, 0x11, 0]);
        file
    }

    #[test]
    fn jpeg_gives_its_pixels_and_its_jfif_density() {
        let per_inch = jpeg(b"JFIF\0\x01\x02\x01\x00\x48\x00\x90\0\0", 640, 480);
        let header = jpeg_header(&per_inch).unwrap();
        assert_eq!(header.pixels, (640, 480));
        assert_eq!(header.density, Some((72, 144, DensityUnit::Inch)));
        let per_cm = jpeg(b"JFIF\0\x01\x02\x02\x00\x76\x00\x76\0\0", 4, 3);
        assert_eq!(
            jpeg_header(&per_cm).unwrap().density,
            Some((118, 118, DensityUnit::Centimeter))
        );
        let aspect = jpeg(b"JFIF\0\x01\x02\x00\x00\x01\x00\x01\0\0", 4, 3);
        assert_eq!(jpeg_header(&aspect).unwrap().density, None);
        let other = jpeg(b"JFXX\0\x01\x02\x01\x00\x48\x00\x48\0\0", 4, 3);
        assert_eq!(jpeg_header(&other).unwrap().density, None);
    }

    #[test]
    fn jpeg_cut_short_has_no_header() {
        assert_eq!(jpeg_header(b"\xff\xd8\xff\xe0 cut short"), None);
    }
}