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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/


#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <osl/thread.h>

#include "unotools/atom.hxx"

#include "fontcache.hxx"
#include "fontsubset.hxx"
#include "impfont.hxx"
#include "svdata.hxx"
#include "generic/geninst.h"
#include "vcl/fontmanager.hxx"
#include "vcl/strhelper.hxx"
#include "vcl/ppdparser.hxx"

#include "tools/urlobj.hxx"
#include "tools/stream.hxx"
#include "tools/debug.hxx"

#include "osl/file.hxx"
#include "osl/process.h"

#include "rtl/tencinfo.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/strbuf.hxx"

#include <sal/macros.h>

#include "i18npool/mslangid.hxx"


#include "parseAFM.hxx"
#include "sft.hxx"

#if OSL_DEBUG_LEVEL > 1
#include <sys/times.h>
#include <stdio.h>
#endif

#include "sal/alloca.h"

#include <set>
#include <boost/unordered_set.hpp>
#include <algorithm>

#include "adobeenc.tab" // get encoding table for AFM metrics

#ifdef CALLGRIND_COMPILE
#include <valgrind/callgrind.h>
#endif

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include "com/sun/star/beans/XMaterialHolder.hpp"
#include "com/sun/star/beans/NamedValue.hpp"

#define PRINTER_METRICDIR "fontmetric"

namespace {

namespace css = com::sun::star;

}

using namespace vcl;
using namespace utl;
using namespace psp;
using namespace osl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;

using ::comphelper::string::getToken;
using ::rtl::OUString;
using ::rtl::OString;
using ::rtl::OStringHash;
using ::rtl::OStringBuffer;
using ::rtl::OUStringBuffer;
using ::rtl::OUStringHash;
using ::rtl::OStringToOUString;
using ::rtl::OUStringToOString;

/*
 *  static helpers
 */

inline sal_uInt16 getUInt16BE( const sal_uInt8*& pBuffer )
{
    sal_uInt16 nRet = (sal_uInt16)pBuffer[1] |
        (((sal_uInt16)pBuffer[0]) << 8);
    pBuffer+=2;
    return nRet;
}

inline sal_uInt32 getUInt32BE( const sal_uInt8*& pBuffer )
{
    sal_uInt32 nRet = (((sal_uInt32)pBuffer[0]) << 24) |
                      (((sal_uInt32)pBuffer[1]) << 16) |
                      (((sal_uInt32)pBuffer[2]) << 8)  |
                      (((sal_uInt32)pBuffer[3]) );
    pBuffer += 4;
    return nRet;
}

// -------------------------------------------------------------------------

static FontWeight parseWeight( const rtl::OString& rWeight )
{
    FontWeight eWeight = WEIGHT_DONTKNOW;
    if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("bold") ) != -1)
    {
        if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("emi")) != -1) // semi, demi
            eWeight = WEIGHT_SEMIBOLD;
        else if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("ultra")) != -1)
            eWeight = WEIGHT_ULTRABOLD;
        else
            eWeight = WEIGHT_BOLD;
    }
    else if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("heavy")) != -1)
        eWeight = WEIGHT_BOLD;
    else if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("light")) != -1)
    {
        if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("emi")) != -1) // semi, demi
            eWeight = WEIGHT_SEMILIGHT;
        else if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("ultra")) != -1)
            eWeight = WEIGHT_ULTRALIGHT;
        else
            eWeight = WEIGHT_LIGHT;
    }
    else if (rWeight.indexOfL(RTL_CONSTASCII_STRINGPARAM("black")) != -1)
        eWeight = WEIGHT_BLACK;
    else if (rWeight.equalsL(RTL_CONSTASCII_STRINGPARAM("demi")))
        eWeight = WEIGHT_SEMIBOLD;
    else if (rWeight.equalsL(RTL_CONSTASCII_STRINGPARAM("book")) ||
             rWeight.equalsL(RTL_CONSTASCII_STRINGPARAM("semicondensed")))
        eWeight = WEIGHT_LIGHT;
    else if (rWeight.equalsL(RTL_CONSTASCII_STRINGPARAM("medium")) || rWeight.equalsL(RTL_CONSTASCII_STRINGPARAM("roman")))
        eWeight = WEIGHT_MEDIUM;
    else
        eWeight = WEIGHT_NORMAL;
    return eWeight;
}

/*
 *  PrintFont implementations
 */
PrintFontManager::PrintFont::PrintFont( fonttype::type eType ) :
        m_eType( eType ),
        m_nFamilyName( 0 ),
        m_nPSName( 0 ),
        m_eItalic( ITALIC_DONTKNOW ),
        m_eWidth( WIDTH_DONTKNOW ),
        m_eWeight( WEIGHT_DONTKNOW ),
        m_ePitch( PITCH_DONTKNOW ),
        m_aEncoding( RTL_TEXTENCODING_DONTKNOW ),
        m_bFontEncodingOnly( false ),
        m_pMetrics( NULL ),
        m_nAscend( 0 ),
        m_nDescend( 0 ),
        m_nLeading( 0 ),
        m_nXMin( 0 ),
        m_nYMin( 0 ),
        m_nXMax( 0 ),
        m_nYMax( 0 ),
        m_bHaveVerticalSubstitutedGlyphs( false ),
        m_bUserOverride( false )
{
}

// -------------------------------------------------------------------------

PrintFontManager::PrintFont::~PrintFont()
{
    if( m_pMetrics )
        delete m_pMetrics;
}

// -------------------------------------------------------------------------

PrintFontManager::Type1FontFile::~Type1FontFile()
{
}

// -------------------------------------------------------------------------

PrintFontManager::TrueTypeFontFile::TrueTypeFontFile()
:   PrintFont( fonttype::TrueType )
,   m_nDirectory( 0 )
,   m_nCollectionEntry( 0 )
,   m_nTypeFlags( TYPEFLAG_INVALID )
{}

// -------------------------------------------------------------------------

PrintFontManager::TrueTypeFontFile::~TrueTypeFontFile()
{
}

// -------------------------------------------------------------------------

PrintFontManager::BuiltinFont::~BuiltinFont()
{
}

// -------------------------------------------------------------------------

bool PrintFontManager::Type1FontFile::queryMetricPage( int /*nPage*/, MultiAtomProvider* pProvider )
{
    return readAfmMetrics( PrintFontManager::get().getAfmFile( this ), pProvider, false, false );
}

// -------------------------------------------------------------------------

bool PrintFontManager::BuiltinFont::queryMetricPage( int /*nPage*/, MultiAtomProvider* pProvider )
{
    return readAfmMetrics( PrintFontManager::get().getAfmFile( this ), pProvider, false, false );
}

// -------------------------------------------------------------------------

bool PrintFontManager::TrueTypeFontFile::queryMetricPage( int nPage, MultiAtomProvider* pProvider )
{
    bool bSuccess = false;

    rtl::OString aFile( PrintFontManager::get().getFontFile( this ) );

    TrueTypeFont* pTTFont = NULL;

    if( OpenTTFontFile( aFile.getStr(), m_nCollectionEntry, &pTTFont ) == SF_OK )
    {
        if( ! m_pMetrics )
        {
            m_pMetrics = new PrintFontMetrics;
            memset (m_pMetrics->m_aPages, 0, sizeof(m_pMetrics->m_aPages));
        }
        m_pMetrics->m_aPages[ nPage/8 ] |= (1 << ( nPage & 7 ));
        int i;
        sal_uInt16 table[256], table_vert[256];

        for( i = 0; i < 256; i++ )
            table[ i ] = 256*nPage + i;

        int nCharacters = nPage < 255 ? 256 : 254;
        MapString( pTTFont, table, nCharacters, NULL, 0 );
        TTSimpleGlyphMetrics* pMetrics = GetTTSimpleCharMetrics( pTTFont, nPage*256, nCharacters, 0 );
        if( pMetrics )
        {
            for( i = 0; i < nCharacters; i++ )
            {
                if( table[i] )
                {
                    CharacterMetric& rChar = m_pMetrics->m_aMetrics[ nPage*256 + i ];
                    rChar.width = pMetrics[ i ].adv;
                    rChar.height = m_aGlobalMetricX.height;
                }
            }

            free( pMetrics );
        }

        for( i = 0; i < 256; i++ )
            table_vert[ i ] = 256*nPage + i;
        MapString( pTTFont, table_vert, nCharacters, NULL, 1 );
        pMetrics = GetTTSimpleCharMetrics( pTTFont, nPage*256, nCharacters, 1 );
        if( pMetrics )
        {
            for( i = 0; i < nCharacters; i++ )
            {
                if( table_vert[i] )
                {
                    CharacterMetric& rChar = m_pMetrics->m_aMetrics[ nPage*256 + i + ( 1 << 16 ) ];
                    rChar.width = m_aGlobalMetricY.width;
                    rChar.height = pMetrics[ i ].adv;
                    if( table_vert[i] != table[i] )
                        m_pMetrics->m_bVerticalSubstitutions[ nPage*256 + i ] = 1;
                }
            }
            free( pMetrics );
        }

        if( ! m_pMetrics->m_bKernPairsQueried )
        {
            m_pMetrics->m_bKernPairsQueried = true;
            // this is really a hack
            // in future MapString/KernGlyphs should be used
            // but vcl is not in a state where that could be used
            // so currently we get kernpairs by accessing the raw data
            struct _TrueTypeFont* pImplTTFont = (struct _TrueTypeFont*)pTTFont;

            //-----------------------------------------------------------------
            // Kerning:  KT_MICROSOFT
            //-----------------------------------------------------------------
            if( pImplTTFont->nkern && pImplTTFont->kerntype == KT_MICROSOFT )
            {
                // create a glyph -> character mapping
                ::boost::unordered_map< sal_uInt16, sal_Unicode > aGlyphMap;
                ::boost::unordered_map< sal_uInt16, sal_Unicode >::iterator left, right;
                for( i = 21; i < 0xfffd; i++ )
                {
                    sal_uInt16 nGlyph = MapChar( pTTFont, (sal_Unicode)i, 0 ); // kerning for horz only
                    if( nGlyph != 0 )
                        aGlyphMap[ nGlyph ] = (sal_Unicode)i;
                }


                KernPair aPair;
                for( i = 0; i < (int)pImplTTFont->nkern; i++ )
                {
                    const sal_uInt8* pTable = pImplTTFont->kerntables[i];

                    /*sal_uInt16 nVersion     =*/ getUInt16BE( pTable );
                    /*sal_uInt16 nLength      =*/ getUInt16BE( pTable );
                    sal_uInt16 nCoverage    = getUInt16BE( pTable );

                    aPair.kern_x    = 0;
                    aPair.kern_y    = 0;
                    switch( nCoverage >> 8 )
                    {
                        case 0:
                        {
                            sal_uInt16 nPairs = getUInt16BE( pTable );
                            pTable += 6;
                            for( int n = 0; n < nPairs; n++ )
                            {
                                sal_uInt16 nLeftGlyph   = getUInt16BE( pTable );
                                sal_uInt16 nRightGlyph  = getUInt16BE( pTable );
                                sal_Int16 nKern         = (sal_Int16)getUInt16BE( pTable );

                                left = aGlyphMap.find( nLeftGlyph );
                                right = aGlyphMap.find( nRightGlyph );
                                if( left != aGlyphMap.end() && right != aGlyphMap.end() )
                                {
                                    aPair.first     = left->second;
                                    aPair.second    = right->second;
                                    switch( nCoverage & 1 )
                                    {
                                        case 1:
                                            aPair.kern_x = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aXKernPairs.push_back( aPair );
                                            break;
                                        case 0:
                                            aPair.kern_y = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aYKernPairs.push_back( aPair );
                                            break;
                                    }
                                }
                            }
                        }
                        break;

                        case 2:
                        {
                            const sal_uInt8* pSubTable = pTable;
                            /*sal_uInt16 nRowWidth    =*/ getUInt16BE( pTable );
                            sal_uInt16 nOfLeft      = getUInt16BE( pTable );
                            sal_uInt16 nOfRight     = getUInt16BE( pTable );
                            /*sal_uInt16 nOfArray     =*/ getUInt16BE( pTable );
                            const sal_uInt8* pTmp = pSubTable + nOfLeft;
                            sal_uInt16 nFirstLeft   = getUInt16BE( pTmp );
                            sal_uInt16 nLastLeft    = getUInt16BE( pTmp ) + nFirstLeft - 1;
                            pTmp = pSubTable + nOfRight;
                            sal_uInt16 nFirstRight  = getUInt16BE( pTmp );
                            sal_uInt16 nLastRight   = getUInt16BE( pTmp ) + nFirstRight -1;

                            // int nPairs = (int)(nLastLeft-nFirstLeft+1)*(int)(nLastRight-nFirstRight+1);
                            for( aPair.first = nFirstLeft; aPair.first < nLastLeft; aPair.first++ )
                            {
                                for( aPair.second = 0; aPair.second < nLastRight; aPair.second++ )
                                {
                                    sal_Int16 nKern = (sal_Int16)getUInt16BE( pTmp );
                                    switch( nCoverage & 1 )
                                    {
                                        case 1:
                                            aPair.kern_x = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aXKernPairs.push_back( aPair );
                                            break;
                                        case 0:
                                            aPair.kern_y = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aYKernPairs.push_back( aPair );
                                            break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }

            //-----------------------------------------------------------------
            // Kerning:  KT_APPLE_NEW
            //-----------------------------------------------------------------
            if( pImplTTFont->nkern && pImplTTFont->kerntype == KT_APPLE_NEW )
            {
                // create a glyph -> character mapping
                ::boost::unordered_map< sal_uInt16, sal_Unicode > aGlyphMap;
                ::boost::unordered_map< sal_uInt16, sal_Unicode >::iterator left, right;
                for( i = 21; i < 0xfffd; i++ )
                {
                    sal_uInt16 nGlyph = MapChar( pTTFont, (sal_Unicode)i, 0 ); // kerning for horz only
                    if( nGlyph != 0 )
                        aGlyphMap[ nGlyph ] = (sal_Unicode)i;
                }

                // Loop through each of the 'kern' subtables
                KernPair aPair;
                for( i = 0; (unsigned int)i < pImplTTFont->nkern; i++ )
                {
                    const sal_uInt8* pTable = pImplTTFont->kerntables[i];

                    /*sal_uInt32 nLength      =*/ getUInt32BE( pTable );
                    sal_uInt16 nCoverage    = getUInt16BE( pTable );
                    /*sal_uInt16 nTupleIndex  =*/ getUInt16BE( pTable );

                    // Get kerning type
                    // sal_Bool bKernVertical     = nCoverage & 0x8000;
                    // sal_Bool bKernCrossStream  = nCoverage & 0x4000;
                    // sal_Bool bKernVariation    = nCoverage & 0x2000;

                    // Kerning sub-table format, 0 through 3
                    sal_uInt8 nSubTableFormat  = nCoverage & 0x00FF;

                    aPair.kern_x    = 0;
                    aPair.kern_y    = 0;
                    switch( nSubTableFormat )
                    {
                        case 0:
                        {
                            // Grab the # of kern pairs but skip over the:
                            //   searchRange
                            //   entrySelector
                            //   rangeShift
                            sal_uInt16 nPairs = getUInt16BE( pTable );
                            pTable += 6;

                            for( int n = 0; n < nPairs; n++ )
                            {
                                sal_uInt16 nLeftGlyph   = getUInt16BE( pTable );
                                sal_uInt16 nRightGlyph  = getUInt16BE( pTable );
                                sal_Int16  nKern         = (sal_Int16)getUInt16BE( pTable );

                                left = aGlyphMap.find( nLeftGlyph );
                                right = aGlyphMap.find( nRightGlyph );
                                if( left != aGlyphMap.end() && right != aGlyphMap.end() )
                                {
                                    aPair.first     = left->second;
                                    aPair.second    = right->second;

                                    // Only support horizontal kerning for now
                                    aPair.kern_x = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                    aPair.kern_y = 0;
                                    m_pMetrics->m_aXKernPairs.push_back( aPair );

/*                                  switch( nCoverage & 1 )
                                    {
                                        case 1:
                                            aPair.kern_x = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aXKernPairs.push_back( aPair );
                                            break;
                                        case 0:
                                            aPair.kern_y = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aYKernPairs.push_back( aPair );
                                            break;
                                    }
*/
                                }
                            }
                        }
                        break;

                        case 2:
                        {
                            const sal_uInt8* pSubTable = pTable;
                            /*sal_uInt16 nRowWidth    =*/ getUInt16BE( pTable );
                            sal_uInt16 nOfLeft      = getUInt16BE( pTable );
                            sal_uInt16 nOfRight     = getUInt16BE( pTable );
                            /*sal_uInt16 nOfArray     =*/ getUInt16BE( pTable );
                            const sal_uInt8* pTmp = pSubTable + nOfLeft;
                            sal_uInt16 nFirstLeft   = getUInt16BE( pTmp );
                            sal_uInt16 nLastLeft    = getUInt16BE( pTmp ) + nFirstLeft - 1;
                            pTmp = pSubTable + nOfRight;
                            sal_uInt16 nFirstRight  = getUInt16BE( pTmp );
                            sal_uInt16 nLastRight   = getUInt16BE( pTmp ) + nFirstRight -1;

                            for( aPair.first = nFirstLeft; aPair.first < nLastLeft; aPair.first++ )
                            {
                                for( aPair.second = 0; aPair.second < nLastRight; aPair.second++ )
                                {
                                    sal_Int16 nKern = (sal_Int16)getUInt16BE( pTmp );
                                    switch( nCoverage & 1 )
                                    {
                                        case 1:
                                            aPair.kern_x = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aXKernPairs.push_back( aPair );
                                            break;
                                        case 0:
                                            aPair.kern_y = (int)nKern * 1000 / pImplTTFont->unitsPerEm;
                                            m_pMetrics->m_aYKernPairs.push_back( aPair );
                                            break;
                                    }
                                }
                            }
                        }
                        break;

                        default:
                            fprintf( stderr, "Found unsupported Apple-style kern subtable type %d.\n", nSubTableFormat );
                            break;
                    }
                }
            }

#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "found %" SAL_PRI_SIZET "u/%" SAL_PRI_SIZET "u kern pairs for %s\n",
                     m_pMetrics->m_aXKernPairs.size(),
                     m_pMetrics->m_aYKernPairs.size(),
                     OUStringToOString( pProvider->getString( ATOM_FAMILYNAME, m_nFamilyName ), RTL_TEXTENCODING_MS_1252 ).getStr() );
#else
            (void) pProvider; /* avoid warnings */
#endif
        }

        CloseTTFont( pTTFont );
        bSuccess = true;
    }
    return bSuccess;
}

// -------------------------------------------------------------------------

/* #i73387# There seem to be fonts with a rather unwell chosen family name
*  consider e.g. "Helvetica Narrow" which defines its family as "Helvetica"
*  It can really only be distinguished by its PSName and FullName. Both of
*  which are not user presentable in OOo. So replace it by something sensible.
*
*  If other fonts feature this behaviour, insert them to the map.
*/
static bool familyNameOverride( const OUString& i_rPSname, OUString& o_rFamilyName )
{
    static boost::unordered_map< OUString, OUString, OUStringHash > aPSNameToFamily( 16 );
    if( aPSNameToFamily.empty() ) // initialization
    {
        aPSNameToFamily[ OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica-Narrow" ) ) ] =
                         OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica Narrow" ) );
        aPSNameToFamily[ OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica-Narrow-Bold" ) ) ] =
                         OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica Narrow" ) );
        aPSNameToFamily[ OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica-Narrow-BoldOblique" ) ) ] =
                         OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica Narrow" ) );
        aPSNameToFamily[ OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica-Narrow-Oblique" ) ) ] =
                         OUString( RTL_CONSTASCII_USTRINGPARAM( "Helvetica Narrow" ) );
    }
    boost::unordered_map<OUString,OUString,OUStringHash>::const_iterator it =
       aPSNameToFamily.find( i_rPSname );
    bool bReplaced = (it != aPSNameToFamily.end() );
    if( bReplaced )
        o_rFamilyName = it->second;
    return bReplaced;
};

bool PrintFontManager::PrintFont::readAfmMetrics( const OString& rFileName, MultiAtomProvider* pProvider, bool bFillEncodingvector, bool bOnlyGlobalAttributes )
{
    PrintFontManager& rManager( PrintFontManager::get() );

    FontInfo* pInfo = NULL;
    parseFile( rFileName.getStr(), &pInfo, P_ALL );
    if( ! pInfo || ! pInfo->numOfChars )
    {
        if( pInfo )
            freeFontInfo( pInfo );
        return false;
    }

    m_aEncodingVector.clear();
    // fill in global info

    // PSName
    OUString aPSName( OStringToOUString( pInfo->gfi->fontName, RTL_TEXTENCODING_ISO_8859_1 ) );
    m_nPSName = pProvider->getAtom( ATOM_PSNAME, aPSName, sal_True );

    // family name (if not already set)
    OUString aFamily;
    if( ! m_nFamilyName )
    {
        aFamily = OStringToOUString( pInfo->gfi->familyName, RTL_TEXTENCODING_ISO_8859_1 );
        if( aFamily.isEmpty() )
        {
            aFamily = OStringToOUString( pInfo->gfi->fontName, RTL_TEXTENCODING_ISO_8859_1 );
            sal_Int32 nIndex  = 0;
            aFamily = aFamily.getToken( 0, '-', nIndex );
        }
        familyNameOverride( aPSName, aFamily );
        m_nFamilyName = pProvider->getAtom( ATOM_FAMILYNAME, aFamily, sal_True );
    }
    else
        aFamily = pProvider->getString( ATOM_FAMILYNAME, m_nFamilyName );

    // style name: if fullname begins with family name
    // interpret the rest of fullname as style
    if( m_aStyleName.isEmpty() && pInfo->gfi->fullName && *pInfo->gfi->fullName )
    {
        OUString aFullName( OStringToOUString( pInfo->gfi->fullName, RTL_TEXTENCODING_ISO_8859_1 ) );
        if( aFullName.indexOf( aFamily ) == 0 )
            m_aStyleName = WhitespaceToSpace( aFullName.copy( aFamily.getLength() ) );
    }

    // italic
    if( pInfo->gfi->italicAngle > 0 )
        m_eItalic = ITALIC_OBLIQUE;
    else if( pInfo->gfi->italicAngle < 0 )
        m_eItalic = ITALIC_NORMAL;
    else
        m_eItalic = ITALIC_NONE;

    // weight
    rtl::OString aWeight( pInfo->gfi->weight );
    m_eWeight = parseWeight( aWeight.toAsciiLowerCase() );

    // pitch
    m_ePitch = pInfo->gfi->isFixedPitch ? PITCH_FIXED : PITCH_VARIABLE;

    // encoding - only set if unknown
    int nAdobeEncoding = 0;
    if( pInfo->gfi->encodingScheme )
    {
        if( !strcmp( pInfo->gfi->encodingScheme, "AdobeStandardEncoding" ) )
            nAdobeEncoding = 1;
        else if( !strcmp( pInfo->gfi->encodingScheme, "ISO10646-1" ) )
        {
            nAdobeEncoding = 1;
            m_aEncoding = RTL_TEXTENCODING_UNICODE;
        }
        else if( !strcmp( pInfo->gfi->encodingScheme, "Symbol") )
            nAdobeEncoding = 2;
        else if( !strcmp( pInfo->gfi->encodingScheme, "FontSpecific") )
            nAdobeEncoding = 3;

        if( m_aEncoding == RTL_TEXTENCODING_DONTKNOW )
            m_aEncoding = nAdobeEncoding == 1 ?
                RTL_TEXTENCODING_ADOBE_STANDARD : RTL_TEXTENCODING_SYMBOL;
    }
    else if( m_aEncoding == RTL_TEXTENCODING_DONTKNOW )
        m_aEncoding = RTL_TEXTENCODING_ADOBE_STANDARD;

    // try to parse the font name and decide whether it might be a
    // japanese font. Who invented this PITA ?
    OUString aPSNameLastToken( aPSName.copy( aPSName.lastIndexOf( '-' )+1 ) );
    if( ! aPSNameLastToken.compareToAscii( "H" )    ||
        ! aPSNameLastToken.compareToAscii( "V" )  )
    {
        static const char* pEncs[] =
            {
                "EUC",
                "RKSJ",
                "SJ"
            };
        static const rtl_TextEncoding aEncs[] =
            {
                RTL_TEXTENCODING_EUC_JP,
                RTL_TEXTENCODING_SHIFT_JIS,
                RTL_TEXTENCODING_JIS_X_0208
            };

        for( unsigned int enc = 0; enc < SAL_N_ELEMENTS( aEncs ) && m_aEncoding == RTL_TEXTENCODING_DONTKNOW; enc++ )
        {
            sal_Int32 nIndex = 0, nOffset = 1;
            do
            {
                OUString aToken( aPSName.getToken( nOffset, '-', nIndex ) );
                if( nIndex == -1 )
                    break;
                nOffset = 0;
                if( ! aToken.compareToAscii( pEncs[enc] ) )
                {
                    m_aEncoding = aEncs[ enc ];
                    m_bFontEncodingOnly = true;
                }
            } while( nIndex != -1 );
        }

        // default is jis
        if( m_aEncoding == RTL_TEXTENCODING_DONTKNOW )
            m_aEncoding = RTL_TEXTENCODING_JIS_X_0208;
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "Encoding %d for %s\n", m_aEncoding, pInfo->gfi->fontName );
#endif
    }

    // hack for GB encoded builtin fonts posing as FontSpecific
    if( m_eType == fonttype::Builtin && ( nAdobeEncoding == 3 || nAdobeEncoding == 0 ) )
    {
        int nLen = aFamily.getLength();
        if( nLen > 2 &&
            aFamily.getStr()[ nLen-2 ] == 'G' &&
            aFamily.getStr()[ nLen-1 ] == 'B' &&
            pInfo->numOfChars > 255 )
        {
            m_aEncoding = RTL_TEXTENCODING_GBK;
            m_bFontEncodingOnly = true;
#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "found builtin font %s with GBK encoding\n", pInfo->gfi->fontName );
#endif
        }
    }

    // #i37313# check if Fontspecific is not rather some character encoding
    if( nAdobeEncoding == 3 && m_aEncoding == RTL_TEXTENCODING_SYMBOL )
    {
        bool bYFound = false;
        bool bQFound = false;
        CharMetricInfo* pChar = pInfo->cmi;
        for( int j = 0; j < pInfo->numOfChars && ! (bYFound && bQFound); j++ )
        {
            if( pChar[j].name )
            {
                if( pChar[j].name[0] == 'Y' && pChar[j].name[1] == 0 )
                    bYFound = true;
                else if( pChar[j].name[0] == 'Q' && pChar[j].name[1] == 0 )
                    bQFound = true;
            }
        }
        if( bQFound && bYFound )
        {
            #if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "setting FontSpecific font %s (file %s) to unicode\n",
                     pInfo->gfi->fontName,
                     rFileName.getStr()
                     );
            #endif
            nAdobeEncoding = 4;
            m_aEncoding = RTL_TEXTENCODING_UNICODE;
            bFillEncodingvector = false; // will be filled anyway, don't do the work twice
        }
    }

    // ascend
    m_nAscend = pInfo->gfi->fontBBox.ury;

    // descend
    // descends have opposite sign of our definition
    m_nDescend = -pInfo->gfi->fontBBox.lly;

    // fallback to ascender, descender
    // interesting: the BBox seems to describe Ascender and Descender better
    // as we understand it
    if( m_nAscend == 0 )
        m_nAscend = pInfo->gfi->ascender;
    if( m_nDescend == 0)
        m_nDescend = -pInfo->gfi->descender;

    m_nLeading = m_nAscend + m_nDescend - 1000;

    if( m_pMetrics )
        delete m_pMetrics;
    m_pMetrics = new PrintFontMetrics;
    // mark all pages as queried (or clear if only global font info queiried)
    memset( m_pMetrics->m_aPages, bOnlyGlobalAttributes ? 0 : 0xff, sizeof( m_pMetrics->m_aPages ) );

    m_aGlobalMetricX.width = m_aGlobalMetricY.width =
        pInfo->gfi->charwidth ? pInfo->gfi->charwidth : pInfo->gfi->fontBBox.urx;
    m_aGlobalMetricX.height = m_aGlobalMetricY.height =
        pInfo->gfi->capHeight ? pInfo->gfi->capHeight : pInfo->gfi->fontBBox.ury;

    m_nXMin = pInfo->gfi->fontBBox.llx;
    m_nYMin = pInfo->gfi->fontBBox.lly;
    m_nXMax = pInfo->gfi->fontBBox.urx;
    m_nYMax = pInfo->gfi->fontBBox.ury;

    if( bFillEncodingvector || !bOnlyGlobalAttributes )
    {
        // fill in character metrics

        // first transform the character codes to unicode
        // note: this only works with single byte encodings
        sal_Unicode* pUnicodes = (sal_Unicode*)alloca( pInfo->numOfChars * sizeof(sal_Unicode));
        CharMetricInfo* pChar = pInfo->cmi;
        int i;

        for( i = 0; i < pInfo->numOfChars; i++, pChar++ )
        {
            if( nAdobeEncoding == 4 )
            {
                if( pChar->name )
                {
                    pUnicodes[i] = 0;
                    std::list< sal_Unicode > aCodes = rManager.getUnicodeFromAdobeName( pChar->name );
                    for( std::list< sal_Unicode >::const_iterator it = aCodes.begin(); it != aCodes.end(); ++it )
                    {
                        if( *it != 0 )
                        {
                            m_aEncodingVector[ *it ] = pChar->code;
                            if( pChar->code == -1 )
                                m_aNonEncoded[ *it ] = pChar->name;
                            if( ! pUnicodes[i] ) // map the first
                                pUnicodes[i] = *it;
                        }
                    }
                }
            }
            else if( pChar->code != -1 )
            {
                if( nAdobeEncoding == 3 && m_aEncoding == RTL_TEXTENCODING_SYMBOL )
                {
                    pUnicodes[i] = pChar->code + 0xf000;
                    if( bFillEncodingvector )
                        m_aEncodingVector[ pUnicodes[i] ] = pChar->code;
                    continue;
                }

                if( m_aEncoding == RTL_TEXTENCODING_UNICODE )
                {
                    pUnicodes[i] = (sal_Unicode)pChar->code;
                    continue;
                }

                rtl::OStringBuffer aTranslate;
                if( pChar->code & 0xff000000 )
                    aTranslate.append((char)(pChar->code >> 24));
                if( pChar->code & 0xffff0000 )
                    aTranslate.append((char)((pChar->code & 0x00ff0000) >> 16));
                if( pChar->code & 0xffffff00 )
                    aTranslate.append((char)((pChar->code & 0x0000ff00) >> 8 ));
                aTranslate.append((char)(pChar->code & 0xff));
                rtl::OUString aUni(rtl::OStringToOUString(aTranslate.makeStringAndClear(), m_aEncoding));
                pUnicodes[i] = aUni.toChar();
            }
            else
                pUnicodes[i] = 0;
        }

        // now fill in the character metrics
        // parseAFM.cxx effectively only supports direction 0 (horizontal)
        pChar = pInfo->cmi;
        CharacterMetric aMetric;
        for( i = 0; i < pInfo->numOfChars; i++, pChar++ )
        {
            if( pChar->code == -1 && ! pChar->name )
                continue;

            if( bFillEncodingvector && pChar->name )
            {
                std::list< sal_Unicode > aCodes = rManager.getUnicodeFromAdobeName( pChar->name );
                for( std::list< sal_Unicode >::const_iterator it = aCodes.begin(); it != aCodes.end(); ++it )
                {
                    if( *it != 0 )
                    {
                        m_aEncodingVector[ *it ] = pChar->code;
                        if( pChar->code == -1 )
                            m_aNonEncoded[ *it ] = pChar->name;
                    }
                }
            }

            aMetric.width   = pChar->wx ? pChar->wx : pChar->charBBox.urx;
            aMetric.height  = pChar->wy ? pChar->wy : pChar->charBBox.ury - pChar->charBBox.lly;
            if( aMetric.width == 0 && aMetric.height == 0 )
                // guess something for e.g. space
                aMetric.width = m_aGlobalMetricX.width/4;

            if( ( nAdobeEncoding == 0 ) ||
                ( ( nAdobeEncoding == 3 ) && ( m_aEncoding != RTL_TEXTENCODING_SYMBOL ) ) )
            {
                if( pChar->code != -1 )
                {
                    m_pMetrics->m_aMetrics[ pUnicodes[i] ] = aMetric;
                    if( bFillEncodingvector )
                        m_aEncodingVector[ pUnicodes[i] ] = pChar->code;
                }
                else if( pChar->name )
                {
                    std::list< sal_Unicode > aCodes = rManager.getUnicodeFromAdobeName( pChar->name );
                    for( std::list< sal_Unicode >::const_iterator it = aCodes.begin(); it != aCodes.end(); ++it )
                    {
                        if( *it != 0 )
                            m_pMetrics->m_aMetrics[ *it ] = aMetric;
                    }
                }
            }
            else if( nAdobeEncoding == 1 || nAdobeEncoding == 2 || nAdobeEncoding == 4)
            {
                if( pChar->name )
                {
                    std::list< sal_Unicode > aCodes = rManager.getUnicodeFromAdobeName( pChar->name );
                    for( std::list< sal_Unicode >::const_iterator it = aCodes.begin(); it != aCodes.end(); ++it )
                    {
                        if( *it != 0 )
                            m_pMetrics->m_aMetrics[ *it ] = aMetric;
                    }
                }
                else if( pChar->code != -1 )
                {
                    ::std::pair< ::boost::unordered_multimap< sal_uInt8, sal_Unicode >::const_iterator,
                          ::boost::unordered_multimap< sal_uInt8, sal_Unicode >::const_iterator >
                          aCodes = rManager.getUnicodeFromAdobeCode( pChar->code );
                    while( aCodes.first != aCodes.second )
                    {
                        if( (*aCodes.first).second != 0 )
                        {
                            m_pMetrics->m_aMetrics[ (*aCodes.first).second ] = aMetric;
                            if( bFillEncodingvector )
                                m_aEncodingVector[ (*aCodes.first).second ] = pChar->code;
                        }
                        ++aCodes.first;
                    }
                }
            }
            else if( nAdobeEncoding == 3 )
            {
                if( pChar->code != -1 )
                {
                    sal_Unicode code = 0xf000 + pChar->code;
                    m_pMetrics->m_aMetrics[ code ] = aMetric;
                    // maybe should try to find the name in the convtabs ?
                    if( bFillEncodingvector )
                        m_aEncodingVector[ code ] = pChar->code;
                }
            }
        }

        m_pMetrics->m_aXKernPairs.clear();
        m_pMetrics->m_aYKernPairs.clear();

        // now fill in the kern pairs
        // parseAFM.cxx effectively only supports direction 0 (horizontal)
        PairKernData* pKern = pInfo->pkd;
        KernPair aPair;
        for( i = 0; i < pInfo->numOfPairs; i++, pKern++ )
        {
            // #i37703# broken kern table
            if( ! pKern->name1 || ! pKern->name2 )
                continue;

            aPair.first = 0;
            aPair.second = 0;
            // currently we have to find the adobe character names
            // in the already parsed character metrics to find
            // the corresponding UCS2 code which is a bit dangerous
            // since the character names are not required
            // in the metric descriptions
            pChar = pInfo->cmi;
            for( int j = 0;
                 j < pInfo->numOfChars && ( aPair.first == 0 || aPair.second == 0 );
                 j++, pChar++ )
            {
                if( pChar->code != -1 )
                {
                    if( ! strcmp( pKern->name1, pChar->name ? pChar->name : "" ) )
                        aPair.first = pUnicodes[ j ];
                    if( ! strcmp( pKern->name2, pChar->name ? pChar->name : "" ) )
                        aPair.second = pUnicodes[ j ];
                }
            }
            if( aPair.first && aPair.second )
            {
                aPair.kern_x = pKern->xamt;
                aPair.kern_y = pKern->yamt;
                m_pMetrics->m_aXKernPairs.push_back( aPair );
            }
        }
        m_pMetrics->m_bKernPairsQueried = true;
    }

    freeFontInfo( pInfo );
    return true;
}

/*
 *  one instance only
 */
PrintFontManager& PrintFontManager::get()
{
    static PrintFontManager* pManager = NULL;
    if( ! pManager )
    {
        static PrintFontManager theManager;
        pManager = &theManager;
        pManager->initialize();
    }
    return *pManager;
}

// -------------------------------------------------------------------------

/*
 *  the PrintFontManager
 */

PrintFontManager::PrintFontManager()
    : m_nNextFontID( 1 )
    , m_pAtoms( new MultiAtomProvider() )
    , m_nNextDirAtom( 1 )
    , m_pFontCache( NULL )
{
    for( unsigned int i = 0; i < SAL_N_ELEMENTS( aAdobeCodes ); i++ )
    {
        m_aUnicodeToAdobename.insert( ::boost::unordered_multimap< sal_Unicode, ::rtl::OString >::value_type( aAdobeCodes[i].aUnicode, aAdobeCodes[i].pAdobename ) );
        m_aAdobenameToUnicode.insert( ::boost::unordered_multimap< ::rtl::OString, sal_Unicode, ::rtl::OStringHash >::value_type( aAdobeCodes[i].pAdobename, aAdobeCodes[i].aUnicode ) );
        if( aAdobeCodes[i].aAdobeStandardCode )
        {
            m_aUnicodeToAdobecode.insert( ::boost::unordered_multimap< sal_Unicode, sal_uInt8 >::value_type( aAdobeCodes[i].aUnicode, aAdobeCodes[i].aAdobeStandardCode ) );
            m_aAdobecodeToUnicode.insert( ::boost::unordered_multimap< sal_uInt8, sal_Unicode >::value_type( aAdobeCodes[i].aAdobeStandardCode, aAdobeCodes[i].aUnicode ) );
        }
    }
}

// -------------------------------------------------------------------------

PrintFontManager::~PrintFontManager()
{
    deinitFontconfig();
    for( ::boost::unordered_map< fontID, PrintFont* >::const_iterator it = m_aFonts.begin(); it != m_aFonts.end(); ++it )
        delete (*it).second;
    delete m_pAtoms;
    if( m_pFontCache )
        delete m_pFontCache;
}

// -------------------------------------------------------------------------

OString PrintFontManager::getDirectory( int nAtom ) const
{
    ::boost::unordered_map< int, OString >::const_iterator it( m_aAtomToDir.find( nAtom ) );
    return it != m_aAtomToDir.end() ? it->second : OString();
}

// -------------------------------------------------------------------------

int PrintFontManager::getDirectoryAtom( const OString& rDirectory, bool bCreate )
{
    int nAtom = 0;
    ::boost::unordered_map< OString, int, OStringHash >::const_iterator it
          ( m_aDirToAtom.find( rDirectory ) );
    if( it != m_aDirToAtom.end() )
        nAtom = it->second;
    else if( bCreate )
    {
        nAtom = m_nNextDirAtom++;
        m_aDirToAtom[ rDirectory ] = nAtom;
        m_aAtomToDir[ nAtom ] = rDirectory;
    }
    return nAtom;
}

// -------------------------------------------------------------------------

std::vector<fontID> PrintFontManager::addFontFile( const ::rtl::OString& rFileName )
{
    rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
    INetURLObject aPath( OStringToOUString( rFileName, aEncoding ), INET_PROT_FILE, INetURLObject::ENCODE_ALL );
    OString aName( OUStringToOString( aPath.GetName(), aEncoding ) );
    OString aDir( OUStringToOString( aPath.GetPath(), aEncoding ) );

    int nDirID = getDirectoryAtom( aDir, true );
    std::vector<fontID> aFontIds = findFontFileIDs( nDirID, aName );
    if( aFontIds.empty() )
    {
        ::std::list< PrintFont* > aNewFonts;
        if( analyzeFontFile( nDirID, aName, aNewFonts ) )
        {
            for( ::std::list< PrintFont* >::iterator it = aNewFonts.begin();
                 it != aNewFonts.end(); ++it )
            {
                fontID nFontId = m_nNextFontID++;
                m_aFonts[nFontId] = *it;
                m_aFontFileToFontID[ aName ].insert( nFontId );
                m_pFontCache->updateFontCacheEntry( *it, true );
                aFontIds.push_back(nFontId);
            }
        }
    }
    return aFontIds;
}

enum fontFormat
{
    UNKNOWN, TRUETYPE, CFF, TYPE1, AFM
};

bool PrintFontManager::analyzeFontFile( int nDirID, const OString& rFontFile, ::std::list< PrintFontManager::PrintFont* >& rNewFonts, const char *pFormat ) const
{
    rNewFonts.clear();

    OString aDir( getDirectory( nDirID ) );

    OString aFullPath( aDir );
    aFullPath += "/";
    aFullPath += rFontFile;

    // #i1872# reject unreadable files
    if( access( aFullPath.getStr(), R_OK ) )
        return false;

    fontFormat eFormat = UNKNOWN;
    if (pFormat)
    {
        if (!strcmp(pFormat, "TrueType"))
            eFormat = TRUETYPE;
        else if (!strcmp(pFormat, "CFF"))
            eFormat = CFF;
        else if (!strcmp(pFormat, "Type 1"))
            eFormat = TYPE1;
    }
    if (eFormat == UNKNOWN)
    {
        rtl::OString aExt( rFontFile.copy( rFontFile.lastIndexOf( '.' )+1 ) );
        if( aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("pfb")) || aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("pfa")) )
            eFormat = TYPE1;
        else if( aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("afm")))
            eFormat = AFM;
        else if( aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("ttf"))
             ||  aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("ttc"))
             ||  aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("tte")) ) // #i33947# for Gaiji support
            eFormat = TRUETYPE;
        else if( aExt.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("otf")) ) // check for TTF- and PS-OpenType too
            eFormat = CFF;
    }

    if (eFormat == TYPE1)
    {
        // check for corresponding afm metric
        // first look for an adjacent file
        static const char* pSuffix[] = { ".afm", ".AFM" };

        for( unsigned int i = 0; i < SAL_N_ELEMENTS(pSuffix); i++ )
        {
            rtl::OString aName = rtl::OStringBuffer(
                rFontFile.copy(0, rFontFile.getLength() - 4)).
                append(pSuffix[i]).makeStringAndClear();

            rtl::OStringBuffer aFilePath(aDir);
            aFilePath.append('/').append(aName);

            rtl::OString aAfmFile;
            if( access( aFilePath.makeStringAndClear().getStr(), R_OK ) )
            {
                // try in subdirectory afm instead
                aFilePath.append(aDir).append(RTL_CONSTASCII_STRINGPARAM("/afm/")).append(aName);

                if (!access(aFilePath.getStr(), R_OK))
                    aAfmFile = rtl::OString(RTL_CONSTASCII_STRINGPARAM("afm/")) + aName;
            }
            else
                aAfmFile = aName;

            if( !aAfmFile.isEmpty() )
            {
                Type1FontFile* pFont = new Type1FontFile();
                pFont->m_nDirectory     = nDirID;

                pFont->m_aFontFile      = rFontFile;
                pFont->m_aMetricFile    = aAfmFile;

                if( ! pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, true ) )
                {
                    delete pFont;
                    pFont = NULL;
                }
                if( pFont )
                    rNewFonts.push_back( pFont );
                break;
            }
        }
    }
    else if (eFormat == AFM)
    {
        rtl::OStringBuffer aFilePath(aDir);
        aFilePath.append('/').append(rFontFile);
        BuiltinFont* pFont = new BuiltinFont();
        pFont->m_nDirectory     = nDirID;
        pFont->m_aMetricFile    = rFontFile;
        if( pFont->readAfmMetrics( aFilePath.makeStringAndClear(), m_pAtoms,
            false, true ) )
        {
            rNewFonts.push_back( pFont );
        }
        else
            delete pFont;
    }
    else if (eFormat == TRUETYPE || eFormat == CFF)
    {
        // get number of ttc entries
        int nLength = CountTTCFonts( aFullPath.getStr() );
        if( nLength )
        {
#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "ttc: %s contains %d fonts\n", aFullPath.getStr(), nLength );
#endif
            for( int i = 0; i < nLength; i++ )
            {
                TrueTypeFontFile* pFont     = new TrueTypeFontFile();
                pFont->m_nDirectory         = nDirID;
                pFont->m_aFontFile          = rFontFile;
                pFont->m_nCollectionEntry   = i;
                if( ! analyzeTrueTypeFile( pFont ) )
                {
                    delete pFont;
                    pFont = NULL;
                }
                else
                    rNewFonts.push_back( pFont );
            }
        }
        else
        {
            TrueTypeFontFile* pFont     = new TrueTypeFontFile();
            pFont->m_nDirectory         = nDirID;
            pFont->m_aFontFile          = rFontFile;
            pFont->m_nCollectionEntry   = 0;

            // need to read the font anyway to get aliases inside the font file
            if( ! analyzeTrueTypeFile( pFont ) )
            {
                delete pFont;
                pFont = NULL;
            }
            else
                rNewFonts.push_back( pFont );
        }
    }
    return ! rNewFonts.empty();
}

// -------------------------------------------------------------------------

fontID PrintFontManager::findFontBuiltinID( int nPSNameAtom ) const
{
    fontID nID = 0;
    ::boost::unordered_map< fontID, PrintFont* >::const_iterator it;
    for( it = m_aFonts.begin(); nID == 0 && it != m_aFonts.end(); ++it )
    {
        if( it->second->m_eType == fonttype::Builtin &&
            it->second->m_nPSName == nPSNameAtom )
            nID = it->first;
    }
    return nID;
}

// -------------------------------------------------------------------------

fontID PrintFontManager::findFontFileID( int nDirID, const OString& rFontFile, int nFaceIndex ) const
{
    fontID nID = 0;

    ::boost::unordered_map< OString, ::std::set< fontID >, OStringHash >::const_iterator set_it = m_aFontFileToFontID.find( rFontFile );
    if( set_it == m_aFontFileToFontID.end() )
        return nID;

    for( ::std::set< fontID >::const_iterator font_it = set_it->second.begin(); font_it != set_it->second.end() && ! nID; ++font_it )
    {
        ::boost::unordered_map< fontID, PrintFont* >::const_iterator it = m_aFonts.find( *font_it );
        if( it == m_aFonts.end() )
            continue;
        switch( it->second->m_eType )
        {
            case fonttype::Type1:
            {
                Type1FontFile* const pFont = static_cast< Type1FontFile* const >((*it).second);
                if( pFont->m_nDirectory == nDirID &&
                    pFont->m_aFontFile == rFontFile )
                    nID = it->first;
            }
            break;
            case fonttype::TrueType:
            {
                TrueTypeFontFile* const pFont = static_cast< TrueTypeFontFile* const >((*it).second);
                if( pFont->m_nDirectory == nDirID &&
                    pFont->m_aFontFile == rFontFile && pFont->m_nCollectionEntry == nFaceIndex )
                        nID = it->first;
            }
            break;
            case fonttype::Builtin:
                if( static_cast<const BuiltinFont*>((*it).second)->m_nDirectory == nDirID &&
                    static_cast<const BuiltinFont*>((*it).second)->m_aMetricFile == rFontFile )
                    nID = it->first;
                break;
            default:
                break;
        }
    }

    return nID;
}

std::vector<fontID> PrintFontManager::findFontFileIDs( int nDirID, const OString& rFontFile ) const
{
    std::vector<fontID> aIds;

    ::boost::unordered_map< OString, ::std::set< fontID >, OStringHash >::const_iterator set_it = m_aFontFileToFontID.find( rFontFile );
    if( set_it == m_aFontFileToFontID.end() )
        return aIds;

    for( ::std::set< fontID >::const_iterator font_it = set_it->second.begin(); font_it != set_it->second.end(); ++font_it )
    {
        ::boost::unordered_map< fontID, PrintFont* >::const_iterator it = m_aFonts.find( *font_it );
        if( it == m_aFonts.end() )
            continue;
        switch( it->second->m_eType )
        {
            case fonttype::Type1:
            {
                Type1FontFile* const pFont = static_cast< Type1FontFile* const >((*it).second);
                if( pFont->m_nDirectory == nDirID &&
                    pFont->m_aFontFile == rFontFile )
                    aIds.push_back(it->first);
            }
            break;
            case fonttype::TrueType:
            {
                TrueTypeFontFile* const pFont = static_cast< TrueTypeFontFile* const >((*it).second);
                if( pFont->m_nDirectory == nDirID &&
                    pFont->m_aFontFile == rFontFile )
                    aIds.push_back(it->first);
            }
            break;
            case fonttype::Builtin:
                if( static_cast<const BuiltinFont*>((*it).second)->m_nDirectory == nDirID &&
                    static_cast<const BuiltinFont*>((*it).second)->m_aMetricFile == rFontFile )
                    aIds.push_back(it->first);
                break;
            default:
                break;
        }
    }

    return aIds;
}

// -------------------------------------------------------------------------

OUString PrintFontManager::convertTrueTypeName( void* pRecord ) const
{
    NameRecord* pNameRecord = (NameRecord*)pRecord;
    OUString aValue;
    if(
       ( pNameRecord->platformID == 3 && ( pNameRecord->encodingID == 0 || pNameRecord->encodingID == 1 ) )  // MS, Unicode
       ||
       ( pNameRecord->platformID == 0 ) // Apple, Unicode
       )
    {
        OUStringBuffer aName( pNameRecord->slen/2 );
        const sal_uInt8* pNameBuffer = pNameRecord->sptr;
        for(int n = 0; n < pNameRecord->slen/2; n++ )
            aName.append( (sal_Unicode)getUInt16BE( pNameBuffer ) );
        aValue = aName.makeStringAndClear();
    }
    else if( pNameRecord->platformID == 3 )
    {
        if( pNameRecord->encodingID >= 2 && pNameRecord->encodingID <= 6 )
        {
            /*
             *  and now for a special kind of madness:
             *  some fonts encode their byte value string as BE uint16
             *  (leading to stray zero bytes in the string)
             *  while others code two bytes as a uint16 and swap to BE
             */
            OStringBuffer aName;
            const sal_uInt8* pNameBuffer = pNameRecord->sptr;
            for(int n = 0; n < pNameRecord->slen/2; n++ )
            {
                sal_Unicode aCode = (sal_Unicode)getUInt16BE( pNameBuffer );
                sal_Char aChar = aCode >> 8;
                if( aChar )
                    aName.append( aChar );
                aChar = aCode & 0x00ff;
                if( aChar )
                    aName.append( aChar );
            }
            switch( pNameRecord->encodingID )
            {
                case 2:
                    aValue = OStringToOUString( aName.makeStringAndClear(), RTL_TEXTENCODING_MS_932 );
                    break;
                case 3:
                    aValue = OStringToOUString( aName.makeStringAndClear(), RTL_TEXTENCODING_MS_936 );
                    break;
                case 4:
                    aValue = OStringToOUString( aName.makeStringAndClear(), RTL_TEXTENCODING_MS_950 );
                    break;
                case 5:
                    aValue = OStringToOUString( aName.makeStringAndClear(), RTL_TEXTENCODING_MS_949 );
                    break;
                case 6:
                    aValue = OStringToOUString( aName.makeStringAndClear(), RTL_TEXTENCODING_MS_1361 );
                    break;
            }
        }
    }
    return aValue;
}

//fdo#33349.There exists an archaic Berling Antiqua font which has a "Times New
//Roman" name field in it. We don't want the "Times New Roman" name to take
//precedence in this case. We take Berling Antiqua as a higher priority name,
//and erase the "Times New Roman" name
namespace
{
    bool isBadTNR(const OUString &rName, ::std::set< OUString >& rSet)
    {
        bool bRet = false;
        if ( rName == "Berling Antiqua" )
        {
            ::std::set< OUString >::iterator aEnd = rSet.end();
            ::std::set< OUString >::iterator aI = rSet.find(OUString(RTL_CONSTASCII_USTRINGPARAM("Times New Roman")));
            if (aI != aEnd)
            {
                bRet = true;
                rSet.erase(aI);
            }
        }
        return bRet;
    }
}

// -------------------------------------------------------------------------

void PrintFontManager::analyzeTrueTypeFamilyName( void* pTTFont, ::std::list< OUString >& rNames ) const
{
    OUString aFamily;

    rNames.clear();
    ::std::set< OUString > aSet;

    NameRecord* pNameRecords = NULL;
    int nNameRecords = GetTTNameRecords( (TrueTypeFont*)pTTFont, &pNameRecords );
    if( nNameRecords && pNameRecords )
    {
        LanguageType aLang = MsLangId::getSystemLanguage();
        int nLastMatch = -1;
        for( int i = 0; i < nNameRecords; i++ )
        {
            if( pNameRecords[i].nameID != 1 || pNameRecords[i].sptr == NULL )
                continue;
            int nMatch = -1;
            if( pNameRecords[i].platformID == 0 ) // Unicode
                nMatch = 4000;
            else if( pNameRecords[i].platformID == 3 )
            {
                // this bases on the LanguageType actually being a Win LCID
                if( pNameRecords[i].languageID == aLang )
                    nMatch = 8000;
                else if( pNameRecords[i].languageID == LANGUAGE_ENGLISH_US )
                    nMatch = 2000;
                else if( pNameRecords[i].languageID == LANGUAGE_ENGLISH ||
                         pNameRecords[i].languageID == LANGUAGE_ENGLISH_UK )
                    nMatch = 1500;
                else
                    nMatch = 1000;
            }
            OUString aName = convertTrueTypeName( pNameRecords + i );
            aSet.insert( aName );
            if( nMatch > nLastMatch || isBadTNR(aName, aSet) )
            {
                nLastMatch = nMatch;
                aFamily = aName;
            }
        }
        DisposeNameRecords( pNameRecords, nNameRecords );
    }
    if( !aFamily.isEmpty() )
    {
        rNames.push_front( aFamily );
        for( ::std::set< OUString >::const_iterator it = aSet.begin(); it != aSet.end(); ++it )
            if( *it != aFamily )
                rNames.push_back( *it );
    }
    return;
}

// -------------------------------------------------------------------------

bool PrintFontManager::analyzeTrueTypeFile( PrintFont* pFont ) const
{
    bool bSuccess = false;
    rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
    rtl::OString aFile = getFontFile( pFont );
    TrueTypeFont* pTTFont = NULL;

    TrueTypeFontFile* pTTFontFile = static_cast< TrueTypeFontFile* >(pFont);
    if( OpenTTFontFile( aFile.getStr(), pTTFontFile->m_nCollectionEntry, &pTTFont ) == SF_OK )
    {
        TTGlobalFontInfo aInfo;
        GetTTGlobalFontInfo( pTTFont, & aInfo );

        ::std::list< OUString > aNames;
        analyzeTrueTypeFamilyName( pTTFont, aNames );

        // set family name from XLFD if possible
        if( ! pFont->m_nFamilyName )
        {
            if( aNames.begin() != aNames.end() )
            {
                pFont->m_nFamilyName = m_pAtoms->getAtom( ATOM_FAMILYNAME, aNames.front(), sal_True );
                aNames.pop_front();
            }
            else
            {
                 sal_Int32   dotIndex;

                 // poor font does not have a family name
                 // name it to file name minus the extension
                 dotIndex = pTTFontFile->m_aFontFile.lastIndexOf( '.' );
                 if ( dotIndex == -1 )
                     dotIndex = pTTFontFile->m_aFontFile.getLength();

                 pFont->m_nFamilyName = m_pAtoms->getAtom( ATOM_FAMILYNAME, OStringToOUString( pTTFontFile->m_aFontFile.copy( 0, dotIndex ), aEncoding ), sal_True );
            }
        }
        for( ::std::list< OUString >::iterator it = aNames.begin(); it != aNames.end(); ++it )
        {
            if( !it->isEmpty() )
            {
                int nAlias = m_pAtoms->getAtom( ATOM_FAMILYNAME, *it, sal_True );
                if( nAlias != pFont->m_nFamilyName )
                {
                    std::list< int >::const_iterator al_it;
                    for( al_it = pFont->m_aAliases.begin(); al_it != pFont->m_aAliases.end() && *al_it != nAlias; ++al_it )
                        ;
                    if( al_it == pFont->m_aAliases.end() )
                        pFont->m_aAliases.push_back( nAlias );
                }
            }
        }

        if( aInfo.usubfamily )
            pFont->m_aStyleName = OUString( aInfo.usubfamily );

        pFont->m_nPSName = m_pAtoms->getAtom( ATOM_PSNAME,
            rtl::OUString(aInfo.psname, rtl_str_getLength(aInfo.psname), aEncoding),
            sal_True );
        switch( aInfo.weight )
        {
            case FW_THIN:           pFont->m_eWeight = WEIGHT_THIN; break;
            case FW_EXTRALIGHT: pFont->m_eWeight = WEIGHT_ULTRALIGHT; break;
            case FW_LIGHT:          pFont->m_eWeight = WEIGHT_LIGHT; break;
            case FW_MEDIUM:     pFont->m_eWeight = WEIGHT_MEDIUM; break;
            case FW_SEMIBOLD:       pFont->m_eWeight = WEIGHT_SEMIBOLD; break;
            case FW_BOLD:           pFont->m_eWeight = WEIGHT_BOLD; break;
            case FW_EXTRABOLD:      pFont->m_eWeight = WEIGHT_ULTRABOLD; break;
            case FW_BLACK:          pFont->m_eWeight = WEIGHT_BLACK; break;

            case FW_NORMAL:
            default:        pFont->m_eWeight = WEIGHT_NORMAL; break;
        }

        switch( aInfo.width )
        {
            case FWIDTH_ULTRA_CONDENSED:    pFont->m_eWidth = WIDTH_ULTRA_CONDENSED; break;
            case FWIDTH_EXTRA_CONDENSED:    pFont->m_eWidth = WIDTH_EXTRA_CONDENSED; break;
            case FWIDTH_CONDENSED:          pFont->m_eWidth = WIDTH_CONDENSED; break;
            case FWIDTH_SEMI_CONDENSED: pFont->m_eWidth = WIDTH_SEMI_CONDENSED; break;
            case FWIDTH_SEMI_EXPANDED:      pFont->m_eWidth = WIDTH_SEMI_EXPANDED; break;
            case FWIDTH_EXPANDED:           pFont->m_eWidth = WIDTH_EXPANDED; break;
            case FWIDTH_EXTRA_EXPANDED: pFont->m_eWidth = WIDTH_EXTRA_EXPANDED; break;
            case FWIDTH_ULTRA_EXPANDED: pFont->m_eWidth = WIDTH_ULTRA_EXPANDED; break;

            case FWIDTH_NORMAL:
            default:                        pFont->m_eWidth = WIDTH_NORMAL; break;
        }

        pFont->m_ePitch = aInfo.pitch ? PITCH_FIXED : PITCH_VARIABLE;
        pFont->m_eItalic = aInfo.italicAngle == 0 ? ITALIC_NONE : ( aInfo.italicAngle < 0 ? ITALIC_NORMAL : ITALIC_OBLIQUE );
        // #104264# there are fonts that set italic angle 0 although they are
        // italic; use macstyle bit here
        if( aInfo.italicAngle == 0 && (aInfo.macStyle & 2) )
            pFont->m_eItalic = ITALIC_NORMAL;

        pFont->m_aEncoding = aInfo.symbolEncoded ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UCS2;

        pFont->m_aGlobalMetricY.width = pFont->m_aGlobalMetricX.width = aInfo.xMax - aInfo.xMin;
        pFont->m_aGlobalMetricY.height = pFont->m_aGlobalMetricX.height = aInfo.yMax - aInfo.yMin;

        if( aInfo.winAscent && aInfo.winDescent )
        {
            pFont->m_nAscend    = aInfo.winAscent;
            pFont->m_nDescend   = aInfo.winDescent;
            pFont->m_nLeading   = pFont->m_nAscend + pFont->m_nDescend - 1000;
        }
        else if( aInfo.typoAscender && aInfo.typoDescender )
        {
            pFont->m_nLeading   = aInfo.typoLineGap;
            pFont->m_nAscend    = aInfo.typoAscender;
            pFont->m_nDescend   = -aInfo.typoDescender;
        }
        else
        {
            pFont->m_nLeading   = aInfo.linegap;
            pFont->m_nAscend    = aInfo.ascender;
            pFont->m_nDescend   = -aInfo.descender;
        }

        // last try: font bounding box
        if( pFont->m_nAscend == 0 )
            pFont->m_nAscend = aInfo.yMax;
        if( pFont->m_nDescend == 0 )
            pFont->m_nDescend = -aInfo.yMin;
        if( pFont->m_nLeading == 0 )
            pFont->m_nLeading = 15 * (pFont->m_nAscend+pFont->m_nDescend) / 100;

        if( pFont->m_nAscend )
            pFont->m_aGlobalMetricX.height = pFont->m_aGlobalMetricY.height = pFont->m_nAscend + pFont->m_nDescend;

        // get bounding box
        pFont->m_nXMin = aInfo.xMin;
        pFont->m_nYMin = aInfo.yMin;
        pFont->m_nXMax = aInfo.xMax;
        pFont->m_nYMax = aInfo.yMax;

        // get type flags
        pTTFontFile->m_nTypeFlags = (unsigned int)aInfo.typeFlags;

        // get vertical substitutions flag
        pFont->m_bHaveVerticalSubstitutedGlyphs = DoesVerticalSubstitution( pTTFont, 1 );

        CloseTTFont( pTTFont );
        bSuccess = true;
    }
#if OSL_DEBUG_LEVEL > 1
    else
        fprintf( stderr, "could not OpenTTFont \"%s\"\n", aFile.getStr() );
#endif

    return bSuccess;
}

static bool AreFCSubstitutionsEnabled()
{
    return (SalGenericInstance::FetchFontSubstitutionFlags() & 3) == 0;
}

void PrintFontManager::initialize()
{
    #ifdef CALLGRIND_COMPILE
    CALLGRIND_TOGGLE_COLLECT();
    CALLGRIND_ZERO_STATS();
    #endif

    long aDirEntBuffer[ (sizeof(struct dirent)+_PC_NAME_MAX)+1 ];

    if( ! m_pFontCache )
    {
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "creating font cache ... " );
        clock_t aStart;
        struct tms tms;
        aStart = times( &tms );
#endif
        m_pFontCache = new FontCache();
#if OSL_DEBUG_LEVEL > 1
        clock_t aStop = times( &tms );
        fprintf( stderr, "done in %lf s\n", (double)(aStop - aStart)/(double)sysconf( _SC_CLK_TCK ) );
#endif
    }

    // initialize may be called twice in the future
    {
        for( ::boost::unordered_map< fontID, PrintFont* >::const_iterator it = m_aFonts.begin(); it != m_aFonts.end(); ++it )
            delete (*it).second;
        m_nNextFontID = 1;
        m_aFonts.clear();
        m_aFontDirectories.clear();
        m_aPrivateFontDirectories.clear();
        m_aOverrideFonts.clear();
    }

#if OSL_DEBUG_LEVEL > 1
    clock_t aStart;
    clock_t aStep1;
    clock_t aStep2;
    clock_t aStep3;
    int nBuiltinFonts = 0;
    int nCached = 0;

    struct tms tms;

    aStart = times( &tms );
#endif

    // first try fontconfig
    initFontconfig();

    // part one - look for downloadable fonts
    rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
    const ::rtl::OUString &rSalPrivatePath = psp::getFontPath();

    // search for the fonts in SAL_PRIVATE_FONTPATH first; those are
    // the fonts installed with the office
    if( !rSalPrivatePath.isEmpty() )
    {
        OString aPath = rtl::OUStringToOString( rSalPrivatePath, aEncoding );
        const bool bAreFCSubstitutionsEnabled = AreFCSubstitutionsEnabled();
        sal_Int32 nIndex = 0;
        do
        {
            OString aToken = aPath.getToken( 0, ';', nIndex );
            normPath( aToken );
            if ( aToken.isEmpty() )
            {
                continue;
            }
            // if registering an app-specific fontdir with fontconfig fails
            // and fontconfig-based substitutions are enabled
            // then trying to use these app-specific fonts doesn't make sense
            if( !addFontconfigDir( aToken ) )
                if( bAreFCSubstitutionsEnabled )
                    continue;
            m_aFontDirectories.push_back( aToken );
            m_aPrivateFontDirectories.push_back( getDirectoryAtom( aToken, true ) );
        } while( nIndex >= 0 );
    }

    // protect against duplicate paths
    boost::unordered_map< OString, int, OStringHash > visited_dirs;

    // Don't search directories that fontconfig already did
    countFontconfigFonts( visited_dirs );

    // search for font files in each path
    std::list< OString >::iterator dir_it;
    for( dir_it = m_aFontDirectories.begin(); dir_it != m_aFontDirectories.end(); ++dir_it )
    {
        OString aPath( *dir_it );
        // see if we were here already
        if( visited_dirs.find( aPath ) != visited_dirs.end() )
            continue;
        visited_dirs[ aPath ] = 1;

        // there may be ":unscaled" directories (see XFree86)
        // it should be safe to ignore them since they should not
        // contain any of our recognizeable fonts

        // ask the font cache whether it handles this directory
        std::list< PrintFont* > aCacheFonts;
        if( m_pFontCache->listDirectory( aPath, aCacheFonts ) )
        {
#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "adding cache directory: %s\n", aPath.getStr() );
#endif
            for( ::std::list< PrintFont* >::iterator it = aCacheFonts.begin(); it != aCacheFonts.end(); ++it )
            {
                fontID aFont = m_nNextFontID++;
                m_aFonts[ aFont ] = *it;
                if( (*it)->m_eType == fonttype::Type1 )
                    m_aFontFileToFontID[ static_cast<Type1FontFile*>(*it)->m_aFontFile ].insert( aFont );
                else if( (*it)->m_eType == fonttype::TrueType )
                    m_aFontFileToFontID[ static_cast<TrueTypeFontFile*>(*it)->m_aFontFile ].insert( aFont );
                else if( (*it)->m_eType == fonttype::Builtin )
                    m_aFontFileToFontID[ static_cast<BuiltinFont*>(*it)->m_aMetricFile ].insert( aFont );
#if OSL_DEBUG_LEVEL > 1
                if( (*it)->m_eType == fonttype::Builtin )
                    nBuiltinFonts++;
                nCached++;
#if OSL_DEBUG_LEVEL > 2
                fprintf( stderr, "adding cached font %d: %s\n", aFont, getFontFileSysPath( aFont ).getStr() );
#endif
#endif
            }
            if( ! m_pFontCache->scanAdditionalFiles( aPath ) )
                continue;
        }

    }

#if OSL_DEBUG_LEVEL > 1
    aStep1 = times( &tms );
#endif

    // part two - look for metrics for builtin printer fonts
    std::list< OUString > aMetricDirs;
    psp::getPrinterPathList( aMetricDirs, PRINTER_METRICDIR );

    for( std::list< OUString >::const_iterator met_dir_it = aMetricDirs.begin(); met_dir_it != aMetricDirs.end(); ++met_dir_it )
    {
        OString aDir = OUStringToOString( *met_dir_it, aEncoding );

        // ask the font cache whether it handles this directory
        std::list< PrintFont* > aCacheFonts;

        if( m_pFontCache->listDirectory( aDir, aCacheFonts ) )
        {
#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "adding cache directory: %s\n", aDir.getStr() );
#endif
            for( ::std::list< PrintFont* >::iterator it = aCacheFonts.begin(); it != aCacheFonts.end(); ++it )
            {
                fontID aFont = m_nNextFontID++;
                m_aFonts[ aFont ] = *it;
                if( (*it)->m_eType == fonttype::Type1 )
                    m_aFontFileToFontID[ static_cast<Type1FontFile*>(*it)->m_aFontFile ].insert( aFont );
                else if( (*it)->m_eType == fonttype::TrueType )
                    m_aFontFileToFontID[ static_cast<TrueTypeFontFile*>(*it)->m_aFontFile ].insert( aFont );
                else if( (*it)->m_eType == fonttype::Builtin )
                    m_aFontFileToFontID[ static_cast<BuiltinFont*>(*it)->m_aMetricFile ].insert( aFont );
#if OSL_DEBUG_LEVEL > 1
                if( (*it)->m_eType == fonttype::Builtin )
                    nBuiltinFonts++;
                nCached++;
#if OSL_DEBUG_LEVEL > 2
                fprintf( stderr, "adding cached font %d: from %s\n", aFont,
                         getFontFileSysPath( aFont ).getStr() );
#endif
#endif
            }
            continue;
        }

        DIR* pDIR = opendir( aDir.getStr() );
        if( pDIR )
        {
            struct dirent* pDirEntry = (struct dirent*)aDirEntBuffer;
            int nDirID = getDirectoryAtom( aDir, true );
            int nDirFonts = 0;

            while( ! readdir_r( pDIR, (struct dirent*)aDirEntBuffer, &pDirEntry ) && pDirEntry )
            {
                rtl::OStringBuffer aFile(aDir);
                aFile.append('/').append(pDirEntry->d_name);
                struct stat aStat;
                if( ! stat( aFile.getStr(), &aStat )
                    && S_ISREG( aStat.st_mode )
                    )
                {
                    OString aFileName( pDirEntry->d_name, strlen( pDirEntry->d_name ) );
                    OString aExt( aFileName.copy( aFileName.lastIndexOf( '.' )+1 ) );
                    if( aExt.equalsIgnoreAsciiCase( "afm" ) )
                    {
                        ::std::list< PrintFont* > aNewFonts;

                        analyzeFontFile( nDirID, aFileName, aNewFonts );
                        for( ::std::list< PrintFont* >::iterator it = aNewFonts.begin(); it != aNewFonts.end(); ++it )
                        {
                            if( findFontBuiltinID( (*it)->m_nPSName ) == 0 )
                            {
                                m_aFontFileToFontID[ aFileName ].insert( m_nNextFontID );
                                m_aFonts[ m_nNextFontID++ ] = *it;
                                m_pFontCache->updateFontCacheEntry( *it, false );
#if OSL_DEBUG_LEVEL > 2
                                nBuiltinFonts++;
#endif
                            }
                            else
                                delete *it;
                        }
                    }
                }
            }
            closedir( pDIR );
            if( ! nDirFonts )
                m_pFontCache->markEmptyDir( nDirID );
        }
    }

#if OSL_DEBUG_LEVEL > 1
    aStep2 = times( &tms );
#endif

    // part three - fill in family styles
    ::boost::unordered_map< fontID, PrintFont* >::iterator font_it;
    for (font_it = m_aFonts.begin(); font_it != m_aFonts.end(); ++font_it)
    {
        ::boost::unordered_map< int, FontFamily >::const_iterator it =
              m_aFamilyTypes.find( font_it->second->m_nFamilyName );
        if (it != m_aFamilyTypes.end())
            continue;
        const ::rtl::OUString& rFamily =
            m_pAtoms->getString( ATOM_FAMILYNAME, font_it->second->m_nFamilyName);
        FontFamily eType = matchFamilyName( rFamily );
        m_aFamilyTypes[ font_it->second->m_nFamilyName ] = eType;
    }

#if OSL_DEBUG_LEVEL > 1
    aStep3 = times( &tms );
    fprintf( stderr, "PrintFontManager::initialize: collected %" SAL_PRI_SIZET "u fonts (%d builtin, %d cached)\n", m_aFonts.size(), nBuiltinFonts, nCached );
    double fTick = (double)sysconf( _SC_CLK_TCK );
    fprintf( stderr, "Step 1 took %lf seconds\n", (double)(aStep1 - aStart)/fTick );
    fprintf( stderr, "Step 2 took %lf seconds\n", (double)(aStep2 - aStep1)/fTick );
    fprintf( stderr, "Step 3 took %lf seconds\n", (double)(aStep3 - aStep2)/fTick );
#endif

    m_pFontCache->flush();

    #ifdef CALLGRIND_COMPILE
    CALLGRIND_DUMP_STATS();
    CALLGRIND_TOGGLE_COLLECT();
    #endif
}

// -------------------------------------------------------------------------
inline bool
equalPitch (FontPitch from, FontPitch to)
{
    return from == to;
}

inline bool
equalWeight (FontWeight from, FontWeight to)
{
    return from > to ? (from - to) <= 3 : (to - from) <= 3;
}

inline bool
equalItalic (FontItalic from, FontItalic to)
{
    if ( (from == ITALIC_NORMAL) || (from == ITALIC_OBLIQUE) )
        return (to == ITALIC_NORMAL) || (to == ITALIC_OBLIQUE);
    return to == from;
}
inline bool
equalEncoding (rtl_TextEncoding from, rtl_TextEncoding to)
{
    if ((from == RTL_TEXTENCODING_ISO_8859_1) || (from == RTL_TEXTENCODING_MS_1252))
        return (to == RTL_TEXTENCODING_ISO_8859_1) || (to == RTL_TEXTENCODING_MS_1252);
    return from == to;
}

namespace {
    struct BuiltinFontIdentifier
    {
        OUString            aFamily;
        FontItalic          eItalic;
        FontWeight          eWeight;
        FontPitch           ePitch;
        rtl_TextEncoding    aEncoding;

        BuiltinFontIdentifier( const OUString& rFam,
                               FontItalic eIt,
                               FontWeight eWg,
                               FontPitch ePt,
                               rtl_TextEncoding enc ) :
            aFamily( rFam ),
            eItalic( eIt ),
            eWeight( eWg ),
            ePitch( ePt ),
            aEncoding( enc )
        {}

        bool operator==( const BuiltinFontIdentifier& rRight ) const
        {
            return equalItalic( eItalic, rRight.eItalic ) &&
                   equalWeight( eWeight, rRight.eWeight ) &&
                   equalPitch( ePitch, rRight.ePitch ) &&
                   equalEncoding( aEncoding, rRight.aEncoding ) &&
                   aFamily.equalsIgnoreAsciiCase( rRight.aFamily );
        }
    };

    struct BuiltinFontIdentifierHash
    {
        size_t operator()( const BuiltinFontIdentifier& rFont ) const
        {
            return rFont.aFamily.hashCode() ^ rFont.eItalic ^ rFont.eWeight ^ rFont.ePitch ^ rFont.aEncoding;
        }
    };
}

void PrintFontManager::getFontList( ::std::list< fontID >& rFontIDs, const PPDParser* pParser, bool bUseOverrideMetrics )
{
    rFontIDs.clear();
    boost::unordered_map< fontID, PrintFont* >::const_iterator it;

    /*
    * Note: there are two easy steps making this faster:
    * first: insert the printer builtins first, then the not builtins,
    * if they do not match.
    * drawback: this would change the sequence of fonts; this could have
    * subtle, unknown consequences in vcl font matching
    * second: instead of comparing attributes to see whether a softfont
    * is duplicate to a builtin one could simply compare the PSName (which is
    * supposed to be unique), which at this point is just an int.
    * drawback: this could change which fonts are listed; especially TrueType
    * fonts often have a rather dubious PSName, so this could change the
    * font list not so subtle.
    * Until getFontList for a printer becomes a performance issue (which is
    * currently not the case), best stay with the current algorithm.
    */

    // fill sets of printer supported fonts
    if( pParser )
    {
        std::set<int> aBuiltinPSNames;
        boost::unordered_set< BuiltinFontIdentifier,
                       BuiltinFontIdentifierHash
                       > aBuiltinFonts;

        std::map<int, fontID > aOverridePSNames;
        if( bUseOverrideMetrics )
        {
            readOverrideMetrics();
            for( std::vector<fontID>::const_iterator over = m_aOverrideFonts.begin();
                 over != m_aOverrideFonts.end(); ++over )
            {
                boost::unordered_map<fontID,PrintFont*>::const_iterator font_it = m_aFonts.find( *over );
                DBG_ASSERT( font_it != m_aFonts.end(), "override to nonexistant font" );
                if( font_it != m_aFonts.end() )
                    aOverridePSNames[ font_it->second->m_nPSName ] = *over;
            }
        }

        int nFonts = pParser->getFonts();
        for( int i = 0; i < nFonts; i++ )
            aBuiltinPSNames.insert( m_pAtoms->getAtom( ATOM_PSNAME, pParser->getFont( i ) ) );
        for( it = m_aFonts.begin(); it != m_aFonts.end(); ++it )
        {
            PrintFont* pFont = it->second;
            if( it->second->m_eType == fonttype::Builtin &&
                aBuiltinPSNames.find( pFont->m_nPSName ) != aBuiltinPSNames.end() )
            {
                bool bInsert = true;
                if( bUseOverrideMetrics )
                {
                    // in override case only use the override fonts, not their counterparts
                    std::map<int,fontID>::const_iterator over = aOverridePSNames.find( pFont->m_nPSName );
                    if( over != aOverridePSNames.end() && over->second != it->first )
                        bInsert = false;
                }
                else
                {
                    // do not insert override fonts in non override case
                    if( std::find( m_aOverrideFonts.begin(), m_aOverrideFonts.end(), it->first ) != m_aOverrideFonts.end() )
                        bInsert = false;
                }
                if( bInsert )
                {
                    aBuiltinFonts.insert( BuiltinFontIdentifier(
                        m_pAtoms->getString( ATOM_FAMILYNAME, pFont->m_nFamilyName ),
                        pFont->m_eItalic,
                        pFont->m_eWeight,
                        pFont->m_ePitch,
                        pFont->m_aEncoding
                        ) );
                }
            }
        }
        for( it = m_aFonts.begin(); it != m_aFonts.end(); ++it )
        {
            PrintFont* pFont = it->second;
            if( it->second->m_eType == fonttype::Builtin )
            {
                if( aBuiltinPSNames.find( pFont->m_nPSName ) != aBuiltinPSNames.end() )
                {
                    bool bInsert = true;
                    if( bUseOverrideMetrics )
                    {
                        // in override case only use the override fonts, not their counterparts
                        std::map<int,fontID>::const_iterator over = aOverridePSNames.find( pFont->m_nPSName );
                        if( over != aOverridePSNames.end() && over->second != it->first )
                            bInsert = false;
                    }
                    else
                    {
                        // do not insert override fonts in non override case
                        if( std::find( m_aOverrideFonts.begin(), m_aOverrideFonts.end(), it->first ) != m_aOverrideFonts.end() )
                            bInsert = false;
                    }
                    if( bInsert )
                        rFontIDs.push_back( it->first );
                }
            }
            else if( aBuiltinFonts.find( BuiltinFontIdentifier(
                m_pAtoms->getString( ATOM_FAMILYNAME, pFont->m_nFamilyName ),
                pFont->m_eItalic,
                pFont->m_eWeight,
                pFont->m_ePitch,
                pFont->m_aEncoding
                ) ) == aBuiltinFonts.end() )
            {
                rFontIDs.push_back( it->first );
            }
        }
    }
    else // no specific printer
    {
        for( it = m_aFonts.begin(); it != m_aFonts.end(); ++it )
            rFontIDs.push_back( it->first );
    }
}

// -------------------------------------------------------------------------

void PrintFontManager::fillPrintFontInfo( PrintFont* pFont, FastPrintFontInfo& rInfo ) const
{
    ::boost::unordered_map< int, FontFamily >::const_iterator style_it =
          m_aFamilyTypes.find( pFont->m_nFamilyName );
    rInfo.m_eType           = pFont->m_eType;
    rInfo.m_aFamilyName     = m_pAtoms->getString( ATOM_FAMILYNAME, pFont->m_nFamilyName );
    rInfo.m_aStyleName      = pFont->m_aStyleName;
    rInfo.m_eFamilyStyle    = style_it != m_aFamilyTypes.end() ? style_it->second : FAMILY_DONTKNOW;
    rInfo.m_eItalic         = pFont->m_eItalic;
    rInfo.m_eWidth          = pFont->m_eWidth;
    rInfo.m_eWeight         = pFont->m_eWeight;
    rInfo.m_ePitch          = pFont->m_ePitch;
    rInfo.m_aEncoding       = pFont->m_aEncoding;

    rInfo.m_bEmbeddable  = (pFont->m_eType == fonttype::Type1);
    rInfo.m_bSubsettable = (pFont->m_eType == fonttype::TrueType); // TODO: rename to SfntType

    rInfo.m_aAliases.clear();
    for( ::std::list< int >::iterator it = pFont->m_aAliases.begin(); it != pFont->m_aAliases.end(); ++it )
        rInfo.m_aAliases.push_back( m_pAtoms->getString( ATOM_FAMILYNAME, *it ) );
}

// -------------------------------------------------------------------------

void PrintFontManager::fillPrintFontInfo( PrintFont* pFont, PrintFontInfo& rInfo ) const
{
    if( ( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 ) ||
        ! pFont->m_pMetrics || pFont->m_pMetrics->isEmpty()
        )
    {
        // might be a truetype font not analyzed or type1 without metrics read
        if( pFont->m_eType == fonttype::Type1 )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, false );
        else if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
    }

    fillPrintFontInfo( pFont, static_cast< FastPrintFontInfo& >( rInfo ) );

    rInfo.m_nAscend         = pFont->m_nAscend;
    rInfo.m_nDescend        = pFont->m_nDescend;
    rInfo.m_nLeading        = pFont->m_nLeading;
    rInfo.m_nWidth          = pFont->m_aGlobalMetricX.width < pFont->m_aGlobalMetricY.width ? pFont->m_aGlobalMetricY.width : pFont->m_aGlobalMetricX.width;
}

// -------------------------------------------------------------------------

void PrintFontManager::getFontListWithFastInfo( ::std::list< FastPrintFontInfo >& rFonts, const PPDParser* pParser, bool bUseOverrideMetrics )
{
    rFonts.clear();
    ::std::list< fontID > aFontList;
    getFontList( aFontList, pParser, bUseOverrideMetrics );

    ::std::list< fontID >::iterator it;
    for( it = aFontList.begin(); it != aFontList.end(); ++it )
    {
        FastPrintFontInfo aInfo;
        aInfo.m_nID = *it;
        fillPrintFontInfo( getFont( *it ), aInfo );
        rFonts.push_back( aInfo );
    }
}

// -------------------------------------------------------------------------

bool PrintFontManager::getFontInfo( fontID nFontID, PrintFontInfo& rInfo ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont )
    {
        rInfo.m_nID = nFontID;
        fillPrintFontInfo( pFont, rInfo );
    }
    return pFont ? true : false;
}

// -------------------------------------------------------------------------

bool PrintFontManager::getFontFastInfo( fontID nFontID, FastPrintFontInfo& rInfo ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont )
    {
        rInfo.m_nID = nFontID;
        fillPrintFontInfo( pFont, rInfo );
    }
    return pFont ? true : false;
}

// -------------------------------------------------------------------------

bool PrintFontManager::getFontBoundingBox( fontID nFontID, int& xMin, int& yMin, int& xMax, int& yMax )
{
    bool bSuccess = false;
    PrintFont* pFont = getFont( nFontID );
    if( pFont )
    {
        if( pFont->m_nXMin == 0 && pFont->m_nYMin == 0 && pFont->m_nXMax == 0 && pFont->m_nYMax == 0 )
        {
            // might be a truetype font not analyzed or type1 without metrics read
            if( pFont->m_eType == fonttype::Type1 || pFont->m_eType == fonttype::Builtin )
                pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, true );
            else if( pFont->m_eType == fonttype::TrueType )
                analyzeTrueTypeFile( pFont );
        }
        bSuccess = true;
        xMin = pFont->m_nXMin;
        yMin = pFont->m_nYMin;
        xMax = pFont->m_nXMax;
        yMax = pFont->m_nYMax;
    }
    return bSuccess;
}

// -------------------------------------------------------------------------

int PrintFontManager::getFontFaceNumber( fontID nFontID ) const
{
    int nRet = 0;
    PrintFont* pFont = getFont( nFontID );
    if( pFont && pFont->m_eType == fonttype::TrueType )
        nRet = static_cast< TrueTypeFontFile* >(pFont)->m_nCollectionEntry;
    if (nRet < 0)
        nRet = 0;
    return nRet;
}

// -------------------------------------------------------------------------


FontFamily PrintFontManager::matchFamilyName( const ::rtl::OUString& rFamily ) const
{
    typedef struct {
        const char*  mpName;
        sal_uInt16   mnLength;
        FontFamily   meType;
    } family_t;

#define InitializeClass( p, a ) p, sizeof(p) - 1, a
    const family_t pFamilyMatch[] =  {
        { InitializeClass( "arial",                  FAMILY_SWISS )  },
        { InitializeClass( "arioso",                 FAMILY_SCRIPT ) },
        { InitializeClass( "avant garde",            FAMILY_SWISS )  },
        { InitializeClass( "avantgarde",             FAMILY_SWISS )  },
        { InitializeClass( "bembo",                  FAMILY_ROMAN )  },
        { InitializeClass( "bookman",                FAMILY_ROMAN )  },
        { InitializeClass( "conga",                  FAMILY_ROMAN )  },
        { InitializeClass( "courier",                FAMILY_MODERN ) },
        { InitializeClass( "curl",                   FAMILY_SCRIPT ) },
        { InitializeClass( "fixed",                  FAMILY_MODERN ) },
        { InitializeClass( "gill",                   FAMILY_SWISS )  },
        { InitializeClass( "helmet",                 FAMILY_MODERN ) },
        { InitializeClass( "helvetica",              FAMILY_SWISS )  },
        { InitializeClass( "international",          FAMILY_MODERN ) },
        { InitializeClass( "lucida",                 FAMILY_SWISS )  },
        { InitializeClass( "new century schoolbook", FAMILY_ROMAN )  },
        { InitializeClass( "palatino",               FAMILY_ROMAN )  },
        { InitializeClass( "roman",                  FAMILY_ROMAN )  },
        { InitializeClass( "sans serif",             FAMILY_SWISS )  },
        { InitializeClass( "sansserif",              FAMILY_SWISS )  },
        { InitializeClass( "serf",                   FAMILY_ROMAN )  },
        { InitializeClass( "serif",                  FAMILY_ROMAN )  },
        { InitializeClass( "times",                  FAMILY_ROMAN )  },
        { InitializeClass( "utopia",                 FAMILY_ROMAN )  },
        { InitializeClass( "zapf chancery",          FAMILY_SCRIPT ) },
        { InitializeClass( "zapfchancery",           FAMILY_SCRIPT ) }
    };

    rtl::OString aFamily = rtl::OUStringToOString( rFamily, RTL_TEXTENCODING_ASCII_US );
    sal_uInt32 nLower = 0;
    sal_uInt32 nUpper = SAL_N_ELEMENTS(pFamilyMatch);

    while( nLower < nUpper )
    {
        sal_uInt32 nCurrent = (nLower + nUpper) / 2;
        const family_t* pHaystack = pFamilyMatch + nCurrent;
        sal_Int32  nComparison =
            rtl_str_compareIgnoreAsciiCase_WithLength
            (
             aFamily.getStr(), aFamily.getLength(),
             pHaystack->mpName, pHaystack->mnLength
             );

        if( nComparison < 0 )
            nUpper = nCurrent;
        else
            if( nComparison > 0 )
                nLower = nCurrent + 1;
            else
                return pHaystack->meType;
    }

    return FAMILY_DONTKNOW;
}

// -------------------------------------------------------------------------

OString PrintFontManager::getAfmFile( PrintFont* pFont ) const
{
    OString aMetricPath;
    if( pFont )
    {
        switch( pFont->m_eType )
        {
            case fonttype::Type1:
            {
                Type1FontFile* pPSFont = static_cast< Type1FontFile* >(pFont);
                aMetricPath = getDirectory( pPSFont->m_nDirectory );
                aMetricPath += "/";
                aMetricPath += pPSFont->m_aMetricFile;
            }
            break;
            case fonttype::Builtin:
            {
                BuiltinFont* pBuiltinFont = static_cast< BuiltinFont* >(pFont);
                aMetricPath = getDirectory( pBuiltinFont->m_nDirectory );
                aMetricPath += "/";
                aMetricPath += pBuiltinFont->m_aMetricFile;
            }
            break;
            default: break;
        }
    }
    return aMetricPath;
}

// -------------------------------------------------------------------------

OString PrintFontManager::getFontFile( PrintFont* pFont ) const
{
    OString aPath;

    if( pFont && pFont->m_eType == fonttype::Type1 )
    {
        Type1FontFile* pPSFont = static_cast< Type1FontFile* >(pFont);
        ::boost::unordered_map< int, OString >::const_iterator it = m_aAtomToDir.find( pPSFont->m_nDirectory );
        aPath = it->second;
        aPath += "/";
        aPath += pPSFont->m_aFontFile;
    }
    else if( pFont && pFont->m_eType == fonttype::TrueType )
    {
        TrueTypeFontFile* pTTFont = static_cast< TrueTypeFontFile* >(pFont);
        ::boost::unordered_map< int, OString >::const_iterator it = m_aAtomToDir.find( pTTFont->m_nDirectory );
        aPath = it->second;
        aPath += "/";
        aPath += pTTFont->m_aFontFile;
    }
    return aPath;
}

// -------------------------------------------------------------------------

const ::rtl::OUString& PrintFontManager::getPSName( fontID nFontID ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont && pFont->m_nPSName == 0 )
    {
        if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
    }

    return m_pAtoms->getString( ATOM_PSNAME, pFont ? pFont->m_nPSName : INVALID_ATOM );<--- Possible null pointer dereference: pFont - otherwise it is redundant to check if pFont is null at line 2365
}

// -------------------------------------------------------------------------

int PrintFontManager::getFontAscend( fontID nFontID ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 )
    {
        // might be a truetype font not yet analyzed
        if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
        else if( pFont->m_eType == fonttype::Type1 || pFont->m_eType == fonttype::Builtin )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, true );
    }
    return pFont->m_nAscend;
}

// -------------------------------------------------------------------------

int PrintFontManager::getFontDescend( fontID nFontID ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 )
    {
        // might be a truetype font not yet analyzed
        if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
        else if( pFont->m_eType == fonttype::Type1 || pFont->m_eType == fonttype::Builtin )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, true );
    }
    return pFont->m_nDescend;
}

// -------------------------------------------------------------------------

void PrintFontManager::hasVerticalSubstitutions( fontID nFontID,
    const sal_Unicode* pCharacters, int nCharacters, bool* pHasSubst ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 )
    {
        // might be a truetype font not yet analyzed
        if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
    }

    if( ! pFont->m_bHaveVerticalSubstitutedGlyphs )
        memset( pHasSubst, 0, sizeof(bool)*nCharacters );
    else
    {
        for( int i = 0; i < nCharacters; i++ )
        {
            sal_Unicode code = pCharacters[i];
            if( ! pFont->m_pMetrics ||
                ! ( pFont->m_pMetrics->m_aPages[ code >> 11 ] & ( 1 << ( ( code >> 8 ) & 7 ) ) ) )
                pFont->queryMetricPage( code >> 8, m_pAtoms );
            ::boost::unordered_map< sal_Unicode, bool >::const_iterator it = pFont->m_pMetrics->m_bVerticalSubstitutions.find( code );
            pHasSubst[i] = it != pFont->m_pMetrics->m_bVerticalSubstitutions.end();
        }
    }
}

// -------------------------------------------------------------------------

const ::std::list< KernPair >& PrintFontManager::getKernPairs( fontID nFontID, bool bVertical ) const
{
    static ::std::list< KernPair > aEmpty;

    PrintFont* pFont = getFont( nFontID );
    if( ! pFont )
        return aEmpty;

    if( ! pFont->m_pMetrics || ! pFont->m_pMetrics->m_bKernPairsQueried )
        pFont->queryMetricPage( 0, m_pAtoms );
    if( ! pFont->m_pMetrics || ! pFont->m_pMetrics->m_bKernPairsQueried )
        return aEmpty;
    return bVertical ? pFont->m_pMetrics->m_aYKernPairs : pFont->m_pMetrics->m_aXKernPairs;
}

// -------------------------------------------------------------------------

bool PrintFontManager::isFontDownloadingAllowed( fontID nFont ) const
{
    static const char* pEnable = getenv( "PSPRINT_ENABLE_TTF_COPYRIGHTAWARENESS" );
    bool bRet = true;

    if( pEnable && *pEnable )
    {
        PrintFont* pFont = getFont( nFont );
        if( pFont && pFont->m_eType == fonttype::TrueType )
        {
            TrueTypeFontFile* pTTFontFile = static_cast<TrueTypeFontFile*>(pFont);
            if( pTTFontFile->m_nTypeFlags & TYPEFLAG_INVALID )
            {
                TrueTypeFont* pTTFont = NULL;
                rtl::OString aFile = getFontFile( pFont );
                if( OpenTTFontFile( aFile.getStr(), pTTFontFile->m_nCollectionEntry, &pTTFont ) == SF_OK )
                {
                    // get type flags
                    TTGlobalFontInfo aInfo;
                    GetTTGlobalFontInfo( pTTFont, & aInfo );
                    pTTFontFile->m_nTypeFlags = (unsigned int)aInfo.typeFlags;
                    CloseTTFont( pTTFont );
                }
            }

            unsigned int nCopyrightFlags = pTTFontFile->m_nTypeFlags & TYPEFLAG_COPYRIGHT_MASK;

            // font embedding is allowed if either
            //   no restriction at all (bit 1 clear)
            //   printing allowed (bit 1 set, bit 2 set )
            bRet = ! ( nCopyrightFlags & 0x02 ) || ( nCopyrightFlags & 0x04 );
        }
    }
    return bRet;
}

// -------------------------------------------------------------------------

bool PrintFontManager::getMetrics( fontID nFontID, const sal_Unicode* pString, int nLen, CharacterMetric* pArray, bool bVertical ) const
{
    PrintFont* pFont = getFont( nFontID );
    if( ! pFont )
        return false;

    if( ( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 )
        || ! pFont->m_pMetrics || pFont->m_pMetrics->isEmpty()
        )
    {
        // might be a font not yet analyzed
        if( pFont->m_eType == fonttype::Type1 || pFont->m_eType == fonttype::Builtin )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, false );
        else if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
    }

    for( int i = 0; i < nLen; i++ )
    {
        if( ! pFont->m_pMetrics ||
            ! ( pFont->m_pMetrics->m_aPages[ pString[i] >> 11 ] & ( 1 << ( ( pString[i] >> 8 ) & 7 ) ) ) )
            pFont->queryMetricPage( pString[i] >> 8, m_pAtoms );
        pArray[i].width = pArray[i].height = -1;
        if( pFont->m_pMetrics )
        {
            int effectiveCode = pString[i];
            effectiveCode |= bVertical ? 1 << 16 : 0;
            ::boost::unordered_map< int, CharacterMetric >::const_iterator it =
                  pFont->m_pMetrics->m_aMetrics.find( effectiveCode );
        // if no vertical metrics are available assume rotated horizontal metrics
        if( bVertical && (it == pFont->m_pMetrics->m_aMetrics.end()) )
                  it = pFont->m_pMetrics->m_aMetrics.find( pString[i] );
        // the character metrics are in it->second
            if( it != pFont->m_pMetrics->m_aMetrics.end() )
                pArray[ i ] = it->second;
        }
    }

    return true;
}

// -------------------------------------------------------------------------

bool PrintFontManager::getMetrics( fontID nFontID, sal_Unicode minCharacter, sal_Unicode maxCharacter, CharacterMetric* pArray, bool bVertical ) const
{
    OSL_PRECOND(minCharacter <= maxCharacter, "invalid char. range");
    if (minCharacter > maxCharacter)
        return false;

    PrintFont* pFont = getFont( nFontID );
    if( ! pFont )
        return false;

    if( ( pFont->m_nAscend == 0 && pFont->m_nDescend == 0 )
        || ! pFont->m_pMetrics || pFont->m_pMetrics->isEmpty()
        )
    {
        // might be a font not yet analyzed
        if( pFont->m_eType == fonttype::Type1 || pFont->m_eType == fonttype::Builtin )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, false, false );
        else if( pFont->m_eType == fonttype::TrueType )
            analyzeTrueTypeFile( pFont );
    }

    sal_Unicode code = minCharacter;
    do
    {
        if( ! pFont->m_pMetrics ||
            ! ( pFont->m_pMetrics->m_aPages[ code >> 11 ] & ( 1 << ( ( code >> 8 ) & 7 ) ) ) )
            pFont->queryMetricPage( code >> 8, m_pAtoms );
        pArray[ code - minCharacter ].width     = -1;
        pArray[ code - minCharacter ].height    = -1;
        if( pFont->m_pMetrics )
        {
            int effectiveCode = code;
            effectiveCode |= bVertical ? 1 << 16 : 0;
            ::boost::unordered_map< int, CharacterMetric >::const_iterator it =
                  pFont->m_pMetrics->m_aMetrics.find( effectiveCode );
            // if no vertical metrics are available assume rotated horizontal metrics
            if( bVertical && (it == pFont->m_pMetrics->m_aMetrics.end()) )
                it = pFont->m_pMetrics->m_aMetrics.find( code );
            // the character metrics are in it->second
            if( it != pFont->m_pMetrics->m_aMetrics.end() )
                pArray[ code - minCharacter ] = it->second;
        }
    } while( code++ != maxCharacter );

    return true;
}

// -------------------------------------------------------------------------

// TODO: move most of this stuff into the central font-subsetting code
bool PrintFontManager::createFontSubset(
                                        FontSubsetInfo& rInfo,
                                        fontID nFont,
                                        const OUString& rOutFile,
                                        sal_Int32* pGlyphIDs,
                                        sal_uInt8* pNewEncoding,
                                        sal_Int32* pWidths,
                                        int nGlyphs,
                                        bool bVertical
                                        )
{
    PrintFont* pFont = getFont( nFont );
    if( !pFont )
        return false;

    switch( pFont->m_eType )
    {
        case psp::fonttype::TrueType: rInfo.m_nFontType = FontSubsetInfo::SFNT_TTF; break;
        case psp::fonttype::Type1: rInfo.m_nFontType = FontSubsetInfo::ANY_TYPE1; break;
        default:
            return false;
    }
    // TODO: remove when Type1 subsetting gets implemented
    if( pFont->m_eType != fonttype::TrueType )
        return false;

    // reshuffle array of requested glyphs to make sure glyph0==notdef
    sal_uInt8  pEnc[256];
    sal_uInt16 pGID[256];
    sal_uInt8  pOldIndex[256];
    memset( pEnc, 0, sizeof( pEnc ) );
    memset( pGID, 0, sizeof( pGID ) );
    memset( pOldIndex, 0, sizeof( pOldIndex ) );
    if( nGlyphs > 256 )
        return false;
    int nChar = 1;
    for( int i = 0; i < nGlyphs; i++ )
    {
        if( pNewEncoding[i] == 0 )
        {
            pOldIndex[ 0 ] = i;
        }
        else
        {
            DBG_ASSERT( !(pGlyphIDs[i] & 0x007f0000), "overlong glyph id" );
            DBG_ASSERT( (int)pNewEncoding[i] < nGlyphs, "encoding wrong" );
            DBG_ASSERT( pEnc[pNewEncoding[i]] == 0 && pGID[pNewEncoding[i]] == 0, "duplicate encoded glyph" );
            pEnc[ pNewEncoding[i] ] = pNewEncoding[i];
            pGID[ pNewEncoding[i] ] = (sal_uInt16)pGlyphIDs[ i ];
            pOldIndex[ pNewEncoding[i] ] = i;
            nChar++;
        }
    }
    nGlyphs = nChar; // either input value or increased by one

    // prepare system name for read access for subset source file
    // TODO: since this file is usually already mmapped there is no need to open it again
    const rtl::OString aFromFile = getFontFile( pFont );

    TrueTypeFont* pTTFont = NULL; // TODO: rename to SfntFont
    TrueTypeFontFile* pTTFontFile = static_cast< TrueTypeFontFile* >(pFont);
    if( OpenTTFontFile( aFromFile.getStr(), pTTFontFile->m_nCollectionEntry, &pTTFont ) != SF_OK )
        return false;

    // prepare system name for write access for subset file target
    OUString aSysPath;
    if( osl_File_E_None != osl_getSystemPathFromFileURL( rOutFile.pData, &aSysPath.pData ) )
        return false;
    const rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
    const rtl::OString aToFile( OUStringToOString( aSysPath, aEncoding ) );

    // do CFF subsetting if possible
    int nCffLength = 0;
    const sal_uInt8* pCffBytes = NULL;
    if( GetSfntTable( pTTFont, O_CFF, &pCffBytes, &nCffLength ) )
    {
        rInfo.LoadFont( FontSubsetInfo::CFF_FONT, pCffBytes, nCffLength );
#if 1 // TODO: remove 16bit->long conversion when related methods handle non-16bit glyphids
        long aRequestedGlyphs[256];
        for( int i = 0; i < nGlyphs; ++i )
            aRequestedGlyphs[i] = pGID[i];
#endif
        // create subset file at requested path
        FILE* pOutFile = fopen( aToFile.getStr(), "wb" );
        // create font subset
        const char* pGlyphSetName = NULL; // TODO: better name?
        const bool bOK = rInfo.CreateFontSubset(
            FontSubsetInfo::TYPE1_PFB,
            pOutFile, pGlyphSetName,
            aRequestedGlyphs, pEnc, nGlyphs, pWidths );
        fclose( pOutFile );
        // cleanup before early return
        CloseTTFont( pTTFont );
        return bOK;
    }

    // do TTF->Type42 or Type3 subsetting
    // fill in font info
    psp::PrintFontInfo aFontInfo;
    if( ! getFontInfo( nFont, aFontInfo ) )
        return false;

    rInfo.m_nAscent     = aFontInfo.m_nAscend;
    rInfo.m_nDescent    = aFontInfo.m_nDescend;
    rInfo.m_aPSName     = getPSName( nFont );

    int xMin, yMin, xMax, yMax;
    getFontBoundingBox( nFont, xMin, yMin, xMax, yMax );
    rInfo.m_aFontBBox   = Rectangle( Point( xMin, yMin ), Size( xMax-xMin, yMax-yMin ) );
    rInfo.m_nCapHeight  = yMax; // Well ...

    // fill in glyph advance widths
    TTSimpleGlyphMetrics* pMetrics = GetTTSimpleGlyphMetrics( pTTFont,
                                                              pGID,
                                                              nGlyphs,
                                                              bVertical ? 1 : 0 );
    if( pMetrics )
    {
        for( int i = 0; i < nGlyphs; i++ )
            pWidths[pOldIndex[i]] = pMetrics[i].adv;
        free( pMetrics );
    }
    else
    {
        CloseTTFont( pTTFont );
        return false;
    }

    bool bSuccess = ( SF_OK == CreateTTFromTTGlyphs( pTTFont,
                                                     aToFile.getStr(),
                                                     pGID,
                                                     pEnc,
                                                     nGlyphs,
                                                     0,
                                                     NULL,
                                                     0 ) );
    CloseTTFont( pTTFont );

    return bSuccess;
}

void PrintFontManager::getGlyphWidths( fontID nFont,
                                       bool bVertical,
                                       std::vector< sal_Int32 >& rWidths,
                                       std::map< sal_Unicode, sal_uInt32 >& rUnicodeEnc )
{
    PrintFont* pFont = getFont( nFont );
    if( !pFont ||
        (pFont->m_eType != fonttype::TrueType && pFont->m_eType != fonttype::Type1) )
        return;
    if( pFont->m_eType == fonttype::TrueType )
    {
        TrueTypeFont* pTTFont = NULL;
        TrueTypeFontFile* pTTFontFile = static_cast< TrueTypeFontFile* >(pFont);
        rtl::OString aFromFile = getFontFile( pFont );
        if( OpenTTFontFile( aFromFile.getStr(), pTTFontFile->m_nCollectionEntry, &pTTFont ) != SF_OK )
            return;
        int nGlyphs = GetTTGlyphCount( pTTFont );
        if( nGlyphs > 0 )
        {
            rWidths.resize(nGlyphs);
            std::vector<sal_uInt16> aGlyphIds(nGlyphs);
            for( int i = 0; i < nGlyphs; i++ )
                aGlyphIds[i] = sal_uInt16(i);
            TTSimpleGlyphMetrics* pMetrics = GetTTSimpleGlyphMetrics( pTTFont,
                                                                      &aGlyphIds[0],
                                                                      nGlyphs,
                                                                      bVertical ? 1 : 0 );
            if( pMetrics )
            {
                for( int i = 0; i< nGlyphs; i++ )
                    rWidths[i] = pMetrics[i].adv;
                free( pMetrics );
                rUnicodeEnc.clear();
            }

            // fill the unicode map
            // TODO: isn't this map already available elsewhere in the fontmanager?
            const sal_uInt8* pCmapData = NULL;
            int nCmapSize = 0;
            if( GetSfntTable( pTTFont, O_cmap, &pCmapData, &nCmapSize ) )
            {
                CmapResult aCmapResult;
                if( ParseCMAP( pCmapData, nCmapSize, aCmapResult ) )
                {
                    const ImplFontCharMap aCharMap( aCmapResult );
                    for( sal_uInt32 cOld = 0;;)
                    {
                        // get next unicode covered by font
                        const sal_uInt32 c = aCharMap.GetNextChar( cOld );
                        if( c == cOld )
                            break;
                        cOld = c;
#if 1 // TODO: remove when sal_Unicode covers all of unicode
                        if( c > (sal_Unicode)~0 )
                            break;
#endif
                        // get the matching glyph index
                        const sal_uInt32 nGlyphId = aCharMap.GetGlyphIndex( c );
                        // update the requested map
                        rUnicodeEnc[ (sal_Unicode)c ] = nGlyphId;
                    }
                }
            }
        }
        CloseTTFont( pTTFont );
    }
    else if( pFont->m_eType == fonttype::Type1 )
    {
        if( ! pFont->m_aEncodingVector.size() )
            pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, true, true );
        if( pFont->m_pMetrics )
        {
            rUnicodeEnc.clear();
            rWidths.clear();
            rWidths.reserve( pFont->m_pMetrics->m_aMetrics.size() );
            for( boost::unordered_map< int, CharacterMetric >::const_iterator it =
                 pFont->m_pMetrics->m_aMetrics.begin();
                 it != pFont->m_pMetrics->m_aMetrics.end(); ++it )
            {
                if( (it->first & 0x00010000) == 0 || bVertical )
                {
                    rUnicodeEnc[ sal_Unicode(it->first & 0x0000ffff) ] = sal_uInt32(rWidths.size());
                    rWidths.push_back( it->second.width );
                }
            }
        }
    }
}

// -------------------------------------------------------------------------

const std::map< sal_Unicode, sal_Int32 >* PrintFontManager::getEncodingMap( fontID nFont, const std::map< sal_Unicode, rtl::OString >** pNonEncoded ) const
{
    PrintFont* pFont = getFont( nFont );
    if( !pFont ||
        (pFont->m_eType != fonttype::Type1 && pFont->m_eType != fonttype::Builtin)
        )
        return NULL;

    if( ! pFont->m_aEncodingVector.size() )
        pFont->readAfmMetrics( getAfmFile( pFont ), m_pAtoms, true, true );

    if( pNonEncoded )
        *pNonEncoded = pFont->m_aNonEncoded.size() ? &pFont->m_aNonEncoded : NULL;

    return pFont->m_aEncodingVector.size() ? &pFont->m_aEncodingVector : NULL;
}

// -------------------------------------------------------------------------

std::list< OString > PrintFontManager::getAdobeNameFromUnicode( sal_Unicode aChar ) const
{
    std::pair< boost::unordered_multimap< sal_Unicode, rtl::OString >::const_iterator,
        boost::unordered_multimap< sal_Unicode, rtl::OString >::const_iterator > range
        =  m_aUnicodeToAdobename.equal_range( aChar );

    std::list< OString > aRet;
    for( ; range.first != range.second; ++range.first )
        aRet.push_back( range.first->second );

    if( aRet.begin() == aRet.end() && aChar != 0 )
    {
        sal_Char aBuf[8];
        sal_Int32 nChars = snprintf( (char*)aBuf, sizeof( aBuf ), "uni%.4hX", aChar );
        aRet.push_back( OString( aBuf, nChars ) );
    }

    return aRet;
}

// -------------------------------------------------------------------------
std::list< sal_Unicode >  PrintFontManager::getUnicodeFromAdobeName( const rtl::OString& rName ) const
{
    std::pair< boost::unordered_multimap< rtl::OString, sal_Unicode, rtl::OStringHash >::const_iterator,
        boost::unordered_multimap< rtl::OString, sal_Unicode, rtl::OStringHash >::const_iterator > range
        =  m_aAdobenameToUnicode.equal_range( rName );

    std::list< sal_Unicode > aRet;
    for( ; range.first != range.second; ++range.first )
        aRet.push_back( range.first->second );

    if( aRet.begin() == aRet.end() )
    {
        if( rName.getLength() == 7 && rName.indexOf( "uni" ) == 0 )
        {
            sal_Unicode aCode = (sal_Unicode)rName.copy( 3 ).toInt32( 16 );
            aRet.push_back( aCode );
        }
    }

    return aRet;
}

// -------------------------------------------------------------------------
namespace
{
    OUString getString( const Any& rAny )
    {
        OUString aStr;
        rAny >>= aStr;
        return aStr;
    }
    bool getBool( const Any& rAny )
    {
        sal_Bool bBool = sal_False;
        rAny >>= bBool;
        return static_cast<bool>(bBool);
    }
    sal_Int32 getInt( const Any& rAny )
    {
        sal_Int32 n = 0;
        rAny >>= n;
        return n;
    }
}
bool PrintFontManager::readOverrideMetrics()
{
    if( ! m_aOverrideFonts.empty() )
        return false;

    css::uno::Reference< XMultiServiceFactory > xFact( comphelper::getProcessServiceFactory() );
    if( !xFact.is() )
        return false;
    css::uno::Reference< XMaterialHolder > xMat(
                xFact->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.psprint.CompatMetricOverride" ) ) ),
                UNO_QUERY );
    if( !xMat.is() )
        return false;

    Any aAny( xMat->getMaterial() );
    Sequence< Any > aOverrideFonts;
    if( ! (aAny >>= aOverrideFonts ) )
        return false;
    sal_Int32 nFonts = aOverrideFonts.getLength();
    for( sal_Int32 i = 0; i < nFonts; i++ )
    {
        Sequence< NamedValue > aMetrics;
        if( ! (aOverrideFonts.getConstArray()[i] >>= aMetrics) )
            continue;
        BuiltinFont* pFont = new BuiltinFont();
        pFont->m_nDirectory = 0;
        pFont->m_bUserOverride = false;
        pFont->m_pMetrics = new PrintFontMetrics;
        memset( pFont->m_pMetrics->m_aPages, 0xff, sizeof( pFont->m_pMetrics->m_aPages ) );
        pFont->m_pMetrics->m_bKernPairsQueried = true;
        sal_Int32 nProps = aMetrics.getLength();
        const NamedValue* pProps = aMetrics.getConstArray();
        for( sal_Int32 n = 0; n < nProps; n++ )
        {
            if ( pProps[n].Name == "FamilyName" )
                pFont->m_nFamilyName = m_pAtoms->getAtom( ATOM_FAMILYNAME,
                                                          getString(pProps[n].Value),
                                                          sal_True );
            else if ( pProps[n].Name == "PSName" )
                pFont->m_nPSName = m_pAtoms->getAtom( ATOM_PSNAME,
                                                      getString(pProps[n].Value),
                                                      sal_True );
            else if ( pProps[n].Name == "StyleName" )
                pFont->m_aStyleName = getString(pProps[n].Value);
            else if ( pProps[n].Name == "Italic" )
                pFont->m_eItalic = static_cast<FontItalic>(getInt(pProps[n].Value));
            else if ( pProps[n].Name == "Width" )
                pFont->m_eWidth = static_cast<FontWidth>(getInt(pProps[n].Value));
            else if ( pProps[n].Name == "Weight" )
                pFont->m_eWeight = static_cast<FontWeight>(getInt(pProps[n].Value));
            else if ( pProps[n].Name == "Pitch" )
                pFont->m_ePitch = static_cast<FontPitch>(getInt(pProps[n].Value));
            else if ( pProps[n].Name == "Encoding" )
                pFont->m_aEncoding = static_cast<rtl_TextEncoding>(getInt(pProps[n].Value));
            else if ( pProps[n].Name == "FontEncodingOnly" )
                pFont->m_bFontEncodingOnly = getBool(pProps[n].Value);
            else if ( pProps[n].Name == "GlobalMetricXWidth" )
                pFont->m_aGlobalMetricX.width = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "GlobalMetricXHeight" )
                pFont->m_aGlobalMetricX.height = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "GlobalMetricYWidth" )
                pFont->m_aGlobalMetricY.width = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "GlobalMetricYHeight" )
                pFont->m_aGlobalMetricY.height = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "Ascend" )
                pFont->m_nAscend = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "Descend" )
                pFont->m_nDescend = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "Leading" )
                pFont->m_nLeading = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "XMin" )
                pFont->m_nXMin = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "YMin" )
                pFont->m_nYMin = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "XMax" )
                pFont->m_nXMax = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "YMax" )
                pFont->m_nYMax = getInt(pProps[n].Value);
            else if ( pProps[n].Name == "VerticalSubstitutes" )
                pFont->m_bHaveVerticalSubstitutedGlyphs = getBool(pProps[n].Value);
            else if ( pProps[n].Name == "EncodingVector" )
            {
                Sequence< NamedValue > aEncoding;
                pProps[n].Value >>= aEncoding;
                sal_Int32 nEnc = aEncoding.getLength();
                const NamedValue* pEnc = aEncoding.getConstArray();
                for( sal_Int32 m = 0; m < nEnc; m++ )
                {
                    sal_Unicode cCode = *pEnc[m].Name.getStr();
                    sal_Int32 nGlyph = getInt(pEnc[m].Value);
                    pFont->m_aEncodingVector[ cCode ] = nGlyph;
                }
            }
            else if ( pProps[n].Name == "NonEncoded" )
            {
                Sequence< NamedValue > aEncoding;
                pProps[n].Value >>= aEncoding;
                sal_Int32 nEnc = aEncoding.getLength();
                const NamedValue* pEnc = aEncoding.getConstArray();
                for( sal_Int32 m = 0; m < nEnc; m++ )
                {
                    sal_Unicode cCode = *pEnc[m].Name.getStr();
                    OUString aGlyphName( getString(pEnc[m].Value) );
                    pFont->m_aNonEncoded[ cCode ] = OUStringToOString(aGlyphName,RTL_TEXTENCODING_ASCII_US);
                }
            }
            else if ( pProps[n].Name == "CharacterMetrics" )
            {
                // fill pFont->m_pMetrics->m_aMetrics
                // expect triples of int: int -> CharacterMetric.{ width, height }
                Sequence< sal_Int32 > aSeq;
                pProps[n].Value >>= aSeq;
                sal_Int32 nInts = aSeq.getLength();
                const sal_Int32* pInts = aSeq.getConstArray();
                for( sal_Int32 m = 0; m < nInts; m+=3 )
                {
                    pFont->m_pMetrics->m_aMetrics[ pInts[m] ].width = static_cast<short int>(pInts[m+1]);
                    pFont->m_pMetrics->m_aMetrics[ pInts[m] ].height = static_cast<short int>(pInts[m+2]);
                }
            }
            else if ( pProps[n].Name == "XKernPairs" )
            {
                // fill pFont->m_pMetrics->m_aXKernPairs
                // expection name: <unicode1><unicode2> value: ((height << 16)| width)
                Sequence< NamedValue > aKern;
                pProps[n].Value >>= aKern;
                KernPair aPair;
                const NamedValue* pVals = aKern.getConstArray();
                int nPairs = aKern.getLength();
                for( int m = 0; m < nPairs; m++ )
                {
                    if( pVals[m].Name.getLength() == 2 )
                    {
                        aPair.first = pVals[m].Name.getStr()[0];
                        aPair.second = pVals[m].Name.getStr()[1];
                        sal_Int32 nKern = getInt( pVals[m].Value );
                        aPair.kern_x = static_cast<short int>(nKern & 0xffff);
                        aPair.kern_y = static_cast<short int>((sal_uInt32(nKern) >> 16) & 0xffff);
                        pFont->m_pMetrics->m_aXKernPairs.push_back( aPair );
                    }
                }
            }
        }
        // sanity check
        if( pFont->m_nPSName                        &&
            pFont->m_nFamilyName                    &&
            ! pFont->m_pMetrics->m_aMetrics.empty() )
        {
            m_aOverrideFonts.push_back( m_nNextFontID );
            m_aFonts[ m_nNextFontID++ ] = pFont;
        }
        else
        {
            DBG_ASSERT( 0, "override font failed" );
            delete pFont;
        }
    }

    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */