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
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=4 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gfxTextRun.h"
#include "gfxGlyphExtents.h"
#include "gfxHarfBuzzShaper.h"
#include "gfxPlatformFontList.h"
#include "gfxUserFontSet.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/Sprintf.h"
#include "gfxContext.h"
#include "gfxFontConstants.h"
#include "gfxFontMissingGlyphs.h"
#include "gfxScriptItemizer.h"
#include "nsUnicodeProperties.h"
#include "nsStyleConsts.h"
#include "nsStyleUtil.h"
#include "mozilla/Likely.h"
#include "gfx2DGlue.h"
#include "mozilla/gfx/Logging.h" // for gfxCriticalError
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "SharedFontList-impl.h"
#include "TextDrawTarget.h"
#include <unicode/unorm2.h>
#ifdef XP_WIN
# include "gfxWindowsPlatform.h"
#endif
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;
using mozilla::services::GetObserverService;
static const char16_t kEllipsisChar[] = {0x2026, 0x0};
static const char16_t kASCIIPeriodsChar[] = {'.', '.', '.', 0x0};
#ifdef DEBUG_roc
# define DEBUG_TEXT_RUN_STORAGE_METRICS
#endif
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
extern uint32_t gTextRunStorageHighWaterMark;
extern uint32_t gTextRunStorage;
extern uint32_t gFontCount;
extern uint32_t gGlyphExtentsCount;
extern uint32_t gGlyphExtentsWidthsTotalSize;
extern uint32_t gGlyphExtentsSetupEagerSimple;
extern uint32_t gGlyphExtentsSetupEagerTight;
extern uint32_t gGlyphExtentsSetupLazyTight;
extern uint32_t gGlyphExtentsSetupFallBackToTight;
#endif
bool gfxTextRun::GlyphRunIterator::NextRun() {
int32_t glyphRunCount;
if (mTextRun->mHasGlyphRunArray) {
glyphRunCount = mTextRun->mGlyphRunArray.Length();
if (mNextIndex >= glyphRunCount || mNextIndex < 0) {
return false;
}
mGlyphRun = &mTextRun->mGlyphRunArray[mNextIndex];
} else {
if (mNextIndex != 0 || !mTextRun->mSingleGlyphRun.mFont) {
return false;
}
glyphRunCount = 1;
mGlyphRun = &mTextRun->mSingleGlyphRun;
}
if (mGlyphRun->mCharacterOffset >= mEndOffset) {
return false;
}
uint32_t glyphRunEndOffset =
mNextIndex + 1 < (int32_t)glyphRunCount
? mTextRun->mGlyphRunArray[mNextIndex + 1].mCharacterOffset
: mTextRun->GetLength();
if (glyphRunEndOffset <= mStartOffset) {
return false;
}
mStringEnd = std::min(mEndOffset, glyphRunEndOffset);
mStringStart = std::max(mStartOffset, mGlyphRun->mCharacterOffset);
mNextIndex += mDirection;
return true;
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
static void AccountStorageForTextRun(gfxTextRun* aTextRun, int32_t aSign) {
// Ignores detailed glyphs... we don't know when those have been constructed
// Also ignores gfxSkipChars dynamic storage (which won't be anything
// for preformatted text)
// Also ignores GlyphRun array, again because it hasn't been constructed
// by the time this gets called. If there's only one glyphrun that's stored
// directly in the textrun anyway so no additional overhead.
uint32_t length = aTextRun->GetLength();
int32_t bytes = length * sizeof(gfxTextRun::CompressedGlyph);
bytes += sizeof(gfxTextRun);
gTextRunStorage += bytes * aSign;
gTextRunStorageHighWaterMark =
std::max(gTextRunStorageHighWaterMark, gTextRunStorage);
}
#endif
static bool NeedsGlyphExtents(gfxTextRun* aTextRun) {
if (aTextRun->GetFlags() & gfx::ShapedTextFlags::TEXT_NEED_BOUNDING_BOX)
return true;
uint32_t numRuns;
const gfxTextRun::GlyphRun* glyphRuns = aTextRun->GetGlyphRuns(&numRuns);
for (uint32_t i = 0; i < numRuns; ++i) {
if (glyphRuns[i].mFont->GetFontEntry()->IsUserFont()) return true;
}
return false;
}
// Helper for textRun creation to preallocate storage for glyph records;
// this function returns a pointer to the newly-allocated glyph storage.
// Returns nullptr if allocation fails.
void* gfxTextRun::AllocateStorageForTextRun(size_t aSize, uint32_t aLength) {
// Allocate the storage we need, returning nullptr on failure rather than
// throwing an exception (because web content can create huge runs).
void* storage = malloc(aSize + aLength * sizeof(CompressedGlyph));
if (!storage) {
NS_WARNING("failed to allocate storage for text run!");
return nullptr;
}
// Initialize the glyph storage (beyond aSize) to zero
memset(reinterpret_cast<char*>(storage) + aSize, 0,
aLength * sizeof(CompressedGlyph));
return storage;
}
already_AddRefed<gfxTextRun> gfxTextRun::Create(
const gfxTextRunFactory::Parameters* aParams, uint32_t aLength,
gfxFontGroup* aFontGroup, gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2) {
void* storage = AllocateStorageForTextRun(sizeof(gfxTextRun), aLength);
if (!storage) {
return nullptr;
}
RefPtr<gfxTextRun> result =
new (storage) gfxTextRun(aParams, aLength, aFontGroup, aFlags, aFlags2);
return result.forget();
}
gfxTextRun::gfxTextRun(const gfxTextRunFactory::Parameters* aParams,
uint32_t aLength, gfxFontGroup* aFontGroup,
gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2)
: gfxShapedText(aLength, aFlags, aParams->mAppUnitsPerDevUnit),
mSingleGlyphRun(),
mUserData(aParams->mUserData),
mFontGroup(aFontGroup),
mFlags2(aFlags2),
mReleasedFontGroup(false),
mReleasedFontGroupSkippedDrawing(false),
mHasGlyphRunArray(false),
mShapingState(eShapingState_Normal) {
NS_ASSERTION(mAppUnitsPerDevUnit > 0, "Invalid app unit scale");
NS_ADDREF(mFontGroup);
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = aFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunConst++;
}
#endif
mCharacterGlyphs = reinterpret_cast<CompressedGlyph*>(this + 1);
if (aParams->mSkipChars) {
mSkipChars.TakeFrom(aParams->mSkipChars);
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, 1);
#endif
mDontSkipDrawing =
!!(aFlags2 & nsTextFrameUtils::Flags::DontSkipDrawingForPendingUserFonts);
}
gfxTextRun::~gfxTextRun() {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, -1);
#endif
#ifdef DEBUG
// Make it easy to detect a dead text run
mFlags = ~gfx::ShapedTextFlags();
mFlags2 = ~nsTextFrameUtils::Flags();
#endif
if (mHasGlyphRunArray) {
mGlyphRunArray.~nsTArray<GlyphRun>();
} else {
mSingleGlyphRun.mFont = nullptr;
}
// The cached ellipsis textrun (if any) in a fontgroup will have already
// been told to release its reference to the group, so we mustn't do that
// again here.
if (!mReleasedFontGroup) {
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = mFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunDestr++;
}
#endif
NS_RELEASE(mFontGroup);
}
}
void gfxTextRun::ReleaseFontGroup() {
NS_ASSERTION(!mReleasedFontGroup, "doubly released!");
// After dropping our reference to the font group, we'll no longer be able
// to get up-to-date results for ShouldSkipDrawing(). Store the current
// value in mReleasedFontGroupSkippedDrawing.
//
// (It doesn't actually matter that we can't get up-to-date results for
// ShouldSkipDrawing(), since the only text runs that we call
// ReleaseFontGroup() for are ellipsis text runs, and we ask the font
// group for a new ellipsis text run each time we want to draw one,
// and ensure that the cached one is cleared in ClearCachedData() when
// font loading status changes.)
mReleasedFontGroupSkippedDrawing = mFontGroup->ShouldSkipDrawing();
NS_RELEASE(mFontGroup);
mReleasedFontGroup = true;
}
bool gfxTextRun::SetPotentialLineBreaks(Range aRange,
const uint8_t* aBreakBefore) {
NS_ASSERTION(aRange.end <= GetLength(), "Overflow");
uint32_t changed = 0;
CompressedGlyph* cg = mCharacterGlyphs + aRange.start;
const CompressedGlyph* const end = cg + aRange.Length();
while (cg < end) {
uint8_t canBreak = *aBreakBefore++;
if (canBreak && !cg->IsClusterStart()) {
// XXX If we replace the line-breaker with one based more closely
// on UAX#14 (e.g. using ICU), this may not be needed any more.
// Avoid possible breaks inside a cluster, EXCEPT when the previous
// character was a space (compare UAX#14 rules LB9, LB10).
if (cg == mCharacterGlyphs || !(cg - 1)->CharIsSpace()) {
canBreak = CompressedGlyph::FLAG_BREAK_TYPE_NONE;
}
}
changed |= cg->SetCanBreakBefore(canBreak);
++cg;
}
return changed != 0;
}
gfxTextRun::LigatureData gfxTextRun::ComputeLigatureData(
Range aPartRange, PropertyProvider* aProvider) const {
NS_ASSERTION(aPartRange.start < aPartRange.end,
"Computing ligature data for empty range");
NS_ASSERTION(aPartRange.end <= GetLength(), "Character length overflow");
LigatureData result;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
uint32_t i;
for (i = aPartRange.start; !charGlyphs[i].IsLigatureGroupStart(); --i) {
NS_ASSERTION(i > 0, "Ligature at the start of the run??");
}
result.mRange.start = i;
for (i = aPartRange.start + 1;
i < GetLength() && !charGlyphs[i].IsLigatureGroupStart(); ++i) {
}
result.mRange.end = i;
int32_t ligatureWidth = GetAdvanceForGlyphs(result.mRange);
// Count the number of started clusters we have seen
uint32_t totalClusterCount = 0;
uint32_t partClusterIndex = 0;
uint32_t partClusterCount = 0;
for (i = result.mRange.start; i < result.mRange.end; ++i) {
// Treat the first character of the ligature as the start of a
// cluster for our purposes of allocating ligature width to its
// characters.
if (i == result.mRange.start || charGlyphs[i].IsClusterStart()) {
++totalClusterCount;
if (i < aPartRange.start) {
++partClusterIndex;
} else if (i < aPartRange.end) {
++partClusterCount;
}
}
}
NS_ASSERTION(totalClusterCount > 0, "Ligature involving no clusters??");
result.mPartAdvance = partClusterIndex * (ligatureWidth / totalClusterCount);
result.mPartWidth = partClusterCount * (ligatureWidth / totalClusterCount);
// Any rounding errors are apportioned to the final part of the ligature,
// so that measuring all parts of a ligature and summing them is equal to
// the ligature width.
if (aPartRange.end == result.mRange.end) {
gfxFloat allParts = totalClusterCount * (ligatureWidth / totalClusterCount);
result.mPartWidth += ligatureWidth - allParts;
}
if (partClusterCount == 0) {
// nothing to draw
result.mClipBeforePart = result.mClipAfterPart = true;
} else {
// Determine whether we should clip before or after this part when
// drawing its slice of the ligature.
// We need to clip before the part if any cluster is drawn before
// this part.
result.mClipBeforePart = partClusterIndex > 0;
// We need to clip after the part if any cluster is drawn after
// this part.
result.mClipAfterPart =
partClusterIndex + partClusterCount < totalClusterCount;
}
if (aProvider && (mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
gfxFont::Spacing spacing;
if (aPartRange.start == result.mRange.start) {
aProvider->GetSpacing(Range(aPartRange.start, aPartRange.start + 1),
&spacing);
result.mPartWidth += spacing.mBefore;
}
if (aPartRange.end == result.mRange.end) {
aProvider->GetSpacing(Range(aPartRange.end - 1, aPartRange.end),
&spacing);
result.mPartWidth += spacing.mAfter;
}
}
return result;
}
gfxFloat gfxTextRun::ComputePartialLigatureWidth(
Range aPartRange, PropertyProvider* aProvider) const {
if (aPartRange.start >= aPartRange.end) return 0;
LigatureData data = ComputeLigatureData(aPartRange, aProvider);
return data.mPartWidth;
}
int32_t gfxTextRun::GetAdvanceForGlyphs(Range aRange) const {
int32_t advance = 0;
for (auto i = aRange.start; i < aRange.end; ++i) {
advance += GetAdvanceForGlyph(i);
}
return advance;
}
static void GetAdjustedSpacing(
const gfxTextRun* aTextRun, gfxTextRun::Range aRange,
gfxTextRun::PropertyProvider* aProvider,
gfxTextRun::PropertyProvider::Spacing* aSpacing) {
if (aRange.start >= aRange.end) return;
aProvider->GetSpacing(aRange, aSpacing);
#ifdef DEBUG
// Check to see if we have spacing inside ligatures
const gfxTextRun::CompressedGlyph* charGlyphs =
aTextRun->GetCharacterGlyphs();
uint32_t i;
for (i = aRange.start; i < aRange.end; ++i) {
if (!charGlyphs[i].IsLigatureGroupStart()) {
NS_ASSERTION(i == aRange.start || aSpacing[i - aRange.start].mBefore == 0,
"Before-spacing inside a ligature!");
NS_ASSERTION(
i - 1 <= aRange.start || aSpacing[i - 1 - aRange.start].mAfter == 0,
"After-spacing inside a ligature!");
}
}
#endif
}
bool gfxTextRun::GetAdjustedSpacingArray(
Range aRange, PropertyProvider* aProvider, Range aSpacingRange,
nsTArray<PropertyProvider::Spacing>* aSpacing) const {
if (!aProvider || !(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
return false;
}
if (!aSpacing->AppendElements(aRange.Length(), fallible)) {
return false;
}
auto spacingOffset = aSpacingRange.start - aRange.start;
memset(aSpacing->Elements(), 0, sizeof(gfxFont::Spacing) * spacingOffset);
GetAdjustedSpacing(this, aSpacingRange, aProvider,
aSpacing->Elements() + spacingOffset);
memset(aSpacing->Elements() + aSpacingRange.end - aRange.start, 0,
sizeof(gfxFont::Spacing) * (aRange.end - aSpacingRange.end));
return true;
}
void gfxTextRun::ShrinkToLigatureBoundaries(Range* aRange) const {
if (aRange->start >= aRange->end) return;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
while (aRange->start < aRange->end &&
!charGlyphs[aRange->start].IsLigatureGroupStart()) {
++aRange->start;
}
if (aRange->end < GetLength()) {
while (aRange->end > aRange->start &&
!charGlyphs[aRange->end].IsLigatureGroupStart()) {
--aRange->end;
}
}
}
void gfxTextRun::DrawGlyphs(gfxFont* aFont, Range aRange, gfx::Point* aPt,
PropertyProvider* aProvider, Range aSpacingRange,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
aParams.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
aFont->Draw(this, aRange.start, aRange.end, aPt, aParams, aOrientation);
}
static void ClipPartialLigature(const gfxTextRun* aTextRun, gfxFloat* aStart,
gfxFloat* aEnd, gfxFloat aOrigin,
gfxTextRun::LigatureData* aLigature) {
if (aLigature->mClipBeforePart) {
if (aTextRun->IsRightToLeft()) {
*aEnd = std::min(*aEnd, aOrigin);
} else {
*aStart = std::max(*aStart, aOrigin);
}
}
if (aLigature->mClipAfterPart) {
gfxFloat endEdge =
aOrigin + aTextRun->GetDirection() * aLigature->mPartWidth;
if (aTextRun->IsRightToLeft()) {
*aStart = std::max(*aStart, endEdge);
} else {
*aEnd = std::min(*aEnd, endEdge);
}
}
}
void gfxTextRun::DrawPartialLigature(gfxFont* aFont, Range aRange,
gfx::Point* aPt,
PropertyProvider* aProvider,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
if (aRange.start >= aRange.end) {
return;
}
// Draw partial ligature. We hack this by clipping the ligature.
LigatureData data = ComputeLigatureData(aRange, aProvider);
gfxRect clipExtents = aParams.context->GetClipExtents();
gfxFloat start, end;
if (aParams.isVerticalRun) {
start = clipExtents.Y() * mAppUnitsPerDevUnit;
end = clipExtents.YMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->y, &data);
} else {
start = clipExtents.X() * mAppUnitsPerDevUnit;
end = clipExtents.XMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->x, &data);
}
{
// use division here to ensure that when the rect is aligned on multiples
// of mAppUnitsPerDevUnit, we clip to true device unit boundaries.
// Also, make sure we snap the rectangle to device pixels.
Rect clipRect =
aParams.isVerticalRun
? Rect(clipExtents.X(), start / mAppUnitsPerDevUnit,
clipExtents.Width(), (end - start) / mAppUnitsPerDevUnit)
: Rect(start / mAppUnitsPerDevUnit, clipExtents.Y(),
(end - start) / mAppUnitsPerDevUnit, clipExtents.Height());
MaybeSnapToDevicePixels(clipRect, *aParams.dt, true);
aParams.context->Clip(clipRect);
}
gfx::Point pt;
if (aParams.isVerticalRun) {
pt = Point(aPt->x, aPt->y - aParams.direction * data.mPartAdvance);
} else {
pt = Point(aPt->x - aParams.direction * data.mPartAdvance, aPt->y);
}
DrawGlyphs(aFont, data.mRange, &pt, aProvider, aRange, aParams, aOrientation);
aParams.context->PopClip();
if (aParams.isVerticalRun) {
aPt->y += aParams.direction * data.mPartWidth;
} else {
aPt->x += aParams.direction * data.mPartWidth;
}
}
// Returns true if the font has synthetic bolding enabled,
// or is a color font (COLR/SVG/sbix/CBDT), false otherwise. This is used to
// check whether the text run needs to be explicitly composited in order to
// support opacity.
static bool HasSyntheticBoldOrColor(gfxFont* aFont) {
if (aFont->IsSyntheticBold()) {
return true;
}
gfxFontEntry* fe = aFont->GetFontEntry();
if (fe->TryGetSVGData(aFont) || fe->TryGetColorGlyphs()) {
return true;
}
#if defined(XP_MACOSX) // sbix fonts only supported via Core Text
if (fe->HasFontTable(TRUETYPE_TAG('s', 'b', 'i', 'x'))) {
return true;
}
#endif
return false;
}
// helper class for double-buffering drawing with non-opaque color
struct MOZ_STACK_CLASS BufferAlphaColor {
explicit BufferAlphaColor(gfxContext* aContext) : mContext(aContext) {}
~BufferAlphaColor() = default;
void PushSolidColor(const gfxRect& aBounds, const DeviceColor& aAlphaColor,
uint32_t appsPerDevUnit) {
mContext->Save();
mContext->SnappedClip(gfxRect(
aBounds.X() / appsPerDevUnit, aBounds.Y() / appsPerDevUnit,
aBounds.Width() / appsPerDevUnit, aBounds.Height() / appsPerDevUnit));
mContext->SetDeviceColor(
DeviceColor(aAlphaColor.r, aAlphaColor.g, aAlphaColor.b));
mContext->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, aAlphaColor.a);
}
void PopAlpha() {
// pop the text, using the color alpha as the opacity
mContext->PopGroupAndBlend();
mContext->Restore();
}
gfxContext* mContext;
};
void gfxTextRun::Draw(const Range aRange, const gfx::Point aPt,
const DrawParams& aParams) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH ||
!(aParams.drawMode & DrawMode::GLYPH_PATH),
"GLYPH_PATH cannot be used with GLYPH_FILL, GLYPH_STROKE or "
"GLYPH_STROKE_UNDERNEATH");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH || !aParams.callbacks,
"callback must not be specified unless using GLYPH_PATH");
bool skipDrawing =
!mDontSkipDrawing && (mFontGroup ? mFontGroup->ShouldSkipDrawing()
: mReleasedFontGroupSkippedDrawing);
if (aParams.drawMode & DrawMode::GLYPH_FILL) {
DeviceColor currentColor;
if (aParams.context->GetDeviceColor(currentColor) && currentColor.a == 0 &&
!aParams.context->GetTextDrawer()) {
skipDrawing = true;
}
}
gfxFloat direction = GetDirection();
if (skipDrawing) {
// We don't need to draw anything;
// but if the caller wants advance width, we need to compute it here
if (aParams.advanceWidth) {
gfxTextRun::Metrics metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
*aParams.advanceWidth = metrics.mAdvanceWidth * direction;
}
// return without drawing
return;
}
// synthetic bolding draws glyphs twice ==> colors with opacity won't draw
// correctly unless first drawn without alpha
BufferAlphaColor syntheticBoldBuffer(aParams.context);
DeviceColor currentColor;
bool mayNeedBuffering =
aParams.drawMode & DrawMode::GLYPH_FILL &&
aParams.context->HasNonOpaqueNonTransparentColor(currentColor) &&
!aParams.context->GetTextDrawer();
// If we need to double-buffer, we'll need to measure the text first to
// get the bounds of the area of interest. Ideally we'd do that just for
// the specific glyph run(s) that need buffering, but because of bug
// 1612610 we currently use the extent of the entire range even when
// just buffering a subrange. So we'll measure the full range once and
// keep the metrics on hand for any subsequent subranges.
gfxTextRun::Metrics metrics;
bool gotMetrics = false;
// Set up parameters that will be constant across all glyph runs we need
// to draw, regardless of the font used.
TextRunDrawParams params;
params.context = aParams.context;
params.devPerApp = 1.0 / double(GetAppUnitsPerDevUnit());
params.isVerticalRun = IsVertical();
params.isRTL = IsRightToLeft();
params.direction = direction;
params.strokeOpts = aParams.strokeOpts;
params.textStrokeColor = aParams.textStrokeColor;
params.textStrokePattern = aParams.textStrokePattern;
params.drawOpts = aParams.drawOpts;
params.drawMode = aParams.drawMode;
params.callbacks = aParams.callbacks;
params.runContextPaint = aParams.contextPaint;
params.paintSVGGlyphs =
!aParams.callbacks || aParams.callbacks->mShouldPaintSVGGlyphs;
params.dt = aParams.context->GetDrawTarget();
GlyphRunIterator iter(this, aRange);
gfxFloat advance = 0.0;
gfx::Point pt = aPt;
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
Range runRange(iter.GetStringStart(), iter.GetStringEnd());
bool needToRestore = false;
if (mayNeedBuffering && HasSyntheticBoldOrColor(font)) {
needToRestore = true;
if (!gotMetrics) {
// Measure text; use the bounding box to determine the area we need
// to buffer. We measure the entire range, rather than just the glyph
// run that we're actually handling, because of bug 1612610: if the
// bounding box passed to PushSolidColor does not intersect the
// drawTarget's current clip, the skia backend fails to clip properly.
// This means we may use a larger buffer than actually needed, but is
// otherwise harmless.
metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
if (IsRightToLeft()) {
metrics.mBoundingBox.MoveBy(
gfxPoint(aPt.x - metrics.mAdvanceWidth, aPt.y));
} else {
metrics.mBoundingBox.MoveBy(gfxPoint(aPt.x, aPt.y));
}
gotMetrics = true;
}
syntheticBoldBuffer.PushSolidColor(metrics.mBoundingBox, currentColor,
GetAppUnitsPerDevUnit());
}
Range ligatureRange(runRange);
ShrinkToLigatureBoundaries(&ligatureRange);
bool drawPartial =
(aParams.drawMode & (DrawMode::GLYPH_FILL | DrawMode::GLYPH_STROKE)) ||
(aParams.drawMode == DrawMode::GLYPH_PATH && aParams.callbacks);
gfx::Point origPt = pt;
if (drawPartial) {
DrawPartialLigature(font, Range(runRange.start, ligatureRange.start), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
DrawGlyphs(font, ligatureRange, &pt, aParams.provider, ligatureRange,
params, iter.GetGlyphRun()->mOrientation);
if (drawPartial) {
DrawPartialLigature(font, Range(ligatureRange.end, runRange.end), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
if (params.isVerticalRun) {
advance += (pt.y - origPt.y) * params.direction;
} else {
advance += (pt.x - origPt.x) * params.direction;
}
// composite result when synthetic bolding used
if (needToRestore) {
syntheticBoldBuffer.PopAlpha();
}
}
if (aParams.advanceWidth) {
*aParams.advanceWidth = advance;
}
}
// This method is mostly parallel to Draw().
void gfxTextRun::DrawEmphasisMarks(gfxContext* aContext, gfxTextRun* aMark,
gfxFloat aMarkAdvance, gfx::Point aPt,
Range aRange,
PropertyProvider* aProvider) const {
MOZ_ASSERT(aRange.end <= GetLength());
EmphasisMarkDrawParams params;
params.context = aContext;
params.mark = aMark;
params.advance = aMarkAdvance;
params.direction = GetDirection();
params.isVertical = IsVertical();
float& inlineCoord = params.isVertical ? aPt.y : aPt.x;
float direction = params.direction;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
inlineCoord +=
direction * ComputePartialLigatureWidth(
Range(start, ligatureRange.start), aProvider);
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing = GetAdjustedSpacingArray(ligatureRange, aProvider,
ligatureRange, &spacingBuffer);
params.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
font->DrawEmphasisMarks(this, &aPt, ligatureRange.start,
ligatureRange.Length(), params);
inlineCoord += direction * ComputePartialLigatureWidth(
Range(ligatureRange.end, end), aProvider);
}
}
void gfxTextRun::AccumulateMetricsForRun(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
Range aSpacingRange, gfx::ShapedTextFlags aOrientation,
Metrics* aMetrics) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
Metrics metrics = aFont->Measure(
this, aRange.start, aRange.end, aBoundingBoxType, aRefDrawTarget,
haveSpacing ? spacingBuffer.Elements() : nullptr, aOrientation);
aMetrics->CombineWith(metrics, IsRightToLeft());
}
void gfxTextRun::AccumulatePartialLigatureMetrics(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
gfx::ShapedTextFlags aOrientation, Metrics* aMetrics) const {
if (aRange.start >= aRange.end) return;
// Measure partial ligature. We hack this by clipping the metrics in the
// same way we clip the drawing.
LigatureData data = ComputeLigatureData(aRange, aProvider);
// First measure the complete ligature
Metrics metrics;
AccumulateMetricsForRun(aFont, data.mRange, aBoundingBoxType, aRefDrawTarget,
aProvider, aRange, aOrientation, &metrics);
// Clip the bounding box to the ligature part
gfxFloat bboxLeft = metrics.mBoundingBox.X();
gfxFloat bboxRight = metrics.mBoundingBox.XMost();
// Where we are going to start "drawing" relative to our left baseline origin
gfxFloat origin =
IsRightToLeft() ? metrics.mAdvanceWidth - data.mPartAdvance : 0;
ClipPartialLigature(this, &bboxLeft, &bboxRight, origin, &data);
metrics.mBoundingBox.SetBoxX(bboxLeft, bboxRight);
// mBoundingBox is now relative to the left baseline origin for the entire
// ligature. Shift it left.
metrics.mBoundingBox.MoveByX(
-(IsRightToLeft()
? metrics.mAdvanceWidth - (data.mPartAdvance + data.mPartWidth)
: data.mPartAdvance));
metrics.mAdvanceWidth = data.mPartWidth;
aMetrics->CombineWith(metrics, IsRightToLeft());
}
gfxTextRun::Metrics gfxTextRun::MeasureText(
Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
Metrics accumulatedMetrics;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
AccumulatePartialLigatureMetrics(
font, Range(start, ligatureRange.start), aBoundingBoxType,
aRefDrawTarget, aProvider, iter.GetGlyphRun()->mOrientation,
&accumulatedMetrics);
// XXX This sucks. We have to get glyph extents just so we can detect
// glyphs outside the font box, even when aBoundingBoxType is LOOSE,
// even though in almost all cases we could get correct results just
// by getting some ascent/descent from the font and using our stored
// advance widths.
AccumulateMetricsForRun(
font, ligatureRange, aBoundingBoxType, aRefDrawTarget, aProvider,
ligatureRange, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
AccumulatePartialLigatureMetrics(
font, Range(ligatureRange.end, end), aBoundingBoxType, aRefDrawTarget,
aProvider, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
}
return accumulatedMetrics;
}
#define MEASUREMENT_BUFFER_SIZE 100
void gfxTextRun::ClassifyAutoHyphenations(uint32_t aStart, Range aRange,
nsTArray<HyphenType>& aHyphenBuffer,
HyphenationState* aWordState) {
MOZ_ASSERT(
aRange.end - aStart <= aHyphenBuffer.Length() && aRange.start >= aStart,
"Range out of bounds");
MOZ_ASSERT(aWordState->mostRecentBoundary >= aStart,
"Unexpected aMostRecentWordBoundary!!");
uint32_t start =
std::min<uint32_t>(aRange.start, aWordState->mostRecentBoundary);
for (uint32_t i = start; i < aRange.end; ++i) {
if (aHyphenBuffer[i - aStart] == HyphenType::Explicit &&
!aWordState->hasExplicitHyphen) {
aWordState->hasExplicitHyphen = true;
}
if (!aWordState->hasManualHyphen &&
(aHyphenBuffer[i - aStart] == HyphenType::Soft ||
aHyphenBuffer[i - aStart] == HyphenType::Explicit)) {
aWordState->hasManualHyphen = true;
// This is the first manual hyphen in the current word. We can only
// know if the current word has a manual hyphen until now. So, we need
// to run a sub loop to update the auto hyphens between the start of
// the current word and this manual hyphen.
if (aWordState->hasAutoHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j < i; j++) {
if (aHyphenBuffer[j - aStart] ==
HyphenType::AutoWithoutManualInSameWord) {
aHyphenBuffer[j - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
}
}
if (aHyphenBuffer[i - aStart] == HyphenType::AutoWithoutManualInSameWord) {
if (!aWordState->hasAutoHyphen) {
aWordState->hasAutoHyphen = true;
}
if (aWordState->hasManualHyphen) {
aHyphenBuffer[i - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
// If we're at the word boundary, clear/reset couple states.
if (mCharacterGlyphs[i].CharIsSpace() || mCharacterGlyphs[i].CharIsTab() ||
mCharacterGlyphs[i].CharIsNewline() ||
// Since we will not have a boundary in the end of the string, let's
// call the end of the string a special case for word boundary.
i == GetLength() - 1) {
// We can only get to know whether we should raise/clear an explicit
// manual hyphen until we get to the end of a word, because this depends
// on whether there exists at least one auto hyphen in the same word.
if (!aWordState->hasAutoHyphen && aWordState->hasExplicitHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j <= i; j++) {
if (aHyphenBuffer[j - aStart] == HyphenType::Explicit) {
aHyphenBuffer[j - aStart] = HyphenType::None;
}
}
}
aWordState->mostRecentBoundary = i;
aWordState->hasManualHyphen = false;
aWordState->hasAutoHyphen = false;
aWordState->hasExplicitHyphen = false;
}
}
}
uint32_t gfxTextRun::BreakAndMeasureText(
uint32_t aStart, uint32_t aMaxLength, bool aLineBreakBefore,
gfxFloat aWidth, PropertyProvider* aProvider, SuppressBreak aSuppressBreak,
gfxFloat* aTrimWhitespace, bool aWhitespaceCanHang, Metrics* aMetrics,
gfxFont::BoundingBoxType aBoundingBoxType, DrawTarget* aRefDrawTarget,
bool* aUsedHyphenation, uint32_t* aLastBreak, bool aCanWordWrap,
bool aCanWhitespaceWrap, gfxBreakPriority* aBreakPriority) {
aMaxLength = std::min(aMaxLength, GetLength() - aStart);
NS_ASSERTION(aStart + aMaxLength <= GetLength(), "Substring out of range");
Range bufferRange(
aStart, aStart + std::min<uint32_t>(aMaxLength, MEASUREMENT_BUFFER_SIZE));
PropertyProvider::Spacing spacingBuffer[MEASUREMENT_BUFFER_SIZE];
bool haveSpacing =
aProvider && !!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING);
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
AutoTArray<HyphenType, 4096> hyphenBuffer;
HyphenationState wordState;
wordState.mostRecentBoundary = aStart;
bool haveHyphenation =
aProvider &&
(aProvider->GetHyphensOption() == StyleHyphens::Auto ||
(aProvider->GetHyphensOption() == StyleHyphens::Manual &&
!!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_HYPHEN_BREAKS)));
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(bufferRange, hyphenBuffer.Elements());
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer, &wordState);
}
} else {
haveHyphenation = false;
}
}
gfxFloat width = 0;
gfxFloat advance = 0;
// The number of space characters that can be trimmed or hang at a soft-wrap
uint32_t trimmableChars = 0;
// The amount of space removed by ignoring trimmableChars
gfxFloat trimmableAdvance = 0;
int32_t lastBreak = -1;
int32_t lastBreakTrimmableChars = -1;
gfxFloat lastBreakTrimmableAdvance = -1;
// Cache the last candidate break
int32_t lastCandidateBreak = -1;
int32_t lastCandidateBreakTrimmableChars = -1;
gfxFloat lastCandidateBreakTrimmableAdvance = -1;
bool lastCandidateBreakUsedHyphenation = false;
gfxBreakPriority lastCandidateBreakPriority = gfxBreakPriority::eNoBreak;
bool aborted = false;
uint32_t end = aStart + aMaxLength;
bool lastBreakUsedHyphenation = false;
Range ligatureRange(aStart, end);
ShrinkToLigatureBoundaries(&ligatureRange);
// We may need to move `i` backwards in the following loop, and re-scan
// part of the textrun; we'll use `rescanLimit` so we can tell when that
// is happening: if `i < rescanLimit` then we're rescanning.
uint32_t rescanLimit = aStart;
for (uint32_t i = aStart; i < end; ++i) {
if (i >= bufferRange.end) {
// Fetch more spacing and hyphenation data
uint32_t oldHyphenBufferLength = hyphenBuffer.Length();
bufferRange.start = i;
bufferRange.end =
std::min(aStart + aMaxLength, i + MEASUREMENT_BUFFER_SIZE);
// For spacing, we always overwrite the old data with the newly
// fetched one. However, for hyphenation, hyphenation data sometimes
// depends on the context in every word (if "hyphens: auto" is set).
// To ensure we get enough information between neighboring buffers,
// we grow the hyphenBuffer instead of overwrite it.
// NOTE that this means bufferRange does not correspond to the
// entire hyphenBuffer, but only to the most recently added portion.
// Therefore, we need to add the old length to hyphenBuffer.Elements()
// when getting more data.
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(
bufferRange, hyphenBuffer.Elements() + oldHyphenBufferLength);
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
uint32_t prevMostRecentWordBoundary = wordState.mostRecentBoundary;
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer,
&wordState);
// If the buffer boundary is in the middle of a word,
// we need to go back to the start of the current word.
// So, we can correct the wrong candidates that we set
// in the previous runs of the loop.
if (prevMostRecentWordBoundary < oldHyphenBufferLength) {
rescanLimit = i;
i = prevMostRecentWordBoundary - 1;
continue;
}
}
} else {
haveHyphenation = false;
}
}
}
// There can't be a word-wrap break opportunity at the beginning of the
// line: if the width is too small for even one character to fit, it
// could be the first and last break opportunity on the line, and that
// would trigger an infinite loop.
if (aSuppressBreak != eSuppressAllBreaks &&
(aSuppressBreak != eSuppressInitialBreak || i > aStart)) {
bool atNaturalBreak = mCharacterGlyphs[i].CanBreakBefore() == 1;
// atHyphenationBreak indicates we're at a "soft" hyphen, where an extra
// hyphen glyph will need to be painted. It is NOT set for breaks at an
// explicit hyphen present in the text.
bool atHyphenationBreak = !atNaturalBreak && haveHyphenation &&
hyphenBuffer[i - aStart] > HyphenType::Explicit;
bool atAutoHyphenWithManualHyphenInSameWord =
atHyphenationBreak &&
hyphenBuffer[i - aStart] == HyphenType::AutoWithManualInSameWord;
bool atBreak = atNaturalBreak || atHyphenationBreak;
bool wordWrapping = aCanWordWrap &&
mCharacterGlyphs[i].IsClusterStart() &&
*aBreakPriority <= gfxBreakPriority::eWordWrapBreak;
bool whitespaceWrapping = false;
if (i > aStart) {
// The spec says the breaking opportunity is *after* whitespace.
auto const& g = mCharacterGlyphs[i - 1];
whitespaceWrapping =
aCanWhitespaceWrap &&
(g.CharIsSpace() || g.CharIsTab() || g.CharIsNewline());
}
if (atBreak || wordWrapping || whitespaceWrapping) {
gfxFloat hyphenatedAdvance = advance;
if (atHyphenationBreak) {
hyphenatedAdvance += aProvider->GetHyphenWidth();
}
if (lastBreak < 0 ||
width + hyphenatedAdvance - trimmableAdvance <= aWidth) {
// We can break here.
lastBreak = i;
lastBreakTrimmableChars = trimmableChars;
lastBreakTrimmableAdvance = trimmableAdvance;
lastBreakUsedHyphenation = atHyphenationBreak;
*aBreakPriority = (atBreak || whitespaceWrapping)
? gfxBreakPriority::eNormalBreak
: gfxBreakPriority::eWordWrapBreak;
}
width += advance;
advance = 0;
if (width - trimmableAdvance > aWidth) {
// No more text fits. Abort
aborted = true;
break;
}
// There are various kinds of break opportunities:
// 1. word wrap break,
// 2. natural break,
// 3. manual hyphenation break,
// 4. auto hyphenation break without any manual hyphenation
// in the same word,
// 5. auto hyphenation break with another manual hyphenation
// in the same word.
// Allow all of them except the last one to be a candidate.
// So, we can ensure that we don't use an automatic
// hyphenation opportunity within a word that contains another
// manual hyphenation, unless it is the only choice.
if (wordWrapping || !atAutoHyphenWithManualHyphenInSameWord) {
lastCandidateBreak = lastBreak;
lastCandidateBreakTrimmableChars = lastBreakTrimmableChars;
lastCandidateBreakTrimmableAdvance = lastBreakTrimmableAdvance;
lastCandidateBreakUsedHyphenation = lastBreakUsedHyphenation;
lastCandidateBreakPriority = *aBreakPriority;
}
}
}
// If we're re-scanning part of a word (to re-process potential
// hyphenation types) then we don't want to accumulate widths again
// for the characters that were already added to `advance`.
if (i < rescanLimit) {
continue;
}
gfxFloat charAdvance;
if (i >= ligatureRange.start && i < ligatureRange.end) {
charAdvance = GetAdvanceForGlyphs(Range(i, i + 1));
if (haveSpacing) {
PropertyProvider::Spacing* space =
&spacingBuffer[i - bufferRange.start];
charAdvance += space->mBefore + space->mAfter;
}
} else {
charAdvance = ComputePartialLigatureWidth(Range(i, i + 1), aProvider);
}
advance += charAdvance;
if (aTrimWhitespace || aWhitespaceCanHang) {
if (mCharacterGlyphs[i].CharIsSpace()) {
++trimmableChars;
trimmableAdvance += charAdvance;
} else {
trimmableAdvance = 0;
trimmableChars = 0;
}
}
}
if (!aborted) {
width += advance;
}
// There are three possibilities:
// 1) all the text fit (width <= aWidth)
// 2) some of the text fit up to a break opportunity (width > aWidth &&
// lastBreak >= 0)
// 3) none of the text fits before a break opportunity (width > aWidth &&
// lastBreak < 0)
uint32_t charsFit;
bool usedHyphenation = false;
if (width - trimmableAdvance <= aWidth) {
charsFit = aMaxLength;
} else if (lastBreak >= 0) {
if (lastCandidateBreak >= 0 && lastCandidateBreak != lastBreak) {
lastBreak = lastCandidateBreak;
lastBreakTrimmableChars = lastCandidateBreakTrimmableChars;
lastBreakTrimmableAdvance = lastCandidateBreakTrimmableAdvance;
lastBreakUsedHyphenation = lastCandidateBreakUsedHyphenation;
*aBreakPriority = lastCandidateBreakPriority;
}
charsFit = lastBreak - aStart;
trimmableChars = lastBreakTrimmableChars;
trimmableAdvance = lastBreakTrimmableAdvance;
usedHyphenation = lastBreakUsedHyphenation;
} else {
charsFit = aMaxLength;
}
if (aMetrics) {
auto fitEnd = aStart + charsFit;
// Initially, measure everything, so that our bounding box includes
// any trimmable or hanging whitespace.
*aMetrics = MeasureText(Range(aStart, fitEnd), aBoundingBoxType,
aRefDrawTarget, aProvider);
if (aTrimWhitespace || aWhitespaceCanHang) {
// Measure trailing whitespace that is to be trimmed/hung.
Metrics trimOrHangMetrics =
MeasureText(Range(fitEnd - trimmableChars, fitEnd), aBoundingBoxType,
aRefDrawTarget, aProvider);
if (aTrimWhitespace) {
aMetrics->mAdvanceWidth -= trimOrHangMetrics.mAdvanceWidth;
} else if (aMetrics->mAdvanceWidth > aWidth) {
// Restrict width of hanging whitespace so it doesn't overflow.
aMetrics->mAdvanceWidth = std::max(
aWidth, aMetrics->mAdvanceWidth - trimOrHangMetrics.mAdvanceWidth);
}
}
}
if (aTrimWhitespace) {
*aTrimWhitespace = trimmableAdvance;
}
if (aUsedHyphenation) {
*aUsedHyphenation = usedHyphenation;
}
if (aLastBreak && charsFit == aMaxLength) {
if (lastBreak < 0) {
*aLastBreak = UINT32_MAX;
} else {
*aLastBreak = lastBreak - aStart;
}
}
return charsFit;
}
gfxFloat gfxTextRun::GetAdvanceWidth(
Range aRange, PropertyProvider* aProvider,
PropertyProvider::Spacing* aSpacing) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
Range ligatureRange = aRange;
ShrinkToLigatureBoundaries(&ligatureRange);
gfxFloat result = ComputePartialLigatureWidth(
Range(aRange.start, ligatureRange.start), aProvider) +
ComputePartialLigatureWidth(
Range(ligatureRange.end, aRange.end), aProvider);
if (aSpacing) {
aSpacing->mBefore = aSpacing->mAfter = 0;
}
// Account for all remaining spacing here. This is more efficient than
// processing it along with the glyphs.
if (aProvider && (mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
uint32_t i;
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
if (spacingBuffer.AppendElements(aRange.Length(), fallible)) {
GetAdjustedSpacing(this, ligatureRange, aProvider,
spacingBuffer.Elements());
for (i = 0; i < ligatureRange.Length(); ++i) {
PropertyProvider::Spacing* space = &spacingBuffer[i];
result += space->mBefore + space->mAfter;
}
if (aSpacing) {
aSpacing->mBefore = spacingBuffer[0].mBefore;
aSpacing->mAfter = spacingBuffer.LastElement().mAfter;
}
}
}
return result + GetAdvanceForGlyphs(ligatureRange);
}
gfxFloat gfxTextRun::GetMinAdvanceWidth(Range aRange) {
MOZ_ASSERT(aRange.end <= GetLength(), "Substring out of range");
Range ligatureRange = aRange;
ShrinkToLigatureBoundaries(&ligatureRange);
gfxFloat result =
std::max(ComputePartialLigatureWidth(
Range(aRange.start, ligatureRange.start), nullptr),
ComputePartialLigatureWidth(Range(ligatureRange.end, aRange.end),
nullptr));
// XXX Do we need to take spacing into account? When each grapheme cluster
// takes its own line, we shouldn't be adding spacings around them.
gfxFloat clusterAdvance = 0;
for (uint32_t i = ligatureRange.start; i < ligatureRange.end; ++i) {
clusterAdvance += GetAdvanceForGlyph(i);
if (i + 1 == ligatureRange.end || IsClusterStart(i + 1)) {
result = std::max(result, clusterAdvance);
clusterAdvance = 0;
}
}
return result;
}
bool gfxTextRun::SetLineBreaks(Range aRange, bool aLineBreakBefore,
bool aLineBreakAfter,
gfxFloat* aAdvanceWidthDelta) {
// Do nothing because our shaping does not currently take linebreaks into
// account. There is no change in advance width.
if (aAdvanceWidthDelta) {
*aAdvanceWidthDelta = 0;
}
return false;
}
uint32_t gfxTextRun::FindFirstGlyphRunContaining(uint32_t aOffset) const {
NS_ASSERTION(aOffset <= GetLength(), "Bad offset looking for glyphrun");
NS_ASSERTION(GetLength() == 0 ||
(!mHasGlyphRunArray && mSingleGlyphRun.mFont) ||
(mHasGlyphRunArray && mGlyphRunArray.Length() > 0),
"non-empty text but no glyph runs present!");
if (!mHasGlyphRunArray) {
return 0;
}
if (aOffset == GetLength()) {
return mGlyphRunArray.Length();
}
uint32_t start = 0;
uint32_t end = mGlyphRunArray.Length();
while (end - start > 1) {
uint32_t mid = (start + end) / 2;
if (mGlyphRunArray[mid].mCharacterOffset <= aOffset) {
start = mid;
} else {
end = mid;
}
}
NS_ASSERTION(mGlyphRunArray[start].mCharacterOffset <= aOffset,
"Hmm, something went wrong, aOffset should have been found");
return start;
}
void gfxTextRun::AddGlyphRun(gfxFont* aFont, FontMatchType aMatchType,
uint32_t aUTF16Offset, bool aForceNewRun,
gfx::ShapedTextFlags aOrientation, bool aIsCJK) {
NS_ASSERTION(aFont, "adding glyph run for null font!");
NS_ASSERTION(aOrientation != gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED,
"mixed orientation should have been resolved");
if (!aFont) {
return;
}
if (!mHasGlyphRunArray) {
// We don't currently have an array.
if (!mSingleGlyphRun.mFont) {
// This is the first glyph run: just store it directly.
mSingleGlyphRun.SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
mSingleGlyphRun.mCharacterOffset = aUTF16Offset;
return;
}
}
uint32_t numGlyphRuns = mHasGlyphRunArray ? mGlyphRunArray.Length() : 1;
if (!aForceNewRun && numGlyphRuns > 0) {
GlyphRun* lastGlyphRun = mHasGlyphRunArray
? &mGlyphRunArray[numGlyphRuns - 1]
: &mSingleGlyphRun;
NS_ASSERTION(lastGlyphRun->mCharacterOffset <= aUTF16Offset,
"Glyph runs out of order (and run not forced)");
// Don't append a run if the font is already the one we want
if (lastGlyphRun->Matches(aFont, aOrientation, aIsCJK, aMatchType)) {
return;
}
// If the offset has not changed, avoid leaving a zero-length run
// by overwriting the last entry instead of appending...
if (lastGlyphRun->mCharacterOffset == aUTF16Offset) {
// ...except that if the run before the last entry had the same
// font as the new one wants, merge with it instead of creating
// adjacent runs with the same font
if (numGlyphRuns > 1 && mGlyphRunArray[numGlyphRuns - 2].Matches(
aFont, aOrientation, aIsCJK, aMatchType)) {
mGlyphRunArray.TruncateLength(numGlyphRuns - 1);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
return;
}
lastGlyphRun->SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
return;
}
}
NS_ASSERTION(
aForceNewRun || numGlyphRuns > 0 || aUTF16Offset == 0,
"First run doesn't cover the first character (and run not forced)?");
if (!mHasGlyphRunArray) {
ConvertToGlyphRunArray();
}
GlyphRun* glyphRun = mGlyphRunArray.AppendElement();
glyphRun->SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
glyphRun->mCharacterOffset = aUTF16Offset;
}
void gfxTextRun::SortGlyphRuns() {
if (!mHasGlyphRunArray) {
return;
}
// We should never have an empty or one-element array here; if there's only
// one glyphrun, it should be stored directly in the textrun without using
// an array at all.
MOZ_ASSERT(mGlyphRunArray.Length() > 1);
AutoTArray<GlyphRun, 16> runs(std::move(mGlyphRunArray));
GlyphRunOffsetComparator comp;
runs.Sort(comp);
// Now copy back, coalescing adjacent glyph runs that have the same
// properties.
mGlyphRunArray.Clear();
GlyphRun* prevRun = nullptr;
for (auto& run : runs) {
// A GlyphRun with the same font and orientation as the previous can
// just be skipped; the last GlyphRun will cover its character range.
MOZ_ASSERT(run.mFont != nullptr);
if (!prevRun || !prevRun->Matches(run.mFont, run.mOrientation, run.mIsCJK,
run.mMatchType)) {
// If two font runs have the same character offset, Sort() will have
// randomized their order!
MOZ_ASSERT(prevRun == nullptr ||
prevRun->mCharacterOffset < run.mCharacterOffset,
"Two fonts for the same run, glyph indices unreliable");
prevRun = mGlyphRunArray.AppendElement(std::move(run));
}
}
MOZ_ASSERT(mGlyphRunArray.Length() > 0);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
}
// Note that SanitizeGlyphRuns scans all glyph runs in the textrun;
// therefore we only call it once, at the end of textrun construction,
// NOT incrementally as each glyph run is added (bug 680402).
void gfxTextRun::SanitizeGlyphRuns() {
if (!mHasGlyphRunArray) {
return;
}
MOZ_ASSERT(mGlyphRunArray.Length() > 1);
// If any glyph run starts with ligature-continuation characters, we need to
// advance it to the first "real" character to avoid drawing partial ligature
// glyphs from wrong font (seen with U+FEFF in reftest 474417-1, as Core Text
// eliminates the glyph, which makes it appear as if a ligature has been
// formed)
int32_t i, lastRunIndex = mGlyphRunArray.Length() - 1;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
for (i = lastRunIndex; i >= 0; --i) {
GlyphRun& run = mGlyphRunArray[i];
while (charGlyphs[run.mCharacterOffset].IsLigatureContinuation() &&
run.mCharacterOffset < GetLength()) {
run.mCharacterOffset++;
}
// if the run has become empty, eliminate it
if ((i < lastRunIndex &&
run.mCharacterOffset >= mGlyphRunArray[i + 1].mCharacterOffset) ||
(i == lastRunIndex && run.mCharacterOffset == GetLength())) {
mGlyphRunArray.RemoveElementAt(i);
--lastRunIndex;
}
}
MOZ_ASSERT(mGlyphRunArray.Length() > 0);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
}
void gfxTextRun::CopyGlyphDataFrom(gfxShapedWord* aShapedWord,
uint32_t aOffset) {
uint32_t wordLen = aShapedWord->GetLength();
NS_ASSERTION(aOffset + wordLen <= GetLength(),
"word overruns end of textrun!");
CompressedGlyph* charGlyphs = GetCharacterGlyphs();
const CompressedGlyph* wordGlyphs = aShapedWord->GetCharacterGlyphs();
if (aShapedWord->HasDetailedGlyphs()) {
for (uint32_t i = 0; i < wordLen; ++i, ++aOffset) {
const CompressedGlyph& g = wordGlyphs[i];
if (!g.IsSimpleGlyph()) {
const DetailedGlyph* details =
g.GetGlyphCount() > 0 ? aShapedWord->GetDetailedGlyphs(i) : nullptr;
SetDetailedGlyphs(aOffset, g.GetGlyphCount(), details);
}
charGlyphs[aOffset] = g;
}
} else {
memcpy(charGlyphs + aOffset, wordGlyphs, wordLen * sizeof(CompressedGlyph));
}
}
void gfxTextRun::CopyGlyphDataFrom(gfxTextRun* aSource, Range aRange,
uint32_t aDest) {
NS_ASSERTION(aRange.end <= aSource->GetLength(),
"Source substring out of range");
NS_ASSERTION(aDest + aRange.Length() <= GetLength(),
"Destination substring out of range");
if (aSource->mDontSkipDrawing) {
mDontSkipDrawing = true;
}
// Copy base glyph data, and DetailedGlyph data where present
const CompressedGlyph* srcGlyphs = aSource->mCharacterGlyphs + aRange.start;
CompressedGlyph* dstGlyphs = mCharacterGlyphs + aDest;
for (uint32_t i = 0; i < aRange.Length(); ++i) {
CompressedGlyph g = srcGlyphs[i];
g.SetCanBreakBefore(!g.IsClusterStart()
? CompressedGlyph::FLAG_BREAK_TYPE_NONE
: dstGlyphs[i].CanBreakBefore());
if (!g.IsSimpleGlyph()) {
uint32_t count = g.GetGlyphCount();
if (count > 0) {
// DetailedGlyphs allocation is infallible, so this should never be
// null unless the source textrun is somehow broken.
DetailedGlyph* src = aSource->GetDetailedGlyphs(i + aRange.start);
MOZ_ASSERT(src, "missing DetailedGlyphs?");
if (src) {
DetailedGlyph* dst = AllocateDetailedGlyphs(i + aDest, count);
::memcpy(dst, src, count * sizeof(DetailedGlyph));
} else {
g.SetMissing();
}
}
}
dstGlyphs[i] = g;
}
// Copy glyph runs
GlyphRunIterator iter(aSource, aRange);
#ifdef DEBUG
GlyphRun* prevRun = nullptr;
#endif
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
MOZ_ASSERT(!prevRun || !prevRun->Matches(iter.GetGlyphRun()->mFont,
iter.GetGlyphRun()->mOrientation,
iter.GetGlyphRun()->mIsCJK,
FontMatchType::Kind::kUnspecified),
"Glyphruns not coalesced?");
#ifdef DEBUG
prevRun = const_cast<GlyphRun*>(iter.GetGlyphRun());
uint32_t end = iter.GetStringEnd();
#endif
uint32_t start = iter.GetStringStart();
// These used to be NS_ASSERTION()s, but WARNING is more appropriate.
// Although it's unusual (and not desirable), it's possible for us to assign
// different fonts to a base character and a following diacritic.
// Example on OSX 10.5/10.6 with default fonts installed:
// data:text/html,<p style="font-family:helvetica, arial, sans-serif;">
// &%23x043E;&%23x0486;&%23x20;&%23x043E;&%23x0486;
// This means the rendering of the cluster will probably not be very good,
// but it's the best we can do for now if the specified font only covered
// the initial base character and not its applied marks.
NS_WARNING_ASSERTION(aSource->IsClusterStart(start),
"Started font run in the middle of a cluster");
NS_WARNING_ASSERTION(
end == aSource->GetLength() || aSource->IsClusterStart(end),
"Ended font run in the middle of a cluster");
AddGlyphRun(font, iter.GetGlyphRun()->mMatchType,
start - aRange.start + aDest, false,
iter.GetGlyphRun()->mOrientation, iter.GetGlyphRun()->mIsCJK);
}
}
void gfxTextRun::ClearGlyphsAndCharacters() {
ResetGlyphRuns();
memset(reinterpret_cast<char*>(mCharacterGlyphs), 0,
mLength * sizeof(CompressedGlyph));
mDetailedGlyphs = nullptr;
}
void gfxTextRun::SetSpaceGlyph(gfxFont* aFont, DrawTarget* aDrawTarget,
uint32_t aCharIndex,
gfx::ShapedTextFlags aOrientation) {
if (SetSpaceGlyphIfSimple(aFont, aCharIndex, ' ', aOrientation)) {
return;
}
aFont->InitWordCache();
static const uint8_t space = ' ';
gfx::ShapedTextFlags flags =
gfx::ShapedTextFlags::TEXT_IS_8BIT | aOrientation;
bool vertical =
!!(GetFlags() & gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT);
gfxFontShaper::RoundingFlags roundingFlags =
aFont->GetRoundOffsetsToPixels(aDrawTarget);
gfxShapedWord* sw = aFont->GetShapedWord(
aDrawTarget, &space, 1, gfxShapedWord::HashMix(0, ' '), Script::LATIN,
/* aLanguage = */ nullptr, vertical, mAppUnitsPerDevUnit, flags,
roundingFlags, nullptr);
if (sw) {
const GlyphRun* prevRun = TrailingGlyphRun();
bool isCJK = prevRun && prevRun->mFont == aFont &&
prevRun->mOrientation == aOrientation
? prevRun->mIsCJK
: false;
AddGlyphRun(aFont, FontMatchType::Kind::kUnspecified, aCharIndex, false,
aOrientation, isCJK);
CopyGlyphDataFrom(sw, aCharIndex);
GetCharacterGlyphs()[aCharIndex].SetIsSpace();
}
}
bool gfxTextRun::SetSpaceGlyphIfSimple(gfxFont* aFont, uint32_t aCharIndex,
char16_t aSpaceChar,
gfx::ShapedTextFlags aOrientation) {
uint32_t spaceGlyph = aFont->GetSpaceGlyph();
if (!spaceGlyph || !CompressedGlyph::IsSimpleGlyphID(spaceGlyph)) {
return false;
}
gfxFont::Orientation fontOrientation =
(aOrientation & gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT)
? nsFontMetrics::eVertical
: nsFontMetrics::eHorizontal;
uint32_t spaceWidthAppUnits = NS_lroundf(
aFont->GetMetrics(fontOrientation).spaceWidth * mAppUnitsPerDevUnit);
if (!CompressedGlyph::IsSimpleAdvance(spaceWidthAppUnits)) {
return false;
}
const GlyphRun* prevRun = TrailingGlyphRun();
bool isCJK = prevRun && prevRun->mFont == aFont &&
prevRun->mOrientation == aOrientation
? prevRun->mIsCJK
: false;
AddGlyphRun(aFont, FontMatchType::Kind::kUnspecified, aCharIndex, false,
aOrientation, isCJK);
CompressedGlyph g =
CompressedGlyph::MakeSimpleGlyph(spaceWidthAppUnits, spaceGlyph);
if (aSpaceChar == ' ') {
g.SetIsSpace();
}
GetCharacterGlyphs()[aCharIndex] = g;
return true;
}
void gfxTextRun::FetchGlyphExtents(DrawTarget* aRefDrawTarget) {
bool needsGlyphExtents = NeedsGlyphExtents(this);
if (!needsGlyphExtents && !mDetailedGlyphs) return;
uint32_t runCount;
const GlyphRun* glyphRuns = GetGlyphRuns(&runCount);
CompressedGlyph* charGlyphs = mCharacterGlyphs;
for (uint32_t i = 0; i < runCount; ++i) {
const GlyphRun& run = glyphRuns[i];
gfxFont* font = run.mFont;
if (MOZ_UNLIKELY(font->GetStyle()->size == 0) ||
MOZ_UNLIKELY(font->GetStyle()->sizeAdjust == 0.0f)) {
continue;
}
uint32_t start = run.mCharacterOffset;
uint32_t end =
i + 1 < runCount ? glyphRuns[i + 1].mCharacterOffset : GetLength();
uint32_t j;
gfxGlyphExtents* extents =
font->GetOrCreateGlyphExtents(mAppUnitsPerDevUnit);
for (j = start; j < end; ++j) {
const gfxTextRun::CompressedGlyph* glyphData = &charGlyphs[j];
if (glyphData->IsSimpleGlyph()) {
// If we're in speed mode, don't set up glyph extents here; we'll
// just return "optimistic" glyph bounds later
if (needsGlyphExtents) {
uint32_t glyphIndex = glyphData->GetSimpleGlyph();
if (!extents->IsGlyphKnown(glyphIndex)) {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
++gGlyphExtentsSetupEagerSimple;
#endif
font->SetupGlyphExtents(aRefDrawTarget, glyphIndex, false, extents);
}
}
} else if (!glyphData->IsMissing()) {
uint32_t glyphCount = glyphData->GetGlyphCount();
if (glyphCount == 0) {
continue;
}
const gfxTextRun::DetailedGlyph* details = GetDetailedGlyphs(j);
if (!details) {
continue;
}
for (uint32_t k = 0; k < glyphCount; ++k, ++details) {
uint32_t glyphIndex = details->mGlyphID;
if (!extents->IsGlyphKnownWithTightExtents(glyphIndex)) {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
++gGlyphExtentsSetupEagerTight;
#endif
font->SetupGlyphExtents(aRefDrawTarget, glyphIndex, true, extents);
}
}
}
}
}
}
size_t gfxTextRun::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) {
// The second arg is how much gfxTextRun::AllocateStorage would have
// allocated.
size_t total = mHasGlyphRunArray
? mGlyphRunArray.ShallowSizeOfExcludingThis(aMallocSizeOf)
: 0;
if (mDetailedGlyphs) {
total += mDetailedGlyphs->SizeOfIncludingThis(aMallocSizeOf);
}
return total;
}
size_t gfxTextRun::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
}
#ifdef DEBUG_FRAME_DUMP
void gfxTextRun::Dump(FILE* out) {
# define APPEND_FLAG(string_, enum_, field_, flag_) \
if (field_ & enum_::flag_) { \
string_.AppendPrintf(remaining != field_ ? " %s" : "%s", #flag_); \
remaining &= ~enum_::flag_; \
}
# define APPEND_FLAGS(string_, enum_, field_, flags_) \
{ \
auto remaining = field_; \
MOZ_FOR_EACH(APPEND_FLAG, (string_, enum_, field_, ), flags_) \
if (int(remaining)) { \
string_.AppendPrintf(" %s(0x%0x)", #enum_, int(remaining)); \
} \
}
nsCString flagsString;
ShapedTextFlags orient = mFlags & ShapedTextFlags::TEXT_ORIENT_MASK;
ShapedTextFlags otherFlags = mFlags & ~ShapedTextFlags::TEXT_ORIENT_MASK;
APPEND_FLAGS(flagsString, ShapedTextFlags, otherFlags,
(TEXT_IS_RTL, TEXT_ENABLE_SPACING, TEXT_IS_8BIT,
TEXT_ENABLE_HYPHEN_BREAKS, TEXT_NEED_BOUNDING_BOX,
TEXT_DISABLE_OPTIONAL_LIGATURES, TEXT_OPTIMIZE_SPEED,
TEXT_HIDE_CONTROL_CHARACTERS, TEXT_TRAILING_ARABICCHAR,
TEXT_INCOMING_ARABICCHAR, TEXT_USE_MATH_SCRIPT))
if (orient != ShapedTextFlags::TEXT_ORIENT_HORIZONTAL &&
!flagsString.IsEmpty()) {
flagsString += ' ';
}
switch (orient) {
case ShapedTextFlags::TEXT_ORIENT_HORIZONTAL:
break;
case ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT:
flagsString += "TEXT_ORIENT_VERTICAL_UPRIGHT";
break;
case ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT:
flagsString += "TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT";
break;
case ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED:
flagsString += "TEXT_ORIENT_VERTICAL_MIXED";
break;
case ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT:
flagsString += "TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT";
break;
default:
flagsString.AppendPrintf("UNKNOWN_TEXT_ORIENT_MASK(0x%0x)", int(orient));
break;
}
nsCString flags2String;
APPEND_FLAGS(
flags2String, nsTextFrameUtils::Flags, mFlags2,
(HasTab, HasShy, DontSkipDrawingForPendingUserFonts, IsSimpleFlow,
IncomingWhitespace, TrailingWhitespace, CompressedLeadingWhitespace,
NoBreaks, IsTransformed, HasTrailingBreak, IsSingleCharMi,
MightHaveGlyphChanges, RunSizeAccounted))
# undef APPEND_FLAGS
# undef APPEND_FLAG
nsAutoCString lang;
mFontGroup->Language()->ToUTF8String(lang);
fprintf(out, "gfxTextRun@%p (length %u) [%s] [%s] [%s]\n", this, mLength,
flagsString.get(), flags2String.get(), lang.get());
uint32_t numGlyphRuns;
const GlyphRun* glyphRuns = GetGlyphRuns(&numGlyphRuns);
fprintf(out, " Glyph runs:\n");
for (uint32_t i = 0; i < numGlyphRuns; ++i) {
gfxFont* font = glyphRuns[i].mFont;
const gfxFontStyle* style = font->GetStyle();
nsAutoString styleString;
nsStyleUtil::AppendFontSlantStyle(style->style, styleString);
fprintf(out, " [%d] offset=%d %s %f/%g/%s\n", i,
glyphRuns[i].mCharacterOffset, font->GetName().get(), style->size,
style->weight.ToFloat(), NS_ConvertUTF16toUTF8(styleString).get());
}
fprintf(out, " Glyphs:\n");
for (uint32_t i = 0; i < mLength; ++i) {
auto glyphData = GetCharacterGlyphs()[i];
nsCString line;
line.AppendPrintf(" [%d] 0x%p %s", i, GetCharacterGlyphs() + i,
glyphData.IsSimpleGlyph() ? "simple" : "detailed");
if (glyphData.IsSimpleGlyph()) {
line.AppendPrintf(" id=%d adv=%d", glyphData.GetSimpleGlyph(),
glyphData.GetSimpleAdvance());
} else {
uint32_t count = glyphData.GetGlyphCount();
if (count) {
line += " ids=";
for (uint32_t j = 0; j < count; j++) {
line.AppendPrintf(j ? ",%d" : "%d", GetDetailedGlyphs(i)[j].mGlyphID);
}
line += " advs=";
for (uint32_t j = 0; j < count; j++) {
line.AppendPrintf(j ? ",%d" : "%d", GetDetailedGlyphs(i)[j].mAdvance);
}
line += " offsets=";
for (uint32_t j = 0; j < count; j++) {
auto offset = GetDetailedGlyphs(i)[j].mOffset;
line.AppendPrintf(j ? ",(%g,%g)" : "(%g,%g)", offset.x, offset.y);
}
} else {
line += " (no glyphs)";
}
}
if (glyphData.CharIsSpace()) {
line += " CHAR_IS_SPACE";
}
if (glyphData.CharIsTab()) {
line += " CHAR_IS_TAB";
}
if (glyphData.CharIsNewline()) {
line += " CHAR_IS_NEWLINE";
}
if (glyphData.CharIsFormattingControl()) {
line += " CHAR_IS_FORMATTING_CONTROL";
}
if (glyphData.CharTypeFlags() &
CompressedGlyph::FLAG_CHAR_NO_EMPHASIS_MARK) {
line += " CHAR_NO_EMPHASIS_MARK";
}
if (!glyphData.IsSimpleGlyph()) {
if (!glyphData.IsMissing()) {
line += " NOT_MISSING";
}
if (!glyphData.IsClusterStart()) {
line += " NOT_IS_CLUSTER_START";
}
if (!glyphData.IsLigatureGroupStart()) {
line += " NOT_LIGATURE_GROUP_START";
}
}
switch (glyphData.CanBreakBefore()) {
case CompressedGlyph::FLAG_BREAK_TYPE_NORMAL:
line += " BREAK_TYPE_NORMAL";
break;
case CompressedGlyph::FLAG_BREAK_TYPE_HYPHEN:
line += " BREAK_TYPE_HYPHEN";
break;
}
fprintf(out, "%s\n", line.get());
}
}
#endif
gfxFontGroup::gfxFontGroup(const FontFamilyList& aFontFamilyList,
const gfxFontStyle* aStyle, nsAtom* aLanguage,
bool aExplicitLanguage,
gfxTextPerfMetrics* aTextPerf,
FontMatchingStats* aFontMatchingStats,
gfxUserFontSet* aUserFontSet, gfxFloat aDevToCssSize)
: mFamilyList(aFontFamilyList),
mStyle(*aStyle),
mLanguage(aLanguage),
mUnderlineOffset(UNDERLINE_OFFSET_NOT_SET),
mHyphenWidth(-1),
mDevToCssSize(aDevToCssSize),
mUserFontSet(aUserFontSet),
mTextPerf(aTextPerf),
mFontMatchingStats(aFontMatchingStats),
mLastPrefLang(eFontPrefLang_Western),
mPageLang(gfxPlatformFontList::GetFontPrefLangFor(aLanguage)),
mLastPrefFirstFont(false),
mSkipDrawing(false),
mExplicitLanguage(aExplicitLanguage) {
// We don't use SetUserFontSet() here, as we want to unconditionally call
// BuildFontList() rather than only do UpdateUserFonts() if it changed.
mCurrGeneration = GetGeneration();
BuildFontList();
}
gfxFontGroup::~gfxFontGroup() {
// Should not be dropped by stylo
MOZ_ASSERT(NS_IsMainThread());
}
void gfxFontGroup::BuildFontList() {
// initialize fonts in the font family list
AutoTArray<FamilyAndGeneric, 10> fonts;
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
// lookup fonts in the fontlist
for (const FontFamilyName& name : mFamilyList.GetFontlist()->mNames) {
if (name.IsNamed()) {
if (name.mName) {
AddPlatformFont(nsAtomCString(name.mName), name.IsQuoted(), fonts);
} else {
MOZ_ASSERT_UNREACHABLE("broken FontFamilyName, no atom!");
}
} else {
pfl->AddGenericFonts(name.mGeneric, mLanguage, fonts);
if (mTextPerf) {
mTextPerf->current.genericLookups++;
}
}
}
if (mFontMatchingStats) {
for (const auto& f : fonts) {
nsCString key; // not nsAutoCString, as the assignment to it won't copy
// characters, it'll just share the string buffer
FontVisibility visibility;
if (f.mFamily.mIsShared) {
key = f.mFamily.mShared->Key().AsString(pfl->SharedFontList());
visibility = f.mFamily.mShared->Visibility();
} else {
key = f.mFamily.mUnshared->Name();
ToLowerCase(key);
visibility = f.mFamily.mUnshared->Visibility();
}
if (mFontMatchingStats->mFamilyNames.EnsureInserted(key)) {
switch (visibility) {
case FontVisibility::Base:
mFontMatchingStats->mBaseFonts++;
break;
case FontVisibility::LangPack:
mFontMatchingStats->mLangPackFonts++;
break;
case FontVisibility::User:
mFontMatchingStats->mUserFonts++;
break;
case FontVisibility::Webfont:
mFontMatchingStats->mWebFonts++;
break;
default:
break;
}
}
}
}
// if necessary, append default generic onto the end
if (mFamilyList.GetDefaultFontType() != StyleGenericFontFamily::None &&
!mFamilyList.HasDefaultGeneric()) {
pfl->AddGenericFonts(mFamilyList.GetDefaultFontType(), mLanguage, fonts);
if (mTextPerf) {
mTextPerf->current.genericLookups++;
}
}
// build the fontlist from the specified families
for (const auto& f : fonts) {
if (f.mFamily.mIsShared) {
AddFamilyToFontList(f.mFamily.mShared, f.mGeneric);
} else {
AddFamilyToFontList(f.mFamily.mUnshared, f.mGeneric);
}
}
mFontListGeneration = pfl->GetGeneration();
}
void gfxFontGroup::AddPlatformFont(const nsACString& aName, bool aQuotedName,
nsTArray<FamilyAndGeneric>& aFamilyList) {
// First, look up in the user font set...
// If the fontSet matches the family, we must not look for a platform
// font of the same name, even if we fail to actually get a fontEntry
// here; we'll fall back to the next name in the CSS font-family list.
if (mUserFontSet) {
// Add userfonts to the fontlist whether already loaded
// or not. Loading is initiated during font matching.
gfxFontFamily* family = mUserFontSet->LookupFamily(aName);
if (family) {
aFamilyList.AppendElement(family);
return;
}
}
// Not known in the user font set ==> check system fonts
gfxPlatformFontList::PlatformFontList()->FindAndAddFamilies(
StyleGenericFontFamily::None, aName, &aFamilyList,
aQuotedName ? gfxPlatformFontList::FindFamiliesFlags::eQuotedFamilyName
: gfxPlatformFontList::FindFamiliesFlags(0),
&mStyle, mLanguage.get(), mDevToCssSize);
}
void gfxFontGroup::AddFamilyToFontList(gfxFontFamily* aFamily,
StyleGenericFontFamily aGeneric) {
if (!aFamily) {
MOZ_ASSERT_UNREACHABLE("don't try to add a null font family!");
return;
}
AutoTArray<gfxFontEntry*, 4> fontEntryList;
aFamily->FindAllFontsForStyle(mStyle, fontEntryList);
// add these to the fontlist
for (gfxFontEntry* fe : fontEntryList) {
if (!HasFont(fe)) {
FamilyFace ff(aFamily, fe, aGeneric);
if (fe->mIsUserFontContainer) {
ff.CheckState(mSkipDrawing);
}
mFonts.AppendElement(ff);
}
}
// for a family marked as "check fallback faces", only mark the last
// entry so that fallbacks for a family are only checked once
if (aFamily->CheckForFallbackFaces() && !fontEntryList.IsEmpty() &&
!mFonts.IsEmpty()) {
mFonts.LastElement().SetCheckForFallbackFaces();
}
}
void gfxFontGroup::AddFamilyToFontList(fontlist::Family* aFamily,
StyleGenericFontFamily aGeneric) {
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
if (!aFamily->IsInitialized()) {
if (!NS_IsMainThread()) {
// If we need to initialize a Family record, but we're on a style
// worker thread, we have to defer it.
ServoStyleSet* set = ServoStyleSet::Current();
MOZ_ASSERT(set);
set->AppendTask(PostTraversalTask::InitializeFamily(aFamily));
set->AppendTask(PostTraversalTask::FontInfoUpdate(set));
return;
}
if (!pfl->InitializeFamily(aFamily)) {
return;
}
}
AutoTArray<fontlist::Face*, 4> faceList;
aFamily->FindAllFacesForStyle(pfl->SharedFontList(), mStyle, faceList);
for (auto face : faceList) {
gfxFontEntry* fe = pfl->GetOrCreateFontEntry(face, aFamily);
if (fe && !HasFont(fe)) {
FamilyFace ff(aFamily, fe, aGeneric);
mFonts.AppendElement(ff);
}
}
}
bool gfxFontGroup::HasFont(const gfxFontEntry* aFontEntry) {
for (auto& f : mFonts) {
if (f.FontEntry() == aFontEntry) {
return true;
}
}
return false;
}
gfxFont* gfxFontGroup::GetFontAt(int32_t i, uint32_t aCh, bool* aLoading) {
if (uint32_t(i) >= mFonts.Length()) {
return nullptr;
}
FamilyFace& ff = mFonts[i];
if (ff.IsInvalid() || ff.IsLoading()) {
return nullptr;
}
gfxFont* font = ff.Font();
if (!font) {
gfxFontEntry* fe = ff.FontEntry();
if (!fe) {
return nullptr;
}
gfxCharacterMap* unicodeRangeMap = nullptr;
if (fe->mIsUserFontContainer) {
gfxUserFontEntry* ufe = static_cast<gfxUserFontEntry*>(fe);
if (ufe->LoadState() == gfxUserFontEntry::STATUS_NOT_LOADED &&
ufe->CharacterInUnicodeRange(aCh) && !*aLoading) {
ufe->Load();
ff.CheckState(mSkipDrawing);
*aLoading = ff.IsLoading();
}
fe = ufe->GetPlatformFontEntry();
if (!fe) {
return nullptr;
}
unicodeRangeMap = ufe->GetUnicodeRangeMap();
}
font = fe->FindOrMakeFont(&mStyle, unicodeRangeMap);
if (!font || !font->Valid()) {
ff.SetInvalid();
// We can't just |delete font| here, in case there are other
// references to the object FindOrMakeFont returned.
RefPtr<gfxFont> ref(font);
return nullptr;
}
ff.SetFont(font);
}
return font;
}
void gfxFontGroup::FamilyFace::CheckState(bool& aSkipDrawing) {
gfxFontEntry* fe = FontEntry();
if (!fe) {
return;
}
if (fe->mIsUserFontContainer) {
gfxUserFontEntry* ufe = static_cast<gfxUserFontEntry*>(fe);
gfxUserFontEntry::UserFontLoadState state = ufe->LoadState();
switch (state) {
case gfxUserFontEntry::STATUS_LOAD_PENDING:
case gfxUserFontEntry::STATUS_LOADING:
SetLoading(true);
break;
case gfxUserFontEntry::STATUS_FAILED:
SetInvalid();
// fall-thru to the default case
[[fallthrough]];
default:
SetLoading(false);
}
if (ufe->WaitForUserFont()) {
aSkipDrawing = true;
}
}
}
bool gfxFontGroup::FamilyFace::EqualsUserFont(
const gfxUserFontEntry* aUserFont) const {
gfxFontEntry* fe = FontEntry();
// if there's a font, the entry is the underlying platform font
if (mFontCreated) {
gfxFontEntry* pfe = aUserFont->GetPlatformFontEntry();
if (pfe == fe) {
return true;
}
} else if (fe == aUserFont) {
return true;
}
return false;
}
gfxFont* gfxFontGroup::GetDefaultFont() {
if (mDefaultFont) {
return mDefaultFont.get();
}
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
FontFamily family = pfl->GetDefaultFont(&mStyle);
MOZ_ASSERT(!family.IsNull(),
"invalid default font returned by GetDefaultFont");
gfxFontEntry* fe = nullptr;
if (family.mIsShared) {
fontlist::Family* fam = family.mShared;
if (!fam->IsInitialized()) {
// If this fails, FindFaceForStyle will just safely return nullptr
Unused << pfl->InitializeFamily(fam);
}
fontlist::Face* face = fam->FindFaceForStyle(pfl->SharedFontList(), mStyle);
if (face) {
fe = pfl->GetOrCreateFontEntry(face, fam);
}
} else {
fe = family.mUnshared->FindFontForStyle(mStyle);
}
if (fe) {
mDefaultFont = fe->FindOrMakeFont(&mStyle);
}
uint32_t numInits, loaderState;
pfl->GetFontlistInitInfo(numInits, loaderState);
MOZ_ASSERT(numInits != 0,
"must initialize system fontlist before getting default font!");
uint32_t numFonts = 0;
if (!mDefaultFont) {
// Try for a "font of last resort...."
// Because an empty font list would be Really Bad for later code
// that assumes it will be able to get valid metrics for layout,
// just look for the first usable font and put in the list.
// (see bug 554544)
if (pfl->SharedFontList()) {
fontlist::FontList* list = pfl->SharedFontList();
numFonts = list->NumFamilies();
fontlist::Family* families = list->Families();
for (uint32_t i = 0; i < numFonts; ++i) {
fontlist::Family* fam = &families[i];
if (!fam->IsInitialized()) {
Unused << pfl->InitializeFamily(fam);
}
fontlist::Face* face =
fam->FindFaceForStyle(pfl->SharedFontList(), mStyle);
if (face) {
fe = pfl->GetOrCreateFontEntry(face, fam);
if (fe) {
mDefaultFont = fe->FindOrMakeFont(&mStyle);
if (mDefaultFont) {
break;
}
NS_WARNING("FindOrMakeFont failed");
}
}
}
} else {
AutoTArray<RefPtr<gfxFontFamily>, 200> familyList;
pfl->GetFontFamilyList(familyList);
numFonts = familyList.Length();
for (uint32_t i = 0; i < numFonts; ++i) {
gfxFontEntry* fe = familyList[i]->FindFontForStyle(mStyle, true);
if (fe) {
mDefaultFont = fe->FindOrMakeFont(&mStyle);
if (mDefaultFont) {
break;
}
}
}
}
}
if (!mDefaultFont && pfl->SharedFontList() && !XRE_IsParentProcess()) {
// If we're a content process, it's possible this is failing because the
// chrome process has just updated the shared font list and we haven't yet
// refreshed our reference to it. If that's the case, update and retry.
// But if we're not on the main thread, we can't do this, so just use
// the platform default font directly.
if (NS_IsMainThread()) {
uint32_t oldGeneration = pfl->SharedFontList()->GetGeneration();
pfl->UpdateFontList();
if (pfl->SharedFontList()->GetGeneration() != oldGeneration) {
return GetDefaultFont();
}
} else {
gfxFontEntry* fe = pfl->GetDefaultFontEntry();
if (fe) {
return fe->FindOrMakeFont(&mStyle);
}
}
}
if (!mDefaultFont) {
// an empty font list at this point is fatal; we're not going to
// be able to do even the most basic layout operations
// annotate crash report with fontlist info
nsAutoCString fontInitInfo;
fontInitInfo.AppendPrintf("no fonts - init: %d fonts: %d loader: %d",
numInits, numFonts, loaderState);
#ifdef XP_WIN
bool dwriteEnabled = gfxWindowsPlatform::GetPlatform()->DWriteEnabled();
double upTime = (double)GetTickCount();
fontInitInfo.AppendPrintf(" backend: %s system-uptime: %9.3f sec",
dwriteEnabled ? "directwrite" : "gdi",
upTime / 1000);
#endif
gfxCriticalError() << fontInitInfo.get();
char msg[256]; // CHECK buffer length if revising message below
nsAutoCString familiesString;
mFamilyList.ToString(familiesString);
SprintfLiteral(msg, "unable to find a usable font (%.220s)",
familiesString.get());
MOZ_CRASH_UNSAFE(msg);
}
return mDefaultFont.get();
}
gfxFont* gfxFontGroup::GetFirstValidFont(uint32_t aCh,
StyleGenericFontFamily* aGeneric) {
uint32_t count = mFonts.Length();
bool loading = false;
for (uint32_t i = 0; i < count; ++i) {
FamilyFace& ff = mFonts[i];
if (ff.IsInvalid()) {
continue;
}
// already have a font?
gfxFont* font = ff.Font();
if (font) {
if (aGeneric) {
*aGeneric = ff.Generic();
}
return font;
}
// Need to build a font, loading userfont if not loaded. In
// cases where unicode range might apply, use the character
// provided.
gfxFontEntry* fe = ff.FontEntry();
if (fe && fe->mIsUserFontContainer) {
gfxUserFontEntry* ufe = static_cast<gfxUserFontEntry*>(fe);
bool inRange = ufe->CharacterInUnicodeRange(aCh);
if (inRange) {
if (!loading &&
ufe->LoadState() == gfxUserFontEntry::STATUS_NOT_LOADED) {
ufe->Load();
ff.CheckState(mSkipDrawing);
}
if (ff.IsLoading()) {
loading = true;
}
}
if (ufe->LoadState() != gfxUserFontEntry::STATUS_LOADED || !inRange) {
continue;
}
}
font = GetFontAt(i, aCh, &loading);
if (font) {
if (aGeneric) {
*aGeneric = ff.Generic();
}
return font;
}
}
if (aGeneric) {
*aGeneric = StyleGenericFontFamily::None;
}
return GetDefaultFont();
}
gfxFont* gfxFontGroup::GetFirstMathFont() {
uint32_t count = mFonts.Length();
for (uint32_t i = 0; i < count; ++i) {
gfxFont* font = GetFontAt(i);
if (font && font->TryGetMathTable()) {
return font;
}
}
return nullptr;
}
bool gfxFontGroup::IsInvalidChar(uint8_t ch) {
return ((ch & 0x7f) < 0x20 || ch == 0x7f);
}
bool gfxFontGroup::IsInvalidChar(char16_t ch) {
// All printable 7-bit ASCII values are OK
if (ch >= ' ' && ch < 0x7f) {
return false;
}
// No point in sending non-printing control chars through font shaping
if (ch <= 0x9f) {
return true;
}
// Word-separating format/bidi control characters are not shaped as part
// of words.
return (((ch & 0xFF00) == 0x2000 /* Unicode control character */ &&
(ch == 0x200B /*ZWSP*/ || ch == 0x2028 /*LSEP*/ ||
ch == 0x2029 /*PSEP*/ || ch == 0x2060 /*WJ*/)) ||
ch == 0xfeff /*ZWNBSP*/ || IsBidiControl(ch));
}
already_AddRefed<gfxTextRun> gfxFontGroup::MakeEmptyTextRun(
const Parameters* aParams, gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2) {
aFlags |= ShapedTextFlags::TEXT_IS_8BIT;
return gfxTextRun::Create(aParams, 0, this, aFlags, aFlags2);
}
already_AddRefed<gfxTextRun> gfxFontGroup::MakeSpaceTextRun(
const Parameters* aParams, gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2) {
aFlags |= ShapedTextFlags::TEXT_IS_8BIT;
RefPtr<gfxTextRun> textRun =
gfxTextRun::Create(aParams, 1, this, aFlags, aFlags2);
if (!textRun) {
return nullptr;
}
gfx::ShapedTextFlags orientation = aFlags & ShapedTextFlags::TEXT_ORIENT_MASK;
if (orientation == ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED) {
orientation = ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT;
}
gfxFont* font = GetFirstValidFont();
if (MOZ_UNLIKELY(GetStyle()->size == 0) ||
MOZ_UNLIKELY(GetStyle()->sizeAdjust == 0.0f)) {
// Short-circuit for size-0 fonts, as Windows and ATSUI can't handle
// them, and always create at least size 1 fonts, i.e. they still
// render something for size 0 fonts.
textRun->AddGlyphRun(font, FontMatchType::Kind::kUnspecified, 0, false,
orientation, false);
} else {
if (font->GetSpaceGlyph()) {
// Normally, the font has a cached space glyph, so we can avoid
// the cost of calling FindFontForChar.
textRun->SetSpaceGlyph(font, aParams->mDrawTarget, 0, orientation);
} else {
// In case the primary font doesn't have <space> (bug 970891),
// find one that does.
FontMatchType matchType;
gfxFont* spaceFont =
FindFontForChar(' ', 0, 0, Script::LATIN, nullptr, &matchType);
if (spaceFont) {
textRun->SetSpaceGlyph(spaceFont, aParams->mDrawTarget, 0, orientation);
}
}
}
// Note that the gfxGlyphExtents glyph bounds storage for the font will
// always contain an entry for the font's space glyph, so we don't have
// to call FetchGlyphExtents here.
return textRun.forget();
}
template <typename T>
already_AddRefed<gfxTextRun> gfxFontGroup::MakeBlankTextRun(
const T* aString, uint32_t aLength, const Parameters* aParams,
gfx::ShapedTextFlags aFlags, nsTextFrameUtils::Flags aFlags2) {
RefPtr<gfxTextRun> textRun =
gfxTextRun::Create(aParams, aLength, this, aFlags, aFlags2);
if (!textRun) {
return nullptr;
}
gfx::ShapedTextFlags orientation = aFlags & ShapedTextFlags::TEXT_ORIENT_MASK;
if (orientation == ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED) {
orientation = ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT;
}
textRun->AddGlyphRun(GetFirstValidFont(), FontMatchType::Kind::kUnspecified,
0, false, orientation, false);
for (uint32_t i = 0; i < aLength; i++) {
if (aString[i] == '\n') {
textRun->SetIsNewline(i);
} else if (aString[i] == '\t') {
textRun->SetIsTab(i);
}
}
return textRun.forget();
}
already_AddRefed<gfxTextRun> gfxFontGroup::MakeHyphenTextRun(
DrawTarget* aDrawTarget, uint32_t aAppUnitsPerDevUnit) {
// only use U+2010 if it is supported by the first font in the group;
// it's better to use ASCII '-' from the primary font than to fall back to
// U+2010 from some other, possibly poorly-matching face
static const char16_t hyphen = 0x2010;
gfxFont* font = GetFirstValidFont(uint32_t(hyphen));
if (font->HasCharacter(hyphen)) {
return MakeTextRun(&hyphen, 1, aDrawTarget, aAppUnitsPerDevUnit,
ShapedTextFlags(), nsTextFrameUtils::Flags(), nullptr);
}
static const uint8_t dash = '-';
return MakeTextRun(&dash, 1, aDrawTarget, aAppUnitsPerDevUnit,
ShapedTextFlags(), nsTextFrameUtils::Flags(), nullptr);
}
gfxFloat gfxFontGroup::GetHyphenWidth(
const gfxTextRun::PropertyProvider* aProvider) {
if (mHyphenWidth < 0) {
RefPtr<DrawTarget> dt(aProvider->GetDrawTarget());
if (dt) {
RefPtr<gfxTextRun> hyphRun(
MakeHyphenTextRun(dt, aProvider->GetAppUnitsPerDevUnit()));
mHyphenWidth = hyphRun.get() ? hyphRun->GetAdvanceWidth() : 0;
}
}
return mHyphenWidth;
}
already_AddRefed<gfxTextRun> gfxFontGroup::MakeTextRun(
const uint8_t* aString, uint32_t aLength, const Parameters* aParams,
gfx::ShapedTextFlags aFlags, nsTextFrameUtils::Flags aFlags2,
gfxMissingFontRecorder* aMFR) {
if (aLength == 0) {
return MakeEmptyTextRun(aParams, aFlags, aFlags2);
}
if (aLength == 1 && aString[0] == ' ') {
return MakeSpaceTextRun(aParams, aFlags, aFlags2);
}
aFlags |= ShapedTextFlags::TEXT_IS_8BIT;
if (MOZ_UNLIKELY(GetStyle()->size == 0) ||
MOZ_UNLIKELY(GetStyle()->sizeAdjust == 0.0f)) {
// Short-circuit for size-0 fonts, as Windows and ATSUI can't handle
// them, and always create at least size 1 fonts, i.e. they still
// render something for size 0 fonts.
return MakeBlankTextRun(aString, aLength, aParams, aFlags, aFlags2);
}
RefPtr<gfxTextRun> textRun =
gfxTextRun::Create(aParams, aLength, this, aFlags, aFlags2);
if (!textRun) {
return nullptr;
}
InitTextRun(aParams->mDrawTarget, textRun.get(), aString, aLength, aMFR);
textRun->FetchGlyphExtents(aParams->mDrawTarget);
return textRun.forget();
}
already_AddRefed<gfxTextRun> gfxFontGroup::MakeTextRun(
const char16_t* aString, uint32_t aLength, const Parameters* aParams,
gfx::ShapedTextFlags aFlags, nsTextFrameUtils::Flags aFlags2,
gfxMissingFontRecorder* aMFR) {
if (aLength == 0) {
return MakeEmptyTextRun(aParams, aFlags, aFlags2);
}
if (aLength == 1 && aString[0] == ' ') {
return MakeSpaceTextRun(aParams, aFlags, aFlags2);
}
if (MOZ_UNLIKELY(GetStyle()->size == 0) ||
MOZ_UNLIKELY(GetStyle()->sizeAdjust == 0.0f)) {
return MakeBlankTextRun(aString, aLength, aParams, aFlags, aFlags2);
}
RefPtr<gfxTextRun> textRun =
gfxTextRun::Create(aParams, aLength, this, aFlags, aFlags2);
if (!textRun) {
return nullptr;
}
InitTextRun(aParams->mDrawTarget, textRun.get(), aString, aLength, aMFR);
textRun->FetchGlyphExtents(aParams->mDrawTarget);
return textRun.forget();
}
template <typename T>
void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun,
const T* aString, uint32_t aLength,
gfxMissingFontRecorder* aMFR) {
NS_ASSERTION(aLength > 0, "don't call InitTextRun for a zero-length run");
// we need to do numeral processing even on 8-bit text,
// in case we're converting Western to Hindi/Arabic digits
int32_t numOption = gfxPlatform::GetPlatform()->GetBidiNumeralOption();
UniquePtr<char16_t[]> transformedString;
if (numOption != IBMBIDI_NUMERAL_NOMINAL) {
// scan the string for numerals that may need to be transformed;
// if we find any, we'll make a local copy here and use that for
// font matching and glyph generation/shaping
bool prevIsArabic =
!!(aTextRun->GetFlags() & ShapedTextFlags::TEXT_INCOMING_ARABICCHAR);
for (uint32_t i = 0; i < aLength; ++i) {
char16_t origCh = aString[i];
char16_t newCh = HandleNumberInChar(origCh, prevIsArabic, numOption);
if (newCh != origCh) {
if (!transformedString) {
transformedString = MakeUnique<char16_t[]>(aLength);
if (sizeof(T) == sizeof(char16_t)) {
memcpy(transformedString.get(), aString, i * sizeof(char16_t));
} else {
for (uint32_t j = 0; j < i; ++j) {
transformedString[j] = aString[j];
}
}
}
}
if (transformedString) {
transformedString[i] = newCh;
}
prevIsArabic = IS_ARABIC_CHAR(newCh);
}
}
LogModule* log = mStyle.systemFont ? gfxPlatform::GetLog(eGfxLog_textrunui)
: gfxPlatform::GetLog(eGfxLog_textrun);
// variant fallback handling may end up passing through this twice
bool redo;
do {
redo = false;
if (sizeof(T) == sizeof(uint8_t) && !transformedString) {
if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Warning))) {
nsAutoCString lang;
mLanguage->ToUTF8String(lang);
nsAutoCString families;
mFamilyList.ToString(families);
nsAutoCString str((const char*)aString, aLength);
nsAutoString styleString;
nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString);
MOZ_LOG(
log, LogLevel::Warning,
("(%s) fontgroup: [%s] default: %s lang: %s script: %d "
"len %d weight: %g stretch: %g%% style: %s size: %6.2f %zu-byte "
"TEXTRUN [%s] ENDTEXTRUN\n",
(mStyle.systemFont ? "textrunui" : "textrun"), families.get(),
(mFamilyList.GetDefaultFontType() == StyleGenericFontFamily::Serif
? "serif"
: (mFamilyList.GetDefaultFontType() ==
StyleGenericFontFamily::SansSerif
? "sans-serif"
: "none")),
lang.get(), static_cast<int>(Script::LATIN), aLength,
mStyle.weight.ToFloat(), mStyle.stretch.Percentage(),
NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T),
str.get()));
}
// the text is still purely 8-bit; bypass the script-run itemizer
// and treat it as a single Latin run
InitScriptRun(aDrawTarget, aTextRun, aString, 0, aLength, Script::LATIN,
aMFR);
} else {
const char16_t* textPtr;
if (transformedString) {
textPtr = transformedString.get();
} else {
// typecast to avoid compilation error for the 8-bit version,
// even though this is dead code in that case
textPtr = reinterpret_cast<const char16_t*>(aString);
}
// split into script runs so that script can potentially influence
// the font matching process below
gfxScriptItemizer scriptRuns(textPtr, aLength);
uint32_t runStart = 0, runLimit = aLength;
Script runScript = Script::LATIN;
while (scriptRuns.Next(runStart, runLimit, runScript)) {
if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Warning))) {
nsAutoCString lang;
mLanguage->ToUTF8String(lang);
nsAutoCString families;
mFamilyList.ToString(families);
nsAutoString styleString;
nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString);
uint32_t runLen = runLimit - runStart;
MOZ_LOG(
log, LogLevel::Warning,
("(%s) fontgroup: [%s] default: %s lang: %s script: %d "
"len %d weight: %g stretch: %g%% style: %s size: %6.2f "
"%zu-byte TEXTRUN [%s] ENDTEXTRUN\n",
(mStyle.systemFont ? "textrunui" : "textrun"), families.get(),
(mFamilyList.GetDefaultFontType() ==
StyleGenericFontFamily::Serif
? "serif"
: (mFamilyList.GetDefaultFontType() ==
StyleGenericFontFamily::SansSerif
? "sans-serif"
: "none")),
lang.get(), static_cast<int>(runScript), runLen,
mStyle.weight.ToFloat(), mStyle.stretch.Percentage(),
NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T),
NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get()));
}
InitScriptRun(aDrawTarget, aTextRun, textPtr + runStart, runStart,
runLimit - runStart, runScript, aMFR);
}
}
// if shaping was aborted due to lack of feature support, clear out
// glyph runs and redo shaping with fallback forced on
if (aTextRun->GetShapingState() == gfxTextRun::eShapingState_Aborted) {
redo = true;
aTextRun->SetShapingState(gfxTextRun::eShapingState_ForceFallbackFeature);
aTextRun->ClearGlyphsAndCharacters();
}
} while (redo);
if (sizeof(T) == sizeof(char16_t) && aLength > 0) {
gfxTextRun::CompressedGlyph* glyph = aTextRun->GetCharacterGlyphs();
if (!glyph->IsSimpleGlyph()) {
glyph->SetClusterStart(true);
}
}
// It's possible for CoreText to omit glyph runs if it decides they contain
// only invisibles (e.g., U+FEFF, see reftest 474417-1). In this case, we
// need to eliminate them from the glyph run array to avoid drawing "partial
// ligatures" with the wrong font.
// We don't do this during InitScriptRun (or gfxFont::InitTextRun) because
// it will iterate back over all glyphruns in the textrun, which leads to
// pathologically-bad perf in the case where a textrun contains many script
// changes (see bug 680402) - we'd end up re-sanitizing all the earlier runs
// every time a new script subrun is processed.
aTextRun->SanitizeGlyphRuns();
aTextRun->SortGlyphRuns();
}
static inline bool IsPUA(uint32_t aUSV) {
// We could look up the General Category of the codepoint here,
// but it's simpler to check PUA codepoint ranges.
return (aUSV >= 0xE000 && aUSV <= 0xF8FF) || (aUSV >= 0xF0000);
}
template <typename T>
void gfxFontGroup::InitScriptRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun,
const T* aString, // text for this script run,
// not the entire textrun
uint32_t aOffset, // position of the script
// run within the textrun
uint32_t aLength, // length of the script run
Script aRunScript,
gfxMissingFontRecorder* aMFR) {
NS_ASSERTION(aLength > 0, "don't call InitScriptRun for a 0-length run");
NS_ASSERTION(aTextRun->GetShapingState() != gfxTextRun::eShapingState_Aborted,
"don't call InitScriptRun with aborted shaping state");
// confirm the load state of userfonts in the list
if (mUserFontSet && mCurrGeneration != mUserFontSet->GetGeneration()) {
UpdateUserFonts();
}
gfxFont* mainFont = GetFirstValidFont();
ShapedTextFlags orientation =
aTextRun->GetFlags() & ShapedTextFlags::TEXT_ORIENT_MASK;
if (orientation != ShapedTextFlags::TEXT_ORIENT_HORIZONTAL &&
(aRunScript == Script::MONGOLIAN || aRunScript == Script::PHAGS_PA)) {
// Mongolian and Phags-pa text should ignore text-orientation and
// always render in its "native" vertical mode, implemented by fonts
// as sideways-right (i.e as if shaped horizontally, and then the
// entire line is rotated to render vertically). Therefore, we ignore
// the aOrientation value from the textrun's flags, and make all
// vertical Mongolian/Phags-pa use sideways-right.
orientation = ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT;
}
uint32_t runStart = 0;
AutoTArray<TextRange, 3> fontRanges;
ComputeRanges(fontRanges, aString, aLength, aRunScript, orientation);
uint32_t numRanges = fontRanges.Length();
bool missingChars = false;
bool isCJK = gfxTextRun::IsCJKScript(aRunScript);
for (uint32_t r = 0; r < numRanges; r++) {
const TextRange& range = fontRanges[r];
uint32_t matchedLength = range.Length();
gfxFont* matchedFont = range.font;
// create the glyph run for this range
if (matchedFont && mStyle.noFallbackVariantFeatures) {
// common case - just do glyph layout and record the
// resulting positioned glyphs
aTextRun->AddGlyphRun(matchedFont, range.matchType, aOffset + runStart,
(matchedLength > 0), range.orientation, isCJK);
if (!matchedFont->SplitAndInitTextRun(
aDrawTarget, aTextRun, aString + runStart, aOffset + runStart,
matchedLength, aRunScript, mLanguage, range.orientation)) {
// glyph layout failed! treat as missing glyphs
matchedFont = nullptr;
}
} else if (matchedFont) {
// shape with some variant feature that requires fallback handling
bool petiteToSmallCaps = false;
bool syntheticLower = false;
bool syntheticUpper = false;
if (mStyle.variantSubSuper != NS_FONT_VARIANT_POSITION_NORMAL &&
(aTextRun->GetShapingState() ==
gfxTextRun::eShapingState_ForceFallbackFeature ||
!matchedFont->SupportsSubSuperscript(mStyle.variantSubSuper, aString,
aLength, aRunScript))) {
// fallback for subscript/superscript variant glyphs
// if the feature was already used, abort and force
// fallback across the entire textrun
gfxTextRun::ShapingState ss = aTextRun->GetShapingState();
if (ss == gfxTextRun::eShapingState_Normal) {
aTextRun->SetShapingState(
gfxTextRun::eShapingState_ShapingWithFallback);
} else if (ss == gfxTextRun::eShapingState_ShapingWithFeature) {
aTextRun->SetShapingState(gfxTextRun::eShapingState_Aborted);
return;
}
RefPtr<gfxFont> subSuperFont = matchedFont->GetSubSuperscriptFont(
aTextRun->GetAppUnitsPerDevUnit());
aTextRun->AddGlyphRun(subSuperFont, range.matchType, aOffset + runStart,
(matchedLength > 0), range.orientation, isCJK);
if (!subSuperFont->SplitAndInitTextRun(
aDrawTarget, aTextRun, aString + runStart, aOffset + runStart,
matchedLength, aRunScript, mLanguage, range.orientation)) {
// glyph layout failed! treat as missing glyphs
matchedFont = nullptr;
}
} else if (mStyle.variantCaps != NS_FONT_VARIANT_CAPS_NORMAL &&
!matchedFont->SupportsVariantCaps(
aRunScript, mStyle.variantCaps, petiteToSmallCaps,
syntheticLower, syntheticUpper)) {
// fallback for small-caps variant glyphs
if (!matchedFont->InitFakeSmallCapsRun(
aDrawTarget, aTextRun, aString + runStart, aOffset + runStart,
matchedLength, range.matchType, range.orientation, aRunScript,
mExplicitLanguage ? mLanguage.get() : nullptr, syntheticLower,
syntheticUpper)) {
matchedFont = nullptr;
}
} else {
// shape normally with variant feature enabled
gfxTextRun::ShapingState ss = aTextRun->GetShapingState();
// adjust the shaping state if necessary
if (ss == gfxTextRun::eShapingState_Normal) {
aTextRun->SetShapingState(
gfxTextRun::eShapingState_ShapingWithFeature);
} else if (ss == gfxTextRun::eShapingState_ShapingWithFallback) {
// already have shaping results using fallback, need to redo
aTextRun->SetShapingState(gfxTextRun::eShapingState_Aborted);
return;
}
// do glyph layout and record the resulting positioned glyphs
aTextRun->AddGlyphRun(matchedFont, range.matchType, aOffset + runStart,
(matchedLength > 0), range.orientation, isCJK);
if (!matchedFont->SplitAndInitTextRun(
aDrawTarget, aTextRun, aString + runStart, aOffset + runStart,
matchedLength, aRunScript, mLanguage, range.orientation)) {
// glyph layout failed! treat as missing glyphs
matchedFont = nullptr;
}
}
} else {
aTextRun->AddGlyphRun(mainFont, FontMatchType::Kind::kFontGroup,
aOffset + runStart, (matchedLength > 0),
range.orientation, isCJK);
}
if (!matchedFont) {
// We need to set cluster boundaries (and mark spaces) so that
// surrogate pairs, combining characters, etc behave properly,
// even if we don't have glyphs for them
aTextRun->SetupClusterBoundaries(aOffset + runStart, aString + runStart,
matchedLength);
// various "missing" characters may need special handling,
// so we check for them here
uint32_t runLimit = runStart + matchedLength;
for (uint32_t index = runStart; index < runLimit; index++) {
T ch = aString[index];
// tab and newline are not to be displayed as hexboxes,
// but do need to be recorded in the textrun
if (ch == '\n') {
aTextRun->SetIsNewline(aOffset + index);
continue;
}
if (ch == '\t') {
aTextRun->SetIsTab(aOffset + index);
continue;
}
// for 16-bit textruns only, check for surrogate pairs and
// special Unicode spaces; omit these checks in 8-bit runs
if (sizeof(T) == sizeof(char16_t)) {
if (index + 1 < aLength &&
NS_IS_SURROGATE_PAIR(ch, aString[index + 1])) {
uint32_t usv = SURROGATE_TO_UCS4(ch, aString[index + 1]);
aTextRun->SetMissingGlyph(aOffset + index, usv, mainFont);
index++;
if (!mSkipDrawing && !IsPUA(usv)) {
missingChars = true;
if (mFontMatchingStats) {
mFontMatchingStats->mFallbacks |= FallbackTypes::MissingFont;
}
}
continue;
}
// check if this is a known Unicode whitespace character that
// we can render using the space glyph with a custom width
gfxFloat wid = mainFont->SynthesizeSpaceWidth(ch);
if (wid >= 0.0) {
nscoord advance =
aTextRun->GetAppUnitsPerDevUnit() * floor(wid + 0.5);
if (gfxShapedText::CompressedGlyph::IsSimpleAdvance(advance)) {
aTextRun->GetCharacterGlyphs()[aOffset + index].SetSimpleGlyph(
advance, mainFont->GetSpaceGlyph());
} else {
gfxTextRun::DetailedGlyph detailedGlyph;
detailedGlyph.mGlyphID = mainFont->GetSpaceGlyph();
detailedGlyph.mAdvance = advance;
aTextRun->SetDetailedGlyphs(aOffset + index, 1, &detailedGlyph);
}
continue;
}
}
if (IsInvalidChar(ch)) {
// invalid chars are left as zero-width/invisible
continue;
}
// record char code so we can draw a box with the Unicode value
aTextRun->SetMissingGlyph(aOffset + index, ch, mainFont);
if (!mSkipDrawing && !IsPUA(ch)) {
missingChars = true;
if (mFontMatchingStats) {
mFontMatchingStats->mFallbacks |= FallbackTypes::MissingFont;
}
}
}
}
runStart += matchedLength;
}
if (aMFR && missingChars) {
aMFR->RecordScript(aRunScript);
}
}
gfxTextRun* gfxFontGroup::GetEllipsisTextRun(
int32_t aAppUnitsPerDevPixel, gfx::ShapedTextFlags aFlags,
LazyReferenceDrawTargetGetter& aRefDrawTargetGetter) {
MOZ_ASSERT(!(aFlags & ~ShapedTextFlags::TEXT_ORIENT_MASK),
"flags here should only be used to specify orientation");
if (mCachedEllipsisTextRun &&
(mCachedEllipsisTextRun->GetFlags() &
ShapedTextFlags::TEXT_ORIENT_MASK) == aFlags &&
mCachedEllipsisTextRun->GetAppUnitsPerDevUnit() == aAppUnitsPerDevPixel) {
return mCachedEllipsisTextRun.get();
}
// Use a Unicode ellipsis if the font supports it,
// otherwise use three ASCII periods as fallback.
gfxFont* firstFont = GetFirstValidFont(uint32_t(kEllipsisChar[0]));
nsString ellipsis =
firstFont->HasCharacter(kEllipsisChar[0])
? nsDependentString(kEllipsisChar, ArrayLength(kEllipsisChar) - 1)
: nsDependentString(kASCIIPeriodsChar,
ArrayLength(kASCIIPeriodsChar) - 1);
RefPtr<DrawTarget> refDT = aRefDrawTargetGetter.GetRefDrawTarget();
Parameters params = {refDT, nullptr, nullptr,
nullptr, 0, aAppUnitsPerDevPixel};
mCachedEllipsisTextRun =
MakeTextRun(ellipsis.get(), ellipsis.Length(), ¶ms, aFlags,
nsTextFrameUtils::Flags(), nullptr);
if (!mCachedEllipsisTextRun) {
return nullptr;
}
// don't let the presence of a cached ellipsis textrun prolong the
// fontgroup's life
mCachedEllipsisTextRun->ReleaseFontGroup();
return mCachedEllipsisTextRun.get();
}
gfxFont* gfxFontGroup::FindFallbackFaceForChar(
gfxFontFamily* aFamily, uint32_t aCh, uint32_t aNextCh,
eFontPresentation aPresentation) {
GlobalFontMatch data(aCh, aNextCh, mStyle, aPresentation);
aFamily->SearchAllFontsForChar(&data);
gfxFontEntry* fe = data.mBestMatch;
if (!fe) {
return nullptr;
}
return fe->FindOrMakeFont(&mStyle);
}
gfxFont* gfxFontGroup::FindFallbackFaceForChar(
fontlist::Family* aFamily, uint32_t aCh, uint32_t aNextCh,
eFontPresentation aPresentation) {
auto* pfl = gfxPlatformFontList::PlatformFontList();
auto* list = pfl->SharedFontList();
// If async fallback is enabled, and the family isn't fully initialized yet,
// just start the async cmap loading and return.
if (!aFamily->IsFullyInitialized() &&
StaticPrefs::gfx_font_rendering_fallback_async()) {
pfl->StartCmapLoadingFromFamily(aFamily - list->Families());
return nullptr;
}
GlobalFontMatch data(aCh, aNextCh, mStyle, aPresentation);
aFamily->SearchAllFontsForChar(list, &data);
gfxFontEntry* fe = data.mBestMatch;
if (!fe) {
return nullptr;
}
return fe->FindOrMakeFont(&mStyle);
}
gfxFont* gfxFontGroup::FindFallbackFaceForChar(
const FamilyFace& aFamily, uint32_t aCh, uint32_t aNextCh,
eFontPresentation aPresentation) {
if (aFamily.IsSharedFamily()) {
return FindFallbackFaceForChar(aFamily.SharedFamily(), aCh, aNextCh,
aPresentation);
}
return FindFallbackFaceForChar(aFamily.OwnedFamily(), aCh, aNextCh,
aPresentation);
}
gfxFloat gfxFontGroup::GetUnderlineOffset() {
if (mUnderlineOffset == UNDERLINE_OFFSET_NOT_SET) {
// if the fontlist contains a bad underline font, make the underline
// offset the min of the first valid font and bad font underline offsets
uint32_t len = mFonts.Length();
for (uint32_t i = 0; i < len; i++) {
FamilyFace& ff = mFonts[i];
gfxFontEntry* fe = ff.FontEntry();
if (!fe) {
continue;
}
if (!fe->mIsUserFontContainer && !fe->IsUserFont() &&
((ff.IsSharedFamily() && ff.SharedFamily() &&
ff.SharedFamily()->IsBadUnderlineFamily()) ||
(!ff.IsSharedFamily() && ff.OwnedFamily() &&
ff.OwnedFamily()->IsBadUnderlineFamily()))) {
gfxFont* font = GetFontAt(i);
if (!font) {
continue;
}
gfxFloat bad =
font->GetMetrics(nsFontMetrics::eHorizontal).underlineOffset;
gfxFloat first = GetFirstValidFont()
->GetMetrics(nsFontMetrics::eHorizontal)
.underlineOffset;
mUnderlineOffset = std::min(first, bad);
return mUnderlineOffset;
}
}
// no bad underline fonts, use the first valid font's metric
mUnderlineOffset = GetFirstValidFont()
->GetMetrics(nsFontMetrics::eHorizontal)
.underlineOffset;
}
return mUnderlineOffset;
}
#define NARROW_NO_BREAK_SPACE 0x202fu
gfxFont* gfxFontGroup::FindFontForChar(uint32_t aCh, uint32_t aPrevCh,
uint32_t aNextCh, Script aRunScript,
gfxFont* aPrevMatchedFont,
FontMatchType* aMatchType) {
// If the char is a cluster extender, we want to use the same font as the
// preceding character if possible. This is preferable to using the font
// group because it avoids breaks in shaping within a cluster.
if (aPrevMatchedFont && IsClusterExtender(aCh)) {
if (aPrevMatchedFont->HasCharacter(aCh) || IsDefaultIgnorable(aCh)) {
return aPrevMatchedFont;
}
// Get the singleton NFC normalizer; this does not need to be deleted.
static UErrorCode err = U_ZERO_ERROR;
static const UNormalizer2* nfc = unorm2_getNFCInstance(&err);
// Check if this char and preceding char can compose; if so, is the
// combination supported by the current font.
int32_t composed = unorm2_composePair(nfc, aPrevCh, aCh);
if (composed > 0 && aPrevMatchedFont->HasCharacter(composed)) {
return aPrevMatchedFont;
}
}
// Special cases for NNBSP (as used in Mongolian):
if (aCh == NARROW_NO_BREAK_SPACE) {
// If there is no preceding character, try the font that we'd use
// for the next char (unless it's just another NNBSP; we don't try
// to look ahead through a whole run of them).
if (!aPrevCh && aNextCh && aNextCh != NARROW_NO_BREAK_SPACE) {
gfxFont* nextFont = FindFontForChar(aNextCh, 0, 0, aRunScript,
aPrevMatchedFont, aMatchType);
if (nextFont && nextFont->HasCharacter(aCh)) {
return nextFont;
}
}
// Otherwise, treat NNBSP like a cluster extender (as above) and try
// to continue the preceding font run.
if (aPrevMatchedFont && aPrevMatchedFont->HasCharacter(aCh)) {
return aPrevMatchedFont;
}
}
// To optimize common cases, try the first font in the font-group
// before going into the more detailed checks below
uint32_t fontListLength = mFonts.Length();
uint32_t nextIndex = 0;
bool isJoinControl = gfxFontUtils::IsJoinControl(aCh);
bool wasJoinCauser = gfxFontUtils::IsJoinCauser(aPrevCh);
bool isVarSelector = gfxFontUtils::IsVarSelector(aCh);
bool nextIsVarSelector = gfxFontUtils::IsVarSelector(aNextCh);
// For Unicode hyphens, if not supported in the font then we'll try for
// the ASCII hyphen-minus as a fallback.
uint32_t fallbackChar = (aCh == 0x2010 || aCh == 0x2011) ? '-' : 0;
// Whether we've seen a font that is currently loading a resource that may
// provide this character (so we should not start a new load).
bool loading = false;
// Do we need to explicitly look for a font that does or does not provide a
// color glyph for the given character?
// For characters with no `EMOJI` property, we'll use whatever the family
// list calls for; but if it's a potential emoji codepoint, we need to check
// if there's a variation selector specifically asking for Text-style or
// Emoji-style rendering and look for a suitable font.
eFontPresentation presentation = eFontPresentation::Any;
EmojiPresentation emojiPresentation = GetEmojiPresentation(aCh);
if (emojiPresentation != TextOnly) {
// If the prefer-emoji selector is present, or if it's a default-emoji char
// and the prefer-text selector is NOT present, or if there's a skin-tone
// modifier, we specifically look for a font with a color glyph.
// If the prefer-text selector is present, we specifically look for a font
// that will provide a monochrome glyph.
// Otherwise, we'll accept either color or monochrome font-family entries,
// so that a color font can be explicitly applied via font-family even to
// characters that are not inherently emoji-style.
if (aNextCh == kVariationSelector16 ||
(aNextCh >= kEmojiSkinToneFirst && aNextCh <= kEmojiSkinToneLast)) {
// Emoji presentation is explicitly requested by a variation selector or
// the presence of a skin-tone codepoint.
presentation = eFontPresentation::EmojiExplicit;
} else if (emojiPresentation == EmojiPresentation::EmojiDefault &&
aNextCh != kVariationSelector15) {
// Emoji presentation is the default for this Unicode character. but we
// will allow an explicitly-specified webfont to apply to it, regardless
// of its glyph type.
presentation = eFontPresentation::EmojiDefault;
} else if (aNextCh == kVariationSelector15) {
// Text presentation is explicitly requested.
presentation = eFontPresentation::Text;
}
}
if (!isJoinControl && !wasJoinCauser && !isVarSelector &&
!nextIsVarSelector && presentation == eFontPresentation::Any) {
gfxFont* firstFont = GetFontAt(0, aCh, &loading);
if (firstFont) {
if (firstFont->HasCharacter(aCh) ||
(fallbackChar && firstFont->HasCharacter(fallbackChar))) {
*aMatchType = {FontMatchType::Kind::kFontGroup, mFonts[0].Generic()};
return firstFont;
}
gfxFont* font = nullptr;
if (mFonts[0].CheckForFallbackFaces()) {
font = FindFallbackFaceForChar(mFonts[0], aCh, aNextCh, presentation);
} else if (!firstFont->GetFontEntry()->IsUserFont()) {
// For platform fonts (but not userfonts), we may need to do
// fallback within the family to handle cases where some faces
// such as Italic or Black have reduced character sets compared
// to the family's Regular face.
font = FindFallbackFaceForChar(mFonts[0], aCh, aNextCh, presentation);
}
if (font) {
*aMatchType = {FontMatchType::Kind::kFontGroup, mFonts[0].Generic()};
return font;
}
} else {
if (fontListLength > 0) {
loading = loading || mFonts[0].IsLoadingFor(aCh);
}
}
// we don't need to check the first font again below
++nextIndex;
}
if (aPrevMatchedFont) {
// Don't switch fonts for control characters, regardless of
// whether they are present in the current font, as they won't
// actually be rendered (see bug 716229)
if (isJoinControl ||
GetGeneralCategory(aCh) == HB_UNICODE_GENERAL_CATEGORY_CONTROL) {
return aPrevMatchedFont;
}
// if previous character was a join-causer (ZWJ),
// use the same font as the previous range if we can
if (wasJoinCauser) {
if (aPrevMatchedFont->HasCharacter(aCh)) {
return aPrevMatchedFont;
}
}
}
// If this character is a variation selector or default-ignorable, use the
// previous font regardless of whether it supports the codepoint or not.
// (We don't want to unnecessarily split glyph runs, and the character will
// not be visibly rendered.)
if (isVarSelector || IsDefaultIgnorable(aCh)) {
return aPrevMatchedFont;
}
// Used to remember the first "candidate" font that would provide a fallback
// text-style rendering if no color glyph can be found.
gfxFont* candidateFont = nullptr;
FontMatchType candidateMatchType;
// Handle a candidate font that could support the character, returning true
// if we should go ahead and return |f|, false to continue searching.
auto CheckCandidate = [&](gfxFont* f, FontMatchType t) -> bool {
// If no preference, then just accept the font.
if (presentation == eFontPresentation::Any ||
(presentation == eFontPresentation::EmojiDefault &&
f->GetFontEntry()->IsUserFont())) {
RefPtr<gfxFont> autoRefDeref(candidateFont);
*aMatchType = t;
return true;
}
// Does the candidate font provide a color glyph for the current character?
bool hasColorGlyph = f->HasColorGlyphFor(aCh, aNextCh);
// If the provided glyph matches the preference, accept the font.
if (hasColorGlyph == PrefersColor(presentation)) {
RefPtr<gfxFont> autoRefDeref(candidateFont);
*aMatchType = t;
return true;
}
// Otherwise, remember the first potential fallback, but keep searching.
if (!candidateFont) {
candidateFont = f;
candidateMatchType = t;
}
return false;
};
// 1. check remaining fonts in the font group
for (uint32_t i = nextIndex; i < fontListLength; i++) {
FamilyFace& ff = mFonts[i];
if (ff.IsInvalid() || ff.IsLoading()) {
if (ff.IsLoadingFor(aCh)) {
loading = true;
}
continue;
}
gfxFont* font = ff.Font();
if (font) {
// if available, use already-made gfxFont and check for character
if (font->HasCharacter(aCh) ||
(fallbackChar && font->HasCharacter(fallbackChar))) {
if (CheckCandidate(font,
{FontMatchType::Kind::kFontGroup, ff.Generic()})) {
return font;
}
}
} else {
// don't have a gfxFont yet, test charmap before instantiating
gfxFontEntry* fe = ff.FontEntry();
if (fe && fe->mIsUserFontContainer) {
// for userfonts, need to test both the unicode range map and
// the cmap of the platform font entry
gfxUserFontEntry* ufe = static_cast<gfxUserFontEntry*>(fe);
// never match a character outside the defined unicode range
if (!ufe->CharacterInUnicodeRange(aCh)) {
continue;
}
// Load if not already loaded, unless we've already seen an in-
// progress load that is expected to satisfy this request.
if (!loading &&
ufe->LoadState() == gfxUserFontEntry::STATUS_NOT_LOADED) {
ufe->Load();
ff.CheckState(mSkipDrawing);
}
if (ff.IsLoading()) {
loading = true;
}
gfxFontEntry* pfe = ufe->GetPlatformFontEntry();
if (pfe && (pfe->HasCharacter(aCh) ||
(fallbackChar && pfe->HasCharacter(fallbackChar)))) {
font = GetFontAt(i, aCh, &loading);
if (font) {
if (CheckCandidate(font, {FontMatchType::Kind::kFontGroup,
mFonts[i].Generic()})) {
return font;
}
}
}
} else if (fe && (fe->HasCharacter(aCh) ||
(fallbackChar && fe->HasCharacter(fallbackChar)))) {
// for normal platform fonts, after checking the cmap
// build the font via GetFontAt
font = GetFontAt(i, aCh, &loading);
if (font) {
if (CheckCandidate(font, {FontMatchType::Kind::kFontGroup,
mFonts[i].Generic()})) {
return font;
}
}
}
}
// check other family faces if needed
if (ff.CheckForFallbackFaces()) {
#ifdef DEBUG
if (i > 0) {
fontlist::FontList* list =
gfxPlatformFontList::PlatformFontList()->SharedFontList();
nsCString s1 = mFonts[i - 1].IsSharedFamily()
? mFonts[i - 1].SharedFamily()->Key().AsString(list)
: mFonts[i - 1].OwnedFamily()->Name();
nsCString s2 = ff.IsSharedFamily()
? ff.SharedFamily()->Key().AsString(list)
: ff.OwnedFamily()->Name();
MOZ_ASSERT(!mFonts[i - 1].CheckForFallbackFaces() || !s1.Equals(s2),
"should only do fallback once per font family");
}
#endif
font = FindFallbackFaceForChar(ff, aCh, aNextCh, presentation);
if (font) {
if (CheckCandidate(font,
{FontMatchType::Kind::kFontGroup, ff.Generic()})) {
return font;
}
}
} else {
// For platform fonts, but not user fonts, consider intra-family
// fallback to handle styles with reduced character sets (see
// also above).
gfxFontEntry* fe = ff.FontEntry();
if (fe && !fe->mIsUserFontContainer && !fe->IsUserFont()) {
font = FindFallbackFaceForChar(ff, aCh, aNextCh, presentation);
if (font) {
if (CheckCandidate(font,
{FontMatchType::Kind::kFontGroup, ff.Generic()})) {
return font;
}
}
}
}
}
if (fontListLength == 0) {
gfxFont* defaultFont = GetDefaultFont();
if (defaultFont->HasCharacter(aCh) ||
(fallbackChar && defaultFont->HasCharacter(fallbackChar))) {
if (CheckCandidate(defaultFont, FontMatchType::Kind::kFontGroup)) {
return defaultFont;
}
}
}
// If character is in Private Use Area, or is unassigned in Unicode, don't do
// matching against pref or system fonts. We only support such codepoints
// when used with an explicitly-specified font, as they have no standard/
// interoperable meaning.
// Also don't attempt any fallback for control characters or noncharacters,
// where we won't be rendering a glyph anyhow, or for codepoints where global
// fallback has already noted a failure.
if (gfxPlatformFontList::PlatformFontList()->SkipFontFallbackForChar(aCh) ||
GetGeneralCategory(aCh) == HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED) {
if (candidateFont) {
*aMatchType = candidateMatchType;
}
return candidateFont;
}
// 2. search pref fonts
gfxFont* font = WhichPrefFontSupportsChar(aCh, aNextCh, presentation);
if (font) {
if (PrefersColor(presentation)) {
// For emoji, always accept the font from preferences even if it isn't
// actually a color-emoji font, as some users may explicitly choose to
// set their emoji font preference to a monochrome font like Symbola.
// So the font.name-list.emoji preference takes precedence over the
// Unicode presentation style here.
*aMatchType = FontMatchType::Kind::kPrefsFallback;
return font;
}
if (CheckCandidate(font, FontMatchType::Kind::kPrefsFallback)) {
return font;
}
// Don't leak `font` if we decided not to return it.
RefPtr<gfxFont> autoRefDeref(font);
}
// For fallback searches, we don't want to use a color-emoji font unless
// emoji-style presentation is specifically required, so we map Any to
// Text here.
if (presentation == eFontPresentation::Any) {
presentation = eFontPresentation::Text;
}
// 3. use fallback fonts
// -- before searching for something else check the font used for the
// previous character
if (aPrevMatchedFont &&
(aPrevMatchedFont->HasCharacter(aCh) ||
(fallbackChar && aPrevMatchedFont->HasCharacter(fallbackChar)))) {
if (CheckCandidate(aPrevMatchedFont,
FontMatchType::Kind::kSystemFallback)) {
return aPrevMatchedFont;
}
}
// for known "space" characters, don't do a full system-fallback search;
// we'll synthesize appropriate-width spaces instead of missing-glyph boxes
if (GetGeneralCategory(aCh) == HB_UNICODE_GENERAL_CATEGORY_SPACE_SEPARATOR &&
GetFirstValidFont()->SynthesizeSpaceWidth(aCh) >= 0.0) {
RefPtr<gfxFont> autoRefDeref(candidateFont);
return nullptr;
}
// -- otherwise look for other stuff
font = WhichSystemFontSupportsChar(aCh, aNextCh, aRunScript, presentation);
if (font) {
if (CheckCandidate(font, FontMatchType::Kind::kSystemFallback)) {
return font;
}
RefPtr<gfxFont> autoRefDeref(font);
}
if (candidateFont) {
*aMatchType = candidateMatchType;
}
return candidateFont;
}
template <typename T>
void gfxFontGroup::ComputeRanges(nsTArray<TextRange>& aRanges, const T* aString,
uint32_t aLength, Script aRunScript,
gfx::ShapedTextFlags aOrientation) {
NS_ASSERTION(aRanges.Length() == 0, "aRanges must be initially empty");
NS_ASSERTION(aLength > 0, "don't call ComputeRanges for zero-length text");
uint32_t prevCh = 0;
uint32_t nextCh = aString[0];
if (sizeof(T) == sizeof(char16_t)) {
if (aLength > 1 && NS_IS_SURROGATE_PAIR(nextCh, aString[1])) {
nextCh = SURROGATE_TO_UCS4(nextCh, aString[1]);
}
}
int32_t lastRangeIndex = -1;
// initialize prevFont to the group's primary font, so that this will be
// used for string-initial control chars, etc rather than risk hitting font
// fallback for these (bug 716229)
StyleGenericFontFamily generic = StyleGenericFontFamily::None;
gfxFont* prevFont = GetFirstValidFont(' ', &generic);
// if we use the initial value of prevFont, we treat this as a match from
// the font group; fixes bug 978313
FontMatchType matchType = {FontMatchType::Kind::kFontGroup, generic};
for (uint32_t i = 0; i < aLength; i++) {
const uint32_t origI = i; // save off in case we increase for surrogate
// set up current ch
uint32_t ch = nextCh;
// Get next char (if any) so that FindFontForChar can look ahead
// for a possible variation selector.
if (sizeof(T) == sizeof(char16_t)) {
// In 16-bit case only, check for surrogate pairs.
if (ch > 0xffffu) {
i++;
}
if (i < aLength - 1) {
nextCh = aString[i + 1];
if (i + 2 < aLength && NS_IS_SURROGATE_PAIR(nextCh, aString[i + 2])) {
nextCh = SURROGATE_TO_UCS4(nextCh, aString[i + 2]);
}
} else {
nextCh = 0;
}
} else {
// 8-bit case is trivial.
nextCh = i < aLength - 1 ? aString[i + 1] : 0;
}
if (ch == 0xa0) {
ch = ' ';
}
gfxFont* font;
// Find the font for this char; but try to avoid calling the expensive
// FindFontForChar method for the most common case, where the first
// font in the list supports the current char, and it is not one of
// the special cases where FindFontForChar will attempt to propagate
// the font selected for an adjacent character.
if ((font = GetFontAt(0, ch)) != nullptr && font->HasCharacter(ch) &&
(sizeof(T) == sizeof(uint8_t) ||
(!IsClusterExtender(ch) && ch != NARROW_NO_BREAK_SPACE &&
!gfxFontUtils::IsJoinControl(ch) &&
!gfxFontUtils::IsJoinCauser(prevCh) &&
!gfxFontUtils::IsVarSelector(ch) &&
GetEmojiPresentation(ch) == TextOnly))) {
matchType = {FontMatchType::Kind::kFontGroup, mFonts[0].Generic()};
} else {
font =
FindFontForChar(ch, prevCh, nextCh, aRunScript, prevFont, &matchType);
}
#ifndef RELEASE_OR_BETA
if (MOZ_UNLIKELY(mTextPerf)) {
if (matchType.kind == FontMatchType::Kind::kPrefsFallback) {
mTextPerf->current.fallbackPrefs++;
} else if (matchType.kind == FontMatchType::Kind::kSystemFallback) {
mTextPerf->current.fallbackSystem++;
}
}
#endif
prevCh = ch;
ShapedTextFlags orient = aOrientation;
if (aOrientation == ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED) {
// For CSS text-orientation:mixed, we need to resolve orientation
// on a per-character basis using the UTR50 orientation property.
switch (GetVerticalOrientation(ch)) {
case VERTICAL_ORIENTATION_U:
case VERTICAL_ORIENTATION_Tu:
orient = ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT;
break;
case VERTICAL_ORIENTATION_Tr: {
// We check for a vertical presentation form first as that's
// likely to be cheaper than inspecting lookups to see if the
// 'vert' feature is going to handle this character, and if the
// presentation form is available then it will be used as
// fallback if needed, so it's OK if the feature is missing.
//
// Because "common" CJK punctuation characters in isolation will be
// resolved to Bopomofo script (as the first script listed in their
// ScriptExtensions property), but this is not always well supported
// by fonts' OpenType tables, we also try Han script; harfbuzz will
// apply a 'vert' feature from any available script (see
// https://github.com/harfbuzz/harfbuzz/issues/63) when shaping,
// so this is OK. It's not quite as general as what harfbuzz does
// (it will find the feature in *any* script), but should be enough
// for likely real-world examples.
uint32_t v = gfxHarfBuzzShaper::GetVerticalPresentationForm(ch);
const uint32_t kVert = HB_TAG('v', 'e', 'r', 't');
orient = (!font || (v && font->HasCharacter(v)) ||
font->FeatureWillHandleChar(aRunScript, kVert, ch) ||
(aRunScript == Script::BOPOMOFO &&
font->FeatureWillHandleChar(Script::HAN, kVert, ch)))
? ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT
: ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT;
break;
}
case VERTICAL_ORIENTATION_R:
orient = ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT;
break;
}
}
if (lastRangeIndex == -1) {
// first char ==> make a new range
aRanges.AppendElement(TextRange(0, 1, font, matchType, orient));
lastRangeIndex++;
prevFont = font;
} else {
// if font or orientation has changed, make a new range...
// unless ch is a variation selector (bug 1248248)
TextRange& prevRange = aRanges[lastRangeIndex];
if (prevRange.font != font ||
(prevRange.orientation != orient && !IsClusterExtender(ch))) {
// close out the previous range
prevRange.end = origI;
aRanges.AppendElement(TextRange(origI, i + 1, font, matchType, orient));
lastRangeIndex++;
// update prevFont for the next match, *unless* we switched
// fonts on a ZWJ, in which case propagating the changed font
// is probably not a good idea (see bug 619511)
if (sizeof(T) == sizeof(uint8_t) || !gfxFontUtils::IsJoinCauser(ch)) {
prevFont = font;
}
} else {
prevRange.matchType |= matchType;
}
}
}
aRanges[lastRangeIndex].end = aLength;
#ifndef RELEASE_OR_BETA
LogModule* log = mStyle.systemFont ? gfxPlatform::GetLog(eGfxLog_textrunui)
: gfxPlatform::GetLog(eGfxLog_textrun);
if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Debug))) {
nsAutoCString lang;
mLanguage->ToUTF8String(lang);
nsAutoCString families;
mFamilyList.ToString(families);
// collect the font matched for each range
nsAutoCString fontMatches;
for (size_t i = 0, i_end = aRanges.Length(); i < i_end; i++) {
const TextRange& r = aRanges[i];
nsAutoCString matchTypes;
if (r.matchType.kind & FontMatchType::Kind::kFontGroup) {
matchTypes.AppendLiteral("list");
}
if (r.matchType.kind & FontMatchType::Kind::kPrefsFallback) {
if (!matchTypes.IsEmpty()) {
matchTypes.AppendLiteral(",");
}
matchTypes.AppendLiteral("prefs");
}
if (r.matchType.kind & FontMatchType::Kind::kPrefsFallback) {
if (!matchTypes.IsEmpty()) {
matchTypes.AppendLiteral(",");
}
matchTypes.AppendLiteral("sys");
}
fontMatches.AppendPrintf(
" [%u:%u] %.200s (%s)", r.start, r.end,
(r.font.get() ? r.font->GetName().get() : "<null>"),
matchTypes.get());
}
MOZ_LOG(log, LogLevel::Debug,
("(%s-fontmatching) fontgroup: [%s] default: %s lang: %s script: %d"
"%s\n",
(mStyle.systemFont ? "textrunui" : "textrun"), families.get(),
(mFamilyList.GetDefaultFontType() == StyleGenericFontFamily::Serif
? "serif"
: (mFamilyList.GetDefaultFontType() ==
StyleGenericFontFamily::SansSerif
? "sans-serif"
: "none")),
lang.get(), static_cast<int>(aRunScript), fontMatches.get()));
}
#endif
}
gfxUserFontSet* gfxFontGroup::GetUserFontSet() { return mUserFontSet; }
void gfxFontGroup::SetUserFontSet(gfxUserFontSet* aUserFontSet) {
if (aUserFontSet == mUserFontSet) {
return;
}
mUserFontSet = aUserFontSet;
mCurrGeneration = GetGeneration() - 1;
UpdateUserFonts();
}
uint64_t gfxFontGroup::GetGeneration() {
if (!mUserFontSet) return 0;
return mUserFontSet->GetGeneration();
}
uint64_t gfxFontGroup::GetRebuildGeneration() {
if (!mUserFontSet) return 0;
return mUserFontSet->GetRebuildGeneration();
}
void gfxFontGroup::UpdateUserFonts() {
if (mCurrGeneration < GetRebuildGeneration()) {
// fonts in userfont set changed, need to redo the fontlist
mFonts.Clear();
ClearCachedData();
BuildFontList();
mCurrGeneration = GetGeneration();
} else if (mCurrGeneration != GetGeneration()) {
// load state change occurred, verify load state and validity of fonts
ClearCachedData();
uint32_t len = mFonts.Length();
for (uint32_t i = 0; i < len; i++) {
FamilyFace& ff = mFonts[i];
if (ff.Font() || !ff.IsUserFontContainer()) {
continue;
}
ff.CheckState(mSkipDrawing);
}
mCurrGeneration = GetGeneration();
}
}
bool gfxFontGroup::ContainsUserFont(const gfxUserFontEntry* aUserFont) {
UpdateUserFonts();
// search through the fonts list for a specific user font
uint32_t len = mFonts.Length();
for (uint32_t i = 0; i < len; i++) {
FamilyFace& ff = mFonts[i];
if (ff.EqualsUserFont(aUserFont)) {
return true;
}
}
return false;
}
gfxFont* gfxFontGroup::WhichPrefFontSupportsChar(
uint32_t aCh, uint32_t aNextCh, eFontPresentation aPresentation) {
eFontPrefLang charLang;
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
if (PrefersColor(aPresentation)) {
charLang = eFontPrefLang_Emoji;
} else {
// get the pref font list if it hasn't been set up already
charLang = pfl->GetFontPrefLangFor(aCh);
}
// if the last pref font was the first family in the pref list, no need to
// recheck through a list of families
if (mLastPrefFont && charLang == mLastPrefLang && mLastPrefFirstFont &&
mLastPrefFont->HasCharacter(aCh)) {
return mLastPrefFont;
}
// based on char lang and page lang, set up list of pref lang fonts to check
eFontPrefLang prefLangs[kMaxLenPrefLangList];
uint32_t i, numLangs = 0;
pfl->GetLangPrefs(prefLangs, numLangs, charLang, mPageLang);
for (i = 0; i < numLangs; i++) {
eFontPrefLang currentLang = prefLangs[i];
StyleGenericFontFamily defaultGeneric = pfl->GetDefaultGeneric(currentLang);
gfxPlatformFontList::PrefFontList* families =
pfl->GetPrefFontsLangGroup(defaultGeneric, currentLang);
NS_ASSERTION(families, "no pref font families found");
// find the first pref font that includes the character
uint32_t j, numPrefs;
numPrefs = families->Length();
for (j = 0; j < numPrefs; j++) {
// look up the appropriate face
FontFamily family = (*families)[j];
if (family.IsNull()) {
continue;
}
// if a pref font is used, it's likely to be used again in the same text
// run. the style doesn't change so the face lookup can be cached rather
// than calling FindOrMakeFont repeatedly. speeds up FindFontForChar
// lookup times for subsequent pref font lookups
if (family == mLastPrefFamily && mLastPrefFont->HasCharacter(aCh)) {
return mLastPrefFont;
}
gfxFontEntry* fe = nullptr;
if (family.mIsShared) {
fontlist::Family* fam = family.mShared;
if (!fam->IsInitialized()) {
Unused << pfl->InitializeFamily(fam);
}
fontlist::Face* face =
fam->FindFaceForStyle(pfl->SharedFontList(), mStyle);
if (face) {
fe = pfl->GetOrCreateFontEntry(face, fam);
}
} else {
fe = family.mUnshared->FindFontForStyle(mStyle);
}
if (!fe) {
continue;
}
// if ch in cmap, create and return a gfxFont
gfxFont* prefFont = nullptr;
if (fe->HasCharacter(aCh)) {
prefFont = fe->FindOrMakeFont(&mStyle);
if (!prefFont) {
continue;
}
}
// If the char was not available, see if we can fall back to an
// alternative face in the same family.
if (!prefFont) {
prefFont = family.mIsShared
? FindFallbackFaceForChar(family.mShared, aCh, aNextCh,
aPresentation)
: FindFallbackFaceForChar(family.mUnshared, aCh, aNextCh,
aPresentation);
}
if (prefFont) {
mLastPrefFamily = family;
mLastPrefFont = prefFont;
mLastPrefLang = charLang;
mLastPrefFirstFont = (i == 0 && j == 0);
if (mFontMatchingStats) {
mFontMatchingStats->mFallbacks |= FallbackTypes::FallbackToPrefsFont;
}
return prefFont;
}
}
}
return nullptr;
}
gfxFont* gfxFontGroup::WhichSystemFontSupportsChar(
uint32_t aCh, uint32_t aNextCh, Script aRunScript,
eFontPresentation aPresentation) {
FontVisibility visibility;
gfxFont* font =
gfxPlatformFontList::PlatformFontList()->SystemFindFontForChar(
aCh, aNextCh, aRunScript, aPresentation, &mStyle, &visibility,
mFontMatchingStats);
if (font) {
if (mFontMatchingStats) {
switch (visibility) {
case FontVisibility::Unknown:
// We don't currently track stats for systems lacking font visibility
// categories, so just ignore this.
break;
case FontVisibility::Base:
mFontMatchingStats->mFallbacks |= FallbackTypes::FallbackToBaseFont;
break;
case FontVisibility::LangPack:
mFontMatchingStats->mFallbacks |=
FallbackTypes::FallbackToLangPackFont;
break;
case FontVisibility::User:
mFontMatchingStats->mFallbacks |= FallbackTypes::FallbackToUserFont;
break;
case FontVisibility::Hidden:
// If macOS font fallback uses the system font, we consider this a
// base OS font even though it wouldn't be exposed via font-family.
mFontMatchingStats->mFallbacks |= FallbackTypes::FallbackToBaseFont;
break;
case FontVisibility::Webfont:
default:
MOZ_ASSERT_UNREACHABLE("this can't happen!");
break;
}
}
return font;
}
return nullptr;
}
void gfxMissingFontRecorder::Flush() {
static bool mNotifiedFontsInitialized = false;
static uint32_t mNotifiedFonts[gfxMissingFontRecorder::kNumScriptBitsWords];
if (!mNotifiedFontsInitialized) {
memset(&mNotifiedFonts, 0, sizeof(mNotifiedFonts));
mNotifiedFontsInitialized = true;
}
nsAutoString fontNeeded;
for (uint32_t i = 0; i < kNumScriptBitsWords; ++i) {
mMissingFonts[i] &= ~mNotifiedFonts[i];
if (!mMissingFonts[i]) {
continue;
}
for (uint32_t j = 0; j < 32; ++j) {
if (!(mMissingFonts[i] & (1 << j))) {
continue;
}
mNotifiedFonts[i] |= (1 << j);
if (!fontNeeded.IsEmpty()) {
fontNeeded.Append(char16_t(','));
}
uint32_t sc = i * 32 + j;
MOZ_ASSERT(sc < static_cast<uint32_t>(Script::NUM_SCRIPT_CODES),
"how did we set the bit for an invalid script code?");
uint32_t tag = GetScriptTagForCode(static_cast<Script>(sc));
fontNeeded.Append(char16_t(tag >> 24));
fontNeeded.Append(char16_t((tag >> 16) & 0xff));
fontNeeded.Append(char16_t((tag >> 8) & 0xff));
fontNeeded.Append(char16_t(tag & 0xff));
}
mMissingFonts[i] = 0;
}
if (!fontNeeded.IsEmpty()) {
nsCOMPtr<nsIObserverService> service = GetObserverService();
service->NotifyObservers(nullptr, "font-needed", fontNeeded.get());
}
}
|