File: fapiufst.c

package info (click to toggle)
ghostscript 9.06~dfsg-2%2Bdeb8u7
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 62,484 kB
  • sloc: ansic: 440,074; python: 4,915; cpp: 3,565; sh: 2,520; tcl: 1,482; perl: 1,374; makefile: 421; lisp: 407; awk: 66; yacc: 18
file content (1781 lines) | stat: -rw-r--r-- 61,649 bytes parent folder | download | duplicates (2)
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
/* Copyright (C) 2001-2012 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134, San Rafael,
   CA  94903, U.S.A., +1(415)492-9861, for further information.
*/


/* Agfa UFST plugin */

/* GS includes : */
#include "stdio_.h"
#include "stream.h"
#include "strmio.h"

#include "memory_.h"
#include "gsmemory.h"
#include "math_.h"
#include "stat_.h" /* include before definition of esp macro, bug 691123 */
#include "ghost.h"
#include "gp.h"
#include "oper.h"
#include "gxdevice.h"
#include "gxfont.h"
#include "gxfont1.h"
#include "gxchar.h"
#include "gxpath.h"
#include "gxfcache.h"
#include "gxchrout.h"
#include "gximask.h"
#include "gscoord.h"
#include "gspaint.h"
#include "gsfont.h"
#include "gspath.h"
#include "bfont.h"
#include "dstack.h"
#include "estack.h"
#include "ichar.h"
#include "idict.h"
#include "iname.h"
#include "ifont.h"
#include "icid.h"
#include "igstate.h"
#include "icharout.h"
#include "ifapi.h"
#include "iplugin.h"
#include "store.h"
#include "gzstate.h"
#include "gdevpsf.h"
#include "stream.h"		/* for files.h */
#include "gscrypt1.h"
#include "gxfcid.h"
#include "gsstype.h"
#include "gxchar.h"		/* for st_gs_show_enum */
#include "ipacked.h"	    /* for packed_next */
#include "iddict.h"
#include "ifont42.h"        /* for string_array_access_proc */
#include "gsmalloc.h"
#include "gsmchunk.h"

#undef frac_bits

#ifndef _MSC_VER
#define _MSC_VER 0
#endif

/* UFST includes : */
#include "cgconfig.h"
#include "ufstport.h"
#include "dbg_ufst.h"
#include "shareinc.h"
#include "t1isfnt.h"
#include "cgmacros.h"
#include "sfntenum.h"
#define DOES_ANYONE_USE_THIS_STRUCTURE /* see TTPCLEO.H, UFST 4.2 */
#include "ttpcleo.h"
#undef  DOES_ANYONE_USE_THIS_STRUCTURE
#include "gxfapiu.h"

/* more gs includes */
#include "iref.h"
#include "ialloc.h"
#include "imemory.h"
#include "iname.h"
#include "iapi.h"
#include "iminst.h"
#include "imain.h"
#include "igstate.h"
#include "idict.h"
#include "dstack.h"
#include "store.h"

#if UFST_VERSION_MAJOR >= 6 && UFST_VERSION_MINOR >= 2
#include "t1itype1.h"
#endif

#if UFST_VERSION_MAJOR >= 6 && UFST_VERSION_MINOR >= 2
#undef true
#undef false

#define false FALSE
#define true TRUE
#define UNICODE UFST_UNICODE
#endif

#ifndef UFSTFONTDIR
#define UFSTFONTDIR ""
#endif

#define UFST_PlugIn_Str "UFST_PlugIn"
#define UFST_PlugIn_Path "mtfonts/pcl45/mt3/plug__xi.fco"

#define FCOfontfilePath "mtfonts/pclps2/mt3/pclp2_xj.fco"
#define FCOfontfileStr "FCOfontfile"

#define FCOfontfile2Str "FCOfontfile2"
#define FCOfontfile2Path "mtfonts/pcl45/mt3/wd____xh.fco"

#define FAPIfontmapStr  "FAPIfontmap"
#define FAPIfontmap  "FCOfontmap-PCLPS2"

/* Prior to 6.2, prototypes had empty parameter lists, causing problems
 * when passing 64 bit pointers into the UFST functions.
 * Prototype "properly" here.
 */
#if UFST_VERSION_MAJOR < 6
#if defined (ANSI_DEFS)
UW16 CGENTRY CGIFFfont (FSP PFONTCONTEXT fc);
#else
UW16 CGENTRY CGIFFfont (fc);
    PFONTCONTEXT  fc;
#endif /* ANSI_DEFS */
#endif

typedef struct fapi_ufst_server_s fapi_ufst_server;

static unsigned int font_ids = 0x7fffffff;

#if UFST_REENTRANT
#define FSA_FROM_SERVER IF_STATE *pIFS = &r->IFS
#else
EXTERN IF_STATE if_state;
#define FSA_FROM_SERVER IF_STATE *pIFS = &if_state;    (void)r; (void)pIFS;
static fapi_ufst_server *static_server_ptr_for_ufst_callback = 0;
#endif

GLOBAL UW16  PCLswapHdr( FSP LPUB8 p, UW16 gifct ); /* UFST header doesn't define it. */

typedef struct pcleo_glyph_list_elem_s pcleo_glyph_list_elem;
struct pcleo_glyph_list_elem_s {
    UW16 chId;
    pcleo_glyph_list_elem *next;
    /* more data follows here depending on font type */
};

typedef struct {
    SL32 font_id;
    uint tt_font_body_offset;
    UW16 is_disk_font;
    UW16 font_type;
    UW16 platformId;
    UW16 specificId;
    pcleo_glyph_list_elem *glyphs;
    char decodingID[40];
} ufst_common_font_data;

typedef struct {
    PCLETTO_CHR_HDR h;
    UW16   add_data;
    UW16   charDataSize;
    UW16   glyphID;
} PCLETTO_CHDR;

struct fapi_ufst_server_s {
    FAPI_server If;
    int bInitialized;
    FAPI_font *ff;
    gs_memory_t *mem;
    byte *param;
    int param_size;
    IF_STATE IFS;
    FONTCONTEXT fc;
    void *char_data;
    bool bRaster;
    bool ufst_is_singleton;
    double tran_xx, tran_xy, tran_yx, tran_yy;
    fco_list_elem *fco_list;
    FAPI_retcode callback_error;
    FAPI_metrics_type metrics_type;
    FracInt sb_x, aw_x; /* replaced PS metrics. */
};

static inline void release_char_data_inline(fapi_ufst_server *r);
static void release_glyphs(fapi_ufst_server *r, ufst_common_font_data *d);

/* Type casts : */

static inline fapi_ufst_server *If_to_I(FAPI_server *If)
{   return (fapi_ufst_server *)If;
}

static inline fapi_ufst_server *IFS_to_I(IF_STATE *pIFS)
{   return (fapi_ufst_server *)((char *)pIFS - offset_of(fapi_ufst_server, IFS));
}

/* assign font_id not based on fchandle value, nor read from font */
static inline int assign_font_id(void)
{
    /* We're only allowed 5 open FCOs at one time
     * so make sure we don't clash with those
     */
     if ((--font_ids) <= (5 << 16)) {
         /* When we clash with the expected values for FCO's
          * wrap around. No will ever have enough concurrent
          * fonts for this to be a problem!
          */
         font_ids = 0x7fffffff;
     }
     return(font_ids);
}

/*------------------ FAPI_server members ------------------------------------*/

static inline void release_char_data_inline(fapi_ufst_server *r)
{   /*  The server keeps character raster between calls to get_char_raster_metrics
        and get_char_raster, as well as between calls to get_char_outline_metrics
        and get_char_outline. Meanwhile this regular
        sequence of calls may be interrupted by an error in CDefProc or setchachedevice2,
        which may be invoked between them. In this case Ghostscript
        is unable to provide a signal to FAPI that the data are not
        longer needed. This would cause memory leaks in UFST heap.
        To work around this, appropriate server's entries check whether
        raster data were left after a previous call, and ultimately release them.
        This function provides it.
    */
    if (r->char_data != NULL) {
        FSA_FROM_SERVER;

        CHARfree(FSA (MEM_HANDLE)r->char_data);
        r->char_data = 0;
    }
}

/*
 * In the language switch build (which we detect because PSI_INCLUDED
 * is defined), we use the gx_UFST_init() call to initialize the UFST,
 * rather than calling into the UFST directly. That has the advantage
 * that the same UFST configuration is used for PCL and PS, but the
 * disadvantage that the dynamic parameters set in server_param are
 * not available. Thus, it is switched through this compile time option.
*/
static FAPI_retcode open_UFST(fapi_ufst_server *r, const byte *server_param, int server_param_size)
{
    int code;
    SW16 fcHandle;
    int l;
    char ufst_root_dir[1024] = "";
    char sPlugIn[1024] = "";
    bool bSSdir = FALSE, bPlugIn = FALSE;
    const char *keySSdir = "UFST_SSdir=";
    const int keySSdir_length = strlen(keySSdir);
    const char *keyPlugIn = "UFST_PlugIn=";
    const int keyPlugIn_length = strlen(keyPlugIn);
    const char sep = gp_file_name_list_separator;
    const byte *p = server_param, *e = server_param + server_param_size, *q;
    FSA_FROM_SERVER;

    if (server_param_size > 0 && server_param) {
        r->param = (byte *)gs_malloc(r->mem, server_param_size, 1, "server_params");
        if (!r->param) {
            return_error (e_VMerror);
        }
        memcpy(r->param, server_param, server_param_size);
        r->param_size = server_param_size;
    }

    for (; p < e ; p = q + 1) {
        for (q = p; q < e && *q != sep; q++)
            /* DO_NOTHING */;
        l = q - p;
        if (l > keySSdir_length && !memcmp(p, keySSdir, keySSdir_length)) {
            l = q - p - keySSdir_length;
            if (l > sizeof(ufst_root_dir) - 1)
                l = sizeof(ufst_root_dir) - 1;
            memcpy(ufst_root_dir, p + keySSdir_length, l);
            ufst_root_dir[l] = 0;
            bSSdir = TRUE;
        } else if (l > keyPlugIn_length && !memcmp(p, keyPlugIn, keyPlugIn_length)) {
            l = q - p - keyPlugIn_length;
            if (l > sizeof(sPlugIn) - 1)
                l = sizeof(sPlugIn) - 1;
            memcpy(sPlugIn, p + keyPlugIn_length, l);
            sPlugIn[l] = 0;
            bPlugIn = TRUE;
        } else
            emprintf(r->mem,
                     "Warning: Unknown UFST parameter ignored.\n");
    }
#if !NO_SYMSET_MAPPING
    if (!bSSdir) {
        strcpy(ufst_root_dir, ".");
        emprintf(r->mem,
                 "Warning: UFST_SSdir is not specified, will search *.ss files in the curent directory.\n");
    }
#endif
    code = gx_UFST_init(r->mem, (const UB8 *)ufst_root_dir);
    if (code < 0)
        return code;
    r->ufst_is_singleton = (code == 1);
    CGIFfont_access (FSA DISK_ACCESS);
    if (bPlugIn) {
        if ((code = gx_UFST_open_static_fco(sPlugIn, &fcHandle)) != 0)
            return code;
        if ((code = CGIFfco_Plugin(FSA fcHandle)) != 0)
            return code;
    } else {
#ifdef FCO_RDR
        emprintf(r->mem,
                 "Warning: UFST_PlugIn is not specified, some characters may be missing.\n");
#endif
    }
    return 0;
}

static LPUB8 impl_PCLchId2ptr(FSP UW16 chId);

static FAPI_retcode ensure_open(FAPI_server *server, const byte *server_param, int server_param_size)
{   fapi_ufst_server *r = If_to_I(server);
    int code;

    if (r->bInitialized)
        return 0;
    r->bInitialized = 1;
    {
        code = open_UFST(r, server_param, server_param_size);
        if (code < 0) {
            emprintf(r->mem, "Error opening the UFST font server.\n");
            return code;
        }
    }
    gx_set_UFST_Callbacks(NULL, impl_PCLchId2ptr, impl_PCLchId2ptr);
    return 0;
}

static UW16 get_font_type(stream *f)
{   char buf[20], mark_PS[]="%!";
    int i;

    if (sfread(buf, 1, sizeof(buf), f) != sizeof(buf))
        return 0;
    if (buf[0] == 0x15 || buf[0] == 0x00) /* fixme : don't know how to do correctly. */
        return FC_FCO_TYPE;
    for (i = 0; i < sizeof(buf) - sizeof(mark_PS); i++)
        if(!memcmp(buf + i, mark_PS, sizeof(mark_PS) - 1))
            return FC_PST1_TYPE;
    if (buf[0] == '\0' && buf[1] == '\1')
        return FC_TT_TYPE;
    if (buf[0] == 't' && buf[1] == 't')
        return FC_TT_TYPE;
    return 0; /* fixme : unknown type - actually an error. */
}

static int choose_decoding_general(fapi_ufst_server *r, ufst_common_font_data *d, const char *cmapId)
{
    if (!d->decodingID[0])
        strncpy(d->decodingID, "Unicode", sizeof(d->decodingID));
    /*    fixme : must depend on charset used in the font.  */
    return 1;
}

static int choose_decoding_TT(fapi_ufst_server *r, ufst_common_font_data *d, const char *cmapId)
{
#if TT_ROM || TT_DISK
    int platId, specId, i;
    CMAP_QUERY q;
    UW16 font_access;
    bool failed;
    void *p = (d->is_disk_font ? (void *)(d + 1) : (void *)((UB8 *)d + d->tt_font_body_offset));
    FSA_FROM_SERVER;

    if (sscanf(cmapId, "%d.%d", &platId, &specId) != 2)
        return 0;
    font_access = pIFS->font_access;
    pIFS->font_access = (d->is_disk_font ? DISK_ACCESS : ROM_ACCESS);
    failed = CGIFtt_cmap_query(FSA p, r->fc.ttc_index, &q);
    pIFS->font_access = font_access;
    if(failed)
        return 0;
    for (i = 0; i < q.numCmap; i++)
        if (q.entry[i].platId == platId && q.entry[i].specId == specId) {
            d->platformId = platId;
            d->specificId = specId;
            return 1;
        }
    return 0;
#else
    if (!d->decodingID[0])
        strncpy(d->decodingID, "Unicode", sizeof(d->decodingID));
    return 1;
#endif
}

static void scan_xlatmap(fapi_ufst_server *r, ufst_common_font_data *d, const char *xlatmap, const char *font_kind,
                                    int (*choose_proc)(fapi_ufst_server *r, ufst_common_font_data *d, const char *cmapId))
{   const char *p = xlatmap;

    while(*p) {
        int good_kind =!strcmp(p, font_kind);
        p += strlen(p) + 2;
        while(*p) {
            const char *cmapId = p, *decodingID = p + strlen(p) + 1;
            strncpy(d->decodingID, decodingID, sizeof(d->decodingID));
            if (!decodingID[0])
                break;
            p = decodingID + strlen(decodingID) + 1;
            if (good_kind)
                if (choose_proc(r, d, cmapId))
                    return;
        }
    }
    d->decodingID[0] = 0;
}

static void choose_decoding(fapi_ufst_server *r, ufst_common_font_data *d, const char *xlatmap)
{   if (xlatmap != 0)
        switch (d->font_type) {
            case FC_IF_TYPE: /* fixme */ break;
            case FC_PST1_TYPE: scan_xlatmap(r, d, xlatmap, "PostScript", choose_decoding_general); break;
            case FC_TT_TYPE:   scan_xlatmap(r, d, xlatmap, "TrueType", choose_decoding_TT); break;
            case FC_FCO_TYPE:  scan_xlatmap(r, d, xlatmap, "Microtype", choose_decoding_general); break;
        }
}

static inline void store_word(byte **p, ushort w)
{   *((*p)++) = w / 256;
    *((*p)++) = w % 256;

}

static LPUB8 get_TT_glyph(fapi_ufst_server *r, FAPI_font *ff, UW16 chId)
{   pcleo_glyph_list_elem *g;
    PCLETTO_CHDR *h;
    ufst_common_font_data *d = (ufst_common_font_data *)r->fc.font_hdr - 1;
    LPUB8 q;
    ushort glyph_length = ff->get_glyph(ff, chId, 0, 0);
    bool use_XL_format = ff->is_mtx_skipped;

    /*
     * The client must set ff->is_mtx_skipped iff
     * it requests a replaced lsb for True Type.
     * If it is set, a replaced width to be supplied.
     * This constraint is derived from UFST restriction :
     * the font header format must be compatible with
     * glyph header format.
     */

    if (glyph_length == (ushort)-1) {
        r->callback_error = e_invalidfont;
        return 0;
    }
    g = (pcleo_glyph_list_elem *)gs_malloc(r->mem,
            sizeof(pcleo_glyph_list_elem) +
            (use_XL_format ? 12 : sizeof(PCLETTO_CHDR)) + glyph_length + 2, 1,
            "PCLETTO char");
    if (g == 0) {
        r->callback_error = e_VMerror;
        return 0;
    }
    g->chId = chId;
    g->next = d->glyphs;
    d->glyphs = g;
    h = (PCLETTO_CHDR *)(g + 1);
    h->h.format = 15;
    if (use_XL_format) {
        h->h.continuation = 2;
        q = (LPUB8)h + 2;
        store_word(&q, (ushort)(glyph_length + 10));
        store_word(&q, (ushort)(r->sb_x >> r->If.frac_shift)); /* see can_replace_metrics */
        store_word(&q, (ushort)(r->aw_x >> r->If.frac_shift));
        store_word(&q, 0);
        store_word(&q, chId);
    } else {
        h->h.continuation = 0;
        h->h.descriptorsize = 4;
        h->h.ch_class = 15;
        h->add_data = 0;
        q = (LPUB8)&h->charDataSize;
        store_word(&q, (ushort)(glyph_length + 4));
        store_word(&q, chId);
    }
    if (ff->get_glyph(ff, chId, (LPUB8)q, glyph_length) == (ushort)-1) {
        r->callback_error = e_invalidfont;
        return 0;
    }
    q += glyph_length;
    store_word(&q, 0); /* checksum */
    return (LPUB8)h;
    /*
     * The metrics replacement here is done only for the case
     * corresponding to non-disk TT fonts with MetricsCount != 0;
     * Other cases are not supported because UFST cannot handle them.
     * Here we don't take care of cases which can_replace_metrics rejects.
     *
     * We don't care of metrics for subglyphs, because
     * it is ignored by TT interpreter.
     */
}

static LPUB8 get_T1_glyph(fapi_ufst_server *r, FAPI_font *ff, UW16 chId)
{
#if PST1_SFNTI
#if UFST_VERSION_MAJOR >= 6 && UFST_VERSION_MINOR >= 2
    ushort glyph_length = ff->get_glyph(ff, chId, 0, 0);
    CDATASTR charstring;
    PCDATASTR_DEMO pcharstring;
    byte *cstring;
    ufst_common_font_data *d = (ufst_common_font_data *)r->fc.font_hdr - 1;
    MEM_HANDLE hndl;
    FSA_FROM_SERVER;

    d->glyphs = NULL;

    charstring.len = glyph_length;
    charstring.hdata = BUFalloc(charstring.len);
    if (!charstring.hdata)
    {
        r->callback_error = e_VMerror;
        return (NULL);
    }

    cstring = (unsigned char *)MEMptr(charstring.hdata);

    if (ff->get_glyph(ff, chId, cstring, glyph_length) != glyph_length)
    {
        r->callback_error = e_VMerror;
        BUFfree(charstring.hdata);
        return (NULL);
    }

    hndl = BUFalloc (FSA (SL32)(sizeof (CDATASTR)));
    if (!hndl)
    {
        r->callback_error = e_VMerror;
        BUFfree(charstring.hdata);
        return (NULL);
    }

    pcharstring = (PCDATASTR_DEMO)MEMptr(hndl);

    pcharstring->len = charstring.len; /* Datalen */
    pcharstring->hdata = charstring.hdata;
    pcharstring->decrypted = 1;

    return ((LPUB8) pcharstring);
#else
    ushort glyph_length = ff->get_glyph(ff, chId, 0, 0);
    LPUB8 q;
    pcleo_glyph_list_elem *g = (pcleo_glyph_list_elem *)gs_malloc(r->mem,
                    sizeof(pcleo_glyph_list_elem) + sizeof(PS_CHAR_HDR) + 2 + 2 + glyph_length + 1, 1, "PSEO char");
    PS_CHAR_HDR *h;
    ufst_common_font_data *d = (ufst_common_font_data *)r->fc.font_hdr - 1;
    FSA_FROM_SERVER;

    if (g == 0 || glyph_length == (ushort)-1) {
        r->callback_error = e_invalidfont;
        return 0;
    }
    g->chId = chId;
    g->next = d->glyphs;
    d->glyphs = g;
    h = (PS_CHAR_HDR *)(g + 1);
    h->format = 30;           /* raster=4, DJ=5, IF=10, TT=15, PS=30 */
    h->continuation = 0;     /* always 0 */
    h->descriptorsize = 2;   /* always 2 */
    h->ch_class = 11;           /* contour=3, compound=4, tt=10, ps=11 */
    h->len = 0;              /* # of bytes to follow (not including csum) */
    q = (byte *)h + sizeof(*h);
    /* A workaround for UFST4.6 bug in t1idecod.c (UNPACK_WORD uses pIFS->ph instead ph) :
       setting Namelen=4, rather normally it must be 0. */
    q[0] = 0; /* Namelen */
    q[1] = 4; /* Namelen */
    q[2] = (glyph_length) / 256; /* Datalen */
    q[3] = (glyph_length) % 256; /* Datalen */
    /* Glyph name goes here, but we don't use it. */
    q += 4;
    glyph_length = ff->get_glyph(ff, chId, q, glyph_length);
    q += glyph_length;
    *q = 1; /* Decrypt flag */
    pIFS->ph = (byte *)h + sizeof(*h); /* A workaround for UFST4.6 bug in t1idecod.c (UNPACK_WORD uses pIFS->ph instead ph) */
    return (LPUB8)h;
#endif
#else
    return 0;
#endif
}

static pcleo_glyph_list_elem * find_glyph(ufst_common_font_data *d, UW16 chId)
{   pcleo_glyph_list_elem *e;

    for (e = d->glyphs; e != 0; e = e->next)
        if (e->chId == chId)
            return e;
    return 0;
}

/* UFST callback : */
static LPUB8 impl_PCLchId2ptr(FSP UW16 chId)
{
#if UFST_REENTRANT
    fapi_ufst_server *r = IFS_to_I(pIFS);
#else
    fapi_ufst_server *r = static_server_ptr_for_ufst_callback;
#endif
    FAPI_font *ff = r->ff;
    ufst_common_font_data *d = (ufst_common_font_data *)r->fc.font_hdr - 1;
    pcleo_glyph_list_elem *g = find_glyph(d, chId);
    LPUB8 result = 0;

    if (g != 0)
        result = (LPUB8)(g + 1);
    if ((r->fc.format & FC_FONTTYPE_MASK) == FC_PST1_TYPE)
        result = get_T1_glyph(r, ff, chId);
    if ((r->fc.format & FC_FONTTYPE_MASK) == FC_TT_TYPE)
        result = get_TT_glyph(r, ff, chId);
    return result;
}

static inline void pack_word(LPUB8 *p, UW16 v)
{   LPUB8 q = (LPUB8)&v;

#if (BYTEORDER == LOHI) /* defied in UFST includes */
         (*p)[1] = q[0];
         (*p)[0] = q[1];
#else
        *(UW16 *)(*p) = v;
#endif
    *p += 2;
}

static inline void pack_long(LPUB8 *p, UL32 v)
{   LPUB8 q = (LPUB8)&v;

#if (BYTEORDER == LOHI) /* defied in UFST includes */
         (*p)[3] = q[0];
         (*p)[2] = q[1];
         (*p)[1] = q[2];
         (*p)[0] = q[3];
#else
        *(UL32 *)(*p) = v;
#endif
    *p += 4;
}

static inline void pack_float(LPUB8 *p, float v)
{   sprintf((char *)(*p), "%f", v);
    *p += strlen((const char *)*p) + 1;
}

#define PACK_ZERO(p) *(p++) = 0
#define PACK_BYTE(p, c) *(p++) = c
#define PACK_WORD(p, i, var) pack_word(&p, ff->get_word(ff, var, i))
#define PACK_LONG(p, i, var) pack_long(&p, ff->get_long(ff, var, i))

static void pack_pseo_word_array(fapi_ufst_server *r, FAPI_font *ff, UB8 **p,
                                  UW16 max_count, fapi_font_feature count_id, fapi_font_feature array_id)
{   UW16 k = min(ff->get_word(ff, count_id, 0), max_count), j;

    pack_word(p, k);
    for (j = 0; j < k; j++)
        PACK_WORD(*p, j, array_id);
    for (; j < max_count; j++)
        pack_word(p, 0);
}

static void pack_pseo_fhdr(fapi_ufst_server *r, FAPI_font *ff, UB8 *p)
{   ushort j, n, skip = 0;

    while (((uint64_t)p) & 0x03) /* align to QUADWORD */
        PACK_ZERO(p);
    pack_long(&p, 1);  /* format = 1 */
    for (j = 0; j < 6; j++)
        pack_float(&p, ff->get_float(ff, FAPI_FONT_FEATURE_FontMatrix, j));
    while (((uint64_t)p) & 0x03) /* align to QUADWORD */
        PACK_ZERO(p);
    /* UFST has no definition for PSEO structure, so implement serialization : */
    PACK_LONG(p, 0, FAPI_FONT_FEATURE_UniqueID);
    PACK_LONG(p, 0, FAPI_FONT_FEATURE_BlueScale);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_Weight);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_ItalicAngle);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_IsFixedPitch);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_UnderLinePosition);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_UnderlineThickness);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_FontType);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_FontBBox);
    PACK_WORD(p, 1, FAPI_FONT_FEATURE_FontBBox);
    PACK_WORD(p, 2, FAPI_FONT_FEATURE_FontBBox);
    PACK_WORD(p, 3, FAPI_FONT_FEATURE_FontBBox);
    pack_pseo_word_array(r, ff, &p, 14, FAPI_FONT_FEATURE_BlueValues_count, FAPI_FONT_FEATURE_BlueValues);
    pack_pseo_word_array(r, ff, &p, 10, FAPI_FONT_FEATURE_OtherBlues_count, FAPI_FONT_FEATURE_OtherBlues);
    pack_pseo_word_array(r, ff, &p, 14, FAPI_FONT_FEATURE_FamilyBlues_count, FAPI_FONT_FEATURE_FamilyBlues);
    pack_pseo_word_array(r, ff, &p, 10, FAPI_FONT_FEATURE_FamilyOtherBlues_count, FAPI_FONT_FEATURE_FamilyOtherBlues);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_BlueShift);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_BlueFuzz);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_StdHW);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_StdVW);
    pack_pseo_word_array(r, ff, &p, 12, FAPI_FONT_FEATURE_StemSnapH_count, FAPI_FONT_FEATURE_StemSnapH);
    pack_pseo_word_array(r, ff, &p, 12, FAPI_FONT_FEATURE_StemSnapV_count, FAPI_FONT_FEATURE_StemSnapV);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_ForceBold);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_LanguageGroup);
    PACK_WORD(p, 0, FAPI_FONT_FEATURE_lenIV);
    for (j = 0; j < 12; j++)
        PACK_ZERO(p), PACK_ZERO(p);     /* Reserved2 */
    /* max data size = 107 words + 6 floats in ASCII */
    n = ff->get_word(ff, FAPI_FONT_FEATURE_Subrs_count, 0);
    pack_word(&p, n);
    for (j = 0; j < n; j++) {
        ushort subr_len = ff->get_subr(ff, j, 0, 0);
        if (subr_len != 0) {
            pack_word(&p, j);
            pack_word(&p, subr_len);
            PACK_BYTE(p, 1); /* is_decrypted */
            ff->get_subr(ff, j, p, subr_len);
            p += subr_len;
        } else
            skip = 1;
    }
    n = ff->get_word(ff, FAPI_FONT_FEATURE_GlobalSubrs_count, 0);
    /* get_word() doesn't have an error return value, so I've used an unlikely value */
    if (n != 65535) {
        pack_word(&p, n);
        for (j = 0; j < n; j++) {
            ushort subr_len = ff->get_gsubr(ff, j, 0, 0);
            if (subr_len != 0) {
                pack_word(&p, j);
                pack_word(&p, subr_len);
                PACK_BYTE(p, 1); /* is_decrypted */
                ff->get_gsubr(ff, j, p, subr_len);
                p += subr_len;
            } else
                skip = 1;
        }
    }
    if (skip)
        pack_word(&p, 0xFFFF);
}

static char *my_strdup(fapi_ufst_server *r, const char *s, const char *cname)
{   int len = strlen(s) + 1;
    char *p = (char *)gs_malloc(r->mem, len, 1, cname);

    if (p != 0)
        memcpy(p, s, len);
    return p;
}

static FAPI_retcode fco_open(fapi_ufst_server *r, const char *font_file_path, fco_list_elem **result)
{   int code;
    fco_list_elem *e = gx_UFST_find_static_fco(font_file_path);

    if (e != NULL) {
        *result = e;
        return 0;
    }
    for (e = r->fco_list; e != 0; e = e->next) {
        if (!strcmp(e->file_path, font_file_path))
            break;
    }
    if (e == 0) {
        SW16 fcHandle;
        FSA_FROM_SERVER;

        if ((code = CGIFfco_Open(FSA (UB8 *)font_file_path, &fcHandle)) != 0)
            return code;
        e = (fco_list_elem *)gs_malloc(r->mem, sizeof(*e), 1, "fco_list_elem");
        if (e == 0) {
            CGIFfco_Close(FSA fcHandle);
            return e_VMerror;
        }
        e->open_count = 0;
        e->fcHandle = fcHandle;
        e->file_path = my_strdup(r, font_file_path, "fco_file_path");
        if (e->file_path == 0) {
            CGIFfco_Close(FSA fcHandle);
            gs_free(r->mem, e, 0, 0, "fco_list_elem");
            return e_VMerror;
        }
        e->next = r->fco_list;
        r->fco_list = e;
    }
    e->open_count++;
    *result = e;
    return 0;
}

static FAPI_retcode make_font_data(fapi_ufst_server *r, const char *font_file_path, FAPI_font *ff, ufst_common_font_data **return_data)
{   ulong area_length = sizeof(ufst_common_font_data), tt_size = 0;
    LPUB8 buf;
    PCLETTO_FHDR *h;
    ufst_common_font_data *d;
    bool use_XL_format = ff->is_mtx_skipped;
    int code;
    FSA_FROM_SERVER;

    *return_data = 0;
    r->fc.ttc_index = ff->subfont;
    if (ff->font_file_path == NULL) {
#if UFST_VERSION_MAJOR < 6
        return(e_invalidaccess);
#else
        area_length += PCLETTOFONTHDRSIZE;
        if (ff->is_type1) {
            int subrs_count  = ff->get_word(ff, FAPI_FONT_FEATURE_Subrs_count, 0);
            int subrs_length = ff->get_long(ff, FAPI_FONT_FEATURE_Subrs_total_size, 0);
            int subrs_area_size;
            int gsubrs_count = ff->get_word(ff, FAPI_FONT_FEATURE_GlobalSubrs_count, 0);

            /* get_word() doesn't have an error return value, so I've used an unlikely value */
            if (gsubrs_count != 65535)
                subrs_count  += gsubrs_count;

            subrs_area_size = subrs_count * 5 + subrs_length + 2;
            area_length += 360 + subrs_area_size; /* some inprecise - see pack_pseo_fhdr */
        } else {
            tt_size  = ff->get_long(ff, FAPI_FONT_FEATURE_TT_size, 0);
            if (tt_size == 0)
                return e_invalidfont;
            area_length += tt_size + (use_XL_format ? 6 : 4) + 4 + 2;
        }
#endif
    } else {
#if UFST_VERSION_MAJOR < 6
        int sind = strlen(font_file_path) - 1;

        if ((font_file_path[sind] != 'o' || font_file_path[sind] != 'O') &&
            (font_file_path[sind - 1] != 'c' || font_file_path[sind - 1] != 'C') &&
            (font_file_path[sind - 2] != 'f' || font_file_path[sind - 2] != 'F') &&
            font_file_path[sind - 3] != '.') {
            return(e_invalidaccess);
        }
#endif
        area_length += strlen(font_file_path) + 1;
    }
    buf = gs_malloc(r->mem, area_length, 1, "ufst font data");
    if (buf == 0)
        return e_VMerror;

    memset(buf, 0x00, area_length);

    d = (ufst_common_font_data *)buf;
    d->tt_font_body_offset = 0;
    d->platformId = 0;
    d->specificId = 0;
    d->decodingID[0] = 0;
    d->glyphs = 0;
    d->is_disk_font = (ff->font_file_path != NULL);
    if (d->is_disk_font) {
         fco_list_elem *e = gx_UFST_find_static_fco(font_file_path);

         if (e != NULL) {
             memcpy(d + 1, font_file_path, strlen(font_file_path) + 1);
             d->font_id = (e->fcHandle << 16) | ff->subfont;
             d->font_type = FC_FCO_TYPE;
         } else {
            stream *f = sfopen(font_file_path, "rb", r->mem);
            if (f == NULL) {
                emprintf1(r->mem,
                          "fapiufst: Can't open %s\n",
                          font_file_path);
                return e_undefinedfilename;
            }
            memcpy(d + 1, font_file_path, strlen(font_file_path) + 1);
            d->font_type = get_font_type(f);
            sfclose(f);
            if (d->font_type == FC_FCO_TYPE) {
                fco_list_elem *e;
                if ((code = fco_open(r, font_file_path, &e)) != 0)
                    return code;
                d->font_id = (e->fcHandle << 16) | ff->subfont;
            }
        }
    } else {
        d->font_type = (ff->is_type1 ? FC_PST1_TYPE : FC_TT_TYPE);
        d->font_id = ff->get_long(ff, FAPI_FONT_FEATURE_UniqueID, 0);
        if (d->font_id < 0) {
            d->font_id = assign_font_id();
        }
        h = (PCLETTO_FHDR *)(buf + sizeof(ufst_common_font_data));
        h->fontDescriptorSize = PCLETTOFONTHDRSIZE;
        h->descriptorFormat = 15;
        h->fontType = 11; /* wrong */                /*  3- 11=Unicode; 0,1,2 also possible */
        h->style_msb = 0; /* wrong */               /*  4- from PCLT table in TrueType font */
        h->reserved1 = 0;
        h->baselinePosition = 0; /* wrong */        /*  6- from head table in TT font; = 0 */
        h->cellWidth = 1024; /* wrong */               /*  8- head, use xMax - xMin */
        h->cellHeight = 1024; /* wrong */             /* 10- head, use yMax - yMin */
        h->orientation = 0;             /* 12- 0 */
        h->spacing = 1; /* wrong */                 /* 13- 1=proportional, 0-fixed pitch */
        h->characterSet = 56; /* wrong */            /* 14- same as symSetCode; =56 if unbound. */
        h->pitch = 1024; /* wrong */                   /* 16- PCLT */
        h->height = 0;                  /* 18- 0 if TrueType */
        h->xHeight = 512; /* wrong */                 /* 20- PCLT */
        h->widthType = 0; /* wrong */               /* 22- PCLT */
        h->style_lsb = 0; /* wrong */               /* 23- PCLT */
        h->strokeWeight = 0; /* wrong */            /* 24- PCLT */
        h->typeface_lsb = 0; /* wrong */            /* 25- PCLT */
        h->typeface_msb = 0; /* wrong */           /* 26- PCLT */
        h->serifStyle = 0; /* wrong */              /* 27- PCLT */
        h->quality = 0; /* wrong */                 /* 28- 2 if TrueType */
        h->placement = 0; /* wronfg */               /* 29- 0 if TrueType */
        h->underlinePosition = 0;       /* 30- 0 */
        h->underlineHeight = 0;         /* 31- 0 */
        h->textHeight = 102; /* wrong */              /* 32- from OS/2 table in TT font */
        h->textWidth = 1024; /* wrong */              /* 34- OS/2 */
        h->firstCode = 0;               /* 36- set to 0 if unbound */
        h->lastCode = 255; /* wrong */                /* 38- max number of downloadable chars if unbound */
        h->pitch_ext = 0;               /* 40- 0 if TrueType */
        h->height_ext = 0;              /* 41- 0 if TrueType */
        h->capHeight = 1024; /* wrong */               /* 42- PCLT */
        h->fontNumber = d->font_id;              /* 44- PCLT */
        h->fontName[0] = 0; /* wrong */            /* 48- PCLT */
        h->scaleFactor = 1024; /* wrong */             /* 64- head:unitsPerEm */
        h->masterUnderlinePosition = 0; /* wrong */ /* 66- post table, or -20% of em */
        h->masterUnderlineHeight = 0; /* wrong */   /* 68- post table, or 5% of em */
        h->fontScalingTechnology = 1;   /* 70- 1=TrueType; 0=Intellifont */
        h->variety = 0;                 /* 71- 0 if TrueType */
        memset((LPUB8)h + PCLETTOFONTHDRSIZE, 0 ,8); /* work around bug in PCLswapHdr : it wants format 10 */
        /*  fixme : Most fields above being marked "wrong" look unused by UFST.
            Need to check for sure.
        */
        /*  fixme : This code assumes 1-byte alignment for PCLETTO_FHDR structure.
            Use PACK_* macros to improve.
        */
        PCLswapHdr(FSA (UB8 *)h, 0);
        if (ff->is_type1) {
            LPUB8 fontdata = (LPUB8)h + PCLETTOFONTHDRSIZE;
            pack_pseo_fhdr(r, ff, fontdata);
        } else {
            LPUB8 pseg = (LPUB8)h + PCLETTOFONTHDRSIZE;
            LPUB8 fontdata = pseg + (use_XL_format ? 6 : 4);
            if (tt_size > 65000)
                return e_unregistered; /* Must not happen because we skept 'glyp', 'loca' and 'cmap'. */
            pseg[0] = 'G';
            pseg[1] = 'T';
            if (use_XL_format) {
                pseg[2] = tt_size >> 24;
                pseg[3] = (tt_size >> 16) % 256;
                pseg[4] = (tt_size >> 8) % 256;
                pseg[5] = tt_size % 256;
            } else {
                pseg[2] = tt_size / 256;
                pseg[3] = tt_size % 256;
            }
            d->tt_font_body_offset = (LPUB8)fontdata - (LPUB8)d;
            if (ff->serialize_tt_font(ff, fontdata, tt_size))
                return e_invalidfont;
            *(fontdata + tt_size    ) = 255;
            *(fontdata + tt_size + 1) = 255;
            *(fontdata + tt_size + 2) = 0;
            *(fontdata + tt_size + 3) = 0;
            *(fontdata + tt_size + 4) = 0;
            *(fontdata + tt_size + 5) = 0;  /* checksum */
        }
    }
    *return_data = d;
    return 0;
}

static void prepare_typeface(fapi_ufst_server *r, ufst_common_font_data *d)
{   r->fc.format = d->font_type;
    r->fc.font_id = d->font_id;
    r->fc.font_hdr = (UB8 *)(d + 1);
    if (!d->is_disk_font)
        r->fc.format |= FC_EXTERN_TYPE;
}

static FAPI_retcode get_scaled_font(FAPI_server *server, FAPI_font *ff,
         const FAPI_font_scale *font_scale, const char *xlatmap, FAPI_descendant_code dc)
{   fapi_ufst_server *r = If_to_I(server);
    FONTCONTEXT *fc = &r->fc;
    /*  Note : UFST doesn't provide handles for opened fonts,
        but copies FONTCONTEXT to IFSTATE and caches it.
        Due to this the plugin cannot provide a handle for the font.
        This assumes that only one font context is active at a moment.
    */
    ufst_common_font_data *d = (ufst_common_font_data *)ff->server_font_data;
    const double scale = F_ONE;
    double hx, hy;
    FAPI_retcode code = 0;
    bool use_XL_format = ff->is_mtx_skipped;
    int world_scale = 0;
    FONT_METRICS fm;
    FSA_FROM_SERVER;

    if (ff->is_cid && ff->is_type1 && ff->font_file_path == NULL &&
        (dc == FAPI_TOPLEVEL_BEGIN || dc == FAPI_TOPLEVEL_COMPLETE)) {
        /* Don't need any processing for the top level font of a non-disk CIDFontType 0.
           See comment in FAPI_prepare_font.
           Will do with its subfonts individually.
         */
        return 0;
    }

    ff->need_decrypt = 1;
    if (d == 0) {
        if ((code = make_font_data(r, ff->font_file_path, ff, &d)) != 0)
            return code;
        ff->server_font_data = d;
        prepare_typeface(r, d);
        if (ff->font_file_path != NULL || ff->is_type1) /* such fonts don't use RAW_GLYPH */
            choose_decoding(r, d, xlatmap);
    }
    else {
        prepare_typeface(r, d);
        if (ff->font_file_path != NULL || ff->is_type1) /* such fonts don't use RAW_GLYPH */
            choose_decoding(r, d, xlatmap);
    }

    r->tran_xx = font_scale->matrix[0] / scale, r->tran_xy = font_scale->matrix[1] / scale;
    r->tran_yx = font_scale->matrix[2] / scale, r->tran_yy = font_scale->matrix[3] / scale;
    hx = hypot(r->tran_xx, r->tran_xy), hy = hypot(r->tran_yx, r->tran_yy);
    fc->xspot     = F_ONE;
    fc->yspot     = F_ONE;
    fc->fc_type   = FC_MAT2_TYPE;

    fc->s.m2.m[0] = (int)((double)font_scale->matrix[0] / hx + 0.5);
    fc->s.m2.m[1] = (int)((double)font_scale->matrix[1] / hx + 0.5);
    fc->s.m2.m[2] = (int)((double)font_scale->matrix[2] / hy + 0.5);
    fc->s.m2.m[3] = (int)((double)font_scale->matrix[3] / hy + 0.5);
    fc->s.m2.matrix_scale = 16;
    fc->s.m2.xworld_res = font_scale->HWResolution[0] >> 16;
    fc->s.m2.yworld_res = font_scale->HWResolution[1] >> 16;

    if ((hx > 0 && hy > 0) && (hx < 1.5 || hy < 1.5)) {
        world_scale = 8;
        hx *= 256;
        hy *= 256;

        while (hx < 1.5 || hy < 1.5) {
            world_scale += 8;
            hx *= 256;
            hy *= 256;
        }
    }
    fc->s.m2.world_scale = world_scale;
    fc->s.m2.point_size   = (int)(hy * 8 + 0.5); /* 1/8ths of pixels */
    fc->s.m2.set_size     = (int)(hx * 8 + 0.5);
    fc->numXsubpixels = font_scale->subpixels[0];
    fc->numYsubpixels = font_scale->subpixels[1];
    fc->alignment = (font_scale->align_to_pixels ? GAGG : GAPP);
    fc->ExtndFlags = 0;
    if (d->font_type == FC_TT_TYPE)
        fc->ssnum = USER_CMAP;
    else if (d->font_type == FC_FCO_TYPE) {
        fc->ssnum = UNICODE;
    } else if (d->font_type == FC_PST1_TYPE) {
        fc->ssnum = T1ENCODING;
    }

    if (d->font_type != FC_TT_TYPE && d->font_type != FC_FCO_TYPE) {
        fc->ExtndFlags = EF_NOSYMSETMAP;
    }
    fc->ExtndFlags |= EF_SUBSTHOLLOWBOX_TYPE;
    fc->format      |= FC_NON_Z_WIND;   /* NON_ZERO Winding required for TrueType */
    fc->format      |= FC_INCHES_TYPE;  /* output in units per inch */
    fc->user_platID = d->platformId;
    fc->user_specID = d->specificId;
    if (use_XL_format)
        fc->ExtndFlags |= EF_XLFONT_TYPE;
    if (ff->is_vertical)
        fc->ExtndFlags |= EF_UFSTVERT_TYPE;
    fc->dl_ssnum = (d->specificId << 4) | d->platformId;
    fc->ttc_index   = ff->subfont;
    r->callback_error = 0;

    code = CGIFfont(FSA fc);
    if (r->callback_error != 0)
        return r->callback_error;

    code = CGIFfont_metrics(&fm);
    if (r->callback_error != 0)
        return r->callback_error;

    return code;
}

static FAPI_retcode get_decodingID(FAPI_server *server, FAPI_font *ff, const char **decodingID_result)
{   fapi_ufst_server *r = If_to_I(server);
    ufst_common_font_data *d = (ufst_common_font_data *)r->fc.font_hdr - 1;

    *decodingID_result = d->decodingID;
    return 0;
}

static FAPI_retcode get_font_bbox(FAPI_server *server, FAPI_font *ff, int BBox[4])
{   fapi_ufst_server *r = If_to_I(server);
    SW16 VLCPower = 0;
    int code;
    FSA_FROM_SERVER;

    if ((code = CGIFbound_box(FSA BBox, &VLCPower)) < 0)
        return code;
    /*  UFST expands bbox for internal needs, and retrives the expanded bbox.
        We believe it's bug in UFST.
        Now we collapse it back to the correct size :
    */
    BBox[0] += 2;
    BBox[1] += 2;
    BBox[2] -= 2;
    BBox[3] -= 2;
    BBox[0] >>= VLCPower;
    BBox[1] >>= VLCPower;
    BBox[2] >>= VLCPower;
    BBox[3] >>= VLCPower;
    return 0;
}

static FAPI_retcode get_font_proportional_feature(FAPI_server *server, FAPI_font *ff, bool *bProportional)
{   fapi_ufst_server *r = If_to_I(server);
    FSA_FROM_SERVER;

    *bProportional = FALSE;
    if (ff->font_file_path == NULL || ff->is_type1)
        return 0;
#if TT_ROM || TT_DISK
    {
        UB8 buf[74];
        UL32 length = sizeof(buf);

    if (CGIFtt_query(FSA (UB8 *)ff->font_file_path, *(UL32 *)"OS/2", (UW16)ff->subfont, &length, buf) != 0)
        return 0; /* No OS/2 table - no chance to get the info. Use default == FALSE. */
    *bProportional = (buf[35] == 9);
    }
#endif
    return 0;
}

static inline void make_asciiz_char_name(char *buf, int buf_length, FAPI_char_ref *c)
{   int len = min(buf_length - 1, c->char_name_length);

    memcpy(buf, c->char_name, len);
    buf[len] = 0;
}

#define MAX_CHAR_NAME_LENGTH 30

static FAPI_retcode can_retrieve_char_by_name(FAPI_server *server, FAPI_font *ff, FAPI_char_ref *c, int *result)
{   fapi_ufst_server *r = If_to_I(server);
    FSA_FROM_SERVER;

    *result = 0;

    switch (r->fc.format & FC_FONTTYPE_MASK) {
        case FC_PST1_TYPE :
            *result = 1;
            break;
        case FC_TT_TYPE :
            break;
    }

    return 0;
}

static FAPI_retcode can_replace_metrics(FAPI_server *server, FAPI_font *ff, FAPI_char_ref *c, int *result)
{   *result = (!ff->is_type1 && ff->font_file_path == NULL &&
               c->metrics_scale == 0 && c->metrics_type == FAPI_METRICS_REPLACE);
    return 0;
}

static void release_glyphs(fapi_ufst_server *r, ufst_common_font_data *d)
{
    if (d) {
        while (d->glyphs != 0) {
            pcleo_glyph_list_elem *e = d->glyphs;
            d->glyphs = e->next;
            gs_free(r->mem, e, 0, 0, "PCLEO char");
        }
        d->glyphs = NULL;
    }
}

static FAPI_retcode get_fontmatrix(FAPI_server *I, gs_matrix *m)
{
    fapi_ufst_server *r = If_to_I(I);
    ufst_common_font_data *d = (ufst_common_font_data *)I->ff.server_font_data;
    FAPI_retcode code = 0;
    
    if (d == 0) {
        if ((code = make_font_data(r, I->ff.font_file_path, &(I->ff), &d)) != 0)
            return (code);
        I->ff.server_font_data = d;
        prepare_typeface(r, d);
    }
    
    /* There are PS jobs that rely on the standard fonts having
     * a FontMatrix of [0.001 0 0 0.001 0 0], but MT fonts actually
     * have an identity matrix. We need to compensate here. Other
     * fonts need an identity matrix returned here, as we apply the
     * font matrix explicitly in the scale calculation in zfapi.c
     */
    if (d->font_type & FC_FCO_TYPE) {
        m->xx = 0.001;
        m->xy = 0.0;
        m->yx = 0.0;
        m->yy = 0.001;
        m->tx = 0.0;
        m->ty = 0.0;
    }
    else {
        m->xx = 1.0;
        m->xy = 0.0;
        m->yx = 0.0;
        m->yy = 1.0;
        m->tx = 0.0;
        m->ty = 0.0;
    }

#if 0
    gs_matrix *base_font_matrix = &I->initial_FontMatrix;
    m->xx = I->initial_FontMatrix.xx;
    m->xy = I->initial_FontMatrix.xy;
    m->yx = I->initial_FontMatrix.yx;
    m->yy = I->initial_FontMatrix.yy;
    m->tx = I->initial_FontMatrix.tx;
    m->ty = I->initial_FontMatrix.ty;
#endif
    return (code);

}

static int export_outline(fapi_ufst_server *r, PIFOUTLINE pol, FAPI_path *p)
{   POUTLINE_CHAR outchar;
    SW16 num_contrs,num_segmts;
    LPSB8 segment;
    PINTRVECTOR points;
    SW16  i,j;

    if (pol == NULL)
        return 0;
    p->shift += r->If.frac_shift + pol->VLCpower;
    outchar = &pol->ol;
    num_contrs = outchar->num_loops;
    for(i = 0; i<num_contrs; i++) {
        num_segmts = outchar->loop[i].num_segmts;
        segment = (LPSB8)((LPSB8)(outchar->loop) + outchar->loop[i].segmt_offset);
        points = (PINTRVECTOR)((LPSB8)(outchar->loop) + outchar->loop[i].coord_offset);
        for(j=0; j<num_segmts; j++) {

            if(*segment == 0x00) {
                if ((p->gs_error = p->moveto(p, ((int64_t)points->x) << 16, ((int64_t)points->y) << 16)) != 0)
                    return p->gs_error;
                points++;
            } else if (*segment == 0x01) {
                if ((p->gs_error = p->lineto(p, ((int64_t)points->x) << 16, ((int64_t)points->y) << 16)) != 0)
                    return p->gs_error;
                points++;
            } else if (*segment == 0x02) {
                points+=2;
                return e_invalidfont; /* This must not happen */
            } else if (*segment == 0x03) {
                if ((p->gs_error = p->curveto(p, ((int64_t)points[0].x) << 16, ((int64_t)points[0].y) << 16,
                                        ((int64_t)points[1].x) << 16, ((int64_t)points[1].y) << 16,
                                        ((int64_t)points[2].x) << 16, ((int64_t)points[2].y)<< 16) < 0))
                    return p->gs_error;
                points+=3;
            } else
                return e_invalidfont; /* This must not happen */
            segment++;
        }
    }
    return 0;
}

static inline void set_metrics(fapi_ufst_server *r, FAPI_metrics *metrics, SL32 design_bbox[4], SW16 design_escapement[2], SW16 du_emx, SW16 du_emy)
{

    metrics->escapement = design_escapement[0];
    metrics->v_escapement = design_escapement[1];
    metrics->em_x = du_emx;
    metrics->em_y = du_emy;
    metrics->bbox_x0 = design_bbox[0];
    metrics->bbox_y0 = design_bbox[1];
    metrics->bbox_x1 = design_bbox[2];
    metrics->bbox_y1 = design_bbox[3];
}

static FAPI_retcode get_char(fapi_ufst_server *r, FAPI_font *ff, FAPI_char_ref *c, FAPI_path *p, FAPI_metrics *metrics, UW16 format)
{
    UW16 code = 0, code2 = 0;
    UW16 cc = (UW16)c->char_code;
    SL32 design_bbox[4];
    char PSchar_name[MAX_CHAR_NAME_LENGTH];
    MEM_HANDLE result;
    ufst_common_font_data *d = (ufst_common_font_data *)ff->server_font_data;
    SW16 design_escapement[2];
    SW16 du_emx, du_emy;
    const char *notdef = ".notdef";
    const void *client_char_data = ff->char_data;
    const int client_char_data_len = ff->char_data_len;
    bool need_decrypt = ff->need_decrypt;
    int length;
    FSA_FROM_SERVER;

    design_escapement[0] = design_escapement[1] = 0;

    if (ff->is_type1) {
        /* If a charstring in a Type 1 has been replaced with a PS procedure
         * get_glyph will return -1. We can then return char_code + 1 which
         * tells the FAPI code we might be dealing with a procedure, and to
         * try executing it as such.
         */
        ff->need_decrypt = false;
        length = ff->get_glyph(ff, c->char_code, NULL, 0);
        ff->need_decrypt = need_decrypt;
        if (length == -1) {
            return(c->char_code + 1);
        }
    }

    memset(metrics, 0, sizeof(*metrics));
    metrics->bbox_x1 = -1;

    if (ff->is_type1 && !ff->is_cid) {
        int len = min(ff->char_data_len, sizeof(PSchar_name) - 1);
        memcpy (PSchar_name, ff->char_data, len);
        PSchar_name[len] = 0;
    } else {
        make_asciiz_char_name(PSchar_name, sizeof(PSchar_name), c);
    }

    CGIFchIdptr(FSA &cc, PSchar_name); /* fixme : Likely only FC_PST1_TYPE needs it. */
    {   /* hack : Changing UFST internal data. Change to r->fc doesn't help,
           because UFST thinks that the "outline/raster" is a property of current font. */
        pIFS->fcCur.format &= ~FC_OUTPUT_MASK;
        pIFS->fcCur.format |= format;
    }
    r->bRaster = FALSE;
    r->ff = ff;
    r->callback_error = 0;
    r->sb_x = c->sb_x;
    r->aw_x = c->aw_x;
    r->metrics_type = c->metrics_type;
    if (d->font_type == FC_FCO_TYPE && r->fc.ExtndFlags & EF_SUBSTHOLLOWBOX_TYPE) {
        if (c->char_name != NULL && c->char_name_length == 7 &&
                !memcmp(c->char_name, ".notdef", 7)) {
            /* With EF_SUBSTHOLLOWBOX_TYPE and FCO,
               UFST paints a hollow box insted .notdef .
               For Adobe compatibility we substitute a space,
               because Adobe Type 1 fonts define .notdef as a space . */
            cc = 32;
        }
    }
#if !UFST_REENTRANT
    static_server_ptr_for_ufst_callback = r;
#endif
    code = CGIFchar_handle(FSA cc, &result, (SW16)0);
    if (code && code != ERR_fixed_space && code != ERR_bm_buff && code != ERR_bm_too_big) {
        /* There is no such char in the font, try the glyph 0 (notdef) : */
        UW16 c1 = 0, ssnum = pIFS->fcCur.ssnum;

        if (d->font_type == FC_FCO_TYPE) {
            /* EF_SUBSTHOLLOWBOX_TYPE must work against it.
               Ensure the plugin plug__xi.fco is loaded. */
            /* fixme : Due to unknown reason EF_SUBSTHOLLOWBOX_TYPE
               doesn't work for Symbol, Dingbats, Wingdings.
               hack : render the space character. */
            c1 = 32;
        } else {
            /* hack : Changing UFST internal data - see above. */
            pIFS->fcCur.ssnum = RAW_GLYPH;
        }
        r->callback_error = 0;
        ff->char_data = (void *)notdef;
        ff->char_data_len = strlen(notdef);
        CGIFchIdptr(FSA (void *)&c1, (void *)notdef);
        code2 = CGIFchar_handle(FSA c1, &result, (SW16)0);
        if (code2 && code2 != ERR_fixed_space && code2 != ERR_bm_buff && code2 != ERR_bm_too_big) {
            ff->char_data = (void *)"space";
            ff->char_data_len = strlen("space");
            CGIFchIdptr(FSA (void *)&c1, (void *)"space");
            code2 = CGIFchar_handle(FSA c1, &result, (SW16)0);
        }
        if (!code2 || code2 == ERR_fixed_space) {
            code = code2;
        }
        pIFS->fcCur.ssnum = ssnum;
    }
    ff->char_data = client_char_data;
    ff->char_data_len = client_char_data_len;

#if !UFST_REENTRANT
    static_server_ptr_for_ufst_callback = 0;
#endif
    r->ff = 0;
    release_glyphs(r, (ufst_common_font_data *)ff->server_font_data);
    if (code != ERR_fixed_space && code != 0)
        return code;
    if (r->callback_error != 0)
        return r->callback_error;
    if (format == FC_BITMAP_TYPE) {
        IFBITMAP *pbm = (IFBITMAP *)result;

        du_emx = pbm->du_emx;
        du_emy = pbm->du_emy;
        r->char_data = pbm;
        r->bRaster = TRUE;

                design_escapement[0] = pbm->escapement;

#if UFST_VERSION_MAJOR >= 6 && UFST_VERSION_MINOR >= 2

        design_bbox[0] = pIFS->glyphMetricsDU.bbox.BBox[0];
        design_bbox[1] = pIFS->glyphMetricsDU.bbox.BBox[1];
        design_bbox[2] = pIFS->glyphMetricsDU.bbox.BBox[2];
        design_bbox[3] = pIFS->glyphMetricsDU.bbox.BBox[3];
        if (d->font_type != FC_FCO_TYPE) {
            design_escapement[0] = pIFS->glyphMetricsDU.aw.x;
            design_escapement[1] = pIFS->glyphMetricsDU.aw.y;
        }
#endif

    } else {
        IFOUTLINE *pol = (IFOUTLINE *)result;

        design_escapement[0] = pol->escapement;
        du_emx = pol->du_emx;
        du_emy = pol->du_emy;
        r->char_data = (IFOUTLINE *)result;
    }
#if 1 /* UFST 5.0 */
    if (USBOUNDBOX && d->font_type == FC_FCO_TYPE) {
        if (pIFS->USBBOXorigScaleFactor /* fixme : Must we check this ? */
            && pIFS->USBBOXorigScaleFactor != pIFS->USBBOXscaleFactor) {
            /* See fco_make_gaso_and_stats in fc_if.c . Debugged with hollow box in Helvetica. */
            /* Fixme : this looses a precision, an UFST bug has been reported. */
            int w = pIFS->USBBOXorigScaleFactor / 2;

            design_bbox[0] = pIFS->USBBOXxmin * pIFS->USBBOXscaleFactor / pIFS->USBBOXorigScaleFactor;
            design_bbox[1] = pIFS->USBBOXymin * pIFS->USBBOXscaleFactor / pIFS->USBBOXorigScaleFactor;
            design_bbox[2] = (pIFS->USBBOXxmax * pIFS->USBBOXscaleFactor + w) / pIFS->USBBOXorigScaleFactor;
            design_bbox[3] = (pIFS->USBBOXymax * pIFS->USBBOXscaleFactor + w) / pIFS->USBBOXorigScaleFactor;
        } else {
            design_bbox[0] = pIFS->USBBOXxmin;
            design_bbox[1] = pIFS->USBBOXymin;
            design_bbox[2] = pIFS->USBBOXxmax;
            design_bbox[3] = pIFS->USBBOXymax;
        }
    } else {
#if UFST_VERSION_MAJOR >= 6 && UFST_VERSION_MINOR >= 2
#else
        /* fixme: UFST 5.0 doesn't provide this data.
           Stubbing with Em box.
           Non-FCO fonts may be cropped if a glyph goes outside Em box
           (or occupy negative coordinates, such as 'y'.).
           Non-FCO fonts may be uncached if Em box is much bigger than the glyph.
         */
        design_bbox[0] = 0;
        design_bbox[1] = 0;
        design_bbox[2] = du_emx;
        design_bbox[3] = du_emy;
#endif
    }
#endif
    {	/* UFST performs a dual rounding of the glyph origin : first
           the scaled glyph design origin is rounded to pixels with floor(x + 0.5),
           second the glyph position is rounded to pixels with floor(x + 0.5).
           Ghostscript rounds with floor(x) due to the pixel-center-inside rule.

           A right way would be to specify the half pixel offset to the glyph
           origin for the rendering glyph, but UFST has no interface for doing that.
           Instead that, to prevent a possible cropping while copying a glyph to cache cell,
           we expand the design bbox in a value of a pixel size.
           We could not determine the necessary expansion theoretically,
           and choosen expansion coefficients empirically,
           which appears equal to 2 pixels.

           fixme: Actually the expansion is the FONTCONTEXT property,
           so it could be computed at once when the scaled font is created.
         */
        const double expansion_x = 2, expansion_y = 2; /* pixels */ /* adesso5.pdf */
        const double XX = r->tran_xx * (r->fc.s.m2.xworld_res >> 16) / 72 / du_emx;
        const double XY = r->tran_xy * (r->fc.s.m2.yworld_res >> 16) / 72 / du_emy;
        const double YX = r->tran_yx * (r->fc.s.m2.xworld_res >> 16) / 72 / du_emx;
        const double YY = r->tran_yy * (r->fc.s.m2.yworld_res >> 16) / 72 / du_emy;
        const double det = XX * YY - XY * YX;
        const double deta = det < 0 ? -det : det;

        if (deta > 0.0000000001) {
            const double xx =  YY / det, xy = -XY / det;
            const double yx = -YX / det, yy =  XX / det;
            const double dx = -(expansion_x * xx + expansion_y * xy);
            const double dy = -(expansion_x * yx + expansion_y * yy);
            const SL32 dxa = (SL32)((dx < 0 ? -dx : dx) + 0.5);
            const SL32 dya = (SL32)((dy < 0 ? -dy : dy) + 0.5);

            design_bbox[0] -= dxa;
            design_bbox[1] -= dya;
            design_bbox[2] += dxa;
            design_bbox[3] += dya;
        }
    }
    set_metrics(r, metrics, design_bbox, design_escapement, du_emx, du_emy);
    if (code == ERR_fixed_space)
        release_char_data_inline(r);
    return 0;
}

static FAPI_retcode get_char_outline_metrics(FAPI_server *server, FAPI_font *ff, FAPI_char_ref *c, FAPI_metrics *metrics)
{   fapi_ufst_server *r = If_to_I(server);

    release_char_data_inline(r);
    return get_char(r, ff, c, NULL, metrics, FC_CUBIC_TYPE);
    /*	UFST cannot render enough metrics information without generating raster or outline.
        r->char_data keeps an outline after calling this function.
    */
}

static FAPI_retcode get_char_outline(FAPI_server *server, FAPI_path *p)
{   fapi_ufst_server *r = If_to_I(server);

    return export_outline(r, (IFOUTLINE *)r->char_data, p);
}

static FAPI_retcode get_char_raster_metrics(FAPI_server *server, FAPI_font *ff, FAPI_char_ref *c, FAPI_metrics *metrics)
{
    fapi_ufst_server *r = If_to_I(server);
    int code;

    release_char_data_inline(r);
    code = get_char(r, ff, c, NULL, metrics, FC_BITMAP_TYPE);
    if (code == ERR_bm_buff || code == ERR_bm_too_big) /* Too big character ? */
        return (e_VMerror);
    return code;
    /*	UFST cannot render enough metrics information without generating raster or outline.
        r->char_data keeps a raster after calling this function.
    */
}

static FAPI_retcode get_char_width(FAPI_server *server, FAPI_font *ff, FAPI_char_ref *c, FAPI_metrics *metrics)
{
    fapi_ufst_server *r = If_to_I(server);
    int code;

    release_char_data_inline(r);
    code = get_char(r, ff, c, NULL, metrics, server->use_outline ? FC_CUBIC_TYPE : FC_BITMAP_TYPE);
    if (code == ERR_bm_buff || code == ERR_bm_too_big) /* Too big character ? */
        return (e_VMerror);
    return code;
    /*	UFST cannot render enough metrics information without generating raster or outline.
        r->char_data keeps a raster after calling this function.
    */
}


static FAPI_retcode get_char_raster(FAPI_server *server, FAPI_raster *rast)
{   fapi_ufst_server *r = If_to_I(server);

    if (!r->bRaster)
        return e_limitcheck;
    else if (r->char_data == NULL) {
        rast->height = rast->width = rast->line_step = 0;
        rast->p = 0;
    } else {
        IFBITMAP *pbm = (IFBITMAP *)r->char_data;
        rast->p = pbm->bm;
        rast->height = pbm->top_indent + pbm->black_depth;
        rast->width = pbm->left_indent + pbm->black_width;
        rast->line_step = pbm->width;
        rast->left_indent = pbm->left_indent;
        rast->top_indent = pbm->top_indent;
        rast->black_width = pbm->black_width;
        rast->black_height = pbm->black_depth;
        if (rast->width != 0) {
            rast->orig_x = pbm->xorigin;
            rast->orig_y = pbm->yorigin;
        } else
            rast->orig_x = rast->orig_y = 0;
    }
    return 0;
}

static FAPI_retcode release_char_data(FAPI_server *server)
{   fapi_ufst_server *r = If_to_I(server);

    release_char_data_inline(r);
    return 0;
}

static void release_fco(fapi_ufst_server *r, SW16 fcHandle)
{
    fco_list_elem **e;

    if(gx_UFST_find_static_fco_handle(fcHandle) != NULL)
        return;
    for (e = &r->fco_list; *e != 0; )
        if ((*e)->fcHandle == fcHandle && (--(*e)->open_count) == 0) {
            fco_list_elem *ee = *e;
            FSA_FROM_SERVER;

            *e = ee->next;
            CGIFfco_Close(FSA ee->fcHandle);
            gs_free(r->mem, ee->file_path, 0, 0, "fco_file_path");
            gs_free(r->mem, ee, 0, 0, "fco_list_elem");
        } else
            e = &(*e)->next;
}

static FAPI_retcode FAPIU_release_typeface(FAPI_server *server, void *font_data)
{   fapi_ufst_server *r = If_to_I(server);
    ufst_common_font_data *d;
    FAPI_retcode code = 0;
    FSA_FROM_SERVER;

    release_char_data_inline(r);
    if (font_data == 0)
        return 0;
    d = (ufst_common_font_data *)font_data;
#if 0
    prepare_typeface(r, d);
    if (d->is_disk_font)
        code = CGIFhdr_font_purge(FSA &r->fc);
    else
        code = CGIFfont_purge(FSA &r->fc);
#endif

    release_glyphs(r, d);
    release_fco(r, (SW16)(d->font_id >> 16));
    gs_free(r->mem, font_data, 0, 0, "ufst font data");
    return code;
}

static FAPI_retcode check_cmap_for_GID(FAPI_server *server, uint *index)
{
    return 0;
}

/* --------------------- The plugin definition : ------------------------- */

static void gs_fapiufst_finit(i_plugin_instance *instance, i_plugin_client_memory *mem);

static const i_plugin_descriptor ufst_descriptor = {
    "FAPI",
    "UFST",
    gs_fapiufst_finit
};

static const FAPI_server If0 = {
    {   &ufst_descriptor
    },
    16, /* frac_shift */
    {gs_no_id},
    {0},
    0,
    false,
    {1, 0, 0, 1, 0, 0},
    ensure_open,
    get_scaled_font,
    get_decodingID,
    get_font_bbox,
    get_font_proportional_feature,
    can_retrieve_char_by_name,
    can_replace_metrics,
    get_fontmatrix,
    get_char_width,
    get_char_raster_metrics,
    get_char_raster,
    get_char_outline_metrics,
    get_char_outline,
    release_char_data,
    FAPIU_release_typeface,
    check_cmap_for_GID
};

static int fapiu_make_string (i_ctx_t *i_ctx_p, const char *str, ref *obj)
{
    int len = strlen(str);
    byte *sbody;

    sbody = ialloc_string(len, "fapiu_make_string");
    if (!sbody) {
        return(e_VMerror);
    }
    memcpy (sbody, str, len);

    make_string(obj, a_all | icurrent_space, len, sbody);

    return(0);
}

plugin_instantiation_proc(gs_fapiufst_instantiate);      /* check prototype */

int gs_fapiufst_instantiate(i_plugin_client_memory *client_mem, i_plugin_instance **p_instance)
{
    fapi_ufst_server *r = (fapi_ufst_server *)client_mem->alloc(client_mem, sizeof(fapi_ufst_server), "fapi_ufst_server");
    i_ctx_t *i_ctx_p = NULL;
    gs_main_instance *inst;
    ref entry;
    char tmppath[gp_file_name_sizeof];
    int code = 0;

    if (r == 0)
        return e_Fatal;
    memset(r, 0, sizeof(*r));
    r->If = If0;

    code = gs_memory_chunk_wrap(&(r->mem), client_mem->client_data);
    if (code != 0) {
        return(code);
    }

    *p_instance = &r->If.ig;

    inst = get_minst_from_memory((const gs_memory_t *)(client_mem->client_data));
    i_ctx_p = inst->i_ctx_p;

    /* The following entries will get overwritten if the user specifies alternative settings
     * on the command line.
     */
    strncpy(tmppath, UFSTFONTDIR, gp_file_name_sizeof);
    strncat(tmppath, UFST_PlugIn_Path, gp_file_name_sizeof - strlen(tmppath));

    fapiu_make_string (i_ctx_p, (const char *)tmppath, &entry);
    (void)dict_put_string(systemdict, UFST_PlugIn_Str, &entry, NULL);

    strncpy(tmppath, UFSTFONTDIR, gp_file_name_sizeof);
    strncat(tmppath, FCOfontfilePath, gp_file_name_sizeof - strlen(tmppath));

    fapiu_make_string (i_ctx_p, (const char *)tmppath, &entry);
    (void)dict_put_string(systemdict, FCOfontfileStr, &entry, NULL);

    strncpy(tmppath, UFSTFONTDIR, gp_file_name_sizeof);
    strncat(tmppath, FCOfontfile2Path, gp_file_name_sizeof - strlen(tmppath));

    fapiu_make_string (i_ctx_p, (const char *)tmppath, &entry);
    (void)dict_put_string(systemdict, FCOfontfile2Str, &entry, NULL);

    fapiu_make_string (i_ctx_p, FAPIfontmap, &entry);
    (void)dict_put_string(systemdict, FAPIfontmapStr, &entry, NULL);

    return 0;
}

#ifndef UFST_MEMORY_CHECKING
#define UFST_MEMORY_CHECKING 0
#endif

#if UFST_MEMORY_CHECKING
extern unsigned long maxmem;
#endif

static void gs_fapiufst_finit(i_plugin_instance *this, i_plugin_client_memory *mem)
{   fapi_ufst_server *r = (fapi_ufst_server *)this;
    FSA_FROM_SERVER;

#if UFST_MEMORY_CHECKING
    dprintf1("UFST used %Lf kb\n", ((long double)maxmem) / 1024);
#endif

    if (r->If.ig.d != &ufst_descriptor)
        return; /* safety */
#if 0 /* Disabled against a reentrancy problem
         in a single language build for host-based applications. */
    gx_set_UFST_Callbacks(NULL, NULL, NULL);
#endif
    release_char_data_inline(r);
    if (r->bInitialized && !r->ufst_is_singleton)
        gx_UFST_fini();
    if (r->param) {
        gs_free (r->mem, r->param, 0, 0, "server_params");
    }
    gs_memory_chunk_release (r->mem);

    mem->free(mem, r, "fapi_ufst_server");
}