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
//! 構文木に寸法と位置を与える
//!
//! 単位はすべてルートの文字サイズを 1 とした em で、y は下向きを正とする。
//! 縦位置と空きの値はフォントの MATH テーブルから取るので、書体を替えれば組み方も替わる。
//! 伸びる括弧と根号は、引き伸ばすのではなく、フォントが持つ大きさ違いの字形と積み木で作る。
use crate::font::{self, Font};
use crate::math::Construction;
use crate::node::{self, Align, Class, Level, Limits, Node, Style};
use crate::symbol;
/// 記号のあいだの空き。TeX と同じく 18 分の 1 em を 1 として数える
const THIN: f64 = 3.0 / 18.0;
const MEDIUM: f64 = 4.0 / 18.0;
const THICK: f64 = 5.0 / 18.0;
/// 分数の線が分子分母より左右へ出る幅
const FRACTION_PADDING: f64 = 0.12;
/// 括弧の内側に空けたい幅
///
/// 括弧の字形が自分で持っている内側の余白は、Latin Modern Math だと丸括弧で 0.057em、
/// 角括弧では 0.022em しかない。しかも字形が大きくなってもここはほとんど増えないので、
/// 背の高い括弧ほど中身に貼り付いて見える。足りないぶんをここで補う
const FENCE_ROOM: f64 = 0.12;
/// 横に付ける添字を、土台から離す幅。土台の背に比例させる
///
/// 字形が持つ右の余白は背が高くなっても増えない。積分のように背の高い記号では、
/// 同じ余白でも比率として足りず、添字が貼り付いて見える
const SCRIPT_GAP: f64 = 0.04;
/// 添字を離す幅の下限
///
/// 背の低い字では比例ぶんがほとんど出ない。x^2 のような並びが詰まって見えるので、
/// ここまでは必ず空ける
const SCRIPT_GAP_MIN: f64 = 0.03;
/// 上に付ける印と、上下に引く線を、中身から離す幅
///
/// 印は MATH テーブルの決めるままだと字の上に直に載る。線の空きもフォントの値だけでは
/// 窮屈に見えるので、どちらにもここぶんを足す
const MARK_GAP: f64 = 0.05;
/// 伸びる記号と、その上下に置くもののあいだ
const EXTEND_GAP: f64 = 0.09;
/// 伸びる記号が、上下に置くものより左右へ出る幅
const EXTEND_PADDING: f64 = 0.3;
/// 行列の列と列のあいだ
const COLUMN_GAP: f64 = 0.6;
/// 行列の左右の端に空ける幅
///
/// 列と列のあいだの半分を外側にも空ける。これがないと、背の高い括弧が
/// 端の列に貼り付いて見える。括弧を置かない側には空けない
const MATRIX_ROOM: f64 = COLUMN_GAP / 2.0;
/// 行列の行と行のあいだ
const ROW_GAP: f64 = 0.35;
/// 行列のセルが最低限とる高さと深さ
const ROW_HEIGHT: f64 = 0.5;
const ROW_DEPTH: f64 = 0.2;
/// 字形をどう書き出すか
///
/// 組み上げには関わらない。どちらを選んでも寸法と位置は同じになる。
/// 伸びる括弧、根号、上に付ける印、display の大きな演算子は、どちらでも輪郭で描く。
/// それらの字形には文字が割り当てられていないためである
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
/// 文字として書き出す。表示する側にフォントが要るが、選んで写せる
Text,
/// 輪郭として書き出す。表示する側にフォントが要らない
Outline,
}
/// 位置と寸法が決まったひとまとまり
#[derive(Debug, Clone, PartialEq)]
pub struct Layout {
pub content: Content,
/// 送り幅
pub width: f64,
/// ベースラインから上
pub height: f64,
/// ベースラインから下
pub depth: f64,
}
/// まとまりの中身
#[derive(Debug, Clone, PartialEq)]
pub enum Content {
/// 1 文字。text は書き出す文字、glyph はフォントの字形番号
Glyph {
text: String,
glyph: u16,
class: Class,
size: f64,
/// 数式用の字形がなく、字を傾けて代わりにするとき
italic: bool,
/// 数式用の字形がなく、字を太らせて代わりにするとき
bold: bool,
/// 縦の引き伸ばし率
///
/// フォントが大きさ違いの字形を持たないときだけ 1 以外になる。
/// 持っている書体では、伸ばす代わりにその字形へ差し替える
stretch: f64,
},
/// 置き場所を決めた子の集まり
Group(Vec<Placed>),
/// 塗りつぶした矩形。分数線、根号の線、\hline に使う
Rule,
}
/// 親の中に置いた子
#[derive(Debug, Clone, PartialEq)]
pub struct Placed {
/// 親の左端からの距離
pub x: f64,
/// 親のベースラインからの下向きのずれ
pub y: f64,
pub layout: Layout,
}
/// 構文木の寸法と位置を決める
pub fn layout(node: &Node, font: &Font, size: f64, style: Style, display: bool) -> Layout {
match node {
Node::Symbol {text, class} => symbol_layout(font, text, *class, style, size, display),
Node::Text(body) => text_layout(font, body, size),
Node::Row(items) => row_layout(items, font, size, style, display),
Node::Fraction {numerator, denominator, bar} => {
fraction_layout(numerator, denominator, *bar, font, size, style, display)
}
Node::Root {index, body} => {
root_layout(index.as_deref(), body, font, size, style, display)
}
Node::Scripts {base, superscript, subscript, limits} => scripts_layout(
base,
superscript.as_deref(),
subscript.as_deref(),
*limits,
font,
size,
style,
display,
),
Node::Fenced {left, right, body} => {
let inside = layout(body, font, size, style, display);
fence(inside, left, right, font, size)
}
Node::Matrix {rows, left, right, align, lines} => {
matrix_layout(rows, left, right, align, lines, font, size, style)
}
Node::Styled {style: inner, body} => layout(body, font, size, *inner, display),
Node::Accent {mark, body, above} => {
accent_layout(mark, body, *above, font, size, style, display)
}
Node::Sized {level, body} => {
let value = font::constant(font);
let (inner, factor) = match level {
Level::Display => (true, 1.0),
Level::Text => (false, 1.0),
Level::Script => (false, value.script_percent),
Level::ScriptScript => (false, value.script_script_percent),
};
layout(body, font, size * factor, style, inner)
}
Node::Delimiter {text, height, ..} => sized_delimiter(font, text, height * size, size),
Node::Extend {mark, above, below} => extend_layout(
mark,
above.as_deref(),
below.as_deref(),
font,
size,
style,
),
Node::Line {body, above} => line_layout(body, *above, font, size, style, display),
Node::Phantom {body, width, height} => {
phantom_layout(body, *width, *height, font, size, style, display)
}
}
}
/// 高さと深さだけを知りたいときに使う
pub fn measure(node: &Node, font: &Font, size: f64, style: Style, display: bool) -> (f64, f64) {
let placed = layout(node, font, size, style, display);
(placed.height, placed.depth)
}
/// 隣り合う記号のあいだに入れる空き
pub fn gap(left: Class, right: Class) -> f64 {
if matches!(left, Class::Space(_)) || matches!(right, Class::Space(_)) {
return 0.0;
}
match (normalize(left), normalize(right)) {
(Class::Punctuation, _) => THIN,
(Class::Ordinary, Class::Large)
| (Class::Large, Class::Ordinary)
| (Class::Large, Class::Large)
| (Class::Large, Class::Open)
| (Class::Large, Class::Close)
| (Class::Close, Class::Large) => THIN,
(Class::Ordinary, Class::Binary)
| (Class::Binary, Class::Ordinary)
| (Class::Large, Class::Binary)
| (Class::Binary, Class::Large)
| (Class::Binary, Class::Open)
| (Class::Close, Class::Binary) => MEDIUM,
(Class::Ordinary, Class::Relation)
| (Class::Relation, Class::Ordinary)
| (Class::Large, Class::Relation)
| (Class::Relation, Class::Large)
| (Class::Relation, Class::Open)
| (Class::Relation, Class::Close)
| (Class::Close, Class::Relation)
| (Class::Relation, Class::Punctuation) => THICK,
_ => 0.0,
}
}
/// 空きを決めるうえで同じ扱いにする種別をまとめる
fn normalize(class: Class) -> Class {
match class {
Class::Variable => Class::Ordinary,
Class::Function => Class::Large,
other => other,
}
}
/// 子を包んで、全体の寸法を求める
fn group(children: Vec<Placed>) -> Layout {
let mut width: f64 = 0.0;
let mut height: f64 = 0.0;
let mut depth: f64 = 0.0;
for child in &children {
width = width.max(child.x + child.layout.width);
height = height.max(child.layout.height - child.y);
depth = depth.max(child.layout.depth + child.y);
}
Layout {content: Content::Group(children), width, height, depth}
}
/// 塗りつぶした矩形。下端がベースラインに来る
fn rule(width: f64, thickness: f64) -> Layout {
Layout {content: Content::Rule, width, height: thickness, depth: 0.0}
}
/// 幅だけを持つ空き
fn blank(width: f64) -> Layout {
Layout {content: Content::Group(Vec::new()), width, height: 0.0, depth: 0.0}
}
/// ベースラインを下へずらす
fn shift(layout: Layout, y: f64) -> Layout {
if y == 0.0 {
return layout;
}
group(vec![Placed {x: 0.0, y, layout}])
}
/// 字形 1 つを置く
fn glyph_layout(
font: &Font,
glyph: u16,
class: Class,
size: f64,
text: &str,
slant: (bool, bool),
) -> Layout {
stretched_glyph(font, glyph, class, size, text, slant, 1.0)
}
/// 字形 1 つを、縦に伸ばして置く。伸ばし率が要るのは文字として書き出すときだけである
fn stretched_glyph(
font: &Font,
glyph: u16,
class: Class,
size: f64,
text: &str,
slant: (bool, bool),
stretch: f64,
) -> Layout {
let (height, depth) = font::extent(font, glyph);
let mut width = font::advance(font, glyph);
let mut above = height;
let mut below = depth;
// 書体が持たない文字は字形番号 0 になる。場所だけはおおよそで空けておく
if glyph == 0 {
if let Some(character) = text.chars().next() {
let (fallback_width, fallback_height, fallback_depth) = font::fallback_metric(character);
width = fallback_width;
above = fallback_height;
below = fallback_depth;
}
}
Layout {
content: Content::Glyph {
text: text.to_string(),
glyph,
class,
size,
italic: slant.0,
bold: slant.1,
stretch,
},
width: width * size,
height: above * size * stretch,
depth: below * size * stretch,
}
}
/// 装いに合う字形を選ぶ。数式用の字形があればそれを使い、なければ素の字を傾けて代える
fn pick(font: &Font, character: char, style: Style) -> (u16, String, bool, bool) {
if let Some(wanted) = symbol::styled(character, style) {
if let Some(glyph) = font::glyph_of(font, wanted) {
return (glyph, wanted.to_string(), false, false);
}
}
let glyph = font::glyph_of(font, character).unwrap_or(0);
let italic = matches!(style, Style::Italic);
let bold = matches!(style, Style::Bold);
(glyph, character.to_string(), italic, bold)
}
/// 種別と装いから、実際に使う装いを決める
fn resolve(class: Class, style: Style) -> Style {
match style {
Style::Auto if class == Class::Variable => Style::Italic,
Style::Auto => Style::Roman,
other => other,
}
}
fn symbol_layout(
font: &Font,
text: &str,
class: Class,
style: Style,
size: f64,
display: bool,
) -> Layout {
if let Class::Space(width) = class {
return blank(width * size);
}
let wanted = resolve(class, style);
let mut children = Vec::new();
let mut cursor = 0.0;
for character in text.chars() {
let (mut glyph, mut shown, italic, bold) = pick(font, character, wanted);
// display の大きな演算子は、フォントが持つ大きい字形に替える。
// 替えた字形には文字の割り当てがないので、書き出す文字は空にする
if class == Class::Large && display {
let bigger = larger(font, glyph, font::constant(font).display_operator_min_height);
if bigger != glyph {
glyph = bigger;
shown = String::new();
}
}
let drawn = glyph_layout(font, glyph, class, size, &shown, (italic, bold));
let width = drawn.width;
children.push(Placed {x: cursor, y: 0.0, layout: drawn});
cursor += width;
}
if children.len() == 1 {
let only = children.pop().expect("子が 1 つある");
let placed = only.layout;
if class == Class::Large {
return center_on_axis(placed, font, size);
}
return placed;
}
let mut result = group(children);
result.width = cursor;
result
}
/// 大きな演算子を数式軸の高さに合わせる
fn center_on_axis(placed: Layout, font: &Font, size: f64) -> Layout {
let axis = font::constant(font).axis_height * size;
let middle = (placed.height - placed.depth) / 2.0;
shift(placed, middle - axis)
}
/// 高さが足りる大きさ違いの字形を選ぶ。なければ持っているうちで一番大きいもの
fn larger(font: &Font, glyph: u16, needed: f64) -> u16 {
let Some(growth) = font::vertical_growth(font, glyph) else {
return glyph;
};
for variant in &growth.variant {
if variant.measure >= needed {
return variant.glyph;
}
}
growth.variant.last().map_or(glyph, |variant| variant.glyph)
}
fn text_layout(font: &Font, body: &str, size: f64) -> Layout {
let mut children = Vec::new();
let mut cursor = 0.0;
for character in body.chars() {
let glyph = font::glyph_of(font, character).unwrap_or(0);
let shown = character.to_string();
let drawn = glyph_layout(font, glyph, Class::Ordinary, size, &shown, (false, false));
let width = drawn.width;
children.push(Placed {x: cursor, y: 0.0, layout: drawn});
cursor += width;
}
let mut result = group(children);
result.width = cursor;
result
}
fn row_layout(
items: &[Node],
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let mut children = Vec::new();
let mut cursor = 0.0;
let mut previous: Option<Class> = None;
for item in items {
let class = node::class_of(item);
if let Some(left) = previous {
cursor += gap(left, class) * size;
}
let placed = layout(item, font, size, style, display);
let width = placed.width + trailing_slant(item, &placed, font) * size;
children.push(Placed {x: cursor, y: 0.0, layout: placed});
cursor += width;
previous = Some(class);
}
let mut result = group(children);
result.width = cursor.max(result.width);
result
}
/// 添字の文字の大きさ
fn script_size(font: &Font, size: f64) -> f64 {
let value = font::constant(font);
(size * value.script_percent).max(value.script_script_percent)
}
#[allow(clippy::too_many_arguments)]
fn fraction_layout(
numerator: &Node,
denominator: &Node,
bar: bool,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let value = font::constant(font);
let inner = if display {size} else {script_size(font, size)};
let upper = layout(numerator, font, inner, style, false);
let lower = layout(denominator, font, inner, style, false);
let axis = value.axis_height * size;
let thickness = value.fraction_rule_thickness * size;
let mut up;
let mut down;
if bar {
up = if display {
value.fraction_numerator_display_shift_up
} else {
value.fraction_numerator_shift_up
} * size;
down = if display {
value.fraction_denominator_display_shift_down
} else {
value.fraction_denominator_shift_down
} * size;
let upper_gap = if display {
value.fraction_numerator_display_gap_min
} else {
value.fraction_numerator_gap_min
} * size;
let lower_gap = if display {
value.fraction_denominator_display_gap_min
} else {
value.fraction_denominator_gap_min
} * size;
let above = (up - upper.depth) - (axis + thickness / 2.0);
let below = (axis - thickness / 2.0) - (lower.height - down);
if above < upper_gap {
up += upper_gap - above;
}
if below < lower_gap {
down += lower_gap - below;
}
} else {
up = if display {value.stack_top_display_shift_up} else {value.stack_top_shift_up} * size;
down = if display {
value.stack_bottom_display_shift_down
} else {
value.stack_bottom_shift_down
} * size;
let least = if display {value.stack_display_gap_min} else {value.stack_gap_min} * size;
let between = (up - upper.depth) - (lower.height - down);
if between < least {
let extra = (least - between) / 2.0;
up += extra;
down += extra;
}
}
let padding = FRACTION_PADDING * size;
let upper_width = upper.width;
let lower_width = lower.width;
let width = upper_width.max(lower_width) + 2.0 * padding;
let mut children = vec![
Placed {x: (width - upper_width) / 2.0, y: -up, layout: upper},
Placed {x: (width - lower_width) / 2.0, y: down, layout: lower},
];
if bar {
children.push(Placed {
x: 0.0,
y: -(axis - thickness / 2.0),
layout: rule(width, thickness),
});
}
let mut result = group(children);
result.width = width;
result
}
/// 縦に伸ばした字形を作る
///
/// フォントが持つ大きさ違いの字形を選び、それでも足りなければ部品を積む。
/// 大きさ違いを持たない書体(MATH テーブルのないもの)でだけ、素の字を縦へ引き伸ばす
fn stretch_vertical(font: &Font, glyph: u16, needed: f64, size: f64) -> Layout {
let (height, depth) = font::extent(font, glyph);
let natural = (height + depth) * size;
if natural >= needed || natural <= 0.0 {
return glyph_layout(font, glyph, Class::Ordinary, size, "", (false, false));
}
let Some(growth) = font::vertical_growth(font, glyph) else {
let pull = needed / natural;
return stretched_glyph(font, glyph, Class::Ordinary, size, "", (false, false), pull);
};
for variant in &growth.variant {
if variant.measure * size >= needed {
return glyph_layout(font, variant.glyph, Class::Ordinary, size, "", (false, false));
}
}
if growth.part.is_empty() {
let last = growth.variant.last().map_or(glyph, |variant| variant.glyph);
return glyph_layout(font, last, Class::Ordinary, size, "", (false, false));
}
assemble(font, growth, needed, size)
}
/// 字形が縦に占める長さ
fn reach_of(font: &Font, glyph: u16, size: f64) -> f64 {
let (height, depth) = font::extent(font, glyph);
(height + depth) * size
}
/// 部品を縦に積んで、要る高さの字形を作る
///
/// 部品は下から上へ並んでいる。伸ばせる部品を何回か繰り返し、隣どうしを重ねてつなぐ。
fn assemble(font: &Font, growth: &Construction, needed: f64, size: f64) -> Layout {
let least = font::min_overlap(font) * size;
let steady: f64 = growth
.part
.iter()
.filter(|part| !part.extender)
.map(|part| reach_of(font, part.glyph, size))
.sum();
let stretchy: f64 = growth
.part
.iter()
.filter(|part| part.extender)
.map(|part| reach_of(font, part.glyph, size))
.sum();
let extenders = growth.part.iter().filter(|part| part.extender).count();
let fixed = growth.part.len() - extenders;
let mut repeat = 1usize;
// 重なりを最小にしたときが一番高い。そこで足りる繰り返しの回数を探す
while repeat < 200 && extenders > 0 {
let joints = (fixed + extenders * repeat).saturating_sub(1) as f64;
if steady + stretchy * repeat as f64 - least * joints >= needed {
break;
}
repeat += 1;
}
let mut used = Vec::new();
for part in &growth.part {
let times = if part.extender {repeat} else {1};
for _ in 0..times {
used.push(*part);
}
}
let total: f64 = used.iter().map(|part| reach_of(font, part.glyph, size)).sum();
let joints = used.len().saturating_sub(1) as f64;
let mut overlap = least;
if joints > 0.0 {
let widest = used
.windows(2)
.map(|pair| (pair[0].end_connector * size).min(pair[1].start_connector * size))
.fold(f64::INFINITY, f64::min);
overlap = ((total - needed) / joints).clamp(least, widest.max(least));
}
let mut children = Vec::new();
let mut bottom = 0.0;
for part in &used {
let drawn = glyph_layout(font, part.glyph, Class::Ordinary, size, "", (false, false));
let reach = drawn.height + drawn.depth;
let y = bottom - drawn.depth;
children.push(Placed {x: 0.0, y, layout: drawn});
bottom -= reach - overlap;
}
let width = used
.iter()
.map(|part| font::advance(font, part.glyph) * size)
.fold(0.0, f64::max);
let mut result = group(children);
result.width = width;
result.depth = 0.0;
result.height = total - overlap * joints;
result
}
/// 大きさを決めた括弧。数式軸を中心にして置く
fn sized_delimiter(font: &Font, text: &str, needed: f64, size: f64) -> Layout {
match place_delimiter(font, text, needed, size) {
Some(part) => shift(part.layout, part.y),
None => blank(0.0),
}
}
/// 中身の幅に合わせて横に伸ばした字形。伸ばした字形には文字の割り当てがない
fn stretch_horizontal(font: &Font, character: char, needed: f64, size: f64, class: Class) -> Layout {
let plain = font::glyph_of(font, character).unwrap_or(0);
let Some(growth) = font::horizontal_growth(font, plain) else {
return glyph_layout(font, plain, class, size, &character.to_string(), (false, false));
};
for variant in &growth.variant {
if variant.measure * size >= needed {
let shown = if variant.glyph == plain {character.to_string()} else {String::new()};
return glyph_layout(font, variant.glyph, class, size, &shown, (false, false));
}
}
if !growth.part.is_empty() {
return assemble_horizontal(font, growth, needed, size, class);
}
let last = growth.variant.last().map_or(plain, |variant| variant.glyph);
let shown = if last == plain {character.to_string()} else {String::new()};
glyph_layout(font, last, class, size, &shown, (false, false))
}
/// 部品を横に並べて、要る幅の字形を作る
///
/// 部品は左から右へ並んでいる。伸ばせる部品を何回か繰り返し、隣どうしを重ねてつなぐ。
/// 印に使う字形は送り幅を持たないので、長さは MATH テーブルの値で測る
fn assemble_horizontal(
font: &Font,
growth: &Construction,
needed: f64,
size: f64,
class: Class,
) -> Layout {
let least = font::min_overlap(font) * size;
let steady: f64 = growth
.part
.iter()
.filter(|part| !part.extender)
.map(|part| part.full_advance * size)
.sum();
let stretchy: f64 = growth
.part
.iter()
.filter(|part| part.extender)
.map(|part| part.full_advance * size)
.sum();
let extenders = growth.part.iter().filter(|part| part.extender).count();
let fixed = growth.part.len() - extenders;
let mut repeat = 1usize;
while repeat < 200 && extenders > 0 {
let joints = (fixed + extenders * repeat).saturating_sub(1) as f64;
if steady + stretchy * repeat as f64 - least * joints >= needed {
break;
}
repeat += 1;
}
let mut used = Vec::new();
for part in &growth.part {
let times = if part.extender {repeat} else {1};
for _ in 0..times {
used.push(*part);
}
}
let total: f64 = used.iter().map(|part| part.full_advance * size).sum();
let joints = used.len().saturating_sub(1) as f64;
let mut overlap = least;
if joints > 0.0 {
let widest = used
.windows(2)
.map(|pair| (pair[0].end_connector * size).min(pair[1].start_connector * size))
.fold(f64::INFINITY, f64::min);
overlap = ((total - needed) / joints).clamp(least, widest.max(least));
}
let mut children = Vec::new();
let mut cursor = 0.0;
// 印の字形はベースラインより上にしか墨がない。group は深さを 0 で切り上げるので、
// ここでは切り上げずに測る。切り上げると印が中身から浮いてしまう
let mut height = f64::NEG_INFINITY;
let mut depth = f64::NEG_INFINITY;
for part in &used {
let drawn = glyph_layout(font, part.glyph, class, size, "", (false, false));
height = height.max(drawn.height);
depth = depth.max(drawn.depth);
children.push(Placed {x: cursor, y: 0.0, layout: drawn});
cursor += part.full_advance * size - overlap;
}
let mut result = group(children);
result.width = total - overlap * joints;
result.height = height;
result.depth = depth;
result
}
/// 上下に置くものの幅に合わせて伸びる記号
fn extend_layout(
mark: &str,
above: Option<&Node>,
below: Option<&Node>,
font: &Font,
size: f64,
style: Style,
) -> Layout {
let small = script_size(font, size);
let upper = above.map(|node| layout(node, font, small, style, false));
let lower = below.map(|node| layout(node, font, small, style, false));
let label = upper
.as_ref()
.map_or(0.0, |item| item.width)
.max(lower.as_ref().map_or(0.0, |item| item.width));
let character = mark.chars().next().unwrap_or(' ');
let needed = label + EXTEND_PADDING * size;
let drawn = stretch_horizontal(font, character, needed, size, Class::Relation);
let drawn_width = drawn.width;
let drawn_height = drawn.height;
let drawn_depth = drawn.depth;
let width = drawn_width.max(label);
let gap = EXTEND_GAP * size;
let mut children = vec![Placed {x: (width - drawn_width) / 2.0, y: 0.0, layout: drawn}];
if let Some(item) = upper {
let y = -(drawn_height + gap + item.depth);
children.push(Placed {x: (width - item.width) / 2.0, y, layout: item});
}
if let Some(item) = lower {
let y = drawn_depth + gap + item.height;
children.push(Placed {x: (width - item.width) / 2.0, y, layout: item});
}
let mut result = group(children);
result.width = width;
result
}
/// 括弧を数式軸の中心にそろえて置く
fn place_delimiter(font: &Font, text: &str, needed: f64, size: f64) -> Option<Placed> {
let character = text.chars().next()?;
let plain = font::glyph_of(font, character)?;
let mut drawn = stretch_vertical(font, plain, needed, size);
// 素の大きさのままなら文字として書き出せる。大きい字形に替わったものは輪郭で描く
if let Content::Glyph {text: shown, glyph, ..} = &mut drawn.content {
if *glyph == plain {
*shown = character.to_string();
}
}
let axis = font::constant(font).axis_height * size;
let middle = (drawn.height - drawn.depth) / 2.0;
Some(Placed {x: 0.0, y: middle - axis, layout: drawn})
}
/// 中身の高さに合わせて伸びる括弧で囲む
fn fence(inside: Layout, left: &str, right: &str, font: &Font, size: f64) -> Layout {
let axis = font::constant(font).axis_height * size;
let half = (inside.height - axis).max(inside.depth + axis);
let needed = 2.0 * half;
let mut children = Vec::new();
let mut cursor = 0.0;
if let Some(mut part) = place_delimiter(font, left, needed, size) {
part.x = cursor;
cursor += part.layout.width + inner_room(font, &part.layout, false) * size;
children.push(part);
}
let inside_width = inside.width;
children.push(Placed {x: cursor, y: 0.0, layout: inside});
cursor += inside_width;
if let Some(mut part) = place_delimiter(font, right, needed, size) {
cursor += inner_room(font, &part.layout, true) * size;
part.x = cursor;
cursor += part.layout.width;
children.push(part);
}
let mut result = group(children);
result.width = cursor;
result
}
/// まとまりの先頭にある字形
fn leading_glyph(placed: &Layout) -> Option<u16> {
match &placed.content {
Content::Glyph {glyph, ..} => Some(*glyph),
Content::Group(children) => children.first().and_then(|child| leading_glyph(&child.layout)),
Content::Rule => None,
}
}
/// 括弧の内側に足りない余白。closing が true なら閉じ括弧で、内側は左になる
///
/// 素の大きさのままの括弧には足さない。地の文に書く (x) と同じ詰まり具合になり、
/// \left( x \right) と (x) が違って見えることがなくなる
fn inner_room(font: &Font, placed: &Layout, closing: bool) -> f64 {
let Some(glyph) = leading_glyph(placed) else {
return FENCE_ROOM;
};
if let Content::Glyph {text, stretch, ..} = &placed.content {
let plain = text.chars().next().and_then(|character| font::glyph_of(font, character));
if plain == Some(glyph) && *stretch == 1.0 {
return 0.0;
}
}
let (left, right) = font::bearing(font, glyph);
let inner = if closing {left} else {right};
(FENCE_ROOM - inner).max(0.0)
}
/// 字の後ろに入れる、斜体のはみ出しぶんの空き
///
/// 斜体の字は上へ行くほど右へ出る。f(x) のように括弧が続くと、字の頭が括弧に迫って窮屈になる。
/// TeX と同じく、はみ出す量を字の後ろに足す。添字が付いているものは、その量を
/// 添字の位置決めにすでに使っているので足さない
fn trailing_slant(item: &Node, placed: &Layout, font: &Font) -> f64 {
if matches!(item, Node::Scripts {..}) {
return 0.0;
}
trailing_glyph(placed).map_or(0.0, |glyph| font::italic_correction(font, glyph))
}
/// まとまりが字形 1 つだけでできているなら、その字形
///
/// 印を横のどこに置くかは、フォントが字形ごとに持っている取り付け位置で決まる。
/// 字が 2 つ以上あるまとまりにはその値がないので、幅の真ん中に置く
fn lone_glyph(placed: &Layout) -> Option<u16> {
match &placed.content {
Content::Glyph {glyph, ..} => Some(*glyph),
Content::Group(children) => {
let mut found = None;
for child in children {
if let Some(glyph) = lone_glyph(&child.layout) {
if found.is_some() {
return None;
}
found = Some(glyph);
}
}
found
}
Content::Rule => None,
}
}
/// まとまりの終わりにある字形。斜体のはみ出しを測るのに使う
fn trailing_glyph(placed: &Layout) -> Option<u16> {
match &placed.content {
Content::Glyph {glyph, ..} => Some(*glyph),
Content::Group(children) => children.last().and_then(|child| trailing_glyph(&child.layout)),
Content::Rule => None,
}
}
#[allow(clippy::too_many_arguments)]
fn scripts_layout(
base: &Node,
superscript: Option<&Node>,
subscript: Option<&Node>,
limits: Limits,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let core = layout(base, font, size, style, display);
let small = script_size(font, size);
let upper = superscript.map(|node| layout(node, font, small, style, false));
let lower = subscript.map(|node| layout(node, font, small, style, false));
let stacked = match limits {
Limits::Always => true,
Limits::Never => false,
Limits::Auto => display,
};
if stacked {
return stacked_scripts(core, upper, lower, font, size);
}
side_scripts(core, upper, lower, font, size)
}
fn side_scripts(
core: Layout,
upper: Option<Layout>,
lower: Option<Layout>,
font: &Font,
size: f64,
) -> Layout {
let value = font::constant(font);
let start = core.width;
let core_height = core.height;
let core_depth = core.depth;
let slant = trailing_glyph(&core).map_or(0.0, |glyph| font::italic_correction(font, glyph) * size);
let mut up = value.superscript_shift_up * size;
let mut down = value.subscript_shift_down * size;
if let Some(above) = upper.as_ref() {
up = up.max(core_height - value.superscript_baseline_drop_max * size);
up = up.max(value.superscript_bottom_min * size + above.depth);
}
if let Some(below) = lower.as_ref() {
down = down.max(core_depth + value.subscript_baseline_drop_min * size);
down = down.max(below.height - value.subscript_top_max * size);
}
if let (Some(above), Some(below)) = (upper.as_ref(), lower.as_ref()) {
let least = value.sub_superscript_gap_min * size;
let between = (up - above.depth) - (below.height - down);
if between < least {
down += least - between;
let room = value.superscript_bottom_max_with_subscript * size - (up - above.depth);
if room > 0.0 {
up += room;
down -= room;
}
}
}
// 斜体の字形は上へ行くほど右へ寄る。上付きは送り幅の位置でよく、下付きは
// その張り出しぶん左へ寄せて、字の下側に入れる
let room = (SCRIPT_GAP * (core_height + core_depth)).max(SCRIPT_GAP_MIN * size);
let upper_x = start + room;
let lower_x = (start + room - slant).max(0.0);
let mut width = start;
let mut children = vec![Placed {x: 0.0, y: 0.0, layout: core}];
if let Some(above) = upper {
width = width.max(upper_x + above.width);
children.push(Placed {x: upper_x, y: -up, layout: above});
}
if let Some(below) = lower {
width = width.max(lower_x + below.width);
children.push(Placed {x: lower_x, y: down, layout: below});
}
let mut result = group(children);
result.width = width + value.space_after_script * size;
result
}
fn stacked_scripts(
core: Layout,
upper: Option<Layout>,
lower: Option<Layout>,
font: &Font,
size: f64,
) -> Layout {
let value = font::constant(font);
let core_width = core.width;
let core_height = core.height;
let core_depth = core.depth;
let width = core_width
.max(upper.as_ref().map_or(0.0, |item| item.width))
.max(lower.as_ref().map_or(0.0, |item| item.width));
let mut children = vec![Placed {x: (width - core_width) / 2.0, y: 0.0, layout: core}];
if let Some(above) = upper {
let rise = (value.upper_limit_gap_min * size + above.depth)
.max(value.upper_limit_baseline_rise_min * size);
children.push(Placed {
x: (width - above.width) / 2.0,
y: -(core_height + rise),
layout: above,
});
}
if let Some(below) = lower {
let drop = (value.lower_limit_gap_min * size + below.height)
.max(value.lower_limit_baseline_drop_min * size);
children.push(Placed {
x: (width - below.width) / 2.0,
y: core_depth + drop,
layout: below,
});
}
let mut result = group(children);
result.width = width;
result
}
fn root_layout(
index: Option<&Node>,
body: &Node,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let value = font::constant(font);
let inside = layout(body, font, size, style, display);
let inside_width = inside.width;
let inside_height = inside.height;
let inside_depth = inside.depth;
let thickness = value.radical_rule_thickness * size;
let clearance = if display {
value.radical_display_vertical_gap
} else {
value.radical_vertical_gap
} * size;
let extra = value.radical_extra_ascender * size;
let needed = inside_height + inside_depth + clearance + thickness;
let surd_glyph = font::glyph_of(font, '\u{221a}').unwrap_or(0);
let mut surd = stretch_vertical(font, surd_glyph, needed, size);
if let Content::Glyph {text, glyph, ..} = &mut surd.content {
if *glyph == surd_glyph {
*text = "\u{221a}".to_string();
}
}
let surd_width = surd.width;
let surd_reach = surd.height + surd.depth;
// 根号の下端を中身の下端にそろえる。線は根号の頭に来る
let surd_y = inside_depth - surd.depth;
let top = inside_depth - surd_reach;
let small = index.map(|node| {
let tiny = size * value.script_script_percent;
layout(node, font, tiny, style, false)
});
let before = value.radical_kern_before_degree * size;
let after = value.radical_kern_after_degree * size;
let index_width = small.as_ref().map_or(0.0, |item| item.width);
let surd_x = if small.is_some() {
(before + index_width + after).max(0.0)
} else {
0.0
};
let body_x = surd_x + surd_width;
let mut children = Vec::new();
if let Some(item) = small {
let raise = value.radical_degree_bottom_raise_percent * surd_reach;
let y = inside_depth - raise - item.depth;
children.push(Placed {x: before, y, layout: item});
}
children.push(Placed {x: surd_x, y: surd_y, layout: surd});
children.push(Placed {
x: body_x,
y: top + thickness,
layout: rule(inside_width, thickness),
});
children.push(Placed {x: body_x, y: 0.0, layout: inside});
let mut result = group(children);
result.width = body_x + inside_width;
result.height = result.height.max(-top) + extra;
result
}
#[allow(clippy::too_many_arguments)]
fn matrix_layout(
rows: &[Vec<Node>],
left: &str,
right: &str,
align: &[Align],
lines: &[usize],
font: &Font,
size: f64,
style: Style,
) -> Layout {
let cells: Vec<Vec<Layout>> = rows
.iter()
.map(|row| row.iter().map(|cell| layout(cell, font, size, style, false)).collect())
.collect();
let columns = cells.iter().map(Vec::len).max().unwrap_or(0);
let mut column_width = vec![0.0f64; columns];
for row in &cells {
for (index, cell) in row.iter().enumerate() {
column_width[index] = column_width[index].max(cell.width);
}
}
let row_height: Vec<f64> = cells
.iter()
.map(|row| row.iter().fold(ROW_HEIGHT * size, |value, cell| value.max(cell.height)))
.collect();
let row_depth: Vec<f64> = cells
.iter()
.map(|row| row.iter().fold(ROW_DEPTH * size, |value, cell| value.max(cell.depth)))
.collect();
let column_gap = COLUMN_GAP * size;
let row_gap = ROW_GAP * size;
let thickness = font::constant(font).fraction_rule_thickness * size;
let axis = font::constant(font).axis_height * size;
let mut baselines = Vec::new();
let mut down = 0.0;
for index in 0..cells.len() {
if index > 0 {
down += row_depth[index - 1] + row_gap;
}
down += row_height[index];
baselines.push(down);
}
let total = down + cells.last().map_or(0.0, |_| row_depth[cells.len() - 1]);
let offset = total / 2.0 + axis;
let mut column_start = Vec::with_capacity(columns);
let mut across = 0.0;
for width in &column_width {
column_start.push(across);
across += width + column_gap;
}
let content_width = if columns == 0 {0.0} else {across - column_gap};
// 括弧を置く側だけ空ける。cases のように片側だけ括弧が付くものがある
let left_edge = if left.is_empty() {0.0} else {MATRIX_ROOM * size};
let right_edge = if right.is_empty() {0.0} else {MATRIX_ROOM * size};
let mut children = Vec::new();
for (row_index, row) in cells.into_iter().enumerate() {
for (column_index, cell) in row.into_iter().enumerate() {
let room = column_width[column_index];
let inside = match align.get(column_index) {
Some(Align::Left) => 0.0,
Some(Align::Right) => room - cell.width,
_ => (room - cell.width) / 2.0,
};
children.push(Placed {
x: left_edge + column_start[column_index] + inside,
y: baselines[row_index] - offset,
layout: cell,
});
}
}
for line in lines {
let down = match line {
0 => -row_gap / 2.0,
index if *index >= baselines.len() => total + row_gap / 2.0,
index => baselines[index - 1] + row_depth[index - 1] + row_gap / 2.0,
};
children.push(Placed {
x: 0.0,
y: down - offset + thickness / 2.0,
layout: rule(content_width + left_edge + right_edge, thickness),
});
}
let mut block = group(children);
block.width = content_width + left_edge + right_edge;
fence(block, left, right, font, size)
}
#[allow(clippy::too_many_arguments)]
fn accent_layout(
mark: &str,
body: &Node,
above: bool,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let value = font::constant(font);
let inside = layout(body, font, size, style, display);
let character = mark.chars().next().unwrap_or(' ');
// 組み合わせ用の印は、文字として置くと前の字に付いてしまう。輪郭で描くので文字は持たせない
let inside_width = inside.width;
let inside_height = inside.height;
let inside_depth = inside.depth;
let base_center = lone_glyph(&inside)
.map(|found| font::accent_center(font, found) * size)
.unwrap_or(inside_width / 2.0);
// 幅のある印は、中身の幅に合わせて横に伸ばす
let drawn = stretch_horizontal(font, character, inside_width, size, Class::Ordinary);
let drawn_width = drawn.width;
let drawn_depth = drawn.depth;
let drawn_height = drawn.height;
// 部品を並べて作った印には取り付け位置がないので、幅の真ん中を使う
let mark_center = match lone_glyph(&drawn) {
Some(wide) => font::accent_center(font, wide) * size,
None => drawn_width / 2.0,
};
let y = if above {
// 印の字形は下端がベースラインより上にあるので、その深さぶんを戻して置く
let bottom = inside_height.max(value.accent_base_height * size) + MARK_GAP * size;
-bottom - drawn_depth
} else {
inside_depth + MARK_GAP * size + drawn_height
};
// 印の取り付け位置を中身の中心にそろえる。印のほうが広いときは中身を右へずらす。
// 中身を動かさずに印を 0 で止めると、印が右へはみ出したまま中央からずれる
let offset = base_center - mark_center;
let inside_x = (-offset).max(0.0);
let mark_x = offset.max(0.0);
let width = (inside_x + inside_width).max(mark_x + drawn_width);
let children = vec![
Placed {x: inside_x, y: 0.0, layout: inside},
Placed {x: mark_x, y, layout: drawn},
];
let mut result = group(children);
result.width = width;
result
}
fn line_layout(
body: &Node,
above: bool,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let value = font::constant(font);
let inside = layout(body, font, size, style, display);
let thickness = if above {
value.overbar_rule_thickness
} else {
value.underbar_rule_thickness
} * size;
let clearance = (if above {
value.overbar_vertical_gap
} else {
value.underbar_vertical_gap
} + MARK_GAP) * size;
let extra = if above {
value.overbar_extra_ascender
} else {
value.underbar_extra_descender
} * size;
let width = inside.width;
let inside_height = inside.height;
let inside_depth = inside.depth;
let y = if above {
-(inside_height + clearance)
} else {
inside_depth + clearance + thickness
};
let children = vec![
Placed {x: 0.0, y: 0.0, layout: inside},
Placed {x: 0.0, y, layout: rule(width, thickness)},
];
let mut result = group(children);
result.width = width;
if above {
result.height += extra;
} else {
result.depth += extra;
}
result
}
/// 場所だけ空けて何も描かない
///
/// 中身を組んでその寸法だけを取り、中身は捨てる。桁をそろえるのに使う
fn phantom_layout(
body: &Node,
width: bool,
height: bool,
font: &Font,
size: f64,
style: Style,
display: bool,
) -> Layout {
let inside = layout(body, font, size, style, display);
Layout {
content: Content::Group(Vec::new()),
width: if width {inside.width} else {0.0},
height: if height {inside.height} else {0.0},
depth: if height {inside.depth} else {0.0},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::parse;
fn sample() -> Font {
let data = std::fs::read("font/latinmodern-math.otf").expect("試験用のフォントを読めません");
font::load(data).expect("フォントを読み込めません")
}
fn build(font: &Font, source: &str, display: bool) -> Layout {
layout(&parse(source).unwrap(), font, 1.0, Style::Auto, display)
}
/// 一番外側は Row なので、その中の最初のまとまりを取り出す
fn first(placed: &Layout) -> &Layout {
&parts(placed)[0].layout
}
fn parts(placed: &Layout) -> &[Placed] {
let Content::Group(children) = &placed.content else {panic!("Group ではありません")};
children
}
/// 入れ子をたどって最初の字形を取り出す
fn deep_glyph(placed: &Layout) -> u16 {
match &placed.content {
Content::Glyph {glyph, ..} => *glyph,
Content::Group(children) => deep_glyph(&children[0].layout),
Content::Rule => 0,
}
}
/// 描かれるものの数を数える
fn drawn(placed: &Layout) -> usize {
match &placed.content {
Content::Glyph {..} | Content::Rule => 1,
Content::Group(children) => children.iter().map(|one| drawn(&one.layout)).sum(),
}
}
#[test]
fn a_phantom_keeps_the_room_and_draws_nothing() {
let font = sample();
let shown = build(&font, "abc", false);
let hidden = build(&font, "\\phantom{abc}", false);
assert_eq!(hidden.width, shown.width);
assert_eq!(hidden.height, shown.height);
assert_eq!(hidden.depth, shown.depth);
assert!(drawn(&shown) > 0);
assert_eq!(drawn(&hidden), 0);
}
#[test]
fn a_one_way_phantom_keeps_only_one_size() {
let font = sample();
let shown = build(&font, "abc", false);
let across = build(&font, "\\hphantom{abc}", false);
let tall = build(&font, "\\vphantom{abc}", false);
assert_eq!(across.width, shown.width);
assert_eq!(across.height, 0.0);
assert_eq!(across.depth, 0.0);
assert_eq!(tall.width, 0.0);
assert_eq!(tall.height, shown.height);
assert_eq!(tall.depth, shown.depth);
}
#[test]
fn a_phantom_lines_the_columns_up() {
let font = sample();
let plain = build(&font, "5", false);
let padded = build(&font, "\\phantom{-}5", false);
let signed = build(&font, "-5", false);
assert!(padded.width > plain.width);
assert!((padded.width - signed.width).abs() < 1e-9);
}
fn glyph_id(placed: &Layout) -> u16 {
let Content::Glyph {glyph, ..} = &placed.content else {panic!("Glyph ではありません")};
*glyph
}
fn shown(placed: &Layout) -> String {
match &placed.content {
Content::Glyph {text, ..} => text.clone(),
Content::Group(children) => children.iter().map(|child| shown(&child.layout)).collect(),
Content::Rule => String::new(),
}
}
fn close(left: f64, right: f64) -> bool {
(left - right).abs() < 0.0005
}
#[test]
fn a_variable_uses_the_math_italic_shape() {
let font = sample();
let placed = build(&font, "x", false);
assert_eq!(shown(&placed), "\u{1d465}");
assert_eq!(shown(&build(&font, "2", false)), "2");
assert_eq!(shown(&build(&font, r"\mathrm{x}", false)), "x");
assert_eq!(shown(&build(&font, r"\sin", false)), "sin");
}
#[test]
fn a_letter_takes_the_width_the_font_gives_it() {
let font = sample();
let placed = build(&font, "x", false);
let glyph = font::glyph_of(&font, '\u{1d465}').unwrap();
assert!(close(placed.width, font::advance(&font, glyph)));
assert!(close(placed.height, font::extent(&font, glyph).0));
}
#[test]
fn binary_operators_get_space_around_them() {
let font = sample();
let tight = build(&font, "ab", false).width;
let spaced = build(&font, "a+b", false).width;
let plus = font::advance(&font, font::glyph_of(&font, '+').unwrap());
assert!(close(spaced - tight - plus, 2.0 * MEDIUM));
}
#[test]
fn relations_get_more_space_than_binary_operators() {
assert!(gap(Class::Ordinary, Class::Relation) > gap(Class::Ordinary, Class::Binary));
assert_eq!(gap(Class::Open, Class::Ordinary), 0.0);
assert_eq!(gap(Class::Space(1.0), Class::Relation), 0.0);
}
#[test]
fn the_fraction_rule_comes_from_the_font() {
let font = sample();
let placed = build(&font, r"\frac{a}{b}", false);
let bar = parts(first(&placed))
.iter()
.find(|child| child.layout.content == Content::Rule)
.expect("分数線がありません");
assert!(close(bar.layout.height, font::constant(&font).fraction_rule_thickness));
// 線の中心が数式軸に来る
let center = -bar.y + bar.layout.height / 2.0;
assert!(close(center, font::constant(&font).axis_height));
}
#[test]
fn a_fixed_fraction_ignores_the_surrounding_shape() {
let font = sample();
let inline = build(&font, r"\frac{a}{b}", false);
let display = build(&font, r"\frac{a}{b}", true);
// 文中でも \dfrac は display の分数と同じ寸法になる
let fixed = build(&font, r"\dfrac{a}{b}", false);
assert!(fixed.height > inline.height, "文中の \\dfrac が大きくなっていません");
assert!(close(fixed.height, display.height) && close(fixed.depth, display.depth));
// display の中でも \tfrac は文中の分数と同じ寸法になる
let text = build(&font, r"\tfrac{a}{b}", true);
assert!(close(text.height, inline.height) && close(text.depth, inline.depth));
}
#[test]
fn a_plain_paren_keeps_its_own_shape() {
let font = sample();
let placed = build(&font, r"\left( x \right)", false);
let base = font::glyph_of(&font, '(').unwrap();
assert_eq!(glyph_id(&parts(first(&placed))[0].layout), base);
}
#[test]
fn a_tall_fence_uses_a_bigger_shape_from_the_font() {
let font = sample();
let placed = build(&font, r"\left( \frac{a}{b} \right)", false);
let base = font::glyph_of(&font, '(').unwrap();
let used = glyph_id(&parts(first(&placed))[0].layout);
assert_ne!(used, base, "大きい字形に替わっていません");
assert!(font::extent(&font, used).0 > font::extent(&font, base).0);
}
#[test]
fn a_grown_fence_keeps_room_for_its_content() {
let font = sample();
let placed = build(&font, r"\left[ \frac{a}{b} \right]", false);
let pieces = parts(first(&placed));
let open = &pieces[0];
let body = &pieces[1];
let (_, right) = font::bearing(&font, glyph_id(&open.layout));
let room = body.x - (open.x + open.layout.width) + right;
assert!(room >= FENCE_ROOM - 0.0005, "内側の空きが足りません: {room}");
}
#[test]
fn a_stretched_fence_gets_room_too() {
let font = sample();
let placed = build(&font, r"\left[ \frac{a}{b} \right]", false);
let pieces = parts(first(&placed));
let open = &pieces[0];
assert!(pieces[1].x > open.x + open.layout.width, "引き伸ばした括弧に空きがありません");
}
#[test]
fn a_fence_at_its_natural_size_is_left_alone() {
let font = sample();
let placed = build(&font, r"\left[ x \right]", false);
let pieces = parts(first(&placed));
let open = &pieces[0];
assert!(close(pieces[1].x, open.x + open.layout.width), "素の括弧に空きが入っています");
}
#[test]
fn a_very_tall_fence_is_built_from_parts() {
let font = sample();
let rows = r"a \\ b \\ c \\ d \\ e \\ f \\ g \\ h \\ i \\ j";
let source = format!(r"\left\{{ \begin{{matrix}} {rows} \end{{matrix}} \right\}}");
let placed = build(&font, &source, false);
let brace = &parts(first(&placed))[0].layout;
let Content::Group(pieces) = &brace.content else {
panic!("積み木になっていません")
};
assert!(pieces.len() > 3, "部品の数: {}", pieces.len());
// 積んだ結果が要る高さに届いている
assert!(brace.height + brace.depth > 5.0);
}
#[test]
fn stretched_shapes_carry_no_character() {
let font = sample();
let sources = [
r"\left\{ \begin{matrix} a \\ b \\ c \\ d \\ e \\ f \end{matrix} \right\}",
r"\sqrt{\frac{a}{b}}",
r"\widehat{xyz}",
];
fn drawn_only(placed: &Layout, found: &mut bool) {
match &placed.content {
Content::Glyph {text, glyph, ..} => {
if text.is_empty() && *glyph != 0 {
*found = true;
}
}
Content::Group(children) => {
for child in children {
drawn_only(&child.layout, found);
}
}
Content::Rule => {}
}
}
for source in sources {
let mut found = false;
drawn_only(&build(&font, source, true), &mut found);
assert!(found, "輪郭で描く字形が出ていません: {source}");
}
}
#[test]
fn a_grown_glyph_carries_no_character() {
let font = sample();
let placed = build(&font, r"\left( \frac{a}{b} \right)", false);
let open = &parts(first(&placed))[0].layout;
let Content::Glyph {text, glyph, ..} = &open.content else {
panic!("字形になっていません")
};
assert_ne!(*glyph, font::glyph_of(&font, '(').unwrap());
assert!(text.is_empty(), "大きい字形に文字が付いています");
}
#[test]
fn the_radical_bar_meets_the_top_of_the_sign() {
let font = sample();
let placed = build(&font, r"\sqrt{x + y}", false);
let inside = parts(first(&placed));
let surd = &inside[0];
let bar = inside
.iter()
.find(|child| child.layout.content == Content::Rule)
.expect("根号の線がありません");
let surd_top = surd.y - surd.layout.height;
let bar_top = bar.y - bar.layout.height;
assert!((surd_top - bar_top).abs() < 0.001, "線と根号の頭がずれています");
}
#[test]
fn limits_move_above_and_below_in_display() {
let font = sample();
let inline = build(&font, r"\sum_{k=1}^{n}", false);
let block = build(&font, r"\sum_{k=1}^{n}", true);
assert!(block.height > inline.height);
assert!(block.width < inline.width);
}
#[test]
fn large_operators_grow_in_display() {
let font = sample();
let inline = build(&font, r"\sum", false);
let block = build(&font, r"\sum", true);
assert!(block.height + block.depth > inline.height + inline.depth);
assert_ne!(glyph_id(first(&inline)), glyph_id(&parts(first(&block))[0].layout));
}
#[test]
fn a_slanted_letter_keeps_room_after_it() {
let font = sample();
let slanted = font::glyph_of(&font, '\u{1d453}').unwrap();
let correction = font::italic_correction(&font, slanted);
assert!(correction > 0.0, "f に張り出しがありません");
let placed = build(&font, "f(x)", false);
let pieces = parts(&placed);
let room = pieces[1].x - pieces[0].layout.width;
assert!(close(room, correction), "張り出しぶんが空いていません: {room}");
// 立体の字は張り出しが小さいので、空きもわずかになる
let placed = build(&font, r"\mathrm{f}(x)", false);
let upright = parts(&placed);
let narrow = upright[1].x - upright[0].layout.width;
assert!(narrow < room, "立体のほうが広く空いています: {narrow}");
// 括弧が伸びていても同じように空く
let placed = build(&font, r"P\left( x \right)", false);
let pieces = parts(&placed);
let capital = font::glyph_of(&font, '\u{1d443}').unwrap();
let slant = font::italic_correction(&font, capital);
assert!(slant > 0.0, "P に張り出しがありません");
assert!(close(pieces[1].x - pieces[0].layout.width, slant));
}
#[test]
fn a_subscript_tucks_under_a_slanted_base() {
let font = sample();
let placed = build(&font, r"\int_0^1", true);
let pieces = parts(first(&placed));
assert_eq!(pieces.len(), 3, "積分と添字 2 つになっていません");
let base = &pieces[0];
let slant = font::italic_correction(&font, deep_glyph(&base.layout));
assert!(slant > 0.0, "積分に斜体の張り出しがありません");
let reach = base.layout.height + base.layout.depth;
let room = (SCRIPT_GAP * reach).max(SCRIPT_GAP_MIN);
assert!(close(pieces[1].x, base.layout.width + room), "上付きの位置がずれています");
assert!(close(pieces[2].x, base.layout.width + room - slant), "下付きが左へ寄っていません");
assert!(room > 0.05, "背の高い記号に空きが入っていません: {room}");
}
#[test]
fn a_low_base_still_keeps_a_little_room() {
let font = sample();
let placed = build(&font, "x^2", false);
let pieces = parts(first(&placed));
let room = pieces[1].x - pieces[0].layout.width;
assert!(close(room, SCRIPT_GAP_MIN), "下限ぶんの空きがありません: {room}");
}
#[test]
fn an_upright_base_moves_neither_script() {
let font = sample();
// 数字は立体なので張り出しがなく、上付きと下付きが同じ位置に来る
let placed = build(&font, "2_1^2", false);
let pieces = parts(first(&placed));
let slant = font::italic_correction(&font, deep_glyph(&pieces[0].layout));
assert_eq!(slant, 0.0);
assert!(close(pieces[1].x, pieces[2].x), "立体の字で添字がずれています");
}
#[test]
fn scripts_shrink_but_stop_at_a_floor() {
let font = sample();
let floor = font::constant(&font).script_script_percent;
fn smallest(placed: &Layout) -> f64 {
match &placed.content {
Content::Glyph {size, ..} => *size,
Content::Group(children) => children
.iter()
.map(|child| smallest(&child.layout))
.fold(f64::INFINITY, f64::min),
Content::Rule => f64::INFINITY,
}
}
let placed = build(&font, "x^{y^{z^{w}}}", false);
assert!(close(smallest(&placed), floor));
}
#[test]
fn matrix_columns_line_up() {
let font = sample();
let source = r"\begin{pmatrix} a & bb \\ ccc & d \end{pmatrix}";
let placed = build(&font, source, false);
let block = &parts(first(&placed))[1].layout;
let cells = parts(block);
assert_eq!(cells.len(), 4);
let middle = |cell: &Placed| cell.x + cell.layout.width / 2.0;
assert!(close(middle(&cells[0]), middle(&cells[2])));
assert!(close(middle(&cells[1]), middle(&cells[3])));
assert!(cells[1].x > cells[0].x);
}
#[test]
fn a_matrix_keeps_room_at_its_edges() {
let font = sample();
let source = r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}";
let placed = build(&font, source, false);
let block = &parts(first(&placed))[1].layout;
let cells = parts(block);
let leftmost = cells.iter().map(|cell| cell.x).fold(f64::INFINITY, f64::min);
let rightmost = cells
.iter()
.map(|cell| cell.x + cell.layout.width)
.fold(0.0, f64::max);
assert!(close(leftmost, MATRIX_ROOM), "左端の空き: {leftmost}");
assert!(close(block.width - rightmost, MATRIX_ROOM), "右端の空きが足りません");
}
#[test]
fn a_side_without_a_bracket_gets_no_room() {
let font = sample();
// cases は左にだけ括弧が付く
let source = r"\begin{cases} 1 & x > 0 \\ 0 & x \leq 0 \end{cases}";
let placed = build(&font, source, false);
let block = &parts(first(&placed))[1].layout;
let cells = parts(block);
let rightmost = cells
.iter()
.map(|cell| cell.x + cell.layout.width)
.fold(0.0, f64::max);
assert!(close(block.width - rightmost, 0.0), "右端に空きが入っています");
}
#[test]
fn horizontal_lines_span_the_whole_block() {
let font = sample();
let source = r"\begin{array}{cc} \hline a & b \end{array}";
let placed = build(&font, source, false);
let block = &parts(first(&placed))[0].layout;
let bar = parts(block)
.iter()
.find(|part| part.layout.content == Content::Rule)
.expect("横線がありません");
assert!(close(bar.layout.width, block.width));
}
#[test]
fn negative_space_pulls_back() {
let font = sample();
let plain = build(&font, "ab", false).width;
let pulled = build(&font, r"a \! b", false).width;
assert!(pulled < plain);
}
#[test]
fn a_mark_keeps_off_the_body() {
let font = sample();
let placed = build(&font, r"\hat{A}", false);
let pieces = parts(first(&placed));
let body = &pieces[0];
let mark = &pieces[1];
// 印の墨の下端は、中身の上端よりこれだけ上にある
let room = -(mark.y + mark.layout.depth) - body.layout.height;
assert!(room >= MARK_GAP - 0.0005, "印が字に載っています: {room}");
}
#[test]
fn a_line_keeps_off_the_body() {
let font = sample();
let placed = build(&font, r"\overline{A}", false);
let pieces = parts(first(&placed));
let body = &pieces[0];
let bar = &pieces[1];
let room = -bar.y - body.layout.height;
let least = font::constant(&font).overbar_vertical_gap + MARK_GAP;
assert!(room >= least - 0.0005, "線が字に近すぎます: {room}");
}
#[test]
fn a_mark_sits_over_the_middle_of_a_long_body() {
let font = sample();
let placed = build(&font, r"\overrightarrow{AB}", false);
let pieces = parts(first(&placed));
let body = &pieces[0];
let mark = &pieces[1];
let middle = |part: &Placed| part.x + part.layout.width / 2.0;
assert!((middle(body) - middle(mark)).abs() < 0.05, "印が中身の真ん中にありません");
}
#[test]
fn a_mark_wider_than_its_body_stays_over_the_middle() {
let font = sample();
let placed = build(&font, r"\overbrace{a}", false);
let pieces = parts(first(&placed));
let body = &pieces[0];
let mark = &pieces[1];
let middle = |part: &Placed| part.x + part.layout.width / 2.0;
assert!(mark.layout.width > body.layout.width, "印が中身より広くなっていません");
assert!(body.x > 0.0, "中身が左端に寄ったままです");
assert!((middle(body) - middle(mark)).abs() < 0.05, "広い印が中身からずれています");
}
#[test]
fn a_wide_accent_stretches_over_its_body() {
let font = sample();
let narrow = build(&font, r"\widehat{x}", false);
let wide = build(&font, r"\widehat{xyz}", false);
let narrow_mark = glyph_id(&parts(first(&narrow))[1].layout);
let wide_mark = glyph_id(&parts(first(&wide))[1].layout);
assert_ne!(narrow_mark, wide_mark, "印が中身の幅に合わせて替わっていません");
}
#[test]
fn a_mark_without_a_long_enough_variant_is_built_from_parts() {
let font = sample();
let placed = build(&font, r"\overrightarrow{AB}", false);
let pieces = parts(first(&placed));
let body = &pieces[0];
let mark = &pieces[1];
let Content::Group(_) = &mark.layout.content else {
panic!("部品を並べていません")
};
// 中身の幅に届いている
assert!(mark.layout.width >= body.layout.width - 0.01, "矢印が中身より短いままです");
// 中身の上に乗っている
let room = -(mark.y + mark.layout.depth) - body.layout.height;
assert!((0.0..0.3).contains(&room), "矢印の高さが合っていません: {room}");
}
#[test]
fn the_shape_of_the_font_changes_the_layout() {
let font = sample();
let placed = build(&font, r"\frac{a}{b}", false);
let other = "/System/Library/Fonts/Supplemental/Times New Roman.ttf";
let Ok(data) = std::fs::read(other) else {
return;
};
let fallback = font::load(data).unwrap();
let node = parse(r"\frac{a}{b}").unwrap();
let same = layout(&node, &fallback, 1.0, Style::Auto, false);
assert_ne!(placed.width, same.width, "書体を替えても寸法が変わっていません");
}
}