summaryrefslogtreecommitdiff
path: root/src/macfont.m
blob: cbf1b07bc94370c8db11b9b40f0487f430a3ca9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
/* Font driver on Mac OSX Core text.
   Copyright (C) 2009-2015 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

Original author: YAMAMOTO Mitsuharu
*/

#include <config.h>

#include "lisp.h"
#include "dispextern.h"
#include "frame.h"
#include "blockinput.h"
#include "character.h"
#include "charset.h"
#include "composite.h"
#include "fontset.h"
#include "font.h"
#include "termchar.h"
#include "nsgui.h"
#include "nsterm.h"
#include "macfont.h"
#include "macuvs.h"

#include <libkern/OSByteOrder.h>

static struct font_driver macfont_driver;

static double mac_ctfont_get_advance_width_for_glyph (CTFontRef, CGGlyph);
static CGRect mac_ctfont_get_bounding_rect_for_glyph (CTFontRef, CGGlyph);
static CFArrayRef mac_ctfont_create_available_families (void);
static Boolean mac_ctfont_equal_in_postscript_name (CTFontRef, CTFontRef);
static CTLineRef mac_ctfont_create_line_with_string_and_font (CFStringRef,
                                                              CTFontRef);
static CFComparisonResult mac_font_family_compare (const void *,
                                                   const void *, void *);
static Boolean mac_ctfont_descriptor_supports_languages (CTFontDescriptorRef,
                                                         CFArrayRef);
static CFStringRef mac_ctfont_create_preferred_family_for_attributes (CFDictionaryRef);
static CFIndex mac_ctfont_shape (CTFontRef, CFStringRef,
                                 struct mac_glyph_layout *, CFIndex);
static CFArrayRef
mac_font_copy_default_descriptors_for_language (CFStringRef language);

static CFStringRef
mac_font_copy_default_name_for_charset_and_languages (CFCharacterSetRef charset,
                                                      CFArrayRef languages);

#if USE_CT_GLYPH_INFO
static CGGlyph mac_ctfont_get_glyph_for_cid (CTFontRef,
                                             CTCharacterCollection,
                                             CGFontIndex);
#endif

struct macfont_metrics;

/* The actual structure for Mac font that can be cast to struct font.  */

struct macfont_info
{
  struct font font;
  FontRef macfont;
  CGFontRef cgfont;
  ScreenFontRef screen_font;
  struct macfont_cache *cache;
  struct macfont_metrics **metrics;
  short metrics_nrows;
  bool_bf synthetic_italic_p : 1;
  bool_bf synthetic_bold_p : 1;
  unsigned spacing : 2;
  unsigned antialias : 2;
  bool_bf color_bitmap_p : 1;
};

/* Values for the `spacing' member in `struct macfont_info'.  */

enum
  {
    MACFONT_SPACING_PROPORTIONAL,
    MACFONT_SPACING_MONO,
    MACFONT_SPACING_SYNTHETIC_MONO,
  };

/* Values for the `antialias' member in `struct macfont_info'.  */

enum
  {
    MACFONT_ANTIALIAS_DEFAULT,
    MACFONT_ANTIALIAS_OFF,
    MACFONT_ANTIALIAS_ON,
  };

enum {FONT_SLANT_SYNTHETIC_ITALIC = 200}; /* FC_SLANT_ITALIC + 100 */
enum {FONT_WEIGHT_SYNTHETIC_BOLD = 200};  /* FC_WEIGHT_BOLD */
enum {FONT_SPACING_SYNTHETIC_MONO = FONT_SPACING_MONO};

static const CGAffineTransform synthetic_italic_atfm = {1, 0, 0.25, 1, 0, 0};
static const CGFloat synthetic_bold_factor = 0.024;

static Boolean cfnumber_get_font_symbolic_traits_value (CFNumberRef,
                                                        FontSymbolicTraits *);
static void macfont_store_descriptor_attributes (FontDescriptorRef,
                                                 Lisp_Object);
static Lisp_Object macfont_descriptor_entity (FontDescriptorRef,
                                              Lisp_Object,
                                              FontSymbolicTraits);
static CFStringRef macfont_create_family_with_symbol (Lisp_Object);
static int macfont_glyph_extents (struct font *, CGGlyph,
                                  struct font_metrics *, CGFloat *, int);
static CFMutableDictionaryRef macfont_create_attributes_with_spec (Lisp_Object);
static Boolean macfont_supports_charset_and_languages_p (FontDescriptorRef,
                                                         CFCharacterSetRef,
                                                         Lisp_Object,
                                                         CFArrayRef);
static Boolean macfont_closest_traits_index_p (CFArrayRef, FontSymbolicTraits,
                                               CFIndex);
static CFDataRef mac_font_copy_uvs_table (FontRef);
static void mac_font_get_glyphs_for_variants (CFDataRef, UTF32Char,
                                              const UTF32Char [],
                                              CGGlyph [], CFIndex);

/* From CFData to a lisp string.  Always returns a unibyte string.  */

static Lisp_Object
cfdata_to_lisp (CFDataRef data)
{
  CFIndex len = CFDataGetLength (data);
  Lisp_Object result = make_uninit_string (len);

  CFDataGetBytes (data, CFRangeMake (0, len), SDATA (result));

  return result;
}



/* From CFString to a lisp string.  Returns a unibyte string
   containing a UTF-8 byte sequence.  */

static Lisp_Object
cfstring_to_lisp_nodecode (CFStringRef string)
{
  Lisp_Object result = Qnil;
  CFDataRef data;
  const char *s = CFStringGetCStringPtr (string, kCFStringEncodingUTF8);

  if (s)
    {
      CFIndex i, length = CFStringGetLength (string);

      for (i = 0; i < length; i++)
        if (CFStringGetCharacterAtIndex (string, i) == 0)
          break;

      if (i == length)
        return make_unibyte_string (s, strlen (s));
    }

  data = CFStringCreateExternalRepresentation (NULL, string,
                                               kCFStringEncodingUTF8, '?');
  if (data)
    {
      result = cfdata_to_lisp (data);
      CFRelease (data);
    }

  return result;
}

/* Lisp string containing a UTF-8 byte sequence to CFString.  Unlike
   cfstring_create_with_utf8_cstring, this function preserves NUL
   characters.  */

static CFStringRef
cfstring_create_with_string_noencode (Lisp_Object s)
{
  CFStringRef string = CFStringCreateWithBytes (NULL, SDATA (s), SBYTES (s),
                                                kCFStringEncodingUTF8, false);

  if (string == NULL)
    /* Failed to interpret as UTF 8.  Fall back on Mac Roman.  */
    string = CFStringCreateWithBytes (NULL, SDATA (s), SBYTES (s),
                                      kCFStringEncodingMacRoman, false);

  return string;
}

static CGFloat
mac_screen_font_get_advance_width_for_glyph (ScreenFontRef font, CGGlyph glyph)
{
  NSSize advancement = [(NSFont *)font advancementForGlyph:glyph];

  return advancement.width;
}

static CGGlyph
mac_font_get_glyph_for_cid (FontRef font, CharacterCollection collection,
                            CGFontIndex cid)
{
#if USE_CT_GLYPH_INFO
  return mac_ctfont_get_glyph_for_cid ((CTFontRef) font, collection, cid);
#else
  {
    CGGlyph result = kCGFontIndexInvalid;
    NSFont *nsFont = (NSFont *) font;
    unichar characters[] = {0xfffd};
    NSString *string =
      [NSString stringWithCharacters:characters
                              length:ARRAYELTS (characters)];
    NSGlyphInfo *glyphInfo =
      [NSGlyphInfo glyphInfoWithCharacterIdentifier:cid
                                         collection:collection
                                         baseString:string];
    NSDictionary *attributes =
      [NSDictionary dictionaryWithObjectsAndKeys:nsFont,NSFontAttributeName,
                    glyphInfo,NSGlyphInfoAttributeName,nil];
    NSTextStorage *textStorage =
      [[NSTextStorage alloc] initWithString:string
                                 attributes:attributes];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] init];
    NSFont *fontInTextStorage;

    [layoutManager addTextContainer:textContainer];
    [textContainer release];
    [textStorage addLayoutManager:layoutManager];
    [layoutManager release];

    /* Force layout.  */
    (void) [layoutManager glyphRangeForTextContainer:textContainer];

    fontInTextStorage = [textStorage attribute:NSFontAttributeName atIndex:0
                                effectiveRange:NULL];
    if (fontInTextStorage == nsFont
        || [[fontInTextStorage fontName] isEqualToString:[nsFont fontName]])
      {
        NSGlyph glyph = [layoutManager glyphAtIndex:0];

        if (glyph < [nsFont numberOfGlyphs])
          result = glyph;
      }

    [textStorage release];

    return result;
  }
}
#endif

static ScreenFontRef
mac_screen_font_create_with_name (CFStringRef name, CGFloat size)
{
  NSFont *result, *font;

  font = [NSFont fontWithName:((NSString *) name) size:size];
  result = [font screenFont];

  return (ScreenFontRef)[result retain];
}


static Boolean
mac_screen_font_get_metrics (ScreenFontRef font, CGFloat *ascent,
                             CGFloat *descent, CGFloat *leading)
{
  NSFont *nsFont = [(NSFont *)font printerFont];
  NSTextStorage *textStorage;
  NSLayoutManager *layoutManager;
  NSTextContainer *textContainer;
  NSRect usedRect;
  NSPoint spaceLocation;
  CGFloat descender;

  textStorage = [[NSTextStorage alloc] initWithString:@" "];
  layoutManager = [[NSLayoutManager alloc] init];
  textContainer = [[NSTextContainer alloc] init];

  [textStorage setFont:nsFont];
  [textContainer setLineFragmentPadding:0];
  [layoutManager setUsesScreenFonts:YES];

  [layoutManager addTextContainer:textContainer];
  [textContainer release];
  [textStorage addLayoutManager:layoutManager];
  [layoutManager release];

  if (!(textStorage && layoutManager && textContainer))
    {
      [textStorage release];

      return false;
    }

  usedRect = [layoutManager lineFragmentUsedRectForGlyphAtIndex:0
                                                 effectiveRange:NULL];
  spaceLocation = [layoutManager locationForGlyphAtIndex:0];
  [textStorage release];

  *ascent = spaceLocation.y;
  *descent = NSHeight (usedRect) - spaceLocation.y;
  *leading = 0;
  descender = [nsFont descender];
  if (- descender < *descent)
    {
      *leading = *descent + descender;
      *descent = - descender;
    }

  return true;
}

static CFIndex
mac_font_shape_1 (NSFont *font, NSString *string,
                  struct mac_glyph_layout *glyph_layouts, CFIndex glyph_len,
                  BOOL screen_font_p)
{
  NSUInteger i;
  CFIndex result = 0;
  NSTextStorage *textStorage;
  NSLayoutManager *layoutManager;
  NSTextContainer *textContainer;
  NSUInteger stringLength;
  NSPoint spaceLocation;
  NSUInteger used, numberOfGlyphs;

  textStorage = [[NSTextStorage alloc] initWithString:string];
  layoutManager = [[NSLayoutManager alloc] init];
  textContainer = [[NSTextContainer alloc] init];

  /* Append a trailing space to measure baseline position.  */
  [textStorage appendAttributedString:([[[NSAttributedString alloc]
                                          initWithString:@" "] autorelease])];
  [textStorage setFont:font];
  [textContainer setLineFragmentPadding:0];
  [layoutManager setUsesScreenFonts:screen_font_p];

  [layoutManager addTextContainer:textContainer];
  [textContainer release];
  [textStorage addLayoutManager:layoutManager];
  [layoutManager release];

  if (!(textStorage && layoutManager && textContainer))
    {
      [textStorage release];

      return 0;
    }

  stringLength = [string length];

  /* Force layout.  */
  (void) [layoutManager glyphRangeForTextContainer:textContainer];

  spaceLocation = [layoutManager locationForGlyphAtIndex:stringLength];

  /* Remove the appended trailing space because otherwise it may
     generate a wrong result for a right-to-left text.  */
  [textStorage beginEditing];
  [textStorage deleteCharactersInRange:(NSMakeRange (stringLength, 1))];
  [textStorage endEditing];
  (void) [layoutManager glyphRangeForTextContainer:textContainer];

  i = 0;
  while (i < stringLength)
    {
      NSRange range;
      NSFont *fontInTextStorage =
        [textStorage attribute:NSFontAttributeName atIndex:i
                     longestEffectiveRange:&range
                       inRange:(NSMakeRange (0, stringLength))];

      if (!(fontInTextStorage == font
            || [[fontInTextStorage fontName] isEqualToString:[font fontName]]))
        break;
      i = NSMaxRange (range);
    }
  if (i < stringLength)
    /* Make the test `used <= glyph_len' below fail if textStorage
       contained some fonts other than the specified one.  */
    used = glyph_len + 1;
  else
    {
      NSRange range = NSMakeRange (0, stringLength);

      range = [layoutManager glyphRangeForCharacterRange:range
                                    actualCharacterRange:NULL];
      numberOfGlyphs = NSMaxRange (range);
      used = numberOfGlyphs;
      for (i = 0; i < numberOfGlyphs; i++)
        if ([layoutManager notShownAttributeForGlyphAtIndex:i])
          used--;
    }

  if (0 < used && used <= glyph_len)
    {
      NSUInteger glyphIndex, prevGlyphIndex;
      unsigned char bidiLevel;
      NSUInteger *permutation;
      NSRange compRange, range;
      CGFloat totalAdvance;

      glyphIndex = 0;
      while ([layoutManager notShownAttributeForGlyphAtIndex:glyphIndex])
        glyphIndex++;

      /* For now we assume the direction is not changed within the
         string.  */
      [layoutManager getGlyphsInRange:(NSMakeRange (glyphIndex, 1))
                               glyphs:NULL characterIndexes:NULL
                    glyphInscriptions:NULL elasticBits:NULL
                           bidiLevels:&bidiLevel];
      if (bidiLevel & 1)
        permutation = xmalloc (sizeof (NSUInteger) * used);
      else
        permutation = NULL;

#define RIGHT_TO_LEFT_P permutation

      /* Fill the `comp_range' member of struct mac_glyph_layout, and
         setup a permutation for right-to-left text.  */
      compRange = NSMakeRange (0, 0);
      for (range = NSMakeRange (0, 0); NSMaxRange (range) < used;
           range.length++)
        {
          struct mac_glyph_layout *gl = glyph_layouts + NSMaxRange (range);
          NSUInteger characterIndex =
            [layoutManager characterIndexForGlyphAtIndex:glyphIndex];

          gl->string_index = characterIndex;

          if (characterIndex >= NSMaxRange (compRange))
            {
              compRange.location = NSMaxRange (compRange);
              do
                {
                  NSRange characterRange =
                    [string
                      rangeOfComposedCharacterSequenceAtIndex:characterIndex];

                  compRange.length =
                    NSMaxRange (characterRange) - compRange.location;
                  [layoutManager glyphRangeForCharacterRange:compRange
                                        actualCharacterRange:&characterRange];
                  characterIndex = NSMaxRange (characterRange) - 1;
                }
              while (characterIndex >= NSMaxRange (compRange));

              if (RIGHT_TO_LEFT_P)
                for (i = 0; i < range.length; i++)
                  permutation[range.location + i] = NSMaxRange (range) - i - 1;

              range = NSMakeRange (NSMaxRange (range), 0);
            }

          gl->comp_range.location = compRange.location;
          gl->comp_range.length = compRange.length;

          while (++glyphIndex < numberOfGlyphs)
            if (![layoutManager notShownAttributeForGlyphAtIndex:glyphIndex])
              break;
        }
      if (RIGHT_TO_LEFT_P)
        for (i = 0; i < range.length; i++)
          permutation[range.location + i] = NSMaxRange (range) - i - 1;

      /* Then fill the remaining members.  */
      glyphIndex = prevGlyphIndex = 0;
      while ([layoutManager notShownAttributeForGlyphAtIndex:glyphIndex])
        glyphIndex++;

      if (!RIGHT_TO_LEFT_P)
        totalAdvance = 0;
      else
        {
          NSUInteger nrects;
          NSRect *glyphRects =
            [layoutManager
              rectArrayForGlyphRange:(NSMakeRange (0, numberOfGlyphs))
              withinSelectedGlyphRange:(NSMakeRange (NSNotFound, 0))
                     inTextContainer:textContainer rectCount:&nrects];

          totalAdvance = NSMaxX (glyphRects[0]);
        }

      for (i = 0; i < used; i++)
        {
          struct mac_glyph_layout *gl;
          NSPoint location;
          NSUInteger nextGlyphIndex;
          NSRange glyphRange;
          NSRect *glyphRects;
          NSUInteger nrects;

          if (!RIGHT_TO_LEFT_P)
            gl = glyph_layouts + i;
          else
            {
              NSUInteger dest = permutation[i];

              gl = glyph_layouts + dest;
              if (i < dest)
                {
                  CFIndex tmp = gl->string_index;

                  gl->string_index = glyph_layouts[i].string_index;
                  glyph_layouts[i].string_index = tmp;
                }
            }
          gl->glyph_id = [layoutManager glyphAtIndex:glyphIndex];

          location = [layoutManager locationForGlyphAtIndex:glyphIndex];
          gl->baseline_delta = spaceLocation.y - location.y;

          for (nextGlyphIndex = glyphIndex + 1; nextGlyphIndex < numberOfGlyphs;
               nextGlyphIndex++)
            if (![layoutManager
                   notShownAttributeForGlyphAtIndex:nextGlyphIndex])
              break;

          if (!RIGHT_TO_LEFT_P)
            {
              CGFloat maxX;

              if (prevGlyphIndex == 0)
                glyphRange = NSMakeRange (0, nextGlyphIndex);
              else
                glyphRange = NSMakeRange (glyphIndex,
                                          nextGlyphIndex - glyphIndex);
              glyphRects =
                [layoutManager
                  rectArrayForGlyphRange:glyphRange
                  withinSelectedGlyphRange:(NSMakeRange (NSNotFound, 0))
                         inTextContainer:textContainer rectCount:&nrects];
              maxX = max (NSMaxX (glyphRects[0]), totalAdvance);
              gl->advance_delta = location.x - totalAdvance;
              gl->advance = maxX - totalAdvance;
              totalAdvance = maxX;
            }
          else
            {
              CGFloat minX;

              if (nextGlyphIndex == numberOfGlyphs)
                glyphRange = NSMakeRange (prevGlyphIndex,
                                          numberOfGlyphs - prevGlyphIndex);
              else
                glyphRange = NSMakeRange (prevGlyphIndex,
                                          glyphIndex + 1 - prevGlyphIndex);
              glyphRects =
                [layoutManager
                  rectArrayForGlyphRange:glyphRange
                  withinSelectedGlyphRange:(NSMakeRange (NSNotFound, 0))
                         inTextContainer:textContainer rectCount:&nrects];
              minX = min (NSMinX (glyphRects[0]), totalAdvance);
              gl->advance = totalAdvance - minX;
              totalAdvance = minX;
              gl->advance_delta = location.x - totalAdvance;
            }

          prevGlyphIndex = glyphIndex + 1;
          glyphIndex = nextGlyphIndex;
        }

      if (RIGHT_TO_LEFT_P)
        xfree (permutation);

#undef RIGHT_TO_LEFT_P

      result = used;
    }
  [textStorage release];

  return result;
}

static CFIndex
mac_screen_font_shape (ScreenFontRef font, CFStringRef string,
                       struct mac_glyph_layout *glyph_layouts,
                       CFIndex glyph_len)
{
  return mac_font_shape_1 ([(NSFont *)font printerFont],
                           (NSString *) string,
                           glyph_layouts, glyph_len, YES);
}

static CGColorRef
get_cgcolor(unsigned long idx, struct frame *f)
{
  NSColor *nsColor = ns_lookup_indexed_color (idx, f);
  [nsColor set];
  CGColorSpaceRef colorSpace = [[nsColor colorSpace] CGColorSpace];
  NSInteger noc = [nsColor numberOfComponents];
  CGFloat *components = xmalloc (sizeof(CGFloat)*(1+noc));
  CGColorRef cgColor;

  [nsColor getComponents: components];
  cgColor = CGColorCreate (colorSpace, components);
  xfree (components);
  return cgColor;
}

#define CG_SET_FILL_COLOR_WITH_FACE_FOREGROUND(context, face, f)        \
  do {                                                                  \
    CGColorRef refcol_ = get_cgcolor (NS_FACE_FOREGROUND (face), f);    \
    CGContextSetFillColorWithColor (context, refcol_) ;                 \
    CGColorRelease (refcol_);                                           \
  } while (0)
#define CG_SET_FILL_COLOR_WITH_FACE_BACKGROUND(context, face, f)        \
  do {                                                                  \
    CGColorRef refcol_ = get_cgcolor (NS_FACE_BACKGROUND (face), f);    \
    CGContextSetFillColorWithColor (context, refcol_);                  \
    CGColorRelease (refcol_);                                           \
  } while (0)
#define CG_SET_STROKE_COLOR_WITH_FACE_FOREGROUND(context, face, f)      \
  do {                                                                  \
    CGColorRef refcol_ = get_cgcolor (NS_FACE_FOREGROUND (face), f);    \
    CGContextSetStrokeColorWithColor (context, refcol_);                \
    CGColorRelease (refcol_);                                           \
  } while (0)



/* Mac font driver.  */

static struct
{
  /* registry name */
  const char *name;
  /* characters to distinguish the charset from the others */
  int uniquifier[6];
  /* additional constraint by language */
  CFStringRef lang;
  /* set on demand */
  CFCharacterSetRef cf_charset;
  CFStringRef cf_charset_string;
} cf_charset_table[] =
  { { "iso8859-1", { 0x00A0, 0x00A1, 0x00B4, 0x00BC, 0x00D0 } },
    { "iso8859-2", { 0x00A0, 0x010E }},
    { "iso8859-3", { 0x00A0, 0x0108 }},
    { "iso8859-4", { 0x00A0, 0x00AF, 0x0128, 0x0156, 0x02C7 }},
    { "iso8859-5", { 0x00A0, 0x0401 }},
    { "iso8859-6", { 0x00A0, 0x060C }},
    { "iso8859-7", { 0x00A0, 0x0384 }},
    { "iso8859-8", { 0x00A0, 0x05D0 }},
    { "iso8859-9", { 0x00A0, 0x00A1, 0x00BC, 0x011E }},
    { "iso8859-10", { 0x00A0, 0x00D0, 0x0128, 0x2015 }},
    { "iso8859-11", { 0x00A0, 0x0E01 }},
    { "iso8859-13", { 0x00A0, 0x201C }},
    { "iso8859-14", { 0x00A0, 0x0174 }},
    { "iso8859-15", { 0x00A0, 0x00A1, 0x00D0, 0x0152 }},
    { "iso8859-16", { 0x00A0, 0x0218}},
    { "gb2312.1980-0", { 0x4E13 }, CFSTR ("zh-Hans")},
    { "big5-0", { /* 0xF6B1 in ftfont.c */ 0x4EDC }, CFSTR ("zh-Hant") },
    { "jisx0208.1983-0", { 0x4E55 }, CFSTR ("ja")},
    { "ksc5601.1987-0", { 0xAC00 }, CFSTR ("ko")},
    { "cns11643.1992-1", { 0xFE32 }, CFSTR ("zh-Hant")},
    { "cns11643.1992-2", { 0x4E33, 0x7934 }},
    { "cns11643.1992-3", { 0x201A9 }},
    { "cns11643.1992-4", { 0x20057 }},
    { "cns11643.1992-5", { 0x20000 }},
    { "cns11643.1992-6", { 0x20003 }},
    { "cns11643.1992-7", { 0x20055 }},
    { "gbk-0", { 0x4E06 }, CFSTR ("zh-Hans")},
    { "jisx0212.1990-0", { 0x4E44 }},
    { "jisx0213.2000-1", { 0xFA10 }, CFSTR ("ja")},
    { "jisx0213.2000-2", { 0xFA49 }},
    { "jisx0213.2004-1", { 0x20B9F }},
    { "viscii1.1-1", { 0x1EA0, 0x1EAE, 0x1ED2 }, CFSTR ("vi")},
    { "tis620.2529-1", { 0x0E01 }, CFSTR ("th")},
    { "windows-1251", { 0x0401, 0x0490 }, CFSTR ("ru")},
    { "koi8-r", { 0x0401, 0x2219 }, CFSTR ("ru")},
    { "mulelao-1", { 0x0E81 }, CFSTR ("lo")},
    { "unicode-sip", { 0x20000 }},
    { NULL }
  };

#if MAC_OS_X_VERSION_MIN_REQUIRED < 1080
static const struct
{
  CFStringRef language;
  CFStringRef font_names[3];
} macfont_language_default_font_names[] = {
  { CFSTR ("ja"), { CFSTR ("HiraKakuProN-W3"), /* 10.5 - 10.9 */
                    CFSTR ("HiraKakuPro-W3"),  /* 10.4 */
                    NULL }},
  { CFSTR ("ko"), { CFSTR ("AppleSDGothicNeo-Regular"), /* 10.8 - 10.9 */
                    CFSTR ("AppleGothic"), /* 10.4 - 10.7 */
                    NULL }},
  { CFSTR ("zh-Hans"), { CFSTR ("STHeitiSC-Light"), /* 10.6 - 10.9 */
                         CFSTR ("STXihei"),	    /* 10.4 - 10.5 */
                         NULL }},
  { CFSTR ("zh-Hant"), { CFSTR ("STHeitiTC-Light"), /* 10.6 - 10.9 */
                         CFSTR ("LiHeiPro"),	    /* 10.4 - 10.5 */
                         NULL }},
  { NULL }
};
#endif

static CGFloat macfont_antialias_threshold;

void
macfont_update_antialias_threshold (void)
{
  int threshold;
  Boolean valid_p;

  threshold =
    CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
                                     kCFPreferencesCurrentApplication,
                                     &valid_p);
  if (valid_p)
    macfont_antialias_threshold = threshold;
}

static inline Lisp_Object
macfont_intern_prop_cfstring (CFStringRef cfstring)
{
  Lisp_Object string = cfstring_to_lisp_nodecode (cfstring);

  return font_intern_prop (SSDATA (string), SBYTES (string), 1);
}

static inline CFIndex
macfont_store_utf32char_to_unichars (UTF32Char c, UniChar *unichars)
{
  if (c < 0x10000)
    {
      unichars[0] = c;

      return 1;
    }
  else
    {
      c -= 0x10000;
      unichars[0] = (c >> 10) + 0xD800;
      unichars[1] = (c & 0x3FF) + 0xDC00;

      return 2;
    }
}

static Boolean
cfnumber_get_font_symbolic_traits_value (CFNumberRef number,
                                         FontSymbolicTraits *sym_traits)
{
  SInt64 sint64_value;

  /* Getting symbolic traits with kCFNumberSInt32Type is lossy on Mac
     OS X 10.6 when the value is greater than or equal to 1 << 31.  */
  if (CFNumberGetValue (number, kCFNumberSInt64Type, &sint64_value))
    {
      *sym_traits = (FontSymbolicTraits) sint64_value;

      return true;
    }

  return false;
}

static void
macfont_store_descriptor_attributes (FontDescriptorRef desc,
                                     Lisp_Object spec_or_entity)
{
  CFStringRef str;
  CFDictionaryRef dict;
  CFNumberRef num;
  CGFloat floatval;

  str = mac_font_descriptor_copy_attribute (desc,
                                            MAC_FONT_FAMILY_NAME_ATTRIBUTE);
  if (str)
    {
      ASET (spec_or_entity, FONT_FAMILY_INDEX,
            macfont_intern_prop_cfstring (str));
      CFRelease (str);
    }
  dict = mac_font_descriptor_copy_attribute (desc, MAC_FONT_TRAITS_ATTRIBUTE);
  if (dict)
    {
      struct {
        enum font_property_index index;
        CFStringRef trait;
        CGPoint points[6];
      } numeric_traits[] =
          {{FONT_WEIGHT_INDEX, MAC_FONT_WEIGHT_TRAIT,
            {{-0.4, 50},	/* light */
             {-0.24, 87.5},	/* (semi-light + normal) / 2 */
             {0, 100},		/* normal */
             {0.24, 140},	/* (semi-bold + normal) / 2 */
             {0.4, 200},	/* bold */
             {CGFLOAT_MAX, CGFLOAT_MAX}}},
           {FONT_SLANT_INDEX, MAC_FONT_SLANT_TRAIT,
            {{0, 100}, {0.1, 200}, {CGFLOAT_MAX, CGFLOAT_MAX}}},
           {FONT_WIDTH_INDEX, MAC_FONT_WIDTH_TRAIT,
            {{0, 100}, {1, 200}, {CGFLOAT_MAX, CGFLOAT_MAX}}}};
      int i;

      for (i = 0; i < ARRAYELTS (numeric_traits); i++)
        {
          num = CFDictionaryGetValue (dict, numeric_traits[i].trait);
          if (num && CFNumberGetValue (num, kCFNumberCGFloatType, &floatval))
            {
              CGPoint *point = numeric_traits[i].points;

              while (point->x < floatval)
                point++;
              if (point == numeric_traits[i].points)
                point++;
              else if (point->x == CGFLOAT_MAX)
                point--;
              floatval = (point - 1)->y + ((floatval - (point - 1)->x)
                                           * ((point->y - (point - 1)->y)
                                              / (point->x - (point - 1)->x)));
              FONT_SET_STYLE (spec_or_entity, numeric_traits[i].index,
                              make_number (lround (floatval)));
            }
        }

      num = CFDictionaryGetValue (dict, MAC_FONT_SYMBOLIC_TRAIT);
      if (num)
        {
          FontSymbolicTraits sym_traits;
          int spacing;

          cfnumber_get_font_symbolic_traits_value (num, &sym_traits);
          spacing = (sym_traits & MAC_FONT_TRAIT_MONO_SPACE
                     ? FONT_SPACING_MONO : FONT_SPACING_PROPORTIONAL);
          ASET (spec_or_entity, FONT_SPACING_INDEX, make_number (spacing));
        }

      CFRelease (dict);
    }
  num = mac_font_descriptor_copy_attribute (desc, MAC_FONT_SIZE_ATTRIBUTE);
  if (num && CFNumberGetValue (num, kCFNumberCGFloatType, &floatval))
    ASET (spec_or_entity, FONT_SIZE_INDEX, make_number (floatval));
  else
    ASET (spec_or_entity, FONT_SIZE_INDEX, make_number (0));
  if (num)
    CFRelease (num);
}

static Lisp_Object
macfont_descriptor_entity (FontDescriptorRef desc, Lisp_Object extra,
                           FontSymbolicTraits synth_sym_traits)
{
  Lisp_Object entity;
  CFDictionaryRef dict;
  FontSymbolicTraits sym_traits = 0;
  CFStringRef name;

  entity = font_make_entity ();

  ASET (entity, FONT_TYPE_INDEX, macfont_driver.type);
  ASET (entity, FONT_REGISTRY_INDEX, Qiso10646_1);

  macfont_store_descriptor_attributes (desc, entity);

  dict = mac_font_descriptor_copy_attribute (desc, MAC_FONT_TRAITS_ATTRIBUTE);
  if (dict)
    {
      CFNumberRef num = CFDictionaryGetValue (dict, MAC_FONT_SYMBOLIC_TRAIT);

      if (num)
        cfnumber_get_font_symbolic_traits_value (num, &sym_traits);
      CFRelease (dict);
    }
  if (EQ (AREF (entity, FONT_SIZE_INDEX), make_number (0)))
    ASET (entity, FONT_AVGWIDTH_INDEX, make_number (0));
  ASET (entity, FONT_EXTRA_INDEX, Fcopy_sequence (extra));
  name = mac_font_descriptor_copy_attribute (desc, MAC_FONT_NAME_ATTRIBUTE);
  font_put_extra (entity, QCfont_entity,
                  make_save_ptr_int ((void *) name, sym_traits));
  if (synth_sym_traits & MAC_FONT_TRAIT_ITALIC)
    FONT_SET_STYLE (entity, FONT_SLANT_INDEX,
                    make_number (FONT_SLANT_SYNTHETIC_ITALIC));
  if (synth_sym_traits & MAC_FONT_TRAIT_BOLD)
    FONT_SET_STYLE (entity, FONT_WEIGHT_INDEX,
                    make_number (FONT_WEIGHT_SYNTHETIC_BOLD));
  if (synth_sym_traits & MAC_FONT_TRAIT_MONO_SPACE)
    ASET (entity, FONT_SPACING_INDEX,
          make_number (FONT_SPACING_SYNTHETIC_MONO));

  return entity;
}

static CFStringRef
macfont_create_family_with_symbol (Lisp_Object symbol)
{
  static CFArrayRef families = NULL;
  CFStringRef result = NULL, family_name;
  int using_cache_p = 1;
  CFComparatorFunction family_name_comparator;

  family_name = cfstring_create_with_string_noencode (SYMBOL_NAME (symbol));
  if (family_name == NULL)
    return NULL;

    {
      family_name_comparator = CTFontManagerCompareFontFamilyNames;
    }

  if ((*family_name_comparator) (family_name, CFSTR ("LastResort"), NULL)
      == kCFCompareEqualTo)
    result = CFSTR ("LastResort");
  else
    while (1)
      {
        CFIndex i, count;

        if (families == NULL)
          {
            families = mac_font_create_available_families ();
            using_cache_p = 0;
            if (families == NULL)
              break;
          }

        count = CFArrayGetCount (families);
        i = CFArrayBSearchValues (families, CFRangeMake (0, count),
                                  (const void *) family_name,
                                  family_name_comparator, NULL);
        if (i < count)
          {
            CFStringRef name = CFArrayGetValueAtIndex (families, i);

            if ((*family_name_comparator) (name, family_name, NULL)
                == kCFCompareEqualTo)
              result = CFRetain (name);
          }

        if (result || !using_cache_p)
          break;
        else
          {
            CFRelease (families);
            families = NULL;
          }
      }

  CFRelease (family_name);

  return result;
}

#define WIDTH_FRAC_BITS		(4)
#define WIDTH_FRAC_SCALE	(2 * ((1 << (WIDTH_FRAC_BITS - 1)) - 1))

struct macfont_metrics
{
  unsigned char lbearing_low, rbearing_low;
  signed lbearing_high : 4, rbearing_high : 4;
  unsigned char ascent_low, descent_low;
  signed ascent_high : 4, descent_high : 4;

  /* These two members are used for fixed-point representation of
     glyph width.  The `width_int' member is an integer that is
     closest to the width.  The `width_frac' member is the fractional
     adjustment representing a value in [-.5, .5], multiplied by
     WIDTH_FRAC_SCALE.  For synthetic monospace fonts, they represent
     the advance delta for centering instead of the glyph width.  */
  signed width_frac : WIDTH_FRAC_BITS, width_int : 16 - WIDTH_FRAC_BITS;
};

#define METRICS_VALUE(metrics, member)                          \
  (((metrics)->member##_high << 8) | (metrics)->member##_low)
#define METRICS_SET_VALUE(metrics, member, value)                   \
  do {short tmp = (value); (metrics)->member##_low = tmp & 0xff;    \
    (metrics)->member##_high = tmp >> 8;} while (0)

enum metrics_status
{
  METRICS_INVALID = -1,    /* metrics entry is invalid */
  METRICS_WIDTH_VALID = -2 /* width is valid but others are invalid */
};

#define METRICS_STATUS(metrics)                                         \
  (METRICS_VALUE (metrics, ascent) + METRICS_VALUE (metrics, descent))
#define METRICS_SET_STATUS(metrics, status)                     \
  do {METRICS_SET_VALUE (metrics, ascent, 0);                   \
    METRICS_SET_VALUE (metrics, descent, status);} while (0)

#define METRICS_NCOLS_PER_ROW	(128)
#define LCD_FONT_SMOOTHING_LEFT_MARGIN	(0.396f)
#define LCD_FONT_SMOOTHING_RIGHT_MARGIN	(0.396f)

static int
macfont_glyph_extents (struct font *font, CGGlyph glyph,
                       struct font_metrics *metrics, CGFloat *advance_delta,
                       int force_integral_p)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;
  int row, col;
  struct macfont_metrics *cache;
  int width;

  row = glyph / METRICS_NCOLS_PER_ROW;
  col = glyph % METRICS_NCOLS_PER_ROW;
  if (row >= macfont_info->metrics_nrows)
    {
      macfont_info->metrics =
        xrealloc (macfont_info->metrics,
                  sizeof (struct macfont_metrics *) * (row + 1));
      memset (macfont_info->metrics + macfont_info->metrics_nrows, 0,
              (sizeof (struct macfont_metrics *)
               * (row + 1 - macfont_info->metrics_nrows)));
      macfont_info->metrics_nrows = row + 1;
    }
  if (macfont_info->metrics[row] == NULL)
    {
      struct macfont_metrics *new;
      int i;

      new = xmalloc (sizeof (struct macfont_metrics) * METRICS_NCOLS_PER_ROW);
      for (i = 0; i < METRICS_NCOLS_PER_ROW; i++)
        METRICS_SET_STATUS (new + i, METRICS_INVALID);
      macfont_info->metrics[row] = new;
    }
  cache = macfont_info->metrics[row] + col;

  if (METRICS_STATUS (cache) == METRICS_INVALID)
    {
      CGFloat fwidth;

      if (macfont_info->screen_font)
        fwidth = mac_screen_font_get_advance_width_for_glyph (macfont_info->screen_font, glyph);
      else
        fwidth = mac_font_get_advance_width_for_glyph (macfont, glyph);

      /* For synthetic mono fonts, cache->width_{int,frac} holds the
         advance delta value.  */
      if (macfont_info->spacing == MACFONT_SPACING_SYNTHETIC_MONO)
        fwidth = (font->pixel_size - fwidth) / 2;
      cache->width_int = lround (fwidth);
      cache->width_frac = lround ((fwidth - cache->width_int)
                                  * WIDTH_FRAC_SCALE);
      METRICS_SET_STATUS (cache, METRICS_WIDTH_VALID);
    }
  if (macfont_info->spacing == MACFONT_SPACING_SYNTHETIC_MONO)
    width = font->pixel_size;
  else
    width = cache->width_int;

  if (metrics)
    {
      if (METRICS_STATUS (cache) == METRICS_WIDTH_VALID)
        {
          CGRect bounds = mac_font_get_bounding_rect_for_glyph (macfont, glyph);

          if (macfont_info->synthetic_italic_p)
            {
              /* We assume the members a, b, c, and d in
                 synthetic_italic_atfm are non-negative.  */
              bounds.origin =
                CGPointApplyAffineTransform (bounds.origin,
                                             synthetic_italic_atfm);
              bounds.size =
                CGSizeApplyAffineTransform (bounds.size, synthetic_italic_atfm);
            }
          if (macfont_info->synthetic_bold_p && ! force_integral_p)
            {
              CGFloat d =
                - synthetic_bold_factor * mac_font_get_size (macfont) / 2;

                bounds = CGRectInset (bounds, d, d);
            }
          switch (macfont_info->spacing)
            {
            case MACFONT_SPACING_PROPORTIONAL:
              bounds.origin.x += - (cache->width_frac
                                    / (CGFloat) (WIDTH_FRAC_SCALE * 2));
              break;
            case MACFONT_SPACING_MONO:
              break;
            case MACFONT_SPACING_SYNTHETIC_MONO:
              bounds.origin.x += (cache->width_int
                                  + (cache->width_frac
                                     / (CGFloat) WIDTH_FRAC_SCALE));
              break;
            }
          if (bounds.size.width > 0)
            {
              bounds.origin.x -= LCD_FONT_SMOOTHING_LEFT_MARGIN;
              bounds.size.width += (LCD_FONT_SMOOTHING_LEFT_MARGIN
                                    + LCD_FONT_SMOOTHING_RIGHT_MARGIN);
            }
          bounds = CGRectIntegral (bounds);
          METRICS_SET_VALUE (cache, lbearing, CGRectGetMinX (bounds));
          METRICS_SET_VALUE (cache, rbearing, CGRectGetMaxX (bounds));
          METRICS_SET_VALUE (cache, ascent, CGRectGetMaxY (bounds));
          METRICS_SET_VALUE (cache, descent, -CGRectGetMinY (bounds));
        }
      metrics->lbearing = METRICS_VALUE (cache, lbearing);
      metrics->rbearing = METRICS_VALUE (cache, rbearing);
      metrics->width = width;
      metrics->ascent = METRICS_VALUE (cache, ascent);
      metrics->descent = METRICS_VALUE (cache, descent);
    }

  if (advance_delta)
    {
      switch (macfont_info->spacing)
        {
        case MACFONT_SPACING_PROPORTIONAL:
          *advance_delta = (force_integral_p ? 0
                            : - (cache->width_frac
                                 / (CGFloat) (WIDTH_FRAC_SCALE * 2)));
          break;
        case MACFONT_SPACING_MONO:
          *advance_delta = 0;
          break;
        case MACFONT_SPACING_SYNTHETIC_MONO:
          *advance_delta = (force_integral_p ? cache->width_int
                            : (cache->width_int
                               + (cache->width_frac
                                  / (CGFloat) WIDTH_FRAC_SCALE)));
          break;
        }
    }

  return width;
}

static CFMutableDictionaryRef macfont_cache_dictionary;

/* Threshold used in row_nkeys_or_perm.  This must be less than or
   equal to the number of rows that are invalid as BMP (i.e., from
   U+D800 to U+DFFF).  */
#define ROW_PERM_OFFSET	(8)

/* The number of glyphs that can be stored in a value for a single
   entry of CFDictionary.  */
#define NGLYPHS_IN_VALUE (sizeof (void *) / sizeof (CGGlyph))

struct macfont_cache
{
  int reference_count;
  CFCharacterSetRef cf_charset;
  struct {
    /* The cached glyph for a BMP character c is stored in
       matrix[row_nkeys_or_perm[c / 256] - ROW_PERM_OFFSET][c % 256]
       if row_nkeys_or_perm[c / 256] >= ROW_PERM_OFFSET.  */
    unsigned char row_nkeys_or_perm[256];
    CGGlyph **matrix;

    /* Number of rows for which the BMP cache is allocated so far.
       I.e., matrix[0] ... matrix[nrows - 1] are non-NULL.  */
    int nrows;

    /* The cached glyph for a character c is stored as the (c %
       NGLYPHS_IN_VALUE)-th CGGlyph block of a value for the key (c /
       NGLYPHS_IN_VALUE).  However, the glyph for a BMP character c is
       not stored here if row_nkeys_or_perm[c / 256] >=
       ROW_PERM_OFFSET.  */
    CFMutableDictionaryRef dictionary;
  } glyph;

  struct {
    /* UVS (Unicode Variation Sequence) subtable data, which is of
       type CFDataRef if available.  NULL means it is not initialized
       yet.  kCFNull means the subtable is not found and there is no
       suitable fallback table for this font.  */
    CFTypeRef table;

    /* Character collection specifying the destination of the mapping
       provided by `table' above.  If `table' is obtained from the UVS
       subtable in the font cmap table, then the value of this member
       should be MAC_CHARACTER_COLLECTION_IDENTITY_MAPPING.  */
    CharacterCollection collection;
  } uvs;
};

static struct macfont_cache *macfont_lookup_cache (CFStringRef);
static struct macfont_cache *macfont_retain_cache (struct macfont_cache *);
static void macfont_release_cache (struct macfont_cache *);
static CFCharacterSetRef macfont_get_cf_charset (struct font *);
static CFCharacterSetRef macfont_get_cf_charset_for_name (CFStringRef);
static CGGlyph macfont_get_glyph_for_character (struct font *, UTF32Char);
static CGGlyph macfont_get_glyph_for_cid (struct font *font,
                                          CharacterCollection, CGFontIndex);
static CFDataRef macfont_get_uvs_table (struct font *, CharacterCollection *);

static struct macfont_cache *
macfont_lookup_cache (CFStringRef key)
{
  struct macfont_cache *cache;

  if (macfont_cache_dictionary == NULL)
    {
      macfont_cache_dictionary =
        CFDictionaryCreateMutable (NULL, 0,
                                   &kCFTypeDictionaryKeyCallBacks, NULL);
      cache = NULL;
    }
  else
    cache = ((struct macfont_cache *)
             CFDictionaryGetValue (macfont_cache_dictionary, key));

  if (cache == NULL)
    {
      FontRef macfont = mac_font_create_with_name (key, 0);

      if (macfont)
        {
          cache = xzalloc (sizeof (struct macfont_cache));
          /* Treat the LastResort font as if it contained glyphs for
             all characters.  This may look too rough, but neither
             CTFontCopyCharacterSet nor -[NSFont coveredCharacterSet]
             for this font is correct for non-BMP characters on Mac OS
             X 10.5, anyway.  */
          if (CFEqual (key, CFSTR ("LastResort")))
            {
              CFRange range = CFRangeMake (0, MAX_UNICODE_CHAR + 1);

              cache->cf_charset =
                CFCharacterSetCreateWithCharactersInRange (NULL, range);
            }
          if (cache->cf_charset == NULL)
            cache->cf_charset = mac_font_copy_character_set (macfont);
          CFDictionaryAddValue (macfont_cache_dictionary, key,
                                (const void *) cache);
          CFRelease (macfont);
        }
    }

  return cache;
}

static struct macfont_cache *
macfont_retain_cache (struct macfont_cache *cache)
{
  cache->reference_count++;

  return cache;
}

static void
macfont_release_cache (struct macfont_cache *cache)
{
  if (--cache->reference_count == 0)
    {
      int i;

      for (i = 0; i < cache->glyph.nrows; i++)
        xfree (cache->glyph.matrix[i]);
      xfree (cache->glyph.matrix);
      if (cache->glyph.dictionary)
        CFRelease (cache->glyph.dictionary);
      memset (&cache->glyph, 0, sizeof (cache->glyph));
      if (cache->uvs.table)
        CFRelease (cache->uvs.table);
      memset (&cache->uvs, 0, sizeof (cache->uvs));
    }
}

static CFCharacterSetRef
macfont_get_cf_charset (struct font *font)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;

  return macfont_info->cache->cf_charset;
}

static CFCharacterSetRef
macfont_get_cf_charset_for_name (CFStringRef name)
{
  struct macfont_cache *cache = macfont_lookup_cache (name);

  return cache->cf_charset;
}

static CGGlyph
macfont_get_glyph_for_character (struct font *font, UTF32Char c)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;
  struct macfont_cache *cache = macfont_info->cache;

  if (c < 0xD800 || (c > 0xDFFF && c < 0x10000))
    {
      int row = c / 256;
      int nkeys_or_perm = cache->glyph.row_nkeys_or_perm[row];

      if (nkeys_or_perm < ROW_PERM_OFFSET)
        {
          UniChar unichars[256], ch;
          CGGlyph *glyphs;
          int i, len;
          int nrows;
          dispatch_queue_t queue;
          dispatch_group_t group = NULL;

          if (row != 0)
            {
              CFMutableDictionaryRef dictionary;
              uintptr_t key, value;
              int nshifts;
              CGGlyph glyph;

              if (cache->glyph.dictionary == NULL)
                cache->glyph.dictionary =
                  CFDictionaryCreateMutable (NULL, 0, NULL, NULL);
              dictionary = cache->glyph.dictionary;
              key = c / NGLYPHS_IN_VALUE;
              nshifts = ((c % NGLYPHS_IN_VALUE) * sizeof (CGGlyph) * 8);
              value = ((uintptr_t)
                       CFDictionaryGetValue (dictionary, (const void *) key));
              glyph = (value >> nshifts);
              if (glyph)
                return glyph;

              if (nkeys_or_perm + 1 != ROW_PERM_OFFSET)
                {
                  ch = c;
                  if (!mac_font_get_glyphs_for_characters (macfont, &ch,
                                                           &glyph, 1)
                      || glyph == 0)
                    glyph = kCGFontIndexInvalid;

                  if (value == 0)
                    cache->glyph.row_nkeys_or_perm[row] = nkeys_or_perm + 1;
                  value |= ((uintptr_t) glyph << nshifts);
                  CFDictionarySetValue (dictionary, (const void *) key,
                                        (const void *) value);

                  return glyph;
                }

              queue =
                dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
              group = dispatch_group_create ();
              dispatch_group_async (group, queue, ^{
                  int nkeys;
                  uintptr_t key;
                  nkeys = nkeys_or_perm;
                  for (key = row * (256 / NGLYPHS_IN_VALUE); ; key++)
                    if (CFDictionaryContainsKey (dictionary,
                                                 (const void *) key))
                      {
                        CFDictionaryRemoveValue (dictionary,
                                                 (const void *) key);
                        if (--nkeys == 0)
                          break;
                      }
                });
            }

          len = 0;
          for (i = 0; i < 256; i++)
            {
              ch = row * 256 + i;
              if (CFCharacterSetIsLongCharacterMember (cache->cf_charset, ch))
                unichars[len++] = ch;
            }

          glyphs = xmalloc (sizeof (CGGlyph) * 256);
          if (len > 0)
            {
              mac_font_get_glyphs_for_characters (macfont, unichars,
                                                  glyphs, len);
              while (i > len)
                {
                  int next = unichars[len - 1] % 256;

                  while (--i > next)
                    glyphs[i] = kCGFontIndexInvalid;

                  len--;
                  glyphs[i] = glyphs[len];
                  if (len == 0)
                    break;
                }
            }
          if (i > len)
            while (i-- > 0)
              glyphs[i] = kCGFontIndexInvalid;

          nrows = cache->glyph.nrows;
          nkeys_or_perm = nrows + ROW_PERM_OFFSET;
          cache->glyph.row_nkeys_or_perm[row] = nkeys_or_perm;
          nrows++;
          cache->glyph.matrix = xrealloc (cache->glyph.matrix,
                                          sizeof (CGGlyph *) * nrows);
          cache->glyph.matrix[nrows - 1] = glyphs;
          cache->glyph.nrows = nrows;

          if (group)
            {
              dispatch_group_wait (group, DISPATCH_TIME_FOREVER);
              dispatch_release (group);
            }
        }

      return cache->glyph.matrix[nkeys_or_perm - ROW_PERM_OFFSET][c % 256];
    }
  else
    {
      uintptr_t key, value;
      int nshifts;
      CGGlyph glyph;

      if (cache->glyph.dictionary == NULL)
        cache->glyph.dictionary =
          CFDictionaryCreateMutable (NULL, 0, NULL, NULL);
      key = c / NGLYPHS_IN_VALUE;
      nshifts = ((c % NGLYPHS_IN_VALUE) * sizeof (CGGlyph) * 8);
      value = (uintptr_t) CFDictionaryGetValue (cache->glyph.dictionary,
                                                (const void *) key);
      glyph = (value >> nshifts);
      if (glyph == 0)
        {
          UniChar unichars[2];
          CGGlyph glyphs[2];
          CFIndex count = macfont_store_utf32char_to_unichars (c, unichars);

          if (mac_font_get_glyphs_for_characters (macfont, unichars, glyphs,
                                                  count))
            glyph = glyphs[0];
          if (glyph == 0)
            glyph = kCGFontIndexInvalid;

          value |= ((uintptr_t) glyph << nshifts);
          CFDictionarySetValue (cache->glyph.dictionary,
                                (const void *) key, (const void *) value);
        }

      return glyph;
    }
}

static CGGlyph
macfont_get_glyph_for_cid (struct font *font, CharacterCollection collection,
                           CGFontIndex cid)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;

  /* Cache it? */
  return mac_font_get_glyph_for_cid (macfont, collection, cid);
}

static CFDataRef
macfont_get_uvs_table (struct font *font, CharacterCollection *collection)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;
  struct macfont_cache *cache = macfont_info->cache;
  CFDataRef result = NULL;

  if (cache->uvs.table == NULL)
    {
      CFDataRef uvs_table = mac_font_copy_uvs_table (macfont);
      CharacterCollection uvs_collection =
        MAC_CHARACTER_COLLECTION_IDENTITY_MAPPING;

      if (uvs_table == NULL
          && mac_font_get_glyph_for_cid (macfont,
                                         MAC_CHARACTER_COLLECTION_ADOBE_JAPAN1,
                                         6480) != kCGFontIndexInvalid)
        {
          /* If the glyph for U+4E55 is accessible via its CID 6480,
             then we use the Adobe-Japan1 UVS table, which maps a
             variation sequence to a CID, as a fallback.  */
          static CFDataRef mac_uvs_table_adobe_japan1 = NULL;

          if (mac_uvs_table_adobe_japan1 == NULL)
            mac_uvs_table_adobe_japan1 =
              CFDataCreateWithBytesNoCopy (NULL,
                                           mac_uvs_table_adobe_japan1_bytes,
                                           sizeof (mac_uvs_table_adobe_japan1_bytes),
                                           kCFAllocatorNull);
          if (mac_uvs_table_adobe_japan1)
            {
              uvs_table = CFRetain (mac_uvs_table_adobe_japan1);
              uvs_collection = MAC_CHARACTER_COLLECTION_ADOBE_JAPAN1;
            }
        }
      if (uvs_table == NULL)
        cache->uvs.table = kCFNull;
      else
        cache->uvs.table = uvs_table;
      cache->uvs.collection = uvs_collection;
    }

  if (cache->uvs.table != kCFNull)
    {
      result = cache->uvs.table;
      *collection = cache->uvs.collection;
    }

  return result;
}

static Lisp_Object macfont_get_cache (struct frame *);
static Lisp_Object macfont_list (struct frame *, Lisp_Object);
static Lisp_Object macfont_match (struct frame *, Lisp_Object);
static Lisp_Object macfont_list_family (struct frame *);
static void macfont_free_entity (Lisp_Object);
static Lisp_Object macfont_open (struct frame *, Lisp_Object, int);
static void macfont_close (struct font *);
static int macfont_has_char (Lisp_Object, int);
static unsigned macfont_encode_char (struct font *, int);
static void macfont_text_extents (struct font *, unsigned int *, int,
                                  struct font_metrics *);
static int macfont_draw (struct glyph_string *, int, int, int, int, bool);
static Lisp_Object macfont_shape (Lisp_Object);
static int macfont_variation_glyphs (struct font *, int c,
                                     unsigned variations[256]);
static void macfont_filter_properties (Lisp_Object, Lisp_Object);

static struct font_driver macfont_driver =
  {
    LISP_INITIALLY_ZERO,	/* Qmac_ct */
    0,				/* case insensitive */
    macfont_get_cache,
    macfont_list,
    macfont_match,
    macfont_list_family,
    macfont_free_entity,
    macfont_open,
    macfont_close,
    NULL,			/* prepare_face */
    NULL,			/* done_face */
    macfont_has_char,
    macfont_encode_char,
    macfont_text_extents,
    macfont_draw,
    NULL,			/* get_bitmap */
    NULL,			/* free_bitmap */
    NULL,			/* anchor_point */
    NULL,			/* otf_capability */
    NULL,			/* otf_drive */
    NULL,			/* start_for_frame */
    NULL,			/* end_for_frame */
    macfont_shape,
    NULL,			/* check */
    macfont_variation_glyphs,
    macfont_filter_properties,
  };

static Lisp_Object
macfont_get_cache (struct frame * f)
{
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);

  return (dpyinfo->name_list_element);
}

static int
macfont_get_charset (Lisp_Object registry)
{
  char *str = SSDATA (SYMBOL_NAME (registry));
  char *re = alloca (SBYTES (SYMBOL_NAME (registry)) * 2 + 1);
  Lisp_Object regexp;
  int i, j;

  for (i = j = 0; i < SBYTES (SYMBOL_NAME (registry)); i++, j++)
    {
      if (str[i] == '.')
        re[j++] = '\\';
      else if (str[i] == '*')
        re[j++] = '.';
      re[j] = str[i];
      if (re[j] == '?')
        re[j] = '.';
    }
  re[j] = '\0';
  regexp = make_unibyte_string (re, j);
  for (i = 0; cf_charset_table[i].name; i++)
    if (fast_c_string_match_ignore_case
        (regexp, cf_charset_table[i].name,
         strlen (cf_charset_table[i].name)) >= 0)
      break;
  if (! cf_charset_table[i].name)
    return -1;
  if (! cf_charset_table[i].cf_charset)
    {
      int *uniquifier = cf_charset_table[i].uniquifier;
      UniChar *unichars = alloca (sizeof (cf_charset_table[i].uniquifier));
      CFIndex count = 0;
      CFStringRef string;
      CFMutableCharacterSetRef charset = CFCharacterSetCreateMutable (NULL);

      if (! charset)
        return -1;
      for (j = 0; uniquifier[j]; j++)
        {
          count += macfont_store_utf32char_to_unichars (uniquifier[j],
                                                        unichars + count);
          CFCharacterSetAddCharactersInRange (charset,
                                              CFRangeMake (uniquifier[j], 1));
        }

      string = CFStringCreateWithCharacters (NULL, unichars, count);
      if (! string)
        {
          CFRelease (charset);
          return -1;
        }
      cf_charset_table[i].cf_charset = CFCharacterSetCreateCopy (NULL,
                                                                 charset);
      CFRelease (charset);
      /* CFCharacterSetCreateWithCharactersInString does not handle
         surrogate pairs properly as of Mac OS X 10.5.  */
      cf_charset_table[i].cf_charset_string = string;
    }
  return i;
}

struct OpenTypeSpec
{
  Lisp_Object script;
  unsigned int script_tag, langsys_tag;
  int nfeatures[2];
  unsigned int *features[2];
};

#define OTF_SYM_TAG(SYM, TAG)                               \
  do {                                                      \
    unsigned char *p = SDATA (SYMBOL_NAME (SYM));           \
    TAG = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];	\
  } while (0)

#define OTF_TAG_STR(TAG, P)                     \
  do {                                          \
    (P)[0] = (char) (TAG >> 24);                \
    (P)[1] = (char) ((TAG >> 16) & 0xFF);       \
    (P)[2] = (char) ((TAG >> 8) & 0xFF);        \
    (P)[3] = (char) (TAG & 0xFF);               \
    (P)[4] = '\0';                              \
  } while (0)

static struct OpenTypeSpec *
macfont_get_open_type_spec (Lisp_Object otf_spec)
{
  struct OpenTypeSpec *spec = xmalloc (sizeof *spec);
  Lisp_Object val;
  int i, j;
  bool negative;

  if (! spec)
    return NULL;
  spec->script = XCAR (otf_spec);
  if (! NILP (spec->script))
    {
      OTF_SYM_TAG (spec->script, spec->script_tag);
      val = assq_no_quit (spec->script, Votf_script_alist);
      if (CONSP (val) && SYMBOLP (XCDR (val)))
        spec->script = XCDR (val);
      else
        spec->script = Qnil;
    }
  else
    spec->script_tag = 0x44464C54; 	/* "DFLT" */
  otf_spec = XCDR (otf_spec);
  spec->langsys_tag = 0;
  if (! NILP (otf_spec))
    {
      val = XCAR (otf_spec);
      if (! NILP (val))
        OTF_SYM_TAG (val, spec->langsys_tag);
      otf_spec = XCDR (otf_spec);
    }
  spec->nfeatures[0] = spec->nfeatures[1] = 0;
  for (i = 0; i < 2 && ! NILP (otf_spec); i++, otf_spec = XCDR (otf_spec))
    {
      Lisp_Object len;

      val = XCAR (otf_spec);
      if (NILP (val))
        continue;
      len = Flength (val);
      spec->features[i] =
        (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) < XINT (len)
         ? 0
         : malloc (XINT (len) * sizeof *spec->features[i]));
      if (! spec->features[i])
        {
          if (i > 0 && spec->features[0])
            free (spec->features[0]);
          free (spec);
          return NULL;
        }
      for (j = 0, negative = 0; CONSP (val); val = XCDR (val))
        {
          if (NILP (XCAR (val)))
            negative = 1;
          else
            {
              unsigned int tag;

              OTF_SYM_TAG (XCAR (val), tag);
              spec->features[i][j++] = negative ? tag & 0x80000000 : tag;
            }
        }
      spec->nfeatures[i] = j;
    }
  return spec;
}

static CFMutableDictionaryRef
macfont_create_attributes_with_spec (Lisp_Object spec)
{
  Lisp_Object tmp, extra;
  CFMutableArrayRef langarray = NULL;
  CFCharacterSetRef charset = NULL;
  CFStringRef charset_string = NULL;
  CFMutableDictionaryRef attributes = NULL, traits = NULL;
  Lisp_Object script = Qnil;
  Lisp_Object registry;
  int cf_charset_idx, i;
  struct OpenTypeSpec *otspec = NULL;
  struct {
    enum font_property_index index;
    CFStringRef trait;
    CGPoint points[6];
  } numeric_traits[] =
      {{FONT_WEIGHT_INDEX, MAC_FONT_WEIGHT_TRAIT,
        {{-0.4, 50},		/* light */
         {-0.24, 87.5},		/* (semi-light + normal) / 2 */
         {0, 100},		/* normal */
         {0.24, 140},		/* (semi-bold + normal) / 2 */
         {0.4, 200},		/* bold */
         {CGFLOAT_MAX, CGFLOAT_MAX}}},
       {FONT_SLANT_INDEX, MAC_FONT_SLANT_TRAIT,
        {{0, 100}, {0.1, 200}, {CGFLOAT_MAX, CGFLOAT_MAX}}},
       {FONT_WIDTH_INDEX, MAC_FONT_WIDTH_TRAIT,
        {{0, 100}, {1, 200}, {CGFLOAT_MAX, CGFLOAT_MAX}}}};

  registry = AREF (spec, FONT_REGISTRY_INDEX);
  if (NILP (registry)
      || EQ (registry, Qascii_0)
      || EQ (registry, Qiso10646_1)
      || EQ (registry, Qunicode_bmp))
    cf_charset_idx = -1;
  else
    {
      CFStringRef lang;

      cf_charset_idx = macfont_get_charset (registry);
      if (cf_charset_idx < 0)
        goto err;
      charset = cf_charset_table[cf_charset_idx].cf_charset;
      charset_string = cf_charset_table[cf_charset_idx].cf_charset_string;
      lang = cf_charset_table[cf_charset_idx].lang;
      if (lang)
        {
          langarray = CFArrayCreateMutable (NULL, 0, &kCFTypeArrayCallBacks);
          if (! langarray)
            goto err;
          CFArrayAppendValue (langarray, lang);
        }
    }

  for (extra = AREF (spec, FONT_EXTRA_INDEX);
       CONSP (extra); extra = XCDR (extra))
    {
      Lisp_Object key, val;

      tmp = XCAR (extra);
      key = XCAR (tmp), val = XCDR (tmp);
      if (EQ (key, QClang))
        {
          if (! langarray)
            langarray = CFArrayCreateMutable (NULL, 0, &kCFTypeArrayCallBacks);
          if (! langarray)
            goto err;
          if (SYMBOLP (val))
            val = list1 (val);
          for (; CONSP (val); val = XCDR (val))
            if (SYMBOLP (XCAR (val)))
              {
                CFStringRef lang =
                  cfstring_create_with_string_noencode (SYMBOL_NAME
                                                        (XCAR (val)));

                if (lang == NULL)
                  goto err;
                CFArrayAppendValue (langarray, lang);
                CFRelease (lang);
              }
        }
      else if (EQ (key, QCotf))
        {
          otspec = macfont_get_open_type_spec (val);
          if (! otspec)
            goto err;
          script = otspec->script;
        }
      else if (EQ (key, QCscript))
        script = val;
    }

  if (! NILP (script) && ! charset)
    {
      Lisp_Object chars = assq_no_quit (script, Vscript_representative_chars);

      if (CONSP (chars) && CONSP (CDR (chars)))
        {
          CFMutableStringRef string = CFStringCreateMutable (NULL, 0);
          CFMutableCharacterSetRef cs = CFCharacterSetCreateMutable (NULL);

          if (! string || !cs)
            {
              if (string)
                CFRelease (string);
              else if (cs)
                CFRelease (cs);
              goto err;
            }
          for (chars = XCDR (chars); CONSP (chars); chars = XCDR (chars))
            if (CHARACTERP (XCAR (chars)))
              {
                UniChar unichars[2];
                CFIndex count =
                  macfont_store_utf32char_to_unichars (XFASTINT (XCAR (chars)),
                                                       unichars);
                CFRange range = CFRangeMake (XFASTINT (XCAR (chars)), 1);

                CFStringAppendCharacters (string, unichars, count);
                CFCharacterSetAddCharactersInRange (cs, range);
              }
          charset = cs;
          /* CFCharacterSetCreateWithCharactersInString does not
             handle surrogate pairs properly as of Mac OS X 10.5.  */
          charset_string = string;
        }
    }

  attributes = CFDictionaryCreateMutable (NULL, 0,
                                          &kCFTypeDictionaryKeyCallBacks,
                                          &kCFTypeDictionaryValueCallBacks);
  if (! attributes)
    goto err;

  tmp = AREF (spec, FONT_FAMILY_INDEX);
  if (SYMBOLP (tmp) && ! NILP (tmp))
    {
      CFStringRef family = macfont_create_family_with_symbol (tmp);

      if (! family)
        goto err;
      CFDictionaryAddValue (attributes, MAC_FONT_FAMILY_NAME_ATTRIBUTE,
                            family);
      CFRelease (family);
    }

  traits = CFDictionaryCreateMutable (NULL, 4,
                                      &kCFTypeDictionaryKeyCallBacks,
                                      &kCFTypeDictionaryValueCallBacks);
  if (! traits)
    goto err;

  for (i = 0; i < ARRAYELTS (numeric_traits); i++)
    {
      tmp = AREF (spec, numeric_traits[i].index);
      if (INTEGERP (tmp))
        {
          CGPoint *point = numeric_traits[i].points;
          CGFloat floatval = (XINT (tmp) >> 8); // XXX
          CFNumberRef num;

          while (point->y < floatval)
            point++;
          if (point == numeric_traits[i].points)
            point++;
          else if (point->y == CGFLOAT_MAX)
            point--;
          floatval = (point - 1)->x + ((floatval - (point - 1)->y)
                                       * ((point->x - (point - 1)->x)
                                          / (point->y - (point - 1)->y)));
          if (floatval > 1.0)
            floatval = 1.0;
          else if (floatval < -1.0)
            floatval = -1.0;
          num = CFNumberCreate (NULL, kCFNumberCGFloatType, &floatval);
          if (! num)
            goto err;
          CFDictionaryAddValue (traits, numeric_traits[i].trait, num);
          CFRelease (num);
        }
    }
  if (CFDictionaryGetCount (traits))
    CFDictionaryAddValue (attributes, MAC_FONT_TRAITS_ATTRIBUTE, traits);

  if (charset)
    CFDictionaryAddValue (attributes, MAC_FONT_CHARACTER_SET_ATTRIBUTE,
                          charset);
  if (charset_string)
    CFDictionaryAddValue (attributes, MAC_FONT_CHARACTER_SET_STRING_ATTRIBUTE,
                          charset_string);
  if (langarray)
    CFDictionaryAddValue (attributes, MAC_FONT_LANGUAGES_ATTRIBUTE, langarray);

  goto finish;

 err:
  if (attributes)
    {
      CFRelease (attributes);
      attributes = NULL;
    }

 finish:
  if (langarray) CFRelease (langarray);
  if (charset && cf_charset_idx < 0) CFRelease (charset);
  if (charset_string && cf_charset_idx < 0) CFRelease (charset_string);
  if (traits) CFRelease (traits);
  if (otspec)
    {
      if (otspec->nfeatures[0] > 0)
        free (otspec->features[0]);
      if (otspec->nfeatures[1] > 0)
        free (otspec->features[1]);
      free (otspec);
    }

  return attributes;
}

static Boolean
macfont_supports_charset_and_languages_p (FontDescriptorRef desc,
                                          CFCharacterSetRef charset,
                                          Lisp_Object chars,
                                          CFArrayRef languages)
{
  Boolean result = true;

  if (charset || VECTORP (chars))
    {
      CFCharacterSetRef desc_charset =
        mac_font_descriptor_copy_attribute (desc,
                                            MAC_FONT_CHARACTER_SET_ATTRIBUTE);

      if (desc_charset == NULL)
        result = false;
      else
        {
          if (charset)
            result = CFCharacterSetIsSupersetOfSet (desc_charset, charset);
          else 			/* VECTORP (chars) */
            {
              ptrdiff_t j;

              for (j = 0; j < ASIZE (chars); j++)
                if (TYPE_RANGED_INTEGERP (UTF32Char, AREF (chars, j))
                    && CFCharacterSetIsLongCharacterMember (desc_charset,
                                                            XFASTINT (AREF (chars, j))))
                  break;
              if (j == ASIZE (chars))
                result = false;
            }
          CFRelease (desc_charset);
        }
    }
  if (result && languages)
    result = mac_font_descriptor_supports_languages (desc, languages);

  return result;
}

static int
macfont_traits_distance (FontSymbolicTraits sym_traits1,
                         FontSymbolicTraits sym_traits2)
{
  FontSymbolicTraits diff = (sym_traits1 ^ sym_traits2);
  int distance = 0;

  /* We prefer synthetic bold of italic to synthetic italic of bold
     when both bold and italic are available but bold-italic is not
     available.  */
  if (diff & MAC_FONT_TRAIT_BOLD)
    distance |= (1 << 0);
  if (diff & MAC_FONT_TRAIT_ITALIC)
    distance |= (1 << 1);
  if (diff & MAC_FONT_TRAIT_MONO_SPACE)
    distance |= (1 << 2);

  return distance;
}

static Boolean
macfont_closest_traits_index_p (CFArrayRef traits_array,
                                FontSymbolicTraits target,
                                CFIndex index)
{
  CFIndex i, count = CFArrayGetCount (traits_array);
  FontSymbolicTraits traits;
  int my_distance;

  traits = ((FontSymbolicTraits) (uintptr_t)
            CFArrayGetValueAtIndex (traits_array, index));
  my_distance = macfont_traits_distance (target, traits);

  for (i = 0; i < count; i++)
    if (i != index)
      {
        traits = ((FontSymbolicTraits) (uintptr_t)
                  CFArrayGetValueAtIndex (traits_array, i));
        if (macfont_traits_distance (target, traits) < my_distance)
          return false;
      }

  return true;
}

static Lisp_Object
macfont_list (struct frame *f, Lisp_Object spec)
{
  Lisp_Object val = Qnil, family, extra;
  int i, n;
  CFStringRef family_name = NULL;
  CFMutableDictionaryRef attributes = NULL, traits;
  Lisp_Object chars = Qnil;
  int spacing = -1;
  FontSymbolicTraits synth_sym_traits = 0;
  CFArrayRef families;
  CFIndex families_count;
  CFCharacterSetRef charset = NULL;
  CFArrayRef languages = NULL;

  block_input ();

  family = AREF (spec, FONT_FAMILY_INDEX);
  if (! NILP (family))
    {
      family_name = macfont_create_family_with_symbol (family);
      if (family_name == NULL)
        goto finish;
    }

  attributes = macfont_create_attributes_with_spec (spec);
  if (! attributes)
    goto finish;

  languages = CFDictionaryGetValue (attributes, MAC_FONT_LANGUAGES_ATTRIBUTE);

  if (INTEGERP (AREF (spec, FONT_SPACING_INDEX)))
    spacing = XINT (AREF (spec, FONT_SPACING_INDEX));

  traits = ((CFMutableDictionaryRef)
            CFDictionaryGetValue (attributes, MAC_FONT_TRAITS_ATTRIBUTE));

  n = FONT_SLANT_NUMERIC (spec);
  if (n < 0 || n == FONT_SLANT_SYNTHETIC_ITALIC)
    {
      synth_sym_traits |= MAC_FONT_TRAIT_ITALIC;
      if (traits)
        CFDictionaryRemoveValue (traits, MAC_FONT_SLANT_TRAIT);
    }

  n = FONT_WEIGHT_NUMERIC (spec);
  if (n < 0 || n == FONT_WEIGHT_SYNTHETIC_BOLD)
    {
      synth_sym_traits |= MAC_FONT_TRAIT_BOLD;
      if (traits)
        CFDictionaryRemoveValue (traits, MAC_FONT_WEIGHT_TRAIT);
    }

  if (languages
      && (spacing < 0 || spacing == FONT_SPACING_SYNTHETIC_MONO))
    {
      CFStringRef language = CFArrayGetValueAtIndex (languages, 0);

      if (CFStringHasPrefix (language, CFSTR ("ja"))
          || CFStringHasPrefix (language, CFSTR ("ko"))
          || CFStringHasPrefix (language, CFSTR ("zh")))
        synth_sym_traits |= MAC_FONT_TRAIT_MONO_SPACE;
    }

  /* Create array of families.  */
  if (family_name)
    families = CFArrayCreate (NULL, (const void **) &family_name,
                              1, &kCFTypeArrayCallBacks);
  else
    {
      CFStringRef pref_family;
      CFIndex families_count, pref_family_index = -1;

      families = mac_font_create_available_families ();
      if (families == NULL)
        goto err;

      families_count = CFArrayGetCount (families);

      /* Move preferred family to the front if exists.  */
      pref_family =
        mac_font_create_preferred_family_for_attributes (attributes);
      if (pref_family)
        {
          pref_family_index =
            CFArrayGetFirstIndexOfValue (families,
                                         CFRangeMake (0, families_count),
                                         pref_family);
          CFRelease (pref_family);
        }
      if (pref_family_index > 0)
        {
          CFMutableArrayRef mutable_families =
            CFArrayCreateMutable (NULL, families_count, &kCFTypeArrayCallBacks);

          if (mutable_families)
            {
              CFArrayAppendValue (mutable_families,
                                  CFArrayGetValueAtIndex (families,
                                                          pref_family_index));
              CFArrayAppendArray (mutable_families, families,
                                  CFRangeMake (0, pref_family_index));
              if (pref_family_index + 1 < families_count)
                CFArrayAppendArray (mutable_families, families,
                                    CFRangeMake (pref_family_index + 1,
                                                 families_count
                                                 - (pref_family_index + 1)));
              CFRelease (families);
              families = mutable_families;
            }
        }
    }

  charset = CFDictionaryGetValue (attributes,
                                  MAC_FONT_CHARACTER_SET_ATTRIBUTE);
  if (charset)
    {
      CFRetain (charset);
      CFDictionaryRemoveValue (attributes, MAC_FONT_CHARACTER_SET_ATTRIBUTE);
    }
  else
    {
      val = assq_no_quit (QCscript, AREF (spec, FONT_EXTRA_INDEX));
      if (! NILP (val))
        {
          val = assq_no_quit (XCDR (val), Vscript_representative_chars);
          if (CONSP (val) && VECTORP (XCDR (val)))
            chars = XCDR (val);
        }
      val = Qnil;
    }

  if (languages)
    {
      CFRetain (languages);
      CFDictionaryRemoveValue (attributes, MAC_FONT_LANGUAGES_ATTRIBUTE);
    }

  val = Qnil;
  extra = AREF (spec, FONT_EXTRA_INDEX);
  families_count = CFArrayGetCount (families);
  for (i = 0; i < families_count; i++)
    {
      CFStringRef family_name = CFArrayGetValueAtIndex (families, i);
      FontDescriptorRef pat_desc;
      CFArrayRef descs;
      CFIndex descs_count;
      CFMutableArrayRef filtered_descs, traits_array;
      Lisp_Object entity;
      int j;

      CFDictionarySetValue (attributes, MAC_FONT_FAMILY_NAME_ATTRIBUTE,
                            family_name);
      pat_desc = mac_font_descriptor_create_with_attributes (attributes);
      if (! pat_desc)
        goto err;

      /* CTFontDescriptorCreateMatchingFontDescriptors on Mac OS X
         10.7 returns NULL if pat_desc represents the LastResort font.
         So we use CTFontDescriptorCreateMatchingFontDescriptor (no
         trailing "s") for such a font.  */
      if (!CFEqual (family_name, CFSTR ("LastResort")))
        descs = mac_font_descriptor_create_matching_font_descriptors (pat_desc,
                                                                      NULL);
      else
        {
          FontDescriptorRef lr_desc =
            mac_font_descriptor_create_matching_font_descriptor (pat_desc,
                                                                 NULL);
          if (lr_desc)
            {
              descs = CFArrayCreate (NULL, (const void **) &lr_desc, 1,
                                     &kCFTypeArrayCallBacks);
              CFRelease (lr_desc);
            }
          else
            descs = NULL;
        }
      CFRelease (pat_desc);
      if (! descs)
        goto err;

      descs_count = CFArrayGetCount (descs);
      if (descs_count == 0
          || !macfont_supports_charset_and_languages_p (CFArrayGetValueAtIndex (descs, 0),
                                                        charset, chars,
                                                        languages))
        {
          CFRelease (descs);
          continue;
        }

      filtered_descs =
        CFArrayCreateMutable (NULL, descs_count, &kCFTypeArrayCallBacks);
      traits_array = CFArrayCreateMutable (NULL, descs_count, NULL);
      for (j = 0; j < descs_count; j++)
        {
          FontDescriptorRef desc = CFArrayGetValueAtIndex (descs, j);
          CFDictionaryRef dict;
          CFNumberRef num;
          FontSymbolicTraits sym_traits;

          dict = mac_font_descriptor_copy_attribute (desc,
                                                     MAC_FONT_TRAITS_ATTRIBUTE);
          if (dict == NULL)
            continue;

          num = CFDictionaryGetValue (dict, MAC_FONT_SYMBOLIC_TRAIT);
          CFRelease (dict);
          if (num == NULL
              || !cfnumber_get_font_symbolic_traits_value (num, &sym_traits))
            continue;

          if (spacing >= 0
              && !(synth_sym_traits & MAC_FONT_TRAIT_MONO_SPACE)
              && (((sym_traits & MAC_FONT_TRAIT_MONO_SPACE) != 0)
                  != (spacing >= FONT_SPACING_MONO)))
            continue;

          /* Don't use a color bitmap font unless its family is
             explicitly specified.  */
          if ((sym_traits & MAC_FONT_TRAIT_COLOR_GLYPHS) && NILP (family))
            continue;

          if (j > 0
              && !macfont_supports_charset_and_languages_p (desc, charset,
                                                            chars, languages))
            continue;

          CFArrayAppendValue (filtered_descs, desc);
          CFArrayAppendValue (traits_array,
                              (const void *) (uintptr_t) sym_traits);
        }

      CFRelease (descs);
      descs = filtered_descs;
      descs_count = CFArrayGetCount (descs);

      for (j = 0; j < descs_count; j++)
        {
          FontDescriptorRef desc = CFArrayGetValueAtIndex (descs, j);
          FontSymbolicTraits sym_traits =
            ((FontSymbolicTraits) (uintptr_t)
             CFArrayGetValueAtIndex (traits_array, j));
          FontSymbolicTraits mask_min, mask_max, imask, bmask, mmask;

          mask_min = ((synth_sym_traits ^ sym_traits)
                      & (MAC_FONT_TRAIT_ITALIC | MAC_FONT_TRAIT_BOLD));
          if (FONT_SLANT_NUMERIC (spec) < 0)
            mask_min &= ~MAC_FONT_TRAIT_ITALIC;
          if (FONT_WEIGHT_NUMERIC (spec) < 0)
            mask_min &= ~MAC_FONT_TRAIT_BOLD;

          mask_max = (synth_sym_traits & ~sym_traits);
          /* Synthetic bold does not work for bitmap-only fonts on Mac
             OS X 10.6.  */
          if ((mask_min ^ mask_max) & MAC_FONT_TRAIT_BOLD)
            {
              CFNumberRef format =
                mac_font_descriptor_copy_attribute (desc,
                                                    MAC_FONT_FORMAT_ATTRIBUTE);

              if (format)
                {
                  uint32_t format_val;

                  if (CFNumberGetValue (format, kCFNumberSInt32Type,
                                        &format_val)
                      && format_val == MAC_FONT_FORMAT_BITMAP)
                    mask_max &= ~MAC_FONT_TRAIT_BOLD;
                }
            }
          if (spacing >= 0)
            mask_min |= (mask_max & MAC_FONT_TRAIT_MONO_SPACE);

          for (mmask = (mask_min & MAC_FONT_TRAIT_MONO_SPACE);
               mmask <= (mask_max & MAC_FONT_TRAIT_MONO_SPACE);
               mmask += MAC_FONT_TRAIT_MONO_SPACE)
            for (bmask = (mask_min & MAC_FONT_TRAIT_BOLD);
                 bmask <= (mask_max & MAC_FONT_TRAIT_BOLD);
                 bmask += MAC_FONT_TRAIT_BOLD)
              for (imask = (mask_min & MAC_FONT_TRAIT_ITALIC);
                   imask <= (mask_max & MAC_FONT_TRAIT_ITALIC);
                   imask += MAC_FONT_TRAIT_ITALIC)
                {
                  FontSymbolicTraits synth = (imask | bmask | mmask);

                  if (synth == 0
                      || macfont_closest_traits_index_p (traits_array,
                                                         (sym_traits | synth),
                                                         j))
                    {
                      entity = macfont_descriptor_entity (desc, extra, synth);
                      if (! NILP (entity))
                        val = Fcons (entity, val);
                    }
                }
        }

      CFRelease (traits_array);
      CFRelease (descs);
    }

  CFRelease (families);
  val = Fnreverse (val);
  goto finish;
 err:
  val = Qnil;

 finish:
  FONT_ADD_LOG ("macfont-list", spec, val);
  if (charset) CFRelease (charset);
  if (languages) CFRelease (languages);
  if (attributes) CFRelease (attributes);
  if (family_name) CFRelease (family_name);

  unblock_input ();

  return val;
}

static Lisp_Object
macfont_match (struct frame * frame, Lisp_Object spec)
{
  Lisp_Object entity = Qnil;
  CFMutableDictionaryRef attributes;
  FontDescriptorRef pat_desc = NULL, desc = NULL;

  block_input ();

  attributes = macfont_create_attributes_with_spec (spec);
  if (attributes)
    {
      pat_desc = mac_font_descriptor_create_with_attributes (attributes);
      CFRelease (attributes);
    }
  if (pat_desc)
    {
      desc = mac_font_descriptor_create_matching_font_descriptor (pat_desc,
                                                                  NULL);
      CFRelease (pat_desc);
    }
  if (desc)
    {
      entity = macfont_descriptor_entity (desc, AREF (spec, FONT_EXTRA_INDEX),
                                          0);
      CFRelease (desc);
    }
  unblock_input ();

  FONT_ADD_LOG ("macfont-match", spec, entity);
  return entity;
}

static Lisp_Object
macfont_list_family (struct frame *frame)
{
  Lisp_Object list = Qnil;
  CFArrayRef families;

  block_input ();

  families = mac_font_create_available_families ();
  if (families)
    {
      CFIndex i, count = CFArrayGetCount (families);

      for (i = 0; i < count; i++)
        list = Fcons (macfont_intern_prop_cfstring (CFArrayGetValueAtIndex (families, i)), list);
      CFRelease (families);
    }

  unblock_input ();

  return list;
}

static void
macfont_free_entity (Lisp_Object entity)
{
  Lisp_Object val = assq_no_quit (QCfont_entity,
                                  AREF (entity, FONT_EXTRA_INDEX));
  CFStringRef name = XSAVE_POINTER (XCDR (val), 0);

  block_input ();
  CFRelease (name);
  unblock_input ();
}

static Lisp_Object
macfont_open (struct frame * f, Lisp_Object entity, int pixel_size)
{
  Lisp_Object val, font_object;
  CFStringRef font_name;
  struct macfont_info *macfont_info = NULL;
  struct font *font;
  int size;
  FontRef macfont;
  FontSymbolicTraits sym_traits;
  char name[256];
  int len, i, total_width;
  CGGlyph glyph;
  CGFloat ascent, descent, leading;

  val = assq_no_quit (QCfont_entity, AREF (entity, FONT_EXTRA_INDEX));
  if (! CONSP (val)
      || XTYPE (XCDR (val)) != Lisp_Misc
      || XMISCTYPE (XCDR (val)) != Lisp_Misc_Save_Value)
    return Qnil;
  font_name = XSAVE_POINTER (XCDR (val), 0);
  sym_traits = XSAVE_INTEGER (XCDR (val), 1);

  size = XINT (AREF (entity, FONT_SIZE_INDEX));
  if (size == 0)
    size = pixel_size;

  block_input ();
  macfont = mac_font_create_with_name (font_name, size);
  if (macfont)
    {
      int fontsize = (int) [((NSFont *) macfont) pointSize];
      if (fontsize != size) size = fontsize;
    }
  unblock_input ();
  if (! macfont)
    return Qnil;

  font_object = font_build_object (VECSIZE (struct macfont_info),
                                   Qmac_ct, entity, size);
  font = XFONT_OBJECT (font_object);
  font->pixel_size = size;
  font->driver = &macfont_driver;
  font->encoding_charset = font->repertory_charset = -1;

  block_input ();

  macfont_info = (struct macfont_info *) font;
  macfont_info->macfont = macfont;
  macfont_info->cgfont = mac_font_copy_graphics_font (macfont);

  val = assq_no_quit (QCdestination, AREF (entity, FONT_EXTRA_INDEX));
  if (CONSP (val) && EQ (XCDR (val), make_number (1)))
    macfont_info->screen_font = mac_screen_font_create_with_name (font_name,
                                                                  size);
  else
    macfont_info->screen_font = NULL;
  macfont_info->cache = macfont_lookup_cache (font_name);
  macfont_retain_cache (macfont_info->cache);
  macfont_info->metrics = NULL;
  macfont_info->metrics_nrows = 0;
  macfont_info->synthetic_italic_p = 0;
  macfont_info->synthetic_bold_p = 0;
  macfont_info->spacing = MACFONT_SPACING_PROPORTIONAL;
  macfont_info->antialias = MACFONT_ANTIALIAS_DEFAULT;
  if (!(sym_traits & MAC_FONT_TRAIT_ITALIC)
      && FONT_SLANT_NUMERIC (entity) == FONT_SLANT_SYNTHETIC_ITALIC)
    macfont_info->synthetic_italic_p = 1;
  if (!(sym_traits & MAC_FONT_TRAIT_BOLD)
      && FONT_WEIGHT_NUMERIC (entity) == FONT_WEIGHT_SYNTHETIC_BOLD)
    macfont_info->synthetic_bold_p = 1;
  if (sym_traits & MAC_FONT_TRAIT_MONO_SPACE)
    macfont_info->spacing = MACFONT_SPACING_MONO;
  else if (INTEGERP (AREF (entity, FONT_SPACING_INDEX))
           && (XINT (AREF (entity, FONT_SPACING_INDEX))
               == FONT_SPACING_SYNTHETIC_MONO))
    macfont_info->spacing = MACFONT_SPACING_SYNTHETIC_MONO;
  if (macfont_info->synthetic_italic_p || macfont_info->synthetic_bold_p)
    macfont_info->antialias = MACFONT_ANTIALIAS_ON;
  else
    {
      val = assq_no_quit (QCantialias, AREF (entity, FONT_EXTRA_INDEX));
      if (CONSP (val))
        macfont_info->antialias =
          NILP (XCDR (val)) ? MACFONT_ANTIALIAS_OFF : MACFONT_ANTIALIAS_ON;
    }
  macfont_info->color_bitmap_p = 0;
  if (sym_traits & MAC_FONT_TRAIT_COLOR_GLYPHS)
    macfont_info->color_bitmap_p = 1;

  glyph = macfont_get_glyph_for_character (font, ' ');
  if (glyph != kCGFontIndexInvalid)
    font->space_width = macfont_glyph_extents (font, glyph, NULL, NULL, 0);
  else
    /* dirty workaround */
    font->space_width = pixel_size;

  total_width = font->space_width;
  for (i = 1; i < 95; i++)
    {
      glyph = macfont_get_glyph_for_character (font, ' ' + i);
      if (glyph == kCGFontIndexInvalid)
        break;
      total_width += macfont_glyph_extents (font, glyph, NULL, NULL, 0);
    }
  if (i == 95)
    font->average_width = total_width / 95;
  else
    font->average_width = font->space_width; /* XXX */

  if (!(macfont_info->screen_font
        && mac_screen_font_get_metrics (macfont_info->screen_font,
                                        &ascent, &descent, &leading)))
    {
      CFStringRef family_name;

      ascent = mac_font_get_ascent (macfont);
      descent = mac_font_get_descent (macfont);
      leading = mac_font_get_leading (macfont);
      /* AppKit and WebKit do some adjustment to the heights of
         Courier, Helvetica, and Times.  */
      family_name = mac_font_copy_family_name (macfont);
      if (family_name)
        {
          if (CFEqual (family_name, CFSTR ("Courier"))
              || CFEqual (family_name, CFSTR ("Helvetica"))
              || CFEqual (family_name, CFSTR ("Times")))
            ascent += (ascent + descent) * .15f;
          else if (CFStringHasPrefix (family_name, CFSTR ("Hiragino")))
            {
              leading *= .25f;
              ascent += leading;
            }
          CFRelease (family_name);
        }
    }
  font->ascent = ascent + 0.5f;
  val = assq_no_quit (QCminspace, AREF (entity, FONT_EXTRA_INDEX));
  if (CONSP (val) && !NILP (XCDR (val)))
    font->descent = descent + 0.5f;
  else
    font->descent = descent + leading + 0.5f;
  font->height = font->ascent + font->descent;

  font->underline_position = - mac_font_get_underline_position (macfont) + 0.5f;
  font->underline_thickness = mac_font_get_underline_thickness (macfont) + 0.5f;

  unblock_input ();

  /* Unfortunately Xft doesn't provide a way to get minimum char
     width.  So, we use space_width instead.  */
  font->min_width = font->max_width = font->space_width; /* XXX */

  font->baseline_offset = 0;
  font->relative_compose = 0;
  font->default_ascent = 0;
  font->vertical_centering = 0;

  return font_object;
}

static void
macfont_close (struct font *font)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;

  if (macfont_info->cache)
    {
      int i;

      block_input ();
      CFRelease (macfont_info->macfont);
      CGFontRelease (macfont_info->cgfont);
      if (macfont_info->screen_font)
        CFRelease (macfont_info->screen_font);
      macfont_release_cache (macfont_info->cache);
      for (i = 0; i < macfont_info->metrics_nrows; i++)
        if (macfont_info->metrics[i])
          xfree (macfont_info->metrics[i]);
      if (macfont_info->metrics)
        xfree (macfont_info->metrics);
      macfont_info->cache = NULL;
      unblock_input ();
    }
}

static int
macfont_has_char (Lisp_Object font, int c)
{
  int result;
  CFCharacterSetRef charset;

  block_input ();
  if (FONT_ENTITY_P (font))
    {
      Lisp_Object val;
      CFStringRef name;

      val = assq_no_quit (QCfont_entity, AREF (font, FONT_EXTRA_INDEX));
      val = XCDR (val);
      name = XSAVE_POINTER (val, 0);
      charset = macfont_get_cf_charset_for_name (name);
    }
  else
    charset = macfont_get_cf_charset (XFONT_OBJECT (font));

  result = CFCharacterSetIsLongCharacterMember (charset, c);
  unblock_input ();

  return result;
}

static unsigned
macfont_encode_char (struct font *font, int c)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  CGGlyph glyph;

  block_input ();
  glyph = macfont_get_glyph_for_character (font, c);
  unblock_input ();

  return glyph != kCGFontIndexInvalid ? glyph : FONT_INVALID_CODE;
}

static void
macfont_text_extents (struct font *font, unsigned int *code, int nglyphs,
                      struct font_metrics *metrics)
{
  int width, i;

  block_input ();
  width = macfont_glyph_extents (font, code[0], metrics, NULL, 0);
  for (i = 1; i < nglyphs; i++)
    {
      struct font_metrics m;
      int w = macfont_glyph_extents (font, code[i], metrics ? &m : NULL,
                                     NULL, 0);

      if (metrics)
        {
          if (width + m.lbearing < metrics->lbearing)
            metrics->lbearing = width + m.lbearing;
          if (width + m.rbearing > metrics->rbearing)
            metrics->rbearing = width + m.rbearing;
          if (m.ascent > metrics->ascent)
            metrics->ascent = m.ascent;
          if (m.descent > metrics->descent)
            metrics->descent = m.descent;
        }
      width += w;
    }
  unblock_input ();

  if (metrics)
    metrics->width = width;
}

static int
macfont_draw (struct glyph_string *s, int from, int to, int x, int y,
              bool with_background)
{
  struct frame * f = s->f;
  struct macfont_info *macfont_info = (struct macfont_info *) s->font;
  CGRect background_rect;
  CGPoint text_position;
  CGGlyph *glyphs;
  CGPoint *positions;
  CGFloat font_size = mac_font_get_size (macfont_info->macfont);
  bool no_antialias_p =
    (NILP (ns_antialias_text)
     || macfont_info->antialias == MACFONT_ANTIALIAS_OFF
     || (macfont_info->antialias == MACFONT_ANTIALIAS_DEFAULT
         && font_size <= macfont_antialias_threshold));
  int len = to - from;
  struct face *face = s->face;
  CGContextRef context;

  block_input ();

  if (with_background)
    background_rect = CGRectMake (x, y - FONT_BASE (s->font),
                                  s->width, FONT_HEIGHT (s->font));
  else
    background_rect = CGRectNull;

  text_position = CGPointMake (x, -y);
  glyphs = xmalloc (sizeof (CGGlyph) * len);
  {
    CGFloat advance_delta = 0;
    int i;
    CGFloat total_width = 0;

    positions = xmalloc (sizeof (CGPoint) * len);
    for (i = 0; i < len; i++)
      {
        int width;

        glyphs[i] = s->char2b[from + i];
        width = (s->padding_p ? 1
                 : macfont_glyph_extents (s->font, glyphs[i],
                                          NULL, &advance_delta,
                                          no_antialias_p));
        positions[i].x = total_width + advance_delta;
        positions[i].y = 0;
        total_width += width;
      }
  }

  context = [[NSGraphicsContext currentContext] graphicsPort];
  CGContextSaveGState (context);

  if (!CGRectIsNull (background_rect))
    {
      if (s->hl == DRAW_MOUSE_FACE)
        {
          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
          if (!face)
            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
        }
      CG_SET_FILL_COLOR_WITH_FACE_BACKGROUND (context, face, f);
      CGContextFillRects (context, &background_rect, 1);
    }

  if (macfont_info->cgfont)
    {
      CGAffineTransform atfm;

      CGContextScaleCTM (context, 1, -1);
      CG_SET_FILL_COLOR_WITH_FACE_FOREGROUND (context, face, s->f);
      if (macfont_info->synthetic_italic_p)
        atfm = synthetic_italic_atfm;
      else
        atfm = CGAffineTransformIdentity;
      if (macfont_info->synthetic_bold_p && ! no_antialias_p)
        {
          CGContextSetTextDrawingMode (context, kCGTextFillStroke);
          CGContextSetLineWidth (context, synthetic_bold_factor * font_size);
          CG_SET_STROKE_COLOR_WITH_FACE_FOREGROUND (context, face, f);
        }
      if (no_antialias_p)
        CGContextSetShouldAntialias (context, false);

      CGContextSetTextMatrix (context, atfm);
      CGContextSetTextPosition (context, text_position.x, text_position.y);

#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
      if (macfont_info->color_bitmap_p
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1070
          && CTFontDrawGlyphs != NULL
#endif
          )
        {
          if (len > 0)
            {
              CTFontDrawGlyphs (macfont_info->macfont, glyphs, positions, len,
                                context);
            }
        }
      else
#endif	/* MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 */
        {
          CGContextSetFont (context, macfont_info->cgfont);
          CGContextSetFontSize (context, font_size);
          CGContextShowGlyphsAtPositions (context, glyphs, positions, len);
        }
    }


  xfree (glyphs);
  xfree (positions);
  CGContextRestoreGState (context);

  unblock_input ();

  return len;
}

static Lisp_Object
macfont_shape (Lisp_Object lgstring)
{
  struct font *font = CHECK_FONT_GET_OBJECT (LGSTRING_FONT (lgstring));
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;
  ptrdiff_t glyph_len, len, i, j;
  CFIndex nonbmp_len;
  UniChar *unichars;
  CFIndex *nonbmp_indices;
  CFStringRef string;
  CFIndex used = 0;
  struct mac_glyph_layout *glyph_layouts;

  glyph_len = LGSTRING_GLYPH_LEN (lgstring);
  nonbmp_len = 0;
  for (i = 0; i < glyph_len; i++)
    {
      Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, i);

      if (NILP (lglyph))
        break;
      if (LGLYPH_CHAR (lglyph) >= 0x10000)
        nonbmp_len++;
    }

  len = i;

  if (INT_MAX / 2 < len)
    memory_full (SIZE_MAX);

  unichars = alloca (sizeof (UniChar) * (len + nonbmp_len));
  nonbmp_indices = alloca (sizeof (CFIndex) * (nonbmp_len + 1));
  for (i = j = 0; i < len; i++)
    {
      UTF32Char c = LGLYPH_CHAR (LGSTRING_GLYPH (lgstring, i));

      if (macfont_store_utf32char_to_unichars (c, unichars + i + j) > 1)
        {
          nonbmp_indices[j] = i + j;
          j++;
        }
    }
  nonbmp_indices[j] = len + j;	/* sentinel */

  block_input ();

  string = CFStringCreateWithCharactersNoCopy (NULL, unichars, len + nonbmp_len,
                                               kCFAllocatorNull);
  if (string)
    {
      glyph_layouts = alloca (sizeof (struct mac_glyph_layout) * glyph_len);
      if (macfont_info->screen_font)
        used = mac_screen_font_shape (macfont_info->screen_font, string,
                                      glyph_layouts, glyph_len);
      else
        used = mac_font_shape (macfont, string, glyph_layouts, glyph_len);
      CFRelease (string);
    }

  unblock_input ();

  if (used == 0)
    return Qnil;

  block_input ();

  for (i = 0; i < used; i++)
    {
      Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, i);
      struct mac_glyph_layout *gl = glyph_layouts + i;
      EMACS_INT from, to;
      struct font_metrics metrics;
      int xoff, yoff, wadjust;

      if (NILP (lglyph))
        {
          lglyph = Fmake_vector (make_number (LGLYPH_SIZE), Qnil);
          LGSTRING_SET_GLYPH (lgstring, i, lglyph);
        }

      from = gl->comp_range.location;
      /* Convert UTF-16 index to UTF-32.  */
      j = 0;
      while (nonbmp_indices[j] < from)
        j++;
      from -= j;
      LGLYPH_SET_FROM (lglyph, from);

      to = gl->comp_range.location + gl->comp_range.length;
      /* Convert UTF-16 index to UTF-32.  */
      while (nonbmp_indices[j] < to)
        j++;
      to -= j;
      LGLYPH_SET_TO (lglyph, to - 1);

      /* LGLYPH_CHAR is used in `describe-char' for checking whether
         the composition is trivial.  */
      {
        UTF32Char c;

        if (unichars[gl->string_index] >= 0xD800
            && unichars[gl->string_index] < 0xDC00)
          c = (((unichars[gl->string_index] - 0xD800) << 10)
               + (unichars[gl->string_index + 1] - 0xDC00) + 0x10000);
        else
          c = unichars[gl->string_index];
        if (macfont_get_glyph_for_character (font, c) != gl->glyph_id)
          c = 0;
        LGLYPH_SET_CHAR (lglyph, c);
      }

      {
        unsigned long cc = gl->glyph_id;
        LGLYPH_SET_CODE (lglyph, cc);
      }

      macfont_glyph_extents (font, gl->glyph_id, &metrics, NULL, 0);
      LGLYPH_SET_WIDTH (lglyph, metrics.width);
      LGLYPH_SET_LBEARING (lglyph, metrics.lbearing);
      LGLYPH_SET_RBEARING (lglyph, metrics.rbearing);
      LGLYPH_SET_ASCENT (lglyph, metrics.ascent);
      LGLYPH_SET_DESCENT (lglyph, metrics.descent);

      xoff = lround (gl->advance_delta);
      yoff = lround (- gl->baseline_delta);
      wadjust = lround (gl->advance);
      if (xoff != 0 || yoff != 0 || wadjust != metrics.width)
        {
          Lisp_Object vec;

          vec = Fmake_vector (make_number (3), Qnil);
          ASET (vec, 0, make_number (xoff));
          ASET (vec, 1, make_number (yoff));
          ASET (vec, 2, make_number (wadjust));
          LGLYPH_SET_ADJUSTMENT (lglyph, vec);
        }
    }

  unblock_input ();

  return make_number (used);
}

/* Structures for the UVS subtable (format 14) in the cmap table.  */
typedef UInt8 UINT24[3];

#pragma pack(push, 1)
struct variation_selector_record
{
  UINT24 var_selector;
  UInt32 default_uvs_offset, non_default_uvs_offset;
};
struct uvs_table
{
  UInt16 format;
  UInt32 length, num_var_selector_records;
  struct variation_selector_record variation_selector_records[1];
};
#define SIZEOF_UVS_TABLE_HEADER                                         \
  (sizeof (struct uvs_table) - sizeof (struct variation_selector_record))

struct unicode_value_range
{
  UINT24 start_unicode_value;
  UInt8 additional_count;
};
struct default_uvs_table {
  UInt32 num_unicode_value_ranges;
  struct unicode_value_range unicode_value_ranges[1];
};
#define SIZEOF_DEFAULT_UVS_TABLE_HEADER                                 \
  (sizeof (struct default_uvs_table) - sizeof (struct unicode_value_range))

struct uvs_mapping
{
  UINT24 unicode_value;
  UInt16 glyph_id;
};
struct non_default_uvs_table
{
  UInt32 num_uvs_mappings;
  struct uvs_mapping uvs_mappings[1];
};
#define SIZEOF_NON_DEFAULT_UVS_TABLE_HEADER                             \
  (sizeof (struct non_default_uvs_table) - sizeof (struct uvs_mapping))
#pragma pack(pop)

/* Read big endian values.  The argument LVAL must be an lvalue.  */
/* I suppose OSReadBigInt* takes care of unaligned data.  At least, we
   can find "... = OSReadBigInt32(cdb, 2);" followed by "... =
   OSReadBigInt16(cdb, 7);" in a sample code by Apple.  */
#define BUINT8_VALUE(lval)	(*((UInt8 *) &(lval)))
#define BUINT16_VALUE(lval)	OSReadBigInt16 (&(lval), 0)
/* Succeeding one byte should also be accessible.  */
#define BUINT24_VALUE(lval)	(OSReadBigInt32 (&(lval), 0) >> 8)
#define BUINT32_VALUE(lval)	OSReadBigInt32 (&(lval), 0)

/* Return UVS subtable for the specified FONT.  If the subtable is not
   found or ill-formatted, then return NULL.  */

static CFDataRef
mac_font_copy_uvs_table (FontRef font)
{
  CFDataRef cmap_table, uvs_table = NULL;

  cmap_table = mac_font_copy_non_synthetic_table (font, cmapFontTableTag);
  if (cmap_table)
    {
      sfntCMapHeader *cmap = (sfntCMapHeader *) CFDataGetBytePtr (cmap_table);
      struct uvs_table *uvs;
      struct variation_selector_record *records;
      UInt32 cmap_len, ntables, i, uvs_offset, uvs_len, nrecords;

#if __LP64__
      if (CFDataGetLength (cmap_table) > UINT32_MAX)
        goto finish;
#endif

      cmap_len = CFDataGetLength (cmap_table);
      if (sizeof_sfntCMapHeader > cmap_len)
        goto finish;

      ntables = BUINT16_VALUE (cmap->numTables);
      if (ntables > ((cmap_len - sizeof_sfntCMapHeader)
                     / sizeof_sfntCMapEncoding))
        goto finish;

      for (i = 0; i < ntables; i++)
        if ((BUINT16_VALUE (cmap->encoding[i].platformID)
             == kFontUnicodePlatform)
            && (BUINT16_VALUE (cmap->encoding[i].scriptID)
                == 5)) /* kFontUnicodeV4_0VariationSequenceSemantics */
          {
            uvs_offset = BUINT32_VALUE (cmap->encoding[i].offset);
            break;
          }
      if (i == ntables
          || uvs_offset > cmap_len
          || SIZEOF_UVS_TABLE_HEADER > cmap_len - uvs_offset)
        goto finish;

      uvs = (struct uvs_table *) ((UInt8 *) cmap + uvs_offset);
      uvs_len = BUINT32_VALUE (uvs->length);
      if (uvs_len > cmap_len - uvs_offset
          || SIZEOF_UVS_TABLE_HEADER > uvs_len)
        goto finish;

      if (BUINT16_VALUE (uvs->format) != 14)
        goto finish;

      nrecords = BUINT32_VALUE (uvs->num_var_selector_records);
      if (nrecords > ((uvs_len - SIZEOF_UVS_TABLE_HEADER)
                      / sizeof (struct variation_selector_record)))
        goto finish;

      records = uvs->variation_selector_records;
      for (i = 0; i < nrecords; i++)
        {
          UInt32 default_uvs_offset, non_default_uvs_offset;

          default_uvs_offset = BUINT32_VALUE (records[i].default_uvs_offset);
          if (default_uvs_offset)
            {
              struct default_uvs_table *default_uvs;
              UInt32 nranges;

              if (default_uvs_offset > uvs_len
                  || (SIZEOF_DEFAULT_UVS_TABLE_HEADER
                      > uvs_len - default_uvs_offset))
                goto finish;

              default_uvs = ((struct default_uvs_table *)
                             ((UInt8 *) uvs + default_uvs_offset));
              nranges = BUINT32_VALUE (default_uvs->num_unicode_value_ranges);
              if (nranges > ((uvs_len - default_uvs_offset
                              - SIZEOF_DEFAULT_UVS_TABLE_HEADER)
                             / sizeof (struct unicode_value_range)))
                goto finish;
              /* Now 2 * nranges can't overflow, so we can safely use
                 `(lo + hi) / 2' instead of `lo + (hi - lo) / 2' in
                 mac_font_get_glyphs_for_variants.  */
            }

          non_default_uvs_offset =
            BUINT32_VALUE (records[i].non_default_uvs_offset);
          if (non_default_uvs_offset)
            {
              struct non_default_uvs_table *non_default_uvs;
              UInt32 nmappings;

              if (non_default_uvs_offset > uvs_len
                  || (SIZEOF_NON_DEFAULT_UVS_TABLE_HEADER
                      > uvs_len - non_default_uvs_offset))
                goto finish;

              non_default_uvs = ((struct non_default_uvs_table *)
                                 ((UInt8 *) uvs + non_default_uvs_offset));
              nmappings = BUINT32_VALUE (non_default_uvs->num_uvs_mappings);
              if (nmappings > ((uvs_len - non_default_uvs_offset
                                - SIZEOF_NON_DEFAULT_UVS_TABLE_HEADER)
                               / sizeof (struct uvs_mapping)))
                goto finish;
              /* Now 2 * nmappings can't overflow, so we can safely
                 use `(lo + hi) / 2' instead of `lo + (hi - lo) / 2'
                 in mac_font_get_glyphs_for_variants.  */
            }
        }

      uvs_table = CFDataCreate (NULL, (UInt8 *) uvs, uvs_len);

    finish:
      CFRelease (cmap_table);
    }

  return uvs_table;
}

/* Find an entry in the given UVS subtable UVS_TABLE for a variation
   sequence consisting of the given base character C and each
   variation selector SELECTORS[i] for 0 <= i < COUNT, and store the
   result (explained below) into the corresponding GLYPHS[i].  If the
   entry is found in the Default UVS Table, then the result is 0.  If
   the entry is found in the Non-Default UVS Table, then the result is
   the associated glyph ID.  Otherwise, kCGFontIndexInvalid.  The
   elements in SELECTORS must be sorted in strictly increasing
   order.  */

static void
mac_font_get_glyphs_for_variants (CFDataRef uvs_table, UTF32Char c,
                                  const UTF32Char selectors[], CGGlyph glyphs[],
                                  CFIndex count)
{
  struct uvs_table *uvs = (struct uvs_table *) CFDataGetBytePtr (uvs_table);
  struct variation_selector_record *records = uvs->variation_selector_records;
  CFIndex i;
  UInt32 ir, nrecords;
  dispatch_queue_t queue =
    dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t group = dispatch_group_create ();

  nrecords = BUINT32_VALUE (uvs->num_var_selector_records);
  i = 0;
  ir = 0;
  while (i < count && ir < nrecords)
    {
      UInt32 default_uvs_offset, non_default_uvs_offset;

      if (selectors[i] < BUINT24_VALUE (records[ir].var_selector))
        {
          glyphs[i++] = kCGFontIndexInvalid;
          continue;
        }
      else if (selectors[i] > BUINT24_VALUE (records[ir].var_selector))
        {
          ir++;
          continue;
        }

      /* selectors[i] == BUINT24_VALUE (records[ir].var_selector) */
      default_uvs_offset = BUINT32_VALUE (records[ir].default_uvs_offset);
      non_default_uvs_offset =
        BUINT32_VALUE (records[ir].non_default_uvs_offset);
      dispatch_group_async (group, queue, ^{
          glyphs[i] = kCGFontIndexInvalid;

          if (default_uvs_offset)
            {
              struct default_uvs_table *default_uvs =
                (struct default_uvs_table *) ((UInt8 *) uvs
                                              + default_uvs_offset);
              struct unicode_value_range *ranges =
                default_uvs->unicode_value_ranges;
              UInt32 lo, hi;

              lo = 0;
              hi = BUINT32_VALUE (default_uvs->num_unicode_value_ranges);
              while (lo < hi)
                {
                  UInt32 mid = (lo + hi) / 2;

                  if (c < BUINT24_VALUE (ranges[mid].start_unicode_value))
                    hi = mid;
                  else
                    lo = mid + 1;
                }
              if (hi > 0
                  && (c <= (BUINT24_VALUE (ranges[hi - 1].start_unicode_value)
                            + BUINT8_VALUE (ranges[hi - 1].additional_count))))
                glyphs[i] = 0;
            }

          if (glyphs[i] == kCGFontIndexInvalid && non_default_uvs_offset)
            {
              struct non_default_uvs_table *non_default_uvs =
                (struct non_default_uvs_table *) ((UInt8 *) uvs
                                                  + non_default_uvs_offset);
              struct uvs_mapping *mappings = non_default_uvs->uvs_mappings;
              UInt32 lo, hi;

              lo = 0;
              hi = BUINT32_VALUE (non_default_uvs->num_uvs_mappings);
              while (lo < hi)
                {
                  UInt32 mid = (lo + hi) / 2;

                  if (c < BUINT24_VALUE (mappings[mid].unicode_value))
                    hi = mid;
                  else
                    lo = mid + 1;
                }
              if (hi > 0 &&
                  BUINT24_VALUE (mappings[hi - 1].unicode_value) == c)
                glyphs[i] = BUINT16_VALUE (mappings[hi - 1].glyph_id);
            }
        });
      i++;
      ir++;
    }
  while (i < count)
    glyphs[i++] = kCGFontIndexInvalid;
  dispatch_group_wait (group, DISPATCH_TIME_FOREVER);
  dispatch_release (group);
}

static int
macfont_variation_glyphs (struct font *font, int c, unsigned variations[256])
{
  CFDataRef uvs_table;
  CharacterCollection uvs_collection;
  int i, n = 0;

  block_input ();
  uvs_table = macfont_get_uvs_table (font, &uvs_collection);

  if (uvs_table)
    {
      UTF32Char selectors[256];
      CGGlyph glyphs[256];

      for (i = 0; i < 16; i++)
        selectors[i] = 0xFE00 + i;
      for (; i < 256; i++)
        selectors[i] = 0xE0100 + (i - 16);
      mac_font_get_glyphs_for_variants (uvs_table, c, selectors, glyphs, 256);
      for (i = 0; i < 256; i++)
        {
          CGGlyph glyph = glyphs[i];

          if (uvs_collection != MAC_CHARACTER_COLLECTION_IDENTITY_MAPPING
              && glyph != kCGFontIndexInvalid)
            glyph = macfont_get_glyph_for_cid (font, uvs_collection, glyph);
          if (glyph == kCGFontIndexInvalid)
            variations[i] = 0;
          else
            {
              variations[i] = (glyph ? glyph
                               : macfont_get_glyph_for_character (font, c));
              n++;
            }
        }
    }
  unblock_input ();

  return n;
}

static const char *const macfont_booleans[] = {
  ":antialias",
  ":minspace",
  NULL,
};

static const char *const macfont_non_booleans[] = {
  ":lang",
  ":script",
  ":destination",
  NULL,
};

static void
macfont_filter_properties (Lisp_Object font, Lisp_Object alist)
{
  font_filter_properties (font, alist, macfont_booleans, macfont_non_booleans);
}

static Boolean
mac_ctfont_descriptor_supports_languages (CTFontDescriptorRef descriptor,
                                          CFArrayRef languages)
{
  Boolean result = true;
  CFArrayRef desc_languages =
    CTFontDescriptorCopyAttribute (descriptor, kCTFontLanguagesAttribute);

  if (desc_languages == NULL)
    result = false;
  else
    {
      CFIndex desc_languages_count, i, languages_count;

      desc_languages_count = CFArrayGetCount (desc_languages);
      languages_count = CFArrayGetCount (languages);
      for (i = 0; i < languages_count; i++)
        if (!CFArrayContainsValue (desc_languages,
                                   CFRangeMake (0, desc_languages_count),
                                   CFArrayGetValueAtIndex (languages, i)))
          {
            result = false;
            break;
          }
      CFRelease (desc_languages);
    }

  return result;
}

static CFStringRef
mac_ctfont_create_preferred_family_for_attributes (CFDictionaryRef attributes)
{
  CFStringRef result = NULL;
  CFStringRef charset_string =
    CFDictionaryGetValue (attributes, MAC_FONT_CHARACTER_SET_STRING_ATTRIBUTE);

  if (charset_string && CFStringGetLength (charset_string) > 0)
    {
      CFStringRef keys[] = {
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
        kCTLanguageAttributeName
#else
        CFSTR ("NSLanguage")
#endif
      };
      CFTypeRef values[] = {NULL};
      CFIndex num_values = 0;
      CFArrayRef languages
        = CFDictionaryGetValue (attributes, MAC_FONT_LANGUAGES_ATTRIBUTE);

      if (languages && CFArrayGetCount (languages) > 0)
        {
          if (CTGetCoreTextVersion () >= kCTVersionNumber10_9)
            values[num_values++] = CFArrayGetValueAtIndex (languages, 0);
          else
            {
              CFCharacterSetRef charset =
                CFDictionaryGetValue (attributes,
                                      MAC_FONT_CHARACTER_SET_ATTRIBUTE);

              result = mac_font_copy_default_name_for_charset_and_languages (charset, languages);
            }
        }
      if (result == NULL)
        {
          CFAttributedStringRef attr_string = NULL;
          CTLineRef ctline = NULL;
          CFDictionaryRef attrs
            = CFDictionaryCreate (NULL, (const void **) keys,
                                  (const void **) values, num_values,
                                  &kCFTypeDictionaryKeyCallBacks,
                                  &kCFTypeDictionaryValueCallBacks);

          if (attrs)
            {
              attr_string = CFAttributedStringCreate (NULL, charset_string,
                                                      attrs);
              CFRelease (attrs);
            }
          if (attr_string)
            {
              ctline = CTLineCreateWithAttributedString (attr_string);
              CFRelease (attr_string);
            }
          if (ctline)
            {
              CFArrayRef runs = CTLineGetGlyphRuns (ctline);
              CFIndex i, nruns = CFArrayGetCount (runs);
              CTFontRef font;

              for (i = 0; i < nruns; i++)
                {
                  CTRunRef run = CFArrayGetValueAtIndex (runs, i);
                  CFDictionaryRef attributes = CTRunGetAttributes (run);
                  CTFontRef font_in_run;

                  if (attributes == NULL)
                    break;
                  font_in_run =
                    CFDictionaryGetValue (attributes, kCTFontAttributeName);
                  if (font_in_run == NULL)
                    break;
                  if (i == 0)
                    font = font_in_run;
                  else if (!mac_ctfont_equal_in_postscript_name (font,
                                                                 font_in_run))
                    break;
                }
              if (nruns > 0 && i == nruns)
                result = CTFontCopyAttribute (font, kCTFontFamilyNameAttribute);
              CFRelease (ctline);
            }
        }
    }

  return result;
}

static inline double
mac_ctfont_get_advance_width_for_glyph (CTFontRef font, CGGlyph glyph)
{
  return CTFontGetAdvancesForGlyphs (font, kCTFontDefaultOrientation,
                                     &glyph, NULL, 1);
}

static inline CGRect
mac_ctfont_get_bounding_rect_for_glyph (CTFontRef font, CGGlyph glyph)
{
  return CTFontGetBoundingRectsForGlyphs (font, kCTFontDefaultOrientation,
                                          &glyph, NULL, 1);
}

static CFArrayRef
mac_ctfont_create_available_families (void)
{
  CFMutableArrayRef families = NULL;

    {
      CFArrayRef orig_families = CTFontManagerCopyAvailableFontFamilyNames ();

      if (orig_families)
        {
          CFIndex i, count = CFArrayGetCount (orig_families);

          families = CFArrayCreateMutable (NULL, count, &kCFTypeArrayCallBacks);
          if (families)
            for (i = 0; i < count; i++)
              {
                CFStringRef family = CFArrayGetValueAtIndex (orig_families, i);

                if (!CFStringHasPrefix (family, CFSTR ("."))
                    && (CTFontManagerCompareFontFamilyNames (family,
                                                             CFSTR ("LastResort"),
                                                             NULL)
                        != kCFCompareEqualTo))
                  CFArrayAppendValue (families, family);
              }
          CFRelease (orig_families);
        }
    }

    return families;
}

static Boolean
mac_ctfont_equal_in_postscript_name (CTFontRef font1, CTFontRef font2)
{
  Boolean result;
  CFStringRef name1, name2;

  if (font1 == font2)
    return true;

  result = false;
  name1 = CTFontCopyPostScriptName (font1);
  if (name1)
    {
      name2 = CTFontCopyPostScriptName (font2);
      if (name2)
        {
          result = CFEqual (name1, name2);
          CFRelease (name2);
        }
      CFRelease (name1);
    }

  return result;
}

static CTLineRef
mac_ctfont_create_line_with_string_and_font (CFStringRef string,
                                             CTFontRef macfont)
{
  CFStringRef keys[] = {kCTFontAttributeName, kCTKernAttributeName};
  CFTypeRef values[] = {NULL, NULL};
  CFDictionaryRef attributes = NULL;
  CFAttributedStringRef attr_string = NULL;
  CTLineRef ctline = NULL;
  float float_zero = 0.0f;

  values[0] = macfont;
  values[1] = CFNumberCreate (NULL, kCFNumberFloatType, &float_zero);
  if (values[1])
    {
      attributes = CFDictionaryCreate (NULL, (const void **) keys,
                                       (const void **) values,
                                       ARRAYELTS (keys),
                                       &kCFTypeDictionaryKeyCallBacks,
                                       &kCFTypeDictionaryValueCallBacks);
      CFRelease (values[1]);
    }
  if (attributes)
    {
      attr_string = CFAttributedStringCreate (NULL, string, attributes);
      CFRelease (attributes);
    }
  if (attr_string)
    {
      ctline = CTLineCreateWithAttributedString (attr_string);
      CFRelease (attr_string);
    }
  if (ctline)
    {
      /* Abandon if ctline contains some fonts other than the
         specified one.  */
      CFArrayRef runs = CTLineGetGlyphRuns (ctline);
      CFIndex i, nruns = CFArrayGetCount (runs);

      for (i = 0; i < nruns; i++)
        {
          CTRunRef run = CFArrayGetValueAtIndex (runs, i);
          CFDictionaryRef attributes = CTRunGetAttributes (run);
          CTFontRef font_in_run;

          if (attributes == NULL)
            break;
          font_in_run =
            CFDictionaryGetValue (attributes, kCTFontAttributeName);
          if (font_in_run == NULL)
            break;
          if (!mac_ctfont_equal_in_postscript_name (macfont, font_in_run))
            break;
        }
      if (i < nruns)
        {
          CFRelease (ctline);
          ctline = NULL;
        }
    }

  return ctline;
}

static CFIndex
mac_ctfont_shape (CTFontRef font, CFStringRef string,
                  struct mac_glyph_layout *glyph_layouts, CFIndex glyph_len)
{
  CFIndex used, result = 0;
  CTLineRef ctline = mac_ctfont_create_line_with_string_and_font (string, font);

  if (ctline == NULL)
    return 0;

  used = CTLineGetGlyphCount (ctline);
  if (used <= glyph_len)
    {
      CFArrayRef ctruns = CTLineGetGlyphRuns (ctline);
      CFIndex k, ctrun_count = CFArrayGetCount (ctruns);
      CGFloat total_advance = 0;
      CFIndex total_glyph_count = 0;

      for (k = 0; k < ctrun_count; k++)
        {
          CTRunRef ctrun = CFArrayGetValueAtIndex (ctruns, k);
          CFIndex i, min_location, glyph_count = CTRunGetGlyphCount (ctrun);
          struct mac_glyph_layout *glbuf = glyph_layouts + total_glyph_count;
          CFRange string_range, comp_range, range;
          CFIndex *permutation;

          if (CTRunGetStatus (ctrun) & kCTRunStatusRightToLeft)
            permutation = xmalloc (sizeof (CFIndex) * glyph_count);
          else
            permutation = NULL;

#define RIGHT_TO_LEFT_P permutation

          /* Now the `comp_range' member of struct mac_glyph_layout is
             temporarily used as a work area such that:
             glbuf[i].comp_range.location =
             min {compRange[i + 1].location, ...,
		     compRange[glyph_count - 1].location,
		     maxRange (stringRangeForCTRun)}
             glbuf[i].comp_range.length = maxRange (compRange[i])
             where compRange[i] is the range of composed characters
             containing i-th glyph.  */
          string_range = CTRunGetStringRange (ctrun);
          min_location = string_range.location + string_range.length;
          for (i = 0; i < glyph_count; i++)
            {
              struct mac_glyph_layout *gl = glbuf + glyph_count - i - 1;
              CFIndex glyph_index;
              CFRange rng;

              if (!RIGHT_TO_LEFT_P)
                glyph_index = glyph_count - i - 1;
              else
                glyph_index = i;
              CTRunGetStringIndices (ctrun, CFRangeMake (glyph_index, 1),
                                     &gl->string_index);
              rng =
                CFStringGetRangeOfComposedCharactersAtIndex (string,
                                                             gl->string_index);
              gl->comp_range.location = min_location;
              gl->comp_range.length = rng.location + rng.length;
              if (rng.location < min_location)
                min_location = rng.location;
            }

          /* Fill the `comp_range' member of struct mac_glyph_layout,
             and setup a permutation for right-to-left text.  */
          comp_range = CFRangeMake (string_range.location, 0);
          range = CFRangeMake (0, 0);
          while (1)
            {
              struct mac_glyph_layout *gl =
                glbuf + range.location + range.length;

              if (gl->comp_range.length
                  > comp_range.location + comp_range.length)
                comp_range.length = gl->comp_range.length - comp_range.location;
              min_location = gl->comp_range.location;
              range.length++;

              if (min_location >= comp_range.location + comp_range.length)
                {
                  comp_range.length = min_location - comp_range.location;
                  for (i = 0; i < range.length; i++)
                    {
                      glbuf[range.location + i].comp_range = comp_range;
                      if (RIGHT_TO_LEFT_P)
                        permutation[range.location + i] =
                          range.location + range.length - i - 1;
                    }

                  comp_range = CFRangeMake (min_location, 0);
                  range.location += range.length;
                  range.length = 0;
                  if (range.location == glyph_count)
                    break;
                }
            }

          /* Then fill the remaining members.  */
          for (range = CFRangeMake (0, 1); range.location < glyph_count;
               range.location++)
            {
              struct mac_glyph_layout *gl;
              CGPoint position;

              if (!RIGHT_TO_LEFT_P)
                gl = glbuf + range.location;
              else
                {
                  CFIndex src, dest;

                  src = glyph_count - 1 - range.location;
                  dest = permutation[src];
                  gl = glbuf + dest;
                  if (src < dest)
                    {
                      CFIndex tmp = gl->string_index;

                      gl->string_index = glbuf[src].string_index;
                      glbuf[src].string_index = tmp;
                    }
                }
              CTRunGetGlyphs (ctrun, range, &gl->glyph_id);

              CTRunGetPositions (ctrun, range, &position);
              gl->advance_delta = position.x - total_advance;
              gl->baseline_delta = position.y;
              gl->advance = (gl->advance_delta
                             + CTRunGetTypographicBounds (ctrun, range,
                                                          NULL, NULL, NULL));
              total_advance += gl->advance;
            }

          if (RIGHT_TO_LEFT_P)
            xfree (permutation);

#undef RIGHT_TO_LEFT_P

          total_glyph_count += glyph_count;
        }

      result = used;
    }
  CFRelease (ctline);

  return result;
}

/* The function below seems to cause a memory leak for the CFString
   created by CFStringCreateWithCharacters as of Mac OS X 10.5.8 and
   10.6.3.  For now, we use the NSGlyphInfo version instead.  */
#if USE_CT_GLYPH_INFO
static CGGlyph
mac_ctfont_get_glyph_for_cid (CTFontRef font, CTCharacterCollection collection,
                              CGFontIndex cid)
{
  CGGlyph result = kCGFontIndexInvalid;
  UniChar characters[] = {0xfffd};
  CFStringRef string;
  CFAttributedStringRef attr_string = NULL;
  CTLineRef ctline = NULL;

  string = CFStringCreateWithCharacters (NULL, characters,
                                         ARRAYELTS (characters));

  if (string)
    {
      CTGlyphInfoRef glyph_info =
        CTGlyphInfoCreateWithCharacterIdentifier (cid, collection, string);
      CFDictionaryRef attributes = NULL;

      if (glyph_info)
        {
          CFStringRef keys[] = {kCTFontAttributeName,
                                kCTGlyphInfoAttributeName};
          CFTypeRef values[] = {font, glyph_info};

          attributes = CFDictionaryCreate (NULL, (const void **) keys,
                                           (const void **) values,
                                           ARRAYELTS (keys),
                                           &kCFTypeDictionaryKeyCallBacks,
                                           &kCFTypeDictionaryValueCallBacks);
          CFRelease (glyph_info);
        }
      if (attributes)
        {
          attr_string = CFAttributedStringCreate (NULL, string, attributes);
          CFRelease (attributes);
        }
      CFRelease (string);
    }
  if (attr_string)
    {
      ctline = CTLineCreateWithAttributedString (attr_string);
      CFRelease (attr_string);
    }
  if (ctline)
    {
      CFArrayRef runs = CTLineGetGlyphRuns (ctline);

      if (CFArrayGetCount (runs) > 0)
        {
          CTRunRef run = CFArrayGetValueAtIndex (runs, 0);
          CFDictionaryRef attributes = CTRunGetAttributes (run);

          if (attributes)
            {
              CTFontRef font_in_run =
                CFDictionaryGetValue (attributes, kCTFontAttributeName);

              if (font_in_run
                  && mac_ctfont_equal_in_postscript_name (font_in_run, font))
                {
                  CTRunGetGlyphs (run, CFRangeMake (0, 1), &result);
                  if (result >= CTFontGetGlyphCount (font))
                    result = kCGFontIndexInvalid;
                }
            }
        }
      CFRelease (ctline);
    }

  return result;
}
#endif

static CFArrayRef
mac_font_copy_default_descriptors_for_language (CFStringRef language)
{
  CFArrayRef result = NULL;

#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1080
  if (CTFontCopyDefaultCascadeListForLanguages != NULL)
#endif
    {
      CTFontRef user_font =
        CTFontCreateUIFontForLanguage (kCTFontUserFontType, 0, language);

      if (user_font)
        {
          CFArrayRef languages =
            CFArrayCreate (NULL, (const void **) &language, 1,
                           &kCFTypeArrayCallBacks);

          if (languages)
            {
              result = CTFontCopyDefaultCascadeListForLanguages (user_font,
                                                                 languages);
              CFRelease (languages);
            }
          CFRelease (user_font);
        }
    }
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1080
  else		/* CTFontCopyDefaultCascadeListForLanguages == NULL */
#endif
#endif	/* MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 */
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1080
    {
      CFIndex i;

      for (i = 0; macfont_language_default_font_names[i].language; i++)
        {
          if (CFEqual (macfont_language_default_font_names[i].language,
                       language))
            {
              CFMutableArrayRef descriptors =
                CFArrayCreateMutable (NULL, 0, &kCFTypeArrayCallBacks);

              if (descriptors)
                {
                  CFIndex j;

                  for (j = 0;
                       macfont_language_default_font_names[i].font_names[j];
                       j++)
                    {
                      CFDictionaryRef attributes =
                        CFDictionaryCreate (NULL,
                                            ((const void **)
                                             &MAC_FONT_NAME_ATTRIBUTE),
                                            ((const void **)
                                             &macfont_language_default_font_names[i].font_names[j]),
                                            1, &kCFTypeDictionaryKeyCallBacks,
                                            &kCFTypeDictionaryValueCallBacks);

                      if (attributes)
                        {
                          FontDescriptorRef pat_desc =
                            mac_font_descriptor_create_with_attributes (attributes);

                          if (pat_desc)
                            {
                              FontDescriptorRef descriptor =
                                mac_font_descriptor_create_matching_font_descriptor (pat_desc, NULL);

                              if (descriptor)
                                {
                                  CFArrayAppendValue (descriptors, descriptor);
                                  CFRelease (descriptor);
                                }
                              CFRelease (pat_desc);
                            }
                          CFRelease (attributes);
                        }
                    }
                  result = descriptors;
                }
              break;
            }
        }
    }
#endif

  return result;
}

static CFStringRef
mac_font_copy_default_name_for_charset_and_languages (CFCharacterSetRef charset,
                                                      CFArrayRef languages)
{
  CFStringRef result = NULL;
  CFStringRef language = CFArrayGetValueAtIndex (languages, 0);
  CFArrayRef descriptors =
    mac_font_copy_default_descriptors_for_language (language);

  if (descriptors)
    {
      CFIndex i, count = CFArrayGetCount (descriptors);

      for (i = 0; i < count; i++)
        {
          FontDescriptorRef descriptor =
            CFArrayGetValueAtIndex (descriptors, i);

          if (macfont_supports_charset_and_languages_p (descriptor, charset,
                                                        Qnil, languages))
            {
              CFStringRef family =
                mac_font_descriptor_copy_attribute (descriptor,
                                                    MAC_FONT_FAMILY_NAME_ATTRIBUTE);
              if (family)
                {
                  if (!CFStringHasPrefix (family, CFSTR ("."))
                      && !CFEqual (family, CFSTR ("LastResort")))
                    {
                      result = family;
                      break;
                    }
                  else
                    CFRelease (family);
                }
            }
        }
      CFRelease (descriptors);
    }

  return result;
}

void *
macfont_get_nsctfont (struct font *font)
{
  struct macfont_info *macfont_info = (struct macfont_info *) font;
  FontRef macfont = macfont_info->macfont;

  return (void *) macfont;
}

void
mac_register_font_driver (struct frame *f)
{
  register_font_driver (&macfont_driver, f);
}


void
syms_of_macfont (void)
{
  static struct font_driver mac_font_driver;

  /* Core Text, for Mac OS X.  */
  DEFSYM (Qmac_ct, "mac-ct");
  macfont_driver.type = Qmac_ct;
  register_font_driver (&macfont_driver, NULL);

  /* The font property key specifying the font design destination.  The
     value is an unsigned integer code: 0 for WYSIWYG, and 1 for Video
     text.  (See the documentation of X Logical Font Description
     Conventions.)  In the Mac font driver, 1 means the screen font is
     used for calculating some glyph metrics.  You can see the
     difference with Monaco 8pt or 9pt, for example.  */
  DEFSYM (QCdestination, ":destination");

  /* The boolean-valued font property key specifying the use of leading.  */
  DEFSYM (QCminspace, ":minspace");
}