update for HEAD-2003050101
[reactos.git] / lib / freetype / src / cff / cffparse.c
1 /***************************************************************************/
2 /*                                                                         */
3 /*  cffparse.c                                                             */
4 /*                                                                         */
5 /*    CFF token stream parser (body)                                       */
6 /*                                                                         */
7 /*  Copyright 1996-2001, 2002 by                                           */
8 /*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
9 /*                                                                         */
10 /*  This file is part of the FreeType project, and may only be used,       */
11 /*  modified, and distributed under the terms of the FreeType project      */
12 /*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
13 /*  this file you indicate that you have read the license and              */
14 /*  understand and accept it fully.                                        */
15 /*                                                                         */
16 /***************************************************************************/
17
18
19 #include <ft2build.h>
20 #include "cffparse.h"
21 #include FT_INTERNAL_STREAM_H
22
23 #include "cfferrs.h"
24
25
26   /*************************************************************************/
27   /*                                                                       */
28   /* The macro FT_COMPONENT is used in trace mode.  It is an implicit      */
29   /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log  */
30   /* messages during execution.                                            */
31   /*                                                                       */
32 #undef  FT_COMPONENT
33 #define FT_COMPONENT  trace_cffparse
34
35
36   enum
37   {
38     cff_kind_none = 0,
39     cff_kind_num,
40     cff_kind_fixed,
41     cff_kind_string,
42     cff_kind_bool,
43     cff_kind_delta,
44     cff_kind_callback,
45
46     cff_kind_max  /* do not remove */
47   };
48
49
50   /* now generate handlers for the most simple fields */
51   typedef FT_Error  (*CFF_Field_Reader)( CFF_Parser  parser );
52
53   typedef struct  CFF_Field_Handler_
54   {
55     int               kind;
56     int               code;
57     FT_UInt           offset;
58     FT_Byte           size;
59     CFF_Field_Reader  reader;
60     FT_UInt           array_max;
61     FT_UInt           count_offset;
62
63   } CFF_Field_Handler;
64
65
66   FT_LOCAL_DEF( void )
67   cff_parser_init( CFF_Parser  parser,
68                    FT_UInt     code,
69                    void*       object )
70   {
71     FT_MEM_ZERO( parser, sizeof ( *parser ) );
72
73     parser->top         = parser->stack;
74     parser->object_code = code;
75     parser->object      = object;
76   }
77
78
79   /* read an integer */
80   static FT_Long
81   cff_parse_integer( FT_Byte*  start,
82                      FT_Byte*  limit )
83   {
84     FT_Byte*  p   = start;
85     FT_Int    v   = *p++;
86     FT_Long   val = 0;
87
88
89     if ( v == 28 )
90     {
91       if ( p + 2 > limit )
92         goto Bad;
93
94       val = (FT_Short)( ( (FT_Int)p[0] << 8 ) | p[1] );
95       p  += 2;
96     }
97     else if ( v == 29 )
98     {
99       if ( p + 4 > limit )
100         goto Bad;
101
102       val = ( (FT_Long)p[0] << 24 ) |
103             ( (FT_Long)p[1] << 16 ) |
104             ( (FT_Long)p[2] <<  8 ) |
105                        p[3];
106       p += 4;
107     }
108     else if ( v < 247 )
109     {
110       val = v - 139;
111     }
112     else if ( v < 251 )
113     {
114       if ( p + 1 > limit )
115         goto Bad;
116
117       val = ( v - 247 ) * 256 + p[0] + 108;
118       p++;
119     }
120     else
121     {
122       if ( p + 1 > limit )
123         goto Bad;
124
125       val = -( v - 251 ) * 256 - p[0] - 108;
126       p++;
127     }
128
129   Exit:
130     return val;
131
132   Bad:
133     val = 0;
134     goto Exit;
135   }
136
137
138   /* read a real */
139   static FT_Fixed
140   cff_parse_real( FT_Byte*  start,
141                   FT_Byte*  limit,
142                   FT_Int    power_ten )
143   {
144     FT_Byte*  p    = start;
145     FT_Long   num, divider, result, exp;
146     FT_Int    sign = 0, exp_sign = 0;
147     FT_UInt   nib;
148     FT_UInt   phase;
149
150
151     result  = 0;
152     num     = 0;
153     divider = 1;
154
155     /* first of all, read the integer part */
156     phase = 4;
157
158     for (;;)
159     {
160       /* If we entered this iteration with phase == 4, we need to */
161       /* read a new byte.  This also skips past the intial 0x1E.  */
162       if ( phase )
163       {
164         p++;
165
166         /* Make sure we don't read past the end. */
167         if ( p >= limit )
168           goto Bad;
169       }
170
171       /* Get the nibble. */
172       nib   = ( p[0] >> phase ) & 0xF;
173       phase = 4 - phase;
174
175       if ( nib == 0xE )
176         sign = 1;
177       else if ( nib > 9 )
178         break;
179       else
180         result = result * 10 + nib;
181     }
182
183     /* read decimal part, if any */
184     if ( nib == 0xa )
185       for (;;)
186       {
187         /* If we entered this iteration with phase == 4, we need */
188         /* to read a new byte.                                   */
189         if ( phase )
190         {
191           p++;
192
193           /* Make sure we don't read past the end. */
194           if ( p >= limit )
195             goto Bad;
196         }
197
198         /* Get the nibble. */
199         nib   = ( p[0] >> phase ) & 0xF;
200         phase = 4 - phase;
201         if ( nib >= 10 )
202           break;
203
204         if ( divider < 10000000L )
205         {
206           num      = num * 10 + nib;
207           divider *= 10;
208         }
209       }
210
211     /* read exponent, if any */
212     if ( nib == 12 )
213     {
214       exp_sign = 1;
215       nib      = 11;
216     }
217
218     if ( nib == 11 )
219     {
220       exp = 0;
221
222       for (;;)
223       {
224         /* If we entered this iteration with phase == 4, we need */
225         /* to read a new byte.                                   */
226         if ( phase )
227         {
228           p++;
229
230           /* Make sure we don't read past the end. */
231           if ( p >= limit )
232             goto Bad;
233         }
234
235         /* Get the nibble. */
236         nib   = ( p[0] >> phase ) & 0xF;
237         phase = 4 - phase;
238         if ( nib >= 10 )
239           break;
240
241         exp = exp * 10 + nib;
242       }
243
244       if ( exp_sign )
245         exp = -exp;
246
247       power_ten += (FT_Int)exp;
248     }
249
250     /* raise to power of ten if needed */
251     while ( power_ten > 0 )
252     {
253       result = result * 10;
254       num    = num * 10;
255
256       power_ten--;
257     }
258
259     while ( power_ten < 0 )
260     {
261       result  = result / 10;
262       divider = divider * 10;
263
264       power_ten++;
265     }
266
267     /* Move the integer part into the high 16 bits. */
268     result <<= 16;
269
270     /* Place the decimal part into the low 16 bits. */
271     if ( num )
272       result |= FT_DivFix( num, divider );
273
274     if ( sign )
275       result = -result;
276
277   Exit:
278     return result;
279
280   Bad:
281     result = 0;
282     goto Exit;
283   }
284
285
286   /* read a number, either integer or real */
287   static FT_Long
288   cff_parse_num( FT_Byte**  d )
289   {
290     return ( **d == 30 ? ( cff_parse_real   ( d[0], d[1], 0 ) >> 16 )
291                        :   cff_parse_integer( d[0], d[1] ) );
292   }
293
294
295   /* read a floating point number, either integer or real */
296   static FT_Fixed
297   cff_parse_fixed( FT_Byte**  d )
298   {
299     return ( **d == 30 ? cff_parse_real   ( d[0], d[1], 0 )
300                        : cff_parse_integer( d[0], d[1] ) << 16 );
301   }
302
303   /* read a floating point number, either integer or real, */
304   /* but return 1000 times the number read in.             */
305   static FT_Fixed
306   cff_parse_fixed_thousand( FT_Byte**  d )
307   {
308     return **d ==
309       30 ? cff_parse_real     ( d[0], d[1], 3 )
310          : (FT_Fixed)FT_MulFix( cff_parse_integer( d[0], d[1] ) << 16, 1000 );
311   }
312
313   static FT_Error
314   cff_parse_font_matrix( CFF_Parser  parser )
315   {
316     CFF_FontRecDict  dict   = (CFF_FontRecDict)parser->object;
317     FT_Matrix*       matrix = &dict->font_matrix;
318     FT_Vector*       offset = &dict->font_offset;
319     FT_UShort*       upm    = &dict->units_per_em;
320     FT_Byte**        data   = parser->stack;
321     FT_Error         error;
322     FT_Fixed         temp;
323
324
325     error = CFF_Err_Stack_Underflow;
326
327     if ( parser->top >= parser->stack + 6 )
328     {
329       matrix->xx = cff_parse_fixed_thousand( data++ );
330       matrix->yx = cff_parse_fixed_thousand( data++ );
331       matrix->xy = cff_parse_fixed_thousand( data++ );
332       matrix->yy = cff_parse_fixed_thousand( data++ );
333       offset->x  = cff_parse_fixed_thousand( data++ );
334       offset->y  = cff_parse_fixed_thousand( data   );
335
336       temp = ABS( matrix->yy );
337
338       *upm = (FT_UShort)FT_DivFix( 0x10000L, FT_DivFix( temp, 1000 ) );
339
340       if ( temp != 0x10000L )
341       {
342         matrix->xx = FT_DivFix( matrix->xx, temp );
343         matrix->yx = FT_DivFix( matrix->yx, temp );
344         matrix->xy = FT_DivFix( matrix->xy, temp );
345         matrix->yy = FT_DivFix( matrix->yy, temp );
346         offset->x  = FT_DivFix( offset->x,  temp );
347         offset->y  = FT_DivFix( offset->y,  temp );
348       }
349
350       /* note that the offsets must be expressed in integer font units */
351       offset->x >>= 16;
352       offset->y >>= 16;
353
354       error = CFF_Err_Ok;
355     }
356
357     return error;
358   }
359
360
361   static FT_Error
362   cff_parse_font_bbox( CFF_Parser  parser )
363   {
364     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
365     FT_BBox*         bbox = &dict->font_bbox;
366     FT_Byte**        data = parser->stack;
367     FT_Error         error;
368
369
370     error = CFF_Err_Stack_Underflow;
371
372     if ( parser->top >= parser->stack + 4 )
373     {
374       bbox->xMin = FT_RoundFix( cff_parse_fixed( data++ ) );
375       bbox->yMin = FT_RoundFix( cff_parse_fixed( data++ ) );
376       bbox->xMax = FT_RoundFix( cff_parse_fixed( data++ ) );
377       bbox->yMax = FT_RoundFix( cff_parse_fixed( data   ) );
378       error = CFF_Err_Ok;
379     }
380
381     return error;
382   }
383
384
385   static FT_Error
386   cff_parse_private_dict( CFF_Parser  parser )
387   {
388     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
389     FT_Byte**        data = parser->stack;
390     FT_Error         error;
391
392
393     error = CFF_Err_Stack_Underflow;
394
395     if ( parser->top >= parser->stack + 2 )
396     {
397       dict->private_size   = cff_parse_num( data++ );
398       dict->private_offset = cff_parse_num( data   );
399       error = CFF_Err_Ok;
400     }
401
402     return error;
403   }
404
405
406   static FT_Error
407   cff_parse_cid_ros( CFF_Parser  parser )
408   {
409     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
410     FT_Byte**        data = parser->stack;
411     FT_Error         error;
412
413
414     error = CFF_Err_Stack_Underflow;
415
416     if ( parser->top >= parser->stack + 3 )
417     {
418       dict->cid_registry   = (FT_UInt)cff_parse_num ( data++ );
419       dict->cid_ordering   = (FT_UInt)cff_parse_num ( data++ );
420       dict->cid_supplement = (FT_ULong)cff_parse_num( data );
421       error = CFF_Err_Ok;
422     }
423
424     return error;
425   }
426
427
428 #define CFF_FIELD_NUM( code, name ) \
429           CFF_FIELD( code, name, cff_kind_num )
430 #define CFF_FIELD_FIXED( code, name ) \
431           CFF_FIELD( code, name, cff_kind_fixed )
432 #define CFF_FIELD_STRING( code, name ) \
433           CFF_FIELD( code, name, cff_kind_string )
434 #define CFF_FIELD_BOOL( code, name ) \
435           CFF_FIELD( code, name, cff_kind_bool )
436 #define CFF_FIELD_DELTA( code, name, max ) \
437           CFF_FIELD( code, name, cff_kind_delta )
438
439 #define CFF_FIELD_CALLBACK( code, name ) \
440           {                              \
441             cff_kind_callback,           \
442             code | CFFCODE,              \
443             0, 0,                        \
444             cff_parse_ ## name,          \
445             0, 0                         \
446           },
447
448 #undef  CFF_FIELD
449 #define CFF_FIELD( code, name, kind ) \
450           {                          \
451             kind,                    \
452             code | CFFCODE,          \
453             FT_FIELD_OFFSET( name ), \
454             FT_FIELD_SIZE( name ),   \
455             0, 0, 0                  \
456           },
457
458 #undef  CFF_FIELD_DELTA
459 #define CFF_FIELD_DELTA( code, name, max ) \
460         {                                  \
461           cff_kind_delta,                  \
462           code | CFFCODE,                  \
463           FT_FIELD_OFFSET( name ),         \
464           FT_FIELD_SIZE_DELTA( name ),     \
465           0,                               \
466           max,                             \
467           FT_FIELD_OFFSET( num_ ## name )  \
468         },
469
470 #define CFFCODE_TOPDICT  0x1000
471 #define CFFCODE_PRIVATE  0x2000
472
473   static const CFF_Field_Handler  cff_field_handlers[] =
474   {
475
476 #include "cfftoken.h"
477
478     { 0, 0, 0, 0, 0, 0, 0 }
479   };
480
481
482   FT_LOCAL_DEF( FT_Error )
483   cff_parser_run( CFF_Parser  parser,
484                   FT_Byte*    start,
485                   FT_Byte*    limit )
486   {
487     FT_Byte*  p     = start;
488     FT_Error  error = CFF_Err_Ok;
489
490
491     parser->top    = parser->stack;
492     parser->start  = start;
493     parser->limit  = limit;
494     parser->cursor = start;
495
496     while ( p < limit )
497     {
498       FT_UInt  v = *p;
499
500
501       if ( v >= 27 && v != 31 )
502       {
503         /* it's a number; we will push its position on the stack */
504         if ( parser->top - parser->stack >= CFF_MAX_STACK_DEPTH )
505           goto Stack_Overflow;
506
507         *parser->top ++ = p;
508
509         /* now, skip it */
510         if ( v == 30 )
511         {
512           /* skip real number */
513           p++;
514           for (;;)
515           {
516             if ( p >= limit )
517               goto Syntax_Error;
518             v = p[0] >> 4;
519             if ( v == 15 )
520               break;
521             v = p[0] & 0xF;
522             if ( v == 15 )
523               break;
524             p++;
525           }
526         }
527         else if ( v == 28 )
528           p += 2;
529         else if ( v == 29 )
530           p += 4;
531         else if ( v > 246 )
532           p += 1;
533       }
534       else
535       {
536         /* This is not a number, hence it's an operator.  Compute its code */
537         /* and look for it in our current list.                            */
538
539         FT_UInt                   code;
540         FT_UInt                   num_args = (FT_UInt)
541                                              ( parser->top - parser->stack );
542         const CFF_Field_Handler*  field;
543
544
545         *parser->top = p;
546         code = v;
547         if ( v == 12 )
548         {
549           /* two byte operator */
550           p++;
551           if ( p >= limit )
552             goto Syntax_Error;
553
554           code = 0x100 | p[0];
555         }
556         code = code | parser->object_code;
557
558         for ( field = cff_field_handlers; field->kind; field++ )
559         {
560           if ( field->code == (FT_Int)code )
561           {
562             /* we found our field's handler; read it */
563             FT_Long   val;
564             FT_Byte*  q = (FT_Byte*)parser->object + field->offset;
565
566
567             /* check that we have enough arguments -- except for */
568             /* delta encoded arrays, which can be empty          */
569             if ( field->kind != cff_kind_delta && num_args < 1 )
570               goto Stack_Underflow;
571
572             switch ( field->kind )
573             {
574             case cff_kind_bool:
575             case cff_kind_string:
576             case cff_kind_num:
577               val = cff_parse_num( parser->stack );
578               goto Store_Number;
579
580             case cff_kind_fixed:
581               val = cff_parse_fixed( parser->stack );
582
583             Store_Number:
584               switch ( field->size )
585               {
586               case 1:
587                 *(FT_Byte*)q = (FT_Byte)val;
588                 break;
589
590               case 2:
591                 *(FT_Short*)q = (FT_Short)val;
592                 break;
593
594               case 4:
595                 *(FT_Int32*)q = (FT_Int)val;
596                 break;
597
598               default:  /* for 64-bit systems where long is 8 bytes */
599                 *(FT_Long*)q = val;
600               }
601               break;
602
603             case cff_kind_delta:
604               {
605                 FT_Byte*   qcount = (FT_Byte*)parser->object +
606                                       field->count_offset;
607
608                 FT_Byte**  data = parser->stack;
609
610
611                 if ( num_args > field->array_max )
612                   num_args = field->array_max;
613
614                 /* store count */
615                 *qcount = (FT_Byte)num_args;
616
617                 val = 0;
618                 while ( num_args > 0 )
619                 {
620                   val += cff_parse_num( data++ );
621                   switch ( field->size )
622                   {
623                   case 1:
624                     *(FT_Byte*)q = (FT_Byte)val;
625                     break;
626
627                   case 2:
628                     *(FT_Short*)q = (FT_Short)val;
629                     break;
630
631                   case 4:
632                     *(FT_Int32*)q = (FT_Int)val;
633                     break;
634
635                   default:  /* for 64-bit systems */
636                     *(FT_Long*)q = val;
637                   }
638
639                   q += field->size;
640                   num_args--;
641                 }
642               }
643               break;
644
645             default:  /* callback */
646               error = field->reader( parser );
647               if ( error )
648                 goto Exit;
649             }
650             goto Found;
651           }
652         }
653
654         /* this is an unknown operator, or it is unsupported; */
655         /* we will ignore it for now.                         */
656
657       Found:
658         /* clear stack */
659         parser->top = parser->stack;
660       }
661       p++;
662     }
663
664   Exit:
665     return error;
666
667   Stack_Overflow:
668     error = CFF_Err_Invalid_Argument;
669     goto Exit;
670
671   Stack_Underflow:
672     error = CFF_Err_Invalid_Argument;
673     goto Exit;
674
675   Syntax_Error:
676     error = CFF_Err_Invalid_Argument;
677     goto Exit;
678   }
679
680
681 /* END */