f-office 0.2.2

Renders Office Open XML documents the way Microsoft Office does.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
use std::sync::Arc;

use f_office_jpeg::{Samples, coefficients, decode, encode};
use f_office_paint::{
    AlphaMix, DisplayList, Image, ImageFault, ImageFormat, ImageItem, Item, LinearLimit,
    MAX_DECODED_BYTES, MAX_DECODED_BYTES_TO_WRITE_AGAIN, Orientation, Page, PaletteClass,
    PictureCrop, Resampler, decode_file, testing::zero_png,
};

use super::{
    Resampling, Rewriting, cut, divided_by_alpha, edges_of, png_again, premultiplied,
    weighted_level,
};
use crate::{Length, Warning, Warnings};
use f_office_paint::image_header::{jpeg_header, png_header};

/// The filter's limit of a new writer, 2^17 source pixels.
const COUNT: LinearLimit = LinearLimit::Pixels(std::num::NonZeroU32::new(1 << 17).unwrap());

/// Writes the pictures again, without the warnings, for the tests that do not read them.
fn write_pictures_again(list: DisplayList, rewriting: Rewriting) -> DisplayList {
    super::write_pictures_again(list, rewriting, &mut Warnings::new())
}

/// The writer of JPEG files at quality 75, which keeps every picture's pixels, and its
/// warnings.
fn write_jpegs_again(list: DisplayList, quality: u8) -> (DisplayList, Warnings) {
    let quality = f_office_paint::JpegQuality::new(quality).unwrap();
    let mut warnings = Warnings::new();
    let list = super::write_pictures_again(
        list,
        rewriting(Some(quality), &|_, _, _| None),
        &mut warnings,
    );
    (list, warnings)
}

/// A writer that writes JPEG files at `quality`, crops no picture and resamples by
/// `resampling`.
fn rewriting(quality: Option<f_office_paint::JpegQuality>, resampling: Resampling) -> Rewriting {
    Rewriting {
        quality,
        jpeg_share: None,
        jpeg_sample: None,
        crop: PictureCrop::WholeFileUnderClip,
        alpha_mix: AlphaMix::Plain,
        resampling,
    }
}

/// A page item that shows an image file.
fn picture(data: &Arc<[u8]>) -> Item {
    Item::Image(ImageItem {
        x: Length::ZERO,
        y: Length::ZERO,
        width: Length::ZERO,
        height: Length::ZERO,
        clip: None,
        turn: None,
        image: Image::new(Arc::clone(data)),
    })
}

/// A page of `items`.
fn page(items: Vec<Item>) -> Page {
    Page::new(Length::ZERO, Length::ZERO, Orientation::Portrait, items)
}

/// The file of each picture of a page, in order.
fn files(page: &Page) -> Vec<Arc<[u8]>> {
    page.items()
        .iter()
        .filter_map(|item| match item {
            Item::Image(image) => image.image.load_bytes(),
            _ => None,
        })
        .collect()
}

#[test]
fn writes_each_jpeg_file_again_once_and_keeps_other_files() {
    let pixels = (0..24 * 16 * 3)
        .map(|i| u8::try_from(i % 251).unwrap())
        .collect();
    let fine: Arc<[u8]> = encode(&Samples::rgb((24, 16), pixels).unwrap(), 95)
        .unwrap()
        .into();
    let png: Arc<[u8]> = b"\x89PNG\r\n\x1a\n not read".as_slice().into();
    let broken: Arc<[u8]> = b"\xff\xd8\xff\xe0 cut short".as_slice().into();
    let group = Item::Group(f_office_paint::Group::new(vec![picture(&fine)]));
    let list = DisplayList::new(vec![
        page(vec![picture(&fine), picture(&png), picture(&broken), group]),
        page(vec![picture(&fine)]),
    ]);
    let (list, warnings) = write_jpegs_again(list, 75);
    // The JPEG file that does not decode keeps its file, with a warning.
    let format = ImageFormat::Jpeg;
    assert_eq!(
        warnings.into_iter().collect::<Vec<_>>(),
        [(Warning::PictureNotWrittenAgain { format }, 1)]
    );
    let first = files(&list.pages()[0]);
    let again = &first[0];
    // The quality-75 luma table starts with 8, and quality 95 with 2.
    assert_eq!(
        coefficients(again, MAX_DECODED_BYTES).unwrap()[0].table[0],
        8
    );
    assert_eq!(
        coefficients(&fine, MAX_DECODED_BYTES).unwrap()[0].table[0],
        2
    );
    assert!(Arc::ptr_eq(again, &files(&list.pages()[1])[0]));
    assert!(Arc::ptr_eq(&first[1], &png) && Arc::ptr_eq(&first[2], &broken));
    let Item::Group(group) = &list.pages()[0].items()[3] else {
        panic!("the group stays a group");
    };
    assert_eq!(group.items, vec![picture(&fine)]);
}

#[test]
fn writes_a_picture_in_a_group_of_the_page_as_the_page_s_own() {
    // A clip of the page that cuts a picture gives it no space of its own: the writer writes
    // its JPEG file again as it writes one on the page, and keeps the group and its clip.
    let fine = jpeg_file();
    let clip = f_office_paint::GroupClip::rect(
        Length::ZERO,
        Length::ZERO,
        Length::from_units(100),
        Length::from_units(50),
    );
    let group = f_office_paint::Group::of_page(vec![picture(&fine)], clip.clone());
    let (list, _) = write_jpegs_again(DisplayList::new(vec![page(vec![Item::Group(group)])]), 75);
    let Item::Group(group) = &list.pages()[0].items()[0] else {
        panic!("the group stays a group");
    };
    assert_eq!(
        (group.clip.as_ref(), group.places),
        (Some(&clip), f_office_paint::GroupPlaces::Page)
    );
    let [Item::Image(image)] = group.items.as_slice() else {
        panic!("the group holds the picture");
    };
    // The quality-75 luma table starts with 8, and quality 95 with 2.
    let bytes = image.image.load_bytes().unwrap();
    assert_eq!(
        coefficients(&bytes, MAX_DECODED_BYTES).unwrap()[0].table[0],
        8
    );
}

/// A JPEG file of 24 by 16 pixels at quality 95, with `segments` application segments of
/// 65,533 bytes after its start, which a reader skips.
fn padded_jpeg(segments: usize) -> Arc<[u8]> {
    let pixels = (0..24 * 16 * 3)
        .map(|i| u8::try_from(i % 251).unwrap())
        .collect();
    let file = encode(&Samples::rgb((24, 16), pixels).unwrap(), 95).unwrap();
    let (start, rest) = file.split_at(2);
    let mut padded = start.to_vec();
    for _ in 0..segments {
        // An APP1 marker and its length, which counts its own two bytes.
        padded.extend_from_slice(&[0xff, 0xe1, 0xff, 0xff]);
        padded.resize(padded.len() + 65_533, 0);
    }
    padded.extend_from_slice(rest);
    padded.into()
}

#[test]
fn reads_a_file_that_many_pages_show_once() {
    // 2,000 pages show one JPEG file of 1 MiB, and one more page shows a copy of its bytes in
    // an `Arc` of its own. A hash of the file and a read of its header for each use would read
    // about 2 · 2,000 MiB.
    const PAGES: usize = 2_000;
    let file = padded_jpeg(16);
    assert_eq!(
        jpeg_header(&file).map(|header| header.pixels),
        Some((24, 16))
    );
    let copy: Arc<[u8]> = file.to_vec().into();
    let mut pages: Vec<Page> = (0..PAGES).map(|_| page(vec![picture(&file)])).collect();
    pages.push(page(vec![picture(&copy)]));
    super::READ_BYTES.with(|read| read.set(0));
    let (list, warnings) = write_jpegs_again(DisplayList::new(pages), 75);
    let read = super::READ_BYTES.with(std::cell::Cell::get);
    // The hash of each of the two `Arc`s and the one header.
    assert!(read <= 3 * file.len(), "{read} bytes");
    assert_eq!(warnings.into_iter().count(), 0);
    // Every page, the copy's too, shows the one file written again.
    let again = Arc::clone(&files(&list.pages()[0])[0]);
    assert!(!Arc::ptr_eq(&again, &file));
    assert_eq!(list.pages().len(), PAGES + 1);
    assert!(
        list.pages()
            .iter()
            .all(|page| Arc::ptr_eq(&files(page)[0], &again))
    );
}

/// A JPEG file of 40 by 20 pixels at quality 95.
fn jpeg_file() -> Arc<[u8]> {
    let pixels = (0..40 * 20 * 3)
        .map(|i| u8::try_from(i % 241).unwrap())
        .collect();
    encode(&Samples::rgb((40, 20), pixels).unwrap(), 95)
        .unwrap()
        .into()
}

/// A PNG file of 30 by 10 pixels of one color at half alpha.
fn png_file() -> Arc<[u8]> {
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(30, 10, image::Rgba([10, 20, 30, 128]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .unwrap();
    png.into()
}

/// The pixel size in the header of the PNG file `data`.
fn png_size(data: &[u8]) -> Option<(usize, usize)> {
    png_header(data).map(|header| header.pixels)
}

#[test]
fn reads_the_pixel_size_from_the_header() {
    assert_eq!(
        jpeg_header(&jpeg_file()).map(|header| header.pixels),
        Some((40, 20))
    );
    assert_eq!(png_size(&png_file()), Some((30, 10)));
}

#[test]
fn resamples_the_pictures_that_the_writer_gives_a_size() {
    let (jpeg, png) = (jpeg_file(), png_file());
    let list = DisplayList::new(vec![page(vec![
        picture(&jpeg),
        picture(&png),
        picture(&jpeg),
    ])]);
    let list = write_pictures_again(
        list,
        rewriting(f_office_paint::JpegQuality::new(75), &|(w, h), _, _| {
            Some(((w / 2, h / 2), Resampler::Filter(COUNT)))
        }),
    );
    let written = files(&list.pages()[0]);
    let samples = decode(&written[0], MAX_DECODED_BYTES).unwrap();
    assert_eq!((samples.width(), samples.height()), (20, 10));
    assert!(Arc::ptr_eq(&written[0], &written[2]));
    let small = image::load_from_memory(&written[1]).unwrap().to_rgba8();
    assert_eq!(small.dimensions(), (15, 5));
    assert_eq!(small.get_pixel(3, 2).0, [10, 20, 30, 128]);
}

#[test]
fn resamples_png_files_without_a_jpeg_quality() {
    let (jpeg, png) = (jpeg_file(), png_file());
    let list = DisplayList::new(vec![page(vec![picture(&jpeg), picture(&png)])]);
    let list = write_pictures_again(
        list,
        rewriting(None, &|(w, h), _, _| {
            Some(((w / 2, h / 2), Resampler::Filter(COUNT)))
        }),
    );
    let written = files(&list.pages()[0]);
    assert!(Arc::ptr_eq(&written[0], &jpeg));
    assert_eq!(png_size(&written[1]), Some((15, 5)));
}

#[test]
fn gives_the_resampling_the_palette_class_and_resamples_as_it_says() {
    // The header and the palette of a 1-bit palette file of 4 by 4 pixels, with no data.
    let mut palette = b"\x89PNG\r\n\x1a\n".to_vec();
    let header = [0, 0, 0, 4, 0, 0, 0, 4, 1, 3, 0, 0, 0];
    for (kind, body) in [(b"IHDR", &header[..]), (b"PLTE", &[0, 0, 0, 255, 255, 255])] {
        palette.extend(u32::try_from(body.len()).unwrap().to_be_bytes());
        palette.extend(kind);
        palette.extend(body);
        palette.extend([0; 4]);
    }
    let palette: Arc<[u8]> = palette.into();
    // A stripe of black, white and black.
    let mut stripe = Vec::new();
    image::RgbImage::from_fn(3, 1, |x, _| image::Rgb([if x == 1 { 255 } else { 0 }; 3]))
        .write_to(
            &mut std::io::Cursor::new(&mut stripe),
            image::ImageFormat::Png,
        )
        .unwrap();
    let stripe: Arc<[u8]> = stripe.into();
    let classes = std::cell::RefCell::new(Vec::new());
    let resampling = |(width, _): (usize, usize), class, _: &ImageItem| {
        classes.borrow_mut().push(class);
        Some(((width * 2 / 3, 1), Resampler::CentrePixel))
    };
    let list = DisplayList::new(vec![page(vec![picture(&palette), picture(&stripe)])]);
    let list = write_pictures_again(list, rewriting(None, &resampling));
    assert_eq!(*classes.borrow(), [Some(PaletteClass::OneBit), None]);
    let written = files(&list.pages()[0]);
    // The palette file does not decode and stays; the stripe keeps its pixels 0 and 2, where
    // the filter would mix the white one in.
    assert!(Arc::ptr_eq(&written[0], &palette));
    let small = image::load_from_memory(&written[1]).unwrap().to_rgb8();
    assert_eq!(small.dimensions(), (2, 1));
    assert_eq!(small.into_raw(), [0; 6]);
}

#[test]
fn rounds_the_start_and_the_size_of_the_visible_part_to_the_nearest_pixel_a_half_up() {
    // A file of 240 by 180 pixels over 2,400 by 1,800 units, 10 units a pixel. The rectangle
    // and the clips are left, top, right and bottom edges in units.
    let rect = [0, 0, 2_400, 1_800];
    let part = |clip: [i64; 4]| edges_of(rect, clip, (240, 180));
    // Starts at 29.6 and 13.9 pixels with sizes of 202.4 and 121.1, and a start on a half,
    // 37.5, with a size of 165.
    assert_eq!(part([296, 139, 2_320, 1_350]), Some([30, 14, 232, 135]));
    assert_eq!(part([375, 0, 2_025, 1_800]), Some([38, 0, 203, 180]));
    // Starts at 10.6 and 10.4 with sizes of 89.8 and 90.2 keep 90 pixels each, where edges
    // rounded alone would keep 89 and 91.
    assert_eq!(part([106, 106, 1_004, 1_004]), Some([11, 11, 101, 101]));
    assert_eq!(part([104, 104, 1_006, 1_006]), Some([10, 10, 100, 100]));
    // A start of -0.4, and a crop below half a pixel, keep every pixel.
    assert_eq!(part([-4, 0, 2_400, 1_800]), Some([0, 0, 240, 180]));
    assert_eq!(part([1, 1, 2_399, 1_799]), Some([0, 0, 240, 180]));
}

#[test]
fn keeps_no_part_outside_the_file_or_without_a_whole_pixel() {
    let rect = [0, 0, 2_400, 1_800];
    let part = |clip: [i64; 4]| edges_of(rect, clip, (240, 180));
    // A part that starts before the file or ends after it (a start of -0.6, or a size of
    // 240.5), or holds no whole pixel.
    assert_eq!(part([-6, 0, 2_400, 1_800]), None);
    assert_eq!(part([0, 0, 2_405, 1_800]), None);
    assert_eq!(part([100, 0, 104, 1_800]), None);
    assert_eq!(edges_of([0, 0, 0, 1_800], [0, 0, 10, 10], (240, 180)), None);
}

#[test]
fn cuts_the_samples_of_a_part() {
    // A picture of 3 by 2 pixels with one sample each.
    let samples = [1, 2, 3, 4, 5, 6];
    assert_eq!(
        cut(&samples, (3, 2), 1, [1, 0, 3, 2]),
        Some(vec![2, 3, 5, 6])
    );
    assert_eq!(cut(&samples, (3, 2), 1, [0, 1, 1, 2]), Some(vec![4]));
    assert_eq!(cut(&samples, (3, 2), 1, [0, 0, 4, 2]), None);
    assert_eq!(cut(&samples[..4], (3, 2), 1, [0, 0, 3, 2]), None);
}

#[test]
fn reads_a_png_file_within_the_limit_that_it_is_given() {
    // The hand-written file is a PNG file that decodes.
    let small = zero_png(3, 2, 8).unwrap();
    let pixels = decode_file(&small, ImageFormat::Png, MAX_DECODED_BYTES)
        .unwrap()
        .to_rgba8();
    assert_eq!(pixels.dimensions(), (3, 2));
    assert!(pixels.pixels().all(|pixel| pixel.0 == [0; 4]));
    assert_eq!(
        decode_file(&small, ImageFormat::Png, 0).err(),
        Some(ImageFault::Limit)
    );
}

#[test]
fn keeps_a_png_file_whose_pixels_need_more_than_the_writers_limit_with_a_warning() {
    // 8,192 by 16,385 RGBA pixels need 32 KiB more than the writer's limit, and one row fewer
    // fits.
    let (width, height) = (8_192, 16_385);
    let bytes = |rows: u64| u64::from(width) * rows * 4;
    assert!(bytes(u64::from(height)) > MAX_DECODED_BYTES_TO_WRITE_AGAIN);
    assert!(bytes(u64::from(height) - 1) <= MAX_DECODED_BYTES_TO_WRITE_AGAIN);
    let large: Arc<[u8]> = zero_png(width, height, 8).unwrap().into();
    assert_eq!(png_size(&large), Some((8_192, 16_385)));
    // The outputs' smaller limit refuses it too.
    assert_eq!(
        decode_file(&large, ImageFormat::Png, MAX_DECODED_BYTES).err(),
        Some(ImageFault::Limit)
    );
    let list = DisplayList::new(vec![page(vec![picture(&large)])]);
    let mut warnings = Warnings::new();
    let list = super::write_pictures_again(
        list,
        rewriting(None, &|(w, h), _, _| {
            Some(((w / 2, h / 2), Resampler::Filter(COUNT)))
        }),
        &mut warnings,
    );
    assert!(Arc::ptr_eq(&files(&list.pages()[0])[0], &large));
    let format = ImageFormat::Png;
    assert_eq!(
        warnings.into_iter().collect::<Vec<_>>(),
        [(Warning::PictureNotWrittenAgain { format }, 1)]
    );
}

#[test]
fn weights_a_color_by_its_alpha_to_the_nearest_level() {
    let levels = [200 * 128, 255 * 255, 128, 127].map(weighted_level);
    assert_eq!(levels, [100, 255, 1, 0]);
    let pairs = [
        (
            premultiplied(vec![200, 10, 255, 128]),
            vec![100, 5, 128, 128],
        ),
        (
            divided_by_alpha(vec![100, 5, 128, 128]),
            vec![199, 10, 255, 128],
        ),
        (divided_by_alpha(vec![9, 9, 9, 0]), vec![0, 0, 0, 0]),
        // An opaque color keeps its level both ways.
        (
            divided_by_alpha(premultiplied(vec![7, 99, 254, 255])),
            vec![7, 99, 254, 255],
        ),
    ];
    for (got, expected) in pairs {
        assert_eq!(got, expected);
    }
    assert_eq!(divided_by_alpha(vec![1, 0, 0, 1]), vec![255, 0, 0, 1]);
}

/// The colors of a PNG file of RGBA pixels resampled by `png_again` to `size` with `mix`.
fn resampled_rgba(pixels: &image::RgbaImage, size: (usize, usize), mix: AlphaMix) -> Vec<u8> {
    let mut png = std::io::Cursor::new(Vec::new());
    pixels.write_to(&mut png, image::ImageFormat::Png).unwrap();
    let again = png_again(
        png.get_ref(),
        (None, Some((size, Resampler::Filter(COUNT)))),
        mix,
        PictureCrop::VisiblePart,
    )
    .unwrap();
    image::load_from_memory(&again)
        .unwrap()
        .to_rgba8()
        .into_raw()
}

#[test]
fn leaves_the_color_of_a_clear_pixel_out_of_a_weighted_mix() {
    // Red, red and a clear white pixel, resampled to two pixels: the second lies halfway
    // between the second red pixel and the clear one.
    let pixels = image::RgbaImage::from_fn(3, 1, |x, _| match x {
        2 => image::Rgba([255, 255, 255, 0]),
        _ => image::Rgba([255, 0, 0, 255]),
    });
    let plain = resampled_rgba(&pixels, (2, 1), AlphaMix::Plain);
    let weighted = resampled_rgba(&pixels, (2, 1), AlphaMix::Weighted);
    assert_eq!(plain, vec![255, 0, 0, 255, 255, 128, 128, 128]);
    assert_eq!(weighted, vec![255, 0, 0, 255, 255, 0, 0, 128]);
    // A picture that keeps its pixels keeps its colors either way.
    assert_eq!(
        resampled_rgba(&pixels, (3, 1), AlphaMix::Weighted),
        pixels.into_raw()
    );
}

#[test]
fn takes_a_part_of_the_mean_of_the_area_from_the_whole_file_at_its_scale() {
    // A column of 6 grays and its part of rows 1 to 5 written as 2 rows. Cut first, the area
    // mean gives 90 and 210. At the part's scale, the whole column goes to 3 rows (30, 150,
    // 240) and the written rows lie at 0.5 and 1.5 of them: 90 and 195. A part that the linear
    // interpolation resamples is cut first by both crops: 60 and 180.
    let grays = [0u8, 60, 120, 180, 240, 240];
    let pixels = image::RgbImage::from_fn(1, 6, |_, y| image::Rgb([grays[y as usize]; 3]));
    let mut png = std::io::Cursor::new(Vec::new());
    pixels.write_to(&mut png, image::ImageFormat::Png).unwrap();
    let area = LinearLimit::Pixels(std::num::NonZeroU32::new(1).unwrap());
    let written = |limit, crop| {
        let size = Some(((1, 2), Resampler::Filter(limit)));
        let again = png_again(
            png.get_ref(),
            (Some([0, 1, 1, 5]), size),
            AlphaMix::Plain,
            crop,
        );
        let rows = image::load_from_memory(&again.unwrap()).unwrap().to_rgb8();
        rows.pixels().map(|p| p.0[0]).collect::<Vec<_>>()
    };
    assert_eq!(written(area, PictureCrop::VisiblePart), vec![90, 210]);
    assert_eq!(
        written(area, PictureCrop::VisiblePartAtScale),
        vec![90, 195]
    );
    for crop in [PictureCrop::VisiblePart, PictureCrop::VisiblePartAtScale] {
        assert_eq!(written(COUNT, crop), vec![60, 180], "{crop:?}");
    }
}

/// A PNG file of 64 by 32 RGB pixels: noise from a fixed sequence, or one gray.
fn rgb_png(noisy: bool) -> Arc<[u8]> {
    band_png((64, 32), if noisy { 32 } else { 0 })
}

/// A PNG file of RGB pixels of `size`: noise from a fixed sequence in its first `rows` rows, and
/// one gray below them.
fn band_png(size: (u32, u32), rows: u32) -> Arc<[u8]> {
    let mut state = 12_345_u32;
    let image = image::RgbImage::from_fn(size.0, size.1, |_, y| {
        if y >= rows {
            return image::Rgb([128, 128, 128]);
        }
        state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
        let [red, green, blue, _] = state.to_be_bytes();
        image::Rgb([red, green, blue])
    });
    let mut png = Vec::new();
    image
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .unwrap();
    png.into()
}

#[test]
fn writes_an_opaque_png_picture_as_jpeg_below_its_share_of_the_color_under_flate() {
    let (noisy, flat, transparent) = (rgb_png(true), rgb_png(false), png_file());
    let list = DisplayList::new(vec![page(vec![
        picture(&noisy),
        picture(&flat),
        picture(&transparent),
    ])]);
    let share = |thousandths| Rewriting {
        jpeg_share: f_office_paint::JpegShare::new(thousandths),
        ..rewriting(f_office_paint::JpegQuality::new(75), &|_, _, _| None)
    };
    let formats = |list: &DisplayList| -> Vec<ImageFormat> {
        list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Image(image) => Some(image.image.format),
                _ => None,
            })
            .collect()
    };
    // Noise of 64 by 32 pixels takes about 6 KB under Flate and less than a third of that as a
    // quality-75 JPEG file; one gray takes far less under Flate than any JPEG file.
    let written = write_pictures_again(list.clone(), share(380));
    assert_eq!(
        formats(&written),
        [ImageFormat::Jpeg, ImageFormat::Png, ImageFormat::Png]
    );
    assert_eq!(files(&written.pages()[0])[1], flat);
    assert_eq!(files(&written.pages()[0])[2], transparent);
    // A share too small for the noise's JPEG file keeps it lossless.
    let kept = write_pictures_again(list, share(1));
    assert_eq!(files(&kept.pages()[0])[0], noisy);
}

#[test]
fn keeps_a_picture_lossless_when_its_sample_falls_below_the_second_test() {
    // Noise in the first 32 of 128 rows of a picture 120 pixels wide: its quality-75 JPEG file
    // is far below 0.38 of its color under Flate, and its sample, four strips of noise, gives an
    // estimate of about 11.5 KB, the whole color's own size under Flate.
    let band = band_png((120, 128), 32);
    let list = DisplayList::new(vec![page(vec![picture(&band)])]);
    let tests = |floor| Rewriting {
        jpeg_share: f_office_paint::JpegShare::new(380),
        jpeg_sample: f_office_paint::JpegSample::new(535, floor, 500),
        ..rewriting(f_office_paint::JpegQuality::new(75), &|_, _, _| None)
    };
    let format = |list: &DisplayList| match list.pages()[0].items().first() {
        Some(Item::Image(image)) => Some(image.image.format),
        _ => None,
    };
    let lossless = write_pictures_again(list.clone(), tests(21_382));
    assert_eq!(format(&lossless), Some(ImageFormat::Png));
    assert_eq!(files(&lossless.pages()[0])[0], band);
    let jpeg = write_pictures_again(list.clone(), tests(1));
    assert_eq!(format(&jpeg), Some(ImageFormat::Jpeg));
    let first_alone = write_pictures_again(
        list,
        Rewriting {
            jpeg_sample: None,
            ..tests(1)
        },
    );
    assert_eq!(format(&first_alone), Some(ImageFormat::Jpeg));
}

#[test]
fn the_strips_of_the_sample_start_at_sixteenths_of_the_height() {
    let starts = |height| {
        f_office_paint::JpegSample::strips(height)
            .map(|rows| (rows.start, rows.end))
            .collect::<Vec<_>>()
    };
    let tall = starts(320);
    assert_eq!(tall.len(), 16);
    assert_eq!(tall[1], (20, 28));
    assert_eq!(tall[15], (300, 308));
    // A picture below 128 rows has strips that overlap, and the last one ends at its bottom.
    let short = starts(40);
    assert_eq!(short[1], (2, 10));
    assert_eq!(short[15], (37, 40));
}

#[derive(Debug)]
struct CountingImageLoader {
    bytes: Arc<[u8]>,
    full_loads: std::sync::atomic::AtomicUsize,
    prefix_loads: std::sync::atomic::AtomicUsize,
}

impl f_office_paint::ImageLoader for CountingImageLoader {
    fn load(&self, _index: u32) -> Option<Arc<[u8]>> {
        self.full_loads
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Some(Arc::clone(&self.bytes))
    }

    fn load_prefix(&self, _index: u32, max_bytes: usize) -> Option<Arc<[u8]>> {
        self.prefix_loads
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let len = self.bytes.len().min(max_bytes);
        Some(Arc::from(&self.bytes[..len]))
    }
}

#[test]
fn lazy_images_defer_full_load_and_rewriting_until_requested() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use f_office_paint::{Image, ImageId, ImageLoader, ImageRef, next_store_id};

    let fine = jpeg_file();
    let loader = Arc::new(CountingImageLoader {
        bytes: Arc::clone(&fine),
        full_loads: AtomicUsize::new(0),
        prefix_loads: AtomicUsize::new(0),
    });
    let handle = ImageRef::new(
        ImageId::new(next_store_id(), 0),
        fine.len() as u64,
        Arc::clone(&loader) as Arc<dyn ImageLoader>,
    );
    let lazy_item = Item::Image(ImageItem {
        x: Length::ZERO,
        y: Length::ZERO,
        width: Length::from_units(100),
        height: Length::from_units(100),
        clip: None,
        turn: None,
        image: Image::from_ref(ImageFormat::Jpeg, handle),
    });
    let (rewritten, warnings) = write_jpegs_again(
        DisplayList::new(vec![page(vec![lazy_item.clone()]), page(vec![lazy_item])]),
        75,
    );
    assert_eq!(
        (
            warnings.is_empty(),
            loader.full_loads.load(Ordering::SeqCst),
            loader.prefix_loads.load(Ordering::SeqCst),
        ),
        (true, 0, 1)
    );
    let [first, second] = [0, 1].map(|page_idx| match &rewritten.pages()[page_idx].items()[0] {
        Item::Image(item) => item,
        _ => panic!("expected image"),
    });
    assert_eq!(
        (
            first.image.data.is_lazy(),
            first.image.cache_key() == second.image.cache_key()
        ),
        (true, true)
    );
    let (bytes1, fmt1) = first.image.load_bytes_with_format().unwrap();
    let (bytes2, fmt2) = second.image.load_bytes_with_format().unwrap();
    assert_eq!(
        (
            fmt1,
            fmt2,
            loader.full_loads.load(Ordering::SeqCst),
            Arc::ptr_eq(&bytes1, &bytes2),
            coefficients(&bytes1, MAX_DECODED_BYTES).unwrap()[0].table[0],
        ),
        (ImageFormat::Jpeg, ImageFormat::Jpeg, 1, true, 8)
    );
}

#[test]
fn lazy_cropped_cmyk_jpeg_keeps_clip_and_emits_warning() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use f_office_paint::{Clip, Image, ImageId, ImageLoader, ImageRef, JpegQuality, next_store_id};

    // Minimal valid 4-component (CMYK) SOF2 JPEG header (100x80 pixels).
    let cmyk_header: Arc<[u8]> = Arc::from(
        [
            0xFF, 0xD8, // SOI
            0xFF, 0xC2, 0x00, 0x14, // SOF2, length 20
            0x08, // 8-bit precision
            0x00, 0x50, // height = 80
            0x00, 0x64, // width = 100
            0x04, // 4 components (CMYK)
            1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0, 4, 0x11, 0, // 4 components
            0xFF, 0xD9, // EOI
        ]
        .as_slice(),
    );
    let loader = Arc::new(CountingImageLoader {
        bytes: Arc::clone(&cmyk_header),
        full_loads: AtomicUsize::new(0),
        prefix_loads: AtomicUsize::new(0),
    });
    let handle = ImageRef::new(
        ImageId::new(next_store_id(), 0),
        cmyk_header.len() as u64,
        Arc::clone(&loader) as Arc<dyn ImageLoader>,
    );
    let clip = Clip {
        x: Length::from_units(10),
        y: Length::from_units(10),
        width: Length::from_units(50),
        height: Length::from_units(40),
    };
    let lazy_item = Item::Image(ImageItem {
        x: Length::ZERO,
        y: Length::ZERO,
        width: Length::from_units(100),
        height: Length::from_units(80),
        clip: Some(clip),
        turn: None,
        image: Image::from_ref(ImageFormat::Jpeg, handle),
    });
    let mut warnings = Warnings::new();
    let rewritten = super::write_pictures_again(
        DisplayList::new(vec![page(vec![lazy_item])]),
        Rewriting {
            quality: Some(JpegQuality::new(75).unwrap()),
            jpeg_share: None,
            jpeg_sample: None,
            crop: PictureCrop::VisiblePart,
            alpha_mix: AlphaMix::Plain,
            resampling: &|_, _, _| None,
        },
        &mut warnings,
    );
    let Item::Image(out) = &rewritten.pages()[0].items()[0] else {
        panic!("expected image");
    };
    assert_eq!(out.clip, Some(clip));
    assert_eq!(out.width, Length::from_units(100));
    assert_eq!(out.height, Length::from_units(80));
    assert_eq!(warnings.len(), 1);
    assert_eq!(loader.full_loads.load(Ordering::SeqCst), 0);
}