f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
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
use f_office_fonts::SymbolFont;
use f_office_paint::paper_forms::{DocumentedSide, PaperForm, page_entry};
use f_office_paint::{Orientation, PictureCrop};

use super::{
    Decimal, Error, Facts, Layer, Merged, OffOr, Overrides, Profile, Section, Setting, Target,
    WriterTable,
};
use crate::configuration::{Configuration, NumberSeparators};
use crate::grid::DOT;
use f_office_units::Length;

/// What each target's built-in configuration says, base first: its ID, the
/// profile that it inherits from, the page side that its writer gives an A4 page's width,
/// 210 mm (15,120,000 units), in units, and one dot of its layout device in units.
const TARGETS: [(&str, Option<&str>, i64, i64); 3] = [
    ("word-mac", None, 2480 * DOT, DOT),
    (
        "word-web",
        Some("word-mac"),
        2381 * Length::UNITS_PER_POINT / 4,
        Length::UNITS_PER_POINT / 4,
    ),
    (
        "word-win",
        Some("word-mac"),
        4961 * Length::UNITS_PER_INCH / 600,
        Length::UNITS_PER_INCH / 600,
    ),
];

#[test]
fn reads_every_target_and_its_profile() {
    assert_eq!(Target::all().count(), TARGETS.len());
    for (target, row) in Target::all().zip(TARGETS) {
        check_target(target, row);
    }
}

#[test]
fn written_width_source_uses_the_evidenced_font_path() {
    use crate::quirks::WrittenWidths::{HintedAdvanceAt1000, RoundsAdvance};
    for (target, expected) in [
        ("word-mac", RoundsAdvance),
        ("word-web", HintedAdvanceAt1000),
        ("word-win", HintedAdvanceAt1000),
    ] {
        assert_eq!(
            Profile::of(target.parse().unwrap())
                .unwrap()
                .quirks()
                .written_widths,
            expected
        );
    }
}

#[test]
fn writer_adjustment_count_is_the_targets() {
    use crate::quirks::WriterAdjustments::{ExactIdeal, SingleCount, TwoSums};
    for (target, expected) in [
        ("word-mac", ExactIdeal),
        ("word-web", SingleCount),
        ("word-win", TwoSums),
    ] {
        assert_eq!(
            Profile::of(target.parse().unwrap())
                .unwrap()
                .quirks()
                .writer_adjustments,
            expected
        );
    }
}

/// Checks one target against its row of [`TARGETS`].
fn check_target(target: Target, (id, inherits, a4_width, dot): (&str, Option<&str>, i64, i64)) {
    assert_eq!(target.to_string(), id);
    assert_eq!(id.parse::<Target>(), Ok(target));
    let profile = Profile::of(target).unwrap();
    assert!(profile.to_string().starts_with(&format!("{id} 1 (")));
    let width = profile.writer().page_side(Length::from_units(15_120_000));
    assert_eq!(width.units(), a4_width, "{id}");
    assert_eq!(profile.device().dots(1).units(), dot, "{id}");
    let facts = Facts::of(target).unwrap();
    assert_eq!(
        (facts.id.as_str(), facts.inherits.as_deref()),
        (id, inherits)
    );
}

#[test]
fn writes_jpeg_pictures_again_only_where_the_writer_does() {
    // Word for Windows and Word for the web write every JPEG picture again at quality 75; Word
    // for Mac keeps the files.
    let quality = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .jpeg_quality()
            .map(f_office_paint::JpegQuality::get)
    };
    assert_eq!(quality("word-win"), Some(75));
    assert_eq!(quality("word-web"), Some(75));
    assert_eq!(quality("word-mac"), None);
}

#[test]
fn resamples_dense_pictures_only_where_the_writer_does() {
    // Word for Windows writes a picture at 275 ppi or denser with the most pixels below 200
    // ppi, and Word for the web one at 450 ppi or denser with the most below 300 ppi; Word for
    // Mac keeps the pixels.
    let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
    let size = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .resampled_size((600, 450), (points(108), points(81)), None)
            .map(|(pixels, _)| pixels)
    };
    assert_eq!(size("word-win"), Some((299, 224)));
    assert_eq!(size("word-web"), None);
    assert_eq!(size("word-mac"), None);
    let dense = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .resampled_size((900, 675), (points(108), points(81)), None)
            .map(|(pixels, _)| pixels)
    };
    assert_eq!(dense("word-web"), Some((449, 337)));
    assert_eq!(dense("word-mac"), None);
}

#[test]
fn keeps_palette_pictures_to_limits_of_their_own_only_where_the_writer_does() {
    // Word for Windows keeps a 1-bit palette of 1.5 by 1.125 inches at 749 ppi and resamples
    // it at 750 ppi to the most pixels below 600 ppi, each the pixel under its centre; Word for
    // the web and Word for Mac have no palette density.
    let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
    let one_bit = Some(f_office_paint::PaletteClass::OneBit);
    let size = |id: &str, pixels| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .resampled_size(pixels, (points(108), points(81)), one_bit)
    };
    let centre = f_office_paint::Resampler::CentrePixel;
    assert_eq!(size("word-win", (1_124, 842)), None);
    assert_eq!(size("word-win", (1_125, 844)), Some(((899, 674), centre)));
    let count = std::num::NonZeroU32::new(1 << 17).unwrap();
    let filter = f_office_paint::Resampler::Filter(f_office_paint::LinearLimit::Pixels(count));
    assert_eq!(size("word-web", (1_125, 844)), Some(((449, 337), filter)));
    assert_eq!(size("word-mac", (1_125, 844)), None);
}

#[test]
fn writes_baselines_with_five_significant_digits_where_the_writer_does() {
    // Word for Windows and Word for the web write a baseline's distance from the page's foot
    // with five significant digits; Word for Mac's PDFs keep the layout's place.
    let digits = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .digits()
            .map(std::num::NonZeroU32::get)
    };
    assert_eq!(digits("word-win"), Some(5));
    assert_eq!(digits("word-web"), Some(5));
    assert_eq!(digits("word-mac"), None);
    // Only Word for Windows holds a rectangle's edges on its steps of 1/3000 inch and writes
    // the width and height as their differences.
    let steps = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .rectangle_steps()
            .map(std::num::NonZeroU32::get)
    };
    assert_eq!(steps("word-win"), Some(3_000));
    assert_eq!(steps("word-web"), None);
    assert_eq!(steps("word-mac"), None);
}

#[test]
fn counts_baseline_steps_where_the_writer_does() {
    // Only Word for the web holds a glyph's baseline as its count of steps of 1/2880 inch,
    // converted to points in single precision.
    let baseline_steps = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .baseline_steps()
            .map(std::num::NonZeroU32::get)
    };
    assert_eq!(baseline_steps("word-web"), Some(2_880));
    assert_eq!(baseline_steps("word-win"), None);
    assert_eq!(baseline_steps("word-mac"), None);
}

#[test]
fn keeps_two_decimals_where_the_writer_does() {
    // Word for Windows and Word for the web keep at least two decimals, which matters from
    // 1,000 pt; Word for Mac's writer has no digits.
    let least = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .least_decimals()
    };
    assert_eq!(least("word-win"), 2);
    assert_eq!(least("word-web"), 2);
    assert_eq!(least("word-mac"), 0);
}

#[test]
fn writes_cropped_pictures_as_their_visible_part_only_where_the_writer_does() {
    // Word for Windows and Word for the web write only the visible part's pixels, Word for
    // Windows a part of the mean of the area at its scale; Word for Mac draws the whole file
    // under a clip.
    let crop = |id: &str| {
        Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .picture_crop()
    };
    assert_eq!(crop("word-win"), PictureCrop::VisiblePartAtScale);
    assert_eq!(crop("word-web"), PictureCrop::VisiblePart);
    assert_eq!(crop("word-mac"), PictureCrop::WholeFileUnderClip);
}

#[test]
fn counts_stretch_steps_with_factors_only_where_the_writer_does() {
    // Word for the web counts its stretch steps with a factor of each measured page height and
    // an offset of 0.031 steps; Word for Mac and Word for Windows have neither.
    let writer = |id: &str| Profile::of(id.parse().unwrap()).unwrap().writer();
    let without = |id: &str| writer(id).with_stretch_factors((0, 1), &[]).unwrap();
    assert_ne!(writer("word-web"), without("word-web"));
    assert_eq!(writer("word-mac"), without("word-mac"));
    assert_eq!(writer("word-win"), without("word-win"));
}

#[test]
fn reads_a_decimal_number_as_a_fraction() {
    use super::decimal_fraction;
    assert_eq!(decimal_fraction("0.031"), Some((31, 1000)));
    assert_eq!(decimal_fraction("-2"), Some((-2, 1)));
    assert_eq!(decimal_fraction("1.018640"), Some((1_018_640, 1_000_000)));
    for text in ["", ".5", "1.2.3", "x", "1e3"] {
        assert_eq!(decimal_fraction(text), None, "{text}");
    }
}

#[test]
fn reads_the_stretch_factors_of_written_page_heights() {
    use super::stretch_factors;
    let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
    assert_eq!(
        stretch_factors("792 1.003165, 841.75 1"),
        Ok(vec![
            (points(792), (1_003_165, 1_000_000)),
            (Length::from_units(21_380_450), (1, 1)),
        ])
    );
    assert_eq!(stretch_factors(""), Ok(Vec::new()));
    let key = Error::Value("stretch_factors");
    for list in ["792", "792 1 2", "0 1", "792 -1", "0.00001 1"] {
        assert_eq!(stretch_factors(list), Err(key.clone()), "{list}");
    }
}

/// The offset of a text object's start in the profile of `id`.
fn start_offset(id: &str) -> f_office_paint::WriterOffset {
    match Profile::of(id.parse().unwrap())
        .unwrap()
        .device()
        .advances()
    {
        crate::grid::Advances::RightEdge { start, .. } => start,
        crate::grid::Advances::PdfSteps => f_office_paint::WriterOffset::NONE,
    }
}

/// The steps of the page form of an offset, and the parts of a step in which it rounds first.
fn page_steps(offset: f_office_paint::Offset) -> (f_office_paint::Fraction, i64) {
    match offset {
        f_office_paint::Offset::Page { steps, parts, .. } => (steps, parts),
        _ => ((0, 1), 0),
    }
}

/// A side of `dots` written dots of 1/600 inch in half-EMUs.
const fn written_side(dots: i64) -> i64 {
    dots * DOT / 2
}

const LETTER: PaperForm = PaperForm::inches("Letter", 8_500, 11_000);
const A3: PaperForm = PaperForm::millimetres("A3", 297, 420);
const A4: PaperForm = PaperForm::millimetres("A4", 210, 297);

/// The steps of the page entry of a side of `dots` written dots of the documented form side
/// `side`, for Word for Windows's writer: 16 parts of a step, 3,000 steps and 600 dots to the
/// inch.
fn entry_steps(dots: i64, side: DocumentedSide) -> f_office_paint::Fraction {
    let writer = (16, 3_000, 600);
    let entry = page_entry(dots, side.form_side(600), writer).unwrap();
    f_office_paint::paper_forms::entry_steps(entry, dots, writer).unwrap()
}

#[test]
fn gives_two_sizes_near_a4_the_entries_that_word_s_lines_fit() {
    // With the product of the dot and the page entry held in binary32, the class rule gives a
    // page of 4,961 by 7,017 and one of 4,958 by 7,017 written dots the page entries of the
    // factors that Word's lines fit there: 4.72645 and 5.08057 across, 5.00296 down.
    let windows = start_offset("word-win");
    let entry = |((count, per), parts): (f_office_paint::Fraction, i64), dots: i64| {
        let (count, per, parts, dots) = (
            i128::from(count),
            i128::from(per),
            i128::from(parts),
            i128::from(dots),
        );
        f_office_units::binary32::Binary32::nearest(parts * (5 * dots * per + count), dots * per)
    };
    let fit = |count| ((count, 100_000), 16);
    for ((width, height), (across, down)) in [
        ((4_961, 7_017), (472_645, 500_296)),
        ((4_958, 7_017), (508_057, 500_296)),
    ] {
        let (on_across, on_down) = windows.on_page(
            written_side(width),
            written_side(height),
            Orientation::Portrait,
        );
        assert_eq!(
            entry(page_steps(on_across), width),
            entry(fit(across), width)
        );
        assert_eq!(entry(page_steps(on_down), height), entry(fit(down), height));
    }
}

#[test]
fn gives_measured_sizes_their_steps_in_their_orientation() {
    // Word for Windows's writer gives a page of a measured size, in the orientation of its
    // sections, the steps of that size, each rounded in sixteenths of a step first.
    let windows = start_offset("word-win");
    let on_page = |(width, height), orientation| {
        let (across, down) =
            windows.on_page(written_side(width), written_side(height), orientation);
        (page_steps(across), page_steps(down))
    };
    let steps = |count| ((count, 100_000), 16);
    let (dots, (across, down)) = crate::params::PAGE_4961_7016_STEPS;
    assert_eq!(dots, (4_961, 7_016));
    assert_eq!(
        on_page(dots, Orientation::Portrait),
        (steps(across), steps(down))
    );
    let (dots, (across, down)) = crate::params::PAGE_7016_4961_STEPS;
    assert_eq!(dots, (7_016, 4_961));
    assert_eq!(
        on_page(dots, Orientation::Landscape),
        (steps(across), steps(down))
    );
    // A page of A4 across in a portrait section takes A3's entries, the class rule's form.
    let a3 = |dots, side| (entry_steps(dots, side), 16);
    let (across, down) = (A3.across, A3.down);
    assert_eq!(
        on_page((7_016, 4_961), Orientation::Portrait),
        (a3(7_016, across), a3(4_961, down))
    );
    assert_eq!(
        on_page((7_016, 9_921), Orientation::Portrait),
        (a3(7_016, across), a3(9_921, down))
    );
}

#[test]
fn gives_every_other_page_the_entries_of_its_paper_form() {
    // A page one dot off A4 takes A4's entries, across and down, not Letter's factor.
    let windows = start_offset("word-win");
    let (across, down) = windows.on_page(
        written_side(4_962),
        written_side(7_014),
        Orientation::Portrait,
    );
    assert_eq!(page_steps(across), (entry_steps(4_962, A4.across), 16));
    assert_eq!(page_steps(down), (entry_steps(7_014, A4.down), 16));
    assert_ne!(page_steps(across).0, (473_073, 100_000));
}

#[test]
fn gives_a_letter_page_its_own_steps_across_and_letters_factor_down() {
    // Word for Windows gives a Letter page the steps 4.72515 across and Letter's factor, the
    // configuration's, down, in every orientation. Letter across keeps Letter's factor across;
    // down, it takes the steps across a Letter page in a landscape section, and the entry of its
    // paper form, A3's, in a portrait section, which takes no rotated form.
    let windows = start_offset("word-win");
    let letter = (473_073, 100_000);
    let a3_down = entry_steps(5_100, A3.down);
    for (orientation, down) in [
        (Orientation::Portrait, a3_down),
        (Orientation::Landscape, (472_515, 100_000)),
    ] {
        let on_page = |width, height| {
            let (across, down) =
                windows.on_page(written_side(width), written_side(height), orientation);
            (page_steps(across).0, page_steps(down).0)
        };
        assert_eq!(on_page(5_100, 6_600), ((472_515, 100_000), letter));
        assert_eq!(on_page(6_600, 5_100), (letter, down));
    }
}

#[test]
fn holds_the_drivers_papers_and_the_documented_rotated_forms() {
    // The 84 papers of the driver and the 23 forms that the `DEVMODE` documentation names
    // rotated, each name once; exactly the rotated forms are landscape forms, and they come last.
    let forms = crate::params::PAPER_FORMS;
    assert_eq!(forms.len(), 107);
    let first_rotated = forms
        .iter()
        .position(|form| form.orientation == Orientation::Landscape);
    assert_eq!(first_rotated, Some(84));
    let names: std::collections::BTreeSet<&str> = forms.iter().map(|form| form.name).collect();
    assert_eq!(names.len(), forms.len());
    for form in forms {
        let rotated = form.orientation == Orientation::Landscape;
        assert_eq!(rotated, form.name.ends_with("_ROTATED"), "{}", form.name);
    }
    let rule = crate::params::PAPER_FORM_CLASS_RULE;
    assert_eq!((forms.first(), rule.last), (Some(&LETTER), LETTER));
    assert_eq!(rule.holding, [A4, A3]);
}

#[test]
fn offsets_the_starts_of_win_starts_by_the_steps_of_words_pages() {
    // Across a Letter page, the dot 1,585 takes one step of 1/3000 inch (610 half-EMUs) and
    // the dot 1,586 two (1,219); across a page of 4,961 by 7,016 dots, the dot 1,540 takes one
    // step and the dot 1,544 two.
    let windows = start_offset("word-win");
    let across = |(width, height): (i64, i64), dot: i64| {
        let portrait = Orientation::Portrait;
        let (offset, _) = windows.on_page(written_side(width), written_side(height), portrait);
        offset.of(written_side(dot), written_side(width))
    };
    assert_eq!(across((5_100, 6_600), 1_585), 610);
    assert_eq!(across((5_100, 6_600), 1_586), 1_219);
    assert_eq!(across((4_961, 7_016), 1_540), 610);
    assert_eq!(across((4_961, 7_016), 1_544), 1_219);
}

#[test]
fn gives_measured_sizes_only_in_the_profile_of_word_win() {
    // Only Word for Windows's writer writes places in steps of the page form that depend on
    // the page's size.
    let sizes = |id| matches!(start_offset(id), f_office_paint::WriterOffset::Sizes(_));
    assert_eq!(
        ["word-win", "word-mac", "word-web"].map(sizes),
        [true, false, false]
    );
}

#[test]
fn gives_each_writer_its_linear_limit() {
    // Word for Windows resamples by the linear interpolation up to a side of 419 source pixels;
    // the other targets keep the limit of 2^17 source pixels.
    let inch = Length::from_units(Length::UNITS_PER_INCH);
    let limit = |id: &str| {
        let answer = Profile::of(id.parse().unwrap())
            .unwrap()
            .writer()
            .resampled_size((600, 600), (inch, inch), None);
        match answer {
            Some((_, f_office_paint::Resampler::Filter(limit))) => Some(limit),
            _ => None,
        }
    };
    let count = |n| std::num::NonZeroU32::new(n).unwrap();
    assert_eq!(
        limit("word-win"),
        Some(f_office_paint::LinearLimit::Side(count(419)))
    );
    assert_eq!(
        limit("word-web"),
        Some(f_office_paint::LinearLimit::Pixels(count(1 << 17)))
    );
}

#[test]
fn sets_a_quirk_in_place_of_the_profiles_own() {
    use crate::quirks::Markup;
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        // The profile's own variant gives the same quirks, device, writer and reader.
        let own = profile.quirks().markup;
        let same = profile.with_variant(own);
        assert_eq!(same.quirks(), profile.quirks());
        assert_eq!(same.device(), profile.device());
        assert_eq!(same.writer(), profile.writer());
        assert_eq!(same.reader_settings(), profile.reader_settings());
        let other = [Markup::PrintsMarkupArea, Markup::PrintsNoMarkup]
            .into_iter()
            .find(|markup| *markup != own)
            .unwrap();
        assert_eq!(profile.with_variant(other).quirks().markup, other);
    }
}

#[test]
fn lists_the_variant_that_each_target_takes_of_every_quirk() {
    let facts = Facts::all().unwrap();
    let own = |id: &str| -> std::collections::BTreeMap<&str, &str> {
        facts
            .iter()
            .filter(|fact| fact.id == id)
            .flat_map(|fact| &fact.entries)
            .filter(|(entry, _)| entry.section == Section::Quirks)
            .map(|(entry, _)| (entry.name.as_str(), entry.value.as_str()))
            .collect()
    };
    for fact in &facts {
        let variants = Profile::of(fact.id.parse().unwrap()).unwrap().variants();
        let quirks: Vec<_> = variants.iter().map(|(quirk, _)| *quirk).collect();
        assert_eq!(quirks, crate::quirks::NAMES, "{}", fact.id);
        let mut written = fact.inherits.as_deref().map_or_default(own);
        written.extend(own(&fact.id));
        assert_eq!(
            variants
                .into_iter()
                .collect::<std::collections::BTreeMap<_, _>>(),
            written
        );
    }
}

#[test]
fn says_whether_a_target_takes_a_variant_named_by_its_quirk() {
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        for (quirk, variant) in profile.variants() {
            let taken = format!("{quirk}::{variant}");
            assert_eq!(profile.chooses(&taken), Some(true), "{taken}");
        }
        assert_eq!(profile.chooses("Markup::Never"), None);
        assert_eq!(profile.chooses("Never::PrintsNoMarkup"), None);
        assert_eq!(profile.chooses("Markup"), None);
    }
    let win = Profile::of("word-win".parse().unwrap()).unwrap();
    assert_eq!(win.chooses("Markup::PrintsMarkupArea"), Some(false));
}

/// A layer read from its JSON form.
fn layer(json: &str) -> Layer {
    serde_json::from_str(json).unwrap()
}

/// The writer's table of a layer whose `writer` table is `json`.
fn writer_table(json: &str) -> WriterTable {
    layer(&format!(r#"{{"writer":{json}}}"#)).writer
}

/// A setting whose value is written `written` in JSON, or the reader's error.
fn setting<T: serde::de::DeserializeOwned>(written: &str) -> Result<Setting<T>, String> {
    serde_json::from_str(&format!(r#"{{"value":{written}}}"#)).map_err(|e| e.to_string())
}

/// The profile of the target `id` with the configuration's values `configuration` over the
/// target's defaults and the override's layer `overrides`, named `test`, both in JSON; `{}` for
/// an override sets no layer.
fn resolved(id: &str, configuration: &str, overrides: &str) -> Result<Profile, Error> {
    let mut chosen = Configuration::of(id.parse().unwrap());
    chosen.merge(&serde_json::from_str(configuration).unwrap(), &mut |_| {});
    let overrides = if overrides == "{}" {
        Overrides::default()
    } else {
        Overrides::default().with_layer("test", layer(overrides))
    };
    Profile::resolve(&chosen, &overrides)
}

/// The profile of the target `id` with the override's layer `json`, named `test`.
fn with(id: &str, json: &str) -> Result<Profile, Error> {
    resolved(id, "{}", json)
}

/// The profile of the target `id` with the configuration's values `json`.
fn configured(id: &str, json: &str) -> Result<Profile, Error> {
    resolved(id, json, "{}")
}

#[test]
fn names_a_font_environment_for_each_target() {
    // Each target names its own font environment, in the folder of the profiles.
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        assert_eq!(
            profile.font_environment_path(),
            format!("fonts/{target}.toml")
        );
        assert_eq!(
            profile.origin("fonts.environment"),
            Some(target.to_string().as_str())
        );
        // The library holds the font environment for the font choice, made once in a process.
        let environment = profile.font_environment();
        assert_ne!(environment.faces(), []);
        assert!(std::ptr::eq(
            environment,
            Profile::of(target).unwrap().font_environment()
        ));
    }
}

#[test]
fn keeps_each_font_environment_as_its_table_writes_it() {
    // So the tool that writes the own faces changes only what its inputs change.
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        let table = super::environment_table(profile.font_environment_path()).unwrap();
        // The symbol fonts' widths are no part of the environment and stay with the table.
        let mut written = super::fonts::table(profile.font_environment());
        written.symbol_font.clone_from(&table.symbol_font);
        assert!(written == *table, "{target}");
    }
}

#[test]
fn keeps_whole_widths_of_symbol_fonts_in_each_font_environment() {
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        let table = super::environment_table(profile.font_environment_path()).unwrap();
        for (family, entry) in &table.symbol_font {
            let place = format!("{target}: {family}");
            assert!(SymbolFont::of(family).is_some(), "{place}");
            assert!(entry.units_per_em.is_some_and(|units| units > 0), "{place}");
            check_symbol_codes(&place, entry);
        }
    }
}

/// Checks that each code of a symbol font's widths is a code of its private use form or the
/// missing glyph, and that the widths hold the missing glyph.
fn check_symbol_keys(place: &str, entry: &super::fonts::SymbolFontEntry) {
    let missing = super::fonts::SymbolFontEntry::MISSING_GLYPH;
    let private_use = |key: &String| {
        key == missing
            || u32::from_str_radix(key, 16).is_ok_and(|code| (0xF020..=0xF0FF).contains(&code))
    };
    assert!(entry.advance.keys().all(private_use), "{place}");
    assert!(entry.advance.contains_key(missing), "{place}");
}

/// Checks the keys of a symbol font's widths ([`check_symbol_keys`]), and that each list of
/// sizes rises within the measured sizes, with no size both wider and narrower.
fn check_symbol_codes(place: &str, entry: &super::fonts::SymbolFontEntry) {
    let most = entry.measured_sizes.unwrap_or(0);
    check_symbol_keys(place, entry);
    for (key, sizes) in entry.wider.iter().chain(&entry.narrower) {
        assert!(entry.advance.contains_key(key), "{place} {key}");
        assert!(
            sizes.windows(2).all(|pair| pair[0] < pair[1]),
            "{place} {key}"
        );
        assert!(
            sizes.iter().all(|&size| (1..=most).contains(&size)),
            "{place} {key}"
        );
    }
    for (key, sizes) in &entry.wider {
        let narrower = entry.narrower.get(key).map_or(&[][..], Vec::as_slice);
        assert!(
            sizes.iter().all(|size| !narrower.contains(size)),
            "{place} {key}"
        );
    }
}

#[test]
fn takes_the_widths_of_a_symbol_font_of_a_later_layer_as_one_value() {
    let mut own: super::fonts::Table = serde_json::from_str(
        r#"{"symbol_font": {"Symbol": {"units_per_em": 2048, "advance": {"F020": 512, "F041": 1479}, "wider": {"F041": [57]}}}}"#,
    )
    .unwrap();
    let later: super::fonts::Table = serde_json::from_str(
        r#"{"symbol_font": {"Symbol": {"units_per_em": 1000, "advance": {"F041": 700}}}}"#,
    )
    .unwrap();
    let mut paths = Vec::new();
    own.merge(&later, &mut |path| paths.push(path.join(".")));
    assert_eq!(own.symbol_font, later.symbol_font);
    assert_eq!(paths, ["symbol_font.Symbol"]);
}

#[test]
fn names_the_base_target_as_the_default() {
    let base = Target::all().next().unwrap();
    assert_eq!(Target::base(), base);
    assert_eq!(Target::default().to_string(), "word-win");
    let unknown = "word-ios".parse::<Target>().unwrap_err();
    assert_eq!(unknown, Error::UnknownTarget("word-ios".to_owned()));
    assert_eq!(unknown.to_string(), "no target is named \"word-ios\"");
}

#[test]
fn lists_each_value_with_the_value_that_it_overrides() {
    let facts = Facts::all().unwrap();
    let base = &facts[0];
    assert!(
        base.entries
            .iter()
            .all(|(_, overridden)| overridden.is_none())
    );
    let web = &facts[1];
    let (entry, overridden) = web
        .entries
        .iter()
        .find(|(entry, _)| entry.name == "page_steps_per_inch")
        .unwrap();
    assert_eq!(
        (entry.section, entry.value.as_str(), overridden.as_deref()),
        (Section::Writer, "288", Some("300"))
    );
}

#[test]
fn lists_the_entries_of_a_layer_as_written() {
    let entries = super::facts::entries(&layer(
        r#"{"quirks":{"DescentRounding":{"value":"TruncateToTwips"}},
            "writer":{"digits":{"value":5},"offset":{"value":"off"}}}"#,
    ));
    let entries: Vec<_> = entries
        .iter()
        .map(|e| (e.section, e.name.as_str(), e.value.as_str()))
        .collect();
    assert_eq!(
        entries,
        [
            (Section::Writer, "digits", "5"),
            (Section::Writer, "offset", "\"off\""),
            (Section::Quirks, "DescentRounding", "TruncateToTwips"),
        ]
    );
}

#[test]
fn takes_an_added_family_as_present_for_every_use_of_the_font_environment() {
    // `word-win` lacks Andalus, which Word draws with Arial and whose metafile fonts of the
    // character set 0 the mapper gives to Arial. A configuration that installs Andalus, as Word
    // has the family once it is installed, makes it present for each of the three.
    let built_in = Profile::of("word-win".parse().unwrap()).unwrap();
    let fonts = built_in.font_environment();
    assert!(fonts.lacks("Andalus"));
    assert_eq!(fonts.family_substitute("Andalus"), Some("Arial"));
    assert_eq!(fonts.metafile_face("Andalus", 0, 0), Some("Arial"));
    let added = configured("word-win", r#"{"fonts":{"installed":{"Andalus":true}}}"#).unwrap();
    let fonts = added.font_environment();
    assert!(!fonts.lacks("Andalus"));
    assert_eq!(fonts.family_substitute("Andalus"), None);
    assert_eq!(fonts.metafile_face("Andalus", 0, 0), None);
    assert_eq!(added.added_families().collect::<Vec<_>>(), ["Andalus"]);
}

#[test]
fn takes_a_removed_family_as_one_that_the_target_lacks() {
    let built_in = Profile::of("word-win".parse().unwrap()).unwrap();
    assert!(!built_in.font_environment().lacks("Arial"));
    let removed = configured("word-win", r#"{"fonts":{"installed":{"Arial":false}}}"#).unwrap();
    assert!(removed.font_environment().lacks("Arial"));
    assert_eq!(removed.added_families().count(), 0);
}

#[test]
fn refuses_a_layer_that_is_not_one() {
    for json in [
        r#"{"colour":{"red":{"value":1}}}"#,
        r#"{"writer":{"a":{"value":1}}}"#,
        r#"{"writer":{"digits":{}}}"#,
        r#"{"writer":{"digits":{"value":"x"}}}"#,
        r#"{"writer":{"digits":{"value":1,"note":"n"}}}"#,
        r#"{"quirks":{"Markup":{"value":3}}}"#,
        r#"{"params":{"LINE":{"value":16}}}"#,
        r#"{"fonts":{"available":{"Aptos":"yes"}}}"#,
        r#"{"layout":{"device_dots_per_inch":{"value":600}}}"#,
        r#"{"configuration":{"printer":{"resolution":600}}}"#,
    ] {
        assert!(serde_json::from_str::<Layer>(json).is_err(), "{json}");
    }
    assert_eq!(
        with("word-win", r#"{"version":0}"#),
        Err(Error::Value("version"))
    );
}

#[test]
fn refuses_an_override_that_sets_what_only_a_profile_or_the_configuration_sets() {
    for (json, key) in [
        (r#"{"product":"p"}"#, "product"),
        (r#"{"renderer":"r"}"#, "renderer"),
        (
            r#"{"fonts":{"environment":"fonts/word-mac.toml"}}"#,
            "fonts.environment",
        ),
        (r#"{"configuration":{"zone_minutes":60}}"#, "configuration"),
    ] {
        assert_eq!(
            with("word-win", json),
            Err(Error::BuiltInKey(key)),
            "{json}"
        );
    }
    assert_eq!(
        with("word-win", r#"{"inherits":"word-mac"}"#),
        Err(Error::Inherits("test".to_owned()))
    );
    assert!(with("word-win", r#"{"id":"mine","inherits":"word-win"}"#).is_ok());
}

#[test]
fn says_what_is_wrong_with_a_profile() {
    let cases = [
        (Error::Missing("id"), "a profile has no id"),
        (Error::Value("a"), "a profile has a wrong value for a"),
        (
            Error::Pair("a", "b"),
            "a profile sets only one of a and b, which are \"off\" or set together",
        ),
        (
            Error::Group(&["a", "b", "c"]),
            "a profile sets only some of a, b, c, which are \"off\" or set together",
        ),
        (
            Error::BuiltInKey("product"),
            "an override sets product, which only a profile or the configuration sets",
        ),
        (
            Error::NotRead("fonts.use"),
            "the configuration sets fonts.use, which F-Office does not read yet",
        ),
    ];
    for (error, message) in cases {
        assert_eq!(error.to_string(), message);
    }
}

#[test]
fn names_the_variant_of_every_quirk_for_every_target() {
    use crate::quirks::Markup;
    for (target, markup) in [
        ("word-mac", Markup::PrintsMarkupArea),
        ("word-web", Markup::PrintsNoMarkup),
        ("word-win", Markup::PrintsNoMarkup),
    ] {
        let configuration = Profile::of(target.parse().unwrap()).unwrap();
        assert_eq!(configuration.quirks().markup, markup, "{target}");
    }
    let base = &Merged::of(Target::base()).unwrap().layer;
    let quirks = |name: &str, variant: &str| {
        super::quirks(&base.clone().with_quirk(name, variant)).map(|quirks| quirks.markup)
    };
    assert_eq!(
        quirks("Markup", "PrintsNoMarkup"),
        Ok(Markup::PrintsNoMarkup)
    );
    assert_eq!(
        quirks("Nothing", "X"),
        Err(Error::UnknownQuirk("Nothing".to_owned()))
    );
    assert_eq!(quirks("Markup", "Never"), Err(Error::Value("Markup")));
    // A merged profile names every quirk.
    assert_eq!(
        super::quirks(&Layer::default()),
        Err(Error::Missing("Markup"))
    );
}

#[test]
fn names_every_key_of_a_palette_density_that_a_profile_sets_only_some_of() {
    let density = |values: [&str; 4]| {
        let keys: Vec<String> = (super::PALETTE_DENSITY_KEYS.iter().zip(values))
            .map(|(key, value)| format!(r#""{key}":{{"value":{value}}}"#))
            .collect();
        let writer = writer_table(&format!("{{{}}}", keys.join(",")));
        super::palette_density(&writer).map(|density| density.map(|d| d.one_bit_ppi.get()))
    };
    let off = "\"off\"";
    let group = Error::Group(&super::PALETTE_DENSITY_KEYS);
    assert_eq!(density(["750", off, off, off]), Err(group.clone()));
    assert_eq!(density(["750", "600", "562", off]), Err(group));
    assert_eq!(density([off; 4]), Ok(None));
    assert_eq!(density(["750", "600", "562", "395"]), Ok(Some(600)));
}

#[test]
fn names_both_keys_of_a_pair_that_a_profile_sets_only_one_of() {
    let density = |limit: &str, ppi: &str| {
        let writer = writer_table(&format!(
            r#"{{"picture_limit_ppi":{{"value":{limit}}},"picture_ppi":{{"value":{ppi}}}}}"#
        ));
        super::picture_density(&writer)
            .map(|density| density.map(|d| (d.limit_ppi.get(), d.ppi.get())))
    };
    let pair = Error::Pair("picture_limit_ppi", "picture_ppi");
    assert_eq!(density("\"off\"", "200"), Err(pair.clone()));
    assert_eq!(density("275", "\"off\""), Err(pair));
    assert_eq!(density("\"off\"", "\"off\""), Ok(None));
    assert_eq!(density("275", "200"), Ok(Some((275, 200))));
}

#[test]
fn reads_a_setting_that_can_be_off_with_one_spelling_for_each_meaning() {
    let count = |written| {
        setting::<OffOr>(written).map(|setting| super::count_or_off(Some(&setting), "digits"))
    };
    assert_eq!(count("\"off\""), Ok(Ok(None)));
    assert_eq!(
        count("5").map(|digits| digits.map(|digits| digits.map(std::num::NonZeroU32::get))),
        Ok(Ok(Some(5)))
    );
    for written in ["0", "-5", "4294967296"] {
        assert_eq!(count(written), Ok(Err(Error::Value("digits"))), "{written}");
    }
    // Text other than "off" does not read as such a setting.
    assert!(count("\"none\"").is_err());
    let quality = |written| {
        super::off_or(
            Some(&setting(written).unwrap()),
            "jpeg_quality",
            |quality| {
                u8::try_from(quality)
                    .ok()
                    .and_then(f_office_paint::JpegQuality::new)
            },
        )
    };
    assert_eq!(
        quality("100").map(|q| q.map(f_office_paint::JpegQuality::get)),
        Ok(Some(100))
    );
    assert_eq!(quality("101"), Err(Error::Value("jpeg_quality")));
}

#[test]
fn reads_a_step_from_its_steps_per_inch() {
    let step = |written| super::step_per_inch(Some(&setting(written).unwrap()), "steps");
    // 2,880 steps per inch are 1/40 pt, 600 are 0.12 pt; "off" keeps the exact value.
    assert_eq!(step("2880"), Ok(Some(Length::from_units(635))));
    assert_eq!(step("600"), Ok(Some(Length::from_units(3_048))));
    assert_eq!(step("\"off\""), Ok(None));
    for written in ["7", "-40", "0"] {
        assert_eq!(step(written), Err(Error::Value("steps")), "{written}");
    }
}

#[test]
fn reads_the_separators_of_numbers() {
    let separators = configured("word-win", r#"{"number_separators":",."}"#)
        .map(|profile| profile.reader_settings());
    let base = Profile::of("word-win".parse().unwrap()).unwrap();
    let chosen = base
        .reader_settings()
        .with_number_separators(Some(NumberSeparators::new(',', '.').unwrap()));
    assert_eq!(separators, Ok(chosen));
    for written in ["..", ".", "0,"] {
        let json = format!(r#"{{"number_separators":"{written}"}}"#);
        assert!(
            serde_json::from_str::<Configuration>(&json).is_err(),
            "{written}"
        );
    }
}

#[test]
fn reads_the_form_of_the_writers_offset_with_its_own_keys() {
    let offsets = |json: &str| {
        super::writer_offsets(
            super::Id::default(),
            (
                crate::quirks::PageOffsetSizes::OneFactor,
                crate::quirks::PageOffsetProduct::Exact,
            ),
            &writer_table(json),
        )
    };
    let none = f_office_paint::WriterOffset::NONE;
    assert_eq!(offsets(r#"{"offset":{"value":"off"}}"#), Ok((none, none)));
    let share = r#"{"offset":{"value":"share_of_place"},
        "start_offset_share":{"value":2400},
        "start_offset_bias_half_emus":{"value":18},
        "start_offset_step_half_emus":{"value":635}}"#;
    let across = f_office_paint::WriterOffset::EveryPage(f_office_paint::Offset::Share {
        share: 2_400,
        bias: 18,
        step: 635,
    });
    assert_eq!(offsets(share), Ok((across, none)));
    // A form reads its own keys, and a profile names one of the three forms.
    assert_eq!(
        offsets(r#"{"offset":{"value":"page_steps"}}"#),
        Err(Error::Missing("offset_page_steps_per_inch"))
    );
    assert_eq!(
        offsets(r#"{"offset":{"value":"none"}}"#),
        Err(Error::Value("offset"))
    );
}

#[test]
fn reads_a_whole_number_in_the_range_that_its_key_takes() {
    let value = |number: i64| Setting { value: number };
    let wrong = Some(Error::Value("k"));
    assert_eq!(super::positive(Some(&value(3)), "k"), Ok(3));
    assert_eq!(super::positive(Some(&value(0)), "k").err(), wrong);
    assert_eq!(super::whole(Some(&value(0)), "k"), Ok(0));
    assert_eq!(super::whole(Some(&value(-1)), "k").err(), wrong);
    assert_eq!(super::number::<u8>(300, "k", |_| true).err(), wrong);
    assert!(setting::<i64>("0.5").is_err());
}

#[test]
fn reads_decimal_numbers_as_written() {
    let decimal = |written| setting::<Decimal>(written).map(|setting| setting.value.0);
    assert_eq!(decimal("-2"), Ok((-2, 1)));
    assert_eq!(decimal("0.031"), Ok((31, 1000)));
    assert!(decimal("\"0.5\"").is_err());
    assert_eq!(Decimal((31, 1000)).to_string(), "0.031");
    assert_eq!(Decimal((-2, 1)).to_string(), "-2");
    assert_eq!(
        serde_json::to_string(&Decimal((31, 1000))).unwrap(),
        "0.031"
    );
}

#[test]
fn names_a_missing_key_in_its_error() {
    assert_eq!(super::whole(None, "other"), Err(Error::Missing("other")));
}

#[test]
fn reads_how_the_writer_writes_a_cropped_picture_by_its_name() {
    let crop = |written: &str| {
        let setting = Setting {
            value: written.to_owned(),
        };
        super::variant(Some(&setting), "picture_crop", &super::PICTURE_CROPS)
    };
    assert_eq!(crop("visible_part"), Ok(PictureCrop::VisiblePart));
    assert_eq!(
        crop("visible_part_at_scale"),
        Ok(PictureCrop::VisiblePartAtScale)
    );
    assert_eq!(
        crop("whole_file_under_clip"),
        Ok(PictureCrop::WholeFileUnderClip)
    );
    assert_eq!(crop("clip"), Err(Error::Value("picture_crop")));
}

#[test]
fn records_the_layer_that_set_each_value() {
    let win = resolved(
        "word-win",
        r#"{"zone_minutes":60,"fonts":{"installed":{"Aptos":true}}}"#,
        r#"{"quirks":{"Markup":{"value":"PrintsMarkupArea"}}}"#,
    )
    .unwrap();
    for (path, origin) in [
        ("id", "word-win"),
        ("version", "word-win"),
        ("configuration.printer.dots_per_inch", "word-win"),
        ("writer.vertical_stretch_steps", "word-mac"),
        ("configuration.zone_minutes", "configuration"),
        ("writer.page_steps_per_inch", "word-win"),
        ("quirks.Markup", "test"),
        ("quirks.LinkedStyles", "word-mac"),
        ("fonts.environment", "word-win"),
        ("configuration.fonts.installed.Aptos", "configuration"),
    ] {
        assert_eq!(win.origin(path), Some(origin), "{path}");
    }
    // The font environment that a profile names replaces the inherited one.
    let mac = Profile::of("word-mac".parse().unwrap()).unwrap();
    let (family, styles) = super::environment_table("fonts/word-mac.toml")
        .unwrap()
        .face
        .iter()
        .find(|(family, _)| {
            !(super::environment_table("fonts/word-win.toml")
                .unwrap()
                .face)
                .contains_key(*family)
        })
        .unwrap();
    let style = styles.keys().next().unwrap();
    let path = format!(
        "fonts.face.{}.{}.version",
        super::path_key(family),
        super::path_key(style)
    );
    assert_eq!(mac.origin(&path), Some("word-mac"), "{path}");
    assert_eq!(win.origin(&path), None, "{path}");
    assert_eq!(win.origin("nothing"), None);
}

#[test]
fn a_later_layer_wins() {
    use crate::quirks::Markup;
    let overrides = Overrides::default()
        .with_layer(
            "one",
            Layer::default().with_quirk("Markup", "PrintsMarkupArea"),
        )
        .with_layer(
            "two",
            Layer::default().with_quirk("Markup", "PrintsNoMarkup"),
        );
    let configuration =
        Profile::resolve(&Configuration::of("word-win".parse().unwrap()), &overrides).unwrap();
    assert_eq!(configuration.quirks().markup, Markup::PrintsNoMarkup);
    assert_eq!(configuration.origin("quirks.Markup"), Some("two"));
}

#[test]
fn builds_the_device_from_a_quirk_set_in_place_and_refuses_a_wrong_one() {
    use crate::quirks::GridAdvances;
    // A quirk that the device is built from reaches the device, and a variant needs the
    // numbers that it reads.
    let profile = Profile::of("word-win".parse().unwrap()).unwrap();
    let rounded = profile.with_variant(GridAdvances::RoundToPdfSteps);
    assert_eq!(
        rounded.quirks().grid_advances,
        GridAdvances::RoundToPdfSteps
    );
    assert_ne!(rounded.device(), profile.device());
    let quirk = |id: &str, name: &str, variant: &str| {
        Profile::resolve(
            &Configuration::of(id.parse().unwrap()),
            &Overrides::default().with_quirk(name, variant),
        )
    };
    assert_eq!(
        quirk("word-mac", "GridAdvances", "RightEdgeSteps"),
        Err(Error::Missing("glyph_step_bias_half_emus"))
    );
    assert_eq!(
        quirk("word-win", "Nothing", "X"),
        Err(Error::UnknownQuirk("Nothing".to_owned()))
    );
    assert_eq!(
        quirk("word-win", "Markup", "Never"),
        Err(Error::Value("Markup"))
    );
}

#[test]
fn an_empty_layer_keeps_the_profiles_values() {
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        let empty = Profile::resolve(
            &Configuration::of(target),
            &Overrides::default().with_layer("empty", Layer::default()),
        )
        .unwrap();
        assert_eq!(empty.device(), profile.device(), "{target}");
        assert_eq!(empty.writer(), profile.writer(), "{target}");
        assert_eq!(
            empty.reader_settings(),
            profile.reader_settings(),
            "{target}"
        );
        assert_eq!(empty.quirks(), profile.quirks(), "{target}");
        assert_eq!(
            empty.font_environment(),
            profile.font_environment(),
            "{target}"
        );
    }
}

/// The configuration's values that set the printer's resolution to `dots` per inch.
fn printer(dots: i64) -> String {
    format!(r#"{{"printer":{{"dots_per_inch":{dots}}}}}"#)
}

#[test]
fn a_printer_resolution_sets_the_device_dot_only() {
    let profile = Profile::of("word-win".parse().unwrap()).unwrap();
    // 3,000 dpi gives a dot of 609.6 units, which goes to 610.
    for (dots, dot) in [
        (300, 6096),
        (600, 3048),
        (1200, 1524),
        (2400, 762),
        (3000, 610),
    ] {
        let laid_out = configured("word-win", &printer(dots)).unwrap();
        assert_eq!(laid_out.device_dot(), Length::from_units(dot), "{dots}");
        assert_eq!(laid_out.quirks(), profile.quirks());
    }
}

#[test]
fn a_printer_of_another_resolution_has_no_page_offset_unless_an_override_sets_one() {
    use f_office_paint::WriterOffset;
    let profile = Profile::of("word-win".parse().unwrap()).unwrap();
    let none = profile
        .writer()
        .with_horizontal_offset(WriterOffset::NONE)
        .with_vertical_offset(WriterOffset::NONE);
    for (dots, writer) in [(600, profile.writer()), (1200, none), (3000, none)] {
        assert_eq!(
            configured("word-win", &printer(dots)).unwrap().writer(),
            writer,
            "{dots}"
        );
    }
    // The page offset `none` takes the target's away on its own printer too, as an override's
    // writer offset "off" does.
    let off = configured("word-win", r#"{"printer":{"page_offset":"none"}}"#).unwrap();
    assert_eq!(off.writer(), none);
    let off = with("word-win", r#"{"writer":{"offset":{"value":"off"}}}"#).unwrap();
    assert_eq!(off.writer(), none);
    // An override that sets the writer's offset keeps it on another printer.
    let kept = resolved(
        "word-win",
        &printer(1200),
        r#"{"writer":{"offset":{"value":"page_steps"}}}"#,
    )
    .unwrap();
    assert_eq!(kept.writer(), profile.writer());
}

#[test]
fn refuses_a_printer_resolution_that_the_layout_cannot_lay_out_for() {
    // 3,657,600 dpi gives a dot of half a unit, and a resolution of 0 does not read.
    assert_eq!(
        configured("word-win", &printer(3_657_600)),
        Err(Error::Value("printer.dots_per_inch"))
    );
    assert!(serde_json::from_str::<Configuration>(&printer(0)).is_err());
}

/// The layer that sets the quirks of `chosen`, each by its name and its variant's.
fn choosing(chosen: &[(&str, &str)]) -> Layer {
    chosen
        .iter()
        .fold(Layer::default(), |layer, (name, variant)| {
            layer.with_quirk(name, variant)
        })
}

#[test]
fn an_override_that_sets_the_profiles_own_variants_keeps_its_values() {
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        let chosen = Profile::resolve(
            &Configuration::of(target),
            &Overrides::default().with_layer("own", choosing(&profile.variants())),
        )
        .unwrap();
        assert_eq!(chosen.device(), profile.device(), "{target:?}");
        assert_eq!(chosen.writer(), profile.writer(), "{target:?}");
        assert_eq!(
            chosen.reader_settings(),
            profile.reader_settings(),
            "{target:?}"
        );
        assert_eq!(chosen.quirks(), profile.quirks(), "{target:?}");
    }
}

#[test]
fn a_quirk_of_another_variant_reaches_the_device_the_writer_and_the_reader() {
    let profile = Profile::of("word-win".parse().unwrap()).unwrap();
    let with = |name, variant| {
        Profile::resolve(
            &Configuration::of("word-win".parse().unwrap()),
            &Overrides::default().with_layer("test", choosing(&[(name, variant)])),
        )
        .unwrap()
    };
    // The grid and the line height: the device's glyph steps and its single baseline.
    for (name, variant) in [
        ("GridAdvances", "RoundToPdfSteps"),
        ("SingleBaseline", "CutDescent"),
    ] {
        assert_ne!(with(name, variant).device(), profile.device(), "{name}");
    }
    // The writer: one factor of the page offset on every page in place of the paper forms'.
    assert_ne!(
        with("PageOffsetSizes", "OneFactor").writer(),
        profile.writer()
    );
    // The reader: a document prints with its markup area.
    assert_ne!(
        with("Markup", "PrintsMarkupArea").reader_settings(),
        profile.reader_settings()
    );
    // The target's other page offset product takes its own page sizes, and leaves the target's
    // own as they were.
    assert_ne!(
        with("PageOffsetProduct", "Exact").writer(),
        profile.writer()
    );
    assert_eq!(
        Profile::of("word-win".parse().unwrap()).unwrap().writer(),
        profile.writer()
    );
}

/// The configuration's values that set only the machine's time zone, `minutes` east of UTC.
fn zone(minutes: i32) -> String {
    format!(r#"{{"zone_minutes":{minutes}}}"#)
}

#[test]
fn takes_the_machines_time_zone_from_the_configuration() {
    let word_win = Profile::of("word-win".parse().unwrap()).unwrap();
    assert_eq!(word_win.zone_minutes(), Ok(480));
    for target in Target::all() {
        let profile = Profile::of(target).unwrap();
        let zoned = |minutes| {
            configured(&target.to_string(), &zone(minutes)).map(|chosen| chosen.zone_minutes())
        };
        assert_eq!(
            (
                profile.zone_minutes().is_ok(),
                zoned(-300),
                zoned(1440),
                zoned(-1440)
            ),
            (
                true,
                Ok(Ok(-300)),
                Err(Error::Value("zone_minutes")),
                Err(Error::Value("zone_minutes"))
            ),
            "{target}"
        );
    }
}

#[test]
fn needs_a_time_zone_where_a_date_property_is_written_as_its_local_date() {
    // The base target's profile gives no zone.
    let local = Profile::base().with_variant(crate::quirks::PropertyDateZone::LocalDate);
    assert_eq!(local.zone_minutes(), Err(Error::Missing("zone_minutes")));
    let mut configuration = local.configuration().clone();
    configuration.zone_minutes = Some(60);
    let zoned = Profile::resolve(&configuration, local.overrides()).unwrap();
    assert_eq!(zoned.zone_minutes(), Ok(60));
}

#[test]
fn needs_a_target_and_reads_the_choice_of_family() {
    let none = Overrides::default();
    assert_eq!(
        Profile::resolve(&Configuration::default(), &none),
        Err(Error::Missing("target"))
    );
    let profile = configured("word-win", r#"{"fonts":{"use":{"Calibri":"Carlito"}}}"#).unwrap();
    assert_eq!(
        profile.used_families().collect::<Vec<_>>(),
        [("Calibri", "Carlito")]
    );
}

#[test]
fn takes_the_targets_own_profile_for_its_defaults() {
    // A configuration that changes nothing gives the profile of the target, made once.
    for target in Target::all() {
        let own = Profile::resolve(&Configuration::of(target), &Overrides::default()).unwrap();
        assert_eq!(own, Profile::of(target).unwrap(), "{target}");
        assert_eq!(own.configuration(), &Configuration::of(target), "{target}");
    }
}