Coverage Report

Created: 2026-08-08 08:00

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
131k
#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
12.4k
{
85
12.4k
    int reprobe = 17;
86
87
12.4k
    memset(items, 0, size * sizeof(*items));
88
12.4k
    pcst->items = items;
89
12.4k
    pcst->count = 0;
90
12.4k
    pcst->size = size;
91
12.8k
    while (reprobe != 1 && igcd(size, reprobe) != 1)
92
391
        reprobe = (reprobe * 2 + 1) % size;
93
12.4k
    pcst->total = 0;
94
12.4k
    pcst->reprobe = reprobe;
95
12.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
2.44M
{
101
2.44M
    int index;
102
103
2.44M
    if (pcst->count >= pcst->size)
104
0
        return_error(gs_error_limitcheck);
105
2.44M
    index = pcst->count++;
106
2.44M
    pcst->items[index].key.data = data;
107
2.44M
    pcst->items[index].key.size = size;
108
2.44M
    pcst->total += size;
109
2.44M
    return index;
110
2.44M
}
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
3.26M
{
118
    /****** FAILS IF TABLE FULL AND KEY MISSING ******/
119
3.26M
    int j = (size == 0 ? 0 : data[0] * 23 + data[size - 1] * 59 + size);
120
3.26M
    int index, c = 0;
121
122
8.89M
    while ((index = pcst->items[j %= pcst->size].index1) != 0) {
123
6.31M
        --index;
124
6.31M
        if (!bytes_compare(pcst->items[index].key.data,
125
6.31M
                           pcst->items[index].key.size, data, size)) {
126
687k
            *pindex = index;
127
687k
            return 0;
128
687k
        }
129
5.62M
        j += pcst->reprobe;
130
5.62M
        if (++c >= pcst->size)
131
0
            break;
132
5.62M
    }
133
2.57M
    if (!enter)
134
131k
        return_error(gs_error_undefined);
135
2.44M
    index = cff_string_add(pcst, data, size);
136
2.44M
    if (index < 0)
137
0
        return index;
138
2.44M
    pcst->items[j].index1 = index + 1;
139
2.44M
    *pindex = index;
140
2.44M
    return 1;
141
2.44M
}
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
709k
{
147
709k
    int index;
148
709k
    int code = cff_string_index(&pcw->std_strings, data, size, false, &index);
149
150
709k
    if (code < 0) {
151
131k
        code = cff_string_index(&pcw->strings, data, size, true, &index);
152
131k
        if (code < 0)
153
0
            return code;
154
131k
        index += NUM_STD_STRINGS;
155
131k
    }
156
709k
    return index;
157
709k
}
158
static int
159
cff_glyph_sid(cff_writer_t *pcw, gs_glyph glyph)
160
591k
{
161
591k
    gs_const_string str;
162
591k
    int code =
163
591k
        pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
164
165
591k
    if (code < 0)
166
0
        return code;
167
591k
    return cff_string_sid(pcw, str.data, str.size);
168
591k
}
169
170
/* ------ Low level ------ */
171
172
static void
173
put_card16(cff_writer_t *pcw, uint c16)
174
999k
{
175
999k
    sputc(pcw->strm, (byte)(c16 >> 8));
176
999k
    sputc(pcw->strm, (byte)c16);
177
999k
}
178
static int
179
offset_size(uint offset)
180
173k
{
181
173k
    int size = 1;
182
183
234k
    while (offset > 255)
184
61.0k
        offset >>= 8, ++size;
185
173k
    return size;
186
173k
}
187
static void
188
put_offset(cff_writer_t *pcw, int offset)
189
853k
{
190
853k
    int i;
191
192
2.24M
    for (i = pcw->offset_size - 1; i >= 0; --i)
193
1.39M
        sputc(pcw->strm, (byte)(offset >> (i * 8)));
194
853k
}
195
static int
196
put_bytes(stream * s, const byte *ptr, uint count)
197
189k
{
198
189k
    uint used;
199
200
189k
    sputs(s, ptr, count, &used);
201
189k
    return (int)used;
202
189k
}
203
static int
204
check_ioerror(stream * s)
205
98.7k
{
206
98.7k
    uint used = 0;
207
208
98.7k
    return sputs(s, (byte *)&used, 0, &used);
209
98.7k
}
210
211
/* ------ Data types ------ */
212
213
443k
#define CE_OFFSET 32
214
static void
215
cff_put_op(cff_writer_t *pcw, int op)
216
443k
{
217
443k
    if (op >= CE_OFFSET) {
218
138k
        sputc(pcw->strm, cx_escape);
219
138k
        sputc(pcw->strm, (byte)(op - CE_OFFSET));
220
138k
    } else
221
304k
        sputc(pcw->strm, (byte)op);
222
443k
}
223
static void
224
cff_put_int(cff_writer_t *pcw, int i)
225
1.17M
{
226
1.17M
    stream *s = pcw->strm;
227
228
1.17M
    if (i >= -107 && i <= 107)
229
822k
        sputc(s, (byte)(i + 139));
230
351k
    else if (i <= 1131 && i >= 0)
231
289k
        put_card16(pcw, (c_pos2_0 << 8) + i - 108);
232
62.4k
    else if (i >= -1131 && i < 0)
233
23.0k
        put_card16(pcw, (c_neg2_0 << 8) - i - 108);
234
39.4k
    else if (i >= -32768 && i <= 32767) {
235
8.44k
        sputc(s, c2_shortint);
236
8.44k
        put_card16(pcw, i & 0xffff);
237
30.9k
    } else {
238
30.9k
        sputc(s, CD_LONGINT);
239
30.9k
        put_card16(pcw, i >> 16);
240
30.9k
        put_card16(pcw, i & 0xffff);
241
30.9k
    }
242
1.17M
}
243
static void
244
cff_put_int_value(cff_writer_t *pcw, int i, int op)
245
174k
{
246
174k
    cff_put_int(pcw, i);
247
174k
    cff_put_op(pcw, op);
248
174k
}
249
static void
250
cff_put_int_if_ne(cff_writer_t *pcw, int i, int i_default, int op)
251
237k
{
252
237k
    if (i != i_default)
253
111k
        cff_put_int_value(pcw, i, op);
254
237k
}
255
static void
256
cff_put_bool(cff_writer_t *pcw, bool b)
257
832
{
258
832
    cff_put_int(pcw, (b ? 1 : 0));
259
832
}
260
static void
261
cff_put_bool_value(cff_writer_t *pcw, bool b, int op)
262
832
{
263
832
    cff_put_bool(pcw, b);
264
832
    cff_put_op(pcw, op);
265
832
}
266
static void
267
cff_put_real(cff_writer_t *pcw, double f)
268
854k
{
269
854k
    if (f == (int)f)
270
850k
        cff_put_int(pcw, (int)f);
271
4.23k
    else {
272
        /* Use decimal representation. */
273
4.23k
        char str[50];
274
4.23k
        byte b = 0xff;
275
4.23k
        const char *p;
276
277
4.23k
        gs_snprintf(str, sizeof(str), "%g", f);
278
4.23k
        sputc(pcw->strm, CD_REAL);
279
31.7k
        for (p = str; ; ++p) {
280
31.7k
            int digit;
281
282
31.7k
            switch (*p) {
283
4.23k
            case 0:
284
4.23k
                goto done;
285
4.23k
            case '.':
286
4.23k
                digit = 0xa; break;
287
8
            case '+':
288
8
                continue;
289
0
            case '-':
290
0
                digit = 0xe; break;
291
8
            case 'e': case 'E':
292
8
                if (p[1] == '-')
293
0
                    digit = 0xc, ++p;
294
8
                else
295
8
                    digit = 0xb;
296
8
                break;
297
13.2k
            case '0': case '1': case '2': case '3': case '4':
298
23.3k
            case '5': case '6': case '7': case '8': case '9':
299
23.3k
                digit = *p - '0';
300
23.3k
                break;
301
0
            default:    /* can't happen */
302
0
                digit = 0xd;  /* invalid */
303
0
                break;
304
31.7k
            }
305
27.5k
            if (b == 0xff)
306
15.2k
                b = (digit << 4) + 0xf;
307
12.2k
            else {
308
12.2k
                sputc(pcw->strm, (byte)((b & 0xf0) + digit));
309
12.2k
                b = 0xff;
310
12.2k
            }
311
27.5k
        }
312
4.23k
    done:
313
4.23k
        sputc(pcw->strm, b);
314
4.23k
    }
315
854k
}
316
static void
317
cff_put_real_value(cff_writer_t *pcw, double f, int op)
318
51.3k
{
319
51.3k
    cff_put_real(pcw, f);
320
51.3k
    cff_put_op(pcw, op);
321
51.3k
}
322
static void
323
cff_put_real_if_ne(cff_writer_t *pcw, double f, double f_default, int op)
324
136k
{
325
136k
    if ((float)f != (float)f_default)
326
1.83k
        cff_put_real_value(pcw, f, op);
327
136k
}
328
static void
329
cff_put_real_deltarray(cff_writer_t *pcw, const float *pf, int count, int op)
330
149k
{
331
149k
    float prev = 0;
332
149k
    int i;
333
334
149k
    if (count <= 0)
335
77.9k
        return;
336
758k
    for (i = 0; i < count; ++i) {
337
687k
        float f = pf[i];
338
339
687k
        cff_put_real(pcw, f - prev);
340
687k
        prev = f;
341
687k
    }
342
71.2k
    cff_put_op(pcw, op);
343
71.2k
}
344
static int
345
cff_put_string(cff_writer_t *pcw, const byte *data, uint size)
346
117k
{
347
117k
    int sid = cff_string_sid(pcw, data, size);
348
349
117k
    if (sid < 0)
350
0
        return sid;
351
117k
    cff_put_int(pcw, sid);
352
117k
    return 0;
353
117k
}
354
static int
355
cff_put_string_value(cff_writer_t *pcw, const byte *data, uint size, int op)
356
117k
{
357
117k
    int code = cff_put_string(pcw, data, size);
358
359
117k
    if (code >= 0)
360
117k
        cff_put_op(pcw, op);
361
117k
    return code;
362
117k
}
363
static int
364
cff_extra_lenIV(const cff_writer_t *pcw, const gs_font_type1 *pfont)
365
617k
{
366
617k
    return (pcw->options & WRITE_TYPE2_NO_LENIV ?
367
617k
            max(pfont->data.lenIV, 0) : 0);
368
617k
}
369
static bool
370
cff_convert_charstrings(const cff_writer_t *pcw, const gs_font_base *pfont)
371
1.14M
{
372
1.14M
    return (pfont->FontType != ft_encrypted2 &&
373
1.08M
            (pcw->options & WRITE_TYPE2_CHARSTRINGS) != 0);
374
1.14M
}
375
static int
376
cff_put_CharString(cff_writer_t *pcw, const byte *data, uint size,
377
                   gs_font_type1 *pfont)
378
494k
{
379
494k
    int lenIV = pfont->data.lenIV;
380
494k
    stream *s = pcw->strm;
381
382
494k
    if (cff_convert_charstrings(pcw, (gs_font_base *)pfont)) {
383
465k
        gs_glyph_data_t gdata;
384
465k
        int code;
385
386
465k
        gdata.memory = pfont->memory;
387
465k
        gs_glyph_data_from_string(&gdata, data, size, NULL);
388
465k
        code = psf_convert_type1_to_type2(s, &gdata, pfont);
389
465k
        if (code < 0)
390
0
            return code;
391
465k
    } else if (lenIV < 0 || !(pcw->options & WRITE_TYPE2_NO_LENIV))
392
29.5k
        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
494k
    return 0;
410
494k
}
411
static uint
412
cff_Index_size(uint count, uint total)
413
92.8k
{
414
92.8k
    return (count == 0 ? 2 :
415
92.8k
            3 + offset_size(total + 1) * (count + 1) + total);
416
92.8k
}
417
static void
418
cff_put_Index_header(cff_writer_t *pcw, uint count, uint total)
419
147k
{
420
147k
    put_card16(pcw, count);
421
147k
    if (count > 0) {
422
99.0k
        pcw->offset_size = offset_size(total + 1);
423
99.0k
        sputc(pcw->strm, (byte)pcw->offset_size);
424
99.0k
        put_offset(pcw, 1);
425
99.0k
    }
426
147k
}
427
static void
428
cff_put_Index(cff_writer_t *pcw, const cff_string_table_t *pcst)
429
24.7k
{
430
24.7k
    uint j, offset;
431
432
24.7k
    if (pcst->count == 0) {
433
12
        put_card16(pcw, 0);
434
12
        return;
435
12
    }
436
24.7k
    cff_put_Index_header(pcw, pcst->count, pcst->total);
437
110k
    for (j = 0, offset = 1; j < pcst->count; ++j) {
438
85.6k
        offset += pcst->items[j].key.size;
439
85.6k
        put_offset(pcw, offset);
440
85.6k
    }
441
110k
    for (j = 0; j < pcst->count; ++j)
442
85.6k
        put_bytes(pcw->strm, pcst->items[j].key.data, pcst->items[j].key.size);
443
24.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
24.7k
{
453
24.7k
    pcw->offset_size = (end_offset > 0x7fff ? 3 : 2);
454
24.7k
    put_bytes(pcw->strm, (const byte *)"\001\000\004", 3);
455
24.7k
    sputc(pcw->strm, (byte)pcw->offset_size);
456
24.7k
    return 0;
457
24.7k
}
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
30.9k
#define charset_DEFAULT 0
480
    TOP_Encoding = 16,    /* (offset or predefined index) */
481
#define Encoding_Standard 0
482
#define Encoding_Expert 1
483
30.8k
#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
62.2k
#define ItalicAngle_DEFAULT 0
491
    TOP_UnderlinePosition = 35,
492
62.2k
#define UnderlinePosition_DEFAULT (-100)
493
    TOP_UnderlineThickness = 36,
494
62.2k
#define UnderlineThickness_DEFAULT 50
495
    TOP_PaintType = 37,
496
31.1k
#define PaintType_DEFAULT 0
497
    TOP_CharstringType = 38,
498
30.8k
#define CharstringType_DEFAULT 2
499
    TOP_FontMatrix = 39,  /* default is [0.001 0 0 0.001 0 0] */
500
    TOP_StrokeWidth = 40,
501
31.1k
#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
60
#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
31.1k
{
521
31.1k
    pinfo->Flags_requested = FONT_IS_FIXED_WIDTH;
522
    /* Preset defaults */
523
31.1k
    pinfo->members = 0;
524
31.1k
    pinfo->Flags = pinfo->Flags_returned = 0;
525
31.1k
    pinfo->ItalicAngle = ItalicAngle_DEFAULT;
526
31.1k
    pinfo->UnderlinePosition = UnderlinePosition_DEFAULT;
527
31.1k
    pinfo->UnderlineThickness = UnderlineThickness_DEFAULT;
528
31.1k
    return pbfont->procs.font_info
529
31.1k
        ((gs_font *)pbfont, NULL,
530
31.1k
         (full_info ?
531
30.9k
          FONT_INFO_FLAGS | FONT_INFO_ITALIC_ANGLE |
532
30.9k
            FONT_INFO_UNDERLINE_POSITION |
533
30.9k
            FONT_INFO_UNDERLINE_THICKNESS : 0) |
534
31.1k
         (FONT_INFO_COPYRIGHT | FONT_INFO_NOTICE |
535
31.1k
          FONT_INFO_FAMILY_NAME | FONT_INFO_FULL_NAME),
536
31.1k
         pinfo);
537
31.1k
}
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
31.1k
{
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
31.1k
    if (pinfo->members & FONT_INFO_NOTICE)
552
30.1k
        cff_put_string_value(pcw, pinfo->Notice.data, pinfo->Notice.size,
553
30.1k
                             TOP_Notice);
554
31.1k
    if (pinfo->members & FONT_INFO_FULL_NAME)
555
30.0k
        cff_put_string_value(pcw, pinfo->FullName.data, pinfo->FullName.size,
556
30.0k
                             TOP_FullName);
557
31.1k
    if (pinfo->members & FONT_INFO_FAMILY_NAME)
558
30.0k
        cff_put_string_value(pcw, pinfo->FamilyName.data,
559
30.0k
                             pinfo->FamilyName.size, TOP_FamilyName);
560
31.1k
    if (pcw->FontBBox.p.x != 0 || pcw->FontBBox.p.y != 0 ||
561
4.76k
        pcw->FontBBox.q.x != 0 || pcw->FontBBox.q.y != 0
562
31.1k
        ) {
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
28.1k
        cff_put_real(pcw, pcw->FontBBox.p.x);
571
28.1k
        cff_put_real(pcw, pcw->FontBBox.p.y);
572
28.1k
        cff_put_real(pcw, pcw->FontBBox.q.x);
573
28.1k
        cff_put_real(pcw, pcw->FontBBox.q.y);
574
28.1k
        cff_put_op(pcw, TOP_FontBBox);
575
28.1k
      }
576
31.1k
    if (uid_is_UniqueID(&pbfont->UID))
577
5
        cff_put_int_value(pcw, pbfont->UID.id, TOP_UniqueID);
578
31.1k
    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
31.1k
    if (!(pcw->options & WRITE_TYPE2_AR3)) {
595
31.1k
        if (pinfo->members & FONT_INFO_COPYRIGHT)
596
26.9k
            cff_put_string_value(pcw, pinfo->Copyright.data,
597
26.9k
                                 pinfo->Copyright.size, TOP_Copyright);
598
31.1k
        if (pinfo->Flags & pinfo->Flags_returned & FONT_IS_FIXED_WIDTH)
599
384
            cff_put_bool_value(pcw, true, TOP_isFixedPitch);
600
31.1k
        cff_put_real_if_ne(pcw, pinfo->ItalicAngle, ItalicAngle_DEFAULT,
601
31.1k
                           TOP_ItalicAngle);
602
31.1k
        cff_put_int_if_ne(pcw, pinfo->UnderlinePosition,
603
31.1k
                          UnderlinePosition_DEFAULT, TOP_UnderlinePosition);
604
31.1k
        cff_put_int_if_ne(pcw, pinfo->UnderlineThickness,
605
31.1k
                          UnderlineThickness_DEFAULT, TOP_UnderlineThickness);
606
31.1k
        cff_put_int_if_ne(pcw, pbfont->PaintType, PaintType_DEFAULT,
607
31.1k
                          TOP_PaintType);
608
31.1k
    }
609
31.1k
    {
610
31.1k
        static const gs_matrix fm_default = {
611
31.1k
            constant_matrix_body(0.001, 0, 0, 0.001, 0, 0)
612
31.1k
        };
613
614
31.1k
        if (write_FontMatrix ||
615
30.8k
            pbfont->FontMatrix.xx != fm_default.xx ||
616
30.8k
            pbfont->FontMatrix.xy != 0 || pbfont->FontMatrix.yx != 0 ||
617
30.6k
            pbfont->FontMatrix.yy != fm_default.yy ||
618
30.6k
            pbfont->FontMatrix.tx != 0 || pbfont->FontMatrix.ty != 0
619
31.1k
            ) {
620
486
            cff_put_real(pcw, pbfont->FontMatrix.xx);
621
486
            cff_put_real(pcw, pbfont->FontMatrix.xy);
622
486
            cff_put_real(pcw, pbfont->FontMatrix.yx);
623
486
            cff_put_real(pcw, pbfont->FontMatrix.yy);
624
486
            cff_put_real(pcw, pbfont->FontMatrix.tx);
625
486
            cff_put_real(pcw, pbfont->FontMatrix.ty);
626
486
            cff_put_op(pcw, TOP_FontMatrix);
627
486
        }
628
31.1k
    }
629
31.1k
    cff_put_real_if_ne(pcw, pbfont->StrokeWidth, StrokeWidth_DEFAULT,
630
31.1k
                       TOP_StrokeWidth);
631
31.1k
}
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
30.8k
{
639
30.8k
    gs_font_base *pbfont = (gs_font_base *)pcw->pfont;
640
30.8k
    gs_font_info_t info;
641
642
30.8k
    cff_get_Top_info_common(pcw, pbfont, true, &info);
643
30.8k
    cff_write_Top_common(pcw, pbfont, false, &info);
644
30.8k
    cff_put_int(pcw, Private_size);
645
30.8k
    cff_put_int_value(pcw, Private_offset, TOP_Private);
646
30.8k
    cff_put_int_value(pcw, CharStrings_offset, TOP_CharStrings);
647
30.8k
    cff_put_int_if_ne(pcw, charset_offset, charset_DEFAULT, TOP_charset);
648
30.8k
    cff_put_int_if_ne(pcw, Encoding_offset, Encoding_DEFAULT, TOP_Encoding);
649
30.8k
    {
650
30.8k
        int type = (pcw->options & WRITE_TYPE2_CHARSTRINGS ? 2 :
651
30.8k
                    pbfont->FontType == ft_encrypted2 ? 2 : 1);
652
653
30.8k
        cff_put_int_if_ne(pcw, type, CharstringType_DEFAULT,
654
30.8k
                          TOP_CharstringType);
655
30.8k
    }
656
30.8k
}
657
658
/* CIDFontType 0 CIDFont */
659
static void
660
cff_write_ROS(cff_writer_t *pcw, const gs_cid_system_info_t *pcidsi)
661
75
{
662
75
    cff_put_string(pcw, pcidsi->Registry.data, pcidsi->Registry.size);
663
75
    cff_put_string(pcw, pcidsi->Ordering.data, pcidsi->Ordering.size);
664
75
    cff_put_int_value(pcw, pcidsi->Supplement, TOP_ROS);
665
75
}
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
60
{
671
60
    gs_font_base *pbfont = (gs_font_base *)pcw->pfont;
672
60
    gs_font_cid0 *pfont = (gs_font_cid0 *)pbfont;
673
674
60
    cff_write_ROS(pcw, &pfont->cidata.common.CIDSystemInfo);
675
60
    cff_write_Top_common(pcw, pbfont, true, pinfo); /* full_info = true */
676
60
    cff_put_int_if_ne(pcw, charset_offset, charset_DEFAULT, TOP_charset);
677
60
    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
60
    cff_put_int_if_ne(pcw, pfont->cidata.common.CIDCount, CIDCount_DEFAULT,
683
60
                      TOP_CIDCount);
684
    /* We don't use UIDBase. */
685
60
    cff_put_int_value(pcw, Font_offset, TOP_FDArray);
686
60
    cff_put_int_value(pcw, FDSelect_offset, TOP_FDSelect);
687
60
}
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
60
{
694
60
    int j;
695
696
60
    cff_put_Index_header(pcw, num_fonts,
697
60
                         FDArray_offsets[num_fonts] - FDArray_offsets[0]);
698
240
    for (j = 1; j <= num_fonts; ++j)
699
180
        put_offset(pcw, FDArray_offsets[j] - FDArray_offsets[0] + 1);
700
60
}
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
225
{
707
225
    const gs_font_name *pfname = &pbfont->font_name;
708
225
    gs_font_info_t info;
709
710
225
    cff_get_Top_info_common(pcw, pbfont, false, &info);
711
225
    cff_write_Top_common(pcw, pbfont, true, &info);
712
225
    cff_put_int(pcw, Private_size);
713
225
    cff_put_int_value(pcw, Private_offset, TOP_Private);
714
225
    if (pfname->size == 0)
715
0
        pfname = &pbfont->key_name;
716
225
    if (pfname->size) {
717
225
        cff_put_string(pcw, pfname->chars, pfname->size);
718
225
        cff_put_op(pcw, TOP_FontName);
719
225
    }
720
225
}
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
1.34k
#define defaultWidthX_DEFAULT fixed_0
735
    PRIVATE_nominalWidthX = 21,
736
1.34k
#define nominalWidthX_DEFAULT fixed_0
737
    PRIVATE_BlueScale = 41,
738
24.8k
#define BlueScale_DEFAULT 0.039625
739
    PRIVATE_BlueShift = 42,
740
24.8k
#define BlueShift_DEFAULT 7
741
    PRIVATE_BlueFuzz = 43,
742
24.8k
#define BlueFuzz_DEFAULT 1
743
    PRIVATE_StemSnapH = 44, /* (deltarray) */
744
    PRIVATE_StemSnapV = 45, /* (deltarray) */
745
    PRIVATE_ForceBold = 46,
746
24.8k
#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
24.8k
#define LanguageGroup_DEFAULT 0
753
    PRIVATE_ExpansionFactor = 50,
754
24.8k
#define ExpansionFactor_DEFAULT 0.06
755
    PRIVATE_initialRandomSeed = 51
756
1.34k
#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
24.8k
{
765
24.8k
#define PUT_FLOAT_TABLE(member, op)\
766
149k
    cff_put_real_deltarray(pcw, pfont->data.member.values,\
767
149k
                           pfont->data.member.count, op)
768
769
24.8k
    PUT_FLOAT_TABLE(BlueValues, PRIVATE_BlueValues);
770
24.8k
    PUT_FLOAT_TABLE(OtherBlues, PRIVATE_OtherBlues);
771
24.8k
    PUT_FLOAT_TABLE(FamilyBlues, PRIVATE_FamilyBlues);
772
24.8k
    PUT_FLOAT_TABLE(FamilyOtherBlues, PRIVATE_FamilyOtherBlues);
773
24.8k
    if (pfont->data.StdHW.count > 0)
774
24.1k
        cff_put_real_value(pcw, pfont->data.StdHW.values[0], PRIVATE_StdHW);
775
24.8k
    if (pfont->data.StdVW.count > 0)
776
24.1k
        cff_put_real_value(pcw, pfont->data.StdVW.values[0], PRIVATE_StdVW);
777
24.8k
    if (Subrs_offset)
778
4
        cff_put_int_value(pcw, Subrs_offset, PRIVATE_Subrs);
779
24.8k
    if (pfont->FontType != ft_encrypted) {
780
1.34k
        if (pfont->data.defaultWidthX != defaultWidthX_DEFAULT)
781
717
            cff_put_real_value(pcw, fixed2float(pfont->data.defaultWidthX),
782
717
                               PRIVATE_defaultWidthX);
783
1.34k
        if (pfont->data.nominalWidthX != nominalWidthX_DEFAULT)
784
542
            cff_put_real_value(pcw, fixed2float(pfont->data.nominalWidthX),
785
542
                               PRIVATE_nominalWidthX);
786
1.34k
        cff_put_int_if_ne(pcw, pfont->data.initialRandomSeed,
787
1.34k
                          initialRandomSeed_DEFAULT,
788
1.34k
                          PRIVATE_initialRandomSeed);
789
1.34k
    }
790
24.8k
    cff_put_real_if_ne(pcw, pfont->data.BlueScale, BlueScale_DEFAULT,
791
24.8k
                       PRIVATE_BlueScale);
792
24.8k
    cff_put_real_if_ne(pcw, pfont->data.BlueShift, BlueShift_DEFAULT,
793
24.8k
                       PRIVATE_BlueShift);
794
24.8k
    cff_put_int_if_ne(pcw, pfont->data.BlueFuzz, BlueFuzz_DEFAULT,
795
24.8k
                      PRIVATE_BlueFuzz);
796
24.8k
    PUT_FLOAT_TABLE(StemSnapH, PRIVATE_StemSnapH);
797
24.8k
    PUT_FLOAT_TABLE(StemSnapV, PRIVATE_StemSnapV);
798
24.8k
    if (pfont->data.ForceBold != ForceBold_DEFAULT)
799
448
        cff_put_bool_value(pcw, pfont->data.ForceBold,
800
448
                           PRIVATE_ForceBold);
801
    /* (ForceBoldThreshold) */
802
24.8k
    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
24.8k
    cff_put_int_if_ne(pcw, pfont->data.LanguageGroup, LanguageGroup_DEFAULT,
806
24.8k
                      PRIVATE_LanguageGroup);
807
24.8k
    cff_put_real_if_ne(pcw, pfont->data.ExpansionFactor,
808
24.8k
                       ExpansionFactor_DEFAULT, PRIVATE_ExpansionFactor);
809
    /* initialRandomSeed was handled above */
810
811
24.8k
#undef PUT_FLOAT_TABLE
812
24.8k
}
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
30.9k
{
821
30.9k
    gs_font_base *pfont = pcw->pfont;
822
30.9k
    int offset;
823
30.9k
    gs_glyph glyph;
824
30.9k
    uint count;
825
30.9k
    stream poss;
826
30.9k
    int code;
827
828
30.9k
    s_init(&poss, NULL);
829
30.9k
    psf_enumerate_glyphs_reset(penum);
830
30.9k
    for (glyph = GS_NO_GLYPH, count = 0, offset = 1;
831
647k
         (code = psf_enumerate_glyphs_next(penum, &glyph)) != 1;
832
617k
         ) {
833
617k
        gs_glyph_data_t gdata;
834
617k
        gs_font_type1 *pfd;
835
617k
        int gcode;
836
837
617k
        gdata.memory = pfont->memory;
838
617k
        if (code == 0 &&
839
617k
            (gcode = pcw->glyph_data(pfont, glyph, &gdata, &pfd)) >= 0
840
617k
            ) {
841
617k
            int extra_lenIV;
842
843
617k
            if (gdata.bits.size >= (extra_lenIV = cff_extra_lenIV(pcw, pfd))) {
844
617k
                if (cff_convert_charstrings(pcw, (gs_font_base *)pfd)) {
845
582k
                    swrite_position_only(&poss);
846
582k
                    code = psf_convert_type1_to_type2(&poss, &gdata, pfd);
847
582k
                    if (code < 0)
848
41
                        return code;
849
582k
                    offset += stell(&poss);
850
582k
                } else
851
34.9k
                    offset += gdata.bits.size - extra_lenIV;
852
617k
            }
853
616k
            gs_glyph_data_free(&gdata, "cff_write_CharStrings_offsets");
854
616k
            put_offset(pcw, offset);
855
616k
            count++;
856
616k
        }
857
617k
    }
858
30.9k
    *pcount = count;
859
30.9k
    return offset - 1;
860
30.9k
}
861
static void
862
cff_write_CharStrings(cff_writer_t *pcw, psf_glyph_enum_t *penum,
863
                      uint charstrings_count, uint charstrings_size)
864
24.7k
{
865
24.7k
    gs_font_base *pfont = pcw->pfont;
866
24.7k
    uint ignore_count;
867
24.7k
    gs_glyph glyph;
868
24.7k
    int code;
869
870
24.7k
    cff_put_Index_header(pcw, charstrings_count, charstrings_size);
871
24.7k
    cff_write_CharStrings_offsets(pcw, penum, &ignore_count);
872
24.7k
    psf_enumerate_glyphs_reset(penum);
873
24.7k
    for (glyph = GS_NO_GLYPH;
874
518k
         (code = psf_enumerate_glyphs_next(penum, &glyph)) != 1;
875
493k
         ) {
876
493k
        gs_glyph_data_t gdata;
877
493k
        gs_font_type1 *pfd;
878
879
493k
        gdata.memory = pfont->memory;
880
493k
        if (code == 0 &&
881
493k
            (code = pcw->glyph_data(pfont, glyph, &gdata, &pfd)) >= 0
882
493k
            ) {
883
493k
            cff_put_CharString(pcw, gdata.bits.data, gdata.bits.size, pfd);
884
493k
            gs_glyph_data_free(&gdata, "cff_write_CharStrings");
885
493k
        }
886
493k
    }
887
24.7k
}
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
628
{
900
628
    int extra_lenIV = cff_extra_lenIV(pcw, pfont);
901
628
    int j, offset;
902
628
    int code;
903
628
    gs_glyph_data_t gdata;
904
905
628
    gdata.memory = pfont->memory;
906
628
    for (j = 0, offset = 1;
907
2.24k
         (code = pfont->data.procs.subr_data(pfont, j, global, &gdata)) !=
908
2.24k
             gs_error_rangecheck;
909
1.61k
         ++j) {
910
1.61k
        if (code >= 0 && gdata.bits.size >= extra_lenIV)
911
1.61k
            offset += gdata.bits.size - extra_lenIV;
912
1.61k
        put_offset(pcw, offset);
913
1.61k
        if (code >= 0)
914
1.61k
            gs_glyph_data_free(&gdata, "cff_write_Subrs_offsets");
915
1.61k
    }
916
628
    *pcount = j;
917
628
    return offset - 1;
918
628
}
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
8
{
924
8
    int j;
925
8
    uint ignore_count;
926
8
    gs_glyph_data_t gdata;
927
8
    int code;
928
929
8
    gdata.memory = pfont->memory;
930
8
    cff_put_Index_header(pcw, subrs_count, subrs_size);
931
8
    cff_write_Subrs_offsets(pcw, &ignore_count, pfont, global);
932
8
    for (j = 0;
933
1.30k
         (code = pfont->data.procs.subr_data(pfont, j, global, &gdata)) !=
934
1.30k
             gs_error_rangecheck;
935
1.29k
         ++j) {
936
1.29k
        if (code >= 0) {
937
1.29k
            cff_put_CharString(pcw, gdata.bits.data, gdata.bits.size, pfont);
938
1.29k
            gs_glyph_data_free(&gdata, "cff_write_Subrs");
939
1.29k
        }
940
1.29k
    }
941
8
}
942
943
/* ------ Encoding/charset ------ */
944
945
static uint
946
cff_Encoding_size(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
947
6.19k
{
948
6.19k
    int j, code, max_enc = 0, nsupp = 0;
949
6.19k
    gs_font_type1 *pfont = (gs_font_type1 *)pcw->pfont;
950
6.19k
    byte used[255];
951
6.19k
    gs_const_string str;
952
953
6.19k
    memset(used, 0, 255);
954
1.59M
    for (j = 0; j < 256; ++j) {
955
1.58M
        gs_glyph glyph = pfont->procs.encode_char((gs_font *)pfont,
956
1.58M
                                                  (gs_char)j,
957
1.58M
                                                  GLYPH_SPACE_NAME);
958
1.58M
        int i;
959
960
1.58M
        if (glyph == GS_NO_GLYPH || glyph == pgsub->glyphs.notdef)
961
1.46M
            continue;
962
117k
        i = psf_sorted_glyphs_index_of(pgsub->glyphs.subset_data + 1,
963
117k
                                       pgsub->num_encoded, glyph);
964
117k
        if (i < 0)
965
0
            continue;   /* encoded but not in subset */
966
117k
        code = pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
967
117k
        if (code < 0)
968
0
            continue;
969
117k
        if (i >= sizeof(used) || used[i])
970
9
            nsupp++;
971
117k
        else {
972
117k
            used[i] = 1;
973
117k
            if (i > max_enc)
974
17.3k
                max_enc = i;
975
117k
        }
976
117k
    }
977
6.19k
    return 2 + (max_enc+1) + (3 * nsupp) + (nsupp > 0 ? 1 : 0);
978
6.19k
}
979
980
static int
981
cff_write_Encoding(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
982
24.6k
{
983
24.6k
    stream *s = pcw->strm;
984
    /* This procedure is only used for Type 1 / Type 2 fonts. */
985
24.6k
    gs_font_type1 *pfont = (gs_font_type1 *)pcw->pfont;
986
24.6k
    byte used[255], index[255], supplement[256];
987
24.6k
    int num_enc = min(pgsub->num_encoded, sizeof(index));
988
24.6k
    int nsupp = 0;
989
24.6k
    int j, code;
990
24.6k
    int max_enc = 0;
991
24.6k
    gs_const_string str;
992
993
24.6k
    memset(used, 0, num_enc);
994
24.6k
    memset(index, 0, sizeof(index));
995
6.34M
    for (j = 0; j < 256; ++j) {
996
6.32M
        gs_glyph glyph = pfont->procs.encode_char((gs_font *)pfont,
997
6.32M
                                                  (gs_char)j,
998
6.32M
                                                  GLYPH_SPACE_NAME);
999
6.32M
        int i;
1000
1001
6.32M
        if (glyph == GS_NO_GLYPH || glyph == pgsub->glyphs.notdef)
1002
5.85M
            continue;
1003
468k
        i = psf_sorted_glyphs_index_of(pgsub->glyphs.subset_data + 1,
1004
468k
                                       pgsub->num_encoded, glyph);
1005
468k
        if (i < 0)
1006
0
            continue;   /* encoded but not in subset */
1007
468k
        code = pcw->pfont->procs.glyph_name((gs_font *)pcw->pfont, glyph, &str);
1008
468k
        if (code < 0)
1009
0
            continue;
1010
468k
        if (i >= sizeof(used) || used[i])
1011
36
            supplement[nsupp++] = j;
1012
468k
        else {
1013
468k
            index[i] = j;
1014
468k
            used[i] = 1;
1015
468k
            if (i > max_enc)
1016
68.9k
                max_enc = i;
1017
468k
        }
1018
468k
    }
1019
24.6k
    sputc(s, (byte)(nsupp ? 0x80 : 0));
1020
24.6k
    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
24.6k
    put_bytes(s, index, max_enc+1);
1034
24.6k
    if (nsupp) {
1035
        /* Write supplementary entries for multiply-encoded glyphs. */
1036
16
        sputc(s, (byte)nsupp);
1037
52
        for (j = 0; j < nsupp; ++j) {
1038
36
            byte chr = supplement[j];
1039
1040
36
            sputc(s, chr);
1041
36
            put_card16(pcw,
1042
36
                cff_glyph_sid(pcw,
1043
36
                              pfont->procs.encode_char((gs_font *)pfont,
1044
36
                                                       (gs_char)chr,
1045
36
                                                       GLYPH_SPACE_NAME)));
1046
36
        }
1047
16
    }
1048
24.6k
    return 0;
1049
24.6k
}
1050
1051
static int
1052
cff_write_charset(cff_writer_t *pcw, cff_glyph_subset_t *pgsub)
1053
24.6k
{
1054
24.6k
    int j, code;
1055
1056
24.6k
    sputc(pcw->strm, 0);
1057
492k
    for (j = 1; j < pgsub->glyphs.subset_size; j++) {
1058
468k
        code = cff_glyph_sid(pcw, pgsub->glyphs.subset_data[j]);
1059
468k
        if (code < 0)
1060
0
            continue;
1061
468k
        put_card16(pcw, code);
1062
468k
    }
1063
24.6k
    return 0;
1064
24.6k
}
1065
static int
1066
cff_write_cidset(cff_writer_t *pcw, psf_glyph_enum_t *penum)
1067
75
{
1068
75
    gs_glyph glyph;
1069
75
    int code;
1070
1071
75
    sputc(pcw->strm, 0);
1072
75
    psf_enumerate_glyphs_reset(penum);
1073
1.03k
    while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1074
        /* Skip glyph 0 (the .notdef glyph), which is always first. */
1075
960
        if (glyph != GS_MIN_CID_GLYPH)
1076
885
            put_card16(pcw, (uint)(glyph - GS_MIN_CID_GLYPH));
1077
960
    }
1078
75
    return min(code, 0);
1079
75
}
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
15
{
1087
15
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pcw->pfont;
1088
15
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1089
15
    gs_glyph glyph;
1090
15
    int prev = -1;
1091
15
    uint linear_size = 1, range_size = 5;
1092
15
    int code;
1093
1094
    /* Determine whether format 0 or 3 is more efficient. */
1095
15
    psf_enumerate_glyphs_reset(penum);
1096
207
    while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1097
192
        int font_index;
1098
1099
192
        code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1100
192
        if (code >= 0) {
1101
192
            if (font_index != prev)
1102
33
                range_size += 3, prev = font_index;
1103
192
            ++linear_size;
1104
192
        }
1105
192
    }
1106
15
    if (range_size < linear_size) {
1107
11
        *pformat = 3;
1108
11
        return range_size;
1109
11
    } else {
1110
4
        *pformat = 0;
1111
4
        return linear_size;
1112
4
    }
1113
15
}
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
60
{
1120
60
    stream *s = pcw->strm;
1121
60
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pcw->pfont;
1122
60
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1123
60
    gs_glyph glyph;
1124
60
    int prev = -1;
1125
60
    uint cid_count = 0;
1126
60
    int code;
1127
1128
60
    spputc(s, (byte)format);
1129
60
    psf_enumerate_glyphs_reset(penum);
1130
60
    switch (format) {
1131
44
    case 3:     /* ranges */
1132
44
        put_card16(pcw, (size - 5) / 3);
1133
768
        while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1134
724
            int font_index;
1135
1136
724
            code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1137
724
            if (code >= 0) {
1138
724
                if (font_index != prev) {
1139
116
                    put_card16(pcw, cid_count);
1140
116
                    sputc(s, (byte)font_index);
1141
116
                    prev = font_index;
1142
116
                }
1143
724
                ++cid_count;
1144
724
            }
1145
724
        }
1146
44
        put_card16(pcw, cid_count);
1147
44
        break;
1148
16
    case 0:     /* linear table */
1149
60
        while ((code = psf_enumerate_glyphs_next(penum, &glyph)) == 0) {
1150
44
            int font_index;
1151
1152
44
            code = pfont->cidata.glyph_data(pbfont, glyph, NULL, &font_index);
1153
44
            if (code >= 0)
1154
44
                sputc(s, (byte)font_index);
1155
44
        }
1156
16
        break;
1157
0
    default:      /* not possible */
1158
0
        return_error(gs_error_rangecheck);
1159
60
    }
1160
60
    return 0;
1161
60
}
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
6.19k
{
1172
6.19k
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1173
6.19k
    cff_writer_t writer;
1174
6.19k
    cff_glyph_subset_t subset;
1175
6.19k
    cff_string_item_t *std_string_items;
1176
6.19k
    cff_string_item_t *string_items;
1177
6.19k
    gs_const_string font_name;
1178
6.19k
    stream poss;
1179
6.19k
    uint charstrings_count, charstrings_size;
1180
6.19k
    uint subrs_count, subrs_size;
1181
6.19k
    uint gsubrs_count, gsubrs_size, encoding_size;
1182
6.19k
    int charset_size = -1;
1183
6.19k
    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
6.19k
    uint
1189
6.19k
        Top_size = 0x7fffff,
1190
6.19k
        GSubrs_offset,
1191
6.19k
        Encoding_offset,
1192
6.19k
        charset_offset,
1193
6.19k
        CharStrings_offset,
1194
6.19k
        Private_offset,
1195
6.19k
        Private_size = 0x7fffff,
1196
6.19k
        Subrs_offset,
1197
6.19k
        End_offset = 0x7fffff;
1198
6.19k
    int j;
1199
6.19k
    psf_glyph_enum_t genum;
1200
6.19k
    gs_glyph glyph;
1201
6.19k
    long start_pos;
1202
6.19k
    uint offset;
1203
6.19k
    int code;
1204
1205
    /* Allocate the string tables. */
1206
6.19k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1207
6.19k
                               NULL, 0, GLYPH_SPACE_NAME);
1208
129k
    while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1209
123k
        number_of_glyphs++;
1210
6.19k
    subset.glyphs.subset_data = (gs_glyph *)gs_alloc_bytes(pfont->memory,
1211
6.19k
                    (size_t)number_of_glyphs * sizeof(glyph), "psf_write_type2_font");
1212
6.19k
    number_of_strings = number_of_glyphs + MAX_CFF_MISC_STRINGS;
1213
6.19k
    std_string_items = (cff_string_item_t *)gs_alloc_bytes(pfont->memory,
1214
6.19k
                    (MAX_CFF_STD_STRINGS + number_of_strings) * (size_t)sizeof(cff_string_item_t),
1215
6.19k
                    "psf_write_type2_font");
1216
6.19k
    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
6.19k
    string_items = std_string_items + MAX_CFF_STD_STRINGS;
1221
1222
    /* Get subset glyphs. */
1223
6.19k
    code = psf_get_type1_glyphs(&subset.glyphs, pfont, subset_glyphs,
1224
6.19k
                              subset_size);
1225
6.19k
    if (code < 0)
1226
0
        goto error;
1227
6.19k
    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
6.19k
    if (options & WRITE_TYPE2_CHARSTRINGS) {
1234
6.19k
        options |= WRITE_TYPE2_NO_LENIV;
1235
6.19k
        if (pfont->FontType != ft_encrypted2)
1236
5.91k
            pfont->data.defaultWidthX = pfont->data.nominalWidthX = 0;
1237
6.19k
    }
1238
6.19k
    writer.options = options;
1239
6.19k
    s_init(&poss, NULL);
1240
6.19k
    swrite_position_only(&poss);
1241
6.19k
    writer.strm = &poss;
1242
6.19k
    writer.pfont = pbfont;
1243
6.19k
    writer.glyph_data = psf_type1_glyph_data;
1244
6.19k
    writer.offset_size = 1; /* arbitrary */
1245
6.19k
    writer.start_pos = stell(s);
1246
6.19k
    writer.FontBBox = *FontBBox;
1247
1248
    /* Initialize the enumeration of the glyphs. */
1249
6.19k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1250
6.19k
                                subset.glyphs.subset_glyphs,
1251
6.19k
                                (subset.glyphs.subset_glyphs ?
1252
6.19k
                                 subset.glyphs.subset_size : 0),
1253
6.19k
                                GLYPH_SPACE_NAME);
1254
1255
    /* Shuffle the glyphs into the order .notdef, encoded, unencoded. */
1256
6.19k
    {
1257
6.19k
        gs_glyph encoded[256];
1258
6.19k
        int num_enc, num_enc_chars;
1259
1260
        /* Get the list of encoded glyphs. */
1261
1.59M
        for (j = 0, num_enc_chars = 0; j < 256; ++j) {
1262
1.58M
            glyph = pfont->procs.encode_char((gs_font *)pfont, (gs_char)j,
1263
1.58M
                                             GLYPH_SPACE_NAME);
1264
1.58M
            if (glyph != GS_NO_GLYPH && glyph != subset.glyphs.notdef &&
1265
117k
                (subset.glyphs.subset_glyphs == 0 ||
1266
0
                 psf_sorted_glyphs_include(subset.glyphs.subset_data,
1267
0
                                            subset.glyphs.subset_size, glyph)))
1268
117k
                encoded[num_enc_chars++] = glyph;
1269
1.58M
        }
1270
6.19k
        subset.num_encoded_chars = num_enc_chars;
1271
6.19k
        subset.num_encoded = num_enc =
1272
6.19k
            psf_sort_glyphs(encoded, num_enc_chars);
1273
1274
        /* Get the complete list of glyphs if we don't have it already. */
1275
6.19k
        if (!subset.glyphs.subset_glyphs) {
1276
6.19k
            int num_glyphs = 0;
1277
1278
6.19k
            psf_enumerate_glyphs_reset(&genum);
1279
129k
            while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1280
123k
                if (code == 0) {
1281
123k
                    if (num_glyphs == number_of_glyphs){
1282
0
                        code = gs_note_error(gs_error_limitcheck);
1283
0
                        goto error;
1284
0
                    }
1285
123k
                    subset.glyphs.subset_data[num_glyphs++] = glyph;
1286
123k
                }
1287
6.19k
            subset.glyphs.subset_size =
1288
6.19k
                psf_sort_glyphs(subset.glyphs.subset_data, num_glyphs);
1289
6.19k
            subset.glyphs.subset_glyphs = subset.glyphs.subset_data;
1290
6.19k
        }
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
6.19k
        {
1298
6.19k
            int from = subset.glyphs.subset_size;
1299
6.19k
            int to = from;
1300
1301
129k
            while (from > 0) {
1302
123k
                glyph = subset.glyphs.subset_data[--from];
1303
123k
                if (glyph != subset.glyphs.notdef &&
1304
117k
                    !psf_sorted_glyphs_include(encoded, num_enc, glyph))
1305
0
                    subset.glyphs.subset_data[--to] = glyph;
1306
123k
            }
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
6.19k
        }
1312
1313
        /* Move .notdef and the encoded glyphs to the bottom of the list. */
1314
6.19k
        subset.glyphs.subset_data[0] = subset.glyphs.notdef;
1315
6.19k
        memcpy(subset.glyphs.subset_data + 1, encoded,
1316
6.19k
               sizeof(encoded[0]) * num_enc);
1317
6.19k
    }
1318
1319
    /* Set the font name. */
1320
6.19k
    if (alt_font_name)
1321
6.19k
        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
6.19k
    cff_string_table_init(&writer.std_strings, std_string_items,
1328
6.19k
                          MAX_CFF_STD_STRINGS);
1329
2.42M
    for (j = 0; (glyph = gs_c_known_encode((gs_char)j,
1330
2.42M
                                ENCODING_INDEX_CFFSTRINGS)) != GS_NO_GLYPH;
1331
2.42M
         ++j) {
1332
2.42M
        gs_const_string str;
1333
2.42M
        int ignore;
1334
1335
2.42M
        gs_c_glyph_name(glyph, &str);
1336
2.42M
        cff_string_index(&writer.std_strings, str.data, str.size, true,
1337
2.42M
                         &ignore);
1338
2.42M
    }
1339
6.19k
    cff_string_table_init(&writer.strings, string_items, number_of_strings);
1340
1341
    /* Enter miscellaneous strings in the string table. */
1342
6.19k
    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
6.19k
    psf_enumerate_glyphs_begin(&genum, (gs_font *)pfont,
1347
6.19k
                               subset.glyphs.subset_data,
1348
6.19k
                               subset.glyphs.subset_size,
1349
6.19k
                               GLYPH_SPACE_NAME);
1350
129k
    while ((code = psf_enumerate_glyphs_next(&genum, &glyph)) != 1)
1351
123k
        if (code == 0) {
1352
123k
            code = cff_glyph_sid(&writer, glyph);
1353
123k
            if (code == gs_error_undefined)
1354
0
                continue;
1355
123k
            if (code < 0)
1356
0
                goto error;
1357
123k
            charset_size += 2;
1358
123k
        }
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
6.19k
    if ((options & WRITE_TYPE2_NO_GSUBRS) != 0 ||
1371
6.19k
        cff_convert_charstrings(&writer, pbfont) /* we expand all Subrs */
1372
6.19k
        )
1373
5.91k
        gsubrs_count = 0, gsubrs_size = 0;
1374
280
    else
1375
280
        gsubrs_size = cff_write_Subrs_offsets(&writer, &gsubrs_count,
1376
280
                                              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
6.19k
    encoding_size = cff_Encoding_size(&writer, &subset);
1385
1386
    /* Compute the size of the CharStrings Index. */
1387
6.19k
    code = cff_write_CharStrings_offsets(&writer, &genum, &charstrings_count);
1388
6.19k
    if (code < 0)
1389
41
        goto error;
1390
6.15k
    charstrings_size = (uint)code;
1391
1392
    /* Compute the size of the (local) Subrs Index. */
1393
6.15k
#ifdef SKIP_EMPTY_SUBRS
1394
6.15k
    subrs_size =
1395
6.15k
        (cff_convert_charstrings(&writer, pbfont) ? 0 :
1396
6.15k
         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
18.5k
 iter:
1417
18.5k
    swrite_position_only(&poss);
1418
18.5k
    writer.strm = &poss;
1419
1420
    /* Compute the offsets. */
1421
18.5k
    GSubrs_offset = 4 + cff_Index_size(1, font_name.size) +
1422
18.5k
        cff_Index_size(1, Top_size) +
1423
18.5k
        cff_Index_size(writer.strings.count, writer.strings.total);
1424
18.5k
    Encoding_offset = GSubrs_offset +
1425
18.5k
        cff_Index_size(gsubrs_count, gsubrs_size);
1426
18.5k
    charset_offset = Encoding_offset + encoding_size;
1427
18.5k
    CharStrings_offset = charset_offset + charset_size;
1428
18.5k
    Private_offset = CharStrings_offset +
1429
18.5k
        cff_Index_size(charstrings_count, charstrings_size);
1430
18.5k
    Subrs_offset = Private_size;  /* relative to Private Dict */
1431
1432
24.6k
 write:
1433
24.6k
    if(check_ioerror(writer.strm)) {
1434
0
        code = gs_note_error(gs_error_ioerror);
1435
0
        goto error;
1436
0
    }
1437
24.6k
    start_pos = stell(writer.strm);
1438
    /* Write the header, setting offset_size. */
1439
24.6k
    cff_write_header(&writer, End_offset);
1440
1441
    /* Write the names Index. */
1442
24.6k
    cff_put_Index_header(&writer, 1, font_name.size);
1443
24.6k
    put_offset(&writer, font_name.size + 1);
1444
24.6k
    put_bytes(writer.strm, font_name.data, font_name.size);
1445
1446
    /* Write the Top Index. */
1447
24.6k
    cff_put_Index_header(&writer, 1, Top_size);
1448
24.6k
    put_offset(&writer, Top_size + 1);
1449
24.6k
    offset = stell(writer.strm) - start_pos;
1450
24.6k
    cff_write_Top_font(&writer, Encoding_offset, charset_offset,
1451
24.6k
                       CharStrings_offset,
1452
24.6k
                       Private_offset, Private_size);
1453
24.6k
    Top_size = stell(writer.strm) - start_pos - offset;
1454
1455
    /* Write the strings Index. */
1456
24.6k
    cff_put_Index(&writer, &writer.strings);
1457
24.6k
    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
24.6k
    offset = stell(writer.strm) - start_pos;
1464
24.6k
    if_debug2m('l', s->memory, "[l]GSubrs = %u => %u\n", GSubrs_offset, offset);
1465
24.6k
    if (offset > GSubrs_offset) {
1466
0
        code = gs_note_error(gs_error_rangecheck);
1467
0
        goto error;
1468
0
    }
1469
24.6k
    GSubrs_offset = offset;
1470
24.6k
    if (gsubrs_count == 0 || cff_convert_charstrings(&writer, pbfont))
1471
24.6k
        cff_put_Index_header(&writer, 0, 0);
1472
0
    else
1473
0
        cff_write_Subrs(&writer, gsubrs_count, gsubrs_size, pfont, true);
1474
1475
    /* Write the Encoding. */
1476
24.6k
    cff_write_Encoding(&writer, &subset);
1477
1478
    /* Write the charset. */
1479
24.6k
    cff_write_charset(&writer, &subset);
1480
1481
    /* Write the CharStrings Index, checking the offset. */
1482
24.6k
    offset = stell(writer.strm) - start_pos;
1483
24.6k
    if (offset > CharStrings_offset) {
1484
0
        code = gs_note_error(gs_error_rangecheck);
1485
0
        goto error;
1486
0
    }
1487
24.6k
    CharStrings_offset = offset;
1488
24.6k
    cff_write_CharStrings(&writer, &genum, charstrings_count,
1489
24.6k
                          charstrings_size);
1490
24.6k
    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
24.6k
    offset = stell(writer.strm) - start_pos;
1497
24.6k
    if (offset > Private_offset) {
1498
0
        code = gs_note_error(gs_error_rangecheck);
1499
0
        goto error;
1500
0
    }
1501
24.6k
    Private_offset = offset;
1502
24.6k
    cff_write_Private(&writer, (subrs_size == 0 ? 0 : Subrs_offset), pfont);
1503
24.6k
    Private_size = stell(writer.strm) - start_pos - offset;
1504
1505
    /* Write the Subrs Index, checking the offset. */
1506
24.6k
    offset = stell(writer.strm) - (start_pos + Private_offset);
1507
24.6k
    if (offset > Subrs_offset) {
1508
0
        code = gs_note_error(gs_error_rangecheck);
1509
0
        goto error;
1510
0
    }
1511
24.6k
    Subrs_offset = offset;
1512
24.6k
    if (cff_convert_charstrings(&writer, pbfont))
1513
23.5k
        cff_put_Index_header(&writer, 0, 0);
1514
1.16k
    else if (subrs_size != 0)
1515
0
        cff_write_Subrs(&writer, subrs_count, subrs_size, pfont, false);
1516
1517
    /* Check the final offset. */
1518
24.6k
    if(check_ioerror(writer.strm)) {
1519
0
        code = gs_note_error(gs_error_ioerror);
1520
0
        goto error;
1521
0
    }
1522
24.6k
    offset = stell(writer.strm) - start_pos;
1523
24.6k
    if (offset > End_offset) {
1524
0
        code = gs_note_error(gs_error_rangecheck);
1525
0
        goto error;
1526
0
    }
1527
24.6k
    if (offset == End_offset) {
1528
        /* The iteration has converged.  Write the result. */
1529
12.3k
        if (writer.strm == &poss) {
1530
6.15k
            writer.strm = s;
1531
6.15k
            goto write;
1532
6.15k
        }
1533
12.3k
    } else {
1534
        /* No convergence yet. */
1535
12.3k
        End_offset = offset;
1536
12.3k
        goto iter;
1537
12.3k
    }
1538
1539
    /* All done. */
1540
6.15k
    gs_free_object(pfont->memory, std_string_items, "psf_write_type2_font");
1541
6.15k
    gs_free_object(pfont->memory, subset.glyphs.subset_data, "psf_write_type2_font");
1542
6.15k
    return 0;
1543
1544
41
error:
1545
41
    gs_free_object(pfont->memory, std_string_items, "psf_write_type2_font");
1546
41
    gs_free_object(pfont->memory, subset.glyphs.subset_data, "psf_write_type2_font");
1547
41
    subset.glyphs.subset_data = NULL;
1548
41
    return code;
1549
24.6k
}
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
1.92k
{
1556
1.92k
    gs_font_cid0 *const pfont = (gs_font_cid0 *)pbfont;
1557
1.92k
    int font_index;
1558
1.92k
    int code = pfont->cidata.glyph_data(pbfont, glyph, pgd, &font_index);
1559
1560
1.92k
    if (code >= 0)
1561
1.92k
        *ppfont = pfont->cidata.FDArray[font_index];
1562
1.92k
    return code;
1563
1.92k
}
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
15
{
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
15
    gs_font_base *const pbfont = (gs_font_base *)pfont;
1593
15
    cff_writer_t writer;
1594
15
    cff_string_item_t std_string_items[500]; /* 391 entries used */
1595
    /****** HOW TO DETERMINE THE SIZE OF STRINGS? ******/
1596
15
    cff_string_item_t string_items[500 /* character names */ +
1597
15
                                   40 /* misc. values */];
1598
15
    gs_const_string font_name;
1599
15
    stream poss;
1600
15
    uint charstrings_count, charstrings_size;
1601
15
    uint gsubrs_count, gsubrs_size;
1602
15
    uint charset_size, fdselect_size, fdselect_format;
1603
15
    uint subrs_count[256], subrs_size[256];
1604
    /*
1605
     * Set the offsets and sizes to the largest reasonable values
1606
     * (see below).
1607
     */
1608
15
    uint
1609
15
        Top_size = 0x7fffff,
1610
15
        GSubrs_offset = 0x1ffffff,
1611
15
        charset_offset = 0x1ffffff,
1612
15
        FDSelect_offset = 0x1ffffff,
1613
15
        CharStrings_offset = 0x1ffffff,
1614
15
        Font_offset = 0x1ffffff,
1615
15
        FDArray_offsets[257],
1616
15
        Private_offsets[257],
1617
15
        Subrs_offsets[257],
1618
15
        End_offset = 0x1ffffff;
1619
15
    int j;
1620
15
    psf_glyph_enum_t genum;
1621
15
    gs_font_info_t info;
1622
15
    long start_pos;
1623
15
    uint offset;
1624
15
    int num_fonts = pfont->cidata.FDArray_size;
1625
15
    int code;
1626
1627
15
    if (num_fonts > 256)
1628
0
        return_error(gs_error_invalidfont);
1629
1630
15
    memset(&subrs_count, 0x00, 256 * sizeof(uint));
1631
15
    memset(&subrs_size, 0x00, 256 * sizeof(uint));
1632
1633
    /* Initialize the enumeration of the glyphs. */
1634
15
    psf_enumerate_cids_begin(&genum, (gs_font *)pfont, subset_cids,
1635
15
                             subset_size);
1636
1637
    /* Check that the font can be written. */
1638
15
    code = psf_check_outline_glyphs((gs_font_base *)pfont, &genum,
1639
15
                                    cid0_glyph_data);
1640
15
    if (code < 0)
1641
0
        return code;
1642
    /* The .notdef glyph (glyph 0) must be included. */
1643
15
    if (subset_cids && subset_size > 0 && !(subset_cids[0] & 0x80))
1644
0
        return_error(gs_error_rangecheck);
1645
1646
15
    writer.options = options;
1647
15
    s_init(&poss, NULL);
1648
15
    swrite_position_only(&poss);
1649
15
    writer.strm = &poss;
1650
15
    writer.pfont = pbfont;
1651
15
    writer.glyph_data = cid0_glyph_data;
1652
15
    writer.offset_size = 1; /* arbitrary */
1653
15
    writer.start_pos = stell(s);
1654
15
    writer.FontBBox.p.x = writer.FontBBox.p.y = 0;
1655
15
    writer.FontBBox.q.x = writer.FontBBox.q.y = 0;
1656
1657
    /* Set the font name. */
1658
15
    if (alt_font_name)
1659
15
        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
15
    cff_string_table_init(&writer.std_strings, std_string_items,
1669
15
                          countof(std_string_items));
1670
15
    cff_string_table_init(&writer.strings, string_items,
1671
15
                          countof(string_items));
1672
1673
    /* Make all entries in the string table. */
1674
15
    cff_write_ROS(&writer, &pfont->cidata.common.CIDSystemInfo);
1675
60
    for (j = 0; j < num_fonts; ++j) {
1676
45
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1677
1678
45
        cff_write_Top_fdarray(&writer, (gs_font_base *)pfd, 0, 0);
1679
45
    }
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
75
    for (j = 0; j <= num_fonts; ++j)
1690
60
        FDArray_offsets[j] = Private_offsets[j] = Subrs_offsets[j] =
1691
60
            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
15
    if ((options & WRITE_TYPE2_NO_GSUBRS) != 0 ||
1699
15
        cff_convert_charstrings(&writer,
1700
15
                        (const gs_font_base *)pfont->cidata.FDArray[0])
1701
                                /* we expand all Subrs */
1702
15
        )
1703
0
        gsubrs_count = 0, gsubrs_size = 0;
1704
15
    else
1705
15
        gsubrs_size = cff_write_Subrs_offsets(&writer, &gsubrs_count,
1706
15
                                              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
15
    swrite_position_only(&poss);
1713
15
    cff_write_cidset(&writer, &genum);
1714
15
    charset_size = stell(&poss);
1715
1716
    /* Compute the size of the FDSelect strucure. */
1717
15
    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
15
    code = cff_write_CharStrings_offsets(&writer, &genum, &charstrings_count);
1722
15
    if (code < 0)
1723
0
        return code;
1724
15
    charstrings_size = (uint)code;
1725
1726
    /* Compute the size of the (local) Subrs Indexes. */
1727
60
    for (j = 0; j < num_fonts; ++j) {
1728
45
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1729
1730
45
#ifdef SKIP_EMPTY_SUBRS
1731
45
        subrs_size[j] =
1732
45
            (cff_convert_charstrings(&writer, (gs_font_base *)pfd) ? 0 :
1733
45
             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
45
    }
1740
1741
    /* Get the font_info once, since it may be expensive. */
1742
15
    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
45
 iter:
1758
45
    swrite_position_only(&poss);
1759
45
    writer.strm = &poss;
1760
1761
    /* Compute the offsets. */
1762
45
    GSubrs_offset = 4 + cff_Index_size(1, font_name.size) +
1763
45
        cff_Index_size(1, Top_size) +
1764
45
        cff_Index_size(writer.strings.count, writer.strings.total);
1765
45
    charset_offset = GSubrs_offset +
1766
45
        cff_Index_size(gsubrs_count, gsubrs_size);
1767
45
    FDSelect_offset = charset_offset + charset_size;
1768
45
    CharStrings_offset = FDSelect_offset + fdselect_size;
1769
45
    if_debug4m('l', s->memory,
1770
45
               "[l]GSubrs at %u, charset at %u, FDSelect at %u, CharStrings at %u\n",
1771
45
               GSubrs_offset, charset_offset, FDSelect_offset, CharStrings_offset);
1772
1773
60
 write:
1774
60
    start_pos = stell(writer.strm);
1775
60
    if_debug1m('l', s->memory, "[l]start_pos = %ld\n", start_pos);
1776
    /* Write the header, setting offset_size. */
1777
60
    cff_write_header(&writer, End_offset);
1778
1779
    /* Write the names Index. */
1780
60
    cff_put_Index_header(&writer, 1, font_name.size);
1781
60
    put_offset(&writer, font_name.size + 1);
1782
60
    put_bytes(writer.strm, font_name.data, font_name.size);
1783
1784
    /* Write the Top Index. */
1785
60
    cff_put_Index_header(&writer, 1, Top_size);
1786
60
    put_offset(&writer, Top_size + 1);
1787
60
    offset = stell(writer.strm) - start_pos;
1788
60
    cff_write_Top_cidfont(&writer, charset_offset, CharStrings_offset,
1789
60
                          FDSelect_offset, Font_offset, &info);
1790
60
    Top_size = stell(writer.strm) - start_pos - offset;
1791
60
    if_debug1m('l', s->memory, "[l]Top_size = %u\n", Top_size);
1792
1793
    /* Write the strings Index. */
1794
60
    cff_put_Index(&writer, &writer.strings);
1795
1796
    /* Write the GSubrs Index, if any, checking the offset. */
1797
60
    offset = stell(writer.strm) - start_pos;
1798
60
    if_debug2m('l', s->memory, "[l]GSubrs = %u => %u\n", GSubrs_offset, offset);
1799
60
    if (offset > GSubrs_offset)
1800
0
        return_error(gs_error_rangecheck);
1801
60
    GSubrs_offset = offset;
1802
60
    if (gsubrs_count == 0 ||
1803
4
        cff_convert_charstrings(&writer,
1804
4
                        (const gs_font_base *)pfont->cidata.FDArray[0])
1805
60
        )
1806
56
        cff_put_Index_header(&writer, 0, 0);
1807
4
    else
1808
4
        cff_write_Subrs(&writer, gsubrs_count, gsubrs_size,
1809
4
                        pfont->cidata.FDArray[0], true);
1810
1811
    /* Write the charset. */
1812
60
    if_debug1m('l', s->memory, "[l]charset = %"PRId64"\n", (int64_t)(stell(writer.strm) - start_pos));
1813
60
    cff_write_cidset(&writer, &genum);
1814
1815
    /* Write the FDSelect structure, checking the offset. */
1816
60
    offset = stell(writer.strm) - start_pos;
1817
60
    if_debug2m('l', s->memory, "[l]FDSelect = %u => %u\n", FDSelect_offset, offset);
1818
60
    if (offset > FDSelect_offset)
1819
0
        return_error(offset_error("FDselect"));
1820
60
    FDSelect_offset = offset;
1821
60
    cff_write_FDSelect(&writer, &genum, fdselect_size, fdselect_format);
1822
1823
    /* Write the CharStrings Index, checking the offset. */
1824
60
    offset = stell(writer.strm) - start_pos;
1825
60
    if_debug2m('l', s->memory, "[l]CharStrings = %u => %u\n", CharStrings_offset, offset);
1826
60
    if (offset > CharStrings_offset)
1827
0
        return_error(offset_error("CharStrings"));
1828
60
    CharStrings_offset = offset;
1829
60
    cff_write_CharStrings(&writer, &genum, charstrings_count,
1830
60
                          charstrings_size);
1831
1832
    /* Write the Font Dict Index. */
1833
60
    offset = stell(writer.strm) - start_pos;
1834
60
    if_debug2m('l', s->memory, "[l]Font = %u => %u\n", Font_offset, offset);
1835
60
    if (offset > Font_offset)
1836
0
        return_error(offset_error("Font"));
1837
60
    Font_offset = offset;
1838
60
    cff_write_FDArray_offsets(&writer, FDArray_offsets, num_fonts);
1839
60
    offset = stell(writer.strm) - start_pos;
1840
60
    if_debug2m('l', s->memory, "[l]FDArray[0] = %u => %u\n", FDArray_offsets[0], offset);
1841
60
    if (offset > FDArray_offsets[0])
1842
0
        return_error(offset_error("FDArray[0]"));
1843
60
    FDArray_offsets[0] = offset;
1844
240
    for (j = 0; j < num_fonts; ++j) {
1845
180
        gs_font_type1 *pfd = pfont->cidata.FDArray[j];
1846
1847
        /* If we're writing Type 2 CharStrings, don't encrypt them. */
1848
180
        if (options & WRITE_TYPE2_CHARSTRINGS) {
1849
180
            options |= WRITE_TYPE2_NO_LENIV;
1850
180
            if (pfd->FontType != ft_encrypted2)
1851
0
                pfd->data.defaultWidthX = pfd->data.nominalWidthX = 0;
1852
180
        }
1853
180
        cff_write_Top_fdarray(&writer, (gs_font_base *)pfd, Private_offsets[j],
1854
180
                              Private_offsets[j + 1] - Private_offsets[j]);
1855
180
        offset = stell(writer.strm) - start_pos;
1856
180
        if_debug3m('l', s->memory, "[l]FDArray[%d] = %u => %u\n", j + 1,
1857
180
                   FDArray_offsets[j + 1], offset);
1858
180
        if (offset > FDArray_offsets[j + 1])
1859
0
            return_error(offset_error("FDArray"));
1860
180
        FDArray_offsets[j + 1] = offset;
1861
180
    }
1862
1863
    /* Write the Private Dicts, checking the offset. */
1864
240
    for (j = 0; ; ++j) {
1865
240
        gs_font_type1 *pfd;
1866
1867
240
        offset = stell(writer.strm) - start_pos;
1868
240
        if_debug3m('l', s->memory, "[l]Private[%d] = %u => %u\n",
1869
240
                   j, Private_offsets[j], offset);
1870
240
        if (offset > Private_offsets[j])
1871
0
            return_error(offset_error("Private"));
1872
240
        Private_offsets[j] = offset;
1873
240
        if (j == num_fonts)
1874
60
            break;
1875
180
        pfd = pfont->cidata.FDArray[j];
1876
180
        cff_write_Private(&writer,
1877
180
                          (subrs_size[j] == 0 ? 0 : Subrs_offsets[j]), pfd);
1878
180
    }
1879
1880
    /* Write the Subrs Indexes, checking the offsets. */
1881
240
    for (j = 0; ; ++j) {
1882
240
        gs_font_type1 *pfd;
1883
1884
240
        offset = stell(writer.strm) - (start_pos + Private_offsets[j]);
1885
240
        if_debug3m('l', s->memory, "[l]Subrs[%d] = %u => %u\n",
1886
240
                   j, Subrs_offsets[j], offset);
1887
240
        if (offset > Subrs_offsets[j])
1888
0
            return_error(offset_error("Subrs"));
1889
240
        Subrs_offsets[j] = offset;
1890
240
        if (j == num_fonts)
1891
60
            break;
1892
180
        pfd = pfont->cidata.FDArray[j];
1893
180
        if (cff_convert_charstrings(&writer, (gs_font_base *)pfd))
1894
0
            cff_put_Index_header(&writer, 0, 0);
1895
180
        else if (subrs_size[j] != 0)
1896
4
            cff_write_Subrs(&writer, subrs_count[j], subrs_size[j], pfd, false);
1897
180
    }
1898
1899
    /* Check the final offset. */
1900
60
    offset = stell(writer.strm) - start_pos;
1901
60
    if_debug2m('l', s->memory, "[l]End = %u => %u\n", End_offset, offset);
1902
60
    if (offset > End_offset)
1903
0
        return_error(offset_error("End"));
1904
60
    if (offset == End_offset) {
1905
        /* The iteration has converged.  Write the result. */
1906
30
        if (writer.strm == &poss) {
1907
15
            writer.strm = s;
1908
15
            goto write;
1909
15
        }
1910
30
    } else {
1911
        /* No convergence yet. */
1912
30
        End_offset = offset;
1913
30
        goto iter;
1914
30
    }
1915
1916
    /* All done. */
1917
15
    return 0;
1918
60
}