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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
//! The layout device: the grid on which a target's Word places page sizes, the edges of text
//! columns, baselines and drawn lines. The configuration names the device, the resolution of
//! the printer that Word lays out for (`printer.dots_per_inch`, by default the target
//! profile's), and the layout reads it from there. The base target's device has 300 dots per
//! inch.
//!
//! The glyph steps of [`Advances::RightEdge`] are in three modules: `steps` holds the step
//! arithmetic that every target shares ([`EdgeSteps`]), and `from_restart` and
//! `from_line_start` each hold one segment rule, a variant of the quirk `GlyphSegments`. The
//! match on `GlyphSegments` in `steps` is the only place that names a segment rule.
use std::num::NonZeroU32;
use f_office_paint::Orientation;
use f_office_units::binary32::Binary32;
use f_office_units::scale::{PERCENT, POINTS_PER_INCH, TENTHS, THOUSANDTHS};
use f_office_units::{
Edges, Length, count_factor, div_round, div_round_i128, lowest_terms, saturated,
};
use crate::params;
use crate::text::FontSide;
mod borders;
mod from_line_start;
mod from_restart;
mod heights;
mod lines;
mod steps;
mod tables;
pub use heights::LowBaseline;
pub use steps::{EdgeCheck, EdgeSteps, GlyphExtra, counted_spacing_excess};
/// A layout device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Device {
/// One device dot.
dot: Dot,
/// How the glyphs of a line step on the device.
advances: Advances,
/// The variant of every quirk that the target's profile names, which the device reads
/// for the quirks of the device: `MultipleBaseline`, `SingleBaseline`, `ExactBaseline`,
/// `LowMultipleBaseline`, `ExactSpacedBottom`,
/// `TableLines`, `LineStartHalves`, `AlignedEnds`, `AlignedLineSegments`,
/// `AlignedLineEdge`, `OffPageObjects`,
/// `ScaledGlyphs`,
/// `GlyphEdgeCheck`, `GlyphSegments`, `TopHalves`, `ShiftDots`, `FooterHalves`, `HeaderHalves`,
/// `WriterAdjustments`, `WriterSpacing`, `NoneBorders`, `InlineRoom`, `BorderSpace`,
/// `CellSpaceAfter` and `AtLeastSpaceAfter`. The rules of tables and VML shapes read their quirks from the layout's
/// context.
quirks: crate::quirks::Quirks,
/// The step to which the advance of a tab leader's character rounds before the leader's
/// grid takes it (`layout.leader_steps_per_inch`), or `None` for the exact advance.
leader_step: Option<Length>,
/// The part of the drawn size that the line along a synthetic bold glyph's outline is
/// wide: the width is the size divided by this number (`layout.bold_stroke_parts`), or no
/// line for `None`.
bold_stroke_parts: Option<NonZeroU32>,
/// How far a synthetic italic glyph leans: a step up the glyph goes this part of the step
/// to the right (`layout.italic_slant_parts`), or the glyph stands upright for `None`.
italic_slant_parts: Option<NonZeroU32>,
/// The page that the layout draws, on whose size the PDF writer's offset of a text object's
/// start may depend ([`f_office_paint::WriterOffset::on_page`]), or none before a layout
/// gives the device its page ([`Self::with_page`]).
page: Option<PageSize>,
/// Whether glyphs stay at their places on the device, without the PDF writer's
/// adjustments ([`TextObject::draw`]), for a tool's measurement; never set by a profile.
writer_off: bool,
}
/// One device dot as a fraction of half-EMUs in lowest terms, `units / per`: a whole number of
/// units, `per` 1, at a resolution that divides the half-EMUs of an inch, such as 600 dots per
/// inch, and a fraction at another, such as 3,000 dots per inch (3,048/5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Dot {
units: i64,
per: i64,
}
impl Dot {
/// The dot of a device with `dots` per inch, or `None` for no dots or for a dot smaller
/// than a half-EMU.
fn of(dots: i64) -> Option<Self> {
if dots <= 0 || dots > Length::UNITS_PER_INCH {
return None;
}
let (units, per) = lowest_terms(i128::from(Length::UNITS_PER_INCH), i128::from(dots));
Some(Self {
units: i64::try_from(units).ok()?,
per: i64::try_from(per).ok()?,
})
}
/// `count` dots as a length, to the nearest half-EMU, a half up: exact at a resolution
/// whose dot is a whole number of half-EMUs.
#[must_use]
pub fn dots(self, count: i64) -> Length {
let units = i128::from(count) * i128::from(self.units);
Length::from_units(saturated(div_round_i128(units, i128::from(self.per))))
}
/// The whole dots, a half up, in a length of `numerator / denominator` half-EMUs whose terms
/// need more than 64 bits, or `None` when the dots do not fit in an `i64`.
#[must_use]
pub fn count_exact(self, numerator: i128, denominator: i128) -> Option<i64> {
let dots = div_round_i128(
numerator * i128::from(self.per),
denominator * i128::from(self.units),
);
i64::try_from(dots).ok()
}
/// How the part of `length` past the dot below it compares with half a dot: `Equal` for a
/// length that lies exactly on half a dot.
#[must_use]
pub fn half_dot_side(self, length: Length) -> std::cmp::Ordering {
let dot = i128::from(self.units);
let past = (i128::from(length.units()) * i128::from(self.per)).rem_euclid(dot);
(past * 2).cmp(&dot)
}
/// The whole dots in `length`, rounded as `rounding` says. A length within half a half-EMU
/// of a dot, such as one that [`Self::dots`] made of a dot that is no whole number of
/// half-EMUs, counts as on that dot when it rounds down, up or toward zero.
#[must_use]
pub fn count(self, length: Length, rounding: Rounding) -> i64 {
let parts = i128::from(length.units()) * i128::from(self.per);
let dot = i128::from(self.units);
let near = i128::from(self.per / 2);
let down = || (parts + near).div_euclid(dot);
let up = || -(near - parts).div_euclid(dot);
saturated(match rounding {
Rounding::HalfUp => div_round_i128(parts, dot),
Rounding::HalfDown => (parts * 2 + dot - 1).div_euclid(dot * 2),
Rounding::Up => up(),
Rounding::TowardZero if parts < 0 => up(),
Rounding::Down | Rounding::TowardZero => down(),
})
}
/// Rounds a position to the nearest dot, a half dot up.
#[must_use]
pub fn snap(self, length: Length) -> Length {
self.dots(self.count(length, Rounding::HalfUp))
}
}
/// How a length goes to a whole number of device dots ([`Device::count`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rounding {
/// To the nearest dot, a half dot up.
HalfUp,
/// To the nearest dot, a half dot down.
HalfDown,
/// Down to a whole dot.
Down,
/// Up to a whole dot.
Up,
/// Toward zero to a whole dot, as an integer division cuts.
TowardZero,
}
/// How the thickness of a drawn line lands on whole device dots ([`Device::line_thickness`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineRounding {
/// To the nearest dot, a half dot up: an underline, a strikethrough, a note separator's
/// rule, a fraction's bar, a page border's line, and a table's line under the quirk
/// `TableLines::RoundsStarts`.
Nearest,
/// Down to whole dots: a paragraph border's line, and a table's line under the quirk
/// `TableLines::RoundsCenters`.
Down,
}
/// The width and the height of a page, and the orientation that its section sets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PageSize {
width: Length,
height: Length,
orientation: Orientation,
}
/// How the glyphs of a line step on the device: the variant of the quirk `GridAdvances`
/// (`src/quirks.rs`) that the target's configuration names, with its numbers from the
/// configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Advances {
/// Each advance rounds to the PDF writer's advance steps (`GridAdvances::RoundToPdfSteps`).
PdfSteps,
/// Each glyph goes one step after the glyph before, and moves a dot when its right edge
/// would end too far from its exact right edge (`GridAdvances::RightEdgeSteps`; see
/// [`EdgeSteps`]).
RightEdge {
/// What is added to a distance before it rounds to a step.
bias: Length,
/// How far a right edge may end past its exact place.
limit: Length,
/// The length of a segment of the line: the glyph whose exact right edge first ends
/// more than a whole number of segments after the line's first glyph starts the steps
/// again.
segment: Length,
/// The steps per point in which the edge check counts the device's dots per point,
/// rounded up ([`Device::exact_scale`]); `None` keeps the exact places as they are.
point_steps: Option<NonZeroU32>,
/// The PDF writer's offset of a text object's start from its first glyph's place, which
/// each page chooses ([`TextObject::of`]).
start: f_office_paint::WriterOffset,
},
}
/// What the device takes of a glyph to place it off its step ([`Device::placement`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PlacedGlyph {
/// Whether the glyph is of right-to-left text.
pub(crate) right_to_left: bool,
/// The glyph's advance in its line: zero for a mark.
pub(crate) advance: Length,
/// The advance that the glyph's font gives it at its size, which the shaper takes into a
/// mark's move.
pub(crate) own: Length,
/// The glyph's size.
pub(crate) size: Length,
}
/// `length` scaled by `to` over `from`, in whole half-EMUs toward zero; `length` itself when
/// `from` is zero or the scaled length is out of range.
fn scaled(length: Length, (to, from): (Length, Length)) -> Length {
if from == Length::ZERO {
return length;
}
let units = i128::from(length.units()) * i128::from(to.units()) / i128::from(from.units());
i64::try_from(units).map_or(length, Length::from_units)
}
impl Device {
/// The device with `dots` per inch and the target's `quirks`, or `None` for no dots or for
/// a dot smaller than a half-EMU: the one place where the device takes the variants of its
/// quirks. Its glyphs step as [`Advances::PdfSteps`] says, its tab leaders step by the
/// exact advance of their character, and it draws no line along the outlines of synthetic
/// bold glyphs, until the profile gives other numbers.
#[must_use]
pub fn of(dots: i64, quirks: &crate::quirks::Quirks) -> Option<Self> {
Dot::of(dots).map(|dot| Self {
dot,
advances: Advances::PdfSteps,
quirks: *quirks,
leader_step: None,
bold_stroke_parts: None,
italic_slant_parts: None,
page: None,
writer_off: false,
})
}
/// The device with `dots` per inch and the base target's quirks, for tests of the
/// device's arithmetic at other resolutions.
#[cfg(test)]
pub fn per_inch(dots: i64) -> Option<Self> {
Self::of(dots, &base_quirks())
}
/// The device with `dots` per inch and the quirks of the base target's profile with some
/// quirks of another variant (`change`), for a test that names the variant that it means.
///
/// # Panics
///
/// When `dots` gives no device dot, or the profile does not read with the variants.
#[cfg(test)]
#[must_use]
pub fn per_inch_with(
dots: i64,
change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> Self {
Self::of(dots, &change(&crate::profile::Profile::base()).quirks()).expect("a device dot")
}
/// How the edge check of the glyph steps counts a glyph's exact right edge: the variant of
/// the quirk `GlyphEdgeCheck` that the device carries ([`EdgeSteps`]).
#[must_use]
const fn glyph_edge_check(self) -> crate::quirks::GlyphEdgeCheck {
self.quirks.glyph_edge_check
}
/// The font side of a glyph that the PDF writer counts for its text objects: the glyph's
/// own `side` under `FontSideChange::StartsObject`, and [`FontSide::Open`], which starts
/// nothing, under `FontSideChange::Joins` ([`TextObjects::starts`]).
#[must_use]
pub const fn writer_side(self, side: FontSide) -> FontSide {
match self.quirks.font_side_change {
crate::quirks::FontSideChange::Joins => FontSide::Open,
crate::quirks::FontSideChange::StartsObject => side,
}
}
/// How far a glyph lies `right` of its step, and up, where the font's layout tables move it
/// `(right, up)` from its step. Under `RightToLeftPlacements::Rounded` a glyph of
/// right-to-left text lies its move to the right in whole dots, so that it lies on a dot as
/// its step does, and the move counts at the device's em, the glyph's size in whole dots:
/// scaled from the size to that em. A glyph whose advance in its line is zero, a mark, lies
/// its move with the advance that its font gives it taken out, rounded toward zero, less
/// that advance rounded to the nearest dot: the shaper takes a mark's own advance into its
/// move when it gives the mark no advance in the line. Another glyph lies its move rounded
/// to the nearest dot. Otherwise the glyph lies its exact move. It lies its move up as
/// [`Self::vertical_placement`] says.
#[must_use]
pub(crate) fn placement(
self,
(right, up): (Length, Length),
glyph: PlacedGlyph,
) -> (Length, Length) {
let up = self.vertical_placement(up, glyph.size);
// quirk: RightToLeftPlacements (src/quirks.rs)
match self.quirks.right_to_left_placements {
crate::quirks::RightToLeftPlacements::Rounded if glyph.right_to_left => {
let at_em = |length: Length| scaled(length, (self.em(glyph.size), glyph.size));
let dots = if glyph.advance == Length::ZERO {
self.count(at_em(right + glyph.own), Rounding::TowardZero)
- self.count(at_em(glyph.own), Rounding::HalfUp)
} else {
self.count(at_em(right), Rounding::HalfUp)
};
(self.dots(dots), up)
}
crate::quirks::RightToLeftPlacements::Exact
| crate::quirks::RightToLeftPlacements::Rounded => (right, up),
}
}
/// The device's em at `size`: the size in whole dots, a half up.
fn em(self, size: Length) -> Length {
self.dots(self.count(size, Rounding::HalfUp))
}
/// How far up from the baseline the device draws a glyph of `size` that the font's layout
/// tables move `up`: under `VerticalPlacements::WholeDots` the move at the device's em,
/// rounded toward zero to whole dots, and otherwise the exact move.
#[must_use]
pub(crate) fn vertical_placement(self, up: Length, size: Length) -> Length {
// quirk: VerticalPlacements (src/quirks.rs)
match self.quirks.vertical_placements {
crate::quirks::VerticalPlacements::WholeDots => {
self.dots(self.count(scaled(up, (self.em(size), size)), Rounding::TowardZero))
}
crate::quirks::VerticalPlacements::Exact => up,
}
}
/// Whether the PDF writer writes each glyph of a text object as an object of its own
/// because of a glyph of it that the font's layout tables move `up` at `size`, in
/// right-to-left text when `right_to_left`: under `VerticalPlacements::WholeDots` when the
/// glyph is of right-to-left text and lies one dot or more off the baseline
/// ([`Self::vertical_placement`]), and never otherwise ([`TextObjects::alone_off_baseline`]).
#[must_use]
pub(crate) fn object_per_glyph(self, up: Length, size: Length, right_to_left: bool) -> bool {
// quirk: VerticalPlacements (src/quirks.rs)
match self.quirks.vertical_placements {
crate::quirks::VerticalPlacements::WholeDots => {
right_to_left && self.vertical_placement(up, size) != Length::ZERO
}
crate::quirks::VerticalPlacements::Exact => false,
}
}
/// Whether the PDF writer starts its count of a run of text at a glyph, as at the start of
/// a run of the document ([`TextObjects::starts`]): when `starts`, the glyph starts a run
/// of the document or a text piece, and under `FormatCharacterObjects::StartsObject` also
/// when a format character that the shaper leaves out comes right before it in reading
/// order (`before`).
#[must_use]
pub const fn writer_run_start(self, starts: bool, before: crate::text::LeftOutBefore) -> bool {
match self.quirks.format_character_objects {
crate::quirks::FormatCharacterObjects::Joins => starts,
crate::quirks::FormatCharacterObjects::StartsObject => {
starts || matches!(before, crate::text::LeftOutBefore::FormatCharacter)
}
}
}
/// The text-object starts inside a stretch of right-to-left text counted in reading order,
/// where `glyphs` gives `(ch, side, run_start)` for each glyph of the stretch from the
/// left: the character and font side that the writer counts and whether it starts a run,
/// a text piece, or another face in reading order.
///
/// Under `RightToLeftObjectCount::ReadingOrder` the writer counts objects in reading order
/// from the stretch's right end ([`TextObjects`]):
/// - when an object reaches [`params::TEXT_OBJECT_GLYPHS`], the glyph after it in reading
/// order starts the next object on its left, so on the line drawn from the left the glyph
/// right of it starts an object (`full`);
/// - when a space-only object starts in reading order and a non-space follows it, that
/// space-only object sits right of the non-space on the line, so drawn from the left the
/// leftmost space of that space-only object starts an object (`after_spaces`), while
/// reading-order trailing spaces stay inside the object of the glyphs before them.
///
/// Under `RightToLeftObjectCount::FromTheLeft` none: `reading_order` is `false` and the
/// count of the line's glyphs from its left end decides ([`TextObjects::starts`]).
#[must_use]
pub fn right_to_left_object_starts(
self,
glyphs: &[(char, FontSide, bool)],
) -> RightToLeftObjectStarts {
let len = glyphs.len();
let mut full = vec![false; len];
let mut after_spaces = vec![false; len];
// quirk: RightToLeftObjectCount (src/quirks.rs)
if self.quirks.right_to_left_object_count
== crate::quirks::RightToLeftObjectCount::FromTheLeft
{
return RightToLeftObjectStarts {
reading_order: false,
full,
after_spaces,
};
}
let mut objects = TextObjects::default();
objects.restart();
for (at, &(ch, side, run)) in glyphs.iter().enumerate().rev() {
objects.starts(ch, side, run);
match objects.reason() {
Some(ObjectStart::Full) => {
if let Some(mark) = full.get_mut(at + 1) {
*mark = true;
}
}
Some(ObjectStart::AfterSpaces) => {
if let Some(mark) = after_spaces.get_mut(at + 1) {
*mark = true;
}
}
_ => {}
}
}
RightToLeftObjectStarts {
reading_order: true,
full,
after_spaces,
}
}
/// The character that the PDF writer counts for its text objects in place of `ch`:
/// [`crate::text::LINE_END_HYPHEN`] (which joins surrounding text) for a non-breaking hyphen
/// under `NonBreakingHyphen::OwnGlyph`, and `ch` itself otherwise ([`TextObjects::starts`]),
/// so under `AsHyphenMinus` a non-breaking hyphen forms its own isolated-character run
/// distinct from ASCII `'-'`.
#[must_use]
pub const fn writer_char(self, ch: char) -> char {
match self.quirks.non_breaking_hyphen {
crate::quirks::NonBreakingHyphen::OwnGlyph
if ch == crate::text::NON_BREAKING_HYPHEN =>
{
crate::text::LINE_END_HYPHEN
}
_ => ch,
}
}
/// How far the device draws the last visible glyph of a filled justified line from its
/// steps' place, by the place `space` that the steps give the space after it, whose exact
/// place `x` is the line's right edge: one dot left when `space` lies more than one dot
/// past the nearest dot of `x`, the lower dot at an exact half, and one dot right when it
/// lies more than one dot short of it (`AlignedEnds::OnDots`).
#[must_use]
pub fn justified_end_move(self, space: Length, x: Length) -> Length {
let past = space - self.snap_half_down(x);
let dot = self.dots(1);
if past > dot {
-dot
} else if past < -dot {
dot
} else {
Length::ZERO
}
}
/// How far the device draws the last visible glyph of a filled justified line from its
/// place when a segment of its steps starts at that glyph, by the place `space` that the
/// steps give the space after it and the line's right edge `end`, which lies past `edge`,
/// the dot that the line counts its start from: one dot left when `space` lies more than
/// one dot past the dot of `end`, and one dot right when it lies more than one dot short of
/// it (`AlignedEnds::OnDots`). The right edge takes its dot as a line's
/// start does, by its length from `edge` ([`Self::line_start`]): its nearest dot, and at an
/// exact half the dot that the quirk `LineStartHalves` gives.
#[must_use]
pub fn restarted_end_move(self, space: Length, end: Length, edge: Length) -> Length {
let past = space - edge - self.snap(self.line_start(end - edge));
let dot = self.dots(1);
if past > dot {
-dot
} else if past < -dot {
dot
} else {
Length::ZERO
}
}
/// How far the device draws the last visible glyph of a filled justified line that
/// stretched spaces come right before, whose place with the edge check's move lies `past`
/// right of its exact place: left by whole dots until it lies `limit` or less right of that
/// place, and never right (`SpacedLastGlyph::EdgeLimit`). Zero under the other variant.
#[must_use]
pub fn spaced_end_move(self, past: Length, limit: Length) -> Length {
let over = past - limit;
// quirk: SpacedLastGlyph::EdgeLimit (src/quirks.rs)
if self.quirks.spaced_last_glyph != crate::quirks::SpacedLastGlyph::EdgeLimit
|| over <= Length::ZERO
{
return Length::ZERO;
}
-self.dots(self.count(over, Rounding::Up))
}
/// The same device, whose glyphs step as `advances` says.
#[must_use]
pub const fn with_advances(self, advances: Advances) -> Self {
Self { advances, ..self }
}
/// How the glyphs of a line step on the device.
#[must_use]
pub const fn advances(self) -> Advances {
self.advances
}
/// The offset of the baseline from the rounded top of a box of single spacing, or of exact
/// spacing under `ExactBaseline::BoxForms`, of the exact `height`, whose height rounds down
/// to the device grid, with the baseline `ascent` below its exact top and `descent` above
/// its exact bottom. The line is the first of a paragraph that sets its own space before
/// when `below_space`, whether or not the box holds that space. The device's variant of the
/// quirk `SingleBaseline` decides. With `CutDescent`, the bottom is the rounded height, and
/// the baseline sits the descent above it, cut to whole twips and rounded. With `Centered`,
/// the exact box sits in the middle of the rounded one: the baseline moves up by half of
/// what the height loses, and then rounds. With `RoundedDescentBelowSpace`, the baseline of
/// a line below space before sits the exact descent, rounded, above the rounded height, and
/// every other line takes the centered form.
#[must_use]
pub fn rounded_down_baseline(
self,
(ascent, descent): (Length, Length),
height: Length,
below_space: bool,
) -> Length {
use crate::quirks::SingleBaseline;
let centered = || self.snap(ascent - (height - self.snap(height)).div_toward_zero(2));
match self.quirks.single_baseline {
SingleBaseline::CutDescent => {
self.snap(height) - self.snap(descent.down_to_whole(Length::UNITS_PER_TWIP))
}
// quirk: SingleBaseline::RoundedDescentBelowSpace (src/quirks.rs)
SingleBaseline::RoundedDescentBelowSpace if below_space => {
self.snap(height) - self.snap(descent)
}
// quirk: SingleBaseline::Centered (src/quirks.rs)
SingleBaseline::Centered | SingleBaseline::RoundedDescentBelowSpace => centered(),
}
}
/// The same device, on which the advance of a tab leader's character rounds to `step`, or
/// stays exact for `None`.
#[must_use]
pub const fn with_leader_step(self, step: Option<Length>) -> Self {
Self {
leader_step: step,
..self
}
}
/// The step of a tab leader's grid for a character of `advance`: the advance rounded to the
/// target's leader step, or the exact advance where the target has none.
#[must_use]
pub fn leader_step(self, advance: Length) -> Length {
match self.leader_step {
Some(step) => step * div_round(advance.units(), step.units()),
None => advance,
}
}
/// The same device, which draws a line along the outline of each synthetic bold glyph, a
/// `parts`-th of the drawn size wide, or no line for `None`.
#[must_use]
pub const fn with_bold_stroke(self, parts: Option<NonZeroU32>) -> Self {
Self {
bold_stroke_parts: parts,
..self
}
}
/// The same device, which slants each synthetic italic glyph so that a step up the glyph
/// goes a `parts`-th of the step to the right, or draws it upright for `None`.
#[must_use]
pub const fn with_italic_slant(self, parts: Option<NonZeroU32>) -> Self {
Self {
italic_slant_parts: parts,
..self
}
}
/// The width of the line along the outline of a synthetic bold glyph drawn at `size`, or
/// `None` where the target draws no such line.
#[must_use]
pub fn bold_stroke(self, size: Length) -> Option<Length> {
self.bold_stroke_parts
.map(|parts| Length::from_units(div_round(size.units(), i64::from(parts.get()))))
}
/// The same device, drawing a page `width` wide and `height` high in a section of
/// `orientation`.
#[must_use]
pub const fn with_page(self, width: Length, height: Length, orientation: Orientation) -> Self {
Self {
page: Some(PageSize {
width,
height,
orientation,
}),
..self
}
}
/// The same device, whose glyphs stay at their places on it when `on`, without the PDF
/// writer's adjustments.
#[must_use]
pub const fn with_device_places(self, on: bool) -> Self {
Self {
writer_off: on,
..self
}
}
/// Whether the device's glyphs stay at their places on it, without the PDF writer.
#[must_use]
const fn device_places(self) -> bool {
self.writer_off
}
/// Whether the device draws an object whose box is `object`, from the top left corner of a
/// page `width` by `height`. A target that leaves out objects outside the page draws an
/// object only when its box reaches into the page; it then draws all of it.
#[must_use]
pub fn draws_object(self, object: Edges<Length>, (width, height): (Length, Length)) -> bool {
match self.quirks.off_page_objects {
crate::quirks::OffPageObjects::Drawn => true,
crate::quirks::OffPageObjects::LeftOut => {
object.right > Length::ZERO
&& object.left < width
&& object.bottom > Length::ZERO
&& object.top < height
}
}
}
/// Whether the device draws a line of a text box whose box reaches into the page: the
/// line's top lies at `top` and the bottom of the box's text area, the box inside its
/// insets, at `text_bottom`, from the top of a page `height` high. A target that leaves out
/// objects outside the page leaves out a line whose top lies at or below the page's bottom,
/// and all the lines of a box whose text area ends at or above the page's top; it draws the
/// other lines, also those wholly above the page.
#[must_use]
pub fn draws_box_line(self, (top, text_bottom): (Length, Length), height: Length) -> bool {
match self.quirks.off_page_objects {
crate::quirks::OffPageObjects::Drawn => true,
crate::quirks::OffPageObjects::LeftOut => top < height && text_bottom > Length::ZERO,
}
}
/// One dot of the device, which counts lengths in whole dots.
#[must_use]
pub const fn dot_size(self) -> Dot {
self.dot
}
/// `count` dots as a length, as [`Dot::dots`] says.
#[must_use]
pub fn dots(self, count: i64) -> Length {
self.dot.dots(count)
}
/// The whole dots in a length of `numerator / denominator` half-EMUs, as
/// [`Dot::count_exact`] says.
#[must_use]
pub fn count_exact(self, numerator: i128, denominator: i128) -> Option<i64> {
self.dot.count_exact(numerator, denominator)
}
/// How the part of `length` past the dot below it compares with half a dot, as
/// [`Dot::half_dot_side`] says.
#[must_use]
pub fn half_dot_side(self, length: Length) -> std::cmp::Ordering {
self.dot.half_dot_side(length)
}
/// The whole dots in `length`, rounded as `rounding` says.
#[must_use]
pub fn count(self, length: Length, rounding: Rounding) -> i64 {
self.dot.count(length, rounding)
}
/// The turn with which the device draws each glyph of a run of drawn size `size` and
/// character scale `percent` (`w:w`) in a face of `metrics`, about the glyph's origin, or
/// `None` for glyphs upright at their normal width. With `ScaledGlyphs::AverageWidthDots`,
/// the glyphs are narrowed or widened by N/A, where A is the face's average width at the
/// drawn size in whole dots, a half up, and N is A times the scale, rounded down; a run
/// whose N is A or 0 stays upright. A synthetic italic glyph (`slanted`) leans by the
/// device's slant after that scale: a step up the scaled glyph goes the slant's part of
/// the step to the right.
#[must_use]
pub fn glyph_turn(
self,
size: Length,
metrics: &crate::FaceMetrics,
percent: Option<i64>,
slanted: bool,
) -> Option<f_office_paint::Turn> {
let whole = f_office_paint::Turn::SCALE;
let xx = self.glyph_scale(size, metrics, percent);
// A step down the glyph goes left, by the whole in millionths over the slant's parts,
// to the nearest millionth.
let xy = self
.italic_slant_parts
.filter(|_| slanted)
.map(|parts| -div_round(i64::from(whole), i64::from(parts.get())));
if xx.is_none() && xy.is_none() {
return None;
}
Some(f_office_paint::Turn {
xx: xx.unwrap_or(whole),
yx: 0,
xy: i32::try_from(xy.unwrap_or(0)).ok()?,
yy: whole,
})
}
/// The factor in millionths by which the device narrows or widens each glyph of a run of
/// drawn size `size` and character scale `percent` in a face of `metrics`, as
/// [`Self::glyph_turn`] says, or `None` for glyphs at their normal width.
fn glyph_scale(
self,
size: Length,
metrics: &crate::FaceMetrics,
percent: Option<i64>,
) -> Option<i32> {
let percent = percent.filter(|p| *p > 0 && *p != PERCENT)?;
match self.quirks.scaled_glyphs {
crate::quirks::ScaledGlyphs::Upright => None,
crate::quirks::ScaledGlyphs::AverageWidthDots => {
let dots = self.count(size, Rounding::HalfUp);
let em = i64::from(metrics.units_per_em);
let average = div_round(i64::from(metrics.average_width) * dots, em);
let count = (average * percent).div_euclid(PERCENT);
let whole = i64::from(f_office_paint::Turn::SCALE);
(average > 0 && count > 0 && count != average).then_some(())?;
i32::try_from(div_round(count * whole, average)).ok()
}
}
}
/// The factor, as a numerator and a denominator, by which the edge check of
/// [`Advances::RightEdge`] scales the exact places of a line from its first glyph: the
/// device's dots per point, kept in [`Advances::RightEdge`]'s `point_steps` per point and
/// rounded up, over the exact dots per point. At 600 dots per inch in steps of 1/1024 it is
/// 8,534/1,024 over 8,533â…“/1,024, 12,801/12,800; a device whose dots per point are a whole
/// number of steps, such as 288 dots per inch, keeps its exact places.
#[must_use]
pub fn exact_scale(self) -> (i64, i64) {
match self.advances {
Advances::RightEdge {
point_steps: Some(point_steps),
..
} => {
let per_point = Length::UNITS_PER_POINT * i64::from(point_steps.get());
let Dot { units, per } = self.dot;
let steps = (per_point * per + units - 1) / units;
(steps * units, per_point * per)
}
_ => (1, 1),
}
}
/// Rounds a position to the nearest dot, a half dot up.
#[must_use]
pub fn snap(self, length: Length) -> Length {
self.dot.snap(length)
}
/// How far right a line moves that is centered (`centered`) or right-aligned in the space
/// up to the dot `edge`, when its written text ends on the dot `end`: the free whole dots,
/// or half of them, rounded down. `None` when the target starts such a line at its exact
/// place.
#[must_use]
pub fn aligned_shift(self, centered: bool, end: Length, edge: Length) -> Option<Length> {
// quirk: AlignedEnds (src/quirks.rs), whose variant the device carries.
if !self.aligns_on_dots() {
return None;
}
let (end, edge) = (end.units(), edge.units());
let free_dots = if edge > end {
self.count(Length::from_units(edge - end), Rounding::TowardZero)
} else {
0
};
let dots = if centered { free_dots / 2 } else { free_dots };
Some(self.dots(dots))
}
/// The dot of the right edge of a line's space, up to which a centered or a right-aligned
/// line moves: the dot `start` of the line's start plus the space's width `width`, which
/// goes to a dot as a line's start past its column's edge does ([`Self::line_start`]).
/// With the quirk `AlignedLineEdge::FromColumnEdge` and a `column`, a column of the page or
/// the text area of an upright table cell, the dot of the column's left edge, `left`, plus the
/// column's width `width` less the space's distance `inset` from the column's right edge,
/// taken to a dot by [`Self::difference_dot`].
#[must_use]
pub fn aligned_edge(
self,
(start, width): (Length, Length),
column: Option<ColumnEdges>,
) -> Length {
match (self.quirks.aligned_line_edge, column) {
// quirk: AlignedLineEdge::FromColumnEdge (src/quirks.rs)
(crate::quirks::AlignedLineEdge::FromColumnEdge, Some(column)) => {
column.left + self.difference_dot(column.width, column.inset)
}
_ => self.snap(start + self.line_start(width)),
}
}
/// `length` less `less`, taken to a dot. With the quirk `LineStartHalves::FixedPoint` each
/// of the two goes to the fixed-point points of [`fixed_points`] on its own, and their
/// difference to the nearest dot, a half up, so that a difference that lies exactly half a
/// dot past a dot goes the way that the two roundings of the first step leave it. Else the
/// difference goes to its nearest dot.
#[must_use]
pub fn difference_dot(self, length: Length, less: Length) -> Length {
if !self.starts_in_fixed_point() {
return self.snap(length - less);
}
self.dots(self.fixed_point_dot(fixed_points(length) - fixed_points(less)))
}
/// Whether a centered or a right-aligned line starts on a dot, by its written end.
#[must_use]
pub const fn aligns_on_dots(self) -> bool {
matches!(self.quirks.aligned_ends, crate::quirks::AlignedEnds::OnDots)
}
/// How far right of the dot `start` of a centered or right-aligned line the text after a tab
/// or a list label's gap counts its segment from, when the line's exact start at its indent is
/// `exact`: the part of a dot that the start lost under the quirk `AlignedLineSegments`'s
/// variant `FromExactStart`, and nothing under `FromStartDot` or for a line whose steps alone
/// decide (`steps_alone`), which keeps the dot.
#[must_use]
pub fn aligned_segment_rest(
self,
(exact, start): (Length, Length),
steps_alone: bool,
) -> Length {
match self.quirks.aligned_line_segments {
crate::quirks::AlignedLineSegments::FromExactStart if !steps_alone => exact - start,
crate::quirks::AlignedLineSegments::FromStartDot
| crate::quirks::AlignedLineSegments::FromExactStart => Length::ZERO,
}
}
/// Whether a start-aligned line of a right-to-left paragraph that does not end the
/// paragraph starts on whole dots by its steps alone (`RightToLeftLineStart::WholeDots`).
#[must_use]
pub const fn starts_right_to_left_on_dots(self) -> bool {
// quirk: RightToLeftLineStart::WholeDots (src/quirks.rs)
matches!(
self.quirks.right_to_left_line_start,
crate::quirks::RightToLeftLineStart::WholeDots
)
}
/// Whether the device draws a justified line of a right-to-left paragraph by its steps
/// alone, ending at the column's edge, with each stretched space spanning its own advance
/// (`RightToLeftJustifiedLine::EndsAtEdge`).
#[must_use]
pub const fn ends_right_to_left_at_edge(self) -> bool {
// quirk: RightToLeftJustifiedLine::EndsAtEdge (src/quirks.rs)
matches!(
self.quirks.right_to_left_justified_line,
crate::quirks::RightToLeftJustifiedLine::EndsAtEdge
)
}
/// How the device's steps take a glyph of a stretch of right-to-left text from the glyph
/// before it in reading order, given the glyph's measured device width with its advance
/// alone and whether it rounds without the bias. As a glyph of left-to-right text
/// (`RightToLeftSteps::DeviceWidths`), the glyph keeps both. By its advance at the nearest
/// dot (`RightToLeftSteps::Nearest`), the glyph steps and counts its right edge without a
/// device width and without the bias, and the step into it from the glyph before rounds
/// their distance to the nearest dot, which this readies on `edge`. Gives the device width
/// and the choice of bias with which the glyph steps.
pub const fn right_to_left_step(
self,
edge: &mut EdgeSteps,
(measured, without_bias): (Option<(i64, Length)>, bool),
) -> (Option<(i64, Length)>, bool) {
// quirk: RightToLeftSteps (src/quirks.rs)
match self.quirks.right_to_left_steps {
crate::quirks::RightToLeftSteps::DeviceWidths => (measured, without_bias),
crate::quirks::RightToLeftSteps::Nearest => {
edge.step_to_nearest_dot();
(None, true)
}
}
}
/// The exact place from which the steps count the exact places of a stretch of
/// right-to-left text in reading order, when the stretch starts its line's steps: the
/// stretch's exact left edge `left` (`RightToLeftCount::LeftEdge`), or the dot of that
/// edge, so that each glyph's exact distance from the stretch's right end goes to whole
/// dots (`RightEnd`). The stretch's glyphs keep the dots of its ends.
#[must_use]
pub fn right_to_left_origin(self, left: Length) -> Length {
// quirk: RightToLeftCount (src/quirks.rs)
match self.quirks.right_to_left_count {
crate::quirks::RightToLeftCount::LeftEdge => left,
crate::quirks::RightToLeftCount::RightEnd => self.snap(left),
}
}
/// The exact left edge of a centered line that ends its right-to-left paragraph, `written`
/// wide, whose space's left edge lies on the dot `start` and right edge on the dot `edge`:
/// where its right end lies on `edge`, moved left by half the free whole dots, rounded
/// down, between the dot where its text then ends, `written` to the nearest dot left of
/// `edge`, and `start` (`RightToLeftCenteredLine::OnDots`). `None` where the line keeps its
/// exact place (`Exact`) or the device does not start aligned lines on dots.
#[must_use]
pub fn right_to_left_center(
self,
(start, edge): (Length, Length),
written: Length,
) -> Option<Length> {
// quirk: RightToLeftCenteredLine (src/quirks.rs)
match self.quirks.right_to_left_centered_line {
crate::quirks::RightToLeftCenteredLine::Exact => None,
crate::quirks::RightToLeftCenteredLine::OnDots => {
let moved = self.aligned_shift(true, start, edge - self.snap(written))?;
Some(edge - moved - written)
}
}
}
/// A length from a page's or a column's edge, `start`, as the length that rounds to its
/// dot: `start` itself, or, where the fixed-point arithmetic of the quirk
/// `LineStartHalves` gives another dot than the nearest one, one half-EMU toward that dot.
/// That arithmetic takes the length to the nearest point in binary fixed point with
/// `params::LINE_START_FRACTION_BITS` fraction bits, a half up, and that number to the
/// nearest dot, a half up, so a length that ends exactly half a dot past a whole dot goes
/// the way that the first step rounded it.
///
/// A length below zero, a start left of the edge, takes the mirror of the dot of its size,
/// so that each rounding takes a half away from zero.
#[must_use]
pub fn line_start(self, start: Length) -> Length {
if !self.starts_in_fixed_point() {
return start;
}
let dot = if start.units() < 0 {
-self.fixed_point_snap(Length::from_units(-start.units()))
} else {
self.fixed_point_snap(start)
};
let nearest = self.count(start, Rounding::HalfUp);
Length::from_units(start.units() + (dot - nearest).signum())
}
/// [`Self::line_start`] for the start of a paragraph's first line, `start` past its
/// column's edge, of which `own` is the first line's own indent on top of the left indent.
/// With the quirk `FirstLineIndentHalves::Parts`, the left indent and `own` each go to the
/// fixed-point points of [`fixed_points`] on their own and their sum to the nearest dot, a
/// half up, so a start that lies exactly half a dot past a whole dot goes the way that the
/// two roundings leave it. A start left of the column's edge keeps [`Self::line_start`].
#[must_use]
pub fn first_line_start(self, start: Length, own: Length) -> Length {
// quirk: FirstLineIndentHalves::Parts (src/quirks.rs)
let parts = matches!(
self.quirks.first_line_indent_halves,
crate::quirks::FirstLineIndentHalves::Parts
);
if !parts || own.units() == 0 || start.units() < 0 || !self.starts_in_fixed_point() {
return self.line_start(start);
}
let left = Length::from_units(start.units() - own.units());
let dot = self.fixed_point_dot(fixed_points(left) + fixed_points(own));
let nearest = self.count(start, Rounding::HalfUp);
Length::from_units(start.units() + (dot - nearest).signum())
}
/// How far a tab stop `distance` past a line's start moves before it goes to its dot, when
/// the line starts `start` past its column's edge, `own` of it the first line's own indent:
/// what [`Self::line_start`] adds to the stop's distance from the column's edge, less what
/// [`Self::first_line_start`] adds to the line's start. The stop then takes the dot of its
/// own distance from the column's edge.
#[must_use]
pub fn stop_halves(self, (start, own): (Length, Length), distance: Length) -> Length {
let halves = |length: Length| self.line_start(length) - length;
halves(start + distance) - (self.first_line_start(start, own) - start)
}
/// The rounded top of a line of single spacing whose height rounds down, `top` from the
/// page's top: the nearest dot, a half up, or with the quirk `TopHalves::FixedPoint`, for a
/// top that is a whole number of twips, the dot of the fixed-point arithmetic of
/// [`Self::line_start`], so that such a top that lies exactly half a dot past a whole dot
/// goes the way that the first step rounded it. Another top, such as a sum of exact line
/// heights, lies on half a dot only in F-Office's half-EMUs and keeps the half up.
#[must_use]
pub fn top_dot(self, top: Length) -> Length {
match self.quirks.top_halves {
// quirk: TopHalves::FixedPoint (src/quirks.rs)
crate::quirks::TopHalves::FixedPoint => self.fixed_point_or(top, Self::snap),
crate::quirks::TopHalves::AwayFromTop => self.snap(top),
}
}
/// The length `rise` of a run's shift, up from the baseline, on its dot where its glyphs are
/// drawn: the nearest dot, a half up the page, or with the quirk
/// `ShiftDots::HalfAwayFromBaseline`, a half away from the baseline, so that a lowering that
/// lies exactly half a dot past a whole dot goes to the dot below it.
#[must_use]
pub fn shift_dots(self, rise: Length) -> Length {
let rounding = match self.quirks.shift_dots {
// quirk: ShiftDots::HalfAwayFromBaseline (src/quirks.rs)
crate::quirks::ShiftDots::HalfAwayFromBaseline if rise < Length::ZERO => {
Rounding::HalfDown
}
crate::quirks::ShiftDots::HalfAwayFromBaseline | crate::quirks::ShiftDots::HalfUp => {
Rounding::HalfUp
}
};
self.dots(self.count(rise, rounding))
}
/// The rounded exact bottom of a footer line of single spacing whose baseline rounds from
/// it, `bottom` from the page's top: the nearest dot, a half up, or with the quirk
/// `FooterHalves::FixedPoint`, for a bottom that is a whole number of twips, the dot of the
/// fixed-point arithmetic of [`Self::top_dot`].
#[must_use]
pub fn footer_bottom_dot(self, bottom: Length) -> Length {
match self.quirks.footer_halves {
// quirk: FooterHalves::FixedPoint (src/quirks.rs)
crate::quirks::FooterHalves::FixedPoint => self.fixed_point_or(bottom, Self::snap),
crate::quirks::FooterHalves::AwayFromTop => self.snap(bottom),
}
}
/// A rounded place of a header line, `at` from the page's top: the nearest dot, a half
/// down, or with the quirk `HeaderHalves::FixedPoint`, for a place that is a whole number of
/// twips, the dot of the fixed-point arithmetic of [`Self::top_dot`], as a body line's top.
#[must_use]
pub fn header_dot(self, at: Length) -> Length {
match self.quirks.header_halves {
// quirk: HeaderHalves::FixedPoint (src/quirks.rs)
crate::quirks::HeaderHalves::FixedPoint => {
self.fixed_point_or(at, Self::snap_half_down)
}
crate::quirks::HeaderHalves::TowardTop => self.snap_half_down(at),
}
}
/// The dot of `at` from the page's top under a quirk of a half dot whose variant is
/// `FixedPoint`: for a place that is a whole number of twips, the dot of the fixed-point
/// arithmetic of [`Self::line_start`]; for another place, the dot that `otherwise` gives.
fn fixed_point_or(self, at: Length, otherwise: fn(Self, Length) -> Length) -> Length {
if at.units() % Length::UNITS_PER_TWIP == 0 {
self.dots(self.fixed_point_snap(at))
} else {
otherwise(self, at)
}
}
/// Whether the device takes the start of a line through fixed-point points.
const fn starts_in_fixed_point(self) -> bool {
// quirk: LineStartHalves (src/quirks.rs), whose variant the device carries.
matches!(
self.quirks.line_start_halves,
crate::quirks::LineStartHalves::FixedPoint
)
}
/// The dot of `length` by the fixed-point arithmetic of the quirks
/// `LineStartHalves::FixedPoint` and `TopHalves::FixedPoint`: the length goes to the
/// fixed-point points of [`fixed_points`], a half up, and those to the nearest dot, a half
/// up, as a number of dots.
fn fixed_point_snap(self, length: Length) -> i64 {
self.fixed_point_dot(fixed_points(length))
}
/// The nearest dot, a half up, of a length in the fixed-point points of [`fixed_points`],
/// as a number of dots.
fn fixed_point_dot(self, fixed: i64) -> i64 {
let one = 1_i64 << params::LINE_START_FRACTION_BITS;
let parts = i128::from(fixed) * i128::from(Length::UNITS_PER_POINT);
saturated(div_round_i128(
parts * i128::from(self.dot.per),
i128::from(one * self.dot.units),
))
}
/// The dot of an edge that is the sum of `parts`, such as a table cell's text edge (the
/// left edge of the page's column, the cell's edge past it and the cell's left margin) or
/// a later column's left edge (the left margin and each earlier column's width with the
/// space after it). With the quirk `LineStartHalves::FixedPoint` each part goes to
/// fixed-point points of `params::LINE_START_FRACTION_BITS`, a half up, the parts are
/// summed there, and the sum goes to the nearest dot, a half up. Else the sum goes to the
/// nearest dot.
#[must_use]
pub fn parts_dot(self, parts: impl IntoIterator<Item = Length>) -> Length {
if !self.starts_in_fixed_point() {
return self.snap(parts.into_iter().sum());
}
let sum = parts.into_iter().map(fixed_points).sum();
self.dots(self.fixed_point_dot(sum))
}
/// The nearest dot of `place`, a half up, from its fixed-point points.
#[must_use]
pub fn fixed_place_dot(self, place: FixedPlace) -> Length {
self.dots(self.fixed_point_dot(place.fixed))
}
/// The dot of an edge that lies `parts` right of `place`: each part in fixed-point points,
/// a half up, added to the place's points, and the sum to the nearest dot, a half up.
#[must_use]
pub fn parts_dot_from(
self,
place: FixedPlace,
parts: impl IntoIterator<Item = Length>,
) -> Length {
let sum = place.fixed + parts.into_iter().map(fixed_points).sum::<i64>();
self.dots(self.fixed_point_dot(sum))
}
/// Which side of the exact sum of a table cell's three lengths their fixed-point sum
/// ([`Self::parts_dot`]) lies on: -1 below it, 1 above it, and 0 on it or where the device
/// does not sum them in fixed point.
#[must_use]
pub fn parts_side(self, origin: Length, edge: Length, inner: Length) -> i64 {
if !self.starts_in_fixed_point() {
return 0;
}
let one = 1_i64 << params::LINE_START_FRACTION_BITS;
let fixed = fixed_points(origin) + fixed_points(edge) + fixed_points(inner);
(fixed * Length::UNITS_PER_POINT - (origin + edge + inner).units() * one).signum()
}
/// Rounds a position down to a whole dot.
#[must_use]
pub fn floor(self, length: Length) -> Length {
self.dots(self.count(length, Rounding::Down))
}
/// Rounds a position up to a whole dot.
#[must_use]
pub fn ceil(self, length: Length) -> Length {
self.dots(self.count(length, Rounding::Up))
}
/// The thickness on the device of a drawn line whose exact thickness is `thickness`:
/// rounded to whole dots as `rounding` says, and at least one dot. This is the one floor
/// of every line of the text layout whose thickness comes from the document or a font and
/// that it draws as a rectangle: an underline, a strikethrough, a note separator's rule, a
/// fraction's bar, and a line of a paragraph, table or page border. A line whose thickness
/// rounds to no dot is still drawn one dot thick. A line of a fixed width in dots does not
/// take it: the change bar (`params::CHANGE_BAR_WIDTH`), the strokes of a check box
/// (`params::CHECK_BOX_STROKE`) and the outline of a balloon. Nor do a chart's gridlines
/// and axis: they take the width of the chart's line, off the dots (`chart_rule`).
#[must_use]
pub fn line_thickness(self, thickness: Length, rounding: LineRounding) -> Length {
let dots = match rounding {
LineRounding::Nearest => self.snap(thickness),
LineRounding::Down => self.floor(thickness),
};
dots.max(self.dots(1))
}
/// Rounds a position to the nearest dot, a half dot down.
#[must_use]
pub fn snap_half_down(self, length: Length) -> Length {
self.dots(self.count(length, Rounding::HalfDown))
}
/// Rounds a length to the nearest dot, a half dot away from zero: a length below zero takes
/// the mirror of the dot of its size.
#[must_use]
pub fn snap_half_away(self, length: Length) -> Length {
if length.units() < 0 {
Length::from_units(-self.snap(Length::from_units(-length.units())).units())
} else {
self.snap(length)
}
}
}
/// The edges of a column of the page that a line's space lies in, for the right edge of a
/// centered or a right-aligned line ([`Device::aligned_edge`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnEdges {
/// The dot of the column's left edge.
pub left: Length,
/// The column's width.
pub width: Length,
/// The distance of the space's right edge from the column's right edge.
pub inset: Length,
}
/// A place that a target keeps in fixed-point points (`Device::centered_outer_edge`): its
/// exact x and its x in fixed-point points, which can lie on the other side of a
/// half dot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FixedPlace {
/// The exact x.
pub exact: Length,
fixed: i64,
}
/// A length in points in binary fixed point with `params::LINE_START_FRACTION_BITS` fraction
/// bits, a half up, as the quirk `LineStartHalves::FixedPoint` counts a line's start and
/// `TopHalves::FixedPoint` the top of a line.
const fn fixed_points(length: Length) -> i64 {
let one = 1_i64 << params::LINE_START_FRACTION_BITS;
div_round(length.units() * one, Length::UNITS_PER_POINT)
}
/// Whether the points in binary fixed point of [`fixed_points`] hold `length` exactly, as they
/// hold a length of whole twips that is a whole number of quarter points.
pub(crate) const fn in_fixed_points(length: Length) -> bool {
let one = 1_i64 << params::LINE_START_FRACTION_BITS;
(length.units() * one) % Length::UNITS_PER_POINT == 0
}
/// How the PDF writer of [`Advances::RightEdge`] draws the glyphs of one text object.
///
/// The object starts at its first glyph's place plus the writer's offset, which the target's
/// configuration gives ([`Self::starting`]): the place from the page's left edge divided by a
/// share, plus a bias, rounded to a step. The start is written with five significant digits, so
/// that from 100 pt it is rounded again to 0.01 pt. From there each glyph steps by its width in
/// whole thousandths of an em (its advance, rounded), a character spacing that is the same for the
/// whole object, and an adjustment in whole thousandths toward the next place. The character
/// spacing is a step less its width that most steps share, so that those steps need no adjustment,
/// and else 0: the quirk `WriterSpacing` says which ([`character_spacing`]). With `ideal` the
/// adjustment that would reach the next place exactly, a step shorter than the width and the
/// spacing takes `ideal` rounded, and a longer one takes `ideal + 1`, both rounded to the nearest
/// whole number. An exact half of a longer step goes to the lower number, and one of a shorter step
/// to the higher number, the one farther from zero (the variant `WriterAdjustments::ExactIdeal`).
/// An ideal inside the dead zone is not written and carries to the next step. Right after a written
/// adjustment, an ideal on the dead zone's edge toward a longer step carries too, and one toward a
/// shorter step carries when the ideal that the glyph's exact advance gives, in place of its width,
/// lies inside the dead zone.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TextObject {
/// The place of each glyph so far, and its width in whole thousandths of an em.
glyphs: Vec<(Length, i64)>,
/// The size at which the writer draws the object.
size: Length,
/// The writer's offset of the object's start, and the width of the page on which it
/// lies.
start: (f_office_paint::Offset, Length),
/// Whether the glyphs keep their places on the device from the written start, without
/// adjustments ([`Device::device_places`]).
device_places: bool,
/// Whether the current object is drawn glyph by glyph with `TD` moves from its single `Tm`
/// start (`VerticalPlacements::WholeDots`), keeping its glyphs' places on the device from the
/// first glyph's written start without re-applying the writer's page offset or adjustments.
per_glyph: bool,
/// Which count the writer rounds to an adjustment, and with `TwoSums` which decides every
/// step.
adjustments: crate::quirks::WriterAdjustments,
/// Which length the writer gives the object as its character spacing.
spacing: crate::quirks::WriterSpacing,
/// Which character spacing the writer draws the object's glyphs with.
written: crate::quirks::WrittenSpacing,
}
impl TextObject {
/// An empty object whose writer offsets its start by `start` of its place, on a page
/// `page_width` wide.
#[must_use]
pub fn starting(start: f_office_paint::Offset, page_width: Length) -> Self {
Self {
start: (start, page_width),
..Self::default()
}
}
/// The same object, whose glyphs keep their places on the device from the written start
/// when `on`, without the writer's adjustments: for a measurement of those places.
#[must_use]
pub fn with_device_places(self, on: bool) -> Self {
Self {
device_places: on,
..self
}
}
/// An empty object of the PDF writer of `device`: the writer offsets its start by the
/// offset that the device's glyph steps give on the device's page (none without edge
/// steps), its glyphs keep their places on the device when the device says so, and it
/// takes the variants of the quirks `WriterAdjustments` and `WriterSpacing` that the device
/// carries: the adjustment count, which with `TwoSums` decides every step too, and the
/// character spacing of the object.
#[must_use]
pub fn of(device: &Device) -> Self {
let start = match device.advances {
Advances::RightEdge { start, .. } => start,
Advances::PdfSteps => f_office_paint::WriterOffset::NONE,
};
// The offset on the device's page. A device without a page takes none: the layout
// gives its device the page that it draws at each page and section
// (`Device::with_page`), so only a device outside a layout has none, and it draws no
// text object.
let (start, width) = match device.page {
Some(page) => {
let (width, height) = (page.width.units(), page.height.units());
let on_page = start.on_page(width, height, page.orientation).0;
(on_page, page.width)
}
None => (f_office_paint::Offset::None, Length::ZERO),
};
Self {
// quirk: WriterAdjustments (src/quirks.rs), whose variant the device carries.
adjustments: device.quirks.writer_adjustments,
// quirk: WriterSpacing (src/quirks.rs), whose variant the device carries.
spacing: device.quirks.writer_spacing,
// quirk: WrittenSpacing (src/quirks.rs), whose variant the device carries.
written: device.quirks.written_spacing,
..Self::starting(start, width).with_device_places(device.device_places())
}
}
/// Adds the next glyph of the object, whose place is `place`, whose advance is `advance`
/// and whose font size is `size`. Its width is `written`, the target's written width in
/// whole thousandths of an em, when there is one (the quirk `WrittenWidths` of the shaper),
/// and else its advance rounded to whole thousandths.
///
/// The writer draws the object at the size `drawn`, the size on the device's grid, in
/// place of the nominal size `size`. The glyph's width in thousandths of an em stays the
/// font's, and the writer counts the steps and the adjustments in thousandths of the drawn
/// em.
pub fn push_at(
&mut self,
place: Length,
advance: Length,
(size, drawn): (Length, Length),
written: Option<u16>,
) {
let rounded = || {
if size > Length::ZERO {
div_round(advance.units() * THOUSANDTHS, size.units())
} else {
0
}
};
let width = written.map_or_else(rounded, i64::from);
self.glyphs.push((place, width));
self.size = drawn;
}
/// Marks the current text object as drawn glyph by glyph with relative `TD` moves from its
/// first glyph's written start (`VerticalPlacements::WholeDots`); reset when [`Self::draw`]
/// finishes the object.
pub(crate) fn set_per_glyph(&mut self) {
self.per_glyph = true;
}
/// Whether the object holds no glyph.
#[must_use]
pub fn is_empty(&self) -> bool {
self.glyphs.is_empty()
}
/// Where the writer draws each glyph of the object, and empties the object: the half-EMU
/// nearest the writer's exact place, which is the object's start plus whole thousandths
/// of the em times the drawn size, and the character spacing, summed without rounding.
pub fn draw(&mut self) -> Vec<Length> {
// The writer counts its steps in half-EMUs and in thousandths of an em times the
// size, so the places go to bare half-EMUs here and come back as lengths.
let glyphs: Vec<(i64, i64)> = std::mem::take(&mut self.glyphs)
.into_iter()
.map(|(place, width)| (place.units(), width))
.collect();
let drawn = self
.writer_places(&glyphs)
.into_iter()
.map(|exact| Length::from_units(div_round(exact, THOUSANDTHS)))
.collect();
self.per_glyph = false;
drawn
}
/// Where the writer writes the start of an object whose first glyph lies at `place` across
/// the page: the place plus the writer's offset on the page, with the writer's digits
/// ([`written_start`]), at the nearest half-EMU.
#[must_use]
pub fn written_start_of(&self, place: Length) -> Length {
Length::from_units(div_round(self.exact_start_of(place), THOUSANDTHS))
}
/// The start of [`Self::written_start_of`] exactly, in thousandths of a half-EMU.
fn exact_start_of(&self, place: Length) -> i64 {
let (offset, page_width) = self.start;
let place = place.units();
let exact = offset.of_in(place, page_width.units(), THOUSANDTHS);
written_start(place, (exact, offset.of(place, page_width.units())))
}
/// Where the writer draws each of `glyphs`, given by their places in half-EMUs and their
/// widths in whole thousandths of an em, in thousandths of a half-EMU.
fn writer_places(&self, glyphs: &[(i64, i64)]) -> Vec<i64> {
let size = self.size.units();
let Some(&(first, _)) = glyphs.first() else {
return Vec::new();
};
let start = self.exact_start_of(Length::from_units(first));
if size <= 0 {
return glyphs
.iter()
.map(|&(place, _)| place * THOUSANDTHS)
.collect();
}
if self.device_places || self.per_glyph {
return glyphs
.iter()
.map(|&(place, _)| start + (place - first) * THOUSANDTHS)
.collect();
}
// Each step less its glyph's width, in thousandths of a half-EMU.
let excesses: Vec<i64> = glyphs
.windows(2)
.filter_map(|pair| match pair {
[(place, width), (next, _)] => Some(THOUSANDTHS * (next - place) - width * size),
_ => None,
})
.collect();
// The writer decides with `spacing` and draws with `written`.
let (spacing, written) = written_spacing(self.written, self.spacing, &excesses);
// quirk: WriterAdjustments (src/quirks.rs)
if self.adjustments == crate::quirks::WriterAdjustments::TwoSums {
return two_sum_places(start, glyphs, size, (spacing, written));
}
let mut drawn = vec![start];
let mut at = start;
// What the steps since the last written adjustment left out, in thousandths of an em
// times the size.
let mut skipped = 0;
// The writer's own count since the last written adjustment, which decides a step on
// the edge of the dead zone.
let mut count = WriterCount::default();
for (&(_, width), &excess) in glyphs.iter().zip(&excesses) {
// The adjustment that reaches the next place exactly, in thousandths of an em, is
// `left / size`, with what the steps before left out.
let left = spacing - excess + skipped;
// An adjustment of less than the dead zone is not written, and what it would have
// moved carries to the next step. One of exactly the dead zone is written or
// carried as the writer's own count in single precision falls.
let dead = params::WRITER_DEAD_ZONE * size;
count.step(width * size + spacing, width * size + excess, size);
// quirk: WriterAdjustments (src/quirks.rs)
let wrote = left.abs() > dead || left.abs() == dead && count.reaches_dead_zone();
if !wrote {
skipped = left;
at += width * size + written;
drawn.push(at);
continue;
}
skipped = 0;
// A step longer than its width and spacing takes the ideal plus a thousandth,
// rounded to the nearest thousandth, an exact half to the lower one. A shorter
// step takes the ideal rounded, and its exact half goes to the higher thousandth.
// quirk: WriterAdjustments (src/quirks.rs)
let adjustment = if self.adjustments == crate::quirks::WriterAdjustments::SingleCount {
count.adjustment(left)
} else if left > 0 {
div_round(left, size)
} else {
-div_round(-(left + params::WRITER_LONGER_EXTRA * size), size)
};
count = WriterCount::default();
at += (width - adjustment) * size + written;
drawn.push(at);
}
drawn
}
}
/// The character spacing that the PDF writer gives a text object whose steps exceed their
/// glyphs' widths by `excesses`, in thousandths of a half-EMU, as the quirk `WriterSpacing`
/// says: with `SharedStep` the excess that at least 20 of each 23 steps share exactly,
/// unrounded; with `FirstStep` the first step's excess, rounded to a step of
/// `params::WRITER_SPACING_STEPS` per point, when each of the first
/// `params::WRITER_SPACING_LOOKAHEAD` steps lies less than `params::WRITER_SPACING_BAND`
/// hundredths of a point from it, whatever the size and whatever the later steps. Else 0.
fn character_spacing(rule: crate::quirks::WriterSpacing, excesses: &[i64]) -> i64 {
// quirk: WriterSpacing (src/quirks.rs)
match rule {
crate::quirks::WriterSpacing::SharedStep => {
let steps = count_factor(excesses.len());
let (share, of) = params::WRITER_SPACING_SHARE;
let mut counts = std::collections::BTreeMap::<i64, usize>::new();
for &excess in excesses {
*counts.entry(excess).or_default() += 1;
}
counts
.iter()
.max_by_key(|&(_, &count)| count)
.filter(|&(_, &count)| of * i64::try_from(count).unwrap_or(0) >= share * steps)
.map_or(0, |(&excess, _)| excess)
}
crate::quirks::WriterSpacing::FirstStep => first_excess(excesses).map_or(0, |first| {
let unit = Length::UNITS_PER_POINT * THOUSANDTHS / params::WRITER_SPACING_STEPS;
div_round(first, unit) * unit
}),
}
}
/// The first of `excesses` when each of the first `params::WRITER_SPACING_LOOKAHEAD` lies less
/// than `params::WRITER_SPACING_BAND` hundredths of a point from it, as
/// `WriterSpacing::FirstStep` asks, and else `None`.
fn first_excess(excesses: &[i64]) -> Option<i64> {
let &first = excesses.first()?;
// The writer looks at the first steps only: each must lie less than the band from the
// first step's excess.
let band = Length::UNITS_PER_POINT * THOUSANDTHS * params::WRITER_SPACING_BAND / PERCENT;
let lookahead = usize::try_from(params::WRITER_SPACING_LOOKAHEAD).unwrap_or(0);
(!excesses
.iter()
.take(lookahead)
.any(|&excess| (excess - first).abs() >= band))
.then_some(first)
}
/// The character spacing with which the PDF writer decides adjustments and the spacing with
/// which it draws a text object whose steps exceed their glyphs' widths by `excesses`, both in
/// thousandths of a half-EMU, as the quirks `WrittenSpacing` and `WriterSpacing` say: with
/// `AsCounted` both equal [`character_spacing`]; with `PrintedDigits` and `FirstStep` the writer
/// decides with the unrounded first step's excess ([`first_excess`]) and draws with that excess
/// printed by [`printed_points`]; with `PrintedDigits` and `SharedStep` it decides with the
/// unrounded shared excess and draws with [`printed_points`].
fn written_spacing(
written: crate::quirks::WrittenSpacing,
rule: crate::quirks::WriterSpacing,
excesses: &[i64],
) -> (i64, i64) {
// quirk: WrittenSpacing (src/quirks.rs)
match (written, rule) {
(crate::quirks::WrittenSpacing::AsCounted, _) => {
let spacing = character_spacing(rule, excesses);
(spacing, spacing)
}
(crate::quirks::WrittenSpacing::PrintedDigits, crate::quirks::WriterSpacing::FirstStep) => {
let spacing = first_excess(excesses).unwrap_or(0);
(spacing, printed_points(spacing))
}
(
crate::quirks::WrittenSpacing::PrintedDigits,
crate::quirks::WriterSpacing::SharedStep,
) => {
let spacing = character_spacing(rule, excesses);
(spacing, printed_points(spacing))
}
}
}
/// A length `length` in thousandths of a half-EMU as the writer prints it in points: with
/// `params::WRITER_SPACING_DIGITS` significant digits and at least
/// `params::WRITER_SPACING_LEAST_DECIMALS` decimals, a dropped half away from zero. A length
/// whose last printed decimal is no whole number of thousandths of a half-EMU, below a
/// thousandth of a point, keeps its value: what it drops there is below 0.03 half-EMU.
fn printed_points(length: i64) -> i64 {
let point = i128::from(Length::UNITS_PER_POINT * THOUSANDTHS);
let size = i128::from(length).abs();
if size == 0 {
return 0;
}
let ten = i128::from(TENTHS);
// The power of ten of the first significant digit, in points: 10^power <= size < 10^(power + 1).
// A length of an `i64` ends both loops: above a point before 10^19 points, below it before
// 10^-8 points.
let mut power: i32 = 0;
let mut above = point * ten;
while size >= above {
above *= ten;
power += 1;
}
if size < point {
power = -1;
let mut scaled = size * ten;
while scaled < point {
scaled *= ten;
power -= 1;
}
}
let digits = i32::try_from(params::WRITER_SPACING_DIGITS).unwrap_or(i32::MAX);
let least = i32::try_from(params::WRITER_SPACING_LEAST_DECIMALS).unwrap_or(0);
let decimals = (digits - 1 - power).max(least).unsigned_abs();
let scale = ten.pow(decimals);
if point % scale != 0 {
return length;
}
let unit = point / scale;
let rounded = (size + unit / 2) / unit * unit;
let signed = if length < 0 { -rounded } else { rounded };
i64::try_from(signed).unwrap_or(length)
}
// Word's writer counts in binary single precision, whose mantissa the registry records.
const _: () = assert!(params::WRITER_COUNT_BITS == Binary32::BITS);
/// The PDF writer's count of what its steps left out since its last written adjustment: the
/// sum of what the widths and the spacing draw and the sum of the steps to the glyphs' places,
/// both in the drawn em and in single precision. Each term is rounded to single precision
/// before it is added. In exact arithmetic the two differ by the adjustment that the writer
/// carries; the count differs from it by the rounding, which decides a step whose adjustment is
/// exactly the dead zone.
#[derive(Clone, Copy, Debug, Default)]
struct WriterCount {
/// The sum of the widths with their spacing, in the em.
widths: Binary32,
/// The sum of the steps, in the em.
places: Binary32,
}
impl WriterCount {
/// Adds a step whose width and spacing draw `drawn` and whose glyphs lie `step` apart, both
/// in thousandths of a half-EMU, at the size `size` in half-EMUs.
fn step(&mut self, drawn: i64, step: i64, size: i64) {
let em = i128::from(THOUSANDTHS) * i128::from(size);
self.widths = self.widths.plus(Binary32::nearest(drawn.into(), em));
self.places = self.places.plus(Binary32::nearest(step.into(), em));
}
/// The single-precision subtraction followed by the single-precision multiplication,
/// rounded by the existing sign branch and half rule. The longer-step extra is an exact
/// integer added after those operations, so whole rounding commutes with that extra.
fn adjustment(self, ideal: i64) -> i64 {
let count = self.widths.minus(self.places).times(THOUSANDTHS);
let rounded = count.whole(ideal <= 0);
rounded
+ if ideal <= 0 {
params::WRITER_LONGER_EXTRA
} else {
0
}
}
/// Whether the two sums differ by the dead zone or more.
fn reaches_dead_zone(self) -> bool {
self.widths
.differs_by(self.places, params::WRITER_DEAD_ZONE, THOUSANDTHS)
}
}
/// The places, in thousandths of a half-EMU, at which the writer of
/// `WriterAdjustments::TwoSums` draws the glyphs of one text object that starts at `start`, in
/// the same unit, from the glyphs' device places in half-EMUs and widths in whole thousandths
/// of an em, at the drawn size `size` with the character spacing `spacing` that it decides with
/// and the spacing `written` that it draws with, both in thousandths of a half-EMU: each step
/// moves by its width and the written spacing less the number that the two-sum count writes.
fn two_sum_places(
start: i64,
glyphs: &[(i64, i64)],
size: i64,
(spacing, written): (i64, i64),
) -> Vec<i64> {
let mut drawn = vec![start];
let mut at = start;
let mut count = TwoSums::default();
for pair in glyphs.windows(2) {
let [(place, width), (next, _)] = pair else {
continue;
};
let adjustment = count.step(width * size + spacing, next - place, size);
at += (width - adjustment) * size + written;
drawn.push(at);
}
drawn
}
/// The PDF writer's two-sum count: the sum of what the widths and
/// the spacing draw, and the sum of the device steps taken to inches, points and ems of the
/// drawn size, which is taken to inches and points from its dots too, each operation in single
/// precision, since the object's start or the last written adjustment.
#[derive(Clone, Copy, Debug, Default)]
struct TwoSums {
/// The sum of the widths with their spacing, in the em.
widths: Binary32,
/// The sum of the device steps, in the em.
places: Binary32,
}
impl TwoSums {
/// Adds a step whose width and spacing draw `drawn` thousandths of a half-EMU and whose
/// glyphs lie `step` half-EMUs apart on the device, at the drawn size `size` in half-EMUs,
/// and gives the adjustment that the writer writes after it in thousandths of the em, 0
/// when it carries.
fn step(&mut self, drawn: i64, step: i64, size: i64) -> i64 {
let em = i128::from(THOUSANDTHS) * i128::from(size);
self.widths = self.widths.plus(Binary32::nearest(drawn.into(), em));
let inch = Length::UNITS_PER_INCH;
let in_points =
|length: i64| Binary32::nearest(length.into(), inch.into()).times(POINTS_PER_INCH);
// The drawn size is a device length too, its whole dots taken through inches and
// points as a step is, not the size in points.
self.places = self.places.plus(in_points(step).over(in_points(size)));
let count = self.widths.minus(self.places);
let dead = Binary32::nearest(params::WRITER_DEAD_ZONE.into(), THOUSANDTHS.into());
if !count.reaches(dead) {
return 0;
}
*self = Self::default();
count
.times(THOUSANDTHS)
.plus(Binary32::nearest(1, 2))
.toward_zero()
}
}
/// The text-object starts that reading-order counting finds inside a stretch of right-to-left
/// text ([`Device::right_to_left_object_starts`]), in visual left-to-right order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RightToLeftObjectStarts {
/// Whether the target counts objects in reading order for this stretch: when true, the
/// visual pass suppresses its own `AfterSpaces` split and takes [`Self::after_spaces`].
pub reading_order: bool,
/// Glyphs where a new visual object starts because the reading-order object before it
/// holds the most glyphs ([`params::TEXT_OBJECT_GLYPHS`]).
pub full: Vec<bool>,
/// Glyphs where a new visual object starts because in reading order the object right of
/// it holds only leading spaces ([`ObjectStart::AfterSpaces`]).
pub after_spaces: Vec<bool>,
}
/// Whether the previous glyph was an isolated character (`TextObjects`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum AfterAlone {
/// Not an isolated character.
#[default]
None,
/// A dash or special space: consecutive identical copies stay in one text object.
Repeat(char),
/// A non-Latin-1 emoji character: every glyph sits in its own single-glyph text object.
Single,
}
impl AfterAlone {
fn of(ch: char) -> Self {
if crate::character_class::is_emoji_above_latin_1(ch) {
Self::Single
} else if alone(ch) {
Self::Repeat(ch)
} else {
Self::None
}
}
fn starts_alone(self, prev: Self) -> bool {
match self {
Self::None => false,
Self::Single => true,
Self::Repeat(ch) => prev != Self::Repeat(ch),
}
}
fn starts_after(self, prev: Self) -> bool {
self == Self::None && prev != Self::None
}
}
/// Where the PDF writer starts a text object, from whose first glyph [`TextObject`] draws
/// again: at each run of the document, at a dash, a no-break/en/em space, or a non-Latin-1 emoji
/// character and at the glyph after it, after the spaces that start an object, after
/// [`params::TEXT_OBJECT_GLYPHS`] glyphs, and on a target with `FontSideChange::StartsObject` at
/// a change of font side.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextObjects {
/// Why the next glyph starts an object whatever it is: a piece of the line that is not a
/// glyph came before ([`ObjectStart::Fresh`]), reading-order leading spaces start an
/// object here ([`ObjectStart::AfterSpaces`]), or the writer writes each glyph of its
/// object alone ([`ObjectStart::Alone`], [`Self::alone_off_baseline`]); `None` when none
/// holds.
forced: Option<ObjectStart>,
/// Whether the glyph before was an isolated character: consecutive identical dashes or
/// special spaces join into one text object (up to `TEXT_OBJECT_GLYPHS`), while every
/// non-Latin-1 emoji character sits in its own single-glyph text object.
after_alone: AfterAlone,
/// Whether the object so far holds only spaces.
spaces: bool,
/// Whether the next glyph lies in a right-to-left stretch whose leading-space splits come
/// from reading order ([`Self::reading_order_spaces`]).
reading_order_spaces: bool,
/// How many glyphs the object holds so far, or the most that it can hold when the object
/// before the next glyph in reading order is full ([`Self::fill`]).
glyphs: usize,
/// The font side of the last glyph before that has one, or [`FontSide::Open`] when an open
/// character came after it.
side: FontSide,
/// Why the last glyph started an object, or `None` when it did not.
reason: Option<ObjectStart>,
}
/// Why the PDF writer starts a text object at a glyph (`TextObjects::starts`). Only the trace of
/// the test tools reads it; the layout asks only whether an object starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObjectStart {
/// The glyph starts a run of the document, as its caller says.
Run,
/// The glyph starts a run of the line's glyphs: the line's first, or the first in another
/// face. The line's drawing tells it from [`Self::Run`].
GlyphRun,
/// The glyph starts a text piece. The line's drawing tells it from [`Self::Run`].
Piece,
/// The glyph starts a run that starts a text buffer. The line's drawing tells it from
/// [`Self::Run`] and [`Self::GlyphRun`].
Buffer,
/// A piece of the line that is not a glyph, such as a tab or an inline object, came before.
Fresh,
/// The object before holds the most glyphs that the writer puts in one object.
Full,
/// The glyph is an object of its own: a dash or a no-break space, or a glyph of a text
/// object that the writer writes glyph by glyph because a glyph of it lies off the baseline
/// in right-to-left text (`TextObjects::alone_off_baseline`).
Alone,
/// The glyph before is a dash or a no-break space.
AfterAlone,
/// The object before holds only spaces.
AfterSpaces,
/// The glyph's font side differs from the side before.
FontSide,
}
impl TextObjects {
/// Makes the next glyph start a text object, as after a piece of the line that is not a
/// glyph.
pub fn restart(&mut self) {
self.forced = Some(ObjectStart::Fresh);
}
/// Makes the next glyph start a text object because the object before it in reading order
/// holds the most glyphs that the writer puts in one ([`Device::right_to_left_object_starts`]).
pub fn fill(&mut self) {
self.glyphs = self.glyphs.max(params::TEXT_OBJECT_GLYPHS);
}
/// Tells the tracker that the next glyph lies in a right-to-left stretch whose leading
/// space splits are decided in reading order ([`Device::right_to_left_object_starts`]):
/// visual left-to-right `AfterSpaces` is suppressed for this glyph so reading-order
/// trailing spaces stay inside their object.
pub fn reading_order_spaces(&mut self) {
self.reading_order_spaces = true;
}
/// Makes the next glyph start a text object because in reading order the object right of
/// it holds only leading spaces ([`Device::right_to_left_object_starts`]).
pub fn after_spaces(&mut self) {
self.forced.get_or_insert(ObjectStart::AfterSpaces);
}
/// Makes the next glyph start a text object because the writer writes each glyph of the
/// object that holds it as an object of its own: a glyph of that object lies one dot or
/// more off the baseline in right-to-left text ([`Device::object_per_glyph`]).
pub fn alone_off_baseline(&mut self) {
// Such a glyph is an object of its own, as a dash is: the reasons keep one name for both.
self.forced.get_or_insert(ObjectStart::Alone);
}
/// Whether the glyph of `ch` starts a text object, where `side` is the font side that the
/// target's writer counts ([`Device::writer_side`]) and `run` says that it starts a run of
/// the document or of the line.
pub fn starts(&mut self, ch: char, side: FontSide, run: bool) -> bool {
let cur_alone = AfterAlone::of(ch);
let space = ch == ' ';
// The writer ends an object after a fixed number of glyphs, spaces among them.
let full = self.glyphs >= params::TEXT_OBJECT_GLYPHS;
// A glyph whose font side differs from the side of the last glyph before it that has
// one starts an object. An open space keeps the side before it; a space with an explicit
// side (ASCII when ASCII and High ANSI slots differ) updates the side so transitions out
// of High ANSI start a space-only object; any other open character leaves none.
let other_side = side != FontSide::Open && self.side != FontSide::Open && side != self.side;
if !space || side != FontSide::Open {
self.side = side;
}
let after_spaces = if self.reading_order_spaces {
self.forced == Some(ObjectStart::AfterSpaces)
} else {
self.spaces && !space
};
let reasons = [
(run, ObjectStart::Run),
(self.forced == Some(ObjectStart::Fresh), ObjectStart::Fresh),
(full, ObjectStart::Full),
(cur_alone.starts_alone(self.after_alone), ObjectStart::Alone),
(
cur_alone.starts_after(self.after_alone),
ObjectStart::AfterAlone,
),
(after_spaces, ObjectStart::AfterSpaces),
(other_side, ObjectStart::FontSide),
(self.forced == Some(ObjectStart::Alone), ObjectStart::Alone),
];
self.reason = reasons
.into_iter()
.find_map(|(holds, reason)| holds.then_some(reason));
let starts = self.reason.is_some();
self.spaces = space && (starts || self.spaces);
self.after_alone = cur_alone;
self.forced = None;
self.reading_order_spaces = false;
self.glyphs = if starts { 1 } else { self.glyphs + 1 };
starts
}
/// Why the last glyph that [`Self::starts`] took started an object, or `None` when it did
/// not.
#[must_use]
pub const fn reason(&self) -> Option<ObjectStart> {
self.reason
}
}
/// Whether the writer draws a run of identical `ch` glyphs in a text object of its own: a dash
/// (hyphen-minus, non-breaking hyphen, en dash, or em dash), a no-break space, or an en/em space.
const fn alone(ch: char) -> bool {
matches!(
ch,
'-' | crate::text::NON_BREAKING_HYPHEN
| '\u{2013}'
| '\u{2014}'
| '\u{a0}'
| '\u{2002}'
| '\u{2003}'
)
}
/// One dot of 1/300 inch, in half-EMUs: the unit in which some fitted lengths of the parameter
/// registry are counted, because the base target's PDFs showed them in its device's dots. It
/// is a unit of length, not the device of a target.
pub const DOT: i64 = Length::UNITS_PER_DOT;
/// The base target's device, from its profile, for tests of layout functions.
#[cfg(test)]
pub fn base_device() -> Device {
crate::profile::Profile::of(crate::Target::base())
.expect("the base profile reads")
.device()
}
/// The base target's quirks, from its profile, for tests.
#[cfg(test)]
pub fn base_quirks() -> crate::quirks::Quirks {
crate::profile::Profile::of(crate::Target::base())
.expect("the base profile reads")
.quirks()
}
/// A text object's start, its first glyph's `place` in half-EMUs plus the writer's offset, as
/// the writer writes it in points, with [`params::WRITER_START_DIGITS`] significant digits, in
/// thousandths of a half-EMU. The offset comes as `exact`, in thousandths of a half-EMU, and
/// `units`, at the nearest half-EMU. The writer holds the offset as a single-precision number,
/// so a start that lies on a half of the last digit rounds down when that number is below the
/// offset, and up otherwise. A thousandth of a point is 25,400 thousandths of a half-EMU, so
/// every printed digit down to a hundred-thousandth of a point is a whole number of them.
fn written_start(place: i64, (exact, units): (i64, i64)) -> i64 {
let x = place * THOUSANDTHS + exact;
let point = Length::UNITS_PER_POINT * THOUSANDTHS;
let digits = (x / point).max(1).ilog10() + 1;
let scale = TENTHS.pow(params::WRITER_START_DIGITS.saturating_sub(digits));
if x <= 0 || point % scale != 0 {
return x;
}
let unit = point / scale;
let rest = x.rem_euclid(unit);
if 2 * rest == unit && held_below(units) {
return x - rest;
}
(x + unit / 2).div_euclid(unit) * unit
}
/// Whether `offset`, in half-EMUs, held as a single-precision number of points, lies below its
/// exact value.
fn held_below(offset: i64) -> bool {
let point = i128::from(Length::UNITS_PER_POINT);
f_office_paint::single(i128::from(offset), point).is_some_and(|held| {
let (mantissa, exponent) = (i128::from(held.mantissa()), held.exponent());
// `mantissa * 2^exponent` points against `offset / point`.
match u32::try_from(exponent) {
Ok(up) => (mantissa << up) * point < i128::from(offset),
Err(_) => mantissa * point < i128::from(offset) << exponent.unsigned_abs(),
}
})
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
use super::{DOT, Device, EdgeSteps, Edges, PlacedGlyph, Rounding};
use f_office_units::{Length, div_round};
/// The last visible glyph of a justified line moves one dot when its trailing space lies
/// more than one dot from the dot of the line's right edge, counted from the lower dot at
/// an exact half.
#[test]
fn moves_a_justified_lines_last_glyph_by_its_trailing_space_and_the_right_edges_dot() {
let device = Device::per_inch(600).unwrap();
let dot = device.dots(1);
let u = Length::from_units;
let moves = |space: i64, right: Length| device.justified_end_move(dot * space, right);
// A right edge 0.4 dots past dot 100 has dot 100.
let right = dot * 100 + u(dot.units() * 2 / 5);
assert_eq!(moves(101, right), Length::ZERO);
assert_eq!(moves(102, right), -dot);
assert_eq!(moves(99, right), Length::ZERO);
assert_eq!(moves(98, right), dot);
// A right edge exactly half a dot past dot 100 counts from dot 100, where the nearest
// dot a half up, 101, would keep the glyph at 102 and move it at 99.
let half = dot * 100 + u(dot.units() / 2);
assert_eq!(moves(102, half), -dot);
assert_eq!(moves(99, half), Length::ZERO);
assert_eq!(moves(98, half), dot);
}
/// Adds a glyph to `object` whose place, advance and sizes are given in half-EMUs, through
/// [`super::TextObject::push_at`].
fn push_units(
object: &mut super::TextObject,
place: i64,
advance: i64,
(size, drawn): (i64, i64),
written: Option<u16>,
) {
let u = Length::from_units;
object.push_at(u(place), u(advance), (u(size), u(drawn)), written);
}
/// Where the writer draws the glyphs of `object`, in half-EMUs
/// ([`super::TextObject::draw`]).
fn drawn_units(object: &mut super::TextObject) -> Vec<i64> {
object.draw().into_iter().map(Length::units).collect()
}
/// The horizontal factor in millionths with which a device of `dots_per_inch` and the
/// variant `scaled` draws a run of `half_points` at `percent` in a face whose average width
/// is `average` units of 2,048, or `None` for upright glyphs.
fn scaled_factor(
dots_per_inch: i64,
scaled: crate::quirks::ScaledGlyphs,
half_points: i64,
average: i16,
percent: Option<i64>,
) -> Option<i32> {
let device = Device::per_inch_with(dots_per_inch, |p| p.with_variant(scaled));
let size = device.snap(Length::from_half_points(half_points).unwrap());
let metrics = crate::FaceMetrics {
units_per_em: 2048,
average_width: average,
..crate::FaceMetrics::default()
};
let turn = device.glyph_turn(size, &metrics, percent, false)?;
assert_eq!(
(turn.yx, turn.xy, turn.yy),
(0, 0, f_office_paint::Turn::SCALE)
);
Some(turn.xx)
}
#[test]
fn slants_synthetic_italic_glyphs_by_the_devices_part_after_their_scale() {
use crate::quirks::ScaledGlyphs::AverageWidthDots;
let one = f_office_paint::Turn::SCALE;
let device = Device::per_inch_with(600, |p| p.with_variant(AverageWidthDots));
let size = device.snap(Length::from_half_points(18).unwrap());
let metrics = crate::FaceMetrics {
units_per_em: 2048,
average_width: 904,
..crate::FaceMetrics::default()
};
let third = device.with_italic_slant(NonZeroU32::new(3));
// A step up the glyph goes a third of the step right, to the nearest millionth.
let slant = f_office_paint::Turn {
xx: one,
yx: 0,
xy: -333_333,
yy: one,
};
assert_eq!(third.glyph_turn(size, &metrics, None, true), Some(slant));
// The slant leans the glyph of a scaled run as it is, after its scale.
let scaled = third.glyph_turn(size, &metrics, Some(33), true);
assert_eq!(
scaled,
Some(f_office_paint::Turn {
xx: 303_030,
..slant
})
);
// An upright face, and a device without a slant, draw the glyph upright.
assert_eq!(third.glyph_turn(size, &metrics, None, false), None);
assert_eq!(device.glyph_turn(size, &metrics, None, true), None);
}
#[test]
fn draws_scaled_glyphs_with_the_average_width_in_whole_dots() {
use crate::quirks::ScaledGlyphs::AverageWidthDots;
// An average width of 904 units at 9 pt, 75 dots of 600 per inch, is 33 dots: Word
// draws 10 of them at 33%, a factor of 10/33, and 34 at 105%, 34/33.
assert_eq!(
scaled_factor(600, AverageWidthDots, 18, 904, Some(33)),
Some(303_030)
);
assert_eq!(
scaled_factor(600, AverageWidthDots, 18, 904, Some(105)),
Some(1_030_303)
);
// 1067 units at 11 pt, 44 dots of 288 per inch, are 23 dots: 105% draws 24/23.
assert_eq!(
scaled_factor(288, AverageWidthDots, 22, 1067, Some(105)),
Some(1_043_478)
);
}
#[test]
fn draws_upright_without_a_factor_other_than_one_or_zero() {
use crate::quirks::ScaledGlyphs::{AverageWidthDots, Upright};
// 101% of 33 dots draws 33 of them; no scale, 100%, a target that draws upright, and
// 1%, whose factor is 0, draw upright too.
for percent in [Some(101), None, Some(100), Some(1)] {
assert_eq!(scaled_factor(600, AverageWidthDots, 18, 904, percent), None);
}
assert_eq!(scaled_factor(600, Upright, 18, 904, Some(33)), None);
}
#[test]
fn snaps_to_the_dots_of_a_device() {
let device = Device::per_inch(300).unwrap();
assert_eq!(device.dots(1), Length::from_units(DOT));
// A 1417 twip margin (70.85 pt) lands on 295 dots (70.80 pt).
let margin = Length::from_twips(1_417).unwrap();
assert_eq!(device.snap(margin).units(), 295 * DOT);
// 11 pt lands on 46 dots (11.04 pt).
let size = Length::from_half_points(22).unwrap();
assert_eq!(device.snap(size).units(), 46 * DOT);
let dots = |count: i64| Length::from_units(count * DOT);
assert_eq!(device.snap(dots(-2)), dots(-2));
// A half dot goes up.
assert_eq!(device.snap(Length::from_units(DOT / 2)), dots(1));
assert_eq!(device.snap(Length::from_units(-DOT / 2)), Length::ZERO);
assert_eq!(device.floor(dots(3) - Length::from_units(1)), dots(2));
}
#[test]
fn counts_the_dots_of_a_device_whose_dot_is_no_whole_number_of_units() {
// At 3,000 dots per inch a dot is 609.6 half-EMUs: five dots are 3,048.
let device = Device::per_inch(3_000).unwrap();
let u = Length::from_units;
assert_eq!(
[1, 2, 5, -1].map(|n| device.dots(n)),
[u(610), u(1_219), u(3_048), u(-610)]
);
// 1,000 half-EMUs are 1.64 dots.
let rounded = [
Rounding::HalfUp,
Rounding::Down,
Rounding::Up,
Rounding::TowardZero,
]
.map(|rounding| device.count(u(1_000), rounding));
assert_eq!(rounded, [2, 1, 2, 1]);
assert_eq!(device.count(u(-1_000), Rounding::TowardZero), -1);
assert_eq!(device.count(u(-1_000), Rounding::Down), -2);
}
#[test]
fn keeps_each_dot_that_it_made_on_its_dot() {
let roundings = [
Rounding::HalfUp,
Rounding::HalfDown,
Rounding::Down,
Rounding::Up,
Rounding::TowardZero,
];
for dots in [7, 600, 3_000, 6_000] {
let device = Device::per_inch(dots).unwrap();
for k in -50..=50 {
let place = device.dots(k);
assert_eq!(
(device.floor(place), device.ceil(place)),
(place, place),
"{dots}: {k}"
);
let counts = roundings.map(|rounding| device.count(place, rounding));
assert_eq!(counts, [k; 5], "{dots}: {k}");
}
}
}
#[test]
fn finds_half_dots_of_a_device_whose_dot_is_no_whole_number_of_units() {
let device = Device::per_inch(3_000).unwrap();
let u = Length::from_units;
// 1,524 half-EMUs are 2.5 dots: a half dot.
assert!(device.half_dot_side(u(1_524)).is_eq());
assert_eq!(device.count(u(1_524), Rounding::HalfUp), 3);
assert_eq!(device.count(u(1_524), Rounding::HalfDown), 2);
assert!(device.half_dot_side(u(1_523)).is_lt());
assert_eq!(
(device.snap(u(1_000)), device.floor(u(1_000))),
(u(1_219), u(610))
);
// A dot smaller than a half-EMU is no device.
assert!(Device::per_inch(Length::UNITS_PER_INCH + 1).is_none());
assert!(Device::per_inch(Length::UNITS_PER_INCH).is_some());
}
#[test]
fn snaps_a_half_dot_away_from_zero() {
let device = Device::per_inch(300).unwrap();
let dots = |count: i64| Length::from_units(count * DOT);
assert_eq!(device.snap_half_away(Length::from_units(DOT / 2)), dots(1));
assert_eq!(
device.snap_half_away(Length::from_units(-DOT / 2)),
dots(-1)
);
assert_eq!(
device.snap_half_away(Length::from_units(-5 * DOT / 2)),
dots(-3)
);
assert_eq!(
device.snap_half_away(Length::from_units(-5 * DOT / 2 + 1)),
dots(-2)
);
assert_eq!(device.snap_half_away(dots(-2)), dots(-2));
}
#[test]
fn draws_a_line_at_least_one_dot_thick_whatever_its_rounding() {
use super::LineRounding::{Down, Nearest};
let device = Device::per_inch(300).unwrap();
let dots = |count: i64| Length::from_units(count * DOT);
// A line of 2.6 dots is 3 dots to the nearest dot and 2 dots rounded down.
let line = Length::from_units(26 * DOT / 10);
assert_eq!(device.line_thickness(line, Nearest), dots(3));
assert_eq!(device.line_thickness(line, Down), dots(2));
// A line of 0.3 dots rounds to no dot either way, and is drawn one dot thick, as a
// line of no thickness is.
for thin in [Length::from_units(3 * DOT / 10), Length::ZERO] {
assert_eq!(device.line_thickness(thin, Nearest), dots(1));
assert_eq!(device.line_thickness(thin, Down), dots(1));
}
}
#[test]
fn scales_exact_places_by_the_dots_per_point_rounded_up() {
let u = Length::from_units;
let numbers = super::steps::tests::NUMBERS_AT_600_DPI;
let steps = |dots, point_steps: u32| {
Device::per_inch(dots)
.unwrap()
.with_advances(super::Advances::RightEdge {
bias: numbers.0,
limit: numbers.1,
segment: numbers.2,
point_steps: std::num::NonZeroU32::new(point_steps),
start: f_office_paint::WriterOffset::NONE,
})
};
// 600 dots per inch are 8,533â…“ dots per 1,024 points, rounded up to 8,534: 12,801/12,800.
let (numerator, denominator) = steps(600, 1_024).exact_scale();
assert_eq!(numerator * 12_800, denominator * 12_801);
// 288 dots per inch are 4 dots per point, a whole number of steps.
let (numerator, denominator) = steps(288, 1_024).exact_scale();
assert_eq!(numerator, denominator);
assert_eq!(steps(600, 0).exact_scale(), (1, 1));
// A glyph of 40 at 12 pt in Arial's `e` (1,139/2,048 em, 55.615 dots) from 72 pt: its
// fourth glyph lies 1.539 dots past its exact edge and moves; with the scale, the
// seventeenth, at 1.541 dots before the scale, stays.
let device = steps(600, 1_024);
let advance = div_round(1_139 * 12 * Length::UNITS_PER_POINT, 2_048);
let mut edge = super::EdgeSteps::default();
let start = 72 * Length::UNITS_PER_POINT;
let places: Vec<i64> = (0..18)
.map(|k| {
let x = start + k * advance;
edge.place(&device, numbers, u(x), u(advance)).units() / device.dots(1).units()
})
.collect();
let steps: Vec<i64> = places.windows(2).map(|w| w[1] - w[0]).collect();
assert_eq!(steps[2], 55);
assert_eq!(steps[15], 56);
}
#[test]
fn a_nudge_after_a_tab_moves_the_dot_of_the_next_glyph_alone() {
let u = Length::from_units;
let numbers = super::steps::tests::NUMBERS_AT_600_DPI;
let device = Device::per_inch(600)
.unwrap()
.with_advances(super::Advances::RightEdge {
bias: numbers.0,
limit: numbers.1,
segment: numbers.2,
point_steps: std::num::NonZeroU32::new(1_024),
start: f_office_paint::WriterOffset::NONE,
});
let dot = device.dots(1).units();
// The glyph after the tab ends exactly half a dot past 1,215 dots.
let tie = 1_215 * dot + dot / 2;
let places = |nudge: Option<i64>, gap: bool| {
let mut edge = super::EdgeSteps::default();
edge.place(&device, numbers, Length::from_points(72).unwrap(), u(1_000));
edge.tab();
if let Some(nudge) = nudge {
edge.with_stop_nudge(u(nudge));
}
if gap {
edge.gap(&device);
}
let first = edge.place(&device, numbers, u(tie), u(1_000)).units();
let next = edge
.place(&device, numbers, u(tie + 100 * dot), u(1_000))
.units();
(first / dot, next / dot)
};
assert_eq!(places(None, false), (1_216, 1_316));
assert_eq!(places(Some(-1), false).0, 1_215);
// Another gap before the glyph takes the nudge away.
assert_eq!(places(Some(-1), true), (1_216, 1_316));
}
/// A centered line that ends its right-to-left paragraph puts its right end on the dot of
/// its space's right edge, moved left by half the free whole dots, rounded down, between
/// the dot where its text then ends, its width to the nearest dot, and its left edge's dot.
#[test]
fn centers_a_right_to_left_line_from_the_dot_of_its_right_edge() {
use crate::quirks::{AlignedEnds, RightToLeftCenteredLine};
let with = |variant: RightToLeftCenteredLine| {
Device::per_inch_with(600, |p| {
p.with_variant(AlignedEnds::OnDots).with_variant(variant)
})
};
let (device, exact) = (
with(RightToLeftCenteredLine::OnDots),
with(RightToLeftCenteredLine::Exact),
);
let dot = device.dots(1);
let space = (dot * 100, dot * 200);
// 30.4 dots end the text on the dot 170: 70 free dots, of which the line moves 35.
let narrow = dot * 30 + Length::from_units(dot.units() * 2 / 5);
assert_eq!(
device.right_to_left_center(space, narrow),
Some(dot * 165 - narrow)
);
// 30.6 dots end it on the dot 169: 69 free dots, of which the line moves 34.
let wide = dot * 30 + Length::from_units(dot.units() * 3 / 5);
assert_eq!(
device.right_to_left_center(space, wide),
Some(dot * 166 - wide)
);
assert_eq!(exact.right_to_left_center(space, narrow), None);
}
#[test]
fn takes_the_edge_of_an_aligned_line_from_the_column_edge() {
use crate::quirks::{AlignedLineEdge, LineStartHalves};
let plain = Device::per_inch(600).unwrap();
let fixed = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let device = Device::per_inch_with(600, |p| {
p.with_variant(LineStartHalves::FixedPoint)
.with_variant(AlignedLineEdge::FromColumnEdge)
});
let twips = |t: i64| Length::from_twips(t).unwrap();
let dots = |length: Length| length.units() / device.dots(1).units();
// 8,622 twips are 3,592.5 dots. The column's width and the right indent go to
// fixed-point points each on its own, which leaves their difference a little below the
// half or a little above it.
assert_eq!(dots(fixed.difference_dot(twips(9_343), twips(721))), 3_592);
assert_eq!(dots(fixed.difference_dot(twips(9_351), twips(729))), 3_593);
assert_eq!(dots(plain.difference_dot(twips(9_343), twips(722))), 3_592);
// The edge is the column's dot plus that difference, wherever the line starts: a start
// on dot 900 and a space of 8,000 twips (3,333.33 dots) would give dot 4,233.
let column = super::ColumnEdges {
left: twips(1_440),
width: twips(9_343),
inset: twips(721),
};
let space = (twips(2_160), twips(8_000));
assert_eq!(dots(device.aligned_edge(space, Some(column))), 600 + 3_592);
assert_eq!(dots(fixed.aligned_edge(space, Some(column))), 900 + 3_333);
// A table cell's space keeps the edge from its start.
assert_eq!(dots(device.aligned_edge(space, None)), 900 + 3_333);
}
#[test]
fn takes_a_first_line_start_in_two_parts() {
use crate::quirks::{FirstLineIndentHalves, LineStartHalves};
let summed = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let parts = Device::per_inch_with(600, |p| {
p.with_variant(LineStartHalves::FixedPoint)
.with_variant(FirstLineIndentHalves::Parts)
});
let twips = |t: i64| Length::from_twips(t).unwrap();
let dot = |length: Length| summed.snap(length).units() / summed.dots(1).units();
// A left indent of 993 twips less a hanging indent of 567 starts 426 twips past the
// edge, 177.5 dots. As one length it goes up; in two parts the roundings of the left
// indent (down by 0.4 of a unit) and of the hanging indent (up by 0.4) leave it below.
let start = twips(426);
assert_eq!(dot(summed.first_line_start(start, twips(-567))), 178);
assert_eq!(dot(parts.first_line_start(start, twips(-567))), 177);
// A line without an indent of its own keeps the one length.
assert_eq!(dot(parts.first_line_start(start, Length::ZERO)), 178);
// A first-line indent of 66 twips on a left indent of 360: 177.5 dots again. The left
// indent is a whole number of units of 1/65,536 pt and the first-line indent rounds up
// by 0.2 of one, so in two parts it goes up too.
assert_eq!(dot(parts.first_line_start(start, twips(66))), 178);
}
#[test]
fn moves_an_aligned_line_by_its_free_whole_dots() {
use crate::quirks::AlignedEnds;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(AlignedEnds::OnDots));
let dot = device.dots(1);
assert_eq!(plain.aligned_shift(true, Length::ZERO, dot * 9), None);
assert!(device.aligns_on_dots() && !plain.aligns_on_dots());
// Nine free dots: a right-aligned line moves by all of them, a centered one by four.
assert_eq!(
device.aligned_shift(false, dot * 91, dot * 100),
Some(dot * 9)
);
assert_eq!(
device.aligned_shift(true, dot * 91, dot * 100),
Some(dot * 4)
);
// A line that ends past the edge does not move.
assert_eq!(
device.aligned_shift(true, dot * 101, dot * 100),
Some(Length::ZERO)
);
}
#[test]
fn sends_the_half_of_a_line_start_down_by_its_remainder() {
use crate::quirks::LineStartHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |device: Device, twips: i64| {
let start = device.line_start(Length::from_twips(twips).unwrap());
device.snap(start).units() / size
};
// Indents of 12 k + 6 twips end in half a dot of 1/600 inch: 2.5, 7.5, 12.5, 17.5 and
// 22.5 dots, then 27.5. Those that leave 18 or 54 in 60 twips go down.
let dots = [6, 18, 30, 42, 54, 66, 1_134].map(|twips| dot(device, twips));
assert_eq!(dots, [3, 7, 13, 18, 22, 28, 472]);
assert_eq!(dot(plain, 18), 8);
// Far indents keep the period: 5,002.5 dots goes up
// and 5,007.5 down.
assert_eq!(
[12_006, 12_018].map(|twips| dot(device, twips)),
[5_003, 5_007]
);
// Other starts go to the nearest dot.
assert_eq!([17, 19, 1_133].map(|twips| dot(device, twips)), [7, 8, 472]);
// A start that is no whole number of twips keeps the higher dot.
let start = Length::from_units(15 * size / 2 + size * 5);
assert_eq!(device.line_start(start), start);
}
/// The right edge of a line whose last glyph starts a segment of the steps takes its dot as
/// a line's start does, by its length from the line's edge: at exactly half a dot past a
/// whole dot, the lower dot when that length leaves 18 or 54 in 60 twips (0.9 or 0.7 pt past
/// a whole point), so that a space one dot past the upper dot moves the glyph.
#[test]
fn takes_the_dot_of_a_restarted_line_end_as_a_line_start() {
use crate::quirks::LineStartHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let dot = device.dots(1);
let twips = |twips: i64| Length::from_twips(twips).unwrap();
// The line counts its start from the dot of a left margin of 1,450 twips.
let edge = device.snap(twips(1_450));
for (length, moves) in [
(7_242, false),
(7_206, false),
(7_230, false),
(7_194, true),
(7_218, true),
] {
let end = edge + twips(length);
assert_eq!((end - edge).units() % dot.units(), dot.units() / 2);
let space = device.snap(end) + dot;
let expected = if moves { -dot } else { Length::ZERO };
assert_eq!(device.restarted_end_move(space, end, edge), expected);
assert_eq!(plain.restarted_end_move(space, end, edge), Length::ZERO);
}
// An edge off a half dot takes its nearest dot on either device.
let end = edge + twips(7_195);
let space = device.snap(end) + dot * 2;
assert_eq!(device.restarted_end_move(space, end, edge), -dot);
assert_eq!(plain.restarted_end_move(space, end, edge), -dot);
}
#[test]
fn sends_the_half_of_a_start_left_of_the_edge_away_from_zero() {
use crate::quirks::LineStartHalves;
let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |twips: i64| {
let start = device.line_start(Length::from_twips(twips).unwrap());
device.snap(start).units() / size
};
// -810 twips is exactly -337.5 dots in fixed point: the half goes away from zero, to
// the left, where 810 twips goes up to 338.
assert_eq!([-810, -30, 810, 30].map(dot), [-338, -13, 338, 13]);
// A half that the first rounding decides goes the way of its size's.
assert_eq!([-18, -54, -6].map(dot), [-7, -22, -3]);
// Every start left of the edge takes the mirror of its size's dot.
assert!((1..=1_200).all(|twips| dot(-twips) == -dot(twips)));
}
#[test]
fn sends_the_half_of_a_line_top_the_way_of_the_fixed_point_step() {
use crate::quirks::TopHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(TopHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |device: Device, twips: i64| {
device.top_dot(Length::from_twips(twips).unwrap()).units() / size
};
// Top margins of 12 k + 6 twips lie on half a dot: 477.5, 482.5, 487.5, 492.5 and
// 472.5 dots. Those that leave 18 or 54 in 60 twips go up the page.
let margins = [1_146, 1_158, 1_170, 1_182, 1_134];
assert_eq!(
margins.map(|twips| dot(device, twips)),
[478, 482, 488, 493, 472]
);
// The device without the quirk takes the dot farther from the page's top of each.
assert_eq!(
margins.map(|twips| dot(plain, twips)),
[478, 483, 488, 493, 473]
);
// Other tops go to the nearest dot.
assert_eq!(
[1_133, 1_135, 1_440].map(|twips| dot(device, twips)),
[472, 473, 600]
);
}
#[test]
fn sends_a_lowering_on_half_a_dot_away_from_the_baseline() {
use crate::quirks::ShiftDots;
let plain = Device::per_inch(600).unwrap();
let device =
Device::per_inch_with(600, |p| p.with_variant(ShiftDots::HalfAwayFromBaseline));
let size = device.dots(1).units();
let dots = |device: Device, half_points: i64| {
let rise = Length::from_half_points(half_points).unwrap();
device.shift_dots(rise).units() / size
};
// Shifts of 9 and 15 half-points lie on half a dot, 37.5 and 62.5 dots; 4 half-points
// are 16.67 dots.
let shifts = [9, 15, -9, -15, 4, -4];
assert_eq!(shifts.map(|v| dots(device, v)), [38, 63, -38, -63, 17, -17]);
assert_eq!(shifts.map(|v| dots(plain, v)), [38, 63, -37, -62, 17, -17]);
}
#[test]
fn sends_the_half_of_a_footer_bottom_the_way_of_the_fixed_point_step() {
use crate::quirks::FooterHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(FooterHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |device: Device, twips: i64| {
device
.footer_bottom_dot(Length::from_twips(twips).unwrap())
.units()
/ size
};
// Bottoms of 15,114 twips down in steps of 12 lie on half a dot, 6,297.5 dots down in
// steps of 5: 755.7, 755.1, 754.5, 753.9 and 753.3 pt. Those at x.7 and x.9 pt go up the
// page.
let bottoms = [15_114, 15_102, 15_090, 15_078, 15_066];
assert_eq!(
bottoms.map(|twips| dot(device, twips)),
[6_297, 6_293, 6_288, 6_282, 6_278]
);
// The device without the quirk takes the dot farther from the page's top of each.
assert_eq!(
bottoms.map(|twips| dot(plain, twips)),
[6_298, 6_293, 6_288, 6_283, 6_278]
);
// A bottom on half a dot that is no whole number of twips, 6,296.5 dots (15,111.6
// twips), keeps the dot farther from the page's top.
let bottom = Length::from_units(size * 6_296 + size / 2);
assert_eq!(device.footer_bottom_dot(bottom), device.snap(bottom));
}
#[test]
fn sends_the_half_of_a_header_place_the_way_of_the_fixed_point_step() {
use crate::quirks::HeaderHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(HeaderHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |device: Device, twips: i64| {
device
.header_dot(Length::from_twips(twips).unwrap())
.units()
/ size
};
// Places at 426, 510, 1,806 and 2,130 twips (21.3, 25.5, 90.3 and 106.5 pt, at 6 and 30
// twips in 60) go down the page; those at 498 and 1,134
// twips (24.9 and 56.7 pt, 18 and 54 in 60) go up, as the device without the quirk
// sends every half.
let places = [426, 510, 1_806, 2_130, 498, 1_134];
assert_eq!(
places.map(|twips| dot(device, twips)),
[178, 213, 753, 888, 207, 472]
);
assert_eq!(
places.map(|twips| dot(plain, twips)),
[177, 212, 752, 887, 207, 472]
);
// A place on half a dot that is no whole number of twips keeps the dot nearer the page's
// top.
let place = Length::from_units(size * 386 + size / 2);
assert_eq!(device.header_dot(place), device.snap_half_down(place));
}
#[test]
fn keeps_the_dot_away_from_the_top_for_a_line_top_that_the_fixed_point_step_does_not_take() {
use crate::quirks::TopHalves;
let device = Device::per_inch_with(600, |p| p.with_variant(TopHalves::FixedPoint));
let size = device.dots(1).units();
// A top on half a dot that is a whole number of 1/65536 pt, 12.5 dots (1.5 pt), keeps
// the dot farther from the page's top.
let top = Length::from_units(size * 12 + size / 2);
assert_eq!(device.top_dot(top), device.snap(top));
assert_eq!(device.top_dot(top).units() / size, 13);
// A top that is no whole number of twips, such as the sum of exact line heights at
// 339.06 pt (6,781.2 twips, 2,825.5 dots), keeps the dot farther from the page's top,
// though its fixed-point
// step rounds down.
let sum = Length::from_units(size * 2_825 + size / 2);
assert_ne!(sum.units() % Length::UNITS_PER_TWIP, 0);
assert_eq!(device.top_dot(sum).units() / size, 2_826);
assert_eq!(device.fixed_point_snap(sum), 2_825);
}
#[test]
fn sums_the_parts_of_a_cell_edge_in_fixed_point() {
use crate::quirks::LineStartHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let size = device.dots(1).units();
let dot = |device: Device, parts: [i64; 3]| {
let parts = parts.map(|twips| Length::from_twips(twips).unwrap());
device.parts_dot(parts).units() / size
};
// 102 twips past a margin of 600 dots are 42.5 dots. The parts 6 and 96 twips each
// round up in fixed point, and 18 and 84 each round down.
assert_eq!(dot(device, [1_440, 6, 96]), 643);
assert_eq!(dot(device, [1_440, 18, 84]), 642);
// 6,486 twips are 2,702.5 dots: with the column's edge as a part of its own the sum
// goes up, and as one length with the cell's edge it goes down.
assert_eq!(dot(device, [1_701, 4_677, 108]), 2_703);
assert_eq!(dot(device, [0, 6_378, 108]), 2_702);
// Without the quirk the sum goes to the nearest dot, a half up.
assert_eq!(dot(plain, [0, 6_378, 108]), 2_703);
// A later column's edge of 6,258 twips, 2,607.5 dots: the margin of 1,127 twips and
// the column's width with its space, 5,131 twips, each round up in fixed point, so the
// sum goes up; the edge as one length rounds down.
let column = [1_127, 5_131].map(|twips| Length::from_twips(twips).unwrap());
assert_eq!(device.parts_dot(column).units() / size, 2_608);
assert_eq!(
device.parts_dot([column[0] + column[1]]).units() / size,
2_607
);
}
#[test]
fn keeps_a_centered_tables_outer_edge_in_fixed_point() {
use crate::quirks::{CenteredTablePlace, LineStartHalves};
let plain =
Device::per_inch_with(600, |p| p.with_variant(CenteredTablePlace::FixedPointHalf));
let device = Device::per_inch_with(600, |p| {
p.with_variant(CenteredTablePlace::FixedPointHalf)
.with_variant(LineStartHalves::FixedPoint)
});
let size = device.dots(1).units();
let twips = |twips: i64| Length::from_twips(twips).unwrap();
// A grid of 5,013 twips centered in a column of 9,360 from a margin of 1,440, with a
// border of 0.75 pt, has its outer edge at 3,606 twips, exactly 1,502.5 dots. Its
// fixed-point place lies above the half and takes the dot above.
let margin = twips(1_440);
let half_border = Length::from_units(9_525);
let place = device
.centered_outer_edge((margin, margin), (twips(9_360), twips(5_013)), half_border)
.unwrap();
assert_eq!(place.exact, twips(3_606));
assert_eq!(device.fixed_place_dot(place).units() / size, 1_503);
// A text edge 12 and 108 twips right of it, 3,726 twips, is exactly 1,552.5 dots: from
// the fixed-point place it goes up, and from the margin as a cell's parts down.
let edge = device.parts_dot_from(place, [twips(12), twips(108)]);
assert_eq!(edge.units() / size, 1_553);
let parts = device.parts_dot([margin, twips(2_178), twips(108)]);
assert_eq!(parts.units() / size, 1_552);
// A device that does not take the start of a line through fixed-point points keeps no
// place.
let plain_place =
plain.centered_outer_edge((margin, margin), (twips(9_360), twips(5_013)), half_border);
assert_eq!(plain_place, None);
}
/// A 600 dpi device whose table lines round their centers, whose centered tables before
/// mode 15 take their lines from the column edge, and whose column edges on half a dot take
/// the dot of `halves`.
fn table_edge_device(halves: crate::quirks::TableEdgeHalves) -> Device {
use crate::quirks::{CenteredTableLinesBefore15, TableLines};
Device::per_inch_with(600, |p| {
p.with_variant(TableLines::RoundsCenters)
.with_variant(CenteredTableLinesBefore15::FromColumnEdge)
.with_variant(halves)
})
}
#[test]
fn takes_a_column_edge_on_half_a_dot_in_fixed_point() {
use crate::quirks::TableEdgeHalves;
let device = table_edge_device(TableEdgeHalves::FixedPoint);
let dot = device.dots(1);
// Margins of 1,134, 1,410 and 1,446 twips are 472.5, 587.5 and 602.5 dots. In
// fixed-point points, a half up, the first lies below the half, the second on it and the
// third above it: they take the dot below, above and above.
for (twips, whole) in [(1_134, 472), (1_410, 588), (1_446, 603)] {
let left = Length::from_twips(twips).unwrap();
assert_eq!(device.table_line_edge(left, true), dot * whole, "{twips}");
assert_eq!(
device.column_edge_dot(left, true),
Some(dot * whole),
"{twips}"
);
}
// A margin off a half dot takes its nearest dot either way: 1,418 twips, 590.83 dots.
let left = Length::from_twips(1_418).unwrap();
assert_eq!(device.table_line_edge(left, true), dot * 591);
let plain = table_edge_device(TableEdgeHalves::BelowOrExact);
assert_eq!(plain.column_edge_dot(left, false), Some(dot * 591));
}
#[test]
fn keeps_a_column_edge_on_half_a_dot_below_where_it_takes_no_half() {
use crate::quirks::TableEdgeHalves;
// Without the quirk, and for an edge that takes no half, such as a centered floating
// table's own place, a left-aligned table takes the dot below and a centered table
// before mode 15 no dot: 1,446 twips, 602.5 dots.
let left = Length::from_twips(1_446).unwrap();
for (variant, halves) in [
(TableEdgeHalves::BelowOrExact, true),
(TableEdgeHalves::FixedPoint, false),
] {
let device = table_edge_device(variant);
assert_eq!(device.table_line_edge(left, halves), device.dots(602));
assert_eq!(device.column_edge_dot(left, halves), None);
}
}
#[test]
fn rounds_a_half_dot_down_when_asked() {
let device = Device::per_inch(600).unwrap();
let dot = device.dots(1);
let size = dot.units();
// A 1134 twip margin is 472.5 dots of 1/600 inch: 473 to the nearest dot, a half up,
// and 472 a half down. A 1418 twip margin, 590.83 dots, goes to 591 both ways.
let margin = Length::from_twips(1_134).unwrap();
assert_eq!(device.snap(margin), dot * 473);
assert_eq!(device.snap_half_down(margin), dot * 472);
let margin = Length::from_twips(1_418).unwrap();
assert_eq!(device.snap_half_down(margin), dot * 591);
assert_eq!(device.snap_half_down(Length::from_units(-size / 2)), -dot);
assert_eq!(
device.snap_half_down(Length::from_units(-size / 2 + 1)),
Length::ZERO
);
}
#[test]
fn makes_devices_of_any_resolution() {
// A device of twips keeps a twip margin.
let twips = Device::per_inch(1440).unwrap();
let margin = Length::from_twips(1_417).unwrap();
assert_eq!(twips.snap(margin), margin);
// A dot of 1/7 inch is no whole number of half-EMUs, but seven of them are an inch.
let sevenths = Device::per_inch(7).unwrap();
assert_eq!(sevenths.dots(7), Length::from_units(Length::UNITS_PER_INCH));
assert_eq!(Device::per_inch(0), None);
}
#[test]
fn rounds_the_step_of_a_leader_to_the_targets_step() {
// A period of 2.7785 pt.
let period = Length::from_units(70_574);
let device = Device::per_inch(300).unwrap();
assert_eq!(device.leader_step(period), period);
// 1/600 inch: 23 steps of 0.12 pt, 2.76 pt.
let windows = device.with_leader_step(Some(Length::from_units(3_048)));
assert_eq!(windows.leader_step(period), Length::from_units(23 * 3_048));
// 1/288 inch: 11 quarter points, 2.75 pt.
let web = device.with_leader_step(Some(Length::from_units(6_350)));
assert_eq!(web.leader_step(period), Length::from_units(11 * 6_350));
}
#[test]
fn strokes_a_synthetic_bold_a_35th_of_its_size() {
let device = Device::per_inch(600).unwrap();
let twelve = Length::from_units(12 * Length::UNITS_PER_POINT);
assert_eq!(device.bold_stroke(twelve), None);
// A 35th of the size: 0.34286 pt at 12 pt and 0.28457 pt at 9.96 pt.
let stroked = device.with_bold_stroke(std::num::NonZeroU32::new(35));
assert_eq!(stroked.bold_stroke(twelve), Some(Length::from_units(8_709)));
assert_eq!(
stroked.bold_stroke(Length::from_units(252_984)),
Some(Length::from_units(7_228))
);
}
#[test]
fn leaves_out_only_objects_wholly_outside_the_page() {
let pt = |points: i64| Length::from_units(points * Length::UNITS_PER_POINT);
let page = (pt(612), pt(792));
let device = Device::per_inch(600).unwrap();
let windows = Device::per_inch_with(600, |p| {
p.with_variant(crate::quirks::OffPageObjects::LeftOut)
});
// A cell from 616 to 793 pt and a box left of the page are left out; a box that
// reaches 12 pt into the page, or 1 pt above its bottom, is drawn.
let edges = |sides: [i64; 4]| Edges::from(sides.map(pt));
let right = edges([616, 100, 793, 120]);
let left = edges([-766, 700, -150, 718]);
let crossing = edges([-185, 100, 12, 200]);
let low = edges([300, 791, 400, 830]);
assert!(!windows.draws_object(right, page));
assert!(!windows.draws_object(left, page));
assert!(windows.draws_object(crossing, page));
assert!(windows.draws_object(low, page));
assert!(!windows.draws_object(edges([300, 792, 400, 830]), page));
assert!(device.draws_object(right, page));
}
#[test]
fn leaves_out_the_lines_of_a_box_below_the_page_and_all_above_it() {
let pt = |points: i64| Length::from_units(points * Length::UNITS_PER_POINT);
let page = (pt(612), pt(792));
let device = Device::per_inch(600).unwrap();
let windows = Device::per_inch_with(600, |p| {
p.with_variant(crate::quirks::OffPageObjects::LeftOut)
});
// A line 30 pt above the page is drawn when the box's text area ends 18 pt into it, and
// left out when the text area ends above it; a line from 798 pt is left out, and one
// from 790 pt is drawn.
assert!(windows.draws_box_line((pt(-30), pt(18)), page.1));
assert!(!windows.draws_box_line((pt(-30), pt(-17)), page.1));
assert!(!windows.draws_box_line((pt(798), pt(810)), page.1));
assert!(windows.draws_box_line((pt(790), pt(814)), page.1));
assert!(device.draws_box_line((pt(798), pt(-17)), page.1));
}
#[test]
fn takes_the_first_steps_excess_or_the_shared_one_as_the_quirk_says() {
use crate::quirks::WriterSpacing::{FirstStep, SharedStep};
// Excesses in thousandths of a point, of 25,400 thousandths of a half-EMU each.
let points = |thousandths: i64| thousandths * 25_400;
// A first step 0.004 pt short of 22 steps that share an excess of 0.5 pt: the first
// step's excess, or the excess that the 22 share.
let mut excesses = vec![points(496)];
excesses.extend([points(500); 22]);
assert_eq!(super::character_spacing(FirstStep, &excesses), points(496));
assert_eq!(super::character_spacing(SharedStep, &excesses), points(500));
// A first step 0.018 pt short of the others lies outside the band.
excesses[0] = points(482);
assert_eq!(super::character_spacing(FirstStep, &excesses), 0);
assert_eq!(super::character_spacing(SharedStep, &excesses), points(500));
// 20 of 23 steps that share an excess are enough for the shared step, 19 are not.
let mut excesses = vec![points(500); 20];
excesses.extend([points(510); 3]);
assert_eq!(super::character_spacing(SharedStep, &excesses), points(500));
excesses[19] = points(510);
assert_eq!(super::character_spacing(SharedStep, &excesses), 0);
assert_eq!(super::character_spacing(FirstStep, &[]), 0);
}
#[test]
fn gives_the_first_steps_excess_when_the_first_seven_steps_lie_near_it() {
use crate::quirks::WriterSpacing::FirstStep;
let points = |thousandths: i64| thousandths * 25_400;
// Steps of 0.5 pt with a step 0.125 pt longer, as after a space that is not a whole
// number of dots: as the 8th step or later, it leaves the first step's excess, however
// many such steps follow.
let mut excesses = vec![points(500); 7];
excesses.extend([points(625), points(500), points(250), points(625)].repeat(4));
assert_eq!(super::character_spacing(FirstStep, &excesses), points(500));
// As the 7th step, it gives 0, however few such steps follow.
let mut excesses = vec![points(500); 6];
excesses.push(points(625));
excesses.extend([points(500); 30]);
assert_eq!(super::character_spacing(FirstStep, &excesses), 0);
// An object of fewer steps looks at them all.
assert_eq!(
super::character_spacing(FirstStep, &[points(500); 3]),
points(500)
);
}
#[test]
fn counts_a_step_near_the_first_when_it_lies_less_than_a_hundredth_of_a_point_from_it() {
use crate::quirks::WriterSpacing::FirstStep;
let points = |thousandths: i64| thousandths * 25_400;
// A first step 0.0094 pt short of the others shares their excess at every size, so the
// writer writes it rounded to 0.491 pt.
let mut excesses = vec![points(500) - 238_760];
excesses.extend([points(500); 22]);
assert_eq!(super::character_spacing(FirstStep, &excesses), points(491));
// One 0.01 pt short of them does not.
excesses[0] = points(490);
assert_eq!(super::character_spacing(FirstStep, &excesses), 0);
}
#[test]
fn prints_a_spacing_with_three_significant_digits_and_two_decimals_at_least() {
let points = |millionths: i64| millionths * 25_400 / 1_000;
// From 1 pt two decimals, below it three significant digits, a dropped half away from
// zero: each pair is a counted length and its printed form, in millionths of a point.
for (counted, printed) in [
(-1_512_000, -1_510_000),
(52_944_000, 52_940_000),
(-312_000, -312_000),
(17_840, 17_800),
(-1_515_000, -1_520_000),
(104_055_000, 104_060_000),
] {
assert_eq!(
super::printed_points(points(counted)),
points(printed),
"{counted} millionths of a point"
);
}
// Below a thousandth of a point the length stays as it is.
for length in [12, 0] {
assert_eq!(super::printed_points(length), length);
}
}
#[test]
fn draws_a_text_object_with_its_printed_spacing_and_decides_with_the_counted_one() {
use crate::quirks::{WriterAdjustments, WriterSpacing, WrittenSpacing};
// Arial's n at 12 pt, 1,139 of 2,048 units, written as 556 thousandths (6.672 pt), with
// device steps of 43 dots of 600 dpi (5.16 pt): the excess is -1.512 pt, printed as
// -1.51 pt, so each step draws 5.162 pt and the writer adjusts none.
let size = 12 * Length::UNITS_PER_POINT;
let advance = 169_515;
let draw = |written| {
let mut object = super::TextObject {
adjustments: WriterAdjustments::TwoSums,
spacing: WriterSpacing::FirstStep,
written,
..super::TextObject::default()
};
for glyph in 0..4 {
push_units(
&mut object,
glyph * 43 * 3_048,
advance,
(size, size),
Some(556),
);
}
drawn_units(&mut object)
};
assert_eq!(
draw(WrittenSpacing::AsCounted),
[0, 131_064, 262_128, 393_192]
);
assert_eq!(
draw(WrittenSpacing::PrintedDigits),
[0, 131_115, 262_230, 393_344]
);
}
#[test]
fn printed_digits_decides_adjustments_with_unrounded_first_step_excess() {
use crate::quirks::{WriterAdjustments, WriterSpacing, WrittenSpacing};
// 30 identical steps of 34 dots (4.08 pt) followed by 1 step of 33 dots (3.96 pt) at
// 11.04 pt (92 dots) with written width 371/1000 em (4.09584 pt): first excess is
// -0.01584 pt. AsCounted rounds that to -0.016 pt and accumulates -0.0048 pt across 30
// steps, tipping the restart adjustment from 11 to 10; PrintedDigits decides with the
// unrounded -0.01584 pt (adjustment 11) and draws with -0.0158 pt.
let size = 92 * 3_048;
let advance = 104_034;
let draw = |written| {
let mut object = super::TextObject {
adjustments: WriterAdjustments::TwoSums,
spacing: WriterSpacing::FirstStep,
written,
..super::TextObject::default()
};
for i in 0..=30 {
push_units(
&mut object,
i * 34 * 3_048,
advance,
(size, size),
Some(371),
);
}
push_units(
&mut object,
(30 * 34 + 33) * 3_048,
advance,
(size, size),
Some(371),
);
drawn_units(&mut object)
};
let as_counted = draw(WrittenSpacing::AsCounted);
let printed = draw(WrittenSpacing::PrintedDigits);
let step_counted = as_counted[31] - as_counted[30];
let step_printed = printed[31] - printed[30];
// Adjustment 10 draws (371 - 10) * 11.04 / 1000 - 0.016 = 3.96944 pt (100_824 units);
// adjustment 11 draws (371 - 11) * 11.04 / 1000 - 0.0158 = 3.9586 pt (100_549 units).
assert_eq!(step_counted, 100_824);
assert_eq!(step_printed, 100_549);
}
#[test]
fn draws_a_text_object_in_whole_thousandths_of_an_em() {
// Carlito's i at 448 of 2,048 units and 11 pt, 2.40625 pt, whose width is written as 219
// thousandths: the writer draws a step of 2.5 pt as
// 2.486 pt (adjustment -7) and one of 2.25 pt as 2.255 pt (adjustment 14).
let size = 11 * Length::UNITS_PER_POINT;
let advance = 61_119;
let mut object = super::TextObject::default();
for place in [0, 63_500, 120_650] {
push_units(&mut object, place, advance, (size, size), None);
}
assert_eq!(drawn_units(&mut object), [0, 63_144, 63_144 + 57_277]);
assert!(object.is_empty());
}
#[test]
fn decides_an_ideal_on_the_dead_zones_edge_by_the_count_in_single_precision() {
// At 12 pt a dot of 0.12 pt is 10 thousandths of the em, so a width that ends in 3 or 7
// makes an ideal of exactly 3. Word's choices for the first steps of an object: a
// width of 333 that steps 33 dots is carried, and
// one of 833 that steps 83 dots is written, as is one of 667 that steps 67 dots, a
// longer step, which takes -2. Widths of 389 and 278 that step 39 and 28 dots carry
// -1 and then -3; widths of 389 and 444 that step 39 and 44 dots carry -1 and then
// write 3.
let size = 12 * Length::UNITS_PER_POINT;
let draw = |glyphs: &[(u16, i64)]| {
let mut object = super::TextObject::default();
let mut place = 0;
for &(width, dots) in glyphs {
push_units(&mut object, place, 0, (size, size), Some(width));
place += dots * 3_048;
}
// Three glyphs that step by their width follow, so that the object has no
// character spacing.
for _ in 0..4 {
push_units(&mut object, place, 0, (size, size), Some(500));
place += 50 * 3_048;
}
let mut drawn = drawn_units(&mut object);
drawn.truncate(glyphs.len() + 1);
drawn
};
assert_eq!(draw(&[(333, 33)]), [0, 101_498]);
assert_eq!(draw(&[(833, 83)]), [0, 252_984]);
assert_eq!(draw(&[(667, 67)]), [0, 203_911]);
assert_eq!(draw(&[(389, 39), (278, 28)]), [0, 118_567, 203_302]);
assert_eq!(draw(&[(389, 39), (444, 44)]), [0, 118_567, 252_984]);
}
#[test]
fn decides_a_dead_zone_tie_by_the_count() {
// At 12 pt, a width of 433 that steps 43 dots
// makes an ideal of exactly 3 at the object's first step, which the count carries.
let draw = |points: i64, glyphs: &[(u16, i64)]| {
let size = points * Length::UNITS_PER_POINT;
let mut object = super::TextObject::default();
let mut place = 0;
for &(width, dots) in glyphs {
push_units(&mut object, place, 0, (size, size), Some(width));
place += dots * 3_048;
}
for _ in 0..4 {
push_units(&mut object, place, 0, (size, size), Some(500));
place += points * 50 * 3_048 / 12;
}
let mut drawn = drawn_units(&mut object);
drawn.truncate(glyphs.len() + 1);
drawn
};
assert_eq!(draw(12, &[(433, 43)]), [0, 131_978]);
// After a carried step of no adjustment, the count carries the tie too.
assert_eq!(draw(12, &[(500, 50), (433, 43)]), [0, 152_400, 284_378]);
}
#[test]
fn the_two_sum_count_writes_the_numbers_of_its_sequences() {
// A dot at 600 dots per inch.
let dot = Length::UNITS_PER_DOT / 2;
let point = Length::UNITS_PER_POINT;
// Steps of (width, dots) from an object's start, at a drawn size in points, and the
// numbers that the count writes after them: the 48 pt line carries three times and
// writes -2 for a count of -3.49998 thousandths.
let written = |points: i64, steps: &[(i64, i64)]| {
let size = points * point;
let mut count = super::TwoSums::default();
steps
.iter()
.map(|&(width, dots)| count.step(width * size, dots * dot, size))
.collect::<Vec<i64>>()
};
let b = [527, 239, 323, 239, 551];
let at = |dots: [i64; 5]| -> Vec<(i64, i64)> { b.into_iter().zip(dots).collect() };
assert_eq!(written(6, &at([26, 12, 16, 12, 28])), [7, 0, 0, 0, -7]);
assert_eq!(written(12, &at([53, 24, 32, 24, 55])), [0, -3, 0, 0, 3]);
let long = [(722, 289), (444, 178), (444, 178), (444, 178)];
assert_eq!(written(48, &long), [0, 0, 0, -2]);
// At 12.96 pt (108 dots), a first step of half the em in dots and a width 3 thousandths
// over it is an exact tie that Word writes, as the drawn size in whole dots gives; the
// size in points, 12.96 in binary32, carries it.
let mut count = super::TwoSums::default();
assert_eq!(count.step(503 * 108 * dot, 54 * dot, 108 * dot), 3);
}
#[test]
// The casts deliberately apply IEEE rounding and convert small whole numbers.
#[allow(
clippy::float_arithmetic,
clippy::cast_possible_truncation,
clippy::cast_precision_loss
)]
fn the_two_sum_count_agrees_with_native_binary32() {
// An independent IEEE binary32 reference of the same operations, on steps near their
// widths, at drawn sizes in whole dots whose size in points binary32 holds exactly (6,
// 9, 12, 18, 24 and 48 pt) and does not (8.52, 10.56, 11.52, 12.96, 13.56, 14.04 and
// 23.04 pt).
let dot = Length::UNITS_PER_DOT / 2;
let mut state = 0x7018_u32;
let mut next = || {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
i64::from(state >> 16)
};
for em in [
50_i64, 71, 75, 88, 96, 100, 108, 113, 117, 150, 192, 200, 400,
] {
let size = em * dot;
let mut count = super::TwoSums::default();
let (mut widths, mut places) = (0_f32, 0_f32);
let in_points = |dots: i64| dots as f32 / 600.0 * 72.0;
for _ in 0..10_000 {
let width = 150 + next() % 850;
// The device step nearest the width, and one dot either way.
let dots = (width * em + 500) / 1000 + next() % 3 - 1;
let step = count.step(width * size, dots * dot, size);
widths += width as f32 / 1000.0;
places += in_points(dots) / in_points(em);
let difference = widths - places;
let expected = if difference.abs() >= 0.003 {
widths = 0.0;
places = 0.0;
(difference * 1000.0 + 0.5).trunc() as i64
} else {
0
};
assert_eq!(
step, expected,
"{em} dots per em, width {width}, {dots} dots"
);
}
}
}
#[test]
// The casts deliberately apply IEEE rounding and convert already-rounded small integers.
#[allow(clippy::float_arithmetic, clippy::cast_possible_truncation)]
fn integer_adjustment_count_agrees_with_native_binary32() {
// An independent IEEE binary32 reference, including cancellation and carry sums.
for width in (1_i32..1000).step_by(37) {
for place in (1_i32..1000).step_by(43) {
let mut count = super::WriterCount::default();
let (mut widths, mut places) = (0_f32, 0_f32);
for carry in [1, 3, 7, 17] {
count.step(i64::from(width * carry), i64::from(place * carry), 1000);
widths += (f64::from(width * carry) / 1_000_000.0) as f32;
places += (f64::from(place * carry) / 1_000_000.0) as f32;
let native = f64::from((widths - places) * 1000.0);
let ideal = i64::from(width - place);
let expected = if ideal <= 0 {
(native - 0.5).ceil() as i64
} else {
(native + 0.5).floor() as i64
} + i64::from(ideal <= 0);
assert_eq!(count.adjustment(ideal), expected);
}
}
}
}
#[test]
fn writes_a_half_away_from_zero() {
// At 11.52 pt a dot of 0.12 pt is 10 5/12 thousandths of the em. A glyph written 600
// thousandths wide that steps 54 dots (562.5 thousandths) has an ideal of 37.5, which
// the writer writes as 38: a step of 562 thousandths, 164,446 half-EMUs. The next
// steps 66 dots (687.5): an ideal of -87.5, with the longer step's thousandth -86.5,
// written as -87, 687 thousandths. The third steps 60 dots, with no half. Each place is
// the exact sum of the steps, rounded once.
let size = 292_608;
let mut object = super::TextObject::default();
for dots in [0, 54, 120, 180] {
push_units(&mut object, dots * 3_048, 175_565, (size, size), Some(600));
}
assert_eq!(drawn_units(&mut object), [0, 164_446, 365_467, 548_055]);
}
#[test]
fn writes_a_text_objects_start_with_five_significant_digits() {
// Starts on 1/40 pt as the target's PDFs write them: 72.025 pt keeps its three
// decimals; 155.575 pt becomes 155.58 pt and 284.875 pt becomes 284.88 pt, halves
// rounded up because the offsets 0.075 pt and 0.125 pt are held as single-precision
// numbers at or above them; 400.675 pt becomes 400.67 pt, because 0.175 pt is held as
// 0.17499999; and 1,000.075 pt becomes 1,000.1 pt.
let point = |thousandths: i64| thousandths * Length::UNITS_PER_POINT / 1000;
let exact = |thousandths: i64| point(thousandths) * 1000;
let cases = [
(72_000, 25, 72_025),
(99_750, 225, 99_975),
(155_500, 75, 155_580),
(284_750, 125, 284_880),
(400_500, 175, 400_670),
(361_000, 150, 361_150),
(1_000_000, 75, 1_000_100),
(0, 0, 0),
];
for (place, offset, written) in cases {
assert_eq!(
super::written_start(point(place), (exact(offset), point(offset))),
exact(written),
"{place} + {offset}"
);
}
}
#[test]
fn steps_from_the_written_width_where_the_target_writes_one() {
// Glyphs 200 thousandths wide at 10 pt, 200 thousandths apart. When the target writes
// 201 for the second glyph, as a target writes 230 for Calibri's i of 229.49,
// the step after it needs -1, inside the dead zone, so the writer leaves it out and the
// third glyph lands a thousandth of an em further right.
let size = 10 * Length::UNITS_PER_POINT;
let advance = 50_800;
let draw = |written: Option<u16>| {
let mut object = super::TextObject::default();
push_units(&mut object, 0, advance, (size, size), None);
push_units(&mut object, 50_800, advance, (size, size), written);
push_units(&mut object, 101_600, advance, (size, size), None);
drawn_units(&mut object)
};
assert_eq!(draw(None), [0, 50_800, 101_600]);
assert_eq!(draw(Some(201)), [0, 50_800, 101_854]);
}
#[test]
fn starts_text_objects_at_dashes_and_no_break_spaces() {
let mut objects = super::TextObjects::default();
// "a–b c\u{a0}d\u{2002}e\u{2003}f": dashes, no-break space, en space, and em space are
// objects of their own, and so the glyphs after them start objects too.
let starts: Vec<bool> = "a–b c\u{a0}d\u{2002}e\u{2003}f"
.chars()
.enumerate()
.map(|(k, ch)| objects.starts(ch, super::FontSide::Open, k == 0))
.collect();
assert_eq!(
starts,
[
true, true, true, false, false, true, true, true, true, true, true
]
);
}
#[test]
fn joins_consecutive_identical_dashes_and_splits_distinct_ones() {
let starts = |text: &str| {
let mut objects = super::TextObjects::default();
text.chars()
.enumerate()
.map(|(k, ch)| objects.starts(ch, super::FontSide::Open, k == 0))
.collect::<Vec<_>>()
};
let cases: [(&str, &[bool]); 5] = [
// Consecutive identical dashes join into one object; trailing letters start a new one.
("a---b", &[true, true, false, false, true]),
// Distinct dashes split from each other.
("a-\u{2013}\u{2014}b", &[true, true, true, true, true]),
// Consecutive identical special spaces join; distinct special spaces split.
(
"a\u{a0}\u{a0}\u{2002}\u{2003}b",
&[true, true, false, true, true, true],
),
// Non-breaking hyphen joins copies of itself and splits from ASCII hyphen-minus.
(
"a-\u{2011}\u{2011}-b",
&[true, true, true, false, true, true],
),
// Mid-run minus signs stay joined with surrounding letters (run-leading splits come
// from the run's non-default `w:eastAsia` font in `layout::measure`).
("a\u{2212}\u{2212}b", &[true, false, false, false]),
];
for (text, expected) in cases {
assert_eq!(starts(text), expected, "{text:?}");
}
// A run of repeated hyphens still splits at TEXT_OBJECT_GLYPHS.
let many = starts(&"-".repeat(crate::params::TEXT_OBJECT_GLYPHS + 1));
assert_eq!(many.iter().filter(|&&s| s).count(), 2);
assert!(many[0] && many[crate::params::TEXT_OBJECT_GLYPHS]);
}
#[test]
fn isolates_each_non_latin1_emoji_glyph_in_its_own_text_object() {
let starts = |text: &str| {
let mut objects = super::TextObjects::default();
text.chars()
.enumerate()
.map(|(k, ch)| objects.starts(ch, super::FontSide::Open, k == 0))
.collect::<Vec<_>>()
};
// Repeated and distinct non-Latin-1 emoji characters each start a 1-glyph text object,
// and a following space becomes a space-only object followed by another fresh start.
let cases: [(&str, &[bool]); 5] = [
("a\u{2122}\u{2122}b", &[true, true, true, true]),
("a\u{25AA} b", &[true, true, true, true]),
(
"a\u{2660}\u{2665}\u{2663}\u{2666}b",
&[true, true, true, true, true, true],
),
// Latin-1 emoji (©, ®) stay in the surrounding text object.
("a\u{00A9}\u{00AE}b", &[true, false, false, false]),
// Non-emoji symbols in the same blocks stay in the surrounding text object.
(
"a\u{2192}\u{25A0}\u{263B}b",
&[true, false, false, false, false],
),
];
for (text, expected) in cases {
assert_eq!(starts(text), expected, "{text:?}");
}
}
/// Each start gives its reason: the run, the dash and the glyph after it, the glyph after
/// a restart, the glyph after an object of spaces only, and the glyph after a full object.
#[test]
fn gives_the_reason_of_each_text_object_start() {
use super::ObjectStart::{AfterAlone, AfterSpaces, Alone, Fresh, Full, Run};
// The reasons of a text's glyphs, after a run start or after a restart.
let reasons = |text: &str, run: bool| {
let mut objects = super::TextObjects::default();
objects.restart();
text.chars()
.enumerate()
.map(|(k, ch)| {
objects.starts(ch, super::FontSide::Open, run && k == 0);
objects.reason()
})
.collect::<Vec<_>>()
};
assert_eq!(reasons("ab", true), [Some(Run), None]);
assert_eq!(
reasons("a\u{2013}b", false),
[Some(Fresh), Some(Alone), Some(AfterAlone)]
);
assert_eq!(reasons(" c", false), [Some(Fresh), Some(AfterSpaces)]);
let full = reasons(&"e".repeat(crate::params::TEXT_OBJECT_GLYPHS + 1), false);
assert_eq!(full.iter().flatten().count(), 2);
assert_eq!(full.last(), Some(&Some(Full)));
}
/// A glyph after `TextObjects::alone_off_baseline` starts a text object for that reason
/// when nothing else starts one, and the glyph after it does not.
#[test]
fn starts_an_object_at_each_glyph_written_alone_off_the_baseline() {
use super::ObjectStart::{Alone, Run};
let mut objects = super::TextObjects::default();
let mut reason = |alone: bool, run: bool| {
if alone {
objects.alone_off_baseline();
}
objects.starts('b', super::FontSide::Open, run);
objects.reason()
};
assert_eq!(reason(true, true), Some(Run));
assert_eq!(reason(true, false), Some(Alone));
assert_eq!(reason(true, false), Some(Alone));
assert_eq!(reason(false, false), None);
}
/// Under `RightToLeftSteps::Nearest` a glyph of right-to-left text steps without its device
/// width and without the bias; under `RightToLeftSteps::DeviceWidths` it keeps both.
#[test]
fn steps_right_to_left_glyphs_as_the_quirk_says() {
use crate::quirks::RightToLeftSteps;
let step = |variant| {
let device = crate::profile::Profile::base()
.with_variant(variant)
.device();
let measured = Some((15, Length::from_units(91_440)));
device.right_to_left_step(&mut EdgeSteps::default(), (measured, false))
};
assert_eq!(
step(RightToLeftSteps::DeviceWidths),
(Some((15, Length::from_units(91_440))), false)
);
assert_eq!(step(RightToLeftSteps::Nearest), (None, true));
}
/// The devices of `RightToLeftPlacements::Rounded` and `RightToLeftPlacements::Exact`.
fn placement_devices() -> (Device, Device) {
use crate::quirks::RightToLeftPlacements;
let device = |variant| {
crate::profile::Profile::base()
.with_variant(variant)
.device()
};
(
device(RightToLeftPlacements::Rounded),
device(RightToLeftPlacements::Exact),
)
}
/// `hundredths` hundredths of a dot of `device`.
fn hundredths_of(device: &Device, hundredths: i64) -> Length {
Length::from_units(device.dots(1).units() * hundredths / 100)
}
/// Under `RightToLeftPlacements::Rounded` a glyph of right-to-left text at a size on the
/// device's grid lies its placement in whole dots off its step: a mark, which has no
/// advance, rounded toward zero, and another glyph rounded to the nearest dot; its move up
/// and every move of a glyph of left-to-right text stay exact. Under
/// `RightToLeftPlacements::Exact` every move stays exact.
#[test]
fn rounds_the_placement_of_right_to_left_glyphs_as_the_quirk_says() {
let (rounded, exact) = placement_devices();
let up = Length::from_units(1_001);
let letter = rounded.dots(40);
let size = rounded.dots(125);
// Each move in hundredths of a dot, with the dots that it rounds to for a letter and
// for a mark.
for (hundredths, nearest, toward_zero) in [
(-2246, -22, -22),
(-944, -9, -9),
(-960, -10, -9),
(70, 1, 0),
(-40, 0, 0),
(350, 4, 3),
(1290, 13, 12),
] {
let right = hundredths_of(&rounded, hundredths);
let at = |device: &Device, right_to_left, advance| {
let own = if advance == Length::ZERO {
Length::ZERO
} else {
letter
};
let glyph = PlacedGlyph {
right_to_left,
advance,
own,
size,
};
device.placement((right, up), glyph)
};
assert_eq!(at(&rounded, true, letter), (rounded.dots(nearest), up));
assert_eq!(
at(&rounded, true, Length::ZERO),
(rounded.dots(toward_zero), up)
);
assert_eq!(at(&rounded, false, letter), (right, up));
assert_eq!(at(&rounded, false, Length::ZERO), (right, up));
assert_eq!(at(&exact, true, Length::ZERO), (right, up));
}
}
/// The base profile's device with each variant of `VerticalPlacements`: `WholeDots` and
/// `Exact`.
fn vertical_devices() -> (Device, Device) {
use crate::quirks::VerticalPlacements;
let device = |variant| {
crate::profile::Profile::base()
.with_variant(variant)
.device()
};
(
device(VerticalPlacements::WholeDots),
device(VerticalPlacements::Exact),
)
}
/// Under `VerticalPlacements::WholeDots` a glyph lies its move up or down in whole dots at
/// the device's em, rounded toward zero: at a size on the grid, the move itself; at a size
/// off it, the move scaled to the size in whole dots. Under `VerticalPlacements::Exact` the
/// move stays exact.
#[test]
fn draws_a_move_up_or_down_in_whole_dots_toward_zero_as_the_quirk_says() {
let (whole, exact) = vertical_devices();
let on_grid = whole.dots(129);
for (hundredths, dots) in [
(94, 0),
(-94, 0),
(113, 1),
(-113, -1),
(2603, 26),
(-199, -1),
] {
let up = hundredths_of(&whole, hundredths);
assert_eq!(whole.vertical_placement(up, on_grid), whole.dots(dots));
assert_eq!(exact.vertical_placement(up, on_grid), up);
}
// A size of 120.83 dots draws at an em of 121: a move of 0.9970 dots at that size is
// 0.9983 dots at the em, and one of 0.9990 dots is 1.0004.
let off_grid = Length::from_units(whole.dots(12_083).units() / 100);
let below = Length::from_units(whole.dots(9_970).units() / 10_000);
let reaches = Length::from_units(whole.dots(9_990).units() / 10_000);
assert_eq!(whole.vertical_placement(below, off_grid), Length::ZERO);
assert_eq!(whole.vertical_placement(reaches, off_grid), whole.dots(1));
}
/// Under `VerticalPlacements::WholeDots` the writer writes a text object glyph by glyph
/// when a glyph of right-to-left text in it lies one dot or more off the baseline, and not
/// for a glyph of left-to-right text or one less than a dot off it; under
/// `VerticalPlacements::Exact`, never.
#[test]
fn writes_an_object_glyph_by_glyph_for_a_right_to_left_glyph_a_dot_off_the_baseline() {
let (whole, exact) = vertical_devices();
let size = whole.dots(129);
let dot = hundredths_of(&whole, 113);
let less = hundredths_of(&whole, -94);
assert!(whole.object_per_glyph(dot, size, true));
assert!(whole.object_per_glyph(-dot, size, true));
assert!(!whole.object_per_glyph(less, size, true));
assert!(!whole.object_per_glyph(dot, size, false));
assert!(!exact.object_per_glyph(dot, size, true));
}
/// Under `RightToLeftPlacements::Rounded` a mark whose font gives it an advance of its own
/// lies its move by its anchors rounded toward zero, less that advance rounded to the
/// nearest dot: the shaper's move holds the advance taken away.
#[test]
fn takes_a_marks_own_advance_out_in_whole_dots() {
let (rounded, _) = placement_devices();
let up = Length::from_units(1_001);
let size = rounded.dots(125);
// Each own advance and move to the right in hundredths of a dot, with the dots that the
// mark lies off its step.
for (own, hundredths, dots) in [
(5251, -5221, -53),
(5251, -5281, -53),
(5240, -5170, -52),
(5240, -5310, -52),
(5240, -5110, -51),
] {
let own = hundredths_of(&rounded, own);
let mark = PlacedGlyph {
right_to_left: true,
advance: Length::ZERO,
own,
size,
};
let placed = rounded.placement((hundredths_of(&rounded, hundredths), up), mark);
assert_eq!(placed, (rounded.dots(dots), up));
}
}
/// Under `RightToLeftPlacements::Rounded` a size off the device's grid counts a placement at
/// the device's em: at 10.5 pt, 87.5 dots, the em is 88 dots, and a move counts 88/87.5 of
/// itself.
#[test]
fn counts_a_placement_at_the_devices_em() {
let (rounded, _) = placement_devices();
let up = Length::from_units(1_001);
let size = Length::from_units(266_700);
let at = |hundredths, (advance, own): (i64, i64)| {
let glyph = PlacedGlyph {
right_to_left: true,
advance: hundredths_of(&rounded, advance),
own: hundredths_of(&rounded, own),
size,
};
rounded.placement((hundredths_of(&rounded, hundredths), up), glyph)
};
assert_eq!(at(597, (0, 0)), (rounded.dots(6), up));
assert_eq!(at(-564, (0, 5251)), (rounded.dots(-6), up));
assert_eq!(at(-946, (4000, 4000)), (rounded.dots(-10), up));
}
/// Under `FormatCharacterObjects::StartsObject` the writer counts a glyph after a format
/// character as the start of a run of text; under `FormatCharacterObjects::Joins` only a
/// run of the document or a text piece starts one.
#[test]
fn starts_writer_text_after_a_format_character_as_the_quirk_says() {
use crate::quirks::FormatCharacterObjects;
let starts = |variant, (run, after_character): (bool, bool)| {
let before = if after_character {
crate::text::LeftOutBefore::FormatCharacter
} else {
crate::text::LeftOutBefore::Nothing
};
crate::profile::Profile::base()
.with_variant(variant)
.device()
.writer_run_start(run, before)
};
for variant in [
FormatCharacterObjects::Joins,
FormatCharacterObjects::StartsObject,
] {
assert!(starts(variant, (true, false)));
assert!(starts(variant, (true, true)));
assert!(!starts(variant, (false, false)));
}
assert!(starts(FormatCharacterObjects::StartsObject, (false, true)));
assert!(!starts(FormatCharacterObjects::Joins, (false, true)));
}
/// Under `RightToLeftObjectCount::ReadingOrder` the writer counts the glyphs of
/// right-to-left text from the stretch's right end and from each run start, so that on the
/// line, from the left, the glyph right of the 126th in reading order starts an object;
/// under `RightToLeftObjectCount::FromTheLeft` the stretch adds no start.
#[test]
fn counts_right_to_left_objects_in_reading_order_as_the_quirk_says() {
use crate::quirks::RightToLeftObjectCount;
let most = crate::params::TEXT_OBJECT_GLYPHS;
let full = |variant, starts: &[bool]| {
let device = crate::profile::Profile::base()
.with_variant(variant)
.device();
let glyphs: Vec<_> = starts
.iter()
.map(|&run| ('\u{0628}', super::FontSide::Open, run))
.collect();
device.right_to_left_object_starts(&glyphs).full
};
let marked = |marks: Vec<bool>| -> Vec<usize> {
marks
.iter()
.enumerate()
.filter_map(|(at, &mark)| mark.then_some(at))
.collect()
};
let plain = vec![false; most + 5];
assert_eq!(
marked(full(RightToLeftObjectCount::ReadingOrder, &plain)),
[5]
);
assert_eq!(
marked(full(RightToLeftObjectCount::FromTheLeft, &plain)),
Vec::<usize>::new()
);
let twice = vec![false; 2 * most + 1];
assert_eq!(
marked(full(RightToLeftObjectCount::ReadingOrder, &twice)),
[1, most + 1]
);
// A run that starts at the tenth glyph in reading order counts again from it.
let mut run = vec![false; most + 20];
let tenth = run.len() - 10;
if let Some(start) = run.get_mut(tenth) {
*start = true;
}
assert_eq!(
marked(full(RightToLeftObjectCount::ReadingOrder, &run)),
[tenth - most + 1]
);
assert_eq!(
marked(full(RightToLeftObjectCount::ReadingOrder, &[false; 125])),
Vec::<usize>::new()
);
}
/// Under `RightToLeftObjectCount::ReadingOrder`, reading-order trailing spaces (at the
/// visual left of an RTL run) stay inside their object while reading-order leading spaces
/// (at the visual right of a run, line start, or hyphen) form their own space-only object;
/// under `FromTheLeft`, `reading_order` is false and visual counting decides.
#[test]
fn splits_right_to_left_leading_spaces_and_keeps_trailing_spaces_in_reading_order() {
use crate::quirks::RightToLeftObjectCount;
let device = |variant| {
crate::profile::Profile::base()
.with_variant(variant)
.device()
};
// Visual order for reading-order `"أب - جد"` (one run: `أ` starts the run on the right):
// 0: د, 1: ج, 2: ' ' (leading after `-`), 3: '-', 4: ' ' (trailing before `-`), 5: ب, 6: أ
let hyphen_line = [
('\u{062F}', super::FontSide::Open, false),
('\u{062C}', super::FontSide::Open, false),
(' ', super::FontSide::Open, false),
('-', super::FontSide::Open, false),
(' ', super::FontSide::Open, false),
('\u{0628}', super::FontSide::Open, false),
('\u{0623}', super::FontSide::Open, true),
];
let reading =
device(RightToLeftObjectCount::ReadingOrder).right_to_left_object_starts(&hyphen_line);
assert!(reading.reading_order);
assert_eq!(
reading.after_spaces,
[false, false, true, false, false, false, false]
);
let visual =
device(RightToLeftObjectCount::FromTheLeft).right_to_left_object_starts(&hyphen_line);
assert!(!visual.reading_order);
assert_eq!(visual.after_spaces, [false; 7]);
// Visual order for reading-order `" أب"` (two leading spaces at line start):
// 0: ب, 1: أ, 2: ' ', 3: ' ' (run start)
let two_leading = [
('\u{0628}', super::FontSide::Open, false),
('\u{0623}', super::FontSide::Open, false),
(' ', super::FontSide::Open, false),
(' ', super::FontSide::Open, true),
];
let marks =
device(RightToLeftObjectCount::ReadingOrder).right_to_left_object_starts(&two_leading);
assert_eq!(marks.after_spaces, [false, false, true, false]);
// Visual pass with those marks keeps trailing space inside `{4, 5, 6}` and isolates `{2}`.
let mut objects = super::TextObjects::default();
let starts: Vec<bool> = hyphen_line
.iter()
.enumerate()
.map(|(i, &(ch, side, _))| {
if reading.reading_order {
objects.reading_order_spaces();
}
if reading.after_spaces[i] {
objects.after_spaces();
}
objects.starts(ch, side, i == 0)
})
.collect();
assert_eq!(starts, [true, false, true, true, true, false, false]);
}
/// Under `NonBreakingHyphen::AsHyphenMinus` the writer counts a non-breaking hyphen as a
/// hyphen-minus, a text object of its own with another one at the glyph after it; under
/// `NonBreakingHyphen::OwnGlyph` it stays inside the object of the glyphs around it.
#[test]
fn starts_text_objects_at_a_non_breaking_hyphen_as_the_quirk_says() {
use crate::quirks::NonBreakingHyphen;
let starts = |variant| {
let device = crate::profile::Profile::base()
.with_variant(variant)
.device();
let mut objects = super::TextObjects::default();
['a', 'b', crate::text::NON_BREAKING_HYPHEN, 'c', 'd']
.iter()
.enumerate()
.map(|(k, &ch)| {
objects.starts(device.writer_char(ch), super::FontSide::Open, k == 0)
})
.collect::<Vec<bool>>()
};
assert_eq!(
starts(NonBreakingHyphen::AsHyphenMinus),
[true, false, true, true, false]
);
assert_eq!(
starts(NonBreakingHyphen::OwnGlyph),
[true, false, false, false, false]
);
}
/// The hyphen that a line shows at an automatic hyphenation point stays in the text object
/// of the letters before it, where a typed hyphen-minus is an object of its own.
#[test]
fn keeps_the_hyphen_of_an_automatic_point_in_its_text_object() {
let device = super::base_device();
let starts = |last| {
let mut objects = super::TextObjects::default();
['i', 'n', 't', 'e', 'r', last]
.iter()
.enumerate()
.map(|(k, &ch)| {
objects.starts(device.writer_char(ch), super::FontSide::Open, k == 0)
})
.collect::<Vec<bool>>()
};
assert_eq!(
starts(crate::text::LINE_END_HYPHEN),
[true, false, false, false, false, false]
);
assert_eq!(starts('-'), [true, false, false, false, false, true]);
}
/// A glyph whose font side differs from the side of the last glyph before it that has one
/// starts a text object; a space keeps the side before it, and an open character leaves
/// none.
#[test]
fn starts_text_objects_at_a_change_of_font_side() {
use super::FontSide::{EastAsian, Open, Other};
let mut objects = super::TextObjects::default();
let glyphs = [
('\u{4E00}', EastAsian),
('\u{4E8C}', EastAsian),
('7', Other),
('k', Other),
(' ', Open),
('\u{4E09}', EastAsian),
('\u{00E9}', Open),
('8', Other),
('\u{56DB}', EastAsian),
];
let starts: Vec<bool> = glyphs
.iter()
.enumerate()
.map(|(k, &(ch, side))| objects.starts(ch, side, k == 0))
.collect();
assert_eq!(
starts,
[true, false, true, false, false, true, false, false, true]
);
}
/// With distinct ASCII and High ANSI sides, ASCII spaces have side `Other`: transitions
/// between `Other` and `HighAnsi` start text objects, adjacent `HighAnsi` characters stay
/// together, and a space after `HighAnsi` starts a space-only object so the following
/// character starts a fresh object too.
#[test]
fn starts_text_objects_across_ascii_spaces_and_high_ansi_sides() {
use super::FontSide::{HighAnsi, Other};
let mut objects = super::TextObjects::default();
// "a éé ’ ’ g"
let glyphs = [
('a', Other),
(' ', Other),
(' ', Other),
('\u{00E9}', HighAnsi),
('\u{00E9}', HighAnsi),
(' ', Other),
('\u{2019}', HighAnsi),
(' ', Other),
('\u{2019}', HighAnsi),
(' ', Other),
('g', Other),
];
let starts: Vec<bool> = glyphs
.iter()
.enumerate()
.map(|(k, &(ch, side))| objects.starts(ch, side, k == 0))
.collect();
assert_eq!(
starts,
[
true, false, false, true, false, true, true, true, true, true, true
]
);
}
#[test]
fn ends_a_text_object_after_its_last_glyph_place() {
// 260 glyphs of one run, with spaces among them: objects start at glyphs 1, 126 and
// 251, and a run that starts inside counts again from its own first glyph.
let mut objects = super::TextObjects::default();
let text: Vec<char> = "abc ".repeat(65).chars().collect();
let starts: Vec<usize> = text
.iter()
.enumerate()
.filter(|&(k, &ch)| objects.starts(ch, super::FontSide::Open, k == 0 || k == 200))
.map(|(k, _)| k + 1)
.collect();
assert_eq!(starts, [1, 126, 201]);
}
#[test]
fn spaces_the_characters_of_a_text_object_for_its_common_step() {
// Calibri's low line at 12 pt, 498 thousandths wide: ten steps of 6 pt and one of
// 5.75 pt take a character spacing of 0.024 pt and an adjustment of 21 on the short step.
let size = 12 * Length::UNITS_PER_POINT;
let advance = 151_790;
let quarter = Length::UNITS_PER_POINT / 4;
let mut object = super::TextObject::default();
let mut place = 72 * Length::UNITS_PER_POINT;
for step in [24, 24, 24, 24, 24, 23, 24, 24, 24, 24, 24, 24] {
push_units(&mut object, place, advance, (size, size), None);
place += step * quarter;
}
let drawn = drawn_units(&mut object);
let steps: Vec<i64> = drawn.windows(2).map(|pair| pair[1] - pair[0]).collect();
assert_eq!(steps.first(), Some(&(6 * Length::UNITS_PER_POINT)));
// 5.976 + 0.024 - 0.252 = 5.748 pt.
assert_eq!(steps.get(5), Some(&145_999));
}
#[test]
fn starts_a_text_object_at_the_offset_of_its_target() {
// Word for Windows's offset across a Letter page, steps of 1/3000 inch as if the page
// were 4.72515 steps wider, rounded in sixteenths of a step first: a place of 455.16 pt
// takes four steps, 0.096 pt, and the start is written with five significant digits,
// 455.26 pt.
let place = 11_561_064;
let advance = 133_451;
let letter = 12_240 * 1_270;
let windows = f_office_paint::Offset::Page {
steps: (472_515, 100_000),
parts: 16,
per_inch: 3_000,
product: f_office_paint::OffsetProduct::Exact,
};
let mut object = super::TextObject::starting(windows, Length::from_units(letter));
push_units(&mut object, place, advance, (304_800, 304_800), None);
assert_eq!(drawn_units(&mut object).first(), Some(&11_563_604));
// Without an offset the start is the place.
let mut object =
super::TextObject::starting(f_office_paint::Offset::None, Length::from_units(letter));
push_units(&mut object, place, advance, (304_800, 304_800), None);
assert_eq!(drawn_units(&mut object).first(), Some(&place));
// With the device's places, the glyphs keep their distances on the device from the
// written start, and the writer writes no adjustment.
let mut object = super::TextObject::starting(windows, Length::from_units(letter))
.with_device_places(true);
push_units(&mut object, place, advance, (304_800, 304_800), None);
push_units(
&mut object,
place + 3_048 * 33,
advance,
(304_800, 304_800),
None,
);
assert_eq!(
drawn_units(&mut object),
[11_563_604, 11_563_604 + 3_048 * 33]
);
}
#[test]
fn counts_the_steps_of_a_text_object_at_its_drawn_size() {
// Calibri's e at 11 pt, 498 thousandths wide, drawn at 11.04 pt on a device of 600
// dots per inch, with steps of 46, 45 and 46 dots and no shared step: the first step's
// adjustment lies in the dead zone at the drawn size, so the step is the width at 11.04
// pt alone, 5.498 pt, and the second takes an adjustment of 7 thousandths, 5.421 pt.
let size = 11 * Length::UNITS_PER_POINT;
let drawn = 280_416;
let advance = 139_141;
let dot = Length::UNITS_PER_INCH / 600;
let mut object = super::TextObject::default();
let mut place = 72 * Length::UNITS_PER_POINT;
for step in [46, 45, 46, 0] {
push_units(&mut object, place, advance, (size, drawn), None);
place += step * dot;
}
let drawn = drawn_units(&mut object);
let steps: Vec<i64> = drawn.windows(2).map(|pair| pair[1] - pair[0]).collect();
assert_eq!(steps.first(), Some(&139_647));
assert_eq!(steps.get(1), Some(&137_684));
}
#[test]
fn whole_twips_cut_the_room_of_an_extent_only() {
use crate::quirks::InlineRoom;
let room = |rule: InlineRoom, height: Length, extent: Option<Length>| {
Device::per_inch_with(600, |p| p.with_variant(rule)).inline_room_height(height, extent)
};
// A header picture of 597,159 EMU is 940.4079 twips; it takes 940.
let height = Length::from_emus(597_159).unwrap();
let whole = Length::from_twips(940).unwrap();
assert_eq!(room(InlineRoom::WholeTwips, height, Some(height)), whole);
assert_eq!(room(InlineRoom::WholeTwips, height, None), height);
assert_eq!(room(InlineRoom::Exact, height, Some(height)), height);
// A room of whole twips stays as it is, and a fraction above a half is cut too.
assert_eq!(room(InlineRoom::WholeTwips, whole, Some(whole)), whole);
let above_half = Length::from_emus(940 * 635 + 600).unwrap();
assert_eq!(
room(InlineRoom::WholeTwips, above_half, Some(above_half)),
whole
);
// The effect extent above and below the extent counts as it is: an extent of 940 twips
// and 600 EMU under an effect extent of 318 EMU takes 940 twips and 318 EMU, where a cut
// of the sum would take 941 twips.
let effect = Length::from_emus(318).unwrap();
assert_eq!(
room(
InlineRoom::WholeTwips,
above_half + effect,
Some(above_half)
),
whole + effect
);
}
#[test]
fn per_glyph_text_object_keeps_first_start_offset_and_resets_after_draw() {
let device = Device::per_inch(600).unwrap();
let page_width = Length::from_points(612).unwrap();
let offset = f_office_paint::Offset::Share {
share: 200,
bias: 0,
step: 610,
};
let size = Length::from_points(12).unwrap();
let first = device.dots(1706); // ~204.72 pt
let second = device.dots(3760); // ~451.20 pt (crosses writer offset steps)
let advance = Length::from_points(6).unwrap();
let mut obj = super::TextObject::starting(offset, page_width);
obj.set_per_glyph();
obj.push_at(first, advance, (size, size), None);
obj.push_at(second, advance, (size, size), None);
let drawn = obj.draw();
let start = obj.written_start_of(first);
assert_eq!(drawn, vec![start, start + (second - first)]);
// Confirm the second glyph would have received a different start offset on its own.
assert_ne!(obj.written_start_of(second), start + (second - first));
// A second object after draw() resets per_glyph and uses normal writer adjustments.
obj.push_at(first, advance, (size, size), None);
obj.push_at(first + device.dots(50), advance, (size, size), None);
let normal = obj.draw();
assert_eq!(normal.len(), 2);
assert_eq!(normal[0], start);
}
#[test]
fn inline_object_step_cuts_width_to_whole_twips_then_whole_dots() {
use crate::quirks::GlyphSegments;
let dev_with = |rule: GlyphSegments| {
Device::per_inch_with(600, |p| p.with_variant(rule)).with_advances(
super::Advances::RightEdge {
bias: Length::from_units(127),
limit: Length::from_units(4_572),
segment: Length::from_units(3_121_152),
point_steps: std::num::NonZeroU32::new(1_024),
start: f_office_paint::WriterOffset::NONE,
},
)
};
let step_dev = dev_with(GlyphSegments::FromRestart);
let step =
|emus: i64| EdgeSteps::inline_object_step(&step_dev, Length::from_emus(emus).unwrap());
// 138,684 EMU (218.40 twips) -> 218 twips -> 90 dots;
// 139,064 EMU (218.998 twips) -> 218 twips -> 90 dots;
// 139,065 EMU (219.00 twips) -> 219 twips -> 91 dots.
assert_eq!(step(138_684), Some(step_dev.dots(90)));
assert_eq!(step(139_064), Some(step_dev.dots(90)));
assert_eq!(step(139_065), Some(step_dev.dots(91)));
// Extent + effectExtent sum (137,160 + 19,050 = 156,210 EMU = 246 twips = 102.5 dots) -> 102 dots.
assert_eq!(step(156_210), Some(step_dev.dots(102)));
// FromLineStart returns None (uses standard gap restart).
let other = dev_with(GlyphSegments::FromLineStart);
assert_eq!(
EdgeSteps::inline_object_step(&other, Length::from_emus(156_210).unwrap()),
None
);
}
}