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