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