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

#define QT_FATAL_ASSERT

#include "qfont.h"
#include "qfontdatabase.h"
#include "qfontmetrics.h"
#include "qfontinfo.h"
#include "qpainter.h"
#include "qdict.h"
#include "qcache.h"
#include "qdatastream.h"
#include "qapplication.h"
#include "qcleanuphandler.h"
#include "qstringlist.h"
#ifdef Q_WS_MAC
#include "qpaintdevicemetrics.h"
#endif

#include <private/qunicodetables_p.h>
#include "qfontdata_p.h"
#include "qfontengine_p.h"
#include "qpainter_p.h"
#include "qtextengine_p.h"

// #define QFONTCACHE_DEBUG
#ifdef QFONTCACHE_DEBUG
#  define FC_DEBUG tqDebug
#else
#  define FC_DEBUG if (FALSE) tqDebug
#endif




bool QFontDef::operator==( const QFontDef &other ) const
{
    /*
      QFontDef comparison is more complicated than just simple
      per-member comparisons.

      When comparing point/pixel sizes, either point or pixelsize
      could be -1.  in This case we have to compare the non negative
      size value.

      This test will fail if the point-sizes differ by 1/2 point or
      more or they do not round to the same value.  We have to do this
      since our API still uses 'int' point-sizes in the API, but store
      deci-point-sizes internally.

      To compare the family members, we need to parse the font names
      and compare the family/foundry strings separately.  This allows
      us to compare e.g. "Helvetica" and "Helvetica [Adobe]" with
      positive results.
    */
    if (pixelSize != -1 && other.pixelSize != -1) {
	if (pixelSize != other.pixelSize)
	    return FALSE;
    } else if (pointSize != -1 && other.pointSize != -1) {
	if (pointSize != other.pointSize
	    && (QABS(pointSize - other.pointSize) >= 5
		|| qRound(pointSize/10.) != qRound(other.pointSize/10.)))
	    return FALSE;
    } else {
	return FALSE;
    }

    if (!ignorePitch && !other.ignorePitch && fixedPitch != other.fixedPitch)
	return FALSE;

    if (stretch != 0 && other.stretch != 0 && stretch != other.stretch)
	return FALSE;

    QString this_family, this_foundry, other_family, other_foundry;
    QFontDatabase::parseFontName(family, this_foundry, this_family);
    QFontDatabase::parseFontName(other.family, other_foundry, other_family);

    return ( styleHint     == other.styleHint
	    && styleStrategy == other.styleStrategy
	    && weight        == other.weight
	    && italic        == other.italic
	    && this_family   == other_family
	    && (this_foundry.isEmpty()
		|| other_foundry.isEmpty()
		|| this_foundry == other_foundry)
#ifdef Q_WS_X11
	    && addStyle == other.addStyle
#endif // Q_WS_X11
	);
}




QFontPrivate::QFontPrivate()
    : engineData( 0 ), paintdevice( 0 ),
      rawMode( FALSE ), underline( FALSE ), overline( FALSE ), strikeOut( FALSE ),
      mask( 0 )
{
#ifdef Q_WS_X11
    screen = QPaintDevice::x11AppScreen();
#else
    screen = 0;
#endif // Q_WS_X11
}

QFontPrivate::QFontPrivate( const QFontPrivate &other )
    : QShared(), request( other.request ), engineData( 0 ),
      paintdevice( other.paintdevice ), screen( other.screen ),
      rawMode( other.rawMode ), underline( other.underline ), overline( other.overline ),
      strikeOut( other.strikeOut ), mask( other.mask )
{
}

QFontPrivate::~QFontPrivate()
{
    if ( engineData )
	engineData->deref();
    engineData = 0;
}

void QFontPrivate::resolve( const QFontPrivate *other )
{
#ifdef QT_CHECK_STATE
    Q_ASSERT( other != 0 );
#endif

    if ( ( mask & Complete ) == Complete ) return;

    // assign the unset-bits with the set-bits of the other font def
    if ( ! ( mask & Family ) )
	request.family = other->request.family;

    if ( ! ( mask & Size ) ) {
	request.pointSize = other->request.pointSize;
	request.pixelSize = other->request.pixelSize;
    }

    if ( ! ( mask & StyleHint ) )
	request.styleHint = other->request.styleHint;

    if ( ! ( mask & StyleStrategy ) )
	request.styleStrategy = other->request.styleStrategy;

    if ( ! ( mask & Weight ) )
	request.weight = other->request.weight;

    if ( ! ( mask & Italic ) )
	request.italic = other->request.italic;

    if ( ! ( mask & FixedPitch ) )
	request.fixedPitch = other->request.fixedPitch;

    if ( ! ( mask & Stretch ) )
	request.stretch = other->request.stretch;

    if ( ! ( mask & Underline ) )
	underline = other->underline;

    if ( ! ( mask & Overline ) )
	overline = other->overline;

    if ( ! ( mask & StrikeOut ) )
	strikeOut = other->strikeOut;
}




QFontEngineData::QFontEngineData()
    : lineWidth( 1 )
{
#if defined(Q_WS_X11) || defined(Q_WS_WIN)
    memset( engines, 0, QFont::LastPrivateScript * sizeof( QFontEngine * ) );
#else
    engine = 0;
#endif // Q_WS_X11 || Q_WS_WIN
#ifndef Q_WS_MAC
    memset( widthCache, 0, widthCacheSize*sizeof( uchar ) );
#endif
}

QFontEngineData::~QFontEngineData()
{
#if defined(Q_WS_X11) || defined(Q_WS_WIN)
    for ( int i = 0; i < QFont::LastPrivateScript; i++ ) {
	if ( engines[i] )
	    engines[i]->deref();
	engines[i] = 0;
    }
#else
    if ( engine )
	engine->deref();
    engine = 0;
#endif // Q_WS_X11 || Q_WS_WIN
}




/*!
    \class QFont qfont.h
    \brief The QFont class specifies a font used for drawing text.

    \ingroup graphics
    \ingroup appearance
    \ingroup shared
    \mainclass

    When you create a QFont object you specify various attributes that
    you want the font to have. Qt will use the font with the specified
    attributes, or if no matching font exists, Qt will use the closest
    matching installed font. The attributes of the font that is
    actually used are retrievable from a QFontInfo object. If the
    window system provides an exact match exactMatch() returns TRUE.
    Use QFontMetrics to get measurements, e.g. the pixel length of a
    string using QFontMetrics::width().

    Use QApplication::setFont() to set the application's default font.

    If a choosen X11 font does not include all the characters that
    need to be displayed, QFont will try to find the characters in the
    nearest equivalent fonts. When a QPainter draws a character from a
    font the QFont will report whether or not it has the character; if
    it does not, QPainter will draw an unfilled square.

    Create QFonts like this:
    \code
    QFont serifFont( "Times", 10, Bold );
    QFont sansFont( "Helvetica [Cronyx]", 12 );
    \endcode

    The attributes set in the constructor can also be set later, e.g.
    setFamily(), setPointSize(), setPointSizeFloat(), setWeight() and
    setItalic(). The remaining attributes must be set after
    contstruction, e.g. setBold(), setUnderline(), setOverline(),
    setStrikeOut() and setFixedPitch(). QFontInfo objects should be
    created \e after the font's attributes have been set. A QFontInfo
    object will not change, even if you change the font's
    attributes. The corresponding "get" functions, e.g. family(),
    pointSize(), etc., return the values that were set, even though
    the values used may differ. The actual values are available from a
    QFontInfo object.

    If the requested font family is unavailable you can influence the
    \link #fontmatching font matching algorithm\endlink by choosing a
    particular \l{QFont::StyleHint} and \l{QFont::StyleStrategy} with
    setStyleHint(). The default family (corresponding to the current
    style hint) is returned by defaultFamily().

    The font-matching algorithm has a lastResortFamily() and
    lastResortFont() in cases where a suitable match cannot be found.
    You can provide substitutions for font family names using
    insertSubstitution() and insertSubstitutions(). Substitutions can
    be removed with removeSubstitution(). Use substitute() to retrieve
    a family's first substitute, or the family name itself if it has
    no substitutes. Use substitutes() to retrieve a list of a family's
    substitutes (which may be empty).

    Every QFont has a key() which you can use, for example, as the key
    in a cache or dictionary. If you want to store a user's font
    preferences you could use QSettings, writing the font information
    with toString() and reading it back with fromString(). The
    operator<<() and operator>>() functions are also available, but
    they work on a data stream.

    It is possible to set the height of characters shown on the screen
    to a specified number of pixels with setPixelSize(); however using
    setPointSize() has a similar effect and provides device
    independence.

    Under the X Window System you can set a font using its system
    specific name with setRawName().

    Loading fonts can be expensive, especially on X11. QFont contains
    extensive optimizations to make the copying of QFont objects fast,
    and to cache the results of the slow window system functions it
    depends upon.

    \target fontmatching
    The font matching algorithm works as follows:
    \list 1
    \i The specified font family is searched for.
    \i If not found, the styleHint() is used to select a replacement
       family.
    \i Each replacement font family is searched for.
    \i If none of these are found or there was no styleHint(), "helvetica"
       will be searched for.
    \i If "helvetica" isn't found Qt will try the lastResortFamily().
    \i If the lastResortFamily() isn't found Qt will try the
       lastResortFont() which will always return a name of some kind.
    \endlist

    Once a font is found, the remaining attributes are matched in order of
    priority:
    \list 1
    \i fixedPitch()
    \i pointSize() (see below)
    \i weight()
    \i italic()
    \endlist

    If you have a font which matches on family, even if none of the
    other attributes match, this font will be chosen in preference to
    a font which doesn't match on family but which does match on the
    other attributes. This is because font family is the dominant
    search criteria.

    The point size is defined to match if it is within 20% of the
    requested point size. When several fonts match and are only
    distinguished by point size, the font with the closest point size
    to the one requested will be chosen.

    The actual family, font size, weight and other font attributes
    used for drawing text will depend on what's available for the
    chosen family under the window system. A QFontInfo object can be
    used to determine the actual values used for drawing the text.

    Examples:

    \code
    QFont f("Helvetica");
    \endcode
    If you had both an Adobe and a Cronyx Helvetica, you might get
    either.

    \code
    QFont f1( "Helvetica [Cronyx]" );  // Qt 3.x
    QFont f2( "Cronyx-Helvetica" );    // Qt 2.x compatibility
    \endcode
    You can specify the foundry you want in the family name. Both fonts,
    f1 and f2, in the above example will be set to  "Helvetica
    [Cronyx]".

    To determine the attributes of the font actually used in the window
    system, use a QFontInfo object, e.g.
    \code
    QFontInfo info( f1 );
    QString family = info.family();
    \endcode

    To find out font metrics use a QFontMetrics object, e.g.
    \code
    QFontMetrics fm( f1 );
    int pixelWidth = fm.width( "How many pixels wide is this text?" );
    int pixelHeight = fm.height();
    \endcode

    For more general information on fonts, see the
    \link http://www.nwalsh.com/comp.fonts/FAQ/ comp.fonts FAQ.\endlink
    Information on encodings can be found from
    \link http://czyborra.com/ Roman Czyborra's\endlink page.

    \sa QFontMetrics QFontInfo QFontDatabase QApplication::setFont()
    QWidget::setFont() QPainter::setFont() QFont::StyleHint
    QFont::Weight
*/

/*!
    \enum QFont::Script

    This enum represents \link unicode.html Unicode \endlink allocated
    scripts. For exhaustive coverage see \link
    http://www.amazon.com/exec/obidos/ASIN/0201616335/trolltech/t The
    Unicode Standard Version 3.0 \endlink. The following scripts are
    supported:

    Modern European alphabetic scripts (left to right):

    \value Latin consists of most alphabets based on the original Latin alphabet.
    \value Greek covers ancient and modern Greek and Coptic.
    \value Cyrillic covers the Slavic and non-Slavic languages using
	   cyrillic alphabets.
    \value Armenian contains the Armenian alphabet used with the
	   Armenian language.
    \value Georgian covers at least the language Georgian.
    \value Runic covers the known constituents of the Runic alphabets used
	   by the early and medieval societies in the Germanic,
	   Scandinavian, and Anglo-Saxon areas.
    \value Ogham is an alphabetical script used to write a very early
	   form of Irish.
    \value SpacingModifiers are small signs indicating modifications
	   to the preceeding letter.
    \value CombiningMarks consist of diacritical marks not specific to
	   a particular alphabet, diacritical marks used in
	   combination with mathematical and technical symbols, and
	   glyph encodings applied to multiple letterforms.

    Middle Eastern scripts (right to left):

    \value Hebrew is used for writing Hebrew, Yiddish, and some other languages.
    \value Arabic covers the Arabic language as well as Persian, Urdu,
	   Kurdish and some others.
    \value Syriac is used to write the active liturgical languages and
	   dialects of several Middle Eastern and Southeast Indian
	   communities.
    \value Thaana is used to write the Maledivian Dhivehi language.

    South and Southeast Asian scripts (left to right with few historical exceptions):

    \value Devanagari covers classical Sanskrit and modern Hindi as
	   well as several other languages.
    \value Bengali is a relative to Devanagari employed to write the
	   Bengali language used in West Bengal/India and Bangladesh
	   as well as several minority languages.
    \value Gurmukhi is another Devanagari relative used to write Punjabi.
    \value Gujarati is closely related to Devanagari and used to write
	   the Gujarati language of the Gujarat state in India.
    \value Oriya is used to write the Oriya language of Orissa state/India.
    \value Tamil is used to write the Tamil language of Tamil Nadu state/India,
	   Sri Lanka, Singapore and parts of Malaysia as well as some
	   minority languages.
    \value Telugu is used to write the Telugu language of Andhra
	   Pradesh state/India and some minority languages.
    \value Kannada is another South Indian script used to write the
	   Kannada language of Karnataka state/India and some minority
	   languages.
    \value Malayalam is used to write the Malayalam language of Kerala
	   state/India.
    \value Sinhala is used for Sri Lanka's majority language Sinhala
	   and is also employed to write Pali, Sanskrit, and Tamil.
    \value Thai is used to write Thai and other Southeast Asian languages.
    \value Lao is a language and script quite similar to Thai.
    \value Tibetan is the script used to write Tibetan in several
	   countries like Tibet, the bordering Indian regions and
	   Nepal. It is also used in the Buddist philosophy and
	   liturgy of the Mongolian cultural area.
    \value Myanmar is mainly used to write the Burmese language of
	   Myanmar (former Burma).
    \value Khmer is the official language of Kampuchea.

    East Asian scripts (traditionally top-down, right to left, modern
    often horizontal left to right):

    \value Han consists of the CJK (Chinese, Japanese, Korean)
	   idiographic characters.
    \value Hiragana is a cursive syllabary used to indicate phonetics
	   and pronounciation of Japanese words.
    \value Katakana is a non-cursive syllabic script used to write
	   Japanese words with visual emphasis and non-Japanese words
	   in a phonetical manner.
    \value Hangul is a Korean script consisting of alphabetic components.
    \value Bopomofo is a phonetic alphabet for Chinese (mainly Mandarin).
    \value Yi (also called Cuan or Wei) is a syllabary used to write
	   the Yi language of Southwestern China, Myanmar, Laos, and Vietnam.

    Additional scripts that do not fit well into the script categories above:

    \value Ethiopic is a syllabary used by several Central East African languages.
    \value Cherokee is a left-to-right syllabic script used to write
	   the Cherokee language.
    \value CanadianAboriginal consists of the syllabics used by some
	   Canadian aboriginal societies.
    \value Mongolian is the traditional (and recently reintroduced)
	   script used to write Mongolian.

    Symbols:

    \value CurrencySymbols contains currency symbols not encoded in other scripts.
    \value LetterlikeSymbols consists of symbols derived  from
	   ordinary letters of an alphabetical script.
    \value NumberForms are provided for compatibility with other
	   existing character sets.
    \value MathematicalOperators consists of encodings for operators,
	   relations and other symbols like arrows used in a mathematical context.
    \value TechnicalSymbols contains representations for control
	   codes, the space symbol, APL symbols and other symbols
	   mainly used in the context of electronic data processing.
    \value GeometricSymbols covers block elements and geometric shapes.
    \value MiscellaneousSymbols consists of a heterogeneous collection
	   of symbols that do not fit any other Unicode character
	   block, e.g. Dingbats.
    \value EnclosedAndSquare is provided for compatibility with some
	   East Asian standards.
    \value Braille is an international writing system used by blind
	   people. This script encodes the 256 eight-dot patterns with
	   the 64 six-dot patterns as a subset.

    \value Tagalog
    \value Hanunoo
    \value Buhid
    \value Tagbanwa

    \value KatakanaHalfWidth

    \value Limbu (Unicode 4.0)
    \value TaiLe (Unicode 4.0)

    \value Unicode includes all the above scripts.
*/

/*! \internal

    Constructs a font for use on the paint device \a pd using the
    specified font \a data.
*/
QFont::QFont( QFontPrivate *data, QPaintDevice *pd )
{
    d = new QFontPrivate( *data );
    Q_CHECK_PTR( d );
    d->paintdevice = pd;

    // now a single reference
    d->count = 1;
}

/*! \internal
    Detaches the font object from common font data.
*/
void QFont::detach()
{
    if (d->count == 1) {
	if ( d->engineData )
	    d->engineData->deref();
	d->engineData = 0;

	return;
    }

    QFontPrivate *old_d = d;
    d = new QFontPrivate( *old_d );

    /*
      if this font is a copy of the application default font, set the
      fontdef mask to zero to indicate that *nothing* has been
      explicitly set by the programmer.
    */
    const QFont appfont = QApplication::font();
    if ( old_d == appfont.d )
	d->mask = 0;

    if ( old_d->deref() )
	delete old_d;
}

/*!
    Constructs a font object that uses the application's default font.

    \sa QApplication::setFont(), QApplication::font()
*/
QFont::QFont()
{
    const QFont appfont = QApplication::font();
    d = appfont.d;
    d->ref();
}

/*!
    Constructs a font object with the specified \a family, \a
    pointSize, \a weight and \a italic settings.

    If \a pointSize is <= 0 it is set to 1.

    The \a family name may optionally also include a foundry name,
    e.g. "Helvetica [Cronyx]". (The Qt 2.x syntax, i.e.
    "Cronyx-Helvetica", is also supported.) If the \a family is
    available from more than one foundry and the foundry isn't
    specified, an arbitrary foundry is chosen. If the family isn't
    available a family will be set using the \link #fontmatching font
    matching\endlink algorithm.

    \sa Weight, setFamily(), setPointSize(), setWeight(), setItalic(),
    setStyleHint() QApplication::font()
*/
QFont::QFont( const QString &family, int pointSize, int weight, bool italic )
{

    d = new QFontPrivate;
    Q_CHECK_PTR( d );

    d->mask = QFontPrivate::Family;

    if (pointSize <= 0) {
	pointSize = 12;
    } else {
	d->mask |= QFontPrivate::Size;
    }

    if (weight < 0) {
	weight = Normal;
    } else {
	d->mask |= QFontPrivate::Weight | QFontPrivate::Italic;
    }

    d->request.family = family;
    d->request.pointSize = pointSize * 10;
    d->request.pixelSize = -1;
    d->request.weight = weight;
    d->request.italic = italic;
}

/*!
    Constructs a font that is a copy of \a font.
*/
QFont::QFont( const QFont &font )
{
    d = font.d;
    d->ref();
}

/*!
    Destroys the font object and frees all allocated resources.
*/
QFont::~QFont()
{
    if ( d->deref() )
	delete d;
    d = 0;
}

/*!
    Assigns \a font to this font and returns a reference to it.
*/
QFont &QFont::operator=( const QFont &font )
{
    if ( font.d != d ) {
	if ( d->deref() )
	    delete d;
	d = font.d;
	d->ref();
    }

    return *this;
}

/*!
    Returns the requested font family name, i.e. the name set in the
    constructor or the last setFont() call.

    \sa setFamily() substitutes() substitute()
*/
QString QFont::family() const
{
    return d->request.family;
}

/*!
    Sets the family name of the font. The name is case insensitive and
    may include a foundry name.

    The \a family name may optionally also include a foundry name,
    e.g. "Helvetica [Cronyx]". (The Qt 2.x syntax, i.e.
    "Cronyx-Helvetica", is also supported.) If the \a family is
    available from more than one foundry and the foundry isn't
    specified, an arbitrary foundry is chosen. If the family isn't
    available a family will be set using the \link #fontmatching font
    matching\endlink algorithm.

    \sa family(), setStyleHint(), QFontInfo
*/
void QFont::setFamily( const QString &family )
{
    detach();

    d->request.family = family;
#if defined(Q_WS_X11)
    d->request.addStyle = QString::null;
#endif // Q_WS_X11

    d->mask |= QFontPrivate::Family;
}

/*!
    Returns the point size in 1/10ths of a point.

    The returned value will be -1 if the font size has been specified
    in pixels.

    \sa pointSize() pointSizeFloat()
  */
int QFont::deciPointSize() const
{
    return d->request.pointSize;
}

/*!
    Returns the point size of the font. Returns -1 if the font size
    was specified in pixels.

    \sa setPointSize() deciPointSize() pointSizeFloat()
*/
int QFont::pointSize() const
{
    return d->request.pointSize == -1 ? -1 : (d->request.pointSize + 5) / 10;
}

/*!
    Sets the point size to \a pointSize. The point size must be
    greater than zero.

    \sa pointSize() setPointSizeFloat()
*/
void QFont::setPointSize( int pointSize )
{
    if ( pointSize <= 0 ) {

#if defined(QT_CHECK_RANGE)
	tqWarning( "QFont::setPointSize: Point size <= 0 (%d)", pointSize );
#endif

	return;
    }

    detach();

    d->request.pointSize = pointSize * 10;
    d->request.pixelSize = -1;

    d->mask |= QFontPrivate::Size;
}

/*!
    Sets the point size to \a pointSize. The point size must be
    greater than zero. The requested precision may not be achieved on
    all platforms.

    \sa pointSizeFloat() setPointSize() setPixelSize()
*/
void QFont::setPointSizeFloat( float pointSize )
{
    if ( pointSize <= 0.0 ) {
#if defined(QT_CHECK_RANGE)
	tqWarning( "QFont::setPointSize: Point size <= 0 (%f)", pointSize );
#endif
	return;
    }

    detach();

    d->request.pointSize = qRound(pointSize * 10.0);
    d->request.pixelSize = -1;

    d->mask |= QFontPrivate::Size;
}

/*!
    Returns the point size of the font. Returns -1 if the font size was
    specified in pixels.

    \sa pointSize() setPointSizeFloat() pixelSize() QFontInfo::pointSize() QFontInfo::pixelSize()
*/
float QFont::pointSizeFloat() const
{
    return float( d->request.pointSize == -1 ? -10 : d->request.pointSize ) / 10.0;
}

/*!
    Sets the font size to \a pixelSize pixels.

    Using this function makes the font device dependent. Use
    setPointSize() or setPointSizeFloat() to set the size of the font
    in a device independent manner.

    \sa pixelSize()
*/
void QFont::setPixelSize( int pixelSize )
{
    if ( pixelSize <= 0 ) {
#if defined(QT_CHECK_RANGE)
	tqWarning( "QFont::setPixelSize: Pixel size <= 0 (%d)", pixelSize );
#endif
	return;
    }

    detach();

    d->request.pixelSize = pixelSize;
    d->request.pointSize = -1;

    d->mask |= QFontPrivate::Size;
}

/*!
    Returns the pixel size of the font if it was set with
    setPixelSize(). Returns -1 if the size was set with setPointSize()
    or setPointSizeFloat().

    \sa setPixelSize() pointSize() QFontInfo::pointSize() QFontInfo::pixelSize()
*/
int QFont::pixelSize() const
{
    return d->request.pixelSize;
}

/*! \obsolete

  Sets the logical pixel height of font characters when shown on
  the screen to \a pixelSize.
*/
void QFont::setPixelSizeFloat( float pixelSize )
{
    setPixelSize( (int)pixelSize );
}

/*!
    Returns TRUE if italic has been set; otherwise returns FALSE.

    \sa setItalic()
*/
bool QFont::italic() const
{
    return d->request.italic;
}

/*!
    If \a enable is TRUE, italic is set on; otherwise italic is set
    off.

    \sa italic(), QFontInfo
*/
void QFont::setItalic( bool enable )
{
    detach();

    d->request.italic = enable;
    d->mask |= QFontPrivate::Italic;
}

/*!
    Returns the weight of the font which is one of the enumerated
    values from \l{QFont::Weight}.

    \sa setWeight(), Weight, QFontInfo
*/
int QFont::weight() const
{
    return d->request.weight;
}

/*!
    \enum QFont::Weight

    Qt uses a weighting scale from 0 to 99 similar to, but not the
    same as, the scales used in Windows or CSS. A weight of 0 is
    ultralight, whilst 99 will be an extremely black.

    This enum contains the predefined font weights:

    \value Light 25
    \value Normal 50
    \value DemiBold 63
    \value Bold 75
    \value Black 87
*/

/*!
    Sets the weight the font to \a weight, which should be a value
    from the \l QFont::Weight enumeration.

    \sa weight(), QFontInfo
*/
void QFont::setWeight( int weight )
{
    if ( weight < 0 || weight > 99 ) {

#if defined(QT_CHECK_RANGE)
	tqWarning( "QFont::setWeight: Value out of range (%d)", weight );
#endif

	return;
    }

    detach();

    d->request.weight = weight;
    d->mask |= QFontPrivate::Weight;
}

/*!
    \fn bool QFont::bold() const

    Returns TRUE if weight() is a value greater than \link Weight
    QFont::Normal \endlink; otherwise returns FALSE.

    \sa weight(), setBold(), QFontInfo::bold()
*/

/*!
    \fn void QFont::setBold( bool enable )

    If \a enable is true sets the font's weight to \link Weight
    QFont::Bold \endlink; otherwise sets the weight to \link Weight
    QFont::Normal\endlink.

    For finer boldness control use setWeight().

    \sa bold(), setWeight()
*/

/*!
    Returns TRUE if underline has been set; otherwise returns FALSE.

    \sa setUnderline()
*/
bool QFont::underline() const
{
    return d->underline;
}

/*!
    If \a enable is TRUE, sets underline on; otherwise sets underline
    off.

    \sa underline(), QFontInfo
*/
void QFont::setUnderline( bool enable )
{
    detach();

    d->underline = enable;
    d->mask |= QFontPrivate::Underline;
}

/*!
    Returns TRUE if overline has been set; otherwise returns FALSE.

    \sa setOverline()
*/
bool QFont::overline() const
{
    return d->overline;
}

/*!
  If \a enable is TRUE, sets overline on; otherwise sets overline off.

  \sa overline(), QFontInfo
*/
void QFont::setOverline( bool enable )
{
    detach();

    d->overline = enable;
    d->mask |= QFontPrivate::Overline;
}

/*!
    Returns TRUE if strikeout has been set; otherwise returns FALSE.

    \sa setStrikeOut()
*/
bool QFont::strikeOut() const
{
    return d->strikeOut;
}

/*!
    If \a enable is TRUE, sets strikeout on; otherwise sets strikeout
    off.

    \sa strikeOut(), QFontInfo
*/
void QFont::setStrikeOut( bool enable )
{
    detach();

    d->strikeOut = enable;
    d->mask |= QFontPrivate::StrikeOut;
}

/*!
    Returns TRUE if fixed pitch has been set; otherwise returns FALSE.

    \sa setFixedPitch(), QFontInfo::fixedPitch()
*/
bool QFont::fixedPitch() const
{
    return d->request.fixedPitch;
}

/*!
    If \a enable is TRUE, sets fixed pitch on; otherwise sets fixed
    pitch off.

    \sa fixedPitch(), QFontInfo
*/
void QFont::setFixedPitch( bool enable )
{
    detach();

    d->request.fixedPitch = enable;
    d->request.ignorePitch = FALSE;
    d->mask |= QFontPrivate::FixedPitch;
}

/*!
    Returns the StyleStrategy.

    The style strategy affects the \link #fontmatching font
    matching\endlink algorithm. See \l QFont::StyleStrategy for the
    list of strategies.

    \sa setStyleHint() QFont::StyleHint
*/
QFont::StyleStrategy QFont::styleStrategy() const
{
    return (StyleStrategy) d->request.styleStrategy;
}

/*!
    Returns the StyleHint.

    The style hint affects the \link #fontmatching font
    matching\endlink algorithm. See \l QFont::StyleHint for the list
    of strategies.

    \sa setStyleHint(), QFont::StyleStrategy QFontInfo::styleHint()
*/
QFont::StyleHint QFont::styleHint() const
{
    return (StyleHint) d->request.styleHint;
}

/*!
    \enum QFont::StyleHint

    Style hints are used by the \link #fontmatching font
    matching\endlink algorithm to find an appropriate default family
    if a selected font family is not available.

    \value AnyStyle leaves the font matching algorithm to choose the
	   family. This is the default.

    \value SansSerif the font matcher prefer sans serif fonts.
    \value Helvetica is a synonym for \c SansSerif.

    \value Serif the font matcher prefers serif fonts.
    \value Times is a synonym for \c Serif.

    \value TypeWriter the font matcher prefers fixed pitch fonts.
    \value Courier a synonym for \c TypeWriter.

    \value OldEnglish the font matcher prefers decorative fonts.
    \value Decorative is a synonym for \c OldEnglish.

    \value System the font matcher prefers system fonts.
*/

/*!
    \enum QFont::StyleStrategy

    The style strategy tells the \link #fontmatching font
    matching\endlink algorithm what type of fonts should be used to
    find an appropriate default family.

    The following strategies are available:

    \value PreferDefault the default style strategy. It does not prefer
	   any type of font.
    \value PreferBitmap prefers bitmap fonts (as opposed to outline
	   fonts).
    \value PreferDevice prefers device fonts.
    \value PreferOutline prefers outline fonts (as opposed to bitmap fonts).
    \value ForceOutline forces the use of outline fonts.
    \value NoAntialias don't antialias the fonts.
    \value PreferAntialias antialias if possible.
    \value OpenGLCompatible forces the use of OpenGL compatible
           fonts.

    Any of these may be OR-ed with one of these flags:

    \value PreferMatch prefer an exact match. The font matcher will try to
	   use the exact font size that has been specified.
    \value PreferQuality prefer the best quality font. The font matcher
	   will use the nearest standard point size that the font
	   supports.
*/

/*!
    Sets the style hint and strategy to \a hint and \a strategy,
    respectively.

    If these aren't set explicitly the style hint will default to
    \c AnyStyle and the style strategy to \c PreferDefault.

    Qt does not support style hints on X11 since this information
    is not provided by the window system.

    \sa StyleHint, styleHint(), StyleStrategy, styleStrategy(), QFontInfo
*/
void QFont::setStyleHint( StyleHint hint, StyleStrategy strategy )
{
    detach();

    if ( ( d->mask & ( QFontPrivate::StyleHint | QFontPrivate::StyleStrategy ) ) &&
	 (StyleHint) d->request.styleHint == hint &&
	 (StyleStrategy) d->request.styleStrategy == strategy )
	return;

    d->request.styleHint = hint;
    d->request.styleStrategy = strategy;
    d->mask |= QFontPrivate::StyleHint;
    d->mask |= QFontPrivate::StyleStrategy;

#if defined(Q_WS_X11)
    d->request.addStyle = QString::null;
#endif // Q_WS_X11
}

/*!
    Sets the style strategy for the font to \a s.

    \sa QFont::StyleStrategy
*/
void QFont::setStyleStrategy( StyleStrategy s )
{
    detach();

    if ( ( d->mask & QFontPrivate::StyleStrategy ) &&
	 s == (StyleStrategy)d->request.styleStrategy )
	return;

    d->request.styleStrategy = s;
    d->mask |= QFontPrivate::StyleStrategy;
}


/*!
    \enum QFont::Stretch

    Predefined stretch values that follow the CSS naming convention.

    \value UltraCondensed 50
    \value ExtraCondensed 62
    \value Condensed 75
    \value SemiCondensed 87
    \value Unstretched 100
    \value SemiExpanded 112
    \value Expanded 125
    \value ExtraExpanded 150
    \value UltraExpanded 200

    \sa setStretch() stretch()
*/

/*!
    Returns the stretch factor for the font.

    \sa setStretch()
 */
int QFont::stretch() const
{
    return d->request.stretch;
}

/*!
    Sets the stretch factor for the font.

    The stretch factor changes the width of all characters in the font
    by \a factor percent.  For example, setting \a factor to 150
    results in all characters in the font being 1.5 times ( ie. 150% )
    wider.  The default stretch factor is 100.  The minimum stretch
    factor is 1, and the maximum stretch factor is 4000.

    The stretch factor is only applied to outline fonts.  The stretch
    factor is ignored for bitmap fonts.

    NOTE: QFont cannot stretch XLFD fonts.  When loading XLFD fonts on
    X11, the stretch factor is matched against a predefined set of
    values for the SETWIDTH_NAME field of the XLFD.

    \sa stretch() QFont::StyleStrategy
*/
void QFont::setStretch( int factor )
{
    if ( factor < 1 || factor > 4000 ) {
#ifdef QT_CHECK_RANGE
	tqWarning( "QFont::setStretch(): parameter '%d' out of range", factor );
#endif // QT_CHECK_RANGE

	return;
    }

    detach();

    if ( ( d->mask & QFontPrivate::Stretch ) &&
	 d->request.stretch == (uint)factor )
	return;

    d->request.stretch = (uint)factor;
    d->mask |= QFontPrivate::Stretch;
}

/*!
    If \a enable is TRUE, turns raw mode on; otherwise turns raw mode
    off. This function only has an effect under X11.

    If raw mode is enabled, Qt will search for an X font with a
    complete font name matching the family name, ignoring all other
    values set for the QFont. If the font name matches several fonts,
    Qt will use the first font returned by X. QFontInfo \e cannot be
    used to fetch information about a QFont using raw mode (it will
    return the values set in the QFont for all parameters, including
    the family name).

    \warning Do not use raw mode unless you really, really need it! In
    most (if not all) cases, setRawName() is a much better choice.

    \sa rawMode(), setRawName()
*/
void QFont::setRawMode( bool enable )
{
    detach();

    if ( (bool) d->rawMode == enable ) return;

    d->rawMode = enable;
}

/*!
    Returns TRUE if a window system font exactly matching the settings
    of this font is available.

    \sa QFontInfo
*/
bool QFont::exactMatch() const
{
    QFontEngine *engine = d->engineForScript( QFont::NoScript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    return d->rawMode ? engine->type() != QFontEngine::Box
			     : d->request == engine->fontDef;
}

/*!
    Returns TRUE if this font is equal to \a f; otherwise returns
    FALSE.

    Two QFonts are considered equal if their font attributes are
    equal. If rawMode() is enabled for both fonts, only the family
    fields are compared.

    \sa operator!=() isCopyOf()
*/
bool QFont::operator==( const QFont &f ) const
{
    return f.d == d || ( f.d->request   == d->request   &&
			 f.d->underline == d->underline &&
			 f.d->overline  == d->overline  &&
			 f.d->strikeOut == d->strikeOut );
}

/*!
    Returns TRUE if this font is different from \a f; otherwise
    returns FALSE.

    Two QFonts are considered to be different if their font attributes
    are different. If rawMode() is enabled for both fonts, only the
    family fields are compared.

    \sa operator==()
*/
bool QFont::operator!=( const QFont &f ) const
{
    return !(operator==( f ));
}

/*!
    Returns TRUE if this font and \a f are copies of each other, i.e.
    one of them was created as a copy of the other and neither has
    been modified since. This is much stricter than equality.

    \sa operator=() operator==()
*/
bool QFont::isCopyOf( const QFont & f ) const
{
    return d == f.d;
}

/*!
    Returns TRUE if raw mode is used for font name matching; otherwise
    returns FALSE.

    \sa setRawMode() rawName()
*/
bool QFont::rawMode() const
{
    return d->rawMode;
}

/*!
    Returns a new QFont that has attributes copied from \a other.
*/
QFont QFont::resolve( const QFont &other ) const
{
    if ( *this == other && d->mask == other.d->mask )
	return *this;

    QFont font( *this );
    font.detach();

    /*
      if this font is a copy of the application default font, set the
      fontdef mask to zero to indicate that *nothing* has been
      explicitly set by the programmer.
    */
    const QFont appfont = QApplication::font();
    if ( d == appfont.d )
	font.d->mask = 0;

    font.d->resolve( other.d );

    return font;
}

#ifndef QT_NO_COMPAT

/*! \obsolete

  Please use QApplication::font() instead.
*/
QFont QFont::defaultFont()
{
    return QApplication::font();
}

/*! \obsolete

  Please use QApplication::setFont() instead.
*/
void QFont::setDefaultFont( const QFont &f )
{
    QApplication::setFont( f );
}


#endif




#ifndef QT_NO_STRINGLIST

/*****************************************************************************
  QFont substitution management
 *****************************************************************************/

typedef QDict<QStringList> QFontSubst;
static QFontSubst *fontSubst = 0;
static QSingleCleanupHandler<QFontSubst> qfont_cleanup_fontsubst;


// create substitution dict
static void initFontSubst()
{
    // default substitutions
    static const char *initTbl[] = {

#if defined(Q_WS_X11)
	"arial",        "helvetica",
	"helv",         "helvetica",
	"tms rmn",      "times",
#elif defined(Q_WS_WIN)
	"times",        "Times New Roman",
	"courier",      "Courier New",
	"helvetica",    "Arial",
#endif

	0,              0
    };

    if (fontSubst)
	return;

    fontSubst = new QFontSubst(17, FALSE);
    Q_CHECK_PTR( fontSubst );
    fontSubst->setAutoDelete( TRUE );
    qfont_cleanup_fontsubst.set(&fontSubst);

    for ( int i=0; initTbl[i] != 0; i += 2 )
	QFont::insertSubstitution(QString::fromLatin1(initTbl[i]),
				  QString::fromLatin1(initTbl[i+1]));
}


/*!
    Returns the first family name to be used whenever \a familyName is
    specified. The lookup is case insensitive.

    If there is no substitution for \a familyName, \a familyName is
    returned.

    To obtain a list of substitutions use substitutes().

    \sa setFamily() insertSubstitutions() insertSubstitution() removeSubstitution()
*/
QString QFont::substitute( const QString &familyName )
{
    initFontSubst();

    QStringList *list = fontSubst->find(familyName);
    if (list && list->count() > 0)
	return *(list->at(0));

    return familyName;
}


/*!
    Returns a list of family names to be used whenever \a familyName
    is specified. The lookup is case insensitive.

    If there is no substitution for \a familyName, an empty list is
    returned.

    \sa substitute() insertSubstitutions() insertSubstitution() removeSubstitution()
 */
QStringList QFont::substitutes(const QString &familyName)
{
    initFontSubst();

    QStringList ret, *list = fontSubst->find(familyName);
    if (list)
	ret += *list;
    return ret;
}


/*!
    Inserts the family name \a substituteName into the substitution
    table for \a familyName.

    \sa insertSubstitutions() removeSubstitution() substitutions() substitute() substitutes()
*/
void QFont::insertSubstitution(const QString &familyName,
			       const QString &substituteName)
{
    initFontSubst();

    QStringList *list = fontSubst->find(familyName);
    if (! list) {
	list = new QStringList;
	fontSubst->insert(familyName, list);
    }

    if (! list->contains(substituteName))
	list->append(substituteName);
}


/*!
    Inserts the list of families \a substituteNames into the
    substitution list for \a familyName.

    \sa insertSubstitution(), removeSubstitution(), substitutions(), substitute()
*/
void QFont::insertSubstitutions(const QString &familyName,
				const QStringList &substituteNames)
{
    initFontSubst();

    QStringList *list = fontSubst->find(familyName);
    if (! list) {
	list = new QStringList;
	fontSubst->insert(familyName, list);
    }

    QStringList::ConstIterator it = substituteNames.begin();
    while (it != substituteNames.end()) {
	if (! list->contains(*it))
	    list->append(*it);
	it++;
    }
}

// ### mark: should be called removeSubstitutions()
/*!
    Removes all the substitutions for \a familyName.

    \sa insertSubstitutions(), insertSubstitution(), substitutions(), substitute()
*/
void QFont::removeSubstitution( const QString &familyName )
{ // ### function name should be removeSubstitutions() or
  // ### removeSubstitutionList()
    initFontSubst();

    fontSubst->remove(familyName);
}


/*!
    Returns a sorted list of substituted family names.

    \sa insertSubstitution(), removeSubstitution(), substitute()
*/
QStringList QFont::substitutions()
{
    initFontSubst();

    QStringList ret;
    QDictIterator<QStringList> it(*fontSubst);

    while (it.current()) {
	ret.append(it.currentKey());
	++it;
    }

    ret.sort();

    return ret;
}

#endif // QT_NO_STRINGLIST


/*  \internal
    Internal function. Converts boolean font settings to an unsigned
    8-bit number. Used for serialization etc.
*/
static Q_UINT8 get_font_bits( const QFontPrivate *f )
{
#ifdef QT_CHECK_STATE
    Q_ASSERT( f != 0 );
#endif

    Q_UINT8 bits = 0;
    if ( f->request.italic )
	bits |= 0x01;
    if ( f->underline )
	bits |= 0x02;
    if ( f->overline )
	bits |= 0x40;
    if ( f->strikeOut )
	bits |= 0x04;
    if ( f->request.fixedPitch )
	bits |= 0x08;
    // if ( f.hintSetByUser )
    // bits |= 0x10;
    if ( f->rawMode )
	bits |= 0x20;
    return bits;
}


#ifndef QT_NO_DATASTREAM

/*  \internal
    Internal function. Sets boolean font settings from an unsigned
    8-bit number. Used for serialization etc.
*/
static void set_font_bits( Q_UINT8 bits, QFontPrivate *f )
{
#ifdef QT_CHECK_STATE
    Q_ASSERT( f != 0 );
#endif

    f->request.italic        = (bits & 0x01) != 0;
    f->underline             = (bits & 0x02) != 0;
    f->overline              = (bits & 0x40) != 0;
    f->strikeOut             = (bits & 0x04) != 0;
    f->request.fixedPitch    = (bits & 0x08) != 0;
    // f->hintSetByUser      = (bits & 0x10) != 0;
    f->rawMode               = (bits & 0x20) != 0;
}

#endif


/*!
    Returns the font's key, a textual representation of a font. It is
    typically used as the key for a cache or dictionary of fonts.

    \sa QMap
*/
QString QFont::key() const
{
    return toString();
}

/*!
    Returns a description of the font. The description is a
    comma-separated list of the attributes, perfectly suited for use
    in QSettings.

    \sa fromString() operator<<()
 */
QString QFont::toString() const
{
    const QChar comma( ',' );
    return family() + comma +
	QString::number(  pointSizeFloat() ) + comma +
	QString::number(       pixelSize() ) + comma +
	QString::number( (int) styleHint() ) + comma +
	QString::number(          weight() ) + comma +
	QString::number( (int)    italic() ) + comma +
	QString::number( (int) underline() ) + comma +
	QString::number( (int) strikeOut() ) + comma +
	QString::number( (int)fixedPitch() ) + comma +
	QString::number( (int)   rawMode() );
}


/*!
    Sets this font to match the description \a descrip. The description
    is a comma-separated list of the font attributes, as returned by
    toString().

    \sa toString() operator>>()
 */
bool QFont::fromString(const QString &descrip)
{
#ifndef QT_NO_STRINGLIST
    QStringList l(QStringList::split(',', descrip));

    int count = (int)l.count();
#else
    int count = 0;
    QString l[11];
    int from = 0;
    int to = descrip.find( ',' );
    while ( to > 0 && count < 11 ) {
	l[count] = descrip.mid( from, to-from );
	count++;
	from = to+1;
	to = descrip.find( ',', from );
    }
#endif // QT_NO_STRINGLIST
    if ( !count || ( count > 2 && count < 9 ) || count > 11 ) {

#ifdef QT_CHECK_STATE
	tqWarning("QFont::fromString: invalid description '%s'",
                 descrip.isEmpty() ? "(empty)" : descrip.latin1());
#endif

	return FALSE;
    }

    setFamily(l[0]);
    if ( count > 1 && l[1].toDouble() > 0.0 )
	setPointSizeFloat(l[1].toDouble());
    if ( count == 9 ) {
	setStyleHint((StyleHint) l[2].toInt());
	setWeight(l[3].toInt());
	setItalic(l[4].toInt());
	setUnderline(l[5].toInt());
	setStrikeOut(l[6].toInt());
	setFixedPitch(l[7].toInt());
	setRawMode(l[8].toInt());
    } else if ( count == 10 ) {
	if ( l[2].toInt() > 0 )
	    setPixelSize( l[2].toInt() );
	setStyleHint((StyleHint) l[3].toInt());
	setWeight(l[4].toInt());
	setItalic(l[5].toInt());
	setUnderline(l[6].toInt());
	setStrikeOut(l[7].toInt());
	setFixedPitch(l[8].toInt());
	setRawMode(l[9].toInt());
    }

    return TRUE;
}

#if !defined( Q_WS_QWS )
/*! \internal

  Internal function that dumps font cache statistics.
*/
void QFont::cacheStatistics()
{


}
#endif // !Q_WS_QWS



/*****************************************************************************
  QFont stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM

/*!
    \relates QFont

    Writes the font \a font to the data stream \a s. (toString()
    writes to a text stream.)

    \sa \link datastreamformat.html Format of the QDataStream operators \endlink
*/
QDataStream &operator<<( QDataStream &s, const QFont &font )
{
    if ( s.version() == 1 ) {
	QCString fam( font.d->request.family.latin1() );
	s << fam;
    } else {
	s << font.d->request.family;
    }

    if ( s.version() <= 3 ) {
	Q_INT16 pointSize = (Q_INT16) font.d->request.pointSize;
	if ( pointSize == -1 ) {
#ifdef Q_WS_X11
	    pointSize = (Q_INT16)(font.d->request.pixelSize*720/QPaintDevice::x11AppDpiY());
#else
	    pointSize = (Q_INT16)QFontInfo( font ).pointSize() * 10;
#endif
	}
	s << pointSize;
    } else {
	s << (Q_INT16) font.d->request.pointSize;
	s << (Q_INT16) font.d->request.pixelSize;
    }

    s << (Q_UINT8) font.d->request.styleHint;
    if ( s.version() >= 5 )
	s << (Q_UINT8 ) font.d->request.styleStrategy;
    return s << (Q_UINT8) 0
	     << (Q_UINT8) font.d->request.weight
	     << get_font_bits(font.d);
}


/*!
    \relates QFont

    Reads the font \a font from the data stream \a s. (fromString()
    reads from a text stream.)

    \sa \link datastreamformat.html Format of the QDataStream operators \endlink
*/
QDataStream &operator>>( QDataStream &s, QFont &font )
{
    if (font.d->deref()) delete font.d;

    font.d = new QFontPrivate;
    font.d->mask = QFontPrivate::Complete;

    Q_INT16 pointSize, pixelSize = -1;
    Q_UINT8 styleHint, styleStrategy = QFont::PreferDefault, charSet, weight, bits;

    if ( s.version() == 1 ) {
	QCString fam;
	s >> fam;
	font.d->request.family = QString( fam );
    } else {
	s >> font.d->request.family;
    }

    s >> pointSize;
    if ( s.version() >= 4 )
	s >> pixelSize;
    s >> styleHint;
    if ( s.version() >= 5 )
	s >> styleStrategy;
    s >> charSet;
    s >> weight;
    s >> bits;

    font.d->request.pointSize = pointSize;
    font.d->request.pixelSize = pixelSize;
    font.d->request.styleHint = styleHint;
    font.d->request.styleStrategy = styleStrategy;
    font.d->request.weight = weight;

    set_font_bits( bits, font.d );

    return s;
}

#endif // QT_NO_DATASTREAM




/*****************************************************************************
  QFontMetrics member functions
 *****************************************************************************/

/*!
    \class QFontMetrics qfontmetrics.h
    \brief The QFontMetrics class provides font metrics information.

    \ingroup graphics
    \ingroup shared

    QFontMetrics functions calculate the size of characters and
    strings for a given font. There are three ways you can create a
    QFontMetrics object:

    \list 1
    \i Calling the QFontMetrics constructor with a QFont creates a
    font metrics object for a screen-compatible font, i.e. the font
    cannot be a printer font<sup>*</sup>. If the font is changed
    later, the font metrics object is \e not updated.

    \i QWidget::fontMetrics() returns the font metrics for a widget's
    font. This is equivalent to QFontMetrics(widget->font()). If the
    widget's font is changed later, the font metrics object is \e not
    updated.

    \i QPainter::fontMetrics() returns the font metrics for a
    painter's current font. If the painter's font is changed later, the
    font metrics object is \e not updated.
    \endlist

    <sup>*</sup> If you use a printer font the values returned may be
    inaccurate. Printer fonts are not always accessible so the nearest
    screen font is used if a printer font is supplied.

    Once created, the object provides functions to access the
    individual metrics of the font, its characters, and for strings
    rendered in the font.

    There are several functions that operate on the font: ascent(),
    descent(), height(), leading() and lineSpacing() return the basic
    size properties of the font. The underlinePos(), overlinePos(),
    strikeOutPos() and lineWidth() functions, return the properties of
    the line that underlines, overlines or strikes out the
    characters. These functions are all fast.

    There are also some functions that operate on the set of glyphs in
    the font: minLeftBearing(), minRightBearing() and maxWidth().
    These are by necessity slow, and we recommend avoiding them if
    possible.

    For each character, you can get its width(), leftBearing() and
    rightBearing() and find out whether it is in the font using
    inFont(). You can also treat the character as a string, and use
    the string functions on it.

    The string functions include width(), to return the width of a
    string in pixels (or points, for a printer), boundingRect(), to
    return a rectangle large enough to contain the rendered string,
    and size(), to return the size of that rectangle.

    Example:
    \code
    QFont font( "times", 24 );
    QFontMetrics fm( font );
    int pixelsWide = fm.width( "What's the width of this text?" );
    int pixelsHigh = fm.height();
    \endcode

    \sa QFont QFontInfo QFontDatabase
*/

/*!
    Constructs a font metrics object for \a font.

    The font must be screen-compatible, i.e. a font you use when
    drawing text in \link QWidget widgets\endlink or \link QPixmap
    pixmaps\endlink, not QPicture or QPrinter.

    The font metrics object holds the information for the font that is
    passed in the constructor at the time it is created, and is not
    updated if the font's attributes are changed later.

  Use QPainter::fontMetrics() to get the font metrics when painting.
  This will give correct results also when painting on paint device
  that is not screen-compatible.
*/
QFontMetrics::QFontMetrics( const QFont &font )
    : d( font.d ), painter( 0 ), fscript( QFont::NoScript )
{
    d->ref();
}

/*!
    \overload

    Constructs a font metrics object for \a font using the given \a
    script.
*/
QFontMetrics::QFontMetrics( const QFont &font, QFont::Script script )
    : d( font.d ), painter( 0 ), fscript( script )
{
    d->ref();
}

/*! \internal

  Constructs a font metrics object for the painter's font \a p.
*/
QFontMetrics::QFontMetrics( const QPainter *p )
    : painter ( (QPainter *) p ), fscript( QFont::NoScript )
{
#if defined(CHECK_STATE)
    if ( !painter->isActive() )
	tqWarning( "QFontMetrics: Get font metrics between QPainter::begin() "
		  "and QPainter::end()" );
#endif

    if ( painter->testf(QPainter::DirtyFont) )
	painter->updateFont();

    d = painter->pfont ? painter->pfont->d : painter->cfont.d;

#if defined(Q_WS_X11)
    if ( d->screen != p->scrn ) {
	QFontPrivate *new_d = new QFontPrivate( *d );
	Q_CHECK_PTR( new_d );
	d = new_d;
	d->screen = p->scrn;
	d->count = 1;
    } else
#endif // Q_WS_X11
	d->ref();
}

/*!
    Constructs a copy of \a fm.
*/
QFontMetrics::QFontMetrics( const QFontMetrics &fm )
    : d( fm.d ), painter( 0 ),  fscript( fm.fscript )
{
    d->ref();
}

/*!
    Destroys the font metrics object and frees all allocated
    resources.
*/
QFontMetrics::~QFontMetrics()
{
    if ( d->deref() )
	delete d;
}

/*!
    Assigns the font metrics \a fm.
*/
QFontMetrics &QFontMetrics::operator=( const QFontMetrics &fm )
{
    if ( d != fm.d ) {
	if ( d->deref() )
	    delete d;
	d = fm.d;
	d->ref();
    }
    painter = fm.painter;
    return *this;
}

/*!
    Returns the ascent of the font.

    The ascent of a font is the distance from the baseline to the
    highest position characters extend to. In practice, some font
    designers break this rule, e.g. when they put more than one accent
    on top of a character, or to accommodate an unusual character in
    an exotic language, so it is possible (though rare) that this
    value will be too small.

    \sa descent()
*/
int QFontMetrics::ascent() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return QMAX(engine->ascent(), latin_engine->ascent());
}


/*!
    Returns the descent of the font.

    The descent is the distance from the base line to the lowest point
    characters extend to. (Note that this is different from X, which
    adds 1 pixel.) In practice, some font designers break this rule,
    e.g. to accommodate an unusual character in an exotic language, so
    it is possible (though rare) that this value will be too small.

    \sa ascent()
*/
int QFontMetrics::descent() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return QMAX(engine->descent(), latin_engine->descent());
}

/*!
    Returns the height of the font.

    This is always equal to ascent()+descent()+1 (the 1 is for the
    base line).

    \sa leading(), lineSpacing()
*/
int QFontMetrics::height() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return (QMAX(engine->ascent(), latin_engine->ascent()) +
	    QMAX(engine->descent(), latin_engine->descent()) + 1);
}

/*!
    Returns the leading of the font.

    This is the natural inter-line spacing.

    \sa height(), lineSpacing()
*/
int QFontMetrics::leading() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return QMAX(engine->leading(), latin_engine->leading());
}

/*!
    Returns the distance from one base line to the next.

    This value is always equal to leading()+height().

    \sa height(), leading()
*/
int QFontMetrics::lineSpacing() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return (QMAX(engine->leading(), latin_engine->leading()) +
	    QMAX(engine->ascent(), latin_engine->ascent()) +
	    QMAX(engine->descent(), latin_engine->descent()) + 1);
}

/*!
    Returns the minimum left bearing of the font.

    This is the smallest leftBearing(char) of all characters in the
    font.

    Note that this function can be very slow if the font is large.

    \sa minRightBearing(), leftBearing()
*/
int QFontMetrics::minLeftBearing() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return QMIN(engine->minLeftBearing(), latin_engine->minLeftBearing());
}

/*!
    Returns the minimum right bearing of the font.

    This is the smallest rightBearing(char) of all characters in the
    font.

    Note that this function can be very slow if the font is large.

    \sa minLeftBearing(), rightBearing()
*/
int QFontMetrics::minRightBearing() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *latin_engine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( latin_engine != 0 );
#endif // QT_CHECK_STATE

    return QMIN(engine->minRightBearing(), latin_engine->minRightBearing());
}

/*!
    Returns the width of the widest character in the font.
*/
int QFontMetrics::maxWidth() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
    QFontEngine *lengine = d->engineForScript( QFont::Latin );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
    Q_ASSERT( lengine != 0 );
#endif // QT_CHECK_STATE

    return QMAX(engine->maxCharWidth(), lengine->maxCharWidth());
}

/*!
    Returns TRUE if character \a ch is a valid character in the font;
    otherwise returns FALSE.
*/
bool QFontMetrics::inFont(QChar ch) const
{
    QFont::Script script;
    SCRIPT_FOR_CHAR( script, ch );

    QFontEngine *engine = d->engineForScript( script );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    if ( engine->type() == QFontEngine::Box ) return FALSE;
    return engine->canRender( &ch, 1 );
}

/*! \fn int QFontMetrics::leftBearing( QChar ch ) const
    Returns the left bearing of character \a ch in the font.

    The left bearing is the right-ward distance of the left-most pixel
    of the character from the logical origin of the character. This
    value is negative if the pixels of the character extend to the
    left of the logical origin.

    See width(QChar) for a graphical description of this metric.

    \sa rightBearing(), minLeftBearing(), width()
*/
#if !defined(Q_WS_WIN) && !defined(Q_WS_QWS)
int QFontMetrics::leftBearing(QChar ch) const
{
    QFont::Script script;
    SCRIPT_FOR_CHAR( script, ch );

    QFontEngine *engine = d->engineForScript( script );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    if ( engine->type() == QFontEngine::Box ) return 0;

    glyph_t glyphs[10];
    int nglyphs = 9;
    engine->stringToCMap( &ch, 1, glyphs, 0, &nglyphs, FALSE );
    // ### can nglyphs != 1 happen at all? Not currently I think
    glyph_metrics_t gi = engine->boundingBox( glyphs[0] );
    return gi.x;
}
#endif // !Q_WS_WIN

/*! \fn int QFontMetrics::rightBearing(QChar ch) const
    Returns the right bearing of character \a ch in the font.

    The right bearing is the left-ward distance of the right-most
    pixel of the character from the logical origin of a subsequent
    character. This value is negative if the pixels of the character
    extend to the right of the width() of the character.

    See width() for a graphical description of this metric.

    \sa leftBearing(), minRightBearing(), width()
*/
#if !defined(Q_WS_WIN) && !defined(Q_WS_QWS)
int QFontMetrics::rightBearing(QChar ch) const
{
    QFont::Script script;
    SCRIPT_FOR_CHAR( script, ch );

    QFontEngine *engine = d->engineForScript( script );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    if ( engine->type() == QFontEngine::Box ) return 0;

    glyph_t glyphs[10];
    int nglyphs = 9;
    engine->stringToCMap( &ch, 1, glyphs, 0, &nglyphs, FALSE );
    // ### can nglyphs != 1 happen at all? Not currently I think
    glyph_metrics_t gi = engine->boundingBox( glyphs[0] );
    return gi.xoff - gi.x - gi.width;
}
#endif // !Q_WS_WIN


#ifndef Q_WS_QWS
/*!
    Returns the width in pixels of the first \a len characters of \a
    str. If \a len is negative (the default), the entire string is
    used.

    Note that this value is \e not equal to boundingRect().width();
    boundingRect() returns a rectangle describing the pixels this
    string will cover whereas width() returns the distance to where
    the next string should be drawn.

    \sa boundingRect()
*/
int QFontMetrics::width( const QString &str, int len ) const
{
    if (len < 0)
	len = str.length();
    if (len == 0)
	return 0;

    int pos = 0;
    int width = 0;
#ifndef Q_WS_MAC
    const QChar *ch = str.unicode();

    while (pos < len) {
	unsigned short uc = ch->unicode();
	if (uc < QFontEngineData::widthCacheSize && d->engineData && d->engineData->widthCache[uc])
	    width += d->engineData->widthCache[uc];
	else {
	    QFont::Script script;
	    SCRIPT_FOR_CHAR( script, *ch );

	    if (script >= QFont::Arabic && script <= QFont::Khmer)
		break;
            if ( ::category( *ch ) != QChar::Mark_NonSpacing && !qIsZeroWidthChar(ch->unicode())) {
                QFontEngine *engine = d->engineForScript( script );
#ifdef QT_CHECK_STATE
                Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

                glyph_t glyphs[8];
                advance_t advances[8];
                int nglyphs = 7;
                engine->stringToCMap( ch, 1, glyphs, advances, &nglyphs, FALSE );

                // ### can nglyphs != 1 happen at all? Not currently I think
                if ( uc < QFontEngineData::widthCacheSize && advances[0] > 0 && advances[0] < 0x100 )
                    d->engineData->widthCache[ uc ] = advances[0];
                width += advances[0];
            }
	}
	++pos;
	++ch;
    }
    if ( pos < len ) {
#endif
	QTextEngine layout( str, d );
	layout.itemize( QTextEngine::WidthOnly );
	width += layout.width( pos, len-pos );
#ifndef Q_WS_MAC
    }
#endif
    return width;
}
#endif

/*! \fn int QFontMetrics::width( QChar ch ) const

    <img src="bearings.png" align=right>

    Returns the logical width of character \a ch in pixels. This is a
    distance appropriate for drawing a subsequent character after \a
    ch.

    Some of the metrics are described in the image to the right. The
    central dark rectangles cover the logical width() of each
    character. The outer pale rectangles cover the leftBearing() and
    rightBearing() of each character. Notice that the bearings of "f"
    in this particular font are both negative, while the bearings of
    "o" are both positive.

    \warning This function will produce incorrect results for Arabic
    characters or non spacing marks in the middle of a string, as the
    glyph shaping and positioning of marks that happens when
    processing strings cannot be taken into account. Use charWidth()
    instead if you aren't looking for the width of isolated
    characters.

    \sa boundingRect(), charWidth()
*/

/*! \fn int QFontMetrics::width( char c ) const

  \overload
  \obsolete

  Provided to aid porting from Qt 1.x.
*/

/*! \fn int QFontMetrics::charWidth( const QString &str, int pos ) const
    Returns the width of the character at position \a pos in the
    string \a str.

    The whole string is needed, as the glyph drawn may change
    depending on the context (the letter before and after the current
    one) for some languages (e.g. Arabic).

    This function also takes non spacing marks and ligatures into
    account.
*/

#ifndef Q_WS_QWS
/*!
    Returns the bounding rectangle of the first \a len characters of
    \a str, which is the set of pixels the text would cover if drawn
    at (0, 0).

    If \a len is negative (the default), the entire string is used.

    Note that the bounding rectangle may extend to the left of (0, 0),
    e.g. for italicized fonts, and that the text output may cover \e
    all pixels in the bounding rectangle.

    Newline characters are processed as normal characters, \e not as
    linebreaks.

    Due to the different actual character heights, the height of the
    bounding rectangle of e.g. "Yes" and "yes" may be different.

    \sa width(), QPainter::boundingRect()
*/
QRect QFontMetrics::boundingRect( const QString &str, int len ) const
{
    if (len < 0)
	len = str.length();
    if (len == 0)
	return QRect();

    QTextEngine layout( str, d );
    layout.itemize( QTextEngine::NoBidi|QTextEngine::SingleLine );
    glyph_metrics_t gm = layout.boundingBox( 0, len );
    return QRect( gm.x, gm.y, gm.width, gm.height );
}
#endif

/*!
    Returns the rectangle that is covered by ink if the character
    specified by \a ch were to be drawn at the origin of the coordinate
    system.

    Note that the bounding rectangle may extend to the left of (0, 0),
    e.g. for italicized fonts, and that the text output may cover \e
    all pixels in the bounding rectangle. For a space character the rectangle
    will usually be empty.

    Note that the rectangle usually extends both above and below the
    base line.
    
    \warning The width of the returned rectangle is not the advance width
    of the character. Use boundingRect(const QString &) or width() instead.
    
    \sa width() 
*/
QRect QFontMetrics::boundingRect( QChar ch ) const
{
    QFont::Script script;
    SCRIPT_FOR_CHAR( script, ch );

    QFontEngine *engine = d->engineForScript( script );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    glyph_t glyphs[10];
    int nglyphs = 9;
    engine->stringToCMap( &ch, 1, glyphs, 0, &nglyphs, FALSE );
    glyph_metrics_t gi = engine->boundingBox( glyphs[0] );
    return QRect( gi.x, gi.y, gi.width, gi.height );
}

/*!
    \overload

    Returns the bounding rectangle of the first \a len characters of
    \a str, which is the set of pixels the text would cover if drawn
    at (0, 0). The drawing, and hence the bounding rectangle, is
    constrained to the rectangle (\a x, \a y, \a w, \a h).

    If \a len is negative (which is the default), the entire string is
    used.

    The \a flgs argument is the bitwise OR of the following flags:
    \list
    \i \c AlignAuto aligns to the left border for all languages except
	  Arabic and Hebrew where it aligns to the right.
    \i \c AlignLeft aligns to the left border.
    \i \c AlignRight aligns to the right border.
    \i \c AlignJustify produces justified text.
    \i \c AlignHCenter aligns horizontally centered.
    \i \c AlignTop aligns to the top border.
    \i \c AlignBottom aligns to the bottom border.
    \i \c AlignVCenter aligns vertically centered
    \i \c AlignCenter (== \c{AlignHCenter | AlignVCenter})
    \i \c SingleLine ignores newline characters in the text.
    \i \c ExpandTabs expands tabs (see below)
    \i \c ShowPrefix interprets "&amp;x" as "<u>x</u>", i.e. underlined.
    \i \c WordBreak breaks the text to fit the rectangle.
    \endlist

    Horizontal alignment defaults to \c AlignAuto and vertical
    alignment defaults to \c AlignTop.

    If several of the horizontal or several of the vertical alignment
    flags are set, the resulting alignment is undefined.

    These flags are defined in \c qnamespace.h.

    If \c ExpandTabs is set in \a flgs, then: if \a tabarray is
    non-null, it specifies a 0-terminated sequence of pixel-positions
    for tabs; otherwise if \a tabstops is non-zero, it is used as the
    tab spacing (in pixels).

    Note that the bounding rectangle may extend to the left of (0, 0),
    e.g. for italicized fonts, and that the text output may cover \e
    all pixels in the bounding rectangle.

    Newline characters are processed as linebreaks.

    Despite the different actual character heights, the heights of the
    bounding rectangles of "Yes" and "yes" are the same.

    The bounding rectangle given by this function is somewhat larger
    than that calculated by the simpler boundingRect() function. This
    function uses the \link minLeftBearing() maximum left \endlink and
    \link minRightBearing() right \endlink font bearings as is
    necessary for multi-line text to align correctly. Also,
    fontHeight() and lineSpacing() are used to calculate the height,
    rather than individual character heights.

    The \a intern argument should not be used.

    \sa width(), QPainter::boundingRect(), Qt::AlignmentFlags
*/
QRect QFontMetrics::boundingRect( int x, int y, int w, int h, int flgs,
				  const QString& str, int len, int tabstops,
				  int *tabarray, QTextParag **intern ) const
{
    if ( len < 0 )
	len = str.length();

    int tabarraylen=0;
    if (tabarray)
	while (tabarray[tabarraylen])
	    tabarraylen++;

    QRect rb;
    QRect r(x, y, w, h);
    qt_format_text( QFont( d, d->paintdevice ), r, flgs|Qt::DontPrint, str, len, &rb,
		    tabstops, tabarray, tabarraylen, intern, 0 );

    return rb;
}

/*!
    Returns the size in pixels of the first \a len characters of \a
    str.

    If \a len is negative (the default), the entire string is used.

    The \a flgs argument is the bitwise OR of the following flags:
    \list
    \i \c SingleLine ignores newline characters.
    \i \c ExpandTabs expands tabs (see below)
    \i \c ShowPrefix interprets "&amp;x" as "<u>x</u>", i.e. underlined.
    \i \c WordBreak breaks the text to fit the rectangle.
    \endlist

    These flags are defined in \c qnamespace.h.

    If \c ExpandTabs is set in \a flgs, then: if \a tabarray is
    non-null, it specifies a 0-terminated sequence of pixel-positions
    for tabs; otherwise if \a tabstops is non-zero, it is used as the
    tab spacing (in pixels).

    Newline characters are processed as linebreaks.

    Despite the different actual character heights, the heights of the
    bounding rectangles of "Yes" and "yes" are the same.

    The \a intern argument should not be used.

    \sa boundingRect()
*/
QSize QFontMetrics::size( int flgs, const QString &str, int len, int tabstops,
			  int *tabarray, QTextParag **intern ) const
{
    return boundingRect(0,0,0,0,flgs,str,len,tabstops,tabarray,intern).size();
}

/*!
    Returns the distance from the base line to where an underscore
    should be drawn.

    \sa overlinePos(), strikeOutPos(), lineWidth()
*/
int QFontMetrics::underlinePos() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    return engine->underlinePosition();
}

/*!
    Returns the distance from the base line to where an overline
    should be drawn.

    \sa underlinePos(), strikeOutPos(), lineWidth()
*/
int QFontMetrics::overlinePos() const
{
    int pos = ascent() + 1;
    return pos > 0 ? pos : 1;
}

/*!
    Returns the distance from the base line to where the strikeout
    line should be drawn.

    \sa underlinePos(), overlinePos(), lineWidth()
*/
int QFontMetrics::strikeOutPos() const
{
    int pos = ascent() / 3;
    return pos > 0 ? pos : 1;
}

/*!
    Returns the width of the underline and strikeout lines, adjusted
    for the point size of the font.

    \sa underlinePos(), overlinePos(), strikeOutPos()
*/
int QFontMetrics::lineWidth() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    return engine->lineThickness();
}




/*****************************************************************************
  QFontInfo member functions
 *****************************************************************************/

/*!
    \class QFontInfo qfontinfo.h

    \brief The QFontInfo class provides general information about fonts.

    \ingroup graphics
    \ingroup shared

    The QFontInfo class provides the same access functions as QFont,
    e.g. family(), pointSize(), italic(), weight(), fixedPitch(),
    styleHint() etc. But whilst the QFont access functions return the
    values that were set, a QFontInfo object returns the values that
    apply to the font that will actually be used to draw the text.

    For example, when the program asks for a 25pt Courier font on a
    machine that has a non-scalable 24pt Courier font, QFont will
    (normally) use the 24pt Courier for rendering. In this case,
    QFont::pointSize() returns 25 and QFontInfo::pointSize() returns
    24.

    There are three ways to create a QFontInfo object.
    \list 1
    \i Calling the QFontInfo constructor with a QFont creates a font
    info object for a screen-compatible font, i.e. the font cannot be
    a printer font<sup>*</sup>. If the font is changed later, the font
    info object is \e not updated.

    \i QWidget::fontInfo() returns the font info for a widget's font.
    This is equivalent to calling QFontInfo(widget->font()). If the
    widget's font is changed later, the font info object is \e not
    updated.

    \i QPainter::fontInfo() returns the font info for a painter's
    current font. If the painter's font is changed later, the font
    info object is \e not updated.
    \endlist

    <sup>*</sup> If you use a printer font the values returned may be
    inaccurate. Printer fonts are not always accessible so the nearest
    screen font is used if a printer font is supplied.

    \sa QFont QFontMetrics QFontDatabase
*/

/*!
    Constructs a font info object for \a font.

    The font must be screen-compatible, i.e. a font you use when
    drawing text in \link QWidget widgets\endlink or \link QPixmap
    pixmaps\endlink, not QPicture or QPrinter.

    The font info object holds the information for the font that is
    passed in the constructor at the time it is created, and is not
    updated if the font's attributes are changed later.

    Use QPainter::fontInfo() to get the font info when painting.
    This will give correct results also when painting on paint device
    that is not screen-compatible.
*/
QFontInfo::QFontInfo( const QFont &font )
    : d( font.d ), painter( 0 ), fscript( QFont::NoScript )
{
    d->ref();
}

/*!
    Constructs a font info object for \a font using the specified \a
    script.
*/
QFontInfo::QFontInfo( const QFont &font, QFont::Script script )
    : d( font.d ), painter( 0 ), fscript( script )
{
    d->ref();
}

/*! \internal

  Constructs a font info object from the painter's font \a p.
*/
QFontInfo::QFontInfo( const QPainter *p )
    : painter( 0 ), fscript( QFont::NoScript )
{
    QPainter *painter = (QPainter *) p;

#if defined(CHECK_STATE)
    if ( !painter->isActive() )
	tqWarning( "QFontInfo: Get font info between QPainter::begin() "
		  "and QPainter::end()" );
#endif

    painter->setf( QPainter::FontInf );
    if ( painter->testf(QPainter::DirtyFont) )
	painter->updateFont();
    if ( painter->pfont )
	d = painter->pfont->d;
    else
	d = painter->cfont.d;
    d->ref();
}

/*!
    Constructs a copy of \a fi.
*/
QFontInfo::QFontInfo( const QFontInfo &fi )
    : d(fi.d), painter(0), fscript( fi.fscript )
{
    d->ref();
}

/*!
    Destroys the font info object.
*/
QFontInfo::~QFontInfo()
{
    if ( d->deref() )
	delete d;
}

/*!
    Assigns the font info in \a fi.
*/
QFontInfo &QFontInfo::operator=( const QFontInfo &fi )
{
    if ( d != fi.d ) {
	if ( d->deref() )
	    delete d;
	d = fi.d;
	d->ref();
    }
    painter = 0;
    fscript = fi.fscript;
    return *this;
}

/*!
    Returns the family name of the matched window system font.

    \sa QFont::family()
*/
QString QFontInfo::family() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return engine->fontDef.family;
}

/*!
    Returns the point size of the matched window system font.

    \sa QFont::pointSize()
*/
int QFontInfo::pointSize() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return ( engine->fontDef.pointSize + 5 ) / 10;
}

/*!
    Returns the pixel size of the matched window system font.

    \sa QFont::pointSize()
*/
int QFontInfo::pixelSize() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return engine->fontDef.pixelSize;
}

/*!
    Returns the italic value of the matched window system font.

    \sa QFont::italic()
*/
bool QFontInfo::italic() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return engine->fontDef.italic;
}

/*!
    Returns the weight of the matched window system font.

    \sa QFont::weight(), bold()
*/
int QFontInfo::weight() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return engine->fontDef.weight;

}

/*!
    \fn bool QFontInfo::bold() const

    Returns TRUE if weight() would return a value greater than \c
    QFont::Normal; otherwise returns FALSE.

    \sa weight(), QFont::bold()
*/

/*!
    Returns the underline value of the matched window system font.

  \sa QFont::underline()

  \internal

  Here we read the underline flag directly from the QFont.
  This is OK for X11 and for Windows because we always get what we want.
*/
bool QFontInfo::underline() const
{
    return d->underline;
}

/*!
    Returns the overline value of the matched window system font.

    \sa QFont::overline()

    \internal

    Here we read the overline flag directly from the QFont.
    This is OK for X11 and for Windows because we always get what we want.
*/
bool QFontInfo::overline() const
{
    return d->overline;
}

/*!
    Returns the strikeout value of the matched window system font.

  \sa QFont::strikeOut()

  \internal Here we read the strikeOut flag directly from the QFont.
  This is OK for X11 and for Windows because we always get what we want.
*/
bool QFontInfo::strikeOut() const
{
    return d->strikeOut;
}

/*!
    Returns the fixed pitch value of the matched window system font.

    \sa QFont::fixedPitch()
*/
bool QFontInfo::fixedPitch() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
#ifdef Q_OS_MAC
    if (!engine->fontDef.fixedPitchComputed) {
	QChar ch[2] = { QChar('i'), QChar('m') };
	glyph_t g[2];
	int l = 2;
	advance_t a[2];
	engine->stringToCMap(ch, 2, g, a, &l, FALSE);
	engine->fontDef.fixedPitch = a[0] == a[1];
	engine->fontDef.fixedPitchComputed = TRUE;
    }
#endif
    return engine->fontDef.fixedPitch;
}

/*!
    Returns the style of the matched window system font.

    Currently only returns the style hint set in QFont.

    \sa QFont::styleHint() QFont::StyleHint
*/
QFont::StyleHint QFontInfo::styleHint() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE
    return (QFont::StyleHint) engine->fontDef.styleHint;
}

/*!
    Returns TRUE if the font is a raw mode font; otherwise returns
    FALSE.

    If it is a raw mode font, all other functions in QFontInfo will
    return the same values set in the QFont, regardless of the font
    actually used.

    \sa QFont::rawMode()
*/
bool QFontInfo::rawMode() const
{
    return d->rawMode;
}

/*!
    Returns TRUE if the matched window system font is exactly the same
    as the one specified by the font; otherwise returns FALSE.

    \sa QFont::exactMatch()
*/
bool QFontInfo::exactMatch() const
{
    QFontEngine *engine = d->engineForScript( (QFont::Script) fscript );
#ifdef QT_CHECK_STATE
    Q_ASSERT( engine != 0 );
#endif // QT_CHECK_STATE

    return d->rawMode ? engine->type() != QFontEngine::Box
			     : d->request == engine->fontDef;
}




// **********************************************************************
// QFontCache
// **********************************************************************

#ifdef QFONTCACHE_DEBUG
// fast timeouts for debugging
static const int fast_timeout =   1000;  // 1s
static const int slow_timeout =   5000;  // 5s
#else
static const int fast_timeout =  10000; // 10s
static const int slow_timeout = 300000; //  5m
#endif // QFONTCACHE_DEBUG

QFontCache *QFontCache::instance = 0;
const uint QFontCache::min_cost = 4*1024; // 4mb

static QSingleCleanupHandler<QFontCache> cleanup_fontcache;


QFontCache::QFontCache()
    : QObject( qApp, "global font cache" ), total_cost( 0 ), max_cost( min_cost ),
      current_timestamp( 0 ), fast( FALSE ), timer_id( -1 )
{
    Q_ASSERT( instance == 0 );
    instance = this;
    cleanup_fontcache.set( &instance );
}

QFontCache::~QFontCache()
{
    {
	EngineDataCache::Iterator it = engineDataCache.begin(),
				 end = engineDataCache.end();
	while ( it != end ) {
	    if ( it.data()->count == 0 )
		delete it.data();
	    else
		FC_DEBUG("QFontCache::~QFontCache: engineData %p still has refcount %d",
			 it.data(), it.data()->count);
	    ++it;
	}
    }
    EngineCache::Iterator it = engineCache.begin(),
			 end = engineCache.end();
    while ( it != end ) {
	if ( it.data().data->count == 0 ) {
	    if ( --it.data().data->cache_count == 0 ) {
		FC_DEBUG("QFontCache::~QFontCache: deleting engine %p key=(%d / %d %d %d %d %d)",
			 it.data().data, it.key().script, it.key().def.pointSize,
			 it.key().def.pixelSize, it.key().def.weight, it.key().def.italic,
			 it.key().def.fixedPitch);

		delete it.data().data;
	    }
	} else {
	    FC_DEBUG("QFontCache::~QFontCache: engine = %p still has refcount %d",
		     it.data().data, it.data().data->count);
	}
	++it;
    }
    instance = 0;
}

#ifdef Q_WS_QWS
void QFontCache::clear()
{
    {
	EngineDataCache::Iterator it = engineDataCache.begin(),
				 end = engineDataCache.end();
	while ( it != end ) {
	    QFontEngineData *data = it.data();
	    if ( data->engine )
		data->engine->deref();
	    data->engine = 0;
	    ++it;
	}
    }

    EngineCache::Iterator it = engineCache.begin(),
			 end = engineCache.end();
    while ( it != end ) {
	if ( it.data().data->count == 0 ) {
	    if ( --it.data().data->cache_count == 0 ) {
		FC_DEBUG("QFontCache::~QFontCache: deleting engine %p key=(%d / %d %d %d %d %d)",
			 it.data().data, it.key().script, it.key().def.pointSize,
			 it.key().def.pixelSize, it.key().def.weight, it.key().def.italic,
			 it.key().def.fixedPitch);
		delete it.data().data;
	    }
	} else {
	    FC_DEBUG("QFontCache::~QFontCache: engine = %p still has refcount %d",
		     it.data().data, it.data().data->count);
	}
	++it;
    }
}
#endif

QFontEngineData *QFontCache::findEngineData( const Key &key ) const
{
    EngineDataCache::ConstIterator it = engineDataCache.find( key ),
				  end = engineDataCache.end();
    if ( it == end ) return 0;

    // found
    return it.data();
}

void QFontCache::insertEngineData( const Key &key, QFontEngineData *engineData )
{
    FC_DEBUG( "QFontCache: inserting new engine data %p", engineData );

    engineDataCache.insert( key, engineData );
    increaseCost( sizeof( QFontEngineData ) );
}

QFontEngine *QFontCache::findEngine( const Key &key )
{
    EngineCache::Iterator it = engineCache.find( key ),
			 end = engineCache.end();
    if ( it == end ) return 0;

    // found... update the hitcount and timestamp
    it.data().hits++;
    it.data().timestamp = ++current_timestamp;

    FC_DEBUG( "QFontCache: found font engine\n"
	    "  %p: timestamp %4u hits %3u ref %2d/%2d, type '%s'",
	    it.data().data, it.data().timestamp, it.data().hits,
	    it.data().data->count, it.data().data->cache_count,
	    it.data().data->name() );

    return it.data().data;
}

void QFontCache::insertEngine( const Key &key, QFontEngine *engine )
{
    FC_DEBUG( "QFontCache: inserting new engine %p", engine );

    Engine data( engine );
    data.timestamp = ++current_timestamp;

    engineCache.insert( key, data );

    // only increase the cost if this is the first time we insert the engine
    if ( engine->cache_count == 0 )
	increaseCost( engine->cache_cost );

    ++engine->cache_count;
}

void QFontCache::increaseCost( uint cost )
{
    cost = ( cost + 512 ) / 1024; // store cost in kb
    cost = cost > 0 ? cost : 1;
    total_cost += cost;

    FC_DEBUG( "  COST: increased %u kb, total_cost %u kb, max_cost %u kb",
	    cost, total_cost, max_cost );

    if ( total_cost > max_cost) {
	max_cost = total_cost;

	if ( timer_id == -1 || ! fast ) {
	    FC_DEBUG( "  TIMER: starting fast timer (%d ms)", fast_timeout );

	    if (timer_id != -1) killTimer( timer_id );
	    timer_id = startTimer( fast_timeout );
	    fast = TRUE;
	}
    }
}

void QFontCache::decreaseCost( uint cost )
{
    cost = ( cost + 512 ) / 1024; // cost is stored in kb
    cost = cost > 0 ? cost : 1;
    Q_ASSERT( cost <= total_cost );
    total_cost -= cost;

    FC_DEBUG( "  COST: decreased %u kb, total_cost %u kb, max_cost %u kb",
	    cost, total_cost, max_cost );
}

#if defined(Q_WS_WIN ) || defined (Q_WS_QWS)
void QFontCache::cleanupPrinterFonts()
{
    FC_DEBUG( "QFontCache::cleanupPrinterFonts" );

    {
	FC_DEBUG( "  CLEAN engine data:" );

	// clean out all unused engine datas
	EngineDataCache::Iterator it = engineDataCache.begin(),
				 end = engineDataCache.end();
	while ( it != end ) {
	    if ( it.key().screen == 0 ) {
		++it;
		continue;
	    }

	    if( it.data()->count > 0 ) {
#ifdef Q_WS_WIN
		for(int i = 0; i < QFont::LastPrivateScript; ++i) {
		    if( it.data()->engines[i] ) {
			it.data()->engines[i]->deref();
			it.data()->engines[i] = 0;
		    }
		}
#else
		if ( it.data()->engine ) {
		    it.data()->engine->deref();
		    it.data()->engine = 0;
		}
#endif
		++it;
	    } else {

		EngineDataCache::Iterator rem = it++;

		decreaseCost( sizeof( QFontEngineData ) );

		FC_DEBUG( "    %p", rem.data() );

		delete rem.data();
		engineDataCache.remove( rem );
	    }
	}
    }

    EngineCache::Iterator it = engineCache.begin(),
			 end = engineCache.end();
    while( it != end ) {
	if ( it.data().data->count > 0 || it.key().screen == 0) {
	    ++it;
	    continue;
	}

	FC_DEBUG( "    %p: timestamp %4u hits %2u ref %2d/%2d, type '%s'",
		  it.data().data, it.data().timestamp, it.data().hits,
		  it.data().data->count, it.data().data->cache_count,
		  it.data().data->name() );

	if ( --it.data().data->cache_count == 0 ) {
	    FC_DEBUG( "    DELETE: last occurence in cache" );

	    decreaseCost( it.data().data->cache_cost );
	    delete it.data().data;
	}

	engineCache.remove( it++ );
    }
}
#endif

void QFontCache::timerEvent( QTimerEvent * )
{
    FC_DEBUG( "QFontCache::timerEvent: performing cache maintenance (timestamp %u)",
	      current_timestamp );

    if ( total_cost <= max_cost && max_cost <= min_cost ) {
	FC_DEBUG( "  cache redused sufficiently, stopping timer" );

	killTimer( timer_id );
	timer_id = -1;
	fast = FALSE;

	return;
    }

    // go through the cache and count up everything in use
    uint in_use_cost = 0;

    {
	FC_DEBUG( "  SWEEP engine data:" );

	// make sure the cost of each engine data is at least 1kb
        const uint engine_data_cost =
	    sizeof( QFontEngineData ) > 1024 ? sizeof( QFontEngineData ) : 1024;

	EngineDataCache::ConstIterator it = engineDataCache.begin(),
	                              end = engineDataCache.end();
	for ( ; it != end; ++it ) {
#ifdef QFONTCACHE_DEBUG
	    FC_DEBUG( "    %p: ref %2d", it.data(), it.data()->count );

#  if defined(Q_WS_X11) || defined(Q_WS_WIN)
	    // print out all engines
	    for ( int i = 0; i < QFont::LastPrivateScript; ++i ) {
		if ( ! it.data()->engines[i] ) continue;
		FC_DEBUG( "      contains %p", it.data()->engines[i] );
	    }
#  endif // Q_WS_X11 || Q_WS_WIN
#endif // QFONTCACHE_DEBUG

	    if ( it.data()->count > 0 )
		in_use_cost += engine_data_cost;
	}
    }

    {
	FC_DEBUG( "  SWEEP engine:" );

	EngineCache::ConstIterator it = engineCache.begin(),
				  end = engineCache.end();
	for ( ; it != end; ++it ) {
	    FC_DEBUG( "    %p: timestamp %4u hits %2u ref %2d/%2d, cost %u bytes",
		      it.data().data, it.data().timestamp, it.data().hits,
		      it.data().data->count, it.data().data->cache_count,
		      it.data().data->cache_cost );

	    if ( it.data().data->count > 0 )
		in_use_cost += it.data().data->cache_cost / it.data().data->cache_count;
	}

	// attempt to make up for rounding errors
	in_use_cost += (uint)engineCache.count();
    }

    in_use_cost = ( in_use_cost + 512 ) / 1024; // cost is stored in kb

    /*
      calculate the new maximum cost for the cache

      NOTE: in_use_cost is *not* correct due to rounding errors in the
      above algorithm.  instead of worrying about getting the
      calculation correct, we are more interested in speed, and use
      in_use_cost as a floor for new_max_cost
    */
    uint new_max_cost = QMAX( QMAX( max_cost / 2, in_use_cost ), min_cost );

    FC_DEBUG( "  after sweep, in use %u kb, total %u kb, max %u kb, new max %u kb",
	      in_use_cost, total_cost, max_cost, new_max_cost );

    if ( new_max_cost == max_cost ) {
	if ( fast ) {
	    FC_DEBUG( "  cannot shrink cache, slowing timer" );

	    killTimer( timer_id );
	    timer_id = startTimer( slow_timeout );
	    fast = FALSE;
	}

	return;
    } else if ( ! fast ) {
	FC_DEBUG( "  dropping into passing gear" );

	killTimer( timer_id );
	timer_id = startTimer( fast_timeout );
	fast = TRUE;
    }

    max_cost = new_max_cost;

    {
	FC_DEBUG( "  CLEAN engine data:" );

	// clean out all unused engine datas
	EngineDataCache::Iterator it = engineDataCache.begin(),
				 end = engineDataCache.end();
	while ( it != end ) {
	    if ( it.data()->count > 0 ) {
		++it;
		continue;
	    }

	    EngineDataCache::Iterator rem = it++;

	    decreaseCost( sizeof( QFontEngineData ) );

	    FC_DEBUG( "    %p", rem.data() );

	    delete rem.data();
	    engineDataCache.remove( rem );
	}
    }

    // clean out the engine cache just enough to get below our new max cost
    uint current_cost;
    do {
	current_cost = total_cost;

	EngineCache::Iterator it = engineCache.begin(),
			     end = engineCache.end();
	// determine the oldest and least popular of the unused engines
	uint oldest = ~0;
	uint least_popular = ~0;

	for ( ; it != end; ++it ) {
	    if ( it.data().data->count > 0 ) continue;

	    if ( it.data().timestamp < oldest &&
		 it.data().hits <= least_popular ) {
		oldest = it.data().timestamp;
		least_popular = it.data().hits;
	    }
	}

	FC_DEBUG( "    oldest %u least popular %u", oldest, least_popular );

	for ( it = engineCache.begin(); it != end; ++it ) {
	    if ( it.data().data->count == 0 &&
		 it.data().timestamp == oldest &&
		 it.data().hits == least_popular)
		break;
	}

	if ( it != end ) {
	    FC_DEBUG( "    %p: timestamp %4u hits %2u ref %2d/%2d, type '%s'",
		      it.data().data, it.data().timestamp, it.data().hits,
		      it.data().data->count, it.data().data->cache_count,
		      it.data().data->name() );

	    if ( --it.data().data->cache_count == 0 ) {
		FC_DEBUG( "    DELETE: last occurence in cache" );

		decreaseCost( it.data().data->cache_cost );
		delete it.data().data;
	    } else {
		/*
		  this particular font engine is in the cache multiple
		  times...  set current_cost to zero, so that we can
		  keep looping to get rid of all occurences
		*/
		current_cost = 0;
	    }

	    engineCache.remove( it );
	}
    } while ( current_cost != total_cost && total_cost > max_cost );
}