Coverage Report

Created: 2026-04-01 07:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/devices/vector/gdevpsf2.c
Line
Count
Source
1
/* Copyright (C) 2001-2025 Artifex Software, Inc.
2
   All Rights Reserved.
3
4
   This software is provided AS-IS with no warranty, either express or
5
   implied.
6
7
   This software is distributed under license and may not be copied,
8
   modified or distributed except as expressly authorized under the terms
9
   of the license contained in the file LICENSE in this distribution.
10
11
   Refer to licensing information at http://www.artifex.com or contact
12
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
13
   CA 94129, USA, for further information.
14
*/
15
16
17
/* Write an embedded CFF font with either Type 1 or Type 2 CharStrings */
18
#include "math_.h"    /* for fabs */
19
#include "memory_.h"
20
#include "gx.h"
21
#include "gxarith.h"
22
#include "gscencs.h"
23
#include "gserrors.h"
24
#include "gsccode.h"
25
#include "gscrypt1.h"
26
#include "gsmatrix.h"
27
#include "gsutil.h"
28
#include "gxfixed.h"
29
#include "gxfont.h"
30
#include "gxfont1.h"
31
#include "gxfcid.h"
32
#include "stream.h"
33
#include "gdevpsf.h"
34
35
/* Define additional opcodes used in Dicts, but not in CharStrings. */
36
#define CD_LONGINT 29
37
#define CD_REAL 30
38
39
/* Define the count of standard strings. */
40
235k
#define NUM_STD_STRINGS 391
41
42
/* Define whether or not to skip writing an empty Subrs Index. */
43
#define SKIP_EMPTY_SUBRS
44
45
/* Define the structure for the string table. */
46
typedef struct cff_string_item_s {
47
    gs_const_string key;
48
    int index1;   /* index + 1, 0 means empty */
49
} cff_string_item_t;
50
typedef struct cff_string_table_s {
51
    cff_string_item_t *items;
52
    int count;
53
    int size;
54
    uint total;
55
    int reprobe;
56
} cff_string_table_t;
57
58
/* Define the state of the CFF writer. */
59
typedef struct cff_writer_s {
60
    int options;
61
    stream *strm;
62
    gs_font_base *pfont;  /* type1 or cid0 */
63
    glyph_data_proc_t glyph_data;
64
    gs_offset_t offset_size;
65
    gs_offset_t start_pos;
66
    cff_string_table_t std_strings;
67
    cff_string_table_t strings;
68
    gs_int_rect FontBBox;
69
} cff_writer_t;
70
typedef struct cff_glyph_subset_s {
71
    psf_outline_glyphs_t glyphs;
72
    int num_encoded;    /* glyphs.subset_data[1..num_e] are encoded */
73
    int num_encoded_chars;  /* Encoding has num_e_chars defined entries */
74
} cff_glyph_subset_t;
75
76
/* ---------------- Output utilities ---------------- */
77
78
/* ------ String tables ------ */
79
80
/* Initialize a string table. */
81
static void
82
cff_string_table_init(cff_string_table_t *pcst, cff_string_item_t *items,
83
                      int size)
84
23.4k
{
85
23.4k
    int reprobe = 17;
86
87
23.4k
    memset(items, 0, size * sizeof(*items));
88
23.4k
    pcst->items = items;
89
23.4k
    pcst->count = 0;
90
23.4k
    pcst->size = size;
91
24.1k
    while (reprobe != 1 && igcd(size, reprobe) != 1)
92
712
        reprobe = (reprobe * 2 + 1) % size;
93
23.4k
    pcst->total = 0;
94
23.4k
    pcst->reprobe = reprobe;
95
23.4k
}
96
97
/* Add a string to a string table. */
98
static int
99
cff_string_add(cff_string_table_t *pcst, const byte *data, uint size)
100
4.57M
{
101
4.57M
    int index;
102
103
4.57M
    if (pcst->count >= pcst->size)
104
0
        return_error(gs_error_limitcheck);
105
4.57M
    index = pcst->count++;
106
4.57M
    pcst->items[index].key.data = data;
107
4.57M
    pcst->items[index].key.size = size;
108
4.57M
    pcst->total += size;
109
4.57M
    return index;
110
4.57M
}
111
112
/* Look up a string, optionally adding it. */
113
/* Return 1 if the string was added. */
114
static int
115
cff_string_index(cff_string_table_t *pcst, const byte *data, uint size,
116
                 bool enter, int *pindex)
117
6.05M
{
118
    /****** FAILS IF TABLE FULL AND KEY MISSING ******/
119
6.05M
    int j = (size == 0 ? 0 : data[0] * 23 + data[size - 1] * 59 + size);
120
6.05M
    int index, c = 0;
121
122
16.2M
    while ((index = pcst->items[j %= pcst->size].index1) != 0) {
123
11.4M
        --index;
124
11.4M
        if (!bytes_compare(pcst->items[index].key.data,
125
11.4M
                           pcst->items[index].key.size, data, size)) {
126
1.23M
            *pindex = index;
127
1.23M
            return 0;
128
1.23M
        }
129
10.1M
        j += pcst->reprobe;
130
10.1M
        if (++c >= pcst->size)
131
0
            break;
132
10.1M
    }
133
4.81M
    if (!enter)
134
235k
        return_error(gs_error_undefined);
135
4.57M
    index = cff_string_add(pcst, data, size);
136
4.57M
    if (index < 0)
137
0
        return index;
138
4.57M
    pcst->items[j].index1 = index + 1;
139
4.57M
    *pindex = index;
140
4.57M
    return 1;
141
4.57M
}
142
143
/* Get the SID for a string or a glyph. */
144
static int
145
cff_string_sid(cff_writer_t *pcw, const byte *data, uint size)
146
1.27M
{
147
1.27M
    int index;
148
1.27M
    int code = cff_string_index(&pcw->std_strings, data, size, false, &index);
149
150
1.27M
    if (code < 0) {
151
235k
        code = cff_string_index(&pcw->strings, data, size, true, &index);
152
235k
        if (code < 0)
153
0
            return code;
154
235k
        index += NUM_STD_STRINGS;
155
235k
    }
156
1.27M
    return index;
157
1.27M
}
158
static int
159
cff_glyph_sid(cff_writer_t *pcw, gs_glyph glyph)
160
1.04M
{
161
1.04M
    gs_const_string str;
162
1.04M
    int code =
163
1.04M
        pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
164
165
1.04M
    if (code < 0)
166
0
        return code;
167
1.04M
    return cff_string_sid(pcw, str.data, str.size);
168
1.04M
}
169
170
/* ------ Low level ------ */
171
172
static void
173
put_card16(cff_writer_t *pcw, uint c16)
174
1.84M
{
175
1.84M
    sputc(pcw->strm, (byte)(c16 >> 8));
176
1.84M
    sputc(pcw->strm, (byte)c16);
177
1.84M
}
178
static int
179
offset_size(uint offset)
180
328k
{
181
328k
    int size = 1;
182
183
440k
    while (offset > 255)
184
111k
        offset >>= 8, ++size;
185
328k
    return size;
186
328k
}
187
static void
188
put_offset(cff_writer_t *pcw, int offset)
189
1.55M
{
190
1.55M
    int i;
191
192
4.06M
    for (i = pcw->offset_size - 1; i >= 0; --i)
193
2.51M
        sputc(pcw->strm, (byte)(offset >> (i * 8)));
194
1.55M
}
195
static int
196
put_bytes(stream * s, const byte *ptr, uint count)
197
343k
{
198
343k
    uint used;
199
200
343k
    sputs(s, ptr, count, &used);
201
343k
    return (int)used;
202
343k
}
203
static int
204
check_ioerror(stream * s)
205
186k
{
206
186k
    uint used = 0;
207
208
186k
    return sputs(s, (byte *)&used, 0, &used);
209
186k
}
210
211
/* ------ Data types ------ */
212
213
852k
#define CE_OFFSET 32
214
static void
215
cff_put_op(cff_writer_t *pcw, int op)
216
852k
{
217
852k
    if (op >= CE_OFFSET) {
218
272k
        sputc(pcw->strm, cx_escape);
219
272k
        sputc(pcw->strm, (byte)(op - CE_OFFSET));
220
272k
    } else
221
579k
        sputc(pcw->strm, (byte)op);
222
852k
}
223
static void
224
cff_put_int(cff_writer_t *pcw, int i)
225
2.30M
{
226
2.30M
    stream *s = pcw->strm;
227
228
2.30M
    if (i >= -107 && i <= 107)
229
1.63M
        sputc(s, (byte)(i + 139));
230
672k
    else if (i <= 1131 && i >= 0)
231
554k
        put_card16(pcw, (c_pos2_0 << 8) + i - 108);
232
117k
    else if (i >= -1131 && i < 0)
233
41.3k
        put_card16(pcw, (c_neg2_0 << 8) - i - 108);
234
75.9k
    else if (i >= -32768 && i <= 32767) {
235
16.7k
        sputc(s, c2_shortint);
236
16.7k
        put_card16(pcw, i & 0xffff);
237
59.1k
    } else {
238
59.1k
        sputc(s, CD_LONGINT);
239
59.1k
        put_card16(pcw, i >> 16);
240
59.1k
        put_card16(pcw, i & 0xffff);
241
59.1k
    }
242
2.30M
}
243
static void
244
cff_put_int_value(cff_writer_t *pcw, int i, int op)
245
333k
{
246
333k
    cff_put_int(pcw, i);
247
333k
    cff_put_op(pcw, op);
248
333k
}
249
static void
250
cff_put_int_if_ne(cff_writer_t *pcw, int i, int i_default, int op)
251
452k
{
252
452k
    if (i != i_default)
253
214k
        cff_put_int_value(pcw, i, op);
254
452k
}
255
static void
256
cff_put_bool(cff_writer_t *pcw, bool b)
257
1.66k
{
258
1.66k
    cff_put_int(pcw, (b ? 1 : 0));
259
1.66k
}
260
static void
261
cff_put_bool_value(cff_writer_t *pcw, bool b, int op)
262
1.66k
{
263
1.66k
    cff_put_bool(pcw, b);
264
1.66k
    cff_put_op(pcw, op);
265
1.66k
}
266
static void
267
cff_put_real(cff_writer_t *pcw, double f)
268
1.68M
{
269
1.68M
    if (f == (int)f)
270
1.68M
        cff_put_int(pcw, (int)f);
271
7.45k
    else {
272
        /* Use decimal representation. */
273
7.45k
        char str[50];
274
7.45k
        byte b = 0xff;
275
7.45k
        const char *p;
276
277
7.45k
        gs_snprintf(str, sizeof(str), "%g", f);
278
7.45k
        sputc(pcw->strm, CD_REAL);
279
56.3k
        for (p = str; ; ++p) {
280
56.3k
            int digit;
281
282
56.3k
            switch (*p) {
283
7.45k
            case 0:
284
7.45k
                goto done;
285
7.45k
            case '.':
286
7.45k
                digit = 0xa; break;
287
20
            case '+':
288
20
                continue;
289
5
            case '-':
290
5
                digit = 0xe; break;
291
20
            case 'e': case 'E':
292
20
                if (p[1] == '-')
293
0
                    digit = 0xc, ++p;
294
20
                else
295
20
                    digit = 0xb;
296
20
                break;
297
23.5k
            case '0': case '1': case '2': case '3': case '4':
298
41.3k
            case '5': case '6': case '7': case '8': case '9':
299
41.3k
                digit = *p - '0';
300
41.3k
                break;
301
0
            default:    /* can't happen */
302
0
                digit = 0xd;  /* invalid */
303
0
                break;
304
56.3k
            }
305
48.8k
            if (b == 0xff)
306
26.8k
                b = (digit << 4) + 0xf;
307
21.9k
            else {
308
21.9k
                sputc(pcw->strm, (byte)((b & 0xf0) + digit));
309
21.9k
                b = 0xff;
310
21.9k
            }
311
48.8k
        }
312
7.45k
    done:
313
7.45k
        sputc(pcw->strm, b);
314
7.45k
    }
315
1.68M
}
316
static void
317
cff_put_real_value(cff_writer_t *pcw, double f, int op)
318
99.7k
{
319
99.7k
    cff_put_real(pcw, f);
320
99.7k
    cff_put_op(pcw, op);
321
99.7k
}
322
static void
323
cff_put_real_if_ne(cff_writer_t *pcw, double f, double f_default, int op)
324
261k
{
325
261k
    if ((float)f != (float)f_default)
326
4.68k
        cff_put_real_value(pcw, f, op);
327
261k
}
328
static void
329
cff_put_real_deltarray(cff_writer_t *pcw, const float *pf, int count, int op)
330
284k
{
331
284k
    float prev = 0;
332
284k
    int i;
333
334
284k
    if (count <= 0)
335
147k
        return;
336
1.50M
    for (i = 0; i < count; ++i) {
337
1.36M
        float f = pf[i];
338
339
1.36M
        cff_put_real(pcw, f - prev);
340
1.36M
        prev = f;
341
1.36M
    }
342
137k
    cff_put_op(pcw, op);
343
137k
}
344
static int
345
cff_put_string(cff_writer_t *pcw, const byte *data, uint size)
346
226k
{
347
226k
    int sid = cff_string_sid(pcw, data, size);
348
349
226k
    if (sid < 0)
350
0
        return sid;
351
226k
    cff_put_int(pcw, sid);
352
226k
    return 0;
353
226k
}
354
static int
355
cff_put_string_value(cff_writer_t *pcw, const byte *data, uint size, int op)
356
224k
{
357
224k
    int code = cff_put_string(pcw, data, size);
358
359
224k
    if (code >= 0)
360
224k
        cff_put_op(pcw, op);
361
224k
    return code;
362
224k
}
363
static int
364
cff_extra_lenIV(const cff_writer_t *pcw, const gs_font_type1 *pfont)
365
1.10M
{
366
1.10M
    return (pcw->options & WRITE_TYPE2_NO_LENIV ?
367
1.10M
            max(pfont->data.lenIV, 0) : 0);
368
1.10M
}
369
static bool
370
cff_convert_charstrings(const cff_writer_t *pcw, const gs_font_base *pfont)
371
2.07M
{
372
2.07M
    return (pfont->FontType != ft_encrypted2 &&
373
1.96M
            (pcw->options & WRITE_TYPE2_CHARSTRINGS) != 0);
374
2.07M
}
375
static int
376
cff_put_CharString(cff_writer_t *pcw, const byte *data, uint size,
377
                   gs_font_type1 *pfont)
378
897k
{
379
897k
    int lenIV = pfont->data.lenIV;
380
897k
    stream *s = pcw->strm;
381
382
897k
    if (cff_convert_charstrings(pcw, (gs_font_base *)pfont)) {
383
842k
        gs_glyph_data_t gdata;
384
842k
        int code;
385
386
842k
        gdata.memory = pfont->memory;
387
842k
        gs_glyph_data_from_string(&gdata, data, size, NULL);
388
842k
        code = psf_convert_type1_to_type2(s, &gdata, pfont);
389
842k
        if (code < 0)
390
0
            return code;
391
842k
    } else if (lenIV < 0 || !(pcw->options & WRITE_TYPE2_NO_LENIV))
392
55.0k
        put_bytes(s, data, size);
393
0
    else if (size >= lenIV) {
394
        /* Remove encryption. */
395
0
        crypt_state state = crypt_charstring_seed;
396
0
        byte buf[50];   /* arbitrary */
397
0
        uint left, n;
398
399
0
        for (left = lenIV; left > 0; left -= n) {
400
0
            n = min(left, sizeof(buf));
401
0
            gs_type1_decrypt(buf, data + lenIV - left, n, &state);
402
0
        }
403
0
        for (left = size - lenIV; left > 0; left -= n) {
404
0
            n = min(left, sizeof(buf));
405
0
            gs_type1_decrypt(buf, data + size - left, n, &state);
406
0
            put_bytes(s, buf, n);
407
0
        }
408
0
    }
409
897k
    return 0;
410
897k
}
411
static uint
412
cff_Index_size(uint count, uint total)
413
176k
{
414
176k
    return (count == 0 ? 2 :
415
176k
            3 + offset_size(total + 1) * (count + 1) + total);
416
176k
}
417
static void
418
cff_put_Index_header(cff_writer_t *pcw, uint count, uint total)
419
279k
{
420
279k
    put_card16(pcw, count);
421
279k
    if (count > 0) {
422
188k
        pcw->offset_size = offset_size(total + 1);
423
188k
        sputc(pcw->strm, (byte)pcw->offset_size);
424
188k
        put_offset(pcw, 1);
425
188k
    }
426
279k
}
427
static void
428
cff_put_Index(cff_writer_t *pcw, const cff_string_table_t *pcst)
429
46.9k
{
430
46.9k
    uint j, offset;
431
432
46.9k
    if (pcst->count == 0) {
433
181
        put_card16(pcw, 0);
434
181
        return;
435
181
    }
436
46.7k
    cff_put_Index_header(pcw, pcst->count, pcst->total);
437
194k
    for (j = 0, offset = 1; j < pcst->count; ++j) {
438
147k
        offset += pcst->items[j].key.size;
439
147k
        put_offset(pcw, offset);
440
147k
    }
441
194k
    for (j = 0; j < pcst->count; ++j)
442
147k
        put_bytes(pcw->strm, pcst->items[j].key.data, pcst->items[j].key.size);
443
46.7k
}
444
445
/* ---------------- Main code ---------------- */
446
447
/* ------ Header ------ */
448
449
/* Write the header, setting offset_size. */
450
static int
451
cff_write_header(cff_writer_t *pcw, uint end_offset)
452
46.9k
{
453
46.9k
    pcw->offset_size = (end_offset > 0x7fff ? 3 : 2);
454
46.9k
    put_bytes(pcw->strm, (const byte *)"\001\000\004", 3);
455
46.9k
    sputc(pcw->strm, (byte)pcw->offset_size);
456
46.9k
    return 0;
457
46.9k
}
458
459
/* ------ Top Dict ------ */
460
461
/*
462
 * There are 3 variants of this: Type 1 / Type 2 font, CIDFontType 0
463
 * CIDFont, and FDArray entry for CIDFont.
464
 */
465
466
typedef enum {
467
    TOP_version = 0,
468
    TOP_Notice = 1,
469
    TOP_FullName = 2,
470
    TOP_FamilyName = 3,
471
    TOP_Weight = 4,
472
    TOP_FontBBox = 5,
473
    TOP_UniqueID = 13,
474
    TOP_XUID = 14,
475
    TOP_charset = 15,   /* (offset or predefined index) */
476
#define charset_ISOAdobe 0
477
#define charset_Expert 1
478
#define charset_ExpertSubset 2
479
58.5k
#define charset_DEFAULT 0
480
    TOP_Encoding = 16,    /* (offset or predefined index) */
481
#define Encoding_Standard 0
482
#define Encoding_Expert 1
483
58.1k
#define Encoding_DEFAULT 0
484
    TOP_CharStrings = 17, /* (offset) */
485
    TOP_Private = 18,   /* (offset) */
486
    TOP_Copyright = 32,
487
    TOP_isFixedPitch = 33,
488
#define isFixedPitch_DEFAULT false
489
    TOP_ItalicAngle = 34,
490
118k
#define ItalicAngle_DEFAULT 0
491
    TOP_UnderlinePosition = 35,
492
118k
#define UnderlinePosition_DEFAULT (-100)
493
    TOP_UnderlineThickness = 36,
494
118k
#define UnderlineThickness_DEFAULT 50
495
    TOP_PaintType = 37,
496
59.6k
#define PaintType_DEFAULT 0
497
    TOP_CharstringType = 38,
498
58.1k
#define CharstringType_DEFAULT 2
499
    TOP_FontMatrix = 39,  /* default is [0.001 0 0 0.001 0 0] */
500
    TOP_StrokeWidth = 40,
501
59.6k
#define StrokeWidth_DEFAULT 0
502
    TOP_ROS = 62,
503
    TOP_CIDFontVersion = 63,
504
#define CIDFontVersion_DEFAULT 0
505
    TOP_CIDFontRevision = 64,
506
#define CIDFontRevision_DEFAULT 0
507
    TOP_CIDFontType = 65,
508
#define CIDFontType_DEFAULT 0
509
    TOP_CIDCount = 66,
510
407
#define CIDCount_DEFAULT 8720
511
    TOP_UIDBase = 67,
512
    TOP_FDArray = 68,   /* (offset) */
513
    TOP_FDSelect = 69,    /* (offset) */
514
    TOP_FontName = 70   /* only used in FDArray "fonts" */
515
} Top_op;
516
517
static int
518
cff_get_Top_info_common(cff_writer_t *pcw, gs_font_base *pbfont,
519
                        bool full_info, gs_font_info_t *pinfo)
520
59.3k
{
521
59.3k
    pinfo->Flags_requested = FONT_IS_FIXED_WIDTH;
522
    /* Preset defaults */
523
59.3k
    pinfo->members = 0;
524
59.3k
    pinfo->Flags = pinfo->Flags_returned = 0;
525
59.3k
    pinfo->ItalicAngle = ItalicAngle_DEFAULT;
526
59.3k
    pinfo->UnderlinePosition = UnderlinePosition_DEFAULT;
527
59.3k
    pinfo->UnderlineThickness = UnderlineThickness_DEFAULT;
528
59.3k
    return pbfont->procs.font_info
529
59.3k
        ((gs_font *)pbfont, NULL,
530
59.3k
         (full_info ?
531
58.2k
          FONT_INFO_FLAGS | FONT_INFO_ITALIC_ANGLE |
532
58.2k
            FONT_INFO_UNDERLINE_POSITION |
533
58.2k
            FONT_INFO_UNDERLINE_THICKNESS : 0) |
534
59.3k
         (FONT_INFO_COPYRIGHT | FONT_INFO_NOTICE |
535
59.3k
          FONT_INFO_FAMILY_NAME | FONT_INFO_FULL_NAME),
536
59.3k
         pinfo);
537
59.3k
}
538
static void
539
cff_write_Top_common(cff_writer_t *pcw, gs_font_base *pbfont,
540
                     bool write_FontMatrix, const gs_font_info_t *pinfo)
541
59.6k
{
542
    /*
543
     * The Adobe documentation doesn't make it at all clear that if the
544
     * FontMatrix is missing (defaulted) in a CFF CIDFont, all of the
545
     * FontMatrices of the subfonts in FDArray are multiplied by 1000.
546
     * (This is documented for ordinary CIDFonts, but not for CFF CIDFonts.)
547
     * Because of this, the FontMatrix for a CFF CIDFont must be written
548
     * even if if is the default.  write_FontMatrix controls this.
549
     */
550
    /* (version) */
551
59.6k
    if (pinfo->members & FONT_INFO_NOTICE)
552
57.5k
        cff_put_string_value(pcw, pinfo->Notice.data, pinfo->Notice.size,
553
57.5k
                             TOP_Notice);
554
59.6k
    if (pinfo->members & FONT_INFO_FULL_NAME)
555
56.9k
        cff_put_string_value(pcw, pinfo->FullName.data, pinfo->FullName.size,
556
56.9k
                             TOP_FullName);
557
59.6k
    if (pinfo->members & FONT_INFO_FAMILY_NAME)
558
56.9k
        cff_put_string_value(pcw, pinfo->FamilyName.data,
559
56.9k
                             pinfo->FamilyName.size, TOP_FamilyName);
560
59.6k
    if (pcw->FontBBox.p.x != 0 || pcw->FontBBox.p.y != 0 ||
561
11.1k
        pcw->FontBBox.q.x != 0 || pcw->FontBBox.q.y != 0
562
59.6k
        ) {
563
        /* An omitted FontBBox is equivalent to an empty one. */
564
        /*
565
         * Since Acrobat Reader 4 on Solaris doesn't like
566
         * an omitted FontBBox, we copy it here from
567
         * the font descriptor, because the base font
568
         * is allowed to omit it's FontBBox.
569
         */
570
53.4k
        cff_put_real(pcw, pcw->FontBBox.p.x);
571
53.4k
        cff_put_real(pcw, pcw->FontBBox.p.y);
572
53.4k
        cff_put_real(pcw, pcw->FontBBox.q.x);
573
53.4k
        cff_put_real(pcw, pcw->FontBBox.q.y);
574
53.4k
        cff_put_op(pcw, TOP_FontBBox);
575
53.4k
      }
576
59.6k
    if (uid_is_UniqueID(&pbfont->UID))
577
105
        cff_put_int_value(pcw, pbfont->UID.id, TOP_UniqueID);
578
59.5k
    else if (uid_is_XUID(&pbfont->UID) && (pcw->options & WRITE_TYPE2_XUID) != 0) {
579
0
        int j, k = uid_XUID_size(&pbfont->UID);
580
581
        /* Adobe products (specifically Acrobat but the same limitation is mentioned
582
         * in the PLRM) cannot handle XUIDs > 16 entries.
583
         */
584
0
        if (k > 16)
585
0
            k = 16;
586
0
        for (j = 0; j < uid_XUID_size(&pbfont->UID); ++j)
587
0
            cff_put_int(pcw, uid_XUID_values(&pbfont->UID)[j]);
588
0
        cff_put_op(pcw, TOP_XUID);
589
0
    }
590
    /*
591
     * Acrobat Reader 3 gives an error if a CFF font includes any of the
592
     * following opcodes.
593
     */
594
59.6k
    if (!(pcw->options & WRITE_TYPE2_AR3)) {
595
59.6k
        if (pinfo->members & FONT_INFO_COPYRIGHT)
596
52.9k
            cff_put_string_value(pcw, pinfo->Copyright.data,
597
52.9k
                                 pinfo->Copyright.size, TOP_Copyright);
598
59.6k
        if (pinfo->Flags & pinfo->Flags_returned & FONT_IS_FIXED_WIDTH)
599
691
            cff_put_bool_value(pcw, true, TOP_isFixedPitch);
600
59.6k
        cff_put_real_if_ne(pcw, pinfo->ItalicAngle, ItalicAngle_DEFAULT,
601
59.6k
                           TOP_ItalicAngle);
602
59.6k
        cff_put_int_if_ne(pcw, pinfo->UnderlinePosition,
603
59.6k
                          UnderlinePosition_DEFAULT, TOP_UnderlinePosition);
604
59.6k
        cff_put_int_if_ne(pcw, pinfo->UnderlineThickness,
605
59.6k
                          UnderlineThickness_DEFAULT, TOP_UnderlineThickness);
606
59.6k
        cff_put_int_if_ne(pcw, pbfont->PaintType, PaintType_DEFAULT,
607
59.6k
                          TOP_PaintType);
608
59.6k
    }
609
59.6k
    {
610
59.6k
        static const gs_matrix fm_default = {
611
59.6k
            constant_matrix_body(0.001, 0, 0, 0.001, 0, 0)
612
59.6k
        };
613
614
59.6k
        if (write_FontMatrix ||
615
58.1k
            pbfont->FontMatrix.xx != fm_default.xx ||
616
58.0k
            pbfont->FontMatrix.xy != 0 || pbfont->FontMatrix.yx != 0 ||
617
57.8k
            pbfont->FontMatrix.yy != fm_default.yy ||
618
57.8k
            pbfont->FontMatrix.tx != 0 || pbfont->FontMatrix.ty != 0
619
59.6k
            ) {
620
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.xx);
621
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.xy);
622
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.yx);
623
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.yy);
624
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.tx);
625
1.74k
            cff_put_real(pcw, pbfont->FontMatrix.ty);
626
1.74k
            cff_put_op(pcw, TOP_FontMatrix);
627
1.74k
        }
628
59.6k
    }
629
59.6k
    cff_put_real_if_ne(pcw, pbfont->StrokeWidth, StrokeWidth_DEFAULT,
630
59.6k
                       TOP_StrokeWidth);
631
59.6k
}
632
633
/* Type 1 or Type 2 font */
634
static void
635
cff_write_Top_font(cff_writer_t *pcw, uint Encoding_offset,
636
                   uint charset_offset, uint CharStrings_offset,
637
                   uint Private_offset, uint Private_size)
638
58.1k
{
639
58.1k
    gs_font_base *pbfont = (gs_font_base *)pcw->pfont;
640
58.1k
    gs_font_info_t info;
641
642
58.1k
    cff_get_Top_info_common(pcw, pbfont, true, &info);
643
58.1k
    cff_write_Top_common(pcw, pbfont, false, &info);
644
58.1k
    cff_put_int(pcw, Private_size);
645
58.1k
    cff_put_int_value(pcw, Private_offset, TOP_Private);
646
58.1k
    cff_put_int_value(pcw, CharStrings_offset, TOP_CharStrings);
647
58.1k
    cff_put_int_if_ne(pcw, charset_offset, charset_DEFAULT, TOP_charset);
648
58.1k
    cff_put_int_if_ne(pcw, Encoding_offset, Encoding_DEFAULT, TOP_Encoding);
649
58.1k
    {
650
58.1k
        int type = (pcw->options & WRITE_TYPE2_CHARSTRINGS ? 2 :
651
58.1k
                    pbfont->FontType == ft_encrypted2 ? 2 : 1);
652
653
58.1k
        cff_put_int_if_ne(pcw, type, CharstringType_DEFAULT,
654
58.1k
                          TOP_CharstringType);
655
58.1k
    }
656
58.1k
}
657
658
/* CIDFontType 0 CIDFont */
659
static void
660
cff_write_ROS(cff_writer_t *pcw, const gs_cid_system_info_t *pcidsi)
661
508
{
662
508
    cff_put_string(pcw, pcidsi->Registry.data, pcidsi->Registry.size);
663
508
    cff_put_string(pcw, pcidsi->Ordering.data, pcidsi->Ordering.size);
664
508
    cff_put_int_value(pcw, pcidsi->Supplement, TOP_ROS);
665
508
}
666
static void
667
cff_write_Top_cidfont(cff_writer_t *pcw, uint charset_offset,
668
                      uint CharStrings_offset, uint FDSelect_offset,
669
                      uint Font_offset, const gs_font_info_t *pinfo)
670
407
{
671
407
    gs_font_base *pbfont = (gs_font_base *)pcw->pfont;
672
407
    gs_font_cid0 *pfont = (gs_font_cid0 *)pbfont;
673
674
407
    cff_write_ROS(pcw, &pfont->cidata.common.CIDSystemInfo);
675
407
    cff_write_Top_common(pcw, pbfont, true, pinfo); /* full_info = true */
676
407
    cff_put_int_if_ne(pcw, charset_offset, charset_DEFAULT, TOP_charset);
677
407
    cff_put_int_value(pcw, CharStrings_offset, TOP_CharStrings);
678
    /*
679
     * CIDFontVersion and CIDFontRevision aren't used consistently,
680
     * so we don't currently write them.  CIDFontType is always 0.
681
     */
682
407
    cff_put_int_if_ne(pcw, pfont->cidata.common.CIDCount, CIDCount_DEFAULT,
683
407
                      TOP_CIDCount);
684
    /* We don't use UIDBase. */
685
407
    cff_put_int_value(pcw, Font_offset, TOP_FDArray);
686
407
    cff_put_int_value(pcw, FDSelect_offset, TOP_FDSelect);
687
407
}
688
689
/* FDArray Index for CIDFont (offsets only) */
690
static void
691
cff_write_FDArray_offsets(cff_writer_t *pcw, uint *FDArray_offsets,
692
                          int num_fonts)
693
407
{
694
407
    int j;
695
696
407
    cff_put_Index_header(pcw, num_fonts,
697
407
                         FDArray_offsets[num_fonts] - FDArray_offsets[0]);
698
1.24k
    for (j = 1; j <= num_fonts; ++j)
699
834
        put_offset(pcw, FDArray_offsets[j] - FDArray_offsets[0] + 1);
700
407
}
701
702
/* FDArray entry for CIDFont */
703
static void
704
cff_write_Top_fdarray(cff_writer_t *pcw, gs_font_base *pbfont,
705
                      uint Private_offset, uint Private_size)
706
1.04k
{
707
1.04k
    const gs_font_name *pfname = &pbfont->font_name;
708
1.04k
    gs_font_info_t info;
709
710
1.04k
    cff_get_Top_info_common(pcw, pbfont, false, &info);
711
1.04k
    cff_write_Top_common(pcw, pbfont, true, &info);
712
1.04k
    cff_put_int(pcw, Private_size);
713
1.04k
    cff_put_int_value(pcw, Private_offset, TOP_Private);
714
1.04k
    if (pfname->size == 0)
715
32
        pfname = &pbfont->key_name;
716
1.04k
    if (pfname->size) {
717
1.00k
        cff_put_string(pcw, pfname->chars, pfname->size);
718
1.00k
        cff_put_op(pcw, TOP_FontName);
719
1.00k
    }
720
1.04k
}
721
722
/* ------ Private Dict ------ */
723
724
/* Defaults are noted in comments. */
725
typedef enum {
726
    PRIVATE_BlueValues = 6, /* (deltarray) */
727
    PRIVATE_OtherBlues = 7, /* (deltarray) */
728
    PRIVATE_FamilyBlues = 8,  /* (deltarray) */
729
    PRIVATE_FamilyOtherBlues = 9, /* (deltarray) */
730
    PRIVATE_StdHW = 10,
731
    PRIVATE_StdVW = 11,
732
    PRIVATE_Subrs = 19,   /* (offset, relative to Private Dict) */
733
    PRIVATE_defaultWidthX = 20,
734
3.28k
#define defaultWidthX_DEFAULT fixed_0
735
    PRIVATE_nominalWidthX = 21,
736
3.28k
#define nominalWidthX_DEFAULT fixed_0
737
    PRIVATE_BlueScale = 41,
738
47.4k
#define BlueScale_DEFAULT 0.039625
739
    PRIVATE_BlueShift = 42,
740
47.4k
#define BlueShift_DEFAULT 7
741
    PRIVATE_BlueFuzz = 43,
742
47.4k
#define BlueFuzz_DEFAULT 1
743
    PRIVATE_StemSnapH = 44, /* (deltarray) */
744
    PRIVATE_StemSnapV = 45, /* (deltarray) */
745
    PRIVATE_ForceBold = 46,
746
47.4k
#define ForceBold_DEFAULT false
747
    PRIVATE_ForceBoldThreshold = 47,
748
#define ForceBoldThreshold_DEFAULT 0
749
    PRIVATE_lenIV = 48,
750
0
#define lenIV_DEFAULT (-1)
751
    PRIVATE_LanguageGroup = 49,
752
47.4k
#define LanguageGroup_DEFAULT 0
753
    PRIVATE_ExpansionFactor = 50,
754
47.4k
#define ExpansionFactor_DEFAULT 0.06
755
    PRIVATE_initialRandomSeed = 51
756
3.28k
#define initialRandomSeed_DEFAULT 0
757
} Private_op;
758
759
const long default_defaultWidthX = defaultWidthX_DEFAULT; /* For gdevpsfx.c */
760
761
static void
762
cff_write_Private(cff_writer_t *pcw, uint Subrs_offset,
763
                  const gs_font_type1 *pfont)
764
47.4k
{
765
47.4k
#define PUT_FLOAT_TABLE(member, op)\
766
284k
    cff_put_real_deltarray(pcw, pfont->data.member.values,\
767
284k
                           pfont->data.member.count, op)
768
769
47.4k
    PUT_FLOAT_TABLE(BlueValues, PRIVATE_BlueValues);
770
47.4k
    PUT_FLOAT_TABLE(OtherBlues, PRIVATE_OtherBlues);
771
47.4k
    PUT_FLOAT_TABLE(FamilyBlues, PRIVATE_FamilyBlues);
772
47.4k
    PUT_FLOAT_TABLE(FamilyOtherBlues, PRIVATE_FamilyOtherBlues);
773
47.4k
    if (pfont->data.StdHW.count > 0)
774
45.6k
        cff_put_real_value(pcw, pfont->data.StdHW.values[0], PRIVATE_StdHW);
775
47.4k
    if (pfont->data.StdVW.count > 0)
776
45.7k
        cff_put_real_value(pcw, pfont->data.StdVW.values[0], PRIVATE_StdVW);
777
47.4k
    if (Subrs_offset)
778
68
        cff_put_int_value(pcw, Subrs_offset, PRIVATE_Subrs);
779
47.4k
    if (pfont->FontType != ft_encrypted) {
780
3.28k
        if (pfont->data.defaultWidthX != defaultWidthX_DEFAULT)
781
2.02k
            cff_put_real_value(pcw, fixed2float(pfont->data.defaultWidthX),
782
2.02k
                               PRIVATE_defaultWidthX);
783
3.28k
        if (pfont->data.nominalWidthX != nominalWidthX_DEFAULT)
784
1.58k
            cff_put_real_value(pcw, fixed2float(pfont->data.nominalWidthX),
785
1.58k
                               PRIVATE_nominalWidthX);
786
3.28k
        cff_put_int_if_ne(pcw, pfont->data.initialRandomSeed,
787
3.28k
                          initialRandomSeed_DEFAULT,
788
3.28k
                          PRIVATE_initialRandomSeed);
789
3.28k
    }
790
47.4k
    cff_put_real_if_ne(pcw, pfont->data.BlueScale, BlueScale_DEFAULT,
791
47.4k
                       PRIVATE_BlueScale);
792
47.4k
    cff_put_real_if_ne(pcw, pfont->data.BlueShift, BlueShift_DEFAULT,
793
47.4k
                       PRIVATE_BlueShift);
794
47.4k
    cff_put_int_if_ne(pcw, pfont->data.BlueFuzz, BlueFuzz_DEFAULT,
795
47.4k
                      PRIVATE_BlueFuzz);
796
47.4k
    PUT_FLOAT_TABLE(StemSnapH, PRIVATE_StemSnapH);
797
47.4k
    PUT_FLOAT_TABLE(StemSnapV, PRIVATE_StemSnapV);
798
47.4k
    if (pfont->data.ForceBold != ForceBold_DEFAULT)
799
972
        cff_put_bool_value(pcw, pfont->data.ForceBold,
800
972
                           PRIVATE_ForceBold);
801
    /* (ForceBoldThreshold) */
802
47.4k
    if (!(pcw->options & WRITE_TYPE2_NO_LENIV))
803
0
        cff_put_int_if_ne(pcw, pfont->data.lenIV, lenIV_DEFAULT,
804
0
                          PRIVATE_lenIV);
805
47.4k
    cff_put_int_if_ne(pcw, pfont->data.LanguageGroup, LanguageGroup_DEFAULT,
806
47.4k
                      PRIVATE_LanguageGroup);
807
47.4k
    cff_put_real_if_ne(pcw, pfont->data.ExpansionFactor,
808
47.4k
                       ExpansionFactor_DEFAULT, PRIVATE_ExpansionFactor);
809
    /* initialRandomSeed was handled above */
810
811
47.4k
#undef PUT_FLOAT_TABLE
812
47.4k
}
813
814
/* ------ CharStrings Index ------ */
815
816
/* These are separate procedures only for readability. */
817
static int
818
cff_write_CharStrings_offsets(cff_writer_t *pcw, psf_glyph_enum_t *penum,
819
                              uint *pcount)
820
58.6k
{
821
58.6k
    gs_font_base *pfont = pcw->pfont;
822
58.6k
    int offset;
823
58.6k
    gs_glyph glyph;
824
58.6k
    uint count;
825
58.6k
    stream poss;
826
58.6k
    int code;
827
828
58.6k
    s_init(&poss, NULL);
829
58.6k
    psf_enumerate_glyphs_reset(penum);
830
58.6k
    for (glyph = GS_NO_GLYPH, count = 0, offset = 1;
831
1.16M
         (code = psf_enumerate_glyphs_next(penum, &glyph)) != 1;
832
1.10M
         ) {
833
1.10M
        gs_glyph_data_t gdata;
834
1.10M
        gs_font_type1 *pfd;
835
1.10M
        int gcode;
836
837
1.10M
        gdata.memory = pfont->memory;
838
1.10M
        if (code == 0 &&
839
1.10M
            (gcode = pcw->glyph_data(pfont, glyph, &gdata, &pfd)) >= 0
840
1.10M
            ) {
841
1.10M
            int extra_lenIV;
842
843
1.10M
            if (gdata.bits.size >= (extra_lenIV = cff_extra_lenIV(pcw, pfd))) {
844
1.10M
                if (cff_convert_charstrings(pcw, (gs_font_base *)pfd)) {
845
1.05M
                    swrite_position_only(&poss);
846
1.05M
                    code = psf_convert_type1_to_type2(&poss, &gdata, pfd);
847
1.05M
                    if (code < 0)
848
7
                        return code;
849
1.05M
                    offset += stell(&poss);
850
1.05M
                } else
851
50.1k
                    offset += gdata.bits.size - extra_lenIV;
852
1.10M
            }
853
1.10M
            gs_glyph_data_free(&gdata, "cff_write_CharStrings_offsets");
854
1.10M
            put_offset(pcw, offset);
855
1.10M
            count++;
856
1.10M
        }
857
1.10M
    }
858
58.6k
    *pcount = count;
859
58.6k
    return offset - 1;
860
58.6k
}
861
static void
862
cff_write_CharStrings(cff_writer_t *pcw, psf_glyph_enum_t *penum,
863
                      uint charstrings_count, uint charstrings_size)
864
46.9k
{
865
46.9k
    gs_font_base *pfont = pcw->pfont;
866
46.9k
    uint ignore_count;
867
46.9k
    gs_glyph glyph;
868
46.9k
    int code;
869
870
46.9k
    cff_put_Index_header(pcw, charstrings_count, charstrings_size);
871
46.9k
    cff_write_CharStrings_offsets(pcw, penum, &ignore_count);
872
46.9k
    psf_enumerate_glyphs_reset(penum);
873
46.9k
    for (glyph = GS_NO_GLYPH;
874
929k
         (code = psf_enumerate_glyphs_next(penum, &glyph)) != 1;
875
883k
         ) {
876
883k
        gs_glyph_data_t gdata;
877
883k
        gs_font_type1 *pfd;
878
879
883k
        gdata.memory = pfont->memory;
880
883k
        if (code == 0 &&
881
883k
            (code = pcw->glyph_data(pfont, glyph, &gdata, &pfd)) >= 0
882
883k
            ) {
883
883k
            cff_put_CharString(pcw, gdata.bits.data, gdata.bits.size, pfd);
884
883k
            gs_glyph_data_free(&gdata, "cff_write_CharStrings");
885
883k
        }
886
883k
    }
887
46.9k
}
888
889
/* ------ [G]Subrs Index ------ */
890
891
/*
892
 * Currently, we always write all the Subrs, even for subsets.
893
 * We will fix this someday.
894
 */
895
896
static uint
897
cff_write_Subrs_offsets(cff_writer_t *pcw, uint *pcount, gs_font_type1 *pfont,
898
                        bool global)
899
1.60k
{
900
1.60k
    int extra_lenIV = cff_extra_lenIV(pcw, pfont);
901
1.60k
    int j, offset;
902
1.60k
    int code;
903
1.60k
    gs_glyph_data_t gdata;
904
905
1.60k
    gdata.memory = pfont->memory;
906
1.60k
    for (j = 0, offset = 1;
907
19.9k
         (code = pfont->data.procs.subr_data(pfont, j, global, &gdata)) !=
908
19.9k
             gs_error_rangecheck;
909
18.3k
         ++j) {
910
18.3k
        if (code >= 0 && gdata.bits.size >= extra_lenIV)
911
18.3k
            offset += gdata.bits.size - extra_lenIV;
912
18.3k
        put_offset(pcw, offset);
913
18.3k
        if (code >= 0)
914
18.3k
            gs_glyph_data_free(&gdata, "cff_write_Subrs_offsets");
915
18.3k
    }
916
1.60k
    *pcount = j;
917
1.60k
    return offset - 1;
918
1.60k
}
919
920
static void
921
cff_write_Subrs(cff_writer_t *pcw, uint subrs_count, uint subrs_size,
922
                gs_font_type1 *pfont, bool global)
923
100
{
924
100
    int j;
925
100
    uint ignore_count;
926
100
    gs_glyph_data_t gdata;
927
100
    int code;
928
929
100
    gdata.memory = pfont->memory;
930
100
    cff_put_Index_header(pcw, subrs_count, subrs_size);
931
100
    cff_write_Subrs_offsets(pcw, &ignore_count, pfont, global);
932
100
    for (j = 0;
933
14.7k
         (code = pfont->data.procs.subr_data(pfont, j, global, &gdata)) !=
934
14.7k
             gs_error_rangecheck;
935
14.6k
         ++j) {
936
14.6k
        if (code >= 0) {
937
14.6k
            cff_put_CharString(pcw, gdata.bits.data, gdata.bits.size, pfont);
938
14.6k
            gs_glyph_data_free(&gdata, "cff_write_Subrs");
939
14.6k
        }
940
14.6k
    }
941
100
}
942
943
/* ------ Encoding/charset ------ */
944
945
static uint
946
cff_Encoding_size(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
947
11.6k
{
948
11.6k
    int j, code, max_enc = 0, nsupp = 0;
949
11.6k
    gs_font_type1 *pfont = (gs_font_type1 *)pcw->pfont;
950
11.6k
    byte used[255];
951
11.6k
    gs_const_string str;
952
953
11.6k
    memset(used, 0, 255);
954
2.98M
    for (j = 0; j < 256; ++j) {
955
2.97M
        gs_glyph glyph = pfont->procs.encode_char((gs_font *)pfont,
956
2.97M
                                                  (gs_char)j,
957
2.97M
                                                  GLYPH_SPACE_NAME);
958
2.97M
        int i;
959
960
2.97M
        if (glyph == GS_NO_GLYPH || glyph == pgsub->glyphs.notdef)
961
2.76M
            continue;
962
207k
        i = psf_sorted_glyphs_index_of(pgsub->glyphs.subset_data + 1,
963
207k
                                       pgsub->num_encoded, glyph);
964
207k
        if (i < 0)
965
0
            continue;   /* encoded but not in subset */
966
207k
        code = pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
967
207k
        if (code < 0)
968
0
            continue;
969
207k
        if (i >= sizeof(used) || used[i])
970
46
            nsupp++;
971
207k
        else {
972
207k
            used[i] = 1;
973
207k
            if (i > max_enc)
974
35.4k
                max_enc = i;
975
207k
        }
976
207k
    }
977
11.6k
    return 2 + (max_enc+1) + (3 * nsupp) + (nsupp > 0 ? 1 : 0);
978
11.6k
}
979
980
static int
981
cff_write_Encoding(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
982
46.5k
{
983
46.5k
    stream *s = pcw->strm;
984
    /* This procedure is only used for Type 1 / Type 2 fonts. */
985
46.5k
    gs_font_type1 *pfont = (gs_font_type1 *)pcw->pfont;
986
46.5k
    byte used[255], index[255], supplement[256];
987
46.5k
    int num_enc = min(pgsub->num_encoded, sizeof(index));
988
46.5k
    int nsupp = 0;
989
46.5k
    int j, code;
990
46.5k
    int max_enc = 0;
991
46.5k
    gs_const_string str;
992
993
46.5k
    memset(used, 0, num_enc);
994
46.5k
    memset(index, 0, sizeof(index));
995
11.9M
    for (j = 0; j < 256; ++j) {
996
11.9M
        gs_glyph glyph = pfont->procs.encode_char((gs_font *)pfont,
997
11.9M
                                                  (gs_char)j,
998
11.9M
                                                  GLYPH_SPACE_NAME);
999
11.9M
        int i;
1000
1001
11.9M
        if (glyph == GS_NO_GLYPH || glyph == pgsub->glyphs.notdef)
1002
11.0M
            continue;
1003
830k
        i = psf_sorted_glyphs_index_of(pgsub->glyphs.subset_data + 1,
1004
830k
                                       pgsub->num_encoded, glyph);
1005
830k
        if (i < 0)
1006
0
            continue;   /* encoded but not in subset */
1007
830k
        code = pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
1008
830k
        if (code < 0)
1009
0
            continue;
1010
830k
        if (i >= sizeof(used) || used[i])
1011
184
            supplement[nsupp++] = j;
1012
829k
        else {
1013
829k
            index[i] = j;
1014
829k
            used[i] = 1;
1015
829k
            if (i > max_enc)
1016
142k
                max_enc = i;
1017
829k
        }
1018
830k
    }
1019
46.5k
    sputc(s, (byte)(nsupp ? 0x80 : 0));
1020
46.5k
    sputc(s, (byte)max_enc+1);
1021
#ifdef DEBUG
1022
    { int num_enc_chars = pgsub->num_encoded_chars;
1023
1024
        if (nsupp != num_enc_chars - num_enc)
1025
            lprintf3("nsupp = %d, num_enc_chars = %d, num_enc = %d\n",
1026
                     nsupp, num_enc_chars, num_enc);
1027
        for (j = 0; j < num_enc; ++j)
1028
            if (!used[j])
1029
                lprintf2("glyph %d = 0x%lx not used\n", j,
1030
                         pgsub->glyphs.subset_data[j + 1]);
1031
    }
1032
#endif
1033
46.5k
    put_bytes(s, index, max_enc+1);
1034
46.5k
    if (nsupp) {
1035
        /* Write supplementary entries for multiply-encoded glyphs. */
1036
48
        sputc(s, (byte)nsupp);
1037
232
        for (j = 0; j < nsupp; ++j) {
1038
184
            byte chr = supplement[j];
1039
1040
184
            sputc(s, chr);
1041
184
            put_card16(pcw,
1042
184
                cff_glyph_sid(pcw,
1043
184
                              pfont->procs.encode_char((gs_font *)pfont,
1044
184
                                                       (gs_char)chr,
1045
184
                                                       GLYPH_SPACE_NAME)));
1046
184
        }
1047
48
    }
1048
46.5k
    return 0;
1049
46.5k
}
1050
1051
static int
1052
cff_write_charset(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
1053
46.5k
{
1054
46.5k
    int j, code;
1055
1056
46.5k
    sputc(pcw->strm, 0);
1057
876k
    for (j = 1; j < pgsub->glyphs.subset_size; j++) {
1058
829k
        code = cff_glyph_sid(pcw, pgsub->glyphs.subset_data[j]);
1059
829k
        if (code < 0)
1060
0
            continue;
1061
829k
        put_card16(pcw, code);
1062
829k
    }
1063
46.5k
    return 0;
1064
46.5k
}
1065
static int
1066
cff_write_cidset(cff_writer_t *pcw, psf_glyph_enum_t *penum)
1067
508
{
1068
508
    gs_glyph glyph;
1069
508
    int code;
1070
1071
508
    sputc(pcw->strm, 0);
1072
508
    psf_enumerate_glyphs_reset(penum);
1073
8.64k
    while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1074
        /* Skip glyph 0 (the .notdef glyph), which is always first. */
1075
8.13k
        if (glyph != GS_MIN_CID_GLYPH)
1076
7.62k
            put_card16(pcw, (uint)(glyph - GS_MIN_CID_GLYPH));
1077
8.13k
    }
1078
508
    return min(code, 0);
1079
508
}
1080
1081
/* ------ FDSelect ------ */
1082
1083
/* Determine the size of FDSelect. */
1084
static uint
1085
cff_FDSelect_size(cff_writer_t *pcw, psf_glyph_enum_t *penum, uint *pformat)
1086
101
{
1087
101
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pcw->pfont;
1088
101
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1089
101
    gs_glyph glyph;
1090
101
    int prev = -1;
1091
101
    uint linear_size = 1, range_size = 5;
1092
101
    int code;
1093
1094
    /* Determine whether format 0 or 3 is more efficient. */
1095
101
    psf_enumerate_glyphs_reset(penum);
1096
1.72k
    while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1097
1.62k
        int font_index;
1098
1099
1.62k
        code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1100
1.62k
        if (code >= 0) {
1101
1.62k
            if (font_index != prev)
1102
172
                range_size += 3, prev = font_index;
1103
1.62k
            ++linear_size;
1104
1.62k
        }
1105
1.62k
    }
1106
101
    if (range_size < linear_size) {
1107
73
        *pformat = 3;
1108
73
        return range_size;
1109
73
    } else {
1110
28
        *pformat = 0;
1111
28
        return linear_size;
1112
28
    }
1113
101
}
1114
1115
/* Write FDSelect.  size and format were returned by cff_FDSelect_size. */
1116
static int
1117
cff_write_FDSelect(cff_writer_t *pcw, psf_glyph_enum_t *penum, uint size,
1118
                   int format)
1119
407
{
1120
407
    stream *s = pcw->strm;
1121
407
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pcw->pfont;
1122
407
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1123
407
    gs_glyph glyph;
1124
407
    int prev = -1;
1125
407
    uint cid_count = 0;
1126
407
    int code;
1127
1128
407
    spputc(s, (byte)format);
1129
407
    psf_enumerate_glyphs_reset(penum);
1130
407
    switch (format) {
1131
293
    case 3:     /* ranges */
1132
293
        put_card16(pcw, (size - 5) / 3);
1133
6.34k
        while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1134
6.04k
            int font_index;
1135
1136
6.04k
            code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1137
6.04k
            if (code >= 0) {
1138
6.04k
                if (font_index != prev) {
1139
561
                    put_card16(pcw, cid_count);
1140
561
                    sputc(s, (byte)font_index);
1141
561
                    prev = font_index;
1142
561
                }
1143
6.04k
                ++cid_count;
1144
6.04k
            }
1145
6.04k
        }
1146
293
        put_card16(pcw, cid_count);
1147
293
        break;
1148
114
    case 0:     /* linear table */
1149
576
        while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1150
462
            int font_index;
1151
1152
462
            code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1153
462
            if (code >= 0)
1154
462
                sputc(s, (byte)font_index);
1155
462
        }
1156
114
        break;
1157
0
    default:      /* not possible */
1158
0
        return_error(gs_error_rangecheck);
1159
407
    }
1160
407
    return 0;
1161
407
}
1162
1163
/* ------ Main procedure ------ */
1164
1165
/* Write the CFF definition of a Type 1 or Type 2 font. */
1166
int
1167
psf_write_type2_font(stream *s, gs_font_type1 *pfont, int options,
1168
                      gs_glyph *subset_glyphs, uint subset_size,
1169
                      const gs_const_string *alt_font_name,
1170
                      gs_int_rect *FontBBox)
1171
11.6k
{
1172
11.6k
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1173
11.6k
    cff_writer_t writer;
1174
11.6k
    cff_glyph_subset_t subset;
1175
11.6k
    cff_string_item_t *std_string_items;
1176
11.6k
    cff_string_item_t *string_items;
1177
11.6k
    gs_const_string font_name;
1178
11.6k
    stream poss;
1179
11.6k
    uint charstrings_count, charstrings_size;
1180
11.6k
    uint subrs_count, subrs_size;
1181
11.6k
    uint gsubrs_count, gsubrs_size, encoding_size;
1182
11.6k
    int charset_size = -1;
1183
11.6k
    uint number_of_glyphs = 0, number_of_strings;
1184
    /*
1185
     * Set the offsets and sizes to the largest reasonable values
1186
     * (see below).
1187
     */
1188
11.6k
    uint
1189
11.6k
        Top_size = 0x7fffff,
1190
11.6k
        GSubrs_offset,
1191
11.6k
        Encoding_offset,
1192
11.6k
        charset_offset,
1193
11.6k
        CharStrings_offset,
1194
11.6k
        Private_offset,
1195
11.6k
        Private_size = 0x7fffff,
1196
11.6k
        Subrs_offset,
1197
11.6k
        End_offset = 0x7fffff;
1198
11.6k
    int j;
1199
11.6k
    psf_glyph_enum_t genum;
1200
11.6k
    gs_glyph glyph;
1201
11.6k
    long start_pos;
1202
11.6k
    uint offset;
1203
11.6k
    int code;
1204
1205
    /* Allocate the string tables. */
1206
11.6k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1207
11.6k
                               NULL, 0, GLYPH_SPACE_NAME);
1208
230k
    while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1209
218k
        number_of_glyphs++;
1210
11.6k
    subset.glyphs.subset_data = (gs_glyph *)gs_alloc_bytes(pfont->memory,
1211
11.6k
                    (size_t)number_of_glyphs * sizeof(glyph), "psf_write_type2_font");
1212
11.6k
    number_of_strings = number_of_glyphs + MAX_CFF_MISC_STRINGS;
1213
11.6k
    std_string_items = (cff_string_item_t *)gs_alloc_bytes(pfont->memory,
1214
11.6k
                    (MAX_CFF_STD_STRINGS + number_of_strings) * (size_t)sizeof(cff_string_item_t),
1215
11.6k
                    "psf_write_type2_font");
1216
11.6k
    if (std_string_items == NULL || subset.glyphs.subset_data == NULL) {
1217
0
        code = gs_note_error(gs_error_VMerror);
1218
0
        goto error;
1219
0
    }
1220
11.6k
    string_items = std_string_items + MAX_CFF_STD_STRINGS;
1221
1222
    /* Get subset glyphs. */
1223
11.6k
    code = psf_get_type1_glyphs(&subset.glyphs, pfont, subset_glyphs,
1224
11.6k
                              subset_size);
1225
11.6k
    if (code < 0)
1226
0
        goto error;
1227
11.6k
    if (subset.glyphs.notdef == GS_NO_GLYPH) {
1228
0
        code = gs_note_error(gs_error_rangecheck); /* notdef is required */
1229
0
        goto error;
1230
0
    }
1231
1232
    /* If we're writing Type 2 CharStrings, don't encrypt them. */
1233
11.6k
    if (options & WRITE_TYPE2_CHARSTRINGS) {
1234
11.6k
        options |= WRITE_TYPE2_NO_LENIV;
1235
11.6k
        if (pfont->FontType != ft_encrypted2)
1236
11.0k
            pfont->data.defaultWidthX = pfont->data.nominalWidthX = 0;
1237
11.6k
    }
1238
11.6k
    writer.options = options;
1239
11.6k
    s_init(&poss, NULL);
1240
11.6k
    swrite_position_only(&poss);
1241
11.6k
    writer.strm = &poss;
1242
11.6k
    writer.pfont = pbfont;
1243
11.6k
    writer.glyph_data = psf_type1_glyph_data;
1244
11.6k
    writer.offset_size = 1; /* arbitrary */
1245
11.6k
    writer.start_pos = stell(s);
1246
11.6k
    writer.FontBBox = *FontBBox;
1247
1248
    /* Initialize the enumeration of the glyphs. */
1249
11.6k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1250
11.6k
                                subset.glyphs.subset_glyphs,
1251
11.6k
                                (subset.glyphs.subset_glyphs ?
1252
11.6k
                                 subset.glyphs.subset_size : 0),
1253
11.6k
                                GLYPH_SPACE_NAME);
1254
1255
    /* Shuffle the glyphs into the order .notdef, encoded, unencoded. */
1256
11.6k
    {
1257
11.6k
        gs_glyph encoded[256];
1258
11.6k
        int num_enc, num_enc_chars;
1259
1260
        /* Get the list of encoded glyphs. */
1261
2.98M
        for (j = 0, num_enc_chars = 0; j < 256; ++j) {
1262
2.97M
            glyph = pfont->procs.encode_char((gs_font *)pfont, (gs_char)j,
1263
2.97M
                                             GLYPH_SPACE_NAME);
1264
2.97M
            if (glyph != GS_NO_GLYPH && glyph != subset.glyphs.notdef &&
1265
207k
                (subset.glyphs.subset_glyphs == 0 ||
1266
0
                 psf_sorted_glyphs_include(subset.glyphs.subset_data,
1267
0
                                            subset.glyphs.subset_size, glyph)))
1268
207k
                encoded[num_enc_chars++] = glyph;
1269
2.97M
        }
1270
11.6k
        subset.num_encoded_chars = num_enc_chars;
1271
11.6k
        subset.num_encoded = num_enc =
1272
11.6k
            psf_sort_glyphs(encoded, num_enc_chars);
1273
1274
        /* Get the complete list of glyphs if we don't have it already. */
1275
11.6k
        if (!subset.glyphs.subset_glyphs) {
1276
11.6k
            int num_glyphs = 0;
1277
1278
11.6k
            psf_enumerate_glyphs_reset(&genum);
1279
230k
            while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1280
218k
                if (code == 0) {
1281
218k
                    if (num_glyphs == number_of_glyphs){
1282
0
                        code = gs_note_error(gs_error_limitcheck);
1283
0
                        goto error;
1284
0
                    }
1285
218k
                    subset.glyphs.subset_data[num_glyphs++] = glyph;
1286
218k
                }
1287
11.6k
            subset.glyphs.subset_size =
1288
11.6k
                psf_sort_glyphs(subset.glyphs.subset_data, num_glyphs);
1289
11.6k
            subset.glyphs.subset_glyphs = subset.glyphs.subset_data;
1290
11.6k
        }
1291
1292
        /* Move the unencoded glyphs to the top of the list. */
1293
        /*
1294
         * We could do this in time N rather than N log N with a two-finger
1295
         * algorithm, but it doesn't seem worth the trouble right now.
1296
         */
1297
11.6k
        {
1298
11.6k
            int from = subset.glyphs.subset_size;
1299
11.6k
            int to = from;
1300
1301
230k
            while (from > 0) {
1302
218k
                glyph = subset.glyphs.subset_data[--from];
1303
218k
                if (glyph != subset.glyphs.notdef &&
1304
207k
                    !psf_sorted_glyphs_include(encoded, num_enc, glyph))
1305
5
                    subset.glyphs.subset_data[--to] = glyph;
1306
218k
            }
1307
#ifdef DEBUG
1308
            if (to != num_enc + 1)
1309
                lprintf2("to = %d, num_enc + 1 = %d\n", to, num_enc + 1);
1310
#endif
1311
11.6k
        }
1312
1313
        /* Move .notdef and the encoded glyphs to the bottom of the list. */
1314
11.6k
        subset.glyphs.subset_data[0] = subset.glyphs.notdef;
1315
11.6k
        memcpy(subset.glyphs.subset_data + 1, encoded,
1316
11.6k
               sizeof(encoded[0]) * num_enc);
1317
11.6k
    }
1318
1319
    /* Set the font name. */
1320
11.6k
    if (alt_font_name)
1321
11.6k
        font_name = *alt_font_name;
1322
0
    else
1323
0
        font_name.data = pfont->font_name.chars,
1324
0
            font_name.size = pfont->font_name.size;
1325
1326
    /* Initialize the string tables. */
1327
11.6k
    cff_string_table_init(&writer.std_strings, std_string_items,
1328
11.6k
                          MAX_CFF_STD_STRINGS);
1329
4.55M
    for (j = 0; (glyph = gs_c_known_encode((gs_char)j,
1330
4.55M
                                ENCODING_INDEX_CFFSTRINGS)) != GS_NO_GLYPH;
1331
4.54M
         ++j) {
1332
4.54M
        gs_const_string str;
1333
4.54M
        int ignore;
1334
1335
4.54M
        gs_c_glyph_name(glyph, &str);
1336
4.54M
        cff_string_index(&writer.std_strings, str.data, str.size, true,
1337
4.54M
                         &ignore);
1338
4.54M
    }
1339
11.6k
    cff_string_table_init(&writer.strings, string_items, number_of_strings);
1340
1341
    /* Enter miscellaneous strings in the string table. */
1342
11.6k
    cff_write_Top_font(&writer, 0, 0, 0, 0, 0);
1343
1344
    /* Enter the glyph names in the string table. */
1345
    /* (Note that we have changed the glyph list.) */
1346
11.6k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1347
11.6k
                               subset.glyphs.subset_data,
1348
11.6k
                               subset.glyphs.subset_size,
1349
11.6k
                               GLYPH_SPACE_NAME);
1350
230k
    while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1351
218k
        if (code == 0) {
1352
218k
            code = cff_glyph_sid(&writer, glyph);
1353
218k
            if (code == gs_error_undefined)
1354
0
                continue;
1355
218k
            if (code < 0)
1356
0
                goto error;
1357
218k
            charset_size += 2;
1358
218k
        }
1359
1360
    /*
1361
     * The CFF specification says that the Encoding, charset, CharStrings,
1362
     * Private, and Local Subr sections may be in any order.  To minimize
1363
     * the risk of incompatibility with Adobe software, we produce them in
1364
     * the order just mentioned.
1365
     */
1366
1367
    /*
1368
     * Compute the size of the GSubrs Index, if not omitted.
1369
     */
1370
11.6k
    if ((options & WRITE_TYPE2_NO_GSUBRS) != 0 ||
1371
11.6k
        cff_convert_charstrings(&writer, pbfont) /* we expand all Subrs */
1372
11.6k
        )
1373
11.0k
        gsubrs_count = 0, gsubrs_size = 0;
1374
599
    else
1375
599
        gsubrs_size = cff_write_Subrs_offsets(&writer, &gsubrs_count,
1376
599
                                              pfont, true);
1377
1378
    /*
1379
     * Compute the size of the Encoding.  For simplicity, we currently
1380
     * always store the Encoding explicitly.  Note that because CFF stores
1381
     * the Encoding in an "inverted" form, we need to count the number of
1382
     * glyphs that occur at more than one place in the Encoding.
1383
     */
1384
11.6k
    encoding_size = cff_Encoding_size(&writer, &subset);
1385
1386
    /* Compute the size of the CharStrings Index. */
1387
11.6k
    code = cff_write_CharStrings_offsets(&writer, &genum, &charstrings_count);
1388
11.6k
    if (code < 0)
1389
7
        goto error;
1390
11.6k
    charstrings_size = (uint)code;
1391
1392
    /* Compute the size of the (local) Subrs Index. */
1393
11.6k
#ifdef SKIP_EMPTY_SUBRS
1394
11.6k
    subrs_size =
1395
11.6k
        (cff_convert_charstrings(&writer, pbfont) ? 0 :
1396
11.6k
         cff_write_Subrs_offsets(&writer, &subrs_count, pfont, false));
1397
#else
1398
    if (cff_convert_charstrings(&writer, pbfont))
1399
        subrs_count = 0;  /* we expand all Subrs */
1400
    subrs_size = cff_write_Subrs_offsets(&writer, &subrs_count, pfont, false);
1401
#endif
1402
1403
    /*
1404
     * The offsets of the Private Dict and the CharStrings Index
1405
     * depend on the size of the Top Dict; the offset of the Subrs also
1406
     * depends on the size of the Private Dict.  However, the size of the
1407
     * Top Dict depends on the offsets of the CharStrings Index, the
1408
     * charset, and the Encoding, and on the offset and size of the Private
1409
     * Dict, because of the variable-length encoding of the offsets and
1410
     * size; for the same reason, the size of the Private Dict depends on
1411
     * the offset of the Subrs.  Fortunately, the relationship between the
1412
     * value of an offset or size and the size of its encoding is monotonic.
1413
     * Therefore, we start by assuming the largest reasonable value for all
1414
     * the sizes and iterate until everything converges.
1415
     */
1416
34.9k
 iter:
1417
34.9k
    swrite_position_only(&poss);
1418
34.9k
    writer.strm = &poss;
1419
1420
    /* Compute the offsets. */
1421
34.9k
    GSubrs_offset = 4 + cff_Index_size(1, font_name.size) +
1422
34.9k
        cff_Index_size(1, Top_size) +
1423
34.9k
        cff_Index_size(writer.strings.count, writer.strings.total);
1424
34.9k
    Encoding_offset = GSubrs_offset +
1425
34.9k
        cff_Index_size(gsubrs_count, gsubrs_size);
1426
34.9k
    charset_offset = Encoding_offset + encoding_size;
1427
34.9k
    CharStrings_offset = charset_offset + charset_size;
1428
34.9k
    Private_offset = CharStrings_offset +
1429
34.9k
        cff_Index_size(charstrings_count, charstrings_size);
1430
34.9k
    Subrs_offset = Private_size;  /* relative to Private Dict */
1431
1432
46.5k
 write:
1433
46.5k
    if(check_ioerror(writer.strm)) {
1434
0
        code = gs_note_error(gs_error_ioerror);
1435
0
        goto error;
1436
0
    }
1437
46.5k
    start_pos = stell(writer.strm);
1438
    /* Write the header, setting offset_size. */
1439
46.5k
    cff_write_header(&writer, End_offset);
1440
1441
    /* Write the names Index. */
1442
46.5k
    cff_put_Index_header(&writer, 1, font_name.size);
1443
46.5k
    put_offset(&writer, font_name.size + 1);
1444
46.5k
    put_bytes(writer.strm, font_name.data, font_name.size);
1445
1446
    /* Write the Top Index. */
1447
46.5k
    cff_put_Index_header(&writer, 1, Top_size);
1448
46.5k
    put_offset(&writer, Top_size + 1);
1449
46.5k
    offset = stell(writer.strm) - start_pos;
1450
46.5k
    cff_write_Top_font(&writer, Encoding_offset, charset_offset,
1451
46.5k
                       CharStrings_offset,
1452
46.5k
                       Private_offset, Private_size);
1453
46.5k
    Top_size = stell(writer.strm) - start_pos - offset;
1454
1455
    /* Write the strings Index. */
1456
46.5k
    cff_put_Index(&writer, &writer.strings);
1457
46.5k
    if(check_ioerror(writer.strm)){
1458
0
        code = gs_note_error(gs_error_ioerror);
1459
0
        goto error;
1460
0
    }
1461
1462
    /* Write the GSubrs Index, if any, checking the offset. */
1463
46.5k
    offset = stell(writer.strm) - start_pos;
1464
46.5k
    if_debug2m('l', s->memory, "[l]GSubrs = %u => %u\n", GSubrs_offset, offset);
1465
46.5k
    if (offset > GSubrs_offset) {
1466
0
        code = gs_note_error(gs_error_rangecheck);
1467
0
        goto error;
1468
0
    }
1469
46.5k
    GSubrs_offset = offset;
1470
46.5k
    if (gsubrs_count == 0 || cff_convert_charstrings(&writer, pbfont))
1471
46.5k
        cff_put_Index_header(&writer, 0, 0);
1472
12
    else
1473
12
        cff_write_Subrs(&writer, gsubrs_count, gsubrs_size, pfont, true);
1474
1475
    /* Write the Encoding. */
1476
46.5k
    cff_write_Encoding(&writer, &subset);
1477
1478
    /* Write the charset. */
1479
46.5k
    cff_write_charset(&writer, &subset);
1480
1481
    /* Write the CharStrings Index, checking the offset. */
1482
46.5k
    offset = stell(writer.strm) - start_pos;
1483
46.5k
    if (offset > CharStrings_offset) {
1484
0
        code = gs_note_error(gs_error_rangecheck);
1485
0
        goto error;
1486
0
    }
1487
46.5k
    CharStrings_offset = offset;
1488
46.5k
    cff_write_CharStrings(&writer, &genum, charstrings_count,
1489
46.5k
                          charstrings_size);
1490
46.5k
    if(check_ioerror(writer.strm)) {
1491
0
        code = gs_note_error(gs_error_ioerror);
1492
0
        goto error;
1493
0
    }
1494
1495
    /* Write the Private Dict, checking the offset. */
1496
46.5k
    offset = stell(writer.strm) - start_pos;
1497
46.5k
    if (offset > Private_offset) {
1498
0
        code = gs_note_error(gs_error_rangecheck);
1499
0
        goto error;
1500
0
    }
1501
46.5k
    Private_offset = offset;
1502
46.5k
    cff_write_Private(&writer, (subrs_size == 0 ? 0 : Subrs_offset), pfont);
1503
46.5k
    Private_size = stell(writer.strm) - start_pos - offset;
1504
1505
    /* Write the Subrs Index, checking the offset. */
1506
46.5k
    offset = stell(writer.strm) - (start_pos + Private_offset);
1507
46.5k
    if (offset > Subrs_offset) {
1508
0
        code = gs_note_error(gs_error_rangecheck);
1509
0
        goto error;
1510
0
    }
1511
46.5k
    Subrs_offset = offset;
1512
46.5k
    if (cff_convert_charstrings(&writer, pbfont))
1513
44.1k
        cff_put_Index_header(&writer, 0, 0);
1514
2.44k
    else if (subrs_size != 0)
1515
12
        cff_write_Subrs(&writer, subrs_count, subrs_size, pfont, false);
1516
1517
    /* Check the final offset. */
1518
46.5k
    if(check_ioerror(writer.strm)) {
1519
0
        code = gs_note_error(gs_error_ioerror);
1520
0
        goto error;
1521
0
    }
1522
46.5k
    offset = stell(writer.strm) - start_pos;
1523
46.5k
    if (offset > End_offset) {
1524
0
        code = gs_note_error(gs_error_rangecheck);
1525
0
        goto error;
1526
0
    }
1527
46.5k
    if (offset == End_offset) {
1528
        /* The iteration has converged.  Write the result. */
1529
23.2k
        if (writer.strm == &poss) {
1530
11.6k
            writer.strm = s;
1531
11.6k
            goto write;
1532
11.6k
        }
1533
23.3k
    } else {
1534
        /* No convergence yet. */
1535
23.3k
        End_offset = offset;
1536
23.3k
        goto iter;
1537
23.3k
    }
1538
1539
    /* All done. */
1540
11.6k
    gs_free_object(pfont->memory, std_string_items, "psf_write_type2_font");
1541
11.6k
    gs_free_object(pfont->memory, subset.glyphs.subset_data, "psf_write_type2_font");
1542
11.6k
    return 0;
1543
1544
7
error:
1545
7
    gs_free_object(pfont->memory, std_string_items, "psf_write_type2_font");
1546
7
    gs_free_object(pfont->memory, subset.glyphs.subset_data, "psf_write_type2_font");
1547
7
    subset.glyphs.subset_data = NULL;
1548
7
    return code;
1549
46.5k
}
1550
1551
/* Write the CFF definition of a CIDFontType 0 font (CIDFont). */
1552
static int
1553
cid0_glyph_data(gs_font_base *pbfont, gs_glyph glyph, gs_glyph_data_t *pgd,
1554
                gs_font_type1 **ppfont)
1555
16.2k
{
1556
16.2k
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pbfont;
1557
16.2k
    int font_index;
1558
16.2k
    int code = pfont->cidata.glyph_data(pbfont, glyph, pgd, &font_index);
1559
1560
16.2k
    if (code >= 0)
1561
16.2k
        *ppfont = pfont->cidata.FDArray[font_index];
1562
16.2k
    return code;
1563
16.2k
}
1564
#ifdef DEBUG
1565
static int
1566
offset_error(const char *msg)
1567
{
1568
    if_debug1('l', "[l]%s offset error\n", msg);
1569
    return_error(gs_error_rangecheck);
1570
}
1571
#else
1572
#  define offset_error(msg) gs_error_rangecheck
1573
#endif
1574
int
1575
psf_write_cid0_font(stream *s, gs_font_cid0 *pfont, int options,
1576
                    const byte *subset_cids, uint subset_size,
1577
                    const gs_const_string *alt_font_name)
1578
101
{
1579
    /*
1580
     * CIDFontType 0 fonts differ from ordinary Type 1 / Type 2 fonts
1581
     * as follows:
1582
     *   The TOP Dict starts with a ROS operator.
1583
     *   The TOP Dict must include FDArray and FDSelect operators.
1584
     *   The TOP Dict may include CIDFontVersion, CIDFontRevision,
1585
     *     CIDFontType, CIDCount, and UIDBase operators.
1586
     *   The TOP Dict must not include an Encoding operator.
1587
     *   The charset is defined in terms of CIDs rather than SIDs.
1588
     *   FDArray references a Font Index in which each element is a Dict
1589
     *     defining a font without charset, Encoding, or CharStrings.
1590
     *   FDSelect references a structure mapping CIDs to font numbers.
1591
     */
1592
101
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1593
101
    cff_writer_t writer;
1594
101
    cff_string_item_t std_string_items[500]; /* 391 entries used */
1595
    /****** HOW TO DETERMINE THE SIZE OF STRINGS? ******/
1596
101
    cff_string_item_t string_items[500 /* character names */ +
1597
101
                                   40 /* misc. values */];
1598
101
    gs_const_string font_name;
1599
101
    stream poss;
1600
101
    uint charstrings_count, charstrings_size;
1601
101
    uint gsubrs_count, gsubrs_size;
1602
101
    uint charset_size, fdselect_size, fdselect_format;
1603
101
    uint subrs_count[256], subrs_size[256];
1604
    /*
1605
     * Set the offsets and sizes to the largest reasonable values
1606
     * (see below).
1607
     */
1608
101
    uint
1609
101
        Top_size = 0x7fffff,
1610
101
        GSubrs_offset = 0x1ffffff,
1611
101
        charset_offset = 0x1ffffff,
1612
101
        FDSelect_offset = 0x1ffffff,
1613
101
        CharStrings_offset = 0x1ffffff,
1614
101
        Font_offset = 0x1ffffff,
1615
101
        FDArray_offsets[257],
1616
101
        Private_offsets[257],
1617
101
        Subrs_offsets[257],
1618
101
        End_offset = 0x1ffffff;
1619
101
    int j;
1620
101
    psf_glyph_enum_t genum;
1621
101
    gs_font_info_t info;
1622
101
    long start_pos;
1623
101
    uint offset;
1624
101
    int num_fonts = pfont->cidata.FDArray_size;
1625
101
    int code;
1626
1627
101
    if (num_fonts > 256)
1628
0
        return_error(gs_error_invalidfont);
1629
1630
101
    memset(&subrs_count, 0x00, 256 * sizeof(uint));
1631
101
    memset(&subrs_size, 0x00, 256 * sizeof(uint));
1632
1633
    /* Initialize the enumeration of the glyphs. */
1634
101
    psf_enumerate_cids_begin(&genum, (gs_font *)pfont, subset_cids,
1635
101
                             subset_size);
1636
1637
    /* Check that the font can be written. */
1638
101
    code = psf_check_outline_glyphs((gs_font_base *)pfont, &genum,
1639
101
                                    cid0_glyph_data);
1640
101
    if (code < 0)
1641
0
        return code;
1642
    /* The .notdef glyph (glyph 0) must be included. */
1643
101
    if (subset_cids && subset_size > 0 && !(subset_cids[0] & 0x80))
1644
0
        return_error(gs_error_rangecheck);
1645
1646
101
    writer.options = options;
1647
101
    s_init(&poss, NULL);
1648
101
    swrite_position_only(&poss);
1649
101
    writer.strm = &poss;
1650
101
    writer.pfont = pbfont;
1651
101
    writer.glyph_data = cid0_glyph_data;
1652
101
    writer.offset_size = 1; /* arbitrary */
1653
101
    writer.start_pos = stell(s);
1654
101
    writer.FontBBox.p.x = writer.FontBBox.p.y = 0;
1655
101
    writer.FontBBox.q.x = writer.FontBBox.q.y = 0;
1656
1657
    /* Set the font name. */
1658
101
    if (alt_font_name)
1659
101
        font_name = *alt_font_name;
1660
0
    else if (pfont->font_name.size)
1661
0
        font_name.data = pfont->font_name.chars,
1662
0
            font_name.size = pfont->font_name.size;
1663
0
    else
1664
0
        font_name.data = pfont->key_name.chars,
1665
0
            font_name.size = pfont->key_name.size;
1666
1667
    /* Initialize the string tables. */
1668
101
    cff_string_table_init(&writer.std_strings, std_string_items,
1669
101
                          countof(std_string_items));
1670
101
    cff_string_table_init(&writer.strings, string_items,
1671
101
                          countof(string_items));
1672
1673
    /* Make all entries in the string table. */
1674
101
    cff_write_ROS(&writer, &pfont->cidata.common.CIDSystemInfo);
1675
308
    for (j = 0; j < num_fonts; ++j) {
1676
207
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1677
1678
207
        cff_write_Top_fdarray(&writer, (gs_font_base *)pfd, 0, 0);
1679
207
    }
1680
1681
    /*
1682
     * The CFF specification says that sections after the initial Indexes
1683
     * may be in any order.  To minimize the risk of incompatibility with
1684
     * Adobe software, we produce them in the order illustrated in the
1685
     * specification.
1686
     */
1687
1688
    /* Initialize the offset arrays. */
1689
409
    for (j = 0; j <= num_fonts; ++j)
1690
308
        FDArray_offsets[j] = Private_offsets[j] = Subrs_offsets[j] =
1691
308
            0x7effffff / num_fonts * j + 0x1000000;
1692
1693
    /*
1694
     * Compute the size of the GSubrs Index, if not omitted.
1695
     * Arbitrarily use FDArray[0] to access the GSubrs and to determine
1696
     * the CharString type.
1697
     */
1698
101
    if ((options & WRITE_TYPE2_NO_GSUBRS) != 0 ||
1699
101
        cff_convert_charstrings(&writer,
1700
101
                        (const gs_font_base *)pfont->cidata.FDArray[0])
1701
                                /* we expand all Subrs */
1702
101
        )
1703
0
        gsubrs_count = 0, gsubrs_size = 0;
1704
101
    else
1705
101
        gsubrs_size = cff_write_Subrs_offsets(&writer, &gsubrs_count,
1706
101
                                              pfont->cidata.FDArray[0], true);
1707
1708
    /*
1709
     * Compute the size of the charset.  For simplicity, we currently
1710
     * always store the charset explicitly.
1711
     */
1712
101
    swrite_position_only(&poss);
1713
101
    cff_write_cidset(&writer, &genum);
1714
101
    charset_size = stell(&poss);
1715
1716
    /* Compute the size of the FDSelect strucure. */
1717
101
    fdselect_size = cff_FDSelect_size(&writer, &genum, &fdselect_format);
1718
1719
    /* Compute the size of the CharStrings Index. */
1720
    /* Compute the size of the CharStrings Index. */
1721
101
    code = cff_write_CharStrings_offsets(&writer, &genum, &charstrings_count);
1722
101
    if (code < 0)
1723
0
        return code;
1724
101
    charstrings_size = (uint)code;
1725
1726
    /* Compute the size of the (local) Subrs Indexes. */
1727
308
    for (j = 0; j < num_fonts; ++j) {
1728
207
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1729
1730
207
#ifdef SKIP_EMPTY_SUBRS
1731
207
        subrs_size[j] =
1732
207
            (cff_convert_charstrings(&writer, (gs_font_base *)pfd) ? 0 :
1733
207
             cff_write_Subrs_offsets(&writer, &subrs_count[j], pfd, false));
1734
#else
1735
        if (cff_convert_charstrings(&writer, (gs_font_base *)pfd))
1736
            subrs_count[j] = 0;  /* we expand all Subrs */
1737
        subrs_size[j] = cff_write_Subrs_offsets(&writer, &subrs_count[j], pfd, false);
1738
#endif
1739
207
    }
1740
1741
    /* Get the font_info once, since it may be expensive. */
1742
101
    cff_get_Top_info_common(&writer, (gs_font_base *)pfont, true, &info);
1743
1744
    /*
1745
     * The offsets of the Private Dict and the CharStrings Index
1746
     * depend on the size of the Top Dict; the offset of the Subrs also
1747
     * depends on the size of the Private Dict.  However, the size of the
1748
     * Top Dict depends on the offsets of the CharStrings Index and the
1749
     * charset, and on the offset and size of the Private Dict,
1750
     * because of the variable-length encoding of the offsets and
1751
     * size; for the same reason, the size of the Private Dict depends on
1752
     * the offset of the Subrs.  Fortunately, the relationship between the
1753
     * value of an offset or size and the size of its encoding is monotonic.
1754
     * Therefore, we start by assuming the largest reasonable value for all
1755
     * the sizes and iterate until everything converges.
1756
     */
1757
306
 iter:
1758
306
    swrite_position_only(&poss);
1759
306
    writer.strm = &poss;
1760
1761
    /* Compute the offsets. */
1762
306
    GSubrs_offset = 4 + cff_Index_size(1, font_name.size) +
1763
306
        cff_Index_size(1, Top_size) +
1764
306
        cff_Index_size(writer.strings.count, writer.strings.total);
1765
306
    charset_offset = GSubrs_offset +
1766
306
        cff_Index_size(gsubrs_count, gsubrs_size);
1767
306
    FDSelect_offset = charset_offset + charset_size;
1768
306
    CharStrings_offset = FDSelect_offset + fdselect_size;
1769
306
    if_debug4m('l', s->memory,
1770
306
               "[l]GSubrs at %u, charset at %u, FDSelect at %u, CharStrings at %u\n",
1771
306
               GSubrs_offset, charset_offset, FDSelect_offset, CharStrings_offset);
1772
1773
407
 write:
1774
407
    start_pos = stell(writer.strm);
1775
407
    if_debug1m('l', s->memory, "[l]start_pos = %ld\n", start_pos);
1776
    /* Write the header, setting offset_size. */
1777
407
    cff_write_header(&writer, End_offset);
1778
1779
    /* Write the names Index. */
1780
407
    cff_put_Index_header(&writer, 1, font_name.size);
1781
407
    put_offset(&writer, font_name.size + 1);
1782
407
    put_bytes(writer.strm, font_name.data, font_name.size);
1783
1784
    /* Write the Top Index. */
1785
407
    cff_put_Index_header(&writer, 1, Top_size);
1786
407
    put_offset(&writer, Top_size + 1);
1787
407
    offset = stell(writer.strm) - start_pos;
1788
407
    cff_write_Top_cidfont(&writer, charset_offset, CharStrings_offset,
1789
407
                          FDSelect_offset, Font_offset, &info);
1790
407
    Top_size = stell(writer.strm) - start_pos - offset;
1791
407
    if_debug1m('l', s->memory, "[l]Top_size = %u\n", Top_size);
1792
1793
    /* Write the strings Index. */
1794
407
    cff_put_Index(&writer, &writer.strings);
1795
1796
    /* Write the GSubrs Index, if any, checking the offset. */
1797
407
    offset = stell(writer.strm) - start_pos;
1798
407
    if_debug2m('l', s->memory, "[l]GSubrs = %u => %u\n", GSubrs_offset, offset);
1799
407
    if (offset > GSubrs_offset)
1800
0
        return_error(gs_error_rangecheck);
1801
407
    GSubrs_offset = offset;
1802
407
    if (gsubrs_count == 0 ||
1803
20
        cff_convert_charstrings(&writer,
1804
20
                        (const gs_font_base *)pfont->cidata.FDArray[0])
1805
407
        )
1806
387
        cff_put_Index_header(&writer, 0, 0);
1807
20
    else
1808
20
        cff_write_Subrs(&writer, gsubrs_count, gsubrs_size,
1809
20
                        pfont->cidata.FDArray[0], true);
1810
1811
    /* Write the charset. */
1812
407
    if_debug1m('l', s->memory, "[l]charset = %"PRId64"\n", (int64_t)(stell(writer.strm) - start_pos));
1813
407
    cff_write_cidset(&writer, &genum);
1814
1815
    /* Write the FDSelect structure, checking the offset. */
1816
407
    offset = stell(writer.strm) - start_pos;
1817
407
    if_debug2m('l', s->memory, "[l]FDSelect = %u => %u\n", FDSelect_offset, offset);
1818
407
    if (offset > FDSelect_offset)
1819
0
        return_error(offset_error("FDselect"));
1820
407
    FDSelect_offset = offset;
1821
407
    cff_write_FDSelect(&writer, &genum, fdselect_size, fdselect_format);
1822
1823
    /* Write the CharStrings Index, checking the offset. */
1824
407
    offset = stell(writer.strm) - start_pos;
1825
407
    if_debug2m('l', s->memory, "[l]CharStrings = %u => %u\n", CharStrings_offset, offset);
1826
407
    if (offset > CharStrings_offset)
1827
0
        return_error(offset_error("CharStrings"));
1828
407
    CharStrings_offset = offset;
1829
407
    cff_write_CharStrings(&writer, &genum, charstrings_count,
1830
407
                          charstrings_size);
1831
1832
    /* Write the Font Dict Index. */
1833
407
    offset = stell(writer.strm) - start_pos;
1834
407
    if_debug2m('l', s->memory, "[l]Font = %u => %u\n", Font_offset, offset);
1835
407
    if (offset > Font_offset)
1836
0
        return_error(offset_error("Font"));
1837
407
    Font_offset = offset;
1838
407
    cff_write_FDArray_offsets(&writer, FDArray_offsets, num_fonts);
1839
407
    offset = stell(writer.strm) - start_pos;
1840
407
    if_debug2m('l', s->memory, "[l]FDArray[0] = %u => %u\n", FDArray_offsets[0], offset);
1841
407
    if (offset > FDArray_offsets[0])
1842
0
        return_error(offset_error("FDArray[0]"));
1843
407
    FDArray_offsets[0] = offset;
1844
1.24k
    for (j = 0; j < num_fonts; ++j) {
1845
834
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1846
1847
        /* If we're writing Type 2 CharStrings, don't encrypt them. */
1848
834
        if (options & WRITE_TYPE2_CHARSTRINGS) {
1849
834
            options |= WRITE_TYPE2_NO_LENIV;
1850
834
            if (pfd->FontType != ft_encrypted2)
1851
0
                pfd->data.defaultWidthX = pfd->data.nominalWidthX = 0;
1852
834
        }
1853
834
        cff_write_Top_fdarray(&writer, (gs_font_base *)pfd, Private_offsets[j],
1854
834
                              Private_offsets[j + 1] - Private_offsets[j]);
1855
834
        offset = stell(writer.strm) - start_pos;
1856
834
        if_debug3m('l', s->memory, "[l]FDArray[%d] = %u => %u\n", j + 1,
1857
834
                   FDArray_offsets[j + 1], offset);
1858
834
        if (offset > FDArray_offsets[j + 1])
1859
0
            return_error(offset_error("FDArray"));
1860
834
        FDArray_offsets[j + 1] = offset;
1861
834
    }
1862
1863
    /* Write the Private Dicts, checking the offset. */
1864
1.24k
    for (j = 0; ; ++j) {
1865
1.24k
        gs_font_type1 *pfd;
1866
1867
1.24k
        offset = stell(writer.strm) - start_pos;
1868
1.24k
        if_debug3m('l', s->memory, "[l]Private[%d] = %u => %u\n",
1869
1.24k
                   j, Private_offsets[j], offset);
1870
1.24k
        if (offset > Private_offsets[j])
1871
0
            return_error(offset_error("Private"));
1872
1.24k
        Private_offsets[j] = offset;
1873
1.24k
        if (j == num_fonts)
1874
407
            break;
1875
834
        pfd = pfont->cidata.FDArray[j];
1876
834
        cff_write_Private(&writer,
1877
834
                          (subrs_size[j] == 0 ? 0 : Subrs_offsets[j]), pfd);
1878
834
    }
1879
1880
    /* Write the Subrs Indexes, checking the offsets. */
1881
1.24k
    for (j = 0; ; ++j) {
1882
1.24k
        gs_font_type1 *pfd;
1883
1884
1.24k
        offset = stell(writer.strm) - (start_pos + Private_offsets[j]);
1885
1.24k
        if_debug3m('l', s->memory, "[l]Subrs[%d] = %u => %u\n",
1886
1.24k
                   j, Subrs_offsets[j], offset);
1887
1.24k
        if (offset > Subrs_offsets[j])
1888
0
            return_error(offset_error("Subrs"));
1889
1.24k
        Subrs_offsets[j] = offset;
1890
1.24k
        if (j == num_fonts)
1891
407
            break;
1892
834
        pfd = pfont->cidata.FDArray[j];
1893
834
        if (cff_convert_charstrings(&writer, (gs_font_base *)pfd))
1894
0
            cff_put_Index_header(&writer, 0, 0);
1895
834
        else if (subrs_size[j] != 0)
1896
56
            cff_write_Subrs(&writer, subrs_count[j], subrs_size[j], pfd, false);
1897
834
    }
1898
1899
    /* Check the final offset. */
1900
407
    offset = stell(writer.strm) - start_pos;
1901
407
    if_debug2m('l', s->memory, "[l]End = %u => %u\n", End_offset, offset);
1902
407
    if (offset > End_offset)
1903
0
        return_error(offset_error("End"));
1904
407
    if (offset == End_offset) {
1905
        /* The iteration has converged.  Write the result. */
1906
202
        if (writer.strm == &poss) {
1907
101
            writer.strm = s;
1908
101
            goto write;
1909
101
        }
1910
205
    } else {
1911
        /* No convergence yet. */
1912
205
        End_offset = offset;
1913
205
        goto iter;
1914
205
    }
1915
1916
    /* All done. */
1917
101
    return 0;
1918
407
}