e507abeae4cb0ec2cf1134dfa556998afa675387
[framework/graphics/cairo.git] / src / cairo-type1-subset.c
1 /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright © 2006 Red Hat, Inc
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it either under the terms of the GNU Lesser General Public
8  * License version 2.1 as published by the Free Software Foundation
9  * (the "LGPL") or, at your option, under the terms of the Mozilla
10  * Public License Version 1.1 (the "MPL"). If you do not alter this
11  * notice, a recipient may use your version of this file under either
12  * the MPL or the LGPL.
13  *
14  * You should have received a copy of the LGPL along with this library
15  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17  * You should have received a copy of the MPL along with this library
18  * in the file COPYING-MPL-1.1
19  *
20  * The contents of this file are subject to the Mozilla Public License
21  * Version 1.1 (the "License"); you may not use this file except in
22  * compliance with the License. You may obtain a copy of the License at
23  * http://www.mozilla.org/MPL/
24  *
25  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27  * the specific language governing rights and limitations.
28  *
29  * The Original Code is the cairo graphics library.
30  *
31  * The Initial Developer of the Original Code is Red Hat, Inc.
32  *
33  * Contributor(s):
34  *      Kristian Høgsberg <krh@redhat.com>
35  */
36
37 /*
38  * Useful links:
39  * http://partners.adobe.com/public/developer/en/font/T1_SPEC.PDF
40  */
41
42
43 #define _BSD_SOURCE /* for snprintf(), strdup() */
44 #include "cairoint.h"
45
46 #include "cairo-array-private.h"
47 #include "cairo-error-private.h"
48
49 #if CAIRO_HAS_FONT_SUBSET
50
51 #include "cairo-type1-private.h"
52 #include "cairo-scaled-font-subsets-private.h"
53 #include "cairo-output-stream-private.h"
54
55 #include <ctype.h>
56
57 #define TYPE1_STACKSIZE 24 /* Defined in Type 1 Font Format */
58
59
60 typedef struct {
61     int subset_index;
62     double width;
63     const char *encrypted_charstring;
64     int encrypted_charstring_length;
65 } glyph_data_t;
66
67 typedef struct _cairo_type1_font_subset {
68     cairo_scaled_font_subset_t *scaled_font_subset;
69
70     struct {
71         unsigned int font_id;
72         char *base_font;
73         unsigned int num_glyphs;
74         double x_min, y_min, x_max, y_max;
75         double ascent, descent;
76         double units_per_em;
77
78         const char    *data;
79         unsigned long  header_size;
80         unsigned long  data_size;
81         unsigned long  trailer_size;
82     } base;
83
84     int num_glyphs;
85
86     /* The glyphs and glyph_names arrays are indexed by the order of
87      * the Charstrings in the font. This is not necessarily the same
88      * order as the glyph index. The index_to_glyph_name() font backend
89      * function is used to map the glyph index to the glyph order in
90      * the Charstrings. */
91
92     glyph_data_t *glyphs;
93     char **glyph_names;
94     cairo_array_t glyphs_array;
95     cairo_array_t glyph_names_array;
96
97     int num_subrs;
98     cairo_bool_t subset_subrs;
99     struct {
100         const char *subr_string;
101         int subr_length;
102         const char *np;
103         int np_length;
104         cairo_bool_t used;
105     } *subrs;
106
107     /* Indexed by subset_index this maps to the glyph order in the
108      * glyph_names and glyphs arrays. Has font->num_golyphs
109      * elements. */
110     int *subset_index_to_glyphs;
111
112     cairo_output_stream_t *output;
113     cairo_array_t contents;
114
115     const char *rd, *nd, *np;
116
117     char *type1_data;
118     unsigned int type1_length;
119     char *type1_end;
120
121     char *header_segment;
122     int header_segment_size;
123     char *eexec_segment;
124     int eexec_segment_size;
125     cairo_bool_t eexec_segment_is_ascii;
126
127     char *cleartext;
128     char *cleartext_end;
129
130     int header_size;
131
132     unsigned short eexec_key;
133     cairo_bool_t hex_encode;
134     int hex_column;
135
136     struct {
137         int stack[TYPE1_STACKSIZE], sp, top_value;
138     } build_stack;
139
140     struct {
141         int other_subr_args[TYPE1_STACKSIZE], num_other_subr_args, cur_other_subr_arg;
142     } ps_stack;
143
144
145 } cairo_type1_font_subset_t;
146
147
148 static cairo_status_t
149 _cairo_type1_font_subset_init (cairo_type1_font_subset_t  *font,
150                                cairo_scaled_font_subset_t *scaled_font_subset,
151                                cairo_bool_t                hex_encode)
152 {
153     memset (font, 0, sizeof (*font));
154     font->scaled_font_subset = scaled_font_subset;
155
156     _cairo_array_init (&font->glyphs_array, sizeof (glyph_data_t));
157     _cairo_array_init (&font->glyph_names_array, sizeof (char *));
158     font->subset_index_to_glyphs = NULL;
159     font->base.num_glyphs = 0;
160     font->num_subrs = 0;
161     font->subset_subrs = TRUE;
162     font->subrs = NULL;
163
164     font->hex_encode = hex_encode;
165     font->num_glyphs = 0;
166
167     _cairo_array_init (&font->contents, sizeof (char));
168
169     return CAIRO_STATUS_SUCCESS;
170 }
171
172 static void
173 cairo_type1_font_subset_use_glyph (cairo_type1_font_subset_t *font, int glyph)
174 {
175     if (font->glyphs[glyph].subset_index >= 0)
176         return;
177
178     font->glyphs[glyph].subset_index = font->num_glyphs;
179     font->subset_index_to_glyphs[font->num_glyphs] = glyph;
180     font->num_glyphs++;
181 }
182
183 static cairo_bool_t
184 is_ps_delimiter(int c)
185 {
186     static const char delimiters[] = "()[]{}<>/% \t\r\n";
187
188     return strchr (delimiters, c) != NULL;
189 }
190
191 static const char *
192 find_token (const char *buffer, const char *end, const char *token)
193 {
194     int i, length;
195     /* FIXME: find substring really must be find_token */
196
197     if (buffer == NULL)
198         return NULL;
199
200     length = strlen (token);
201     for (i = 0; buffer + i < end - length + 1; i++)
202         if (memcmp (buffer + i, token, length) == 0)
203             if ((i == 0 || token[0] == '/' || is_ps_delimiter(buffer[i - 1])) &&
204                 (buffer + i == end - length || is_ps_delimiter(buffer[i + length])))
205                 return buffer + i;
206
207     return NULL;
208 }
209
210 static cairo_status_t
211 cairo_type1_font_subset_find_segments (cairo_type1_font_subset_t *font)
212 {
213     unsigned char *p;
214     const char *eexec_token;
215     int size, i;
216
217     p = (unsigned char *) font->type1_data;
218     font->type1_end = font->type1_data + font->type1_length;
219     if (p[0] == 0x80 && p[1] == 0x01) {
220         font->header_segment_size =
221             p[2] | (p[3] << 8) | (p[4] << 16) | (p[5] << 24);
222         font->header_segment = (char *) p + 6;
223
224         p += 6 + font->header_segment_size;
225         font->eexec_segment_size =
226             p[2] | (p[3] << 8) | (p[4] << 16) | (p[5] << 24);
227         font->eexec_segment = (char *) p + 6;
228         font->eexec_segment_is_ascii = (p[1] == 1);
229
230         p += 6 + font->eexec_segment_size;
231         while (p < (unsigned char *) (font->type1_end) && p[1] != 0x03) {
232             size = p[2] | (p[3] << 8) | (p[4] << 16) | (p[5] << 24);
233             p += 6 + size;
234         }
235         font->type1_end = (char *) p;
236     } else {
237         eexec_token = find_token ((char *) p, font->type1_end, "eexec");
238         if (eexec_token == NULL)
239             return CAIRO_INT_STATUS_UNSUPPORTED;
240
241         font->header_segment_size = eexec_token - (char *) p + strlen ("eexec\n");
242         font->header_segment = (char *) p;
243         font->eexec_segment_size = font->type1_length - font->header_segment_size;
244         font->eexec_segment = (char *) p + font->header_segment_size;
245         font->eexec_segment_is_ascii = TRUE;
246         for (i = 0; i < 4; i++) {
247             if (!isxdigit(font->eexec_segment[i]))
248                 font->eexec_segment_is_ascii = FALSE;
249         }
250     }
251
252     return CAIRO_STATUS_SUCCESS;
253 }
254
255 /* Search for the definition of key and erase it by overwriting with spaces.
256  * This function is looks for definitions of the form:
257  *
258  * /key1 1234 def
259  * /key2 [12 34 56] def
260  *
261  * ie a key defined as an integer or array of integers.
262  *
263  */
264 static void
265 cairo_type1_font_erase_dict_key (cairo_type1_font_subset_t *font,
266                                  const char *key)
267 {
268     const char *start, *p, *segment_end;
269
270     segment_end = font->header_segment + font->header_segment_size;
271
272     start = font->header_segment;
273     do {
274         start = find_token (start, segment_end, key);
275         if (start) {
276             p = start + strlen(key);
277             /* skip integers or array of integers */
278             while (p < segment_end &&
279                    (_cairo_isspace(*p) ||
280                     _cairo_isdigit(*p) ||
281                     *p == '[' ||
282                     *p == ']'))
283             {
284                 p++;
285             }
286
287             if (p + 3 < segment_end && memcmp(p, "def", 3) == 0) {
288                 /* erase definition of the key */
289                 memset((char *) start, ' ', p + 3 - start);
290             }
291             start += strlen(key);
292         }
293     } while (start);
294 }
295
296 static cairo_status_t
297 cairo_type1_font_subset_get_matrix (cairo_type1_font_subset_t *font,
298                                     const char                *name,
299                                     double                    *a,
300                                     double                    *b,
301                                     double                    *c,
302                                     double                    *d)
303 {
304     const char *start, *end, *segment_end;
305     int ret;
306     char *s;
307
308     segment_end = font->header_segment + font->header_segment_size;
309     start = find_token (font->header_segment, segment_end, name);
310     if (start == NULL)
311         return CAIRO_INT_STATUS_UNSUPPORTED;
312
313     end = find_token (start, segment_end, "def");
314     if (end == NULL)
315         return CAIRO_INT_STATUS_UNSUPPORTED;
316
317     s = malloc (end - start + 1);
318     if (unlikely (s == NULL))
319         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
320
321     strncpy (s, start, end - start);
322     s[end - start] = 0;
323
324     start = strpbrk (s, "{[");
325     if (!start) {
326         free (s);
327         return CAIRO_INT_STATUS_UNSUPPORTED;
328     }
329
330     start++;
331     ret = 0;
332     if (*start)
333         ret = sscanf(start, "%lf %lf %lf %lf", a, b, c, d);
334
335     free (s);
336
337     if (ret != 4)
338         return CAIRO_INT_STATUS_UNSUPPORTED;
339
340     return CAIRO_STATUS_SUCCESS;
341 }
342
343 static cairo_status_t
344 cairo_type1_font_subset_get_bbox (cairo_type1_font_subset_t *font)
345 {
346     cairo_status_t status;
347     double x_min, y_min, x_max, y_max;
348     double xx, yx, xy, yy;
349
350     status = cairo_type1_font_subset_get_matrix (font, "/FontBBox",
351                                                  &x_min,
352                                                  &y_min,
353                                                  &x_max,
354                                                  &y_max);
355     if (unlikely (status))
356         return status;
357
358     status = cairo_type1_font_subset_get_matrix (font, "/FontMatrix",
359                                                  &xx, &yx, &xy, &yy);
360     if (unlikely (status))
361         return status;
362
363     if (yy == 0.0)
364         return CAIRO_INT_STATUS_UNSUPPORTED;
365
366     /* Freetype uses 1/yy to get units per EM */
367     font->base.units_per_em = 1.0/yy;
368
369     font->base.x_min = x_min / font->base.units_per_em;
370     font->base.y_min = y_min / font->base.units_per_em;
371     font->base.x_max = x_max / font->base.units_per_em;
372     font->base.y_max = y_max / font->base.units_per_em;
373     font->base.ascent = font->base.y_max;
374     font->base.descent = font->base.y_min;
375
376     return CAIRO_STATUS_SUCCESS;
377 }
378
379 static cairo_status_t
380 cairo_type1_font_subset_get_fontname (cairo_type1_font_subset_t *font)
381 {
382     const char *start, *end, *segment_end;
383     char *s;
384     int i;
385
386     segment_end = font->header_segment + font->header_segment_size;
387     start = find_token (font->header_segment, segment_end, "/FontName");
388     if (start == NULL)
389         return CAIRO_INT_STATUS_UNSUPPORTED;
390
391     start += strlen ("/FontName");
392
393     end = find_token (start, segment_end, "def");
394     if (end == NULL)
395         return CAIRO_INT_STATUS_UNSUPPORTED;
396
397     s = malloc (end - start + 1);
398     if (unlikely (s == NULL))
399         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
400
401     strncpy (s, start, end - start);
402     s[end - start] = 0;
403
404     start = strchr (s, '/');
405     if (!start++ || !start) {
406         free (s);
407         return CAIRO_INT_STATUS_UNSUPPORTED;
408     }
409
410     /* If font name is prefixed with a subset tag, strip it off. */
411     if (strlen(start) > 7 && start[6] == '+') {
412         for (i = 0; i < 6; i++) {
413             if (start[i] < 'A' || start[i] > 'Z')
414                 break;
415         }
416         if (i == 6)
417             start += 7;
418     }
419
420     font->base.base_font = strdup (start);
421     free (s);
422     if (unlikely (font->base.base_font == NULL))
423         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
424
425     s = font->base.base_font;
426     while (*s && !is_ps_delimiter(*s))
427         s++;
428
429     *s = 0;
430
431     return CAIRO_STATUS_SUCCESS;
432 }
433
434 static cairo_status_t
435 cairo_type1_font_subset_write_header (cairo_type1_font_subset_t *font,
436                                          const char *name)
437 {
438     const char *start, *end, *segment_end;
439     unsigned int i;
440
441     /* FIXME:
442      * This function assumes that /FontName always appears
443      * before /Encoding. This appears to always be the case with Type1
444      * fonts.
445      *
446      * The more recently added code for removing the UniqueID and XUID
447      * keys can not make any assumptions about the position of the
448      * keys in the dictionary so it is implemented by overwriting the
449      * key definition with spaces before we start copying the font to
450      * the output.
451      *
452      * This code should be rewritten to not make any assumptions about
453      * the order of dictionary keys. This will allow UniqueID to be
454      * stripped out instead of leaving a bunch of spaces in the
455      * output.
456      */
457     cairo_type1_font_erase_dict_key (font, "/UniqueID");
458     cairo_type1_font_erase_dict_key (font, "/XUID");
459
460     segment_end = font->header_segment + font->header_segment_size;
461
462     /* Type 1 fonts created by Fontforge have some PostScript code at
463      * the start of the font that skips the font if the printer has a
464      * cached copy of the font with the same unique id. This breaks
465      * our subsetted font so we disable it by searching for the
466      * PostScript operator "known" when used to check for the
467      * "/UniqueID" dictionary key. We append " pop false " after it to
468      * pop the result of this check off the stack and replace it with
469      * "false" to make the PostScript code think "/UniqueID" does not
470      * exist.
471      */
472     end = font->header_segment;
473     start = find_token (font->header_segment, segment_end, "/UniqueID");
474     if (start) {
475         start += 9;
476         while (start < segment_end && _cairo_isspace (*start))
477             start++;
478         if (start + 5 < segment_end && memcmp(start, "known", 5) == 0) {
479             _cairo_output_stream_write (font->output, font->header_segment,
480                                         start + 5 - font->header_segment);
481             _cairo_output_stream_printf (font->output, " pop false ");
482             end = start + 5;
483         }
484     }
485
486     start = find_token (end, segment_end, "/FontName");
487     if (start == NULL)
488         return CAIRO_INT_STATUS_UNSUPPORTED;
489
490     _cairo_output_stream_write (font->output, end,
491                                 start - end);
492
493     _cairo_output_stream_printf (font->output, "/FontName /%s def", name);
494
495     end = find_token (start, segment_end, "def");
496     if (end == NULL)
497         return CAIRO_INT_STATUS_UNSUPPORTED;
498     end += 3;
499
500     start = find_token (end, segment_end, "/Encoding");
501     if (start == NULL)
502         return CAIRO_INT_STATUS_UNSUPPORTED;
503     _cairo_output_stream_write (font->output, end, start - end);
504
505     _cairo_output_stream_printf (font->output,
506                                  "/Encoding 256 array\n"
507                                  "0 1 255 {1 index exch /.notdef put} for\n");
508     if (font->scaled_font_subset->is_latin) {
509         for (i = 1; i < 256; i++) {
510             int subset_glyph = font->scaled_font_subset->latin_to_subset_glyph_index[i];
511             int glyph_num = font->subset_index_to_glyphs[subset_glyph];
512
513             if (subset_glyph > 0) {
514                 _cairo_output_stream_printf (font->output,
515                                              "dup %d /%s put\n",
516                                              i,
517                                              font->glyph_names[glyph_num]);
518             }
519         }
520     } else {
521         for (i = 1; i < font->base.num_glyphs; i++) {
522             if (font->glyphs[i].subset_index < 0)
523                 continue;
524             _cairo_output_stream_printf (font->output,
525                                          "dup %d /%s put\n",
526                                          font->glyphs[i].subset_index,
527                                          font->glyph_names[i]);
528         }
529     }
530     _cairo_output_stream_printf (font->output, "readonly def");
531
532     end = find_token (start, segment_end, "def");
533     if (end == NULL)
534         return CAIRO_INT_STATUS_UNSUPPORTED;
535     end += 3;
536
537     /* There are some buggy fonts that contain more than one /Encoding */
538     if (find_token (end, segment_end, "/Encoding"))
539         return CAIRO_INT_STATUS_UNSUPPORTED;
540
541     _cairo_output_stream_write (font->output, end, segment_end - end);
542
543     return font->output->status;
544 }
545
546 static int
547 hex_to_int (int ch)
548 {
549     if (ch <= '9')
550         return ch - '0';
551     else if (ch <= 'F')
552         return ch - 'A' + 10;
553     else
554         return ch - 'a' + 10;
555 }
556
557 static cairo_status_t
558 cairo_type1_font_subset_write_encrypted (cairo_type1_font_subset_t *font,
559                                          const char *data, unsigned int length)
560 {
561     const unsigned char *in, *end;
562     int c, p;
563     static const char hex_digits[16] = "0123456789abcdef";
564     char digits[3];
565
566     in = (const unsigned char *) data;
567     end = (const unsigned char *) data + length;
568     while (in < end) {
569         p = *in++;
570         c = p ^ (font->eexec_key >> 8);
571         font->eexec_key = (c + font->eexec_key) * CAIRO_TYPE1_ENCRYPT_C1 + CAIRO_TYPE1_ENCRYPT_C2;
572
573         if (font->hex_encode) {
574             digits[0] = hex_digits[c >> 4];
575             digits[1] = hex_digits[c & 0x0f];
576             digits[2] = '\n';
577             font->hex_column += 2;
578
579             if (font->hex_column == 78) {
580                 _cairo_output_stream_write (font->output, digits, 3);
581                 font->hex_column = 0;
582             } else {
583                 _cairo_output_stream_write (font->output, digits, 2);
584             }
585         } else {
586             digits[0] = c;
587             _cairo_output_stream_write (font->output, digits, 1);
588         }
589     }
590
591     return font->output->status;
592 }
593
594 static cairo_status_t
595 cairo_type1_font_subset_decrypt_eexec_segment (cairo_type1_font_subset_t *font)
596 {
597     unsigned short r = CAIRO_TYPE1_PRIVATE_DICT_KEY;
598     unsigned char *in, *end;
599     char *out;
600     int c, p;
601     int i;
602
603     in = (unsigned char *) font->eexec_segment;
604     end = (unsigned char *) in + font->eexec_segment_size;
605
606     font->cleartext = malloc (font->eexec_segment_size + 1);
607     if (unlikely (font->cleartext == NULL))
608         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
609
610     out = font->cleartext;
611     while (in < end) {
612         if (font->eexec_segment_is_ascii) {
613             c = *in++;
614             if (_cairo_isspace (c))
615                 continue;
616             c = (hex_to_int (c) << 4) | hex_to_int (*in++);
617         } else {
618             c = *in++;
619         }
620         p = c ^ (r >> 8);
621         r = (c + r) * CAIRO_TYPE1_ENCRYPT_C1 + CAIRO_TYPE1_ENCRYPT_C2;
622
623         *out++ = p;
624     }
625     font->cleartext_end = out;
626
627     /* Overwrite random bytes with spaces.
628      *
629      * The first 4 bytes of the cleartext are the random bytes
630      * required by the encryption algorithm. When encrypting the
631      * cleartext, the first ciphertext byte must not be a white space
632      * character and the first 4 bytes must not be an ASCII Hex
633      * character. Some fonts do not check that their randomly chosen
634      * bytes results in ciphertext that complies with this
635      * restriction. This may cause problems for some PDF consumers. By
636      * replacing the random bytes with spaces, the first four bytes of
637      * ciphertext will always be 0xf9, 0x83, 0xef, 0x00 which complies
638      * with this restriction. Using spaces also means we don't have to
639      * skip over the random bytes when parsing the cleartext.
640      */
641     for (i = 0; i < 4 && i < font->eexec_segment_size; i++)
642         font->cleartext[i] = ' ';
643
644     /* Ensure strtol() can not scan past the end of the cleartext */
645     font->cleartext[font->eexec_segment_size] = 0;
646
647     return CAIRO_STATUS_SUCCESS;
648 }
649
650 static const char *
651 skip_token (const char *p, const char *end)
652 {
653     while (p < end && _cairo_isspace(*p))
654         p++;
655
656     while (p < end && !_cairo_isspace(*p))
657         p++;
658
659     if (p == end)
660         return NULL;
661
662     return p;
663 }
664
665 static void
666 cairo_type1_font_subset_decrypt_charstring (const unsigned char *in, int size, unsigned char *out)
667 {
668     unsigned short r = CAIRO_TYPE1_CHARSTRING_KEY;
669     int c, p, i;
670
671     for (i = 0; i < size; i++) {
672         c = *in++;
673         p = c ^ (r >> 8);
674         r = (c + r) * CAIRO_TYPE1_ENCRYPT_C1 + CAIRO_TYPE1_ENCRYPT_C2;
675         *out++ = p;
676     }
677 }
678
679 static const unsigned char *
680 cairo_type1_font_subset_decode_integer (const unsigned char *p, int *integer)
681 {
682     if (*p <= 246) {
683         *integer = *p++ - 139;
684     } else if (*p <= 250) {
685         *integer = (p[0] - 247) * 256 + p[1] + 108;
686         p += 2;
687     } else if (*p <= 254) {
688         *integer = -(p[0] - 251) * 256 - p[1] - 108;
689         p += 2;
690     } else {
691         *integer = (p[1] << 24) | (p[2] << 16) | (p[3] << 8) | p[4];
692         p += 5;
693     }
694
695     return p;
696 }
697
698 static cairo_status_t
699 use_standard_encoding_glyph (cairo_type1_font_subset_t *font, int index)
700 {
701     const char *glyph_name;
702     unsigned int i;
703
704     if (index < 0 || index > 255)
705         return CAIRO_STATUS_SUCCESS;
706
707     glyph_name = _cairo_ps_standard_encoding_to_glyphname (index);
708     if (glyph_name == NULL)
709         return CAIRO_STATUS_SUCCESS;
710
711     for (i = 0; i < font->base.num_glyphs; i++) {
712         if (font->glyph_names[i] &&  strcmp (font->glyph_names[i], glyph_name) == 0) {
713             cairo_type1_font_subset_use_glyph (font, i);
714
715             return CAIRO_STATUS_SUCCESS;
716         }
717     }
718
719     return CAIRO_INT_STATUS_UNSUPPORTED;
720 }
721
722 #define TYPE1_CHARSTRING_COMMAND_ESCAPE         0x0c
723 #define TYPE1_CHARSTRING_COMMAND_SEAC           0x0c06
724 #define TYPE1_CHARSTRING_COMMAND_SBW            0x0c07
725 #define TYPE1_CHARSTRING_COMMAND_HSBW           0x0d
726 #define TYPE1_CHARSTRING_COMMAND_CALLSUBR       0x0a
727 #define TYPE1_CHARSTRING_COMMAND_CALLOTHERSUBR  0x0c10
728 #define TYPE1_CHARSTRING_COMMAND_POP            0x0c11
729
730
731
732 /* Get glyph width and look for seac operatorParse charstring */
733 static cairo_status_t
734 cairo_type1_font_subset_parse_charstring (cairo_type1_font_subset_t *font,
735                                           int                        glyph,
736                                           const char                *encrypted_charstring,
737                                           int                        encrypted_charstring_length)
738 {
739     cairo_status_t status;
740     unsigned char *charstring;
741     const unsigned char *end;
742     const unsigned char *p;
743     cairo_bool_t last_op_was_integer;
744     int command;
745     int subr_num, i;
746
747     charstring = malloc (encrypted_charstring_length);
748     if (unlikely (charstring == NULL))
749         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
750
751     cairo_type1_font_subset_decrypt_charstring ((const unsigned char *)
752                                                 encrypted_charstring,
753                                                 encrypted_charstring_length,
754                                                 charstring);
755     end = charstring + encrypted_charstring_length;
756
757     p = charstring + 4;
758
759     last_op_was_integer = FALSE;
760
761     while (p < end) {
762         if (*p < 32) {
763             command = *p++;
764             switch (command) {
765             case TYPE1_CHARSTRING_COMMAND_HSBW:
766                 if (! last_op_was_integer)
767                     return CAIRO_INT_STATUS_UNSUPPORTED;
768
769                 font->glyphs[glyph].width = font->build_stack.stack[1]/font->base.units_per_em;
770                 font->build_stack.sp = 0;
771                 last_op_was_integer = FALSE;
772                 break;
773
774             case TYPE1_CHARSTRING_COMMAND_CALLSUBR:
775                 if (font->subset_subrs  &&
776                     last_op_was_integer &&
777                     font->build_stack.top_value >= 0    &&
778                     font->build_stack.top_value < font->num_subrs)
779                 {
780                     subr_num = font->build_stack.top_value;
781                     font->subrs[subr_num].used = TRUE;
782                     last_op_was_integer = FALSE;
783                     status = cairo_type1_font_subset_parse_charstring (font,
784                                                                        glyph,
785                                                                        font->subrs[subr_num].subr_string,
786                                                                        font->subrs[subr_num].subr_length);
787                 } else {
788                     font->subset_subrs = FALSE;
789                 }
790                 break;
791
792             case TYPE1_CHARSTRING_COMMAND_ESCAPE:
793                 command = command << 8 | *p++;
794                 switch (command) {
795                 case TYPE1_CHARSTRING_COMMAND_SEAC:
796                     /* The seac command takes five integer arguments.  The
797                      * last two are glyph indices into the PS standard
798                      * encoding give the names of the glyphs that this
799                      * glyph is composed from.  All we need to do is to
800                      * make sure those glyphs are present in the subset
801                      * under their standard names. */
802                     status = use_standard_encoding_glyph (font, font->build_stack.stack[3]);
803                     if (unlikely (status))
804                         return status;
805
806                     status = use_standard_encoding_glyph (font, font->build_stack.stack[4]);
807                     if (unlikely (status))
808                         return status;
809
810                     font->build_stack.sp = 0;
811                     last_op_was_integer = FALSE;
812                     break;
813
814                 case TYPE1_CHARSTRING_COMMAND_SBW:
815                     if (! last_op_was_integer)
816                         return CAIRO_INT_STATUS_UNSUPPORTED;
817
818                     font->glyphs[glyph].width = font->build_stack.stack[2]/font->base.units_per_em;
819                     font->build_stack.sp = 0;
820                     last_op_was_integer = FALSE;
821                     break;
822
823                 case TYPE1_CHARSTRING_COMMAND_CALLOTHERSUBR:
824                     for (i = 0; i < font->build_stack.sp; i++)
825                         font->ps_stack.other_subr_args[i] = font->build_stack.stack[i];
826                     font->ps_stack.num_other_subr_args = font->build_stack.sp;
827                     font->ps_stack.cur_other_subr_arg = 0;
828                     font->build_stack.sp = 0;
829                     last_op_was_integer = FALSE;
830                     break;
831
832                 case TYPE1_CHARSTRING_COMMAND_POP:
833                     if (font->ps_stack.num_other_subr_args > font->ps_stack.cur_other_subr_arg) {
834                         font->build_stack.top_value = font->ps_stack.other_subr_args[font->ps_stack.cur_other_subr_arg++];
835                         last_op_was_integer = TRUE;
836                     } else {
837                         font->subset_subrs = FALSE;
838                     }
839                     break;
840
841                 default:
842                     font->build_stack.sp = 0;
843                     last_op_was_integer = FALSE;
844                     break;
845                 }
846                 break;
847
848             default:
849                 font->build_stack.sp = 0;
850                 last_op_was_integer = FALSE;
851                 break;
852             }
853         } else {
854             /* integer argument */
855             p = cairo_type1_font_subset_decode_integer (p, &font->build_stack.top_value);
856             last_op_was_integer = TRUE;
857             if (font->build_stack.sp < TYPE1_STACKSIZE)
858                 font->build_stack.stack[font->build_stack.sp++] = font->build_stack.top_value;
859         }
860     }
861
862     free (charstring);
863
864     return CAIRO_STATUS_SUCCESS;
865 }
866
867 static cairo_status_t
868 cairo_type1_font_subset_build_subr_list (cairo_type1_font_subset_t *font,
869                                          int subr_number,
870                                          const char *encrypted_charstring, int encrypted_charstring_length,
871                                          const char *np, int np_length)
872 {
873
874     font->subrs[subr_number].subr_string = encrypted_charstring;
875     font->subrs[subr_number].subr_length = encrypted_charstring_length;
876     font->subrs[subr_number].np = np;
877     font->subrs[subr_number].np_length = np_length;
878
879     return CAIRO_STATUS_SUCCESS;
880 }
881
882 static cairo_status_t
883 write_used_subrs (cairo_type1_font_subset_t *font,
884                   int subr_number,
885                   const char *subr_string, int subr_string_length,
886                   const char *np, int np_length)
887 {
888     cairo_status_t status;
889     char buffer[256];
890     int length;
891
892     if (!font->subrs[subr_number].used)
893         return CAIRO_STATUS_SUCCESS;
894
895     length = snprintf (buffer, sizeof buffer,
896                        "dup %d %d %s ",
897                        subr_number, subr_string_length, font->rd);
898     status = cairo_type1_font_subset_write_encrypted (font, buffer, length);
899     if (unlikely (status))
900         return status;
901
902     status = cairo_type1_font_subset_write_encrypted (font,
903                                                       subr_string,
904                                                       subr_string_length);
905     if (unlikely (status))
906         return status;
907
908     if (np) {
909         status = cairo_type1_font_subset_write_encrypted (font, np, np_length);
910     } else {
911         length = snprintf (buffer, sizeof buffer, "%s\n", font->np);
912         status = cairo_type1_font_subset_write_encrypted (font, buffer, length);
913     }
914     if (unlikely (status))
915         return status;
916
917     return CAIRO_STATUS_SUCCESS;
918 }
919
920 typedef cairo_status_t (*subr_func_t) (cairo_type1_font_subset_t *font,
921                                        int subr_number,
922                                        const char *subr_string, int subr_string_length,
923                                        const char *np, int np_length);
924
925 static cairo_status_t
926 cairo_type1_font_for_each_subr (cairo_type1_font_subset_t  *font,
927                                 const char                 *array_start,
928                                 const char                 *cleartext_end,
929                                 subr_func_t                 func,
930                                 const char                **array_end)
931 {
932     const char *p, *subr_string;
933     char *end;
934     int subr_num, subr_length;
935     const char *np;
936     int np_length;
937     cairo_status_t status;
938
939     /* We're looking at "dup" at the start of the first subroutine. The subroutines
940      * definitions are on the form:
941      *
942      *   dup 5 23 RD <23 binary bytes> NP
943      *
944      * or alternatively using -| and |- instead of RD and ND.
945      * The first number is the subroutine number.
946      */
947
948     p = array_start;
949     while (p + 3 < cleartext_end && strncmp (p, "dup", 3) == 0) {
950         p = skip_token (p, cleartext_end);
951
952         /* get subr number */
953         subr_num = strtol (p, &end, 10);
954         if (p == end)
955             return CAIRO_INT_STATUS_UNSUPPORTED;
956
957         if (subr_num < 0 || subr_num >= font->num_subrs)
958             return CAIRO_INT_STATUS_UNSUPPORTED;
959
960         /* get subr length */
961         p = end;
962         subr_length = strtol (p, &end, 10);
963         if (p == end)
964             return CAIRO_INT_STATUS_UNSUPPORTED;
965
966         /* Skip past -| or RD to binary data.  There is exactly one space
967          * between the -| or RD token and the encrypted data, thus '+ 1'. */
968         subr_string = skip_token (end, cleartext_end) + 1;
969
970         np = NULL;
971         np_length = 0;
972
973         /* Skip binary data and | or NP token. */
974         p = skip_token (subr_string + subr_length, cleartext_end);
975         while (p < cleartext_end && _cairo_isspace(*p))
976             p++;
977
978         /* Some fonts have "noaccess put" instead of "NP" */
979         if (p + 3 < cleartext_end && strncmp (p, "put", 3) == 0) {
980             p = skip_token (p, cleartext_end);
981             while (p < cleartext_end && _cairo_isspace(*p))
982                 p++;
983
984             np = subr_string + subr_length;
985             np_length = p - np;
986         }
987
988         status = func (font, subr_num,
989                        subr_string, subr_length, np, np_length);
990         if (unlikely (status))
991             return status;
992
993     }
994
995     *array_end = (char *) p;
996
997     return CAIRO_STATUS_SUCCESS;
998 }
999
1000 static cairo_status_t
1001 cairo_type1_font_subset_build_glyph_list (cairo_type1_font_subset_t *font,
1002                                           int glyph_number,
1003                                           const char *name, int name_length,
1004                                           const char *encrypted_charstring, int encrypted_charstring_length)
1005 {
1006     char *s;
1007     glyph_data_t glyph;
1008     cairo_status_t status;
1009
1010     s = malloc (name_length + 1);
1011     if (unlikely (s == NULL))
1012         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1013
1014     strncpy (s, name, name_length);
1015     s[name_length] = 0;
1016
1017     status = _cairo_array_append (&font->glyph_names_array, &s);
1018     if (unlikely (status))
1019         return status;
1020
1021     glyph.subset_index = -1;
1022     glyph.width = 0;
1023     glyph.encrypted_charstring = encrypted_charstring;
1024     glyph.encrypted_charstring_length = encrypted_charstring_length;
1025     status = _cairo_array_append (&font->glyphs_array, &glyph);
1026
1027     return status;
1028 }
1029
1030 static cairo_status_t
1031 write_used_glyphs (cairo_type1_font_subset_t *font,
1032                    int glyph_number,
1033                    const char *name, int name_length,
1034                    const char *charstring, int charstring_length)
1035 {
1036     cairo_status_t status;
1037     char buffer[256];
1038     int length;
1039
1040     if (font->glyphs[glyph_number].subset_index < 0)
1041         return CAIRO_STATUS_SUCCESS;
1042
1043     length = snprintf (buffer, sizeof buffer,
1044                        "/%.*s %d %s ",
1045                        name_length, name, charstring_length, font->rd);
1046     status = cairo_type1_font_subset_write_encrypted (font, buffer, length);
1047     if (unlikely (status))
1048         return status;
1049
1050     status = cairo_type1_font_subset_write_encrypted (font,
1051                                                       charstring,
1052                                                       charstring_length);
1053     if (unlikely (status))
1054         return status;
1055
1056     length = snprintf (buffer, sizeof buffer, "%s\n", font->nd);
1057     status = cairo_type1_font_subset_write_encrypted (font, buffer, length);
1058     if (unlikely (status))
1059         return status;
1060
1061     return CAIRO_STATUS_SUCCESS;
1062 }
1063
1064 typedef cairo_status_t (*glyph_func_t) (cairo_type1_font_subset_t *font,
1065                                         int glyph_number,
1066                                         const char *name, int name_length,
1067                                         const char *charstring, int charstring_length);
1068
1069 static cairo_status_t
1070 cairo_type1_font_subset_for_each_glyph (cairo_type1_font_subset_t *font,
1071                                         const char *dict_start,
1072                                         const char *dict_end,
1073                                         glyph_func_t func,
1074                                         const char **dict_out)
1075 {
1076     int charstring_length, name_length;
1077     const char *p, *charstring, *name;
1078     char *end;
1079     cairo_status_t status;
1080     int glyph_count;
1081
1082     /* We're looking at '/' in the name of the first glyph.  The glyph
1083      * definitions are on the form:
1084      *
1085      *   /name 23 RD <23 binary bytes> ND
1086      *
1087      * or alternatively using -| and |- instead of RD and ND.
1088      *
1089      * We parse the glyph name and see if it is in the subset.  If it
1090      * is, we call the specified callback with the glyph name and
1091      * glyph data, otherwise we just skip it.  We need to parse
1092      * through a glyph definition; we can't just find the next '/',
1093      * since the binary data could contain a '/'.
1094      */
1095
1096     p = dict_start;
1097     glyph_count = 0;
1098     while (*p == '/') {
1099         name = p + 1;
1100         p = skip_token (p, dict_end);
1101         name_length = p - name;
1102
1103         charstring_length = strtol (p, &end, 10);
1104         if (p == end)
1105             return CAIRO_INT_STATUS_UNSUPPORTED;
1106
1107         /* Skip past -| or RD to binary data.  There is exactly one space
1108          * between the -| or RD token and the encrypted data, thus '+ 1'. */
1109         charstring = skip_token (end, dict_end) + 1;
1110
1111         /* Skip binary data and |- or ND token. */
1112         p = skip_token (charstring + charstring_length, dict_end);
1113         while (p < dict_end && _cairo_isspace(*p))
1114             p++;
1115
1116         /* In case any of the skip_token() calls above reached EOF, p will
1117          * be equal to dict_end. */
1118         if (p == dict_end)
1119             return CAIRO_INT_STATUS_UNSUPPORTED;
1120
1121         status = func (font, glyph_count++,
1122                        name, name_length,
1123                        charstring, charstring_length);
1124         if (unlikely (status))
1125             return status;
1126     }
1127
1128     *dict_out = p;
1129
1130     return CAIRO_STATUS_SUCCESS;
1131 }
1132
1133
1134 static cairo_status_t
1135 cairo_type1_font_subset_write_private_dict (cairo_type1_font_subset_t *font,
1136                                             const char                *name)
1137 {
1138     cairo_status_t status;
1139     const char *p, *subrs, *charstrings, *array_start, *array_end, *dict_start, *dict_end;
1140     const char *closefile_token;
1141     char buffer[32], *subr_count_end, *glyph_count_end;
1142     int length;
1143     const cairo_scaled_font_backend_t *backend;
1144     unsigned int i;
1145     int glyph, j;
1146
1147     /* The private dict holds hint information, common subroutines and
1148      * the actual glyph definitions (charstrings).
1149      *
1150      * What we do here is scan directly to the /Subrs token, which
1151      * marks the beginning of the subroutines. We then read in all the
1152      * subroutines then move on to the /CharString token, which marks
1153      * the beginning of the glyph definitions, and read in the chastrings.
1154      *
1155      * The charstrings are parsed to extracts glyph widths, work out
1156      * which subroutines are called, and too see if any extra glyphs
1157      * need to be included due to the use of the seac glyph combining
1158      * operator.
1159      *
1160      * Finally the private dict is copied to the subset font minus the
1161      * subroutines and charstrings not required.
1162      */
1163
1164     /* Find start of Subrs */
1165     subrs = find_token (font->cleartext, font->cleartext_end, "/Subrs");
1166     if (subrs == NULL) {
1167         font->subset_subrs = FALSE;
1168         p = font->cleartext;
1169         goto skip_subrs;
1170     }
1171
1172     /* Scan past /Subrs and get the array size. */
1173     p = subrs + strlen ("/Subrs");
1174     font->num_subrs = strtol (p, &subr_count_end, 10);
1175     if (subr_count_end == p)
1176         return CAIRO_INT_STATUS_UNSUPPORTED;
1177
1178     if (font->num_subrs <= 0)
1179         return CAIRO_INT_STATUS_UNSUPPORTED;
1180
1181     font->subrs = calloc (font->num_subrs, sizeof (font->subrs[0]));
1182     if (unlikely (font->subrs == NULL))
1183         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1184
1185     /* look for "dup" which marks the beginning of the first subr */
1186     array_start = find_token (subr_count_end, font->cleartext_end, "dup");
1187     if (subrs == NULL)
1188         return CAIRO_INT_STATUS_UNSUPPORTED;
1189
1190     /* Read in the subroutines */
1191     status = cairo_type1_font_for_each_subr (font,
1192                                              array_start,
1193                                              font->cleartext_end,
1194                                              cairo_type1_font_subset_build_subr_list,
1195                                              &array_end);
1196     if (unlikely(status))
1197         return status;
1198
1199     p = array_end;
1200 skip_subrs:
1201
1202     /* Find start of CharStrings */
1203     charstrings = find_token (p, font->cleartext_end, "/CharStrings");
1204     if (charstrings == NULL)
1205         return CAIRO_INT_STATUS_UNSUPPORTED;
1206
1207     /* Scan past /CharStrings and the integer following it. */
1208     p = charstrings + strlen ("/CharStrings");
1209     strtol (p, &glyph_count_end, 10);
1210     if (p == glyph_count_end)
1211         return CAIRO_INT_STATUS_UNSUPPORTED;
1212
1213     /* Look for a '/' which marks the beginning of the first glyph
1214      * definition. */
1215     for (p = glyph_count_end; p < font->cleartext_end; p++)
1216         if (*p == '/')
1217             break;
1218     if (p == font->cleartext_end)
1219         return CAIRO_INT_STATUS_UNSUPPORTED;
1220     dict_start = p;
1221
1222     /* Now that we have the private dictionary broken down in
1223      * sections, do the first pass through the glyph definitions to
1224      * build a list of glyph names and charstrings. */
1225     status = cairo_type1_font_subset_for_each_glyph (font,
1226                                                      dict_start,
1227                                                      font->cleartext_end,
1228                                                      cairo_type1_font_subset_build_glyph_list,
1229                                                      &dict_end);
1230     if (unlikely(status))
1231         return status;
1232
1233     font->glyphs = _cairo_array_index (&font->glyphs_array, 0);
1234     font->glyph_names = _cairo_array_index (&font->glyph_names_array, 0);
1235     font->base.num_glyphs = _cairo_array_num_elements (&font->glyphs_array);
1236     font->subset_index_to_glyphs = calloc (font->base.num_glyphs, sizeof font->subset_index_to_glyphs[0]);
1237     if (unlikely (font->subset_index_to_glyphs == NULL))
1238         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1239
1240     backend = font->scaled_font_subset->scaled_font->backend;
1241     if (!backend->index_to_glyph_name)
1242         return CAIRO_INT_STATUS_UNSUPPORTED;
1243
1244     /* Find the glyph number corresponding to each glyph in the subset
1245      * and mark it as in use */
1246
1247     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
1248         unsigned long index;
1249
1250         status = backend->index_to_glyph_name (font->scaled_font_subset->scaled_font,
1251                                                font->glyph_names,
1252                                                font->base.num_glyphs,
1253                                                font->scaled_font_subset->glyphs[i],
1254                                                &index);
1255         if (unlikely(status))
1256             return status;
1257
1258         cairo_type1_font_subset_use_glyph (font, index);
1259     }
1260
1261     /* Go through the charstring of each glyph in use, get the glyph
1262      * width and figure out which extra glyphs may be required by the
1263      * seac operator (which may cause font->num_glyphs to increase
1264      * while this loop is executing). Also subset the Subrs. */
1265     for (j = 0; j < font->num_glyphs; j++) {
1266         glyph = font->subset_index_to_glyphs[j];
1267         font->build_stack.sp = 0;
1268         font->ps_stack.num_other_subr_args = 0;
1269         status = cairo_type1_font_subset_parse_charstring (font,
1270                                                            glyph,
1271                                                            font->glyphs[glyph].encrypted_charstring,
1272                                                            font->glyphs[glyph].encrypted_charstring_length);
1273         if (unlikely (status))
1274             return status;
1275     }
1276
1277     closefile_token = find_token (dict_end, font->cleartext_end, "closefile");
1278     if (closefile_token == NULL)
1279         return CAIRO_INT_STATUS_UNSUPPORTED;
1280
1281     /* We're ready to start outputting. First write the header,
1282      * i.e. the public part of the font dict.*/
1283     status = cairo_type1_font_subset_write_header (font, name);
1284     if (unlikely (status))
1285         return status;
1286
1287     font->base.header_size = _cairo_output_stream_get_position (font->output);
1288
1289     /* Start outputting the private dict */
1290     if (font->subset_subrs) {
1291         /* First output everything up to the start of the Subrs array. */
1292         status = cairo_type1_font_subset_write_encrypted (font, font->cleartext,
1293                                                           array_start - font->cleartext);
1294         if (unlikely (status))
1295             return status;
1296
1297         /* Write out the subr definitions for each of the glyphs in
1298          * the subset. */
1299         status = cairo_type1_font_for_each_subr (font,
1300                                                  array_start,
1301                                                  font->cleartext_end,
1302                                                  write_used_subrs,
1303                                                  &p);
1304         if (unlikely (status))
1305             return status;
1306     } else {
1307         p = font->cleartext;
1308     }
1309
1310     /* If subr subsetting, output everything from end of subrs to
1311      * start of /CharStrings token.  If not subr subsetting, output
1312      * everything start of private dict to start of /CharStrings
1313      * token. */
1314     status = cairo_type1_font_subset_write_encrypted (font, p, charstrings - p);
1315     if (unlikely (status))
1316         return status;
1317
1318     /* Write out new charstring count */
1319     length = snprintf (buffer, sizeof buffer,
1320                        "/CharStrings %d", font->num_glyphs);
1321     status = cairo_type1_font_subset_write_encrypted (font, buffer, length);
1322     if (unlikely (status))
1323         return status;
1324
1325     /* Write out text between the charstring count and the first
1326      * charstring definition */
1327     status = cairo_type1_font_subset_write_encrypted (font, glyph_count_end,
1328                                                   dict_start - glyph_count_end);
1329     if (unlikely (status))
1330         return status;
1331
1332     /* Write out the charstring definitions for each of the glyphs in
1333      * the subset. */
1334     status = cairo_type1_font_subset_for_each_glyph (font,
1335                                                      dict_start,
1336                                                      font->cleartext_end,
1337                                                      write_used_glyphs,
1338                                                      &p);
1339     if (unlikely (status))
1340         return status;
1341
1342     /* Output what's left between the end of the glyph definitions and
1343      * the end of the private dict to the output. */
1344     status = cairo_type1_font_subset_write_encrypted (font, p,
1345                                 closefile_token - p + strlen ("closefile") + 1);
1346     if (unlikely (status))
1347         return status;
1348
1349     if (font->hex_encode)
1350         _cairo_output_stream_write (font->output, "\n", 1);
1351
1352     return CAIRO_STATUS_SUCCESS;
1353 }
1354
1355 static cairo_status_t
1356 cairo_type1_font_subset_write_trailer(cairo_type1_font_subset_t *font)
1357 {
1358     const char *cleartomark_token;
1359     int i;
1360     static const char zeros[65] =
1361         "0000000000000000000000000000000000000000000000000000000000000000\n";
1362
1363
1364     for (i = 0; i < 8; i++)
1365         _cairo_output_stream_write (font->output, zeros, sizeof zeros);
1366
1367     cleartomark_token = find_token (font->type1_data, font->type1_end, "cleartomark");
1368     if (cleartomark_token) {
1369         /* Some fonts have conditional save/restore around the entire
1370          * font dict, so we need to retain whatever postscript code
1371          * that may come after 'cleartomark'. */
1372
1373         _cairo_output_stream_write (font->output, cleartomark_token,
1374                                     font->type1_end - cleartomark_token);
1375         if (*(font->type1_end - 1) != '\n')
1376             _cairo_output_stream_printf (font->output, "\n");
1377
1378     } else if (!font->eexec_segment_is_ascii) {
1379         /* Fonts embedded in PDF may omit the fixed-content portion
1380          * that includes the 'cleartomark' operator. Type 1 in PDF is
1381          * always binary. */
1382
1383         _cairo_output_stream_printf (font->output, "cleartomark\n");
1384     } else {
1385         return CAIRO_INT_STATUS_UNSUPPORTED;
1386     }
1387
1388     /* some fonts do not have a newline at the end of the last line */
1389     _cairo_output_stream_printf (font->output, "\n");
1390
1391     return CAIRO_STATUS_SUCCESS;
1392 }
1393
1394 static cairo_status_t
1395 type1_font_write (void *closure, const unsigned char *data, unsigned int length)
1396 {
1397     cairo_type1_font_subset_t *font = closure;
1398
1399     return _cairo_array_append_multiple (&font->contents, data, length);
1400 }
1401
1402 static cairo_status_t
1403 cairo_type1_font_subset_write (cairo_type1_font_subset_t *font,
1404                                const char *name)
1405 {
1406     cairo_status_t status;
1407
1408     status = cairo_type1_font_subset_find_segments (font);
1409     if (unlikely (status))
1410         return status;
1411
1412     status = cairo_type1_font_subset_decrypt_eexec_segment (font);
1413     if (unlikely (status))
1414         return status;
1415
1416     /* Determine which glyph definition delimiters to use. */
1417     if (find_token (font->cleartext, font->cleartext_end, "/-|") != NULL) {
1418         font->rd = "-|";
1419         font->nd = "|-";
1420         font->np = "|";
1421     } else if (find_token (font->cleartext, font->cleartext_end, "/RD") != NULL) {
1422         font->rd = "RD";
1423         font->nd = "ND";
1424         font->np = "NP";
1425     } else {
1426         /* Don't know *what* kind of font this is... */
1427         return CAIRO_INT_STATUS_UNSUPPORTED;
1428     }
1429
1430     font->eexec_key = CAIRO_TYPE1_PRIVATE_DICT_KEY;
1431     font->hex_column = 0;
1432
1433     status = cairo_type1_font_subset_get_bbox (font);
1434     if (unlikely (status))
1435         return status;
1436
1437     status = cairo_type1_font_subset_get_fontname (font);
1438     if (unlikely (status))
1439         return status;
1440
1441     status = cairo_type1_font_subset_write_private_dict (font, name);
1442     if (unlikely (status))
1443         return status;
1444
1445     font->base.data_size = _cairo_output_stream_get_position (font->output) -
1446         font->base.header_size;
1447
1448     status = cairo_type1_font_subset_write_trailer (font);
1449     if (unlikely (status))
1450         return status;
1451
1452     font->base.trailer_size =
1453         _cairo_output_stream_get_position (font->output) -
1454         font->base.header_size - font->base.data_size;
1455
1456     return CAIRO_STATUS_SUCCESS;
1457 }
1458
1459 static cairo_bool_t
1460 check_fontdata_is_type1 (const unsigned char *data, long length)
1461 {
1462     /* Test for  Type 1 Binary (PFB) */
1463     if (length > 2 && data[0] == 0x80 && data[1] == 0x01)
1464         return TRUE;
1465
1466     /* Test for Type 1 1 ASCII (PFA) */
1467     if (length > 2 && data[0] == '%' && data[1] == '!')
1468         return TRUE;
1469
1470     return FALSE;
1471 }
1472
1473 static cairo_status_t
1474 cairo_type1_font_subset_generate (void       *abstract_font,
1475                                   const char *name)
1476
1477 {
1478     cairo_type1_font_subset_t *font = abstract_font;
1479     cairo_scaled_font_t *scaled_font;
1480     cairo_status_t status;
1481     unsigned long data_length;
1482
1483     scaled_font = font->scaled_font_subset->scaled_font;
1484     if (!scaled_font->backend->load_type1_data)
1485         return CAIRO_INT_STATUS_UNSUPPORTED;
1486
1487     status = scaled_font->backend->load_type1_data (scaled_font, 0, NULL, &data_length);
1488     if (status)
1489         return CAIRO_INT_STATUS_UNSUPPORTED;
1490
1491     font->type1_length = data_length;
1492     font->type1_data = malloc (font->type1_length);
1493     if (unlikely (font->type1_data == NULL))
1494         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1495
1496     status = scaled_font->backend->load_type1_data (scaled_font, 0,
1497                                                     (unsigned char *) font->type1_data,
1498                                                     &data_length);
1499     if (unlikely (status))
1500         return status;
1501
1502     if (!check_fontdata_is_type1 ((unsigned char *)font->type1_data, data_length))
1503         return CAIRO_INT_STATUS_UNSUPPORTED;
1504
1505     status = _cairo_array_grow_by (&font->contents, 4096);
1506     if (unlikely (status))
1507         return status;
1508
1509     font->output = _cairo_output_stream_create (type1_font_write, NULL, font);
1510     if (unlikely ((status = font->output->status)))
1511         return status;
1512
1513     status = cairo_type1_font_subset_write (font, name);
1514     if (unlikely (status))
1515         return status;
1516
1517     font->base.data = _cairo_array_index (&font->contents, 0);
1518
1519     return status;
1520 }
1521
1522 static cairo_status_t
1523 _cairo_type1_font_subset_fini (cairo_type1_font_subset_t *font)
1524 {
1525     cairo_status_t status = CAIRO_STATUS_SUCCESS;
1526     unsigned int i;
1527
1528     /* If the subset generation failed, some of the pointers below may
1529      * be NULL depending on at which point the error occurred. */
1530
1531     _cairo_array_fini (&font->contents);
1532
1533     free (font->type1_data);
1534     for (i = 0; i < _cairo_array_num_elements (&font->glyph_names_array); i++) {
1535         char **s;
1536
1537         s = _cairo_array_index (&font->glyph_names_array, i);
1538         free (*s);
1539     }
1540     _cairo_array_fini (&font->glyph_names_array);
1541     _cairo_array_fini (&font->glyphs_array);
1542
1543     free (font->subrs);
1544
1545     if (font->output != NULL)
1546         status = _cairo_output_stream_destroy (font->output);
1547
1548     free (font->base.base_font);
1549
1550     free (font->subset_index_to_glyphs);
1551
1552     return status;
1553 }
1554
1555 cairo_status_t
1556 _cairo_type1_subset_init (cairo_type1_subset_t          *type1_subset,
1557                           const char                    *name,
1558                           cairo_scaled_font_subset_t    *scaled_font_subset,
1559                           cairo_bool_t                   hex_encode)
1560 {
1561     cairo_type1_font_subset_t font;
1562     cairo_status_t status;
1563     unsigned long length;
1564     unsigned int i;
1565     char buf[30];
1566
1567     /* We need to use a fallback font generated from the synthesized outlines. */
1568     if (scaled_font_subset->scaled_font->backend->is_synthetic &&
1569         scaled_font_subset->scaled_font->backend->is_synthetic (scaled_font_subset->scaled_font))
1570         return CAIRO_INT_STATUS_UNSUPPORTED;
1571
1572     status = _cairo_type1_font_subset_init (&font, scaled_font_subset, hex_encode);
1573     if (unlikely (status))
1574         return status;
1575
1576     status = cairo_type1_font_subset_generate (&font, name);
1577     if (unlikely (status))
1578         goto fail1;
1579
1580     if (font.base.base_font) {
1581         type1_subset->base_font = strdup (font.base.base_font);
1582     } else {
1583         snprintf(buf, sizeof (buf), "CairoFont-%u-%u",
1584                  scaled_font_subset->font_id, scaled_font_subset->subset_id);
1585         type1_subset->base_font = strdup (buf);
1586     }
1587     if (unlikely (type1_subset->base_font == NULL))
1588         goto fail1;
1589
1590     type1_subset->widths = calloc (sizeof (double), font.num_glyphs);
1591     if (unlikely (type1_subset->widths == NULL))
1592         goto fail2;
1593     for (i = 0; i < font.base.num_glyphs; i++) {
1594         if (font.glyphs[i].subset_index < 0)
1595             continue;
1596         type1_subset->widths[font.glyphs[i].subset_index] =
1597             font.glyphs[i].width;
1598     }
1599
1600     type1_subset->x_min = font.base.x_min;
1601     type1_subset->y_min = font.base.y_min;
1602     type1_subset->x_max = font.base.x_max;
1603     type1_subset->y_max = font.base.y_max;
1604     type1_subset->ascent = font.base.ascent;
1605     type1_subset->descent = font.base.descent;
1606
1607     length = font.base.header_size +
1608              font.base.data_size +
1609              font.base.trailer_size;
1610     type1_subset->data = malloc (length);
1611     if (unlikely (type1_subset->data == NULL))
1612         goto fail3;
1613
1614     memcpy (type1_subset->data,
1615             _cairo_array_index (&font.contents, 0), length);
1616
1617     type1_subset->header_length = font.base.header_size;
1618     type1_subset->data_length = font.base.data_size;
1619     type1_subset->trailer_length = font.base.trailer_size;
1620
1621     return _cairo_type1_font_subset_fini (&font);
1622
1623  fail3:
1624     free (type1_subset->widths);
1625  fail2:
1626     free (type1_subset->base_font);
1627  fail1:
1628     _cairo_type1_font_subset_fini (&font);
1629
1630     return status;
1631 }
1632
1633 void
1634 _cairo_type1_subset_fini (cairo_type1_subset_t *subset)
1635 {
1636     free (subset->base_font);
1637     free (subset->widths);
1638     free (subset->data);
1639 }
1640
1641 cairo_bool_t
1642 _cairo_type1_scaled_font_is_type1 (cairo_scaled_font_t *scaled_font)
1643 {
1644     cairo_status_t status;
1645     unsigned long length;
1646     unsigned char buf[64];
1647
1648     if (!scaled_font->backend->load_type1_data)
1649         return FALSE;
1650
1651     status = scaled_font->backend->load_type1_data (scaled_font, 0, NULL, &length);
1652     if (status)
1653         return FALSE;
1654
1655     /* We only need a few bytes to test for Type 1 */
1656     if (length > sizeof (buf))
1657         length = sizeof (buf);
1658
1659     status = scaled_font->backend->load_type1_data (scaled_font, 0, buf, &length);
1660     if (status)
1661         return FALSE;
1662
1663     return check_fontdata_is_type1 (buf, length);
1664 }
1665
1666 #endif /* CAIRO_HAS_FONT_SUBSET */