summaryrefslogtreecommitdiff
path: root/src/cairo-ft-font.c
blob: 929ce58b73c5fe252469eb8882931d4480d8f084 (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
/* cairo - a vector graphics library with display and print output
 *
 * Copyright © 2000 Keith Packard
 * Copyright © 2005 Red Hat, Inc
 *
 * This library is free software; you can redistribute it and/or
 * modify it either under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * (the "LGPL") or, at your option, under the terms of the Mozilla
 * Public License Version 1.1 (the "MPL"). If you do not alter this
 * notice, a recipient may use your version of this file under either
 * the MPL or the LGPL.
 *
 * You should have received a copy of the LGPL along with this library
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 * You should have received a copy of the MPL along with this library
 * in the file COPYING-MPL-1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
 * the specific language governing rights and limitations.
 *
 * The Original Code is the cairo graphics library.
 *
 * The Initial Developer of the Original Code is Red Hat, Inc.
 *
 * Contributor(s):
 *      Graydon Hoare <graydon@redhat.com>
 *	Owen Taylor <otaylor@redhat.com>
 *      Keith Packard <keithp@keithp.com>
 *      Carl Worth <cworth@cworth.org>
 */

#include <float.h>

#include "cairo-ft-private.h"

#include <fontconfig/fontconfig.h>
#include <fontconfig/fcfreetype.h>

#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_OUTLINE_H
#include FT_IMAGE_H

#define DOUBLE_TO_26_6(d) ((FT_F26Dot6)((d) * 64.0))
#define DOUBLE_FROM_26_6(t) ((double)(t) / 64.0)
#define DOUBLE_TO_16_16(d) ((FT_Fixed)((d) * 65536.0))
#define DOUBLE_FROM_16_16(t) ((double)(t) / 65536.0)

/* We pack some of our own information into the bits unused
 * by FreeType's load flags. If FreeType ever uses up all
 * the load flag bits, we'll have to do something else.
 * (probably just store what we care about in load_flags
 * then convert into FreeType terms.
 */
#define PRIVATE_FLAG_HINT_METRICS (0x01 << 24)
#define PRIVATE_FLAGS_MASK        (0xff << 24)

 /* This is the max number of FT_face objects we keep open at once
  */
 #define MAX_OPEN_FACES 10

/* This is the max number of FT_face objects we keep open at once
 */
#define MAX_OPEN_FACES 10

/*
 * The simple 2x2 matrix is converted into separate scale and shape
 * factors so that hinting works right
 */

typedef struct {
    double  x_scale, y_scale;
    double  shape[2][2];
} ft_font_transform_t;

/* 
 * We create an object that corresponds to a single font on the disk;
 * (identified by a filename/id pair) these are shared between all
 * fonts using that file.  For cairo_ft_scaled_font_create_for_ft_face(), we
 * just create a one-off version with a permanent face value.
 */

typedef struct _ft_font_face ft_font_face_t;

typedef struct {
    cairo_unscaled_font_t base;

    cairo_bool_t from_face; /* from cairo_ft_scaled_font_create_for_ft_face()? */
    FT_Face face;	    /* provided or cached face */

    /* only set if from_face is false */
    char *filename;
    int id;

    /* We temporarily scale the unscaled font as neede */
    cairo_bool_t have_scale;
    cairo_matrix_t current_scale;
    double x_scale;		/* Extracted X scale factor */
    double y_scale;             /* Extracted Y scale factor */
    cairo_bool_t have_shape;	/* true if the current scale has a non-scale component*/
    
    int lock;		/* count of how many times this font has been locked */

    ft_font_face_t *faces;	/* Linked list of faces for this font */
} ft_unscaled_font_t;

struct _ft_font_face {
    cairo_font_face_t base;
    ft_unscaled_font_t *unscaled;
    int load_flags;
    ft_font_face_t *next_face;
};

const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend;

static ft_unscaled_font_t *
_ft_unscaled_font_create_from_face (FT_Face face)
{
    ft_unscaled_font_t *unscaled = malloc (sizeof(ft_unscaled_font_t));
    if (!unscaled)
	return NULL;
	
    unscaled->from_face = 1;
    unscaled->face = face;

    unscaled->filename = NULL;
    unscaled->id = 0;
    
    unscaled->have_scale = 0;
    unscaled->lock = 0;

    unscaled->faces = NULL;

    _cairo_unscaled_font_init (&unscaled->base,
			       &cairo_ft_unscaled_font_backend);
    return unscaled;
}

cairo_bool_t
_cairo_unscaled_font_is_ft (cairo_unscaled_font_t *unscaled_font)
{
    return unscaled_font->backend == &cairo_ft_unscaled_font_backend;
}

static ft_unscaled_font_t *
_ft_unscaled_font_create_from_filename (const char *filename,
					int         id)
{
    ft_unscaled_font_t *unscaled;
    char *new_filename;
    
    new_filename = strdup (filename);
    if (!new_filename)
	return NULL;

    unscaled = malloc (sizeof (ft_unscaled_font_t));
    if (!unscaled) {
	free (new_filename);
	return NULL;
    }
	
    unscaled->from_face = 0;
    unscaled->face = NULL;

    unscaled->filename = new_filename;
    unscaled->id = id;
    
    unscaled->have_scale = 0;
    unscaled->lock = 0;
    
    unscaled->faces = NULL;

    _cairo_unscaled_font_init (&unscaled->base,
			       &cairo_ft_unscaled_font_backend);
    return unscaled;
}

/*
 * We keep a global cache from [file/id] => [ft_unscaled_font_t]. This
 * hash isn't limited in size. However, we limit the number of
 * FT_Face objects we keep around; when we've exceeeded that
 * limit and need to create a new FT_Face, we dump the FT_Face from
 * a random ft_unscaled_font_t.
 */

typedef struct {
    cairo_cache_entry_base_t base;
    char *filename;
    int id;
} cairo_ft_cache_key_t;

typedef struct {
    cairo_ft_cache_key_t key;
    ft_unscaled_font_t *unscaled;
} cairo_ft_cache_entry_t;

typedef struct {
    cairo_cache_t base;
    FT_Library lib;
    int n_faces;		/* Number of open FT_Face objects */
} ft_cache_t;

static unsigned long
_ft_font_cache_hash (void *cache, void *key)
{
    cairo_ft_cache_key_t *in = (cairo_ft_cache_key_t *) key;
    unsigned long hash;

    /* 1607 is just a random prime. */
    hash = _cairo_hash_string (in->filename);
    hash += ((unsigned long) in->id) * 1607;
	
    return hash;
}

static int
_ft_font_cache_keys_equal (void *cache,
			   void *k1,
			   void *k2)
{
    cairo_ft_cache_key_t *a;
    cairo_ft_cache_key_t *b;
    a = (cairo_ft_cache_key_t *) k1;
    b = (cairo_ft_cache_key_t *) k2;

    return strcmp (a->filename, b->filename) == 0 &&
	a->id == b->id;
}

static cairo_status_t
_ft_font_cache_create_entry (void *cache,
			     void *key,
			     void **return_entry)
{
    cairo_ft_cache_key_t *k = key;
    cairo_ft_cache_entry_t *entry;

    entry = malloc (sizeof (cairo_ft_cache_entry_t));
    if (entry == NULL)
	return CAIRO_STATUS_NO_MEMORY;

    entry->unscaled = _ft_unscaled_font_create_from_filename (k->filename,
							      k->id);
    if (!entry->unscaled) {
	free (entry);
	return CAIRO_STATUS_NO_MEMORY;
    }
    
    entry->key.base.memory = 0;
    entry->key.filename = entry->unscaled->filename;
    entry->key.id = entry->unscaled->id;
    
    *return_entry = entry;

    return CAIRO_STATUS_SUCCESS;
}

/* Entries are never spontaneously destroyed; but only when
 * we remove them from the cache specifically. We free entry->unscaled
 * in the code that removes the entry from the cache
 */
static void
_ft_font_cache_destroy_entry (void *cache,
			      void *entry)
{    
    cairo_ft_cache_entry_t *e = (cairo_ft_cache_entry_t *) entry;

    free (e);
}

static void 
_ft_font_cache_destroy_cache (void *cache)
{
    ft_cache_t *fc = (ft_cache_t *) cache;

    FT_Done_FreeType (fc->lib);
    free (fc);
}

static const cairo_cache_backend_t _ft_font_cache_backend = {
    _ft_font_cache_hash,
    _ft_font_cache_keys_equal,
    _ft_font_cache_create_entry,
    _ft_font_cache_destroy_entry,
    _ft_font_cache_destroy_cache
};

static ft_cache_t *_global_ft_cache = NULL;

CAIRO_MUTEX_DECLARE(_global_ft_cache_mutex);

static void
_lock_global_ft_cache (void)
{
    CAIRO_MUTEX_LOCK(_global_ft_cache_mutex);
}

static void
_unlock_global_ft_cache (void)
{
    CAIRO_MUTEX_UNLOCK(_global_ft_cache_mutex);
}

static cairo_cache_t *
_get_global_ft_cache (void)
{
    if (_global_ft_cache == NULL)
    {
	_global_ft_cache = malloc (sizeof(ft_cache_t));	
	if (!_global_ft_cache)
	    goto FAIL;

	if (_cairo_cache_init (&_global_ft_cache->base,
			       &_ft_font_cache_backend,
			       0)) /* No memory limit */
	    goto FAIL;
	
	if (FT_Init_FreeType (&_global_ft_cache->lib)) 
	    goto FAIL;
	_global_ft_cache->n_faces = 0;
    }
    return &_global_ft_cache->base;

 FAIL:
    if (_global_ft_cache)
	free (_global_ft_cache);
    _global_ft_cache = NULL;
    return NULL;
}

/* Finds or creates a ft_unscaled_font for the filename/id from pattern.
 * Returns a new reference to the unscaled font.
 */
static ft_unscaled_font_t *
_ft_unscaled_font_get_for_pattern (FcPattern *pattern)
{
    cairo_ft_cache_entry_t *entry;
    cairo_ft_cache_key_t key;
    cairo_cache_t *cache;
    cairo_status_t status;
    FcChar8 *filename;
    int created_entry;
    
    if (FcPatternGetString (pattern, FC_FILE, 0, &filename) != FcResultMatch)
	return NULL;
    key.filename = (char *)filename;
	    
    if (FcPatternGetInteger (pattern, FC_INDEX, 0, &key.id) != FcResultMatch)
	return NULL;
    
    _lock_global_ft_cache ();
    cache = _get_global_ft_cache ();
    if (cache == NULL) {
	_unlock_global_ft_cache ();
	return NULL;
    }

    status = _cairo_cache_lookup (cache, &key, (void **) &entry, &created_entry);
    if (status == CAIRO_STATUS_SUCCESS && !created_entry)
	_cairo_unscaled_font_reference (&entry->unscaled->base);

    _unlock_global_ft_cache ();
    if (status)
	return NULL;

    return entry->unscaled;
}

static int
_has_unlocked_face (void *entry)
{
    cairo_ft_cache_entry_t *e = entry;

    return (e->unscaled->lock == 0 && e->unscaled->face);
}

/* Ensures that an unscaled font has a face object. If we exceed
 * MAX_OPEN_FACES, try to close some.
 */
static FT_Face
_ft_unscaled_font_lock_face (ft_unscaled_font_t *unscaled)
{
    ft_cache_t *ftcache;
    FT_Face face = NULL;

    if (unscaled->face) {
	unscaled->lock++;
	return unscaled->face;
    }

    assert (!unscaled->from_face);
    
    _lock_global_ft_cache ();
    ftcache = (ft_cache_t *) _get_global_ft_cache ();
    assert (ftcache != NULL);
    
    while (ftcache->n_faces >= MAX_OPEN_FACES) {
	cairo_ft_cache_entry_t *entry;
    
	entry = _cairo_cache_random_entry ((cairo_cache_t *)ftcache, _has_unlocked_face);
	if (entry) {
	    FT_Done_Face (entry->unscaled->face);
	    entry->unscaled->face = NULL;
	    entry->unscaled->have_scale = 0;
	    ftcache->n_faces--;
	} else {
	    break;
	}
    }

    if (FT_New_Face (ftcache->lib,
		     unscaled->filename,
		     unscaled->id,
		     &face) != FT_Err_Ok)
	goto FAIL;

    unscaled->face = face;
    unscaled->lock++;
    ftcache->n_faces++;

 FAIL:
    _unlock_global_ft_cache ();
    return face;
}

/* Unlock unscaled font locked with _ft_unscaled_font_lock_face
 */
static void
_ft_unscaled_font_unlock_face (ft_unscaled_font_t *unscaled)
{
    assert (unscaled->lock > 0);
    
    unscaled->lock--;
}

static void
_compute_transform (ft_font_transform_t *sf,
		    cairo_matrix_t      *scale)
{
    cairo_matrix_t normalized = *scale;
    double tx, ty;
    
    /* The font matrix has x and y "scale" components which we extract and
     * use as character scale values. These influence the way freetype
     * chooses hints, as well as selecting different bitmaps in
     * hand-rendered fonts. We also copy the normalized matrix to
     * freetype's transformation.
     */

    _cairo_matrix_compute_scale_factors (&normalized, 
					 &sf->x_scale, &sf->y_scale,
					 /* XXX */ 1);
    
    if (sf->x_scale != 0 && sf->y_scale != 0) {
	cairo_matrix_scale (&normalized, 1.0 / sf->x_scale, 1.0 / sf->y_scale);
    
	_cairo_matrix_get_affine (&normalized, 
				  &sf->shape[0][0], &sf->shape[0][1],
				  &sf->shape[1][0], &sf->shape[1][1],
				  &tx, &ty);
    } else {
	sf->shape[0][0] = sf->shape[1][1] = 1.0;
	sf->shape[0][1] = sf->shape[1][0] = 0.0;
    }
}

/* Temporarily scales an unscaled font to the give scale. We catch
 * scaling to the same size, since changing a FT_Face is expensive.
 */
static void
_ft_unscaled_font_set_scale (ft_unscaled_font_t *unscaled,
			     cairo_matrix_t     *scale)
{
    ft_font_transform_t sf;
    FT_Matrix mat;
    FT_UInt pixel_width, pixel_height;
    FT_Error error;

    assert (unscaled->face != NULL);
    
    if (unscaled->have_scale &&
	scale->xx == unscaled->current_scale.xx &&
	scale->yx == unscaled->current_scale.yx &&
	scale->xy == unscaled->current_scale.xy &&
	scale->yy == unscaled->current_scale.yy)
	return;

    unscaled->have_scale = 1;
    unscaled->current_scale = *scale;
	
    _compute_transform (&sf, scale);

    unscaled->x_scale = sf.x_scale;
    unscaled->y_scale = sf.y_scale;
	
    mat.xx = DOUBLE_TO_16_16(sf.shape[0][0]);
    mat.yx = - DOUBLE_TO_16_16(sf.shape[0][1]);
    mat.xy = - DOUBLE_TO_16_16(sf.shape[1][0]);
    mat.yy = DOUBLE_TO_16_16(sf.shape[1][1]);

    unscaled->have_shape = (mat.xx != 0x10000 ||
			    mat.yx != 0x00000 ||
			    mat.xy != 0x00000 ||
			    mat.yy != 0x10000);
    
    FT_Set_Transform(unscaled->face, &mat, NULL);

    if ((unscaled->face->face_flags & FT_FACE_FLAG_SCALABLE) != 0) {
	pixel_width = sf.x_scale;
	pixel_height = sf.y_scale;
	error = FT_Set_Char_Size (unscaled->face,
				  sf.x_scale * 64.0,
				  sf.y_scale * 64.0,
				  0, 0);
    } else {
	double min_distance = DBL_MAX;
	int i;
	int best_i = 0;

	pixel_width = pixel_height = 0;
	
	for (i = 0; i < unscaled->face->num_fixed_sizes; i++) {
	    double size = unscaled->face->available_sizes[i].y_ppem / 64.;
	    double distance = fabs (size - sf.y_scale);
	    
	    if (distance <= min_distance) {
		min_distance = distance;
		best_i = i;
	    }
	}
	error = FT_Set_Char_Size (unscaled->face,
				  unscaled->face->available_sizes[best_i].x_ppem,
				  unscaled->face->available_sizes[best_i].y_ppem,
				  0, 0);
	if (error )
	    error = FT_Set_Pixel_Sizes (unscaled->face,
					unscaled->face->available_sizes[best_i].width,
					unscaled->face->available_sizes[best_i].height);
    }

    assert (error == 0);
}

static void 
_cairo_ft_unscaled_font_destroy (void *abstract_font)
{
    ft_unscaled_font_t *unscaled  = abstract_font;

    if (unscaled == NULL)
	return;

    if (unscaled->from_face) {
	/* See comments in _ft_font_face_destroy about the "zombie" state
	 * for a _ft_font_face.
	 */
	if (unscaled->faces && !unscaled->faces->unscaled)
	    cairo_font_face_destroy (&unscaled->faces->base);
    } else {
	cairo_cache_t *cache;
	cairo_ft_cache_key_t key;
	
	_lock_global_ft_cache ();
	cache = _get_global_ft_cache ();
	assert (cache);

	key.filename = unscaled->filename;
	key.id = unscaled->id;
	
	_cairo_cache_remove (cache, &key);
	
	_unlock_global_ft_cache ();
	
	if (unscaled->filename)
	    free (unscaled->filename);
	
	if (unscaled->face)
	    FT_Done_Face (unscaled->face);
    }
}

/* Empirically-derived subpixel filtering values thanks to Keith
 * Packard and libXft. */
static const int    filters[3][3] = {
    /* red */
#if 0
    {    65538*4/7,65538*2/7,65538*1/7 },
    /* green */
    {    65536*1/4, 65536*2/4, 65537*1/4 },
    /* blue */
    {    65538*1/7,65538*2/7,65538*4/7 },
#endif
    {    65538*9/13,65538*3/13,65538*1/13 },
    /* green */
    {    65538*1/6, 65538*4/6, 65538*1/6 },
    /* blue */
    {    65538*1/13,65538*3/13,65538*9/13 },
};

static cairo_bool_t
_native_byte_order_lsb (void)
{
    int	x = 1;

    return *((char *) &x) == 1;
}

/* Fills in val->image with an image surface created from @bitmap
 */
static cairo_status_t
_get_bitmap_surface (cairo_image_glyph_cache_entry_t *val,
		     FT_Bitmap                       *bitmap,
		     cairo_bool_t                     own_buffer,
		     int			      rgba)
{
    int width, height, stride;
    unsigned char *data;
    int format = CAIRO_FORMAT_A8;
    cairo_bool_t subpixel = FALSE;
    
    width = bitmap->width;
    height = bitmap->rows;
    
    if (width * height == 0) {
	if (own_buffer && bitmap->buffer)
	    free (bitmap->buffer);
	
	val->image = NULL;
    } else {
	switch (bitmap->pixel_mode) {
	case FT_PIXEL_MODE_MONO:
	    stride = (((width + 31) & ~31) >> 3);
	    if (own_buffer) {
		data = bitmap->buffer;
		assert (stride == bitmap->pitch);
	    } else {
		data = malloc (stride * height);
		if (!data)
		    return CAIRO_STATUS_NO_MEMORY;

		if (stride == bitmap->pitch) {
		    memcpy (data, bitmap->buffer, stride * height);
		} else {
		    int i;
		    unsigned char *source, *dest;
		
		    source = bitmap->buffer;
		    dest = data;
		    for (i = height; i; i--) {
			memcpy (dest, source, bitmap->pitch);
			memset (dest + bitmap->pitch, '\0', stride - bitmap->pitch);
			
			source += bitmap->pitch;
			dest += stride;
		    }
		}
	    }
	    
	    if (_native_byte_order_lsb())
	    {
		unsigned char   *d = data, c;
		int		count = stride * height;
		
		while (count--) {
		    c = *d;
		    c = ((c << 1) & 0xaa) | ((c >> 1) & 0x55);
		    c = ((c << 2) & 0xcc) | ((c >> 2) & 0x33);
		    c = ((c << 4) & 0xf0) | ((c >> 4) & 0x0f);
		    *d++ = c;
		}
	    }
	    format = CAIRO_FORMAT_A1;
	    break;

	case FT_PIXEL_MODE_LCD:
	case FT_PIXEL_MODE_LCD_V:
	case FT_PIXEL_MODE_GRAY:
	    if (rgba == FC_RGBA_NONE || rgba == FC_RGBA_UNKNOWN)
	    {
		stride = bitmap->pitch;
		if (own_buffer) {
		    data = bitmap->buffer;
		} else {
		    data = malloc (stride * height);
		    if (!data)
			return CAIRO_STATUS_NO_MEMORY;
		    memcpy (data, bitmap->buffer, stride * height);
		}
		format = CAIRO_FORMAT_A8;
	    } else {
		int		    x, y;
		unsigned char   *in_line, *out_line, *in;
		unsigned int    *out;
		unsigned int    red, green, blue;
		int		    rf, gf, bf;
		int		    s;
		int		    o, os;
		unsigned char   *data_rgba;
		unsigned int    width_rgba, stride_rgba;
		int		    vmul = 1;
		int		    hmul = 1;
		
		switch (rgba) {
		case FC_RGBA_RGB:
		case FC_RGBA_BGR:
		default:
		    width /= 3;
		    hmul = 3;
		    break;
		case FC_RGBA_VRGB:
		case FC_RGBA_VBGR:
		    vmul = 3;
		    height /= 3;
		    break;
		}
		subpixel = TRUE;
		/*
		 * Filter the glyph to soften the color fringes
		 */
		width_rgba = width;
		stride = bitmap->pitch;
		stride_rgba = (width_rgba * 4 + 3) & ~3;
		data_rgba = calloc (1, stride_rgba * height);
    
		os = 1;
		switch (rgba) {
		case FC_RGBA_VRGB:
		    os = stride;
		case FC_RGBA_RGB:
		default:
		    rf = 0;
		    gf = 1;
		    bf = 2;
		    break;
		case FC_RGBA_VBGR:
		    os = stride;
		case FC_RGBA_BGR:
		    bf = 0;
		    gf = 1;
		    rf = 2;
		    break;
		}
		in_line = bitmap->buffer;
		out_line = data_rgba;
		for (y = 0; y < height; y++)
		{
		    in = in_line;
		    out = (unsigned int *) out_line;
		    in_line += stride * vmul;
		    out_line += stride_rgba;
		    for (x = 0; x < width * hmul; x += hmul)
		    {
			red = green = blue = 0;
			o = 0;
			for (s = 0; s < 3; s++)
			{
			    red += filters[rf][s]*in[x+o];
			    green += filters[gf][s]*in[x+o];
			    blue += filters[bf][s]*in[x+o];
			    o += os;
			}
			red = red / 65536;
			green = green / 65536;
			blue = blue / 65536;
			*out++ = (green << 24) | (red << 16) | (green << 8) | blue;
		    }
		}
    
		/* Images here are stored in native format. The
		 * backend must convert to its own format as needed
		 */
    
		if (own_buffer)
		    free (bitmap->buffer);
		data = data_rgba;
		stride = stride_rgba;
		format = CAIRO_FORMAT_ARGB32;
	    }
	    break;
	case FT_PIXEL_MODE_GRAY2:
	case FT_PIXEL_MODE_GRAY4:
	    /* These could be triggered by very rare types of TrueType fonts */
	default:
	    return CAIRO_STATUS_NO_MEMORY;
	}
    
	val->image = (cairo_image_surface_t *)
	    cairo_image_surface_create_for_data (data,
						 format,
						 width, height, stride);
	if (val->image->base.status) {
	    free (data);
	    return val->image->base.status;
	}
	
	if (subpixel)
	    pixman_image_set_component_alpha (val->image->pixman_image, TRUE);

	_cairo_image_surface_assume_ownership_of_data (val->image);
    }

    val->size.width = width;
    val->size.height = height;

    return CAIRO_STATUS_SUCCESS;
}

/* Converts an outline FT_GlyphSlot into an image
 * 
 * This could go through _render_glyph_bitmap as well, letting
 * FreeType convert the outline to a bitmap, but doing it ourselves
 * has two minor advantages: first, we save a copy of the bitmap
 * buffer: we can directly use the buffer that FreeType renders
 * into.
 *
 * Second, it may help when we add support for subpixel
 * rendering: the Xft code does it this way. (Keith thinks that
 * it may also be possible to get the subpixel rendering with
 * FT_Render_Glyph: something worth looking into in more detail
 * when we add subpixel support. If so, we may want to eliminate
 * this version of the code path entirely.
 */
static cairo_status_t
_render_glyph_outline (FT_Face                          face,
		       cairo_image_glyph_cache_entry_t *val)
{
    int rgba = FC_RGBA_UNKNOWN;
    FT_GlyphSlot glyphslot = face->glyph;
    FT_Outline *outline = &glyphslot->outline;
    FT_Bitmap bitmap;
    FT_BBox cbox;
    FT_Matrix matrix;
    int hmul = 1;
    int vmul = 1;
    unsigned int width, height, stride;
    cairo_format_t format;
    cairo_bool_t subpixel = FALSE;
    cairo_status_t status;

    FT_Outline_Get_CBox (outline, &cbox);

    cbox.xMin &= -64;
    cbox.yMin &= -64;
    cbox.xMax = (cbox.xMax + 63) & -64;
    cbox.yMax = (cbox.yMax + 63) & -64;

    width = (unsigned int) ((cbox.xMax - cbox.xMin) >> 6);
    height = (unsigned int) ((cbox.yMax - cbox.yMin) >> 6);
    stride = (width * hmul + 3) & ~3;

    if (width * height == 0) {
	/* Looks like fb handles zero-sized images just fine */
	if ((val->key.flags & FT_LOAD_MONOCHROME) != 0)
	    format = CAIRO_FORMAT_A8;
	else if (FT_LOAD_TARGET_MODE (val->key.flags) == FT_RENDER_MODE_LCD ||
		 FT_LOAD_TARGET_MODE (val->key.flags) == FT_RENDER_MODE_LCD_V)
	    format= CAIRO_FORMAT_ARGB32;
	else
	    format = CAIRO_FORMAT_A8;

	val->image = (cairo_image_surface_t *)
	    cairo_image_surface_create_for_data (NULL, format, 0, 0, 0);
    } else  {

	matrix.xx = matrix.yy = 0x10000L;
	matrix.xy = matrix.yx = 0;
	
	if ((val->key.flags & FT_LOAD_MONOCHROME) != 0) {
	    bitmap.pixel_mode = FT_PIXEL_MODE_MONO;
	    bitmap.num_grays  = 1;
	    stride = ((width + 31) & -32) >> 3;
	} else {
	    /* XXX not a complete set of flags. This code
	     * will go away when cworth rewrites the glyph
	     * cache code */
	    if (FT_LOAD_TARGET_MODE (val->key.flags) == FT_RENDER_MODE_LCD)
		rgba = FC_RGBA_RGB;
	    else if (FT_LOAD_TARGET_MODE (val->key.flags) == FT_RENDER_MODE_LCD_V)
		rgba = FC_RGBA_VBGR;
	
	    switch (rgba) {
	    case FC_RGBA_RGB:
	    case FC_RGBA_BGR:
		matrix.xx *= 3;
		hmul = 3;
		subpixel = TRUE;
		break;
	    case FC_RGBA_VRGB:
	    case FC_RGBA_VBGR:
		matrix.yy *= 3;
		vmul = 3;
		subpixel = TRUE;
		break;
	    }
	    if (subpixel)
		format = CAIRO_FORMAT_ARGB32;
	    else
		format = CAIRO_FORMAT_A8;
	    
	    if (subpixel)
		FT_Outline_Transform (outline, &matrix);

	    bitmap.pixel_mode = FT_PIXEL_MODE_GRAY;
	    bitmap.num_grays  = 256;
	    stride = (width * hmul + 3) & -4;
	}
	bitmap.pitch = stride;   
	bitmap.width = width * hmul;
	bitmap.rows = height * vmul;
	bitmap.buffer = calloc (1, stride * bitmap.rows);
	
	if (bitmap.buffer == NULL) {
	    return CAIRO_STATUS_NO_MEMORY;
	}
	
	FT_Outline_Translate (outline, -cbox.xMin*hmul, -cbox.yMin*vmul);
	
	if (FT_Outline_Get_Bitmap (glyphslot->library, outline, &bitmap) != 0) {
	    free (bitmap.buffer);
	    return CAIRO_STATUS_NO_MEMORY;
	}

	status = _get_bitmap_surface (val, &bitmap, TRUE, rgba);
	if (status)
	    return status;
    }

    /*
     * Note: the font's coordinate system is upside down from ours, so the
     * Y coordinate of the control box needs to be negated.
     */

    val->size.x =   (short) (cbox.xMin >> 6);
    val->size.y = - (short) (cbox.yMax >> 6);

    return CAIRO_STATUS_SUCCESS;
}

/* Converts a bitmap (or other) FT_GlyphSlot into an image
 * 
 * This could go through _render_glyph_bitmap as well, letting
 * FreeType convert the outline to a bitmap, but doing it ourselves
 * has two minor advantages: first, we save a copy of the bitmap
 * buffer: we can directly use the buffer that FreeType renders
 * into.
 *
 * Second, it may help when we add support for subpixel
 * rendering: the Xft code does it this way. (Keith thinks that
 * it may also be possible to get the subpixel rendering with
 * FT_Render_Glyph: something worth looking into in more detail
 * when we add subpixel support. If so, we may want to eliminate
 * this version of the code path entirely.
 */
static cairo_status_t
_render_glyph_bitmap (FT_Face                          face,
		      cairo_image_glyph_cache_entry_t *val)
{
    FT_GlyphSlot glyphslot = face->glyph;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;
    FT_Error error;

    /* According to the FreeType docs, glyphslot->format could be
     * something other than FT_GLYPH_FORMAT_OUTLINE or
     * FT_GLYPH_FORMAT_BITMAP. Calling FT_Render_Glyph gives FreeType
     * the opportunity to convert such to
     * bitmap. FT_GLYPH_FORMAT_COMPOSITE will not be encountered since
     * we avoid the FT_LOAD_NO_RECURSE flag.
     */
    error = FT_Render_Glyph (glyphslot, FT_RENDER_MODE_NORMAL);
    if (error)
	return CAIRO_STATUS_NO_MEMORY;

    _get_bitmap_surface (val, &glyphslot->bitmap, FALSE, FC_RGBA_NONE);

    val->size.x = glyphslot->bitmap_left;
    val->size.y = - glyphslot->bitmap_top;
    
    return status;
}

static cairo_status_t
_transform_glyph_bitmap (cairo_image_glyph_cache_entry_t *val)
{
    ft_font_transform_t sf;
    cairo_matrix_t original_to_transformed;
    cairo_matrix_t transformed_to_original;
    cairo_image_surface_t *old_image;
    cairo_surface_t *image;
    double x[4], y[4];
    double origin_x, origin_y;
    int i;
    int x_min, y_min, x_max, y_max;
    int width, height;
    cairo_status_t status;
    cairo_surface_pattern_t pattern;
    
    /* We want to compute a transform that takes the origin
     * (val->size.x, val->size.y) to 0,0, then applies the "shape"
     * portion of the font transform
     */
    _compute_transform (&sf, &val->key.scale);

    cairo_matrix_init (&original_to_transformed,
		       sf.shape[0][0], sf.shape[0][1],
		       sf.shape[1][0], sf.shape[1][1],
		       0, 0);

    cairo_matrix_translate (&original_to_transformed,
			    val->size.x, val->size.y);

    /* Find the bounding box of the original bitmap under that
     * transform
     */
    x[0] = 0;               y[0] = 0;
    x[1] = val->size.width; y[1] = 0;
    x[2] = val->size.width; y[2] = val->size.height;
    x[3] = 0;               y[3] = val->size.height;

    for (i = 0; i < 4; i++)
      cairo_matrix_transform_point (&original_to_transformed,
				    &x[i], &y[i]);

    x_min = floor (x[0]);   y_min = floor (y[0]);
    x_max =  ceil (x[0]);   y_max =  ceil (y[0]);
    
    for (i = 1; i < 4; i++) {
	if (x[i] < x_min)
	    x_min = floor (x[i]);
	if (x[i] > x_max)
	    x_max = ceil (x[i]);
	if (y[i] < y_min)
	    y_min = floor (y[i]);
	if (y[i] > y_max)
	    y_max = ceil (y[i]);
    }

    /* Adjust the transform so that the bounding box starts at 0,0 ...
     * this gives our final transform from original bitmap to transformed
     * bitmap.
     */
    original_to_transformed.x0 -= x_min;
    original_to_transformed.y0 -= y_min;

    /* Create the transformed bitmap
     */
    width = x_max - x_min;
    height = y_max - y_min;

    transformed_to_original = original_to_transformed;
    status = cairo_matrix_invert (&transformed_to_original);
    if (status)
	return status;

    /* We need to pad out the width to 32-bit intervals for cairo-xlib-surface.c */
    width = (width + 3) & ~3;
    image = cairo_image_surface_create (CAIRO_FORMAT_A8, width, height);
    if (image->status)
	return image->status;

    /* Initialize it to empty
     */
    _cairo_surface_fill_rectangle (image, CAIRO_OPERATOR_SOURCE,
				   CAIRO_COLOR_TRANSPARENT,
				   0, 0,
				   width, height);

    /* Draw the original bitmap transformed into the new bitmap
     */
    _cairo_pattern_init_for_surface (&pattern, &val->image->base);
    cairo_pattern_set_matrix (&pattern.base, &transformed_to_original);

    _cairo_surface_composite (CAIRO_OPERATOR_OVER,
			      &pattern.base, NULL, image,
			      0, 0, 0, 0, 0, 0,
			      width,
			      height);

    _cairo_pattern_fini (&pattern.base);

    /* Now update the cache entry for the new bitmap, recomputing
     * the origin based on the final transform.
     */
    origin_x = - val->size.x;
    origin_y = - val->size.y;
    cairo_matrix_transform_point (&original_to_transformed,
				  &origin_x, &origin_y);

    old_image = val->image;
    val->image = (cairo_image_surface_t *)image;
    cairo_surface_destroy (&old_image->base);

    val->size.width = width;
    val->size.height = height;
    val->size.x = - floor (origin_x + 0.5);
    val->size.y = - floor (origin_y + 0.5);
    
    return status;
}

static cairo_status_t 
_cairo_ft_unscaled_font_create_glyph (void                            *abstract_font,
				      cairo_image_glyph_cache_entry_t *val)
{
    ft_unscaled_font_t *unscaled = abstract_font;
    FT_GlyphSlot glyphslot;
    FT_Face face;
    FT_Glyph_Metrics *metrics;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;
    double x_factor, y_factor;

    face = _ft_unscaled_font_lock_face (unscaled);
    if (!face)
	return CAIRO_STATUS_NO_MEMORY;

    glyphslot = face->glyph;
    metrics = &glyphslot->metrics;

    _ft_unscaled_font_set_scale (unscaled, &val->key.scale);

    if (FT_Load_Glyph (face, val->key.index, val->key.flags & ~PRIVATE_FLAGS_MASK) != 0) {
	status = CAIRO_STATUS_NO_MEMORY;
	goto FAIL;
    }

    if (unscaled->x_scale == 0)
	x_factor = 0;
    else
	x_factor = 1 / unscaled->x_scale;
    
    if (unscaled->y_scale == 0)
	y_factor = 0;
    else
	y_factor = 1 / unscaled->y_scale;

    /*
     * Note: the font's coordinate system is upside down from ours, so the
     * Y coordinates of the bearing and advance need to be negated.
     *
     * Scale metrics back to glyph space from the scaled glyph space returned
     * by FreeType
     *
     * If we want hinted metrics but aren't asking for hinted glyphs from
     * FreeType, then we need to do the metric hinting ourselves.
     */
    
    if ((val->key.flags & PRIVATE_FLAG_HINT_METRICS) &&
 	(val->key.flags & FT_LOAD_NO_HINTING)) {
 	FT_Pos x1, x2;
 	FT_Pos y1, y2;
 	FT_Pos advance;
	
 	x1 = (metrics->horiBearingX) & -64;
 	x2 = (metrics->horiBearingX + metrics->width + 63) & -64;
 	y1 = (metrics->horiBearingY) & -64;
 	y2 = (metrics->horiBearingY + metrics->height + 63) & -64;
 
 	advance = ((metrics->horiAdvance + 32) & -64);
 	
 	val->extents.x_bearing = DOUBLE_FROM_26_6 (x1) * x_factor;
	val->extents.y_bearing = -DOUBLE_FROM_26_6 (y1) * y_factor;
	
 	val->extents.width  = DOUBLE_FROM_26_6 (x2 - x1) * x_factor;
 	val->extents.height  = DOUBLE_FROM_26_6 (y2 - y1) * y_factor;
 	
 	/*
 	 * use untransformed advance values
 	 * XXX uses horizontal advance only at present; should provide FT_LOAD_VERTICAL_LAYOUT
 	 */
 	val->extents.x_advance = DOUBLE_FROM_26_6 (advance) * x_factor;
 	val->extents.y_advance = 0;
     } else {
	 val->extents.x_bearing = DOUBLE_FROM_26_6 (metrics->horiBearingX) * x_factor;
	 val->extents.y_bearing = -DOUBLE_FROM_26_6 (metrics->horiBearingY) * y_factor;
	 
	 val->extents.width  = DOUBLE_FROM_26_6 (metrics->width) * x_factor;
	 val->extents.height = DOUBLE_FROM_26_6 (metrics->height) * y_factor;
	 
	 val->extents.x_advance = DOUBLE_FROM_26_6 (face->glyph->metrics.horiAdvance) * x_factor;
	 val->extents.y_advance = 0 * y_factor;
     }

    if (glyphslot->format == FT_GLYPH_FORMAT_OUTLINE)
	status = _render_glyph_outline (face, val);
    else
	status = _render_glyph_bitmap (face, val);
    
    if (unscaled->have_shape &&
	(unscaled->face->face_flags & FT_FACE_FLAG_SCALABLE) == 0)
	status = _transform_glyph_bitmap (val);

 FAIL:
    if (status && val->image) {
	cairo_surface_destroy (&val->image->base);
	val->image = NULL;
    }
	    
    _ft_unscaled_font_unlock_face (unscaled);

    return status;
}

const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend = {
    _cairo_ft_unscaled_font_destroy,
    _cairo_ft_unscaled_font_create_glyph
};

/* cairo_ft_scaled_font_t */

typedef struct {
    cairo_scaled_font_t base;
    int load_flags;
    cairo_font_options_t options;
    ft_unscaled_font_t *unscaled;
} cairo_ft_scaled_font_t;

const cairo_scaled_font_backend_t cairo_ft_scaled_font_backend;

/* The load flags passed to FT_Load_Glyph control aspects like hinting and
 * antialiasing. Here we compute them from the fields of a FcPattern.
 */
static int
_get_pattern_load_flags (FcPattern *pattern)
{
    FcBool antialias, vertical_layout, hinting, autohint;
    int rgba;
#ifdef FC_HINT_STYLE    
    int hintstyle;
#endif    
    int load_flags = 0;
    int target_flags = 0;

    /* disable antialiasing if requested */
    if (FcPatternGetBool (pattern,
			  FC_ANTIALIAS, 0, &antialias) != FcResultMatch)
	antialias = FcTrue;

    if (antialias)
	load_flags |= FT_LOAD_NO_BITMAP;
    else
	load_flags |= FT_LOAD_MONOCHROME;
    
    /* disable hinting if requested */
    if (FcPatternGetBool (pattern,
			  FC_HINTING, 0, &hinting) != FcResultMatch)
 	hinting = FcTrue;

#ifdef FC_HINT_STYLE    
    if (FcPatternGetInteger (pattern, FC_HINT_STYLE, 0, &hintstyle) != FcResultMatch)
	hintstyle = FC_HINT_FULL;

    if (!hinting || hintstyle == FC_HINT_NONE)
	load_flags |= FT_LOAD_NO_HINTING;
    
    if (antialias) {
	switch (hintstyle) {
	case FC_HINT_SLIGHT:
	case FC_HINT_MEDIUM:
	    target_flags = FT_LOAD_TARGET_LIGHT;
	    break;
	default:
	    target_flags = FT_LOAD_TARGET_NORMAL;
	    break;
	}
    } else {
#ifdef FT_LOAD_TARGET_MONO
	target_flags = FT_LOAD_TARGET_MONO;
#endif	
    }
#else /* !FC_HINT_STYLE */
    if (!hinting)
	target_flags = FT_LOAD_NO_HINTING;
#endif /* FC_FHINT_STYLE */

    if (FcPatternGetInteger (pattern,
			     FC_RGBA, 0, &rgba) != FcResultMatch)
	rgba = FC_RGBA_UNKNOWN;

    switch (rgba) {
    case FC_RGBA_UNKNOWN:
    case FC_RGBA_NONE:
    default:
	break;
    case FC_RGBA_RGB:
    case FC_RGBA_BGR:
	target_flags = FT_LOAD_TARGET_LCD;
	break;
    case FC_RGBA_VRGB:
    case FC_RGBA_VBGR:
	target_flags = FT_LOAD_TARGET_LCD_V;
	break;
    }

    load_flags |= target_flags;
    
    /* force autohinting if requested */
    if (FcPatternGetBool (pattern,
			  FC_AUTOHINT, 0, &autohint) != FcResultMatch)
	autohint = FcFalse;
    
    if (autohint)
	load_flags |= FT_LOAD_FORCE_AUTOHINT;
    
    if (FcPatternGetBool (pattern,
			  FC_VERTICAL_LAYOUT, 0, &vertical_layout) != FcResultMatch)
	vertical_layout = FcFalse;
    
    if (vertical_layout)
	load_flags |= FT_LOAD_VERTICAL_LAYOUT;
    
    return load_flags;
}

static int
_get_options_load_flags (const cairo_font_options_t *options)
{
    int load_flags = 0;

    /* disable antialiasing if requested */
    switch (options->antialias) {
    case CAIRO_ANTIALIAS_NONE:
#ifdef FT_LOAD_TARGET_MONO
	load_flags |= FT_LOAD_TARGET_MONO;
#endif
	load_flags |= FT_LOAD_MONOCHROME;
	break;
    case CAIRO_ANTIALIAS_SUBPIXEL:
	switch (options->subpixel_order) {
	case CAIRO_SUBPIXEL_ORDER_DEFAULT:
	case CAIRO_SUBPIXEL_ORDER_RGB:
	case CAIRO_SUBPIXEL_ORDER_BGR:
	    load_flags |= FT_LOAD_TARGET_LCD;
	    break;
	case CAIRO_SUBPIXEL_ORDER_VRGB:
	case CAIRO_SUBPIXEL_ORDER_VBGR:
	    load_flags |= FT_LOAD_TARGET_LCD_V;
	    break;
	}
	/* fall through ... */
    case CAIRO_ANTIALIAS_DEFAULT:
    case CAIRO_ANTIALIAS_GRAY:
	load_flags |= FT_LOAD_NO_BITMAP;
	break;
    }
     
    /* disable hinting if requested */
    switch (options->hint_style) {
    case CAIRO_HINT_STYLE_NONE:
	load_flags |= FT_LOAD_NO_HINTING;
	break;
    case CAIRO_HINT_STYLE_SLIGHT:
    case CAIRO_HINT_STYLE_MEDIUM:
 	load_flags |= FT_LOAD_TARGET_LIGHT;
 	break;
    case CAIRO_HINT_STYLE_FULL:
    default:
 	load_flags |= FT_LOAD_TARGET_NORMAL;
 	break;
    }
     
    return load_flags;
}

static cairo_scaled_font_t *
_ft_scaled_font_create (ft_unscaled_font_t         *unscaled,
			const cairo_matrix_t       *font_matrix,
			const cairo_matrix_t       *ctm,
			const cairo_font_options_t *options,
			int                         load_flags)
{    
    cairo_ft_scaled_font_t *f = NULL;

    f = malloc (sizeof(cairo_ft_scaled_font_t));
    if (f == NULL)
	return NULL;

    f->unscaled = unscaled;
    _cairo_unscaled_font_reference (&unscaled->base);
    
    f->options = *options;

    if (options->hint_metrics != CAIRO_HINT_METRICS_OFF)
	load_flags |= PRIVATE_FLAG_HINT_METRICS;

    f->load_flags = load_flags;

    _cairo_scaled_font_init (&f->base, font_matrix, ctm, &cairo_ft_scaled_font_backend);

    return (cairo_scaled_font_t *)f;
}

cairo_bool_t
_cairo_scaled_font_is_ft (cairo_scaled_font_t *scaled_font)
{
    return scaled_font->backend == &cairo_ft_scaled_font_backend;
}

static cairo_status_t
_cairo_ft_scaled_font_create (const char	         *family, 
			      cairo_font_slant_t          slant, 
			      cairo_font_weight_t         weight,
			      const cairo_matrix_t       *font_matrix,
			      const cairo_matrix_t       *ctm,
			      const cairo_font_options_t *options,
			      cairo_scaled_font_t       **font)
{
    FcPattern *pattern, *resolved;
    ft_unscaled_font_t *unscaled;
    cairo_scaled_font_t *new_font;
    FcResult result;
    int fcslant;
    int fcweight;
    cairo_matrix_t scale;
    ft_font_transform_t sf;

    pattern = FcPatternCreate ();
    if (!pattern)
	return CAIRO_STATUS_NO_MEMORY;

    switch (weight)
    {
    case CAIRO_FONT_WEIGHT_BOLD:
        fcweight = FC_WEIGHT_BOLD;
        break;
    case CAIRO_FONT_WEIGHT_NORMAL:
    default:
        fcweight = FC_WEIGHT_MEDIUM;
        break;
    }

    switch (slant)
    {
    case CAIRO_FONT_SLANT_ITALIC:
        fcslant = FC_SLANT_ITALIC;
        break;
    case CAIRO_FONT_SLANT_OBLIQUE:
	fcslant = FC_SLANT_OBLIQUE;
        break;
    case CAIRO_FONT_SLANT_NORMAL:
    default:
        fcslant = FC_SLANT_ROMAN;
        break;
    }

    if (!FcPatternAddString (pattern, FC_FAMILY, (unsigned char *) family))
	goto FREE_PATTERN;
    if (!FcPatternAddInteger (pattern, FC_SLANT, fcslant))
	goto FREE_PATTERN;
    if (!FcPatternAddInteger (pattern, FC_WEIGHT, fcweight))
	goto FREE_PATTERN;

    cairo_matrix_multiply (&scale, font_matrix, ctm);
    _compute_transform (&sf, &scale);

    FcPatternAddInteger (pattern, FC_PIXEL_SIZE, sf.y_scale);

    FcConfigSubstitute (NULL, pattern, FcMatchPattern);
    cairo_ft_font_options_substitute (options, pattern);
    FcDefaultSubstitute (pattern);
    
    resolved = FcFontMatch (NULL, pattern, &result);
    if (!resolved)
	goto FREE_PATTERN;

    unscaled = _ft_unscaled_font_get_for_pattern (resolved);
    if (!unscaled)
	goto FREE_RESOLVED;
    
    new_font = _ft_scaled_font_create (unscaled, 
				       font_matrix, ctm,
				       options, _get_pattern_load_flags (pattern));
    _cairo_unscaled_font_destroy (&unscaled->base);

    FcPatternDestroy (resolved);
    FcPatternDestroy (pattern);

    if (new_font) {
	*font = new_font;
	return CAIRO_STATUS_SUCCESS;
    } else {
	return CAIRO_STATUS_NO_MEMORY; /* A guess */
    }

 FREE_RESOLVED:
    FcPatternDestroy (resolved);
    
 FREE_PATTERN:
    FcPatternDestroy (pattern);

    return CAIRO_STATUS_NO_MEMORY;
}

static void 
_cairo_ft_scaled_font_destroy (void *abstract_font)
{
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
  
    if (scaled_font == NULL)
        return;
  
    _cairo_unscaled_font_destroy (&scaled_font->unscaled->base);
}

static void
_cairo_ft_scaled_font_get_glyph_cache_key (void                    *abstract_font,
					   cairo_glyph_cache_key_t *key)
{
    cairo_ft_scaled_font_t *scaled_font = abstract_font;

    key->unscaled = &scaled_font->unscaled->base;
    key->scale = scaled_font->base.scale;
    key->flags = scaled_font->load_flags;
}

static cairo_status_t 
_cairo_ft_scaled_font_text_to_glyphs (void	     *abstract_font,
				      const char     *utf8,
				      cairo_glyph_t **glyphs, 
				      int	     *num_glyphs)
{
    double x = 0., y = 0.;
    size_t i;
    uint32_t *ucs4 = NULL;
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
    FT_Face face;
    cairo_glyph_cache_key_t key;
    cairo_image_glyph_cache_entry_t *val;
    cairo_cache_t *cache = NULL;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;

    _cairo_ft_scaled_font_get_glyph_cache_key (scaled_font, &key);

    status = _cairo_utf8_to_ucs4 ((unsigned char*)utf8, -1, &ucs4, num_glyphs);
    if (status)
	return status;

    face = cairo_ft_scaled_font_lock_face (&scaled_font->base);
    if (!face) {
	status = CAIRO_STATUS_NO_MEMORY;
	goto FAIL1;
    }

    _cairo_lock_global_image_glyph_cache ();
    cache = _cairo_get_global_image_glyph_cache ();
    if (cache == NULL) {
	status = CAIRO_STATUS_NO_MEMORY;
	goto FAIL2;
    }

    *glyphs = (cairo_glyph_t *) malloc ((*num_glyphs) * (sizeof (cairo_glyph_t)));
    if (*glyphs == NULL) {
	status = CAIRO_STATUS_NO_MEMORY;
	goto FAIL2;
    }

    for (i = 0; i < *num_glyphs; i++)
    {            
        (*glyphs)[i].index = FT_Get_Char_Index (face, ucs4[i]);
	(*glyphs)[i].x = x;
	(*glyphs)[i].y = y;
	
	val = NULL;
	key.index = (*glyphs)[i].index;

	if (_cairo_cache_lookup (cache, &key, (void **) &val, NULL) 
	    != CAIRO_STATUS_SUCCESS || val == NULL)
	    continue;

        x += val->extents.x_advance;
        y += val->extents.y_advance;
    }

 FAIL2:
    if (cache)
	_cairo_unlock_global_image_glyph_cache ();

    cairo_ft_scaled_font_unlock_face (&scaled_font->base);
    
 FAIL1:
    free (ucs4);
    
    return status;
}


static cairo_status_t 
_cairo_ft_scaled_font_font_extents (void		 *abstract_font,
				    cairo_font_extents_t *extents)
{
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
    FT_Face face;
    FT_Size_Metrics *metrics;
    
    face = _ft_unscaled_font_lock_face (scaled_font->unscaled);
    if (!face)
	return CAIRO_STATUS_NO_MEMORY;

    metrics = &face->size->metrics;

    _ft_unscaled_font_set_scale (scaled_font->unscaled, &scaled_font->base.scale);

    /*
     * Get to unscaled metrics so that the upper level can get back to
     * user space
     */
    if (scaled_font->options.hint_metrics != CAIRO_HINT_METRICS_OFF) {
	double x_factor, y_factor;

	if (scaled_font->unscaled->x_scale == 0)
	    x_factor = 0;
	else
	    x_factor = 1 / scaled_font->unscaled->x_scale;
	
	if (scaled_font->unscaled->y_scale == 0)
	    y_factor = 0;
	else
	    y_factor = 1 / scaled_font->unscaled->y_scale;

	extents->ascent =        DOUBLE_FROM_26_6(metrics->ascender) * y_factor;
	extents->descent =       DOUBLE_FROM_26_6(- metrics->descender) * y_factor;
	extents->height =        DOUBLE_FROM_26_6(metrics->height) * y_factor;
	extents->max_x_advance = DOUBLE_FROM_26_6(metrics->max_advance) * x_factor;
    } else {
	double scale = face->units_per_EM;
      
	extents->ascent =        face->ascender / scale;
	extents->descent =       - face->descender / scale;
	extents->height =        face->height / scale;
	extents->max_x_advance = face->max_advance_width / scale;
    }

    /* FIXME: this doesn't do vertical layout atm. */
    extents->max_y_advance = 0.0;

    _ft_unscaled_font_unlock_face (scaled_font->unscaled);

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t 
_cairo_ft_scaled_font_glyph_extents (void			*abstract_font,
				     cairo_glyph_t		*glyphs, 
				     int			num_glyphs,
				     cairo_text_extents_t	*extents)
{
    int i;
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
    cairo_point_double_t origin;
    cairo_point_double_t glyph_min, glyph_max;
    /* Initialize just to squelch anti-helpful compiler warning. */
    cairo_point_double_t total_min = { 0, 0}, total_max = {0,0};

    cairo_image_glyph_cache_entry_t *img = NULL;
    cairo_cache_t *cache;
    cairo_glyph_cache_key_t key;

    if (num_glyphs == 0)
    {
	extents->x_bearing = 0.0;
	extents->y_bearing = 0.0;
	extents->width  = 0.0;
	extents->height = 0.0;
	extents->x_advance = 0.0;
	extents->y_advance = 0.0;

	return CAIRO_STATUS_SUCCESS;
    }

    origin.x = glyphs[0].x;
    origin.y = glyphs[0].y;

    _cairo_lock_global_image_glyph_cache ();
    cache = _cairo_get_global_image_glyph_cache ();
    if (cache == NULL) {
	_cairo_unlock_global_image_glyph_cache ();
	return CAIRO_STATUS_NO_MEMORY;
    }
    
    _cairo_ft_scaled_font_get_glyph_cache_key (scaled_font, &key);

    for (i = 0; i < num_glyphs; i++)
    {
	img = NULL;
	key.index = glyphs[i].index;
	if (_cairo_cache_lookup (cache, &key, (void **) &img, NULL) 
	    != CAIRO_STATUS_SUCCESS || img == NULL)
	    continue;
	
	/* XXX: Need to add code here to check the font's FcPattern
           for FC_VERTICAL_LAYOUT and if set get vertBearingX/Y
           instead. This will require that
           cairo_ft_scaled_font_create_for_ft_face accept an
           FcPattern. */
	glyph_min.x = glyphs[i].x + img->extents.x_bearing;
	glyph_min.y = glyphs[i].y + img->extents.y_bearing;
	glyph_max.x = glyph_min.x + img->extents.width;
	glyph_max.y = glyph_min.y + img->extents.height;
    
	if (i==0) {
	    total_min = glyph_min;
	    total_max = glyph_max;
	} else {
	    if (glyph_min.x < total_min.x)
		total_min.x = glyph_min.x;
	    if (glyph_min.y < total_min.y)
		total_min.y = glyph_min.y;

	    if (glyph_max.x > total_max.x)
		total_max.x = glyph_max.x;
	    if (glyph_max.y > total_max.y)
		total_max.y = glyph_max.y;
	}
    }
    _cairo_unlock_global_image_glyph_cache ();

    extents->x_bearing = (total_min.x - origin.x);
    extents->y_bearing = (total_min.y - origin.y);
    extents->width     = (total_max.x - total_min.x);
    extents->height    = (total_max.y - total_min.y);
    extents->x_advance = glyphs[i-1].x + (img == NULL ? 0 : img->extents.x_advance) - origin.x;
    extents->y_advance = glyphs[i-1].y + (img == NULL ? 0 : img->extents.y_advance) - origin.y;

    return CAIRO_STATUS_SUCCESS;
}


static cairo_status_t 
_cairo_ft_scaled_font_glyph_bbox (void		      *abstract_font,
				  const cairo_glyph_t *glyphs,
				  int                  num_glyphs,
				  cairo_box_t         *bbox)
{
    cairo_image_glyph_cache_entry_t *img;
    cairo_cache_t *cache;
    cairo_glyph_cache_key_t key;
    cairo_ft_scaled_font_t *scaled_font = abstract_font;

    cairo_fixed_t x1, y1, x2, y2;
    int i;

    bbox->p1.x = bbox->p1.y = CAIRO_MAXSHORT << 16;
    bbox->p2.x = bbox->p2.y = CAIRO_MINSHORT << 16;

    _cairo_lock_global_image_glyph_cache ();
    cache = _cairo_get_global_image_glyph_cache();

    if (cache == NULL 
	|| scaled_font == NULL
	|| glyphs == NULL) {
	_cairo_unlock_global_image_glyph_cache ();
        return CAIRO_STATUS_NO_MEMORY;
    }

    _cairo_ft_scaled_font_get_glyph_cache_key (scaled_font, &key);
    
    for (i = 0; i < num_glyphs; i++)
    {

	img = NULL;
	key.index = glyphs[i].index;

	if (_cairo_cache_lookup (cache, &key, (void **) &img, NULL) 
	    != CAIRO_STATUS_SUCCESS || img == NULL)
	    continue;

	x1 = _cairo_fixed_from_double (glyphs[i].x + img->size.x);
	y1 = _cairo_fixed_from_double (glyphs[i].y + img->size.y);
	x2 = x1 + _cairo_fixed_from_double (img->size.width);
	y2 = y1 + _cairo_fixed_from_double (img->size.height);
	
	if (x1 < bbox->p1.x)
	    bbox->p1.x = x1;
	
	if (y1 < bbox->p1.y)
	    bbox->p1.y = y1;
	
	if (x2 > bbox->p2.x)
	    bbox->p2.x = x2;
	
	if (y2 > bbox->p2.y)
	    bbox->p2.y = y2;
    }
    _cairo_unlock_global_image_glyph_cache ();

    return CAIRO_STATUS_SUCCESS;
}


static cairo_status_t 
_cairo_ft_scaled_font_show_glyphs (void		       *abstract_font,
				   cairo_operator_t    	operator,
				   cairo_pattern_t     *pattern,
				   cairo_surface_t     *surface,
				   int                 	source_x,
				   int                 	source_y,
				   int			dest_x,
				   int			dest_y,
				   unsigned int		width,
				   unsigned int		height,
				   const cairo_glyph_t *glyphs,
				   int                 	num_glyphs)
{
    cairo_image_glyph_cache_entry_t *img;
    cairo_cache_t *cache;
    cairo_glyph_cache_key_t key;
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
    cairo_surface_pattern_t glyph_pattern;
    cairo_status_t status;
    int x, y;
    int i;

    _cairo_lock_global_image_glyph_cache ();
    cache = _cairo_get_global_image_glyph_cache();

    if (cache == NULL
	|| scaled_font == NULL 
        || pattern == NULL 
        || surface == NULL 
        || glyphs == NULL) {
	_cairo_unlock_global_image_glyph_cache ();
        return CAIRO_STATUS_NO_MEMORY;
    }

    key.unscaled = &scaled_font->unscaled->base;
    key.scale = scaled_font->base.scale;
    key.flags = scaled_font->load_flags;

    for (i = 0; i < num_glyphs; i++)
    {
	img = NULL;
	key.index = glyphs[i].index;

	if (_cairo_cache_lookup (cache, &key, (void **) &img, NULL) 
	    != CAIRO_STATUS_SUCCESS 
	    || img == NULL 
	    || img->image == NULL)
	    continue;
   
	x = (int) floor (glyphs[i].x + 0.5);
	y = (int) floor (glyphs[i].y + 0.5);

	_cairo_pattern_init_for_surface (&glyph_pattern, &(img->image->base));

	status = _cairo_surface_composite (operator, pattern, 
					   &glyph_pattern.base, 
					   surface,
					   x + img->size.x,
					   y + img->size.y,
					   0, 0, 
					   x + img->size.x, 
					   y + img->size.y, 
					   (double) img->size.width,
					   (double) img->size.height);

	_cairo_pattern_fini (&glyph_pattern.base);

	if (status) {
	    _cairo_unlock_global_image_glyph_cache ();
	    return status;
	}
    }  

    _cairo_unlock_global_image_glyph_cache ();

    return CAIRO_STATUS_SUCCESS;
}


static int
_move_to (const FT_Vector *to, void *closure)
{
    cairo_path_fixed_t *path = closure;
    cairo_fixed_t x, y;

    x = _cairo_fixed_from_26_6 (to->x);
    y = _cairo_fixed_from_26_6 (to->y);

    _cairo_path_fixed_close_path (path);
    _cairo_path_fixed_move_to (path, x, y);

    return 0;
}

static int
_line_to (const FT_Vector *to, void *closure)
{
    cairo_path_fixed_t *path = closure;
    cairo_fixed_t x, y;

    x = _cairo_fixed_from_26_6 (to->x);
    y = _cairo_fixed_from_26_6 (to->y);

    _cairo_path_fixed_line_to (path, x, y);

    return 0;
}

static int
_conic_to (const FT_Vector *control, const FT_Vector *to, void *closure)
{
    cairo_path_fixed_t *path = closure;

    cairo_fixed_t x0, y0;
    cairo_fixed_t x1, y1;
    cairo_fixed_t x2, y2;
    cairo_fixed_t x3, y3;
    cairo_point_t conic;

    _cairo_path_fixed_get_current_point (path, &x0, &y0);

    conic.x = _cairo_fixed_from_26_6 (control->x);
    conic.y = _cairo_fixed_from_26_6 (control->y);

    x3 = _cairo_fixed_from_26_6 (to->x);
    y3 = _cairo_fixed_from_26_6 (to->y);

    x1 = x0 + 2.0/3.0 * (conic.x - x0);
    y1 = y0 + 2.0/3.0 * (conic.y - y0);

    x2 = x3 + 2.0/3.0 * (conic.x - x3);
    y2 = y3 + 2.0/3.0 * (conic.y - y3);

    _cairo_path_fixed_curve_to (path,
				x1, y1,
				x2, y2,
				x3, y3);

    return 0;
}

static int
_cubic_to (const FT_Vector *control1, const FT_Vector *control2,
	   const FT_Vector *to, void *closure)
{
    cairo_path_fixed_t *path = closure;
    cairo_fixed_t x0, y0;
    cairo_fixed_t x1, y1;
    cairo_fixed_t x2, y2;

    x0 = _cairo_fixed_from_26_6 (control1->x);
    y0 = _cairo_fixed_from_26_6 (control1->y);

    x1 = _cairo_fixed_from_26_6 (control2->x);
    y1 = _cairo_fixed_from_26_6 (control2->y);

    x2 = _cairo_fixed_from_26_6 (to->x);
    y2 = _cairo_fixed_from_26_6 (to->y);

    _cairo_path_fixed_curve_to (path,
				x0, y0,
				x1, y1,
				x2, y2);

    return 0;
}

static cairo_status_t 
_cairo_ft_scaled_font_glyph_path (void		     *abstract_font,
				  cairo_glyph_t	     *glyphs, 
				  int		      num_glyphs,
				  cairo_path_fixed_t *path)
{
    int i;
    cairo_ft_scaled_font_t *scaled_font = abstract_font;
    FT_GlyphSlot glyph;
    FT_Face face;
    FT_Error error;
    FT_Outline_Funcs outline_funcs = {
	_move_to,
	_line_to,
	_conic_to,
	_cubic_to,
	0, /* shift */
	0, /* delta */
    };
    
    face = cairo_ft_scaled_font_lock_face (abstract_font);
    if (!face)
	return CAIRO_STATUS_NO_MEMORY;

    glyph = face->glyph;

    for (i = 0; i < num_glyphs; i++)
    {
	FT_Matrix invert_y = {
	    DOUBLE_TO_16_16 (1.0), 0,
	    0, DOUBLE_TO_16_16 (-1.0),
	};

	error = FT_Load_Glyph (scaled_font->unscaled->face, glyphs[i].index, scaled_font->load_flags | FT_LOAD_NO_BITMAP);
	/* XXX: What to do in this error case? */
	if (error)
	    continue;
	/* XXX: Do we want to support bitmap fonts here? */
	if (glyph->format == ft_glyph_format_bitmap)
	    continue;

	/* Font glyphs have an inverted Y axis compared to cairo. */
	FT_Outline_Transform (&glyph->outline, &invert_y);
	FT_Outline_Translate (&glyph->outline,
			      DOUBLE_TO_26_6(glyphs[i].x),
			      DOUBLE_TO_26_6(glyphs[i].y));
	FT_Outline_Decompose (&glyph->outline, &outline_funcs, path);
    }
    _cairo_path_fixed_close_path (path);

    cairo_ft_scaled_font_unlock_face (abstract_font);
    
    return CAIRO_STATUS_SUCCESS;
}

const cairo_scaled_font_backend_t cairo_ft_scaled_font_backend = {
    _cairo_ft_scaled_font_create,
    _cairo_ft_scaled_font_destroy,
    _cairo_ft_scaled_font_font_extents,
    _cairo_ft_scaled_font_text_to_glyphs,
    _cairo_ft_scaled_font_glyph_extents,
    _cairo_ft_scaled_font_glyph_bbox,
    _cairo_ft_scaled_font_show_glyphs,
    _cairo_ft_scaled_font_glyph_path,
    _cairo_ft_scaled_font_get_glyph_cache_key,
};

/* ft_font_face_t */

static void
_ft_font_face_destroy (void *abstract_face)
{
    ft_font_face_t *font_face = abstract_face;
    
    ft_font_face_t *tmp_face = NULL;
    ft_font_face_t *last_face = NULL;

    if (font_face == NULL)
	return;

    /* When destroying the face created by cairo_ft_font_face_create_for_ft_face,
     * we have a special "zombie" state for the face when the unscaled font
     * is still alive but there are no public references to the font face.
     *
     * We go from:
     *
     *   font_face ------> unscaled
     *        <-....weak....../
     *
     * To:
     *
     *    font_face <------- unscaled
     */

    if (font_face->unscaled &&
	font_face->unscaled->from_face &&
	font_face->unscaled->base.ref_count > 1) {
	cairo_font_face_reference (&font_face->base);
	
	_cairo_unscaled_font_destroy (&font_face->unscaled->base);
	font_face->unscaled = NULL;
	
	return;
    }
    
    if (font_face->unscaled) {
	/* Remove face from linked list */
	for (tmp_face = font_face->unscaled->faces; tmp_face; tmp_face = tmp_face->next_face) {
	    if (tmp_face == font_face) {
		if (last_face)
		    last_face->next_face = tmp_face->next_face;
		else
		    font_face->unscaled->faces = tmp_face->next_face;
	    }
	    
	    last_face = tmp_face;
	}

	_cairo_unscaled_font_destroy (&font_face->unscaled->base);
	font_face->unscaled = NULL;
    }
}

static cairo_status_t
_ft_font_face_create_font (void                       *abstract_face,
			   const cairo_matrix_t       *font_matrix,
			   const cairo_matrix_t       *ctm,
			   const cairo_font_options_t *options,
			   cairo_scaled_font_t       **scaled_font)
{
    ft_font_face_t *font_face = abstract_face;
    int load_flags;

    /* The handling of font options is different depending on how the
     * font face was created. When the user creates a font face with
     * cairo_ft_font_face_create_for_ft_face(), then the load flags
     * passed in augment the load flags for the options.  But for
     * cairo_ft_font_face_create_for_pattern(), the load flags are
     * derived from a pattern where the user has called
     * cairo_ft_font_options_substitute(), so *just* use those load
     * flags and ignore the options.
     */
    if (font_face->unscaled->from_face)
	load_flags = _get_options_load_flags (options) | font_face->load_flags;
    else
	load_flags = font_face->load_flags;

    *scaled_font = _ft_scaled_font_create (font_face->unscaled,
					   font_matrix, ctm,
					   options, load_flags);
    if (*scaled_font)
	return CAIRO_STATUS_SUCCESS;
    else
	return CAIRO_STATUS_NO_MEMORY;
}

static const cairo_font_face_backend_t _ft_font_face_backend = {
    _ft_font_face_destroy,
    _ft_font_face_create_font,
};

static cairo_font_face_t *
_ft_font_face_create (ft_unscaled_font_t *unscaled,
		      int                 load_flags)
{
    ft_font_face_t *font_face;

    /* Looked for an existing matching font face */
    for (font_face = unscaled->faces; font_face; font_face = font_face->next_face) {
	if (font_face->load_flags == load_flags) {
	    cairo_font_face_reference (&font_face->base);
	    return &font_face->base;
	}
    }

    /* No match found, create a new one */
    font_face = malloc (sizeof (ft_font_face_t));
    if (!font_face)
	return NULL;
    
    font_face->unscaled = unscaled;
    _cairo_unscaled_font_reference (&unscaled->base);
    
    font_face->load_flags = load_flags;

    font_face->next_face = unscaled->faces;
    unscaled->faces = font_face;
    
    _cairo_font_face_init (&font_face->base, &_ft_font_face_backend);

    return &font_face->base;
}

/* implement the platform-specific interface */

/**
 * cairo_ft_font_options_substitute:
 * @options: a #cairo_font_options_t object
 * @pattern: an existing #FcPattern
 * 
 * Add options to a #FcPattern based on a #cairo_font_options_t font
 * options object. Options that are already in the pattern, are not overriden,
 * so you should call this function after calling FcConfigSubstitute() (the
 * user's settings should override options based on the surface type), but
 * before calling FcDefaultSubstitute().
 **/
void
cairo_ft_font_options_substitute (const cairo_font_options_t *options,
				  FcPattern                  *pattern)
{
    FcValue v;

    if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
    {
	if (FcPatternGet (pattern, FC_ANTIALIAS, 0, &v) == FcResultNoMatch)
	{
	    FcPatternAddBool (pattern, FC_ANTIALIAS, options->antialias != CAIRO_ANTIALIAS_NONE);
	}
    }

    if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
    {
	if (FcPatternGet (pattern, FC_RGBA, 0, &v) == FcResultNoMatch)
	{
	    int rgba;
	    
	    if (options->antialias == CAIRO_ANTIALIAS_SUBPIXEL) {
		switch (options->subpixel_order) {
		case CAIRO_SUBPIXEL_ORDER_DEFAULT:
		case CAIRO_SUBPIXEL_ORDER_RGB:
		default:
		    rgba = FC_RGBA_RGB;
		    break;
		case CAIRO_SUBPIXEL_ORDER_BGR:
		    rgba = FC_RGBA_BGR;
		    break;
		case CAIRO_SUBPIXEL_ORDER_VRGB:
		    rgba = FC_RGBA_VRGB;
		    break;
		case CAIRO_SUBPIXEL_ORDER_VBGR:
		    rgba = FC_RGBA_VBGR;
		    break;
		}
	    } else {
		rgba = FC_RGBA_NONE;
	    }
	    
	    FcPatternAddInteger (pattern, FC_RGBA, rgba);
	}
    }

    if (options->hint_style != CAIRO_HINT_STYLE_DEFAULT)
    {
	if (FcPatternGet (pattern, FC_HINTING, 0, &v) == FcResultNoMatch)
	{
	    FcPatternAddBool (pattern, FC_HINTING, options->hint_style != CAIRO_HINT_STYLE_NONE);
	}

#ifdef FC_HINT_STYLE	
	if (FcPatternGet (pattern, FC_HINT_STYLE, 0, &v) == FcResultNoMatch)
	{
	    int hint_style;

	    switch (options->hint_style) {
	    case CAIRO_HINT_STYLE_SLIGHT:
		hint_style = FC_HINT_SLIGHT;
		break;
	    case CAIRO_HINT_STYLE_MEDIUM:
		hint_style = FC_HINT_MEDIUM;
		break;
	    case CAIRO_HINT_STYLE_FULL:
	    default:
		hint_style = FC_HINT_FULL;
		break;
	    }
	    
	    FcPatternAddInteger (pattern, FC_HINT_STYLE, hint_style);
	}
#endif	
    }
}

/**
 * cairo_ft_font_face_create_for_pattern:
 * @pattern: A fully resolved fontconfig
 *   pattern. A pattern can be resolved, by, among other things, calling
 *   FcConfigSubstitute(), FcDefaultSubstitute(), then
 *   FcFontMatch(). Cairo will call FcPatternReference() on this
 *   pattern, so you should not further modify the pattern, but you can
 *   release your reference to the pattern with FcPatternDestroy() if
 *   you no longer need to access it.
 * 
 * Creates a new font face for the FreeType font backend based on a
 * fontconfig pattern. This font can then be used with
 * cairo_set_font_face() or cairo_font_create(). The #cairo_scaled_font_t
 * returned from cairo_font_create() is also for the FreeType backend
 * and can be used with functions such as cairo_ft_font_lock_face().
 *
 * Font rendering options are representated both here and when you
 * call cairo_scaled_font_create(). Font options that have a representation
 * in a #FcPattern must be passed in here; to modify #FcPattern
 * appropriately to reflect the options in a #cairo_font_options_t, call
 * cairo_ft_font_options_substitute().
 *
 * Return value: a newly created #cairo_font_face_t. Free with
 *  cairo_font_face_destroy() when you are done using it.
 **/
cairo_font_face_t *
cairo_ft_font_face_create_for_pattern (FcPattern *pattern)
{
    ft_unscaled_font_t *unscaled;
    cairo_font_face_t *font_face;

    unscaled = _ft_unscaled_font_get_for_pattern (pattern);
    if (unscaled == NULL) {
	_cairo_error (CAIRO_STATUS_NO_MEMORY);
	return (cairo_font_face_t *)&_cairo_font_face_nil;
    }

    font_face = _ft_font_face_create (unscaled, _get_pattern_load_flags (pattern));
    _cairo_unscaled_font_destroy (&unscaled->base);

    if (font_face)
	return font_face;
    else {
	_cairo_error (CAIRO_STATUS_NO_MEMORY);
	return (cairo_font_face_t *)&_cairo_font_face_nil;
    }
}

/**
 * cairo_ft_font_face_create_for_ft_face:
 * @face: A FreeType face object, already opened. This must
 *   be kept around until the face's ref_count drops to
 *   zero and it is freed. Since the face may be referenced
 *   internally to Cairo, the best way to determine when it
 *   is safe to free the face is to pass a
 *   #cairo_destroy_func_t to cairo_font_face_set_user_data()
 * @load_flags: flags to pass to FT_Load_Glyph when loading
 *   glyphs from the font. These flags are OR'ed together with
 *   the flags derived from the #cairo_font_options_t passed
 *   to cairo_scaled_font_create(), so only a few values such
 *   as %FT_LOAD_VERTICAL_LAYOUT, and %FT_LOAD_FORCE_AUTOHINT
 *   are useful. You should not pass any of the flags affecting
 *   the load target, such as %FT_LOAD_TARGET_LIGHT.
 * 
 * Creates a new font face for the FreeType font backend from a pre-opened
 * FreeType face. This font can then be used with
 * cairo_set_font_face() or cairo_font_create(). The #cairo_scaled_font_t
 * returned from cairo_font_create() is also for the FreeType backend
 * and can be used with functions such as cairo_ft_font_lock_face().
 * 
 * Return value: a newly created #cairo_font_face_t. Free with
 *  cairo_font_face_destroy() when you are done using it.
 **/
cairo_font_face_t *
cairo_ft_font_face_create_for_ft_face (FT_Face         face,
				       int             load_flags)
{
    ft_unscaled_font_t *unscaled;
    cairo_font_face_t *font_face;

    unscaled = _ft_unscaled_font_create_from_face (face);
    if (unscaled == NULL) {
	_cairo_error (CAIRO_STATUS_NO_MEMORY);
	return (cairo_font_face_t *)&_cairo_font_face_nil;
    }

    font_face = _ft_font_face_create (unscaled, load_flags);
    _cairo_unscaled_font_destroy (&unscaled->base);

    if (font_face) {
	return font_face;
    } else {
	_cairo_error (CAIRO_STATUS_NO_MEMORY);
	return (cairo_font_face_t *)&_cairo_font_face_nil;
    }
}

/**
 * cairo_ft_scaled_font_lock_face:
 * @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
 *   object can be created by calling cairo_scaled_font_create() on a
 *   FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
 *   cairo_ft_font_face_create_for_face()).
 * 
 * cairo_ft_font_lock_face() gets the #FT_Face object from a FreeType
 * backend font and scales it appropriately for the font. You must
 * release the face with cairo_ft_font_unlock_face()
 * when you are done using it.  Since the #FT_Face object can be
 * shared between multiple #cairo_scaled_font_t objects, you must not
 * lock any other font objects until you unlock this one. A count is
 * kept of the number of times cairo_ft_font_lock_face() is
 * called. cairo_ft_font_unlock_face() must be called the same number
 * of times.
 *
 * You must be careful when using this function in a library or in a
 * threaded application, because other threads may lock faces that
 * share the same #FT_Face object. For this reason, you must call
 * cairo_ft_lock() before locking any face objects, and
 * cairo_ft_unlock() after you are done. (These functions are not yet
 * implemented, so this function cannot be currently safely used in a
 * threaded application.)
 
 * Return value: The #FT_Face object for @font, scaled appropriately,
 * or %NULL if @scaled_font is in an error state (see
 * cairo_scaled_font_status()) or there is insufficient memory.
 **/
FT_Face
cairo_ft_scaled_font_lock_face (cairo_scaled_font_t *abstract_font)
{
    cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
    FT_Face face;

    if (scaled_font->base.status)
	return NULL;

    face = _ft_unscaled_font_lock_face (scaled_font->unscaled);
    if (face == NULL) {
	_cairo_scaled_font_set_error (&scaled_font->base, CAIRO_STATUS_NO_MEMORY);
	return NULL;
    }
    
    _ft_unscaled_font_set_scale (scaled_font->unscaled, &scaled_font->base.scale);

    return face;
}

/**
 * cairo_ft_scaled_font_unlock_face:
 * @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
 *   object can be created by calling cairo_scaled_font_create() on a
 *   FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
 *   cairo_ft_font_face_create_for_face()).
 * 
 * Releases a face obtained with cairo_ft_font_lock_face(). See the
 * documentation for that function for full details.
 **/
void
cairo_ft_scaled_font_unlock_face (cairo_scaled_font_t *abstract_font)
{
    cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;

    if (scaled_font->base.status)
	return;

    _ft_unscaled_font_unlock_face (scaled_font->unscaled);
}

/* We expose our unscaled font implementation internally for the the
 * PDF backend, which needs to keep track of the the different
 * fonts-on-disk used by a document, so it can embed them.
 */
cairo_unscaled_font_t *
_cairo_ft_scaled_font_get_unscaled_font (cairo_scaled_font_t *abstract_font)
{
    cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;

    return &scaled_font->unscaled->base;
}

/* This differs from _cairo_ft_scaled_font_lock_face in that it doesn't
 * set the scale on the face, but just returns it at the last scale.
 */
FT_Face
_cairo_ft_unscaled_font_lock_face (cairo_unscaled_font_t *unscaled_font)
{
    return _ft_unscaled_font_lock_face ((ft_unscaled_font_t *)unscaled_font);
}

void
_cairo_ft_unscaled_font_unlock_face (cairo_unscaled_font_t *unscaled_font)
{
    _ft_unscaled_font_unlock_face ((ft_unscaled_font_t *)unscaled_font);
}