summaryrefslogtreecommitdiffstats
path: root/macosx/tkMacOSXFont.c
blob: 66d92f2ee7d432282feda3fb2f0a845c46d08abe (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
/*
 * tkMacOSXFont.c --
 *
 *	Contains the Macintosh implementation of the platform-independant
 *	font package interface. This version uses ATSU instead of Quickdraw.
 *
 * Copyright 2002-2004 Benjamin Riefenstahl, Benjamin.Riefenstahl@epost.de
 * Copyright (c) 2006-2008 Daniel A. Steffen <das@users.sourceforge.net>
 *
 * Some functions were originally copied verbatim from the QuickDraw version
 * of tkMacOSXFont.c, which had these copyright notices:
 *
 * Copyright (c) 1990-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * Todos:
 *
 * - Get away from Font Manager and Quickdraw functions as much as possible,
 *   replace with ATS functions instead.
 *
 * - Use Font Manager functions to translate ids from ATS to Font Manager
 *   instead of just assuming that they are the same.
 *
 * - Get a second font register going for fonts that are not assigned to a
 *   font family by the OS. On my system I have 27 fonts of that type,
 *   Hebrew, Arabic and Hindi fonts that actually come with the system.
 *   FMGetFontFamilyInstanceFromFont() returns -981 (kFMInvalidFontFamilyErr)
 *   for these and they are not listed when enumerating families, but they
 *   are when enumerating fonts directly. The problem that the OS sees may
 *   be that at least some of them do not contain any Latin characters. Note
 *   that such fonts can not be used for controls, because controls
 *   definitely require a family id (this assertion needs testing).
 *
 * RCS: @(#) $Id: tkMacOSXFont.c,v 1.37.2.1 2008/06/19 00:10:54 das Exp $
 */

#include "tkMacOSXPrivate.h"
#include "tkMacOSXFont.h"

/*
#ifdef TK_MAC_DEBUG
#define TK_MAC_DEBUG_FONTS
#endif
*/

/*
 * Problem: The sum of two parts is not the same as the whole. In particular
 * the width of two separately measured strings will usually be larger than
 * the width of them pasted together. Tk has a design bug here, because it
 * generally assumes that this kind of arithmetic works.
 * To workaround this, #define TK_MAC_COALESCE_LINE to 1 below, we then avoid
 * lines that tremble and shiver while the cursor passes through them by
 * undercutting the system and behind the scenes pasting strings together that
 * look like they are on the same line and adjacent and that are drawn with
 * the same font. To do this we need some global data.
 */
#define TK_MAC_COALESCE_LINE 0

/*
 * The following structure represents our Macintosh-specific implementation
 * of a font object.
 */

typedef struct {
    TkFont font;		/* Stuff used by generic font package. Must
				 * be first in structure. */

    /*
     * The ATSU view of the font and other text properties. Used for drawing
     * and measuring.
     */

    ATSUFontID atsuFontId;	/* == FMFont. */
    ATSUTextLayout atsuLayout;	/* ATSU layout object, representing the whole
				 * text that ATSU sees with some option
				 * bits. */
    ATSUStyle atsuStyle;	/* ATSU style object, representing a run of
				 * text with the same properties. */

    /*
     * The QuickDraw view of the font. Used to configure controls.
     */

    FMFontFamily qdFont;	/* == FMFontFamilyId, Carbon replacement for
				 * QD face numbers. */
    short qdSize;		/* Font size in points. */
    short qdStyle;		/* QuickDraw style bits. */
} MacFont;

/*
 * Information about font families, initialized at startup time. Font
 * families are described by a mapping from UTF-8 names to MacOS font family
 * IDs. The whole list is kept as the sorted array "familyList", allocated
 * with ckrealloc().
 *
 * Note: This would have been easier, if we could just have used Tcl hash
 * arrays. Unfortunately there seems to be no pre-packaged
 * non-case-sensitive version of that available.
 */

typedef struct {
    const char * name;
    FMFontFamily familyId;
} MacFontFamily;

static MacFontFamily * familyList = NULL;
static int
    familyListNextFree = 0,	/* The next free slot in familyList. */
    familyListMaxValid = 0,	/* The top of the sorted area. */
    familyListSize = 0;		/* The size of the whole array. */

/*
 * A simple one-shot sub-allocator for fast and efficient allocation of
 * strings. Used by the familyList array for the names. These strings are
 * only allocated once at startup and never freed. If you ever need to
 * re-initialize this, you can just ckfree() all the StringBlocks in the list
 * and start over.
 */

#define STRING_BLOCK_MAX (1024-8)	/* Make sizeof(StringBlock) ==
					 * 1024. */
typedef struct StringBlock {
    struct StringBlock *next;		/* Starting from "stringMemory" these
					 * blocks form a linked list. */
    int nextFree;			/* Top of the used area in the
					 * "strings" member. */
    char strings[STRING_BLOCK_MAX];	/* The actual memory managed here. */
} StringBlock;

static StringBlock *stringMemory = NULL;

#if TK_MAC_COALESCE_LINE
static Tcl_DString currentLine;	/* The current line as seen so far. This
				 * contains a Tcl_UniChar DString. */
static int
    currentY = -1,		/* The Y position (row in pixels) of the
				 * current line. */
    currentLeft = -1,		/* The left edge (pixels) of the current
				 * line. */
    currentRight = -1;		/* The right edge (pixels) of the current
				 * line. */
static const MacFont *currentFontPtr = NULL;
				/* The font of the current line. */
#endif /* TK_MAC_COALESCE_LINE */

static int antialiasedTextEnabled;

/*
 * The names for our "native" fonts.
 */

#define SYSTEMFONT_NAME		"system"
#define APPLFONT_NAME		"application"
#define MENUITEMFONT_NAME	"menu"

struct SystemFontMapEntry {
    const ThemeFontID id;
    const char *systemName;
    const char *tkName;
    const char *tkName1;
};

#define ThemeFont(n, ...) { kTheme##n##Font, "system" #n "Font", ##__VA_ARGS__ }
static const struct SystemFontMapEntry systemFontMap[] = {
    ThemeFont(System, 			"TkDefaultFont", "TkIconFont"),
    ThemeFont(EmphasizedSystem,		"TkCaptionFont"),
    ThemeFont(SmallSystem,		"TkHeadingFont", "TkTooltipFont"),
    ThemeFont(SmallEmphasizedSystem),
    ThemeFont(Application,		"TkTextFont"),
    ThemeFont(Label,			"TkSmallCaptionFont"),
    ThemeFont(Views),
    ThemeFont(MenuTitle),
    ThemeFont(MenuItem,			"TkMenuFont"),
    ThemeFont(MenuItemMark),
    ThemeFont(MenuItemCmdKey),
    ThemeFont(WindowTitle),
    ThemeFont(PushButton),
    ThemeFont(UtilityWindowTitle),
    ThemeFont(AlertHeader),
    ThemeFont(Toolbar),
    ThemeFont(MiniSystem),
    { kThemeSystemFontDetail,		"systemDetailSystemFont" },
    { kThemeSystemFontDetailEmphasized,	"systemDetailEmphasizedSystemFont" },
    { -1, NULL }
};
#undef ThemeFont

/*
 * Procedures used only in this file.
 */

static void LayoutSetString(const MacFont *fontPtr,
	const TkMacOSXDrawingContext *drawingContextPtr,
	const UniChar * uchars, int ulen);

/*
 * The actual workers.
 */

static int MeasureStringWidth(const MacFont *fontPtr, int start, int end);

#if TK_MAC_COALESCE_LINE
static const Tcl_UniChar *UpdateLineBuffer(const MacFont *fontPtr,
	const TkMacOSXDrawingContext *drawingContextPtr, const char *source,
	int numBytes, int x, int y, int * offset);
#endif /* TK_MAC_COALESCE_LINE */

/*
 * Initialization and setup of a font data structure.
 */

static const char *FamilyNameForFamilyID(FMFontFamily familyId);
static void InitFont(FMFontFamily familyId, const char *familyName,
	int size, int qdStyle, MacFont *fontPtr);
static void InitATSUObjects(FMFontFamily familyId, short qdsize, short qdStyle,
	ATSUFontID *fontIdPtr, ATSUTextLayout *layoutPtr, ATSUStyle *stylePtr);
static void InitATSUStyle(ATSUFontID fontId, short ptSize, short qdStyle,
	ATSUStyle style);
static void SetFontFeatures(ATSUFontID fontId, int fixed, ATSUStyle style);
static void AdjustFontHeight(MacFont *fontPtr);
static void InitATSULayout(const TkMacOSXDrawingContext *drawingContextPtr,
	ATSUTextLayout layout, int fixed);
static void ReleaseFont(MacFont *fontPtr);

/*
 * Finding fonts by name.
 */

static const MacFontFamily *FindFontFamilyOrAlias(const char *name);
static const MacFontFamily *FindFontFamilyOrAliasOrFallback(const char *name);

/*
 * Doing interesting things with font families and fonts.
 */

static void InitFontFamilies(void);
static OSStatus GetFontFamilyName(FMFontFamily fontFamily, char *name,
	int numBytes);

/*
 * Accessor functions and internal utilities for the font family list.
 */

static const MacFontFamily *AddFontFamily(const char *name,
	FMFontFamily familyId);
static const MacFontFamily *FindFontFamily(const char *name);
static Tcl_Obj *EnumFontFamilies(void);

static OSStatus FontFamilyEnumCallback(ATSFontFamilyRef family, void *refCon);
static void SortFontFamilies(void);
static int CompareFontFamilies(const void *vp1, const void *vp2);
static const char *AddString(const char *in);

static OSStatus GetThemeFontAndFamily(const ThemeFontID themeFontId,
	FMFontFamily *fontFamily, unsigned char *fontName, SInt16 *fontSize,
	Style *fontStyle);
static void InitSystemFonts(TkMainInfo *mainPtr);
static int CreateNamedSystemFont(Tcl_Interp *interp, Tk_Window tkwin,
	const char* name, TkFontAttributes *faPtr);


/*
 *-------------------------------------------------------------------------
 *
 * TkpFontPkgInit --
 *
 *	This procedure is called when an application is created. It
 *	initializes all the structures that are used by the
 *	platform-dependant code on a per application basis.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Initialization of variables local to this file.
 *
 *-------------------------------------------------------------------------
 */

void
TkpFontPkgInit(
    TkMainInfo *mainPtr)	/* The application being created. */
{
    InitFontFamilies();
    InitSystemFonts(mainPtr);

#if TK_MAC_COALESCE_LINE
    Tcl_DStringInit(&currentLine);
#endif
}

/*
 *-------------------------------------------------------------------------
 *
 * InitSystemFonts --
 *
 *	Initialize named system fonts.
 *
 * Results:
 *
 *	None.
 *
 * Side effects:
 *
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static void
InitSystemFonts(
    TkMainInfo *mainPtr)
{
    Tcl_Interp *interp = mainPtr->interp;
    Tk_Window tkwin = (Tk_Window) mainPtr->winPtr;
    const struct SystemFontMapEntry *systemFont = systemFontMap;
    TkFontAttributes fa;

    /* force this for now */
    if (!mainPtr->winPtr->mainPtr) {
	mainPtr->winPtr->mainPtr = mainPtr;
    }
    TkInitFontAttributes(&fa);
    while (systemFont->systemName) {
	Str255 fontName;
	SInt16 fontSize;
	Style  fontStyle;

	if (GetThemeFont(systemFont->id, smSystemScript, fontName,
		&fontSize, &fontStyle) == noErr) {
	    CopyPascalStringToC(fontName, (char*)fontName);
	    fa.family = Tk_GetUid((char*)fontName);
	    fa.size = fontSize;
	    fa.weight = (fontStyle & bold) ? TK_FW_BOLD : TK_FW_NORMAL;
	    fa.slant = (fontStyle & italic) ? TK_FS_ITALIC : TK_FS_ROMAN;
	    fa.underline = ((fontStyle & underline) != 0);
	    CreateNamedSystemFont(interp, tkwin, systemFont->systemName, &fa);
	    if (systemFont->tkName) {
		CreateNamedSystemFont(interp, tkwin, systemFont->tkName, &fa);
	    }
	    if (systemFont->tkName1) {
		CreateNamedSystemFont(interp, tkwin, systemFont->tkName1, &fa);
	    }
	}
	systemFont++;
    }
    fa.family = Tk_GetUid("monaco");
    fa.size = 11;
    fa.weight = TK_FW_NORMAL;
    fa.slant = TK_FS_ROMAN;
    fa.underline = 0;
    CreateNamedSystemFont(interp, tkwin, "TkFixedFont", &fa);
}

/*
 *-------------------------------------------------------------------------
 *
 * CreateNamedSystemFont --
 *
 *	Register a system font with the Tk named font mechanism.
 *
 * Results:
 *
 *	Result from TkCreateNamedFont().
 *
 * Side effects:
 *
 *	A new named font is added to the Tk font registry.
 *
 *-------------------------------------------------------------------------
 */

static int
CreateNamedSystemFont(
    Tcl_Interp *interp,
    Tk_Window tkwin,
    const char* name,
    TkFontAttributes *faPtr)
{
    TkDeleteNamedFont(NULL, tkwin, name);
    return TkCreateNamedFont(interp, tkwin, name, faPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * GetThemeFontAndFamily --
 *
 *	Wrapper around the GetThemeFont and FMGetFontFamilyFromName APIs.
 *
 *---------------------------------------------------------------------------
 */

OSStatus
GetThemeFontAndFamily(
    const ThemeFontID themeFontId,
    FMFontFamily* fontFamily,
    unsigned char *fontName,
    SInt16 *fontSize,
    Style *fontStyle)
{
    OSStatus err = ChkErr(GetThemeFont, themeFontId, smSystemScript, fontName,
	    fontSize, fontStyle);

    if (err == noErr) {
	*fontFamily = FMGetFontFamilyFromName(fontName);
	if (*fontFamily == kInvalidFontFamily) {
	    err = kFMInvalidFontFamilyErr;
	    TkMacOSXDbgMsg("FMGetFontFamilyFromName failed.");
	}
    }

    return err;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpGetNativeFont --
 *
 *	Map a platform-specific native font name to a TkFont.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the
 *	native font. If a native font by the given name could not be
 *	found, the return value is NULL.
 *
 *	Every call to this procedure returns a new TkFont structure, even
 *	if the name has already been seen before. The caller should call
 *	TkpDeleteFont() when the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated
 *	with the generic TkFont when this function returns and releasing
 *	the contents of the generics TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

TkFont *
TkpGetNativeFont(
    Tk_Window tkwin,		/* For display where font will be used. */
    const char *name)		/* Platform-specific font name. */
{
    ThemeFontID themeFontId;
    FMFontFamily fontFamily;
    Str255 fontName;
    SInt16 fontSize;
    Style  fontStyle;
    MacFont *fontPtr;

    if (strcmp(name, SYSTEMFONT_NAME) == 0) {
	themeFontId = kThemeSystemFont;
    } else if (strcmp(name, APPLFONT_NAME) == 0) {
	themeFontId = kThemeApplicationFont;
    } else if (strcmp(name, MENUITEMFONT_NAME) == 0) {
	themeFontId = kThemeMenuItemFont;
    } else {
	return NULL;
    }
    if (GetThemeFontAndFamily(themeFontId, &fontFamily, fontName, &fontSize,
	    &fontStyle) != noErr) {
	return NULL;
    }
    CopyPascalStringToC(fontName, (char*)fontName);

    fontPtr = (MacFont *) ckalloc(sizeof(MacFont));
    InitFont(fontFamily, (char*)fontName, fontSize, fontStyle, fontPtr);

    return (TkFont *) fontPtr;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpGetFontFromAttributes --
 *
 *	Given a desired set of attributes for a font, find a font with the
 *	closest matching attributes.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the font
 *	with the desired attributes. If a font with the desired attributes
 *	could not be constructed, some other font will be substituted
 *	automatically.
 *
 *	Every call to this procedure returns a new TkFont structure, even
 *	if the specified attributes have already been seen before. The
 *	caller should call TkpDeleteFont() to free the platform- specific
 *	data when the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated
 *	with the generic TkFont when this function returns and releasing
 *	the contents of the generic TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

TkFont *
TkpGetFontFromAttributes(
    TkFont *tkFontPtr,		/* If non-NULL, store the information in this
				 * existing TkFont structure, rather than
				 * allocating a new structure to hold the
				 * font; the existing contents of the font
				 * will be released. If NULL, a new TkFont
				 * structure is allocated. */
    Tk_Window tkwin,		/* For display where font will be used. */
    const TkFontAttributes *faPtr)
				/* Set of attributes to match. */
{
    short qdStyle;
    FMFontFamily familyId;
    const char *name;
    const MacFontFamily *familyPtr;
    MacFont *fontPtr;

    familyId = GetAppFont();
    name = NULL;
    qdStyle = 0;

    if (faPtr->family != NULL) {
	familyPtr = FindFontFamilyOrAliasOrFallback(faPtr->family);
	if (familyPtr != NULL) {
	    name = familyPtr->name;
	    familyId = familyPtr->familyId;
	}
    }

    if (faPtr->weight != TK_FW_NORMAL) {
	qdStyle |= bold;
    }
    if (faPtr->slant != TK_FS_ROMAN) {
	qdStyle |= italic;
    }
    if (faPtr->underline) {
	qdStyle |= underline;
    }
    if (tkFontPtr == NULL) {
	fontPtr = (MacFont *) ckalloc(sizeof(MacFont));
    } else {
	fontPtr = (MacFont *) tkFontPtr;
	ReleaseFont(fontPtr);
    }
    InitFont(familyId, name, TkFontGetPoints(tkwin, faPtr->size),
	    qdStyle, fontPtr);

    return (TkFont *) fontPtr;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpDeleteFont --
 *
 *	Called to release a font allocated by TkpGetNativeFont() or
 *	TkpGetFontFromAttributes(). The caller should have already
 *	released the fields of the TkFont that are used exclusively by the
 *	generic TkFont code.
 *
 * Results:
 *	TkFont is deallocated.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

void
TkpDeleteFont(
    TkFont *tkFontPtr)		/* Token of font to be deleted. */
{
    ReleaseFont((MacFont *) tkFontPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpGetFontFamilies --
 *
 *	Return information about the font families that are available on
 *	the display of the given window.
 *
 * Results:
 *	Modifies interp's result object to hold a list of all the available
 *	font families.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

void
TkpGetFontFamilies(
    Tcl_Interp *interp,		/* Interp to hold result. */
    Tk_Window tkwin)		/* For display to query. */
{
    Tcl_SetObjResult(interp, EnumFontFamilies());
}

/*
 *-------------------------------------------------------------------------
 *
 * TkpGetSubFonts --
 *
 *	A function used by the testing package for querying the actual
 *	screen fonts that make up a font object.
 *
 * Results:
 *	Modifies interp's result object to hold a list containing the names
 *	of the screen fonts that make up the given font object.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

void
TkpGetSubFonts(
    Tcl_Interp *interp,		/* Interp to hold result. */
    Tk_Font tkfont)		/* Font object to query. */
{
    /* We don't know much about our fallback fonts, ATSU does all that for
     * us. We could use ATSUMatchFont to implement this function. But as
     * the information is only used for testing, such an effort seems not
     * very useful. */
}

/*
 *----------------------------------------------------------------------
 *
 * TkpGetFontAttrsForChar --
 *
 *	Retrieve the font attributes of the actual font used to render a
 *	given character.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The font attributes are stored in *faPtr.
 *
 *----------------------------------------------------------------------
 */

void
TkpGetFontAttrsForChar(
    Tk_Window tkwin,		/* Window on the font's display */
    Tk_Font tkfont,		/* Font to query */
    Tcl_UniChar c,		/* Character of interest */
    TkFontAttributes* faPtr)	/* Output: Font attributes */
{
    const MacFont * fontPtr = (const MacFont *) tkfont;
    UniChar uchar = c;
    TkMacOSXDrawingContext drawingContext;
    OSStatus err;
    ATSUFontID fontId;
    UniCharArrayOffset changedOffset;
    UniCharCount changedLength;

    /*
     * Most of the attributes are just copied from the base font. This
     * assumes that all fonts can have all attributes.
     */

    *faPtr = fontPtr->font.fa;

    /*
     * But the name of the actual font may still differ, so we activate the
     * string as an ATSU layout and ask ATSU about the fallback.
     */
    if (!TkMacOSXSetupDrawingContext(Tk_WindowId(tkwin), NULL, 1,
	    &drawingContext)) {
	Tcl_Panic("TkpGetFontAttrsForChar: drawingContext not setup");
    }

    LayoutSetString(fontPtr, &drawingContext, &uchar, 1);

    fontId = fontPtr->atsuFontId;
    err = ATSUMatchFontsToText(
	fontPtr->atsuLayout, 0, 1,
	&fontId, &changedOffset, &changedLength);
    if (err != kATSUFontsMatched && err != noErr) {
	TkMacOSXDbgMsg("Can't match \\u%04X", (unsigned) c);
    }

    if (err == kATSUFontsMatched) {
	/*
	 * A fallback was used and the actual font is in fontId. Determine
	 * the name.
	 */

	FMFontFamily fontFamilyId;
	FMFontStyle fontStyle;
	int i;

	err = ChkErr(FMGetFontFamilyInstanceFromFont, fontId, &fontFamilyId,
		&fontStyle);
	if (err == noErr) {
	    /*
	     * Find the canonical name in our global list.
	     */

	    for (i=0; i<familyListMaxValid; ++i) {
		if (fontFamilyId == familyList[i].familyId) {
		    faPtr->family = familyList[i].name;
		    break;
		}
	    }
	    if (i >= familyListMaxValid) {
		TkMacOSXDbgMsg("Can't find font %d for \\u%04X", fontFamilyId,
			(unsigned) c);
	    }
	}
    }

    TkMacOSXRestoreDrawingContext(&drawingContext);
}

/*
 *---------------------------------------------------------------------------
 *
 * Tk_MeasureChars --
 *
 *	Determine the number of characters from the string that will fit in
 *	the given horizontal span. The measurement is done under the
 *	assumption that Tk_DrawChars() will be used to actually display the
 *	characters.
 *
 *	With ATSUI we need the line context to do this right, so we have the
 *	actual implementation in TkpMeasureCharsInContext().
 *
 * Results:
 *	The return value is the number of bytes from source that fit into the
 *	span that extends from 0 to maxLength. *lengthPtr is filled with the
 *	x-coordinate of the right edge of the last character that did fit.
 *
 * Side effects:
 *	None.
 *
 * Todo:
 *	Effects of the "flags" parameter are untested.
 *
 *---------------------------------------------------------------------------
 */

int
Tk_MeasureChars(
    Tk_Font tkfont,		/* Font in which characters will be drawn. */
    const char *source,		/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. */
    int numBytes,		/* Maximum number of bytes to consider from
				 * source string. */
    int maxLength,		/* If >= 0, maxLength specifies the longest
				 * permissible line length; don't consider any
				 * character that would cross this x-position.
				 * If < 0, then line length is unbounded and
				 * the flags argument is ignored. */
    int flags,			/* Various flag bits OR-ed together:
				 * TK_PARTIAL_OK means include the last char
				 * which only partially fit on this line.
				 * TK_WHOLE_WORDS means stop on a word
				 * boundary, if possible. TK_AT_LEAST_ONE
				 * means return at least one character even if
				 * no characters fit. */
    int *lengthPtr)		/* Filled with x-location just after the
				 * terminating character. */
{
    return TkpMeasureCharsInContext(tkfont, source, numBytes, 0, numBytes,
	    maxLength, flags, lengthPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpMeasureCharsInContext --
 *
 *	Determine the number of bytes from the string that will fit in the
 *	given horizontal span. The measurement is done under the assumption
 *	that TkpDrawCharsInContext() will be used to actually display the
 *	characters.
 *
 *	This one is almost the same as Tk_MeasureChars(), but with access to
 *	all the characters on the line for context.
 *
 * Results:
 *	The return value is the number of bytes from source that
 *	fit into the span that extends from 0 to maxLength. *lengthPtr is
 *	filled with the x-coordinate of the right edge of the last
 *	character that did fit.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkpMeasureCharsInContext(
    Tk_Font tkfont,		/* Font in which characters will be drawn. */
    const char * source,	/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. */
    int numBytes,		/* Maximum number of bytes to consider from
				 * source string in all. */
    int rangeStart,		/* Index of first byte to measure. */
    int rangeLength,		/* Length of range to measure in bytes. */
    int maxLength,		/* If >= 0, maxLength specifies the longest
				 * permissible line length; don't consider any
				 * character that would cross this x-position.
				 * If < 0, then line length is unbounded and
				 * the flags argument is ignored. */
    int flags,			/* Various flag bits OR-ed together:
				 * TK_PARTIAL_OK means include the last char
				 * which only partially fits on this line.
				 * TK_WHOLE_WORDS means stop on a word
				 * boundary, if possible. TK_AT_LEAST_ONE
				 * means return at least one character even
				 * if no characters fit.  If TK_WHOLE_WORDS
				 * and TK_AT_LEAST_ONE are set and the first
				 * word doesn't fit, we return at least one
				 * character or whatever characters fit into
				 * maxLength.  TK_ISOLATE_END means that the
				 * last character should not be considered in
				 * context with the rest of the string (used
				 * for breaking lines). */
    int *lengthPtr)		/* Filled with x-location just after the
				 * terminating character. */
{
    const MacFont *fontPtr = (const MacFont *) tkfont;
    int curX = -1, curByte = 0;
    UniChar *uchars;
    int ulen;
    UniCharArrayOffset urstart, urlen, urend;
    Tcl_DString ucharBuffer;
    int forceCharacterMode = 0;

    /*
     * Sanity checks.
     */

    if (rangeStart < 0 || (rangeStart+rangeLength) > numBytes) {
	TkMacOSXDbgMsg("Bad parameters");
	*lengthPtr = 0;
	return 0;
    }

    /*
     * Get simple no-brainers out of the way.
     */

    if (rangeLength == 0 || (maxLength == 0 && !(flags & TK_AT_LEAST_ONE))) {
	*lengthPtr = 0;
	return 0;
    }

    Tcl_DStringInit(&ucharBuffer);
    uchars = Tcl_UtfToUniCharDString(source, numBytes, &ucharBuffer);
    ulen = Tcl_DStringLength(&ucharBuffer) / sizeof(Tcl_UniChar);
    LayoutSetString(fontPtr, NULL, uchars, ulen);

    urstart = Tcl_NumUtfChars(source, rangeStart);
    urlen = Tcl_NumUtfChars(source+rangeStart,rangeLength);
    urend = urstart + urlen;

    if (maxLength < 0) {
	curX = MeasureStringWidth(fontPtr, urstart, urend);
	curByte = rangeLength;
    } else {
	UniCharArrayOffset offset = 0;
	OSStatus err;

	/*
	 * Have some upper limit on the size actually used.
	 */

	if (maxLength > 32767) {
	    maxLength = 32767;
	}

	offset = urstart;
	err = noErr;

	if (maxLength > 1) {
	    /*
	     * Let the system do some work by calculating a line break.
	     *
	     * Somehow ATSUBreakLine seems to assume that it needs at least
	     * one pixel padding. So we add one to the limit. Note also
	     * that ATSUBreakLine sometimes runs into an endless loop when
	     * the third parameter is equal or less than IntToFixed(2), so we
	     * need at least IntToFixed(3) (at least that's the current state
	     * of my knowledge).
	     */

	    err = ATSUBreakLine(fontPtr->atsuLayout, urstart,
		    IntToFixed(maxLength+1), false, /* !iUseAsSoftLineBreak */
		    &offset);

	    /*
	     * There is no way to signal an error from this routine, so we
	     * use predefined offset=urstart and otherwise ignore the
	     * possibility.
	     */

	    if ((err != noErr) && (err != kATSULineBreakInWord)) {
		TkMacOSXDbgMsg("ATSUBreakLine failed: %ld for '%.*s'", err,
			rangeLength, source+rangeStart);
	    }

#ifdef TK_MAC_DEBUG_FONTS
	    TkMacOSXDbgMsg("measure: '%.*s', break offset=%ld, errcode=%ld",
		    rangeLength, source+rangeStart, offset, err);
#endif

	    /*
	     * ATSUBreakLine includes the whitespace that separates words,
	     * but we don't want that. Besides, ATSUBreakLine thinks that
	     * spaces don't occupy pixels at the end of the break, which is
	     * also something we like to decide for ourself.
	     */

	    while ((offset > urstart) && (uchars[offset-1] == ' ')) {
		offset--;
	    }
	}

	/*
	 * Fix up left-overs for the TK_WHOLE_WORDS case.
	 */

	if (flags & TK_WHOLE_WORDS) {
	    if ((flags & TK_AT_LEAST_ONE) && ((offset == urstart)
		    || ((offset != urend) && (uchars[offset] != ' ')))) {
		/*
		 * With TK_AT_LEAST_ONE, if we are the the start of the
		 * range, we need to add at least one character.  If we are
		 * not at the end of a word, we must be in the middle of the
		 * first word still and we want to just use what we have so
		 * far.  In both cases we still need to find the right
		 * character boundary, so we set a flag that gets us into the
		 * code for character mode below.
		 */

		forceCharacterMode = 1;

	    } else {
		/*
		 * If we are not at the end of a word, we must be in the
		 * middle of the first word still.  Return 0.
		 */

		if ((offset != urend) && (uchars[offset] != ' ')) {
		    offset = urstart;
		    curX = 0;
		}
	    }
	}

	if (offset > urend) {
	    offset = urend;
	}

	/*
	 * If "flags" says that we don't actually want a word break, we need
	 * to find the next character break ourself, as ATSUBreakLine will
	 * only give us word breaks.  Do a simple linear search.
	 *
	 * Even do this, if ATSUBreakLine returned kATSULineBreakInWord,
	 * because we have not accounted correctly for all of the flags yet,
	 * like TK_AT_LEAST_ONE.
	 */

	if ((!(flags & TK_WHOLE_WORDS) || forceCharacterMode) && (offset <= urend)) {
	    UniCharArrayOffset lastOffset = offset;
	    UniCharArrayOffset nextoffset;
	    int lastX = -1;
	    int wantonemorechar = -1; /* undecided */

	    while (offset <= urend) {
		if (flags & TK_ISOLATE_END) {
		    LayoutSetString(fontPtr, NULL, uchars, offset);
		}
		curX = MeasureStringWidth(fontPtr, urstart, offset);

#ifdef TK_MAC_DEBUG_FONTS
		TkMacOSXDbgMsg("measure: '%.*s', try until=%ld, width=%d",
			rangeLength, source+rangeStart, offset, curX);
#endif

		if (curX > maxLength) {
		    /*
		     * Even if we are over the limit, we may want another
		     * character in some situations. Than we keep looking
		     * for one more character.
		     */

		    if (wantonemorechar == -1) {
			wantonemorechar = ((flags & TK_AT_LEAST_ONE) &&
				(lastOffset == urstart)) ||
				((flags & TK_PARTIAL_OK) &&
				(lastX != maxLength));
			if (!wantonemorechar) {
			    break;
			}
			lastX = curX;
		    }

		    /*
		     * There may belong combining marks to this character.
		     * Wait for a new curX to collect them all.
		     */

		    if (lastX != curX) {
			break;
		    }
		}

		/*
		 * Save this position, so we can come back to it.
		 */

		lastX = curX;
		lastOffset = offset;

		/*
		 * Increment offset by one character, taking combining marks
		 * into account.
		 */

		if (offset >= urend) {
		    break;
		}
		nextoffset = 0;
		if (flags & TK_ISOLATE_END) {
		    LayoutSetString(fontPtr, NULL, uchars, ulen);
		}
		err = ChkErr(ATSUNextCursorPosition, fontPtr->atsuLayout,
			offset, kATSUByCluster, &nextoffset);
		if (err != noErr) {
		    break;
		}
		if (nextoffset <= offset) {
#ifdef TK_MAC_DEBUG_FONTS
		    TkMacOSXDbgMsg("ATSUNextCursorPosition: Can't move further"
			    " (shouldn't happen, bad data?)");
#endif
		    break;
		}

		offset = nextoffset;
	    }

	    /*
	     * We have overshot one character, so backup one position.
	     */

	    curX = lastX;
	    offset = lastOffset;
	}

	if (curX < 0) {
	    if (flags & TK_ISOLATE_END) {
		LayoutSetString(fontPtr, NULL, uchars, offset);
	    }
	    curX = MeasureStringWidth(fontPtr, urstart, offset);
	}

	curByte = Tcl_UtfAtIndex(source, offset) - source;
	curByte -= rangeStart;
    }

    Tcl_DStringFree(&ucharBuffer);

#ifdef TK_MAC_DEBUG_FONTS
    TkMacOSXDbgMsg("measure: '%.*s', maxLength=%d, flags=%s%s%s%s "
	    "-> width=%d, bytes=%d",
	    rangeLength, source+rangeStart, maxLength,
	    flags & TK_PARTIAL_OK   ? "partialOk "  : "",
	    flags & TK_WHOLE_WORDS  ? "wholeWords " : "",
	    flags & TK_AT_LEAST_ONE ? "atLeastOne " : "",
	    flags & TK_ISOLATE_END  ? "isolateEnd " : "",
	    curX, curByte);
#endif

    *lengthPtr = curX;
    return curByte;
}

/*
 *---------------------------------------------------------------------------
 *
 * Tk_DrawChars --
 *
 *	Draw a string of characters on the screen.
 *
 *	With ATSUI we need the line context to do this right, so we have the
 *	actual implementation in TkpDrawCharsInContext().
 *
 * Results:
  *	None.
 *
 * Side effects:
 *	Information gets drawn on the screen.
 *
 *---------------------------------------------------------------------------
 */

void
Tk_DrawChars(
    Display *display,		/* Display on which to draw. */
    Drawable drawable,		/* Window or pixmap in which to draw. */
    GC gc,			/* Graphics context for drawing characters. */
    Tk_Font tkfont,		/* Font in which characters will be drawn; must
				 * be the same as font used in GC. */
    const char *source,		/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. All Tk meta-characters
				 * (tabs, control characters, and newlines)
				 * should be stripped out of the string that
				 * is passed to this function. If they are not
				 * stripped out, they will be displayed as
				 * regular printing characters. */
    int numBytes,		/* Number of bytes in string. */
    int x, int y)		/* Coordinates at which to place origin of the
				 * string when drawing. */
{
    TkpDrawCharsInContext(display, drawable, gc, tkfont, source, numBytes,
	    0, numBytes, x, y);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpDrawCharsInContext --
 *
 *	Draw a string of characters on the screen like Tk_DrawChars(), with
 *	access to all the characters on the line for context.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information gets drawn on the screen.
 *
 * Todo:
 *	Stippled text drawing.
 *
 *---------------------------------------------------------------------------
 */

void
TkpDrawCharsInContext(
    Display *display,		/* Display on which to draw. */
    Drawable drawable,		/* Window or pixmap in which to draw. */
    GC gc,			/* Graphics context for drawing characters. */
    Tk_Font tkfont,		/* Font in which characters will be drawn; must
				 * be the same as font used in GC. */
    const char * source,	/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. All Tk meta-characters
				 * (tabs, control characters, and newlines)
				 * should be stripped out of the string that
				 * is passed to this function. If they are not
				 * stripped out, they will be displayed as
				 * regular printing characters. */
    int numBytes,		/* Number of bytes in string. */
    int rangeStart,		/* Index of first byte to draw. */
    int rangeLength,		/* Length of range to draw in bytes. */
    int x, int y)		/* Coordinates at which to place origin of the
				 * whole (not just the range) string when
				 * drawing. */
{
    const MacFont * fontPtr = (const MacFont *) tkfont;
    MacDrawable *macWin = (MacDrawable *) drawable;
    Fixed fx, fy;
    int ulen, urstart, urlen;
    const UniChar * uchars;
    int lineOffset;
    TkMacOSXDrawingContext drawingContext;
#if !TK_MAC_COALESCE_LINE
    Tcl_DString runString;
#endif

    if (!TkMacOSXSetupDrawingContext(drawable, gc, tkMacOSXUseCGDrawing,
	    &drawingContext)) {
	return;
    }

#if 0
    /*
     * TODO: implement stippled text drawing
     */

    if ((gc->fill_style == FillStippled
	    || gc->fill_style == FillOpaqueStippled)
	    && gc->stipple != None) {
	#error Stippling not implemented
    }
#endif

    x += macWin->xOff;
    y += macWin->yOff;
    /* Turn the y coordinate upside-down for Quarz drawing. */
    if (drawingContext.context) {
	CGContextConcatCTM(drawingContext.context, CGAffineTransformMake(1.0,
		0.0, 0.0, -1.0, 0.0, drawingContext.portBounds.bottom -
		drawingContext.portBounds.top));
	y = drawingContext.portBounds.bottom -
		drawingContext.portBounds.top - y;
    }
    fy = IntToFixed(y);

#if TK_MAC_COALESCE_LINE
    UpdateLineBuffer(
	    fontPtr, &drawingContext, source, numBytes, x, y, &lineOffset);

    fx = IntToFixed(currentLeft);

    uchars = (const Tcl_UniChar*) Tcl_DStringValue(&currentLine);
    ulen = Tcl_DStringLength(&currentLine) / sizeof(uchars[0]);
#else
    lineOffset = 0;
    fx = IntToFixed(x);

    Tcl_DStringInit(&runString);
    uchars = Tcl_UtfToUniCharDString(source, numBytes, &runString);
    ulen = Tcl_DStringLength(&runString) / sizeof(uchars[0]);

    LayoutSetString(fontPtr, &drawingContext, uchars, ulen);
#endif

    urstart = Tcl_NumUtfChars(source, rangeStart);
    urlen = Tcl_NumUtfChars(source+rangeStart,rangeLength);

    ChkErr(ATSUDrawText, fontPtr->atsuLayout, lineOffset+urstart, urlen, fx,
	    fy);

#if !TK_MAC_COALESCE_LINE
    Tcl_DStringFree(&runString);
#endif

    TkMacOSXRestoreDrawingContext(&drawingContext);
}

/*
 *---------------------------------------------------------------------------
 *
 * MeasureStringWidth --
 *
 *	Low-level measuring of strings.
 *
 * Results:
 *	The width of the string in pixels.
 *
 * Side effects:
 *	None.
 *
 * Assumptions:
 *	fontPtr->atsuLayout is setup with the actual string data to measure.
 *
 *---------------------------------------------------------------------------
 */
static int
MeasureStringWidth(
    const MacFont *fontPtr,	/* Contains font, ATSU layout and string data
				 * to measure. */
    int start, int end)		/* Start and end positions to measure in that
				 * string. */
{
    /*
     * This implementation of measuring via ATSUGetGlyphBounds() does not
     * quite conform with the specification given for [font measure]:
     *
     *	   The return value is the total width in pixels of text, not
     *	   including the extra pixels used by highly exagerrated characters
     *	   such as cursive "f".
     *
     * Instead the result of ATSUGetGlyphBounds() *does* include these
     * "extra pixels".
     */

    ATSTrapezoid bounds;
    ItemCount numBounds;

    if (end <= start) {
	return 0;
    }

    bounds.upperRight.x = bounds.upperLeft.x = 0;
    ChkErr(ATSUGetGlyphBounds, fontPtr->atsuLayout, 0, 0, start, end-start,
	    kATSUseFractionalOrigins, 1, &bounds, &numBounds);
#ifdef TK_MAC_DEBUG_FONTS
    if (numBounds < 1 || numBounds > 1) {
	TkMacOSXDbgMsg("ATSUGetGlyphBounds: %s output",
		numBounds < 1 ? "No " : "More");
    }
#endif

    return FixedToInt(bounds.upperRight.x - bounds.upperLeft.x);
}

#if TK_MAC_COALESCE_LINE
/*
 *-------------------------------------------------------------------------
 *
 * UpdateLineBuffer --
 *
 *	See the general dicussion of TK_MAC_COALESCE_LINE on the header
 *	pages. This function maintains the data for this feature.
 *
 * Results:
 *
 *	The Tcl_UniChar string of the whole line as seen so far.
 *
 * Side effects:
 *	"*offset" is filled with the index of the first new character in
 *	"currentLine". The globals currentLine, currentY, currentLeft,
 *	currentRight and currentFontPtr are updated as necessary.
 *
 *	The currentLine string is set as the current text in
 *	fontPtr->atsuLayout (see LayoutSetString()).
 *
 *-------------------------------------------------------------------------
 */

static const Tcl_UniChar *
UpdateLineBuffer(
    const MacFont *fontPtr,	/* The font to be used for the new piece of
				 * text. */
    const TkMacOSXDrawingContext *drawingContextPtr,
				/* The Quarz drawing parameters. Needed for
				 * measuring the new piece. */
    const char *source,		/* A new piece of line to be added. */
    int numBytes,		/* Length of the new piece. */
    int x, int y,		/* Position of the new piece in the window. */
    int *offset)		/* Filled with the offset of the new piece in
				 * currentLine. */
{
    const Tcl_UniChar * uchars;
    int ulen;

    if (y != currentY
	    || x < currentRight-1 || x > currentRight+2
	    || currentFontPtr != fontPtr) {
	Tcl_DStringFree(&currentLine);
	Tcl_DStringInit(&currentLine);
	currentY = y;
	currentLeft = x;
	currentFontPtr = fontPtr;
	*offset = 0;
    } else {
	*offset = Tcl_DStringLength(&currentLine) / 2;
    }

    Tcl_UtfToUniCharDString(source, numBytes, &currentLine);
    uchars = (const Tcl_UniChar*) Tcl_DStringValue(&currentLine);
    ulen = Tcl_DStringLength(&currentLine) / sizeof(*uchars);
    LayoutSetString(fontPtr, drawingContextPtr, uchars, ulen);
    currentRight = x + MeasureStringWidth(fontPtr, *offset, ulen);

    return uchars;
}
#endif /* TK_MAC_COALESCE_LINE */

/*
 *---------------------------------------------------------------------------
 *
 * FamilyNameForFamilyID --
 *
 *	Helper for InitFont() and TkMacOSXFontDescriptionForFMFontInfo().
 *	Retrieves font family names for a given font family ID.
 *
 * Results:
 *	Font family name or NULL.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static const char *
FamilyNameForFamilyID(
    FMFontFamily familyId)
{
    OSStatus err;
    char name[256] = "";
    const MacFontFamily * familyPtr = NULL;

    err = ChkErr(GetFontFamilyName, familyId, name, sizeof(name));
    if (err == noErr) {
	/*
	 * We find the canonical font name, so we can avoid unnecessary
	 * memory management.
	 */

	familyPtr = FindFontFamily(name);
#ifdef TK_MAC_DEBUG_FONTS
	if (!familyPtr) {
	    TkMacOSXDbgMsg("Font family '%s' not found", name);
	}
#endif
    }
    return familyPtr ? familyPtr->name : NULL;
}

/*
 *---------------------------------------------------------------------------
 *
 * InitFont --
 *
 *	Helper for TkpGetNativeFont() and TkpGetFontFromAttributes().
 *	Initializes the memory for a MacFont that wraps the
 *	platform-specific data.
 *
 *	The caller is responsible for initializing the fields of the TkFont
 *	that are used exclusively by the generic TkFont code, and for
 *	releasing those fields before calling TkpDeleteFont().
 *
 * Results:
 *	Fills the MacFont structure.
 *
 * Side effects:
 *	Memory allocated.
 *
 *---------------------------------------------------------------------------
 */

static void
InitFont(
    FMFontFamily familyId,	/* The font family to initialize for. */
    const char * familyName,	/* The font family name, if known. Otherwise
				 * this can be NULL. */
    int size,			/* Point size for the font. */
    int qdStyle,		/* QuickDraw style bits. */
    MacFont * fontPtr)		/* Filled with information constructed from the
				 * above arguments. */
{
    FontInfo fi;
    TkFontAttributes * faPtr;
    TkFontMetrics * fmPtr;
    int periodWidth, wWidth;

    if (size == 0) {
	size = GetDefFontSize();
    }
    ChkErr(FetchFontInfo, familyId, size, qdStyle, &fi);
    if (!familyName) {
	familyName = FamilyNameForFamilyID(familyId);
    }

    fontPtr->font.fid = (Font) fontPtr;

    faPtr = &fontPtr->font.fa;
    faPtr->family = familyName;
    faPtr->size = size;
    faPtr->weight = (qdStyle & bold) ? TK_FW_BOLD : TK_FW_NORMAL;
    faPtr->slant = (qdStyle & italic) ? TK_FS_ITALIC : TK_FS_ROMAN;
    faPtr->underline = ((qdStyle & underline) != 0);
    faPtr->overstrike = 0;

    fmPtr = &fontPtr->font.fm;

    /*
     * Note: Macs measure the line height as ascent + descent +
     * leading. Leading as a separate entity does not exist in X11
     * and Tk. We add it to the ascent at the moment, because adding
     * it to the descent, as the Mac docs would indicate, would change
     * the position of self-drawn underlines.
     */

    fmPtr->ascent = fi.ascent + fi.leading;
    fmPtr->descent = fi.descent;
    fmPtr->maxWidth = fi.widMax;

    fontPtr->qdFont = familyId;
    fontPtr->qdSize = size;
    fontPtr->qdStyle = (short) qdStyle;

    InitATSUObjects(familyId, size, qdStyle, &fontPtr->atsuFontId,
	    &fontPtr->atsuLayout, &fontPtr->atsuStyle);

    Tk_MeasureChars((Tk_Font)fontPtr, ".", 1, -1, 0, &periodWidth);
    Tk_MeasureChars((Tk_Font)fontPtr, "W", 1, -1, 0, &wWidth);
    fmPtr->fixed = periodWidth == wWidth;

    SetFontFeatures(fontPtr->atsuFontId, fmPtr->fixed, fontPtr->atsuStyle);

    AdjustFontHeight(fontPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * InitATSUObjects --
 *
 *	Helper for InitFont(). Initializes the ATSU data handles for a
 *	MacFont.
 *
 * Results:
 *	Sets up all we know and can do at this point in time in fontIdPtr,
 *	layoutPtr and stylePtr.
 *
 * Side effects:
 *	Allocates data structures inside of ATSU.
 *
 *---------------------------------------------------------------------------
 */

static void
InitATSUObjects(
    FMFontFamily familyId,	/* The font family to use. */
    short ptSize, short qdStyles,
				/* The additional font parameters. */
    ATSUFontID *fontIdPtr,	/* Filled with the font id. */
    ATSUTextLayout *layoutPtr,	/* Filled with the ATSU layout handle. */
    ATSUStyle *stylePtr)	/* Filled with the ATSU style handle,
				 * configured with all parameters. */
{
    FMFontStyle stylesDone, stylesLeft;

    /*
     * Defaults in case of error.
     */

    *fontIdPtr = GetAppFont();
    *stylePtr = 0;
    *layoutPtr = 0;

    /*
     * Generate a font id from family id and QD style bits.
     */

    ChkErr(FMGetFontFromFontFamilyInstance, familyId, qdStyles, fontIdPtr,
	    &stylesDone);

    /*
     * We see what style bits are left and tell ATSU to synthesize what's
     * left like QD does it.
     */

    stylesLeft = qdStyles & ~(unsigned)stylesDone;

    /*
     * Create the style and set its attributes.
     */

    ChkErr(ATSUCreateStyle, stylePtr);
    InitATSUStyle(*fontIdPtr, ptSize, stylesLeft, *stylePtr);

    /*
     * Create the layout. Note: We can't set the layout attributes here,
     * because the text and the style must be set first.
     */

    ChkErr(ATSUCreateTextLayout, layoutPtr);
    /*InitATSULayout(*layoutPtr);*/
}

/*
 *---------------------------------------------------------------------------
 *
 * InitATSUStyle --
 *
 *	Helper for InitATSUObjects(). Initializes the ATSU style for a
 *	MacFont.
 *
 * Results:
 *	Sets up all parameters needed for an ATSU style.
 *
 * Side effects:
 *	Allocates data structures for the style inside of ATSU.
 *
 *---------------------------------------------------------------------------
 */

static void
InitATSUStyle(
    ATSUFontID fontId,		/* The font id to use. */
    short ptSize, short qdStyles,
				/* Additional font parameters. */
    ATSUStyle style)		/* The style handle to configure. */
{
    /*
     * Attributes for the style.
     */

    Fixed fsize = IntToFixed(ptSize);
    Boolean
	isBold = (qdStyles&bold) != 0,
	isUnderline = (qdStyles&underline) != 0,
	isItalic = (qdStyles&italic) != 0;

    ATSStyleRenderingOptions options =
	antialiasedTextEnabled == -1 ? kATSStyleNoOptions :
	antialiasedTextEnabled == 0  ? kATSStyleNoAntiAliasing :
				       kATSStyleApplyAntiAliasing;

    static const ATSUAttributeTag styleTags[] = {
	kATSUFontTag, kATSUSizeTag,
	kATSUQDBoldfaceTag, kATSUQDItalicTag, kATSUQDUnderlineTag,
	kATSUStyleRenderingOptionsTag,
    };
    static const ByteCount styleSizes[] = {
	sizeof(ATSUFontID), sizeof(Fixed),
	sizeof(Boolean), sizeof(Boolean), sizeof(Boolean),
	sizeof(ATSStyleRenderingOptions),
    };
    const ATSUAttributeValuePtr styleValues[] = {
	&fontId, &fsize,
	&isBold, &isItalic, &isUnderline,
	&options,
    };

    ChkErr(ATSUSetAttributes, style, sizeof(styleTags)/sizeof(styleTags[0]),
	    styleTags, styleSizes, styleValues);
}

/*
 *---------------------------------------------------------------------------
 *
 * SetFontFeatures --
 *
 *	Helper for InitFont(). Request specific font features of the ATSU
 *	style object for a MacFont.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Specific font features are enabled on the ATSU style object.
 *
 *---------------------------------------------------------------------------
 */

static void
SetFontFeatures(
    ATSUFontID fontId,		/* The font id to use. */
    int fixed,			/* Is this a fixed font? */
    ATSUStyle style)		/* The style handle to configure. */
{
    /*
     * Don't use the standard latin ligatures, if this is determined to be a
     * fixed-width font.
     */

    static const ATSUFontFeatureType fixed_featureTypes[] = {
	kLigaturesType, kLigaturesType
    };
    static const ATSUFontFeatureSelector fixed_featureSelectors[] = {
	kCommonLigaturesOffSelector, kRareLigaturesOffSelector
    };

    if (fixed) {
	ChkErr(ATSUSetFontFeatures, style, sizeof(fixed_featureTypes) /
		sizeof(fixed_featureTypes[0]), fixed_featureTypes,
		fixed_featureSelectors);
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * AdjustFontHeight --
 *
 *	Helper for InitFont(). Check font height against some real world
 *	examples.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The metrics in fontPtr->font.fm are adjusted so that typical combined
 *	characters fit into ascent+descent.
 *
 *---------------------------------------------------------------------------
 */

static void
AdjustFontHeight(
    MacFont * fontPtr)
{
    /*
     * The standard values for ascent, descent and leading as determined in
     * InitFont do not take composition into account, they are designed for
     * plain ASCII characters. This code measures the actual size of some
     * typical composed characters from the Latin-1 range and corrects these
     * factors, especially the ascent.
     *
     * A font requested with a pixel size may thus have a larger line height
     * than requested.
     *
     * An alternative would be to instruct ATSU to shrink oversized combined
     * characters. I think I have seen that feature somewhere, but I can't
     * find it now [BR].
     */

    static const UniChar chars[]
	    /* Auml,   Aacute, Acirc,  Atilde, Ccedilla */
	    = {0x00C4, 0x00C1, 0x00C2, 0x00C3, 0x00C7};
    static const int charslen = sizeof(chars) / sizeof(chars[0]);
    Rect size;
    OSStatus err;

    LayoutSetString(fontPtr, NULL, chars, charslen);

    size.top = size.bottom = 0;
    err = ChkErr(ATSUMeasureTextImage, fontPtr->atsuLayout, 0, charslen, 0, 0,
	    &size);

    if (err == noErr) {
	TkFontMetrics * fmPtr = &fontPtr->font.fm;
	int ascent = -size.top;
	int descent = size.bottom;

	if (ascent > fmPtr->ascent) {
	    fmPtr->ascent = ascent;
	}
	if (descent > fmPtr->descent) {
	    fmPtr->descent = descent;
	}
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * InitATSULayout --
 *
 *	Helper for LayoutSetString(). Initializes the ATSU layout
 *	object for a MacFont and a specific string.
 *
 * Results:
 *	Sets up all parameters needed for an ATSU layout object.
 *
 * Side effects:
 *	Allocates data structures for the layout object inside of ATSU.
 *
 * Assumptions:
 *	The actual string data and style information is already set by
 *	ATSUSetTextPointerLocation() and ATSUSetRunStyle() (see
 *	LayoutSetString()).
 *
 *---------------------------------------------------------------------------
 */

static void
InitATSULayout(
    const TkMacOSXDrawingContext  *drawingContextPtr,
				/* Specifies the CGContext to use. */
    ATSUTextLayout layout,	/* The layout object to configure. */
    int fixed)			/* Is this a fixed font? */
{
    /*
     * Attributes for the layout.
     */

    ATSLineLayoutOptions layoutOptions = 0
#if TK_MAC_COALESCE_LINE
	    /*
	     * Options to use unconditionally  when we try to do coalescing.
	     */
	    | kATSLineDisableAllLayoutOperations
	    | kATSLineFractDisable
	    | kATSLineUseDeviceMetrics
#endif
	    ;
    CGContextRef context = drawingContextPtr ?
	drawingContextPtr->context : NULL;

    static const ATSUAttributeTag layoutTags[] = {
	kATSUCGContextTag,
	kATSULineLayoutOptionsTag,
    };
    static const ByteCount layoutSizes[] = {
	sizeof(CGContextRef),
	sizeof(ATSLineLayoutOptions),
    };
    const ATSUAttributeValuePtr layoutValues[] = {
	&context,
	&layoutOptions,
    };

    /*
     * Ensure W(abcdefg) == W(a)*7 for fixed fonts (Latin scripts only).
     */

    if (fixed) {
	layoutOptions |= kATSLineFractDisable | kATSLineUseDeviceMetrics;
    }

    ChkErr(ATSUSetLayoutControls, layout, sizeof(layoutTags) /
	    sizeof(layoutTags[0]), layoutTags, layoutSizes, layoutValues);
    ChkErr(ATSUSetTransientFontMatching, layout, true);
}

/*
 *---------------------------------------------------------------------------
 *
 * LayoutSetString --
 *
 *	Setup the MacFont for a specific string.
 *
 * Results:
 *	Sets up all parameters so that ATSU can work with the objects in
 *	MacFont.
 *
 * Side effects:
 *	Sets parameters on the layout object fontPtr->atsuLayout.
 *
 *---------------------------------------------------------------------------
 */

void
LayoutSetString(
    const MacFont *fontPtr,	/* The fontPtr to configure. */
    const TkMacOSXDrawingContext *drawingContextPtr,
				/* For the CGContext to be used.*/
    const UniChar *uchars, int ulen)
				/* The UniChar string to set into
				 * fontPtr->atsuLayout. */
{
    ChkErr(ATSUSetTextPointerLocation, fontPtr->atsuLayout, uchars,
	    kATSUFromTextBeginning, ulen, ulen);

    /*
     * Styles can only be set after the text is set.
     */

    ChkErr(ATSUSetRunStyle, fontPtr->atsuLayout, fontPtr->atsuStyle,
	    kATSUFromTextBeginning, kATSUToTextEnd);

    /*
     * Layout attributes can only be set after the styles are set.
     */

    InitATSULayout(drawingContextPtr, fontPtr->atsuLayout,
	    fontPtr->font.fm.fixed);
}

/*
 *-------------------------------------------------------------------------
 *
 * ReleaseFont --
 *
 *	Called to release the Macintosh-specific contents of a TkFont. The
 *	caller is responsible for freeing the memory used by the font
 *	itself.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory is freed.
 *
 *---------------------------------------------------------------------------
 */

static void
ReleaseFont(
    MacFont *fontPtr)		/* The font to delete. */
{
    ATSUDisposeTextLayout(fontPtr->atsuLayout);
    ATSUDisposeStyle(fontPtr->atsuStyle);
}

/*
 *-------------------------------------------------------------------------
 *
 * FindFontFamilyOrAlias, FindFontFamilyOrAliasOrFallback --
 *
 *	Determine if any physical screen font exists on the system with the
 *	given family name. If the family exists, then it should be possible
 *	to construct some physical screen font with that family name.
 *
 *	FindFontFamilyOrAlias also considers font aliases as determined by
 *	TkFontGetAliasList().
 *
 *	FindFontFamilyOrAliasOrFallback also considers font aliases as
 *	determined by TkFontGetFallbacks().
 *
 *	The overall algorithm to get the closest font to the one requested is
 *	this:
 *
 *		try fontname
 *		try all aliases for fontname
 *		foreach fallback for fontname
 *			try the fallback
 *			try all aliases for the fallback
 *
 * Results:
 *
 *	The return value is NULL if the specified font family does not exist,
 *	a valid MacFontFamily* otherwise.
 *
 * Side effects:
 *
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static const MacFontFamily *
FindFontFamilyOrAlias(
    const char *name)		/* Name or alias name of the font to find. */
{
    const MacFontFamily * familyPtr;
    char ** aliases;
    int i;

    familyPtr = FindFontFamily(name);
    if (familyPtr != NULL) {
	return familyPtr;
    }

    aliases = TkFontGetAliasList(name);
    if (aliases != NULL) {
	for (i = 0; aliases[i] != NULL; i++) {
	    familyPtr = FindFontFamily(aliases[i]);
	    if (familyPtr != NULL) {
		return familyPtr;
	    }
	}
    }
    return NULL;
}

static const MacFontFamily *
FindFontFamilyOrAliasOrFallback(
    const char *name)		/* Name or alias name of the font to find. */
{
    const MacFontFamily * familyPtr;
    const char * fallback;
    char *** fallbacks;
    int i, j;

    familyPtr = FindFontFamilyOrAlias(name);
    if (familyPtr != NULL) {
	return familyPtr;
    }
    fallbacks = TkFontGetFallbacks();
    for (i = 0; fallbacks[i] != NULL; i++) {
	for (j = 0; (fallback = fallbacks[i][j]) != NULL; j++) {
	    if (strcasecmp(name, fallback) == 0) {
		for (j = 0; (fallback = fallbacks[i][j]) != NULL; j++) {
		    familyPtr = FindFontFamilyOrAlias(fallback);
		    if (familyPtr != NULL) {
			return familyPtr;
		    }
		}
	    }
	    break; /* benny: This "break" is a carry-over from
		    * tkMacOSXFont.c, but what is actually its purpose
		    * ???? */
	}
    }


    /*
     * FIXME: We would have liked to recover by re-enumerating fonts. But
     * that doesn't work, because Carbon seems to cache the inital list of
     * fonts. Fonts newly installed don't show up with
     * FMCreateFontFamilyIterator()/FMGetNextFontFamily() without a restart
     * of the app. Similar problem with fonts removed.
     */

#ifdef TK_MAC_DEBUG_FONTS
    TkMacOSXDbgMsg("Font family '%s' not found", name);
#endif

    return NULL;
}

/*
 *-------------------------------------------------------------------------
 *
 * InitFontFamilies --
 *
 *	Helper to TkpFontPkgInit. Use the Font Manager to fill in the
 *	familyList global array.
 *
 * Results:
 *
 *	None.
 *
 * Side effects:
 *
 *	Allocates memory.
 *
 *-------------------------------------------------------------------------
 */

static void
InitFontFamilies(void)
{
    FMFontFamily fontFamily;
    Str255 fontName;
    SInt16 fontSize;
    Style  fontStyle;

    /*
     * Has this been called before?
     */

    if (familyListNextFree > 0) {
	return;
    }

    ChkErr(ATSFontFamilyApplyFunction, FontFamilyEnumCallback,NULL);

    if (GetThemeFontAndFamily(kThemeSystemFont, &fontFamily, fontName,
	    &fontSize, &fontStyle) == noErr) {
	AddFontFamily(SYSTEMFONT_NAME, fontFamily);
    }
    if (GetThemeFontAndFamily(kThemeApplicationFont, &fontFamily, fontName,
	    &fontSize, &fontStyle) == noErr) {
	AddFontFamily(APPLFONT_NAME, fontFamily);
    }
    if (GetThemeFontAndFamily(kThemeMenuItemFont, &fontFamily, fontName,
	    &fontSize, &fontStyle) == noErr) {
	AddFontFamily(MENUITEMFONT_NAME, fontFamily);
    }

    SortFontFamilies();
}

/*
 *-------------------------------------------------------------------------
 *
 * FontFamilyEnumCallback --
 *
 *	Callback for ATSFontFamilyApplyFunction().
 *
 * Results:
 *
 *	noErr.
 *
 * Side effects:
 *
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static OSStatus
FontFamilyEnumCallback(
    ATSFontFamilyRef family,
    void *refCon)
{
    OSStatus err;
    char name[260] = "";

    (void) refCon;

    err = ChkErr(GetFontFamilyName, family, name, sizeof(name));
    if (err == noErr) {
	AddFontFamily(name, family);
    }

    return noErr;
}

/*
 *-------------------------------------------------------------------------
 *
 * GetFontFamilyName --
 *
 *	Use the Font Manager to get the name of a given FMFontfamily. This
 *	currently gets the standard, non-localized QuickDraw name. Other
 *	names would be possible, see docs for ATSUFindFontName for a
 *	selection. The MacOSX font selector seems to use the localized
 *	family name given by ATSUFindFontName(kFontFamilyName), but that API
 *	doesn't give us a name at all for some fonts.
 *
 * Results:
 *	An OS error code, noErr on success. name is filled with the
 *	resulting name.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static OSStatus
GetFontFamilyName(
    FMFontFamily fontFamily,	/* The font family for which to find the
				 * name. */
    char * name, int numBytes)	/* Filled with the result. */
{
    OSStatus err;
    Str255 nativeName;
    CFStringRef cfString;
    TextEncoding encoding;
    ScriptCode nameencoding;

    nativeName[0] = 0;
    name[0] = 0;
    err = ChkErr(FMGetFontFamilyName, fontFamily, nativeName);
    if (err != noErr) {
	return err;
    }

    /*
     * QuickDraw font names are encoded with the script that the font uses.
     * So we determine that encoding and than we reencode the name.
     */

    encoding = kTextEncodingMacRoman;
    ChkErr(FMGetFontFamilyTextEncoding, fontFamily, &encoding);
    nameencoding = encoding;
    ChkErr(RevertTextEncodingToScriptInfo, encoding, &nameencoding, NULL,
	    NULL);

    /*
     * Note: We could use Tcl facilities to do the re-encoding here. We'd
     * have to maintain tables to map OS encoding codes to Tcl encoding names
     * like tkMacOSXFont.c did. Using native re-encoding directly instead is
     * a lot easier and future-proof than that. There is one snag, though: I
     * have seen CFStringGetCString() crash with invalid encoding ids. But
     * than if that happens it would be a bug in
     * FMGetFontFamilyTextEncoding() or RevertTextEncodingToScriptInfo().
     */

    cfString = CFStringCreateWithPascalStringNoCopy(
	    NULL, nativeName, nameencoding, kCFAllocatorNull);
    CFStringGetCString(
	    cfString, name, numBytes, kCFStringEncodingUTF8);
    CFRelease(cfString);

    return noErr;
}

/*
 *-------------------------------------------------------------------------
 *
 * FindFontFamily --
 *
 *	Find the font family with the given name in the global familyList.
 *	Uses bsearch() for convenient access. Comparision is done
 *	non-case-sensitively with CompareFontFamilies() which see.
 *
 * Results:
 *
 *	MacFontFamily: A pair of family id and the actual name registered for
 *	the font.
 *
 * Side effects:
 *
 *	None.
 *
 * Assumption:
 *
 *	Requires the familyList array to be sorted.
 *
 *-------------------------------------------------------------------------
 */

static const MacFontFamily *
FindFontFamily(
    const char *name)		/* The family name. Note: Names are compared
				 * non-case-sensitive. */
{
    const MacFontFamily key = {name,-1};

    if(familyListMaxValid <= 0) {
	return NULL;
    }

    return bsearch(&key, familyList, familyListMaxValid, sizeof(*familyList),
	    CompareFontFamilies);
}

/*
 *-------------------------------------------------------------------------
 *
 * EnumFontFamilies --
 *
 *	Create a Tcl list with the registered names in the global familyList.
 *
 * Results:
 *	A Tcl list of names.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static Tcl_Obj *
EnumFontFamilies(void)
{
    int i;
    Tcl_Obj * tclList;

    tclList = Tcl_NewListObj(0, NULL);
    for (i=0; i<familyListMaxValid; ++i) {
	Tcl_ListObjAppendElement(NULL, tclList,
		Tcl_NewStringObj(familyList[i].name, -1));
    }

    return tclList;
}

/*
 *-------------------------------------------------------------------------
 *
 * AddFontFamily --
 *
 *	Register a font family in familyList. Until SortFontFamilies() is
 *	called, this is not actually available for FindFontFamily().
 *
 * Results:
 *
 *	MacFontFamily: The new pair of family id and the actual name
 *	registered for the font.
 *
 * Side effects:
 *
 *	New entry in familyList and familyListNextFree updated.
 *
 *-------------------------------------------------------------------------
 */

static const MacFontFamily *
AddFontFamily(
    const char *name,		/* Font family name to register. */
    FMFontFamily familyId)	/* Font family id to register. */
{
    MacFontFamily * familyPtr;

    if (familyListNextFree >= familyListSize) {
	familyListSize += 100;
	familyList = (MacFontFamily *) ckrealloc((void*) familyList,
		familyListSize * sizeof(*familyList));
    }

    familyPtr = familyList + familyListNextFree;
    ++familyListNextFree;

    familyPtr->name = AddString(name);
    familyPtr->familyId = familyId;

    return familyPtr;
}

/*
 *-------------------------------------------------------------------------
 *
 * SortFontFamilies --
 *
 *	Sort the entries in familyList. Only after calling
 *	SortFontFamilies(), the new families registered with AddFontFamily()
 *	are actually available for FindFontFamily(), because FindFontFamily()
 *	requires the array to be sorted.
 *
 * Results:
 *
 *	None.
 *
 * Side effects:
 *
 *	familyList is sorted and familyListMaxValid is updated.
 *
 *-------------------------------------------------------------------------
 */

static void
SortFontFamilies(void)
{
    if (familyListNextFree > 0) {
	qsort(familyList, familyListNextFree, sizeof(*familyList),
		CompareFontFamilies);
    }
    familyListMaxValid = familyListNextFree;
}

/*
 *-------------------------------------------------------------------------
 *
 * CompareFontFamilies --
 *
 *	Comparison function used by SortFontFamilies() and FindFontFamily().
 *
 * Results:
 *	Result as required to generate a stable sort order for bsearch() and
 *	qsort(). The ordering is not case-sensitive as far as
 *	Tcl_UtfNcasecmp() (which see) can provide that.
 *
 *	Note: It would be faster to compare first the length and the actual
 *	strings only as a tie-breaker, but than the ordering wouldn't look so
 *	pretty in [font families] ;-).
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static int
CompareFontFamilies(
    const void * vp1,
    const void * vp2)
{
    const char * name1;
    const char * name2;
    int len1, len2, diff;

    name1 = ((const MacFontFamily *) vp1)->name;
    name2 = ((const MacFontFamily *) vp2)->name;

    len1 = Tcl_NumUtfChars(name1, -1);
    len2 = Tcl_NumUtfChars(name2, -1);

    diff = Tcl_UtfNcasecmp(name1, name2, len1<len2 ? len1 : len2);

    return diff == 0 ? len1-len2 : diff;
}

/*
 *-------------------------------------------------------------------------
 *
 * AddString --
 *
 *	Helper for AddFontFamily(). Allocates a string in the one-shot
 *	allocator.
 *
 * Results:
 *	A duplicated string in the one-shot allocator.
 *
 * Side effects:
 *	May allocate a new memory block.
 *
 *-------------------------------------------------------------------------
 */

static const char *
AddString(
    const char *in)		/* String to add, zero-terminated. */
{
    int len;
    char *result;

    len = strlen(in) +1;

    if (stringMemory == NULL
	    || (stringMemory->nextFree+len) > STRING_BLOCK_MAX) {
	StringBlock * newblock = (StringBlock *) ckalloc(sizeof(StringBlock));

	newblock->next = stringMemory;
	newblock->nextFree = 0;
	stringMemory = newblock;
    }

    result = stringMemory->strings + stringMemory->nextFree;
    stringMemory->nextFree += len;

    memcpy(result, in, len);

    return result;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkMacOSXIsCharacterMissing --
 *
 *	Given a tkFont and a character determine whether the character has
 *	a glyph defined in the font or not.
 *
 * Results:
 *	Returns a 1 if the character is missing, a 0 if it is not.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkMacOSXIsCharacterMissing(
    Tk_Font tkfont,		/* The font we are looking in. */
    unsigned int searchChar)	/* The character we are looking for. */
{
    /* Background: This function is private and only used in
     * tkMacOSXMenu.c:FindMarkCharacter().
     *
     * We could use ATSUMatchFont() to implement. We'd have to change the
     * definition of the encoding of the parameter searchChar from MacRoman
     * to UniChar for that.
     *
     * The system uses font fallback for controls, so we don't really need
     * this. */

    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXInitControlFontStyle --
 *
 *	This procedure sets up the appropriate ControlFontStyleRec
 *	for a Mac control.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXInitControlFontStyle(
    Tk_Font tkfont,		/* Tk font object to use for the control. */
    ControlFontStylePtr fsPtr)	/* The style object to configure. */
{
    const MacFont * fontPtr = (MacFont *) tkfont;

    fsPtr->flags = kControlUseFontMask | kControlUseSizeMask |
	    kControlUseFaceMask | kControlUseJustMask;
    fsPtr->font = fontPtr->qdFont;
    fsPtr->size = fontPtr->qdSize;
    fsPtr->style = fontPtr->qdStyle;
    fsPtr->just = teCenter;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseAntialiasedText --
 *
 *	Enables or disables application-wide use of antialiased text (where
 *	available). Sets up a linked Tcl global variable to allow
 *	disabling of antialiased text from tcl.
 *	The possible values for this variable are:
 *
 *	-1 - Use system default as configurable in "System Prefs" -> "General".
 *	 0 - Unconditionally disable antialiasing.
 *	 1 - Unconditionally enable antialiasing.
 *
 * Results:
 *
 *	TCL_OK.
 *
 * Side effects:
 *
 *	None.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE int
TkMacOSXUseAntialiasedText(
    Tcl_Interp * interp,	/* The Tcl interpreter to receive the
				 * variable.*/
    int enable)			/* Initial value. */
{
    static Boolean initialized = FALSE;

    if (!initialized) {
	initialized = TRUE;

	if (Tcl_CreateNamespace(interp, "::tk::mac", NULL, NULL) == NULL) {
	    Tcl_ResetResult(interp);
	}
	if (Tcl_LinkVar(interp, "::tk::mac::antialiasedtext",
		(char *) &antialiasedTextEnabled,
		TCL_LINK_INT) != TCL_OK) {
	    Tcl_ResetResult(interp);
	}
    }
    antialiasedTextEnabled = enable;
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */