f-office-docx 0.3.0

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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
//! Targets and their profiles. A target is the product whose pages a layout reproduces, and its
//! profile is a versioned data file in `profiles/`: Word's behaviors and numbers, and in its
//! table `configuration` the defaults of the configuration. The base profile is the root, every
//! other profile inherits from it along `inherits` and lists only what differs, and the caller's
//! configuration and, in a development build, the override's layers come after the chain
//! ([`Overrides`]). A later layer wins, tables merge key by key, and the merged profile records
//! which layer set each value (`Profile::origin`).
//!
//! Only this module reads the target: its value is private here, so no other code can ask
//! which product it draws for, and no other library source names a target by its ID. Each
//! kind of difference has one home: a behavior is a quirk variant, a number of the layout
//! device is a layout value, and how the PDF writer writes numbers is the writer, which only
//! the output stage reads.
//!
//! The build turns each file of `profiles/` into JSON, which this module reads with serde
//! ([`Layer`]), so that the library carries no TOML reader.

use std::collections::BTreeMap;
use std::fmt::{self, Write as _};
use std::num::NonZeroU32;
use std::str::FromStr;
use std::sync::{Arc, OnceLock};

use crate::font_choice::SymbolFonts;
use f_office_fonts::environment::{EnvironmentError, FontEnvironment};
use f_office_paint::{
    AlphaMix, JpegQuality, JpegSample, JpegShare, LinearLimit, PaletteDensity, PictureCrop,
    PictureDensity, Writer, WriterOffset,
};
use f_office_units::Length;

use crate::configuration::{Configuration, PageOffset};

#[cfg(any(test, feature = "development"))]
mod facts;
#[cfg(feature = "development")]
pub mod fonts;
#[cfg(not(feature = "development"))]
pub(crate) mod fonts;
mod layer;
mod overrides;

#[cfg(feature = "development")]
pub use facts::{Entry, Facts, Section};
#[cfg(all(test, not(feature = "development")))]
use facts::{Facts, Section};
use fonts::Table;
pub(crate) use layer::{Decimal, Layer, Layout, OffOr, Setting, Writer as WriterTable};
#[cfg(feature = "development")]
pub use overrides::Overrides;
#[cfg(not(feature = "development"))]
pub(crate) use overrides::Overrides;

use layer::decimal_fraction;

/// The product whose pages a layout reproduces. The default target is Word for Windows
/// (`word-win`). Preview targets (`word-mac`, `word-web`) are gated behind the
/// `preview-targets` feature.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Target(Id);

/// The Word product of a target: Word for Windows by default, plus preview Word for Mac
/// and Word for the web when `preview-targets` is enabled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
enum Id {
    #[cfg(any(test, feature = "preview-targets"))]
    Mac,
    #[cfg(any(test, feature = "preview-targets"))]
    Web,
    #[default]
    Win,
}

/// One cell for each target, in which a value that depends on the target only is made once in a
/// process: the profiles and the font environments are part of the binary, so each reading
/// gives the same value.
type PerTarget<T> = [OnceLock<T>; TARGETS.len()];

impl Id {
    /// The cell of this target in `cells`.
    #[cfg(any(test, feature = "preview-targets"))]
    const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
        let [mac, web, win] = cells;
        match self {
            Self::Mac => mac,
            Self::Web => web,
            Self::Win => win,
        }
    }

    /// The cell of this target in `cells`.
    #[cfg(not(any(test, feature = "preview-targets")))]
    const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
        let [win] = cells;
        match self {
            Self::Win => win,
        }
    }
}

/// The ID of each enabled target's profile.
#[cfg(any(test, feature = "preview-targets"))]
const TARGETS: [(Id, &str); 3] = [
    (Id::Mac, "word-mac"),
    (Id::Web, "word-web"),
    (Id::Win, "word-win"),
];

/// The ID of each enabled target's profile.
#[cfg(not(any(test, feature = "preview-targets")))]
const TARGETS: [(Id, &str); 1] = [(Id::Win, "word-win")];

/// A file of the profiles by its name, with the JSON that the build makes of it, `$json` in
/// the build's output folder.
macro_rules! built {
    ($name:literal, $json:literal) => {
        ($name, include_str!(concat!(env!("OUT_DIR"), "/", $json)))
    };
}

/// The profiles by their IDs. Even when `preview-targets` is off, `word-mac` stays
/// embedded as the inheritance root of `word-win`.
#[cfg(any(test, feature = "preview-targets"))]
const BUILT_IN: [(&str, &str); 3] = [
    built!("word-mac", "word-mac.json"),
    built!("word-web", "word-web.json"),
    built!("word-win", "word-win.json"),
];

/// The profiles by their IDs (`word-mac` is kept solely as the inheritance root of `word-win`).
#[cfg(not(any(test, feature = "preview-targets")))]
const BUILT_IN: [(&str, &str); 2] = [
    built!("word-mac", "word-mac.json"),
    built!("word-win", "word-win.json"),
];

/// The font environments that a profile can name (`fonts.environment`), by their paths in the
/// folder of the profiles.
#[cfg(any(test, feature = "preview-targets"))]
const FONT_ENVIRONMENTS: [(&str, &str); 3] = [
    built!("fonts/word-mac.toml", "fonts-word-mac.json"),
    built!("fonts/word-web.toml", "fonts-word-web.json"),
    built!("fonts/word-win.toml", "fonts-word-win.json"),
];

/// The font environments for enabled targets only.
#[cfg(not(any(test, feature = "preview-targets")))]
const FONT_ENVIRONMENTS: [(&str, &str); 1] = [built!("fonts/word-win.toml", "fonts-word-win.json")];

impl Target {
    /// Every enabled target. When `preview-targets` is enabled, the inheritance root comes
    /// first.
    pub fn all() -> impl Iterator<Item = Self> {
        TARGETS.iter().map(|(id, _)| Self(*id))
    }

    /// The base profile target from which other profiles inherit (`word-mac`).
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub const fn base() -> Self {
        Self(Id::Mac)
    }

    /// The ID of the target's profile.
    fn name(self) -> &'static str {
        TARGETS
            .iter()
            .find(|(id, _)| *id == self.0)
            .map_or("", |(_, name)| name)
    }
}

impl FromStr for Target {
    type Err = Error;

    /// The target whose profile has the ID `name`.
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::all()
            .find(|target| target.name() == name)
            .ok_or_else(|| Error::UnknownTarget(name.to_owned()))
    }
}

impl fmt::Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl serde::Serialize for Target {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl<'de> serde::Deserialize<'de> for Target {
    /// The target by its ID, such as `"word-win"`.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let name = String::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "development")]
impl schemars::JsonSchema for Target {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Target".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let ids: Vec<String> = Self::all().map(|target| target.to_string()).collect();
        schemars::json_schema!({
            "description": "The Word whose pages the layout reproduces, by its ID.",
            "type": "string",
            "enum": ids
        })
    }
}

/// The profiles of [`BUILT_IN`], each read once in a process.
static PROFILES_READ: [OnceLock<Result<Layer, Error>>; BUILT_IN.len()] =
    [const { OnceLock::new() }; BUILT_IN.len()];

/// The font environments of [`FONT_ENVIRONMENTS`], each read once in a process.
static ENVIRONMENTS_READ: [OnceLock<Result<Table, Error>>; FONT_ENVIRONMENTS.len()] =
    [const { OnceLock::new() }; FONT_ENVIRONMENTS.len()];

/// The profile `name`, read once in a process.
fn built_in(name: &str) -> Result<&'static Layer, Error> {
    let layer = read_once((&BUILT_IN, &PROFILES_READ), name, Error::UnknownProfile)?;
    if layer.id.as_deref() != Some(name) {
        return Err(Error::Missing("id"));
    }
    Ok(layer)
}

/// The font environment `name` that a profile names, read once in a process.
fn environment_table(name: &str) -> Result<&'static Table, Error> {
    read_once(
        (&FONT_ENVIRONMENTS, &ENVIRONMENTS_READ),
        name,
        Error::UnknownEnvironment,
    )
}

/// The cells of the files of one kind, by the order of the files, each read once in a process.
type ReadOnce<T> = [OnceLock<Result<T, Error>>];

/// The value of the file `name` of `files`, read from its JSON once in a process into its cell
/// of `cells`; `unknown` is the error of a name that `files` lacks.
fn read_once<T: serde::de::DeserializeOwned>(
    (files, cells): (&[(&str, &str)], &'static ReadOnce<T>),
    name: &str,
    unknown: fn(String) -> Error,
) -> Result<&'static T, Error> {
    let at = files
        .iter()
        .position(|(own, _)| *own == name)
        .ok_or_else(|| unknown(name.to_owned()))?;
    let (cell, (own, json)) = cells
        .get(at)
        .zip(files.get(at))
        .ok_or_else(|| unknown(name.to_owned()))?;
    cell.get_or_init(|| {
        serde_json::from_str(json).map_err(|error| Error::Read {
            profile: (*own).to_owned(),
            message: error.to_string(),
        })
    })
    .as_ref()
    .map_err(Clone::clone)
}

/// The chain of the profile `name`: the profiles along `inherits`, the root first.
fn chain(name: &str) -> Result<Vec<(&'static str, &'static Layer)>, Error> {
    let mut chain = Vec::new();
    let mut next = Some(name.to_owned());
    while let Some(name) = next.take() {
        if chain.len() == BUILT_IN.len() {
            return Err(Error::Inherits(name));
        }
        let layer = built_in(&name)?;
        let id = BUILT_IN
            .iter()
            .find(|(own, _)| *own == name)
            .map_or("", |(own, _)| own);
        chain.push((id, layer));
        next.clone_from(&layer.inherits);
    }
    chain.reverse();
    Ok(chain)
}

/// The configuration of `target` with the defaults that its profile's chain gives in its tables
/// `configuration`. A profile that does not read gives the target alone, and the profile's
/// error comes when a layout reads the configuration ([`Profile::resolve`]).
pub(crate) fn defaults(target: Target) -> Configuration {
    let mut configuration =
        Merged::of(target).map_or_default(|merged| merged.layer.configuration.clone());
    configuration.target = Some(target);
    configuration
}

/// The layers merged in order, with the layer that set each value.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Merged {
    layer: Layer,
    /// The index in `names` of the layer that set each value, by its path, such as
    /// `layout.leader_steps_per_inch`, `configuration.printer.dots_per_inch` or
    /// `fonts.available.Aptos`.
    origins: BTreeMap<String, usize>,
    /// The name of each layer, in order.
    names: Vec<Arc<str>>,
}

/// A key of a path as TOML writes it: bare when it holds only letters, digits, `_` and `-`, else
/// a basic string in double quotes, with `\"`, `\\` and `\uXXXX` for a quote, a backslash and
/// a control character.
pub(crate) fn path_key(key: &str) -> String {
    if !key.is_empty()
        && key
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
    {
        return key.to_owned();
    }
    let mut out = String::with_capacity(key.len() + 2);
    out.push('"');
    for ch in key.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            ch if ch.is_control() => {
                let _ = write!(out, "\\u{:04X}", u32::from(ch));
            }
            ch => out.push(ch),
        }
    }
    out.push('"');
    out
}

impl Merged {
    /// The chain of `target`'s profile merged, once in a process.
    fn of(target: Target) -> Result<&'static Self, Error> {
        static MERGED: PerTarget<Result<Merged, Error>> =
            [const { OnceLock::new() }; TARGETS.len()];
        target
            .0
            .cell(&MERGED)
            .get_or_init(|| {
                let layers = chain(target.name())?;
                let last_env = layers
                    .iter()
                    .rposition(|(_, layer)| layer.fonts.environment.is_some());
                let mut merged = Self::default();
                for (index, (name, layer)) in layers.into_iter().enumerate() {
                    let load_env = last_env == Some(index);
                    merged.take_with_env(name, layer, load_env)?;
                }
                Ok(merged)
            })
            .as_ref()
            .map_err(Clone::clone)
    }

    /// Takes in the layer `layer`, named `name`, after the others.
    fn take(&mut self, name: &str, layer: &Layer) -> Result<(), Error> {
        self.take_with_env(name, layer, true)
    }

    /// Takes in `layer`, loading its `fonts.environment` table only when `load_env` is true
    /// (skipped for ancestor layers whose environment is completely replaced by a descendant).
    fn take_with_env(&mut self, name: &str, layer: &Layer, load_env: bool) -> Result<(), Error> {
        let at = self.names.len();
        self.names.push(name.into());
        if load_env && let Some(environment) = &layer.fonts.environment {
            let table = environment_table(environment)?;
            self.origins.retain(|path, _| !path.starts_with("fonts."));
            self.layer.fonts = Table {
                environment: Some(environment.clone()),
                ..Table::default()
            };
            self.origins.insert("fonts.environment".to_owned(), at);
            let origins = &mut self.origins;
            self.layer.fonts.merge(table, &mut |path| {
                origins.insert(fonts_path(path), at);
            });
        }
        let (own, origins) = (&mut self.layer, &mut self.origins);
        let mut set = |path: String| {
            origins.insert(path, at);
        };
        for (key, own, later) in [
            ("id", &mut own.id, &layer.id),
            ("inherits", &mut own.inherits, &layer.inherits),
            ("product", &mut own.product, &layer.product),
            ("builds", &mut own.builds, &layer.builds),
            ("renderer", &mut own.renderer, &layer.renderer),
        ] {
            if let Some(value) = later {
                *own = Some(value.clone());
                set(key.to_owned());
            }
        }
        if let Some(version) = layer.version {
            own.version = Some(version);
            set("version".to_owned());
        }
        own.configuration.merge(&layer.configuration, &mut |path| {
            set(format!("configuration.{path}"));
        });
        own.layout
            .merge(&layer.layout, &mut |key| set(format!("layout.{key}")));
        own.writer
            .merge(&layer.writer, &mut |key| set(format!("writer.{key}")));
        for (quirk, setting) in &layer.quirks {
            own.quirks.insert(quirk.clone(), setting.clone());
            set(format!("quirks.{}", path_key(quirk)));
        }
        own.fonts
            .merge(&layer.fonts, &mut |path| set(fonts_path(path)));
        Ok(())
    }

    /// The name of the layer that set the value at `path`.
    #[cfg(any(test, feature = "development"))]
    fn origin(&self, path: &str) -> Option<&str> {
        let at = *self.origins.get(path)?;
        self.names.get(at).map(|name| &**name)
    }

    /// Whether a layer after the first `built_in`, the profile's chain, set the value at `path`.
    fn caller_set(&self, path: &str, built_in: usize) -> bool {
        self.origins.get(path).is_some_and(|at| *at >= built_in)
    }
}

/// The path of a value of the font environment's table, from `fonts` on.
fn fonts_path(path: &[&str]) -> String {
    let mut out = "fonts".to_owned();
    for key in path {
        out.push('.');
        out.push_str(&path_key(key));
    }
    out
}

/// The value of `key`, or the error that the merged configuration lacks it.
fn get<T: Clone>(setting: Option<&Setting<T>>, key: &'static str) -> Result<T, Error> {
    setting
        .map(|setting| setting.value.clone())
        .ok_or(Error::Missing(key))
}

/// A whole number that `accepts` takes, as a `T` that holds it.
fn number<T: TryFrom<i64>>(
    value: i64,
    key: &'static str,
    accepts: fn(i64) -> bool,
) -> Result<T, Error> {
    if !accepts(value) {
        return Err(Error::Value(key));
    }
    T::try_from(value).map_err(|_| Error::Value(key))
}

/// A whole number above 0, such as a count of steps per inch.
fn positive(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
    number(get(setting, key)?, key, |number| number > 0)
}

/// A whole number, 0 or more, such as the bias of the writer's start offset.
fn whole(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
    number(get(setting, key)?, key, |number| number >= 0)
}

/// A setting that a configuration can turn off: `None` for `"off"`, and for a positive whole
/// number the value that `make` gives. Zero, a negative number and a number that `make` refuses
/// are errors, so that each meaning has one spelling.
fn off_or<T>(
    setting: Option<&Setting<OffOr>>,
    key: &'static str,
    make: impl FnOnce(i64) -> Option<T>,
) -> Result<Option<T>, Error> {
    match get(setting, key)? {
        OffOr::Off(_) => Ok(None),
        OffOr::Number(number) if number > 0 => make(number).map(Some).ok_or(Error::Value(key)),
        OffOr::Number(_) => Err(Error::Value(key)),
    }
}

/// A count that a configuration can turn off, such as the significant digits of the writer:
/// `"off"`, or a positive whole number of 32 bits.
fn count_or_off(
    setting: Option<&Setting<OffOr>>,
    key: &'static str,
) -> Result<Option<NonZeroU32>, Error> {
    off_or(setting, key, |number| {
        u32::try_from(number).ok().and_then(NonZeroU32::new)
    })
}

/// A step to which a value rounds, from the number of steps per inch that the configuration
/// gives as `key`, which divides an inch into whole units, or `None` for "off", which keeps the
/// exact value: the step of a tab leader's advance (`layout.leader_steps_per_inch`) and of a
/// glyph's stretch (`writer.glyph_stretch_steps_per_inch`).
fn step_per_inch(
    setting: Option<&Setting<OffOr>>,
    key: &'static str,
) -> Result<Option<Length>, Error> {
    let per_inch = Length::UNITS_PER_INCH;
    off_or(setting, key, |steps| {
        (per_inch % steps == 0).then(|| Length::from_units(per_inch / steps))
    })
}

/// The value of the variant that `key` names, from `variants`.
fn variant<T: Copy>(
    setting: Option<&Setting<String>>,
    key: &'static str,
    variants: &[(&str, T)],
) -> Result<T, Error> {
    let name = get(setting, key)?;
    variants
        .iter()
        .find(|(variant, _)| *variant == name)
        .map(|(_, value)| *value)
        .ok_or(Error::Value(key))
}

/// Whether a time zone of `minutes` east of UTC lies less than a day from it either way.
fn in_a_day(minutes: i32) -> bool {
    minutes.unsigned_abs()
        < u32::from(crate::params::HOURS_PER_DAY) * u32::from(crate::params::MINUTES_PER_HOUR)
}

/// The merged values that a layout takes from a target's profile, the caller's configuration
/// and the development override, and the layer that set each.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Profile {
    target: Target,
    configuration: Configuration,
    overrides: Overrides,
    id: String,
    version: i64,
    product: String,
    builds: String,
    renderer: String,
    environment_name: String,
    device: crate::grid::Device,
    writer: Writer,
    reader: crate::reader::settings::ReaderSettings,
    quirks: crate::quirks::Quirks,
    environment: Arc<FontEnvironment>,
    /// Word's numbers of the symbol fonts, from the font environment's `symbol_font` tables.
    symbol_fonts: Arc<SymbolFonts>,
    /// The time zone of the machine in minutes east of UTC (`zone_minutes`), or none when no
    /// layer gives one.
    zone_minutes: Option<i32>,
    merged: Arc<Merged>,
}

impl Profile {
    /// The profile of a target with its own defaults, merged along its chain, once in a process.
    ///
    /// # Errors
    ///
    /// Returns an error when a profile does not read, or sets a value that F-Office does not
    /// read yet.
    pub fn of(target: Target) -> Result<Self, Error> {
        static RESOLVED: PerTarget<Result<Profile, Error>> =
            [const { OnceLock::new() }; TARGETS.len()];
        target
            .0
            .cell(&RESOLVED)
            .get_or_init(|| {
                let merged = Merged::of(target)?.clone();
                let built_in = merged.names.len();
                Self::read(
                    target,
                    (defaults(target), Overrides::default()),
                    merged,
                    built_in,
                )
            })
            .clone()
    }

    /// The profile of the target that `configuration` names, with the values of
    /// `configuration` that differ from the target's defaults in a layer after its chain, named
    /// `configuration` in the origins, and the layers of `overrides` after that.
    ///
    /// # Errors
    ///
    /// Returns an error when the configuration names no target, when a profile does not read,
    /// when the configuration sets a value that F-Office does not read yet, when an override's
    /// layer sets a key that only a profile sets or a key, quirk or variant that F-Office does
    /// not know, and when a merged value is missing or wrong.
    pub(crate) fn resolve(
        configuration: &Configuration,
        overrides: &Overrides,
    ) -> Result<Self, Error> {
        let target = configuration.target.ok_or(Error::Missing("target"))?;
        let changes = configuration.changes_from(&defaults(target));
        if changes.is_empty() && overrides.is_empty() {
            return Self::of(target);
        }
        let mut merged = Merged::of(target)?.clone();
        let built_in = merged.names.len();
        let configured = Layer {
            configuration: changes,
            ..Layer::default()
        };
        merged.take("configuration", &configured)?;
        for (name, layer) in overrides.layers() {
            if layer
                .inherits
                .as_deref()
                .is_some_and(|id| id != target.name())
            {
                return Err(Error::Inherits(name.to_owned()));
            }
            for (key, set) in [
                ("product", layer.product.is_some()),
                ("builds", layer.builds.is_some()),
                ("renderer", layer.renderer.is_some()),
                ("fonts.environment", layer.fonts.environment.is_some()),
                ("configuration", !layer.configuration.is_empty()),
            ] {
                if set {
                    return Err(Error::BuiltInKey(key));
                }
            }
            merged.take(name, layer)?;
        }
        let configuration = Configuration {
            target: Some(target),
            ..merged.layer.configuration.clone()
        };
        Self::read(target, (configuration, overrides.clone()), merged, built_in)
    }

    /// Reads the values of `merged`, whose first `built_in` layers are the chain of `target`'s
    /// profile, with the configuration and the override that it merges: the quirks first,
    /// then everything built from them.
    fn read(
        target: Target,
        (configuration, overrides): (Configuration, Overrides),
        merged: Merged,
        built_in: usize,
    ) -> Result<Self, Error> {
        let own = &merged.layer;
        let (layout, writer) = (&own.layout, &own.writer);
        let quirks = quirks(own)?;
        let printer = own.configuration.printer;
        let dots = printer
            .dots_per_inch
            .ok_or(Error::Missing("printer.dots_per_inch"))?;
        let device = crate::grid::Device::of(i64::from(dots.get()), &quirks)
            .ok_or(Error::Value("printer.dots_per_inch"))?
            .with_leader_step(step_per_inch(
                layout.leader_steps_per_inch.as_ref(),
                "leader_steps_per_inch",
            )?)
            .with_bold_stroke(count_or_off(
                layout.bold_stroke_parts.as_ref(),
                "bold_stroke_parts",
            )?)
            .with_italic_slant(count_or_off(
                layout.italic_slant_parts.as_ref(),
                "italic_slant_parts",
            )?);
        let offsets = page_offsets(target, &merged, built_in, (device, quirks))?;
        let device = match advances(layout, &quirks, offsets.0)? {
            Some(advances) => device.with_advances(advances),
            None => device,
        };
        let number_separators = own.configuration.number_separators;
        // A target that writes chart labels in their number formats writes the separators of
        // its machine.
        if quirks.chart_label_formats == crate::quirks::ChartLabelFormats::Codes
            && number_separators.is_none()
        {
            return Err(Error::Missing("number_separators"));
        }
        let zone_minutes = own.configuration.zone_minutes;
        if zone_minutes.is_some_and(|minutes| !in_a_day(minutes)) {
            return Err(Error::Value("zone_minutes"));
        }
        let environment_name = own
            .fonts
            .environment
            .clone()
            .ok_or(Error::Missing("fonts.environment"))?;
        let environment = environment(target, &merged, built_in, &environment_name)?;
        let symbol_fonts = Arc::new(SymbolFonts::of(&own.fonts.symbol_font).map_err(Error::Value)?);
        let text = |value: &Option<String>, key| value.clone().ok_or(Error::Missing(key));
        Ok(Self {
            id: text(&own.id, "id")?,
            version: match own.version {
                Some(version) if version > 0 => version,
                Some(_) => return Err(Error::Value("version")),
                None => return Err(Error::Missing("version")),
            },
            product: text(&own.product, "product")?,
            builds: text(&own.builds, "builds")?,
            renderer: text(&own.renderer, "renderer")?,
            environment_name,
            device,
            writer: profile_writer(writer, offsets)?,
            reader: crate::reader::settings::ReaderSettings::of(&quirks)
                .with_number_separators(number_separators),
            quirks,
            environment,
            symbol_fonts,
            zone_minutes,
            target,
            configuration,
            overrides,
            merged: Arc::new(merged),
        })
    }

    /// The base target's profile, for tests.
    #[cfg(test)]
    pub(crate) fn base() -> Self {
        Self::of(Target::base()).expect("the base profile reads")
    }

    /// The profile with the quirk `Q` at `variant`, in an override's layer after this one's,
    /// for a test that names the variant that it means.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn with_variant<Q: crate::quirks::Quirk + PartialEq>(&self, variant: Q) -> Self {
        let (name, _) = (Q::VARIANTS.iter())
            .find(|(_, own)| *own == variant)
            .expect("every variant has a name");
        Self::resolve(
            &self.configuration,
            &self
                .overrides
                .with_layer("test", Layer::default().with_quirk(Q::NAME, name)),
        )
        .expect("the profile reads with the variant")
    }

    /// The target of the profile.
    #[cfg(feature = "development")]
    #[must_use]
    pub const fn target(&self) -> Target {
        self.target
    }

    /// The configuration that the profile merges, with the target's defaults where the caller
    /// sets no value.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub const fn configuration(&self) -> &Configuration {
        &self.configuration
    }

    /// The development override that the profile merges after the configuration.
    #[cfg(test)]
    #[must_use]
    pub(crate) const fn overrides(&self) -> &Overrides {
        &self.overrides
    }

    /// The name of the layer that set the value at `path`, such as
    /// `configuration.zone_minutes` or `quirks.NoteMarkPlace`: a profile's ID, `configuration`
    /// for a value that the caller's configuration changes, or the name of an override's layer.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn origin(&self, path: &str) -> Option<&str> {
        self.merged.origin(path)
    }

    /// The variant of every quirk for the target, which only the decision modules read. See
    /// `src/quirks.rs`.
    #[must_use]
    pub(crate) const fn quirks(&self) -> crate::quirks::Quirks {
        self.quirks
    }

    /// The variant that the profile takes of each quirk, as the quirk's name and the variant's
    /// name in a profile, in the order of `src/quirks.rs`: a list for tools, which read the
    /// target's choices without naming the quirks' types.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn variants(&self) -> Vec<(&'static str, &'static str)> {
        self.quirks
            .variants()
            .iter()
            .map(|chosen| (chosen.quirk, chosen.variant))
            .collect()
    }

    /// Whether the profile takes the quirk variant `variant`, written `Quirk::Variant`, or
    /// `None` when the registry has no such variant.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn chooses(&self, variant: &str) -> Option<bool> {
        let (quirk, name) = variant.split_once("::")?;
        self.quirks
            .variants()
            .iter()
            .find(|chosen| chosen.quirk == quirk && chosen.has(name))
            .map(|chosen| chosen.variant == name)
    }

    /// The target's rule for the line metrics of stand-ins, which only the font choice reads.
    #[must_use]
    pub(crate) const fn stand_in_lines(&self) -> crate::text::StandInLines {
        crate::text::StandInLines::of(&self.quirks)
    }

    /// How the target's PDF writer writes the page size. Only the output stage reads it.
    #[must_use]
    pub const fn writer(&self) -> Writer {
        self.writer
    }

    /// The reader's settings, which only the reader reads. See `src/reader/settings.rs`.
    #[must_use]
    pub(crate) const fn reader_settings(&self) -> crate::reader::settings::ReaderSettings {
        self.reader
    }

    /// The time zone of the machine, in minutes east of UTC, which only the layout reads. A
    /// target that writes date properties in UTC needs none and takes 0 without one.
    ///
    /// # Errors
    ///
    /// Returns an error when the target writes a date property as its local date and no layer
    /// gives the zone.
    pub(crate) fn zone_minutes(&self) -> Result<i32, Error> {
        match self.quirks.property_date_zone {
            crate::quirks::PropertyDateZone::Utc => Ok(self.zone_minutes.unwrap_or(0)),
            crate::quirks::PropertyDateZone::LocalDate => {
                self.zone_minutes.ok_or(Error::Missing("zone_minutes"))
            }
        }
    }

    /// The layout device, which only the layout reads. See `src/grid.rs`.
    #[must_use]
    pub(crate) const fn device(&self) -> crate::grid::Device {
        self.device
    }

    /// One dot of the layout device, to the nearest half-EMU, for tools that split a glyph's
    /// offset from the target's place into whole dots and the rest that the PDF writer adds.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn device_dot(&self) -> Length {
        self.device.dots(1)
    }

    /// The path of the font environment that the profile takes (`fonts.environment`), in the
    /// folder of the profiles.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn font_environment_path(&self) -> &str {
        &self.environment_name
    }

    /// The font environment, which the font choice reads.
    #[cfg(any(test, feature = "development"))]
    #[must_use]
    pub fn font_environment(&self) -> &FontEnvironment {
        &self.environment
    }

    /// The font environment of `Profile::font_environment`, shared.
    pub(crate) fn shared_font_environment(&self) -> Arc<FontEnvironment> {
        Arc::clone(&self.environment)
    }

    /// Word's numbers of the symbol fonts that the font environment holds, shared.
    pub(crate) fn symbol_fonts(&self) -> Arc<SymbolFonts> {
        Arc::clone(&self.symbol_fonts)
    }

    /// The font families that the configuration adds to the fonts of Word's machine
    /// (`fonts.installed`), as Word has the family of a face that a document carries once it
    /// opens the document. The font choice takes a face of such a family as the target's own,
    /// whatever its PostScript name.
    pub fn added_families(&self) -> impl Iterator<Item = &str> {
        (self.merged.layer.configuration.fonts.installed.iter())
            .filter(|(_, installed)| **installed)
            .map(|(family, _)| family.as_str())
    }

    /// The families that draw families on this computer by the configuration (`fonts.use`),
    /// each with the family that it draws: the font choice draws a family that this computer
    /// has no face of with the named family, and that one as it draws any family.
    pub fn used_families(&self) -> impl Iterator<Item = (&str, &str)> {
        (self.merged.layer.configuration.fonts.uses.iter())
            .map(|(family, uses)| (family.as_str(), uses.as_str()))
    }
}

impl fmt::Display for Profile {
    /// The ID, the version, the product, its builds and its renderer.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {} ({}, builds {}, {})",
            self.id, self.version, self.product, self.builds, self.renderer
        )
    }
}

/// The writer's offsets across and down of `merged`, the profile of `target` after its first
/// `built_in` layers, on the layout device `device` with the quirks `quirks`. A configuration
/// that sets the page offset `none` gives no offset. The target's page offset belongs to the
/// target's printer: on a printer of another resolution, the writer writes each place at its
/// place on the device, unless the configuration sets the page offset or an override the
/// writer's offset.
fn page_offsets(
    target: Target,
    merged: &Merged,
    built_in: usize,
    (device, quirks): (crate::grid::Device, crate::quirks::Quirks),
) -> Result<(WriterOffset, WriterOffset), Error> {
    let none = (WriterOffset::NONE, WriterOffset::NONE);
    if merged.layer.configuration.printer.page_offset == Some(PageOffset::None) {
        return Ok(none);
    }
    let offsets = writer_offsets(
        target.0,
        (quirks.page_offset_sizes, quirks.page_offset_product),
        &merged.layer.writer,
    )?;
    if merged.caller_set("configuration.printer.dots_per_inch", built_in)
        && !merged.caller_set("configuration.printer.page_offset", built_in)
        && !merged.caller_set("writer.offset", built_in)
    {
        let own_dots = Merged::of(target)?
            .layer
            .configuration
            .printer
            .dots_per_inch;
        let own_device =
            own_dots.and_then(|dots| crate::grid::Device::of(i64::from(dots.get()), &quirks));
        if own_device.is_none_or(|own| own.dot_size() != device.dot_size()) {
            return Ok(none);
        }
    }
    Ok(offsets)
}

/// The font environment of `merged`, the profile of `target` whose environment file is
/// `name`, after its first `built_in` layers: the chain's, made once in a process, while no
/// later layer changes it. The families that the configuration adds to the fonts of Word's
/// machine join its full font listing, and those that it removes leave it; without a full
/// listing, a target takes every name, so an added family changes nothing there and a removed
/// one becomes a family that it lacks.
fn environment(
    target: Target,
    merged: &Merged,
    built_in: usize,
    name: &str,
) -> Result<Arc<FontEnvironment>, Error> {
    let installed = &merged.layer.configuration.fonts.installed;
    let unchanged = installed.is_empty()
        && !(merged.origins.iter()).any(|(path, at)| *at >= built_in && path.starts_with("fonts."));
    if unchanged {
        static ENVIRONMENTS: PerTarget<Result<Arc<FontEnvironment>, Error>> =
            [const { OnceLock::new() }; TARGETS.len()];
        return target
            .0
            .cell(&ENVIRONMENTS)
            .get_or_init(|| {
                let merged = Merged::of(target)?;
                fonts::environment(&merged.layer.fonts)
                    .map(Arc::new)
                    .map_err(Error::Environment)
            })
            .clone();
    }
    let mut table = merged.layer.fonts.clone();
    if environment_table(name)?.available.is_empty() {
        table.available.clear();
        for (family, _) in installed.iter().filter(|(_, installed)| !**installed) {
            table.lacking.entry(family.clone()).or_default();
        }
    } else {
        table.available.extend(
            installed
                .iter()
                .map(|(family, installed)| (family.clone(), *installed)),
        );
    }
    fonts::environment(&table)
        .map(Arc::new)
        .map_err(Error::Environment)
}

/// The advances of the rule of glyph steps that `quirks` names, with their numbers from
/// `layout`, which a configuration gives only for the variant that uses them, or `None` for the
/// device's own; `start` is the writer's offset across.
fn advances(
    layout: &Layout,
    quirks: &crate::quirks::Quirks,
    start: WriterOffset,
) -> Result<Option<crate::grid::Advances>, Error> {
    Ok(match quirks.grid_advances {
        crate::quirks::GridAdvances::RoundToPdfSteps => None,
        crate::quirks::GridAdvances::RightEdgeSteps => Some(crate::grid::Advances::RightEdge {
            bias: Length::from_units(positive(
                layout.glyph_step_bias_half_emus.as_ref(),
                "glyph_step_bias_half_emus",
            )?),
            limit: Length::from_units(positive(
                layout.glyph_edge_limit_half_emus.as_ref(),
                "glyph_edge_limit_half_emus",
            )?),
            segment: Length::from_units(positive(
                layout.glyph_segment_length_half_emus.as_ref(),
                "glyph_segment_length_half_emus",
            )?),
            point_steps: count_or_off(layout.glyph_point_steps.as_ref(), "glyph_point_steps")?,
            start,
        }),
    })
}

/// The quirks of a merged layer. A profile names quirks of the registry only. See
/// `src/quirks.rs`.
fn quirks(layer: &Layer) -> Result<crate::quirks::Quirks, Error> {
    if let Some(name) = layer
        .quirks
        .keys()
        .find(|name| !crate::quirks::NAMES.contains(&name.as_str()))
    {
        return Err(Error::UnknownQuirk(name.clone()));
    }
    crate::quirks::Quirks::read(&|name| {
        layer.quirks.get(name).map(|setting| setting.value.as_str())
    })
    .map_err(|error| match error {
        crate::quirks::QuirkError::Missing(name) => Error::Missing(name),
        crate::quirks::QuirkError::Variant(name) => Error::Value(name),
    })
}

/// The names of the ways in which a writer writes a cropped picture (`writer.picture_crop`,
/// [`PictureCrop`]).
const PICTURE_CROPS: [(&str, PictureCrop); 3] = [
    ("whole_file_under_clip", PictureCrop::WholeFileUnderClip),
    ("visible_part", PictureCrop::VisiblePart),
    ("visible_part_at_scale", PictureCrop::VisiblePartAtScale),
];

/// The names of the ways in which a writer mixes the colors of a picture with an alpha when it
/// resamples it (`writer.alpha_mix`, [`AlphaMix`]).
const ALPHA_MIXES: [(&str, AlphaMix); 2] =
    [("plain", AlphaMix::Plain), ("weighted", AlphaMix::Weighted)];

/// A linear limit of one measure, from its count.
type LinearLimitOf = fn(NonZeroU32) -> LinearLimit;

/// The names of the measures of a writer's linear limit (`writer.linear_limit_of`): the count of
/// a picture's source pixels, or its larger side ([`LinearLimit`]).
const LINEAR_LIMIT_MEASURES: [(&str, LinearLimitOf); 2] =
    [("pixels", LinearLimit::Pixels), ("side", LinearLimit::Side)];

/// The pictures that a writer's filter resamples by the linear interpolation: those whose
/// measure (`writer.linear_limit_of`) is at most `writer.linear_limit`.
fn linear_limit(writer: &WriterTable) -> Result<LinearLimit, Error> {
    let measure = variant(
        writer.linear_limit_of.as_ref(),
        "linear_limit_of",
        &LINEAR_LIMIT_MEASURES,
    )?;
    let count: u32 = number(
        get(writer.linear_limit.as_ref(), "linear_limit")?,
        "linear_limit",
        |count| count > 0,
    )?;
    NonZeroU32::new(count)
        .map(measure)
        .ok_or(Error::Value("linear_limit"))
}

/// The densities from which and below which a writer resamples a picture
/// (`writer.picture_limit_ppi` and `writer.picture_ppi`), or `None` when both are "off". A
/// profile that sets only one of them gives an error that names both.
fn picture_density(writer: &WriterTable) -> Result<Option<PictureDensity>, Error> {
    let keys = ("picture_limit_ppi", "picture_ppi");
    match (
        count_or_off(writer.picture_limit_ppi.as_ref(), keys.0)?,
        count_or_off(writer.picture_ppi.as_ref(), keys.1)?,
    ) {
        (Some(limit_ppi), Some(ppi)) => Ok(Some(PictureDensity { limit_ppi, ppi })),
        (None, None) => Ok(None),
        _ => Err(Error::Pair(keys.0, keys.1)),
    }
}

/// The keys of a writer's palette density, which are "off" or set together: the limits of a
/// palette of 1 bit, the density of 1 bit, and the limits of 4 and 8 bits, in pixels per inch.
const PALETTE_DENSITY_KEYS: [&str; 4] = [
    "palette_one_bit_limit_ppi",
    "palette_one_bit_ppi",
    "palette_four_bits_limit_ppi",
    "palette_eight_bits_limit_ppi",
];

/// The limits and the density with which a writer resamples a PNG picture of a palette of a
/// class ([`PALETTE_DENSITY_KEYS`]), or `None` when all four keys are "off". A configuration
/// that sets some of them and leaves others "off" gives an error that names them all.
fn palette_density(writer: &WriterTable) -> Result<Option<PaletteDensity>, Error> {
    let [one_bit_limit, one_bit, four_bits_limit, eight_bits_limit] = PALETTE_DENSITY_KEYS;
    let values = (
        count_or_off(writer.palette_one_bit_limit_ppi.as_ref(), one_bit_limit)?,
        count_or_off(writer.palette_one_bit_ppi.as_ref(), one_bit)?,
        count_or_off(writer.palette_four_bits_limit_ppi.as_ref(), four_bits_limit)?,
        count_or_off(
            writer.palette_eight_bits_limit_ppi.as_ref(),
            eight_bits_limit,
        )?,
    );
    match values {
        (
            Some(one_bit_limit_ppi),
            Some(one_bit_ppi),
            Some(four_bits_limit_ppi),
            Some(eight_bits_limit_ppi),
        ) => Ok(Some(PaletteDensity {
            one_bit_limit_ppi,
            one_bit_ppi,
            four_bits_limit_ppi,
            eight_bits_limit_ppi,
        })),
        (None, None, None, None) => Ok(None),
        _ => Err(Error::Group(&PALETTE_DENSITY_KEYS)),
    }
}

/// The keys of a writer's second test of JPEG pictures, which are "off" or set together: the
/// sample share and the whole share in thousandths, and the floor in bytes.
const JPEG_SAMPLE_KEYS: [&str; 3] = ["jpeg_sample_share", "jpeg_sample_floor", "jpeg_whole_share"];

/// The second test of a writer that writes PNG pictures as JPEG files ([`JPEG_SAMPLE_KEYS`]), or
/// `None` when all three keys are "off". A profile that sets some of them and leaves others
/// "off", or gives a share above 1,000, gives an error that names them all.
fn jpeg_sample(writer: &WriterTable) -> Result<Option<JpegSample>, Error> {
    let [share, floor, whole] = JPEG_SAMPLE_KEYS;
    let values = (
        count_or_off(writer.jpeg_sample_share.as_ref(), share)?,
        count_or_off(writer.jpeg_sample_floor.as_ref(), floor)?,
        count_or_off(writer.jpeg_whole_share.as_ref(), whole)?,
    );
    match values {
        (Some(share), Some(floor), Some(whole)) => {
            let (Ok(share), Ok(whole)) = (u16::try_from(share.get()), u16::try_from(whole.get()))
            else {
                return Err(Error::Group(&JPEG_SAMPLE_KEYS));
            };
            JpegSample::new(share, floor.get(), whole)
                .map(Some)
                .ok_or(Error::Group(&JPEG_SAMPLE_KEYS))
        }
        (None, None, None) => Ok(None),
        _ => Err(Error::Group(&JPEG_SAMPLE_KEYS)),
    }
}

/// The writer that the profile's `writer.*` keys give, with its offsets across and down
/// ([`writer_offsets`]).
fn profile_writer(
    writer: &WriterTable,
    (horizontal_offset, vertical_offset): (WriterOffset, WriterOffset),
) -> Result<Writer, Error> {
    // A count of decimals: any number that its type holds.
    let any: fn(i64) -> bool = |_| true;
    let steps = positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
    let stretch = whole(
        writer.vertical_stretch_steps.as_ref(),
        "vertical_stretch_steps",
    )?;
    // The writer rounds how far its stretch moves a glyph's baseline to whole steps of this
    // many to the inch, or moves it by the exact stretch for "off".
    let glyph_step = step_per_inch(
        writer.glyph_stretch_steps_per_inch.as_ref(),
        "glyph_stretch_steps_per_inch",
    )?;
    let Decimal(stretch_offset) = get(writer.stretch_offset.as_ref(), "stretch_offset")?;
    let stretch_factors =
        stretch_factors(&get(writer.stretch_factors.as_ref(), "stretch_factors")?)?;
    let digits = count_or_off(writer.digits.as_ref(), "digits")?;
    let least_decimals = number(
        get(writer.least_decimals.as_ref(), "least_decimals")?,
        "least_decimals",
        any,
    )?;
    let picture_digits = count_or_off(writer.picture_digits.as_ref(), "picture_digits")?;
    let rectangle_steps = count_or_off(
        writer.rectangle_steps_per_inch.as_ref(),
        "rectangle_steps_per_inch",
    )?;
    let baseline_steps = count_or_off(
        writer.baseline_steps_per_inch.as_ref(),
        "baseline_steps_per_inch",
    )?;
    let jpeg_quality = off_or(writer.jpeg_quality.as_ref(), "jpeg_quality", |quality| {
        u8::try_from(quality).ok().and_then(JpegQuality::new)
    })?;
    let jpeg_share = off_or(writer.jpeg_share.as_ref(), "jpeg_share", |share| {
        u16::try_from(share).ok().and_then(JpegShare::new)
    })?;
    let jpeg_sample = jpeg_sample(writer)?;
    let density = picture_density(writer)?;
    let palettes = palette_density(writer)?;
    let crop = variant(writer.picture_crop.as_ref(), "picture_crop", &PICTURE_CROPS)?;
    let alpha_mix = variant(writer.alpha_mix.as_ref(), "alpha_mix", &ALPHA_MIXES)?;
    let linear_limit = linear_limit(writer)?;
    Ok(writer_of(steps)?
        .with_vertical_stretch(stretch)
        .with_glyph_stretch_step(glyph_step)
        .ok_or(Error::Value("glyph_stretch_steps_per_inch"))?
        .with_stretch_factors(stretch_offset, &stretch_factors)
        .ok_or(Error::Value("stretch_factors"))?
        .with_digits(digits)
        .with_least_decimals(least_decimals)
        .with_rectangle_steps(rectangle_steps)
        .with_baseline_steps(baseline_steps)
        .with_picture_digits(picture_digits)
        .with_horizontal_offset(horizontal_offset)
        .with_vertical_offset(vertical_offset)
        .with_jpeg_quality(jpeg_quality)
        .with_jpeg_share(jpeg_share)
        .with_jpeg_sample(jpeg_sample)
        .with_picture_density(density)
        .with_palette_density(palettes)
        .with_picture_crop(crop)
        .with_alpha_mix(alpha_mix)
        .with_linear_limit(linear_limit))
}

/// The stretch factors of `writer.stretch_factors`: a list, empty or of entries `height factor`
/// split by commas, each a written page height in points and its factor as decimal numbers, such
/// as `"792 1.003165, 842 0.982394"`.
fn stretch_factors(list: &str) -> Result<Vec<(Length, f_office_paint::Fraction)>, Error> {
    let wrong = || Error::Value("stretch_factors");
    list.split(',')
        .map(str::trim)
        .filter(|entry| !entry.is_empty())
        .map(|entry| {
            let mut parts = entry.split_whitespace();
            let (Some(height), Some(factor), None) = (parts.next(), parts.next(), parts.next())
            else {
                return Err(wrong());
            };
            let (points, scale) = decimal_fraction(height).ok_or_else(wrong)?;
            let units = points
                .checked_mul(Length::UNITS_PER_POINT)
                .filter(|units| *units > 0 && units % scale == 0)
                .ok_or_else(wrong)?;
            let factor = decimal_fraction(factor)
                .filter(|(value, _)| *value > 0)
                .ok_or_else(wrong)?;
            Ok((Length::from_units(units / scale), factor))
        })
        .collect()
}

/// The writer that rounds the page size to `steps` per inch.
fn writer_of(steps: i64) -> Result<Writer, Error> {
    let per_inch = Length::UNITS_PER_INCH;
    if per_inch % steps != 0 {
        return Err(Error::Value("page_steps_per_inch"));
    }
    Writer::new(Length::from_units(per_inch / steps)).ok_or(Error::Value("page_steps_per_inch"))
}

/// The form of the writer's offset of a place (`writer.offset`), each of which reads only its
/// own keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OffsetForm {
    /// The writer writes each place where the layout puts it (`"off"`).
    Off,
    /// The place across divided by the share, plus the bias, rounded to the step, across only
    /// (`"share_of_place"`, the keys `start_offset_*`).
    ShareOfPlace,
    /// Whole steps as if the page were larger, across and down (`"page_steps"`, the keys
    /// `offset_page_*`).
    PageSteps,
}

/// The names of the forms of the writer's offset (`writer.offset`, [`OffsetForm`]).
const OFFSET_FORMS: [(&str, OffsetForm); 3] = [
    ("off", OffsetForm::Off),
    ("share_of_place", OffsetForm::ShareOfPlace),
    ("page_steps", OffsetForm::PageSteps),
];

/// The writer's offsets across and down the page for the target `id`, in the form that
/// `writer.offset` names ([`OffsetForm`]), from the keys of that form: none; the place divided
/// by the share, plus the bias, rounded to the step, across only; or whole steps as if the page
/// were larger, across and down, with the steps that a page's paper form gives when the quirk
/// `sizes` asks for them ([`page_sizes`]) and the product that the quirk `product` names. It
/// moves a text object's start, a glyph's baseline (down) and a filled rectangle's edges.
fn writer_offsets(
    id: Id,
    (sizes, product): (
        crate::quirks::PageOffsetSizes,
        crate::quirks::PageOffsetProduct,
    ),
    writer: &WriterTable,
) -> Result<(WriterOffset, WriterOffset), Error> {
    match variant(writer.offset.as_ref(), "offset", &OFFSET_FORMS)? {
        OffsetForm::Off => Ok((WriterOffset::NONE, WriterOffset::NONE)),
        OffsetForm::ShareOfPlace => {
            let across = WriterOffset::EveryPage(f_office_paint::Offset::Share {
                share: positive(writer.start_offset_share.as_ref(), "start_offset_share")?,
                bias: whole(
                    writer.start_offset_bias_half_emus.as_ref(),
                    "start_offset_bias_half_emus",
                )?,
                step: positive(
                    writer.start_offset_step_half_emus.as_ref(),
                    "start_offset_step_half_emus",
                )?,
            });
            Ok((across, WriterOffset::NONE))
        }
        OffsetForm::PageSteps => {
            let per_inch = positive(
                writer.offset_page_steps_per_inch.as_ref(),
                "offset_page_steps_per_inch",
            )?;
            let parts = positive(
                writer.offset_page_parts_per_step.as_ref(),
                "offset_page_parts_per_step",
            )?;
            let steps = positive(
                writer.offset_page_steps_hundred_thousandths.as_ref(),
                "offset_page_steps_hundred_thousandths",
            )?;
            let product = match product {
                crate::quirks::PageOffsetProduct::Exact => f_office_paint::OffsetProduct::Exact,
                crate::quirks::PageOffsetProduct::Binary32 => {
                    f_office_paint::OffsetProduct::Binary32 {
                        dots_per_inch: positive(
                            writer.page_steps_per_inch.as_ref(),
                            "page_steps_per_inch",
                        )?,
                    }
                }
            };
            let offset = match sizes {
                crate::quirks::PageOffsetSizes::OneFactor => {
                    WriterOffset::EveryPage(f_office_paint::Offset::Page {
                        steps: in_hundred_thousandths(steps),
                        parts,
                        per_inch,
                        product,
                    })
                }
                crate::quirks::PageOffsetSizes::PaperForms => {
                    WriterOffset::Sizes(page_sizes(id, writer, (steps, parts, per_inch), product)?)
                }
            };
            Ok((offset, offset))
        }
    }
}

/// `steps` hundred-thousandths of a step, the unit of the registry and of the profile's
/// `writer.offset_page_steps_hundred_thousandths`.
const fn in_hundred_thousandths(steps: i64) -> f_office_paint::Fraction {
    (steps, f_office_paint::STEP_PARTS)
}

/// The page sizes of the writer's page offset for the target `id`, built once for each target and product,
/// each in the configuration's `parts` of a step, steps of 1/`per_inch` inch and the written dots
/// per inch of `writer.page_steps_per_inch`: the measured sizes of the parameter registry
/// (`params::PAGE_4961_7016_STEPS` and the others), each in the orientation of the sections that
/// measured it; a Letter page in every orientation, with the steps across of
/// `params::PAGE_5100_6600_ACROSS_STEPS` and the profile's steps, Letter's factor `letter`,
/// down; a page of Letter across with Letter's factor on both axes; and the class rule
/// (`params::PAPER_FORM_CLASS_RULE`) for every other page; each offset with the product `product`.
fn page_sizes(
    id: Id,
    writer: &WriterTable,
    (letter, parts, per_inch): (i64, i64, i64),
    product: f_office_paint::OffsetProduct,
) -> Result<&'static f_office_paint::PageSizes, Error> {
    use f_office_paint::{GivenSize, OffsetProduct, Orientation};
    // One set of sizes for each target and product: a caller may choose the target's other
    // product (`PageOffsetProduct`), and the target's own profile keeps its sizes.
    static EXACT: PerTarget<Result<f_office_paint::PageSizes, Error>> =
        [const { OnceLock::new() }; TARGETS.len()];
    static BINARY32: PerTarget<Result<f_office_paint::PageSizes, Error>> =
        [const { OnceLock::new() }; TARGETS.len()];
    let sizes = match product {
        OffsetProduct::Exact => &EXACT,
        OffsetProduct::Binary32 { .. } => &BINARY32,
    };
    id.cell(sizes)
        .get_or_init(|| {
            let measured = |orientation, (dots, (across, down))| GivenSize {
                dots,
                orientation: Some(orientation),
                steps: (
                    Some(in_hundred_thousandths(across)),
                    Some(in_hundred_thousandths(down)),
                ),
            };
            // The near-A4 sizes were measured on sections that set no orientation, A4 across
            // on sections that set the landscape orientation.
            let mut sizes: Vec<GivenSize> = [
                crate::params::PAGE_4961_7016_STEPS,
                crate::params::PAGE_4960_7015_STEPS,
            ]
            .into_iter()
            .map(|size| measured(Orientation::Portrait, size))
            .collect();
            sizes.push(measured(
                Orientation::Landscape,
                crate::params::PAGE_7016_4961_STEPS,
            ));
            let ((width, height), letter_across) = crate::params::PAGE_5100_6600_ACROSS_STEPS;
            let letter = in_hundred_thousandths(letter);
            sizes.push(GivenSize {
                dots: (width, height),
                orientation: None,
                steps: (Some(in_hundred_thousandths(letter_across)), Some(letter)),
            });
            // Letter across in a landscape section takes Letter's steps with the sides swapped:
            // Letter's factor across and the steps across a Letter page down. In any other
            // section it takes Letter's factor across, and down the page entry of its paper form.
            sizes.push(GivenSize {
                dots: (height, width),
                orientation: Some(Orientation::Landscape),
                steps: (Some(letter), Some(in_hundred_thousandths(letter_across))),
            });
            sizes.push(GivenSize {
                dots: (height, width),
                orientation: None,
                steps: (Some(letter), None),
            });
            let dots_per_inch =
                positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
            Ok(f_office_paint::PageSizes::new(
                (parts, per_inch, dots_per_inch),
                product,
                sizes,
                &crate::params::PAPER_FORM_CLASS_RULE,
            ))
        })
        .as_ref()
        .map_err(Clone::clone)
}

#[cfg(any(test, feature = "development"))]
impl Layer {
    /// The layer with the quirk `name` at its variant `variant`, by their names in a
    /// configuration, in place of any variant of it that the layer sets already.
    #[must_use]
    pub fn with_quirk(mut self, name: &str, variant: &str) -> Self {
        self.quirks.insert(
            name.to_owned(),
            Setting {
                value: variant.to_owned(),
            },
        );
        self
    }
}

/// An error in a target's name, a profile or a configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// No target has this name.
    UnknownTarget(String),
    /// No profile has this name, as `inherits` names it.
    UnknownProfile(String),
    /// No font environment has this name, as `fonts.environment` names it.
    UnknownEnvironment(String),
    /// A profile does not read as a profile, with what is wrong.
    Read {
        /// The profile's or the font environment's name.
        profile: String,
        /// What is wrong, and where.
        message: String,
    },
    /// The chain of `inherits` from this profile does not end, or an override's layer named
    /// this inherits from another profile than its target's.
    Inherits(String),
    /// An override's layer sets a key that only a profile or the configuration sets.
    BuiltInKey(&'static str),
    /// The merged profile or the configuration lacks a key.
    Missing(&'static str),
    /// A value has the wrong kind, or a number is not positive.
    Value(&'static str),
    /// The configuration sets a key that F-Office does not read yet.
    NotRead(&'static str),
    /// A profile sets one key of a pair that is "off" or set together, such as the two
    /// densities of a resampled picture, and leaves the other "off".
    Pair(&'static str, &'static str),
    /// A profile sets some keys of a group that are "off" or set together, such as the keys
    /// of a palette density, and leaves others "off".
    Group(&'static [&'static str]),
    /// A profile sets a quirk that the registry lacks.
    UnknownQuirk(String),
    /// The merged font environment does not build.
    Environment(EnvironmentError),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownTarget(name) => write!(f, "no target is named {name:?}"),
            Self::UnknownProfile(name) => write!(f, "no profile is named {name:?}"),
            Self::UnknownEnvironment(name) => {
                write!(f, "no font environment is named {name:?}")
            }
            Self::Read { profile, message } => {
                write!(f, "the profile {profile} does not read: {message}")
            }
            Self::Inherits(name) => write!(
                f,
                "the profile {name} inherits from a profile that it cannot inherit from"
            ),
            Self::BuiltInKey(key) => {
                write!(
                    f,
                    "an override sets {key}, which only a profile or the configuration sets"
                )
            }
            Self::Missing(key) => write!(f, "a profile has no {key}"),
            Self::Value(key) => write!(f, "a profile has a wrong value for {key}"),
            Self::NotRead(key) => write!(
                f,
                "the configuration sets {key}, which F-Office does not read yet"
            ),
            Self::Pair(one, other) => write!(
                f,
                "a profile sets only one of {one} and {other}, which are \"off\" or set together"
            ),
            Self::Group(keys) => write!(
                f,
                "a profile sets only some of {}, which are \"off\" or set together",
                keys.join(", ")
            ),
            Self::UnknownQuirk(name) => write!(f, "no quirk of the registry is named {name:?}"),
            Self::Environment(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Environment(error) => Some(error),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests;