• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /****************************************************************************
2  *
3  * ftobjs.c
4  *
5  *   The FreeType private base classes (body).
6  *
7  * Copyright (C) 1996-2020 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 <freetype/ftlist.h>
20 #include <freetype/ftoutln.h>
21 #include <freetype/ftfntfmt.h>
22 
23 #include <freetype/internal/ftvalid.h>
24 #include <freetype/internal/ftobjs.h>
25 #include <freetype/internal/ftdebug.h>
26 #include <freetype/internal/ftrfork.h>
27 #include <freetype/internal/ftstream.h>
28 #include <freetype/internal/sfnt.h>          /* for SFNT_Load_Table_Func */
29 #include <freetype/internal/psaux.h>         /* for PS_Driver            */
30 
31 #include <freetype/tttables.h>
32 #include <freetype/tttags.h>
33 #include <freetype/ttnameid.h>
34 
35 #include <freetype/internal/services/svprop.h>
36 #include <freetype/internal/services/svsfnt.h>
37 #include <freetype/internal/services/svpostnm.h>
38 #include <freetype/internal/services/svgldict.h>
39 #include <freetype/internal/services/svttcmap.h>
40 #include <freetype/internal/services/svkern.h>
41 #include <freetype/internal/services/svtteng.h>
42 
43 #include <freetype/ftdriver.h>
44 
45 #ifdef FT_CONFIG_OPTION_MAC_FONTS
46 #include "ftbase.h"
47 #endif
48 
49 
50 #ifdef FT_DEBUG_LEVEL_TRACE
51 
52 #include <freetype/ftbitmap.h>
53 
54 #if defined( _MSC_VER )      /* Visual C++ (and Intel C++)   */
55   /* We disable the warning `conversion from XXX to YYY,     */
56   /* possible loss of data' in order to compile cleanly with */
57   /* the maximum level of warnings: `md5.c' is non-FreeType  */
58   /* code, and it gets used during development builds only.  */
59 #pragma warning( push )
60 #pragma warning( disable : 4244 )
61 #endif /* _MSC_VER */
62 
63   /* It's easiest to include `md5.c' directly.  However, since OpenSSL */
64   /* also provides the same functions, there might be conflicts if     */
65   /* both FreeType and OpenSSL are built as static libraries.  For     */
66   /* this reason, we put the MD5 stuff into the `FT_' namespace.       */
67 #define MD5_u32plus  FT_MD5_u32plus
68 #define MD5_CTX      FT_MD5_CTX
69 #define MD5_Init     FT_MD5_Init
70 #define MD5_Update   FT_MD5_Update
71 #define MD5_Final    FT_MD5_Final
72 
73 #undef  HAVE_OPENSSL
74 
75 #include "md5.c"
76 
77 #if defined( _MSC_VER )
78 #pragma warning( pop )
79 #endif
80 
81   static const char* const  pixel_modes[] =
82   {
83     "none",
84     "monochrome bitmap",
85     "gray 8-bit bitmap",
86     "gray 2-bit bitmap",
87     "gray 4-bit bitmap",
88     "LCD 8-bit bitmap",
89     "vertical LCD 8-bit bitmap",
90     "BGRA 32-bit color image bitmap"
91   };
92 
93 #endif /* FT_DEBUG_LEVEL_TRACE */
94 
95 
96 #define GRID_FIT_METRICS
97 
98 
99   /* forward declaration */
100   static FT_Error
101   ft_open_face_internal( FT_Library           library,
102                          const FT_Open_Args*  args,
103                          FT_Long              face_index,
104                          FT_Face             *aface,
105                          FT_Bool              test_mac_fonts );
106 
107 
108   FT_BASE_DEF( FT_Pointer )
ft_service_list_lookup(FT_ServiceDesc service_descriptors,const char * service_id)109   ft_service_list_lookup( FT_ServiceDesc  service_descriptors,
110                           const char*     service_id )
111   {
112     FT_Pointer      result = NULL;
113     FT_ServiceDesc  desc   = service_descriptors;
114 
115 
116     if ( desc && service_id )
117     {
118       for ( ; desc->serv_id != NULL; desc++ )
119       {
120         if ( ft_strcmp( desc->serv_id, service_id ) == 0 )
121         {
122           result = (FT_Pointer)desc->serv_data;
123           break;
124         }
125       }
126     }
127 
128     return result;
129   }
130 
131 
132   FT_BASE_DEF( void )
ft_validator_init(FT_Validator valid,const FT_Byte * base,const FT_Byte * limit,FT_ValidationLevel level)133   ft_validator_init( FT_Validator        valid,
134                      const FT_Byte*      base,
135                      const FT_Byte*      limit,
136                      FT_ValidationLevel  level )
137   {
138     valid->base  = base;
139     valid->limit = limit;
140     valid->level = level;
141     valid->error = FT_Err_Ok;
142   }
143 
144 
145   FT_BASE_DEF( FT_Int )
ft_validator_run(FT_Validator valid)146   ft_validator_run( FT_Validator  valid )
147   {
148     /* This function doesn't work!  None should call it. */
149     FT_UNUSED( valid );
150 
151     return -1;
152   }
153 
154 
155   FT_BASE_DEF( void )
ft_validator_error(FT_Validator valid,FT_Error error)156   ft_validator_error( FT_Validator  valid,
157                       FT_Error      error )
158   {
159     /* since the cast below also disables the compiler's */
160     /* type check, we introduce a dummy variable, which  */
161     /* will be optimized away                            */
162     volatile ft_jmp_buf* jump_buffer = &valid->jump_buffer;
163 
164 
165     valid->error = error;
166 
167     /* throw away volatileness; use `jump_buffer' or the  */
168     /* compiler may warn about an unused local variable   */
169     ft_longjmp( *(ft_jmp_buf*) jump_buffer, 1 );
170   }
171 
172 
173   /*************************************************************************/
174   /*************************************************************************/
175   /*************************************************************************/
176   /****                                                                 ****/
177   /****                                                                 ****/
178   /****                           S T R E A M                           ****/
179   /****                                                                 ****/
180   /****                                                                 ****/
181   /*************************************************************************/
182   /*************************************************************************/
183   /*************************************************************************/
184 
185 
186   /* create a new input stream from an FT_Open_Args structure */
187   /*                                                          */
188   FT_BASE_DEF( FT_Error )
FT_Stream_New(FT_Library library,const FT_Open_Args * args,FT_Stream * astream)189   FT_Stream_New( FT_Library           library,
190                  const FT_Open_Args*  args,
191                  FT_Stream           *astream )
192   {
193     FT_Error   error;
194     FT_Memory  memory;
195     FT_Stream  stream = NULL;
196 
197 
198     *astream = NULL;
199 
200     if ( !library )
201       return FT_THROW( Invalid_Library_Handle );
202 
203     if ( !args )
204       return FT_THROW( Invalid_Argument );
205 
206     memory = library->memory;
207 
208     if ( FT_NEW( stream ) )
209       goto Exit;
210 
211     stream->memory = memory;
212 
213     if ( args->flags & FT_OPEN_MEMORY )
214     {
215       /* create a memory-based stream */
216       FT_Stream_OpenMemory( stream,
217                             (const FT_Byte*)args->memory_base,
218                             (FT_ULong)args->memory_size );
219     }
220 
221 #ifndef FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT
222 
223     else if ( args->flags & FT_OPEN_PATHNAME )
224     {
225       /* create a normal system stream */
226       error = FT_Stream_Open( stream, args->pathname );
227       stream->pathname.pointer = args->pathname;
228     }
229     else if ( ( args->flags & FT_OPEN_STREAM ) && args->stream )
230     {
231       /* use an existing, user-provided stream */
232 
233       /* in this case, we do not need to allocate a new stream object */
234       /* since the caller is responsible for closing it himself       */
235       FT_FREE( stream );
236       stream = args->stream;
237     }
238 
239 #endif
240 
241     else
242       error = FT_THROW( Invalid_Argument );
243 
244     if ( error )
245       FT_FREE( stream );
246     else
247       stream->memory = memory;  /* just to be certain */
248 
249     *astream = stream;
250 
251   Exit:
252     return error;
253   }
254 
255 
256   FT_BASE_DEF( void )
FT_Stream_Free(FT_Stream stream,FT_Int external)257   FT_Stream_Free( FT_Stream  stream,
258                   FT_Int     external )
259   {
260     if ( stream )
261     {
262       FT_Memory  memory = stream->memory;
263 
264 
265       FT_Stream_Close( stream );
266 
267       if ( !external )
268         FT_FREE( stream );
269     }
270   }
271 
272 
273   /**************************************************************************
274    *
275    * The macro FT_COMPONENT is used in trace mode.  It is an implicit
276    * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
277    * messages during execution.
278    */
279 #undef  FT_COMPONENT
280 #define FT_COMPONENT  objs
281 
282 
283   /*************************************************************************/
284   /*************************************************************************/
285   /*************************************************************************/
286   /****                                                                 ****/
287   /****                                                                 ****/
288   /****               FACE, SIZE & GLYPH SLOT OBJECTS                   ****/
289   /****                                                                 ****/
290   /****                                                                 ****/
291   /*************************************************************************/
292   /*************************************************************************/
293   /*************************************************************************/
294 
295 
296   static FT_Error
ft_glyphslot_init(FT_GlyphSlot slot)297   ft_glyphslot_init( FT_GlyphSlot  slot )
298   {
299     FT_Driver         driver   = slot->face->driver;
300     FT_Driver_Class   clazz    = driver->clazz;
301     FT_Memory         memory   = driver->root.memory;
302     FT_Error          error    = FT_Err_Ok;
303     FT_Slot_Internal  internal = NULL;
304 
305 
306     slot->library = driver->root.library;
307 
308     if ( FT_NEW( internal ) )
309       goto Exit;
310 
311     slot->internal = internal;
312 
313     if ( FT_DRIVER_USES_OUTLINES( driver ) )
314       error = FT_GlyphLoader_New( memory, &internal->loader );
315 
316     if ( !error && clazz->init_slot )
317       error = clazz->init_slot( slot );
318 
319   Exit:
320     return error;
321   }
322 
323 
324   FT_BASE_DEF( void )
ft_glyphslot_free_bitmap(FT_GlyphSlot slot)325   ft_glyphslot_free_bitmap( FT_GlyphSlot  slot )
326   {
327     if ( slot->internal && ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) )
328     {
329       FT_Memory  memory = FT_FACE_MEMORY( slot->face );
330 
331 
332       FT_FREE( slot->bitmap.buffer );
333       slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP;
334     }
335     else
336     {
337       /* assume that the bitmap buffer was stolen or not */
338       /* allocated from the heap                         */
339       slot->bitmap.buffer = NULL;
340     }
341   }
342 
343 
344   /* overflow-resistant presetting of bitmap position and dimensions; */
345   /* also check whether the size is too large for rendering           */
346   FT_BASE_DEF( FT_Bool )
ft_glyphslot_preset_bitmap(FT_GlyphSlot slot,FT_Render_Mode mode,const FT_Vector * origin)347   ft_glyphslot_preset_bitmap( FT_GlyphSlot      slot,
348                               FT_Render_Mode    mode,
349                               const FT_Vector*  origin )
350   {
351     FT_Outline*  outline = &slot->outline;
352     FT_Bitmap*   bitmap  = &slot->bitmap;
353 
354     FT_Pixel_Mode  pixel_mode;
355 
356     FT_BBox  cbox, pbox;
357     FT_Pos   x_shift = 0;
358     FT_Pos   y_shift = 0;
359     FT_Pos   x_left, y_top;
360     FT_Pos   width, height, pitch;
361 
362 
363     if ( slot->format != FT_GLYPH_FORMAT_OUTLINE )
364       return 1;
365 
366     if ( origin )
367     {
368       x_shift = origin->x;
369       y_shift = origin->y;
370     }
371 
372     /* compute the control box, and grid-fit it, */
373     /* taking into account the origin shift      */
374     FT_Outline_Get_CBox( outline, &cbox );
375 
376     /* rough estimate of pixel box */
377     pbox.xMin = ( cbox.xMin >> 6 ) + ( x_shift >> 6 );
378     pbox.yMin = ( cbox.yMin >> 6 ) + ( y_shift >> 6 );
379     pbox.xMax = ( cbox.xMax >> 6 ) + ( x_shift >> 6 );
380     pbox.yMax = ( cbox.yMax >> 6 ) + ( y_shift >> 6 );
381 
382     /* tiny remainder box */
383     cbox.xMin = ( cbox.xMin & 63 ) + ( x_shift & 63 );
384     cbox.yMin = ( cbox.yMin & 63 ) + ( y_shift & 63 );
385     cbox.xMax = ( cbox.xMax & 63 ) + ( x_shift & 63 );
386     cbox.yMax = ( cbox.yMax & 63 ) + ( y_shift & 63 );
387 
388     switch ( mode )
389     {
390     case FT_RENDER_MODE_MONO:
391       pixel_mode = FT_PIXEL_MODE_MONO;
392 #if 1
393       /* x */
394 
395       /* undocumented but confirmed: bbox values get rounded;    */
396       /* we do asymmetric rounding so that the center of a pixel */
397       /* gets always included                                    */
398 
399       pbox.xMin += ( cbox.xMin + 31 ) >> 6;
400       pbox.xMax += ( cbox.xMax + 32 ) >> 6;
401 
402       /* if the bbox collapsed, we add a pixel based on the total */
403       /* rounding remainder to cover most of the original cbox    */
404 
405       if ( pbox.xMin == pbox.xMax )
406       {
407         if ( ( ( cbox.xMin + 31 ) & 63 ) - 31 +
408              ( ( cbox.xMax + 32 ) & 63 ) - 32 < 0 )
409           pbox.xMin -= 1;
410         else
411           pbox.xMax += 1;
412       }
413 
414       /* y */
415 
416       pbox.yMin += ( cbox.yMin + 31 ) >> 6;
417       pbox.yMax += ( cbox.yMax + 32 ) >> 6;
418 
419       if ( pbox.yMin == pbox.yMax )
420       {
421         if ( ( ( cbox.yMin + 31 ) & 63 ) - 31 +
422              ( ( cbox.yMax + 32 ) & 63 ) - 32 < 0 )
423           pbox.yMin -= 1;
424         else
425           pbox.yMax += 1;
426       }
427 
428       break;
429 #else
430       goto Adjust;
431 #endif
432 
433     case FT_RENDER_MODE_LCD:
434       pixel_mode = FT_PIXEL_MODE_LCD;
435       ft_lcd_padding( &cbox, slot, mode );
436       goto Adjust;
437 
438     case FT_RENDER_MODE_LCD_V:
439       pixel_mode = FT_PIXEL_MODE_LCD_V;
440       ft_lcd_padding( &cbox, slot, mode );
441       goto Adjust;
442 
443     case FT_RENDER_MODE_NORMAL:
444     case FT_RENDER_MODE_LIGHT:
445     default:
446       pixel_mode = FT_PIXEL_MODE_GRAY;
447     Adjust:
448       pbox.xMin += cbox.xMin >> 6;
449       pbox.yMin += cbox.yMin >> 6;
450       pbox.xMax += ( cbox.xMax + 63 ) >> 6;
451       pbox.yMax += ( cbox.yMax + 63 ) >> 6;
452     }
453 
454     x_left = pbox.xMin;
455     y_top  = pbox.yMax;
456 
457     width  = pbox.xMax - pbox.xMin;
458     height = pbox.yMax - pbox.yMin;
459 
460     switch ( pixel_mode )
461     {
462     case FT_PIXEL_MODE_MONO:
463       pitch = ( ( width + 15 ) >> 4 ) << 1;
464       break;
465 
466     case FT_PIXEL_MODE_LCD:
467       width *= 3;
468       pitch  = FT_PAD_CEIL( width, 4 );
469       break;
470 
471     case FT_PIXEL_MODE_LCD_V:
472       height *= 3;
473       /* fall through */
474 
475     case FT_PIXEL_MODE_GRAY:
476     default:
477       pitch = width;
478     }
479 
480     slot->bitmap_left = (FT_Int)x_left;
481     slot->bitmap_top  = (FT_Int)y_top;
482 
483     bitmap->pixel_mode = (unsigned char)pixel_mode;
484     bitmap->num_grays  = 256;
485     bitmap->width      = (unsigned int)width;
486     bitmap->rows       = (unsigned int)height;
487     bitmap->pitch      = pitch;
488 
489     if ( pbox.xMin < -0x8000 || pbox.xMax > 0x7FFF ||
490          pbox.yMin < -0x8000 || pbox.yMax > 0x7FFF )
491     {
492       FT_TRACE3(( "ft_glyphslot_preset_bitmap: [%ld %ld %ld %ld]\n",
493                   pbox.xMin, pbox.yMin, pbox.xMax, pbox.yMax ));
494       return 1;
495     }
496 
497     return 0;
498   }
499 
500 
501   FT_BASE_DEF( void )
ft_glyphslot_set_bitmap(FT_GlyphSlot slot,FT_Byte * buffer)502   ft_glyphslot_set_bitmap( FT_GlyphSlot  slot,
503                            FT_Byte*      buffer )
504   {
505     ft_glyphslot_free_bitmap( slot );
506 
507     slot->bitmap.buffer = buffer;
508 
509     FT_ASSERT( (slot->internal->flags & FT_GLYPH_OWN_BITMAP) == 0 );
510   }
511 
512 
513   FT_BASE_DEF( FT_Error )
ft_glyphslot_alloc_bitmap(FT_GlyphSlot slot,FT_ULong size)514   ft_glyphslot_alloc_bitmap( FT_GlyphSlot  slot,
515                              FT_ULong      size )
516   {
517     FT_Memory  memory = FT_FACE_MEMORY( slot->face );
518     FT_Error   error;
519 
520 
521     if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP )
522       FT_FREE( slot->bitmap.buffer );
523     else
524       slot->internal->flags |= FT_GLYPH_OWN_BITMAP;
525 
526     (void)FT_ALLOC( slot->bitmap.buffer, size );
527     return error;
528   }
529 
530 
531   static void
ft_glyphslot_clear(FT_GlyphSlot slot)532   ft_glyphslot_clear( FT_GlyphSlot  slot )
533   {
534     /* free bitmap if needed */
535     ft_glyphslot_free_bitmap( slot );
536 
537     /* clear all public fields in the glyph slot */
538     FT_ZERO( &slot->metrics );
539     FT_ZERO( &slot->outline );
540 
541     slot->bitmap.width      = 0;
542     slot->bitmap.rows       = 0;
543     slot->bitmap.pitch      = 0;
544     slot->bitmap.pixel_mode = 0;
545     /* `slot->bitmap.buffer' has been handled by ft_glyphslot_free_bitmap */
546 
547     slot->bitmap_left   = 0;
548     slot->bitmap_top    = 0;
549     slot->num_subglyphs = 0;
550     slot->subglyphs     = NULL;
551     slot->control_data  = NULL;
552     slot->control_len   = 0;
553     slot->other         = NULL;
554     slot->format        = FT_GLYPH_FORMAT_NONE;
555 
556     slot->linearHoriAdvance = 0;
557     slot->linearVertAdvance = 0;
558     slot->lsb_delta         = 0;
559     slot->rsb_delta         = 0;
560   }
561 
562 
563   static void
ft_glyphslot_done(FT_GlyphSlot slot)564   ft_glyphslot_done( FT_GlyphSlot  slot )
565   {
566     FT_Driver        driver = slot->face->driver;
567     FT_Driver_Class  clazz  = driver->clazz;
568     FT_Memory        memory = driver->root.memory;
569 
570 
571     if ( clazz->done_slot )
572       clazz->done_slot( slot );
573 
574     /* free bitmap buffer if needed */
575     ft_glyphslot_free_bitmap( slot );
576 
577     /* slot->internal might be NULL in out-of-memory situations */
578     if ( slot->internal )
579     {
580       /* free glyph loader */
581       if ( FT_DRIVER_USES_OUTLINES( driver ) )
582       {
583         FT_GlyphLoader_Done( slot->internal->loader );
584         slot->internal->loader = NULL;
585       }
586 
587       FT_FREE( slot->internal );
588     }
589   }
590 
591 
592   /* documentation is in ftobjs.h */
593 
594   FT_BASE_DEF( FT_Error )
FT_New_GlyphSlot(FT_Face face,FT_GlyphSlot * aslot)595   FT_New_GlyphSlot( FT_Face        face,
596                     FT_GlyphSlot  *aslot )
597   {
598     FT_Error         error;
599     FT_Driver        driver;
600     FT_Driver_Class  clazz;
601     FT_Memory        memory;
602     FT_GlyphSlot     slot = NULL;
603 
604 
605     if ( !face )
606       return FT_THROW( Invalid_Face_Handle );
607 
608     if ( !face->driver )
609       return FT_THROW( Invalid_Argument );
610 
611     driver = face->driver;
612     clazz  = driver->clazz;
613     memory = driver->root.memory;
614 
615     FT_TRACE4(( "FT_New_GlyphSlot: Creating new slot object\n" ));
616     if ( !FT_ALLOC( slot, clazz->slot_object_size ) )
617     {
618       slot->face = face;
619 
620       error = ft_glyphslot_init( slot );
621       if ( error )
622       {
623         ft_glyphslot_done( slot );
624         FT_FREE( slot );
625         goto Exit;
626       }
627 
628       slot->next  = face->glyph;
629       face->glyph = slot;
630 
631       if ( aslot )
632         *aslot = slot;
633     }
634     else if ( aslot )
635       *aslot = NULL;
636 
637 
638   Exit:
639     FT_TRACE4(( "FT_New_GlyphSlot: Return 0x%x\n", error ));
640 
641     return error;
642   }
643 
644 
645   /* documentation is in ftobjs.h */
646 
647   FT_BASE_DEF( void )
FT_Done_GlyphSlot(FT_GlyphSlot slot)648   FT_Done_GlyphSlot( FT_GlyphSlot  slot )
649   {
650     if ( slot )
651     {
652       FT_Driver     driver = slot->face->driver;
653       FT_Memory     memory = driver->root.memory;
654       FT_GlyphSlot  prev;
655       FT_GlyphSlot  cur;
656 
657 
658       /* Remove slot from its parent face's list */
659       prev = NULL;
660       cur  = slot->face->glyph;
661 
662       while ( cur )
663       {
664         if ( cur == slot )
665         {
666           if ( !prev )
667             slot->face->glyph = cur->next;
668           else
669             prev->next = cur->next;
670 
671           /* finalize client-specific data */
672           if ( slot->generic.finalizer )
673             slot->generic.finalizer( slot );
674 
675           ft_glyphslot_done( slot );
676           FT_FREE( slot );
677           break;
678         }
679         prev = cur;
680         cur  = cur->next;
681       }
682     }
683   }
684 
685 
686   /* documentation is in freetype.h */
687 
688   FT_EXPORT_DEF( void )
FT_Set_Transform(FT_Face face,FT_Matrix * matrix,FT_Vector * delta)689   FT_Set_Transform( FT_Face     face,
690                     FT_Matrix*  matrix,
691                     FT_Vector*  delta )
692   {
693     FT_Face_Internal  internal;
694 
695 
696     if ( !face )
697       return;
698 
699     internal = face->internal;
700 
701     internal->transform_flags = 0;
702 
703     if ( !matrix )
704     {
705       internal->transform_matrix.xx = 0x10000L;
706       internal->transform_matrix.xy = 0;
707       internal->transform_matrix.yx = 0;
708       internal->transform_matrix.yy = 0x10000L;
709 
710       matrix = &internal->transform_matrix;
711     }
712     else
713       internal->transform_matrix = *matrix;
714 
715     /* set transform_flags bit flag 0 if `matrix' isn't the identity */
716     if ( ( matrix->xy | matrix->yx ) ||
717          matrix->xx != 0x10000L      ||
718          matrix->yy != 0x10000L      )
719       internal->transform_flags |= 1;
720 
721     if ( !delta )
722     {
723       internal->transform_delta.x = 0;
724       internal->transform_delta.y = 0;
725 
726       delta = &internal->transform_delta;
727     }
728     else
729       internal->transform_delta = *delta;
730 
731     /* set transform_flags bit flag 1 if `delta' isn't the null vector */
732     if ( delta->x | delta->y )
733       internal->transform_flags |= 2;
734   }
735 
736 
737   static FT_Renderer
738   ft_lookup_glyph_renderer( FT_GlyphSlot  slot );
739 
740 
741 #ifdef GRID_FIT_METRICS
742   static void
ft_glyphslot_grid_fit_metrics(FT_GlyphSlot slot,FT_Bool vertical)743   ft_glyphslot_grid_fit_metrics( FT_GlyphSlot  slot,
744                                  FT_Bool       vertical )
745   {
746     FT_Glyph_Metrics*  metrics = &slot->metrics;
747     FT_Pos             right, bottom;
748 
749 
750     if ( vertical )
751     {
752       metrics->horiBearingX = FT_PIX_FLOOR( metrics->horiBearingX );
753       metrics->horiBearingY = FT_PIX_CEIL_LONG( metrics->horiBearingY );
754 
755       right  = FT_PIX_CEIL_LONG( ADD_LONG( metrics->vertBearingX,
756                                            metrics->width ) );
757       bottom = FT_PIX_CEIL_LONG( ADD_LONG( metrics->vertBearingY,
758                                            metrics->height ) );
759 
760       metrics->vertBearingX = FT_PIX_FLOOR( metrics->vertBearingX );
761       metrics->vertBearingY = FT_PIX_FLOOR( metrics->vertBearingY );
762 
763       metrics->width  = SUB_LONG( right,
764                                   metrics->vertBearingX );
765       metrics->height = SUB_LONG( bottom,
766                                   metrics->vertBearingY );
767     }
768     else
769     {
770       metrics->vertBearingX = FT_PIX_FLOOR( metrics->vertBearingX );
771       metrics->vertBearingY = FT_PIX_FLOOR( metrics->vertBearingY );
772 
773       right  = FT_PIX_CEIL_LONG( ADD_LONG( metrics->horiBearingX,
774                                            metrics->width ) );
775       bottom = FT_PIX_FLOOR( SUB_LONG( metrics->horiBearingY,
776                                        metrics->height ) );
777 
778       metrics->horiBearingX = FT_PIX_FLOOR( metrics->horiBearingX );
779       metrics->horiBearingY = FT_PIX_CEIL_LONG( metrics->horiBearingY );
780 
781       metrics->width  = SUB_LONG( right,
782                                   metrics->horiBearingX );
783       metrics->height = SUB_LONG( metrics->horiBearingY,
784                                   bottom );
785     }
786 
787     metrics->horiAdvance = FT_PIX_ROUND_LONG( metrics->horiAdvance );
788     metrics->vertAdvance = FT_PIX_ROUND_LONG( metrics->vertAdvance );
789   }
790 #endif /* GRID_FIT_METRICS */
791 
792 
793   /* documentation is in freetype.h */
794 
795   FT_EXPORT_DEF( FT_Error )
FT_Load_Glyph(FT_Face face,FT_UInt glyph_index,FT_Int32 load_flags)796   FT_Load_Glyph( FT_Face   face,
797                  FT_UInt   glyph_index,
798                  FT_Int32  load_flags )
799   {
800     FT_Error      error;
801     FT_Driver     driver;
802     FT_GlyphSlot  slot;
803     FT_Library    library;
804     FT_Bool       autohint = FALSE;
805     FT_Module     hinter;
806     TT_Face       ttface = (TT_Face)face;
807 
808 
809     if ( !face || !face->size || !face->glyph )
810       return FT_THROW( Invalid_Face_Handle );
811 
812     /* The validity test for `glyph_index' is performed by the */
813     /* font drivers.                                           */
814 
815     slot = face->glyph;
816     ft_glyphslot_clear( slot );
817 
818     driver  = face->driver;
819     library = driver->root.library;
820     hinter  = library->auto_hinter;
821 
822     /* resolve load flags dependencies */
823 
824     if ( load_flags & FT_LOAD_NO_RECURSE )
825       load_flags |= FT_LOAD_NO_SCALE         |
826                     FT_LOAD_IGNORE_TRANSFORM;
827 
828     if ( load_flags & FT_LOAD_NO_SCALE )
829     {
830       load_flags |= FT_LOAD_NO_HINTING |
831                     FT_LOAD_NO_BITMAP;
832 
833       load_flags &= ~FT_LOAD_RENDER;
834     }
835 
836     if ( load_flags & FT_LOAD_BITMAP_METRICS_ONLY )
837       load_flags &= ~FT_LOAD_RENDER;
838 
839     /*
840      * Determine whether we need to auto-hint or not.
841      * The general rules are:
842      *
843      * - Do only auto-hinting if we have
844      *
845      *   - a hinter module,
846      *   - a scalable font,
847      *   - not a tricky font, and
848      *   - no transforms except simple slants and/or rotations by
849      *     integer multiples of 90 degrees.
850      *
851      * - Then, auto-hint if FT_LOAD_FORCE_AUTOHINT is set or if we don't
852      *   have a native font hinter.
853      *
854      * - Otherwise, auto-hint for LIGHT hinting mode or if there isn't
855      *   any hinting bytecode in the TrueType/OpenType font.
856      *
857      * - Exception: The font is `tricky' and requires the native hinter to
858      *   load properly.
859      */
860 
861     if ( hinter                                           &&
862          !( load_flags & FT_LOAD_NO_HINTING )             &&
863          !( load_flags & FT_LOAD_NO_AUTOHINT )            &&
864          FT_IS_SCALABLE( face )                           &&
865          !FT_IS_TRICKY( face )                            &&
866          ( ( load_flags & FT_LOAD_IGNORE_TRANSFORM )    ||
867            ( face->internal->transform_matrix.yx == 0 &&
868              face->internal->transform_matrix.xx != 0 ) ||
869            ( face->internal->transform_matrix.xx == 0 &&
870              face->internal->transform_matrix.yx != 0 ) ) )
871     {
872       if ( ( load_flags & FT_LOAD_FORCE_AUTOHINT ) ||
873            !FT_DRIVER_HAS_HINTER( driver )         )
874         autohint = TRUE;
875       else
876       {
877         FT_Render_Mode  mode = FT_LOAD_TARGET_MODE( load_flags );
878         FT_Bool         is_light_type1;
879 
880 
881         /* only the new Adobe engine (for both CFF and Type 1) is `light'; */
882         /* we use `strstr' to catch both `Type 1' and `CID Type 1'         */
883         is_light_type1 =
884           ft_strstr( FT_Get_Font_Format( face ), "Type 1" ) != NULL &&
885           ((PS_Driver)driver)->hinting_engine == FT_HINTING_ADOBE;
886 
887         /* the check for `num_locations' assures that we actually    */
888         /* test for instructions in a TTF and not in a CFF-based OTF */
889         /*                                                           */
890         /* since `maxSizeOfInstructions' might be unreliable, we     */
891         /* check the size of the `fpgm' and `prep' tables, too --    */
892         /* the assumption is that there don't exist real TTFs where  */
893         /* both `fpgm' and `prep' tables are missing                 */
894         if ( ( mode == FT_RENDER_MODE_LIGHT           &&
895                ( !FT_DRIVER_HINTS_LIGHTLY( driver ) &&
896                  !is_light_type1                    ) )         ||
897              ( FT_IS_SFNT( face )                             &&
898                ttface->num_locations                          &&
899                ttface->max_profile.maxSizeOfInstructions == 0 &&
900                ttface->font_program_size == 0                 &&
901                ttface->cvt_program_size == 0                  ) )
902           autohint = TRUE;
903       }
904     }
905 
906     if ( autohint )
907     {
908       FT_AutoHinter_Interface  hinting;
909 
910 
911       /* try to load embedded bitmaps first if available            */
912       /*                                                            */
913       /* XXX: This is really a temporary hack that should disappear */
914       /*      promptly with FreeType 2.1!                           */
915       /*                                                            */
916       if ( FT_HAS_FIXED_SIZES( face )              &&
917            ( load_flags & FT_LOAD_NO_BITMAP ) == 0 )
918       {
919         error = driver->clazz->load_glyph( slot, face->size,
920                                            glyph_index,
921                                            load_flags | FT_LOAD_SBITS_ONLY );
922 
923         if ( !error && slot->format == FT_GLYPH_FORMAT_BITMAP )
924           goto Load_Ok;
925       }
926 
927       {
928         FT_Face_Internal  internal        = face->internal;
929         FT_Int            transform_flags = internal->transform_flags;
930 
931 
932         /* since the auto-hinter calls FT_Load_Glyph by itself, */
933         /* make sure that glyphs aren't transformed             */
934         internal->transform_flags = 0;
935 
936         /* load auto-hinted outline */
937         hinting = (FT_AutoHinter_Interface)hinter->clazz->module_interface;
938 
939         error   = hinting->load_glyph( (FT_AutoHinter)hinter,
940                                        slot, face->size,
941                                        glyph_index, load_flags );
942 
943         internal->transform_flags = transform_flags;
944       }
945     }
946     else
947     {
948       error = driver->clazz->load_glyph( slot,
949                                          face->size,
950                                          glyph_index,
951                                          load_flags );
952       if ( error )
953         goto Exit;
954 
955       if ( slot->format == FT_GLYPH_FORMAT_OUTLINE )
956       {
957         /* check that the loaded outline is correct */
958         error = FT_Outline_Check( &slot->outline );
959         if ( error )
960           goto Exit;
961 
962 #ifdef GRID_FIT_METRICS
963         if ( !( load_flags & FT_LOAD_NO_HINTING ) )
964           ft_glyphslot_grid_fit_metrics(
965             slot,
966             FT_BOOL( load_flags & FT_LOAD_VERTICAL_LAYOUT ) );
967 #endif
968       }
969     }
970 
971   Load_Ok:
972     /* compute the advance */
973     if ( load_flags & FT_LOAD_VERTICAL_LAYOUT )
974     {
975       slot->advance.x = 0;
976       slot->advance.y = slot->metrics.vertAdvance;
977     }
978     else
979     {
980       slot->advance.x = slot->metrics.horiAdvance;
981       slot->advance.y = 0;
982     }
983 
984     /* compute the linear advance in 16.16 pixels */
985     if ( ( load_flags & FT_LOAD_LINEAR_DESIGN ) == 0 &&
986          FT_IS_SCALABLE( face )                      )
987     {
988       FT_Size_Metrics*  metrics = &face->size->metrics;
989 
990 
991       /* it's tricky! */
992       slot->linearHoriAdvance = FT_MulDiv( slot->linearHoriAdvance,
993                                            metrics->x_scale, 64 );
994 
995       slot->linearVertAdvance = FT_MulDiv( slot->linearVertAdvance,
996                                            metrics->y_scale, 64 );
997     }
998 
999     if ( ( load_flags & FT_LOAD_IGNORE_TRANSFORM ) == 0 )
1000     {
1001       FT_Face_Internal  internal = face->internal;
1002 
1003 
1004       /* now, transform the glyph image if needed */
1005       if ( internal->transform_flags )
1006       {
1007         /* get renderer */
1008         FT_Renderer  renderer = ft_lookup_glyph_renderer( slot );
1009 
1010 
1011         if ( renderer )
1012           error = renderer->clazz->transform_glyph(
1013                                      renderer, slot,
1014                                      &internal->transform_matrix,
1015                                      &internal->transform_delta );
1016         else if ( slot->format == FT_GLYPH_FORMAT_OUTLINE )
1017         {
1018           /* apply `standard' transformation if no renderer is available */
1019           if ( internal->transform_flags & 1 )
1020             FT_Outline_Transform( &slot->outline,
1021                                   &internal->transform_matrix );
1022 
1023           if ( internal->transform_flags & 2 )
1024             FT_Outline_Translate( &slot->outline,
1025                                   internal->transform_delta.x,
1026                                   internal->transform_delta.y );
1027         }
1028 
1029         /* transform advance */
1030         FT_Vector_Transform( &slot->advance, &internal->transform_matrix );
1031       }
1032     }
1033 
1034     slot->glyph_index          = glyph_index;
1035     slot->internal->load_flags = load_flags;
1036 
1037     /* do we need to render the image or preset the bitmap now? */
1038     if ( !error                                    &&
1039          ( load_flags & FT_LOAD_NO_SCALE ) == 0    &&
1040          slot->format != FT_GLYPH_FORMAT_BITMAP    &&
1041          slot->format != FT_GLYPH_FORMAT_COMPOSITE )
1042     {
1043       FT_Render_Mode  mode = FT_LOAD_TARGET_MODE( load_flags );
1044 
1045 
1046       if ( mode == FT_RENDER_MODE_NORMAL   &&
1047            load_flags & FT_LOAD_MONOCHROME )
1048         mode = FT_RENDER_MODE_MONO;
1049 
1050       if ( load_flags & FT_LOAD_RENDER )
1051         error = FT_Render_Glyph( slot, mode );
1052       else
1053         ft_glyphslot_preset_bitmap( slot, mode, NULL );
1054     }
1055 
1056 #ifdef FT_DEBUG_LEVEL_TRACE
1057     FT_TRACE5(( "FT_Load_Glyph: index %d, flags 0x%x\n",
1058                 glyph_index, load_flags ));
1059     FT_TRACE5(( "  x advance: %f\n", slot->advance.x / 64.0 ));
1060     FT_TRACE5(( "  y advance: %f\n", slot->advance.y / 64.0 ));
1061     FT_TRACE5(( "  linear x advance: %f\n",
1062                 slot->linearHoriAdvance / 65536.0 ));
1063     FT_TRACE5(( "  linear y advance: %f\n",
1064                 slot->linearVertAdvance / 65536.0 ));
1065     FT_TRACE5(( "\n" ));
1066     FT_TRACE5(( "  bitmap %dx%d, %s (mode %d)\n",
1067                 slot->bitmap.width,
1068                 slot->bitmap.rows,
1069                 pixel_modes[slot->bitmap.pixel_mode],
1070                 slot->bitmap.pixel_mode ));
1071     FT_TRACE5(( "\n" ));
1072 
1073     {
1074       FT_Glyph_Metrics*  metrics = &slot->metrics;
1075 
1076 
1077       FT_TRACE5(( "  metrics:\n" ));
1078       FT_TRACE5(( "    width:  %f\n", metrics->width  / 64.0 ));
1079       FT_TRACE5(( "    height: %f\n", metrics->height / 64.0 ));
1080       FT_TRACE5(( "\n" ));
1081       FT_TRACE5(( "    horiBearingX: %f\n", metrics->horiBearingX / 64.0 ));
1082       FT_TRACE5(( "    horiBearingY: %f\n", metrics->horiBearingY / 64.0 ));
1083       FT_TRACE5(( "    horiAdvance:  %f\n", metrics->horiAdvance  / 64.0 ));
1084       FT_TRACE5(( "\n" ));
1085       FT_TRACE5(( "    vertBearingX: %f\n", metrics->vertBearingX / 64.0 ));
1086       FT_TRACE5(( "    vertBearingY: %f\n", metrics->vertBearingY / 64.0 ));
1087       FT_TRACE5(( "    vertAdvance:  %f\n", metrics->vertAdvance  / 64.0 ));
1088     }
1089 #endif
1090 
1091   Exit:
1092     return error;
1093   }
1094 
1095 
1096   /* documentation is in freetype.h */
1097 
1098   FT_EXPORT_DEF( FT_Error )
FT_Load_Char(FT_Face face,FT_ULong char_code,FT_Int32 load_flags)1099   FT_Load_Char( FT_Face   face,
1100                 FT_ULong  char_code,
1101                 FT_Int32  load_flags )
1102   {
1103     FT_UInt  glyph_index;
1104 
1105 
1106     if ( !face )
1107       return FT_THROW( Invalid_Face_Handle );
1108 
1109     glyph_index = (FT_UInt)char_code;
1110     if ( face->charmap )
1111       glyph_index = FT_Get_Char_Index( face, char_code );
1112 
1113     return FT_Load_Glyph( face, glyph_index, load_flags );
1114   }
1115 
1116 
1117   /* destructor for sizes list */
1118   static void
destroy_size(FT_Memory memory,FT_Size size,FT_Driver driver)1119   destroy_size( FT_Memory  memory,
1120                 FT_Size    size,
1121                 FT_Driver  driver )
1122   {
1123     /* finalize client-specific data */
1124     if ( size->generic.finalizer )
1125       size->generic.finalizer( size );
1126 
1127     /* finalize format-specific stuff */
1128     if ( driver->clazz->done_size )
1129       driver->clazz->done_size( size );
1130 
1131     FT_FREE( size->internal );
1132     FT_FREE( size );
1133   }
1134 
1135 
1136   static void
1137   ft_cmap_done_internal( FT_CMap  cmap );
1138 
1139 
1140   static void
destroy_charmaps(FT_Face face,FT_Memory memory)1141   destroy_charmaps( FT_Face    face,
1142                     FT_Memory  memory )
1143   {
1144     FT_Int  n;
1145 
1146 
1147     if ( !face )
1148       return;
1149 
1150     for ( n = 0; n < face->num_charmaps; n++ )
1151     {
1152       FT_CMap  cmap = FT_CMAP( face->charmaps[n] );
1153 
1154 
1155       ft_cmap_done_internal( cmap );
1156 
1157       face->charmaps[n] = NULL;
1158     }
1159 
1160     FT_FREE( face->charmaps );
1161     face->num_charmaps = 0;
1162   }
1163 
1164 
1165   /* destructor for faces list */
1166   static void
destroy_face(FT_Memory memory,FT_Face face,FT_Driver driver)1167   destroy_face( FT_Memory  memory,
1168                 FT_Face    face,
1169                 FT_Driver  driver )
1170   {
1171     FT_Driver_Class  clazz = driver->clazz;
1172 
1173 
1174     /* discard auto-hinting data */
1175     if ( face->autohint.finalizer )
1176       face->autohint.finalizer( face->autohint.data );
1177 
1178     /* Discard glyph slots for this face.                           */
1179     /* Beware!  FT_Done_GlyphSlot() changes the field `face->glyph' */
1180     while ( face->glyph )
1181       FT_Done_GlyphSlot( face->glyph );
1182 
1183     /* discard all sizes for this face */
1184     FT_List_Finalize( &face->sizes_list,
1185                       (FT_List_Destructor)destroy_size,
1186                       memory,
1187                       driver );
1188     face->size = NULL;
1189 
1190     /* now discard client data */
1191     if ( face->generic.finalizer )
1192       face->generic.finalizer( face );
1193 
1194     /* discard charmaps */
1195     destroy_charmaps( face, memory );
1196 
1197     /* finalize format-specific stuff */
1198     if ( clazz->done_face )
1199       clazz->done_face( face );
1200 
1201     /* close the stream for this face if needed */
1202     FT_Stream_Free(
1203       face->stream,
1204       ( face->face_flags & FT_FACE_FLAG_EXTERNAL_STREAM ) != 0 );
1205 
1206     face->stream = NULL;
1207 
1208     /* get rid of it */
1209     if ( face->internal )
1210     {
1211       FT_FREE( face->internal );
1212     }
1213     FT_FREE( face );
1214   }
1215 
1216 
1217   static void
Destroy_Driver(FT_Driver driver)1218   Destroy_Driver( FT_Driver  driver )
1219   {
1220     FT_List_Finalize( &driver->faces_list,
1221                       (FT_List_Destructor)destroy_face,
1222                       driver->root.memory,
1223                       driver );
1224   }
1225 
1226 
1227   /**************************************************************************
1228    *
1229    * @Function:
1230    *   find_unicode_charmap
1231    *
1232    * @Description:
1233    *   This function finds a Unicode charmap, if there is one.
1234    *   And if there is more than one, it tries to favour the more
1235    *   extensive one, i.e., one that supports UCS-4 against those which
1236    *   are limited to the BMP (said UCS-2 encoding.)
1237    *
1238    *   This function is called from open_face() (just below), and also
1239    *   from FT_Select_Charmap( ..., FT_ENCODING_UNICODE ).
1240    */
1241   static FT_Error
find_unicode_charmap(FT_Face face)1242   find_unicode_charmap( FT_Face  face )
1243   {
1244     FT_CharMap*  first;
1245     FT_CharMap*  cur;
1246 
1247 
1248     /* caller should have already checked that `face' is valid */
1249     FT_ASSERT( face );
1250 
1251     first = face->charmaps;
1252 
1253     if ( !first )
1254       return FT_THROW( Invalid_CharMap_Handle );
1255 
1256     /*
1257      * The original TrueType specification(s) only specified charmap
1258      * formats that are capable of mapping 8 or 16 bit character codes to
1259      * glyph indices.
1260      *
1261      * However, recent updates to the Apple and OpenType specifications
1262      * introduced new formats that are capable of mapping 32-bit character
1263      * codes as well.  And these are already used on some fonts, mainly to
1264      * map non-BMP Asian ideographs as defined in Unicode.
1265      *
1266      * For compatibility purposes, these fonts generally come with
1267      * *several* Unicode charmaps:
1268      *
1269      * - One of them in the "old" 16-bit format, that cannot access
1270      *   all glyphs in the font.
1271      *
1272      * - Another one in the "new" 32-bit format, that can access all
1273      *   the glyphs.
1274      *
1275      * This function has been written to always favor a 32-bit charmap
1276      * when found.  Otherwise, a 16-bit one is returned when found.
1277      */
1278 
1279     /* Since the `interesting' table, with IDs (3,10), is normally the */
1280     /* last one, we loop backwards.  This loses with type1 fonts with  */
1281     /* non-BMP characters (<.0001%), this wins with .ttf with non-BMP  */
1282     /* chars (.01% ?), and this is the same about 99.99% of the time!  */
1283 
1284     cur = first + face->num_charmaps;  /* points after the last one */
1285 
1286     for ( ; --cur >= first; )
1287     {
1288       if ( cur[0]->encoding == FT_ENCODING_UNICODE )
1289       {
1290         /* XXX If some new encodings to represent UCS-4 are added, */
1291         /*     they should be added here.                          */
1292         if ( ( cur[0]->platform_id == TT_PLATFORM_MICROSOFT &&
1293                cur[0]->encoding_id == TT_MS_ID_UCS_4        )     ||
1294              ( cur[0]->platform_id == TT_PLATFORM_APPLE_UNICODE &&
1295                cur[0]->encoding_id == TT_APPLE_ID_UNICODE_32    ) )
1296         {
1297           face->charmap = cur[0];
1298           return FT_Err_Ok;
1299         }
1300       }
1301     }
1302 
1303     /* We do not have any UCS-4 charmap.                */
1304     /* Do the loop again and search for UCS-2 charmaps. */
1305     cur = first + face->num_charmaps;
1306 
1307     for ( ; --cur >= first; )
1308     {
1309       if ( cur[0]->encoding == FT_ENCODING_UNICODE )
1310       {
1311         face->charmap = cur[0];
1312         return FT_Err_Ok;
1313       }
1314     }
1315 
1316     return FT_THROW( Invalid_CharMap_Handle );
1317   }
1318 
1319 
1320   /**************************************************************************
1321    *
1322    * @Function:
1323    *   find_variant_selector_charmap
1324    *
1325    * @Description:
1326    *   This function finds the variant selector charmap, if there is one.
1327    *   There can only be one (platform=0, specific=5, format=14).
1328    */
1329   static FT_CharMap
find_variant_selector_charmap(FT_Face face)1330   find_variant_selector_charmap( FT_Face  face )
1331   {
1332     FT_CharMap*  first;
1333     FT_CharMap*  end;
1334     FT_CharMap*  cur;
1335 
1336 
1337     /* caller should have already checked that `face' is valid */
1338     FT_ASSERT( face );
1339 
1340     first = face->charmaps;
1341 
1342     if ( !first )
1343       return NULL;
1344 
1345     end = first + face->num_charmaps;  /* points after the last one */
1346 
1347     for ( cur = first; cur < end; cur++ )
1348     {
1349       if ( cur[0]->platform_id == TT_PLATFORM_APPLE_UNICODE    &&
1350            cur[0]->encoding_id == TT_APPLE_ID_VARIANT_SELECTOR &&
1351            FT_Get_CMap_Format( cur[0] ) == 14                  )
1352         return cur[0];
1353     }
1354 
1355     return NULL;
1356   }
1357 
1358 
1359   /**************************************************************************
1360    *
1361    * @Function:
1362    *   open_face
1363    *
1364    * @Description:
1365    *   This function does some work for FT_Open_Face().
1366    */
1367   static FT_Error
open_face(FT_Driver driver,FT_Stream * astream,FT_Bool external_stream,FT_Long face_index,FT_Int num_params,FT_Parameter * params,FT_Face * aface)1368   open_face( FT_Driver      driver,
1369              FT_Stream      *astream,
1370              FT_Bool        external_stream,
1371              FT_Long        face_index,
1372              FT_Int         num_params,
1373              FT_Parameter*  params,
1374              FT_Face       *aface )
1375   {
1376     FT_Memory         memory;
1377     FT_Driver_Class   clazz;
1378     FT_Face           face     = NULL;
1379     FT_Face_Internal  internal = NULL;
1380 
1381     FT_Error          error, error2;
1382 
1383 
1384     clazz  = driver->clazz;
1385     memory = driver->root.memory;
1386 
1387     /* allocate the face object and perform basic initialization */
1388     if ( FT_ALLOC( face, clazz->face_object_size ) )
1389       goto Fail;
1390 
1391     face->driver = driver;
1392     face->memory = memory;
1393     face->stream = *astream;
1394 
1395     /* set the FT_FACE_FLAG_EXTERNAL_STREAM bit for FT_Done_Face */
1396     if ( external_stream )
1397       face->face_flags |= FT_FACE_FLAG_EXTERNAL_STREAM;
1398 
1399     if ( FT_NEW( internal ) )
1400       goto Fail;
1401 
1402     face->internal = internal;
1403 
1404 #ifdef FT_CONFIG_OPTION_INCREMENTAL
1405     {
1406       int  i;
1407 
1408 
1409       face->internal->incremental_interface = NULL;
1410       for ( i = 0; i < num_params && !face->internal->incremental_interface;
1411             i++ )
1412         if ( params[i].tag == FT_PARAM_TAG_INCREMENTAL )
1413           face->internal->incremental_interface =
1414             (FT_Incremental_Interface)params[i].data;
1415     }
1416 #endif
1417 
1418     face->internal->random_seed = -1;
1419 
1420     if ( clazz->init_face )
1421       error = clazz->init_face( *astream,
1422                                 face,
1423                                 (FT_Int)face_index,
1424                                 num_params,
1425                                 params );
1426     *astream = face->stream; /* Stream may have been changed. */
1427     if ( error )
1428       goto Fail;
1429 
1430     /* select Unicode charmap by default */
1431     error2 = find_unicode_charmap( face );
1432 
1433     /* if no Unicode charmap can be found, FT_Err_Invalid_CharMap_Handle */
1434     /* is returned.                                                      */
1435 
1436     /* no error should happen, but we want to play safe */
1437     if ( error2 && FT_ERR_NEQ( error2, Invalid_CharMap_Handle ) )
1438     {
1439       error = error2;
1440       goto Fail;
1441     }
1442 
1443     *aface = face;
1444 
1445   Fail:
1446     if ( error )
1447     {
1448       destroy_charmaps( face, memory );
1449       if ( clazz->done_face )
1450         clazz->done_face( face );
1451       FT_FREE( internal );
1452       FT_FREE( face );
1453       *aface = NULL;
1454     }
1455 
1456     return error;
1457   }
1458 
1459 
1460   /* there's a Mac-specific extended implementation of FT_New_Face() */
1461   /* in src/base/ftmac.c                                             */
1462 
1463 #ifndef FT_MACINTOSH
1464 
1465   /* documentation is in freetype.h */
1466 
1467   FT_EXPORT_DEF( FT_Error )
FT_New_Face(FT_Library library,const char * pathname,FT_Long face_index,FT_Face * aface)1468   FT_New_Face( FT_Library   library,
1469                const char*  pathname,
1470                FT_Long      face_index,
1471                FT_Face     *aface )
1472   {
1473     FT_Open_Args  args;
1474 
1475 
1476     /* test for valid `library' and `aface' delayed to `FT_Open_Face' */
1477     if ( !pathname )
1478       return FT_THROW( Invalid_Argument );
1479 
1480     args.flags    = FT_OPEN_PATHNAME;
1481     args.pathname = (char*)pathname;
1482     args.stream   = NULL;
1483 
1484     return ft_open_face_internal( library, &args, face_index, aface, 1 );
1485   }
1486 
1487 #endif
1488 
1489 
1490   /* documentation is in freetype.h */
1491 
1492   FT_EXPORT_DEF( FT_Error )
FT_New_Memory_Face(FT_Library library,const FT_Byte * file_base,FT_Long file_size,FT_Long face_index,FT_Face * aface)1493   FT_New_Memory_Face( FT_Library      library,
1494                       const FT_Byte*  file_base,
1495                       FT_Long         file_size,
1496                       FT_Long         face_index,
1497                       FT_Face        *aface )
1498   {
1499     FT_Open_Args  args;
1500 
1501 
1502     /* test for valid `library' and `face' delayed to `FT_Open_Face' */
1503     if ( !file_base )
1504       return FT_THROW( Invalid_Argument );
1505 
1506     args.flags       = FT_OPEN_MEMORY;
1507     args.memory_base = file_base;
1508     args.memory_size = file_size;
1509     args.stream      = NULL;
1510 
1511     return ft_open_face_internal( library, &args, face_index, aface, 1 );
1512   }
1513 
1514 
1515 #ifdef FT_CONFIG_OPTION_MAC_FONTS
1516 
1517   /* The behavior here is very similar to that in base/ftmac.c, but it     */
1518   /* is designed to work on non-mac systems, so no mac specific calls.     */
1519   /*                                                                       */
1520   /* We look at the file and determine if it is a mac dfont file or a mac  */
1521   /* resource file, or a macbinary file containing a mac resource file.    */
1522   /*                                                                       */
1523   /* Unlike ftmac I'm not going to look at a `FOND'.  I don't really see   */
1524   /* the point, especially since there may be multiple `FOND' resources.   */
1525   /* Instead I'll just look for `sfnt' and `POST' resources, ordered as    */
1526   /* they occur in the file.                                               */
1527   /*                                                                       */
1528   /* Note that multiple `POST' resources do not mean multiple postscript   */
1529   /* fonts; they all get jammed together to make what is essentially a     */
1530   /* pfb file.                                                             */
1531   /*                                                                       */
1532   /* We aren't interested in `NFNT' or `FONT' bitmap resources.            */
1533   /*                                                                       */
1534   /* As soon as we get an `sfnt' load it into memory and pass it off to    */
1535   /* FT_Open_Face.                                                         */
1536   /*                                                                       */
1537   /* If we have a (set of) `POST' resources, massage them into a (memory)  */
1538   /* pfb file and pass that to FT_Open_Face.  (As with ftmac.c I'm not     */
1539   /* going to try to save the kerning info.  After all that lives in the   */
1540   /* `FOND' which isn't in the file containing the `POST' resources so     */
1541   /* we don't really have access to it.                                    */
1542 
1543 
1544   /* Finalizer for a memory stream; gets called by FT_Done_Face(). */
1545   /* It frees the memory it uses.                                  */
1546   /* From `ftmac.c'.                                               */
1547   static void
memory_stream_close(FT_Stream stream)1548   memory_stream_close( FT_Stream  stream )
1549   {
1550     FT_Memory  memory = stream->memory;
1551 
1552 
1553     FT_FREE( stream->base );
1554 
1555     stream->size  = 0;
1556     stream->base  = NULL;
1557     stream->close = NULL;
1558   }
1559 
1560 
1561   /* Create a new memory stream from a buffer and a size. */
1562   /* From `ftmac.c'.                                      */
1563   static FT_Error
new_memory_stream(FT_Library library,FT_Byte * base,FT_ULong size,FT_Stream_CloseFunc close,FT_Stream * astream)1564   new_memory_stream( FT_Library           library,
1565                      FT_Byte*             base,
1566                      FT_ULong             size,
1567                      FT_Stream_CloseFunc  close,
1568                      FT_Stream           *astream )
1569   {
1570     FT_Error   error;
1571     FT_Memory  memory;
1572     FT_Stream  stream = NULL;
1573 
1574 
1575     if ( !library )
1576       return FT_THROW( Invalid_Library_Handle );
1577 
1578     if ( !base )
1579       return FT_THROW( Invalid_Argument );
1580 
1581     *astream = NULL;
1582     memory   = library->memory;
1583     if ( FT_NEW( stream ) )
1584       goto Exit;
1585 
1586     FT_Stream_OpenMemory( stream, base, size );
1587 
1588     stream->close = close;
1589 
1590     *astream = stream;
1591 
1592   Exit:
1593     return error;
1594   }
1595 
1596 
1597   /* Create a new FT_Face given a buffer and a driver name. */
1598   /* From `ftmac.c'.                                        */
1599   FT_LOCAL_DEF( FT_Error )
open_face_from_buffer(FT_Library library,FT_Byte * base,FT_ULong size,FT_Long face_index,const char * driver_name,FT_Face * aface)1600   open_face_from_buffer( FT_Library   library,
1601                          FT_Byte*     base,
1602                          FT_ULong     size,
1603                          FT_Long      face_index,
1604                          const char*  driver_name,
1605                          FT_Face     *aface )
1606   {
1607     FT_Open_Args  args;
1608     FT_Error      error;
1609     FT_Stream     stream = NULL;
1610     FT_Memory     memory = library->memory;
1611 
1612 
1613     error = new_memory_stream( library,
1614                                base,
1615                                size,
1616                                memory_stream_close,
1617                                &stream );
1618     if ( error )
1619     {
1620       FT_FREE( base );
1621       return error;
1622     }
1623 
1624     args.flags  = FT_OPEN_STREAM;
1625     args.stream = stream;
1626     if ( driver_name )
1627     {
1628       args.flags  = args.flags | FT_OPEN_DRIVER;
1629       args.driver = FT_Get_Module( library, driver_name );
1630     }
1631 
1632 #ifdef FT_MACINTOSH
1633     /* At this point, the face index has served its purpose;  */
1634     /* whoever calls this function has already used it to     */
1635     /* locate the correct font data.  We should not propagate */
1636     /* this index to FT_Open_Face() (unless it is negative).  */
1637 
1638     if ( face_index > 0 )
1639       face_index &= 0x7FFF0000L; /* retain GX data */
1640 #endif
1641 
1642     error = ft_open_face_internal( library, &args, face_index, aface, 0 );
1643 
1644     if ( !error )
1645       (*aface)->face_flags &= ~FT_FACE_FLAG_EXTERNAL_STREAM;
1646     else
1647 #ifdef FT_MACINTOSH
1648       FT_Stream_Free( stream, 0 );
1649 #else
1650     {
1651       FT_Stream_Close( stream );
1652       FT_FREE( stream );
1653     }
1654 #endif
1655 
1656     return error;
1657   }
1658 
1659 
1660   /* Look up `TYP1' or `CID ' table from sfnt table directory.       */
1661   /* `offset' and `length' must exclude the binary header in tables. */
1662 
1663   /* Type 1 and CID-keyed font drivers should recognize sfnt-wrapped */
1664   /* format too.  Here, since we can't expect that the TrueType font */
1665   /* driver is loaded unconditionally, we must parse the font by     */
1666   /* ourselves.  We are only interested in the name of the table and */
1667   /* the offset.                                                     */
1668 
1669   static FT_Error
ft_lookup_PS_in_sfnt_stream(FT_Stream stream,FT_Long face_index,FT_ULong * offset,FT_ULong * length,FT_Bool * is_sfnt_cid)1670   ft_lookup_PS_in_sfnt_stream( FT_Stream  stream,
1671                                FT_Long    face_index,
1672                                FT_ULong*  offset,
1673                                FT_ULong*  length,
1674                                FT_Bool*   is_sfnt_cid )
1675   {
1676     FT_Error   error;
1677     FT_UShort  numTables;
1678     FT_Long    pstable_index;
1679     FT_ULong   tag;
1680     int        i;
1681 
1682 
1683     *offset = 0;
1684     *length = 0;
1685     *is_sfnt_cid = FALSE;
1686 
1687     /* TODO: support for sfnt-wrapped PS/CID in TTC format */
1688 
1689     /* version check for 'typ1' (should be ignored?) */
1690     if ( FT_READ_ULONG( tag ) )
1691       return error;
1692     if ( tag != TTAG_typ1 )
1693       return FT_THROW( Unknown_File_Format );
1694 
1695     if ( FT_READ_USHORT( numTables ) )
1696       return error;
1697     if ( FT_STREAM_SKIP( 2 * 3 ) ) /* skip binary search header */
1698       return error;
1699 
1700     pstable_index = -1;
1701     *is_sfnt_cid  = FALSE;
1702 
1703     for ( i = 0; i < numTables; i++ )
1704     {
1705       if ( FT_READ_ULONG( tag )     || FT_STREAM_SKIP( 4 )      ||
1706            FT_READ_ULONG( *offset ) || FT_READ_ULONG( *length ) )
1707         return error;
1708 
1709       if ( tag == TTAG_CID )
1710       {
1711         pstable_index++;
1712         *offset += 22;
1713         *length -= 22;
1714         *is_sfnt_cid = TRUE;
1715         if ( face_index < 0 )
1716           return FT_Err_Ok;
1717       }
1718       else if ( tag == TTAG_TYP1 )
1719       {
1720         pstable_index++;
1721         *offset += 24;
1722         *length -= 24;
1723         *is_sfnt_cid = FALSE;
1724         if ( face_index < 0 )
1725           return FT_Err_Ok;
1726       }
1727       if ( face_index >= 0 && pstable_index == face_index )
1728         return FT_Err_Ok;
1729     }
1730 
1731     return FT_THROW( Table_Missing );
1732   }
1733 
1734 
1735   FT_LOCAL_DEF( FT_Error )
open_face_PS_from_sfnt_stream(FT_Library library,FT_Stream stream,FT_Long face_index,FT_Int num_params,FT_Parameter * params,FT_Face * aface)1736   open_face_PS_from_sfnt_stream( FT_Library     library,
1737                                  FT_Stream      stream,
1738                                  FT_Long        face_index,
1739                                  FT_Int         num_params,
1740                                  FT_Parameter  *params,
1741                                  FT_Face       *aface )
1742   {
1743     FT_Error   error;
1744     FT_Memory  memory = library->memory;
1745     FT_ULong   offset, length;
1746     FT_ULong   pos;
1747     FT_Bool    is_sfnt_cid;
1748     FT_Byte*   sfnt_ps = NULL;
1749 
1750     FT_UNUSED( num_params );
1751     FT_UNUSED( params );
1752 
1753 
1754     /* ignore GX stuff */
1755     if ( face_index > 0 )
1756       face_index &= 0xFFFFL;
1757 
1758     pos = FT_STREAM_POS();
1759 
1760     error = ft_lookup_PS_in_sfnt_stream( stream,
1761                                          face_index,
1762                                          &offset,
1763                                          &length,
1764                                          &is_sfnt_cid );
1765     if ( error )
1766       goto Exit;
1767 
1768     if ( offset > stream->size )
1769     {
1770       FT_TRACE2(( "open_face_PS_from_sfnt_stream: invalid table offset\n" ));
1771       error = FT_THROW( Invalid_Table );
1772       goto Exit;
1773     }
1774     else if ( length > stream->size - offset )
1775     {
1776       FT_TRACE2(( "open_face_PS_from_sfnt_stream: invalid table length\n" ));
1777       error = FT_THROW( Invalid_Table );
1778       goto Exit;
1779     }
1780 
1781     error = FT_Stream_Seek( stream, pos + offset );
1782     if ( error )
1783       goto Exit;
1784 
1785     if ( FT_ALLOC( sfnt_ps, (FT_Long)length ) )
1786       goto Exit;
1787 
1788     error = FT_Stream_Read( stream, (FT_Byte *)sfnt_ps, length );
1789     if ( error )
1790     {
1791       FT_FREE( sfnt_ps );
1792       goto Exit;
1793     }
1794 
1795     error = open_face_from_buffer( library,
1796                                    sfnt_ps,
1797                                    length,
1798                                    FT_MIN( face_index, 0 ),
1799                                    is_sfnt_cid ? "cid" : "type1",
1800                                    aface );
1801   Exit:
1802     {
1803       FT_Error  error1;
1804 
1805 
1806       if ( FT_ERR_EQ( error, Unknown_File_Format ) )
1807       {
1808         error1 = FT_Stream_Seek( stream, pos );
1809         if ( error1 )
1810           return error1;
1811       }
1812 
1813       return error;
1814     }
1815   }
1816 
1817 
1818 #ifndef FT_MACINTOSH
1819 
1820   /* The resource header says we've got resource_cnt `POST' (type1) */
1821   /* resources in this file.  They all need to be coalesced into    */
1822   /* one lump which gets passed on to the type1 driver.             */
1823   /* Here can be only one PostScript font in a file so face_index   */
1824   /* must be 0 (or -1).                                             */
1825   /*                                                                */
1826   static FT_Error
Mac_Read_POST_Resource(FT_Library library,FT_Stream stream,FT_Long * offsets,FT_Long resource_cnt,FT_Long face_index,FT_Face * aface)1827   Mac_Read_POST_Resource( FT_Library  library,
1828                           FT_Stream   stream,
1829                           FT_Long    *offsets,
1830                           FT_Long     resource_cnt,
1831                           FT_Long     face_index,
1832                           FT_Face    *aface )
1833   {
1834     FT_Error   error  = FT_ERR( Cannot_Open_Resource );
1835     FT_Memory  memory = library->memory;
1836 
1837     FT_Byte*   pfb_data = NULL;
1838     int        i, type, flags;
1839     FT_ULong   len;
1840     FT_ULong   pfb_len, pfb_pos, pfb_lenpos;
1841     FT_ULong   rlen, temp;
1842 
1843 
1844     if ( face_index == -1 )
1845       face_index = 0;
1846     if ( face_index != 0 )
1847       return error;
1848 
1849     /* Find the length of all the POST resources, concatenated.  Assume */
1850     /* worst case (each resource in its own section).                   */
1851     pfb_len = 0;
1852     for ( i = 0; i < resource_cnt; i++ )
1853     {
1854       error = FT_Stream_Seek( stream, (FT_ULong)offsets[i] );
1855       if ( error )
1856         goto Exit;
1857       if ( FT_READ_ULONG( temp ) )  /* actually LONG */
1858         goto Exit;
1859 
1860       /* FT2 allocator takes signed long buffer length,
1861        * too large value causing overflow should be checked
1862        */
1863       FT_TRACE4(( "                 POST fragment #%d: length=0x%08lx"
1864                   " total pfb_len=0x%08lx\n",
1865                   i, temp, pfb_len + temp + 6 ));
1866 
1867       if ( FT_MAC_RFORK_MAX_LEN < temp               ||
1868            FT_MAC_RFORK_MAX_LEN - temp < pfb_len + 6 )
1869       {
1870         FT_TRACE2(( "             MacOS resource length cannot exceed"
1871                     " 0x%08lx\n",
1872                     FT_MAC_RFORK_MAX_LEN ));
1873 
1874         error = FT_THROW( Invalid_Offset );
1875         goto Exit;
1876       }
1877 
1878       pfb_len += temp + 6;
1879     }
1880 
1881     FT_TRACE2(( "             total buffer size to concatenate"
1882                 " %ld POST fragments: 0x%08lx\n",
1883                  resource_cnt, pfb_len + 2 ));
1884 
1885     if ( pfb_len + 2 < 6 )
1886     {
1887       FT_TRACE2(( "             too long fragment length makes"
1888                   " pfb_len confused: pfb_len=0x%08lx\n",
1889                   pfb_len ));
1890 
1891       error = FT_THROW( Array_Too_Large );
1892       goto Exit;
1893     }
1894 
1895     if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
1896       goto Exit;
1897 
1898     pfb_data[0] = 0x80;
1899     pfb_data[1] = 1;            /* Ascii section */
1900     pfb_data[2] = 0;            /* 4-byte length, fill in later */
1901     pfb_data[3] = 0;
1902     pfb_data[4] = 0;
1903     pfb_data[5] = 0;
1904     pfb_pos     = 6;
1905     pfb_lenpos  = 2;
1906 
1907     len  = 0;
1908     type = 1;
1909 
1910     for ( i = 0; i < resource_cnt; i++ )
1911     {
1912       error = FT_Stream_Seek( stream, (FT_ULong)offsets[i] );
1913       if ( error )
1914         goto Exit2;
1915       if ( FT_READ_ULONG( rlen ) )
1916         goto Exit2;
1917 
1918       /* FT2 allocator takes signed long buffer length,
1919        * too large fragment length causing overflow should be checked
1920        */
1921       if ( 0x7FFFFFFFUL < rlen )
1922       {
1923         error = FT_THROW( Invalid_Offset );
1924         goto Exit2;
1925       }
1926 
1927       if ( FT_READ_USHORT( flags ) )
1928         goto Exit2;
1929 
1930       FT_TRACE3(( "POST fragment[%d]:"
1931                   " offsets=0x%08lx, rlen=0x%08lx, flags=0x%04x\n",
1932                   i, offsets[i], rlen, flags ));
1933 
1934       error = FT_ERR( Array_Too_Large );
1935 
1936       /* postpone the check of `rlen longer than buffer' */
1937       /* until `FT_Stream_Read'                          */
1938 
1939       if ( ( flags >> 8 ) == 0 )        /* Comment, should not be loaded */
1940       {
1941         FT_TRACE3(( "    Skip POST fragment #%d because it is a comment\n",
1942                     i ));
1943         continue;
1944       }
1945 
1946       /* the flags are part of the resource, so rlen >= 2,  */
1947       /* but some fonts declare rlen = 0 for empty fragment */
1948       if ( rlen > 2 )
1949         rlen -= 2;
1950       else
1951         rlen = 0;
1952 
1953       if ( ( flags >> 8 ) == type )
1954         len += rlen;
1955       else
1956       {
1957         FT_TRACE3(( "    Write POST fragment #%d header (4-byte) to buffer"
1958                     " %p + 0x%08lx\n",
1959                     i, pfb_data, pfb_lenpos ));
1960 
1961         if ( pfb_lenpos + 3 > pfb_len + 2 )
1962           goto Exit2;
1963 
1964         pfb_data[pfb_lenpos    ] = (FT_Byte)( len );
1965         pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
1966         pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
1967         pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
1968 
1969         if ( ( flags >> 8 ) == 5 )      /* End of font mark */
1970           break;
1971 
1972         FT_TRACE3(( "    Write POST fragment #%d header (6-byte) to buffer"
1973                     " %p + 0x%08lx\n",
1974                     i, pfb_data, pfb_pos ));
1975 
1976         if ( pfb_pos + 6 > pfb_len + 2 )
1977           goto Exit2;
1978 
1979         pfb_data[pfb_pos++] = 0x80;
1980 
1981         type = flags >> 8;
1982         len  = rlen;
1983 
1984         pfb_data[pfb_pos++] = (FT_Byte)type;
1985         pfb_lenpos          = pfb_pos;
1986         pfb_data[pfb_pos++] = 0;        /* 4-byte length, fill in later */
1987         pfb_data[pfb_pos++] = 0;
1988         pfb_data[pfb_pos++] = 0;
1989         pfb_data[pfb_pos++] = 0;
1990       }
1991 
1992       if ( pfb_pos > pfb_len || pfb_pos + rlen > pfb_len )
1993         goto Exit2;
1994 
1995       FT_TRACE3(( "    Load POST fragment #%d (%ld byte) to buffer"
1996                   " %p + 0x%08lx\n",
1997                   i, rlen, pfb_data, pfb_pos ));
1998 
1999       error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
2000       if ( error )
2001         goto Exit2;
2002 
2003       pfb_pos += rlen;
2004     }
2005 
2006     error = FT_ERR( Array_Too_Large );
2007 
2008     if ( pfb_pos + 2 > pfb_len + 2 )
2009       goto Exit2;
2010     pfb_data[pfb_pos++] = 0x80;
2011     pfb_data[pfb_pos++] = 3;
2012 
2013     if ( pfb_lenpos + 3 > pfb_len + 2 )
2014       goto Exit2;
2015     pfb_data[pfb_lenpos    ] = (FT_Byte)( len );
2016     pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
2017     pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
2018     pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
2019 
2020     return open_face_from_buffer( library,
2021                                   pfb_data,
2022                                   pfb_pos,
2023                                   face_index,
2024                                   "type1",
2025                                   aface );
2026 
2027   Exit2:
2028     if ( FT_ERR_EQ( error, Array_Too_Large ) )
2029       FT_TRACE2(( "  Abort due to too-short buffer to store"
2030                   " all POST fragments\n" ));
2031     else if ( FT_ERR_EQ( error, Invalid_Offset ) )
2032       FT_TRACE2(( "  Abort due to invalid offset in a POST fragment\n" ));
2033 
2034     if ( error )
2035       error = FT_ERR( Cannot_Open_Resource );
2036     FT_FREE( pfb_data );
2037 
2038   Exit:
2039     return error;
2040   }
2041 
2042 
2043   /* The resource header says we've got resource_cnt `sfnt'      */
2044   /* (TrueType/OpenType) resources in this file.  Look through   */
2045   /* them for the one indicated by face_index, load it into mem, */
2046   /* pass it on to the truetype driver, and return it.           */
2047   /*                                                             */
2048   static FT_Error
Mac_Read_sfnt_Resource(FT_Library library,FT_Stream stream,FT_Long * offsets,FT_Long resource_cnt,FT_Long face_index,FT_Face * aface)2049   Mac_Read_sfnt_Resource( FT_Library  library,
2050                           FT_Stream   stream,
2051                           FT_Long    *offsets,
2052                           FT_Long     resource_cnt,
2053                           FT_Long     face_index,
2054                           FT_Face    *aface )
2055   {
2056     FT_Memory  memory = library->memory;
2057     FT_Byte*   sfnt_data = NULL;
2058     FT_Error   error;
2059     FT_ULong   flag_offset;
2060     FT_Long    rlen;
2061     int        is_cff;
2062     FT_Long    face_index_in_resource = 0;
2063 
2064 
2065     if ( face_index < 0 )
2066       face_index = -face_index - 1;
2067     if ( face_index >= resource_cnt )
2068       return FT_THROW( Cannot_Open_Resource );
2069 
2070     flag_offset = (FT_ULong)offsets[face_index];
2071     error = FT_Stream_Seek( stream, flag_offset );
2072     if ( error )
2073       goto Exit;
2074 
2075     if ( FT_READ_LONG( rlen ) )
2076       goto Exit;
2077     if ( rlen < 1 )
2078       return FT_THROW( Cannot_Open_Resource );
2079     if ( (FT_ULong)rlen > FT_MAC_RFORK_MAX_LEN )
2080       return FT_THROW( Invalid_Offset );
2081 
2082     error = open_face_PS_from_sfnt_stream( library,
2083                                            stream,
2084                                            face_index,
2085                                            0, NULL,
2086                                            aface );
2087     if ( !error )
2088       goto Exit;
2089 
2090     /* rewind sfnt stream before open_face_PS_from_sfnt_stream() */
2091     error = FT_Stream_Seek( stream, flag_offset + 4 );
2092     if ( error )
2093       goto Exit;
2094 
2095     if ( FT_ALLOC( sfnt_data, rlen ) )
2096       return error;
2097     error = FT_Stream_Read( stream, (FT_Byte *)sfnt_data, (FT_ULong)rlen );
2098     if ( error ) {
2099       FT_FREE( sfnt_data );
2100       goto Exit;
2101     }
2102 
2103     is_cff = rlen > 4 && !ft_memcmp( sfnt_data, "OTTO", 4 );
2104     error = open_face_from_buffer( library,
2105                                    sfnt_data,
2106                                    (FT_ULong)rlen,
2107                                    face_index_in_resource,
2108                                    is_cff ? "cff" : "truetype",
2109                                    aface );
2110 
2111   Exit:
2112     return error;
2113   }
2114 
2115 
2116   /* Check for a valid resource fork header, or a valid dfont    */
2117   /* header.  In a resource fork the first 16 bytes are repeated */
2118   /* at the location specified by bytes 4-7.  In a dfont bytes   */
2119   /* 4-7 point to 16 bytes of zeroes instead.                    */
2120   /*                                                             */
2121   static FT_Error
IsMacResource(FT_Library library,FT_Stream stream,FT_Long resource_offset,FT_Long face_index,FT_Face * aface)2122   IsMacResource( FT_Library  library,
2123                  FT_Stream   stream,
2124                  FT_Long     resource_offset,
2125                  FT_Long     face_index,
2126                  FT_Face    *aface )
2127   {
2128     FT_Memory  memory = library->memory;
2129     FT_Error   error;
2130     FT_Long    map_offset, rdata_pos;
2131     FT_Long    *data_offsets;
2132     FT_Long    count;
2133 
2134 
2135     error = FT_Raccess_Get_HeaderInfo( library, stream, resource_offset,
2136                                        &map_offset, &rdata_pos );
2137     if ( error )
2138       return error;
2139 
2140     /* POST resources must be sorted to concatenate properly */
2141     error = FT_Raccess_Get_DataOffsets( library, stream,
2142                                         map_offset, rdata_pos,
2143                                         TTAG_POST, TRUE,
2144                                         &data_offsets, &count );
2145     if ( !error )
2146     {
2147       error = Mac_Read_POST_Resource( library, stream, data_offsets, count,
2148                                       face_index, aface );
2149       FT_FREE( data_offsets );
2150       /* POST exists in an LWFN providing a single face */
2151       if ( !error )
2152         (*aface)->num_faces = 1;
2153       return error;
2154     }
2155 
2156     /* sfnt resources should not be sorted to preserve the face order by
2157        QuickDraw API */
2158     error = FT_Raccess_Get_DataOffsets( library, stream,
2159                                         map_offset, rdata_pos,
2160                                         TTAG_sfnt, FALSE,
2161                                         &data_offsets, &count );
2162     if ( !error )
2163     {
2164       FT_Long  face_index_internal = face_index % count;
2165 
2166 
2167       error = Mac_Read_sfnt_Resource( library, stream, data_offsets, count,
2168                                       face_index_internal, aface );
2169       FT_FREE( data_offsets );
2170       if ( !error )
2171         (*aface)->num_faces = count;
2172     }
2173 
2174     return error;
2175   }
2176 
2177 
2178   /* Check for a valid macbinary header, and if we find one   */
2179   /* check that the (flattened) resource fork in it is valid. */
2180   /*                                                          */
2181   static FT_Error
IsMacBinary(FT_Library library,FT_Stream stream,FT_Long face_index,FT_Face * aface)2182   IsMacBinary( FT_Library  library,
2183                FT_Stream   stream,
2184                FT_Long     face_index,
2185                FT_Face    *aface )
2186   {
2187     unsigned char  header[128];
2188     FT_Error       error;
2189     FT_Long        dlen, offset;
2190 
2191 
2192     if ( !stream )
2193       return FT_THROW( Invalid_Stream_Operation );
2194 
2195     error = FT_Stream_Seek( stream, 0 );
2196     if ( error )
2197       goto Exit;
2198 
2199     error = FT_Stream_Read( stream, (FT_Byte*)header, 128 );
2200     if ( error )
2201       goto Exit;
2202 
2203     if (            header[ 0] !=   0 ||
2204                     header[74] !=   0 ||
2205                     header[82] !=   0 ||
2206                     header[ 1] ==   0 ||
2207                     header[ 1] >   33 ||
2208                     header[63] !=   0 ||
2209          header[2 + header[1]] !=   0 ||
2210                   header[0x53] > 0x7F )
2211       return FT_THROW( Unknown_File_Format );
2212 
2213     dlen = ( header[0x53] << 24 ) |
2214            ( header[0x54] << 16 ) |
2215            ( header[0x55] <<  8 ) |
2216              header[0x56];
2217 #if 0
2218     rlen = ( header[0x57] << 24 ) |
2219            ( header[0x58] << 16 ) |
2220            ( header[0x59] <<  8 ) |
2221              header[0x5A];
2222 #endif /* 0 */
2223     offset = 128 + ( ( dlen + 127 ) & ~127 );
2224 
2225     return IsMacResource( library, stream, offset, face_index, aface );
2226 
2227   Exit:
2228     return error;
2229   }
2230 
2231 
2232   static FT_Error
load_face_in_embedded_rfork(FT_Library library,FT_Stream stream,FT_Long face_index,FT_Face * aface,const FT_Open_Args * args)2233   load_face_in_embedded_rfork( FT_Library           library,
2234                                FT_Stream            stream,
2235                                FT_Long              face_index,
2236                                FT_Face             *aface,
2237                                const FT_Open_Args  *args )
2238   {
2239 
2240 #undef  FT_COMPONENT
2241 #define FT_COMPONENT  raccess
2242 
2243     FT_Memory  memory = library->memory;
2244     FT_Error   error  = FT_ERR( Unknown_File_Format );
2245     FT_UInt    i;
2246 
2247     char*      file_names[FT_RACCESS_N_RULES];
2248     FT_Long    offsets[FT_RACCESS_N_RULES];
2249     FT_Error   errors[FT_RACCESS_N_RULES];
2250     FT_Bool    is_darwin_vfs, vfs_rfork_has_no_font = FALSE; /* not tested */
2251 
2252     FT_Open_Args  args2;
2253     FT_Stream     stream2 = NULL;
2254 
2255 
2256     FT_Raccess_Guess( library, stream,
2257                       args->pathname, file_names, offsets, errors );
2258 
2259     for ( i = 0; i < FT_RACCESS_N_RULES; i++ )
2260     {
2261       is_darwin_vfs = ft_raccess_rule_by_darwin_vfs( library, i );
2262       if ( is_darwin_vfs && vfs_rfork_has_no_font )
2263       {
2264         FT_TRACE3(( "Skip rule %d: darwin vfs resource fork"
2265                     " is already checked and"
2266                     " no font is found\n",
2267                     i ));
2268         continue;
2269       }
2270 
2271       if ( errors[i] )
2272       {
2273         FT_TRACE3(( "Error 0x%x has occurred in rule %d\n",
2274                     errors[i], i ));
2275         continue;
2276       }
2277 
2278       args2.flags    = FT_OPEN_PATHNAME;
2279       args2.pathname = file_names[i] ? file_names[i] : args->pathname;
2280 
2281       FT_TRACE3(( "Try rule %d: %s (offset=%ld) ...",
2282                   i, args2.pathname, offsets[i] ));
2283 
2284       error = FT_Stream_New( library, &args2, &stream2 );
2285       if ( is_darwin_vfs && FT_ERR_EQ( error, Cannot_Open_Stream ) )
2286         vfs_rfork_has_no_font = TRUE;
2287 
2288       if ( error )
2289       {
2290         FT_TRACE3(( "failed\n" ));
2291         continue;
2292       }
2293 
2294       error = IsMacResource( library, stream2, offsets[i],
2295                              face_index, aface );
2296       FT_Stream_Free( stream2, 0 );
2297 
2298       FT_TRACE3(( "%s\n", error ? "failed": "successful" ));
2299 
2300       if ( !error )
2301           break;
2302       else if ( is_darwin_vfs )
2303           vfs_rfork_has_no_font = TRUE;
2304     }
2305 
2306     for (i = 0; i < FT_RACCESS_N_RULES; i++)
2307     {
2308       if ( file_names[i] )
2309         FT_FREE( file_names[i] );
2310     }
2311 
2312     /* Caller (load_mac_face) requires FT_Err_Unknown_File_Format. */
2313     if ( error )
2314       error = FT_ERR( Unknown_File_Format );
2315 
2316     return error;
2317 
2318 #undef  FT_COMPONENT
2319 #define FT_COMPONENT  objs
2320 
2321   }
2322 
2323 
2324   /* Check for some macintosh formats without Carbon framework.    */
2325   /* Is this a macbinary file?  If so look at the resource fork.   */
2326   /* Is this a mac dfont file?                                     */
2327   /* Is this an old style resource fork? (in data)                 */
2328   /* Else call load_face_in_embedded_rfork to try extra rules      */
2329   /* (defined in `ftrfork.c').                                     */
2330   /*                                                               */
2331   static FT_Error
load_mac_face(FT_Library library,FT_Stream stream,FT_Long face_index,FT_Face * aface,const FT_Open_Args * args)2332   load_mac_face( FT_Library           library,
2333                  FT_Stream            stream,
2334                  FT_Long              face_index,
2335                  FT_Face             *aface,
2336                  const FT_Open_Args  *args )
2337   {
2338     FT_Error error;
2339     FT_UNUSED( args );
2340 
2341 
2342     error = IsMacBinary( library, stream, face_index, aface );
2343     if ( FT_ERR_EQ( error, Unknown_File_Format ) )
2344     {
2345 
2346 #undef  FT_COMPONENT
2347 #define FT_COMPONENT  raccess
2348 
2349 #ifdef FT_DEBUG_LEVEL_TRACE
2350       FT_TRACE3(( "Try as dfont: " ));
2351       if ( !( args->flags & FT_OPEN_MEMORY ) )
2352         FT_TRACE3(( "%s ...", args->pathname ));
2353 #endif
2354 
2355       error = IsMacResource( library, stream, 0, face_index, aface );
2356 
2357       FT_TRACE3(( "%s\n", error ? "failed" : "successful" ));
2358 
2359 #undef  FT_COMPONENT
2360 #define FT_COMPONENT  objs
2361 
2362     }
2363 
2364     if ( ( FT_ERR_EQ( error, Unknown_File_Format )      ||
2365            FT_ERR_EQ( error, Invalid_Stream_Operation ) ) &&
2366          ( args->flags & FT_OPEN_PATHNAME )               )
2367       error = load_face_in_embedded_rfork( library, stream,
2368                                            face_index, aface, args );
2369     return error;
2370   }
2371 #endif
2372 
2373 #endif  /* !FT_MACINTOSH && FT_CONFIG_OPTION_MAC_FONTS */
2374 
2375 
2376   /* documentation is in freetype.h */
2377 
2378   FT_EXPORT_DEF( FT_Error )
FT_Open_Face(FT_Library library,const FT_Open_Args * args,FT_Long face_index,FT_Face * aface)2379   FT_Open_Face( FT_Library           library,
2380                 const FT_Open_Args*  args,
2381                 FT_Long              face_index,
2382                 FT_Face             *aface )
2383   {
2384     return ft_open_face_internal( library, args, face_index, aface, 1 );
2385   }
2386 
2387 
2388   static FT_Error
ft_open_face_internal(FT_Library library,const FT_Open_Args * args,FT_Long face_index,FT_Face * aface,FT_Bool test_mac_fonts)2389   ft_open_face_internal( FT_Library           library,
2390                          const FT_Open_Args*  args,
2391                          FT_Long              face_index,
2392                          FT_Face             *aface,
2393                          FT_Bool              test_mac_fonts )
2394   {
2395     FT_Error     error;
2396     FT_Driver    driver = NULL;
2397     FT_Memory    memory = NULL;
2398     FT_Stream    stream = NULL;
2399     FT_Face      face   = NULL;
2400     FT_ListNode  node   = NULL;
2401     FT_Bool      external_stream;
2402     FT_Module*   cur;
2403     FT_Module*   limit;
2404 
2405 #ifndef FT_CONFIG_OPTION_MAC_FONTS
2406     FT_UNUSED( test_mac_fonts );
2407 #endif
2408 
2409 
2410     /* only use lower 31 bits together with sign bit */
2411     if( face_index > 0 )
2412       face_index &= 0x7FFFFFFFL;
2413     else
2414     {
2415       face_index &= 0x7FFFFFFFL;
2416       face_index = -face_index;
2417     }
2418 
2419 #ifdef FT_DEBUG_LEVEL_TRACE
2420     FT_TRACE3(( "FT_Open_Face: " ));
2421     if ( face_index < 0 )
2422       FT_TRACE3(( "Requesting number of faces and named instances\n"));
2423     else
2424     {
2425       FT_TRACE3(( "Requesting face %ld", face_index & 0xFFFFL ));
2426       if ( face_index & 0x7FFF0000L )
2427         FT_TRACE3(( ", named instance %ld", face_index >> 16 ));
2428       FT_TRACE3(( "\n" ));
2429     }
2430 #endif
2431 
2432     /* test for valid `library' delayed to `FT_Stream_New' */
2433 
2434     if ( ( !aface && face_index >= 0 ) || !args )
2435       return FT_THROW( Invalid_Argument );
2436 
2437     external_stream = FT_BOOL( ( args->flags & FT_OPEN_STREAM ) &&
2438                                args->stream                     );
2439 
2440     /* create input stream */
2441     error = FT_Stream_New( library, args, &stream );
2442     if ( error )
2443       goto Fail3;
2444 
2445     memory = library->memory;
2446 
2447     /* If the font driver is specified in the `args' structure, use */
2448     /* it.  Otherwise, we scan the list of registered drivers.      */
2449     if ( ( args->flags & FT_OPEN_DRIVER ) && args->driver )
2450     {
2451       driver = FT_DRIVER( args->driver );
2452 
2453       /* not all modules are drivers, so check... */
2454       if ( FT_MODULE_IS_DRIVER( driver ) )
2455       {
2456         FT_Int         num_params = 0;
2457         FT_Parameter*  params     = NULL;
2458 
2459 
2460         if ( args->flags & FT_OPEN_PARAMS )
2461         {
2462           num_params = args->num_params;
2463           params     = args->params;
2464         }
2465 
2466         error = open_face( driver, &stream, external_stream, face_index,
2467                            num_params, params, &face );
2468         if ( !error )
2469           goto Success;
2470       }
2471       else
2472         error = FT_THROW( Invalid_Handle );
2473 
2474       FT_Stream_Free( stream, external_stream );
2475       goto Fail;
2476     }
2477     else
2478     {
2479       error = FT_ERR( Missing_Module );
2480 
2481       /* check each font driver for an appropriate format */
2482       cur   = library->modules;
2483       limit = cur + library->num_modules;
2484 
2485       for ( ; cur < limit; cur++ )
2486       {
2487         /* not all modules are font drivers, so check... */
2488         if ( FT_MODULE_IS_DRIVER( cur[0] ) )
2489         {
2490           FT_Int         num_params = 0;
2491           FT_Parameter*  params     = NULL;
2492 
2493 
2494           driver = FT_DRIVER( cur[0] );
2495 
2496           if ( args->flags & FT_OPEN_PARAMS )
2497           {
2498             num_params = args->num_params;
2499             params     = args->params;
2500           }
2501 
2502           error = open_face( driver, &stream, external_stream, face_index,
2503                              num_params, params, &face );
2504           if ( !error )
2505             goto Success;
2506 
2507 #ifdef FT_CONFIG_OPTION_MAC_FONTS
2508           if ( test_mac_fonts                                           &&
2509                ft_strcmp( cur[0]->clazz->module_name, "truetype" ) == 0 &&
2510                FT_ERR_EQ( error, Table_Missing )                        )
2511           {
2512             /* TrueType but essential tables are missing */
2513             error = FT_Stream_Seek( stream, 0 );
2514             if ( error )
2515               break;
2516 
2517             error = open_face_PS_from_sfnt_stream( library,
2518                                                    stream,
2519                                                    face_index,
2520                                                    num_params,
2521                                                    params,
2522                                                    aface );
2523             if ( !error )
2524             {
2525               FT_Stream_Free( stream, external_stream );
2526               return error;
2527             }
2528           }
2529 #endif
2530 
2531           if ( FT_ERR_NEQ( error, Unknown_File_Format ) )
2532             goto Fail3;
2533         }
2534       }
2535 
2536     Fail3:
2537       /* If we are on the mac, and we get an                          */
2538       /* FT_Err_Invalid_Stream_Operation it may be because we have an */
2539       /* empty data fork, so we need to check the resource fork.      */
2540       if ( FT_ERR_NEQ( error, Cannot_Open_Stream )       &&
2541            FT_ERR_NEQ( error, Unknown_File_Format )      &&
2542            FT_ERR_NEQ( error, Invalid_Stream_Operation ) )
2543         goto Fail2;
2544 
2545 #if !defined( FT_MACINTOSH ) && defined( FT_CONFIG_OPTION_MAC_FONTS )
2546       if ( test_mac_fonts )
2547       {
2548         error = load_mac_face( library, stream, face_index, aface, args );
2549         if ( !error )
2550         {
2551           /* We don't want to go to Success here.  We've already done   */
2552           /* that.  On the other hand, if we succeeded we still need to */
2553           /* close this stream (we opened a different stream which      */
2554           /* extracted the interesting information out of this stream   */
2555           /* here.  That stream will still be open and the face will    */
2556           /* point to it).                                              */
2557           FT_Stream_Free( stream, external_stream );
2558           return error;
2559         }
2560       }
2561 
2562       if ( FT_ERR_NEQ( error, Unknown_File_Format ) )
2563         goto Fail2;
2564 #endif  /* !FT_MACINTOSH && FT_CONFIG_OPTION_MAC_FONTS */
2565 
2566       /* no driver is able to handle this format */
2567       error = FT_THROW( Unknown_File_Format );
2568 
2569   Fail2:
2570       FT_Stream_Free( stream, external_stream );
2571       goto Fail;
2572     }
2573 
2574   Success:
2575     FT_TRACE4(( "FT_Open_Face: New face object, adding to list\n" ));
2576 
2577     /* add the face object to its driver's list */
2578     if ( FT_NEW( node ) )
2579       goto Fail;
2580 
2581     node->data = face;
2582     /* don't assume driver is the same as face->driver, so use */
2583     /* face->driver instead.                                   */
2584     FT_List_Add( &face->driver->faces_list, node );
2585 
2586     /* now allocate a glyph slot object for the face */
2587     FT_TRACE4(( "FT_Open_Face: Creating glyph slot\n" ));
2588 
2589     if ( face_index >= 0 )
2590     {
2591       error = FT_New_GlyphSlot( face, NULL );
2592       if ( error )
2593         goto Fail;
2594 
2595       /* finally, allocate a size object for the face */
2596       {
2597         FT_Size  size;
2598 
2599 
2600         FT_TRACE4(( "FT_Open_Face: Creating size object\n" ));
2601 
2602         error = FT_New_Size( face, &size );
2603         if ( error )
2604           goto Fail;
2605 
2606         face->size = size;
2607       }
2608     }
2609 
2610     /* some checks */
2611 
2612     if ( FT_IS_SCALABLE( face ) )
2613     {
2614       if ( face->height < 0 )
2615         face->height = (FT_Short)-face->height;
2616 
2617       if ( !FT_HAS_VERTICAL( face ) )
2618         face->max_advance_height = (FT_Short)face->height;
2619     }
2620 
2621     if ( FT_HAS_FIXED_SIZES( face ) )
2622     {
2623       FT_Int  i;
2624 
2625 
2626       for ( i = 0; i < face->num_fixed_sizes; i++ )
2627       {
2628         FT_Bitmap_Size*  bsize = face->available_sizes + i;
2629 
2630 
2631         if ( bsize->height < 0 )
2632           bsize->height = -bsize->height;
2633         if ( bsize->x_ppem < 0 )
2634           bsize->x_ppem = -bsize->x_ppem;
2635         if ( bsize->y_ppem < 0 )
2636           bsize->y_ppem = -bsize->y_ppem;
2637 
2638         /* check whether negation actually has worked */
2639         if ( bsize->height < 0 || bsize->x_ppem < 0 || bsize->y_ppem < 0 )
2640         {
2641           FT_TRACE0(( "FT_Open_Face:"
2642                       " Invalid bitmap dimensions for strike %d,"
2643                       " now disabled\n", i ));
2644           bsize->width  = 0;
2645           bsize->height = 0;
2646           bsize->size   = 0;
2647           bsize->x_ppem = 0;
2648           bsize->y_ppem = 0;
2649         }
2650       }
2651     }
2652 
2653     /* initialize internal face data */
2654     {
2655       FT_Face_Internal  internal = face->internal;
2656 
2657 
2658       internal->transform_matrix.xx = 0x10000L;
2659       internal->transform_matrix.xy = 0;
2660       internal->transform_matrix.yx = 0;
2661       internal->transform_matrix.yy = 0x10000L;
2662 
2663       internal->transform_delta.x = 0;
2664       internal->transform_delta.y = 0;
2665 
2666       internal->refcount = 1;
2667 
2668       internal->no_stem_darkening = -1;
2669 
2670 #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
2671       /* Per-face filtering can only be set up by FT_Face_Properties */
2672       internal->lcd_filter_func = NULL;
2673 #endif
2674     }
2675 
2676     if ( aface )
2677       *aface = face;
2678     else
2679       FT_Done_Face( face );
2680 
2681     goto Exit;
2682 
2683   Fail:
2684     if ( node )
2685       FT_Done_Face( face );    /* face must be in the driver's list */
2686     else if ( face )
2687       destroy_face( memory, face, driver );
2688 
2689   Exit:
2690 #ifdef FT_DEBUG_LEVEL_TRACE
2691     if ( !error && face_index < 0 )
2692     {
2693       FT_TRACE3(( "FT_Open_Face: The font has %ld face%s\n"
2694                   "              and %ld named instance%s for face %ld\n",
2695                   face->num_faces,
2696                   face->num_faces == 1 ? "" : "s",
2697                   face->style_flags >> 16,
2698                   ( face->style_flags >> 16 ) == 1 ? "" : "s",
2699                   -face_index - 1 ));
2700     }
2701 #endif
2702 
2703     FT_TRACE4(( "FT_Open_Face: Return 0x%x\n", error ));
2704 
2705     return error;
2706   }
2707 
2708 
2709   /* documentation is in freetype.h */
2710 
2711   FT_EXPORT_DEF( FT_Error )
FT_Attach_File(FT_Face face,const char * filepathname)2712   FT_Attach_File( FT_Face      face,
2713                   const char*  filepathname )
2714   {
2715     FT_Open_Args  open;
2716 
2717 
2718     /* test for valid `face' delayed to `FT_Attach_Stream' */
2719 
2720     if ( !filepathname )
2721       return FT_THROW( Invalid_Argument );
2722 
2723     open.stream   = NULL;
2724     open.flags    = FT_OPEN_PATHNAME;
2725     open.pathname = (char*)filepathname;
2726 
2727     return FT_Attach_Stream( face, &open );
2728   }
2729 
2730 
2731   /* documentation is in freetype.h */
2732 
2733   FT_EXPORT_DEF( FT_Error )
FT_Attach_Stream(FT_Face face,FT_Open_Args * parameters)2734   FT_Attach_Stream( FT_Face        face,
2735                     FT_Open_Args*  parameters )
2736   {
2737     FT_Stream  stream;
2738     FT_Error   error;
2739     FT_Driver  driver;
2740 
2741     FT_Driver_Class  clazz;
2742 
2743 
2744     /* test for valid `parameters' delayed to `FT_Stream_New' */
2745 
2746     if ( !face )
2747       return FT_THROW( Invalid_Face_Handle );
2748 
2749     driver = face->driver;
2750     if ( !driver )
2751       return FT_THROW( Invalid_Driver_Handle );
2752 
2753     error = FT_Stream_New( driver->root.library, parameters, &stream );
2754     if ( error )
2755       goto Exit;
2756 
2757     /* we implement FT_Attach_Stream in each driver through the */
2758     /* `attach_file' interface                                  */
2759 
2760     error = FT_ERR( Unimplemented_Feature );
2761     clazz = driver->clazz;
2762     if ( clazz->attach_file )
2763       error = clazz->attach_file( face, stream );
2764 
2765     /* close the attached stream */
2766     FT_Stream_Free( stream,
2767                     FT_BOOL( parameters->stream                     &&
2768                              ( parameters->flags & FT_OPEN_STREAM ) ) );
2769 
2770   Exit:
2771     return error;
2772   }
2773 
2774 
2775   /* documentation is in freetype.h */
2776 
2777   FT_EXPORT_DEF( FT_Error )
FT_Reference_Face(FT_Face face)2778   FT_Reference_Face( FT_Face  face )
2779   {
2780     if ( !face )
2781       return FT_THROW( Invalid_Face_Handle );
2782 
2783     face->internal->refcount++;
2784 
2785     return FT_Err_Ok;
2786   }
2787 
2788 
2789   /* documentation is in freetype.h */
2790 
2791   FT_EXPORT_DEF( FT_Error )
FT_Done_Face(FT_Face face)2792   FT_Done_Face( FT_Face  face )
2793   {
2794     FT_Error     error;
2795     FT_Driver    driver;
2796     FT_Memory    memory;
2797     FT_ListNode  node;
2798 
2799 
2800     error = FT_ERR( Invalid_Face_Handle );
2801     if ( face && face->driver )
2802     {
2803       face->internal->refcount--;
2804       if ( face->internal->refcount > 0 )
2805         error = FT_Err_Ok;
2806       else
2807       {
2808         driver = face->driver;
2809         memory = driver->root.memory;
2810 
2811         /* find face in driver's list */
2812         node = FT_List_Find( &driver->faces_list, face );
2813         if ( node )
2814         {
2815           /* remove face object from the driver's list */
2816           FT_List_Remove( &driver->faces_list, node );
2817           FT_FREE( node );
2818 
2819           /* now destroy the object proper */
2820           destroy_face( memory, face, driver );
2821           error = FT_Err_Ok;
2822         }
2823       }
2824     }
2825 
2826     return error;
2827   }
2828 
2829 
2830   /* documentation is in ftobjs.h */
2831 
2832   FT_EXPORT_DEF( FT_Error )
FT_New_Size(FT_Face face,FT_Size * asize)2833   FT_New_Size( FT_Face   face,
2834                FT_Size  *asize )
2835   {
2836     FT_Error         error;
2837     FT_Memory        memory;
2838     FT_Driver        driver;
2839     FT_Driver_Class  clazz;
2840 
2841     FT_Size          size = NULL;
2842     FT_ListNode      node = NULL;
2843 
2844     FT_Size_Internal  internal = NULL;
2845 
2846 
2847     if ( !face )
2848       return FT_THROW( Invalid_Face_Handle );
2849 
2850     if ( !asize )
2851       return FT_THROW( Invalid_Argument );
2852 
2853     if ( !face->driver )
2854       return FT_THROW( Invalid_Driver_Handle );
2855 
2856     *asize = NULL;
2857 
2858     driver = face->driver;
2859     clazz  = driver->clazz;
2860     memory = face->memory;
2861 
2862     /* Allocate new size object and perform basic initialisation */
2863     if ( FT_ALLOC( size, clazz->size_object_size ) || FT_NEW( node ) )
2864       goto Exit;
2865 
2866     size->face = face;
2867 
2868     if ( FT_NEW( internal ) )
2869       goto Exit;
2870 
2871     size->internal = internal;
2872 
2873     if ( clazz->init_size )
2874       error = clazz->init_size( size );
2875 
2876     /* in case of success, add to the face's list */
2877     if ( !error )
2878     {
2879       *asize     = size;
2880       node->data = size;
2881       FT_List_Add( &face->sizes_list, node );
2882     }
2883 
2884   Exit:
2885     if ( error )
2886     {
2887       FT_FREE( node );
2888       if ( size )
2889         FT_FREE( size->internal );
2890       FT_FREE( size );
2891     }
2892 
2893     return error;
2894   }
2895 
2896 
2897   /* documentation is in ftobjs.h */
2898 
2899   FT_EXPORT_DEF( FT_Error )
FT_Done_Size(FT_Size size)2900   FT_Done_Size( FT_Size  size )
2901   {
2902     FT_Error     error;
2903     FT_Driver    driver;
2904     FT_Memory    memory;
2905     FT_Face      face;
2906     FT_ListNode  node;
2907 
2908 
2909     if ( !size )
2910       return FT_THROW( Invalid_Size_Handle );
2911 
2912     face = size->face;
2913     if ( !face )
2914       return FT_THROW( Invalid_Face_Handle );
2915 
2916     driver = face->driver;
2917     if ( !driver )
2918       return FT_THROW( Invalid_Driver_Handle );
2919 
2920     memory = driver->root.memory;
2921 
2922     error = FT_Err_Ok;
2923     node  = FT_List_Find( &face->sizes_list, size );
2924     if ( node )
2925     {
2926       FT_List_Remove( &face->sizes_list, node );
2927       FT_FREE( node );
2928 
2929       if ( face->size == size )
2930       {
2931         face->size = NULL;
2932         if ( face->sizes_list.head )
2933           face->size = (FT_Size)(face->sizes_list.head->data);
2934       }
2935 
2936       destroy_size( memory, size, driver );
2937     }
2938     else
2939       error = FT_THROW( Invalid_Size_Handle );
2940 
2941     return error;
2942   }
2943 
2944 
2945   /* documentation is in ftobjs.h */
2946 
2947   FT_BASE_DEF( FT_Error )
FT_Match_Size(FT_Face face,FT_Size_Request req,FT_Bool ignore_width,FT_ULong * size_index)2948   FT_Match_Size( FT_Face          face,
2949                  FT_Size_Request  req,
2950                  FT_Bool          ignore_width,
2951                  FT_ULong*        size_index )
2952   {
2953     FT_Int   i;
2954     FT_Long  w, h;
2955 
2956 
2957     if ( !FT_HAS_FIXED_SIZES( face ) )
2958       return FT_THROW( Invalid_Face_Handle );
2959 
2960     /* FT_Bitmap_Size doesn't provide enough info... */
2961     if ( req->type != FT_SIZE_REQUEST_TYPE_NOMINAL )
2962       return FT_THROW( Unimplemented_Feature );
2963 
2964     w = FT_REQUEST_WIDTH ( req );
2965     h = FT_REQUEST_HEIGHT( req );
2966 
2967     if ( req->width && !req->height )
2968       h = w;
2969     else if ( !req->width && req->height )
2970       w = h;
2971 
2972     w = FT_PIX_ROUND( w );
2973     h = FT_PIX_ROUND( h );
2974 
2975     if ( !w || !h )
2976       return FT_THROW( Invalid_Pixel_Size );
2977 
2978     for ( i = 0; i < face->num_fixed_sizes; i++ )
2979     {
2980       FT_Bitmap_Size*  bsize = face->available_sizes + i;
2981 
2982 
2983       if ( h != FT_PIX_ROUND( bsize->y_ppem ) )
2984         continue;
2985 
2986       if ( w == FT_PIX_ROUND( bsize->x_ppem ) || ignore_width )
2987       {
2988         FT_TRACE3(( "FT_Match_Size: bitmap strike %d matches\n", i ));
2989 
2990         if ( size_index )
2991           *size_index = (FT_ULong)i;
2992 
2993         return FT_Err_Ok;
2994       }
2995     }
2996 
2997     FT_TRACE3(( "FT_Match_Size: no matching bitmap strike\n" ));
2998 
2999     return FT_THROW( Invalid_Pixel_Size );
3000   }
3001 
3002 
3003   /* documentation is in ftobjs.h */
3004 
3005   FT_BASE_DEF( void )
ft_synthesize_vertical_metrics(FT_Glyph_Metrics * metrics,FT_Pos advance)3006   ft_synthesize_vertical_metrics( FT_Glyph_Metrics*  metrics,
3007                                   FT_Pos             advance )
3008   {
3009     FT_Pos  height = metrics->height;
3010 
3011 
3012     /* compensate for glyph with bbox above/below the baseline */
3013     if ( metrics->horiBearingY < 0 )
3014     {
3015       if ( height < metrics->horiBearingY )
3016         height = metrics->horiBearingY;
3017     }
3018     else if ( metrics->horiBearingY > 0 )
3019       height -= metrics->horiBearingY;
3020 
3021     /* the factor 1.2 is a heuristical value */
3022     if ( !advance )
3023       advance = height * 12 / 10;
3024 
3025     metrics->vertBearingX = metrics->horiBearingX - metrics->horiAdvance / 2;
3026     metrics->vertBearingY = ( advance - height ) / 2;
3027     metrics->vertAdvance  = advance;
3028   }
3029 
3030 
3031   static void
ft_recompute_scaled_metrics(FT_Face face,FT_Size_Metrics * metrics)3032   ft_recompute_scaled_metrics( FT_Face           face,
3033                                FT_Size_Metrics*  metrics )
3034   {
3035     /* Compute root ascender, descender, test height, and max_advance */
3036 
3037 #ifdef GRID_FIT_METRICS
3038     metrics->ascender    = FT_PIX_CEIL( FT_MulFix( face->ascender,
3039                                                    metrics->y_scale ) );
3040 
3041     metrics->descender   = FT_PIX_FLOOR( FT_MulFix( face->descender,
3042                                                     metrics->y_scale ) );
3043 
3044     metrics->height      = FT_PIX_ROUND( FT_MulFix( face->height,
3045                                                     metrics->y_scale ) );
3046 
3047     metrics->max_advance = FT_PIX_ROUND( FT_MulFix( face->max_advance_width,
3048                                                     metrics->x_scale ) );
3049 #else /* !GRID_FIT_METRICS */
3050     metrics->ascender    = FT_MulFix( face->ascender,
3051                                       metrics->y_scale );
3052 
3053     metrics->descender   = FT_MulFix( face->descender,
3054                                       metrics->y_scale );
3055 
3056     metrics->height      = FT_MulFix( face->height,
3057                                       metrics->y_scale );
3058 
3059     metrics->max_advance = FT_MulFix( face->max_advance_width,
3060                                       metrics->x_scale );
3061 #endif /* !GRID_FIT_METRICS */
3062   }
3063 
3064 
3065   FT_BASE_DEF( void )
FT_Select_Metrics(FT_Face face,FT_ULong strike_index)3066   FT_Select_Metrics( FT_Face   face,
3067                      FT_ULong  strike_index )
3068   {
3069     FT_Size_Metrics*  metrics;
3070     FT_Bitmap_Size*   bsize;
3071 
3072 
3073     metrics = &face->size->metrics;
3074     bsize   = face->available_sizes + strike_index;
3075 
3076     metrics->x_ppem = (FT_UShort)( ( bsize->x_ppem + 32 ) >> 6 );
3077     metrics->y_ppem = (FT_UShort)( ( bsize->y_ppem + 32 ) >> 6 );
3078 
3079     if ( FT_IS_SCALABLE( face ) )
3080     {
3081       metrics->x_scale = FT_DivFix( bsize->x_ppem,
3082                                     face->units_per_EM );
3083       metrics->y_scale = FT_DivFix( bsize->y_ppem,
3084                                     face->units_per_EM );
3085 
3086       ft_recompute_scaled_metrics( face, metrics );
3087     }
3088     else
3089     {
3090       metrics->x_scale     = 1L << 16;
3091       metrics->y_scale     = 1L << 16;
3092       metrics->ascender    = bsize->y_ppem;
3093       metrics->descender   = 0;
3094       metrics->height      = bsize->height << 6;
3095       metrics->max_advance = bsize->x_ppem;
3096     }
3097   }
3098 
3099 
3100   FT_BASE_DEF( void )
FT_Request_Metrics(FT_Face face,FT_Size_Request req)3101   FT_Request_Metrics( FT_Face          face,
3102                       FT_Size_Request  req )
3103   {
3104     FT_Size_Metrics*  metrics;
3105 
3106 
3107     metrics = &face->size->metrics;
3108 
3109     if ( FT_IS_SCALABLE( face ) )
3110     {
3111       FT_Long  w = 0, h = 0, scaled_w = 0, scaled_h = 0;
3112 
3113 
3114       switch ( req->type )
3115       {
3116       case FT_SIZE_REQUEST_TYPE_NOMINAL:
3117         w = h = face->units_per_EM;
3118         break;
3119 
3120       case FT_SIZE_REQUEST_TYPE_REAL_DIM:
3121         w = h = face->ascender - face->descender;
3122         break;
3123 
3124       case FT_SIZE_REQUEST_TYPE_BBOX:
3125         w = face->bbox.xMax - face->bbox.xMin;
3126         h = face->bbox.yMax - face->bbox.yMin;
3127         break;
3128 
3129       case FT_SIZE_REQUEST_TYPE_CELL:
3130         w = face->max_advance_width;
3131         h = face->ascender - face->descender;
3132         break;
3133 
3134       case FT_SIZE_REQUEST_TYPE_SCALES:
3135         metrics->x_scale = (FT_Fixed)req->width;
3136         metrics->y_scale = (FT_Fixed)req->height;
3137         if ( !metrics->x_scale )
3138           metrics->x_scale = metrics->y_scale;
3139         else if ( !metrics->y_scale )
3140           metrics->y_scale = metrics->x_scale;
3141         goto Calculate_Ppem;
3142 
3143       case FT_SIZE_REQUEST_TYPE_MAX:
3144         break;
3145       }
3146 
3147       /* to be on the safe side */
3148       if ( w < 0 )
3149         w = -w;
3150 
3151       if ( h < 0 )
3152         h = -h;
3153 
3154       scaled_w = FT_REQUEST_WIDTH ( req );
3155       scaled_h = FT_REQUEST_HEIGHT( req );
3156 
3157       /* determine scales */
3158       if ( req->width )
3159       {
3160         metrics->x_scale = FT_DivFix( scaled_w, w );
3161 
3162         if ( req->height )
3163         {
3164           metrics->y_scale = FT_DivFix( scaled_h, h );
3165 
3166           if ( req->type == FT_SIZE_REQUEST_TYPE_CELL )
3167           {
3168             if ( metrics->y_scale > metrics->x_scale )
3169               metrics->y_scale = metrics->x_scale;
3170             else
3171               metrics->x_scale = metrics->y_scale;
3172           }
3173         }
3174         else
3175         {
3176           metrics->y_scale = metrics->x_scale;
3177           scaled_h = FT_MulDiv( scaled_w, h, w );
3178         }
3179       }
3180       else
3181       {
3182         metrics->x_scale = metrics->y_scale = FT_DivFix( scaled_h, h );
3183         scaled_w = FT_MulDiv( scaled_h, w, h );
3184       }
3185 
3186   Calculate_Ppem:
3187       /* calculate the ppems */
3188       if ( req->type != FT_SIZE_REQUEST_TYPE_NOMINAL )
3189       {
3190         scaled_w = FT_MulFix( face->units_per_EM, metrics->x_scale );
3191         scaled_h = FT_MulFix( face->units_per_EM, metrics->y_scale );
3192       }
3193 
3194       metrics->x_ppem = (FT_UShort)( ( scaled_w + 32 ) >> 6 );
3195       metrics->y_ppem = (FT_UShort)( ( scaled_h + 32 ) >> 6 );
3196 
3197       ft_recompute_scaled_metrics( face, metrics );
3198     }
3199     else
3200     {
3201       FT_ZERO( metrics );
3202       metrics->x_scale = 1L << 16;
3203       metrics->y_scale = 1L << 16;
3204     }
3205   }
3206 
3207 
3208   /* documentation is in freetype.h */
3209 
3210   FT_EXPORT_DEF( FT_Error )
FT_Select_Size(FT_Face face,FT_Int strike_index)3211   FT_Select_Size( FT_Face  face,
3212                   FT_Int   strike_index )
3213   {
3214     FT_Error         error = FT_Err_Ok;
3215     FT_Driver_Class  clazz;
3216 
3217 
3218     if ( !face || !FT_HAS_FIXED_SIZES( face ) )
3219       return FT_THROW( Invalid_Face_Handle );
3220 
3221     if ( strike_index < 0 || strike_index >= face->num_fixed_sizes )
3222       return FT_THROW( Invalid_Argument );
3223 
3224     clazz = face->driver->clazz;
3225 
3226     if ( clazz->select_size )
3227     {
3228       error = clazz->select_size( face->size, (FT_ULong)strike_index );
3229 
3230       FT_TRACE5(( "FT_Select_Size (%s driver):\n",
3231                   face->driver->root.clazz->module_name ));
3232     }
3233     else
3234     {
3235       FT_Select_Metrics( face, (FT_ULong)strike_index );
3236 
3237       FT_TRACE5(( "FT_Select_Size:\n" ));
3238     }
3239 
3240 #ifdef FT_DEBUG_LEVEL_TRACE
3241     {
3242       FT_Size_Metrics*  metrics = &face->size->metrics;
3243 
3244 
3245       FT_TRACE5(( "  x scale: %ld (%f)\n",
3246                   metrics->x_scale, metrics->x_scale / 65536.0 ));
3247       FT_TRACE5(( "  y scale: %ld (%f)\n",
3248                   metrics->y_scale, metrics->y_scale / 65536.0 ));
3249       FT_TRACE5(( "  ascender: %f\n",    metrics->ascender / 64.0 ));
3250       FT_TRACE5(( "  descender: %f\n",   metrics->descender / 64.0 ));
3251       FT_TRACE5(( "  height: %f\n",      metrics->height / 64.0 ));
3252       FT_TRACE5(( "  max advance: %f\n", metrics->max_advance / 64.0 ));
3253       FT_TRACE5(( "  x ppem: %d\n",      metrics->x_ppem ));
3254       FT_TRACE5(( "  y ppem: %d\n",      metrics->y_ppem ));
3255     }
3256 #endif
3257 
3258     return error;
3259   }
3260 
3261 
3262   /* documentation is in freetype.h */
3263 
3264   FT_EXPORT_DEF( FT_Error )
FT_Request_Size(FT_Face face,FT_Size_Request req)3265   FT_Request_Size( FT_Face          face,
3266                    FT_Size_Request  req )
3267   {
3268     FT_Error         error = FT_Err_Ok;
3269     FT_Driver_Class  clazz;
3270     FT_ULong         strike_index;
3271 
3272 
3273     if ( !face )
3274       return FT_THROW( Invalid_Face_Handle );
3275 
3276     if ( !face->size )
3277       return FT_THROW( Invalid_Size_Handle );
3278 
3279     if ( !req || req->width < 0 || req->height < 0 ||
3280          req->type >= FT_SIZE_REQUEST_TYPE_MAX )
3281       return FT_THROW( Invalid_Argument );
3282 
3283     /* signal the auto-hinter to recompute its size metrics */
3284     /* (if requested)                                       */
3285     face->size->internal->autohint_metrics.x_scale = 0;
3286 
3287     clazz = face->driver->clazz;
3288 
3289     if ( clazz->request_size )
3290     {
3291       error = clazz->request_size( face->size, req );
3292 
3293       FT_TRACE5(( "FT_Request_Size (%s driver):\n",
3294                   face->driver->root.clazz->module_name ));
3295     }
3296     else if ( !FT_IS_SCALABLE( face ) && FT_HAS_FIXED_SIZES( face ) )
3297     {
3298       /*
3299        * The reason that a driver doesn't have `request_size' defined is
3300        * either that the scaling here suffices or that the supported formats
3301        * are bitmap-only and size matching is not implemented.
3302        *
3303        * In the latter case, a simple size matching is done.
3304        */
3305       error = FT_Match_Size( face, req, 0, &strike_index );
3306       if ( error )
3307         return error;
3308 
3309       return FT_Select_Size( face, (FT_Int)strike_index );
3310     }
3311     else
3312     {
3313       FT_Request_Metrics( face, req );
3314 
3315       FT_TRACE5(( "FT_Request_Size:\n" ));
3316     }
3317 
3318 #ifdef FT_DEBUG_LEVEL_TRACE
3319     {
3320       FT_Size_Metrics*  metrics = &face->size->metrics;
3321 
3322 
3323       FT_TRACE5(( "  x scale: %ld (%f)\n",
3324                   metrics->x_scale, metrics->x_scale / 65536.0 ));
3325       FT_TRACE5(( "  y scale: %ld (%f)\n",
3326                   metrics->y_scale, metrics->y_scale / 65536.0 ));
3327       FT_TRACE5(( "  ascender: %f\n",    metrics->ascender / 64.0 ));
3328       FT_TRACE5(( "  descender: %f\n",   metrics->descender / 64.0 ));
3329       FT_TRACE5(( "  height: %f\n",      metrics->height / 64.0 ));
3330       FT_TRACE5(( "  max advance: %f\n", metrics->max_advance / 64.0 ));
3331       FT_TRACE5(( "  x ppem: %d\n",      metrics->x_ppem ));
3332       FT_TRACE5(( "  y ppem: %d\n",      metrics->y_ppem ));
3333     }
3334 #endif
3335 
3336     return error;
3337   }
3338 
3339 
3340   /* documentation is in freetype.h */
3341 
3342   FT_EXPORT_DEF( FT_Error )
FT_Set_Char_Size(FT_Face face,FT_F26Dot6 char_width,FT_F26Dot6 char_height,FT_UInt horz_resolution,FT_UInt vert_resolution)3343   FT_Set_Char_Size( FT_Face     face,
3344                     FT_F26Dot6  char_width,
3345                     FT_F26Dot6  char_height,
3346                     FT_UInt     horz_resolution,
3347                     FT_UInt     vert_resolution )
3348   {
3349     FT_Size_RequestRec  req;
3350 
3351 
3352     /* check of `face' delayed to `FT_Request_Size' */
3353 
3354     if ( !char_width )
3355       char_width = char_height;
3356     else if ( !char_height )
3357       char_height = char_width;
3358 
3359     if ( !horz_resolution )
3360       horz_resolution = vert_resolution;
3361     else if ( !vert_resolution )
3362       vert_resolution = horz_resolution;
3363 
3364     if ( char_width  < 1 * 64 )
3365       char_width  = 1 * 64;
3366     if ( char_height < 1 * 64 )
3367       char_height = 1 * 64;
3368 
3369     if ( !horz_resolution )
3370       horz_resolution = vert_resolution = 72;
3371 
3372     req.type           = FT_SIZE_REQUEST_TYPE_NOMINAL;
3373     req.width          = char_width;
3374     req.height         = char_height;
3375     req.horiResolution = horz_resolution;
3376     req.vertResolution = vert_resolution;
3377 
3378     return FT_Request_Size( face, &req );
3379   }
3380 
3381 
3382   /* documentation is in freetype.h */
3383 
3384   FT_EXPORT_DEF( FT_Error )
FT_Set_Pixel_Sizes(FT_Face face,FT_UInt pixel_width,FT_UInt pixel_height)3385   FT_Set_Pixel_Sizes( FT_Face  face,
3386                       FT_UInt  pixel_width,
3387                       FT_UInt  pixel_height )
3388   {
3389     FT_Size_RequestRec  req;
3390 
3391 
3392     /* check of `face' delayed to `FT_Request_Size' */
3393 
3394     if ( pixel_width == 0 )
3395       pixel_width = pixel_height;
3396     else if ( pixel_height == 0 )
3397       pixel_height = pixel_width;
3398 
3399     if ( pixel_width  < 1 )
3400       pixel_width  = 1;
3401     if ( pixel_height < 1 )
3402       pixel_height = 1;
3403 
3404     /* use `>=' to avoid potential compiler warning on 16bit platforms */
3405     if ( pixel_width >= 0xFFFFU )
3406       pixel_width = 0xFFFFU;
3407     if ( pixel_height >= 0xFFFFU )
3408       pixel_height = 0xFFFFU;
3409 
3410     req.type           = FT_SIZE_REQUEST_TYPE_NOMINAL;
3411     req.width          = (FT_Long)( pixel_width << 6 );
3412     req.height         = (FT_Long)( pixel_height << 6 );
3413     req.horiResolution = 0;
3414     req.vertResolution = 0;
3415 
3416     return FT_Request_Size( face, &req );
3417   }
3418 
3419 
3420   /* documentation is in freetype.h */
3421 
3422   FT_EXPORT_DEF( FT_Error )
FT_Get_Kerning(FT_Face face,FT_UInt left_glyph,FT_UInt right_glyph,FT_UInt kern_mode,FT_Vector * akerning)3423   FT_Get_Kerning( FT_Face     face,
3424                   FT_UInt     left_glyph,
3425                   FT_UInt     right_glyph,
3426                   FT_UInt     kern_mode,
3427                   FT_Vector  *akerning )
3428   {
3429     FT_Error   error = FT_Err_Ok;
3430     FT_Driver  driver;
3431 
3432 
3433     if ( !face )
3434       return FT_THROW( Invalid_Face_Handle );
3435 
3436     if ( !akerning )
3437       return FT_THROW( Invalid_Argument );
3438 
3439     driver = face->driver;
3440 
3441     akerning->x = 0;
3442     akerning->y = 0;
3443 
3444     if ( driver->clazz->get_kerning )
3445     {
3446       error = driver->clazz->get_kerning( face,
3447                                           left_glyph,
3448                                           right_glyph,
3449                                           akerning );
3450       if ( !error )
3451       {
3452         if ( kern_mode != FT_KERNING_UNSCALED )
3453         {
3454           akerning->x = FT_MulFix( akerning->x, face->size->metrics.x_scale );
3455           akerning->y = FT_MulFix( akerning->y, face->size->metrics.y_scale );
3456 
3457           if ( kern_mode != FT_KERNING_UNFITTED )
3458           {
3459             FT_Pos  orig_x = akerning->x;
3460             FT_Pos  orig_y = akerning->y;
3461 
3462 
3463             /* we scale down kerning values for small ppem values */
3464             /* to avoid that rounding makes them too big.         */
3465             /* `25' has been determined heuristically.            */
3466             if ( face->size->metrics.x_ppem < 25 )
3467               akerning->x = FT_MulDiv( orig_x,
3468                                        face->size->metrics.x_ppem, 25 );
3469             if ( face->size->metrics.y_ppem < 25 )
3470               akerning->y = FT_MulDiv( orig_y,
3471                                        face->size->metrics.y_ppem, 25 );
3472 
3473             akerning->x = FT_PIX_ROUND( akerning->x );
3474             akerning->y = FT_PIX_ROUND( akerning->y );
3475 
3476 #ifdef FT_DEBUG_LEVEL_TRACE
3477             {
3478               FT_Pos  orig_x_rounded = FT_PIX_ROUND( orig_x );
3479               FT_Pos  orig_y_rounded = FT_PIX_ROUND( orig_y );
3480 
3481 
3482               if ( akerning->x != orig_x_rounded ||
3483                    akerning->y != orig_y_rounded )
3484                 FT_TRACE5(( "FT_Get_Kerning: horizontal kerning"
3485                             " (%ld, %ld) scaled down to (%ld, %ld) pixels\n",
3486                             orig_x_rounded / 64, orig_y_rounded / 64,
3487                             akerning->x / 64, akerning->y / 64 ));
3488             }
3489 #endif
3490           }
3491         }
3492       }
3493     }
3494 
3495     return error;
3496   }
3497 
3498 
3499   /* documentation is in freetype.h */
3500 
3501   FT_EXPORT_DEF( FT_Error )
FT_Get_Track_Kerning(FT_Face face,FT_Fixed point_size,FT_Int degree,FT_Fixed * akerning)3502   FT_Get_Track_Kerning( FT_Face    face,
3503                         FT_Fixed   point_size,
3504                         FT_Int     degree,
3505                         FT_Fixed*  akerning )
3506   {
3507     FT_Service_Kerning  service;
3508     FT_Error            error = FT_Err_Ok;
3509 
3510 
3511     if ( !face )
3512       return FT_THROW( Invalid_Face_Handle );
3513 
3514     if ( !akerning )
3515       return FT_THROW( Invalid_Argument );
3516 
3517     FT_FACE_FIND_SERVICE( face, service, KERNING );
3518     if ( !service )
3519       return FT_THROW( Unimplemented_Feature );
3520 
3521     error = service->get_track( face,
3522                                 point_size,
3523                                 degree,
3524                                 akerning );
3525 
3526     return error;
3527   }
3528 
3529 
3530   /* documentation is in freetype.h */
3531 
3532   FT_EXPORT_DEF( FT_Error )
FT_Select_Charmap(FT_Face face,FT_Encoding encoding)3533   FT_Select_Charmap( FT_Face      face,
3534                      FT_Encoding  encoding )
3535   {
3536     FT_CharMap*  cur;
3537     FT_CharMap*  limit;
3538 
3539 
3540     if ( !face )
3541       return FT_THROW( Invalid_Face_Handle );
3542 
3543     /* FT_ENCODING_NONE is a valid encoding for BDF, PCF, and Windows FNT */
3544     if ( encoding == FT_ENCODING_NONE && !face->num_charmaps )
3545       return FT_THROW( Invalid_Argument );
3546 
3547     /* FT_ENCODING_UNICODE is special.  We try to find the `best' Unicode */
3548     /* charmap available, i.e., one with UCS-4 characters, if possible.   */
3549     /*                                                                    */
3550     /* This is done by find_unicode_charmap() above, to share code.       */
3551     if ( encoding == FT_ENCODING_UNICODE )
3552       return find_unicode_charmap( face );
3553 
3554     cur = face->charmaps;
3555     if ( !cur )
3556       return FT_THROW( Invalid_CharMap_Handle );
3557 
3558     limit = cur + face->num_charmaps;
3559 
3560     for ( ; cur < limit; cur++ )
3561     {
3562       if ( cur[0]->encoding == encoding )
3563       {
3564         face->charmap = cur[0];
3565         return FT_Err_Ok;
3566       }
3567     }
3568 
3569     return FT_THROW( Invalid_Argument );
3570   }
3571 
3572 
3573   /* documentation is in freetype.h */
3574 
3575   FT_EXPORT_DEF( FT_Error )
FT_Set_Charmap(FT_Face face,FT_CharMap charmap)3576   FT_Set_Charmap( FT_Face     face,
3577                   FT_CharMap  charmap )
3578   {
3579     FT_CharMap*  cur;
3580     FT_CharMap*  limit;
3581 
3582 
3583     if ( !face )
3584       return FT_THROW( Invalid_Face_Handle );
3585 
3586     cur = face->charmaps;
3587     if ( !cur || !charmap )
3588       return FT_THROW( Invalid_CharMap_Handle );
3589 
3590     limit = cur + face->num_charmaps;
3591 
3592     for ( ; cur < limit; cur++ )
3593     {
3594       if ( cur[0] == charmap                    &&
3595            FT_Get_CMap_Format ( charmap ) != 14 )
3596       {
3597         face->charmap = cur[0];
3598         return FT_Err_Ok;
3599       }
3600     }
3601 
3602     return FT_THROW( Invalid_Argument );
3603   }
3604 
3605 
3606   /* documentation is in freetype.h */
3607 
3608   FT_EXPORT_DEF( FT_Int )
FT_Get_Charmap_Index(FT_CharMap charmap)3609   FT_Get_Charmap_Index( FT_CharMap  charmap )
3610   {
3611     FT_Int  i;
3612 
3613 
3614     if ( !charmap || !charmap->face )
3615       return -1;
3616 
3617     for ( i = 0; i < charmap->face->num_charmaps; i++ )
3618       if ( charmap->face->charmaps[i] == charmap )
3619         break;
3620 
3621     FT_ASSERT( i < charmap->face->num_charmaps );
3622 
3623     return i;
3624   }
3625 
3626 
3627   static void
ft_cmap_done_internal(FT_CMap cmap)3628   ft_cmap_done_internal( FT_CMap  cmap )
3629   {
3630     FT_CMap_Class  clazz  = cmap->clazz;
3631     FT_Face        face   = cmap->charmap.face;
3632     FT_Memory      memory = FT_FACE_MEMORY( face );
3633 
3634 
3635     if ( clazz->done )
3636       clazz->done( cmap );
3637 
3638     FT_FREE( cmap );
3639   }
3640 
3641 
3642   FT_BASE_DEF( void )
FT_CMap_Done(FT_CMap cmap)3643   FT_CMap_Done( FT_CMap  cmap )
3644   {
3645     if ( cmap )
3646     {
3647       FT_Face    face   = cmap->charmap.face;
3648       FT_Memory  memory = FT_FACE_MEMORY( face );
3649       FT_Error   error;
3650       FT_Int     i, j;
3651 
3652 
3653       for ( i = 0; i < face->num_charmaps; i++ )
3654       {
3655         if ( (FT_CMap)face->charmaps[i] == cmap )
3656         {
3657           FT_CharMap  last_charmap = face->charmaps[face->num_charmaps - 1];
3658 
3659 
3660           if ( FT_RENEW_ARRAY( face->charmaps,
3661                                face->num_charmaps,
3662                                face->num_charmaps - 1 ) )
3663             return;
3664 
3665           /* remove it from our list of charmaps */
3666           for ( j = i + 1; j < face->num_charmaps; j++ )
3667           {
3668             if ( j == face->num_charmaps - 1 )
3669               face->charmaps[j - 1] = last_charmap;
3670             else
3671               face->charmaps[j - 1] = face->charmaps[j];
3672           }
3673 
3674           face->num_charmaps--;
3675 
3676           if ( (FT_CMap)face->charmap == cmap )
3677             face->charmap = NULL;
3678 
3679           ft_cmap_done_internal( cmap );
3680 
3681           break;
3682         }
3683       }
3684     }
3685   }
3686 
3687 
3688   FT_BASE_DEF( FT_Error )
FT_CMap_New(FT_CMap_Class clazz,FT_Pointer init_data,FT_CharMap charmap,FT_CMap * acmap)3689   FT_CMap_New( FT_CMap_Class  clazz,
3690                FT_Pointer     init_data,
3691                FT_CharMap     charmap,
3692                FT_CMap       *acmap )
3693   {
3694     FT_Error   error = FT_Err_Ok;
3695     FT_Face    face;
3696     FT_Memory  memory;
3697     FT_CMap    cmap = NULL;
3698 
3699 
3700     if ( !clazz || !charmap || !charmap->face )
3701       return FT_THROW( Invalid_Argument );
3702 
3703     face   = charmap->face;
3704     memory = FT_FACE_MEMORY( face );
3705 
3706     if ( !FT_ALLOC( cmap, clazz->size ) )
3707     {
3708       cmap->charmap = *charmap;
3709       cmap->clazz   = clazz;
3710 
3711       if ( clazz->init )
3712       {
3713         error = clazz->init( cmap, init_data );
3714         if ( error )
3715           goto Fail;
3716       }
3717 
3718       /* add it to our list of charmaps */
3719       if ( FT_RENEW_ARRAY( face->charmaps,
3720                            face->num_charmaps,
3721                            face->num_charmaps + 1 ) )
3722         goto Fail;
3723 
3724       face->charmaps[face->num_charmaps++] = (FT_CharMap)cmap;
3725     }
3726 
3727   Exit:
3728     if ( acmap )
3729       *acmap = cmap;
3730 
3731     return error;
3732 
3733   Fail:
3734     ft_cmap_done_internal( cmap );
3735     cmap = NULL;
3736     goto Exit;
3737   }
3738 
3739 
3740   /* documentation is in freetype.h */
3741 
3742   FT_EXPORT_DEF( FT_UInt )
FT_Get_Char_Index(FT_Face face,FT_ULong charcode)3743   FT_Get_Char_Index( FT_Face   face,
3744                      FT_ULong  charcode )
3745   {
3746     FT_UInt  result = 0;
3747 
3748 
3749     if ( face && face->charmap )
3750     {
3751       FT_CMap  cmap = FT_CMAP( face->charmap );
3752 
3753 
3754       if ( charcode > 0xFFFFFFFFUL )
3755       {
3756         FT_TRACE1(( "FT_Get_Char_Index: too large charcode" ));
3757         FT_TRACE1(( " 0x%lx is truncated\n", charcode ));
3758       }
3759 
3760       result = cmap->clazz->char_index( cmap, (FT_UInt32)charcode );
3761       if ( result >= (FT_UInt)face->num_glyphs )
3762         result = 0;
3763     }
3764 
3765     return result;
3766   }
3767 
3768 
3769   /* documentation is in freetype.h */
3770 
3771   FT_EXPORT_DEF( FT_ULong )
FT_Get_First_Char(FT_Face face,FT_UInt * agindex)3772   FT_Get_First_Char( FT_Face   face,
3773                      FT_UInt  *agindex )
3774   {
3775     FT_ULong  result = 0;
3776     FT_UInt   gindex = 0;
3777 
3778 
3779     /* only do something if we have a charmap, and we have glyphs at all */
3780     if ( face && face->charmap && face->num_glyphs )
3781     {
3782       gindex = FT_Get_Char_Index( face, 0 );
3783       if ( gindex == 0 )
3784         result = FT_Get_Next_Char( face, 0, &gindex );
3785     }
3786 
3787     if ( agindex )
3788       *agindex = gindex;
3789 
3790     return result;
3791   }
3792 
3793 
3794   /* documentation is in freetype.h */
3795 
3796   FT_EXPORT_DEF( FT_ULong )
FT_Get_Next_Char(FT_Face face,FT_ULong charcode,FT_UInt * agindex)3797   FT_Get_Next_Char( FT_Face   face,
3798                     FT_ULong  charcode,
3799                     FT_UInt  *agindex )
3800   {
3801     FT_ULong  result = 0;
3802     FT_UInt   gindex = 0;
3803 
3804 
3805     if ( face && face->charmap && face->num_glyphs )
3806     {
3807       FT_UInt32  code = (FT_UInt32)charcode;
3808       FT_CMap    cmap = FT_CMAP( face->charmap );
3809 
3810 
3811       do
3812       {
3813         gindex = cmap->clazz->char_next( cmap, &code );
3814 
3815       } while ( gindex >= (FT_UInt)face->num_glyphs );
3816 
3817       result = ( gindex == 0 ) ? 0 : code;
3818     }
3819 
3820     if ( agindex )
3821       *agindex = gindex;
3822 
3823     return result;
3824   }
3825 
3826 
3827   /* documentation is in freetype.h */
3828 
3829   FT_EXPORT_DEF( FT_Error )
FT_Face_Properties(FT_Face face,FT_UInt num_properties,FT_Parameter * properties)3830   FT_Face_Properties( FT_Face        face,
3831                       FT_UInt        num_properties,
3832                       FT_Parameter*  properties )
3833   {
3834     FT_Error  error = FT_Err_Ok;
3835 
3836 
3837     if ( num_properties > 0 && !properties )
3838     {
3839       error = FT_THROW( Invalid_Argument );
3840       goto Exit;
3841     }
3842 
3843     for ( ; num_properties > 0; num_properties-- )
3844     {
3845       if ( properties->tag == FT_PARAM_TAG_STEM_DARKENING )
3846       {
3847         if ( properties->data )
3848         {
3849           if ( *( (FT_Bool*)properties->data ) == TRUE )
3850             face->internal->no_stem_darkening = FALSE;
3851           else
3852             face->internal->no_stem_darkening = TRUE;
3853         }
3854         else
3855         {
3856           /* use module default */
3857           face->internal->no_stem_darkening = -1;
3858         }
3859       }
3860       else if ( properties->tag == FT_PARAM_TAG_LCD_FILTER_WEIGHTS )
3861       {
3862 #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
3863         if ( properties->data )
3864         {
3865           ft_memcpy( face->internal->lcd_weights,
3866                      properties->data,
3867                      FT_LCD_FILTER_FIVE_TAPS );
3868           face->internal->lcd_filter_func = ft_lcd_filter_fir;
3869         }
3870 #else
3871         error = FT_THROW( Unimplemented_Feature );
3872         goto Exit;
3873 #endif
3874       }
3875       else if ( properties->tag == FT_PARAM_TAG_RANDOM_SEED )
3876       {
3877         if ( properties->data )
3878         {
3879           face->internal->random_seed = *( (FT_Int32*)properties->data );
3880           if ( face->internal->random_seed < 0 )
3881             face->internal->random_seed = 0;
3882         }
3883         else
3884         {
3885           /* use module default */
3886           face->internal->random_seed = -1;
3887         }
3888       }
3889       else
3890       {
3891         error = FT_THROW( Invalid_Argument );
3892         goto Exit;
3893       }
3894 
3895       if ( error )
3896         break;
3897 
3898       properties++;
3899     }
3900 
3901   Exit:
3902     return error;
3903   }
3904 
3905 
3906   /* documentation is in freetype.h */
3907 
3908   FT_EXPORT_DEF( FT_UInt )
FT_Face_GetCharVariantIndex(FT_Face face,FT_ULong charcode,FT_ULong variantSelector)3909   FT_Face_GetCharVariantIndex( FT_Face   face,
3910                                FT_ULong  charcode,
3911                                FT_ULong  variantSelector )
3912   {
3913     FT_UInt  result = 0;
3914 
3915 
3916     if ( face                                           &&
3917          face->charmap                                  &&
3918          face->charmap->encoding == FT_ENCODING_UNICODE )
3919     {
3920       FT_CharMap  charmap = find_variant_selector_charmap( face );
3921       FT_CMap     ucmap = FT_CMAP( face->charmap );
3922 
3923 
3924       if ( charmap )
3925       {
3926         FT_CMap  vcmap = FT_CMAP( charmap );
3927 
3928 
3929         if ( charcode > 0xFFFFFFFFUL )
3930         {
3931           FT_TRACE1(( "FT_Face_GetCharVariantIndex:"
3932                       " too large charcode" ));
3933           FT_TRACE1(( " 0x%lx is truncated\n", charcode ));
3934         }
3935         if ( variantSelector > 0xFFFFFFFFUL )
3936         {
3937           FT_TRACE1(( "FT_Face_GetCharVariantIndex:"
3938                       " too large variantSelector" ));
3939           FT_TRACE1(( " 0x%lx is truncated\n", variantSelector ));
3940         }
3941 
3942         result = vcmap->clazz->char_var_index( vcmap, ucmap,
3943                                                (FT_UInt32)charcode,
3944                                                (FT_UInt32)variantSelector );
3945       }
3946     }
3947 
3948     return result;
3949   }
3950 
3951 
3952   /* documentation is in freetype.h */
3953 
3954   FT_EXPORT_DEF( FT_Int )
FT_Face_GetCharVariantIsDefault(FT_Face face,FT_ULong charcode,FT_ULong variantSelector)3955   FT_Face_GetCharVariantIsDefault( FT_Face   face,
3956                                    FT_ULong  charcode,
3957                                    FT_ULong  variantSelector )
3958   {
3959     FT_Int  result = -1;
3960 
3961 
3962     if ( face )
3963     {
3964       FT_CharMap  charmap = find_variant_selector_charmap( face );
3965 
3966 
3967       if ( charmap )
3968       {
3969         FT_CMap  vcmap = FT_CMAP( charmap );
3970 
3971 
3972         if ( charcode > 0xFFFFFFFFUL )
3973         {
3974           FT_TRACE1(( "FT_Face_GetCharVariantIsDefault:"
3975                       " too large charcode" ));
3976           FT_TRACE1(( " 0x%lx is truncated\n", charcode ));
3977         }
3978         if ( variantSelector > 0xFFFFFFFFUL )
3979         {
3980           FT_TRACE1(( "FT_Face_GetCharVariantIsDefault:"
3981                       " too large variantSelector" ));
3982           FT_TRACE1(( " 0x%lx is truncated\n", variantSelector ));
3983         }
3984 
3985         result = vcmap->clazz->char_var_default( vcmap,
3986                                                  (FT_UInt32)charcode,
3987                                                  (FT_UInt32)variantSelector );
3988       }
3989     }
3990 
3991     return result;
3992   }
3993 
3994 
3995   /* documentation is in freetype.h */
3996 
3997   FT_EXPORT_DEF( FT_UInt32* )
FT_Face_GetVariantSelectors(FT_Face face)3998   FT_Face_GetVariantSelectors( FT_Face  face )
3999   {
4000     FT_UInt32  *result = NULL;
4001 
4002 
4003     if ( face )
4004     {
4005       FT_CharMap  charmap = find_variant_selector_charmap( face );
4006 
4007 
4008       if ( charmap )
4009       {
4010         FT_CMap    vcmap  = FT_CMAP( charmap );
4011         FT_Memory  memory = FT_FACE_MEMORY( face );
4012 
4013 
4014         result = vcmap->clazz->variant_list( vcmap, memory );
4015       }
4016     }
4017 
4018     return result;
4019   }
4020 
4021 
4022   /* documentation is in freetype.h */
4023 
4024   FT_EXPORT_DEF( FT_UInt32* )
FT_Face_GetVariantsOfChar(FT_Face face,FT_ULong charcode)4025   FT_Face_GetVariantsOfChar( FT_Face   face,
4026                              FT_ULong  charcode )
4027   {
4028     FT_UInt32  *result = NULL;
4029 
4030 
4031     if ( face )
4032     {
4033       FT_CharMap  charmap = find_variant_selector_charmap( face );
4034 
4035 
4036       if ( charmap )
4037       {
4038         FT_CMap    vcmap  = FT_CMAP( charmap );
4039         FT_Memory  memory = FT_FACE_MEMORY( face );
4040 
4041 
4042         if ( charcode > 0xFFFFFFFFUL )
4043         {
4044           FT_TRACE1(( "FT_Face_GetVariantsOfChar: too large charcode" ));
4045           FT_TRACE1(( " 0x%lx is truncated\n", charcode ));
4046         }
4047 
4048         result = vcmap->clazz->charvariant_list( vcmap, memory,
4049                                                  (FT_UInt32)charcode );
4050       }
4051     }
4052     return result;
4053   }
4054 
4055 
4056   /* documentation is in freetype.h */
4057 
4058   FT_EXPORT_DEF( FT_UInt32* )
FT_Face_GetCharsOfVariant(FT_Face face,FT_ULong variantSelector)4059   FT_Face_GetCharsOfVariant( FT_Face   face,
4060                              FT_ULong  variantSelector )
4061   {
4062     FT_UInt32  *result = NULL;
4063 
4064 
4065     if ( face )
4066     {
4067       FT_CharMap  charmap = find_variant_selector_charmap( face );
4068 
4069 
4070       if ( charmap )
4071       {
4072         FT_CMap    vcmap  = FT_CMAP( charmap );
4073         FT_Memory  memory = FT_FACE_MEMORY( face );
4074 
4075 
4076         if ( variantSelector > 0xFFFFFFFFUL )
4077         {
4078           FT_TRACE1(( "FT_Get_Char_Index: too large variantSelector" ));
4079           FT_TRACE1(( " 0x%lx is truncated\n", variantSelector ));
4080         }
4081 
4082         result = vcmap->clazz->variantchar_list( vcmap, memory,
4083                                                  (FT_UInt32)variantSelector );
4084       }
4085     }
4086 
4087     return result;
4088   }
4089 
4090 
4091   /* documentation is in freetype.h */
4092 
4093   FT_EXPORT_DEF( FT_UInt )
FT_Get_Name_Index(FT_Face face,const FT_String * glyph_name)4094   FT_Get_Name_Index( FT_Face           face,
4095                      const FT_String*  glyph_name )
4096   {
4097     FT_UInt  result = 0;
4098 
4099 
4100     if ( face                       &&
4101          FT_HAS_GLYPH_NAMES( face ) &&
4102          glyph_name                 )
4103     {
4104       FT_Service_GlyphDict  service;
4105 
4106 
4107       FT_FACE_LOOKUP_SERVICE( face,
4108                               service,
4109                               GLYPH_DICT );
4110 
4111       if ( service && service->name_index )
4112         result = service->name_index( face, glyph_name );
4113     }
4114 
4115     return result;
4116   }
4117 
4118 
4119   /* documentation is in freetype.h */
4120 
4121   FT_EXPORT_DEF( FT_Error )
FT_Get_Glyph_Name(FT_Face face,FT_UInt glyph_index,FT_Pointer buffer,FT_UInt buffer_max)4122   FT_Get_Glyph_Name( FT_Face     face,
4123                      FT_UInt     glyph_index,
4124                      FT_Pointer  buffer,
4125                      FT_UInt     buffer_max )
4126   {
4127     FT_Error              error;
4128     FT_Service_GlyphDict  service;
4129 
4130 
4131     if ( !face )
4132       return FT_THROW( Invalid_Face_Handle );
4133 
4134     if ( !buffer || buffer_max == 0 )
4135       return FT_THROW( Invalid_Argument );
4136 
4137     /* clean up buffer */
4138     ((FT_Byte*)buffer)[0] = '\0';
4139 
4140     if ( (FT_Long)glyph_index >= face->num_glyphs )
4141       return FT_THROW( Invalid_Glyph_Index );
4142 
4143     if ( !FT_HAS_GLYPH_NAMES( face ) )
4144       return FT_THROW( Invalid_Argument );
4145 
4146     FT_FACE_LOOKUP_SERVICE( face, service, GLYPH_DICT );
4147     if ( service && service->get_name )
4148       error = service->get_name( face, glyph_index, buffer, buffer_max );
4149     else
4150       error = FT_THROW( Invalid_Argument );
4151 
4152     return error;
4153   }
4154 
4155 
4156   /* documentation is in freetype.h */
4157 
4158   FT_EXPORT_DEF( const char* )
FT_Get_Postscript_Name(FT_Face face)4159   FT_Get_Postscript_Name( FT_Face  face )
4160   {
4161     const char*  result = NULL;
4162 
4163 
4164     if ( !face )
4165       goto Exit;
4166 
4167     if ( !result )
4168     {
4169       FT_Service_PsFontName  service;
4170 
4171 
4172       FT_FACE_LOOKUP_SERVICE( face,
4173                               service,
4174                               POSTSCRIPT_FONT_NAME );
4175 
4176       if ( service && service->get_ps_font_name )
4177         result = service->get_ps_font_name( face );
4178     }
4179 
4180   Exit:
4181     return result;
4182   }
4183 
4184 
4185   /* documentation is in tttables.h */
4186 
4187   FT_EXPORT_DEF( void* )
FT_Get_Sfnt_Table(FT_Face face,FT_Sfnt_Tag tag)4188   FT_Get_Sfnt_Table( FT_Face      face,
4189                      FT_Sfnt_Tag  tag )
4190   {
4191     void*                  table = NULL;
4192     FT_Service_SFNT_Table  service;
4193 
4194 
4195     if ( face && FT_IS_SFNT( face ) )
4196     {
4197       FT_FACE_FIND_SERVICE( face, service, SFNT_TABLE );
4198       if ( service )
4199         table = service->get_table( face, tag );
4200     }
4201 
4202     return table;
4203   }
4204 
4205 
4206   /* documentation is in tttables.h */
4207 
4208   FT_EXPORT_DEF( FT_Error )
FT_Load_Sfnt_Table(FT_Face face,FT_ULong tag,FT_Long offset,FT_Byte * buffer,FT_ULong * length)4209   FT_Load_Sfnt_Table( FT_Face    face,
4210                       FT_ULong   tag,
4211                       FT_Long    offset,
4212                       FT_Byte*   buffer,
4213                       FT_ULong*  length )
4214   {
4215     FT_Service_SFNT_Table  service;
4216 
4217 
4218     if ( !face || !FT_IS_SFNT( face ) )
4219       return FT_THROW( Invalid_Face_Handle );
4220 
4221     FT_FACE_FIND_SERVICE( face, service, SFNT_TABLE );
4222     if ( !service )
4223       return FT_THROW( Unimplemented_Feature );
4224 
4225     return service->load_table( face, tag, offset, buffer, length );
4226   }
4227 
4228 
4229   /* documentation is in tttables.h */
4230 
4231   FT_EXPORT_DEF( FT_Error )
FT_Sfnt_Table_Info(FT_Face face,FT_UInt table_index,FT_ULong * tag,FT_ULong * length)4232   FT_Sfnt_Table_Info( FT_Face    face,
4233                       FT_UInt    table_index,
4234                       FT_ULong  *tag,
4235                       FT_ULong  *length )
4236   {
4237     FT_Service_SFNT_Table  service;
4238     FT_ULong               offset;
4239 
4240 
4241     /* test for valid `length' delayed to `service->table_info' */
4242 
4243     if ( !face || !FT_IS_SFNT( face ) )
4244       return FT_THROW( Invalid_Face_Handle );
4245 
4246     FT_FACE_FIND_SERVICE( face, service, SFNT_TABLE );
4247     if ( !service )
4248       return FT_THROW( Unimplemented_Feature );
4249 
4250     return service->table_info( face, table_index, tag, &offset, length );
4251   }
4252 
4253 
4254   /* documentation is in tttables.h */
4255 
4256   FT_EXPORT_DEF( FT_ULong )
FT_Get_CMap_Language_ID(FT_CharMap charmap)4257   FT_Get_CMap_Language_ID( FT_CharMap  charmap )
4258   {
4259     FT_Service_TTCMaps  service;
4260     FT_Face             face;
4261     TT_CMapInfo         cmap_info;
4262 
4263 
4264     if ( !charmap || !charmap->face )
4265       return 0;
4266 
4267     face = charmap->face;
4268     FT_FACE_FIND_SERVICE( face, service, TT_CMAP );
4269     if ( !service )
4270       return 0;
4271     if ( service->get_cmap_info( charmap, &cmap_info ))
4272       return 0;
4273 
4274     return cmap_info.language;
4275   }
4276 
4277 
4278   /* documentation is in tttables.h */
4279 
4280   FT_EXPORT_DEF( FT_Long )
FT_Get_CMap_Format(FT_CharMap charmap)4281   FT_Get_CMap_Format( FT_CharMap  charmap )
4282   {
4283     FT_Service_TTCMaps  service;
4284     FT_Face             face;
4285     TT_CMapInfo         cmap_info;
4286 
4287 
4288     if ( !charmap || !charmap->face )
4289       return -1;
4290 
4291     face = charmap->face;
4292     FT_FACE_FIND_SERVICE( face, service, TT_CMAP );
4293     if ( !service )
4294       return -1;
4295     if ( service->get_cmap_info( charmap, &cmap_info ))
4296       return -1;
4297 
4298     return cmap_info.format;
4299   }
4300 
4301 
4302   /* documentation is in ftsizes.h */
4303 
4304   FT_EXPORT_DEF( FT_Error )
FT_Activate_Size(FT_Size size)4305   FT_Activate_Size( FT_Size  size )
4306   {
4307     FT_Face  face;
4308 
4309 
4310     if ( !size )
4311       return FT_THROW( Invalid_Size_Handle );
4312 
4313     face = size->face;
4314     if ( !face || !face->driver )
4315       return FT_THROW( Invalid_Face_Handle );
4316 
4317     /* we don't need anything more complex than that; all size objects */
4318     /* are already listed by the face                                  */
4319     face->size = size;
4320 
4321     return FT_Err_Ok;
4322   }
4323 
4324 
4325   /*************************************************************************/
4326   /*************************************************************************/
4327   /*************************************************************************/
4328   /****                                                                 ****/
4329   /****                                                                 ****/
4330   /****                        R E N D E R E R S                        ****/
4331   /****                                                                 ****/
4332   /****                                                                 ****/
4333   /*************************************************************************/
4334   /*************************************************************************/
4335   /*************************************************************************/
4336 
4337   /* lookup a renderer by glyph format in the library's list */
4338   FT_BASE_DEF( FT_Renderer )
FT_Lookup_Renderer(FT_Library library,FT_Glyph_Format format,FT_ListNode * node)4339   FT_Lookup_Renderer( FT_Library       library,
4340                       FT_Glyph_Format  format,
4341                       FT_ListNode*     node )
4342   {
4343     FT_ListNode  cur;
4344     FT_Renderer  result = NULL;
4345 
4346 
4347     if ( !library )
4348       goto Exit;
4349 
4350     cur = library->renderers.head;
4351 
4352     if ( node )
4353     {
4354       if ( *node )
4355         cur = (*node)->next;
4356       *node = NULL;
4357     }
4358 
4359     while ( cur )
4360     {
4361       FT_Renderer  renderer = FT_RENDERER( cur->data );
4362 
4363 
4364       if ( renderer->glyph_format == format )
4365       {
4366         if ( node )
4367           *node = cur;
4368 
4369         result = renderer;
4370         break;
4371       }
4372       cur = cur->next;
4373     }
4374 
4375   Exit:
4376     return result;
4377   }
4378 
4379 
4380   static FT_Renderer
ft_lookup_glyph_renderer(FT_GlyphSlot slot)4381   ft_lookup_glyph_renderer( FT_GlyphSlot  slot )
4382   {
4383     FT_Face      face    = slot->face;
4384     FT_Library   library = FT_FACE_LIBRARY( face );
4385     FT_Renderer  result  = library->cur_renderer;
4386 
4387 
4388     if ( !result || result->glyph_format != slot->format )
4389       result = FT_Lookup_Renderer( library, slot->format, 0 );
4390 
4391     return result;
4392   }
4393 
4394 
4395   static void
ft_set_current_renderer(FT_Library library)4396   ft_set_current_renderer( FT_Library  library )
4397   {
4398     FT_Renderer  renderer;
4399 
4400 
4401     renderer = FT_Lookup_Renderer( library, FT_GLYPH_FORMAT_OUTLINE, 0 );
4402     library->cur_renderer = renderer;
4403   }
4404 
4405 
4406   static FT_Error
ft_add_renderer(FT_Module module)4407   ft_add_renderer( FT_Module  module )
4408   {
4409     FT_Library   library = module->library;
4410     FT_Memory    memory  = library->memory;
4411     FT_Error     error;
4412     FT_ListNode  node    = NULL;
4413 
4414 
4415     if ( FT_NEW( node ) )
4416       goto Exit;
4417 
4418     {
4419       FT_Renderer         render = FT_RENDERER( module );
4420       FT_Renderer_Class*  clazz  = (FT_Renderer_Class*)module->clazz;
4421 
4422 
4423       render->clazz        = clazz;
4424       render->glyph_format = clazz->glyph_format;
4425 
4426       /* allocate raster object if needed */
4427       if ( clazz->glyph_format == FT_GLYPH_FORMAT_OUTLINE &&
4428            clazz->raster_class->raster_new                )
4429       {
4430         error = clazz->raster_class->raster_new( memory, &render->raster );
4431         if ( error )
4432           goto Fail;
4433 
4434         render->raster_render = clazz->raster_class->raster_render;
4435         render->render        = clazz->render_glyph;
4436       }
4437 
4438       /* add to list */
4439       node->data = module;
4440       FT_List_Add( &library->renderers, node );
4441 
4442       ft_set_current_renderer( library );
4443     }
4444 
4445   Fail:
4446     if ( error )
4447       FT_FREE( node );
4448 
4449   Exit:
4450     return error;
4451   }
4452 
4453 
4454   static void
ft_remove_renderer(FT_Module module)4455   ft_remove_renderer( FT_Module  module )
4456   {
4457     FT_Library   library;
4458     FT_Memory    memory;
4459     FT_ListNode  node;
4460 
4461 
4462     library = module->library;
4463     if ( !library )
4464       return;
4465 
4466     memory = library->memory;
4467 
4468     node = FT_List_Find( &library->renderers, module );
4469     if ( node )
4470     {
4471       FT_Renderer  render = FT_RENDERER( module );
4472 
4473 
4474       /* release raster object, if any */
4475       if ( render->clazz->glyph_format == FT_GLYPH_FORMAT_OUTLINE &&
4476            render->raster                                         )
4477         render->clazz->raster_class->raster_done( render->raster );
4478 
4479       /* remove from list */
4480       FT_List_Remove( &library->renderers, node );
4481       FT_FREE( node );
4482 
4483       ft_set_current_renderer( library );
4484     }
4485   }
4486 
4487 
4488   /* documentation is in ftrender.h */
4489 
4490   FT_EXPORT_DEF( FT_Renderer )
FT_Get_Renderer(FT_Library library,FT_Glyph_Format format)4491   FT_Get_Renderer( FT_Library       library,
4492                    FT_Glyph_Format  format )
4493   {
4494     /* test for valid `library' delayed to `FT_Lookup_Renderer' */
4495 
4496     return FT_Lookup_Renderer( library, format, 0 );
4497   }
4498 
4499 
4500   /* documentation is in ftrender.h */
4501 
4502   FT_EXPORT_DEF( FT_Error )
FT_Set_Renderer(FT_Library library,FT_Renderer renderer,FT_UInt num_params,FT_Parameter * parameters)4503   FT_Set_Renderer( FT_Library     library,
4504                    FT_Renderer    renderer,
4505                    FT_UInt        num_params,
4506                    FT_Parameter*  parameters )
4507   {
4508     FT_ListNode  node;
4509     FT_Error     error = FT_Err_Ok;
4510 
4511     FT_Renderer_SetModeFunc  set_mode;
4512 
4513 
4514     if ( !library )
4515     {
4516       error = FT_THROW( Invalid_Library_Handle );
4517       goto Exit;
4518     }
4519 
4520     if ( !renderer )
4521     {
4522       error = FT_THROW( Invalid_Argument );
4523       goto Exit;
4524     }
4525 
4526     if ( num_params > 0 && !parameters )
4527     {
4528       error = FT_THROW( Invalid_Argument );
4529       goto Exit;
4530     }
4531 
4532     node = FT_List_Find( &library->renderers, renderer );
4533     if ( !node )
4534     {
4535       error = FT_THROW( Invalid_Argument );
4536       goto Exit;
4537     }
4538 
4539     FT_List_Up( &library->renderers, node );
4540 
4541     if ( renderer->glyph_format == FT_GLYPH_FORMAT_OUTLINE )
4542       library->cur_renderer = renderer;
4543 
4544     set_mode = renderer->clazz->set_mode;
4545 
4546     for ( ; num_params > 0; num_params-- )
4547     {
4548       error = set_mode( renderer, parameters->tag, parameters->data );
4549       if ( error )
4550         break;
4551       parameters++;
4552     }
4553 
4554   Exit:
4555     return error;
4556   }
4557 
4558 
4559   FT_BASE_DEF( FT_Error )
FT_Render_Glyph_Internal(FT_Library library,FT_GlyphSlot slot,FT_Render_Mode render_mode)4560   FT_Render_Glyph_Internal( FT_Library      library,
4561                             FT_GlyphSlot    slot,
4562                             FT_Render_Mode  render_mode )
4563   {
4564     FT_Error     error = FT_Err_Ok;
4565     FT_Face      face  = slot->face;
4566     FT_Renderer  renderer;
4567 
4568 
4569     switch ( slot->format )
4570     {
4571     case FT_GLYPH_FORMAT_BITMAP:   /* already a bitmap, don't do anything */
4572       break;
4573 
4574     default:
4575       if ( slot->internal->load_flags & FT_LOAD_COLOR )
4576       {
4577         FT_LayerIterator  iterator;
4578 
4579         FT_UInt  base_glyph = slot->glyph_index;
4580 
4581         FT_Bool  have_layers;
4582         FT_UInt  glyph_index;
4583         FT_UInt  color_index;
4584 
4585 
4586         /* check whether we have colored glyph layers */
4587         iterator.p  = NULL;
4588         have_layers = FT_Get_Color_Glyph_Layer( face,
4589                                                 base_glyph,
4590                                                 &glyph_index,
4591                                                 &color_index,
4592                                                 &iterator );
4593         if ( have_layers )
4594         {
4595           error = FT_New_GlyphSlot( face, NULL );
4596           if ( !error )
4597           {
4598             TT_Face       ttface = (TT_Face)face;
4599             SFNT_Service  sfnt   = (SFNT_Service)ttface->sfnt;
4600 
4601 
4602             do
4603             {
4604               FT_Int32  load_flags = slot->internal->load_flags;
4605 
4606 
4607               /* disable the `FT_LOAD_COLOR' flag to avoid recursion */
4608               /* right here in this function                         */
4609               load_flags &= ~FT_LOAD_COLOR;
4610 
4611               /* render into the new `face->glyph' glyph slot */
4612               load_flags |= FT_LOAD_RENDER;
4613 
4614               error = FT_Load_Glyph( face, glyph_index, load_flags );
4615               if ( error )
4616                 break;
4617 
4618               /* blend new `face->glyph' into old `slot'; */
4619               /* at the first call, `slot' is still empty */
4620               error = sfnt->colr_blend( ttface,
4621                                         color_index,
4622                                         slot,
4623                                         face->glyph );
4624               if ( error )
4625                 break;
4626 
4627             } while ( FT_Get_Color_Glyph_Layer( face,
4628                                                 base_glyph,
4629                                                 &glyph_index,
4630                                                 &color_index,
4631                                                 &iterator ) );
4632 
4633             if ( !error )
4634               slot->format = FT_GLYPH_FORMAT_BITMAP;
4635 
4636             /* this call also restores `slot' as the glyph slot */
4637             FT_Done_GlyphSlot( face->glyph );
4638           }
4639 
4640           if ( !error )
4641             return error;
4642 
4643           /* Failed to do the colored layer.  Draw outline instead. */
4644           slot->format = FT_GLYPH_FORMAT_OUTLINE;
4645         }
4646       }
4647 
4648       {
4649         FT_ListNode  node = NULL;
4650 
4651 
4652         /* small shortcut for the very common case */
4653         if ( slot->format == FT_GLYPH_FORMAT_OUTLINE )
4654         {
4655           renderer = library->cur_renderer;
4656           node     = library->renderers.head;
4657         }
4658         else
4659           renderer = FT_Lookup_Renderer( library, slot->format, &node );
4660 
4661         error = FT_ERR( Unimplemented_Feature );
4662         while ( renderer )
4663         {
4664           error = renderer->render( renderer, slot, render_mode, NULL );
4665           if ( !error                                   ||
4666                FT_ERR_NEQ( error, Cannot_Render_Glyph ) )
4667             break;
4668 
4669           /* FT_Err_Cannot_Render_Glyph is returned if the render mode   */
4670           /* is unsupported by the current renderer for this glyph image */
4671           /* format.                                                     */
4672 
4673           /* now, look for another renderer that supports the same */
4674           /* format.                                               */
4675           renderer = FT_Lookup_Renderer( library, slot->format, &node );
4676         }
4677       }
4678     }
4679 
4680 #ifdef FT_DEBUG_LEVEL_TRACE
4681 
4682 #undef  FT_COMPONENT
4683 #define FT_COMPONENT  checksum
4684 
4685     /*
4686      * Computing the MD5 checksum is expensive, unnecessarily distorting a
4687      * possible profiling of FreeType if compiled with tracing support.  For
4688      * this reason, we execute the following code only if explicitly
4689      * requested.
4690      */
4691 
4692     /* we use FT_TRACE3 in this block */
4693     if ( !error                               &&
4694          ft_trace_levels[trace_checksum] >= 3 &&
4695          slot->bitmap.buffer                  )
4696     {
4697       FT_Bitmap  bitmap;
4698       FT_Error   err;
4699 
4700 
4701       FT_Bitmap_Init( &bitmap );
4702 
4703       /* we convert to a single bitmap format for computing the checksum */
4704       /* this also converts the bitmap flow to `down' (i.e., pitch > 0)  */
4705       err = FT_Bitmap_Convert( library, &slot->bitmap, &bitmap, 1 );
4706       if ( !err )
4707       {
4708         MD5_CTX        ctx;
4709         unsigned char  md5[16];
4710         unsigned long  coverage = 0;
4711         int            i, j;
4712         int            rows  = (int)bitmap.rows;
4713         int            pitch = bitmap.pitch;
4714 
4715 
4716         FT_TRACE3(( "FT_Render_Glyph: bitmap %dx%d, %s (mode %d)\n",
4717                     pitch,
4718                     rows,
4719                     pixel_modes[slot->bitmap.pixel_mode],
4720                     slot->bitmap.pixel_mode ));
4721 
4722         for ( i = 0; i < rows; i++ )
4723           for ( j = 0; j < pitch; j++ )
4724             coverage += bitmap.buffer[i * pitch + j];
4725 
4726         FT_TRACE3(( "  Total coverage: %lu\n", coverage ));
4727 
4728         MD5_Init( &ctx );
4729         if ( bitmap.buffer )
4730           MD5_Update( &ctx, bitmap.buffer,
4731                       (unsigned long)rows * (unsigned long)pitch );
4732         MD5_Final( md5, &ctx );
4733 
4734         FT_TRACE3(( "  MD5 checksum: " ));
4735         for ( i = 0; i < 16; i++ )
4736           FT_TRACE3(( "%02X", md5[i] ));
4737         FT_TRACE3(( "\n" ));
4738       }
4739 
4740       FT_Bitmap_Done( library, &bitmap );
4741     }
4742 
4743     /*
4744      * Dump bitmap in Netpbm format (PBM or PGM).
4745      */
4746 
4747     /* we use FT_TRACE7 in this block */
4748     if ( !error                               &&
4749          ft_trace_levels[trace_checksum] >= 7 )
4750     {
4751       if ( slot->bitmap.rows  < 128U &&
4752            slot->bitmap.width < 128U &&
4753            slot->bitmap.buffer       )
4754       {
4755         int  rows  = (int)slot->bitmap.rows;
4756         int  width = (int)slot->bitmap.width;
4757         int  pitch =      slot->bitmap.pitch;
4758         int  i, j, m;
4759 
4760         unsigned char*  topleft = slot->bitmap.buffer;
4761 
4762 
4763         if ( pitch < 0 )
4764           topleft -= pitch * ( rows - 1 );
4765 
4766         FT_TRACE7(( "Netpbm image: start\n" ));
4767         switch ( slot->bitmap.pixel_mode )
4768         {
4769         case FT_PIXEL_MODE_MONO:
4770           FT_TRACE7(( "P1 %d %d\n", width, rows ));
4771           for ( i = 0; i < rows; i++ )
4772           {
4773             for ( j = 0; j < width; )
4774               for ( m = 128; m > 0 && j < width; m >>= 1, j++ )
4775                 FT_TRACE7(( " %d",
4776                             ( topleft[i * pitch + j / 8] & m ) != 0 ));
4777             FT_TRACE7(( "\n" ));
4778           }
4779           break;
4780 
4781         default:
4782           FT_TRACE7(( "P2 %d %d 255\n", width, rows ));
4783           for ( i = 0; i < rows; i++ )
4784           {
4785             for ( j = 0; j < width; j += 1 )
4786               FT_TRACE7(( " %3u", topleft[i * pitch + j] ));
4787             FT_TRACE7(( "\n" ));
4788           }
4789         }
4790         FT_TRACE7(( "Netpbm image: end\n" ));
4791       }
4792       else
4793         FT_TRACE7(( "Netpbm image: too large, omitted\n" ));
4794     }
4795 
4796 #undef  FT_COMPONENT
4797 #define FT_COMPONENT  objs
4798 
4799 #endif /* FT_DEBUG_LEVEL_TRACE */
4800 
4801     return error;
4802   }
4803 
4804 
4805   /* documentation is in freetype.h */
4806 
4807   FT_EXPORT_DEF( FT_Error )
FT_Render_Glyph(FT_GlyphSlot slot,FT_Render_Mode render_mode)4808   FT_Render_Glyph( FT_GlyphSlot    slot,
4809                    FT_Render_Mode  render_mode )
4810   {
4811     FT_Library  library;
4812 
4813 
4814     if ( !slot || !slot->face )
4815       return FT_THROW( Invalid_Argument );
4816 
4817     library = FT_FACE_LIBRARY( slot->face );
4818 
4819     return FT_Render_Glyph_Internal( library, slot, render_mode );
4820   }
4821 
4822 
4823   /*************************************************************************/
4824   /*************************************************************************/
4825   /*************************************************************************/
4826   /****                                                                 ****/
4827   /****                                                                 ****/
4828   /****                         M O D U L E S                           ****/
4829   /****                                                                 ****/
4830   /****                                                                 ****/
4831   /*************************************************************************/
4832   /*************************************************************************/
4833   /*************************************************************************/
4834 
4835 
4836   /**************************************************************************
4837    *
4838    * @Function:
4839    *   Destroy_Module
4840    *
4841    * @Description:
4842    *   Destroys a given module object.  For drivers, this also destroys
4843    *   all child faces.
4844    *
4845    * @InOut:
4846    *   module ::
4847    *     A handle to the target driver object.
4848    *
4849    * @Note:
4850    *   The driver _must_ be LOCKED!
4851    */
4852   static void
Destroy_Module(FT_Module module)4853   Destroy_Module( FT_Module  module )
4854   {
4855     FT_Memory         memory  = module->memory;
4856     FT_Module_Class*  clazz   = module->clazz;
4857     FT_Library        library = module->library;
4858 
4859 
4860     if ( library && library->auto_hinter == module )
4861       library->auto_hinter = NULL;
4862 
4863     /* if the module is a renderer */
4864     if ( FT_MODULE_IS_RENDERER( module ) )
4865       ft_remove_renderer( module );
4866 
4867     /* if the module is a font driver, add some steps */
4868     if ( FT_MODULE_IS_DRIVER( module ) )
4869       Destroy_Driver( FT_DRIVER( module ) );
4870 
4871     /* finalize the module object */
4872     if ( clazz->module_done )
4873       clazz->module_done( module );
4874 
4875     /* discard it */
4876     FT_FREE( module );
4877   }
4878 
4879 
4880   /* documentation is in ftmodapi.h */
4881 
4882   FT_EXPORT_DEF( FT_Error )
FT_Add_Module(FT_Library library,const FT_Module_Class * clazz)4883   FT_Add_Module( FT_Library              library,
4884                  const FT_Module_Class*  clazz )
4885   {
4886     FT_Error   error;
4887     FT_Memory  memory;
4888     FT_Module  module = NULL;
4889     FT_UInt    nn;
4890 
4891 
4892 #define FREETYPE_VER_FIXED  ( ( (FT_Long)FREETYPE_MAJOR << 16 ) | \
4893                                 FREETYPE_MINOR                  )
4894 
4895     if ( !library )
4896       return FT_THROW( Invalid_Library_Handle );
4897 
4898     if ( !clazz )
4899       return FT_THROW( Invalid_Argument );
4900 
4901     /* check FreeType version */
4902     if ( clazz->module_requires > FREETYPE_VER_FIXED )
4903       return FT_THROW( Invalid_Version );
4904 
4905     /* look for a module with the same name in the library's table */
4906     for ( nn = 0; nn < library->num_modules; nn++ )
4907     {
4908       module = library->modules[nn];
4909       if ( ft_strcmp( module->clazz->module_name, clazz->module_name ) == 0 )
4910       {
4911         /* this installed module has the same name, compare their versions */
4912         if ( clazz->module_version <= module->clazz->module_version )
4913           return FT_THROW( Lower_Module_Version );
4914 
4915         /* remove the module from our list, then exit the loop to replace */
4916         /* it by our new version..                                        */
4917         FT_Remove_Module( library, module );
4918         break;
4919       }
4920     }
4921 
4922     memory = library->memory;
4923     error  = FT_Err_Ok;
4924 
4925     if ( library->num_modules >= FT_MAX_MODULES )
4926     {
4927       error = FT_THROW( Too_Many_Drivers );
4928       goto Exit;
4929     }
4930 
4931     /* allocate module object */
4932     if ( FT_ALLOC( module, clazz->module_size ) )
4933       goto Exit;
4934 
4935     /* base initialization */
4936     module->library = library;
4937     module->memory  = memory;
4938     module->clazz   = (FT_Module_Class*)clazz;
4939 
4940     /* check whether the module is a renderer - this must be performed */
4941     /* before the normal module initialization                         */
4942     if ( FT_MODULE_IS_RENDERER( module ) )
4943     {
4944       /* add to the renderers list */
4945       error = ft_add_renderer( module );
4946       if ( error )
4947         goto Fail;
4948     }
4949 
4950     /* is the module a auto-hinter? */
4951     if ( FT_MODULE_IS_HINTER( module ) )
4952       library->auto_hinter = module;
4953 
4954     /* if the module is a font driver */
4955     if ( FT_MODULE_IS_DRIVER( module ) )
4956     {
4957       FT_Driver  driver = FT_DRIVER( module );
4958 
4959 
4960       driver->clazz = (FT_Driver_Class)module->clazz;
4961     }
4962 
4963     if ( clazz->module_init )
4964     {
4965       error = clazz->module_init( module );
4966       if ( error )
4967         goto Fail;
4968     }
4969 
4970     /* add module to the library's table */
4971     library->modules[library->num_modules++] = module;
4972 
4973   Exit:
4974     return error;
4975 
4976   Fail:
4977     if ( FT_MODULE_IS_RENDERER( module ) )
4978     {
4979       FT_Renderer  renderer = FT_RENDERER( module );
4980 
4981 
4982       if ( renderer->clazz                                          &&
4983            renderer->clazz->glyph_format == FT_GLYPH_FORMAT_OUTLINE &&
4984            renderer->raster                                         )
4985         renderer->clazz->raster_class->raster_done( renderer->raster );
4986     }
4987 
4988     FT_FREE( module );
4989     goto Exit;
4990   }
4991 
4992 
4993   /* documentation is in ftmodapi.h */
4994 
4995   FT_EXPORT_DEF( FT_Module )
FT_Get_Module(FT_Library library,const char * module_name)4996   FT_Get_Module( FT_Library   library,
4997                  const char*  module_name )
4998   {
4999     FT_Module   result = NULL;
5000     FT_Module*  cur;
5001     FT_Module*  limit;
5002 
5003 
5004     if ( !library || !module_name )
5005       return result;
5006 
5007     cur   = library->modules;
5008     limit = cur + library->num_modules;
5009 
5010     for ( ; cur < limit; cur++ )
5011       if ( ft_strcmp( cur[0]->clazz->module_name, module_name ) == 0 )
5012       {
5013         result = cur[0];
5014         break;
5015       }
5016 
5017     return result;
5018   }
5019 
5020 
5021   /* documentation is in ftobjs.h */
5022 
5023   FT_BASE_DEF( const void* )
FT_Get_Module_Interface(FT_Library library,const char * mod_name)5024   FT_Get_Module_Interface( FT_Library   library,
5025                            const char*  mod_name )
5026   {
5027     FT_Module  module;
5028 
5029 
5030     /* test for valid `library' delayed to FT_Get_Module() */
5031 
5032     module = FT_Get_Module( library, mod_name );
5033 
5034     return module ? module->clazz->module_interface : 0;
5035   }
5036 
5037 
5038   FT_BASE_DEF( FT_Pointer )
ft_module_get_service(FT_Module module,const char * service_id,FT_Bool global)5039   ft_module_get_service( FT_Module    module,
5040                          const char*  service_id,
5041                          FT_Bool      global )
5042   {
5043     FT_Pointer  result = NULL;
5044 
5045 
5046     if ( module )
5047     {
5048       FT_ASSERT( module->clazz && module->clazz->get_interface );
5049 
5050       /* first, look for the service in the module */
5051       if ( module->clazz->get_interface )
5052         result = module->clazz->get_interface( module, service_id );
5053 
5054       if ( global && !result )
5055       {
5056         /* we didn't find it, look in all other modules then */
5057         FT_Library  library = module->library;
5058         FT_Module*  cur     = library->modules;
5059         FT_Module*  limit   = cur + library->num_modules;
5060 
5061 
5062         for ( ; cur < limit; cur++ )
5063         {
5064           if ( cur[0] != module )
5065           {
5066             FT_ASSERT( cur[0]->clazz );
5067 
5068             if ( cur[0]->clazz->get_interface )
5069             {
5070               result = cur[0]->clazz->get_interface( cur[0], service_id );
5071               if ( result )
5072                 break;
5073             }
5074           }
5075         }
5076       }
5077     }
5078 
5079     return result;
5080   }
5081 
5082 
5083   /* documentation is in ftmodapi.h */
5084 
5085   FT_EXPORT_DEF( FT_Error )
FT_Remove_Module(FT_Library library,FT_Module module)5086   FT_Remove_Module( FT_Library  library,
5087                     FT_Module   module )
5088   {
5089     /* try to find the module from the table, then remove it from there */
5090 
5091     if ( !library )
5092       return FT_THROW( Invalid_Library_Handle );
5093 
5094     if ( module )
5095     {
5096       FT_Module*  cur   = library->modules;
5097       FT_Module*  limit = cur + library->num_modules;
5098 
5099 
5100       for ( ; cur < limit; cur++ )
5101       {
5102         if ( cur[0] == module )
5103         {
5104           /* remove it from the table */
5105           library->num_modules--;
5106           limit--;
5107           while ( cur < limit )
5108           {
5109             cur[0] = cur[1];
5110             cur++;
5111           }
5112           limit[0] = NULL;
5113 
5114           /* destroy the module */
5115           Destroy_Module( module );
5116 
5117           return FT_Err_Ok;
5118         }
5119       }
5120     }
5121     return FT_THROW( Invalid_Driver_Handle );
5122   }
5123 
5124 
5125   static FT_Error
ft_property_do(FT_Library library,const FT_String * module_name,const FT_String * property_name,void * value,FT_Bool set,FT_Bool value_is_string)5126   ft_property_do( FT_Library        library,
5127                   const FT_String*  module_name,
5128                   const FT_String*  property_name,
5129                   void*             value,
5130                   FT_Bool           set,
5131                   FT_Bool           value_is_string )
5132   {
5133     FT_Module*           cur;
5134     FT_Module*           limit;
5135     FT_Module_Interface  interface;
5136 
5137     FT_Service_Properties  service;
5138 
5139 #ifdef FT_DEBUG_LEVEL_ERROR
5140     const FT_String*  set_name  = "FT_Property_Set";
5141     const FT_String*  get_name  = "FT_Property_Get";
5142     const FT_String*  func_name = set ? set_name : get_name;
5143 #endif
5144 
5145     FT_Bool  missing_func;
5146 
5147 
5148     if ( !library )
5149       return FT_THROW( Invalid_Library_Handle );
5150 
5151     if ( !module_name || !property_name || !value )
5152       return FT_THROW( Invalid_Argument );
5153 
5154     cur   = library->modules;
5155     limit = cur + library->num_modules;
5156 
5157     /* search module */
5158     for ( ; cur < limit; cur++ )
5159       if ( !ft_strcmp( cur[0]->clazz->module_name, module_name ) )
5160         break;
5161 
5162     if ( cur == limit )
5163     {
5164       FT_ERROR(( "%s: can't find module `%s'\n",
5165                  func_name, module_name ));
5166       return FT_THROW( Missing_Module );
5167     }
5168 
5169     /* check whether we have a service interface */
5170     if ( !cur[0]->clazz->get_interface )
5171     {
5172       FT_ERROR(( "%s: module `%s' doesn't support properties\n",
5173                  func_name, module_name ));
5174       return FT_THROW( Unimplemented_Feature );
5175     }
5176 
5177     /* search property service */
5178     interface = cur[0]->clazz->get_interface( cur[0],
5179                                               FT_SERVICE_ID_PROPERTIES );
5180     if ( !interface )
5181     {
5182       FT_ERROR(( "%s: module `%s' doesn't support properties\n",
5183                  func_name, module_name ));
5184       return FT_THROW( Unimplemented_Feature );
5185     }
5186 
5187     service = (FT_Service_Properties)interface;
5188 
5189     if ( set )
5190       missing_func = FT_BOOL( !service->set_property );
5191     else
5192       missing_func = FT_BOOL( !service->get_property );
5193 
5194     if ( missing_func )
5195     {
5196       FT_ERROR(( "%s: property service of module `%s' is broken\n",
5197                  func_name, module_name ));
5198       return FT_THROW( Unimplemented_Feature );
5199     }
5200 
5201     return set ? service->set_property( cur[0],
5202                                         property_name,
5203                                         value,
5204                                         value_is_string )
5205                : service->get_property( cur[0],
5206                                         property_name,
5207                                         value );
5208   }
5209 
5210 
5211   /* documentation is in ftmodapi.h */
5212 
5213   FT_EXPORT_DEF( FT_Error )
FT_Property_Set(FT_Library library,const FT_String * module_name,const FT_String * property_name,const void * value)5214   FT_Property_Set( FT_Library        library,
5215                    const FT_String*  module_name,
5216                    const FT_String*  property_name,
5217                    const void*       value )
5218   {
5219     return ft_property_do( library,
5220                            module_name,
5221                            property_name,
5222                            (void*)value,
5223                            TRUE,
5224                            FALSE );
5225   }
5226 
5227 
5228   /* documentation is in ftmodapi.h */
5229 
5230   FT_EXPORT_DEF( FT_Error )
FT_Property_Get(FT_Library library,const FT_String * module_name,const FT_String * property_name,void * value)5231   FT_Property_Get( FT_Library        library,
5232                    const FT_String*  module_name,
5233                    const FT_String*  property_name,
5234                    void*             value )
5235   {
5236     return ft_property_do( library,
5237                            module_name,
5238                            property_name,
5239                            value,
5240                            FALSE,
5241                            FALSE );
5242   }
5243 
5244 
5245 #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES
5246 
5247   /* this variant is used for handling the FREETYPE_PROPERTIES */
5248   /* environment variable                                      */
5249 
5250   FT_BASE_DEF( FT_Error )
ft_property_string_set(FT_Library library,const FT_String * module_name,const FT_String * property_name,FT_String * value)5251   ft_property_string_set( FT_Library        library,
5252                           const FT_String*  module_name,
5253                           const FT_String*  property_name,
5254                           FT_String*        value )
5255   {
5256     return ft_property_do( library,
5257                            module_name,
5258                            property_name,
5259                            (void*)value,
5260                            TRUE,
5261                            TRUE );
5262   }
5263 
5264 #endif
5265 
5266 
5267   /*************************************************************************/
5268   /*************************************************************************/
5269   /*************************************************************************/
5270   /****                                                                 ****/
5271   /****                                                                 ****/
5272   /****                         L I B R A R Y                           ****/
5273   /****                                                                 ****/
5274   /****                                                                 ****/
5275   /*************************************************************************/
5276   /*************************************************************************/
5277   /*************************************************************************/
5278 
5279 
5280   /* documentation is in ftmodapi.h */
5281 
5282   FT_EXPORT_DEF( FT_Error )
FT_Reference_Library(FT_Library library)5283   FT_Reference_Library( FT_Library  library )
5284   {
5285     if ( !library )
5286       return FT_THROW( Invalid_Library_Handle );
5287 
5288     library->refcount++;
5289 
5290     return FT_Err_Ok;
5291   }
5292 
5293 
5294   /* documentation is in ftmodapi.h */
5295 
5296   FT_EXPORT_DEF( FT_Error )
FT_New_Library(FT_Memory memory,FT_Library * alibrary)5297   FT_New_Library( FT_Memory    memory,
5298                   FT_Library  *alibrary )
5299   {
5300     FT_Library  library = NULL;
5301     FT_Error    error;
5302 
5303 
5304     if ( !memory || !alibrary )
5305       return FT_THROW( Invalid_Argument );
5306 
5307 #ifdef FT_DEBUG_LEVEL_ERROR
5308     /* init debugging support */
5309     ft_debug_init();
5310 #endif
5311 
5312     /* first of all, allocate the library object */
5313     if ( FT_NEW( library ) )
5314       return error;
5315 
5316     library->memory = memory;
5317 
5318     library->version_major = FREETYPE_MAJOR;
5319     library->version_minor = FREETYPE_MINOR;
5320     library->version_patch = FREETYPE_PATCH;
5321 
5322     library->refcount = 1;
5323 
5324     /* That's ok now */
5325     *alibrary = library;
5326 
5327     return FT_Err_Ok;
5328   }
5329 
5330 
5331   /* documentation is in freetype.h */
5332 
5333   FT_EXPORT_DEF( void )
FT_Library_Version(FT_Library library,FT_Int * amajor,FT_Int * aminor,FT_Int * apatch)5334   FT_Library_Version( FT_Library   library,
5335                       FT_Int      *amajor,
5336                       FT_Int      *aminor,
5337                       FT_Int      *apatch )
5338   {
5339     FT_Int  major = 0;
5340     FT_Int  minor = 0;
5341     FT_Int  patch = 0;
5342 
5343 
5344     if ( library )
5345     {
5346       major = library->version_major;
5347       minor = library->version_minor;
5348       patch = library->version_patch;
5349     }
5350 
5351     if ( amajor )
5352       *amajor = major;
5353 
5354     if ( aminor )
5355       *aminor = minor;
5356 
5357     if ( apatch )
5358       *apatch = patch;
5359   }
5360 
5361 
5362   /* documentation is in ftmodapi.h */
5363 
5364   FT_EXPORT_DEF( FT_Error )
FT_Done_Library(FT_Library library)5365   FT_Done_Library( FT_Library  library )
5366   {
5367     FT_Memory  memory;
5368 
5369 
5370     if ( !library )
5371       return FT_THROW( Invalid_Library_Handle );
5372 
5373     library->refcount--;
5374     if ( library->refcount > 0 )
5375       goto Exit;
5376 
5377     memory = library->memory;
5378 
5379     /*
5380      * Close all faces in the library.  If we don't do this, we can have
5381      * some subtle memory leaks.
5382      *
5383      * Example:
5384      *
5385      * - the cff font driver uses the pshinter module in cff_size_done
5386      * - if the pshinter module is destroyed before the cff font driver,
5387      *   opened FT_Face objects managed by the driver are not properly
5388      *   destroyed, resulting in a memory leak
5389      *
5390      * Some faces are dependent on other faces, like Type42 faces that
5391      * depend on TrueType faces synthesized internally.
5392      *
5393      * The order of drivers should be specified in driver_name[].
5394      */
5395     {
5396       FT_UInt      m, n;
5397       const char*  driver_name[] = { "type42", NULL };
5398 
5399 
5400       for ( m = 0;
5401             m < sizeof ( driver_name ) / sizeof ( driver_name[0] );
5402             m++ )
5403       {
5404         for ( n = 0; n < library->num_modules; n++ )
5405         {
5406           FT_Module    module      = library->modules[n];
5407           const char*  module_name = module->clazz->module_name;
5408           FT_List      faces;
5409 
5410 
5411           if ( driver_name[m]                                &&
5412                ft_strcmp( module_name, driver_name[m] ) != 0 )
5413             continue;
5414 
5415           if ( ( module->clazz->module_flags & FT_MODULE_FONT_DRIVER ) == 0 )
5416             continue;
5417 
5418           FT_TRACE7(( "FT_Done_Library: close faces for %s\n", module_name ));
5419 
5420           faces = &FT_DRIVER( module )->faces_list;
5421           while ( faces->head )
5422           {
5423             FT_Done_Face( FT_FACE( faces->head->data ) );
5424             if ( faces->head )
5425               FT_TRACE0(( "FT_Done_Library: failed to free some faces\n" ));
5426           }
5427         }
5428       }
5429     }
5430 
5431     /* Close all other modules in the library */
5432 #if 1
5433     /* XXX Modules are removed in the reversed order so that  */
5434     /* type42 module is removed before truetype module.  This */
5435     /* avoids double free in some occasions.  It is a hack.   */
5436     while ( library->num_modules > 0 )
5437       FT_Remove_Module( library,
5438                         library->modules[library->num_modules - 1] );
5439 #else
5440     {
5441       FT_UInt  n;
5442 
5443 
5444       for ( n = 0; n < library->num_modules; n++ )
5445       {
5446         FT_Module  module = library->modules[n];
5447 
5448 
5449         if ( module )
5450         {
5451           Destroy_Module( module );
5452           library->modules[n] = NULL;
5453         }
5454       }
5455     }
5456 #endif
5457 
5458     FT_FREE( library );
5459 
5460   Exit:
5461     return FT_Err_Ok;
5462   }
5463 
5464 
5465   /* documentation is in ftmodapi.h */
5466 
5467   FT_EXPORT_DEF( void )
FT_Set_Debug_Hook(FT_Library library,FT_UInt hook_index,FT_DebugHook_Func debug_hook)5468   FT_Set_Debug_Hook( FT_Library         library,
5469                      FT_UInt            hook_index,
5470                      FT_DebugHook_Func  debug_hook )
5471   {
5472     if ( library && debug_hook &&
5473          hook_index <
5474            ( sizeof ( library->debug_hooks ) / sizeof ( void* ) ) )
5475       library->debug_hooks[hook_index] = debug_hook;
5476   }
5477 
5478 
5479   /* documentation is in ftmodapi.h */
5480 
5481   FT_EXPORT_DEF( FT_TrueTypeEngineType )
FT_Get_TrueType_Engine_Type(FT_Library library)5482   FT_Get_TrueType_Engine_Type( FT_Library  library )
5483   {
5484     FT_TrueTypeEngineType  result = FT_TRUETYPE_ENGINE_TYPE_NONE;
5485 
5486 
5487     if ( library )
5488     {
5489       FT_Module  module = FT_Get_Module( library, "truetype" );
5490 
5491 
5492       if ( module )
5493       {
5494         FT_Service_TrueTypeEngine  service;
5495 
5496 
5497         service = (FT_Service_TrueTypeEngine)
5498                     ft_module_get_service( module,
5499                                            FT_SERVICE_ID_TRUETYPE_ENGINE,
5500                                            0 );
5501         if ( service )
5502           result = service->engine_type;
5503       }
5504     }
5505 
5506     return result;
5507   }
5508 
5509 
5510   /* documentation is in freetype.h */
5511 
5512   FT_EXPORT_DEF( FT_Error )
FT_Get_SubGlyph_Info(FT_GlyphSlot glyph,FT_UInt sub_index,FT_Int * p_index,FT_UInt * p_flags,FT_Int * p_arg1,FT_Int * p_arg2,FT_Matrix * p_transform)5513   FT_Get_SubGlyph_Info( FT_GlyphSlot  glyph,
5514                         FT_UInt       sub_index,
5515                         FT_Int       *p_index,
5516                         FT_UInt      *p_flags,
5517                         FT_Int       *p_arg1,
5518                         FT_Int       *p_arg2,
5519                         FT_Matrix    *p_transform )
5520   {
5521     FT_Error  error = FT_ERR( Invalid_Argument );
5522 
5523 
5524     if ( glyph                                      &&
5525          glyph->subglyphs                           &&
5526          glyph->format == FT_GLYPH_FORMAT_COMPOSITE &&
5527          sub_index < glyph->num_subglyphs           )
5528     {
5529       FT_SubGlyph  subg = glyph->subglyphs + sub_index;
5530 
5531 
5532       *p_index     = subg->index;
5533       *p_flags     = subg->flags;
5534       *p_arg1      = subg->arg1;
5535       *p_arg2      = subg->arg2;
5536       *p_transform = subg->transform;
5537 
5538       error = FT_Err_Ok;
5539     }
5540 
5541     return error;
5542   }
5543 
5544 
5545   /* documentation is in freetype.h */
5546 
5547   FT_EXPORT_DEF( FT_Bool )
FT_Get_Color_Glyph_Layer(FT_Face face,FT_UInt base_glyph,FT_UInt * aglyph_index,FT_UInt * acolor_index,FT_LayerIterator * iterator)5548   FT_Get_Color_Glyph_Layer( FT_Face            face,
5549                             FT_UInt            base_glyph,
5550                             FT_UInt           *aglyph_index,
5551                             FT_UInt           *acolor_index,
5552                             FT_LayerIterator*  iterator )
5553   {
5554     TT_Face       ttface;
5555     SFNT_Service  sfnt;
5556 
5557 
5558     if ( !face                                   ||
5559          !aglyph_index                           ||
5560          !acolor_index                           ||
5561          !iterator                               ||
5562          base_glyph >= (FT_UInt)face->num_glyphs )
5563       return 0;
5564 
5565     if ( !FT_IS_SFNT( face ) )
5566       return 0;
5567 
5568     ttface = (TT_Face)face;
5569     sfnt   = (SFNT_Service)ttface->sfnt;
5570 
5571     if ( sfnt->get_colr_layer )
5572       return sfnt->get_colr_layer( ttface,
5573                                    base_glyph,
5574                                    aglyph_index,
5575                                    acolor_index,
5576                                    iterator );
5577     else
5578       return 0;
5579   }
5580 
5581 
5582 /* END */
5583