Coverage Report

Created: 2022-10-31 07:00

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