code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/***************************************************************************/ /* */ /* ftsystem.c */ /* */ /* ANSI-specific FreeType low-level system interface (body). */ /* */ /* Copyright 1996-2002, 2006, 2008-2011, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file contains the default interface used by FreeType to access */ /* low-level, i.e. memory management, i/o access as well as thread */ /* synchronisation. It can be replaced by user-specific routines if */ /* necessary. */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_SYSTEM_H #include FT_ERRORS_H #include FT_TYPES_H /*************************************************************************/ /* */ /* MEMORY MANAGEMENT INTERFACE */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* It is not necessary to do any error checking for the */ /* allocation-related functions. This will be done by the higher level */ /* routines like ft_mem_alloc() or ft_mem_realloc(). */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* ft_alloc */ /* */ /* <Description> */ /* The memory allocation function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* size :: The requested size in bytes. */ /* */ /* <Return> */ /* The address of newly allocated block. */ /* */ FT_CALLBACK_DEF( void* ) ft_alloc( FT_Memory memory, long size ) { FT_UNUSED( memory ); return ft_smalloc( size ); } /*************************************************************************/ /* */ /* <Function> */ /* ft_realloc */ /* */ /* <Description> */ /* The memory reallocation function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* cur_size :: The current size of the allocated memory block. */ /* */ /* new_size :: The newly requested size in bytes. */ /* */ /* block :: The current address of the block in memory. */ /* */ /* <Return> */ /* The address of the reallocated memory block. */ /* */ FT_CALLBACK_DEF( void* ) ft_realloc( FT_Memory memory, long cur_size, long new_size, void* block ) { FT_UNUSED( memory ); FT_UNUSED( cur_size ); return ft_srealloc( block, new_size ); } /*************************************************************************/ /* */ /* <Function> */ /* ft_free */ /* */ /* <Description> */ /* The memory release function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* block :: The address of block in memory to be freed. */ /* */ FT_CALLBACK_DEF( void ) ft_free( FT_Memory memory, void* block ) { FT_UNUSED( memory ); ft_sfree( block ); } /*************************************************************************/ /* */ /* RESOURCE MANAGEMENT INTERFACE */ /* */ /*************************************************************************/ #ifndef FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_io /* We use the macro STREAM_FILE for convenience to extract the */ /* system-specific stream handle from a given FreeType stream object */ #define STREAM_FILE( stream ) ( (FT_FILE*)stream->descriptor.pointer ) /*************************************************************************/ /* */ /* <Function> */ /* ft_ansi_stream_close */ /* */ /* <Description> */ /* The function to close a stream. */ /* */ /* <Input> */ /* stream :: A pointer to the stream object. */ /* */ FT_CALLBACK_DEF( void ) ft_ansi_stream_close( FT_Stream stream ) { ft_fclose( STREAM_FILE( stream ) ); stream->descriptor.pointer = NULL; stream->size = 0; stream->base = 0; } /*************************************************************************/ /* */ /* <Function> */ /* ft_ansi_stream_io */ /* */ /* <Description> */ /* The function to open a stream. */ /* */ /* <Input> */ /* stream :: A pointer to the stream object. */ /* */ /* offset :: The position in the data stream to start reading. */ /* */ /* buffer :: The address of buffer to store the read data. */ /* */ /* count :: The number of bytes to read from the stream. */ /* */ /* <Return> */ /* The number of bytes actually read. If `count' is zero (this is, */ /* the function is used for seeking), a non-zero return value */ /* indicates an error. */ /* */ FT_CALLBACK_DEF( unsigned long ) ft_ansi_stream_io( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) { FT_FILE* file; if ( !count && offset > stream->size ) return 1; file = STREAM_FILE( stream ); if ( stream->pos != offset ) ft_fseek( file, offset, SEEK_SET ); return (unsigned long)ft_fread( buffer, 1, count, file ); } /* documentation is in ftstream.h */ FT_BASE_DEF( FT_Error ) FT_Stream_Open( FT_Stream stream, const char* filepathname ) { FT_FILE* file; if ( !stream ) return FT_THROW( Invalid_Stream_Handle ); stream->descriptor.pointer = NULL; stream->pathname.pointer = (char*)filepathname; stream->base = 0; stream->pos = 0; stream->read = NULL; stream->close = NULL; file = ft_fopen( filepathname, "rb" ); if ( !file ) { FT_ERROR(( "FT_Stream_Open:" " could not open `%s'\n", filepathname )); return FT_THROW( Cannot_Open_Resource ); } ft_fseek( file, 0, SEEK_END ); stream->size = ft_ftell( file ); if ( !stream->size ) { FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " opened `%s' but zero-sized\n", filepathname )); ft_fclose( file ); return FT_THROW( Cannot_Open_Stream ); } ft_fseek( file, 0, SEEK_SET ); stream->descriptor.pointer = file; stream->read = ft_ansi_stream_io; stream->close = ft_ansi_stream_close; FT_TRACE1(( "FT_Stream_Open:" )); FT_TRACE1(( " opened `%s' (%d bytes) successfully\n", filepathname, stream->size )); return FT_Err_Ok; } #endif /* !FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */ #ifdef FT_DEBUG_MEMORY extern FT_Int ft_mem_debug_init( FT_Memory memory ); extern void ft_mem_debug_done( FT_Memory memory ); #endif /* documentation is in ftobjs.h */ FT_BASE_DEF( FT_Memory ) FT_New_Memory( void ) { FT_Memory memory; memory = (FT_Memory)ft_smalloc( sizeof ( *memory ) ); if ( memory ) { memory->user = 0; memory->alloc = ft_alloc; memory->realloc = ft_realloc; memory->free = ft_free; #ifdef FT_DEBUG_MEMORY ft_mem_debug_init( memory ); #endif } return memory; } /* documentation is in ftobjs.h */ FT_BASE_DEF( void ) FT_Done_Memory( FT_Memory memory ) { #ifdef FT_DEBUG_MEMORY ft_mem_debug_done( memory ); #endif ft_sfree( memory ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/ftsystem.c
C
apache-2.0
14,001
/***************************************************************************/ /* */ /* fttrigon.c */ /* */ /* FreeType trigonometric functions (body). */ /* */ /* Copyright 2001-2005, 2012-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This is a fixed-point CORDIC implementation of trigonometric */ /* functions as well as transformations between Cartesian and polar */ /* coordinates. The angles are represented as 16.16 fixed-point values */ /* in degrees, i.e., the angular resolution is 2^-16 degrees. Note that */ /* only vectors longer than 2^16*180/pi (or at least 22 bits) on a */ /* discrete Cartesian grid can have the same or better angular */ /* resolution. Therefore, to maintain this precision, some functions */ /* require an interim upscaling of the vectors, whereas others operate */ /* with 24-bit long vectors directly. */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_CALC_H #include FT_TRIGONOMETRY_H /* the Cordic shrink factor 0.858785336480436 * 2^32 */ #define FT_TRIG_SCALE 0xDBD95B16UL /* the highest bit in overflow-safe vector components, */ /* MSB of 0.858785336480436 * sqrt(0.5) * 2^30 */ #define FT_TRIG_SAFE_MSB 29 /* this table was generated for FT_PI = 180L << 16, i.e. degrees */ #define FT_TRIG_MAX_ITERS 23 static const FT_Fixed ft_trig_arctan_table[] = { 1740967L, 919879L, 466945L, 234379L, 117304L, 58666L, 29335L, 14668L, 7334L, 3667L, 1833L, 917L, 458L, 229L, 115L, 57L, 29L, 14L, 7L, 4L, 2L, 1L }; #ifdef FT_LONG64 /* multiply a given value by the CORDIC shrink factor */ static FT_Fixed ft_trig_downscale( FT_Fixed val ) { FT_Fixed s; FT_Int64 v; s = val; val = FT_ABS( val ); v = ( val * (FT_Int64)FT_TRIG_SCALE ) + 0x100000000UL; val = (FT_Fixed)( v >> 32 ); return ( s >= 0 ) ? val : -val; } #else /* !FT_LONG64 */ /* multiply a given value by the CORDIC shrink factor */ static FT_Fixed ft_trig_downscale( FT_Fixed val ) { FT_Fixed s; FT_UInt32 v1, v2, k1, k2, hi, lo1, lo2, lo3; s = val; val = FT_ABS( val ); v1 = (FT_UInt32)val >> 16; v2 = (FT_UInt32)( val & 0xFFFFL ); k1 = (FT_UInt32)FT_TRIG_SCALE >> 16; /* constant */ k2 = (FT_UInt32)( FT_TRIG_SCALE & 0xFFFFL ); /* constant */ hi = k1 * v1; lo1 = k1 * v2 + k2 * v1; /* can't overflow */ lo2 = ( k2 * v2 ) >> 16; lo3 = FT_MAX( lo1, lo2 ); lo1 += lo2; hi += lo1 >> 16; if ( lo1 < lo3 ) hi += (FT_UInt32)0x10000UL; val = (FT_Fixed)hi; return ( s >= 0 ) ? val : -val; } #endif /* !FT_LONG64 */ static FT_Int ft_trig_prenorm( FT_Vector* vec ) { FT_Pos x, y; FT_Int shift; x = vec->x; y = vec->y; shift = FT_MSB( FT_ABS( x ) | FT_ABS( y ) ); if ( shift <= FT_TRIG_SAFE_MSB ) { shift = FT_TRIG_SAFE_MSB - shift; vec->x = (FT_Pos)( (FT_ULong)x << shift ); vec->y = (FT_Pos)( (FT_ULong)y << shift ); } else { shift -= FT_TRIG_SAFE_MSB; vec->x = x >> shift; vec->y = y >> shift; shift = -shift; } return shift; } static void ft_trig_pseudo_rotate( FT_Vector* vec, FT_Angle theta ) { FT_Int i; FT_Fixed x, y, xtemp, b; const FT_Fixed *arctanptr; x = vec->x; y = vec->y; /* Rotate inside [-PI/4,PI/4] sector */ while ( theta < -FT_ANGLE_PI4 ) { xtemp = y; y = -x; x = xtemp; theta += FT_ANGLE_PI2; } while ( theta > FT_ANGLE_PI4 ) { xtemp = -y; y = x; x = xtemp; theta -= FT_ANGLE_PI2; } arctanptr = ft_trig_arctan_table; /* Pseudorotations, with right shifts */ for ( i = 1, b = 1; i < FT_TRIG_MAX_ITERS; b <<= 1, i++ ) { if ( theta < 0 ) { xtemp = x + ( ( y + b ) >> i ); y = y - ( ( x + b ) >> i ); x = xtemp; theta += *arctanptr++; } else { xtemp = x - ( ( y + b ) >> i ); y = y + ( ( x + b ) >> i ); x = xtemp; theta -= *arctanptr++; } } vec->x = x; vec->y = y; } static void ft_trig_pseudo_polarize( FT_Vector* vec ) { FT_Angle theta; FT_Int i; FT_Fixed x, y, xtemp, b; const FT_Fixed *arctanptr; x = vec->x; y = vec->y; /* Get the vector into [-PI/4,PI/4] sector */ if ( y > x ) { if ( y > -x ) { theta = FT_ANGLE_PI2; xtemp = y; y = -x; x = xtemp; } else { theta = y > 0 ? FT_ANGLE_PI : -FT_ANGLE_PI; x = -x; y = -y; } } else { if ( y < -x ) { theta = -FT_ANGLE_PI2; xtemp = -y; y = x; x = xtemp; } else { theta = 0; } } arctanptr = ft_trig_arctan_table; /* Pseudorotations, with right shifts */ for ( i = 1, b = 1; i < FT_TRIG_MAX_ITERS; b <<= 1, i++ ) { if ( y > 0 ) { xtemp = x + ( ( y + b ) >> i ); y = y - ( ( x + b ) >> i ); x = xtemp; theta += *arctanptr++; } else { xtemp = x - ( ( y + b ) >> i ); y = y + ( ( x + b ) >> i ); x = xtemp; theta -= *arctanptr++; } } /* round theta */ if ( theta >= 0 ) theta = FT_PAD_ROUND( theta, 32 ); else theta = -FT_PAD_ROUND( -theta, 32 ); vec->x = x; vec->y = theta; } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Fixed ) FT_Cos( FT_Angle angle ) { FT_Vector v; v.x = FT_TRIG_SCALE >> 8; v.y = 0; ft_trig_pseudo_rotate( &v, angle ); return ( v.x + 0x80L ) >> 8; } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Fixed ) FT_Sin( FT_Angle angle ) { return FT_Cos( FT_ANGLE_PI2 - angle ); } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Fixed ) FT_Tan( FT_Angle angle ) { FT_Vector v; v.x = FT_TRIG_SCALE >> 8; v.y = 0; ft_trig_pseudo_rotate( &v, angle ); return FT_DivFix( v.y, v.x ); } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Angle ) FT_Atan2( FT_Fixed dx, FT_Fixed dy ) { FT_Vector v; if ( dx == 0 && dy == 0 ) return 0; v.x = dx; v.y = dy; ft_trig_prenorm( &v ); ft_trig_pseudo_polarize( &v ); return v.y; } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( void ) FT_Vector_Unit( FT_Vector* vec, FT_Angle angle ) { vec->x = FT_TRIG_SCALE >> 8; vec->y = 0; ft_trig_pseudo_rotate( vec, angle ); vec->x = ( vec->x + 0x80L ) >> 8; vec->y = ( vec->y + 0x80L ) >> 8; } /* these macros return 0 for positive numbers, and -1 for negative ones */ #define FT_SIGN_LONG( x ) ( (x) >> ( FT_SIZEOF_LONG * 8 - 1 ) ) #define FT_SIGN_INT( x ) ( (x) >> ( FT_SIZEOF_INT * 8 - 1 ) ) #define FT_SIGN_INT32( x ) ( (x) >> 31 ) #define FT_SIGN_INT16( x ) ( (x) >> 15 ) /* documentation is in fttrigon.h */ FT_EXPORT_DEF( void ) FT_Vector_Rotate( FT_Vector* vec, FT_Angle angle ) { FT_Int shift; FT_Vector v; v.x = vec->x; v.y = vec->y; if ( angle && ( v.x != 0 || v.y != 0 ) ) { shift = ft_trig_prenorm( &v ); ft_trig_pseudo_rotate( &v, angle ); v.x = ft_trig_downscale( v.x ); v.y = ft_trig_downscale( v.y ); if ( shift > 0 ) { FT_Int32 half = (FT_Int32)1L << ( shift - 1 ); vec->x = ( v.x + half + FT_SIGN_LONG( v.x ) ) >> shift; vec->y = ( v.y + half + FT_SIGN_LONG( v.y ) ) >> shift; } else { shift = -shift; vec->x = (FT_Pos)( (FT_ULong)v.x << shift ); vec->y = (FT_Pos)( (FT_ULong)v.y << shift ); } } } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Fixed ) FT_Vector_Length( FT_Vector* vec ) { FT_Int shift; FT_Vector v; v = *vec; /* handle trivial cases */ if ( v.x == 0 ) { return FT_ABS( v.y ); } else if ( v.y == 0 ) { return FT_ABS( v.x ); } /* general case */ shift = ft_trig_prenorm( &v ); ft_trig_pseudo_polarize( &v ); v.x = ft_trig_downscale( v.x ); if ( shift > 0 ) return ( v.x + ( 1 << ( shift - 1 ) ) ) >> shift; return (FT_Fixed)( (FT_UInt32)v.x << -shift ); } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( void ) FT_Vector_Polarize( FT_Vector* vec, FT_Fixed *length, FT_Angle *angle ) { FT_Int shift; FT_Vector v; v = *vec; if ( v.x == 0 && v.y == 0 ) return; shift = ft_trig_prenorm( &v ); ft_trig_pseudo_polarize( &v ); v.x = ft_trig_downscale( v.x ); *length = ( shift >= 0 ) ? ( v.x >> shift ) : (FT_Fixed)( (FT_UInt32)v.x << -shift ); *angle = v.y; } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( void ) FT_Vector_From_Polar( FT_Vector* vec, FT_Fixed length, FT_Angle angle ) { vec->x = length; vec->y = 0; FT_Vector_Rotate( vec, angle ); } /* documentation is in fttrigon.h */ FT_EXPORT_DEF( FT_Angle ) FT_Angle_Diff( FT_Angle angle1, FT_Angle angle2 ) { FT_Angle delta = angle2 - angle1; delta %= FT_ANGLE_2PI; if ( delta < 0 ) delta += FT_ANGLE_2PI; if ( delta > FT_ANGLE_PI ) delta -= FT_ANGLE_2PI; return delta; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/fttrigon.c
C
apache-2.0
11,292
/***************************************************************************/ /* */ /* fttype1.c */ /* */ /* FreeType utility file for PS names support (body). */ /* */ /* Copyright 2002-2004, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_SERVICE_H #include FT_SERVICE_POSTSCRIPT_INFO_H /* documentation is in t1tables.h */ FT_EXPORT_DEF( FT_Error ) FT_Get_PS_Font_Info( FT_Face face, PS_FontInfoRec* afont_info ) { FT_Error error = FT_ERR( Invalid_Argument ); if ( face ) { FT_Service_PsInfo service = NULL; FT_FACE_FIND_SERVICE( face, service, POSTSCRIPT_INFO ); if ( service && service->ps_get_font_info ) error = service->ps_get_font_info( face, afont_info ); } return error; } /* documentation is in t1tables.h */ FT_EXPORT_DEF( FT_Int ) FT_Has_PS_Glyph_Names( FT_Face face ) { FT_Int result = 0; FT_Service_PsInfo service = NULL; if ( face ) { FT_FACE_FIND_SERVICE( face, service, POSTSCRIPT_INFO ); if ( service && service->ps_has_glyph_names ) result = service->ps_has_glyph_names( face ); } return result; } /* documentation is in t1tables.h */ FT_EXPORT_DEF( FT_Error ) FT_Get_PS_Font_Private( FT_Face face, PS_PrivateRec* afont_private ) { FT_Error error = FT_ERR( Invalid_Argument ); if ( face ) { FT_Service_PsInfo service = NULL; FT_FACE_FIND_SERVICE( face, service, POSTSCRIPT_INFO ); if ( service && service->ps_get_font_private ) error = service->ps_get_font_private( face, afont_private ); } return error; } /* documentation is in t1tables.h */ FT_EXPORT_DEF( FT_Long ) FT_Get_PS_Font_Value( FT_Face face, PS_Dict_Keys key, FT_UInt idx, void *value, FT_Long value_len ) { FT_Int result = 0; FT_Service_PsInfo service = NULL; if ( face ) { FT_FACE_FIND_SERVICE( face, service, POSTSCRIPT_INFO ); if ( service && service->ps_get_font_value ) result = service->ps_get_font_value( face, key, idx, value, value_len ); } return result; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/fttype1.c
C
apache-2.0
3,468
/***************************************************************************/ /* */ /* ftutil.c */ /* */ /* FreeType utility file for memory and list management (body). */ /* */ /* Copyright 2002, 2004-2007, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_MEMORY_H #include FT_INTERNAL_OBJECTS_H #include FT_LIST_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_memory /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** *****/ /***** M E M O R Y M A N A G E M E N T *****/ /***** *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ FT_BASE_DEF( FT_Pointer ) ft_mem_alloc( FT_Memory memory, FT_Long size, FT_Error *p_error ) { FT_Error error; FT_Pointer block = ft_mem_qalloc( memory, size, &error ); if ( !error && size > 0 ) FT_MEM_ZERO( block, size ); *p_error = error; return block; } FT_BASE_DEF( FT_Pointer ) ft_mem_qalloc( FT_Memory memory, FT_Long size, FT_Error *p_error ) { FT_Error error = FT_Err_Ok; FT_Pointer block = NULL; if ( size > 0 ) { block = memory->alloc( memory, size ); if ( block == NULL ) error = FT_THROW( Out_Of_Memory ); } else if ( size < 0 ) { /* may help catch/prevent security issues */ error = FT_THROW( Invalid_Argument ); } *p_error = error; return block; } FT_BASE_DEF( FT_Pointer ) ft_mem_realloc( FT_Memory memory, FT_Long item_size, FT_Long cur_count, FT_Long new_count, void* block, FT_Error *p_error ) { FT_Error error = FT_Err_Ok; block = ft_mem_qrealloc( memory, item_size, cur_count, new_count, block, &error ); if ( !error && new_count > cur_count ) FT_MEM_ZERO( (char*)block + cur_count * item_size, ( new_count - cur_count ) * item_size ); *p_error = error; return block; } FT_BASE_DEF( FT_Pointer ) ft_mem_qrealloc( FT_Memory memory, FT_Long item_size, FT_Long cur_count, FT_Long new_count, void* block, FT_Error *p_error ) { FT_Error error = FT_Err_Ok; /* Note that we now accept `item_size == 0' as a valid parameter, in * order to cover very weird cases where an ALLOC_MULT macro would be * called. */ if ( cur_count < 0 || new_count < 0 || item_size < 0 ) { /* may help catch/prevent nasty security issues */ error = FT_THROW( Invalid_Argument ); } else if ( new_count == 0 || item_size == 0 ) { ft_mem_free( memory, block ); block = NULL; } else if ( new_count > FT_INT_MAX/item_size ) { error = FT_THROW( Array_Too_Large ); } else if ( cur_count == 0 ) { FT_ASSERT( block == NULL ); block = ft_mem_alloc( memory, new_count*item_size, &error ); } else { FT_Pointer block2; FT_Long cur_size = cur_count*item_size; FT_Long new_size = new_count*item_size; block2 = memory->realloc( memory, cur_size, new_size, block ); if ( block2 == NULL ) error = FT_THROW( Out_Of_Memory ); else block = block2; } *p_error = error; return block; } FT_BASE_DEF( void ) ft_mem_free( FT_Memory memory, const void *P ) { if ( P ) memory->free( memory, (void*)P ); } FT_BASE_DEF( FT_Pointer ) ft_mem_dup( FT_Memory memory, const void* address, FT_ULong size, FT_Error *p_error ) { FT_Error error; FT_Pointer p = ft_mem_qalloc( memory, size, &error ); if ( !error && address ) ft_memcpy( p, address, size ); *p_error = error; return p; } FT_BASE_DEF( FT_Pointer ) ft_mem_strdup( FT_Memory memory, const char* str, FT_Error *p_error ) { FT_ULong len = str ? (FT_ULong)ft_strlen( str ) + 1 : 0; return ft_mem_dup( memory, str, len, p_error ); } FT_BASE_DEF( FT_Int ) ft_mem_strcpyn( char* dst, const char* src, FT_ULong size ) { while ( size > 1 && *src != 0 ) { *dst++ = *src++; size--; } *dst = 0; /* always zero-terminate */ return *src != 0; } /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** *****/ /***** D O U B L Y L I N K E D L I S T S *****/ /***** *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #undef FT_COMPONENT #define FT_COMPONENT trace_list /* documentation is in ftlist.h */ FT_EXPORT_DEF( FT_ListNode ) FT_List_Find( FT_List list, void* data ) { FT_ListNode cur; cur = list->head; while ( cur ) { if ( cur->data == data ) return cur; cur = cur->next; } return (FT_ListNode)0; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( void ) FT_List_Add( FT_List list, FT_ListNode node ) { FT_ListNode before = list->tail; node->next = 0; node->prev = before; if ( before ) before->next = node; else list->head = node; list->tail = node; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( void ) FT_List_Insert( FT_List list, FT_ListNode node ) { FT_ListNode after = list->head; node->next = after; node->prev = 0; if ( !after ) list->tail = node; else after->prev = node; list->head = node; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( void ) FT_List_Remove( FT_List list, FT_ListNode node ) { FT_ListNode before, after; before = node->prev; after = node->next; if ( before ) before->next = after; else list->head = after; if ( after ) after->prev = before; else list->tail = before; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( void ) FT_List_Up( FT_List list, FT_ListNode node ) { FT_ListNode before, after; before = node->prev; after = node->next; /* check whether we are already on top of the list */ if ( !before ) return; before->next = after; if ( after ) after->prev = before; else list->tail = before; node->prev = 0; node->next = list->head; list->head->prev = node; list->head = node; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( FT_Error ) FT_List_Iterate( FT_List list, FT_List_Iterator iterator, void* user ) { FT_ListNode cur = list->head; FT_Error error = FT_Err_Ok; while ( cur ) { FT_ListNode next = cur->next; error = iterator( cur, user ); if ( error ) break; cur = next; } return error; } /* documentation is in ftlist.h */ FT_EXPORT_DEF( void ) FT_List_Finalize( FT_List list, FT_List_Destructor destroy, FT_Memory memory, void* user ) { FT_ListNode cur; cur = list->head; while ( cur ) { FT_ListNode next = cur->next; void* data = cur->data; if ( destroy ) destroy( memory, data, user ); FT_FREE( cur ); cur = next; } list->head = 0; list->tail = 0; } FT_BASE_DEF( FT_UInt32 ) ft_highpow2( FT_UInt32 value ) { FT_UInt32 value2; /* * We simply clear the lowest bit in each iteration. When * we reach 0, we know that the previous value was our result. */ for ( ;; ) { value2 = value & (value - 1); /* clear lowest bit */ if ( value2 == 0 ) break; value = value2; } return value; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/ftutil.c
C
apache-2.0
11,027
/***************************************************************************/ /* */ /* ftwinfnt.c */ /* */ /* FreeType API for accessing Windows FNT specific info (body). */ /* */ /* Copyright 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_WINFONTS_H #include FT_INTERNAL_OBJECTS_H #include FT_SERVICE_WINFNT_H /* documentation is in ftwinfnt.h */ FT_EXPORT_DEF( FT_Error ) FT_Get_WinFNT_Header( FT_Face face, FT_WinFNT_HeaderRec *header ) { FT_Service_WinFnt service; FT_Error error; error = FT_ERR( Invalid_Argument ); if ( face != NULL ) { FT_FACE_LOOKUP_SERVICE( face, service, WINFNT ); if ( service != NULL ) { error = service->get_header( face, header ); } } return error; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/ftwinfnt.c
C
apache-2.0
1,866
/***************************************************************************/ /* */ /* ftxf86.c */ /* */ /* FreeType utility file for X11 support (body). */ /* */ /* Copyright 2002, 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_XFREE86_H #include FT_INTERNAL_OBJECTS_H #include FT_SERVICE_XFREE86_NAME_H /* documentation is in ftxf86.h */ FT_EXPORT_DEF( const char* ) FT_Get_X11_Font_Format( FT_Face face ) { const char* result = NULL; if ( face ) FT_FACE_FIND_SERVICE( face, result, XF86_NAME ); return result; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/base/ftxf86.c
C
apache-2.0
1,618
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #ifndef HAVE_OPENSSL #include <string.h> #include "md5.h" /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD5_u32plus a, b, c, d; MD5_u32plus saved_a, saved_b, saved_c, saved_d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while (size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used, available; saved_lo = ctx->lo; if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) ctx->hi++; ctx->hi += size >> 29; used = saved_lo & 0x3f; if (used) { available = 64 - used; if (size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if (size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } void MD5_Final(unsigned char *result, MD5_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if (available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = ctx->lo; ctx->buffer[57] = ctx->lo >> 8; ctx->buffer[58] = ctx->lo >> 16; ctx->buffer[59] = ctx->lo >> 24; ctx->buffer[60] = ctx->hi; ctx->buffer[61] = ctx->hi >> 8; ctx->buffer[62] = ctx->hi >> 16; ctx->buffer[63] = ctx->hi >> 24; body(ctx, ctx->buffer, 64); result[0] = ctx->a; result[1] = ctx->a >> 8; result[2] = ctx->a >> 16; result[3] = ctx->a >> 24; result[4] = ctx->b; result[5] = ctx->b >> 8; result[6] = ctx->b >> 16; result[7] = ctx->b >> 24; result[8] = ctx->c; result[9] = ctx->c >> 8; result[10] = ctx->c >> 16; result[11] = ctx->c >> 24; result[12] = ctx->d; result[13] = ctx->d >> 8; result[14] = ctx->d >> 16; result[15] = ctx->d >> 24; memset(ctx, 0, sizeof(*ctx)); } #endif
YifuLiu/AliOS-Things
components/freetype/src/base/md5.c
C
apache-2.0
8,587
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ #ifdef HAVE_OPENSSL #include <openssl/md5.h> #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); #endif
YifuLiu/AliOS-Things
components/freetype/src/base/md5.h
C
apache-2.0
1,410
# # FreeType 2 base layer configuration rules # # Copyright 1996-2000, 2002-2009, 2013 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # It sets the following variables which are used by the master Makefile # after the call: # # BASE_OBJ_S: The single-object base layer. # BASE_OBJ_M: A list of all objects for a multiple-objects build. # BASE_EXT_OBJ: A list of base layer extensions, i.e., components found # in `src/base' which are not compiled within the base # layer proper. BASE_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(SRC_DIR)/base) # Base layer sources # # ftsystem, ftinit, and ftdebug are handled by freetype.mk # # All files listed here should be included in `ftbase.c' (for a `single' # build). # BASE_SRC := $(BASE_DIR)/basepic.c \ $(BASE_DIR)/ftadvanc.c \ $(BASE_DIR)/ftcalc.c \ $(BASE_DIR)/ftdbgmem.c \ $(BASE_DIR)/ftgloadr.c \ $(BASE_DIR)/ftobjs.c \ $(BASE_DIR)/ftoutln.c \ $(BASE_DIR)/ftpic.c \ $(BASE_DIR)/ftrfork.c \ $(BASE_DIR)/ftsnames.c \ $(BASE_DIR)/ftstream.c \ $(BASE_DIR)/fttrigon.c \ $(BASE_DIR)/ftutil.c ifneq ($(ftmac_c),) BASE_SRC += $(BASE_DIR)/$(ftmac_c) endif # for simplicity, we also handle `md5.c' (which gets included by `ftobjs.h') BASE_H := $(BASE_DIR)/basepic.h \ $(BASE_DIR)/ftbase.h \ $(BASE_DIR)/md5.c \ $(BASE_DIR)/md5.h # Base layer `extensions' sources # # An extension is added to the library file as a separate object. It is # then linked to the final executable only if one of its symbols is used by # the application. # BASE_EXT_SRC := $(patsubst %,$(BASE_DIR)/%,$(BASE_EXTENSIONS)) # Default extensions objects # BASE_EXT_OBJ := $(BASE_EXT_SRC:$(BASE_DIR)/%.c=$(OBJ_DIR)/%.$O) # Base layer object(s) # # BASE_OBJ_M is used during `multi' builds (each base source file compiles # to a single object file). # # BASE_OBJ_S is used during `single' builds (the whole base layer is # compiled as a single object file using ftbase.c). # BASE_OBJ_M := $(BASE_SRC:$(BASE_DIR)/%.c=$(OBJ_DIR)/%.$O) BASE_OBJ_S := $(OBJ_DIR)/ftbase.$O # Base layer root source file for single build # BASE_SRC_S := $(BASE_DIR)/ftbase.c # Base layer - single object build # $(BASE_OBJ_S): $(BASE_SRC_S) $(BASE_SRC) $(FREETYPE_H) $(BASE_H) $(BASE_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(BASE_SRC_S)) # Multiple objects build + extensions # $(OBJ_DIR)/%.$O: $(BASE_DIR)/%.c $(FREETYPE_H) $(BASE_H) $(BASE_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # EOF
YifuLiu/AliOS-Things
components/freetype/src/base/rules.mk
Makefile
apache-2.0
2,966
/* bdf.c FreeType font driver for bdf files Copyright (C) 2001, 2002 by Francesco Zappa Nardelli Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define FT_MAKE_OPTION_SINGLE_OBJECT #include <ft2build.h> #include "bdflib.c" #include "bdfdrivr.c" /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdf.c
C
apache-2.0
1,255
/* * Copyright 2000 Computing Research Labs, New Mexico State University * Copyright 2001-2004, 2011 Francesco Zappa Nardelli * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __BDF_H__ #define __BDF_H__ /* * Based on bdf.h,v 1.16 2000/03/16 20:08:51 mleisher */ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_STREAM_H FT_BEGIN_HEADER /* Imported from bdfP.h */ #define _bdf_glyph_modified( map, e ) \ ( (map)[(e) >> 5] & ( 1 << ( (e) & 31 ) ) ) #define _bdf_set_glyph_modified( map, e ) \ ( (map)[(e) >> 5] |= ( 1 << ( (e) & 31 ) ) ) #define _bdf_clear_glyph_modified( map, e ) \ ( (map)[(e) >> 5] &= ~( 1 << ( (e) & 31 ) ) ) /* end of bdfP.h */ /*************************************************************************/ /* */ /* BDF font options macros and types. */ /* */ /*************************************************************************/ #define BDF_CORRECT_METRICS 0x01 /* Correct invalid metrics when loading. */ #define BDF_KEEP_COMMENTS 0x02 /* Preserve the font comments. */ #define BDF_KEEP_UNENCODED 0x04 /* Keep the unencoded glyphs. */ #define BDF_PROPORTIONAL 0x08 /* Font has proportional spacing. */ #define BDF_MONOWIDTH 0x10 /* Font has mono width. */ #define BDF_CHARCELL 0x20 /* Font has charcell spacing. */ #define BDF_ALL_SPACING ( BDF_PROPORTIONAL | \ BDF_MONOWIDTH | \ BDF_CHARCELL ) #define BDF_DEFAULT_LOAD_OPTIONS ( BDF_CORRECT_METRICS | \ BDF_KEEP_COMMENTS | \ BDF_KEEP_UNENCODED | \ BDF_PROPORTIONAL ) typedef struct bdf_options_t_ { int correct_metrics; int keep_unencoded; int keep_comments; int font_spacing; } bdf_options_t; /* Callback function type for unknown configuration options. */ typedef int (*bdf_options_callback_t)( bdf_options_t* opts, char** params, unsigned long nparams, void* client_data ); /*************************************************************************/ /* */ /* BDF font property macros and types. */ /* */ /*************************************************************************/ #define BDF_ATOM 1 #define BDF_INTEGER 2 #define BDF_CARDINAL 3 /* This structure represents a particular property of a font. */ /* There are a set of defaults and each font has their own. */ typedef struct bdf_property_t_ { char* name; /* Name of the property. */ int format; /* Format of the property. */ int builtin; /* A builtin property. */ union { char* atom; long l; unsigned long ul; } value; /* Value of the property. */ } bdf_property_t; /*************************************************************************/ /* */ /* BDF font metric and glyph types. */ /* */ /*************************************************************************/ typedef struct bdf_bbx_t_ { unsigned short width; unsigned short height; short x_offset; short y_offset; short ascent; short descent; } bdf_bbx_t; typedef struct bdf_glyph_t_ { char* name; /* Glyph name. */ long encoding; /* Glyph encoding. */ unsigned short swidth; /* Scalable width. */ unsigned short dwidth; /* Device width. */ bdf_bbx_t bbx; /* Glyph bounding box. */ unsigned char* bitmap; /* Glyph bitmap. */ unsigned long bpr; /* Number of bytes used per row. */ unsigned short bytes; /* Number of bytes used for the bitmap. */ } bdf_glyph_t; typedef struct _hashnode_ { const char* key; size_t data; } _hashnode, *hashnode; typedef struct hashtable_ { int limit; int size; int used; hashnode* table; } hashtable; typedef struct bdf_glyphlist_t_ { unsigned short pad; /* Pad to 4-byte boundary. */ unsigned short bpp; /* Bits per pixel. */ long start; /* Beginning encoding value of glyphs. */ long end; /* Ending encoding value of glyphs. */ bdf_glyph_t* glyphs; /* Glyphs themselves. */ unsigned long glyphs_size; /* Glyph structures allocated. */ unsigned long glyphs_used; /* Glyph structures used. */ bdf_bbx_t bbx; /* Overall bounding box of glyphs. */ } bdf_glyphlist_t; typedef struct bdf_font_t_ { char* name; /* Name of the font. */ bdf_bbx_t bbx; /* Font bounding box. */ long point_size; /* Point size of the font. */ unsigned long resolution_x; /* Font horizontal resolution. */ unsigned long resolution_y; /* Font vertical resolution. */ int spacing; /* Font spacing value. */ unsigned short monowidth; /* Logical width for monowidth font. */ long default_char; /* Encoding of the default glyph. */ long font_ascent; /* Font ascent. */ long font_descent; /* Font descent. */ unsigned long glyphs_size; /* Glyph structures allocated. */ unsigned long glyphs_used; /* Glyph structures used. */ bdf_glyph_t* glyphs; /* Glyphs themselves. */ unsigned long unencoded_size; /* Unencoded glyph struct. allocated. */ unsigned long unencoded_used; /* Unencoded glyph struct. used. */ bdf_glyph_t* unencoded; /* Unencoded glyphs themselves. */ unsigned long props_size; /* Font properties allocated. */ unsigned long props_used; /* Font properties used. */ bdf_property_t* props; /* Font properties themselves. */ char* comments; /* Font comments. */ unsigned long comments_len; /* Length of comment string. */ bdf_glyphlist_t overflow; /* Storage used for glyph insertion. */ void* internal; /* Internal data for the font. */ /* The size of the next two arrays must be in sync with the */ /* size of the `have' array in the `bdf_parse_t' structure. */ unsigned long nmod[34816]; /* Bitmap indicating modified glyphs. */ unsigned long umod[34816]; /* Bitmap indicating modified */ /* unencoded glyphs. */ unsigned short modified; /* Boolean indicating font modified. */ unsigned short bpp; /* Bits per pixel. */ FT_Memory memory; bdf_property_t* user_props; unsigned long nuser_props; hashtable proptbl; } bdf_font_t; /*************************************************************************/ /* */ /* Types for load/save callbacks. */ /* */ /*************************************************************************/ /* Error codes. */ #define BDF_MISSING_START -1 #define BDF_MISSING_FONTNAME -2 #define BDF_MISSING_SIZE -3 #define BDF_MISSING_CHARS -4 #define BDF_MISSING_STARTCHAR -5 #define BDF_MISSING_ENCODING -6 #define BDF_MISSING_BBX -7 #define BDF_OUT_OF_MEMORY -20 #define BDF_INVALID_LINE -100 /*************************************************************************/ /* */ /* BDF font API. */ /* */ /*************************************************************************/ FT_LOCAL( FT_Error ) bdf_load_font( FT_Stream stream, FT_Memory memory, bdf_options_t* opts, bdf_font_t* *font ); FT_LOCAL( void ) bdf_free_font( bdf_font_t* font ); FT_LOCAL( bdf_property_t * ) bdf_get_property( char* name, bdf_font_t* font ); FT_LOCAL( bdf_property_t * ) bdf_get_font_property( bdf_font_t* font, const char* name ); FT_END_HEADER #endif /* __BDF_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdf.h
C
apache-2.0
10,935
/* bdfdrivr.c FreeType font driver for bdf files Copyright (C) 2001-2008, 2011, 2013, 2014 by Francesco Zappa Nardelli Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_OBJECTS_H #include FT_BDF_H #include FT_TRUETYPE_IDS_H #include FT_SERVICE_BDF_H #include FT_SERVICE_XFREE86_NAME_H #include "bdf.h" #include "bdfdrivr.h" #include "bdferror.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_bdfdriver typedef struct BDF_CMapRec_ { FT_CMapRec cmap; FT_ULong num_encodings; /* ftobjs.h: FT_CMap->clazz->size */ BDF_encoding_el* encodings; } BDF_CMapRec, *BDF_CMap; FT_CALLBACK_DEF( FT_Error ) bdf_cmap_init( FT_CMap bdfcmap, FT_Pointer init_data ) { BDF_CMap cmap = (BDF_CMap)bdfcmap; BDF_Face face = (BDF_Face)FT_CMAP_FACE( cmap ); FT_UNUSED( init_data ); cmap->num_encodings = face->bdffont->glyphs_used; cmap->encodings = face->en_table; return FT_Err_Ok; } FT_CALLBACK_DEF( void ) bdf_cmap_done( FT_CMap bdfcmap ) { BDF_CMap cmap = (BDF_CMap)bdfcmap; cmap->encodings = NULL; cmap->num_encodings = 0; } FT_CALLBACK_DEF( FT_UInt ) bdf_cmap_char_index( FT_CMap bdfcmap, FT_UInt32 charcode ) { BDF_CMap cmap = (BDF_CMap)bdfcmap; BDF_encoding_el* encodings = cmap->encodings; FT_ULong min, max, mid; /* num_encodings */ FT_UShort result = 0; /* encodings->glyph */ min = 0; max = cmap->num_encodings; while ( min < max ) { FT_ULong code; mid = ( min + max ) >> 1; code = encodings[mid].enc; if ( charcode == code ) { /* increase glyph index by 1 -- */ /* we reserve slot 0 for the undefined glyph */ result = encodings[mid].glyph + 1; break; } if ( charcode < code ) max = mid; else min = mid + 1; } return result; } FT_CALLBACK_DEF( FT_UInt ) bdf_cmap_char_next( FT_CMap bdfcmap, FT_UInt32 *acharcode ) { BDF_CMap cmap = (BDF_CMap)bdfcmap; BDF_encoding_el* encodings = cmap->encodings; FT_ULong min, max, mid; /* num_encodings */ FT_UShort result = 0; /* encodings->glyph */ FT_ULong charcode = *acharcode + 1; min = 0; max = cmap->num_encodings; while ( min < max ) { FT_ULong code; /* same as BDF_encoding_el.enc */ mid = ( min + max ) >> 1; code = encodings[mid].enc; if ( charcode == code ) { /* increase glyph index by 1 -- */ /* we reserve slot 0 for the undefined glyph */ result = encodings[mid].glyph + 1; goto Exit; } if ( charcode < code ) max = mid; else min = mid + 1; } charcode = 0; if ( min < cmap->num_encodings ) { charcode = encodings[min].enc; result = encodings[min].glyph + 1; } Exit: if ( charcode > 0xFFFFFFFFUL ) { FT_TRACE1(( "bdf_cmap_char_next: charcode 0x%x > 32bit API" )); *acharcode = 0; /* XXX: result should be changed to indicate an overflow error */ } else *acharcode = (FT_UInt32)charcode; return result; } FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec bdf_cmap_class = { sizeof ( BDF_CMapRec ), bdf_cmap_init, bdf_cmap_done, bdf_cmap_char_index, bdf_cmap_char_next, NULL, NULL, NULL, NULL, NULL }; static FT_Error bdf_interpret_style( BDF_Face bdf ) { FT_Error error = FT_Err_Ok; FT_Face face = FT_FACE( bdf ); FT_Memory memory = face->memory; bdf_font_t* font = bdf->bdffont; bdf_property_t* prop; char* strings[4] = { NULL, NULL, NULL, NULL }; size_t nn, len, lengths[4]; face->style_flags = 0; prop = bdf_get_font_property( font, (char *)"SLANT" ); if ( prop && prop->format == BDF_ATOM && prop->value.atom && ( *(prop->value.atom) == 'O' || *(prop->value.atom) == 'o' || *(prop->value.atom) == 'I' || *(prop->value.atom) == 'i' ) ) { face->style_flags |= FT_STYLE_FLAG_ITALIC; strings[2] = ( *(prop->value.atom) == 'O' || *(prop->value.atom) == 'o' ) ? (char *)"Oblique" : (char *)"Italic"; } prop = bdf_get_font_property( font, (char *)"WEIGHT_NAME" ); if ( prop && prop->format == BDF_ATOM && prop->value.atom && ( *(prop->value.atom) == 'B' || *(prop->value.atom) == 'b' ) ) { face->style_flags |= FT_STYLE_FLAG_BOLD; strings[1] = (char *)"Bold"; } prop = bdf_get_font_property( font, (char *)"SETWIDTH_NAME" ); if ( prop && prop->format == BDF_ATOM && prop->value.atom && *(prop->value.atom) && !( *(prop->value.atom) == 'N' || *(prop->value.atom) == 'n' ) ) strings[3] = (char *)(prop->value.atom); prop = bdf_get_font_property( font, (char *)"ADD_STYLE_NAME" ); if ( prop && prop->format == BDF_ATOM && prop->value.atom && *(prop->value.atom) && !( *(prop->value.atom) == 'N' || *(prop->value.atom) == 'n' ) ) strings[0] = (char *)(prop->value.atom); for ( len = 0, nn = 0; nn < 4; nn++ ) { lengths[nn] = 0; if ( strings[nn] ) { lengths[nn] = ft_strlen( strings[nn] ); len += lengths[nn] + 1; } } if ( len == 0 ) { strings[0] = (char *)"Regular"; lengths[0] = ft_strlen( strings[0] ); len = lengths[0] + 1; } { char* s; if ( FT_ALLOC( face->style_name, len ) ) return error; s = face->style_name; for ( nn = 0; nn < 4; nn++ ) { char* src = strings[nn]; len = lengths[nn]; if ( src == NULL ) continue; /* separate elements with a space */ if ( s != face->style_name ) *s++ = ' '; ft_memcpy( s, src, len ); /* need to convert spaces to dashes for */ /* add_style_name and setwidth_name */ if ( nn == 0 || nn == 3 ) { size_t mm; for ( mm = 0; mm < len; mm++ ) if ( s[mm] == ' ' ) s[mm] = '-'; } s += len; } *s = 0; } return error; } FT_CALLBACK_DEF( void ) BDF_Face_Done( FT_Face bdfface ) /* BDF_Face */ { BDF_Face face = (BDF_Face)bdfface; FT_Memory memory; if ( !face ) return; memory = FT_FACE_MEMORY( face ); bdf_free_font( face->bdffont ); FT_FREE( face->en_table ); FT_FREE( face->charset_encoding ); FT_FREE( face->charset_registry ); FT_FREE( bdfface->family_name ); FT_FREE( bdfface->style_name ); FT_FREE( bdfface->available_sizes ); FT_FREE( face->bdffont ); } FT_CALLBACK_DEF( FT_Error ) BDF_Face_Init( FT_Stream stream, FT_Face bdfface, /* BDF_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error = FT_Err_Ok; BDF_Face face = (BDF_Face)bdfface; FT_Memory memory = FT_FACE_MEMORY( face ); bdf_font_t* font = NULL; bdf_options_t options; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_TRACE2(( "BDF driver\n" )); if ( FT_STREAM_SEEK( 0 ) ) goto Exit; options.correct_metrics = 1; /* FZ XXX: options semantics */ options.keep_unencoded = 1; options.keep_comments = 0; options.font_spacing = BDF_PROPORTIONAL; error = bdf_load_font( stream, memory, &options, &font ); if ( FT_ERR_EQ( error, Missing_Startfont_Field ) ) { FT_TRACE2(( " not a BDF file\n" )); goto Fail; } else if ( error ) goto Exit; /* we have a bdf font: let's construct the face object */ face->bdffont = font; /* BDF could not have multiple face in single font file. * XXX: non-zero face_index is already invalid argument, but * Type1, Type42 driver has a convention to return * an invalid argument error when the font could be * opened by the specified driver. */ if ( face_index > 0 ) { FT_ERROR(( "BDF_Face_Init: invalid face index\n" )); BDF_Face_Done( bdfface ); return FT_THROW( Invalid_Argument ); } { bdf_property_t* prop = NULL; FT_TRACE4(( " number of glyphs: allocated %d (used %d)\n", font->glyphs_size, font->glyphs_used )); FT_TRACE4(( " number of unencoded glyphs: allocated %d (used %d)\n", font->unencoded_size, font->unencoded_used )); bdfface->num_faces = 1; bdfface->face_index = 0; bdfface->face_flags |= FT_FACE_FLAG_FIXED_SIZES | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_FAST_GLYPHS; prop = bdf_get_font_property( font, "SPACING" ); if ( prop && prop->format == BDF_ATOM && prop->value.atom && ( *(prop->value.atom) == 'M' || *(prop->value.atom) == 'm' || *(prop->value.atom) == 'C' || *(prop->value.atom) == 'c' ) ) bdfface->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* FZ XXX: TO DO: FT_FACE_FLAGS_VERTICAL */ /* FZ XXX: I need a font to implement this */ prop = bdf_get_font_property( font, "FAMILY_NAME" ); if ( prop && prop->value.atom ) { if ( FT_STRDUP( bdfface->family_name, prop->value.atom ) ) goto Exit; } else bdfface->family_name = 0; if ( ( error = bdf_interpret_style( face ) ) != 0 ) goto Exit; /* the number of glyphs (with one slot for the undefined glyph */ /* at position 0 and all unencoded glyphs) */ bdfface->num_glyphs = font->glyphs_size + 1; bdfface->num_fixed_sizes = 1; if ( FT_NEW_ARRAY( bdfface->available_sizes, 1 ) ) goto Exit; { FT_Bitmap_Size* bsize = bdfface->available_sizes; FT_Short resolution_x = 0, resolution_y = 0; FT_MEM_ZERO( bsize, sizeof ( FT_Bitmap_Size ) ); bsize->height = (FT_Short)( font->font_ascent + font->font_descent ); prop = bdf_get_font_property( font, "AVERAGE_WIDTH" ); if ( prop ) bsize->width = (FT_Short)( ( prop->value.l + 5 ) / 10 ); else bsize->width = (FT_Short)( bsize->height * 2/3 ); prop = bdf_get_font_property( font, "POINT_SIZE" ); if ( prop ) /* convert from 722.7 decipoints to 72 points per inch */ bsize->size = (FT_Pos)( ( prop->value.l * 64 * 7200 + 36135L ) / 72270L ); else bsize->size = bsize->width << 6; prop = bdf_get_font_property( font, "PIXEL_SIZE" ); if ( prop ) bsize->y_ppem = (FT_Short)prop->value.l << 6; prop = bdf_get_font_property( font, "RESOLUTION_X" ); if ( prop ) resolution_x = (FT_Short)prop->value.l; prop = bdf_get_font_property( font, "RESOLUTION_Y" ); if ( prop ) resolution_y = (FT_Short)prop->value.l; if ( bsize->y_ppem == 0 ) { bsize->y_ppem = bsize->size; if ( resolution_y ) bsize->y_ppem = bsize->y_ppem * resolution_y / 72; } if ( resolution_x && resolution_y ) bsize->x_ppem = bsize->y_ppem * resolution_x / resolution_y; else bsize->x_ppem = bsize->y_ppem; } /* encoding table */ { bdf_glyph_t* cur = font->glyphs; unsigned long n; if ( FT_NEW_ARRAY( face->en_table, font->glyphs_size ) ) goto Exit; face->default_glyph = 0; for ( n = 0; n < font->glyphs_size; n++ ) { (face->en_table[n]).enc = cur[n].encoding; FT_TRACE4(( " idx %d, val 0x%lX\n", n, cur[n].encoding )); (face->en_table[n]).glyph = (FT_Short)n; if ( cur[n].encoding == font->default_char ) { if ( n < FT_UINT_MAX ) face->default_glyph = (FT_UInt)n; else FT_TRACE1(( "BDF_Face_Init:" " idx %d is too large for this system\n", n )); } } } /* charmaps */ { bdf_property_t *charset_registry = 0, *charset_encoding = 0; FT_Bool unicode_charmap = 0; charset_registry = bdf_get_font_property( font, "CHARSET_REGISTRY" ); charset_encoding = bdf_get_font_property( font, "CHARSET_ENCODING" ); if ( charset_registry && charset_encoding ) { if ( charset_registry->format == BDF_ATOM && charset_encoding->format == BDF_ATOM && charset_registry->value.atom && charset_encoding->value.atom ) { const char* s; if ( FT_STRDUP( face->charset_encoding, charset_encoding->value.atom ) || FT_STRDUP( face->charset_registry, charset_registry->value.atom ) ) goto Exit; /* Uh, oh, compare first letters manually to avoid dependency */ /* on locales. */ s = face->charset_registry; if ( ( s[0] == 'i' || s[0] == 'I' ) && ( s[1] == 's' || s[1] == 'S' ) && ( s[2] == 'o' || s[2] == 'O' ) ) { s += 3; if ( !ft_strcmp( s, "10646" ) || ( !ft_strcmp( s, "8859" ) && !ft_strcmp( face->charset_encoding, "1" ) ) ) unicode_charmap = 1; } { FT_CharMapRec charmap; charmap.face = FT_FACE( face ); charmap.encoding = FT_ENCODING_NONE; /* initial platform/encoding should indicate unset status? */ charmap.platform_id = TT_PLATFORM_APPLE_UNICODE; charmap.encoding_id = TT_APPLE_ID_DEFAULT; if ( unicode_charmap ) { charmap.encoding = FT_ENCODING_UNICODE; charmap.platform_id = TT_PLATFORM_MICROSOFT; charmap.encoding_id = TT_MS_ID_UNICODE_CS; } error = FT_CMap_New( &bdf_cmap_class, NULL, &charmap, NULL ); #if 0 /* Select default charmap */ if ( bdfface->num_charmaps ) bdfface->charmap = bdfface->charmaps[0]; #endif } goto Exit; } } /* otherwise assume Adobe standard encoding */ { FT_CharMapRec charmap; charmap.face = FT_FACE( face ); charmap.encoding = FT_ENCODING_ADOBE_STANDARD; charmap.platform_id = TT_PLATFORM_ADOBE; charmap.encoding_id = TT_ADOBE_ID_STANDARD; error = FT_CMap_New( &bdf_cmap_class, NULL, &charmap, NULL ); /* Select default charmap */ if ( bdfface->num_charmaps ) bdfface->charmap = bdfface->charmaps[0]; } } } Exit: return error; Fail: BDF_Face_Done( bdfface ); return FT_THROW( Unknown_File_Format ); } FT_CALLBACK_DEF( FT_Error ) BDF_Size_Select( FT_Size size, FT_ULong strike_index ) { bdf_font_t* bdffont = ( (BDF_Face)size->face )->bdffont; FT_Select_Metrics( size->face, strike_index ); size->metrics.ascender = bdffont->font_ascent << 6; size->metrics.descender = -bdffont->font_descent << 6; size->metrics.max_advance = bdffont->bbx.width << 6; return FT_Err_Ok; } FT_CALLBACK_DEF( FT_Error ) BDF_Size_Request( FT_Size size, FT_Size_Request req ) { FT_Face face = size->face; FT_Bitmap_Size* bsize = face->available_sizes; bdf_font_t* bdffont = ( (BDF_Face)face )->bdffont; FT_Error error = FT_ERR( Invalid_Pixel_Size ); FT_Long height; height = FT_REQUEST_HEIGHT( req ); height = ( height + 32 ) >> 6; switch ( req->type ) { case FT_SIZE_REQUEST_TYPE_NOMINAL: if ( height == ( ( bsize->y_ppem + 32 ) >> 6 ) ) error = FT_Err_Ok; break; case FT_SIZE_REQUEST_TYPE_REAL_DIM: if ( height == ( bdffont->font_ascent + bdffont->font_descent ) ) error = FT_Err_Ok; break; default: error = FT_THROW( Unimplemented_Feature ); break; } if ( error ) return error; else return BDF_Size_Select( size, 0 ); } FT_CALLBACK_DEF( FT_Error ) BDF_Glyph_Load( FT_GlyphSlot slot, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { BDF_Face bdf = (BDF_Face)FT_SIZE_FACE( size ); FT_Face face = FT_FACE( bdf ); FT_Error error = FT_Err_Ok; FT_Bitmap* bitmap = &slot->bitmap; bdf_glyph_t glyph; int bpp = bdf->bdffont->bpp; FT_UNUSED( load_flags ); if ( !face || glyph_index >= (FT_UInt)face->num_glyphs ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_TRACE1(( "BDF_Glyph_Load: glyph index %d\n", glyph_index )); /* index 0 is the undefined glyph */ if ( glyph_index == 0 ) glyph_index = bdf->default_glyph; else glyph_index--; /* slot, bitmap => freetype, glyph => bdflib */ glyph = bdf->bdffont->glyphs[glyph_index]; bitmap->rows = glyph.bbx.height; bitmap->width = glyph.bbx.width; if ( glyph.bpr > INT_MAX ) FT_TRACE1(( "BDF_Glyph_Load: too large pitch %d is truncated\n", glyph.bpr )); bitmap->pitch = (int)glyph.bpr; /* same as FT_Bitmap.pitch */ /* note: we don't allocate a new array to hold the bitmap; */ /* we can simply point to it */ ft_glyphslot_set_bitmap( slot, glyph.bitmap ); switch ( bpp ) { case 1: bitmap->pixel_mode = FT_PIXEL_MODE_MONO; break; case 2: bitmap->pixel_mode = FT_PIXEL_MODE_GRAY2; break; case 4: bitmap->pixel_mode = FT_PIXEL_MODE_GRAY4; break; case 8: bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; break; } slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = glyph.bbx.x_offset; slot->bitmap_top = glyph.bbx.ascent; slot->metrics.horiAdvance = glyph.dwidth << 6; slot->metrics.horiBearingX = glyph.bbx.x_offset << 6; slot->metrics.horiBearingY = glyph.bbx.ascent << 6; slot->metrics.width = bitmap->width << 6; slot->metrics.height = bitmap->rows << 6; /* * XXX DWIDTH1 and VVECTOR should be parsed and * used here, provided such fonts do exist. */ ft_synthesize_vertical_metrics( &slot->metrics, bdf->bdffont->bbx.height << 6 ); Exit: return error; } /* * * BDF SERVICE * */ static FT_Error bdf_get_bdf_property( BDF_Face face, const char* prop_name, BDF_PropertyRec *aproperty ) { bdf_property_t* prop; FT_ASSERT( face && face->bdffont ); prop = bdf_get_font_property( face->bdffont, prop_name ); if ( prop ) { switch ( prop->format ) { case BDF_ATOM: aproperty->type = BDF_PROPERTY_TYPE_ATOM; aproperty->u.atom = prop->value.atom; break; case BDF_INTEGER: if ( prop->value.l > 0x7FFFFFFFL || prop->value.l < ( -1 - 0x7FFFFFFFL ) ) { FT_TRACE1(( "bdf_get_bdf_property:" " too large integer 0x%x is truncated\n" )); } aproperty->type = BDF_PROPERTY_TYPE_INTEGER; aproperty->u.integer = (FT_Int32)prop->value.l; break; case BDF_CARDINAL: if ( prop->value.ul > 0xFFFFFFFFUL ) { FT_TRACE1(( "bdf_get_bdf_property:" " too large cardinal 0x%x is truncated\n" )); } aproperty->type = BDF_PROPERTY_TYPE_CARDINAL; aproperty->u.cardinal = (FT_UInt32)prop->value.ul; break; default: goto Fail; } return 0; } Fail: return FT_THROW( Invalid_Argument ); } static FT_Error bdf_get_charset_id( BDF_Face face, const char* *acharset_encoding, const char* *acharset_registry ) { *acharset_encoding = face->charset_encoding; *acharset_registry = face->charset_registry; return 0; } static const FT_Service_BDFRec bdf_service_bdf = { (FT_BDF_GetCharsetIdFunc)bdf_get_charset_id, (FT_BDF_GetPropertyFunc) bdf_get_bdf_property }; /* * * SERVICES LIST * */ static const FT_ServiceDescRec bdf_services[] = { { FT_SERVICE_ID_BDF, &bdf_service_bdf }, { FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_BDF }, { NULL, NULL } }; FT_CALLBACK_DEF( FT_Module_Interface ) bdf_driver_requester( FT_Module module, const char* name ) { FT_UNUSED( module ); return ft_service_list_lookup( bdf_services, name ); } FT_CALLBACK_TABLE_DEF const FT_Driver_ClassRec bdf_driver_class = { { FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_NO_OUTLINES, sizeof ( FT_DriverRec ), "bdf", 0x10000L, 0x20000L, 0, 0, /* FT_Module_Constructor */ 0, /* FT_Module_Destructor */ bdf_driver_requester }, sizeof ( BDF_FaceRec ), sizeof ( FT_SizeRec ), sizeof ( FT_GlyphSlotRec ), BDF_Face_Init, BDF_Face_Done, 0, /* FT_Size_InitFunc */ 0, /* FT_Size_DoneFunc */ 0, /* FT_Slot_InitFunc */ 0, /* FT_Slot_DoneFunc */ BDF_Glyph_Load, 0, /* FT_Face_GetKerningFunc */ 0, /* FT_Face_AttachFunc */ 0, /* FT_Face_GetAdvancesFunc */ BDF_Size_Request, BDF_Size_Select }; /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdfdrivr.c
C
apache-2.0
24,585
/* bdfdrivr.h FreeType font driver for bdf fonts Copyright (C) 2001, 2002, 2003, 2004 by Francesco Zappa Nardelli Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __BDFDRIVR_H__ #define __BDFDRIVR_H__ #include <ft2build.h> #include FT_INTERNAL_DRIVER_H #include "bdf.h" FT_BEGIN_HEADER #ifdef FT_CONFIG_OPTION_PIC #error "this module does not support PIC yet" #endif typedef struct BDF_encoding_el_ { FT_ULong enc; FT_UShort glyph; } BDF_encoding_el; typedef struct BDF_FaceRec_ { FT_FaceRec root; char* charset_encoding; char* charset_registry; bdf_font_t* bdffont; BDF_encoding_el* en_table; FT_CharMap charmap_handle; FT_CharMapRec charmap; /* a single charmap per face */ FT_UInt default_glyph; } BDF_FaceRec, *BDF_Face; FT_EXPORT_VAR( const FT_Driver_ClassRec ) bdf_driver_class; FT_END_HEADER #endif /* __BDFDRIVR_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdfdrivr.h
C
apache-2.0
1,981
/* * Copyright 2001, 2002, 2012 Francesco Zappa Nardelli * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ /* */ /* This file is used to define the BDF error enumeration constants. */ /* */ /*************************************************************************/ #ifndef __BDFERROR_H__ #define __BDFERROR_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX BDF_Err_ #define FT_ERR_BASE FT_Mod_Err_BDF #include FT_ERRORS_H #endif /* __BDFERROR_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdferror.h
C
apache-2.0
1,809
/* * Copyright 2000 Computing Research Labs, New Mexico State University * Copyright 2001-2014 * Francesco Zappa Nardelli * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ /* */ /* This file is based on bdf.c,v 1.22 2000/03/16 20:08:50 */ /* */ /* taken from Mark Leisher's xmbdfed package */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_FREETYPE_H #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_OBJECTS_H #include "bdf.h" #include "bdferror.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_bdflib /*************************************************************************/ /* */ /* Default BDF font options. */ /* */ /*************************************************************************/ static const bdf_options_t _bdf_opts = { 1, /* Correct metrics. */ 1, /* Preserve unencoded glyphs. */ 0, /* Preserve comments. */ BDF_PROPORTIONAL /* Default spacing. */ }; /*************************************************************************/ /* */ /* Builtin BDF font properties. */ /* */ /*************************************************************************/ /* List of most properties that might appear in a font. Doesn't include */ /* the RAW_* and AXIS_* properties in X11R6 polymorphic fonts. */ static const bdf_property_t _bdf_properties[] = { { (char *)"ADD_STYLE_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"AVERAGE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"AVG_CAPITAL_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"AVG_LOWERCASE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"CAP_HEIGHT", BDF_INTEGER, 1, { 0 } }, { (char *)"CHARSET_COLLECTIONS", BDF_ATOM, 1, { 0 } }, { (char *)"CHARSET_ENCODING", BDF_ATOM, 1, { 0 } }, { (char *)"CHARSET_REGISTRY", BDF_ATOM, 1, { 0 } }, { (char *)"COMMENT", BDF_ATOM, 1, { 0 } }, { (char *)"COPYRIGHT", BDF_ATOM, 1, { 0 } }, { (char *)"DEFAULT_CHAR", BDF_CARDINAL, 1, { 0 } }, { (char *)"DESTINATION", BDF_CARDINAL, 1, { 0 } }, { (char *)"DEVICE_FONT_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"END_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"FACE_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"FAMILY_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"FIGURE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"FONT", BDF_ATOM, 1, { 0 } }, { (char *)"FONTNAME_REGISTRY", BDF_ATOM, 1, { 0 } }, { (char *)"FONT_ASCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"FONT_DESCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"FOUNDRY", BDF_ATOM, 1, { 0 } }, { (char *)"FULL_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"ITALIC_ANGLE", BDF_INTEGER, 1, { 0 } }, { (char *)"MAX_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"MIN_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"NORM_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"NOTICE", BDF_ATOM, 1, { 0 } }, { (char *)"PIXEL_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"POINT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"QUAD_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_ASCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_AVERAGE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_AVG_CAPITAL_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_AVG_LOWERCASE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_CAP_HEIGHT", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_DESCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_END_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_FIGURE_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_MAX_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_MIN_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_NORM_SPACE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_PIXEL_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_POINT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_PIXELSIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_POINTSIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_QUAD_WIDTH", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SMALL_CAP_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_STRIKEOUT_ASCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_STRIKEOUT_DESCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUBSCRIPT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUBSCRIPT_X", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUBSCRIPT_Y", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUPERSCRIPT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUPERSCRIPT_X", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_SUPERSCRIPT_Y", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_UNDERLINE_POSITION", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_UNDERLINE_THICKNESS", BDF_INTEGER, 1, { 0 } }, { (char *)"RAW_X_HEIGHT", BDF_INTEGER, 1, { 0 } }, { (char *)"RELATIVE_SETWIDTH", BDF_CARDINAL, 1, { 0 } }, { (char *)"RELATIVE_WEIGHT", BDF_CARDINAL, 1, { 0 } }, { (char *)"RESOLUTION", BDF_INTEGER, 1, { 0 } }, { (char *)"RESOLUTION_X", BDF_CARDINAL, 1, { 0 } }, { (char *)"RESOLUTION_Y", BDF_CARDINAL, 1, { 0 } }, { (char *)"SETWIDTH_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"SLANT", BDF_ATOM, 1, { 0 } }, { (char *)"SMALL_CAP_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"SPACING", BDF_ATOM, 1, { 0 } }, { (char *)"STRIKEOUT_ASCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"STRIKEOUT_DESCENT", BDF_INTEGER, 1, { 0 } }, { (char *)"SUBSCRIPT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"SUBSCRIPT_X", BDF_INTEGER, 1, { 0 } }, { (char *)"SUBSCRIPT_Y", BDF_INTEGER, 1, { 0 } }, { (char *)"SUPERSCRIPT_SIZE", BDF_INTEGER, 1, { 0 } }, { (char *)"SUPERSCRIPT_X", BDF_INTEGER, 1, { 0 } }, { (char *)"SUPERSCRIPT_Y", BDF_INTEGER, 1, { 0 } }, { (char *)"UNDERLINE_POSITION", BDF_INTEGER, 1, { 0 } }, { (char *)"UNDERLINE_THICKNESS", BDF_INTEGER, 1, { 0 } }, { (char *)"WEIGHT", BDF_CARDINAL, 1, { 0 } }, { (char *)"WEIGHT_NAME", BDF_ATOM, 1, { 0 } }, { (char *)"X_HEIGHT", BDF_INTEGER, 1, { 0 } }, { (char *)"_MULE_BASELINE_OFFSET", BDF_INTEGER, 1, { 0 } }, { (char *)"_MULE_RELATIVE_COMPOSE", BDF_INTEGER, 1, { 0 } }, }; static const unsigned long _num_bdf_properties = sizeof ( _bdf_properties ) / sizeof ( _bdf_properties[0] ); /* Auto correction messages. */ #define ACMSG1 "FONT_ASCENT property missing. " \ "Added `FONT_ASCENT %hd'.\n" #define ACMSG2 "FONT_DESCENT property missing. " \ "Added `FONT_DESCENT %hd'.\n" #define ACMSG3 "Font width != actual width. Old: %hd New: %hd.\n" #define ACMSG4 "Font left bearing != actual left bearing. " \ "Old: %hd New: %hd.\n" #define ACMSG5 "Font ascent != actual ascent. Old: %hd New: %hd.\n" #define ACMSG6 "Font descent != actual descent. Old: %hd New: %hd.\n" #define ACMSG7 "Font height != actual height. Old: %hd New: %hd.\n" #define ACMSG8 "Glyph scalable width (SWIDTH) adjustments made.\n" #define ACMSG9 "SWIDTH field missing at line %ld. Set automatically.\n" #define ACMSG10 "DWIDTH field missing at line %ld. Set to glyph width.\n" #define ACMSG11 "SIZE bits per pixel field adjusted to %hd.\n" #define ACMSG12 "Duplicate encoding %ld (%s) changed to unencoded.\n" #define ACMSG13 "Glyph %ld extra rows removed.\n" #define ACMSG14 "Glyph %ld extra columns removed.\n" #define ACMSG15 "Incorrect glyph count: %ld indicated but %ld found.\n" #define ACMSG16 "Glyph %ld missing columns padded with zero bits.\n" /* Error messages. */ #define ERRMSG1 "[line %ld] Missing `%s' line.\n" #define ERRMSG2 "[line %ld] Font header corrupted or missing fields.\n" #define ERRMSG3 "[line %ld] Font glyphs corrupted or missing fields.\n" #define ERRMSG4 "[line %ld] BBX too big.\n" #define ERRMSG5 "[line %ld] `%s' value too big.\n" #define ERRMSG6 "[line %ld] Input line too long.\n" #define ERRMSG7 "[line %ld] Font name too long.\n" #define ERRMSG8 "[line %ld] Invalid `%s' value.\n" #define ERRMSG9 "[line %ld] Invalid keyword.\n" /* Debug messages. */ #define DBGMSG1 " [%6ld] %s" /* no \n */ #define DBGMSG2 " (0x%lX)\n" /*************************************************************************/ /* */ /* Hash table utilities for the properties. */ /* */ /*************************************************************************/ /* XXX: Replace this with FreeType's hash functions */ #define INITIAL_HT_SIZE 241 typedef void (*hash_free_func)( hashnode node ); static hashnode* hash_bucket( const char* key, hashtable* ht ) { const char* kp = key; unsigned long res = 0; hashnode* bp = ht->table, *ndp; /* Mocklisp hash function. */ while ( *kp ) res = ( res << 5 ) - res + *kp++; ndp = bp + ( res % ht->size ); while ( *ndp ) { kp = (*ndp)->key; if ( kp[0] == key[0] && ft_strcmp( kp, key ) == 0 ) break; ndp--; if ( ndp < bp ) ndp = bp + ( ht->size - 1 ); } return ndp; } static FT_Error hash_rehash( hashtable* ht, FT_Memory memory ) { hashnode* obp = ht->table, *bp, *nbp; int i, sz = ht->size; FT_Error error = FT_Err_Ok; ht->size <<= 1; ht->limit = ht->size / 3; if ( FT_NEW_ARRAY( ht->table, ht->size ) ) goto Exit; for ( i = 0, bp = obp; i < sz; i++, bp++ ) { if ( *bp ) { nbp = hash_bucket( (*bp)->key, ht ); *nbp = *bp; } } FT_FREE( obp ); Exit: return error; } static FT_Error hash_init( hashtable* ht, FT_Memory memory ) { int sz = INITIAL_HT_SIZE; FT_Error error = FT_Err_Ok; ht->size = sz; ht->limit = sz / 3; ht->used = 0; if ( FT_NEW_ARRAY( ht->table, sz ) ) goto Exit; Exit: return error; } static void hash_free( hashtable* ht, FT_Memory memory ) { if ( ht != 0 ) { int i, sz = ht->size; hashnode* bp = ht->table; for ( i = 0; i < sz; i++, bp++ ) FT_FREE( *bp ); FT_FREE( ht->table ); } } static FT_Error hash_insert( char* key, size_t data, hashtable* ht, FT_Memory memory ) { hashnode nn; hashnode* bp = hash_bucket( key, ht ); FT_Error error = FT_Err_Ok; nn = *bp; if ( !nn ) { if ( FT_NEW( nn ) ) goto Exit; *bp = nn; nn->key = key; nn->data = data; if ( ht->used >= ht->limit ) { error = hash_rehash( ht, memory ); if ( error ) goto Exit; } ht->used++; } else nn->data = data; Exit: return error; } static hashnode hash_lookup( const char* key, hashtable* ht ) { hashnode *np = hash_bucket( key, ht ); return *np; } /*************************************************************************/ /* */ /* Utility types and functions. */ /* */ /*************************************************************************/ /* Function type for parsing lines of a BDF font. */ typedef FT_Error (*_bdf_line_func_t)( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ); /* List structure for splitting lines into fields. */ typedef struct _bdf_list_t_ { char** field; unsigned long size; unsigned long used; FT_Memory memory; } _bdf_list_t; /* Structure used while loading BDF fonts. */ typedef struct _bdf_parse_t_ { unsigned long flags; unsigned long cnt; unsigned long row; short minlb; short maxlb; short maxrb; short maxas; short maxds; short rbearing; char* glyph_name; long glyph_enc; bdf_font_t* font; bdf_options_t* opts; unsigned long have[34816]; /* must be in sync with `nmod' and `umod' */ /* arrays from `bdf_font_t' structure */ _bdf_list_t list; FT_Memory memory; } _bdf_parse_t; #define setsbit( m, cc ) \ ( m[(FT_Byte)(cc) >> 3] |= (FT_Byte)( 1 << ( (cc) & 7 ) ) ) #define sbitset( m, cc ) \ ( m[(FT_Byte)(cc) >> 3] & ( 1 << ( (cc) & 7 ) ) ) static void _bdf_list_init( _bdf_list_t* list, FT_Memory memory ) { FT_ZERO( list ); list->memory = memory; } static void _bdf_list_done( _bdf_list_t* list ) { FT_Memory memory = list->memory; if ( memory ) { FT_FREE( list->field ); FT_ZERO( list ); } } static FT_Error _bdf_list_ensure( _bdf_list_t* list, unsigned long num_items ) /* same as _bdf_list_t.used */ { FT_Error error = FT_Err_Ok; if ( num_items > list->size ) { unsigned long oldsize = list->size; /* same as _bdf_list_t.size */ unsigned long newsize = oldsize + ( oldsize >> 1 ) + 5; unsigned long bigsize = (unsigned long)( FT_INT_MAX / sizeof ( char* ) ); FT_Memory memory = list->memory; if ( oldsize == bigsize ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } else if ( newsize < oldsize || newsize > bigsize ) newsize = bigsize; if ( FT_RENEW_ARRAY( list->field, oldsize, newsize ) ) goto Exit; list->size = newsize; } Exit: return error; } static void _bdf_list_shift( _bdf_list_t* list, unsigned long n ) { unsigned long i, u; if ( list == 0 || list->used == 0 || n == 0 ) return; if ( n >= list->used ) { list->used = 0; return; } for ( u = n, i = 0; u < list->used; i++, u++ ) list->field[i] = list->field[u]; list->used -= n; } /* An empty string for empty fields. */ static const char empty[1] = { 0 }; /* XXX eliminate this */ static char * _bdf_list_join( _bdf_list_t* list, int c, unsigned long *alen ) { unsigned long i, j; char* dp; *alen = 0; if ( list == 0 || list->used == 0 ) return 0; dp = list->field[0]; for ( i = j = 0; i < list->used; i++ ) { char* fp = list->field[i]; while ( *fp ) dp[j++] = *fp++; if ( i + 1 < list->used ) dp[j++] = (char)c; } if ( dp != empty ) dp[j] = 0; *alen = j; return dp; } /* The code below ensures that we have at least 4 + 1 `field' */ /* elements in `list' (which are possibly NULL) so that we */ /* don't have to check the number of fields in most cases. */ static FT_Error _bdf_list_split( _bdf_list_t* list, char* separators, char* line, unsigned long linelen ) { int mult, final_empty; char *sp, *ep, *end; char seps[32]; FT_Error error = FT_Err_Ok; /* Initialize the list. */ list->used = 0; if ( list->size ) { list->field[0] = (char*)empty; list->field[1] = (char*)empty; list->field[2] = (char*)empty; list->field[3] = (char*)empty; list->field[4] = (char*)empty; } /* If the line is empty, then simply return. */ if ( linelen == 0 || line[0] == 0 ) goto Exit; /* In the original code, if the `separators' parameter is NULL or */ /* empty, the list is split into individual bytes. We don't need */ /* this, so an error is signaled. */ if ( separators == 0 || *separators == 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } /* Prepare the separator bitmap. */ FT_MEM_ZERO( seps, 32 ); /* If the very last character of the separator string is a plus, then */ /* set the `mult' flag to indicate that multiple separators should be */ /* collapsed into one. */ for ( mult = 0, sp = separators; sp && *sp; sp++ ) { if ( *sp == '+' && *( sp + 1 ) == 0 ) mult = 1; else setsbit( seps, *sp ); } /* Break the line up into fields. */ for ( final_empty = 0, sp = ep = line, end = sp + linelen; sp < end && *sp; ) { /* Collect everything that is not a separator. */ for ( ; *ep && !sbitset( seps, *ep ); ep++ ) ; /* Resize the list if necessary. */ if ( list->used == list->size ) { error = _bdf_list_ensure( list, list->used + 1 ); if ( error ) goto Exit; } /* Assign the field appropriately. */ list->field[list->used++] = ( ep > sp ) ? sp : (char*)empty; sp = ep; if ( mult ) { /* If multiple separators should be collapsed, do it now by */ /* setting all the separator characters to 0. */ for ( ; *ep && sbitset( seps, *ep ); ep++ ) *ep = 0; } else if ( *ep != 0 ) /* Don't collapse multiple separators by making them 0, so just */ /* make the one encountered 0. */ *ep++ = 0; final_empty = ( ep > sp && *ep == 0 ); sp = ep; } /* Finally, NULL-terminate the list. */ if ( list->used + final_empty >= list->size ) { error = _bdf_list_ensure( list, list->used + final_empty + 1 ); if ( error ) goto Exit; } if ( final_empty ) list->field[list->used++] = (char*)empty; list->field[list->used] = 0; Exit: return error; } #define NO_SKIP 256 /* this value cannot be stored in a 'char' */ static FT_Error _bdf_readstream( FT_Stream stream, _bdf_line_func_t callback, void* client_data, unsigned long *lno ) { _bdf_line_func_t cb; unsigned long lineno, buf_size; int refill, hold, to_skip; ptrdiff_t bytes, start, end, cursor, avail; char* buf = 0; FT_Memory memory = stream->memory; FT_Error error = FT_Err_Ok; if ( callback == 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } /* initial size and allocation of the input buffer */ buf_size = 1024; if ( FT_NEW_ARRAY( buf, buf_size ) ) goto Exit; cb = callback; lineno = 1; buf[0] = 0; start = 0; avail = 0; cursor = 0; refill = 1; to_skip = NO_SKIP; bytes = 0; /* make compiler happy */ for (;;) { if ( refill ) { bytes = (ptrdiff_t)FT_Stream_TryRead( stream, (FT_Byte*)buf + cursor, (FT_ULong)( buf_size - cursor ) ); avail = cursor + bytes; cursor = 0; refill = 0; } end = start; /* should we skip an optional character like \n or \r? */ if ( start < avail && buf[start] == to_skip ) { start += 1; to_skip = NO_SKIP; continue; } /* try to find the end of the line */ while ( end < avail && buf[end] != '\n' && buf[end] != '\r' ) end++; /* if we hit the end of the buffer, try shifting its content */ /* or even resizing it */ if ( end >= avail ) { if ( bytes == 0 ) /* last line in file doesn't end in \r or \n */ break; /* ignore it then exit */ if ( start == 0 ) { /* this line is definitely too long; try resizing the input */ /* buffer a bit to handle it. */ FT_ULong new_size; if ( buf_size >= 65536UL ) /* limit ourselves to 64KByte */ { FT_ERROR(( "_bdf_readstream: " ERRMSG6, lineno )); error = FT_THROW( Invalid_Argument ); goto Exit; } new_size = buf_size * 2; if ( FT_RENEW_ARRAY( buf, buf_size, new_size ) ) goto Exit; cursor = buf_size; buf_size = new_size; } else { bytes = avail - start; FT_MEM_MOVE( buf, buf + start, bytes ); cursor = bytes; avail -= bytes; start = 0; } refill = 1; continue; } /* Temporarily NUL-terminate the line. */ hold = buf[end]; buf[end] = 0; /* XXX: Use encoding independent value for 0x1a */ if ( buf[start] != '#' && buf[start] != 0x1a && end > start ) { error = (*cb)( buf + start, (unsigned long)( end - start ), lineno, (void*)&cb, client_data ); /* Redo if we have encountered CHARS without properties. */ if ( error == -1 ) error = (*cb)( buf + start, (unsigned long)( end - start ), lineno, (void*)&cb, client_data ); if ( error ) break; } lineno += 1; buf[end] = (char)hold; start = end + 1; if ( hold == '\n' ) to_skip = '\r'; else if ( hold == '\r' ) to_skip = '\n'; else to_skip = NO_SKIP; } *lno = lineno; Exit: FT_FREE( buf ); return error; } /* XXX: make this work with EBCDIC also */ static const unsigned char a2i[128] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char odigits[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char ddigits[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char hdigits[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x03, 0x7e, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; /* Routine to convert an ASCII string into an unsigned long integer. */ static unsigned long _bdf_atoul( char* s, char** end, int base ) { unsigned long v; const unsigned char* dmap; if ( s == 0 || *s == 0 ) return 0; /* Make sure the radix is something recognizable. Default to 10. */ switch ( base ) { case 8: dmap = odigits; break; case 16: dmap = hdigits; break; default: base = 10; dmap = ddigits; break; } /* Check for the special hex prefix. */ if ( *s == '0' && ( *( s + 1 ) == 'x' || *( s + 1 ) == 'X' ) ) { base = 16; dmap = hdigits; s += 2; } for ( v = 0; sbitset( dmap, *s ); s++ ) v = v * base + a2i[(int)*s]; if ( end != 0 ) *end = s; return v; } /* Routine to convert an ASCII string into an signed long integer. */ static long _bdf_atol( char* s, char** end, int base ) { long v, neg; const unsigned char* dmap; if ( s == 0 || *s == 0 ) return 0; /* Make sure the radix is something recognizable. Default to 10. */ switch ( base ) { case 8: dmap = odigits; break; case 16: dmap = hdigits; break; default: base = 10; dmap = ddigits; break; } /* Check for a minus sign. */ neg = 0; if ( *s == '-' ) { s++; neg = 1; } /* Check for the special hex prefix. */ if ( *s == '0' && ( *( s + 1 ) == 'x' || *( s + 1 ) == 'X' ) ) { base = 16; dmap = hdigits; s += 2; } for ( v = 0; sbitset( dmap, *s ); s++ ) v = v * base + a2i[(int)*s]; if ( end != 0 ) *end = s; return ( !neg ) ? v : -v; } /* Routine to convert an ASCII string into an signed short integer. */ static short _bdf_atos( char* s, char** end, int base ) { short v, neg; const unsigned char* dmap; if ( s == 0 || *s == 0 ) return 0; /* Make sure the radix is something recognizable. Default to 10. */ switch ( base ) { case 8: dmap = odigits; break; case 16: dmap = hdigits; break; default: base = 10; dmap = ddigits; break; } /* Check for a minus. */ neg = 0; if ( *s == '-' ) { s++; neg = 1; } /* Check for the special hex prefix. */ if ( *s == '0' && ( *( s + 1 ) == 'x' || *( s + 1 ) == 'X' ) ) { base = 16; dmap = hdigits; s += 2; } for ( v = 0; sbitset( dmap, *s ); s++ ) v = (short)( v * base + a2i[(int)*s] ); if ( end != 0 ) *end = s; return (short)( ( !neg ) ? v : -v ); } /* Routine to compare two glyphs by encoding so they can be sorted. */ static int by_encoding( const void* a, const void* b ) { bdf_glyph_t *c1, *c2; c1 = (bdf_glyph_t *)a; c2 = (bdf_glyph_t *)b; if ( c1->encoding < c2->encoding ) return -1; if ( c1->encoding > c2->encoding ) return 1; return 0; } static FT_Error bdf_create_property( char* name, int format, bdf_font_t* font ) { size_t n; bdf_property_t* p; FT_Memory memory = font->memory; FT_Error error = FT_Err_Ok; /* First check whether the property has */ /* already been added or not. If it has, then */ /* simply ignore it. */ if ( hash_lookup( name, &(font->proptbl) ) ) goto Exit; if ( FT_RENEW_ARRAY( font->user_props, font->nuser_props, font->nuser_props + 1 ) ) goto Exit; p = font->user_props + font->nuser_props; FT_ZERO( p ); n = ft_strlen( name ) + 1; if ( n > FT_ULONG_MAX ) return FT_THROW( Invalid_Argument ); if ( FT_NEW_ARRAY( p->name, n ) ) goto Exit; FT_MEM_COPY( (char *)p->name, name, n ); p->format = format; p->builtin = 0; n = _num_bdf_properties + font->nuser_props; error = hash_insert( p->name, n, &(font->proptbl), memory ); if ( error ) goto Exit; font->nuser_props++; Exit: return error; } FT_LOCAL_DEF( bdf_property_t * ) bdf_get_property( char* name, bdf_font_t* font ) { hashnode hn; size_t propid; if ( name == 0 || *name == 0 ) return 0; if ( ( hn = hash_lookup( name, &(font->proptbl) ) ) == 0 ) return 0; propid = hn->data; if ( propid >= _num_bdf_properties ) return font->user_props + ( propid - _num_bdf_properties ); return (bdf_property_t*)_bdf_properties + propid; } /*************************************************************************/ /* */ /* BDF font file parsing flags and functions. */ /* */ /*************************************************************************/ /* Parse flags. */ #define _BDF_START 0x0001 #define _BDF_FONT_NAME 0x0002 #define _BDF_SIZE 0x0004 #define _BDF_FONT_BBX 0x0008 #define _BDF_PROPS 0x0010 #define _BDF_GLYPHS 0x0020 #define _BDF_GLYPH 0x0040 #define _BDF_ENCODING 0x0080 #define _BDF_SWIDTH 0x0100 #define _BDF_DWIDTH 0x0200 #define _BDF_BBX 0x0400 #define _BDF_BITMAP 0x0800 #define _BDF_SWIDTH_ADJ 0x1000 #define _BDF_GLYPH_BITS ( _BDF_GLYPH | \ _BDF_ENCODING | \ _BDF_SWIDTH | \ _BDF_DWIDTH | \ _BDF_BBX | \ _BDF_BITMAP ) #define _BDF_GLYPH_WIDTH_CHECK 0x40000000UL #define _BDF_GLYPH_HEIGHT_CHECK 0x80000000UL static FT_Error _bdf_add_comment( bdf_font_t* font, char* comment, unsigned long len ) { char* cp; FT_Memory memory = font->memory; FT_Error error = FT_Err_Ok; if ( FT_RENEW_ARRAY( font->comments, font->comments_len, font->comments_len + len + 1 ) ) goto Exit; cp = font->comments + font->comments_len; FT_MEM_COPY( cp, comment, len ); cp[len] = '\n'; font->comments_len += len + 1; Exit: return error; } /* Set the spacing from the font name if it exists, or set it to the */ /* default specified in the options. */ static FT_Error _bdf_set_default_spacing( bdf_font_t* font, bdf_options_t* opts, unsigned long lineno ) { size_t len; char name[256]; _bdf_list_t list; FT_Memory memory; FT_Error error = FT_Err_Ok; FT_UNUSED( lineno ); /* only used in debug mode */ if ( font == 0 || font->name == 0 || font->name[0] == 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } memory = font->memory; _bdf_list_init( &list, memory ); font->spacing = opts->font_spacing; len = ft_strlen( font->name ) + 1; /* Limit ourselves to 256 characters in the font name. */ if ( len >= 256 ) { FT_ERROR(( "_bdf_set_default_spacing: " ERRMSG7, lineno )); error = FT_THROW( Invalid_Argument ); goto Exit; } FT_MEM_COPY( name, font->name, len ); error = _bdf_list_split( &list, (char *)"-", name, (unsigned long)len ); if ( error ) goto Fail; if ( list.used == 15 ) { switch ( list.field[11][0] ) { case 'C': case 'c': font->spacing = BDF_CHARCELL; break; case 'M': case 'm': font->spacing = BDF_MONOWIDTH; break; case 'P': case 'p': font->spacing = BDF_PROPORTIONAL; break; } } Fail: _bdf_list_done( &list ); Exit: return error; } /* Determine whether the property is an atom or not. If it is, then */ /* clean it up so the double quotes are removed if they exist. */ static int _bdf_is_atom( char* line, unsigned long linelen, char** name, char** value, bdf_font_t* font ) { int hold; char *sp, *ep; bdf_property_t* p; *name = sp = ep = line; while ( *ep && *ep != ' ' && *ep != '\t' ) ep++; hold = -1; if ( *ep ) { hold = *ep; *ep = 0; } p = bdf_get_property( sp, font ); /* Restore the character that was saved before any return can happen. */ if ( hold != -1 ) *ep = (char)hold; /* If the property exists and is not an atom, just return here. */ if ( p && p->format != BDF_ATOM ) return 0; /* The property is an atom. Trim all leading and trailing whitespace */ /* and double quotes for the atom value. */ sp = ep; ep = line + linelen; /* Trim the leading whitespace if it exists. */ if ( *sp ) *sp++ = 0; while ( *sp && ( *sp == ' ' || *sp == '\t' ) ) sp++; /* Trim the leading double quote if it exists. */ if ( *sp == '"' ) sp++; *value = sp; /* Trim the trailing whitespace if it exists. */ while ( ep > sp && ( *( ep - 1 ) == ' ' || *( ep - 1 ) == '\t' ) ) *--ep = 0; /* Trim the trailing double quote if it exists. */ if ( ep > sp && *( ep - 1 ) == '"' ) *--ep = 0; return 1; } static FT_Error _bdf_add_property( bdf_font_t* font, char* name, char* value, unsigned long lineno ) { size_t propid; hashnode hn; bdf_property_t *prop, *fp; FT_Memory memory = font->memory; FT_Error error = FT_Err_Ok; FT_UNUSED( lineno ); /* only used in debug mode */ /* First, check whether the property already exists in the font. */ if ( ( hn = hash_lookup( name, (hashtable *)font->internal ) ) != 0 ) { /* The property already exists in the font, so simply replace */ /* the value of the property with the current value. */ fp = font->props + hn->data; switch ( fp->format ) { case BDF_ATOM: /* Delete the current atom if it exists. */ FT_FREE( fp->value.atom ); if ( value && value[0] != 0 ) { if ( FT_STRDUP( fp->value.atom, value ) ) goto Exit; } break; case BDF_INTEGER: fp->value.l = _bdf_atol( value, 0, 10 ); break; case BDF_CARDINAL: fp->value.ul = _bdf_atoul( value, 0, 10 ); break; default: ; } goto Exit; } /* See whether this property type exists yet or not. */ /* If not, create it. */ hn = hash_lookup( name, &(font->proptbl) ); if ( hn == 0 ) { error = bdf_create_property( name, BDF_ATOM, font ); if ( error ) goto Exit; hn = hash_lookup( name, &(font->proptbl) ); } /* Allocate another property if this is overflow. */ if ( font->props_used == font->props_size ) { if ( font->props_size == 0 ) { if ( FT_NEW_ARRAY( font->props, 1 ) ) goto Exit; } else { if ( FT_RENEW_ARRAY( font->props, font->props_size, font->props_size + 1 ) ) goto Exit; } fp = font->props + font->props_size; FT_MEM_ZERO( fp, sizeof ( bdf_property_t ) ); font->props_size++; } propid = hn->data; if ( propid >= _num_bdf_properties ) prop = font->user_props + ( propid - _num_bdf_properties ); else prop = (bdf_property_t*)_bdf_properties + propid; fp = font->props + font->props_used; fp->name = prop->name; fp->format = prop->format; fp->builtin = prop->builtin; switch ( prop->format ) { case BDF_ATOM: fp->value.atom = 0; if ( value != 0 && value[0] ) { if ( FT_STRDUP( fp->value.atom, value ) ) goto Exit; } break; case BDF_INTEGER: fp->value.l = _bdf_atol( value, 0, 10 ); break; case BDF_CARDINAL: fp->value.ul = _bdf_atoul( value, 0, 10 ); break; } /* If the property happens to be a comment, then it doesn't need */ /* to be added to the internal hash table. */ if ( ft_strncmp( name, "COMMENT", 7 ) != 0 ) { /* Add the property to the font property table. */ error = hash_insert( fp->name, font->props_used, (hashtable *)font->internal, memory ); if ( error ) goto Exit; } font->props_used++; /* Some special cases need to be handled here. The DEFAULT_CHAR */ /* property needs to be located if it exists in the property list, the */ /* FONT_ASCENT and FONT_DESCENT need to be assigned if they are */ /* present, and the SPACING property should override the default */ /* spacing. */ if ( ft_strncmp( name, "DEFAULT_CHAR", 12 ) == 0 ) font->default_char = fp->value.l; else if ( ft_strncmp( name, "FONT_ASCENT", 11 ) == 0 ) font->font_ascent = fp->value.l; else if ( ft_strncmp( name, "FONT_DESCENT", 12 ) == 0 ) font->font_descent = fp->value.l; else if ( ft_strncmp( name, "SPACING", 7 ) == 0 ) { if ( !fp->value.atom ) { FT_ERROR(( "_bdf_add_property: " ERRMSG8, lineno, "SPACING" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( fp->value.atom[0] == 'p' || fp->value.atom[0] == 'P' ) font->spacing = BDF_PROPORTIONAL; else if ( fp->value.atom[0] == 'm' || fp->value.atom[0] == 'M' ) font->spacing = BDF_MONOWIDTH; else if ( fp->value.atom[0] == 'c' || fp->value.atom[0] == 'C' ) font->spacing = BDF_CHARCELL; } Exit: return error; } static const unsigned char nibble_mask[8] = { 0xFF, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE }; /* Actually parse the glyph info and bitmaps. */ static FT_Error _bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = FT_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_strncmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_strncmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = FT_THROW( Missing_Chars_Field ); goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = FT_THROW( Invalid_Argument ); goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_strncmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_strncmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_strncmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_strncmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = FT_THROW( Missing_Startchar_Field ); goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); if ( p->glyph_enc < -1 ) p->glyph_enc = -1; FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) / sizeof ( unsigned long ) * 32 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_strncmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_strncmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_strncmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_strncmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = FT_THROW( Missing_Bbx_Field ); goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = FT_THROW( Bbx_Too_Big ); goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = FT_THROW( Invalid_File_Format ); goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = FT_THROW( Missing_Encoding_Field ); Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; } /* Load the font properties. */ static FT_Error _bdf_parse_properties( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { unsigned long vlen; _bdf_line_func_t* next; _bdf_parse_t* p; char* name; char* value; char nbuf[128]; FT_Error error = FT_Err_Ok; FT_UNUSED( lineno ); next = (_bdf_line_func_t *)call_data; p = (_bdf_parse_t *) client_data; /* Check for the end of the properties. */ if ( ft_strncmp( line, "ENDPROPERTIES", 13 ) == 0 ) { /* If the FONT_ASCENT or FONT_DESCENT properties have not been */ /* encountered yet, then make sure they are added as properties and */ /* make sure they are set from the font bounding box info. */ /* */ /* This is *always* done regardless of the options, because X11 */ /* requires these two fields to compile fonts. */ if ( bdf_get_font_property( p->font, "FONT_ASCENT" ) == 0 ) { p->font->font_ascent = p->font->bbx.ascent; ft_sprintf( nbuf, "%hd", p->font->bbx.ascent ); error = _bdf_add_property( p->font, (char *)"FONT_ASCENT", nbuf, lineno ); if ( error ) goto Exit; FT_TRACE2(( "_bdf_parse_properties: " ACMSG1, p->font->bbx.ascent )); p->font->modified = 1; } if ( bdf_get_font_property( p->font, "FONT_DESCENT" ) == 0 ) { p->font->font_descent = p->font->bbx.descent; ft_sprintf( nbuf, "%hd", p->font->bbx.descent ); error = _bdf_add_property( p->font, (char *)"FONT_DESCENT", nbuf, lineno ); if ( error ) goto Exit; FT_TRACE2(( "_bdf_parse_properties: " ACMSG2, p->font->bbx.descent )); p->font->modified = 1; } p->flags &= ~_BDF_PROPS; *next = _bdf_parse_glyphs; goto Exit; } /* Ignore the _XFREE86_GLYPH_RANGES properties. */ if ( ft_strncmp( line, "_XFREE86_GLYPH_RANGES", 21 ) == 0 ) goto Exit; /* Handle COMMENT fields and properties in a special way to preserve */ /* the spacing. */ if ( ft_strncmp( line, "COMMENT", 7 ) == 0 ) { name = value = line; value += 7; if ( *value ) *value++ = 0; error = _bdf_add_property( p->font, name, value, lineno ); if ( error ) goto Exit; } else if ( _bdf_is_atom( line, linelen, &name, &value, p->font ) ) { error = _bdf_add_property( p->font, name, value, lineno ); if ( error ) goto Exit; } else { error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; name = p->list.field[0]; _bdf_list_shift( &p->list, 1 ); value = _bdf_list_join( &p->list, ' ', &vlen ); error = _bdf_add_property( p->font, name, value, lineno ); if ( error ) goto Exit; } Exit: return error; } /* Load the font header. */ static FT_Error _bdf_parse_start( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { unsigned long slen; _bdf_line_func_t* next; _bdf_parse_t* p; bdf_font_t* font; char *s; FT_Memory memory = NULL; FT_Error error = FT_Err_Ok; FT_UNUSED( lineno ); /* only used in debug mode */ next = (_bdf_line_func_t *)call_data; p = (_bdf_parse_t *) client_data; if ( p->font ) memory = p->font->memory; /* Check for a comment. This is done to handle those fonts that have */ /* comments before the STARTFONT line for some reason. */ if ( ft_strncmp( line, "COMMENT", 7 ) == 0 ) { if ( p->opts->keep_comments != 0 && p->font != 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); if ( error ) goto Exit; /* here font is not defined! */ } goto Exit; } if ( !( p->flags & _BDF_START ) ) { memory = p->memory; if ( ft_strncmp( line, "STARTFONT", 9 ) != 0 ) { /* we don't emit an error message since this code gets */ /* explicitly caught one level higher */ error = FT_THROW( Missing_Startfont_Field ); goto Exit; } p->flags = _BDF_START; font = p->font = 0; if ( FT_NEW( font ) ) goto Exit; p->font = font; font->memory = p->memory; p->memory = 0; { /* setup */ size_t i; bdf_property_t* prop; error = hash_init( &(font->proptbl), memory ); if ( error ) goto Exit; for ( i = 0, prop = (bdf_property_t*)_bdf_properties; i < _num_bdf_properties; i++, prop++ ) { error = hash_insert( prop->name, i, &(font->proptbl), memory ); if ( error ) goto Exit; } } if ( FT_ALLOC( p->font->internal, sizeof ( hashtable ) ) ) goto Exit; error = hash_init( (hashtable *)p->font->internal,memory ); if ( error ) goto Exit; p->font->spacing = p->opts->font_spacing; p->font->default_char = -1; goto Exit; } /* Check for the start of the properties. */ if ( ft_strncmp( line, "STARTPROPERTIES", 15 ) == 0 ) { if ( !( p->flags & _BDF_FONT_BBX ) ) { /* Missing the FONTBOUNDINGBOX field. */ FT_ERROR(( "_bdf_parse_start: " ERRMSG1, lineno, "FONTBOUNDINGBOX" )); error = FT_THROW( Missing_Fontboundingbox_Field ); goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; /* at this point, `p->font' can't be NULL */ p->cnt = p->font->props_size = _bdf_atoul( p->list.field[1], 0, 10 ); if ( FT_NEW_ARRAY( p->font->props, p->cnt ) ) { p->font->props_size = 0; goto Exit; } p->flags |= _BDF_PROPS; *next = _bdf_parse_properties; goto Exit; } /* Check for the FONTBOUNDINGBOX field. */ if ( ft_strncmp( line, "FONTBOUNDINGBOX", 15 ) == 0 ) { if ( !( p->flags & _BDF_SIZE ) ) { /* Missing the SIZE field. */ FT_ERROR(( "_bdf_parse_start: " ERRMSG1, lineno, "SIZE" )); error = FT_THROW( Missing_Size_Field ); goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->font->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); p->font->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); p->font->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); p->font->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); p->font->bbx.ascent = (short)( p->font->bbx.height + p->font->bbx.y_offset ); p->font->bbx.descent = (short)( -p->font->bbx.y_offset ); p->flags |= _BDF_FONT_BBX; goto Exit; } /* The next thing to check for is the FONT field. */ if ( ft_strncmp( line, "FONT", 4 ) == 0 ) { error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_start: " ERRMSG8, lineno, "FONT" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Allowing multiple `FONT' lines (which is invalid) doesn't hurt... */ FT_FREE( p->font->name ); if ( FT_NEW_ARRAY( p->font->name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->font->name, s, slen + 1 ); /* If the font name is an XLFD name, set the spacing to the one in */ /* the font name. If there is no spacing fall back on the default. */ error = _bdf_set_default_spacing( p->font, p->opts, lineno ); if ( error ) goto Exit; p->flags |= _BDF_FONT_NAME; goto Exit; } /* Check for the SIZE field. */ if ( ft_strncmp( line, "SIZE", 4 ) == 0 ) { if ( !( p->flags & _BDF_FONT_NAME ) ) { /* Missing the FONT field. */ FT_ERROR(( "_bdf_parse_start: " ERRMSG1, lineno, "FONT" )); error = FT_THROW( Missing_Font_Field ); goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->font->point_size = _bdf_atoul( p->list.field[1], 0, 10 ); p->font->resolution_x = _bdf_atoul( p->list.field[2], 0, 10 ); p->font->resolution_y = _bdf_atoul( p->list.field[3], 0, 10 ); /* Check for the bits per pixel field. */ if ( p->list.used == 5 ) { unsigned short bitcount, i, shift; p->font->bpp = (unsigned short)_bdf_atos( p->list.field[4], 0, 10 ); /* Only values 1, 2, 4, 8 are allowed. */ shift = p->font->bpp; bitcount = 0; for ( i = 0; shift > 0; i++ ) { if ( shift & 1 ) bitcount = i; shift >>= 1; } shift = (short)( ( bitcount > 3 ) ? 8 : ( 1 << bitcount ) ); if ( p->font->bpp > shift || p->font->bpp != shift ) { /* select next higher value */ p->font->bpp = (unsigned short)( shift << 1 ); FT_TRACE2(( "_bdf_parse_start: " ACMSG11, p->font->bpp )); } } else p->font->bpp = 1; p->flags |= _BDF_SIZE; goto Exit; } /* Check for the CHARS field -- font properties are optional */ if ( ft_strncmp( line, "CHARS", 5 ) == 0 ) { char nbuf[128]; if ( !( p->flags & _BDF_FONT_BBX ) ) { /* Missing the FONTBOUNDINGBOX field. */ FT_ERROR(( "_bdf_parse_start: " ERRMSG1, lineno, "FONTBOUNDINGBOX" )); error = FT_THROW( Missing_Fontboundingbox_Field ); goto Exit; } /* Add the two standard X11 properties which are required */ /* for compiling fonts. */ p->font->font_ascent = p->font->bbx.ascent; ft_sprintf( nbuf, "%hd", p->font->bbx.ascent ); error = _bdf_add_property( p->font, (char *)"FONT_ASCENT", nbuf, lineno ); if ( error ) goto Exit; FT_TRACE2(( "_bdf_parse_properties: " ACMSG1, p->font->bbx.ascent )); p->font->font_descent = p->font->bbx.descent; ft_sprintf( nbuf, "%hd", p->font->bbx.descent ); error = _bdf_add_property( p->font, (char *)"FONT_DESCENT", nbuf, lineno ); if ( error ) goto Exit; FT_TRACE2(( "_bdf_parse_properties: " ACMSG2, p->font->bbx.descent )); p->font->modified = 1; *next = _bdf_parse_glyphs; /* A special return value. */ error = -1; goto Exit; } FT_ERROR(( "_bdf_parse_start: " ERRMSG9, lineno )); error = FT_THROW( Invalid_File_Format ); Exit: return error; } /*************************************************************************/ /* */ /* API. */ /* */ /*************************************************************************/ FT_LOCAL_DEF( FT_Error ) bdf_load_font( FT_Stream stream, FT_Memory extmemory, bdf_options_t* opts, bdf_font_t* *font ) { unsigned long lineno = 0; /* make compiler happy */ _bdf_parse_t *p = NULL; FT_Memory memory = extmemory; /* needed for FT_NEW */ FT_Error error = FT_Err_Ok; if ( FT_NEW( p ) ) goto Exit; memory = NULL; p->opts = (bdf_options_t*)( ( opts != 0 ) ? opts : &_bdf_opts ); p->minlb = 32767; p->memory = extmemory; /* only during font creation */ _bdf_list_init( &p->list, extmemory ); error = _bdf_readstream( stream, _bdf_parse_start, (void *)p, &lineno ); if ( error ) goto Fail; if ( p->font != 0 ) { /* If the font is not proportional, set the font's monowidth */ /* field to the width of the font bounding box. */ if ( p->font->spacing != BDF_PROPORTIONAL ) p->font->monowidth = p->font->bbx.width; /* If the number of glyphs loaded is not that of the original count, */ /* indicate the difference. */ if ( p->cnt != p->font->glyphs_used + p->font->unencoded_used ) { FT_TRACE2(( "bdf_load_font: " ACMSG15, p->cnt, p->font->glyphs_used + p->font->unencoded_used )); p->font->modified = 1; } /* Once the font has been loaded, adjust the overall font metrics if */ /* necessary. */ if ( p->opts->correct_metrics != 0 && ( p->font->glyphs_used > 0 || p->font->unencoded_used > 0 ) ) { if ( p->maxrb - p->minlb != p->font->bbx.width ) { FT_TRACE2(( "bdf_load_font: " ACMSG3, p->font->bbx.width, p->maxrb - p->minlb )); p->font->bbx.width = (unsigned short)( p->maxrb - p->minlb ); p->font->modified = 1; } if ( p->font->bbx.x_offset != p->minlb ) { FT_TRACE2(( "bdf_load_font: " ACMSG4, p->font->bbx.x_offset, p->minlb )); p->font->bbx.x_offset = p->minlb; p->font->modified = 1; } if ( p->font->bbx.ascent != p->maxas ) { FT_TRACE2(( "bdf_load_font: " ACMSG5, p->font->bbx.ascent, p->maxas )); p->font->bbx.ascent = p->maxas; p->font->modified = 1; } if ( p->font->bbx.descent != p->maxds ) { FT_TRACE2(( "bdf_load_font: " ACMSG6, p->font->bbx.descent, p->maxds )); p->font->bbx.descent = p->maxds; p->font->bbx.y_offset = (short)( -p->maxds ); p->font->modified = 1; } if ( p->maxas + p->maxds != p->font->bbx.height ) { FT_TRACE2(( "bdf_load_font: " ACMSG7, p->font->bbx.height, p->maxas + p->maxds )); p->font->bbx.height = (unsigned short)( p->maxas + p->maxds ); } if ( p->flags & _BDF_SWIDTH_ADJ ) FT_TRACE2(( "bdf_load_font: " ACMSG8 )); } } if ( p->flags & _BDF_START ) { /* The ENDFONT field was never reached or did not exist. */ if ( !( p->flags & _BDF_GLYPHS ) ) { /* Error happened while parsing header. */ FT_ERROR(( "bdf_load_font: " ERRMSG2, lineno )); error = FT_THROW( Corrupted_Font_Header ); goto Exit; } else { /* Error happened when parsing glyphs. */ FT_ERROR(( "bdf_load_font: " ERRMSG3, lineno )); error = FT_THROW( Corrupted_Font_Glyphs ); goto Exit; } } if ( p->font != 0 ) { /* Make sure the comments are NULL terminated if they exist. */ memory = p->font->memory; if ( p->font->comments_len > 0 ) { if ( FT_RENEW_ARRAY( p->font->comments, p->font->comments_len, p->font->comments_len + 1 ) ) goto Fail; p->font->comments[p->font->comments_len] = 0; } } else if ( error == FT_Err_Ok ) error = FT_THROW( Invalid_File_Format ); *font = p->font; Exit: if ( p ) { _bdf_list_done( &p->list ); memory = extmemory; FT_FREE( p ); } return error; Fail: bdf_free_font( p->font ); memory = extmemory; FT_FREE( p->font ); goto Exit; } FT_LOCAL_DEF( void ) bdf_free_font( bdf_font_t* font ) { bdf_property_t* prop; unsigned long i; bdf_glyph_t* glyphs; FT_Memory memory; if ( font == 0 ) return; memory = font->memory; FT_FREE( font->name ); /* Free up the internal hash table of property names. */ if ( font->internal ) { hash_free( (hashtable *)font->internal, memory ); FT_FREE( font->internal ); } /* Free up the comment info. */ FT_FREE( font->comments ); /* Free up the properties. */ for ( i = 0; i < font->props_size; i++ ) { if ( font->props[i].format == BDF_ATOM ) FT_FREE( font->props[i].value.atom ); } FT_FREE( font->props ); /* Free up the character info. */ for ( i = 0, glyphs = font->glyphs; i < font->glyphs_used; i++, glyphs++ ) { FT_FREE( glyphs->name ); FT_FREE( glyphs->bitmap ); } for ( i = 0, glyphs = font->unencoded; i < font->unencoded_used; i++, glyphs++ ) { FT_FREE( glyphs->name ); FT_FREE( glyphs->bitmap ); } FT_FREE( font->glyphs ); FT_FREE( font->unencoded ); /* Free up the overflow storage if it was used. */ for ( i = 0, glyphs = font->overflow.glyphs; i < font->overflow.glyphs_used; i++, glyphs++ ) { FT_FREE( glyphs->name ); FT_FREE( glyphs->bitmap ); } FT_FREE( font->overflow.glyphs ); /* bdf_cleanup */ hash_free( &(font->proptbl), memory ); /* Free up the user defined properties. */ for ( prop = font->user_props, i = 0; i < font->nuser_props; i++, prop++ ) { FT_FREE( prop->name ); if ( prop->format == BDF_ATOM ) FT_FREE( prop->value.atom ); } FT_FREE( font->user_props ); /* FREE( font ); */ /* XXX Fixme */ } FT_LOCAL_DEF( bdf_property_t * ) bdf_get_font_property( bdf_font_t* font, const char* name ) { hashnode hn; if ( font == 0 || font->props_size == 0 || name == 0 || *name == 0 ) return 0; hn = hash_lookup( name, (hashtable *)font->internal ); return hn ? ( font->props + hn->data ) : 0; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/bdf/bdflib.c
C
apache-2.0
76,150
# # FreeType 2 BDF module definition # # Copyright 2001, 2002, 2006 by # Francesco Zappa Nardelli # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. FTMODULE_H_COMMANDS += BDF_DRIVER define BDF_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, bdf_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)bdf $(ECHO_DRIVER_DESC)bdf bitmap fonts$(ECHO_DRIVER_DONE) endef # EOF
YifuLiu/AliOS-Things
components/freetype/src/bdf/module.mk
Makefile
apache-2.0
1,372
# # FreeType 2 bdf driver configuration rules # # Copyright (C) 2001, 2002, 2003, 2008 by # Francesco Zappa Nardelli # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # bdf driver directory # BDF_DIR := $(SRC_DIR)/bdf BDF_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(BDF_DIR)) # bdf driver sources (i.e., C files) # BDF_DRV_SRC := $(BDF_DIR)/bdflib.c \ $(BDF_DIR)/bdfdrivr.c # bdf driver headers # BDF_DRV_H := $(BDF_DIR)/bdf.h \ $(BDF_DIR)/bdfdrivr.h \ $(BDF_DIR)/bdferror.h # bdf driver object(s) # # BDF_DRV_OBJ_M is used during `multi' builds # BDF_DRV_OBJ_S is used during `single' builds # BDF_DRV_OBJ_M := $(BDF_DRV_SRC:$(BDF_DIR)/%.c=$(OBJ_DIR)/%.$O) BDF_DRV_OBJ_S := $(OBJ_DIR)/bdf.$O # bdf driver source file for single build # BDF_DRV_SRC_S := $(BDF_DIR)/bdf.c # bdf driver - single object # $(BDF_DRV_OBJ_S): $(BDF_DRV_SRC_S) $(BDF_DRV_SRC) $(FREETYPE_H) $(BDF_DRV_H) $(BDF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(BDF_DRV_SRC_S)) # bdf driver - multiple objects # $(OBJ_DIR)/%.$O: $(BDF_DIR)/%.c $(FREETYPE_H) $(BDF_DRV_H) $(BDF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(BDF_DRV_OBJ_S) DRV_OBJS_M += $(BDF_DRV_OBJ_M) # EOF
YifuLiu/AliOS-Things
components/freetype/src/bdf/rules.mk
Makefile
apache-2.0
2,278
/***************************************************************************/ /* */ /* ftbzip2.c */ /* */ /* FreeType support for .bz2 compressed files. */ /* */ /* This optional component relies on libbz2. It should mainly be used to */ /* parse compressed PCF fonts, as found with many X11 server */ /* distributions. */ /* */ /* Copyright 2010, 2012, 2013 by */ /* Joel Klinghed. */ /* */ /* Based on src/gzip/ftgzip.c, Copyright 2002 - 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_MEMORY_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_DEBUG_H #include FT_BZIP2_H #include FT_CONFIG_STANDARD_LIBRARY_H #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX Bzip2_Err_ #define FT_ERR_BASE FT_Mod_Err_Bzip2 #include FT_ERRORS_H #ifdef FT_CONFIG_OPTION_USE_BZIP2 #ifdef FT_CONFIG_OPTION_PIC #error "bzip2 code does not support PIC yet" #endif #define BZ_NO_STDIO /* Do not need FILE */ #include <bzlib.h> /***************************************************************************/ /***************************************************************************/ /***** *****/ /***** B Z I P 2 M E M O R Y M A N A G E M E N T *****/ /***** *****/ /***************************************************************************/ /***************************************************************************/ /* it is better to use FreeType memory routines instead of raw 'malloc/free' */ typedef void *(* alloc_func)(void*, int, int); typedef void (* free_func)(void*, void*); static void* ft_bzip2_alloc( FT_Memory memory, int items, int size ) { FT_ULong sz = (FT_ULong)size * items; FT_Error error; FT_Pointer p = NULL; (void)FT_ALLOC( p, sz ); return p; } static void ft_bzip2_free( FT_Memory memory, void* address ) { FT_MEM_FREE( address ); } /***************************************************************************/ /***************************************************************************/ /***** *****/ /***** B Z I P 2 F I L E D E S C R I P T O R *****/ /***** *****/ /***************************************************************************/ /***************************************************************************/ #define FT_BZIP2_BUFFER_SIZE 4096 typedef struct FT_BZip2FileRec_ { FT_Stream source; /* parent/source stream */ FT_Stream stream; /* embedding stream */ FT_Memory memory; /* memory allocator */ bz_stream bzstream; /* bzlib input stream */ FT_Byte input[FT_BZIP2_BUFFER_SIZE]; /* input read buffer */ FT_Byte buffer[FT_BZIP2_BUFFER_SIZE]; /* output buffer */ FT_ULong pos; /* position in output */ FT_Byte* cursor; FT_Byte* limit; } FT_BZip2FileRec, *FT_BZip2File; /* check and skip .bz2 header - we don't support `transparent' compression */ static FT_Error ft_bzip2_check_header( FT_Stream stream ) { FT_Error error = FT_Err_Ok; FT_Byte head[4]; if ( FT_STREAM_SEEK( 0 ) || FT_STREAM_READ( head, 4 ) ) goto Exit; /* head[0] && head[1] are the magic numbers; */ /* head[2] is the version, and head[3] the blocksize */ if ( head[0] != 0x42 || head[1] != 0x5a || head[2] != 0x68 ) /* only support bzip2 (huffman) */ { error = FT_THROW( Invalid_File_Format ); goto Exit; } Exit: return error; } static FT_Error ft_bzip2_file_init( FT_BZip2File zip, FT_Stream stream, FT_Stream source ) { bz_stream* bzstream = &zip->bzstream; FT_Error error = FT_Err_Ok; zip->stream = stream; zip->source = source; zip->memory = stream->memory; zip->limit = zip->buffer + FT_BZIP2_BUFFER_SIZE; zip->cursor = zip->limit; zip->pos = 0; /* check .bz2 header */ { stream = source; error = ft_bzip2_check_header( stream ); if ( error ) goto Exit; if ( FT_STREAM_SEEK( 0 ) ) goto Exit; } /* initialize bzlib */ bzstream->bzalloc = (alloc_func)ft_bzip2_alloc; bzstream->bzfree = (free_func) ft_bzip2_free; bzstream->opaque = zip->memory; bzstream->avail_in = 0; bzstream->next_in = (char*)zip->buffer; if ( BZ2_bzDecompressInit( bzstream, 0, 0 ) != BZ_OK || bzstream->next_in == NULL ) error = FT_THROW( Invalid_File_Format ); Exit: return error; } static void ft_bzip2_file_done( FT_BZip2File zip ) { bz_stream* bzstream = &zip->bzstream; BZ2_bzDecompressEnd( bzstream ); /* clear the rest */ bzstream->bzalloc = NULL; bzstream->bzfree = NULL; bzstream->opaque = NULL; bzstream->next_in = NULL; bzstream->next_out = NULL; bzstream->avail_in = 0; bzstream->avail_out = 0; zip->memory = NULL; zip->source = NULL; zip->stream = NULL; } static FT_Error ft_bzip2_file_reset( FT_BZip2File zip ) { FT_Stream stream = zip->source; FT_Error error; if ( !FT_STREAM_SEEK( 0 ) ) { bz_stream* bzstream = &zip->bzstream; BZ2_bzDecompressEnd( bzstream ); bzstream->avail_in = 0; bzstream->next_in = (char*)zip->input; bzstream->avail_out = 0; bzstream->next_out = (char*)zip->buffer; zip->limit = zip->buffer + FT_BZIP2_BUFFER_SIZE; zip->cursor = zip->limit; zip->pos = 0; BZ2_bzDecompressInit( bzstream, 0, 0 ); } return error; } static FT_Error ft_bzip2_file_fill_input( FT_BZip2File zip ) { bz_stream* bzstream = &zip->bzstream; FT_Stream stream = zip->source; FT_ULong size; if ( stream->read ) { size = stream->read( stream, stream->pos, zip->input, FT_BZIP2_BUFFER_SIZE ); if ( size == 0 ) return FT_THROW( Invalid_Stream_Operation ); } else { size = stream->size - stream->pos; if ( size > FT_BZIP2_BUFFER_SIZE ) size = FT_BZIP2_BUFFER_SIZE; if ( size == 0 ) return FT_THROW( Invalid_Stream_Operation ); FT_MEM_COPY( zip->input, stream->base + stream->pos, size ); } stream->pos += size; bzstream->next_in = (char*)zip->input; bzstream->avail_in = size; return FT_Err_Ok; } static FT_Error ft_bzip2_file_fill_output( FT_BZip2File zip ) { bz_stream* bzstream = &zip->bzstream; FT_Error error = FT_Err_Ok; zip->cursor = zip->buffer; bzstream->next_out = (char*)zip->cursor; bzstream->avail_out = FT_BZIP2_BUFFER_SIZE; while ( bzstream->avail_out > 0 ) { int err; if ( bzstream->avail_in == 0 ) { error = ft_bzip2_file_fill_input( zip ); if ( error ) break; } err = BZ2_bzDecompress( bzstream ); if ( err == BZ_STREAM_END ) { zip->limit = (FT_Byte*)bzstream->next_out; if ( zip->limit == zip->cursor ) error = FT_THROW( Invalid_Stream_Operation ); break; } else if ( err != BZ_OK ) { error = FT_THROW( Invalid_Stream_Operation ); break; } } return error; } /* fill output buffer; `count' must be <= FT_BZIP2_BUFFER_SIZE */ static FT_Error ft_bzip2_file_skip_output( FT_BZip2File zip, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong delta; for (;;) { delta = (FT_ULong)( zip->limit - zip->cursor ); if ( delta >= count ) delta = count; zip->cursor += delta; zip->pos += delta; count -= delta; if ( count == 0 ) break; error = ft_bzip2_file_fill_output( zip ); if ( error ) break; } return error; } static FT_ULong ft_bzip2_file_io( FT_BZip2File zip, FT_ULong pos, FT_Byte* buffer, FT_ULong count ) { FT_ULong result = 0; FT_Error error; /* Reset inflate stream if we're seeking backwards. */ /* Yes, that is not too efficient, but it saves memory :-) */ if ( pos < zip->pos ) { error = ft_bzip2_file_reset( zip ); if ( error ) goto Exit; } /* skip unwanted bytes */ if ( pos > zip->pos ) { error = ft_bzip2_file_skip_output( zip, (FT_ULong)( pos - zip->pos ) ); if ( error ) goto Exit; } if ( count == 0 ) goto Exit; /* now read the data */ for (;;) { FT_ULong delta; delta = (FT_ULong)( zip->limit - zip->cursor ); if ( delta >= count ) delta = count; FT_MEM_COPY( buffer, zip->cursor, delta ); buffer += delta; result += delta; zip->cursor += delta; zip->pos += delta; count -= delta; if ( count == 0 ) break; error = ft_bzip2_file_fill_output( zip ); if ( error ) break; } Exit: return result; } /***************************************************************************/ /***************************************************************************/ /***** *****/ /***** B Z E M B E D D I N G S T R E A M *****/ /***** *****/ /***************************************************************************/ /***************************************************************************/ static void ft_bzip2_stream_close( FT_Stream stream ) { FT_BZip2File zip = (FT_BZip2File)stream->descriptor.pointer; FT_Memory memory = stream->memory; if ( zip ) { /* finalize bzip file descriptor */ ft_bzip2_file_done( zip ); FT_FREE( zip ); stream->descriptor.pointer = NULL; } } static FT_ULong ft_bzip2_stream_io( FT_Stream stream, FT_ULong pos, FT_Byte* buffer, FT_ULong count ) { FT_BZip2File zip = (FT_BZip2File)stream->descriptor.pointer; return ft_bzip2_file_io( zip, pos, buffer, count ); } FT_EXPORT_DEF( FT_Error ) FT_Stream_OpenBzip2( FT_Stream stream, FT_Stream source ) { FT_Error error; FT_Memory memory = source->memory; FT_BZip2File zip = NULL; /* * check the header right now; this prevents allocating unnecessary * objects when we don't need them */ error = ft_bzip2_check_header( source ); if ( error ) goto Exit; FT_ZERO( stream ); stream->memory = memory; if ( !FT_QNEW( zip ) ) { error = ft_bzip2_file_init( zip, stream, source ); if ( error ) { FT_FREE( zip ); goto Exit; } stream->descriptor.pointer = zip; } stream->size = 0x7FFFFFFFL; /* don't know the real size! */ stream->pos = 0; stream->base = 0; stream->read = ft_bzip2_stream_io; stream->close = ft_bzip2_stream_close; Exit: return error; } #else /* !FT_CONFIG_OPTION_USE_BZIP2 */ FT_EXPORT_DEF( FT_Error ) FT_Stream_OpenBzip2( FT_Stream stream, FT_Stream source ) { FT_UNUSED( stream ); FT_UNUSED( source ); return FT_THROW( Unimplemented_Feature ); } #endif /* !FT_CONFIG_OPTION_USE_BZIP2 */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/bzip2/ftbzip2.c
C
apache-2.0
13,395
# # FreeType 2 BZIP2 support configuration rules # # Copyright 2010 by # Joel Klinghed. # # Based on src/lzw/rules.mk, Copyright 2004-2006 by # Albert Chin-A-Young. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # BZIP2 driver directory # BZIP2_DIR := $(SRC_DIR)/bzip2 # compilation flags for the driver # BZIP2_COMPILE := $(FT_COMPILE) # BZIP2 support sources (i.e., C files) # BZIP2_DRV_SRC := $(BZIP2_DIR)/ftbzip2.c # BZIP2 driver object(s) # # BZIP2_DRV_OBJ_M is used during `multi' builds # BZIP2_DRV_OBJ_S is used during `single' builds # BZIP2_DRV_OBJ_M := $(OBJ_DIR)/ftbzip2.$O BZIP2_DRV_OBJ_S := $(OBJ_DIR)/ftbzip2.$O # BZIP2 support source file for single build # BZIP2_DRV_SRC_S := $(BZIP2_DIR)/ftbzip2.c # BZIP2 support - single object # $(BZIP2_DRV_OBJ_S): $(BZIP2_DRV_SRC_S) $(BZIP2_DRV_SRC) $(FREETYPE_H) $(BZIP2_DRV_H) $(BZIP2_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(BZIP2_DRV_SRC_S)) # BZIP2 support - multiple objects # $(OBJ_DIR)/%.$O: $(BZIP2_DIR)/%.c $(FREETYPE_H) $(BZIP2_DRV_H) $(BZIP2_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(BZIP2_DRV_OBJ_S) DRV_OBJS_M += $(BZIP2_DRV_OBJ_M) # EOF
YifuLiu/AliOS-Things
components/freetype/src/bzip2/rules.mk
Makefile
apache-2.0
1,439
/***************************************************************************/ /* */ /* cf2arrst.c */ /* */ /* Adobe's code for Array Stacks (body). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2glue.h" #include "cf2arrst.h" #include "cf2error.h" /* * CF2_ArrStack uses an error pointer, to enable shared errors. * Shared errors are necessary when multiple objects allow the program * to continue after detecting errors. Only the first error should be * recorded. */ FT_LOCAL_DEF( void ) cf2_arrstack_init( CF2_ArrStack arrstack, FT_Memory memory, FT_Error* error, size_t sizeItem ) { FT_ASSERT( arrstack != NULL ); /* initialize the structure */ arrstack->memory = memory; arrstack->error = error; arrstack->sizeItem = sizeItem; arrstack->allocated = 0; arrstack->chunk = 10; /* chunks of 10 items */ arrstack->count = 0; arrstack->totalSize = 0; arrstack->ptr = NULL; } FT_LOCAL_DEF( void ) cf2_arrstack_finalize( CF2_ArrStack arrstack ) { FT_Memory memory = arrstack->memory; /* for FT_FREE */ FT_ASSERT( arrstack != NULL ); arrstack->allocated = 0; arrstack->count = 0; arrstack->totalSize = 0; /* free the data buffer */ FT_FREE( arrstack->ptr ); } /* allocate or reallocate the buffer size; */ /* return false on memory error */ static FT_Bool cf2_arrstack_setNumElements( CF2_ArrStack arrstack, size_t numElements ) { FT_ASSERT( arrstack != NULL ); { FT_Error error = FT_Err_Ok; /* for FT_REALLOC */ FT_Memory memory = arrstack->memory; /* for FT_REALLOC */ FT_Long newSize = (FT_Long)( numElements * arrstack->sizeItem ); if ( numElements > LONG_MAX / arrstack->sizeItem ) goto exit; FT_ASSERT( newSize > 0 ); /* avoid realloc with zero size */ if ( !FT_REALLOC( arrstack->ptr, arrstack->totalSize, newSize ) ) { arrstack->allocated = numElements; arrstack->totalSize = newSize; if ( arrstack->count > numElements ) { /* we truncated the list! */ CF2_SET_ERROR( arrstack->error, Stack_Overflow ); arrstack->count = numElements; return FALSE; } return TRUE; /* success */ } } exit: /* if there's not already an error, store this one */ CF2_SET_ERROR( arrstack->error, Out_Of_Memory ); return FALSE; } /* set the count, ensuring allocation is sufficient */ FT_LOCAL_DEF( void ) cf2_arrstack_setCount( CF2_ArrStack arrstack, size_t numElements ) { FT_ASSERT( arrstack != NULL ); if ( numElements > arrstack->allocated ) { /* expand the allocation first */ if ( !cf2_arrstack_setNumElements( arrstack, numElements ) ) return; } arrstack->count = numElements; } /* clear the count */ FT_LOCAL_DEF( void ) cf2_arrstack_clear( CF2_ArrStack arrstack ) { FT_ASSERT( arrstack != NULL ); arrstack->count = 0; } /* current number of items */ FT_LOCAL_DEF( size_t ) cf2_arrstack_size( const CF2_ArrStack arrstack ) { FT_ASSERT( arrstack != NULL ); return arrstack->count; } FT_LOCAL_DEF( void* ) cf2_arrstack_getBuffer( const CF2_ArrStack arrstack ) { FT_ASSERT( arrstack != NULL ); return arrstack->ptr; } /* return pointer to the given element */ FT_LOCAL_DEF( void* ) cf2_arrstack_getPointer( const CF2_ArrStack arrstack, size_t idx ) { void* newPtr; FT_ASSERT( arrstack != NULL ); if ( idx >= arrstack->count ) { /* overflow */ CF2_SET_ERROR( arrstack->error, Stack_Overflow ); idx = 0; /* choose safe default */ } newPtr = (FT_Byte*)arrstack->ptr + idx * arrstack->sizeItem; return newPtr; } /* push (append) an element at the end of the list; */ /* return false on memory error */ /* TODO: should there be a length param for extra checking? */ FT_LOCAL_DEF( void ) cf2_arrstack_push( CF2_ArrStack arrstack, const void* ptr ) { FT_ASSERT( arrstack != NULL ); if ( arrstack->count == arrstack->allocated ) { /* grow the buffer by one chunk */ if ( !cf2_arrstack_setNumElements( arrstack, arrstack->allocated + arrstack->chunk ) ) { /* on error, ignore the push */ return; } } FT_ASSERT( ptr != NULL ); { size_t offset = arrstack->count * arrstack->sizeItem; void* newPtr = (FT_Byte*)arrstack->ptr + offset; FT_MEM_COPY( newPtr, ptr, arrstack->sizeItem ); arrstack->count += 1; } } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2arrst.c
C
apache-2.0
7,596
/***************************************************************************/ /* */ /* cf2arrst.h */ /* */ /* Adobe's code for Array Stacks (specification). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2ARRST_H__ #define __CF2ARRST_H__ #include "cf2error.h" FT_BEGIN_HEADER /* need to define the struct here (not opaque) so it can be allocated by */ /* clients */ typedef struct CF2_ArrStackRec_ { FT_Memory memory; FT_Error* error; size_t sizeItem; /* bytes per element */ size_t allocated; /* items allocated */ size_t chunk; /* allocation increment in items */ size_t count; /* number of elements allocated */ size_t totalSize; /* total bytes allocated */ void* ptr; /* ptr to data */ } CF2_ArrStackRec, *CF2_ArrStack; FT_LOCAL( void ) cf2_arrstack_init( CF2_ArrStack arrstack, FT_Memory memory, FT_Error* error, size_t sizeItem ); FT_LOCAL( void ) cf2_arrstack_finalize( CF2_ArrStack arrstack ); FT_LOCAL( void ) cf2_arrstack_setCount( CF2_ArrStack arrstack, size_t numElements ); FT_LOCAL( void ) cf2_arrstack_clear( CF2_ArrStack arrstack ); FT_LOCAL( size_t ) cf2_arrstack_size( const CF2_ArrStack arrstack ); FT_LOCAL( void* ) cf2_arrstack_getBuffer( const CF2_ArrStack arrstack ); FT_LOCAL( void* ) cf2_arrstack_getPointer( const CF2_ArrStack arrstack, size_t idx ); FT_LOCAL( void ) cf2_arrstack_push( CF2_ArrStack arrstack, const void* ptr ); FT_END_HEADER #endif /* __CF2ARRST_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2arrst.h
C
apache-2.0
4,470
/***************************************************************************/ /* */ /* cf2blues.c */ /* */ /* Adobe's code for handling Blue Zones (body). */ /* */ /* Copyright 2009-2014 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2blues.h" #include "cf2hints.h" #include "cf2font.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cf2blues /* * For blue values, the FreeType parser produces an array of integers, * while the Adobe CFF engine produces an array of fixed. * Define a macro to convert FreeType to fixed. */ #define cf2_blueToFixed( x ) cf2_intToFixed( x ) FT_LOCAL_DEF( void ) cf2_blues_init( CF2_Blues blues, CF2_Font font ) { /* pointer to parsed font object */ CFF_Decoder* decoder = font->decoder; CF2_Fixed zoneHeight; CF2_Fixed maxZoneHeight = 0; CF2_Fixed csUnitsPerPixel; size_t numBlueValues; size_t numOtherBlues; size_t numFamilyBlues; size_t numFamilyOtherBlues; FT_Pos* blueValues; FT_Pos* otherBlues; FT_Pos* familyBlues; FT_Pos* familyOtherBlues; size_t i; CF2_Fixed emBoxBottom, emBoxTop; #if 0 CF2_Int unitsPerEm = font->unitsPerEm; if ( unitsPerEm == 0 ) unitsPerEm = 1000; #endif FT_ZERO( blues ); blues->scale = font->innerTransform.d; cf2_getBlueMetrics( decoder, &blues->blueScale, &blues->blueShift, &blues->blueFuzz ); cf2_getBlueValues( decoder, &numBlueValues, &blueValues ); cf2_getOtherBlues( decoder, &numOtherBlues, &otherBlues ); cf2_getFamilyBlues( decoder, &numFamilyBlues, &familyBlues ); cf2_getFamilyOtherBlues( decoder, &numFamilyOtherBlues, &familyOtherBlues ); /* * synthetic em box hint heuristic * * Apply this when ideographic dictionary (LanguageGroup 1) has no * real alignment zones. Adobe tools generate dummy zones at -250 and * 1100 for a 1000 unit em. Fonts with ICF-based alignment zones * should not enable the heuristic. When the heuristic is enabled, * the font's blue zones are ignored. * */ /* get em box from OS/2 typoAscender/Descender */ /* TODO: FreeType does not parse these metrics. Skip them for now. */ #if 0 FCM_getHorizontalLineMetrics( &e, font->font, &ascender, &descender, &linegap ); if ( ascender - descender == unitsPerEm ) { emBoxBottom = cf2_intToFixed( descender ); emBoxTop = cf2_intToFixed( ascender ); } else #endif { emBoxBottom = CF2_ICF_Bottom; emBoxTop = CF2_ICF_Top; } if ( cf2_getLanguageGroup( decoder ) == 1 && ( numBlueValues == 0 || ( numBlueValues == 4 && cf2_blueToFixed( blueValues[0] ) < emBoxBottom && cf2_blueToFixed( blueValues[1] ) < emBoxBottom && cf2_blueToFixed( blueValues[2] ) > emBoxTop && cf2_blueToFixed( blueValues[3] ) > emBoxTop ) ) ) { /* * Construct hint edges suitable for synthetic ghost hints at top * and bottom of em box. +-CF2_MIN_COUNTER allows for unhinted * features above or below the last hinted edge. This also gives a * net 1 pixel boost to the height of ideographic glyphs. * * Note: Adjust synthetic hints outward by epsilon (0x.0001) to * avoid interference. E.g., some fonts have real hints at * 880 and -120. */ blues->emBoxBottomEdge.csCoord = emBoxBottom - CF2_FIXED_EPSILON; blues->emBoxBottomEdge.dsCoord = cf2_fixedRound( FT_MulFix( blues->emBoxBottomEdge.csCoord, blues->scale ) ) - CF2_MIN_COUNTER; blues->emBoxBottomEdge.scale = blues->scale; blues->emBoxBottomEdge.flags = CF2_GhostBottom | CF2_Locked | CF2_Synthetic; blues->emBoxTopEdge.csCoord = emBoxTop + CF2_FIXED_EPSILON + 2 * font->darkenY; blues->emBoxTopEdge.dsCoord = cf2_fixedRound( FT_MulFix( blues->emBoxTopEdge.csCoord, blues->scale ) ) + CF2_MIN_COUNTER; blues->emBoxTopEdge.scale = blues->scale; blues->emBoxTopEdge.flags = CF2_GhostTop | CF2_Locked | CF2_Synthetic; blues->doEmBoxHints = TRUE; /* enable the heuristic */ return; } /* copy `BlueValues' and `OtherBlues' to a combined array of top and */ /* bottom zones */ for ( i = 0; i < numBlueValues; i += 2 ) { blues->zone[blues->count].csBottomEdge = cf2_blueToFixed( blueValues[i] ); blues->zone[blues->count].csTopEdge = cf2_blueToFixed( blueValues[i + 1] ); zoneHeight = blues->zone[blues->count].csTopEdge - blues->zone[blues->count].csBottomEdge; if ( zoneHeight < 0 ) { FT_TRACE4(( "cf2_blues_init: ignoring negative zone height\n" )); continue; /* reject this zone */ } if ( zoneHeight > maxZoneHeight ) { /* take maximum before darkening adjustment */ /* so overshoot suppression point doesn't change */ maxZoneHeight = zoneHeight; } /* adjust both edges of top zone upward by twice darkening amount */ if ( i != 0 ) { blues->zone[blues->count].csTopEdge += 2 * font->darkenY; blues->zone[blues->count].csBottomEdge += 2 * font->darkenY; } /* first `BlueValue' is bottom zone; others are top */ if ( i == 0 ) { blues->zone[blues->count].bottomZone = TRUE; blues->zone[blues->count].csFlatEdge = blues->zone[blues->count].csTopEdge; } else { blues->zone[blues->count].bottomZone = FALSE; blues->zone[blues->count].csFlatEdge = blues->zone[blues->count].csBottomEdge; } blues->count += 1; } for ( i = 0; i < numOtherBlues; i += 2 ) { blues->zone[blues->count].csBottomEdge = cf2_blueToFixed( otherBlues[i] ); blues->zone[blues->count].csTopEdge = cf2_blueToFixed( otherBlues[i + 1] ); zoneHeight = blues->zone[blues->count].csTopEdge - blues->zone[blues->count].csBottomEdge; if ( zoneHeight < 0 ) { FT_TRACE4(( "cf2_blues_init: ignoring negative zone height\n" )); continue; /* reject this zone */ } if ( zoneHeight > maxZoneHeight ) { /* take maximum before darkening adjustment */ /* so overshoot suppression point doesn't change */ maxZoneHeight = zoneHeight; } /* Note: bottom zones are not adjusted for darkening amount */ /* all OtherBlues are bottom zone */ blues->zone[blues->count].bottomZone = TRUE; blues->zone[blues->count].csFlatEdge = blues->zone[blues->count].csTopEdge; blues->count += 1; } /* Adjust for FamilyBlues */ /* Search for the nearest flat edge in `FamilyBlues' or */ /* `FamilyOtherBlues'. According to the Black Book, any matching edge */ /* must be within one device pixel */ csUnitsPerPixel = FT_DivFix( cf2_intToFixed( 1 ), blues->scale ); /* loop on all zones in this font */ for ( i = 0; i < blues->count; i++ ) { size_t j; CF2_Fixed minDiff; CF2_Fixed flatFamilyEdge, diff; /* value for this font */ CF2_Fixed flatEdge = blues->zone[i].csFlatEdge; if ( blues->zone[i].bottomZone ) { /* In a bottom zone, the top edge is the flat edge. */ /* Search `FamilyOtherBlues' for bottom zones; look for closest */ /* Family edge that is within the one pixel threshold. */ minDiff = CF2_FIXED_MAX; for ( j = 0; j < numFamilyOtherBlues; j += 2 ) { /* top edge */ flatFamilyEdge = cf2_blueToFixed( familyOtherBlues[j + 1] ); diff = cf2_fixedAbs( flatEdge - flatFamilyEdge ); if ( diff < minDiff && diff < csUnitsPerPixel ) { blues->zone[i].csFlatEdge = flatFamilyEdge; minDiff = diff; if ( diff == 0 ) break; } } /* check the first member of FamilyBlues, which is a bottom zone */ if ( numFamilyBlues >= 2 ) { /* top edge */ flatFamilyEdge = cf2_blueToFixed( familyBlues[1] ); diff = cf2_fixedAbs( flatEdge - flatFamilyEdge ); if ( diff < minDiff && diff < csUnitsPerPixel ) blues->zone[i].csFlatEdge = flatFamilyEdge; } } else { /* In a top zone, the bottom edge is the flat edge. */ /* Search `FamilyBlues' for top zones; skip first zone, which is a */ /* bottom zone; look for closest Family edge that is within the */ /* one pixel threshold */ minDiff = CF2_FIXED_MAX; for ( j = 2; j < numFamilyBlues; j += 2 ) { /* bottom edge */ flatFamilyEdge = cf2_blueToFixed( familyBlues[j] ); /* adjust edges of top zone upward by twice darkening amount */ flatFamilyEdge += 2 * font->darkenY; /* bottom edge */ diff = cf2_fixedAbs( flatEdge - flatFamilyEdge ); if ( diff < minDiff && diff < csUnitsPerPixel ) { blues->zone[i].csFlatEdge = flatFamilyEdge; minDiff = diff; if ( diff == 0 ) break; } } } } /* TODO: enforce separation of zones, including BlueFuzz */ /* Adjust BlueScale; similar to AdjustBlueScale() in coretype */ /* `bcsetup.c'. */ if ( maxZoneHeight > 0 ) { if ( blues->blueScale > FT_DivFix( cf2_intToFixed( 1 ), maxZoneHeight ) ) { /* clamp at maximum scale */ blues->blueScale = FT_DivFix( cf2_intToFixed( 1 ), maxZoneHeight ); } /* * TODO: Revisit the bug fix for 613448. The minimum scale * requirement catches a number of library fonts. For * example, with default BlueScale (.039625) and 0.4 minimum, * the test below catches any font with maxZoneHeight < 10.1. * There are library fonts ranging from 2 to 10 that get * caught, including e.g., Eurostile LT Std Medium with * maxZoneHeight of 6. * */ #if 0 if ( blueScale < .4 / maxZoneHeight ) { tetraphilia_assert( 0 ); /* clamp at minimum scale, per bug 0613448 fix */ blueScale = .4 / maxZoneHeight; } #endif } /* * Suppress overshoot and boost blue zones at small sizes. Boost * amount varies linearly from 0.5 pixel near 0 to 0 pixel at * blueScale cutoff. * Note: This boost amount is different from the coretype heuristic. * */ if ( blues->scale < blues->blueScale ) { blues->suppressOvershoot = TRUE; /* Change rounding threshold for `dsFlatEdge'. */ /* Note: constant changed from 0.5 to 0.6 to avoid a problem with */ /* 10ppem Arial */ blues->boost = cf2_floatToFixed( .6 ) - FT_MulDiv( cf2_floatToFixed ( .6 ), blues->scale, blues->blueScale ); if ( blues->boost > 0x7FFF ) { /* boost must remain less than 0.5, or baseline could go negative */ blues->boost = 0x7FFF; } } /* boost and darkening have similar effects; don't do both */ if ( font->stemDarkened ) blues->boost = 0; /* set device space alignment for each zone; */ /* apply boost amount before rounding flat edge */ for ( i = 0; i < blues->count; i++ ) { if ( blues->zone[i].bottomZone ) blues->zone[i].dsFlatEdge = cf2_fixedRound( FT_MulFix( blues->zone[i].csFlatEdge, blues->scale ) - blues->boost ); else blues->zone[i].dsFlatEdge = cf2_fixedRound( FT_MulFix( blues->zone[i].csFlatEdge, blues->scale ) + blues->boost ); } } /* * Check whether `stemHint' is captured by one of the blue zones. * * Zero, one or both edges may be valid; only valid edges can be * captured. For compatibility with CoolType, search top and bottom * zones in the same pass (see `BlueLock'). If a hint is captured, * return true and position the edge(s) in one of 3 ways: * * 1) If `BlueScale' suppresses overshoot, position the captured edge * at the flat edge of the zone. * 2) If overshoot is not suppressed and `BlueShift' requires * overshoot, position the captured edge a minimum of 1 device pixel * from the flat edge. * 3) If overshoot is not suppressed or required, position the captured * edge at the nearest device pixel. * */ FT_LOCAL_DEF( FT_Bool ) cf2_blues_capture( const CF2_Blues blues, CF2_Hint bottomHintEdge, CF2_Hint topHintEdge ) { /* TODO: validate? */ CF2_Fixed csFuzz = blues->blueFuzz; /* new position of captured edge */ CF2_Fixed dsNew; /* amount that hint is moved when positioned */ CF2_Fixed dsMove = 0; FT_Bool captured = FALSE; CF2_UInt i; /* assert edge flags are consistent */ FT_ASSERT( !cf2_hint_isTop( bottomHintEdge ) && !cf2_hint_isBottom( topHintEdge ) ); /* TODO: search once without blue fuzz for compatibility with coretype? */ for ( i = 0; i < blues->count; i++ ) { if ( blues->zone[i].bottomZone && cf2_hint_isBottom( bottomHintEdge ) ) { if ( ( blues->zone[i].csBottomEdge - csFuzz ) <= bottomHintEdge->csCoord && bottomHintEdge->csCoord <= ( blues->zone[i].csTopEdge + csFuzz ) ) { /* bottom edge captured by bottom zone */ if ( blues->suppressOvershoot ) dsNew = blues->zone[i].dsFlatEdge; else if ( ( blues->zone[i].csTopEdge - bottomHintEdge->csCoord ) >= blues->blueShift ) { /* guarantee minimum of 1 pixel overshoot */ dsNew = FT_MIN( cf2_fixedRound( bottomHintEdge->dsCoord ), blues->zone[i].dsFlatEdge - cf2_intToFixed( 1 ) ); } else { /* simply round captured edge */ dsNew = cf2_fixedRound( bottomHintEdge->dsCoord ); } dsMove = dsNew - bottomHintEdge->dsCoord; captured = TRUE; break; } } if ( !blues->zone[i].bottomZone && cf2_hint_isTop( topHintEdge ) ) { if ( ( blues->zone[i].csBottomEdge - csFuzz ) <= topHintEdge->csCoord && topHintEdge->csCoord <= ( blues->zone[i].csTopEdge + csFuzz ) ) { /* top edge captured by top zone */ if ( blues->suppressOvershoot ) dsNew = blues->zone[i].dsFlatEdge; else if ( ( topHintEdge->csCoord - blues->zone[i].csBottomEdge ) >= blues->blueShift ) { /* guarantee minimum of 1 pixel overshoot */ dsNew = FT_MAX( cf2_fixedRound( topHintEdge->dsCoord ), blues->zone[i].dsFlatEdge + cf2_intToFixed( 1 ) ); } else { /* simply round captured edge */ dsNew = cf2_fixedRound( topHintEdge->dsCoord ); } dsMove = dsNew - topHintEdge->dsCoord; captured = TRUE; break; } } } if ( captured ) { /* move both edges and flag them `locked' */ if ( cf2_hint_isValid( bottomHintEdge ) ) { bottomHintEdge->dsCoord += dsMove; cf2_hint_lock( bottomHintEdge ); } if ( cf2_hint_isValid( topHintEdge ) ) { topHintEdge->dsCoord += dsMove; cf2_hint_lock( topHintEdge ); } } return captured; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2blues.c
C
apache-2.0
20,633
/***************************************************************************/ /* */ /* cf2blues.h */ /* */ /* Adobe's code for handling Blue Zones (specification). */ /* */ /* Copyright 2009-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ /* * A `CF2_Blues' object stores the blue zones (horizontal alignment * zones) of a font. These are specified in the CFF private dictionary * by `BlueValues', `OtherBlues', `FamilyBlues', and `FamilyOtherBlues'. * Each zone is defined by a top and bottom edge in character space. * Further, each zone is either a top zone or a bottom zone, as recorded * by `bottomZone'. * * The maximum number of `BlueValues' and `FamilyBlues' is 7 each. * However, these are combined to produce a total of 7 zones. * Similarly, the maximum number of `OtherBlues' and `FamilyOtherBlues' * is 5 and these are combined to produce an additional 5 zones. * * Blue zones are used to `capture' hints and force them to a common * alignment point. This alignment is recorded in device space in * `dsFlatEdge'. Except for this value, a `CF2_Blues' object could be * constructed independently of scaling. Construction may occur once * the matrix is known. Other features implemented in the Capture * method are overshoot suppression, overshoot enforcement, and Blue * Boost. * * Capture is determined by `BlueValues' and `OtherBlues', but the * alignment point may be adjusted to the scaled flat edge of * `FamilyBlues' or `FamilyOtherBlues'. No alignment is done to the * curved edge of a zone. * */ #ifndef __CF2BLUES_H__ #define __CF2BLUES_H__ #include "cf2glue.h" FT_BEGIN_HEADER /* * `CF2_Hint' is shared by `cf2hints.h' and * `cf2blues.h', but `cf2blues.h' depends on * `cf2hints.h', so define it here. Note: The typedef is in * `cf2glue.h'. * */ enum { CF2_GhostBottom = 0x1, /* a single bottom edge */ CF2_GhostTop = 0x2, /* a single top edge */ CF2_PairBottom = 0x4, /* the bottom edge of a stem hint */ CF2_PairTop = 0x8, /* the top edge of a stem hint */ CF2_Locked = 0x10, /* this edge has been aligned */ /* by a blue zone */ CF2_Synthetic = 0x20 /* this edge was synthesized */ }; /* * Default value for OS/2 typoAscender/Descender when their difference * is not equal to `unitsPerEm'. The default is based on -250 and 1100 * in `CF2_Blues', assuming 1000 units per em here. * */ enum { CF2_ICF_Top = cf2_intToFixed( 880 ), CF2_ICF_Bottom = cf2_intToFixed( -120 ) }; /* * Constant used for hint adjustment and for synthetic em box hint * placement. */ #define CF2_MIN_COUNTER cf2_floatToFixed( 0.5 ) /* shared typedef is in cf2glue.h */ struct CF2_HintRec_ { CF2_UInt flags; /* attributes of the edge */ size_t index; /* index in original stem hint array */ /* (if not synthetic) */ CF2_Fixed csCoord; CF2_Fixed dsCoord; CF2_Fixed scale; }; typedef struct CF2_BlueRec_ { CF2_Fixed csBottomEdge; CF2_Fixed csTopEdge; CF2_Fixed csFlatEdge; /* may be from either local or Family zones */ CF2_Fixed dsFlatEdge; /* top edge of bottom zone or bottom edge */ /* of top zone (rounded) */ FT_Bool bottomZone; } CF2_BlueRec; /* max total blue zones is 12 */ enum { CF2_MAX_BLUES = 7, CF2_MAX_OTHERBLUES = 5 }; typedef struct CF2_BluesRec_ { CF2_Fixed scale; CF2_UInt count; FT_Bool suppressOvershoot; FT_Bool doEmBoxHints; CF2_Fixed blueScale; CF2_Fixed blueShift; CF2_Fixed blueFuzz; CF2_Fixed boost; CF2_HintRec emBoxTopEdge; CF2_HintRec emBoxBottomEdge; CF2_BlueRec zone[CF2_MAX_BLUES + CF2_MAX_OTHERBLUES]; } CF2_BluesRec, *CF2_Blues; FT_LOCAL( void ) cf2_blues_init( CF2_Blues blues, CF2_Font font ); FT_LOCAL( FT_Bool ) cf2_blues_capture( const CF2_Blues blues, CF2_Hint bottomHintEdge, CF2_Hint topHintEdge ); FT_END_HEADER #endif /* __CF2BLUES_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2blues.h
C
apache-2.0
6,917
/***************************************************************************/ /* */ /* cf2error.c */ /* */ /* Adobe's code for error handling (body). */ /* */ /* Copyright 2006-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include "cf2error.h" FT_LOCAL_DEF( void ) cf2_setError( FT_Error* error, FT_Error value ) { if ( error && *error == 0 ) *error = value; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2error.c
C
apache-2.0
3,019
/***************************************************************************/ /* */ /* cf2error.h */ /* */ /* Adobe's code for error handling (specification). */ /* */ /* Copyright 2006-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2ERROR_H__ #define __CF2ERROR_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX CF2_Err_ #define FT_ERR_BASE FT_Mod_Err_CF2 #include FT_ERRORS_H #include "cf2ft.h" FT_BEGIN_HEADER /* * A poor-man error facility. * * This code being written in vanilla C, doesn't have the luxury of a * language-supported exception mechanism such as the one available in * Java. Instead, we are stuck with using error codes that must be * carefully managed and preserved. However, it is convenient for us to * model our error mechanism on a Java-like exception mechanism. * When we assign an error code we are thus `throwing' an error. * * The perservation of an error code is done by coding convention. * Upon a function call if the error code is anything other than * `FT_Err_Ok', which is guaranteed to be zero, we * will return without altering that error. This will allow the * error to propogate and be handled at the appropriate location in * the code. * * This allows a style of code where the error code is initialized * up front and a block of calls are made with the error code only * being checked after the block. If a new error occurs, the original * error will be preserved and a functional no-op should result in any * subsequent function that has an initial error code not equal to * `FT_Err_Ok'. * * Errors are encoded by calling the `FT_THROW' macro. For example, * * { * FT_Error e; * * * ... * e = FT_THROW( Out_Of_Memory ); * } * */ /* Set error code to a particular value. */ FT_LOCAL( void ) cf2_setError( FT_Error* error, FT_Error value ); /* * A macro that conditionally sets an error code. * * This macro will first check whether `error' is set; * if not, it will set it to `e'. * */ #define CF2_SET_ERROR( error, e ) \ cf2_setError( error, FT_THROW( e ) ) FT_END_HEADER #endif /* __CF2ERROR_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2error.h
C
apache-2.0
4,895
/***************************************************************************/ /* */ /* cf2fixed.h */ /* */ /* Adobe's code for Fixed Point Mathematics (specification only). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2FIXED_H__ #define __CF2FIXED_H__ FT_BEGIN_HEADER /* rasterizer integer and fixed point arithmetic must be 32-bit */ #define CF2_Fixed CF2_F16Dot16 typedef FT_Int32 CF2_Frac; /* 2.30 fixed point */ #define CF2_FIXED_MAX ( (CF2_Fixed)0x7FFFFFFFL ) #define CF2_FIXED_MIN ( (CF2_Fixed)0x80000000L ) #define CF2_FIXED_ONE 0x10000L #define CF2_FIXED_EPSILON 0x0001 /* in C 89, left and right shift of negative numbers is */ /* implementation specific behaviour in the general case */ #define cf2_intToFixed( i ) \ ( (CF2_Fixed)( (FT_UInt32)(i) << 16 ) ) #define cf2_fixedToInt( x ) \ ( (FT_Short)( ( (FT_UInt32)(x) + 0x8000U ) >> 16 ) ) #define cf2_fixedRound( x ) \ ( (CF2_Fixed)( ( (x) + 0x8000 ) & 0xFFFF0000L ) ) #define cf2_floatToFixed( f ) \ ( (CF2_Fixed)( (f) * 65536.0 + 0.5 ) ) #define cf2_fixedAbs( x ) \ ( (x) < 0 ? -(x) : (x) ) #define cf2_fixedFloor( x ) \ ( (CF2_Fixed)( (x) & 0xFFFF0000L ) ) #define cf2_fixedFraction( x ) \ ( (x) - cf2_fixedFloor( x ) ) #define cf2_fracToFixed( x ) \ ( (x) < 0 ? -( ( -(x) + 0x2000 ) >> 14 ) \ : ( ( (x) + 0x2000 ) >> 14 ) ) /* signed numeric types */ typedef enum CF2_NumberType_ { CF2_NumberFixed, /* 16.16 */ CF2_NumberFrac, /* 2.30 */ CF2_NumberInt /* 32.0 */ } CF2_NumberType; FT_END_HEADER #endif /* __CF2FIXED_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2fixed.h
C
apache-2.0
4,579
/***************************************************************************/ /* */ /* cf2font.c */ /* */ /* Adobe's code for font instances (body). */ /* */ /* Copyright 2007-2014 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include "cf2glue.h" #include "cf2font.h" #include "cf2error.h" #include "cf2intrp.h" /* Compute a stem darkening amount in character space. */ static void cf2_computeDarkening( CF2_Fixed emRatio, CF2_Fixed ppem, CF2_Fixed stemWidth, CF2_Fixed* darkenAmount, CF2_Fixed boldenAmount, FT_Bool stemDarkened, FT_Int* darkenParams ) { /* * Total darkening amount is computed in 1000 unit character space * using the modified 5 part curve as Adobe's Avalon rasterizer. * The darkening amount is smaller for thicker stems. * It becomes zero when the stem is thicker than 2.333 pixels. * * By default, we use * * darkenAmount = 0.4 pixels if scaledStem <= 0.5 pixels, * darkenAmount = 0.275 pixels if 1 <= scaledStem <= 1.667 pixels, * darkenAmount = 0 pixel if scaledStem >= 2.333 pixels, * * and piecewise linear in-between: * * * darkening * ^ * | * | (x1,y1) * |--------+ * | \ * | \ * | \ (x3,y3) * | +----------+ * | (x2,y2) \ * | \ * | \ * | +----------------- * | (x4,y4) * +---------------------------------------------> stem * thickness * * * This corresponds to the following values for the * `darkening-parameters' property: * * (x1, y1) = (500, 400) * (x2, y2) = (1000, 275) * (x3, y3) = (1667, 275) * (x4, y4) = (2333, 0) * */ /* Internal calculations are done in units per thousand for */ /* convenience. The x axis is scaled stem width in */ /* thousandths of a pixel. That is, 1000 is 1 pixel. */ /* The y axis is darkening amount in thousandths of a pixel.*/ /* In the code, below, dividing by ppem and */ /* adjusting for emRatio converts darkenAmount to character */ /* space (font units). */ CF2_Fixed stemWidthPer1000, scaledStem; *darkenAmount = 0; if ( boldenAmount == 0 && !stemDarkened ) return; /* protect against range problems and divide by zero */ if ( emRatio < cf2_floatToFixed( .01 ) ) return; if ( stemDarkened ) { FT_Int x1 = darkenParams[0]; FT_Int y1 = darkenParams[1]; FT_Int x2 = darkenParams[2]; FT_Int y2 = darkenParams[3]; FT_Int x3 = darkenParams[4]; FT_Int y3 = darkenParams[5]; FT_Int x4 = darkenParams[6]; FT_Int y4 = darkenParams[7]; /* convert from true character space to 1000 unit character space; */ /* add synthetic emboldening effect */ /* we have to assure that the computation of `scaledStem' */ /* and `stemWidthPer1000' don't overflow */ stemWidthPer1000 = FT_MulFix( stemWidth + boldenAmount, emRatio ); if ( emRatio > CF2_FIXED_ONE && stemWidthPer1000 <= ( stemWidth + boldenAmount ) ) { stemWidthPer1000 = 0; /* to pacify compiler */ scaledStem = cf2_intToFixed( x4 ); } else { scaledStem = FT_MulFix( stemWidthPer1000, ppem ); if ( ppem > CF2_FIXED_ONE && scaledStem <= stemWidthPer1000 ) scaledStem = cf2_intToFixed( x4 ); } /* now apply the darkening parameters */ if ( scaledStem < cf2_intToFixed( x1 ) ) *darkenAmount = FT_DivFix( cf2_intToFixed( y1 ), ppem ); else if ( scaledStem < cf2_intToFixed( x2 ) ) { FT_Int xdelta = x2 - x1; FT_Int ydelta = y2 - y1; FT_Int x = stemWidthPer1000 - FT_DivFix( cf2_intToFixed( x1 ), ppem ); if ( !xdelta ) goto Try_x3; *darkenAmount = FT_MulDiv( x, ydelta, xdelta ) + FT_DivFix( cf2_intToFixed( y1 ), ppem ); } else if ( scaledStem < cf2_intToFixed( x3 ) ) { Try_x3: { FT_Int xdelta = x3 - x2; FT_Int ydelta = y3 - y2; FT_Int x = stemWidthPer1000 - FT_DivFix( cf2_intToFixed( x2 ), ppem ); if ( !xdelta ) goto Try_x4; *darkenAmount = FT_MulDiv( x, ydelta, xdelta ) + FT_DivFix( cf2_intToFixed( y2 ), ppem ); } } else if ( scaledStem < cf2_intToFixed( x4 ) ) { Try_x4: { FT_Int xdelta = x4 - x3; FT_Int ydelta = y4 - y3; FT_Int x = stemWidthPer1000 - FT_DivFix( cf2_intToFixed( x3 ), ppem ); if ( !xdelta ) goto Use_y4; *darkenAmount = FT_MulDiv( x, ydelta, xdelta ) + FT_DivFix( cf2_intToFixed( y3 ), ppem ); } } else { Use_y4: *darkenAmount = FT_DivFix( cf2_intToFixed( y4 ), ppem ); } /* use half the amount on each side and convert back to true */ /* character space */ *darkenAmount = FT_DivFix( *darkenAmount, 2 * emRatio ); } /* add synthetic emboldening effect in character space */ *darkenAmount += boldenAmount / 2; } /* set up values for the current FontDict and matrix */ /* caller's transform is adjusted for subpixel positioning */ static void cf2_font_setup( CF2_Font font, const CF2_Matrix* transform ) { /* pointer to parsed font object */ CFF_Decoder* decoder = font->decoder; FT_Bool needExtraSetup = FALSE; /* character space units */ CF2_Fixed boldenX = font->syntheticEmboldeningAmountX; CF2_Fixed boldenY = font->syntheticEmboldeningAmountY; CFF_SubFont subFont; CF2_Fixed ppem; /* clear previous error */ font->error = FT_Err_Ok; /* if a CID fontDict has changed, we need to recompute some cached */ /* data */ subFont = cf2_getSubfont( decoder ); if ( font->lastSubfont != subFont ) { font->lastSubfont = subFont; needExtraSetup = TRUE; } /* if ppem has changed, we need to recompute some cached data */ /* note: because of CID font matrix concatenation, ppem and transform */ /* do not necessarily track. */ ppem = cf2_getPpemY( decoder ); if ( font->ppem != ppem ) { font->ppem = ppem; needExtraSetup = TRUE; } /* copy hinted flag on each call */ font->hinted = (FT_Bool)( font->renderingFlags & CF2_FlagsHinted ); /* determine if transform has changed; */ /* include Fontmatrix but ignore translation */ if ( ft_memcmp( transform, &font->currentTransform, 4 * sizeof ( CF2_Fixed ) ) != 0 ) { /* save `key' information for `cache of one' matrix data; */ /* save client transform, without the translation */ font->currentTransform = *transform; font->currentTransform.tx = font->currentTransform.ty = cf2_intToFixed( 0 ); /* TODO: FreeType transform is simple scalar; for now, use identity */ /* for outer */ font->innerTransform = *transform; font->outerTransform.a = font->outerTransform.d = cf2_intToFixed( 1 ); font->outerTransform.b = font->outerTransform.c = cf2_intToFixed( 0 ); needExtraSetup = TRUE; } /* * font->darkened is set to true if there is a stem darkening request or * the font is synthetic emboldened. * font->darkened controls whether to adjust blue zones, winding order, * and hinting. * */ if ( font->stemDarkened != ( font->renderingFlags & CF2_FlagsDarkened ) ) { font->stemDarkened = (FT_Bool)( font->renderingFlags & CF2_FlagsDarkened ); /* blue zones depend on darkened flag */ needExtraSetup = TRUE; } /* recompute variables that are dependent on transform or FontDict or */ /* darken flag */ if ( needExtraSetup ) { /* StdVW is found in the private dictionary; */ /* recompute darkening amounts whenever private dictionary or */ /* transform change */ /* Note: a rendering flag turns darkening on or off, so we want to */ /* store the `on' amounts; */ /* darkening amount is computed in character space */ /* TODO: testing size-dependent darkening here; */ /* what to do for rotations? */ CF2_Fixed emRatio; CF2_Fixed stdHW; CF2_Int unitsPerEm = font->unitsPerEm; if ( unitsPerEm == 0 ) unitsPerEm = 1000; ppem = FT_MAX( cf2_intToFixed( 4 ), font->ppem ); /* use minimum ppem of 4 */ #if 0 /* since vstem is measured in the x-direction, we use the `a' member */ /* of the fontMatrix */ emRatio = cf2_fixedFracMul( cf2_intToFixed( 1000 ), fontMatrix->a ); #endif /* Freetype does not preserve the fontMatrix when parsing; use */ /* unitsPerEm instead. */ /* TODO: check precision of this */ emRatio = cf2_intToFixed( 1000 ) / unitsPerEm; font->stdVW = cf2_getStdVW( decoder ); if ( font->stdVW <= 0 ) font->stdVW = FT_DivFix( cf2_intToFixed( 75 ), emRatio ); if ( boldenX > 0 ) { /* Ensure that boldenX is at least 1 pixel for synthetic bold font */ /* (similar to what Avalon does) */ boldenX = FT_MAX( boldenX, FT_DivFix( cf2_intToFixed( unitsPerEm ), ppem ) ); /* Synthetic emboldening adds at least 1 pixel to darkenX, while */ /* stem darkening adds at most half pixel. Since the purpose of */ /* stem darkening (readability at small sizes) is met with */ /* synthetic emboldening, no need to add stem darkening for a */ /* synthetic bold font. */ cf2_computeDarkening( emRatio, ppem, font->stdVW, &font->darkenX, boldenX, FALSE, font->darkenParams ); } else cf2_computeDarkening( emRatio, ppem, font->stdVW, &font->darkenX, 0, font->stemDarkened, font->darkenParams ); #if 0 /* since hstem is measured in the y-direction, we use the `d' member */ /* of the fontMatrix */ /* TODO: use the same units per em as above; check this */ emRatio = cf2_fixedFracMul( cf2_intToFixed( 1000 ), fontMatrix->d ); #endif /* set the default stem width, because it must be the same for all */ /* family members; */ /* choose a constant for StdHW that depends on font contrast */ stdHW = cf2_getStdHW( decoder ); if ( stdHW > 0 && font->stdVW > 2 * stdHW ) font->stdHW = FT_DivFix( cf2_intToFixed( 75 ), emRatio ); else { /* low contrast font gets less hstem darkening */ font->stdHW = FT_DivFix( cf2_intToFixed( 110 ), emRatio ); } cf2_computeDarkening( emRatio, ppem, font->stdHW, &font->darkenY, boldenY, font->stemDarkened, font->darkenParams ); if ( font->darkenX != 0 || font->darkenY != 0 ) font->darkened = TRUE; else font->darkened = FALSE; font->reverseWinding = FALSE; /* initial expectation is CCW */ /* compute blue zones for this instance */ cf2_blues_init( &font->blues, font ); } } /* equivalent to AdobeGetOutline */ FT_LOCAL_DEF( FT_Error ) cf2_getGlyphOutline( CF2_Font font, CF2_Buffer charstring, const CF2_Matrix* transform, CF2_F16Dot16* glyphWidth ) { FT_Error lastError = FT_Err_Ok; FT_Vector translation; #if 0 FT_Vector advancePoint; #endif CF2_Fixed advWidth = 0; FT_Bool needWinding; /* Note: use both integer and fraction for outlines. This allows bbox */ /* to come out directly. */ translation.x = transform->tx; translation.y = transform->ty; /* set up values based on transform */ cf2_font_setup( font, transform ); if ( font->error ) goto exit; /* setup encountered an error */ /* reset darken direction */ font->reverseWinding = FALSE; /* winding order only affects darkening */ needWinding = font->darkened; while ( 1 ) { /* reset output buffer */ cf2_outline_reset( &font->outline ); /* build the outline, passing the full translation */ cf2_interpT2CharString( font, charstring, (CF2_OutlineCallbacks)&font->outline, &translation, FALSE, 0, 0, &advWidth ); if ( font->error ) goto exit; if ( !needWinding ) break; /* check winding order */ if ( font->outline.root.windingMomentum >= 0 ) /* CFF is CCW */ break; /* invert darkening and render again */ /* TODO: this should be a parameter to getOutline-computeOffset */ font->reverseWinding = TRUE; needWinding = FALSE; /* exit after next iteration */ } /* finish storing client outline */ cf2_outline_close( &font->outline ); exit: /* FreeType just wants the advance width; there is no translation */ *glyphWidth = advWidth; /* free resources and collect errors from objects we've used */ cf2_setError( &font->error, lastError ); return font->error; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2font.c
C
apache-2.0
18,200
/***************************************************************************/ /* */ /* cf2font.h */ /* */ /* Adobe's code for font instances (specification). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2FONT_H__ #define __CF2FONT_H__ #include "cf2ft.h" #include "cf2blues.h" FT_BEGIN_HEADER #define CF2_OPERAND_STACK_SIZE 48 #define CF2_MAX_SUBR 10 /* maximum subroutine nesting */ /* typedef is in `cf2glue.h' */ struct CF2_FontRec_ { FT_Memory memory; FT_Error error; /* shared error for this instance */ CF2_RenderingFlags renderingFlags; /* variables that depend on Transform: */ /* the following have zero translation; */ /* inner * outer = font * original */ CF2_Matrix currentTransform; /* original client matrix */ CF2_Matrix innerTransform; /* for hinting; erect, scaled */ CF2_Matrix outerTransform; /* post hinting; includes rotations */ CF2_Fixed ppem; /* transform-dependent */ CF2_Int unitsPerEm; CF2_Fixed syntheticEmboldeningAmountX; /* character space units */ CF2_Fixed syntheticEmboldeningAmountY; /* character space units */ /* FreeType related members */ CF2_OutlineRec outline; /* freetype glyph outline functions */ CFF_Decoder* decoder; CFF_SubFont lastSubfont; /* FreeType parsed data; */ /* top font or subfont */ /* these flags can vary from one call to the next */ FT_Bool hinted; FT_Bool darkened; /* true if stemDarkened or synthetic bold */ /* i.e. darkenX != 0 || darkenY != 0 */ FT_Bool stemDarkened; FT_Int darkenParams[8]; /* 1000 unit character space */ /* variables that depend on both FontDict and Transform */ CF2_Fixed stdVW; /* in character space; depends on dict entry */ CF2_Fixed stdHW; /* in character space; depends on dict entry */ CF2_Fixed darkenX; /* character space units */ CF2_Fixed darkenY; /* depends on transform */ /* and private dict (StdVW) */ FT_Bool reverseWinding; /* darken assuming */ /* counterclockwise winding */ CF2_BluesRec blues; /* computed zone data */ }; FT_LOCAL( FT_Error ) cf2_getGlyphOutline( CF2_Font font, CF2_Buffer charstring, const CF2_Matrix* transform, CF2_F16Dot16* glyphWidth ); FT_END_HEADER #endif /* __CF2FONT_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2font.h
C
apache-2.0
5,395
/***************************************************************************/ /* */ /* cf2ft.c */ /* */ /* FreeType Glue Component to Adobe's Interpreter (body). */ /* */ /* Copyright 2013-2014 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2font.h" #include "cf2error.h" #define CF2_MAX_SIZE cf2_intToFixed( 2000 ) /* max ppem */ /* * This check should avoid most internal overflow cases. Clients should * generally respond to `Glyph_Too_Big' by getting a glyph outline * at EM size, scaling it and filling it as a graphics operation. * */ static FT_Error cf2_checkTransform( const CF2_Matrix* transform, CF2_Int unitsPerEm ) { CF2_Fixed maxScale; FT_ASSERT( unitsPerEm > 0 ); if ( transform->a <= 0 || transform->d <= 0 ) return FT_THROW( Invalid_Size_Handle ); FT_ASSERT( transform->b == 0 && transform->c == 0 ); FT_ASSERT( transform->tx == 0 && transform->ty == 0 ); if ( unitsPerEm > 0x7FFF ) return FT_THROW( Glyph_Too_Big ); maxScale = FT_DivFix( CF2_MAX_SIZE, cf2_intToFixed( unitsPerEm ) ); if ( transform->a > maxScale || transform->d > maxScale ) return FT_THROW( Glyph_Too_Big ); return FT_Err_Ok; } static void cf2_setGlyphWidth( CF2_Outline outline, CF2_Fixed width ) { CFF_Decoder* decoder = outline->decoder; FT_ASSERT( decoder ); decoder->glyph_width = cf2_fixedToInt( width ); } /* Clean up font instance. */ static void cf2_free_instance( void* ptr ) { CF2_Font font = (CF2_Font)ptr; if ( font ) { FT_Memory memory = font->memory; (void)memory; } } /********************************************/ /* */ /* functions for handling client outline; */ /* FreeType uses coordinates in 26.6 format */ /* */ /********************************************/ static void cf2_builder_moveTo( CF2_OutlineCallbacks callbacks, const CF2_CallbackParams params ) { /* downcast the object pointer */ CF2_Outline outline = (CF2_Outline)callbacks; CFF_Builder* builder; (void)params; /* only used in debug mode */ FT_ASSERT( outline && outline->decoder ); FT_ASSERT( params->op == CF2_PathOpMoveTo ); builder = &outline->decoder->builder; /* note: two successive moves simply close the contour twice */ cff_builder_close_contour( builder ); builder->path_begun = 0; } static void cf2_builder_lineTo( CF2_OutlineCallbacks callbacks, const CF2_CallbackParams params ) { /* downcast the object pointer */ CF2_Outline outline = (CF2_Outline)callbacks; CFF_Builder* builder; FT_ASSERT( outline && outline->decoder ); FT_ASSERT( params->op == CF2_PathOpLineTo ); builder = &outline->decoder->builder; if ( !builder->path_begun ) { /* record the move before the line; also check points and set */ /* `path_begun' */ cff_builder_start_point( builder, params->pt0.x, params->pt0.y ); } /* `cff_builder_add_point1' includes a check_points call for one point */ cff_builder_add_point1( builder, params->pt1.x, params->pt1.y ); } static void cf2_builder_cubeTo( CF2_OutlineCallbacks callbacks, const CF2_CallbackParams params ) { /* downcast the object pointer */ CF2_Outline outline = (CF2_Outline)callbacks; CFF_Builder* builder; FT_ASSERT( outline && outline->decoder ); FT_ASSERT( params->op == CF2_PathOpCubeTo ); builder = &outline->decoder->builder; if ( !builder->path_begun ) { /* record the move before the line; also check points and set */ /* `path_begun' */ cff_builder_start_point( builder, params->pt0.x, params->pt0.y ); } /* prepare room for 3 points: 2 off-curve, 1 on-curve */ cff_check_points( builder, 3 ); cff_builder_add_point( builder, params->pt1.x, params->pt1.y, 0 ); cff_builder_add_point( builder, params->pt2.x, params->pt2.y, 0 ); cff_builder_add_point( builder, params->pt3.x, params->pt3.y, 1 ); } static void cf2_outline_init( CF2_Outline outline, FT_Memory memory, FT_Error* error ) { FT_MEM_ZERO( outline, sizeof ( CF2_OutlineRec ) ); outline->root.memory = memory; outline->root.error = error; outline->root.moveTo = cf2_builder_moveTo; outline->root.lineTo = cf2_builder_lineTo; outline->root.cubeTo = cf2_builder_cubeTo; } /* get scaling and hint flag from GlyphSlot */ static void cf2_getScaleAndHintFlag( CFF_Decoder* decoder, CF2_Fixed* x_scale, CF2_Fixed* y_scale, FT_Bool* hinted, FT_Bool* scaled ) { FT_ASSERT( decoder && decoder->builder.glyph ); /* note: FreeType scale includes a factor of 64 */ *hinted = decoder->builder.glyph->hint; *scaled = decoder->builder.glyph->scaled; if ( *hinted ) { *x_scale = ( decoder->builder.glyph->x_scale + 32 ) / 64; *y_scale = ( decoder->builder.glyph->y_scale + 32 ) / 64; } else { /* for unhinted outlines, `cff_slot_load' does the scaling, */ /* thus render at `unity' scale */ *x_scale = 0x0400; /* 1/64 as 16.16 */ *y_scale = 0x0400; } } /* get units per em from `FT_Face' */ /* TODO: should handle font matrix concatenation? */ static FT_UShort cf2_getUnitsPerEm( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->builder.face ); FT_ASSERT( decoder->builder.face->root.units_per_EM ); return decoder->builder.face->root.units_per_EM; } /* Main entry point: Render one glyph. */ FT_LOCAL_DEF( FT_Error ) cf2_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Memory memory; FT_Error error = FT_Err_Ok; CF2_Font font; FT_ASSERT( decoder && decoder->cff ); memory = decoder->builder.memory; /* CF2 data is saved here across glyphs */ font = (CF2_Font)decoder->cff->cf2_instance.data; /* on first glyph, allocate instance structure */ if ( decoder->cff->cf2_instance.data == NULL ) { decoder->cff->cf2_instance.finalizer = (FT_Generic_Finalizer)cf2_free_instance; if ( FT_ALLOC( decoder->cff->cf2_instance.data, sizeof ( CF2_FontRec ) ) ) return FT_THROW( Out_Of_Memory ); font = (CF2_Font)decoder->cff->cf2_instance.data; font->memory = memory; /* initialize a client outline, to be shared by each glyph rendered */ cf2_outline_init( &font->outline, font->memory, &font->error ); } /* save decoder; it is a stack variable and will be different on each */ /* call */ font->decoder = decoder; font->outline.decoder = decoder; { /* build parameters for Adobe engine */ CFF_Builder* builder = &decoder->builder; CFF_Driver driver = (CFF_Driver)FT_FACE_DRIVER( builder->face ); /* local error */ FT_Error error2 = FT_Err_Ok; CF2_BufferRec buf; CF2_Matrix transform; CF2_F16Dot16 glyphWidth; FT_Bool hinted; FT_Bool scaled; /* FreeType has already looked up the GID; convert to */ /* `RegionBuffer', assuming that the input has been validated */ FT_ASSERT( charstring_base + charstring_len >= charstring_base ); FT_ZERO( &buf ); buf.start = buf.ptr = charstring_base; buf.end = charstring_base + charstring_len; FT_ZERO( &transform ); cf2_getScaleAndHintFlag( decoder, &transform.a, &transform.d, &hinted, &scaled ); font->renderingFlags = 0; if ( hinted ) font->renderingFlags |= CF2_FlagsHinted; if ( scaled && !driver->no_stem_darkening ) font->renderingFlags |= CF2_FlagsDarkened; font->darkenParams[0] = driver->darken_params[0]; font->darkenParams[1] = driver->darken_params[1]; font->darkenParams[2] = driver->darken_params[2]; font->darkenParams[3] = driver->darken_params[3]; font->darkenParams[4] = driver->darken_params[4]; font->darkenParams[5] = driver->darken_params[5]; font->darkenParams[6] = driver->darken_params[6]; font->darkenParams[7] = driver->darken_params[7]; /* now get an outline for this glyph; */ /* also get units per em to validate scale */ font->unitsPerEm = (CF2_Int)cf2_getUnitsPerEm( decoder ); if ( scaled ) { error2 = cf2_checkTransform( &transform, font->unitsPerEm ); if ( error2 ) return error2; } error2 = cf2_getGlyphOutline( font, &buf, &transform, &glyphWidth ); if ( error2 ) return FT_ERR( Invalid_File_Format ); cf2_setGlyphWidth( &font->outline, glyphWidth ); return FT_Err_Ok; } } /* get pointer to current FreeType subfont (based on current glyphID) */ FT_LOCAL_DEF( CFF_SubFont ) cf2_getSubfont( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return decoder->current_subfont; } /* get `y_ppem' from `CFF_Size' */ FT_LOCAL_DEF( CF2_Fixed ) cf2_getPpemY( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->builder.face && decoder->builder.face->root.size ); /* * Note that `y_ppem' can be zero if there wasn't a call to * `FT_Set_Char_Size' or something similar. However, this isn't a * problem since we come to this place in the code only if * FT_LOAD_NO_SCALE is set (the other case gets caught by * `cf2_checkTransform'). The ppem value is needed to compute the stem * darkening, which is disabled for getting the unscaled outline. * */ return cf2_intToFixed( decoder->builder.face->root.size->metrics.y_ppem ); } /* get standard stem widths for the current subfont; */ /* FreeType stores these as integer font units */ /* (note: variable names seem swapped) */ FT_LOCAL_DEF( CF2_Fixed ) cf2_getStdVW( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return cf2_intToFixed( decoder->current_subfont->private_dict.standard_height ); } FT_LOCAL_DEF( CF2_Fixed ) cf2_getStdHW( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return cf2_intToFixed( decoder->current_subfont->private_dict.standard_width ); } /* note: FreeType stores 1000 times the actual value for `BlueScale' */ FT_LOCAL_DEF( void ) cf2_getBlueMetrics( CFF_Decoder* decoder, CF2_Fixed* blueScale, CF2_Fixed* blueShift, CF2_Fixed* blueFuzz ) { FT_ASSERT( decoder && decoder->current_subfont ); *blueScale = FT_DivFix( decoder->current_subfont->private_dict.blue_scale, cf2_intToFixed( 1000 ) ); *blueShift = cf2_intToFixed( decoder->current_subfont->private_dict.blue_shift ); *blueFuzz = cf2_intToFixed( decoder->current_subfont->private_dict.blue_fuzz ); } /* get blue values counts and arrays; the FreeType parser has validated */ /* the counts and verified that each is an even number */ FT_LOCAL_DEF( void ) cf2_getBlueValues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ) { FT_ASSERT( decoder && decoder->current_subfont ); *count = decoder->current_subfont->private_dict.num_blue_values; *data = (FT_Pos*) &decoder->current_subfont->private_dict.blue_values; } FT_LOCAL_DEF( void ) cf2_getOtherBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ) { FT_ASSERT( decoder && decoder->current_subfont ); *count = decoder->current_subfont->private_dict.num_other_blues; *data = (FT_Pos*) &decoder->current_subfont->private_dict.other_blues; } FT_LOCAL_DEF( void ) cf2_getFamilyBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ) { FT_ASSERT( decoder && decoder->current_subfont ); *count = decoder->current_subfont->private_dict.num_family_blues; *data = (FT_Pos*) &decoder->current_subfont->private_dict.family_blues; } FT_LOCAL_DEF( void ) cf2_getFamilyOtherBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ) { FT_ASSERT( decoder && decoder->current_subfont ); *count = decoder->current_subfont->private_dict.num_family_other_blues; *data = (FT_Pos*) &decoder->current_subfont->private_dict.family_other_blues; } FT_LOCAL_DEF( CF2_Int ) cf2_getLanguageGroup( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return decoder->current_subfont->private_dict.language_group; } /* convert unbiased subroutine index to `CF2_Buffer' and */ /* return 0 on success */ FT_LOCAL_DEF( CF2_Int ) cf2_initGlobalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ) { FT_ASSERT( decoder ); FT_ZERO( buf ); idx += decoder->globals_bias; if ( idx >= decoder->num_globals ) return TRUE; /* error */ FT_ASSERT( decoder->globals ); buf->start = buf->ptr = decoder->globals[idx]; buf->end = decoder->globals[idx + 1]; return FALSE; /* success */ } /* convert AdobeStandardEncoding code to CF2_Buffer; */ /* used for seac component */ FT_LOCAL_DEF( FT_Error ) cf2_getSeacComponent( CFF_Decoder* decoder, CF2_UInt code, CF2_Buffer buf ) { CF2_Int gid; FT_Byte* charstring; FT_ULong len; FT_Error error; FT_ASSERT( decoder ); FT_ZERO( buf ); gid = cff_lookup_glyph_by_stdcharcode( decoder->cff, code ); if ( gid < 0 ) return FT_THROW( Invalid_Glyph_Format ); error = cff_get_glyph_data( decoder->builder.face, gid, &charstring, &len ); /* TODO: for now, just pass the FreeType error through */ if ( error ) return error; /* assume input has been validated */ FT_ASSERT( charstring + len >= charstring ); buf->start = charstring; buf->end = charstring + len; buf->ptr = buf->start; return FT_Err_Ok; } FT_LOCAL_DEF( void ) cf2_freeSeacComponent( CFF_Decoder* decoder, CF2_Buffer buf ) { FT_ASSERT( decoder ); cff_free_glyph_data( decoder->builder.face, (FT_Byte**)&buf->start, (FT_ULong)( buf->end - buf->start ) ); } FT_LOCAL_DEF( CF2_Int ) cf2_initLocalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ) { FT_ASSERT( decoder ); FT_ZERO( buf ); idx += decoder->locals_bias; if ( idx >= decoder->num_locals ) return TRUE; /* error */ FT_ASSERT( decoder->locals ); buf->start = buf->ptr = decoder->locals[idx]; buf->end = decoder->locals[idx + 1]; return FALSE; /* success */ } FT_LOCAL_DEF( CF2_Fixed ) cf2_getDefaultWidthX( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return cf2_intToFixed( decoder->current_subfont->private_dict.default_width ); } FT_LOCAL_DEF( CF2_Fixed ) cf2_getNominalWidthX( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return cf2_intToFixed( decoder->current_subfont->private_dict.nominal_width ); } FT_LOCAL_DEF( void ) cf2_outline_reset( CF2_Outline outline ) { CFF_Decoder* decoder = outline->decoder; FT_ASSERT( decoder ); outline->root.windingMomentum = 0; FT_GlyphLoader_Rewind( decoder->builder.loader ); } FT_LOCAL_DEF( void ) cf2_outline_close( CF2_Outline outline ) { CFF_Decoder* decoder = outline->decoder; FT_ASSERT( decoder ); cff_builder_close_contour( &decoder->builder ); FT_GlyphLoader_Add( decoder->builder.loader ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2ft.c
C
apache-2.0
20,283
/***************************************************************************/ /* */ /* cf2ft.h */ /* */ /* FreeType Glue Component to Adobe's Interpreter (specification). */ /* */ /* Copyright 2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2FT_H__ #define __CF2FT_H__ #include "cf2types.h" /* TODO: disable asserts for now */ #define CF2_NDEBUG #include FT_SYSTEM_H #include "cf2glue.h" #include "cffgload.h" /* for CFF_Decoder */ FT_BEGIN_HEADER FT_LOCAL( FT_Error ) cf2_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ); FT_LOCAL( CFF_SubFont ) cf2_getSubfont( CFF_Decoder* decoder ); FT_LOCAL( CF2_Fixed ) cf2_getPpemY( CFF_Decoder* decoder ); FT_LOCAL( CF2_Fixed ) cf2_getStdVW( CFF_Decoder* decoder ); FT_LOCAL( CF2_Fixed ) cf2_getStdHW( CFF_Decoder* decoder ); FT_LOCAL( void ) cf2_getBlueMetrics( CFF_Decoder* decoder, CF2_Fixed* blueScale, CF2_Fixed* blueShift, CF2_Fixed* blueFuzz ); FT_LOCAL( void ) cf2_getBlueValues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ); FT_LOCAL( void ) cf2_getOtherBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ); FT_LOCAL( void ) cf2_getFamilyBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ); FT_LOCAL( void ) cf2_getFamilyOtherBlues( CFF_Decoder* decoder, size_t* count, FT_Pos* *data ); FT_LOCAL( CF2_Int ) cf2_getLanguageGroup( CFF_Decoder* decoder ); FT_LOCAL( CF2_Int ) cf2_initGlobalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ); FT_LOCAL( FT_Error ) cf2_getSeacComponent( CFF_Decoder* decoder, CF2_UInt code, CF2_Buffer buf ); FT_LOCAL( void ) cf2_freeSeacComponent( CFF_Decoder* decoder, CF2_Buffer buf ); FT_LOCAL( CF2_Int ) cf2_initLocalRegionBuffer( CFF_Decoder* decoder, CF2_UInt idx, CF2_Buffer buf ); FT_LOCAL( CF2_Fixed ) cf2_getDefaultWidthX( CFF_Decoder* decoder ); FT_LOCAL( CF2_Fixed ) cf2_getNominalWidthX( CFF_Decoder* decoder ); /* * FreeType client outline * * process output from the charstring interpreter */ typedef struct CF2_OutlineRec_ { CF2_OutlineCallbacksRec root; /* base class must be first */ CFF_Decoder* decoder; } CF2_OutlineRec, *CF2_Outline; FT_LOCAL( void ) cf2_outline_reset( CF2_Outline outline ); FT_LOCAL( void ) cf2_outline_close( CF2_Outline outline ); FT_END_HEADER #endif /* __CF2FT_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2ft.h
C
apache-2.0
5,647
/***************************************************************************/ /* */ /* cf2glue.h */ /* */ /* Adobe's code for shared stuff (specification only). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2GLUE_H__ #define __CF2GLUE_H__ /* common includes for other modules */ #include "cf2error.h" #include "cf2fixed.h" #include "cf2arrst.h" #include "cf2read.h" FT_BEGIN_HEADER /* rendering parameters */ /* apply hints to rendered glyphs */ #define CF2_FlagsHinted 1 /* for testing */ #define CF2_FlagsDarkened 2 /* type for holding the flags */ typedef CF2_Int CF2_RenderingFlags; /* elements of a glyph outline */ typedef enum CF2_PathOp_ { CF2_PathOpMoveTo = 1, /* change the current point */ CF2_PathOpLineTo = 2, /* line */ CF2_PathOpQuadTo = 3, /* quadratic curve */ CF2_PathOpCubeTo = 4 /* cubic curve */ } CF2_PathOp; /* a matrix of fixed point values */ typedef struct CF2_Matrix_ { CF2_F16Dot16 a; CF2_F16Dot16 b; CF2_F16Dot16 c; CF2_F16Dot16 d; CF2_F16Dot16 tx; CF2_F16Dot16 ty; } CF2_Matrix; /* these typedefs are needed by more than one header file */ /* and gcc compiler doesn't allow redefinition */ typedef struct CF2_FontRec_ CF2_FontRec, *CF2_Font; typedef struct CF2_HintRec_ CF2_HintRec, *CF2_Hint; /* A common structure for all callback parameters. */ /* */ /* Some members may be unused. For example, `pt0' is not used for */ /* `moveTo' and `pt3' is not used for `quadTo'. The initial point `pt0' */ /* is included for each path element for generality; curve conversions */ /* need it. The `op' parameter allows one function to handle multiple */ /* element types. */ typedef struct CF2_CallbackParamsRec_ { FT_Vector pt0; FT_Vector pt1; FT_Vector pt2; FT_Vector pt3; CF2_Int op; } CF2_CallbackParamsRec, *CF2_CallbackParams; /* forward reference */ typedef struct CF2_OutlineCallbacksRec_ CF2_OutlineCallbacksRec, *CF2_OutlineCallbacks; /* callback function pointers */ typedef void (*CF2_Callback_Type)( CF2_OutlineCallbacks callbacks, const CF2_CallbackParams params ); struct CF2_OutlineCallbacksRec_ { CF2_Callback_Type moveTo; CF2_Callback_Type lineTo; CF2_Callback_Type quadTo; CF2_Callback_Type cubeTo; CF2_Int windingMomentum; /* for winding order detection */ FT_Memory memory; FT_Error* error; }; FT_END_HEADER #endif /* __CF2GLUE_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2glue.h
C
apache-2.0
5,430
/***************************************************************************/ /* */ /* cf2hints.c */ /* */ /* Adobe's code for handling CFF hints (body). */ /* */ /* Copyright 2007-2014 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2glue.h" #include "cf2font.h" #include "cf2hints.h" #include "cf2intrp.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cf2hints typedef struct CF2_HintMoveRec_ { size_t j; /* index of upper hint map edge */ CF2_Fixed moveUp; /* adjustment to optimum position */ } CF2_HintMoveRec, *CF2_HintMove; /* Compute angular momentum for winding order detection. It is called */ /* for all lines and curves, but not necessarily in element order. */ static CF2_Int cf2_getWindingMomentum( CF2_Fixed x1, CF2_Fixed y1, CF2_Fixed x2, CF2_Fixed y2 ) { /* cross product of pt1 position from origin with pt2 position from */ /* pt1; we reduce the precision so that the result fits into 32 bits */ return ( x1 >> 16 ) * ( ( y2 - y1 ) >> 16 ) - ( y1 >> 16 ) * ( ( x2 - x1 ) >> 16 ); } /* * Construct from a StemHint; this is used as a parameter to * `cf2_blues_capture'. * `hintOrigin' is the character space displacement of a seac accent. * Adjust stem hint for darkening here. * */ static void cf2_hint_init( CF2_Hint hint, const CF2_ArrStack stemHintArray, size_t indexStemHint, const CF2_Font font, CF2_Fixed hintOrigin, CF2_Fixed scale, FT_Bool bottom ) { CF2_Fixed width; const CF2_StemHintRec* stemHint; FT_ZERO( hint ); stemHint = (const CF2_StemHintRec*)cf2_arrstack_getPointer( stemHintArray, indexStemHint ); width = stemHint->max - stemHint->min; if ( width == cf2_intToFixed( -21 ) ) { /* ghost bottom */ if ( bottom ) { hint->csCoord = stemHint->max; hint->flags = CF2_GhostBottom; } else hint->flags = 0; } else if ( width == cf2_intToFixed( -20 ) ) { /* ghost top */ if ( bottom ) hint->flags = 0; else { hint->csCoord = stemHint->min; hint->flags = CF2_GhostTop; } } else if ( width < 0 ) { /* inverted pair */ /* * Hints with negative widths were produced by an early version of a * non-Adobe font tool. The Type 2 spec allows edge (ghost) hints * with negative widths, but says * * All other negative widths have undefined meaning. * * CoolType has a silent workaround that negates the hint width; for * permissive mode, we do the same here. * * Note: Such fonts cannot use ghost hints, but should otherwise work. * Note: Some poor hints in our faux fonts can produce negative * widths at some blends. For example, see a light weight of * `u' in ASerifMM. * */ if ( bottom ) { hint->csCoord = stemHint->max; hint->flags = CF2_PairBottom; } else { hint->csCoord = stemHint->min; hint->flags = CF2_PairTop; } } else { /* normal pair */ if ( bottom ) { hint->csCoord = stemHint->min; hint->flags = CF2_PairBottom; } else { hint->csCoord = stemHint->max; hint->flags = CF2_PairTop; } } /* Now that ghost hints have been detected, adjust this edge for */ /* darkening. Bottoms are not changed; tops are incremented by twice */ /* `darkenY'. */ if ( cf2_hint_isTop( hint ) ) hint->csCoord += 2 * font->darkenY; hint->csCoord += hintOrigin; hint->scale = scale; hint->index = indexStemHint; /* index in original stem hint array */ /* if original stem hint has been used, use the same position */ if ( hint->flags != 0 && stemHint->used ) { if ( cf2_hint_isTop( hint ) ) hint->dsCoord = stemHint->maxDS; else hint->dsCoord = stemHint->minDS; cf2_hint_lock( hint ); } else hint->dsCoord = FT_MulFix( hint->csCoord, scale ); } /* initialize an invalid hint map element */ static void cf2_hint_initZero( CF2_Hint hint ) { FT_ZERO( hint ); } FT_LOCAL_DEF( FT_Bool ) cf2_hint_isValid( const CF2_Hint hint ) { return (FT_Bool)( hint->flags != 0 ); } static FT_Bool cf2_hint_isPair( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & ( CF2_PairBottom | CF2_PairTop ) ) != 0 ); } static FT_Bool cf2_hint_isPairTop( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & CF2_PairTop ) != 0 ); } FT_LOCAL_DEF( FT_Bool ) cf2_hint_isTop( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & ( CF2_PairTop | CF2_GhostTop ) ) != 0 ); } FT_LOCAL_DEF( FT_Bool ) cf2_hint_isBottom( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & ( CF2_PairBottom | CF2_GhostBottom ) ) != 0 ); } static FT_Bool cf2_hint_isLocked( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & CF2_Locked ) != 0 ); } static FT_Bool cf2_hint_isSynthetic( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & CF2_Synthetic ) != 0 ); } FT_LOCAL_DEF( void ) cf2_hint_lock( CF2_Hint hint ) { hint->flags |= CF2_Locked; } FT_LOCAL_DEF( void ) cf2_hintmap_init( CF2_HintMap hintmap, CF2_Font font, CF2_HintMap initialMap, CF2_ArrStack hintMoves, CF2_Fixed scale ) { FT_ZERO( hintmap ); /* copy parameters from font instance */ hintmap->hinted = font->hinted; hintmap->scale = scale; hintmap->font = font; hintmap->initialHintMap = initialMap; /* will clear in `cf2_hintmap_adjustHints' */ hintmap->hintMoves = hintMoves; } static FT_Bool cf2_hintmap_isValid( const CF2_HintMap hintmap ) { return hintmap->isValid; } /* transform character space coordinate to device space using hint map */ static CF2_Fixed cf2_hintmap_map( CF2_HintMap hintmap, CF2_Fixed csCoord ) { FT_ASSERT( hintmap->isValid ); /* must call Build before Map */ FT_ASSERT( hintmap->lastIndex < CF2_MAX_HINT_EDGES ); if ( hintmap->count == 0 || ! hintmap->hinted ) { /* there are no hints; use uniform scale and zero offset */ return FT_MulFix( csCoord, hintmap->scale ); } else { /* start linear search from last hit */ CF2_UInt i = hintmap->lastIndex; /* search up */ while ( i < hintmap->count - 1 && csCoord >= hintmap->edge[i + 1].csCoord ) i += 1; /* search down */ while ( i > 0 && csCoord < hintmap->edge[i].csCoord ) i -= 1; hintmap->lastIndex = i; if ( i == 0 && csCoord < hintmap->edge[0].csCoord ) { /* special case for points below first edge: use uniform scale */ return FT_MulFix( csCoord - hintmap->edge[0].csCoord, hintmap->scale ) + hintmap->edge[0].dsCoord; } else { /* * Note: entries with duplicate csCoord are allowed. * Use edge[i], the highest entry where csCoord >= entry[i].csCoord */ return FT_MulFix( csCoord - hintmap->edge[i].csCoord, hintmap->edge[i].scale ) + hintmap->edge[i].dsCoord; } } } /* * This hinting policy moves a hint pair in device space so that one of * its two edges is on a device pixel boundary (its fractional part is * zero). `cf2_hintmap_insertHint' guarantees no overlap in CS * space. Ensure here that there is no overlap in DS. * * In the first pass, edges are adjusted relative to adjacent hints. * Those that are below have already been adjusted. Those that are * above have not yet been adjusted. If a hint above blocks an * adjustment to an optimal position, we will try again in a second * pass. The second pass is top-down. * */ static void cf2_hintmap_adjustHints( CF2_HintMap hintmap ) { size_t i, j; cf2_arrstack_clear( hintmap->hintMoves ); /* working storage */ /* * First pass is bottom-up (font hint order) without look-ahead. * Locked edges are already adjusted. * Unlocked edges begin with dsCoord from `initialHintMap'. * Save edges that are not optimally adjusted in `hintMoves' array, * and process them in second pass. */ for ( i = 0; i < hintmap->count; i++ ) { FT_Bool isPair = cf2_hint_isPair( &hintmap->edge[i] ); /* index of upper edge (same value for ghost hint) */ j = isPair ? i + 1 : i; FT_ASSERT( j < hintmap->count ); FT_ASSERT( cf2_hint_isValid( &hintmap->edge[i] ) ); FT_ASSERT( cf2_hint_isValid( &hintmap->edge[j] ) ); FT_ASSERT( cf2_hint_isLocked( &hintmap->edge[i] ) == cf2_hint_isLocked( &hintmap->edge[j] ) ); if ( !cf2_hint_isLocked( &hintmap->edge[i] ) ) { /* hint edge is not locked, we can adjust it */ CF2_Fixed fracDown = cf2_fixedFraction( hintmap->edge[i].dsCoord ); CF2_Fixed fracUp = cf2_fixedFraction( hintmap->edge[j].dsCoord ); /* calculate all four possibilities; moves down are negative */ CF2_Fixed downMoveDown = 0 - fracDown; CF2_Fixed upMoveDown = 0 - fracUp; CF2_Fixed downMoveUp = fracDown == 0 ? 0 : cf2_intToFixed( 1 ) - fracDown; CF2_Fixed upMoveUp = fracUp == 0 ? 0 : cf2_intToFixed( 1 ) - fracUp; /* smallest move up */ CF2_Fixed moveUp = FT_MIN( downMoveUp, upMoveUp ); /* smallest move down */ CF2_Fixed moveDown = FT_MAX( downMoveDown, upMoveDown ); /* final amount to move edge or edge pair */ CF2_Fixed move; CF2_Fixed downMinCounter = CF2_MIN_COUNTER; CF2_Fixed upMinCounter = CF2_MIN_COUNTER; FT_Bool saveEdge = FALSE; /* minimum counter constraint doesn't apply when adjacent edges */ /* are synthetic */ /* TODO: doesn't seem a big effect; for now, reduce the code */ #if 0 if ( i == 0 || cf2_hint_isSynthetic( &hintmap->edge[i - 1] ) ) downMinCounter = 0; if ( j >= hintmap->count - 1 || cf2_hint_isSynthetic( &hintmap->edge[j + 1] ) ) upMinCounter = 0; #endif /* is there room to move up? */ /* there is if we are at top of array or the next edge is at or */ /* beyond proposed move up? */ if ( j >= hintmap->count - 1 || hintmap->edge[j + 1].dsCoord >= hintmap->edge[j].dsCoord + moveUp + upMinCounter ) { /* there is room to move up; is there also room to move down? */ if ( i == 0 || hintmap->edge[i - 1].dsCoord <= hintmap->edge[i].dsCoord + moveDown - downMinCounter ) { /* move smaller absolute amount */ move = ( -moveDown < moveUp ) ? moveDown : moveUp; /* optimum */ } else move = moveUp; } else { /* is there room to move down? */ if ( i == 0 || hintmap->edge[i - 1].dsCoord <= hintmap->edge[i].dsCoord + moveDown - downMinCounter ) { move = moveDown; /* true if non-optimum move */ saveEdge = (FT_Bool)( moveUp < -moveDown ); } else { /* no room to move either way without overlapping or reducing */ /* the counter too much */ move = 0; saveEdge = TRUE; } } /* Identify non-moves and moves down that aren't optimal, and save */ /* them for second pass. */ /* Do this only if there is an unlocked edge above (which could */ /* possibly move). */ if ( saveEdge && j < hintmap->count - 1 && !cf2_hint_isLocked( &hintmap->edge[j + 1] ) ) { CF2_HintMoveRec savedMove; savedMove.j = j; /* desired adjustment in second pass */ savedMove.moveUp = moveUp - move; cf2_arrstack_push( hintmap->hintMoves, &savedMove ); } /* move the edge(s) */ hintmap->edge[i].dsCoord += move; if ( isPair ) hintmap->edge[j].dsCoord += move; } /* assert there are no overlaps in device space */ FT_ASSERT( i == 0 || hintmap->edge[i - 1].dsCoord <= hintmap->edge[i].dsCoord ); FT_ASSERT( i < j || hintmap->edge[i].dsCoord <= hintmap->edge[j].dsCoord ); /* adjust the scales, avoiding divide by zero */ if ( i > 0 ) { if ( hintmap->edge[i].csCoord != hintmap->edge[i - 1].csCoord ) hintmap->edge[i - 1].scale = FT_DivFix( hintmap->edge[i].dsCoord - hintmap->edge[i - 1].dsCoord, hintmap->edge[i].csCoord - hintmap->edge[i - 1].csCoord ); } if ( isPair ) { if ( hintmap->edge[j].csCoord != hintmap->edge[j - 1].csCoord ) hintmap->edge[j - 1].scale = FT_DivFix( hintmap->edge[j].dsCoord - hintmap->edge[j - 1].dsCoord, hintmap->edge[j].csCoord - hintmap->edge[j - 1].csCoord ); i += 1; /* skip upper edge on next loop */ } } /* second pass tries to move non-optimal hints up, in case there is */ /* room now */ for ( i = cf2_arrstack_size( hintmap->hintMoves ); i > 0; i-- ) { CF2_HintMove hintMove = (CF2_HintMove) cf2_arrstack_getPointer( hintmap->hintMoves, i - 1 ); j = hintMove->j; /* this was tested before the push, above */ FT_ASSERT( j < hintmap->count - 1 ); /* is there room to move up? */ if ( hintmap->edge[j + 1].dsCoord >= hintmap->edge[j].dsCoord + hintMove->moveUp + CF2_MIN_COUNTER ) { /* there is more room now, move edge up */ hintmap->edge[j].dsCoord += hintMove->moveUp; if ( cf2_hint_isPair( &hintmap->edge[j] ) ) { FT_ASSERT( j > 0 ); hintmap->edge[j - 1].dsCoord += hintMove->moveUp; } } } } /* insert hint edges into map, sorted by csCoord */ static void cf2_hintmap_insertHint( CF2_HintMap hintmap, CF2_Hint bottomHintEdge, CF2_Hint topHintEdge ) { CF2_UInt indexInsert; /* set default values, then check for edge hints */ FT_Bool isPair = TRUE; CF2_Hint firstHintEdge = bottomHintEdge; CF2_Hint secondHintEdge = topHintEdge; /* one or none of the input params may be invalid when dealing with */ /* edge hints; at least one edge must be valid */ FT_ASSERT( cf2_hint_isValid( bottomHintEdge ) || cf2_hint_isValid( topHintEdge ) ); /* determine how many and which edges to insert */ if ( !cf2_hint_isValid( bottomHintEdge ) ) { /* insert only the top edge */ firstHintEdge = topHintEdge; isPair = FALSE; } else if ( !cf2_hint_isValid( topHintEdge ) ) { /* insert only the bottom edge */ isPair = FALSE; } /* paired edges must be in proper order */ FT_ASSERT( !isPair || topHintEdge->csCoord >= bottomHintEdge->csCoord ); /* linear search to find index value of insertion point */ indexInsert = 0; for ( ; indexInsert < hintmap->count; indexInsert++ ) { if ( hintmap->edge[indexInsert].csCoord >= firstHintEdge->csCoord ) break; } /* * Discard any hints that overlap in character space. Most often, this * is while building the initial map, where captured hints from all * zones are combined. Define overlap to include hints that `touch' * (overlap zero). Hiragino Sans/Gothic fonts have numerous hints that * touch. Some fonts have non-ideographic glyphs that overlap our * synthetic hints. * * Overlap also occurs when darkening stem hints that are close. * */ if ( indexInsert < hintmap->count ) { /* we are inserting before an existing edge: */ /* verify that an existing edge is not the same */ if ( hintmap->edge[indexInsert].csCoord == firstHintEdge->csCoord ) return; /* ignore overlapping stem hint */ /* verify that a new pair does not straddle the next edge */ if ( isPair && hintmap->edge[indexInsert].csCoord <= secondHintEdge->csCoord ) return; /* ignore overlapping stem hint */ /* verify that we are not inserting between paired edges */ if ( cf2_hint_isPairTop( &hintmap->edge[indexInsert] ) ) return; /* ignore overlapping stem hint */ } /* recompute device space locations using initial hint map */ if ( cf2_hintmap_isValid( hintmap->initialHintMap ) && !cf2_hint_isLocked( firstHintEdge ) ) { if ( isPair ) { /* Use hint map to position the center of stem, and nominal scale */ /* to position the two edges. This preserves the stem width. */ CF2_Fixed midpoint = cf2_hintmap_map( hintmap->initialHintMap, ( secondHintEdge->csCoord + firstHintEdge->csCoord ) / 2 ); CF2_Fixed halfWidth = FT_MulFix( ( secondHintEdge->csCoord - firstHintEdge->csCoord ) / 2, hintmap->scale ); firstHintEdge->dsCoord = midpoint - halfWidth; secondHintEdge->dsCoord = midpoint + halfWidth; } else firstHintEdge->dsCoord = cf2_hintmap_map( hintmap->initialHintMap, firstHintEdge->csCoord ); } /* * Discard any hints that overlap in device space; this can occur * because locked hints have been moved to align with blue zones. * * TODO: Although we might correct this later during adjustment, we * don't currently have a way to delete a conflicting hint once it has * been inserted. See v2.030 MinionPro-Regular, 12 ppem darkened, * initial hint map for second path, glyph 945 (the perispomeni (tilde) * in U+1F6E, Greek omega with psili and perispomeni). Darkening is * 25. Pair 667,747 initially conflicts in design space with top edge * 660. This is because 667 maps to 7.87, and the top edge was * captured by a zone at 8.0. The pair is later successfully inserted * in a zone without the top edge. In this zone it is adjusted to 8.0, * and no longer conflicts with the top edge in design space. This * means it can be included in yet a later zone which does have the top * edge hint. This produces a small mismatch between the first and * last points of this path, even though the hint masks are the same. * The density map difference is tiny (1/256). * */ if ( indexInsert > 0 ) { /* we are inserting after an existing edge */ if ( firstHintEdge->dsCoord < hintmap->edge[indexInsert - 1].dsCoord ) return; } if ( indexInsert < hintmap->count ) { /* we are inserting before an existing edge */ if ( isPair ) { if ( secondHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord ) return; } else { if ( firstHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord ) return; } } /* make room to insert */ { CF2_Int iSrc = hintmap->count - 1; CF2_Int iDst = isPair ? hintmap->count + 1 : hintmap->count; CF2_Int count = hintmap->count - indexInsert; if ( iDst >= CF2_MAX_HINT_EDGES ) { FT_TRACE4(( "cf2_hintmap_insertHint: too many hintmaps\n" )); return; } while ( count-- ) hintmap->edge[iDst--] = hintmap->edge[iSrc--]; /* insert first edge */ hintmap->edge[indexInsert] = *firstHintEdge; /* copy struct */ hintmap->count += 1; if ( isPair ) { /* insert second edge */ hintmap->edge[indexInsert + 1] = *secondHintEdge; /* copy struct */ hintmap->count += 1; } } return; } /* * Build a map from hints and mask. * * This function may recur one level if `hintmap->initialHintMap' is not yet * valid. * If `initialMap' is true, simply build initial map. * * Synthetic hints are used in two ways. A hint at zero is inserted, if * needed, in the initial hint map, to prevent translations from * propagating across the origin. If synthetic em box hints are enabled * for ideographic dictionaries, then they are inserted in all hint * maps, including the initial one. * */ FT_LOCAL_DEF( void ) cf2_hintmap_build( CF2_HintMap hintmap, CF2_ArrStack hStemHintArray, CF2_ArrStack vStemHintArray, CF2_HintMask hintMask, CF2_Fixed hintOrigin, FT_Bool initialMap ) { FT_Byte* maskPtr; CF2_Font font = hintmap->font; CF2_HintMaskRec tempHintMask; size_t bitCount, i; FT_Byte maskByte; /* check whether initial map is constructed */ if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) ) { /* make recursive call with initialHintMap and temporary mask; */ /* temporary mask will get all bits set, below */ cf2_hintmask_init( &tempHintMask, hintMask->error ); cf2_hintmap_build( hintmap->initialHintMap, hStemHintArray, vStemHintArray, &tempHintMask, hintOrigin, TRUE ); } if ( !cf2_hintmask_isValid( hintMask ) ) { /* without a hint mask, assume all hints are active */ cf2_hintmask_setAll( hintMask, cf2_arrstack_size( hStemHintArray ) + cf2_arrstack_size( vStemHintArray ) ); if ( !cf2_hintmask_isValid( hintMask ) ) return; /* too many stem hints */ } /* begin by clearing the map */ hintmap->count = 0; hintmap->lastIndex = 0; /* make a copy of the hint mask so we can modify it */ tempHintMask = *hintMask; maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask ); /* use the hStem hints only, which are first in the mask */ /* TODO: compare this to cffhintmaskGetBitCount */ bitCount = cf2_arrstack_size( hStemHintArray ); /* synthetic embox hints get highest priority */ if ( font->blues.doEmBoxHints ) { CF2_HintRec dummy; cf2_hint_initZero( &dummy ); /* invalid hint map element */ /* ghost bottom */ cf2_hintmap_insertHint( hintmap, &font->blues.emBoxBottomEdge, &dummy ); /* ghost top */ cf2_hintmap_insertHint( hintmap, &dummy, &font->blues.emBoxTopEdge ); } /* insert hints captured by a blue zone or already locked (higher */ /* priority) */ for ( i = 0, maskByte = 0x80; i < bitCount; i++ ) { if ( maskByte & *maskPtr ) { /* expand StemHint into two `CF2_Hint' elements */ CF2_HintRec bottomHintEdge, topHintEdge; cf2_hint_init( &bottomHintEdge, hStemHintArray, i, font, hintOrigin, hintmap->scale, TRUE /* bottom */ ); cf2_hint_init( &topHintEdge, hStemHintArray, i, font, hintOrigin, hintmap->scale, FALSE /* top */ ); if ( cf2_hint_isLocked( &bottomHintEdge ) || cf2_hint_isLocked( &topHintEdge ) || cf2_blues_capture( &font->blues, &bottomHintEdge, &topHintEdge ) ) { /* insert captured hint into map */ cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge ); *maskPtr &= ~maskByte; /* turn off the bit for this hint */ } } if ( ( i & 7 ) == 7 ) { /* move to next mask byte */ maskPtr++; maskByte = 0x80; } else maskByte >>= 1; } /* initial hint map includes only captured hints plus maybe one at 0 */ /* * TODO: There is a problem here because we are trying to build a * single hint map containing all captured hints. It is * possible for there to be conflicts between captured hints, * either because of darkening or because the hints are in * separate hint zones (we are ignoring hint zones for the * initial map). An example of the latter is MinionPro-Regular * v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem. * A stem hint for the psili conflicts with the top edge hint * for the base character. The stem hint gets priority because * of its sort order. In glyph 884 (Greek Capital Alpha with * Psili and Oxia), the top of the base character gets a stem * hint, and the psili does not. This creates different initial * maps for the two glyphs resulting in different renderings of * the base character. Will probably defer this either as not * worth the cost or as a font bug. I don't think there is any * good reason for an accent to be captured by an alignment * zone. -darnold 2/12/10 */ if ( initialMap ) { /* Apply a heuristic that inserts a point for (0,0), unless it's */ /* already covered by a mapping. This locks the baseline for glyphs */ /* that have no baseline hints. */ if ( hintmap->count == 0 || hintmap->edge[0].csCoord > 0 || hintmap->edge[hintmap->count - 1].csCoord < 0 ) { /* all edges are above 0 or all edges are below 0; */ /* construct a locked edge hint at 0 */ CF2_HintRec edge, invalid; cf2_hint_initZero( &edge ); edge.flags = CF2_GhostBottom | CF2_Locked | CF2_Synthetic; edge.scale = hintmap->scale; cf2_hint_initZero( &invalid ); cf2_hintmap_insertHint( hintmap, &edge, &invalid ); } } else { /* insert remaining hints */ maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask ); for ( i = 0, maskByte = 0x80; i < bitCount; i++ ) { if ( maskByte & *maskPtr ) { CF2_HintRec bottomHintEdge, topHintEdge; cf2_hint_init( &bottomHintEdge, hStemHintArray, i, font, hintOrigin, hintmap->scale, TRUE /* bottom */ ); cf2_hint_init( &topHintEdge, hStemHintArray, i, font, hintOrigin, hintmap->scale, FALSE /* top */ ); cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge ); } if ( ( i & 7 ) == 7 ) { /* move to next mask byte */ maskPtr++; maskByte = 0x80; } else maskByte >>= 1; } } /* * Note: The following line is a convenient place to break when * debugging hinting. Examine `hintmap->edge' for the list of * enabled hints, then step over the call to see the effect of * adjustment. We stop here first on the recursive call that * creates the initial map, and then on each counter group and * hint zone. */ /* adjust positions of hint edges that are not locked to blue zones */ cf2_hintmap_adjustHints( hintmap ); /* save the position of all hints that were used in this hint map; */ /* if we use them again, we'll locate them in the same position */ if ( !initialMap ) { for ( i = 0; i < hintmap->count; i++ ) { if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) ) { /* Note: include both valid and invalid edges */ /* Note: top and bottom edges are copied back separately */ CF2_StemHint stemhint = (CF2_StemHint) cf2_arrstack_getPointer( hStemHintArray, hintmap->edge[i].index ); if ( cf2_hint_isTop( &hintmap->edge[i] ) ) stemhint->maxDS = hintmap->edge[i].dsCoord; else stemhint->minDS = hintmap->edge[i].dsCoord; stemhint->used = TRUE; } } } /* hint map is ready to use */ hintmap->isValid = TRUE; /* remember this mask has been used */ cf2_hintmask_setNew( hintMask, FALSE ); } FT_LOCAL_DEF( void ) cf2_glyphpath_init( CF2_GlyphPath glyphpath, CF2_Font font, CF2_OutlineCallbacks callbacks, CF2_Fixed scaleY, /* CF2_Fixed hShift, */ CF2_ArrStack hStemHintArray, CF2_ArrStack vStemHintArray, CF2_HintMask hintMask, CF2_Fixed hintOriginY, const CF2_Blues blues, const FT_Vector* fractionalTranslation ) { FT_ZERO( glyphpath ); glyphpath->font = font; glyphpath->callbacks = callbacks; cf2_arrstack_init( &glyphpath->hintMoves, font->memory, &font->error, sizeof ( CF2_HintMoveRec ) ); cf2_hintmap_init( &glyphpath->initialHintMap, font, &glyphpath->initialHintMap, &glyphpath->hintMoves, scaleY ); cf2_hintmap_init( &glyphpath->firstHintMap, font, &glyphpath->initialHintMap, &glyphpath->hintMoves, scaleY ); cf2_hintmap_init( &glyphpath->hintMap, font, &glyphpath->initialHintMap, &glyphpath->hintMoves, scaleY ); glyphpath->scaleX = font->innerTransform.a; glyphpath->scaleC = font->innerTransform.c; glyphpath->scaleY = font->innerTransform.d; glyphpath->fractionalTranslation = *fractionalTranslation; #if 0 glyphpath->hShift = hShift; /* for fauxing */ #endif glyphpath->hStemHintArray = hStemHintArray; glyphpath->vStemHintArray = vStemHintArray; glyphpath->hintMask = hintMask; /* ptr to current mask */ glyphpath->hintOriginY = hintOriginY; glyphpath->blues = blues; glyphpath->darken = font->darkened; /* TODO: should we make copies? */ glyphpath->xOffset = font->darkenX; glyphpath->yOffset = font->darkenY; glyphpath->miterLimit = 2 * FT_MAX( cf2_fixedAbs( glyphpath->xOffset ), cf2_fixedAbs( glyphpath->yOffset ) ); /* .1 character space unit */ glyphpath->snapThreshold = cf2_floatToFixed( 0.1f ); glyphpath->moveIsPending = TRUE; glyphpath->pathIsOpen = FALSE; glyphpath->pathIsClosing = FALSE; glyphpath->elemIsQueued = FALSE; } FT_LOCAL_DEF( void ) cf2_glyphpath_finalize( CF2_GlyphPath glyphpath ) { cf2_arrstack_finalize( &glyphpath->hintMoves ); } /* * Hint point in y-direction and apply outerTransform. * Input `current' hint map (which is actually delayed by one element). * Input x,y point in Character Space. * Output x,y point in Device Space, including translation. */ static void cf2_glyphpath_hintPoint( CF2_GlyphPath glyphpath, CF2_HintMap hintmap, FT_Vector* ppt, CF2_Fixed x, CF2_Fixed y ) { FT_Vector pt; /* hinted point in upright DS */ pt.x = FT_MulFix( glyphpath->scaleX, x ) + FT_MulFix( glyphpath->scaleC, y ); pt.y = cf2_hintmap_map( hintmap, y ); ppt->x = FT_MulFix( glyphpath->font->outerTransform.a, pt.x ) + FT_MulFix( glyphpath->font->outerTransform.c, pt.y ) + glyphpath->fractionalTranslation.x; ppt->y = FT_MulFix( glyphpath->font->outerTransform.b, pt.x ) + FT_MulFix( glyphpath->font->outerTransform.d, pt.y ) + glyphpath->fractionalTranslation.y; } /* * From two line segments, (u1,u2) and (v1,v2), compute a point of * intersection on the corresponding lines. * Return false if no intersection is found, or if the intersection is * too far away from the ends of the line segments, u2 and v1. * */ static FT_Bool cf2_glyphpath_computeIntersection( CF2_GlyphPath glyphpath, const FT_Vector* u1, const FT_Vector* u2, const FT_Vector* v1, const FT_Vector* v2, FT_Vector* intersection ) { /* * Let `u' be a zero-based vector from the first segment, `v' from the * second segment. * Let `w 'be the zero-based vector from `u1' to `v1'. * `perp' is the `perpendicular dot product'; see * http://mathworld.wolfram.com/PerpDotProduct.html. * `s' is the parameter for the parametric line for the first segment * (`u'). * * See notation in * http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm. * Calculations are done in 16.16, but must handle the squaring of * line lengths in character space. We scale all vectors by 1/32 to * avoid overflow. This allows values up to 4095 to be squared. The * scale factor cancels in the divide. * * TODO: the scale factor could be computed from UnitsPerEm. * */ #define cf2_perp( a, b ) \ ( FT_MulFix( a.x, b.y ) - FT_MulFix( a.y, b.x ) ) /* round and divide by 32 */ #define CF2_CS_SCALE( x ) \ ( ( (x) + 0x10 ) >> 5 ) FT_Vector u, v, w; /* scaled vectors */ CF2_Fixed denominator, s; u.x = CF2_CS_SCALE( u2->x - u1->x ); u.y = CF2_CS_SCALE( u2->y - u1->y ); v.x = CF2_CS_SCALE( v2->x - v1->x ); v.y = CF2_CS_SCALE( v2->y - v1->y ); w.x = CF2_CS_SCALE( v1->x - u1->x ); w.y = CF2_CS_SCALE( v1->y - u1->y ); denominator = cf2_perp( u, v ); if ( denominator == 0 ) return FALSE; /* parallel or coincident lines */ s = FT_DivFix( cf2_perp( w, v ), denominator ); intersection->x = u1->x + FT_MulFix( s, u2->x - u1->x ); intersection->y = u1->y + FT_MulFix( s, u2->y - u1->y ); /* * Special case snapping for horizontal and vertical lines. * This cleans up intersections and reduces problems with winding * order detection. * Sample case is sbc cd KozGoPr6N-Medium.otf 20 16685. * Note: these calculations are in character space. * */ if ( u1->x == u2->x && cf2_fixedAbs( intersection->x - u1->x ) < glyphpath->snapThreshold ) intersection->x = u1->x; if ( u1->y == u2->y && cf2_fixedAbs( intersection->y - u1->y ) < glyphpath->snapThreshold ) intersection->y = u1->y; if ( v1->x == v2->x && cf2_fixedAbs( intersection->x - v1->x ) < glyphpath->snapThreshold ) intersection->x = v1->x; if ( v1->y == v2->y && cf2_fixedAbs( intersection->y - v1->y ) < glyphpath->snapThreshold ) intersection->y = v1->y; /* limit the intersection distance from midpoint of u2 and v1 */ if ( cf2_fixedAbs( intersection->x - ( u2->x + v1->x ) / 2 ) > glyphpath->miterLimit || cf2_fixedAbs( intersection->y - ( u2->y + v1->y ) / 2 ) > glyphpath->miterLimit ) return FALSE; return TRUE; } /* * Push the cached element (glyphpath->prevElem*) to the outline * consumer. When a darkening offset is used, the end point of the * cached element may be adjusted to an intersection point or we may * synthesize a connecting line to the current element. If we are * closing a subpath, we may also generate a connecting line to the start * point. * * This is where Character Space (CS) is converted to Device Space (DS) * using a hint map. This calculation must use a HintMap that was valid * at the time the element was saved. For the first point in a subpath, * that is a saved HintMap. For most elements, it just means the caller * has delayed building a HintMap from the current HintMask. * * Transform each point with outerTransform and call the outline * callbacks. This is a general 3x3 transform: * * x' = a*x + c*y + tx, y' = b*x + d*y + ty * * but it uses 4 elements from CF2_Font and the translation part * from CF2_GlyphPath. * */ static void cf2_glyphpath_pushPrevElem( CF2_GlyphPath glyphpath, CF2_HintMap hintmap, FT_Vector* nextP0, FT_Vector nextP1, FT_Bool close ) { CF2_CallbackParamsRec params; FT_Vector* prevP0; FT_Vector* prevP1; FT_Vector intersection = { 0, 0 }; FT_Bool useIntersection = FALSE; FT_ASSERT( glyphpath->prevElemOp == CF2_PathOpLineTo || glyphpath->prevElemOp == CF2_PathOpCubeTo ); if ( glyphpath->prevElemOp == CF2_PathOpLineTo ) { prevP0 = &glyphpath->prevElemP0; prevP1 = &glyphpath->prevElemP1; } else { prevP0 = &glyphpath->prevElemP2; prevP1 = &glyphpath->prevElemP3; } /* optimization: if previous and next elements are offset by the same */ /* amount, then there will be no gap, and no need to compute an */ /* intersection. */ if ( prevP1->x != nextP0->x || prevP1->y != nextP0->y ) { /* previous element does not join next element: */ /* adjust end point of previous element to the intersection */ useIntersection = cf2_glyphpath_computeIntersection( glyphpath, prevP0, prevP1, nextP0, &nextP1, &intersection ); if ( useIntersection ) { /* modify the last point of the cached element (either line or */ /* curve) */ *prevP1 = intersection; } } params.pt0 = glyphpath->currentDS; switch( glyphpath->prevElemOp ) { case CF2_PathOpLineTo: params.op = CF2_PathOpLineTo; /* note: pt2 and pt3 are unused */ if ( close ) { /* use first hint map if closing */ cf2_glyphpath_hintPoint( glyphpath, &glyphpath->firstHintMap, &params.pt1, glyphpath->prevElemP1.x, glyphpath->prevElemP1.y ); } else { cf2_glyphpath_hintPoint( glyphpath, hintmap, &params.pt1, glyphpath->prevElemP1.x, glyphpath->prevElemP1.y ); } /* output only non-zero length lines */ if ( params.pt0.x != params.pt1.x || params.pt0.y != params.pt1.y ) { glyphpath->callbacks->lineTo( glyphpath->callbacks, &params ); glyphpath->currentDS = params.pt1; } break; case CF2_PathOpCubeTo: params.op = CF2_PathOpCubeTo; /* TODO: should we intersect the interior joins (p1-p2 and p2-p3)? */ cf2_glyphpath_hintPoint( glyphpath, hintmap, &params.pt1, glyphpath->prevElemP1.x, glyphpath->prevElemP1.y ); cf2_glyphpath_hintPoint( glyphpath, hintmap, &params.pt2, glyphpath->prevElemP2.x, glyphpath->prevElemP2.y ); cf2_glyphpath_hintPoint( glyphpath, hintmap, &params.pt3, glyphpath->prevElemP3.x, glyphpath->prevElemP3.y ); glyphpath->callbacks->cubeTo( glyphpath->callbacks, &params ); glyphpath->currentDS = params.pt3; break; } if ( !useIntersection || close ) { /* insert connecting line between end of previous element and start */ /* of current one */ /* note: at the end of a subpath, we might do both, so use `nextP0' */ /* before we change it, below */ if ( close ) { /* if we are closing the subpath, then nextP0 is in the first */ /* hint zone */ cf2_glyphpath_hintPoint( glyphpath, &glyphpath->firstHintMap, &params.pt1, nextP0->x, nextP0->y ); } else { cf2_glyphpath_hintPoint( glyphpath, hintmap, &params.pt1, nextP0->x, nextP0->y ); } if ( params.pt1.x != glyphpath->currentDS.x || params.pt1.y != glyphpath->currentDS.y ) { /* length is nonzero */ params.op = CF2_PathOpLineTo; params.pt0 = glyphpath->currentDS; /* note: pt2 and pt3 are unused */ glyphpath->callbacks->lineTo( glyphpath->callbacks, &params ); glyphpath->currentDS = params.pt1; } } if ( useIntersection ) { /* return intersection point to caller */ *nextP0 = intersection; } } /* push a MoveTo element based on current point and offset of current */ /* element */ static void cf2_glyphpath_pushMove( CF2_GlyphPath glyphpath, FT_Vector start ) { CF2_CallbackParamsRec params; params.op = CF2_PathOpMoveTo; params.pt0 = glyphpath->currentDS; /* Test if move has really happened yet; it would have called */ /* `cf2_hintmap_build' to set `isValid'. */ if ( !cf2_hintmap_isValid( &glyphpath->hintMap ) ) { /* we are here iff first subpath is missing a moveto operator: */ /* synthesize first moveTo to finish initialization of hintMap */ cf2_glyphpath_moveTo( glyphpath, glyphpath->start.x, glyphpath->start.y ); } cf2_glyphpath_hintPoint( glyphpath, &glyphpath->hintMap, &params.pt1, start.x, start.y ); /* note: pt2 and pt3 are unused */ glyphpath->callbacks->moveTo( glyphpath->callbacks, &params ); glyphpath->currentDS = params.pt1; glyphpath->offsetStart0 = start; } /* * All coordinates are in character space. * On input, (x1, y1) and (x2, y2) give line segment. * On output, (x, y) give offset vector. * We use a piecewise approximation to trig functions. * * TODO: Offset true perpendicular and proper length * supply the y-translation for hinting here, too, * that adds yOffset unconditionally to *y. */ static void cf2_glyphpath_computeOffset( CF2_GlyphPath glyphpath, CF2_Fixed x1, CF2_Fixed y1, CF2_Fixed x2, CF2_Fixed y2, CF2_Fixed* x, CF2_Fixed* y ) { CF2_Fixed dx = x2 - x1; CF2_Fixed dy = y2 - y1; /* note: negative offsets don't work here; negate deltas to change */ /* quadrants, below */ if ( glyphpath->font->reverseWinding ) { dx = -dx; dy = -dy; } *x = *y = 0; if ( !glyphpath->darken ) return; /* add momentum for this path element */ glyphpath->callbacks->windingMomentum += cf2_getWindingMomentum( x1, y1, x2, y2 ); /* note: allow mixed integer and fixed multiplication here */ if ( dx >= 0 ) { if ( dy >= 0 ) { /* first quadrant, +x +y */ if ( dx > 2 * dy ) { /* +x */ *x = 0; *y = 0; } else if ( dy > 2 * dx ) { /* +y */ *x = glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* +x +y */ *x = FT_MulFix( cf2_floatToFixed( 0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ), glyphpath->yOffset ); } } else { /* fourth quadrant, +x -y */ if ( dx > -2 * dy ) { /* +x */ *x = 0; *y = 0; } else if ( -dy > 2 * dx ) { /* -y */ *x = -glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* +x -y */ *x = FT_MulFix( cf2_floatToFixed( -0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ), glyphpath->yOffset ); } } } else { if ( dy >= 0 ) { /* second quadrant, -x +y */ if ( -dx > 2 * dy ) { /* -x */ *x = 0; *y = 2 * glyphpath->yOffset; } else if ( dy > -2 * dx ) { /* +y */ *x = glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* -x +y */ *x = FT_MulFix( cf2_floatToFixed( 0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ), glyphpath->yOffset ); } } else { /* third quadrant, -x -y */ if ( -dx > -2 * dy ) { /* -x */ *x = 0; *y = 2 * glyphpath->yOffset; } else if ( -dy > -2 * dx ) { /* -y */ *x = -glyphpath->xOffset; *y = glyphpath->xOffset; } else { /* -x -y */ *x = FT_MulFix( cf2_floatToFixed( -0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ), glyphpath->yOffset ); } } } } /* * The functions cf2_glyphpath_{moveTo,lineTo,curveTo,closeOpenPath} are * called by the interpreter with Character Space (CS) coordinates. Each * path element is placed into a queue of length one to await the * calculation of the following element. At that time, the darkening * offset of the following element is known and joins can be computed, * including possible modification of this element, before mapping to * Device Space (DS) and passing it on to the outline consumer. * */ FT_LOCAL_DEF( void ) cf2_glyphpath_moveTo( CF2_GlyphPath glyphpath, CF2_Fixed x, CF2_Fixed y ) { cf2_glyphpath_closeOpenPath( glyphpath ); /* save the parameters of the move for later, when we'll know how to */ /* offset it; */ /* also save last move point */ glyphpath->currentCS.x = glyphpath->start.x = x; glyphpath->currentCS.y = glyphpath->start.y = y; glyphpath->moveIsPending = TRUE; /* ensure we have a valid map with current mask */ if ( !cf2_hintmap_isValid( &glyphpath->hintMap ) || cf2_hintmask_isNew( glyphpath->hintMask ) ) cf2_hintmap_build( &glyphpath->hintMap, glyphpath->hStemHintArray, glyphpath->vStemHintArray, glyphpath->hintMask, glyphpath->hintOriginY, FALSE ); /* save a copy of current HintMap to use when drawing initial point */ glyphpath->firstHintMap = glyphpath->hintMap; /* structure copy */ } FT_LOCAL_DEF( void ) cf2_glyphpath_lineTo( CF2_GlyphPath glyphpath, CF2_Fixed x, CF2_Fixed y ) { CF2_Fixed xOffset, yOffset; FT_Vector P0, P1; FT_Bool newHintMap; /* * New hints will be applied after cf2_glyphpath_pushPrevElem has run. * In case this is a synthesized closing line, any new hints should be * delayed until this path is closed (`cf2_hintmask_isNew' will be * called again before the next line or curve). */ /* true if new hint map not on close */ newHintMap = cf2_hintmask_isNew( glyphpath->hintMask ) && !glyphpath->pathIsClosing; /* * Zero-length lines may occur in the charstring. Because we cannot * compute darkening offsets or intersections from zero-length lines, * it is best to remove them and avoid artifacts. However, zero-length * lines in CS at the start of a new hint map can generate non-zero * lines in DS due to hint substitution. We detect a change in hint * map here and pass those zero-length lines along. */ /* * Note: Find explicitly closed paths here with a conditional * breakpoint using * * !gp->pathIsClosing && gp->start.x == x && gp->start.y == y * */ if ( glyphpath->currentCS.x == x && glyphpath->currentCS.y == y && !newHintMap ) /* * Ignore zero-length lines in CS where the hint map is the same * because the line in DS will also be zero length. * * Ignore zero-length lines when we synthesize a closing line because * the close will be handled in cf2_glyphPath_pushPrevElem. */ return; cf2_glyphpath_computeOffset( glyphpath, glyphpath->currentCS.x, glyphpath->currentCS.y, x, y, &xOffset, &yOffset ); /* construct offset points */ P0.x = glyphpath->currentCS.x + xOffset; P0.y = glyphpath->currentCS.y + yOffset; P1.x = x + xOffset; P1.y = y + yOffset; if ( glyphpath->moveIsPending ) { /* emit offset 1st point as MoveTo */ cf2_glyphpath_pushMove( glyphpath, P0 ); glyphpath->moveIsPending = FALSE; /* adjust state machine */ glyphpath->pathIsOpen = TRUE; glyphpath->offsetStart1 = P1; /* record second point */ } if ( glyphpath->elemIsQueued ) { FT_ASSERT( cf2_hintmap_isValid( &glyphpath->hintMap ) ); cf2_glyphpath_pushPrevElem( glyphpath, &glyphpath->hintMap, &P0, P1, FALSE ); } /* queue the current element with offset points */ glyphpath->elemIsQueued = TRUE; glyphpath->prevElemOp = CF2_PathOpLineTo; glyphpath->prevElemP0 = P0; glyphpath->prevElemP1 = P1; /* update current map */ if ( newHintMap ) cf2_hintmap_build( &glyphpath->hintMap, glyphpath->hStemHintArray, glyphpath->vStemHintArray, glyphpath->hintMask, glyphpath->hintOriginY, FALSE ); glyphpath->currentCS.x = x; /* pre-offset current point */ glyphpath->currentCS.y = y; } FT_LOCAL_DEF( void ) cf2_glyphpath_curveTo( CF2_GlyphPath glyphpath, CF2_Fixed x1, CF2_Fixed y1, CF2_Fixed x2, CF2_Fixed y2, CF2_Fixed x3, CF2_Fixed y3 ) { CF2_Fixed xOffset1, yOffset1, xOffset3, yOffset3; FT_Vector P0, P1, P2, P3; /* TODO: ignore zero length portions of curve?? */ cf2_glyphpath_computeOffset( glyphpath, glyphpath->currentCS.x, glyphpath->currentCS.y, x1, y1, &xOffset1, &yOffset1 ); cf2_glyphpath_computeOffset( glyphpath, x2, y2, x3, y3, &xOffset3, &yOffset3 ); /* add momentum from the middle segment */ glyphpath->callbacks->windingMomentum += cf2_getWindingMomentum( x1, y1, x2, y2 ); /* construct offset points */ P0.x = glyphpath->currentCS.x + xOffset1; P0.y = glyphpath->currentCS.y + yOffset1; P1.x = x1 + xOffset1; P1.y = y1 + yOffset1; /* note: preserve angle of final segment by using offset3 at both ends */ P2.x = x2 + xOffset3; P2.y = y2 + yOffset3; P3.x = x3 + xOffset3; P3.y = y3 + yOffset3; if ( glyphpath->moveIsPending ) { /* emit offset 1st point as MoveTo */ cf2_glyphpath_pushMove( glyphpath, P0 ); glyphpath->moveIsPending = FALSE; glyphpath->pathIsOpen = TRUE; glyphpath->offsetStart1 = P1; /* record second point */ } if ( glyphpath->elemIsQueued ) { FT_ASSERT( cf2_hintmap_isValid( &glyphpath->hintMap ) ); cf2_glyphpath_pushPrevElem( glyphpath, &glyphpath->hintMap, &P0, P1, FALSE ); } /* queue the current element with offset points */ glyphpath->elemIsQueued = TRUE; glyphpath->prevElemOp = CF2_PathOpCubeTo; glyphpath->prevElemP0 = P0; glyphpath->prevElemP1 = P1; glyphpath->prevElemP2 = P2; glyphpath->prevElemP3 = P3; /* update current map */ if ( cf2_hintmask_isNew( glyphpath->hintMask ) ) cf2_hintmap_build( &glyphpath->hintMap, glyphpath->hStemHintArray, glyphpath->vStemHintArray, glyphpath->hintMask, glyphpath->hintOriginY, FALSE ); glyphpath->currentCS.x = x3; /* pre-offset current point */ glyphpath->currentCS.y = y3; } FT_LOCAL_DEF( void ) cf2_glyphpath_closeOpenPath( CF2_GlyphPath glyphpath ) { if ( glyphpath->pathIsOpen ) { /* * A closing line in Character Space line is always generated below * with `cf2_glyphPath_lineTo'. It may be ignored later if it turns * out to be zero length in Device Space. */ glyphpath->pathIsClosing = TRUE; cf2_glyphpath_lineTo( glyphpath, glyphpath->start.x, glyphpath->start.y ); /* empty the final element from the queue and close the path */ if ( glyphpath->elemIsQueued ) cf2_glyphpath_pushPrevElem( glyphpath, &glyphpath->hintMap, &glyphpath->offsetStart0, glyphpath->offsetStart1, TRUE ); /* reset state machine */ glyphpath->moveIsPending = TRUE; glyphpath->pathIsOpen = FALSE; glyphpath->pathIsClosing = FALSE; glyphpath->elemIsQueued = FALSE; } } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2hints.c
C
apache-2.0
62,997
/***************************************************************************/ /* */ /* cf2hints.h */ /* */ /* Adobe's code for handling CFF hints (body). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2HINTS_H__ #define __CF2HINTS_H__ FT_BEGIN_HEADER enum { CF2_MAX_HINTS = 96 /* maximum # of hints */ }; /* * A HintMask object stores a bit mask that specifies which hints in the * charstring are active at a given time. Hints in CFF must be declared * at the start, before any drawing operators, with horizontal hints * preceding vertical hints. The HintMask is ordered the same way, with * horizontal hints immediately followed by vertical hints. Clients are * responsible for knowing how many of each type are present. * * The maximum total number of hints is 96, as specified by the CFF * specification. * * A HintMask is built 0 or more times while interpreting a charstring, by * the HintMask operator. There is only one HintMask, but it is built or * rebuilt each time there is a hint substitution (HintMask operator) in * the charstring. A default HintMask with all bits set is built if there * has been no HintMask operator prior to the first drawing operator. * */ typedef struct CF2_HintMaskRec_ { FT_Error* error; FT_Bool isValid; FT_Bool isNew; size_t bitCount; size_t byteCount; FT_Byte mask[( CF2_MAX_HINTS + 7 ) / 8]; } CF2_HintMaskRec, *CF2_HintMask; typedef struct CF2_StemHintRec_ { FT_Bool used; /* DS positions are valid */ CF2_Fixed min; /* original character space value */ CF2_Fixed max; CF2_Fixed minDS; /* DS position after first use */ CF2_Fixed maxDS; } CF2_StemHintRec, *CF2_StemHint; /* * A HintMap object stores a piecewise linear function for mapping * y-coordinates from character space to device space, providing * appropriate pixel alignment to stem edges. * * The map is implemented as an array of `CF2_Hint' elements, each * representing an edge. When edges are paired, as from stem hints, the * bottom edge must immediately precede the top edge in the array. * Element character space AND device space positions must both increase * monotonically in the array. `CF2_Hint' elements are also used as * parameters to `cf2_blues_capture'. * * The `cf2_hintmap_build' method must be called before any drawing * operation (beginning with a Move operator) and at each hint * substitution (HintMask operator). * * The `cf2_hintmap_map' method is called to transform y-coordinates at * each drawing operation (move, line, curve). * */ /* TODO: make this a CF2_ArrStack and add a deep copy method */ enum { CF2_MAX_HINT_EDGES = CF2_MAX_HINTS * 2 }; typedef struct CF2_HintMapRec_ { CF2_Font font; /* initial map based on blue zones */ struct CF2_HintMapRec_* initialHintMap; /* working storage for 2nd pass adjustHints */ CF2_ArrStack hintMoves; FT_Bool isValid; FT_Bool hinted; CF2_Fixed scale; CF2_UInt count; /* start search from this index */ CF2_UInt lastIndex; CF2_HintRec edge[CF2_MAX_HINT_EDGES]; /* 192 */ } CF2_HintMapRec, *CF2_HintMap; FT_LOCAL( FT_Bool ) cf2_hint_isValid( const CF2_Hint hint ); FT_LOCAL( FT_Bool ) cf2_hint_isTop( const CF2_Hint hint ); FT_LOCAL( FT_Bool ) cf2_hint_isBottom( const CF2_Hint hint ); FT_LOCAL( void ) cf2_hint_lock( CF2_Hint hint ); FT_LOCAL( void ) cf2_hintmap_init( CF2_HintMap hintmap, CF2_Font font, CF2_HintMap initialMap, CF2_ArrStack hintMoves, CF2_Fixed scale ); FT_LOCAL( void ) cf2_hintmap_build( CF2_HintMap hintmap, CF2_ArrStack hStemHintArray, CF2_ArrStack vStemHintArray, CF2_HintMask hintMask, CF2_Fixed hintOrigin, FT_Bool initialMap ); /* * GlyphPath is a wrapper for drawing operations that scales the * coordinates according to the render matrix and HintMap. It also tracks * open paths to control ClosePath and to insert MoveTo for broken fonts. * */ typedef struct CF2_GlyphPathRec_ { /* TODO: gather some of these into a hinting context */ CF2_Font font; /* font instance */ CF2_OutlineCallbacks callbacks; /* outline consumer */ CF2_HintMapRec hintMap; /* current hint map */ CF2_HintMapRec firstHintMap; /* saved copy */ CF2_HintMapRec initialHintMap; /* based on all captured hints */ CF2_ArrStackRec hintMoves; /* list of hint moves for 2nd pass */ CF2_Fixed scaleX; /* matrix a */ CF2_Fixed scaleC; /* matrix c */ CF2_Fixed scaleY; /* matrix d */ FT_Vector fractionalTranslation; /* including deviceXScale */ #if 0 CF2_Fixed hShift; /* character space horizontal shift */ /* (for fauxing) */ #endif FT_Bool pathIsOpen; /* true after MoveTo */ FT_Bool pathIsClosing; /* true when synthesizing closepath line */ FT_Bool darken; /* true if stem darkening */ FT_Bool moveIsPending; /* true between MoveTo and offset MoveTo */ /* references used to call `cf2_hintmap_build', if necessary */ CF2_ArrStack hStemHintArray; CF2_ArrStack vStemHintArray; CF2_HintMask hintMask; /* ptr to the current mask */ CF2_Fixed hintOriginY; /* copy of current origin */ const CF2_BluesRec* blues; CF2_Fixed xOffset; /* character space offsets */ CF2_Fixed yOffset; /* character space miter limit threshold */ CF2_Fixed miterLimit; /* vertical/horzizontal snap distance in character space */ CF2_Fixed snapThreshold; FT_Vector offsetStart0; /* first and second points of first */ FT_Vector offsetStart1; /* element with offset applied */ /* current point, character space, before offset */ FT_Vector currentCS; /* current point, device space */ FT_Vector currentDS; /* start point of subpath, character space */ FT_Vector start; /* the following members constitute the `queue' of one element */ FT_Bool elemIsQueued; CF2_Int prevElemOp; FT_Vector prevElemP0; FT_Vector prevElemP1; FT_Vector prevElemP2; FT_Vector prevElemP3; } CF2_GlyphPathRec, *CF2_GlyphPath; FT_LOCAL( void ) cf2_glyphpath_init( CF2_GlyphPath glyphpath, CF2_Font font, CF2_OutlineCallbacks callbacks, CF2_Fixed scaleY, /* CF2_Fixed hShift, */ CF2_ArrStack hStemHintArray, CF2_ArrStack vStemHintArray, CF2_HintMask hintMask, CF2_Fixed hintOrigin, const CF2_Blues blues, const FT_Vector* fractionalTranslation ); FT_LOCAL( void ) cf2_glyphpath_finalize( CF2_GlyphPath glyphpath ); FT_LOCAL( void ) cf2_glyphpath_moveTo( CF2_GlyphPath glyphpath, CF2_Fixed x, CF2_Fixed y ); FT_LOCAL( void ) cf2_glyphpath_lineTo( CF2_GlyphPath glyphpath, CF2_Fixed x, CF2_Fixed y ); FT_LOCAL( void ) cf2_glyphpath_curveTo( CF2_GlyphPath glyphpath, CF2_Fixed x1, CF2_Fixed y1, CF2_Fixed x2, CF2_Fixed y2, CF2_Fixed x3, CF2_Fixed y3 ); FT_LOCAL( void ) cf2_glyphpath_closeOpenPath( CF2_GlyphPath glyphpath ); FT_END_HEADER #endif /* __CF2HINTS_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2hints.h
C
apache-2.0
10,806
/***************************************************************************/ /* */ /* cf2intrp.c */ /* */ /* Adobe's CFF Interpreter (body). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2glue.h" #include "cf2font.h" #include "cf2stack.h" #include "cf2hints.h" #include "cf2error.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cf2interp /* some operators are not implemented yet */ #define CF2_FIXME FT_TRACE4(( "cf2_interpT2CharString:" \ " operator not implemented yet\n" )) FT_LOCAL_DEF( void ) cf2_hintmask_init( CF2_HintMask hintmask, FT_Error* error ) { FT_ZERO( hintmask ); hintmask->error = error; } FT_LOCAL_DEF( FT_Bool ) cf2_hintmask_isValid( const CF2_HintMask hintmask ) { return hintmask->isValid; } FT_LOCAL_DEF( FT_Bool ) cf2_hintmask_isNew( const CF2_HintMask hintmask ) { return hintmask->isNew; } FT_LOCAL_DEF( void ) cf2_hintmask_setNew( CF2_HintMask hintmask, FT_Bool val ) { hintmask->isNew = val; } /* clients call `getMaskPtr' in order to iterate */ /* through hint mask */ FT_LOCAL_DEF( FT_Byte* ) cf2_hintmask_getMaskPtr( CF2_HintMask hintmask ) { return hintmask->mask; } static size_t cf2_hintmask_setCounts( CF2_HintMask hintmask, size_t bitCount ) { if ( bitCount > CF2_MAX_HINTS ) { /* total of h and v stems must be <= 96 */ CF2_SET_ERROR( hintmask->error, Invalid_Glyph_Format ); return 0; } hintmask->bitCount = bitCount; hintmask->byteCount = ( hintmask->bitCount + 7 ) / 8; hintmask->isValid = TRUE; hintmask->isNew = TRUE; return bitCount; } /* consume the hintmask bytes from the charstring, advancing the src */ /* pointer */ static void cf2_hintmask_read( CF2_HintMask hintmask, CF2_Buffer charstring, size_t bitCount ) { size_t i; #ifndef CF2_NDEBUG /* these are the bits in the final mask byte that should be zero */ /* Note: this variable is only used in an assert expression below */ /* and then only if CF2_NDEBUG is not defined */ CF2_UInt mask = ( 1 << ( -(CF2_Int)bitCount & 7 ) ) - 1; #endif /* initialize counts and isValid */ if ( cf2_hintmask_setCounts( hintmask, bitCount ) == 0 ) return; FT_ASSERT( hintmask->byteCount > 0 ); FT_TRACE4(( " (maskbytes:" )); /* set mask and advance interpreter's charstring pointer */ for ( i = 0; i < hintmask->byteCount; i++ ) { hintmask->mask[i] = (FT_Byte)cf2_buf_readByte( charstring ); FT_TRACE4(( " 0x%02X", hintmask->mask[i] )); } FT_TRACE4(( ")\n" )); /* assert any unused bits in last byte are zero unless there's a prior */ /* error */ /* bitCount -> mask, 0 -> 0, 1 -> 7f, 2 -> 3f, ... 6 -> 3, 7 -> 1 */ #ifndef CF2_NDEBUG FT_ASSERT( ( hintmask->mask[hintmask->byteCount - 1] & mask ) == 0 || *hintmask->error ); #endif } FT_LOCAL_DEF( void ) cf2_hintmask_setAll( CF2_HintMask hintmask, size_t bitCount ) { size_t i; CF2_UInt mask = ( 1 << ( -(CF2_Int)bitCount & 7 ) ) - 1; /* initialize counts and isValid */ if ( cf2_hintmask_setCounts( hintmask, bitCount ) == 0 ) return; FT_ASSERT( hintmask->byteCount > 0 ); FT_ASSERT( hintmask->byteCount < sizeof ( hintmask->mask ) / sizeof ( hintmask->mask[0] ) ); /* set mask to all ones */ for ( i = 0; i < hintmask->byteCount; i++ ) hintmask->mask[i] = 0xFF; /* clear unused bits */ /* bitCount -> mask, 0 -> 0, 1 -> 7f, 2 -> 3f, ... 6 -> 3, 7 -> 1 */ hintmask->mask[hintmask->byteCount - 1] &= ~mask; } /* Type2 charstring opcodes */ enum { cf2_cmdRESERVED_0, /* 0 */ cf2_cmdHSTEM, /* 1 */ cf2_cmdRESERVED_2, /* 2 */ cf2_cmdVSTEM, /* 3 */ cf2_cmdVMOVETO, /* 4 */ cf2_cmdRLINETO, /* 5 */ cf2_cmdHLINETO, /* 6 */ cf2_cmdVLINETO, /* 7 */ cf2_cmdRRCURVETO, /* 8 */ cf2_cmdRESERVED_9, /* 9 */ cf2_cmdCALLSUBR, /* 10 */ cf2_cmdRETURN, /* 11 */ cf2_cmdESC, /* 12 */ cf2_cmdRESERVED_13, /* 13 */ cf2_cmdENDCHAR, /* 14 */ cf2_cmdRESERVED_15, /* 15 */ cf2_cmdRESERVED_16, /* 16 */ cf2_cmdRESERVED_17, /* 17 */ cf2_cmdHSTEMHM, /* 18 */ cf2_cmdHINTMASK, /* 19 */ cf2_cmdCNTRMASK, /* 20 */ cf2_cmdRMOVETO, /* 21 */ cf2_cmdHMOVETO, /* 22 */ cf2_cmdVSTEMHM, /* 23 */ cf2_cmdRCURVELINE, /* 24 */ cf2_cmdRLINECURVE, /* 25 */ cf2_cmdVVCURVETO, /* 26 */ cf2_cmdHHCURVETO, /* 27 */ cf2_cmdEXTENDEDNMBR, /* 28 */ cf2_cmdCALLGSUBR, /* 29 */ cf2_cmdVHCURVETO, /* 30 */ cf2_cmdHVCURVETO /* 31 */ }; enum { cf2_escDOTSECTION, /* 0 */ cf2_escRESERVED_1, /* 1 */ cf2_escRESERVED_2, /* 2 */ cf2_escAND, /* 3 */ cf2_escOR, /* 4 */ cf2_escNOT, /* 5 */ cf2_escRESERVED_6, /* 6 */ cf2_escRESERVED_7, /* 7 */ cf2_escRESERVED_8, /* 8 */ cf2_escABS, /* 9 */ cf2_escADD, /* 10 like otherADD */ cf2_escSUB, /* 11 like otherSUB */ cf2_escDIV, /* 12 */ cf2_escRESERVED_13, /* 13 */ cf2_escNEG, /* 14 */ cf2_escEQ, /* 15 */ cf2_escRESERVED_16, /* 16 */ cf2_escRESERVED_17, /* 17 */ cf2_escDROP, /* 18 */ cf2_escRESERVED_19, /* 19 */ cf2_escPUT, /* 20 like otherPUT */ cf2_escGET, /* 21 like otherGET */ cf2_escIFELSE, /* 22 like otherIFELSE */ cf2_escRANDOM, /* 23 like otherRANDOM */ cf2_escMUL, /* 24 like otherMUL */ cf2_escRESERVED_25, /* 25 */ cf2_escSQRT, /* 26 */ cf2_escDUP, /* 27 like otherDUP */ cf2_escEXCH, /* 28 like otherEXCH */ cf2_escINDEX, /* 29 */ cf2_escROLL, /* 30 */ cf2_escRESERVED_31, /* 31 */ cf2_escRESERVED_32, /* 32 */ cf2_escRESERVED_33, /* 33 */ cf2_escHFLEX, /* 34 */ cf2_escFLEX, /* 35 */ cf2_escHFLEX1, /* 36 */ cf2_escFLEX1 /* 37 */ }; /* `stemHintArray' does not change once we start drawing the outline. */ static void cf2_doStems( const CF2_Font font, CF2_Stack opStack, CF2_ArrStack stemHintArray, CF2_Fixed* width, FT_Bool* haveWidth, CF2_Fixed hintOffset ) { CF2_UInt i; CF2_UInt count = cf2_stack_count( opStack ); FT_Bool hasWidthArg = (FT_Bool)( count & 1 ); /* variable accumulates delta values from operand stack */ CF2_Fixed position = hintOffset; if ( hasWidthArg && ! *haveWidth ) *width = cf2_stack_getReal( opStack, 0 ) + cf2_getNominalWidthX( font->decoder ); if ( font->decoder->width_only ) goto exit; for ( i = hasWidthArg ? 1 : 0; i < count; i += 2 ) { /* construct a CF2_StemHint and push it onto the list */ CF2_StemHintRec stemhint; stemhint.min = position += cf2_stack_getReal( opStack, i ); stemhint.max = position += cf2_stack_getReal( opStack, i + 1 ); stemhint.used = FALSE; stemhint.maxDS = stemhint.minDS = 0; cf2_arrstack_push( stemHintArray, &stemhint ); /* defer error check */ } cf2_stack_clear( opStack ); exit: /* cf2_doStems must define a width (may be default) */ *haveWidth = TRUE; } static void cf2_doFlex( CF2_Stack opStack, CF2_Fixed* curX, CF2_Fixed* curY, CF2_GlyphPath glyphPath, const FT_Bool* readFromStack, FT_Bool doConditionalLastRead ) { CF2_Fixed vals[14]; CF2_UInt index; FT_Bool isHFlex; CF2_Int top, i, j; vals[0] = *curX; vals[1] = *curY; index = 0; isHFlex = readFromStack[9] == FALSE; top = isHFlex ? 9 : 10; for ( i = 0; i < top; i++ ) { vals[i + 2] = vals[i]; if ( readFromStack[i] ) vals[i + 2] += cf2_stack_getReal( opStack, index++ ); } if ( isHFlex ) vals[9 + 2] = *curY; if ( doConditionalLastRead ) { FT_Bool lastIsX = (FT_Bool)( cf2_fixedAbs( vals[10] - *curX ) > cf2_fixedAbs( vals[11] - *curY ) ); CF2_Fixed lastVal = cf2_stack_getReal( opStack, index ); if ( lastIsX ) { vals[12] = vals[10] + lastVal; vals[13] = *curY; } else { vals[12] = *curX; vals[13] = vals[11] + lastVal; } } else { if ( readFromStack[10] ) vals[12] = vals[10] + cf2_stack_getReal( opStack, index++ ); else vals[12] = *curX; if ( readFromStack[11] ) vals[13] = vals[11] + cf2_stack_getReal( opStack, index ); else vals[13] = *curY; } for ( j = 0; j < 2; j++ ) cf2_glyphpath_curveTo( glyphPath, vals[j * 6 + 2], vals[j * 6 + 3], vals[j * 6 + 4], vals[j * 6 + 5], vals[j * 6 + 6], vals[j * 6 + 7] ); cf2_stack_clear( opStack ); *curX = vals[12]; *curY = vals[13]; } /* * `error' is a shared error code used by many objects in this * routine. Before the code continues from an error, it must check and * record the error in `*error'. The idea is that this shared * error code will record the first error encountered. If testing * for an error anyway, the cost of `goto exit' is small, so we do it, * even if continuing would be safe. In this case, `lastError' is * set, so the testing and storing can be done in one place, at `exit'. * * Continuing after an error is intended for objects which do their own * testing of `*error', e.g., array stack functions. This allows us to * avoid an extra test after the call. * * Unimplemented opcodes are ignored. * */ FT_LOCAL_DEF( void ) cf2_interpT2CharString( CF2_Font font, CF2_Buffer buf, CF2_OutlineCallbacks callbacks, const FT_Vector* translation, FT_Bool doingSeac, CF2_Fixed curX, CF2_Fixed curY, CF2_Fixed* width ) { /* lastError is used for errors that are immediately tested */ FT_Error lastError = FT_Err_Ok; /* pointer to parsed font object */ CFF_Decoder* decoder = font->decoder; FT_Error* error = &font->error; FT_Memory memory = font->memory; CF2_Fixed scaleY = font->innerTransform.d; CF2_Fixed nominalWidthX = cf2_getNominalWidthX( decoder ); /* save this for hinting seac accents */ CF2_Fixed hintOriginY = curY; CF2_Stack opStack = NULL; FT_Byte op1; /* first opcode byte */ /* instruction limit; 20,000,000 matches Avalon */ FT_UInt32 instructionLimit = 20000000UL; CF2_ArrStackRec subrStack; FT_Bool haveWidth; CF2_Buffer charstring = NULL; CF2_Int charstringIndex = -1; /* initialize to empty */ /* TODO: placeholders for hint structures */ /* objects used for hinting */ CF2_ArrStackRec hStemHintArray; CF2_ArrStackRec vStemHintArray; CF2_HintMaskRec hintMask; CF2_GlyphPathRec glyphPath; /* initialize the remaining objects */ cf2_arrstack_init( &subrStack, memory, error, sizeof ( CF2_BufferRec ) ); cf2_arrstack_init( &hStemHintArray, memory, error, sizeof ( CF2_StemHintRec ) ); cf2_arrstack_init( &vStemHintArray, memory, error, sizeof ( CF2_StemHintRec ) ); /* initialize CF2_StemHint arrays */ cf2_hintmask_init( &hintMask, error ); /* initialize path map to manage drawing operations */ /* Note: last 4 params are used to handle `MoveToPermissive', which */ /* may need to call `hintMap.Build' */ /* TODO: MoveToPermissive is gone; are these still needed? */ cf2_glyphpath_init( &glyphPath, font, callbacks, scaleY, /* hShift, */ &hStemHintArray, &vStemHintArray, &hintMask, hintOriginY, &font->blues, translation ); /* * Initialize state for width parsing. From the CFF Spec: * * The first stack-clearing operator, which must be one of hstem, * hstemhm, vstem, vstemhm, cntrmask, hintmask, hmoveto, vmoveto, * rmoveto, or endchar, takes an additional argument - the width (as * described earlier), which may be expressed as zero or one numeric * argument. * * What we implement here uses the first validly specified width, but * does not detect errors for specifying more than one width. * * If one of the above operators occurs without explicitly specifying * a width, we assume the default width. * */ haveWidth = FALSE; *width = cf2_getDefaultWidthX( decoder ); /* * Note: at this point, all pointers to resources must be NULL * and all local objects must be initialized. * There must be no branches to exit: above this point. * */ /* allocate an operand stack */ opStack = cf2_stack_init( memory, error ); if ( !opStack ) { lastError = FT_THROW( Out_Of_Memory ); goto exit; } /* initialize subroutine stack by placing top level charstring as */ /* first element (max depth plus one for the charstring) */ /* Note: Caller owns and must finalize the first charstring. */ /* Our copy of it does not change that requirement. */ cf2_arrstack_setCount( &subrStack, CF2_MAX_SUBR + 1 ); charstring = (CF2_Buffer)cf2_arrstack_getBuffer( &subrStack ); *charstring = *buf; /* structure copy */ charstringIndex = 0; /* entry is valid now */ /* catch errors so far */ if ( *error ) goto exit; /* main interpreter loop */ while ( 1 ) { if ( cf2_buf_isEnd( charstring ) ) { /* If we've reached the end of the charstring, simulate a */ /* cf2_cmdRETURN or cf2_cmdENDCHAR. */ if ( charstringIndex ) op1 = cf2_cmdRETURN; /* end of buffer for subroutine */ else op1 = cf2_cmdENDCHAR; /* end of buffer for top level charstring */ } else op1 = (FT_Byte)cf2_buf_readByte( charstring ); /* check for errors once per loop */ if ( *error ) goto exit; instructionLimit--; if ( instructionLimit == 0 ) { lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; } switch( op1 ) { case cf2_cmdRESERVED_0: case cf2_cmdRESERVED_2: case cf2_cmdRESERVED_9: case cf2_cmdRESERVED_13: case cf2_cmdRESERVED_15: case cf2_cmdRESERVED_16: case cf2_cmdRESERVED_17: /* we may get here if we have a prior error */ FT_TRACE4(( " unknown op (%d)\n", op1 )); break; case cf2_cmdHSTEMHM: case cf2_cmdHSTEM: FT_TRACE4(( op1 == cf2_cmdHSTEMHM ? " hstemhm\n" : " hstem\n" )); /* never add hints after the mask is computed */ if ( cf2_hintmask_isValid( &hintMask ) ) FT_TRACE4(( "cf2_interpT2CharString:" " invalid horizontal hint mask\n" )); cf2_doStems( font, opStack, &hStemHintArray, width, &haveWidth, 0 ); if ( font->decoder->width_only ) goto exit; break; case cf2_cmdVSTEMHM: case cf2_cmdVSTEM: FT_TRACE4(( op1 == cf2_cmdVSTEMHM ? " vstemhm\n" : " vstem\n" )); /* never add hints after the mask is computed */ if ( cf2_hintmask_isValid( &hintMask ) ) FT_TRACE4(( "cf2_interpT2CharString:" " invalid vertical hint mask\n" )); cf2_doStems( font, opStack, &vStemHintArray, width, &haveWidth, 0 ); if ( font->decoder->width_only ) goto exit; break; case cf2_cmdVMOVETO: FT_TRACE4(( " vmoveto\n" )); if ( cf2_stack_count( opStack ) > 1 && !haveWidth ) *width = cf2_stack_getReal( opStack, 0 ) + nominalWidthX; /* width is defined or default after this */ haveWidth = TRUE; if ( font->decoder->width_only ) goto exit; curY += cf2_stack_popFixed( opStack ); cf2_glyphpath_moveTo( &glyphPath, curX, curY ); break; case cf2_cmdRLINETO: { CF2_UInt index; CF2_UInt count = cf2_stack_count( opStack ); FT_TRACE4(( " rlineto\n" )); for ( index = 0; index < count; index += 2 ) { curX += cf2_stack_getReal( opStack, index + 0 ); curY += cf2_stack_getReal( opStack, index + 1 ); cf2_glyphpath_lineTo( &glyphPath, curX, curY ); } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdHLINETO: case cf2_cmdVLINETO: { CF2_UInt index; CF2_UInt count = cf2_stack_count( opStack ); FT_Bool isX = op1 == cf2_cmdHLINETO; FT_TRACE4(( isX ? " hlineto\n" : " vlineto\n" )); for ( index = 0; index < count; index++ ) { CF2_Fixed v = cf2_stack_getReal( opStack, index ); if ( isX ) curX += v; else curY += v; isX = !isX; cf2_glyphpath_lineTo( &glyphPath, curX, curY ); } cf2_stack_clear( opStack ); } continue; case cf2_cmdRCURVELINE: case cf2_cmdRRCURVETO: { CF2_UInt count = cf2_stack_count( opStack ); CF2_UInt index = 0; FT_TRACE4(( op1 == cf2_cmdRCURVELINE ? " rcurveline\n" : " rrcurveto\n" )); while ( index + 6 <= count ) { CF2_Fixed x1 = cf2_stack_getReal( opStack, index + 0 ) + curX; CF2_Fixed y1 = cf2_stack_getReal( opStack, index + 1 ) + curY; CF2_Fixed x2 = cf2_stack_getReal( opStack, index + 2 ) + x1; CF2_Fixed y2 = cf2_stack_getReal( opStack, index + 3 ) + y1; CF2_Fixed x3 = cf2_stack_getReal( opStack, index + 4 ) + x2; CF2_Fixed y3 = cf2_stack_getReal( opStack, index + 5 ) + y2; cf2_glyphpath_curveTo( &glyphPath, x1, y1, x2, y2, x3, y3 ); curX = x3; curY = y3; index += 6; } if ( op1 == cf2_cmdRCURVELINE ) { curX += cf2_stack_getReal( opStack, index + 0 ); curY += cf2_stack_getReal( opStack, index + 1 ); cf2_glyphpath_lineTo( &glyphPath, curX, curY ); } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdCALLGSUBR: case cf2_cmdCALLSUBR: { CF2_UInt subrIndex; FT_TRACE4(( op1 == cf2_cmdCALLGSUBR ? " callgsubr" : " callsubr" )); if ( charstringIndex > CF2_MAX_SUBR ) { /* max subr plus one for charstring */ lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; /* overflow of stack */ } /* push our current CFF charstring region on subrStack */ charstring = (CF2_Buffer) cf2_arrstack_getPointer( &subrStack, charstringIndex + 1 ); /* set up the new CFF region and pointer */ subrIndex = cf2_stack_popInt( opStack ); switch ( op1 ) { case cf2_cmdCALLGSUBR: FT_TRACE4(( "(%d)\n", subrIndex + decoder->globals_bias )); if ( cf2_initGlobalRegionBuffer( decoder, subrIndex, charstring ) ) { lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; /* subroutine lookup or stream error */ } break; default: /* cf2_cmdCALLSUBR */ FT_TRACE4(( "(%d)\n", subrIndex + decoder->locals_bias )); if ( cf2_initLocalRegionBuffer( decoder, subrIndex, charstring ) ) { lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; /* subroutine lookup or stream error */ } } charstringIndex += 1; /* entry is valid now */ } continue; /* do not clear the stack */ case cf2_cmdRETURN: FT_TRACE4(( " return\n" )); if ( charstringIndex < 1 ) { /* Note: cannot return from top charstring */ lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; /* underflow of stack */ } /* restore position in previous charstring */ charstring = (CF2_Buffer) cf2_arrstack_getPointer( &subrStack, --charstringIndex ); continue; /* do not clear the stack */ case cf2_cmdESC: { FT_Byte op2 = (FT_Byte)cf2_buf_readByte( charstring ); switch ( op2 ) { case cf2_escDOTSECTION: /* something about `flip type of locking' -- ignore it */ FT_TRACE4(( " dotsection\n" )); break; /* TODO: should these operators be supported? */ case cf2_escAND: /* in spec */ FT_TRACE4(( " and\n" )); CF2_FIXME; break; case cf2_escOR: /* in spec */ FT_TRACE4(( " or\n" )); CF2_FIXME; break; case cf2_escNOT: /* in spec */ FT_TRACE4(( " not\n" )); CF2_FIXME; break; case cf2_escABS: /* in spec */ FT_TRACE4(( " abs\n" )); CF2_FIXME; break; case cf2_escADD: /* in spec */ FT_TRACE4(( " add\n" )); CF2_FIXME; break; case cf2_escSUB: /* in spec */ FT_TRACE4(( " sub\n" )); CF2_FIXME; break; case cf2_escDIV: /* in spec */ FT_TRACE4(( " div\n" )); CF2_FIXME; break; case cf2_escNEG: /* in spec */ FT_TRACE4(( " neg\n" )); CF2_FIXME; break; case cf2_escEQ: /* in spec */ FT_TRACE4(( " eq\n" )); CF2_FIXME; break; case cf2_escDROP: /* in spec */ FT_TRACE4(( " drop\n" )); CF2_FIXME; break; case cf2_escPUT: /* in spec */ FT_TRACE4(( " put\n" )); CF2_FIXME; break; case cf2_escGET: /* in spec */ FT_TRACE4(( " get\n" )); CF2_FIXME; break; case cf2_escIFELSE: /* in spec */ FT_TRACE4(( " ifelse\n" )); CF2_FIXME; break; case cf2_escRANDOM: /* in spec */ FT_TRACE4(( " random\n" )); CF2_FIXME; break; case cf2_escMUL: /* in spec */ FT_TRACE4(( " mul\n" )); CF2_FIXME; break; case cf2_escSQRT: /* in spec */ FT_TRACE4(( " sqrt\n" )); CF2_FIXME; break; case cf2_escDUP: /* in spec */ FT_TRACE4(( " dup\n" )); CF2_FIXME; break; case cf2_escEXCH: /* in spec */ FT_TRACE4(( " exch\n" )); CF2_FIXME; break; case cf2_escINDEX: /* in spec */ FT_TRACE4(( " index\n" )); CF2_FIXME; break; case cf2_escROLL: /* in spec */ FT_TRACE4(( " roll\n" )); CF2_FIXME; break; case cf2_escHFLEX: { static const FT_Bool readFromStack[12] = { TRUE /* dx1 */, FALSE /* dy1 */, TRUE /* dx2 */, TRUE /* dy2 */, TRUE /* dx3 */, FALSE /* dy3 */, TRUE /* dx4 */, FALSE /* dy4 */, TRUE /* dx5 */, FALSE /* dy5 */, TRUE /* dx6 */, FALSE /* dy6 */ }; FT_TRACE4(( " hflex\n" )); cf2_doFlex( opStack, &curX, &curY, &glyphPath, readFromStack, FALSE /* doConditionalLastRead */ ); } continue; case cf2_escFLEX: { static const FT_Bool readFromStack[12] = { TRUE /* dx1 */, TRUE /* dy1 */, TRUE /* dx2 */, TRUE /* dy2 */, TRUE /* dx3 */, TRUE /* dy3 */, TRUE /* dx4 */, TRUE /* dy4 */, TRUE /* dx5 */, TRUE /* dy5 */, TRUE /* dx6 */, TRUE /* dy6 */ }; FT_TRACE4(( " flex\n" )); cf2_doFlex( opStack, &curX, &curY, &glyphPath, readFromStack, FALSE /* doConditionalLastRead */ ); } break; /* TODO: why is this not a continue? */ case cf2_escHFLEX1: { static const FT_Bool readFromStack[12] = { TRUE /* dx1 */, TRUE /* dy1 */, TRUE /* dx2 */, TRUE /* dy2 */, TRUE /* dx3 */, FALSE /* dy3 */, TRUE /* dx4 */, FALSE /* dy4 */, TRUE /* dx5 */, TRUE /* dy5 */, TRUE /* dx6 */, FALSE /* dy6 */ }; FT_TRACE4(( " hflex1\n" )); cf2_doFlex( opStack, &curX, &curY, &glyphPath, readFromStack, FALSE /* doConditionalLastRead */ ); } continue; case cf2_escFLEX1: { static const FT_Bool readFromStack[12] = { TRUE /* dx1 */, TRUE /* dy1 */, TRUE /* dx2 */, TRUE /* dy2 */, TRUE /* dx3 */, TRUE /* dy3 */, TRUE /* dx4 */, TRUE /* dy4 */, TRUE /* dx5 */, TRUE /* dy5 */, FALSE /* dx6 */, FALSE /* dy6 */ }; FT_TRACE4(( " flex1\n" )); cf2_doFlex( opStack, &curX, &curY, &glyphPath, readFromStack, TRUE /* doConditionalLastRead */ ); } continue; case cf2_escRESERVED_1: case cf2_escRESERVED_2: case cf2_escRESERVED_6: case cf2_escRESERVED_7: case cf2_escRESERVED_8: case cf2_escRESERVED_13: case cf2_escRESERVED_16: case cf2_escRESERVED_17: case cf2_escRESERVED_19: case cf2_escRESERVED_25: case cf2_escRESERVED_31: case cf2_escRESERVED_32: case cf2_escRESERVED_33: default: FT_TRACE4(( " unknown op (12, %d)\n", op2 )); }; /* end of switch statement checking `op2' */ } /* case cf2_cmdESC */ break; case cf2_cmdENDCHAR: FT_TRACE4(( " endchar\n" )); if ( cf2_stack_count( opStack ) == 1 || cf2_stack_count( opStack ) == 5 ) { if ( !haveWidth ) *width = cf2_stack_getReal( opStack, 0 ) + nominalWidthX; } /* width is defined or default after this */ haveWidth = TRUE; if ( font->decoder->width_only ) goto exit; /* close path if still open */ cf2_glyphpath_closeOpenPath( &glyphPath ); if ( cf2_stack_count( opStack ) > 1 ) { /* must be either 4 or 5 -- */ /* this is a (deprecated) implied `seac' operator */ CF2_UInt achar; CF2_UInt bchar; CF2_BufferRec component; CF2_Fixed dummyWidth; /* ignore component width */ FT_Error error2; if ( doingSeac ) { lastError = FT_THROW( Invalid_Glyph_Format ); goto exit; /* nested seac */ } achar = cf2_stack_popInt( opStack ); bchar = cf2_stack_popInt( opStack ); curY = cf2_stack_popFixed( opStack ); curX = cf2_stack_popFixed( opStack ); error2 = cf2_getSeacComponent( decoder, achar, &component ); if ( error2 ) { lastError = error2; /* pass FreeType error through */ goto exit; } cf2_interpT2CharString( font, &component, callbacks, translation, TRUE, curX, curY, &dummyWidth ); cf2_freeSeacComponent( decoder, &component ); error2 = cf2_getSeacComponent( decoder, bchar, &component ); if ( error2 ) { lastError = error2; /* pass FreeType error through */ goto exit; } cf2_interpT2CharString( font, &component, callbacks, translation, TRUE, 0, 0, &dummyWidth ); cf2_freeSeacComponent( decoder, &component ); } goto exit; case cf2_cmdCNTRMASK: case cf2_cmdHINTMASK: /* the final \n in the tracing message gets added in */ /* `cf2_hintmask_read' (which also traces the mask bytes) */ FT_TRACE4(( op1 == cf2_cmdCNTRMASK ? " cntrmask" : " hintmask" )); /* if there are arguments on the stack, there this is an */ /* implied cf2_cmdVSTEMHM */ if ( cf2_stack_count( opStack ) != 0 ) { /* never add hints after the mask is computed */ if ( cf2_hintmask_isValid( &hintMask ) ) FT_TRACE4(( "cf2_interpT2CharString: invalid hint mask\n" )); } cf2_doStems( font, opStack, &vStemHintArray, width, &haveWidth, 0 ); if ( font->decoder->width_only ) goto exit; if ( op1 == cf2_cmdHINTMASK ) { /* consume the hint mask bytes which follow the operator */ cf2_hintmask_read( &hintMask, charstring, cf2_arrstack_size( &hStemHintArray ) + cf2_arrstack_size( &vStemHintArray ) ); } else { /* * Consume the counter mask bytes which follow the operator: * Build a temporary hint map, just to place and lock those * stems participating in the counter mask. These are most * likely the dominant hstems, and are grouped together in a * few counter groups, not necessarily in correspondence * with the hint groups. This reduces the chances of * conflicts between hstems that are initially placed in * separate hint groups and then brought together. The * positions are copied back to `hStemHintArray', so we can * discard `counterMask' and `counterHintMap'. * */ CF2_HintMapRec counterHintMap; CF2_HintMaskRec counterMask; cf2_hintmap_init( &counterHintMap, font, &glyphPath.initialHintMap, &glyphPath.hintMoves, scaleY ); cf2_hintmask_init( &counterMask, error ); cf2_hintmask_read( &counterMask, charstring, cf2_arrstack_size( &hStemHintArray ) + cf2_arrstack_size( &vStemHintArray ) ); cf2_hintmap_build( &counterHintMap, &hStemHintArray, &vStemHintArray, &counterMask, 0, FALSE ); } break; case cf2_cmdRMOVETO: FT_TRACE4(( " rmoveto\n" )); if ( cf2_stack_count( opStack ) > 2 && !haveWidth ) *width = cf2_stack_getReal( opStack, 0 ) + nominalWidthX; /* width is defined or default after this */ haveWidth = TRUE; if ( font->decoder->width_only ) goto exit; curY += cf2_stack_popFixed( opStack ); curX += cf2_stack_popFixed( opStack ); cf2_glyphpath_moveTo( &glyphPath, curX, curY ); break; case cf2_cmdHMOVETO: FT_TRACE4(( " hmoveto\n" )); if ( cf2_stack_count( opStack ) > 1 && !haveWidth ) *width = cf2_stack_getReal( opStack, 0 ) + nominalWidthX; /* width is defined or default after this */ haveWidth = TRUE; if ( font->decoder->width_only ) goto exit; curX += cf2_stack_popFixed( opStack ); cf2_glyphpath_moveTo( &glyphPath, curX, curY ); break; case cf2_cmdRLINECURVE: { CF2_UInt count = cf2_stack_count( opStack ); CF2_UInt index = 0; FT_TRACE4(( " rlinecurve\n" )); while ( index + 6 < count ) { curX += cf2_stack_getReal( opStack, index + 0 ); curY += cf2_stack_getReal( opStack, index + 1 ); cf2_glyphpath_lineTo( &glyphPath, curX, curY ); index += 2; } while ( index < count ) { CF2_Fixed x1 = cf2_stack_getReal( opStack, index + 0 ) + curX; CF2_Fixed y1 = cf2_stack_getReal( opStack, index + 1 ) + curY; CF2_Fixed x2 = cf2_stack_getReal( opStack, index + 2 ) + x1; CF2_Fixed y2 = cf2_stack_getReal( opStack, index + 3 ) + y1; CF2_Fixed x3 = cf2_stack_getReal( opStack, index + 4 ) + x2; CF2_Fixed y3 = cf2_stack_getReal( opStack, index + 5 ) + y2; cf2_glyphpath_curveTo( &glyphPath, x1, y1, x2, y2, x3, y3 ); curX = x3; curY = y3; index += 6; } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdVVCURVETO: { CF2_UInt count = cf2_stack_count( opStack ); CF2_UInt index = 0; FT_TRACE4(( " vvcurveto\n" )); while ( index < count ) { CF2_Fixed x1, y1, x2, y2, x3, y3; if ( ( count - index ) & 1 ) { x1 = cf2_stack_getReal( opStack, index ) + curX; ++index; } else x1 = curX; y1 = cf2_stack_getReal( opStack, index + 0 ) + curY; x2 = cf2_stack_getReal( opStack, index + 1 ) + x1; y2 = cf2_stack_getReal( opStack, index + 2 ) + y1; x3 = x2; y3 = cf2_stack_getReal( opStack, index + 3 ) + y2; cf2_glyphpath_curveTo( &glyphPath, x1, y1, x2, y2, x3, y3 ); curX = x3; curY = y3; index += 4; } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdHHCURVETO: { CF2_UInt count = cf2_stack_count( opStack ); CF2_UInt index = 0; FT_TRACE4(( " hhcurveto\n" )); while ( index < count ) { CF2_Fixed x1, y1, x2, y2, x3, y3; if ( ( count - index ) & 1 ) { y1 = cf2_stack_getReal( opStack, index ) + curY; ++index; } else y1 = curY; x1 = cf2_stack_getReal( opStack, index + 0 ) + curX; x2 = cf2_stack_getReal( opStack, index + 1 ) + x1; y2 = cf2_stack_getReal( opStack, index + 2 ) + y1; x3 = cf2_stack_getReal( opStack, index + 3 ) + x2; y3 = y2; cf2_glyphpath_curveTo( &glyphPath, x1, y1, x2, y2, x3, y3 ); curX = x3; curY = y3; index += 4; } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdVHCURVETO: case cf2_cmdHVCURVETO: { CF2_UInt count = cf2_stack_count( opStack ); CF2_UInt index = 0; FT_Bool alternate = op1 == cf2_cmdHVCURVETO; FT_TRACE4(( alternate ? " hvcurveto\n" : " vhcurveto\n" )); while ( index < count ) { CF2_Fixed x1, x2, x3, y1, y2, y3; if ( alternate ) { x1 = cf2_stack_getReal( opStack, index + 0 ) + curX; y1 = curY; x2 = cf2_stack_getReal( opStack, index + 1 ) + x1; y2 = cf2_stack_getReal( opStack, index + 2 ) + y1; y3 = cf2_stack_getReal( opStack, index + 3 ) + y2; if ( count - index == 5 ) { x3 = cf2_stack_getReal( opStack, index + 4 ) + x2; ++index; } else x3 = x2; alternate = FALSE; } else { x1 = curX; y1 = cf2_stack_getReal( opStack, index + 0 ) + curY; x2 = cf2_stack_getReal( opStack, index + 1 ) + x1; y2 = cf2_stack_getReal( opStack, index + 2 ) + y1; x3 = cf2_stack_getReal( opStack, index + 3 ) + x2; if ( count - index == 5 ) { y3 = cf2_stack_getReal( opStack, index + 4 ) + y2; ++index; } else y3 = y2; alternate = TRUE; } cf2_glyphpath_curveTo( &glyphPath, x1, y1, x2, y2, x3, y3 ); curX = x3; curY = y3; index += 4; } cf2_stack_clear( opStack ); } continue; /* no need to clear stack again */ case cf2_cmdEXTENDEDNMBR: { CF2_Int v; v = (FT_Short)( ( cf2_buf_readByte( charstring ) << 8 ) | cf2_buf_readByte( charstring ) ); FT_TRACE4(( " %d", v )); cf2_stack_pushInt( opStack, v ); } continue; default: /* numbers */ { if ( /* op1 >= 32 && */ op1 <= 246 ) { CF2_Int v; v = op1 - 139; FT_TRACE4(( " %d", v )); /* -107 .. 107 */ cf2_stack_pushInt( opStack, v ); } else if ( /* op1 >= 247 && */ op1 <= 250 ) { CF2_Int v; v = op1; v -= 247; v *= 256; v += cf2_buf_readByte( charstring ); v += 108; FT_TRACE4(( " %d", v )); /* 108 .. 1131 */ cf2_stack_pushInt( opStack, v ); } else if ( /* op1 >= 251 && */ op1 <= 254 ) { CF2_Int v; v = op1; v -= 251; v *= 256; v += cf2_buf_readByte( charstring ); v = -v - 108; FT_TRACE4(( " %d", v )); /* -1131 .. -108 */ cf2_stack_pushInt( opStack, v ); } else /* op1 == 255 */ { CF2_Fixed v; v = (CF2_Fixed) ( ( (FT_UInt32)cf2_buf_readByte( charstring ) << 24 ) | ( (FT_UInt32)cf2_buf_readByte( charstring ) << 16 ) | ( (FT_UInt32)cf2_buf_readByte( charstring ) << 8 ) | (FT_UInt32)cf2_buf_readByte( charstring ) ); FT_TRACE4(( " %.2f", v / 65536.0 )); cf2_stack_pushFixed( opStack, v ); } } continue; /* don't clear stack */ } /* end of switch statement checking `op1' */ cf2_stack_clear( opStack ); } /* end of main interpreter loop */ /* we get here if the charstring ends without cf2_cmdENDCHAR */ FT_TRACE4(( "cf2_interpT2CharString:" " charstring ends without ENDCHAR\n" )); exit: /* check whether last error seen is also the first one */ cf2_setError( error, lastError ); /* free resources from objects we've used */ cf2_glyphpath_finalize( &glyphPath ); cf2_arrstack_finalize( &vStemHintArray ); cf2_arrstack_finalize( &hStemHintArray ); cf2_arrstack_finalize( &subrStack ); cf2_stack_free( opStack ); FT_TRACE4(( "\n" )); return; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2intrp.c
C
apache-2.0
46,582
/***************************************************************************/ /* */ /* cf2font.h */ /* */ /* Adobe's CFF Interpreter (specification). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2INTRP_H__ #define __CF2INTRP_H__ #include "cf2ft.h" #include "cf2hints.h" FT_BEGIN_HEADER FT_LOCAL( void ) cf2_hintmask_init( CF2_HintMask hintmask, FT_Error* error ); FT_LOCAL( FT_Bool ) cf2_hintmask_isValid( const CF2_HintMask hintmask ); FT_LOCAL( FT_Bool ) cf2_hintmask_isNew( const CF2_HintMask hintmask ); FT_LOCAL( void ) cf2_hintmask_setNew( CF2_HintMask hintmask, FT_Bool val ); FT_LOCAL( FT_Byte* ) cf2_hintmask_getMaskPtr( CF2_HintMask hintmask ); FT_LOCAL( void ) cf2_hintmask_setAll( CF2_HintMask hintmask, size_t bitCount ); FT_LOCAL( void ) cf2_interpT2CharString( CF2_Font font, CF2_Buffer charstring, CF2_OutlineCallbacks callbacks, const FT_Vector* translation, FT_Bool doingSeac, CF2_Fixed curX, CF2_Fixed curY, CF2_Fixed* width ); FT_END_HEADER #endif /* __CF2INTRP_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2intrp.h
C
apache-2.0
4,018
/***************************************************************************/ /* */ /* cf2read.c */ /* */ /* Adobe's code for stream handling (body). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2glue.h" #include "cf2error.h" /* Define CF2_IO_FAIL as 1 to enable random errors and random */ /* value errors in I/O. */ #define CF2_IO_FAIL 0 #if CF2_IO_FAIL /* set the .00 value to a nonzero probability */ static int randomError2( void ) { /* for region buffer ReadByte (interp) function */ return (double)rand() / RAND_MAX < .00; } /* set the .00 value to a nonzero probability */ static CF2_Int randomValue() { return (double)rand() / RAND_MAX < .00 ? rand() : 0; } #endif /* CF2_IO_FAIL */ /* Region Buffer */ /* */ /* Can be constructed from a copied buffer managed by */ /* `FCM_getDatablock'. */ /* Reads bytes with check for end of buffer. */ /* reading past the end of the buffer sets error and returns zero */ FT_LOCAL_DEF( CF2_Int ) cf2_buf_readByte( CF2_Buffer buf ) { if ( buf->ptr < buf->end ) { #if CF2_IO_FAIL if ( randomError2() ) { CF2_SET_ERROR( buf->error, Invalid_Stream_Operation ); return 0; } return *(buf->ptr)++ + randomValue(); #else return *(buf->ptr)++; #endif } else { CF2_SET_ERROR( buf->error, Invalid_Stream_Operation ); return 0; } } /* note: end condition can occur without error */ FT_LOCAL_DEF( FT_Bool ) cf2_buf_isEnd( CF2_Buffer buf ) { return (FT_Bool)( buf->ptr >= buf->end ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2read.c
C
apache-2.0
4,441
/***************************************************************************/ /* */ /* cf2read.h */ /* */ /* Adobe's code for stream handling (specification). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2READ_H__ #define __CF2READ_H__ FT_BEGIN_HEADER typedef struct CF2_BufferRec_ { FT_Error* error; const FT_Byte* start; const FT_Byte* end; const FT_Byte* ptr; } CF2_BufferRec, *CF2_Buffer; FT_LOCAL( CF2_Int ) cf2_buf_readByte( CF2_Buffer buf ); FT_LOCAL( FT_Bool ) cf2_buf_isEnd( CF2_Buffer buf ); FT_END_HEADER #endif /* __CF2READ_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2read.h
C
apache-2.0
3,226
/***************************************************************************/ /* */ /* cf2stack.c */ /* */ /* Adobe's code for emulating a CFF stack (body). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #include "cf2ft.h" #include FT_INTERNAL_DEBUG_H #include "cf2glue.h" #include "cf2font.h" #include "cf2stack.h" #include "cf2error.h" /* Allocate and initialize an instance of CF2_Stack. */ /* Note: This function returns NULL on error (does not set */ /* `error'). */ FT_LOCAL_DEF( CF2_Stack ) cf2_stack_init( FT_Memory memory, FT_Error* e ) { FT_Error error = FT_Err_Ok; /* for FT_QNEW */ CF2_Stack stack = NULL; if ( !FT_QNEW( stack ) ) { /* initialize the structure; FT_QNEW zeroes it */ stack->memory = memory; stack->error = e; stack->top = &stack->buffer[0]; /* empty stack */ } return stack; } FT_LOCAL_DEF( void ) cf2_stack_free( CF2_Stack stack ) { if ( stack ) { FT_Memory memory = stack->memory; /* free the main structure */ FT_FREE( stack ); } } FT_LOCAL_DEF( CF2_UInt ) cf2_stack_count( CF2_Stack stack ) { return (CF2_UInt)( stack->top - &stack->buffer[0] ); } FT_LOCAL_DEF( void ) cf2_stack_pushInt( CF2_Stack stack, CF2_Int val ) { if ( stack->top == &stack->buffer[CF2_OPERAND_STACK_SIZE] ) { CF2_SET_ERROR( stack->error, Stack_Overflow ); return; /* stack overflow */ } stack->top->u.i = val; stack->top->type = CF2_NumberInt; ++stack->top; } FT_LOCAL_DEF( void ) cf2_stack_pushFixed( CF2_Stack stack, CF2_Fixed val ) { if ( stack->top == &stack->buffer[CF2_OPERAND_STACK_SIZE] ) { CF2_SET_ERROR( stack->error, Stack_Overflow ); return; /* stack overflow */ } stack->top->u.r = val; stack->top->type = CF2_NumberFixed; ++stack->top; } /* this function is only allowed to pop an integer type */ FT_LOCAL_DEF( CF2_Int ) cf2_stack_popInt( CF2_Stack stack ) { if ( stack->top == &stack->buffer[0] ) { CF2_SET_ERROR( stack->error, Stack_Underflow ); return 0; /* underflow */ } if ( stack->top[-1].type != CF2_NumberInt ) { CF2_SET_ERROR( stack->error, Syntax_Error ); return 0; /* type mismatch */ } --stack->top; return stack->top->u.i; } /* Note: type mismatch is silently cast */ /* TODO: check this */ FT_LOCAL_DEF( CF2_Fixed ) cf2_stack_popFixed( CF2_Stack stack ) { if ( stack->top == &stack->buffer[0] ) { CF2_SET_ERROR( stack->error, Stack_Underflow ); return cf2_intToFixed( 0 ); /* underflow */ } --stack->top; switch ( stack->top->type ) { case CF2_NumberInt: return cf2_intToFixed( stack->top->u.i ); case CF2_NumberFrac: return cf2_fracToFixed( stack->top->u.f ); default: return stack->top->u.r; } } /* Note: type mismatch is silently cast */ /* TODO: check this */ FT_LOCAL_DEF( CF2_Fixed ) cf2_stack_getReal( CF2_Stack stack, CF2_UInt idx ) { FT_ASSERT( cf2_stack_count( stack ) <= CF2_OPERAND_STACK_SIZE ); if ( idx >= cf2_stack_count( stack ) ) { CF2_SET_ERROR( stack->error, Stack_Overflow ); return cf2_intToFixed( 0 ); /* bounds error */ } switch ( stack->buffer[idx].type ) { case CF2_NumberInt: return cf2_intToFixed( stack->buffer[idx].u.i ); case CF2_NumberFrac: return cf2_fracToFixed( stack->buffer[idx].u.f ); default: return stack->buffer[idx].u.r; } } FT_LOCAL_DEF( void ) cf2_stack_clear( CF2_Stack stack ) { stack->top = &stack->buffer[0]; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2stack.c
C
apache-2.0
6,469
/***************************************************************************/ /* */ /* cf2stack.h */ /* */ /* Adobe's code for emulating a CFF stack (specification). */ /* */ /* Copyright 2007-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2STACK_H__ #define __CF2STACK_H__ FT_BEGIN_HEADER /* CFF operand stack; specified maximum of 48 or 192 values */ typedef struct CF2_StackNumber_ { union { CF2_Fixed r; /* 16.16 fixed point */ CF2_Frac f; /* 2.30 fixed point (for font matrix) */ CF2_Int i; } u; CF2_NumberType type; } CF2_StackNumber; typedef struct CF2_StackRec_ { FT_Memory memory; FT_Error* error; CF2_StackNumber buffer[CF2_OPERAND_STACK_SIZE]; CF2_StackNumber* top; } CF2_StackRec, *CF2_Stack; FT_LOCAL( CF2_Stack ) cf2_stack_init( FT_Memory memory, FT_Error* error ); FT_LOCAL( void ) cf2_stack_free( CF2_Stack stack ); FT_LOCAL( CF2_UInt ) cf2_stack_count( CF2_Stack stack ); FT_LOCAL( void ) cf2_stack_pushInt( CF2_Stack stack, CF2_Int val ); FT_LOCAL( void ) cf2_stack_pushFixed( CF2_Stack stack, CF2_Fixed val ); FT_LOCAL( CF2_Int ) cf2_stack_popInt( CF2_Stack stack ); FT_LOCAL( CF2_Fixed ) cf2_stack_popFixed( CF2_Stack stack ); FT_LOCAL( CF2_Fixed ) cf2_stack_getReal( CF2_Stack stack, CF2_UInt idx ); FT_LOCAL( void ) cf2_stack_clear( CF2_Stack stack ); FT_END_HEADER #endif /* __CF2STACK_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2stack.h
C
apache-2.0
4,167
/***************************************************************************/ /* */ /* cf2types.h */ /* */ /* Adobe's code for defining data types (specification only). */ /* */ /* Copyright 2011-2013 Adobe Systems Incorporated. */ /* */ /* This software, and all works of authorship, whether in source or */ /* object code form as indicated by the copyright notice(s) included */ /* herein (collectively, the "Work") is made available, and may only be */ /* used, modified, and distributed under the FreeType Project License, */ /* LICENSE.TXT. Additionally, subject to the terms and conditions of the */ /* FreeType Project License, each contributor to the Work hereby grants */ /* to any individual or legal entity exercising permissions granted by */ /* the FreeType Project License and this section (hereafter, "You" or */ /* "Your") a perpetual, worldwide, non-exclusive, no-charge, */ /* royalty-free, irrevocable (except as stated in this section) patent */ /* license to make, have made, use, offer to sell, sell, import, and */ /* otherwise transfer the Work, where such license applies only to those */ /* patent claims licensable by such contributor that are necessarily */ /* infringed by their contribution(s) alone or by combination of their */ /* contribution(s) with the Work to which such contribution(s) was */ /* submitted. If You institute patent litigation against any entity */ /* (including a cross-claim or counterclaim in a lawsuit) alleging that */ /* the Work or a contribution incorporated within the Work constitutes */ /* direct or contributory patent infringement, then any patent licenses */ /* granted to You under this License for that Work shall terminate as of */ /* the date such litigation is filed. */ /* */ /* By using, modifying, or distributing the Work you indicate that you */ /* have read and understood the terms and conditions of the */ /* FreeType Project License as well as those provided in this section, */ /* and you accept them fully. */ /* */ /***************************************************************************/ #ifndef __CF2TYPES_H__ #define __CF2TYPES_H__ #include <ft2build.h> #include FT_FREETYPE_H FT_BEGIN_HEADER /* * The data models that we expect to support are as follows: * * name char short int long long-long pointer example * ----------------------------------------------------- * ILP32 8 16 32 32 64* 32 32-bit MacOS, x86 * LLP64 8 16 32 32 64 64 x64 * LP64 8 16 32 64 64 64 64-bit MacOS * * *) type may be supported by emulation on a 32-bit architecture * */ /* integers at least 32 bits wide */ #define CF2_UInt FT_UFast #define CF2_Int FT_Fast /* fixed-float numbers */ typedef FT_Int32 CF2_F16Dot16; FT_END_HEADER #endif /* __CF2TYPES_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cf2types.h
C
apache-2.0
3,605
/***************************************************************************/ /* */ /* cff.c */ /* */ /* FreeType OpenType driver component (body only). */ /* */ /* Copyright 1996-2001, 2002, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #define FT_MAKE_OPTION_SINGLE_OBJECT #include <ft2build.h> #include "cffpic.c" #include "cffdrivr.c" #include "cffparse.c" #include "cffload.c" #include "cffobjs.c" #include "cffgload.c" #include "cffcmap.c" #include "cf2arrst.c" #include "cf2blues.c" #include "cf2error.c" #include "cf2font.c" #include "cf2ft.c" #include "cf2hints.c" #include "cf2intrp.c" #include "cf2read.c" #include "cf2stack.c" /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cff.c
C
apache-2.0
1,665
/***************************************************************************/ /* */ /* cffcmap.c */ /* */ /* CFF character mapping table (cmap) support (body). */ /* */ /* Copyright 2002-2007, 2010, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include "cffcmap.h" #include "cffload.h" #include "cfferrs.h" /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CFF STANDARD (AND EXPERT) ENCODING CMAPS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_CALLBACK_DEF( FT_Error ) cff_cmap_encoding_init( CFF_CMapStd cmap ) { TT_Face face = (TT_Face)FT_CMAP_FACE( cmap ); CFF_Font cff = (CFF_Font)face->extra.data; CFF_Encoding encoding = &cff->encoding; cmap->gids = encoding->codes; return 0; } FT_CALLBACK_DEF( void ) cff_cmap_encoding_done( CFF_CMapStd cmap ) { cmap->gids = NULL; } FT_CALLBACK_DEF( FT_UInt ) cff_cmap_encoding_char_index( CFF_CMapStd cmap, FT_UInt32 char_code ) { FT_UInt result = 0; if ( char_code < 256 ) result = cmap->gids[char_code]; return result; } FT_CALLBACK_DEF( FT_UInt32 ) cff_cmap_encoding_char_next( CFF_CMapStd cmap, FT_UInt32 *pchar_code ) { FT_UInt result = 0; FT_UInt32 char_code = *pchar_code; *pchar_code = 0; if ( char_code < 255 ) { FT_UInt code = (FT_UInt)(char_code + 1); for (;;) { if ( code >= 256 ) break; result = cmap->gids[code]; if ( result != 0 ) { *pchar_code = code; break; } code++; } } return result; } FT_DEFINE_CMAP_CLASS(cff_cmap_encoding_class_rec, sizeof ( CFF_CMapStdRec ), (FT_CMap_InitFunc) cff_cmap_encoding_init, (FT_CMap_DoneFunc) cff_cmap_encoding_done, (FT_CMap_CharIndexFunc)cff_cmap_encoding_char_index, (FT_CMap_CharNextFunc) cff_cmap_encoding_char_next, NULL, NULL, NULL, NULL, NULL ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CFF SYNTHETIC UNICODE ENCODING CMAP *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_CALLBACK_DEF( const char* ) cff_sid_to_glyph_name( TT_Face face, FT_UInt idx ) { CFF_Font cff = (CFF_Font)face->extra.data; CFF_Charset charset = &cff->charset; FT_UInt sid = charset->sids[idx]; return cff_index_get_sid_string( cff, sid ); } FT_CALLBACK_DEF( FT_Error ) cff_cmap_unicode_init( PS_Unicodes unicodes ) { TT_Face face = (TT_Face)FT_CMAP_FACE( unicodes ); FT_Memory memory = FT_FACE_MEMORY( face ); CFF_Font cff = (CFF_Font)face->extra.data; CFF_Charset charset = &cff->charset; FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)cff->psnames; /* can't build Unicode map for CID-keyed font */ /* because we don't know glyph names. */ if ( !charset->sids ) return FT_THROW( No_Unicode_Glyph_Name ); return psnames->unicodes_init( memory, unicodes, cff->num_glyphs, (PS_GetGlyphNameFunc)&cff_sid_to_glyph_name, (PS_FreeGlyphNameFunc)NULL, (FT_Pointer)face ); } FT_CALLBACK_DEF( void ) cff_cmap_unicode_done( PS_Unicodes unicodes ) { FT_Face face = FT_CMAP_FACE( unicodes ); FT_Memory memory = FT_FACE_MEMORY( face ); FT_FREE( unicodes->maps ); unicodes->num_maps = 0; } FT_CALLBACK_DEF( FT_UInt ) cff_cmap_unicode_char_index( PS_Unicodes unicodes, FT_UInt32 char_code ) { TT_Face face = (TT_Face)FT_CMAP_FACE( unicodes ); CFF_Font cff = (CFF_Font)face->extra.data; FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)cff->psnames; return psnames->unicodes_char_index( unicodes, char_code ); } FT_CALLBACK_DEF( FT_UInt32 ) cff_cmap_unicode_char_next( PS_Unicodes unicodes, FT_UInt32 *pchar_code ) { TT_Face face = (TT_Face)FT_CMAP_FACE( unicodes ); CFF_Font cff = (CFF_Font)face->extra.data; FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)cff->psnames; return psnames->unicodes_char_next( unicodes, pchar_code ); } FT_DEFINE_CMAP_CLASS(cff_cmap_unicode_class_rec, sizeof ( PS_UnicodesRec ), (FT_CMap_InitFunc) cff_cmap_unicode_init, (FT_CMap_DoneFunc) cff_cmap_unicode_done, (FT_CMap_CharIndexFunc)cff_cmap_unicode_char_index, (FT_CMap_CharNextFunc) cff_cmap_unicode_char_next, NULL, NULL, NULL, NULL, NULL ) /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffcmap.c
C
apache-2.0
6,689
/***************************************************************************/ /* */ /* cffcmap.h */ /* */ /* CFF character mapping table (cmap) support (specification). */ /* */ /* Copyright 2002, 2003, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFCMAP_H__ #define __CFFCMAP_H__ #include "cffobjs.h" FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE1 STANDARD (AND EXPERT) ENCODING CMAPS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* standard (and expert) encoding cmaps */ typedef struct CFF_CMapStdRec_* CFF_CMapStd; typedef struct CFF_CMapStdRec_ { FT_CMapRec cmap; FT_UShort* gids; /* up to 256 elements */ } CFF_CMapStdRec; FT_DECLARE_CMAP_CLASS(cff_cmap_encoding_class_rec) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CFF SYNTHETIC UNICODE ENCODING CMAP *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* unicode (synthetic) cmaps */ FT_DECLARE_CMAP_CLASS(cff_cmap_unicode_class_rec) FT_END_HEADER #endif /* __CFFCMAP_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffcmap.h
C
apache-2.0
2,853
/***************************************************************************/ /* */ /* cffdrivr.c */ /* */ /* OpenType font driver implementation (body). */ /* */ /* Copyright 1996-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_FREETYPE_H #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_SFNT_H #include FT_SERVICE_CID_H #include FT_SERVICE_POSTSCRIPT_INFO_H #include FT_SERVICE_POSTSCRIPT_NAME_H #include FT_SERVICE_TT_CMAP_H #include "cffdrivr.h" #include "cffgload.h" #include "cffload.h" #include "cffcmap.h" #include "cffparse.h" #include "cfferrs.h" #include "cffpic.h" #include FT_SERVICE_XFREE86_NAME_H #include FT_SERVICE_GLYPH_DICT_H #include FT_SERVICE_PROPERTIES_H #include FT_CFF_DRIVER_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffdriver /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** F A C E S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #undef PAIR_TAG #define PAIR_TAG( left, right ) ( ( (FT_ULong)left << 16 ) | \ (FT_ULong)right ) /*************************************************************************/ /* */ /* <Function> */ /* cff_get_kerning */ /* */ /* <Description> */ /* A driver method used to return the kerning vector between two */ /* glyphs of the same face. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* left_glyph :: The index of the left glyph in the kern pair. */ /* */ /* right_glyph :: The index of the right glyph in the kern pair. */ /* */ /* <Output> */ /* kerning :: The kerning vector. This is in font units for */ /* scalable formats, and in pixels for fixed-sizes */ /* formats. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* Only horizontal layouts (left-to-right & right-to-left) are */ /* supported by this function. Other layouts, or more sophisticated */ /* kernings, are out of scope of this method (the basic driver */ /* interface is meant to be simple). */ /* */ /* They can be implemented by format-specific interfaces. */ /* */ FT_CALLBACK_DEF( FT_Error ) cff_get_kerning( FT_Face ttface, /* TT_Face */ FT_UInt left_glyph, FT_UInt right_glyph, FT_Vector* kerning ) { TT_Face face = (TT_Face)ttface; SFNT_Service sfnt = (SFNT_Service)face->sfnt; kerning->x = 0; kerning->y = 0; if ( sfnt ) kerning->x = sfnt->get_kerning( face, left_glyph, right_glyph ); return FT_Err_Ok; } #undef PAIR_TAG /*************************************************************************/ /* */ /* <Function> */ /* cff_glyph_load */ /* */ /* <Description> */ /* A driver method used to load a glyph within a given glyph slot. */ /* */ /* <Input> */ /* slot :: A handle to the target slot object where the glyph */ /* will be loaded. */ /* */ /* size :: A handle to the source face size at which the glyph */ /* must be scaled, loaded, etc. */ /* */ /* glyph_index :: The index of the glyph in the font file. */ /* */ /* load_flags :: A flag indicating what to load for this glyph. The */ /* FT_LOAD_??? constants can be used to control the */ /* glyph loading process (e.g., whether the outline */ /* should be scaled, whether to load bitmaps or not, */ /* whether to hint the outline, etc). */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_CALLBACK_DEF( FT_Error ) cff_glyph_load( FT_GlyphSlot cffslot, /* CFF_GlyphSlot */ FT_Size cffsize, /* CFF_Size */ FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; CFF_GlyphSlot slot = (CFF_GlyphSlot)cffslot; CFF_Size size = (CFF_Size)cffsize; if ( !slot ) return FT_THROW( Invalid_Slot_Handle ); FT_TRACE1(( "cff_glyph_load: glyph index %d\n", glyph_index )); /* check whether we want a scaled outline or bitmap */ if ( !size ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; /* reset the size object if necessary */ if ( load_flags & FT_LOAD_NO_SCALE ) size = NULL; if ( size ) { /* these two objects must have the same parent */ if ( cffsize->face != cffslot->face ) return FT_THROW( Invalid_Face_Handle ); } /* now load the glyph outline if necessary */ error = cff_slot_load( slot, size, glyph_index, load_flags ); /* force drop-out mode to 2 - irrelevant now */ /* slot->outline.dropout_mode = 2; */ return error; } FT_CALLBACK_DEF( FT_Error ) cff_get_advances( FT_Face face, FT_UInt start, FT_UInt count, FT_Int32 flags, FT_Fixed* advances ) { FT_UInt nn; FT_Error error = FT_Err_Ok; FT_GlyphSlot slot = face->glyph; flags |= (FT_UInt32)FT_LOAD_ADVANCE_ONLY; for ( nn = 0; nn < count; nn++ ) { error = cff_glyph_load( slot, face->size, start + nn, flags ); if ( error ) break; advances[nn] = ( flags & FT_LOAD_VERTICAL_LAYOUT ) ? slot->linearVertAdvance : slot->linearHoriAdvance; } return error; } /* * GLYPH DICT SERVICE * */ static FT_Error cff_get_glyph_name( CFF_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ) { CFF_Font font = (CFF_Font)face->extra.data; FT_String* gname; FT_UShort sid; FT_Error error; if ( !font->psnames ) { FT_ERROR(( "cff_get_glyph_name:" " cannot get glyph name from CFF & CEF fonts\n" " " " without the `PSNames' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } /* first, locate the sid in the charset table */ sid = font->charset.sids[glyph_index]; /* now, lookup the name itself */ gname = cff_index_get_sid_string( font, sid ); if ( gname ) FT_STRCPYN( buffer, gname, buffer_max ); error = FT_Err_Ok; Exit: return error; } static FT_UInt cff_get_name_index( CFF_Face face, FT_String* glyph_name ) { CFF_Font cff; CFF_Charset charset; FT_Service_PsCMaps psnames; FT_String* name; FT_UShort sid; FT_UInt i; cff = (CFF_FontRec *)face->extra.data; charset = &cff->charset; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); if ( !psnames ) return 0; for ( i = 0; i < cff->num_glyphs; i++ ) { sid = charset->sids[i]; if ( sid > 390 ) name = cff_index_get_string( cff, sid - 391 ); else name = (FT_String *)psnames->adobe_std_strings( sid ); if ( !name ) continue; if ( !ft_strcmp( glyph_name, name ) ) return i; } return 0; } FT_DEFINE_SERVICE_GLYPHDICTREC( cff_service_glyph_dict, (FT_GlyphDict_GetNameFunc) cff_get_glyph_name, (FT_GlyphDict_NameIndexFunc)cff_get_name_index ) /* * POSTSCRIPT INFO SERVICE * */ static FT_Int cff_ps_has_glyph_names( FT_Face face ) { return ( face->face_flags & FT_FACE_FLAG_GLYPH_NAMES ) > 0; } static FT_Error cff_ps_get_font_info( CFF_Face face, PS_FontInfoRec* afont_info ) { CFF_Font cff = (CFF_Font)face->extra.data; FT_Error error = FT_Err_Ok; if ( cff && cff->font_info == NULL ) { CFF_FontRecDict dict = &cff->top_font.font_dict; PS_FontInfoRec *font_info = NULL; FT_Memory memory = face->root.memory; if ( FT_ALLOC( font_info, sizeof ( *font_info ) ) ) goto Fail; font_info->version = cff_index_get_sid_string( cff, dict->version ); font_info->notice = cff_index_get_sid_string( cff, dict->notice ); font_info->full_name = cff_index_get_sid_string( cff, dict->full_name ); font_info->family_name = cff_index_get_sid_string( cff, dict->family_name ); font_info->weight = cff_index_get_sid_string( cff, dict->weight ); font_info->italic_angle = dict->italic_angle; font_info->is_fixed_pitch = dict->is_fixed_pitch; font_info->underline_position = (FT_Short)dict->underline_position; font_info->underline_thickness = (FT_Short)dict->underline_thickness; cff->font_info = font_info; } if ( cff ) *afont_info = *cff->font_info; Fail: return error; } FT_DEFINE_SERVICE_PSINFOREC( cff_service_ps_info, (PS_GetFontInfoFunc) cff_ps_get_font_info, (PS_GetFontExtraFunc) NULL, (PS_HasGlyphNamesFunc) cff_ps_has_glyph_names, (PS_GetFontPrivateFunc)NULL, /* unsupported with CFF fonts */ (PS_GetFontValueFunc) NULL /* not implemented */ ) /* * POSTSCRIPT NAME SERVICE * */ static const char* cff_get_ps_name( CFF_Face face ) { CFF_Font cff = (CFF_Font)face->extra.data; return (const char*)cff->font_name; } FT_DEFINE_SERVICE_PSFONTNAMEREC( cff_service_ps_name, (FT_PsName_GetFunc)cff_get_ps_name ) /* * TT CMAP INFO * * If the charmap is a synthetic Unicode encoding cmap or * a Type 1 standard (or expert) encoding cmap, hide TT CMAP INFO * service defined in SFNT module. * * Otherwise call the service function in the sfnt module. * */ static FT_Error cff_get_cmap_info( FT_CharMap charmap, TT_CMapInfo *cmap_info ) { FT_CMap cmap = FT_CMAP( charmap ); FT_Error error = FT_Err_Ok; FT_Face face = FT_CMAP_FACE( cmap ); FT_Library library = FT_FACE_LIBRARY( face ); cmap_info->language = 0; cmap_info->format = 0; if ( cmap->clazz != &CFF_CMAP_ENCODING_CLASS_REC_GET && cmap->clazz != &CFF_CMAP_UNICODE_CLASS_REC_GET ) { FT_Module sfnt = FT_Get_Module( library, "sfnt" ); FT_Service_TTCMaps service = (FT_Service_TTCMaps)ft_module_get_service( sfnt, FT_SERVICE_ID_TT_CMAP ); if ( service && service->get_cmap_info ) error = service->get_cmap_info( charmap, cmap_info ); } return error; } FT_DEFINE_SERVICE_TTCMAPSREC( cff_service_get_cmap_info, (TT_CMap_Info_GetFunc)cff_get_cmap_info ) /* * CID INFO SERVICE * */ static FT_Error cff_get_ros( CFF_Face face, const char* *registry, const char* *ordering, FT_Int *supplement ) { FT_Error error = FT_Err_Ok; CFF_Font cff = (CFF_Font)face->extra.data; if ( cff ) { CFF_FontRecDict dict = &cff->top_font.font_dict; if ( dict->cid_registry == 0xFFFFU ) { error = FT_THROW( Invalid_Argument ); goto Fail; } if ( registry ) { if ( cff->registry == NULL ) cff->registry = cff_index_get_sid_string( cff, dict->cid_registry ); *registry = cff->registry; } if ( ordering ) { if ( cff->ordering == NULL ) cff->ordering = cff_index_get_sid_string( cff, dict->cid_ordering ); *ordering = cff->ordering; } /* * XXX: According to Adobe TechNote #5176, the supplement in CFF * can be a real number. We truncate it to fit public API * since freetype-2.3.6. */ if ( supplement ) { if ( dict->cid_supplement < FT_INT_MIN || dict->cid_supplement > FT_INT_MAX ) FT_TRACE1(( "cff_get_ros: too large supplement %d is truncated\n", dict->cid_supplement )); *supplement = (FT_Int)dict->cid_supplement; } } Fail: return error; } static FT_Error cff_get_is_cid( CFF_Face face, FT_Bool *is_cid ) { FT_Error error = FT_Err_Ok; CFF_Font cff = (CFF_Font)face->extra.data; *is_cid = 0; if ( cff ) { CFF_FontRecDict dict = &cff->top_font.font_dict; if ( dict->cid_registry != 0xFFFFU ) *is_cid = 1; } return error; } static FT_Error cff_get_cid_from_glyph_index( CFF_Face face, FT_UInt glyph_index, FT_UInt *cid ) { FT_Error error = FT_Err_Ok; CFF_Font cff; cff = (CFF_Font)face->extra.data; if ( cff ) { FT_UInt c; CFF_FontRecDict dict = &cff->top_font.font_dict; if ( dict->cid_registry == 0xFFFFU ) { error = FT_THROW( Invalid_Argument ); goto Fail; } if ( glyph_index > cff->num_glyphs ) { error = FT_THROW( Invalid_Argument ); goto Fail; } c = cff->charset.sids[glyph_index]; if ( cid ) *cid = c; } Fail: return error; } FT_DEFINE_SERVICE_CIDREC( cff_service_cid_info, (FT_CID_GetRegistryOrderingSupplementFunc)cff_get_ros, (FT_CID_GetIsInternallyCIDKeyedFunc) cff_get_is_cid, (FT_CID_GetCIDFromGlyphIndexFunc) cff_get_cid_from_glyph_index ) /* * PROPERTY SERVICE * */ static FT_Error cff_property_set( FT_Module module, /* CFF_Driver */ const char* property_name, const void* value ) { FT_Error error = FT_Err_Ok; CFF_Driver driver = (CFF_Driver)module; if ( !ft_strcmp( property_name, "darkening-parameters" ) ) { FT_Int* darken_params = (FT_Int*)value; FT_Int x1 = darken_params[0]; FT_Int y1 = darken_params[1]; FT_Int x2 = darken_params[2]; FT_Int y2 = darken_params[3]; FT_Int x3 = darken_params[4]; FT_Int y3 = darken_params[5]; FT_Int x4 = darken_params[6]; FT_Int y4 = darken_params[7]; if ( x1 < 0 || x2 < 0 || x3 < 0 || x4 < 0 || y1 < 0 || y2 < 0 || y3 < 0 || y4 < 0 || x1 > x2 || x2 > x3 || x3 > x4 || y1 > 500 || y2 > 500 || y3 > 500 || y4 > 500 ) return FT_THROW( Invalid_Argument ); driver->darken_params[0] = x1; driver->darken_params[1] = y1; driver->darken_params[2] = x2; driver->darken_params[3] = y2; driver->darken_params[4] = x3; driver->darken_params[5] = y3; driver->darken_params[6] = x4; driver->darken_params[7] = y4; return error; } else if ( !ft_strcmp( property_name, "hinting-engine" ) ) { FT_UInt* hinting_engine = (FT_UInt*)value; #ifndef CFF_CONFIG_OPTION_OLD_ENGINE if ( *hinting_engine != FT_CFF_HINTING_ADOBE ) error = FT_ERR( Unimplemented_Feature ); else #endif driver->hinting_engine = *hinting_engine; return error; } else if ( !ft_strcmp( property_name, "no-stem-darkening" ) ) { FT_Bool* no_stem_darkening = (FT_Bool*)value; driver->no_stem_darkening = *no_stem_darkening; return error; } FT_TRACE0(( "cff_property_set: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } static FT_Error cff_property_get( FT_Module module, /* CFF_Driver */ const char* property_name, const void* value ) { FT_Error error = FT_Err_Ok; CFF_Driver driver = (CFF_Driver)module; if ( !ft_strcmp( property_name, "darkening-parameters" ) ) { FT_Int* darken_params = driver->darken_params; FT_Int* val = (FT_Int*)value; val[0] = darken_params[0]; val[1] = darken_params[1]; val[2] = darken_params[2]; val[3] = darken_params[3]; val[4] = darken_params[4]; val[5] = darken_params[5]; val[6] = darken_params[6]; val[7] = darken_params[7]; return error; } else if ( !ft_strcmp( property_name, "hinting-engine" ) ) { FT_UInt hinting_engine = driver->hinting_engine; FT_UInt* val = (FT_UInt*)value; *val = hinting_engine; return error; } else if ( !ft_strcmp( property_name, "no-stem-darkening" ) ) { FT_Bool no_stem_darkening = driver->no_stem_darkening; FT_Bool* val = (FT_Bool*)value; *val = no_stem_darkening; return error; } FT_TRACE0(( "cff_property_get: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } FT_DEFINE_SERVICE_PROPERTIESREC( cff_service_properties, (FT_Properties_SetFunc)cff_property_set, (FT_Properties_GetFunc)cff_property_get ) /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** D R I V E R I N T E R F A C E ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifndef FT_CONFIG_OPTION_NO_GLYPH_NAMES FT_DEFINE_SERVICEDESCREC7( cff_services, FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_CFF, FT_SERVICE_ID_POSTSCRIPT_INFO, &CFF_SERVICE_PS_INFO_GET, FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &CFF_SERVICE_PS_NAME_GET, FT_SERVICE_ID_GLYPH_DICT, &CFF_SERVICE_GLYPH_DICT_GET, FT_SERVICE_ID_TT_CMAP, &CFF_SERVICE_GET_CMAP_INFO_GET, FT_SERVICE_ID_CID, &CFF_SERVICE_CID_INFO_GET, FT_SERVICE_ID_PROPERTIES, &CFF_SERVICE_PROPERTIES_GET ) #else FT_DEFINE_SERVICEDESCREC6( cff_services, FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_CFF, FT_SERVICE_ID_POSTSCRIPT_INFO, &CFF_SERVICE_PS_INFO_GET, FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &CFF_SERVICE_PS_NAME_GET, FT_SERVICE_ID_TT_CMAP, &CFF_SERVICE_GET_CMAP_INFO_GET, FT_SERVICE_ID_CID, &CFF_SERVICE_CID_INFO_GET, FT_SERVICE_ID_PROPERTIES, &CFF_SERVICE_PROPERTIES_GET ) #endif FT_CALLBACK_DEF( FT_Module_Interface ) cff_get_interface( FT_Module driver, /* CFF_Driver */ const char* module_interface ) { FT_Library library; FT_Module sfnt; FT_Module_Interface result; /* CFF_SERVICES_GET derefers `library' in PIC mode */ #ifdef FT_CONFIG_OPTION_PIC if ( !driver ) return NULL; library = driver->library; if ( !library ) return NULL; #endif result = ft_service_list_lookup( CFF_SERVICES_GET, module_interface ); if ( result != NULL ) return result; /* `driver' is not yet evaluated in non-PIC mode */ #ifndef FT_CONFIG_OPTION_PIC if ( !driver ) return NULL; library = driver->library; if ( !library ) return NULL; #endif /* we pass our request to the `sfnt' module */ sfnt = FT_Get_Module( library, "sfnt" ); return sfnt ? sfnt->clazz->get_interface( sfnt, module_interface ) : 0; } /* The FT_DriverInterface structure is defined in ftdriver.h. */ #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS #define CFF_SIZE_SELECT cff_size_select #else #define CFF_SIZE_SELECT 0 #endif FT_DEFINE_DRIVER( cff_driver_class, FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_SCALABLE | FT_MODULE_DRIVER_HAS_HINTER, sizeof ( CFF_DriverRec ), "cff", 0x10000L, 0x20000L, 0, /* module-specific interface */ cff_driver_init, cff_driver_done, cff_get_interface, /* now the specific driver fields */ sizeof ( TT_FaceRec ), sizeof ( CFF_SizeRec ), sizeof ( CFF_GlyphSlotRec ), cff_face_init, cff_face_done, cff_size_init, cff_size_done, cff_slot_init, cff_slot_done, cff_glyph_load, cff_get_kerning, 0, /* FT_Face_AttachFunc */ cff_get_advances, cff_size_request, CFF_SIZE_SELECT ) /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffdrivr.c
C
apache-2.0
26,063
/***************************************************************************/ /* */ /* cffdrivr.h */ /* */ /* High-level OpenType driver interface (specification). */ /* */ /* Copyright 1996-2001, 2002 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFDRIVER_H__ #define __CFFDRIVER_H__ #include <ft2build.h> #include FT_INTERNAL_DRIVER_H FT_BEGIN_HEADER FT_DECLARE_DRIVER( cff_driver_class ) FT_END_HEADER #endif /* __CFFDRIVER_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffdrivr.h
C
apache-2.0
1,470
/***************************************************************************/ /* */ /* cfferrs.h */ /* */ /* CFF error codes (specification only). */ /* */ /* Copyright 2001, 2012 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to define the CFF error enumeration constants. */ /* */ /*************************************************************************/ #ifndef __CFFERRS_H__ #define __CFFERRS_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX CFF_Err_ #define FT_ERR_BASE FT_Mod_Err_CFF #include FT_ERRORS_H #endif /* __CFFERRS_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cfferrs.h
C
apache-2.0
1,893
/***************************************************************************/ /* */ /* cffgload.c */ /* */ /* OpenType Glyph Loader (body). */ /* */ /* Copyright 1996-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_SFNT_H #include FT_OUTLINE_H #include FT_CFF_DRIVER_H #include "cffobjs.h" #include "cffload.h" #include "cffgload.h" #include "cf2ft.h" /* for cf2_decoder_parse_charstrings */ #include "cfferrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffgload #ifdef CFF_CONFIG_OPTION_OLD_ENGINE typedef enum CFF_Operator_ { cff_op_unknown = 0, cff_op_rmoveto, cff_op_hmoveto, cff_op_vmoveto, cff_op_rlineto, cff_op_hlineto, cff_op_vlineto, cff_op_rrcurveto, cff_op_hhcurveto, cff_op_hvcurveto, cff_op_rcurveline, cff_op_rlinecurve, cff_op_vhcurveto, cff_op_vvcurveto, cff_op_flex, cff_op_hflex, cff_op_hflex1, cff_op_flex1, cff_op_endchar, cff_op_hstem, cff_op_vstem, cff_op_hstemhm, cff_op_vstemhm, cff_op_hintmask, cff_op_cntrmask, cff_op_dotsection, /* deprecated, acts as no-op */ cff_op_abs, cff_op_add, cff_op_sub, cff_op_div, cff_op_neg, cff_op_random, cff_op_mul, cff_op_sqrt, cff_op_blend, cff_op_drop, cff_op_exch, cff_op_index, cff_op_roll, cff_op_dup, cff_op_put, cff_op_get, cff_op_store, cff_op_load, cff_op_and, cff_op_or, cff_op_not, cff_op_eq, cff_op_ifelse, cff_op_callsubr, cff_op_callgsubr, cff_op_return, /* Type 1 opcodes: invalid but seen in real life */ cff_op_hsbw, cff_op_closepath, cff_op_callothersubr, cff_op_pop, cff_op_seac, cff_op_sbw, cff_op_setcurrentpoint, /* do not remove */ cff_op_max } CFF_Operator; #define CFF_COUNT_CHECK_WIDTH 0x80 #define CFF_COUNT_EXACT 0x40 #define CFF_COUNT_CLEAR_STACK 0x20 /* count values which have the `CFF_COUNT_CHECK_WIDTH' flag set are */ /* used for checking the width and requested numbers of arguments */ /* only; they are set to zero afterwards */ /* the other two flags are informative only and unused currently */ static const FT_Byte cff_argument_counts[] = { 0, /* unknown */ 2 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, /* rmoveto */ 1 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, 1 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, 0 | CFF_COUNT_CLEAR_STACK, /* rlineto */ 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, /* rrcurveto */ 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 13, /* flex */ 7, 9, 11, 0 | CFF_COUNT_CHECK_WIDTH, /* endchar */ 2 | CFF_COUNT_CHECK_WIDTH, /* hstem */ 2 | CFF_COUNT_CHECK_WIDTH, 2 | CFF_COUNT_CHECK_WIDTH, 2 | CFF_COUNT_CHECK_WIDTH, 0 | CFF_COUNT_CHECK_WIDTH, /* hintmask */ 0 | CFF_COUNT_CHECK_WIDTH, /* cntrmask */ 0, /* dotsection */ 1, /* abs */ 2, 2, 2, 1, 0, 2, 1, 1, /* blend */ 1, /* drop */ 2, 1, 2, 1, 2, /* put */ 1, 4, 3, 2, /* and */ 2, 1, 2, 4, 1, /* callsubr */ 1, 0, 2, /* hsbw */ 0, 0, 0, 5, /* seac */ 4, /* sbw */ 2 /* setcurrentpoint */ }; #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** *********/ /********** GENERIC CHARSTRING PARSING *********/ /********** *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* cff_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting is active. */ /* */ static void cff_builder_init( CFF_Builder* builder, TT_Face face, CFF_Size size, CFF_GlyphSlot glyph, FT_Bool hinting ) { builder->path_begun = 0; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->root.memory; if ( glyph ) { FT_GlyphLoader loader = glyph->root.internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = 0; builder->hints_funcs = 0; if ( hinting && size ) { CFF_Internal internal = (CFF_Internal)size->root.internal; builder->hints_globals = (void *)internal->topfont; builder->hints_funcs = glyph->root.internal->glyph_hints; } } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; } /*************************************************************************/ /* */ /* <Function> */ /* cff_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ static void cff_builder_done( CFF_Builder* builder ) { CFF_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->root.outline = *builder->base; } /*************************************************************************/ /* */ /* <Function> */ /* cff_compute_bias */ /* */ /* <Description> */ /* Computes the bias value in dependence of the number of glyph */ /* subroutines. */ /* */ /* <Input> */ /* in_charstring_type :: The `CharstringType' value of the top DICT */ /* dictionary. */ /* */ /* num_subrs :: The number of glyph subroutines. */ /* */ /* <Return> */ /* The bias value. */ static FT_Int cff_compute_bias( FT_Int in_charstring_type, FT_UInt num_subrs ) { FT_Int result; if ( in_charstring_type == 1 ) result = 0; else if ( num_subrs < 1240 ) result = 107; else if ( num_subrs < 33900U ) result = 1131; else result = 32768U; return result; } /*************************************************************************/ /* */ /* <Function> */ /* cff_decoder_init */ /* */ /* <Description> */ /* Initializes a given glyph decoder. */ /* */ /* <InOut> */ /* decoder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* slot :: The current glyph object. */ /* */ /* hinting :: Whether hinting is active. */ /* */ /* hint_mode :: The hinting mode. */ /* */ FT_LOCAL_DEF( void ) cff_decoder_init( CFF_Decoder* decoder, TT_Face face, CFF_Size size, CFF_GlyphSlot slot, FT_Bool hinting, FT_Render_Mode hint_mode ) { CFF_Font cff = (CFF_Font)face->extra.data; /* clear everything */ FT_MEM_ZERO( decoder, sizeof ( *decoder ) ); /* initialize builder */ cff_builder_init( &decoder->builder, face, size, slot, hinting ); /* initialize Type2 decoder */ decoder->cff = cff; decoder->num_globals = cff->global_subrs_index.count; decoder->globals = cff->global_subrs; decoder->globals_bias = cff_compute_bias( cff->top_font.font_dict.charstring_type, decoder->num_globals ); decoder->hint_mode = hint_mode; } /* this function is used to select the subfont */ /* and the locals subrs array */ FT_LOCAL_DEF( FT_Error ) cff_decoder_prepare( CFF_Decoder* decoder, CFF_Size size, FT_UInt glyph_index ) { CFF_Builder *builder = &decoder->builder; CFF_Font cff = (CFF_Font)builder->face->extra.data; CFF_SubFont sub = &cff->top_font; FT_Error error = FT_Err_Ok; /* manage CID fonts */ if ( cff->num_subfonts ) { FT_Byte fd_index = cff_fd_select_get( &cff->fd_select, glyph_index ); if ( fd_index >= cff->num_subfonts ) { FT_TRACE4(( "cff_decoder_prepare: invalid CID subfont index\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } FT_TRACE3(( " in subfont %d:\n", fd_index )); sub = cff->subfonts[fd_index]; if ( builder->hints_funcs && size ) { CFF_Internal internal = (CFF_Internal)size->root.internal; /* for CFFs without subfonts, this value has already been set */ builder->hints_globals = (void *)internal->subfonts[fd_index]; } } decoder->num_locals = sub->local_subrs_index.count; decoder->locals = sub->local_subrs; decoder->locals_bias = cff_compute_bias( decoder->cff->top_font.font_dict.charstring_type, decoder->num_locals ); decoder->glyph_width = sub->private_dict.default_width; decoder->nominal_width = sub->private_dict.nominal_width; decoder->current_subfont = sub; /* for Adobe's CFF handler */ Exit: return error; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) cff_check_points( CFF_Builder* builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) cff_builder_add_point( CFF_Builder* builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; #ifdef CFF_CONFIG_OPTION_OLD_ENGINE CFF_Driver driver = (CFF_Driver)FT_FACE_DRIVER( builder->face ); if ( driver->hinting_engine == FT_CFF_HINTING_FREETYPE ) { point->x = x >> 16; point->y = y >> 16; } else #endif { /* cf2_decoder_parse_charstrings uses 16.16 coordinates */ point->x = x >> 10; point->y = y >> 10; } *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) cff_builder_add_point1( CFF_Builder* builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = cff_check_points( builder, 1 ); if ( !error ) cff_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ static FT_Error cff_builder_add_contour( CFF_Builder* builder ) { FT_Outline* outline = builder->current; FT_Error error; if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) cff_builder_start_point( CFF_Builder* builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_Err_Ok; /* test whether we are building a new contour */ if ( !builder->path_begun ) { builder->path_begun = 1; error = cff_builder_add_contour( builder ); if ( !error ) error = cff_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) cff_builder_close_contour( CFF_Builder* builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) { FT_Vector* p1 = outline->points + first; FT_Vector* p2 = outline->points + outline->n_points - 1; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points - 1; /* `delete' last point only if it coincides with the first */ /* point and if it is not a control point (which can happen). */ if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether begin point and last point are the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } } FT_LOCAL_DEF( FT_Int ) cff_lookup_glyph_by_stdcharcode( CFF_Font cff, FT_Int charcode ) { FT_UInt n; FT_UShort glyph_sid; /* CID-keyed fonts don't have glyph names */ if ( !cff->charset.sids ) return -1; /* check range of standard char code */ if ( charcode < 0 || charcode > 255 ) return -1; /* Get code to SID mapping from `cff_standard_encoding'. */ glyph_sid = cff_get_standard_encoding( (FT_UInt)charcode ); for ( n = 0; n < cff->num_glyphs; n++ ) { if ( cff->charset.sids[n] == glyph_sid ) return n; } return -1; } FT_LOCAL_DEF( FT_Error ) cff_get_glyph_data( TT_Face face, FT_UInt glyph_index, FT_Byte** pointer, FT_ULong* length ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( face->root.internal->incremental_interface ) { FT_Data data; FT_Error error = face->root.internal->incremental_interface->funcs->get_glyph_data( face->root.internal->incremental_interface->object, glyph_index, &data ); *pointer = (FT_Byte*)data.pointer; *length = data.length; return error; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); return cff_index_access_element( &cff->charstrings_index, glyph_index, pointer, length ); } } FT_LOCAL_DEF( void ) cff_free_glyph_data( TT_Face face, FT_Byte** pointer, FT_ULong length ) { #ifndef FT_CONFIG_OPTION_INCREMENTAL FT_UNUSED( length ); #endif #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( face->root.internal->incremental_interface ) { FT_Data data; data.pointer = *pointer; data.length = length; face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &data ); } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); cff_index_forget_element( &cff->charstrings_index, pointer ); } } #ifdef CFF_CONFIG_OPTION_OLD_ENGINE static FT_Error cff_operator_seac( CFF_Decoder* decoder, FT_Pos asb, FT_Pos adx, FT_Pos ady, FT_Int bchar, FT_Int achar ) { FT_Error error; CFF_Builder* builder = &decoder->builder; FT_Int bchar_index, achar_index; TT_Face face = decoder->builder.face; FT_Vector left_bearing, advance; FT_Byte* charstring; FT_ULong charstring_len; FT_Pos glyph_width; if ( decoder->seac ) { FT_ERROR(( "cff_operator_seac: invalid nested seac\n" )); return FT_THROW( Syntax_Error ); } adx += decoder->builder.left_bearing.x; ady += decoder->builder.left_bearing.y; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts don't necessarily have valid charsets. */ /* They use the character code, not the glyph index, in this case. */ if ( face->root.internal->incremental_interface ) { bchar_index = bchar; achar_index = achar; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); bchar_index = cff_lookup_glyph_by_stdcharcode( cff, bchar ); achar_index = cff_lookup_glyph_by_stdcharcode( cff, achar ); } if ( bchar_index < 0 || achar_index < 0 ) { FT_ERROR(( "cff_operator_seac:" " invalid seac character code arguments\n" )); return FT_THROW( Syntax_Error ); } /* If we are trying to load a composite glyph, do not load the */ /* accent character and return the array of subglyphs. */ if ( builder->no_recurse ) { FT_GlyphSlot glyph = (FT_GlyphSlot)builder->glyph; FT_GlyphLoader loader = glyph->internal->loader; FT_SubGlyph subg; /* reallocate subglyph array if necessary */ error = FT_GlyphLoader_CheckSubGlyphs( loader, 2 ); if ( error ) goto Exit; subg = loader->current.subglyphs; /* subglyph 0 = base character */ subg->index = bchar_index; subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES | FT_SUBGLYPH_FLAG_USE_MY_METRICS; subg->arg1 = 0; subg->arg2 = 0; subg++; /* subglyph 1 = accent character */ subg->index = achar_index; subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES; subg->arg1 = (FT_Int)( adx >> 16 ); subg->arg2 = (FT_Int)( ady >> 16 ); /* set up remaining glyph fields */ glyph->num_subglyphs = 2; glyph->subglyphs = loader->base.subglyphs; glyph->format = FT_GLYPH_FORMAT_COMPOSITE; loader->current.num_subglyphs = 2; } FT_GlyphLoader_Prepare( builder->loader ); /* First load `bchar' in builder */ error = cff_get_glyph_data( face, bchar_index, &charstring, &charstring_len ); if ( !error ) { /* the seac operator must not be nested */ decoder->seac = TRUE; error = cff_decoder_parse_charstrings( decoder, charstring, charstring_len ); decoder->seac = FALSE; cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Exit; } /* Save the left bearing, advance and glyph width of the base */ /* character as they will be erased by the next load. */ left_bearing = builder->left_bearing; advance = builder->advance; glyph_width = decoder->glyph_width; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->pos_x = adx - asb; builder->pos_y = ady; /* Now load `achar' on top of the base outline. */ error = cff_get_glyph_data( face, achar_index, &charstring, &charstring_len ); if ( !error ) { /* the seac operator must not be nested */ decoder->seac = TRUE; error = cff_decoder_parse_charstrings( decoder, charstring, charstring_len ); decoder->seac = FALSE; cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Exit; } /* Restore the left side bearing, advance and glyph width */ /* of the base character. */ builder->left_bearing = left_bearing; builder->advance = advance; decoder->glyph_width = glyph_width; builder->pos_x = 0; builder->pos_y = 0; Exit: return error; } /*************************************************************************/ /* */ /* <Function> */ /* cff_decoder_parse_charstrings */ /* */ /* <Description> */ /* Parses a given Type 2 charstrings program. */ /* */ /* <InOut> */ /* decoder :: The current Type 1 decoder. */ /* */ /* <Input> */ /* charstring_base :: The base of the charstring stream. */ /* */ /* charstring_len :: The length in bytes of the charstring stream. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_LOCAL_DEF( FT_Error ) cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = FT_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ /* if we use shifts, all computations are done with unsigned */ /* values; the conversion to a signed value is the last step */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_UShort)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) | ( (FT_UInt32)ip[1] << 16 ) | ( (FT_UInt32)ip[2] << 8 ) | (FT_UInt32)ip[3] ); ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val = (FT_Int32)( (FT_UInt32)val << shift ); *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( " %hd", (FT_Short)( (FT_UInt32)val >> 16 ) )); else FT_TRACE4(( " %.2f", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; default: FT_TRACE4(( " unknown op (12, %d)\n", v )); break; } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: FT_TRACE4(( " unknown op (%d)\n", v )); break; } if ( op == cff_op_unknown ) continue; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? " hstem\n" : ( op == cff_op_vstem ? " vstem\n" : ( op == cff_op_hstemhm ? " hstemhm\n" : " vstemhm\n" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? " hintmask" : " cntrmask" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } /* In a valid charstring there must be at least one byte */ /* after `hintmask' or `cntrmask' (e.g., for a `return' */ /* instruction). Additionally, there must be space for */ /* `num_hints' bits. */ if ( ( ip + ( ( decoder->num_hints + 7 ) >> 3 ) ) >= limit ) goto Syntax_Error; if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( " (maskbytes:" )); for ( maskbyte = 0; maskbyte < (FT_UInt)( ( decoder->num_hints + 7 ) >> 3 ); maskbyte++, ip++ ) FT_TRACE4(( " 0x%02X", *ip )); FT_TRACE4(( ")\n" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif args = stack; break; case cff_op_rmoveto: FT_TRACE4(( " rmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( " vmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( " hmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( " rlineto\n" )); if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? " hlineto\n" : " vlineto\n" )); if ( num_args < 0 ) goto Stack_Underflow; /* there exist subsetted fonts (found in PDFs) */ /* which call `hlineto' without arguments */ if ( num_args == 0 ) break; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( " rrcurveto\n" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( " vvcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( cff_check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( " hhcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( cff_check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? " vhcurveto\n" : " hvcurveto\n" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; args -= nargs; if ( cff_check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( " rlinecurve\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( " rcurveline\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( " hflex1\n" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( " hflex\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( " flex1\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( " flex\n" )); if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( " seac\n" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_endchar: FT_TRACE4(( " endchar\n" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = FT_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_abs: FT_TRACE4(( " abs\n" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( " add\n" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( " sub\n" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( " div\n" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( " neg\n" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( " rand\n" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( " mul\n" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( " sqrt\n" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( " drop\n" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( " exch\n" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( " index\n" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " roll\n" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( " dup\n" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " put\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( " get\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( " store\n")); goto Unimplemented; case cff_op_load: FT_TRACE4(( " load\n" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( " dotsection\n" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " closepath (invalid op)\n" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " hsbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " sbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " setcurrentpoint (invalid op)\n" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " callothersubr (invalid op)\n" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ /* */ /* XXX Fix return arguments (see discussion below). */ args -= 2 + ( args[-2] >> 16 ); if ( args < stack ) goto Stack_Underflow; break; case cff_op_pop: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " pop (invalid op)\n" )); /* XXX Increasing `args' is wrong: After a certain number of */ /* `pop's we get a stack overflow. Reason for doing it is */ /* code like this (actually found in a CFF font): */ /* */ /* 17 1 3 callothersubr */ /* pop */ /* callsubr */ /* */ /* Since we handle `callothersubr' as a no-op, and */ /* `callsubr' needs at least one argument, `pop' can't be a */ /* no-op too as it basically should be. */ /* */ /* The right solution would be to provide real support for */ /* `callothersubr' as done in `t1decode.c', however, given */ /* the fact that CFF fonts with `pop' are invalid, it is */ /* questionable whether it is worth the time. */ args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( " and\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( " or\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( " eq\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( " ifelse\n" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( " callsubr(%d)\n", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid local subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( " callgsubr(%d)\n", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid global subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( " return\n" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( "Unimplemented opcode: %d", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( " %d", ip[0] )); FT_ERROR(( "\n" )); return FT_THROW( Unimplemented_Feature ); } decoder->top = args; if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: FT_TRACE4(( "cff_decoder_parse_charstrings: syntax error\n" )); return FT_THROW( Invalid_File_Format ); Stack_Underflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack underflow\n" )); return FT_THROW( Too_Few_Arguments ); Stack_Overflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack overflow\n" )); return FT_THROW( Stack_Overflow ); } #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** *********/ /********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/ /********** *********/ /********** The following code is in charge of computing *********/ /********** the maximum advance width of the font. It *********/ /********** quickly processes each glyph charstring to *********/ /********** extract the value from either a `sbw' or `seac' *********/ /********** operator. *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #if 0 /* unused until we support pure CFF fonts */ FT_LOCAL_DEF( FT_Error ) cff_compute_max_advance( TT_Face face, FT_Int* max_advance ) { FT_Error error = FT_Err_Ok; CFF_Decoder decoder; FT_Int glyph_index; CFF_Font cff = (CFF_Font)face->other; *max_advance = 0; /* Initialize load decoder */ cff_decoder_init( &decoder, face, 0, 0, 0, 0 ); decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; /* For each glyph, parse the glyph charstring and extract */ /* the advance width. */ for ( glyph_index = 0; glyph_index < face->root.num_glyphs; glyph_index++ ) { FT_Byte* charstring; FT_ULong charstring_len; /* now get load the unscaled outline */ error = cff_get_glyph_data( face, glyph_index, &charstring, &charstring_len ); if ( !error ) { error = cff_decoder_prepare( &decoder, size, glyph_index ); if ( !error ) error = cff_decoder_parse_charstrings( &decoder, charstring, charstring_len ); cff_free_glyph_data( face, &charstring, &charstring_len ); } /* ignore the error if one has occurred -- skip to next glyph */ error = FT_Err_Ok; } *max_advance = decoder.builder.advance.x; return FT_Err_Ok; } #endif /* 0 */ FT_LOCAL_DEF( FT_Error ) cff_slot_load( CFF_GlyphSlot glyph, CFF_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; CFF_Decoder decoder; TT_Face face = (TT_Face)glyph->root.face; FT_Bool hinting, scaled, force_scaling; CFF_Font cff = (CFF_Font)face->extra.data; FT_Matrix font_matrix; FT_Vector font_offset; force_scaling = FALSE; /* in a CID-keyed font, consider `glyph_index' as a CID and map */ /* it immediately to the real glyph_index -- if it isn't a */ /* subsetted font, glyph_indices and CIDs are identical, though */ if ( cff->top_font.font_dict.cid_registry != 0xFFFFU && cff->charset.cids ) { /* don't handle CID 0 (.notdef) which is directly mapped to GID 0 */ if ( glyph_index != 0 ) { glyph_index = cff_charset_cid_to_gindex( &cff->charset, glyph_index ); if ( glyph_index == 0 ) return FT_THROW( Invalid_Argument ); } } else if ( glyph_index >= cff->num_glyphs ) return FT_THROW( Invalid_Argument ); if ( load_flags & FT_LOAD_NO_RECURSE ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; glyph->x_scale = 0x10000L; glyph->y_scale = 0x10000L; if ( size ) { glyph->x_scale = size->root.metrics.x_scale; glyph->y_scale = size->root.metrics.y_scale; } #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS /* try to load embedded bitmap if any */ /* */ /* XXX: The convention should be emphasized in */ /* the documents because it can be confusing. */ if ( size ) { CFF_Face cff_face = (CFF_Face)size->root.face; SFNT_Service sfnt = (SFNT_Service)cff_face->sfnt; FT_Stream stream = cff_face->root.stream; if ( size->strike_index != 0xFFFFFFFFUL && sfnt->load_eblc && ( load_flags & FT_LOAD_NO_BITMAP ) == 0 ) { TT_SBit_MetricsRec metrics; error = sfnt->load_sbit_image( face, size->strike_index, glyph_index, (FT_Int)load_flags, stream, &glyph->root.bitmap, &metrics ); if ( !error ) { FT_Bool has_vertical_info; FT_UShort advance; FT_Short dummy; glyph->root.outline.n_points = 0; glyph->root.outline.n_contours = 0; glyph->root.metrics.width = (FT_Pos)metrics.width << 6; glyph->root.metrics.height = (FT_Pos)metrics.height << 6; glyph->root.metrics.horiBearingX = (FT_Pos)metrics.horiBearingX << 6; glyph->root.metrics.horiBearingY = (FT_Pos)metrics.horiBearingY << 6; glyph->root.metrics.horiAdvance = (FT_Pos)metrics.horiAdvance << 6; glyph->root.metrics.vertBearingX = (FT_Pos)metrics.vertBearingX << 6; glyph->root.metrics.vertBearingY = (FT_Pos)metrics.vertBearingY << 6; glyph->root.metrics.vertAdvance = (FT_Pos)metrics.vertAdvance << 6; glyph->root.format = FT_GLYPH_FORMAT_BITMAP; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { glyph->root.bitmap_left = metrics.vertBearingX; glyph->root.bitmap_top = metrics.vertBearingY; } else { glyph->root.bitmap_left = metrics.horiBearingX; glyph->root.bitmap_top = metrics.horiBearingY; } /* compute linear advance widths */ ( (SFNT_Service)face->sfnt )->get_metrics( face, 0, glyph_index, &dummy, &advance ); glyph->root.linearHoriAdvance = advance; has_vertical_info = FT_BOOL( face->vertical_info && face->vertical.number_Of_VMetrics > 0 ); /* get the vertical metrics from the vtmx table if we have one */ if ( has_vertical_info ) { ( (SFNT_Service)face->sfnt )->get_metrics( face, 1, glyph_index, &dummy, &advance ); glyph->root.linearVertAdvance = advance; } else { /* make up vertical ones */ if ( face->os2.version != 0xFFFFU ) glyph->root.linearVertAdvance = (FT_Pos) ( face->os2.sTypoAscender - face->os2.sTypoDescender ); else glyph->root.linearVertAdvance = (FT_Pos) ( face->horizontal.Ascender - face->horizontal.Descender ); } return error; } } } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ /* return immediately if we only want the embedded bitmaps */ if ( load_flags & FT_LOAD_SBITS_ONLY ) return FT_THROW( Invalid_Argument ); /* if we have a CID subfont, use its matrix (which has already */ /* been multiplied with the root matrix) */ /* this scaling is only relevant if the PS hinter isn't active */ if ( cff->num_subfonts ) { FT_ULong top_upm, sub_upm; FT_Byte fd_index = cff_fd_select_get( &cff->fd_select, glyph_index ); if ( fd_index >= cff->num_subfonts ) fd_index = (FT_Byte)( cff->num_subfonts - 1 ); top_upm = cff->top_font.font_dict.units_per_em; sub_upm = cff->subfonts[fd_index]->font_dict.units_per_em; font_matrix = cff->subfonts[fd_index]->font_dict.font_matrix; font_offset = cff->subfonts[fd_index]->font_dict.font_offset; if ( top_upm != sub_upm ) { glyph->x_scale = FT_MulDiv( glyph->x_scale, top_upm, sub_upm ); glyph->y_scale = FT_MulDiv( glyph->y_scale, top_upm, sub_upm ); force_scaling = TRUE; } } else { font_matrix = cff->top_font.font_dict.font_matrix; font_offset = cff->top_font.font_dict.font_offset; } glyph->root.outline.n_points = 0; glyph->root.outline.n_contours = 0; /* top-level code ensures that FT_LOAD_NO_HINTING is set */ /* if FT_LOAD_NO_SCALE is active */ hinting = FT_BOOL( ( load_flags & FT_LOAD_NO_HINTING ) == 0 ); scaled = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 ); glyph->hint = hinting; glyph->scaled = scaled; glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; /* by default */ { #ifdef CFF_CONFIG_OPTION_OLD_ENGINE CFF_Driver driver = (CFF_Driver)FT_FACE_DRIVER( face ); #endif FT_Byte* charstring; FT_ULong charstring_len; cff_decoder_init( &decoder, face, size, glyph, hinting, FT_LOAD_TARGET_MODE( load_flags ) ); if ( load_flags & FT_LOAD_ADVANCE_ONLY ) decoder.width_only = TRUE; decoder.builder.no_recurse = (FT_Bool)( load_flags & FT_LOAD_NO_RECURSE ); /* now load the unscaled outline */ error = cff_get_glyph_data( face, glyph_index, &charstring, &charstring_len ); if ( error ) goto Glyph_Build_Finished; error = cff_decoder_prepare( &decoder, size, glyph_index ); if ( error ) goto Glyph_Build_Finished; #ifdef CFF_CONFIG_OPTION_OLD_ENGINE /* choose which CFF renderer to use */ if ( driver->hinting_engine == FT_CFF_HINTING_FREETYPE ) error = cff_decoder_parse_charstrings( &decoder, charstring, charstring_len ); else #endif { error = cf2_decoder_parse_charstrings( &decoder, charstring, charstring_len ); /* Adobe's engine uses 16.16 numbers everywhere; */ /* as a consequence, glyphs larger than 2000ppem get rejected */ if ( FT_ERR_EQ( error, Glyph_Too_Big ) ) { /* this time, we retry unhinted and scale up the glyph later on */ /* (the engine uses and sets the hardcoded value 0x10000 / 64 = */ /* 0x400 for both `x_scale' and `y_scale' in this case) */ hinting = FALSE; force_scaling = TRUE; glyph->hint = hinting; error = cf2_decoder_parse_charstrings( &decoder, charstring, charstring_len ); } } cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Glyph_Build_Finished; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Control data and length may not be available for incremental */ /* fonts. */ if ( face->root.internal->incremental_interface ) { glyph->root.control_data = 0; glyph->root.control_len = 0; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /* We set control_data and control_len if charstrings is loaded. */ /* See how charstring loads at cff_index_access_element() in */ /* cffload.c. */ { CFF_Index csindex = &cff->charstrings_index; if ( csindex->offsets ) { glyph->root.control_data = csindex->bytes + csindex->offsets[glyph_index] - 1; glyph->root.control_len = charstring_len; } } Glyph_Build_Finished: /* save new glyph tables, if no error */ if ( !error ) cff_builder_done( &decoder.builder ); /* XXX: anything to do for broken glyph entry? */ } #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts can optionally override the metrics. */ if ( !error && face->root.internal->incremental_interface && face->root.internal->incremental_interface->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec metrics; metrics.bearing_x = decoder.builder.left_bearing.x; metrics.bearing_y = 0; metrics.advance = decoder.builder.advance.x; metrics.advance_v = decoder.builder.advance.y; error = face->root.internal->incremental_interface->funcs->get_glyph_metrics( face->root.internal->incremental_interface->object, glyph_index, FALSE, &metrics ); decoder.builder.left_bearing.x = metrics.bearing_x; decoder.builder.advance.x = metrics.advance; decoder.builder.advance.y = metrics.advance_v; } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ if ( !error ) { /* Now, set the metrics -- this is rather simple, as */ /* the left side bearing is the xMin, and the top side */ /* bearing the yMax. */ /* For composite glyphs, return only left side bearing and */ /* advance width. */ if ( load_flags & FT_LOAD_NO_RECURSE ) { FT_Slot_Internal internal = glyph->root.internal; glyph->root.metrics.horiBearingX = decoder.builder.left_bearing.x; glyph->root.metrics.horiAdvance = decoder.glyph_width; internal->glyph_matrix = font_matrix; internal->glyph_delta = font_offset; internal->glyph_transformed = 1; } else { FT_BBox cbox; FT_Glyph_Metrics* metrics = &glyph->root.metrics; FT_Vector advance; FT_Bool has_vertical_info; /* copy the _unscaled_ advance width */ metrics->horiAdvance = decoder.glyph_width; glyph->root.linearHoriAdvance = decoder.glyph_width; glyph->root.internal->glyph_transformed = 0; has_vertical_info = FT_BOOL( face->vertical_info && face->vertical.number_Of_VMetrics > 0 ); /* get the vertical metrics from the vtmx table if we have one */ if ( has_vertical_info ) { FT_Short vertBearingY = 0; FT_UShort vertAdvance = 0; ( (SFNT_Service)face->sfnt )->get_metrics( face, 1, glyph_index, &vertBearingY, &vertAdvance ); metrics->vertBearingY = vertBearingY; metrics->vertAdvance = vertAdvance; } else { /* make up vertical ones */ if ( face->os2.version != 0xFFFFU ) metrics->vertAdvance = (FT_Pos)( face->os2.sTypoAscender - face->os2.sTypoDescender ); else metrics->vertAdvance = (FT_Pos)( face->horizontal.Ascender - face->horizontal.Descender ); } glyph->root.linearVertAdvance = metrics->vertAdvance; glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; glyph->root.outline.flags = 0; if ( size && size->root.metrics.y_ppem < 24 ) glyph->root.outline.flags |= FT_OUTLINE_HIGH_PRECISION; glyph->root.outline.flags |= FT_OUTLINE_REVERSE_FILL; if ( !( font_matrix.xx == 0x10000L && font_matrix.yy == 0x10000L && font_matrix.xy == 0 && font_matrix.yx == 0 ) ) FT_Outline_Transform( &glyph->root.outline, &font_matrix ); if ( !( font_offset.x == 0 && font_offset.y == 0 ) ) FT_Outline_Translate( &glyph->root.outline, font_offset.x, font_offset.y ); advance.x = metrics->horiAdvance; advance.y = 0; FT_Vector_Transform( &advance, &font_matrix ); metrics->horiAdvance = advance.x + font_offset.x; advance.x = 0; advance.y = metrics->vertAdvance; FT_Vector_Transform( &advance, &font_matrix ); metrics->vertAdvance = advance.y + font_offset.y; if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 || force_scaling ) { /* scale the outline and the metrics */ FT_Int n; FT_Outline* cur = &glyph->root.outline; FT_Vector* vec = cur->points; FT_Fixed x_scale = glyph->x_scale; FT_Fixed y_scale = glyph->y_scale; /* First of all, scale the points */ if ( !hinting || !decoder.builder.hints_funcs ) for ( n = cur->n_points; n > 0; n--, vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } /* Then scale the metrics */ metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale ); } /* compute the other metrics */ FT_Outline_Get_CBox( &glyph->root.outline, &cbox ); metrics->width = cbox.xMax - cbox.xMin; metrics->height = cbox.yMax - cbox.yMin; metrics->horiBearingX = cbox.xMin; metrics->horiBearingY = cbox.yMax; if ( has_vertical_info ) metrics->vertBearingX = metrics->horiBearingX - metrics->horiAdvance / 2; else { if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) ft_synthesize_vertical_metrics( metrics, metrics->vertAdvance ); } } } return error; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffgload.c
C
apache-2.0
94,130
/***************************************************************************/ /* */ /* cffgload.h */ /* */ /* OpenType Glyph Loader (specification). */ /* */ /* Copyright 1996-2004, 2006-2009, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFGLOAD_H__ #define __CFFGLOAD_H__ #include <ft2build.h> #include FT_FREETYPE_H #include "cffobjs.h" FT_BEGIN_HEADER #define CFF_MAX_OPERANDS 48 #define CFF_MAX_SUBRS_CALLS 32 #define CFF_MAX_TRANS_ELEMENTS 32 /*************************************************************************/ /* */ /* <Structure> */ /* CFF_Builder */ /* */ /* <Description> */ /* A structure used during glyph loading to store its outline. */ /* */ /* <Fields> */ /* memory :: The current memory object. */ /* */ /* face :: The current face object. */ /* */ /* glyph :: The current glyph slot. */ /* */ /* loader :: The current glyph loader. */ /* */ /* base :: The base glyph outline. */ /* */ /* current :: The current glyph outline. */ /* */ /* pos_x :: The horizontal translation (if composite glyph). */ /* */ /* pos_y :: The vertical translation (if composite glyph). */ /* */ /* left_bearing :: The left side bearing point. */ /* */ /* advance :: The horizontal advance vector. */ /* */ /* bbox :: Unused. */ /* */ /* path_begun :: A flag which indicates that a new path has begun. */ /* */ /* load_points :: If this flag is not set, no points are loaded. */ /* */ /* no_recurse :: Set but not used. */ /* */ /* metrics_only :: A boolean indicating that we only want to compute */ /* the metrics of a given glyph, not load all of its */ /* points. */ /* */ /* hints_funcs :: Auxiliary pointer for hinting. */ /* */ /* hints_globals :: Auxiliary pointer for hinting. */ /* */ typedef struct CFF_Builder_ { FT_Memory memory; TT_Face face; CFF_GlyphSlot glyph; FT_GlyphLoader loader; FT_Outline* base; FT_Outline* current; FT_Pos pos_x; FT_Pos pos_y; FT_Vector left_bearing; FT_Vector advance; FT_BBox bbox; /* bounding box */ FT_Bool path_begun; FT_Bool load_points; FT_Bool no_recurse; FT_Bool metrics_only; void* hints_funcs; /* hinter-specific */ void* hints_globals; /* hinter-specific */ } CFF_Builder; FT_LOCAL( FT_Error ) cff_check_points( CFF_Builder* builder, FT_Int count ); FT_LOCAL( void ) cff_builder_add_point( CFF_Builder* builder, FT_Pos x, FT_Pos y, FT_Byte flag ); FT_LOCAL( FT_Error ) cff_builder_add_point1( CFF_Builder* builder, FT_Pos x, FT_Pos y ); FT_LOCAL( FT_Error ) cff_builder_start_point( CFF_Builder* builder, FT_Pos x, FT_Pos y ); FT_LOCAL( void ) cff_builder_close_contour( CFF_Builder* builder ); FT_LOCAL( FT_Int ) cff_lookup_glyph_by_stdcharcode( CFF_Font cff, FT_Int charcode ); FT_LOCAL( FT_Error ) cff_get_glyph_data( TT_Face face, FT_UInt glyph_index, FT_Byte** pointer, FT_ULong* length ); FT_LOCAL( void ) cff_free_glyph_data( TT_Face face, FT_Byte** pointer, FT_ULong length ); /* execution context charstring zone */ typedef struct CFF_Decoder_Zone_ { FT_Byte* base; FT_Byte* limit; FT_Byte* cursor; } CFF_Decoder_Zone; typedef struct CFF_Decoder_ { CFF_Builder builder; CFF_Font cff; FT_Fixed stack[CFF_MAX_OPERANDS + 1]; FT_Fixed* top; CFF_Decoder_Zone zones[CFF_MAX_SUBRS_CALLS + 1]; CFF_Decoder_Zone* zone; FT_Int flex_state; FT_Int num_flex_vectors; FT_Vector flex_vectors[7]; FT_Pos glyph_width; FT_Pos nominal_width; FT_Bool read_width; FT_Bool width_only; FT_Int num_hints; FT_Fixed buildchar[CFF_MAX_TRANS_ELEMENTS]; FT_UInt num_locals; FT_UInt num_globals; FT_Int locals_bias; FT_Int globals_bias; FT_Byte** locals; FT_Byte** globals; FT_Byte** glyph_names; /* for pure CFF fonts only */ FT_UInt num_glyphs; /* number of glyphs in font */ FT_Render_Mode hint_mode; FT_Bool seac; CFF_SubFont current_subfont; /* for current glyph_index */ } CFF_Decoder; FT_LOCAL( void ) cff_decoder_init( CFF_Decoder* decoder, TT_Face face, CFF_Size size, CFF_GlyphSlot slot, FT_Bool hinting, FT_Render_Mode hint_mode ); FT_LOCAL( FT_Error ) cff_decoder_prepare( CFF_Decoder* decoder, CFF_Size size, FT_UInt glyph_index ); #if 0 /* unused until we support pure CFF fonts */ /* Compute the maximum advance width of a font through quick parsing */ FT_LOCAL( FT_Error ) cff_compute_max_advance( TT_Face face, FT_Int* max_advance ); #endif /* 0 */ #ifdef CFF_CONFIG_OPTION_OLD_ENGINE FT_LOCAL( FT_Error ) cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ); #endif FT_LOCAL( FT_Error ) cff_slot_load( CFF_GlyphSlot glyph, CFF_Size size, FT_UInt glyph_index, FT_Int32 load_flags ); FT_END_HEADER #endif /* __CFFGLOAD_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffgload.h
C
apache-2.0
9,320
/***************************************************************************/ /* */ /* cffload.c */ /* */ /* OpenType and CFF data/program tables loader (body). */ /* */ /* Copyright 1996-2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_STREAM_H #include FT_TRUETYPE_TAGS_H #include FT_TYPE1_TABLES_H #include "cffload.h" #include "cffparse.h" #include "cfferrs.h" #if 1 static const FT_UShort cff_isoadobe_charset[229] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228 }; static const FT_UShort cff_expert_charset[166] = { 0, 1, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 }; static const FT_UShort cff_expertsubset_charset[87] = { 0, 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305, 314, 315, 158, 155, 163, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346 }; static const FT_UShort cff_standard_encoding[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0 }; static const FT_UShort cff_expert_encoding[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 229, 230, 0, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 0, 253, 254, 255, 256, 257, 0, 0, 0, 258, 0, 0, 259, 260, 261, 262, 0, 0, 263, 264, 265, 0, 266, 109, 110, 267, 268, 269, 0, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, 0, 0, 307, 308, 309, 310, 311, 0, 312, 0, 0, 312, 0, 0, 314, 315, 0, 0, 316, 317, 318, 0, 0, 0, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 0, 0, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 }; #endif /* 1 */ FT_LOCAL_DEF( FT_UShort ) cff_get_standard_encoding( FT_UInt charcode ) { return (FT_UShort)( charcode < 256 ? cff_standard_encoding[charcode] : 0 ); } /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffload /* read an offset from the index's stream current position */ static FT_ULong cff_index_read_offset( CFF_Index idx, FT_Error *errorp ) { FT_Error error = FT_Err_Ok; FT_Stream stream = idx->stream; FT_Byte tmp[4]; FT_ULong result = 0; if ( !FT_STREAM_READ( tmp, idx->off_size ) ) { FT_Int nn; for ( nn = 0; nn < idx->off_size; nn++ ) result = ( result << 8 ) | tmp[nn]; } *errorp = error; return result; } static FT_Error cff_index_init( CFF_Index idx, FT_Stream stream, FT_Bool load ) { FT_Error error; FT_Memory memory = stream->memory; FT_UShort count; FT_MEM_ZERO( idx, sizeof ( *idx ) ); idx->stream = stream; idx->start = FT_STREAM_POS(); if ( !FT_READ_USHORT( count ) && count > 0 ) { FT_Byte offsize; FT_ULong size; /* there is at least one element; read the offset size, */ /* then access the offset table to compute the index's total size */ if ( FT_READ_BYTE( offsize ) ) goto Exit; if ( offsize < 1 || offsize > 4 ) { error = FT_THROW( Invalid_Table ); goto Exit; } idx->count = count; idx->off_size = offsize; size = (FT_ULong)( count + 1 ) * offsize; idx->data_offset = idx->start + 3 + size; if ( FT_STREAM_SKIP( size - offsize ) ) goto Exit; size = cff_index_read_offset( idx, &error ); if ( error ) goto Exit; if ( size == 0 ) { error = FT_THROW( Invalid_Table ); goto Exit; } idx->data_size = --size; if ( load ) { /* load the data */ if ( FT_FRAME_EXTRACT( size, idx->bytes ) ) goto Exit; } else { /* skip the data */ if ( FT_STREAM_SKIP( size ) ) goto Exit; } } Exit: if ( error ) FT_FREE( idx->offsets ); return error; } static void cff_index_done( CFF_Index idx ) { if ( idx->stream ) { FT_Stream stream = idx->stream; FT_Memory memory = stream->memory; if ( idx->bytes ) FT_FRAME_RELEASE( idx->bytes ); FT_FREE( idx->offsets ); FT_MEM_ZERO( idx, sizeof ( *idx ) ); } } static FT_Error cff_index_load_offsets( CFF_Index idx ) { FT_Error error = FT_Err_Ok; FT_Stream stream = idx->stream; FT_Memory memory = stream->memory; if ( idx->count > 0 && idx->offsets == NULL ) { FT_Byte offsize = idx->off_size; FT_ULong data_size; FT_Byte* p; FT_Byte* p_end; FT_ULong* poff; data_size = (FT_ULong)( idx->count + 1 ) * offsize; if ( FT_NEW_ARRAY( idx->offsets, idx->count + 1 ) || FT_STREAM_SEEK( idx->start + 3 ) || FT_FRAME_ENTER( data_size ) ) goto Exit; poff = idx->offsets; p = (FT_Byte*)stream->cursor; p_end = p + data_size; switch ( offsize ) { case 1: for ( ; p < p_end; p++, poff++ ) poff[0] = p[0]; break; case 2: for ( ; p < p_end; p += 2, poff++ ) poff[0] = FT_PEEK_USHORT( p ); break; case 3: for ( ; p < p_end; p += 3, poff++ ) poff[0] = FT_PEEK_OFF3( p ); break; default: for ( ; p < p_end; p += 4, poff++ ) poff[0] = FT_PEEK_ULONG( p ); } FT_FRAME_EXIT(); } Exit: if ( error ) FT_FREE( idx->offsets ); return error; } /* Allocate a table containing pointers to an index's elements. */ /* The `pool' argument makes this function convert the index */ /* entries to C-style strings (this is, NULL-terminated). */ static FT_Error cff_index_get_pointers( CFF_Index idx, FT_Byte*** table, FT_Byte** pool ) { FT_Error error = FT_Err_Ok; FT_Memory memory = idx->stream->memory; FT_Byte** t = NULL; FT_Byte* new_bytes = NULL; *table = NULL; if ( idx->offsets == NULL ) { error = cff_index_load_offsets( idx ); if ( error ) goto Exit; } if ( idx->count > 0 && !FT_NEW_ARRAY( t, idx->count + 1 ) && ( !pool || !FT_ALLOC( new_bytes, idx->data_size + idx->count ) ) ) { FT_ULong n, cur_offset; FT_ULong extra = 0; FT_Byte* org_bytes = idx->bytes; /* at this point, `idx->offsets' can't be NULL */ cur_offset = idx->offsets[0] - 1; /* sanity check */ if ( cur_offset != 0 ) { FT_TRACE0(( "cff_index_get_pointers:" " invalid first offset value %d set to zero\n", cur_offset )); cur_offset = 0; } if ( !pool ) t[0] = org_bytes + cur_offset; else t[0] = new_bytes + cur_offset; for ( n = 1; n <= idx->count; n++ ) { FT_ULong next_offset = idx->offsets[n] - 1; /* two sanity checks for invalid offset tables */ if ( next_offset < cur_offset ) next_offset = cur_offset; else if ( next_offset > idx->data_size ) next_offset = idx->data_size; if ( !pool ) t[n] = org_bytes + next_offset; else { t[n] = new_bytes + next_offset + extra; if ( next_offset != cur_offset ) { FT_MEM_COPY( t[n - 1], org_bytes + cur_offset, t[n] - t[n - 1] ); t[n][0] = '\0'; t[n] += 1; extra++; } } cur_offset = next_offset; } *table = t; if ( pool ) *pool = new_bytes; } Exit: return error; } FT_LOCAL_DEF( FT_Error ) cff_index_access_element( CFF_Index idx, FT_UInt element, FT_Byte** pbytes, FT_ULong* pbyte_len ) { FT_Error error = FT_Err_Ok; if ( idx && idx->count > element ) { /* compute start and end offsets */ FT_Stream stream = idx->stream; FT_ULong off1, off2 = 0; /* load offsets from file or the offset table */ if ( !idx->offsets ) { FT_ULong pos = element * idx->off_size; if ( FT_STREAM_SEEK( idx->start + 3 + pos ) ) goto Exit; off1 = cff_index_read_offset( idx, &error ); if ( error ) goto Exit; if ( off1 != 0 ) { do { element++; off2 = cff_index_read_offset( idx, &error ); } while ( off2 == 0 && element < idx->count ); } } else /* use offsets table */ { off1 = idx->offsets[element]; if ( off1 ) { do { element++; off2 = idx->offsets[element]; } while ( off2 == 0 && element < idx->count ); } } /* XXX: should check off2 does not exceed the end of this entry; */ /* at present, only truncate off2 at the end of this stream */ if ( off2 > stream->size + 1 || idx->data_offset > stream->size - off2 + 1 ) { FT_ERROR(( "cff_index_access_element:" " offset to next entry (%d)" " exceeds the end of stream (%d)\n", off2, stream->size - idx->data_offset + 1 )); off2 = stream->size - idx->data_offset + 1; } /* access element */ if ( off1 && off2 > off1 ) { *pbyte_len = off2 - off1; if ( idx->bytes ) { /* this index was completely loaded in memory, that's easy */ *pbytes = idx->bytes + off1 - 1; } else { /* this index is still on disk/file, access it through a frame */ if ( FT_STREAM_SEEK( idx->data_offset + off1 - 1 ) || FT_FRAME_EXTRACT( off2 - off1, *pbytes ) ) goto Exit; } } else { /* empty index element */ *pbytes = 0; *pbyte_len = 0; } } else error = FT_THROW( Invalid_Argument ); Exit: return error; } FT_LOCAL_DEF( void ) cff_index_forget_element( CFF_Index idx, FT_Byte** pbytes ) { if ( idx->bytes == 0 ) { FT_Stream stream = idx->stream; FT_FRAME_RELEASE( *pbytes ); } } /* get an entry from Name INDEX */ FT_LOCAL_DEF( FT_String* ) cff_index_get_name( CFF_Font font, FT_UInt element ) { CFF_Index idx = &font->name_index; FT_Memory memory = idx->stream->memory; FT_Byte* bytes; FT_ULong byte_len; FT_Error error; FT_String* name = 0; error = cff_index_access_element( idx, element, &bytes, &byte_len ); if ( error ) goto Exit; if ( !FT_ALLOC( name, byte_len + 1 ) ) { FT_MEM_COPY( name, bytes, byte_len ); name[byte_len] = 0; } cff_index_forget_element( idx, &bytes ); Exit: return name; } /* get an entry from String INDEX */ FT_LOCAL_DEF( FT_String* ) cff_index_get_string( CFF_Font font, FT_UInt element ) { return ( element < font->num_strings ) ? (FT_String*)font->strings[element] : NULL; } FT_LOCAL_DEF( FT_String* ) cff_index_get_sid_string( CFF_Font font, FT_UInt sid ) { /* value 0xFFFFU indicates a missing dictionary entry */ if ( sid == 0xFFFFU ) return NULL; /* if it is not a standard string, return it */ if ( sid > 390 ) return cff_index_get_string( font, sid - 391 ); /* CID-keyed CFF fonts don't have glyph names */ if ( !font->psnames ) return NULL; /* this is a standard string */ return (FT_String *)font->psnames->adobe_std_strings( sid ); } /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** FD Select table support ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ static void CFF_Done_FD_Select( CFF_FDSelect fdselect, FT_Stream stream ) { if ( fdselect->data ) FT_FRAME_RELEASE( fdselect->data ); fdselect->data_size = 0; fdselect->format = 0; fdselect->range_count = 0; } static FT_Error CFF_Load_FD_Select( CFF_FDSelect fdselect, FT_UInt num_glyphs, FT_Stream stream, FT_ULong offset ) { FT_Error error; FT_Byte format; FT_UInt num_ranges; /* read format */ if ( FT_STREAM_SEEK( offset ) || FT_READ_BYTE( format ) ) goto Exit; fdselect->format = format; fdselect->cache_count = 0; /* clear cache */ switch ( format ) { case 0: /* format 0, that's simple */ fdselect->data_size = num_glyphs; goto Load_Data; case 3: /* format 3, a tad more complex */ if ( FT_READ_USHORT( num_ranges ) ) goto Exit; if ( !num_ranges ) { FT_TRACE0(( "CFF_Load_FD_Select: empty FDSelect array\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } fdselect->data_size = num_ranges * 3 + 2; Load_Data: if ( FT_FRAME_EXTRACT( fdselect->data_size, fdselect->data ) ) goto Exit; break; default: /* hmm... that's wrong */ error = FT_THROW( Invalid_File_Format ); } Exit: return error; } FT_LOCAL_DEF( FT_Byte ) cff_fd_select_get( CFF_FDSelect fdselect, FT_UInt glyph_index ) { FT_Byte fd = 0; switch ( fdselect->format ) { case 0: fd = fdselect->data[glyph_index]; break; case 3: /* first, compare to the cache */ if ( (FT_UInt)( glyph_index - fdselect->cache_first ) < fdselect->cache_count ) { fd = fdselect->cache_fd; break; } /* then, look up the ranges array */ { FT_Byte* p = fdselect->data; FT_Byte* p_limit = p + fdselect->data_size; FT_Byte fd2; FT_UInt first, limit; first = FT_NEXT_USHORT( p ); do { if ( glyph_index < first ) break; fd2 = *p++; limit = FT_NEXT_USHORT( p ); if ( glyph_index < limit ) { fd = fd2; /* update cache */ fdselect->cache_first = first; fdselect->cache_count = limit - first; fdselect->cache_fd = fd2; break; } first = limit; } while ( p < p_limit ); } break; default: ; } return fd; } /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** CFF font support ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ static FT_Error cff_charset_compute_cids( CFF_Charset charset, FT_UInt num_glyphs, FT_Memory memory ) { FT_Error error = FT_Err_Ok; FT_UInt i; FT_Long j; FT_UShort max_cid = 0; if ( charset->max_cid > 0 ) goto Exit; for ( i = 0; i < num_glyphs; i++ ) { if ( charset->sids[i] > max_cid ) max_cid = charset->sids[i]; } if ( FT_NEW_ARRAY( charset->cids, (FT_ULong)max_cid + 1 ) ) goto Exit; /* When multiple GIDs map to the same CID, we choose the lowest */ /* GID. This is not described in any spec, but it matches the */ /* behaviour of recent Acroread versions. */ for ( j = num_glyphs - 1; j >= 0 ; j-- ) charset->cids[charset->sids[j]] = (FT_UShort)j; charset->max_cid = max_cid; charset->num_glyphs = num_glyphs; Exit: return error; } FT_LOCAL_DEF( FT_UInt ) cff_charset_cid_to_gindex( CFF_Charset charset, FT_UInt cid ) { FT_UInt result = 0; if ( cid <= charset->max_cid ) result = charset->cids[cid]; return result; } static void cff_charset_free_cids( CFF_Charset charset, FT_Memory memory ) { FT_FREE( charset->cids ); charset->max_cid = 0; } static void cff_charset_done( CFF_Charset charset, FT_Stream stream ) { FT_Memory memory = stream->memory; cff_charset_free_cids( charset, memory ); FT_FREE( charset->sids ); charset->format = 0; charset->offset = 0; } static FT_Error cff_charset_load( CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset, FT_Bool invert ) { FT_Memory memory = stream->memory; FT_Error error = FT_Err_Ok; FT_UShort glyph_sid; /* If the the offset is greater than 2, we have to parse the */ /* charset table. */ if ( offset > 2 ) { FT_UInt j; charset->offset = base_offset + offset; /* Get the format of the table. */ if ( FT_STREAM_SEEK( charset->offset ) || FT_READ_BYTE( charset->format ) ) goto Exit; /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* assign the .notdef glyph */ charset->sids[0] = 0; switch ( charset->format ) { case 0: if ( num_glyphs > 0 ) { if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) ) goto Exit; for ( j = 1; j < num_glyphs; j++ ) charset->sids[j] = FT_GET_USHORT(); FT_FRAME_EXIT(); } break; case 1: case 2: { FT_UInt nleft; FT_UInt i; j = 1; while ( j < num_glyphs ) { /* Read the first glyph sid of the range. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Read the number of glyphs in the range. */ if ( charset->format == 2 ) { if ( FT_READ_USHORT( nleft ) ) goto Exit; } else { if ( FT_READ_BYTE( nleft ) ) goto Exit; } /* try to rescue some of the SIDs if `nleft' is too large */ if ( glyph_sid > 0xFFFFL - nleft ) { FT_ERROR(( "cff_charset_load: invalid SID range trimmed" " nleft=%d -> %d\n", nleft, 0xFFFFL - glyph_sid )); nleft = ( FT_UInt )( 0xFFFFL - glyph_sid ); } /* Fill in the range of sids -- `nleft + 1' glyphs. */ for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ ) charset->sids[j] = glyph_sid; } } break; default: FT_ERROR(( "cff_charset_load: invalid table format\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } } else { /* Parse default tables corresponding to offset == 0, 1, or 2. */ /* CFF specification intimates the following: */ /* */ /* In order to use a predefined charset, the following must be */ /* true: The charset constructed for the glyphs in the font's */ /* charstrings dictionary must match the predefined charset in */ /* the first num_glyphs. */ charset->offset = offset; /* record charset type */ switch ( (FT_UInt)offset ) { case 0: if ( num_glyphs > 229 ) { FT_ERROR(( "cff_charset_load: implicit charset larger than\n" "predefined charset (Adobe ISO-Latin)\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* Copy the predefined charset into the allocated memory. */ FT_ARRAY_COPY( charset->sids, cff_isoadobe_charset, num_glyphs ); break; case 1: if ( num_glyphs > 166 ) { FT_ERROR(( "cff_charset_load: implicit charset larger than\n" "predefined charset (Adobe Expert)\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* Copy the predefined charset into the allocated memory. */ FT_ARRAY_COPY( charset->sids, cff_expert_charset, num_glyphs ); break; case 2: if ( num_glyphs > 87 ) { FT_ERROR(( "cff_charset_load: implicit charset larger than\n" "predefined charset (Adobe Expert Subset)\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* Copy the predefined charset into the allocated memory. */ FT_ARRAY_COPY( charset->sids, cff_expertsubset_charset, num_glyphs ); break; default: error = FT_THROW( Invalid_File_Format ); goto Exit; } } /* we have to invert the `sids' array for subsetted CID-keyed fonts */ if ( invert ) error = cff_charset_compute_cids( charset, num_glyphs, memory ); Exit: /* Clean up if there was an error. */ if ( error ) { FT_FREE( charset->sids ); FT_FREE( charset->cids ); charset->format = 0; charset->offset = 0; charset->sids = 0; } return error; } static void cff_encoding_done( CFF_Encoding encoding ) { encoding->format = 0; encoding->offset = 0; encoding->count = 0; } static FT_Error cff_encoding_load( CFF_Encoding encoding, CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset ) { FT_Error error = FT_Err_Ok; FT_UInt count; FT_UInt j; FT_UShort glyph_sid; FT_UInt glyph_code; /* Check for charset->sids. If we do not have this, we fail. */ if ( !charset->sids ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Zero out the code to gid/sid mappings. */ for ( j = 0; j < 256; j++ ) { encoding->sids [j] = 0; encoding->codes[j] = 0; } /* Note: The encoding table in a CFF font is indexed by glyph index; */ /* the first encoded glyph index is 1. Hence, we read the character */ /* code (`glyph_code') at index j and make the assignment: */ /* */ /* encoding->codes[glyph_code] = j + 1 */ /* */ /* We also make the assignment: */ /* */ /* encoding->sids[glyph_code] = charset->sids[j + 1] */ /* */ /* This gives us both a code to GID and a code to SID mapping. */ if ( offset > 1 ) { encoding->offset = base_offset + offset; /* we need to parse the table to determine its size */ if ( FT_STREAM_SEEK( encoding->offset ) || FT_READ_BYTE( encoding->format ) || FT_READ_BYTE( count ) ) goto Exit; switch ( encoding->format & 0x7F ) { case 0: { FT_Byte* p; /* By convention, GID 0 is always ".notdef" and is never */ /* coded in the font. Hence, the number of codes found */ /* in the table is `count+1'. */ /* */ encoding->count = count + 1; if ( FT_FRAME_ENTER( count ) ) goto Exit; p = (FT_Byte*)stream->cursor; for ( j = 1; j <= count; j++ ) { glyph_code = *p++; /* Make sure j is not too big. */ if ( j < num_glyphs ) { /* Assign code to GID mapping. */ encoding->codes[glyph_code] = (FT_UShort)j; /* Assign code to SID mapping. */ encoding->sids[glyph_code] = charset->sids[j]; } } FT_FRAME_EXIT(); } break; case 1: { FT_UInt nleft; FT_UInt i = 1; FT_UInt k; encoding->count = 0; /* Parse the Format1 ranges. */ for ( j = 0; j < count; j++, i += nleft ) { /* Read the first glyph code of the range. */ if ( FT_READ_BYTE( glyph_code ) ) goto Exit; /* Read the number of codes in the range. */ if ( FT_READ_BYTE( nleft ) ) goto Exit; /* Increment nleft, so we read `nleft + 1' codes/sids. */ nleft++; /* compute max number of character codes */ if ( (FT_UInt)nleft > encoding->count ) encoding->count = nleft; /* Fill in the range of codes/sids. */ for ( k = i; k < nleft + i; k++, glyph_code++ ) { /* Make sure k is not too big. */ if ( k < num_glyphs && glyph_code < 256 ) { /* Assign code to GID mapping. */ encoding->codes[glyph_code] = (FT_UShort)k; /* Assign code to SID mapping. */ encoding->sids[glyph_code] = charset->sids[k]; } } } /* simple check; one never knows what can be found in a font */ if ( encoding->count > 256 ) encoding->count = 256; } break; default: FT_ERROR(( "cff_encoding_load: invalid table format\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* Parse supplemental encodings, if any. */ if ( encoding->format & 0x80 ) { FT_UInt gindex; /* count supplements */ if ( FT_READ_BYTE( count ) ) goto Exit; for ( j = 0; j < count; j++ ) { /* Read supplemental glyph code. */ if ( FT_READ_BYTE( glyph_code ) ) goto Exit; /* Read the SID associated with this glyph code. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Assign code to SID mapping. */ encoding->sids[glyph_code] = glyph_sid; /* First, look up GID which has been assigned to */ /* SID glyph_sid. */ for ( gindex = 0; gindex < num_glyphs; gindex++ ) { if ( charset->sids[gindex] == glyph_sid ) { encoding->codes[glyph_code] = (FT_UShort)gindex; break; } } } } } else { /* We take into account the fact a CFF font can use a predefined */ /* encoding without containing all of the glyphs encoded by this */ /* encoding (see the note at the end of section 12 in the CFF */ /* specification). */ switch ( (FT_UInt)offset ) { case 0: /* First, copy the code to SID mapping. */ FT_ARRAY_COPY( encoding->sids, cff_standard_encoding, 256 ); goto Populate; case 1: /* First, copy the code to SID mapping. */ FT_ARRAY_COPY( encoding->sids, cff_expert_encoding, 256 ); Populate: /* Construct code to GID mapping from code to SID mapping */ /* and charset. */ encoding->count = 0; error = cff_charset_compute_cids( charset, num_glyphs, stream->memory ); if ( error ) goto Exit; for ( j = 0; j < 256; j++ ) { FT_UInt sid = encoding->sids[j]; FT_UInt gid = 0; if ( sid ) gid = cff_charset_cid_to_gindex( charset, sid ); if ( gid != 0 ) { encoding->codes[j] = (FT_UShort)gid; encoding->count = j + 1; } else { encoding->codes[j] = 0; encoding->sids [j] = 0; } } break; default: FT_ERROR(( "cff_encoding_load: invalid table format\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } } Exit: /* Clean up if there was an error. */ return error; } static FT_Error cff_subfont_load( CFF_SubFont font, CFF_Index idx, FT_UInt font_index, FT_Stream stream, FT_ULong base_offset, FT_Library library ) { FT_Error error; CFF_ParserRec parser; FT_Byte* dict = NULL; FT_ULong dict_len; CFF_FontRecDict top = &font->font_dict; CFF_Private priv = &font->private_dict; cff_parser_init( &parser, CFF_CODE_TOPDICT, &font->font_dict, library ); /* set defaults */ FT_MEM_ZERO( top, sizeof ( *top ) ); top->underline_position = -( 100L << 16 ); top->underline_thickness = 50L << 16; top->charstring_type = 2; top->font_matrix.xx = 0x10000L; top->font_matrix.yy = 0x10000L; top->cid_count = 8720; /* we use the implementation specific SID value 0xFFFF to indicate */ /* missing entries */ top->version = 0xFFFFU; top->notice = 0xFFFFU; top->copyright = 0xFFFFU; top->full_name = 0xFFFFU; top->family_name = 0xFFFFU; top->weight = 0xFFFFU; top->embedded_postscript = 0xFFFFU; top->cid_registry = 0xFFFFU; top->cid_ordering = 0xFFFFU; top->cid_font_name = 0xFFFFU; error = cff_index_access_element( idx, font_index, &dict, &dict_len ); if ( !error ) { FT_TRACE4(( " top dictionary:\n" )); error = cff_parser_run( &parser, dict, dict + dict_len ); } cff_index_forget_element( idx, &dict ); if ( error ) goto Exit; /* if it is a CID font, we stop there */ if ( top->cid_registry != 0xFFFFU ) goto Exit; /* parse the private dictionary, if any */ if ( top->private_offset && top->private_size ) { /* set defaults */ FT_MEM_ZERO( priv, sizeof ( *priv ) ); priv->blue_shift = 7; priv->blue_fuzz = 1; priv->lenIV = -1; priv->expansion_factor = (FT_Fixed)( 0.06 * 0x10000L ); priv->blue_scale = (FT_Fixed)( 0.039625 * 0x10000L * 1000 ); cff_parser_init( &parser, CFF_CODE_PRIVATE, priv, library ); if ( FT_STREAM_SEEK( base_offset + font->font_dict.private_offset ) || FT_FRAME_ENTER( font->font_dict.private_size ) ) goto Exit; FT_TRACE4(( " private dictionary:\n" )); error = cff_parser_run( &parser, (FT_Byte*)stream->cursor, (FT_Byte*)stream->limit ); FT_FRAME_EXIT(); if ( error ) goto Exit; /* ensure that `num_blue_values' is even */ priv->num_blue_values &= ~1; } /* read the local subrs, if any */ if ( priv->local_subrs_offset ) { if ( FT_STREAM_SEEK( base_offset + top->private_offset + priv->local_subrs_offset ) ) goto Exit; error = cff_index_init( &font->local_subrs_index, stream, 1 ); if ( error ) goto Exit; error = cff_index_get_pointers( &font->local_subrs_index, &font->local_subrs, NULL ); if ( error ) goto Exit; } Exit: return error; } static void cff_subfont_done( FT_Memory memory, CFF_SubFont subfont ) { if ( subfont ) { cff_index_done( &subfont->local_subrs_index ); FT_FREE( subfont->local_subrs ); } } FT_LOCAL_DEF( FT_Error ) cff_font_load( FT_Library library, FT_Stream stream, FT_Int face_index, CFF_Font font, FT_Bool pure_cff ) { static const FT_Frame_Field cff_header_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE CFF_FontRec FT_FRAME_START( 4 ), FT_FRAME_BYTE( version_major ), FT_FRAME_BYTE( version_minor ), FT_FRAME_BYTE( header_size ), FT_FRAME_BYTE( absolute_offsize ), FT_FRAME_END }; FT_Error error; FT_Memory memory = stream->memory; FT_ULong base_offset; CFF_FontRecDict dict; CFF_IndexRec string_index; FT_Int subfont_index; FT_ZERO( font ); FT_ZERO( &string_index ); font->stream = stream; font->memory = memory; dict = &font->top_font.font_dict; base_offset = FT_STREAM_POS(); /* read CFF font header */ if ( FT_STREAM_READ_FIELDS( cff_header_fields, font ) ) goto Exit; /* check format */ if ( font->version_major != 1 || font->header_size < 4 || font->absolute_offsize > 4 ) { FT_TRACE2(( " not a CFF font header\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* skip the rest of the header */ if ( FT_STREAM_SKIP( font->header_size - 4 ) ) goto Exit; /* read the name, top dict, string and global subrs index */ if ( FT_SET_ERROR( cff_index_init( &font->name_index, stream, 0 ) ) || FT_SET_ERROR( cff_index_init( &font->font_dict_index, stream, 0 ) ) || FT_SET_ERROR( cff_index_init( &string_index, stream, 1 ) ) || FT_SET_ERROR( cff_index_init( &font->global_subrs_index, stream, 1 ) ) || FT_SET_ERROR( cff_index_get_pointers( &string_index, &font->strings, &font->string_pool ) ) ) goto Exit; font->num_strings = string_index.count; if ( pure_cff ) { /* well, we don't really forget the `disabled' fonts... */ subfont_index = face_index; if ( subfont_index >= (FT_Int)font->name_index.count ) { FT_ERROR(( "cff_font_load:" " invalid subfont index for pure CFF font (%d)\n", subfont_index )); error = FT_THROW( Invalid_Argument ); goto Exit; } font->num_faces = font->name_index.count; } else { subfont_index = 0; if ( font->name_index.count > 1 ) { FT_ERROR(( "cff_font_load:" " invalid CFF font with multiple subfonts\n" " " " in SFNT wrapper\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } } /* in case of a font format check, simply exit now */ if ( face_index < 0 ) goto Exit; /* now, parse the top-level font dictionary */ FT_TRACE4(( "parsing top-level\n" )); error = cff_subfont_load( &font->top_font, &font->font_dict_index, subfont_index, stream, base_offset, library ); if ( error ) goto Exit; if ( FT_STREAM_SEEK( base_offset + dict->charstrings_offset ) ) goto Exit; error = cff_index_init( &font->charstrings_index, stream, 0 ); if ( error ) goto Exit; /* now, check for a CID font */ if ( dict->cid_registry != 0xFFFFU ) { CFF_IndexRec fd_index; CFF_SubFont sub = NULL; FT_UInt idx; /* this is a CID-keyed font, we must now allocate a table of */ /* sub-fonts, then load each of them separately */ if ( FT_STREAM_SEEK( base_offset + dict->cid_fd_array_offset ) ) goto Exit; error = cff_index_init( &fd_index, stream, 0 ); if ( error ) goto Exit; if ( fd_index.count > CFF_MAX_CID_FONTS ) { FT_TRACE0(( "cff_font_load: FD array too large in CID font\n" )); goto Fail_CID; } /* allocate & read each font dict independently */ font->num_subfonts = fd_index.count; if ( FT_NEW_ARRAY( sub, fd_index.count ) ) goto Fail_CID; /* set up pointer table */ for ( idx = 0; idx < fd_index.count; idx++ ) font->subfonts[idx] = sub + idx; /* now load each subfont independently */ for ( idx = 0; idx < fd_index.count; idx++ ) { sub = font->subfonts[idx]; FT_TRACE4(( "parsing subfont %u\n", idx )); error = cff_subfont_load( sub, &fd_index, idx, stream, base_offset, library ); if ( error ) goto Fail_CID; } /* now load the FD Select array */ error = CFF_Load_FD_Select( &font->fd_select, font->charstrings_index.count, stream, base_offset + dict->cid_fd_select_offset ); Fail_CID: cff_index_done( &fd_index ); if ( error ) goto Exit; } else font->num_subfonts = 0; /* read the charstrings index now */ if ( dict->charstrings_offset == 0 ) { FT_ERROR(( "cff_font_load: no charstrings offset\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } font->num_glyphs = font->charstrings_index.count; error = cff_index_get_pointers( &font->global_subrs_index, &font->global_subrs, NULL ); if ( error ) goto Exit; /* read the Charset and Encoding tables if available */ if ( font->num_glyphs > 0 ) { FT_Bool invert = FT_BOOL( dict->cid_registry != 0xFFFFU && pure_cff ); error = cff_charset_load( &font->charset, font->num_glyphs, stream, base_offset, dict->charset_offset, invert ); if ( error ) goto Exit; /* CID-keyed CFFs don't have an encoding */ if ( dict->cid_registry == 0xFFFFU ) { error = cff_encoding_load( &font->encoding, &font->charset, font->num_glyphs, stream, base_offset, dict->encoding_offset ); if ( error ) goto Exit; } } /* get the font name (/CIDFontName for CID-keyed fonts, */ /* /FontName otherwise) */ font->font_name = cff_index_get_name( font, subfont_index ); Exit: cff_index_done( &string_index ); return error; } FT_LOCAL_DEF( void ) cff_font_done( CFF_Font font ) { FT_Memory memory = font->memory; FT_UInt idx; cff_index_done( &font->global_subrs_index ); cff_index_done( &font->font_dict_index ); cff_index_done( &font->name_index ); cff_index_done( &font->charstrings_index ); /* release font dictionaries, but only if working with */ /* a CID keyed CFF font */ if ( font->num_subfonts > 0 ) { for ( idx = 0; idx < font->num_subfonts; idx++ ) cff_subfont_done( memory, font->subfonts[idx] ); /* the subfonts array has been allocated as a single block */ FT_FREE( font->subfonts[0] ); } cff_encoding_done( &font->encoding ); cff_charset_done( &font->charset, font->stream ); cff_subfont_done( memory, &font->top_font ); CFF_Done_FD_Select( &font->fd_select, font->stream ); FT_FREE( font->font_info ); FT_FREE( font->font_name ); FT_FREE( font->global_subrs ); FT_FREE( font->strings ); FT_FREE( font->string_pool ); if ( font->cf2_instance.finalizer ) { font->cf2_instance.finalizer( font->cf2_instance.data ); FT_FREE( font->cf2_instance.data ); } } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffload.c
C
apache-2.0
48,426
/***************************************************************************/ /* */ /* cffload.h */ /* */ /* OpenType & CFF data/program tables loader (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFLOAD_H__ #define __CFFLOAD_H__ #include <ft2build.h> #include "cfftypes.h" FT_BEGIN_HEADER FT_LOCAL( FT_UShort ) cff_get_standard_encoding( FT_UInt charcode ); FT_LOCAL( FT_String* ) cff_index_get_string( CFF_Font font, FT_UInt element ); FT_LOCAL( FT_String* ) cff_index_get_sid_string( CFF_Font font, FT_UInt sid ); FT_LOCAL( FT_Error ) cff_index_access_element( CFF_Index idx, FT_UInt element, FT_Byte** pbytes, FT_ULong* pbyte_len ); FT_LOCAL( void ) cff_index_forget_element( CFF_Index idx, FT_Byte** pbytes ); FT_LOCAL( FT_String* ) cff_index_get_name( CFF_Font font, FT_UInt element ); FT_LOCAL( FT_UInt ) cff_charset_cid_to_gindex( CFF_Charset charset, FT_UInt cid ); FT_LOCAL( FT_Error ) cff_font_load( FT_Library library, FT_Stream stream, FT_Int face_index, CFF_Font font, FT_Bool pure_cff ); FT_LOCAL( void ) cff_font_done( CFF_Font font ); FT_LOCAL( FT_Byte ) cff_fd_select_get( CFF_FDSelect fdselect, FT_UInt glyph_index ); FT_END_HEADER #endif /* __CFFLOAD_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffload.h
C
apache-2.0
2,662
/***************************************************************************/ /* */ /* cffobjs.c */ /* */ /* OpenType objects manager (body). */ /* */ /* Copyright 1996-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_CALC_H #include FT_INTERNAL_STREAM_H #include FT_ERRORS_H #include FT_TRUETYPE_IDS_H #include FT_TRUETYPE_TAGS_H #include FT_INTERNAL_SFNT_H #include FT_CFF_DRIVER_H #include "cffobjs.h" #include "cffload.h" #include "cffcmap.h" #include "cffpic.h" #include "cfferrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffobjs /*************************************************************************/ /* */ /* SIZE FUNCTIONS */ /* */ /* Note that we store the global hints in the size's `internal' root */ /* field. */ /* */ /*************************************************************************/ static PSH_Globals_Funcs cff_size_get_globals_funcs( CFF_Size size ) { CFF_Face face = (CFF_Face)size->root.face; CFF_Font font = (CFF_Font)face->extra.data; PSHinter_Service pshinter = font->pshinter; FT_Module module; module = FT_Get_Module( size->root.face->driver->root.library, "pshinter" ); return ( module && pshinter && pshinter->get_globals_funcs ) ? pshinter->get_globals_funcs( module ) : 0; } FT_LOCAL_DEF( void ) cff_size_done( FT_Size cffsize ) /* CFF_Size */ { CFF_Size size = (CFF_Size)cffsize; CFF_Face face = (CFF_Face)size->root.face; CFF_Font font = (CFF_Font)face->extra.data; CFF_Internal internal = (CFF_Internal)cffsize->internal; if ( internal ) { PSH_Globals_Funcs funcs; funcs = cff_size_get_globals_funcs( size ); if ( funcs ) { FT_UInt i; funcs->destroy( internal->topfont ); for ( i = font->num_subfonts; i > 0; i-- ) funcs->destroy( internal->subfonts[i - 1] ); } /* `internal' is freed by destroy_size (in ftobjs.c) */ } } /* CFF and Type 1 private dictionaries have slightly different */ /* structures; we need to synthesize a Type 1 dictionary on the fly */ static void cff_make_private_dict( CFF_SubFont subfont, PS_Private priv ) { CFF_Private cpriv = &subfont->private_dict; FT_UInt n, count; FT_MEM_ZERO( priv, sizeof ( *priv ) ); count = priv->num_blue_values = cpriv->num_blue_values; for ( n = 0; n < count; n++ ) priv->blue_values[n] = (FT_Short)cpriv->blue_values[n]; count = priv->num_other_blues = cpriv->num_other_blues; for ( n = 0; n < count; n++ ) priv->other_blues[n] = (FT_Short)cpriv->other_blues[n]; count = priv->num_family_blues = cpriv->num_family_blues; for ( n = 0; n < count; n++ ) priv->family_blues[n] = (FT_Short)cpriv->family_blues[n]; count = priv->num_family_other_blues = cpriv->num_family_other_blues; for ( n = 0; n < count; n++ ) priv->family_other_blues[n] = (FT_Short)cpriv->family_other_blues[n]; priv->blue_scale = cpriv->blue_scale; priv->blue_shift = (FT_Int)cpriv->blue_shift; priv->blue_fuzz = (FT_Int)cpriv->blue_fuzz; priv->standard_width[0] = (FT_UShort)cpriv->standard_width; priv->standard_height[0] = (FT_UShort)cpriv->standard_height; count = priv->num_snap_widths = cpriv->num_snap_widths; for ( n = 0; n < count; n++ ) priv->snap_widths[n] = (FT_Short)cpriv->snap_widths[n]; count = priv->num_snap_heights = cpriv->num_snap_heights; for ( n = 0; n < count; n++ ) priv->snap_heights[n] = (FT_Short)cpriv->snap_heights[n]; priv->force_bold = cpriv->force_bold; priv->language_group = cpriv->language_group; priv->lenIV = cpriv->lenIV; } FT_LOCAL_DEF( FT_Error ) cff_size_init( FT_Size cffsize ) /* CFF_Size */ { CFF_Size size = (CFF_Size)cffsize; FT_Error error = FT_Err_Ok; PSH_Globals_Funcs funcs = cff_size_get_globals_funcs( size ); if ( funcs ) { CFF_Face face = (CFF_Face)cffsize->face; CFF_Font font = (CFF_Font)face->extra.data; CFF_Internal internal = NULL; PS_PrivateRec priv; FT_Memory memory = cffsize->face->memory; FT_UInt i; if ( FT_NEW( internal ) ) goto Exit; cff_make_private_dict( &font->top_font, &priv ); error = funcs->create( cffsize->face->memory, &priv, &internal->topfont ); if ( error ) goto Exit; for ( i = font->num_subfonts; i > 0; i-- ) { CFF_SubFont sub = font->subfonts[i - 1]; cff_make_private_dict( sub, &priv ); error = funcs->create( cffsize->face->memory, &priv, &internal->subfonts[i - 1] ); if ( error ) goto Exit; } cffsize->internal = (FT_Size_Internal)(void*)internal; } size->strike_index = 0xFFFFFFFFUL; Exit: return error; } #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS FT_LOCAL_DEF( FT_Error ) cff_size_select( FT_Size size, FT_ULong strike_index ) { CFF_Size cffsize = (CFF_Size)size; PSH_Globals_Funcs funcs; cffsize->strike_index = strike_index; FT_Select_Metrics( size->face, strike_index ); funcs = cff_size_get_globals_funcs( cffsize ); if ( funcs ) { CFF_Face face = (CFF_Face)size->face; CFF_Font font = (CFF_Font)face->extra.data; CFF_Internal internal = (CFF_Internal)size->internal; FT_ULong top_upm = font->top_font.font_dict.units_per_em; FT_UInt i; funcs->set_scale( internal->topfont, size->metrics.x_scale, size->metrics.y_scale, 0, 0 ); for ( i = font->num_subfonts; i > 0; i-- ) { CFF_SubFont sub = font->subfonts[i - 1]; FT_ULong sub_upm = sub->font_dict.units_per_em; FT_Pos x_scale, y_scale; if ( top_upm != sub_upm ) { x_scale = FT_MulDiv( size->metrics.x_scale, top_upm, sub_upm ); y_scale = FT_MulDiv( size->metrics.y_scale, top_upm, sub_upm ); } else { x_scale = size->metrics.x_scale; y_scale = size->metrics.y_scale; } funcs->set_scale( internal->subfonts[i - 1], x_scale, y_scale, 0, 0 ); } } return FT_Err_Ok; } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ FT_LOCAL_DEF( FT_Error ) cff_size_request( FT_Size size, FT_Size_Request req ) { CFF_Size cffsize = (CFF_Size)size; PSH_Globals_Funcs funcs; #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS if ( FT_HAS_FIXED_SIZES( size->face ) ) { CFF_Face cffface = (CFF_Face)size->face; SFNT_Service sfnt = (SFNT_Service)cffface->sfnt; FT_ULong strike_index; if ( sfnt->set_sbit_strike( cffface, req, &strike_index ) ) cffsize->strike_index = 0xFFFFFFFFUL; else return cff_size_select( size, strike_index ); } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ FT_Request_Metrics( size->face, req ); funcs = cff_size_get_globals_funcs( cffsize ); if ( funcs ) { CFF_Face cffface = (CFF_Face)size->face; CFF_Font font = (CFF_Font)cffface->extra.data; CFF_Internal internal = (CFF_Internal)size->internal; FT_ULong top_upm = font->top_font.font_dict.units_per_em; FT_UInt i; funcs->set_scale( internal->topfont, size->metrics.x_scale, size->metrics.y_scale, 0, 0 ); for ( i = font->num_subfonts; i > 0; i-- ) { CFF_SubFont sub = font->subfonts[i - 1]; FT_ULong sub_upm = sub->font_dict.units_per_em; FT_Pos x_scale, y_scale; if ( top_upm != sub_upm ) { x_scale = FT_MulDiv( size->metrics.x_scale, top_upm, sub_upm ); y_scale = FT_MulDiv( size->metrics.y_scale, top_upm, sub_upm ); } else { x_scale = size->metrics.x_scale; y_scale = size->metrics.y_scale; } funcs->set_scale( internal->subfonts[i - 1], x_scale, y_scale, 0, 0 ); } } return FT_Err_Ok; } /*************************************************************************/ /* */ /* SLOT FUNCTIONS */ /* */ /*************************************************************************/ FT_LOCAL_DEF( void ) cff_slot_done( FT_GlyphSlot slot ) { slot->internal->glyph_hints = 0; } FT_LOCAL_DEF( FT_Error ) cff_slot_init( FT_GlyphSlot slot ) { CFF_Face face = (CFF_Face)slot->face; CFF_Font font = (CFF_Font)face->extra.data; PSHinter_Service pshinter = font->pshinter; if ( pshinter ) { FT_Module module; module = FT_Get_Module( slot->face->driver->root.library, "pshinter" ); if ( module ) { T2_Hints_Funcs funcs; funcs = pshinter->get_t2_funcs( module ); slot->internal->glyph_hints = (void*)funcs; } } return FT_Err_Ok; } /*************************************************************************/ /* */ /* FACE FUNCTIONS */ /* */ /*************************************************************************/ static FT_String* cff_strcpy( FT_Memory memory, const FT_String* source ) { FT_Error error; FT_String* result; (void)FT_STRDUP( result, source ); FT_UNUSED( error ); return result; } /* Strip all subset prefixes of the form `ABCDEF+'. Usually, there */ /* is only one, but font names like `APCOOG+JFABTD+FuturaBQ-Bold' */ /* have been seen in the wild. */ static void remove_subset_prefix( FT_String* name ) { FT_Int32 idx = 0; FT_Int32 length = (FT_Int32)strlen( name ) + 1; FT_Bool continue_search = 1; while ( continue_search ) { if ( length >= 7 && name[6] == '+' ) { for ( idx = 0; idx < 6; idx++ ) { /* ASCII uppercase letters */ if ( !( 'A' <= name[idx] && name[idx] <= 'Z' ) ) continue_search = 0; } if ( continue_search ) { for ( idx = 7; idx < length; idx++ ) name[idx - 7] = name[idx]; length -= 7; } } else continue_search = 0; } } /* Remove the style part from the family name (if present). */ static void remove_style( FT_String* family_name, const FT_String* style_name ) { FT_Int32 family_name_length, style_name_length; family_name_length = (FT_Int32)strlen( family_name ); style_name_length = (FT_Int32)strlen( style_name ); if ( family_name_length > style_name_length ) { FT_Int idx; for ( idx = 1; idx <= style_name_length; ++idx ) { if ( family_name[family_name_length - idx] != style_name[style_name_length - idx] ) break; } if ( idx > style_name_length ) { /* family_name ends with style_name; remove it */ idx = family_name_length - style_name_length - 1; /* also remove special characters */ /* between real family name and style */ while ( idx > 0 && ( family_name[idx] == '-' || family_name[idx] == ' ' || family_name[idx] == '_' || family_name[idx] == '+' ) ) --idx; if ( idx > 0 ) family_name[idx + 1] = '\0'; } } } FT_LOCAL_DEF( FT_Error ) cff_face_init( FT_Stream stream, FT_Face cffface, /* CFF_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { CFF_Face face = (CFF_Face)cffface; FT_Error error; SFNT_Service sfnt; FT_Service_PsCMaps psnames; PSHinter_Service pshinter; FT_Bool pure_cff = 1; FT_Bool sfnt_format = 0; FT_Library library = cffface->driver->root.library; sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "cff_face_init: cannot access `sfnt' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); pshinter = (PSHinter_Service)FT_Get_Module_Interface( library, "pshinter" ); FT_TRACE2(( "CFF driver\n" )); /* create input stream from resource */ if ( FT_STREAM_SEEK( 0 ) ) goto Exit; /* check whether we have a valid OpenType file */ error = sfnt->init_face( stream, face, face_index, num_params, params ); if ( !error ) { if ( face->format_tag != TTAG_OTTO ) /* `OTTO'; OpenType/CFF font */ { FT_TRACE2(( " not an OpenType/CFF font\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* if we are performing a simple font format check, exit immediately */ if ( face_index < 0 ) return FT_Err_Ok; sfnt_format = 1; /* now, the font can be either an OpenType/CFF font, or an SVG CEF */ /* font; in the latter case it doesn't have a `head' table */ error = face->goto_table( face, TTAG_head, stream, 0 ); if ( !error ) { pure_cff = 0; /* load font directory */ error = sfnt->load_face( stream, face, face_index, num_params, params ); if ( error ) goto Exit; } else { /* load the `cmap' table explicitly */ error = sfnt->load_cmap( face, stream ); if ( error ) goto Exit; } /* now load the CFF part of the file */ error = face->goto_table( face, TTAG_CFF, stream, 0 ); if ( error ) goto Exit; } else { /* rewind to start of file; we are going to load a pure-CFF font */ if ( FT_STREAM_SEEK( 0 ) ) goto Exit; error = FT_Err_Ok; } /* now load and parse the CFF table in the file */ { CFF_Font cff = NULL; CFF_FontRecDict dict; FT_Memory memory = cffface->memory; FT_Int32 flags; FT_UInt i; if ( FT_NEW( cff ) ) goto Exit; face->extra.data = cff; error = cff_font_load( library, stream, face_index, cff, pure_cff ); if ( error ) goto Exit; cff->pshinter = pshinter; cff->psnames = psnames; cffface->face_index = face_index; /* Complement the root flags with some interesting information. */ /* Note that this is only necessary for pure CFF and CEF fonts; */ /* SFNT based fonts use the `name' table instead. */ cffface->num_glyphs = cff->num_glyphs; dict = &cff->top_font.font_dict; /* we need the `PSNames' module for CFF and CEF formats */ /* which aren't CID-keyed */ if ( dict->cid_registry == 0xFFFFU && !psnames ) { FT_ERROR(( "cff_face_init:" " cannot open CFF & CEF fonts\n" " " " without the `PSNames' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt idx; FT_String* s; FT_TRACE4(( "SIDs\n" )); /* dump string index, including default strings for convenience */ for ( idx = 0; idx < cff->num_strings + 390; idx++ ) { s = cff_index_get_sid_string( cff, idx ); if ( s ) FT_TRACE4((" %5d %s\n", idx, s )); } } #endif /* FT_DEBUG_LEVEL_TRACE */ if ( !dict->has_font_matrix ) dict->units_per_em = pure_cff ? 1000 : face->root.units_per_EM; /* Normalize the font matrix so that `matrix->xx' is 1; the */ /* scaling is done with `units_per_em' then (at this point, */ /* it already contains the scaling factor, but without */ /* normalization of the matrix). */ /* */ /* Note that the offsets must be expressed in integer font */ /* units. */ { FT_Matrix* matrix = &dict->font_matrix; FT_Vector* offset = &dict->font_offset; FT_ULong* upm = &dict->units_per_em; FT_Fixed temp = FT_ABS( matrix->yy ); if ( temp != 0x10000L ) { *upm = FT_DivFix( *upm, temp ); matrix->xx = FT_DivFix( matrix->xx, temp ); matrix->yx = FT_DivFix( matrix->yx, temp ); matrix->xy = FT_DivFix( matrix->xy, temp ); matrix->yy = FT_DivFix( matrix->yy, temp ); offset->x = FT_DivFix( offset->x, temp ); offset->y = FT_DivFix( offset->y, temp ); } offset->x >>= 16; offset->y >>= 16; } for ( i = cff->num_subfonts; i > 0; i-- ) { CFF_FontRecDict sub = &cff->subfonts[i - 1]->font_dict; CFF_FontRecDict top = &cff->top_font.font_dict; FT_Matrix* matrix; FT_Vector* offset; FT_ULong* upm; FT_Fixed temp; if ( sub->has_font_matrix ) { FT_Long scaling; /* if we have a top-level matrix, */ /* concatenate the subfont matrix */ if ( top->has_font_matrix ) { if ( top->units_per_em > 1 && sub->units_per_em > 1 ) scaling = FT_MIN( top->units_per_em, sub->units_per_em ); else scaling = 1; FT_Matrix_Multiply_Scaled( &top->font_matrix, &sub->font_matrix, scaling ); FT_Vector_Transform_Scaled( &sub->font_offset, &top->font_matrix, scaling ); sub->units_per_em = FT_MulDiv( sub->units_per_em, top->units_per_em, scaling ); } } else { sub->font_matrix = top->font_matrix; sub->font_offset = top->font_offset; sub->units_per_em = top->units_per_em; } matrix = &sub->font_matrix; offset = &sub->font_offset; upm = &sub->units_per_em; temp = FT_ABS( matrix->yy ); if ( temp != 0x10000L ) { *upm = FT_DivFix( *upm, temp ); matrix->xx = FT_DivFix( matrix->xx, temp ); matrix->yx = FT_DivFix( matrix->yx, temp ); matrix->xy = FT_DivFix( matrix->xy, temp ); matrix->yy = FT_DivFix( matrix->yy, temp ); offset->x = FT_DivFix( offset->x, temp ); offset->y = FT_DivFix( offset->y, temp ); } offset->x >>= 16; offset->y >>= 16; } if ( pure_cff ) { char* style_name = NULL; /* set up num_faces */ cffface->num_faces = cff->num_faces; /* compute number of glyphs */ if ( dict->cid_registry != 0xFFFFU ) cffface->num_glyphs = cff->charset.max_cid + 1; else cffface->num_glyphs = cff->charstrings_index.count; /* set global bbox, as well as EM size */ cffface->bbox.xMin = dict->font_bbox.xMin >> 16; cffface->bbox.yMin = dict->font_bbox.yMin >> 16; /* no `U' suffix here to 0xFFFF! */ cffface->bbox.xMax = ( dict->font_bbox.xMax + 0xFFFF ) >> 16; cffface->bbox.yMax = ( dict->font_bbox.yMax + 0xFFFF ) >> 16; cffface->units_per_EM = (FT_UShort)( dict->units_per_em ); cffface->ascender = (FT_Short)( cffface->bbox.yMax ); cffface->descender = (FT_Short)( cffface->bbox.yMin ); cffface->height = (FT_Short)( ( cffface->units_per_EM * 12 ) / 10 ); if ( cffface->height < cffface->ascender - cffface->descender ) cffface->height = (FT_Short)( cffface->ascender - cffface->descender ); cffface->underline_position = (FT_Short)( dict->underline_position >> 16 ); cffface->underline_thickness = (FT_Short)( dict->underline_thickness >> 16 ); /* retrieve font family & style name */ cffface->family_name = cff_index_get_name( cff, face_index ); if ( cffface->family_name ) { char* full = cff_index_get_sid_string( cff, dict->full_name ); char* fullp = full; char* family = cffface->family_name; char* family_name = NULL; remove_subset_prefix( cffface->family_name ); if ( dict->family_name ) { family_name = cff_index_get_sid_string( cff, dict->family_name ); if ( family_name ) family = family_name; } /* We try to extract the style name from the full name. */ /* We need to ignore spaces and dashes during the search. */ if ( full && family ) { while ( *fullp ) { /* skip common characters at the start of both strings */ if ( *fullp == *family ) { family++; fullp++; continue; } /* ignore spaces and dashes in full name during comparison */ if ( *fullp == ' ' || *fullp == '-' ) { fullp++; continue; } /* ignore spaces and dashes in family name during comparison */ if ( *family == ' ' || *family == '-' ) { family++; continue; } if ( !*family && *fullp ) { /* The full name begins with the same characters as the */ /* family name, with spaces and dashes removed. In this */ /* case, the remaining string in `fullp' will be used as */ /* the style name. */ style_name = cff_strcpy( memory, fullp ); /* remove the style part from the family name (if present) */ remove_style( cffface->family_name, style_name ); } break; } } } else { char *cid_font_name = cff_index_get_sid_string( cff, dict->cid_font_name ); /* do we have a `/FontName' for a CID-keyed font? */ if ( cid_font_name ) cffface->family_name = cff_strcpy( memory, cid_font_name ); } if ( style_name ) cffface->style_name = style_name; else /* assume "Regular" style if we don't know better */ cffface->style_name = cff_strcpy( memory, (char *)"Regular" ); /*******************************************************************/ /* */ /* Compute face flags. */ /* */ flags = FT_FACE_FLAG_SCALABLE | /* scalable outlines */ FT_FACE_FLAG_HORIZONTAL | /* horizontal data */ FT_FACE_FLAG_HINTER; /* has native hinter */ if ( sfnt_format ) flags |= FT_FACE_FLAG_SFNT; /* fixed width font? */ if ( dict->is_fixed_pitch ) flags |= FT_FACE_FLAG_FIXED_WIDTH; /* XXX: WE DO NOT SUPPORT KERNING METRICS IN THE GPOS TABLE FOR NOW */ #if 0 /* kerning available? */ if ( face->kern_pairs ) flags |= FT_FACE_FLAG_KERNING; #endif cffface->face_flags |= flags; /*******************************************************************/ /* */ /* Compute style flags. */ /* */ flags = 0; if ( dict->italic_angle ) flags |= FT_STYLE_FLAG_ITALIC; { char *weight = cff_index_get_sid_string( cff, dict->weight ); if ( weight ) if ( !ft_strcmp( weight, "Bold" ) || !ft_strcmp( weight, "Black" ) ) flags |= FT_STYLE_FLAG_BOLD; } /* double check */ if ( !(flags & FT_STYLE_FLAG_BOLD) && cffface->style_name ) if ( !ft_strncmp( cffface->style_name, "Bold", 4 ) || !ft_strncmp( cffface->style_name, "Black", 5 ) ) flags |= FT_STYLE_FLAG_BOLD; cffface->style_flags = flags; } #ifndef FT_CONFIG_OPTION_NO_GLYPH_NAMES /* CID-keyed CFF fonts don't have glyph names -- the SFNT loader */ /* has unset this flag because of the 3.0 `post' table. */ if ( dict->cid_registry == 0xFFFFU ) cffface->face_flags |= FT_FACE_FLAG_GLYPH_NAMES; #endif if ( dict->cid_registry != 0xFFFFU && pure_cff ) cffface->face_flags |= FT_FACE_FLAG_CID_KEYED; /*******************************************************************/ /* */ /* Compute char maps. */ /* */ /* Try to synthesize a Unicode charmap if there is none available */ /* already. If an OpenType font contains a Unicode "cmap", we */ /* will use it, whatever be in the CFF part of the file. */ { FT_CharMapRec cmaprec; FT_CharMap cmap; FT_UInt nn; CFF_Encoding encoding = &cff->encoding; for ( nn = 0; nn < (FT_UInt)cffface->num_charmaps; nn++ ) { cmap = cffface->charmaps[nn]; /* Windows Unicode? */ if ( cmap->platform_id == TT_PLATFORM_MICROSOFT && cmap->encoding_id == TT_MS_ID_UNICODE_CS ) goto Skip_Unicode; /* Apple Unicode platform id? */ if ( cmap->platform_id == TT_PLATFORM_APPLE_UNICODE ) goto Skip_Unicode; /* Apple Unicode */ } /* since CID-keyed fonts don't contain glyph names, we can't */ /* construct a cmap */ if ( pure_cff && cff->top_font.font_dict.cid_registry != 0xFFFFU ) goto Exit; #ifdef FT_MAX_CHARMAP_CACHEABLE if ( nn + 1 > FT_MAX_CHARMAP_CACHEABLE ) { FT_ERROR(( "cff_face_init: no Unicode cmap is found, " "and too many subtables (%d) to add synthesized cmap\n", nn )); goto Exit; } #endif /* we didn't find a Unicode charmap -- synthesize one */ cmaprec.face = cffface; cmaprec.platform_id = TT_PLATFORM_MICROSOFT; cmaprec.encoding_id = TT_MS_ID_UNICODE_CS; cmaprec.encoding = FT_ENCODING_UNICODE; nn = (FT_UInt)cffface->num_charmaps; error = FT_CMap_New( &CFF_CMAP_UNICODE_CLASS_REC_GET, NULL, &cmaprec, NULL ); if ( error && FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) ) goto Exit; error = FT_Err_Ok; /* if no Unicode charmap was previously selected, select this one */ if ( cffface->charmap == NULL && nn != (FT_UInt)cffface->num_charmaps ) cffface->charmap = cffface->charmaps[nn]; Skip_Unicode: #ifdef FT_MAX_CHARMAP_CACHEABLE if ( nn > FT_MAX_CHARMAP_CACHEABLE ) { FT_ERROR(( "cff_face_init: Unicode cmap is found, " "but too many preceding subtables (%d) to access\n", nn - 1 )); goto Exit; } #endif if ( encoding->count > 0 ) { FT_CMap_Class clazz; cmaprec.face = cffface; cmaprec.platform_id = TT_PLATFORM_ADOBE; /* Adobe platform id */ if ( encoding->offset == 0 ) { cmaprec.encoding_id = TT_ADOBE_ID_STANDARD; cmaprec.encoding = FT_ENCODING_ADOBE_STANDARD; clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET; } else if ( encoding->offset == 1 ) { cmaprec.encoding_id = TT_ADOBE_ID_EXPERT; cmaprec.encoding = FT_ENCODING_ADOBE_EXPERT; clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET; } else { cmaprec.encoding_id = TT_ADOBE_ID_CUSTOM; cmaprec.encoding = FT_ENCODING_ADOBE_CUSTOM; clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET; } error = FT_CMap_New( clazz, NULL, &cmaprec, NULL ); } } } Exit: return error; } FT_LOCAL_DEF( void ) cff_face_done( FT_Face cffface ) /* CFF_Face */ { CFF_Face face = (CFF_Face)cffface; FT_Memory memory; SFNT_Service sfnt; if ( !face ) return; memory = cffface->memory; sfnt = (SFNT_Service)face->sfnt; if ( sfnt ) sfnt->done_face( face ); { CFF_Font cff = (CFF_Font)face->extra.data; if ( cff ) { cff_font_done( cff ); FT_FREE( face->extra.data ); } } } FT_LOCAL_DEF( FT_Error ) cff_driver_init( FT_Module module ) /* CFF_Driver */ { CFF_Driver driver = (CFF_Driver)module; /* set default property values, cf `ftcffdrv.h' */ #ifdef CFF_CONFIG_OPTION_OLD_ENGINE driver->hinting_engine = FT_CFF_HINTING_FREETYPE; #else driver->hinting_engine = FT_CFF_HINTING_ADOBE; #endif driver->no_stem_darkening = FALSE; driver->darken_params[0] = 500; driver->darken_params[1] = 400; driver->darken_params[2] = 1000; driver->darken_params[3] = 275; driver->darken_params[4] = 1667; driver->darken_params[5] = 275; driver->darken_params[6] = 2333; driver->darken_params[7] = 0; return FT_Err_Ok; } FT_LOCAL_DEF( void ) cff_driver_done( FT_Module module ) /* CFF_Driver */ { FT_UNUSED( module ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffobjs.c
C
apache-2.0
33,669
/***************************************************************************/ /* */ /* cffobjs.h */ /* */ /* OpenType objects manager (specification). */ /* */ /* Copyright 1996-2004, 2006-2008, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFOBJS_H__ #define __CFFOBJS_H__ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include "cfftypes.h" #include FT_INTERNAL_TRUETYPE_TYPES_H #include FT_SERVICE_POSTSCRIPT_CMAPS_H #include FT_INTERNAL_POSTSCRIPT_HINTS_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Type> */ /* CFF_Driver */ /* */ /* <Description> */ /* A handle to an OpenType driver object. */ /* */ typedef struct CFF_DriverRec_* CFF_Driver; typedef TT_Face CFF_Face; /*************************************************************************/ /* */ /* <Type> */ /* CFF_Size */ /* */ /* <Description> */ /* A handle to an OpenType size object. */ /* */ typedef struct CFF_SizeRec_ { FT_SizeRec root; FT_ULong strike_index; /* 0xFFFFFFFF to indicate invalid */ } CFF_SizeRec, *CFF_Size; /*************************************************************************/ /* */ /* <Type> */ /* CFF_GlyphSlot */ /* */ /* <Description> */ /* A handle to an OpenType glyph slot object. */ /* */ typedef struct CFF_GlyphSlotRec_ { FT_GlyphSlotRec root; FT_Bool hint; FT_Bool scaled; FT_Fixed x_scale; FT_Fixed y_scale; } CFF_GlyphSlotRec, *CFF_GlyphSlot; /*************************************************************************/ /* */ /* <Type> */ /* CFF_Internal */ /* */ /* <Description> */ /* The interface to the `internal' field of `FT_Size'. */ /* */ typedef struct CFF_InternalRec_ { PSH_Globals topfont; PSH_Globals subfonts[CFF_MAX_CID_FONTS]; } CFF_InternalRec, *CFF_Internal; /*************************************************************************/ /* */ /* Subglyph transformation record. */ /* */ typedef struct CFF_Transform_ { FT_Fixed xx, xy; /* transformation matrix coefficients */ FT_Fixed yx, yy; FT_F26Dot6 ox, oy; /* offsets */ } CFF_Transform; /***********************************************************************/ /* */ /* CFF driver class. */ /* */ typedef struct CFF_DriverRec_ { FT_DriverRec root; FT_UInt hinting_engine; FT_Bool no_stem_darkening; FT_Int darken_params[8]; } CFF_DriverRec; FT_LOCAL( FT_Error ) cff_size_init( FT_Size size ); /* CFF_Size */ FT_LOCAL( void ) cff_size_done( FT_Size size ); /* CFF_Size */ FT_LOCAL( FT_Error ) cff_size_request( FT_Size size, FT_Size_Request req ); #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS FT_LOCAL( FT_Error ) cff_size_select( FT_Size size, FT_ULong strike_index ); #endif FT_LOCAL( void ) cff_slot_done( FT_GlyphSlot slot ); FT_LOCAL( FT_Error ) cff_slot_init( FT_GlyphSlot slot ); /*************************************************************************/ /* */ /* Face functions */ /* */ FT_LOCAL( FT_Error ) cff_face_init( FT_Stream stream, FT_Face face, /* CFF_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ); FT_LOCAL( void ) cff_face_done( FT_Face face ); /* CFF_Face */ /*************************************************************************/ /* */ /* Driver functions */ /* */ FT_LOCAL( FT_Error ) cff_driver_init( FT_Module module ); /* CFF_Driver */ FT_LOCAL( void ) cff_driver_done( FT_Module module ); /* CFF_Driver */ FT_END_HEADER #endif /* __CFFOBJS_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffobjs.h
C
apache-2.0
7,353
/***************************************************************************/ /* */ /* cffparse.c */ /* */ /* CFF token stream parser (body) */ /* */ /* Copyright 1996-2004, 2007-2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include "cffparse.h" #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_DEBUG_H #include "cfferrs.h" #include "cffpic.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffparse FT_LOCAL_DEF( void ) cff_parser_init( CFF_Parser parser, FT_UInt code, void* object, FT_Library library) { FT_MEM_ZERO( parser, sizeof ( *parser ) ); parser->top = parser->stack; parser->object_code = code; parser->object = object; parser->library = library; } /* read an integer */ static FT_Long cff_parse_integer( FT_Byte* start, FT_Byte* limit ) { FT_Byte* p = start; FT_Int v = *p++; FT_Long val = 0; if ( v == 28 ) { if ( p + 2 > limit ) goto Bad; val = (FT_Short)( ( (FT_UShort)p[0] << 8 ) | p[1] ); } else if ( v == 29 ) { if ( p + 4 > limit ) goto Bad; val = (FT_Long)( ( (FT_ULong)p[0] << 24 ) | ( (FT_ULong)p[1] << 16 ) | ( (FT_ULong)p[2] << 8 ) | (FT_ULong)p[3] ); } else if ( v < 247 ) { val = v - 139; } else if ( v < 251 ) { if ( p + 1 > limit ) goto Bad; val = ( v - 247 ) * 256 + p[0] + 108; } else { if ( p + 1 > limit ) goto Bad; val = -( v - 251 ) * 256 - p[0] - 108; } Exit: return val; Bad: val = 0; FT_TRACE4(( "!!!END OF DATA:!!!" )); goto Exit; } static const FT_Long power_tens[] = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L }; /* read a real */ static FT_Fixed cff_parse_real( FT_Byte* start, FT_Byte* limit, FT_Long power_ten, FT_Long* scaling ) { FT_Byte* p = start; FT_UInt nib; FT_UInt phase; FT_Long result, number, exponent; FT_Int sign = 0, exponent_sign = 0, have_overflow = 0; FT_Long exponent_add, integer_length, fraction_length; if ( scaling ) *scaling = 0; result = 0; number = 0; exponent = 0; exponent_add = 0; integer_length = 0; fraction_length = 0; /* First of all, read the integer part. */ phase = 4; for (;;) { /* If we entered this iteration with phase == 4, we need to */ /* read a new byte. This also skips past the initial 0x1E. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = ( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib == 0xE ) sign = 1; else if ( nib > 9 ) break; else { /* Increase exponent if we can't add the digit. */ if ( number >= 0xCCCCCCCL ) exponent_add++; /* Skip leading zeros. */ else if ( nib || number ) { integer_length++; number = number * 10 + nib; } } } /* Read fraction part, if any. */ if ( nib == 0xa ) for (;;) { /* If we entered this iteration with phase == 4, we need */ /* to read a new byte. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = ( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib >= 10 ) break; /* Skip leading zeros if possible. */ if ( !nib && !number ) exponent_add--; /* Only add digit if we don't overflow. */ else if ( number < 0xCCCCCCCL && fraction_length < 9 ) { fraction_length++; number = number * 10 + nib; } } /* Read exponent, if any. */ if ( nib == 12 ) { exponent_sign = 1; nib = 11; } if ( nib == 11 ) { for (;;) { /* If we entered this iteration with phase == 4, */ /* we need to read a new byte. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = ( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib >= 10 ) break; /* Arbitrarily limit exponent. */ if ( exponent > 1000 ) have_overflow = 1; else exponent = exponent * 10 + nib; } if ( exponent_sign ) exponent = -exponent; } if ( !number ) goto Exit; if ( have_overflow ) { if ( exponent_sign ) goto Underflow; else goto Overflow; } /* We don't check `power_ten' and `exponent_add'. */ exponent += power_ten + exponent_add; if ( scaling ) { /* Only use `fraction_length'. */ fraction_length += integer_length; exponent += integer_length; if ( fraction_length <= 5 ) { if ( number > 0x7FFFL ) { result = FT_DivFix( number, 10 ); *scaling = exponent - fraction_length + 1; } else { if ( exponent > 0 ) { FT_Long new_fraction_length, shift; /* Make `scaling' as small as possible. */ new_fraction_length = FT_MIN( exponent, 5 ); shift = new_fraction_length - fraction_length; if ( shift > 0 ) { exponent -= new_fraction_length; number *= power_tens[shift]; if ( number > 0x7FFFL ) { number /= 10; exponent += 1; } } else exponent -= fraction_length; } else exponent -= fraction_length; result = (FT_Long)( (FT_ULong)number << 16 ); *scaling = exponent; } } else { if ( ( number / power_tens[fraction_length - 5] ) > 0x7FFFL ) { result = FT_DivFix( number, power_tens[fraction_length - 4] ); *scaling = exponent - 4; } else { result = FT_DivFix( number, power_tens[fraction_length - 5] ); *scaling = exponent - 5; } } } else { integer_length += exponent; fraction_length -= exponent; if ( integer_length > 5 ) goto Overflow; if ( integer_length < -5 ) goto Underflow; /* Remove non-significant digits. */ if ( integer_length < 0 ) { number /= power_tens[-integer_length]; fraction_length += integer_length; } /* this can only happen if exponent was non-zero */ if ( fraction_length == 10 ) { number /= 10; fraction_length -= 1; } /* Convert into 16.16 format. */ if ( fraction_length > 0 ) { if ( ( number / power_tens[fraction_length] ) > 0x7FFFL ) goto Exit; result = FT_DivFix( number, power_tens[fraction_length] ); } else { number *= power_tens[-fraction_length]; if ( number > 0x7FFFL ) goto Overflow; result = (FT_Long)( (FT_ULong)number << 16 ); } } Exit: if ( sign ) result = -result; return result; Overflow: result = 0x7FFFFFFFL; FT_TRACE4(( "!!!OVERFLOW:!!!" )); goto Exit; Underflow: result = 0; FT_TRACE4(( "!!!UNDERFLOW:!!!" )); goto Exit; Bad: result = 0; FT_TRACE4(( "!!!END OF DATA:!!!" )); goto Exit; } /* read a number, either integer or real */ static FT_Long cff_parse_num( FT_Byte** d ) { return **d == 30 ? ( cff_parse_real( d[0], d[1], 0, NULL ) >> 16 ) : cff_parse_integer( d[0], d[1] ); } /* read a floating point number, either integer or real */ static FT_Fixed do_fixed( FT_Byte** d, FT_Long scaling ) { if ( **d == 30 ) return cff_parse_real( d[0], d[1], scaling, NULL ); else { FT_Long val = cff_parse_integer( d[0], d[1] ); if ( scaling ) val *= power_tens[scaling]; if ( val > 0x7FFF ) { val = 0x7FFFFFFFL; goto Overflow; } else if ( val < -0x7FFF ) { val = -0x7FFFFFFFL; goto Overflow; } return (FT_Long)( (FT_ULong)val << 16 ); Overflow: FT_TRACE4(( "!!!OVERFLOW:!!!" )); return val; } } /* read a floating point number, either integer or real */ static FT_Fixed cff_parse_fixed( FT_Byte** d ) { return do_fixed( d, 0 ); } /* read a floating point number, either integer or real, */ /* but return `10^scaling' times the number read in */ static FT_Fixed cff_parse_fixed_scaled( FT_Byte** d, FT_Long scaling ) { return do_fixed( d, scaling ); } /* read a floating point number, either integer or real, */ /* and return it as precise as possible -- `scaling' returns */ /* the scaling factor (as a power of 10) */ static FT_Fixed cff_parse_fixed_dynamic( FT_Byte** d, FT_Long* scaling ) { FT_ASSERT( scaling ); if ( **d == 30 ) return cff_parse_real( d[0], d[1], 0, scaling ); else { FT_Long number; FT_Int integer_length; number = cff_parse_integer( d[0], d[1] ); if ( number > 0x7FFFL ) { for ( integer_length = 5; integer_length < 10; integer_length++ ) if ( number < power_tens[integer_length] ) break; if ( ( number / power_tens[integer_length - 5] ) > 0x7FFFL ) { *scaling = integer_length - 4; return FT_DivFix( number, power_tens[integer_length - 4] ); } else { *scaling = integer_length - 5; return FT_DivFix( number, power_tens[integer_length - 5] ); } } else { *scaling = 0; return (FT_Long)( (FT_ULong)number << 16 ); } } } static FT_Error cff_parse_font_matrix( CFF_Parser parser ) { CFF_FontRecDict dict = (CFF_FontRecDict)parser->object; FT_Matrix* matrix = &dict->font_matrix; FT_Vector* offset = &dict->font_offset; FT_ULong* upm = &dict->units_per_em; FT_Byte** data = parser->stack; FT_Error error = FT_ERR( Stack_Underflow ); if ( parser->top >= parser->stack + 6 ) { FT_Long scaling; error = FT_Err_Ok; dict->has_font_matrix = TRUE; /* We expect a well-formed font matrix, this is, the matrix elements */ /* `xx' and `yy' are of approximately the same magnitude. To avoid */ /* loss of precision, we use the magnitude of element `xx' to scale */ /* all other elements. The scaling factor is then contained in the */ /* `units_per_em' value. */ matrix->xx = cff_parse_fixed_dynamic( data++, &scaling ); scaling = -scaling; if ( scaling < 0 || scaling > 9 ) { /* Return default matrix in case of unlikely values. */ FT_TRACE1(( "cff_parse_font_matrix:" " strange scaling value for xx element (%d),\n" " " " using default matrix\n", scaling )); matrix->xx = 0x10000L; matrix->yx = 0; matrix->xy = 0; matrix->yy = 0x10000L; offset->x = 0; offset->y = 0; *upm = 1; goto Exit; } matrix->yx = cff_parse_fixed_scaled( data++, scaling ); matrix->xy = cff_parse_fixed_scaled( data++, scaling ); matrix->yy = cff_parse_fixed_scaled( data++, scaling ); offset->x = cff_parse_fixed_scaled( data++, scaling ); offset->y = cff_parse_fixed_scaled( data, scaling ); *upm = power_tens[scaling]; FT_TRACE4(( " [%f %f %f %f %f %f]\n", (double)matrix->xx / *upm / 65536, (double)matrix->xy / *upm / 65536, (double)matrix->yx / *upm / 65536, (double)matrix->yy / *upm / 65536, (double)offset->x / *upm / 65536, (double)offset->y / *upm / 65536 )); } Exit: return error; } static FT_Error cff_parse_font_bbox( CFF_Parser parser ) { CFF_FontRecDict dict = (CFF_FontRecDict)parser->object; FT_BBox* bbox = &dict->font_bbox; FT_Byte** data = parser->stack; FT_Error error; error = FT_ERR( Stack_Underflow ); if ( parser->top >= parser->stack + 4 ) { bbox->xMin = FT_RoundFix( cff_parse_fixed( data++ ) ); bbox->yMin = FT_RoundFix( cff_parse_fixed( data++ ) ); bbox->xMax = FT_RoundFix( cff_parse_fixed( data++ ) ); bbox->yMax = FT_RoundFix( cff_parse_fixed( data ) ); error = FT_Err_Ok; FT_TRACE4(( " [%d %d %d %d]\n", bbox->xMin / 65536, bbox->yMin / 65536, bbox->xMax / 65536, bbox->yMax / 65536 )); } return error; } static FT_Error cff_parse_private_dict( CFF_Parser parser ) { CFF_FontRecDict dict = (CFF_FontRecDict)parser->object; FT_Byte** data = parser->stack; FT_Error error; error = FT_ERR( Stack_Underflow ); if ( parser->top >= parser->stack + 2 ) { dict->private_size = cff_parse_num( data++ ); dict->private_offset = cff_parse_num( data ); FT_TRACE4(( " %lu %lu\n", dict->private_size, dict->private_offset )); error = FT_Err_Ok; } return error; } static FT_Error cff_parse_cid_ros( CFF_Parser parser ) { CFF_FontRecDict dict = (CFF_FontRecDict)parser->object; FT_Byte** data = parser->stack; FT_Error error; error = FT_ERR( Stack_Underflow ); if ( parser->top >= parser->stack + 3 ) { dict->cid_registry = (FT_UInt)cff_parse_num( data++ ); dict->cid_ordering = (FT_UInt)cff_parse_num( data++ ); if ( **data == 30 ) FT_TRACE1(( "cff_parse_cid_ros: real supplement is rounded\n" )); dict->cid_supplement = cff_parse_num( data ); if ( dict->cid_supplement < 0 ) FT_TRACE1(( "cff_parse_cid_ros: negative supplement %d is found\n", dict->cid_supplement )); error = FT_Err_Ok; FT_TRACE4(( " %d %d %d\n", dict->cid_registry, dict->cid_ordering, dict->cid_supplement )); } return error; } #define CFF_FIELD_NUM( code, name, id ) \ CFF_FIELD( code, name, id, cff_kind_num ) #define CFF_FIELD_FIXED( code, name, id ) \ CFF_FIELD( code, name, id, cff_kind_fixed ) #define CFF_FIELD_FIXED_1000( code, name, id ) \ CFF_FIELD( code, name, id, cff_kind_fixed_thousand ) #define CFF_FIELD_STRING( code, name, id ) \ CFF_FIELD( code, name, id, cff_kind_string ) #define CFF_FIELD_BOOL( code, name, id ) \ CFF_FIELD( code, name, id, cff_kind_bool ) #define CFFCODE_TOPDICT 0x1000 #define CFFCODE_PRIVATE 0x2000 #ifndef FT_CONFIG_OPTION_PIC #undef CFF_FIELD #undef CFF_FIELD_DELTA #ifndef FT_DEBUG_LEVEL_TRACE #define CFF_FIELD_CALLBACK( code, name, id ) \ { \ cff_kind_callback, \ code | CFFCODE, \ 0, 0, \ cff_parse_ ## name, \ 0, 0 \ }, #define CFF_FIELD( code, name, id, kind ) \ { \ kind, \ code | CFFCODE, \ FT_FIELD_OFFSET( name ), \ FT_FIELD_SIZE( name ), \ 0, 0, 0 \ }, #define CFF_FIELD_DELTA( code, name, max, id ) \ { \ cff_kind_delta, \ code | CFFCODE, \ FT_FIELD_OFFSET( name ), \ FT_FIELD_SIZE_DELTA( name ), \ 0, \ max, \ FT_FIELD_OFFSET( num_ ## name ) \ }, static const CFF_Field_Handler cff_field_handlers[] = { #include "cfftoken.h" { 0, 0, 0, 0, 0, 0, 0 } }; #else /* FT_DEBUG_LEVEL_TRACE */ #define CFF_FIELD_CALLBACK( code, name, id ) \ { \ cff_kind_callback, \ code | CFFCODE, \ 0, 0, \ cff_parse_ ## name, \ 0, 0, \ id \ }, #define CFF_FIELD( code, name, id, kind ) \ { \ kind, \ code | CFFCODE, \ FT_FIELD_OFFSET( name ), \ FT_FIELD_SIZE( name ), \ 0, 0, 0, \ id \ }, #define CFF_FIELD_DELTA( code, name, max, id ) \ { \ cff_kind_delta, \ code | CFFCODE, \ FT_FIELD_OFFSET( name ), \ FT_FIELD_SIZE_DELTA( name ), \ 0, \ max, \ FT_FIELD_OFFSET( num_ ## name ), \ id \ }, static const CFF_Field_Handler cff_field_handlers[] = { #include "cfftoken.h" { 0, 0, 0, 0, 0, 0, 0, 0 } }; #endif /* FT_DEBUG_LEVEL_TRACE */ #else /* FT_CONFIG_OPTION_PIC */ void FT_Destroy_Class_cff_field_handlers( FT_Library library, CFF_Field_Handler* clazz ) { FT_Memory memory = library->memory; if ( clazz ) FT_FREE( clazz ); } FT_Error FT_Create_Class_cff_field_handlers( FT_Library library, CFF_Field_Handler** output_class ) { CFF_Field_Handler* clazz = NULL; FT_Error error; FT_Memory memory = library->memory; int i = 0; #undef CFF_FIELD #define CFF_FIELD( code, name, id, kind ) i++; #undef CFF_FIELD_DELTA #define CFF_FIELD_DELTA( code, name, max, id ) i++; #undef CFF_FIELD_CALLBACK #define CFF_FIELD_CALLBACK( code, name, id ) i++; #include "cfftoken.h" i++; /* { 0, 0, 0, 0, 0, 0, 0 } */ if ( FT_ALLOC( clazz, sizeof ( CFF_Field_Handler ) * i ) ) return error; i = 0; #ifndef FT_DEBUG_LEVEL_TRACE #undef CFF_FIELD_CALLBACK #define CFF_FIELD_CALLBACK( code_, name_, id_ ) \ clazz[i].kind = cff_kind_callback; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = 0; \ clazz[i].size = 0; \ clazz[i].reader = cff_parse_ ## name_; \ clazz[i].array_max = 0; \ clazz[i].count_offset = 0; \ i++; #undef CFF_FIELD #define CFF_FIELD( code_, name_, id_, kind_ ) \ clazz[i].kind = kind_; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = FT_FIELD_OFFSET( name_ ); \ clazz[i].size = FT_FIELD_SIZE( name_ ); \ clazz[i].reader = 0; \ clazz[i].array_max = 0; \ clazz[i].count_offset = 0; \ i++; \ #undef CFF_FIELD_DELTA #define CFF_FIELD_DELTA( code_, name_, max_, id_ ) \ clazz[i].kind = cff_kind_delta; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = FT_FIELD_OFFSET( name_ ); \ clazz[i].size = FT_FIELD_SIZE_DELTA( name_ ); \ clazz[i].reader = 0; \ clazz[i].array_max = max_; \ clazz[i].count_offset = FT_FIELD_OFFSET( num_ ## name_ ); \ i++; #include "cfftoken.h" clazz[i].kind = 0; clazz[i].code = 0; clazz[i].offset = 0; clazz[i].size = 0; clazz[i].reader = 0; clazz[i].array_max = 0; clazz[i].count_offset = 0; #else /* FT_DEBUG_LEVEL_TRACE */ #undef CFF_FIELD_CALLBACK #define CFF_FIELD_CALLBACK( code_, name_, id_ ) \ clazz[i].kind = cff_kind_callback; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = 0; \ clazz[i].size = 0; \ clazz[i].reader = cff_parse_ ## name_; \ clazz[i].array_max = 0; \ clazz[i].count_offset = 0; \ clazz[i].id = id_; \ i++; #undef CFF_FIELD #define CFF_FIELD( code_, name_, id_, kind_ ) \ clazz[i].kind = kind_; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = FT_FIELD_OFFSET( name_ ); \ clazz[i].size = FT_FIELD_SIZE( name_ ); \ clazz[i].reader = 0; \ clazz[i].array_max = 0; \ clazz[i].count_offset = 0; \ clazz[i].id = id_; \ i++; \ #undef CFF_FIELD_DELTA #define CFF_FIELD_DELTA( code_, name_, max_, id_ ) \ clazz[i].kind = cff_kind_delta; \ clazz[i].code = code_ | CFFCODE; \ clazz[i].offset = FT_FIELD_OFFSET( name_ ); \ clazz[i].size = FT_FIELD_SIZE_DELTA( name_ ); \ clazz[i].reader = 0; \ clazz[i].array_max = max_; \ clazz[i].count_offset = FT_FIELD_OFFSET( num_ ## name_ ); \ clazz[i].id = id_; \ i++; #include "cfftoken.h" clazz[i].kind = 0; clazz[i].code = 0; clazz[i].offset = 0; clazz[i].size = 0; clazz[i].reader = 0; clazz[i].array_max = 0; clazz[i].count_offset = 0; clazz[i].id = 0; #endif /* FT_DEBUG_LEVEL_TRACE */ *output_class = clazz; return FT_Err_Ok; } #endif /* FT_CONFIG_OPTION_PIC */ FT_LOCAL_DEF( FT_Error ) cff_parser_run( CFF_Parser parser, FT_Byte* start, FT_Byte* limit ) { FT_Byte* p = start; FT_Error error = FT_Err_Ok; FT_Library library = parser->library; FT_UNUSED( library ); parser->top = parser->stack; parser->start = start; parser->limit = limit; parser->cursor = start; while ( p < limit ) { FT_UInt v = *p; if ( v >= 27 && v != 31 ) { /* it's a number; we will push its position on the stack */ if ( parser->top - parser->stack >= CFF_MAX_STACK_DEPTH ) goto Stack_Overflow; *parser->top ++ = p; /* now, skip it */ if ( v == 30 ) { /* skip real number */ p++; for (;;) { /* An unterminated floating point number at the */ /* end of a dictionary is invalid but harmless. */ if ( p >= limit ) goto Exit; v = p[0] >> 4; if ( v == 15 ) break; v = p[0] & 0xF; if ( v == 15 ) break; p++; } } else if ( v == 28 ) p += 2; else if ( v == 29 ) p += 4; else if ( v > 246 ) p += 1; } else { /* This is not a number, hence it's an operator. Compute its code */ /* and look for it in our current list. */ FT_UInt code; FT_UInt num_args = (FT_UInt) ( parser->top - parser->stack ); const CFF_Field_Handler* field; *parser->top = p; code = v; if ( v == 12 ) { /* two byte operator */ p++; if ( p >= limit ) goto Syntax_Error; code = 0x100 | p[0]; } code = code | parser->object_code; for ( field = CFF_FIELD_HANDLERS_GET; field->kind; field++ ) { if ( field->code == (FT_Int)code ) { /* we found our field's handler; read it */ FT_Long val; FT_Byte* q = (FT_Byte*)parser->object + field->offset; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " %s", field->id )); #endif /* check that we have enough arguments -- except for */ /* delta encoded arrays, which can be empty */ if ( field->kind != cff_kind_delta && num_args < 1 ) goto Stack_Underflow; switch ( field->kind ) { case cff_kind_bool: case cff_kind_string: case cff_kind_num: val = cff_parse_num( parser->stack ); goto Store_Number; case cff_kind_fixed: val = cff_parse_fixed( parser->stack ); goto Store_Number; case cff_kind_fixed_thousand: val = cff_parse_fixed_scaled( parser->stack, 3 ); Store_Number: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } #ifdef FT_DEBUG_LEVEL_TRACE switch ( field->kind ) { case cff_kind_bool: FT_TRACE4(( " %s\n", val ? "true" : "false" )); break; case cff_kind_string: FT_TRACE4(( " %ld (SID)\n", val )); break; case cff_kind_num: FT_TRACE4(( " %ld\n", val )); break; case cff_kind_fixed: FT_TRACE4(( " %f\n", (double)val / 65536 )); break; case cff_kind_fixed_thousand: FT_TRACE4(( " %f\n", (double)val / 65536 / 1000 )); default: ; /* never reached */ } #endif break; case cff_kind_delta: { FT_Byte* qcount = (FT_Byte*)parser->object + field->count_offset; FT_Byte** data = parser->stack; if ( num_args > field->array_max ) num_args = field->array_max; FT_TRACE4(( " [" )); /* store count */ *qcount = (FT_Byte)num_args; val = 0; while ( num_args > 0 ) { val += cff_parse_num( data++ ); switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } FT_TRACE4(( " %ld", val )); q += field->size; num_args--; } FT_TRACE4(( "]\n" )); } break; default: /* callback */ error = field->reader( parser ); if ( error ) goto Exit; } goto Found; } } /* this is an unknown operator, or it is unsupported; */ /* we will ignore it for now. */ Found: /* clear stack */ parser->top = parser->stack; } p++; } Exit: return error; Stack_Overflow: error = FT_THROW( Invalid_Argument ); goto Exit; Stack_Underflow: error = FT_THROW( Invalid_Argument ); goto Exit; Syntax_Error: error = FT_THROW( Invalid_Argument ); goto Exit; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffparse.c
C
apache-2.0
31,840
/***************************************************************************/ /* */ /* cffparse.h */ /* */ /* CFF token stream parser (specification) */ /* */ /* Copyright 1996-2003, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFF_PARSE_H__ #define __CFF_PARSE_H__ #include <ft2build.h> #include "cfftypes.h" #include FT_INTERNAL_OBJECTS_H FT_BEGIN_HEADER #define CFF_MAX_STACK_DEPTH 96 #define CFF_CODE_TOPDICT 0x1000 #define CFF_CODE_PRIVATE 0x2000 typedef struct CFF_ParserRec_ { FT_Library library; FT_Byte* start; FT_Byte* limit; FT_Byte* cursor; FT_Byte* stack[CFF_MAX_STACK_DEPTH + 1]; FT_Byte** top; FT_UInt object_code; void* object; } CFF_ParserRec, *CFF_Parser; FT_LOCAL( void ) cff_parser_init( CFF_Parser parser, FT_UInt code, void* object, FT_Library library); FT_LOCAL( FT_Error ) cff_parser_run( CFF_Parser parser, FT_Byte* start, FT_Byte* limit ); enum { cff_kind_none = 0, cff_kind_num, cff_kind_fixed, cff_kind_fixed_thousand, cff_kind_string, cff_kind_bool, cff_kind_delta, cff_kind_callback, cff_kind_max /* do not remove */ }; /* now generate handlers for the most simple fields */ typedef FT_Error (*CFF_Field_Reader)( CFF_Parser parser ); typedef struct CFF_Field_Handler_ { int kind; int code; FT_UInt offset; FT_Byte size; CFF_Field_Reader reader; FT_UInt array_max; FT_UInt count_offset; #ifdef FT_DEBUG_LEVEL_TRACE const char* id; #endif } CFF_Field_Handler; FT_END_HEADER #endif /* __CFF_PARSE_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffparse.h
C
apache-2.0
2,844
/***************************************************************************/ /* */ /* cffpic.c */ /* */ /* The FreeType position independent code services for cff module. */ /* */ /* Copyright 2009, 2010, 2012, 2013 by */ /* Oran Agra and Mickey Gabel. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_FREETYPE_H #include FT_INTERNAL_OBJECTS_H #include "cffcmap.h" #include "cffpic.h" #include "cfferrs.h" #ifdef FT_CONFIG_OPTION_PIC /* forward declaration of PIC init functions from cffdrivr.c */ FT_Error FT_Create_Class_cff_services( FT_Library library, FT_ServiceDescRec** output_class ); void FT_Destroy_Class_cff_services( FT_Library library, FT_ServiceDescRec* clazz ); void FT_Init_Class_cff_service_ps_info( FT_Library library, FT_Service_PsInfoRec* clazz ); void FT_Init_Class_cff_service_glyph_dict( FT_Library library, FT_Service_GlyphDictRec* clazz ); void FT_Init_Class_cff_service_ps_name( FT_Library library, FT_Service_PsFontNameRec* clazz ); void FT_Init_Class_cff_service_get_cmap_info( FT_Library library, FT_Service_TTCMapsRec* clazz ); void FT_Init_Class_cff_service_cid_info( FT_Library library, FT_Service_CIDRec* clazz ); /* forward declaration of PIC init functions from cffparse.c */ FT_Error FT_Create_Class_cff_field_handlers( FT_Library library, CFF_Field_Handler** output_class ); void FT_Destroy_Class_cff_field_handlers( FT_Library library, CFF_Field_Handler* clazz ); void cff_driver_class_pic_free( FT_Library library ) { FT_PIC_Container* pic_container = &library->pic_container; FT_Memory memory = library->memory; if ( pic_container->cff ) { CffModulePIC* container = (CffModulePIC*)pic_container->cff; if ( container->cff_services ) FT_Destroy_Class_cff_services( library, container->cff_services ); container->cff_services = NULL; if ( container->cff_field_handlers ) FT_Destroy_Class_cff_field_handlers( library, container->cff_field_handlers ); container->cff_field_handlers = NULL; FT_FREE( container ); pic_container->cff = NULL; } } FT_Error cff_driver_class_pic_init( FT_Library library ) { FT_PIC_Container* pic_container = &library->pic_container; FT_Error error = FT_Err_Ok; CffModulePIC* container = NULL; FT_Memory memory = library->memory; /* allocate pointer, clear and set global container pointer */ if ( FT_ALLOC ( container, sizeof ( *container ) ) ) return error; FT_MEM_SET( container, 0, sizeof ( *container ) ); pic_container->cff = container; /* initialize pointer table - */ /* this is how the module usually expects this data */ error = FT_Create_Class_cff_services( library, &container->cff_services ); if ( error ) goto Exit; error = FT_Create_Class_cff_field_handlers( library, &container->cff_field_handlers ); if ( error ) goto Exit; FT_Init_Class_cff_service_ps_info( library, &container->cff_service_ps_info ); FT_Init_Class_cff_service_glyph_dict( library, &container->cff_service_glyph_dict ); FT_Init_Class_cff_service_ps_name( library, &container->cff_service_ps_name ); FT_Init_Class_cff_service_get_cmap_info( library, &container->cff_service_get_cmap_info ); FT_Init_Class_cff_service_cid_info( library, &container->cff_service_cid_info ); FT_Init_Class_cff_cmap_encoding_class_rec( library, &container->cff_cmap_encoding_class_rec ); FT_Init_Class_cff_cmap_unicode_class_rec( library, &container->cff_cmap_unicode_class_rec ); Exit: if ( error ) cff_driver_class_pic_free( library ); return error; } #endif /* FT_CONFIG_OPTION_PIC */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffpic.c
C
apache-2.0
5,360
/***************************************************************************/ /* */ /* cffpic.h */ /* */ /* The FreeType position independent code services for cff module. */ /* */ /* Copyright 2009, 2012, 2013 by */ /* Oran Agra and Mickey Gabel. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFPIC_H__ #define __CFFPIC_H__ FT_BEGIN_HEADER #include FT_INTERNAL_PIC_H #ifndef FT_CONFIG_OPTION_PIC #define CFF_SERVICE_PS_INFO_GET cff_service_ps_info #define CFF_SERVICE_GLYPH_DICT_GET cff_service_glyph_dict #define CFF_SERVICE_PS_NAME_GET cff_service_ps_name #define CFF_SERVICE_GET_CMAP_INFO_GET cff_service_get_cmap_info #define CFF_SERVICE_CID_INFO_GET cff_service_cid_info #define CFF_SERVICE_PROPERTIES_GET cff_service_properties #define CFF_SERVICES_GET cff_services #define CFF_CMAP_ENCODING_CLASS_REC_GET cff_cmap_encoding_class_rec #define CFF_CMAP_UNICODE_CLASS_REC_GET cff_cmap_unicode_class_rec #define CFF_FIELD_HANDLERS_GET cff_field_handlers #else /* FT_CONFIG_OPTION_PIC */ #include FT_SERVICE_GLYPH_DICT_H #include "cffparse.h" #include FT_SERVICE_POSTSCRIPT_INFO_H #include FT_SERVICE_POSTSCRIPT_NAME_H #include FT_SERVICE_TT_CMAP_H #include FT_SERVICE_CID_H #include FT_SERVICE_PROPERTIES_H typedef struct CffModulePIC_ { FT_ServiceDescRec* cff_services; CFF_Field_Handler* cff_field_handlers; FT_Service_PsInfoRec cff_service_ps_info; FT_Service_GlyphDictRec cff_service_glyph_dict; FT_Service_PsFontNameRec cff_service_ps_name; FT_Service_TTCMapsRec cff_service_get_cmap_info; FT_Service_CIDRec cff_service_cid_info; FT_Service_PropertiesRec cff_service_properties; FT_CMap_ClassRec cff_cmap_encoding_class_rec; FT_CMap_ClassRec cff_cmap_unicode_class_rec; } CffModulePIC; #define GET_PIC( lib ) \ ( (CffModulePIC*)( (lib)->pic_container.cff ) ) #define CFF_SERVICE_PS_INFO_GET \ ( GET_PIC( library )->cff_service_ps_info ) #define CFF_SERVICE_GLYPH_DICT_GET \ ( GET_PIC( library )->cff_service_glyph_dict ) #define CFF_SERVICE_PS_NAME_GET \ ( GET_PIC( library )->cff_service_ps_name ) #define CFF_SERVICE_GET_CMAP_INFO_GET \ ( GET_PIC( library )->cff_service_get_cmap_info ) #define CFF_SERVICE_CID_INFO_GET \ ( GET_PIC( library )->cff_service_cid_info ) #define CFF_SERVICE_PROPERTIES_GET \ ( GET_PIC( library )->cff_service_properties ) #define CFF_SERVICES_GET \ ( GET_PIC( library )->cff_services ) #define CFF_CMAP_ENCODING_CLASS_REC_GET \ ( GET_PIC( library )->cff_cmap_encoding_class_rec ) #define CFF_CMAP_UNICODE_CLASS_REC_GET \ ( GET_PIC( library )->cff_cmap_unicode_class_rec ) #define CFF_FIELD_HANDLERS_GET \ ( GET_PIC( library )->cff_field_handlers ) /* see cffpic.c for the implementation */ void cff_driver_class_pic_free( FT_Library library ); FT_Error cff_driver_class_pic_init( FT_Library library ); #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __CFFPIC_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cffpic.h
C
apache-2.0
4,368
/***************************************************************************/ /* */ /* cfftoken.h */ /* */ /* CFF token definitions (specification only). */ /* */ /* Copyright 1996-2003, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #undef FT_STRUCTURE #define FT_STRUCTURE CFF_FontRecDictRec #undef CFFCODE #define CFFCODE CFFCODE_TOPDICT CFF_FIELD_STRING ( 0, version, "Version" ) CFF_FIELD_STRING ( 1, notice, "Notice" ) CFF_FIELD_STRING ( 0x100, copyright, "Copyright" ) CFF_FIELD_STRING ( 2, full_name, "FullName" ) CFF_FIELD_STRING ( 3, family_name, "FamilyName" ) CFF_FIELD_STRING ( 4, weight, "Weight" ) CFF_FIELD_BOOL ( 0x101, is_fixed_pitch, "isFixedPitch" ) CFF_FIELD_FIXED ( 0x102, italic_angle, "ItalicAngle" ) CFF_FIELD_FIXED ( 0x103, underline_position, "UnderlinePosition" ) CFF_FIELD_FIXED ( 0x104, underline_thickness, "UnderlineThickness" ) CFF_FIELD_NUM ( 0x105, paint_type, "PaintType" ) CFF_FIELD_NUM ( 0x106, charstring_type, "CharstringType" ) CFF_FIELD_CALLBACK( 0x107, font_matrix, "FontMatrix" ) CFF_FIELD_NUM ( 13, unique_id, "UniqueID" ) CFF_FIELD_CALLBACK( 5, font_bbox, "FontBBox" ) CFF_FIELD_NUM ( 0x108, stroke_width, "StrokeWidth" ) CFF_FIELD_NUM ( 15, charset_offset, "charset" ) CFF_FIELD_NUM ( 16, encoding_offset, "Encoding" ) CFF_FIELD_NUM ( 17, charstrings_offset, "CharStrings" ) CFF_FIELD_CALLBACK( 18, private_dict, "Private" ) CFF_FIELD_NUM ( 0x114, synthetic_base, "SyntheticBase" ) CFF_FIELD_STRING ( 0x115, embedded_postscript, "PostScript" ) #if 0 CFF_FIELD_STRING ( 0x116, base_font_name, "BaseFontName" ) CFF_FIELD_DELTA ( 0x117, base_font_blend, 16, "BaseFontBlend" ) CFF_FIELD_CALLBACK( 0x118, multiple_master, "MultipleMaster" ) CFF_FIELD_CALLBACK( 0x119, blend_axis_types, "BlendAxisTypes" ) #endif CFF_FIELD_CALLBACK( 0x11E, cid_ros, "ROS" ) CFF_FIELD_NUM ( 0x11F, cid_font_version, "CIDFontVersion" ) CFF_FIELD_NUM ( 0x120, cid_font_revision, "CIDFontRevision" ) CFF_FIELD_NUM ( 0x121, cid_font_type, "CIDFontType" ) CFF_FIELD_NUM ( 0x122, cid_count, "CIDCount" ) CFF_FIELD_NUM ( 0x123, cid_uid_base, "UIDBase" ) CFF_FIELD_NUM ( 0x124, cid_fd_array_offset, "FDArray" ) CFF_FIELD_NUM ( 0x125, cid_fd_select_offset, "FDSelect" ) CFF_FIELD_STRING ( 0x126, cid_font_name, "FontName" ) #if 0 CFF_FIELD_NUM ( 0x127, chameleon, "Chameleon" ) #endif #undef FT_STRUCTURE #define FT_STRUCTURE CFF_PrivateRec #undef CFFCODE #define CFFCODE CFFCODE_PRIVATE CFF_FIELD_DELTA ( 6, blue_values, 14, "BlueValues" ) CFF_FIELD_DELTA ( 7, other_blues, 10, "OtherBlues" ) CFF_FIELD_DELTA ( 8, family_blues, 14, "FamilyBlues" ) CFF_FIELD_DELTA ( 9, family_other_blues, 10, "FamilyOtherBlues" ) CFF_FIELD_FIXED_1000( 0x109, blue_scale, "BlueScale" ) CFF_FIELD_NUM ( 0x10A, blue_shift, "BlueShift" ) CFF_FIELD_NUM ( 0x10B, blue_fuzz, "BlueFuzz" ) CFF_FIELD_NUM ( 10, standard_width, "StdHW" ) CFF_FIELD_NUM ( 11, standard_height, "StdVW" ) CFF_FIELD_DELTA ( 0x10C, snap_widths, 13, "StemSnapH" ) CFF_FIELD_DELTA ( 0x10D, snap_heights, 13, "StemSnapV" ) CFF_FIELD_BOOL ( 0x10E, force_bold, "ForceBold" ) CFF_FIELD_FIXED ( 0x10F, force_bold_threshold, "ForceBoldThreshold" ) CFF_FIELD_NUM ( 0x110, lenIV, "lenIV" ) CFF_FIELD_NUM ( 0x111, language_group, "LanguageGroup" ) CFF_FIELD_FIXED ( 0x112, expansion_factor, "ExpansionFactor" ) CFF_FIELD_NUM ( 0x113, initial_random_seed, "initialRandomSeed" ) CFF_FIELD_NUM ( 19, local_subrs_offset, "Subrs" ) CFF_FIELD_NUM ( 20, default_width, "defaultWidthX" ) CFF_FIELD_NUM ( 21, nominal_width, "nominalWidthX" ) /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cfftoken.h
C
apache-2.0
5,275
/***************************************************************************/ /* */ /* cfftypes.h */ /* */ /* Basic OpenType/CFF type definitions and interface (specification */ /* only). */ /* */ /* Copyright 1996-2003, 2006-2008, 2010-2011, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CFFTYPES_H__ #define __CFFTYPES_H__ #include <ft2build.h> #include FT_FREETYPE_H #include FT_TYPE1_TABLES_H #include FT_INTERNAL_SERVICE_H #include FT_SERVICE_POSTSCRIPT_CMAPS_H #include FT_INTERNAL_POSTSCRIPT_HINTS_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Struct> */ /* CFF_IndexRec */ /* */ /* <Description> */ /* A structure used to model a CFF Index table. */ /* */ /* <Fields> */ /* stream :: The source input stream. */ /* */ /* start :: The position of the first index byte in the */ /* input stream. */ /* */ /* count :: The number of elements in the index. */ /* */ /* off_size :: The size in bytes of object offsets in index. */ /* */ /* data_offset :: The position of first data byte in the index's */ /* bytes. */ /* */ /* data_size :: The size of the data table in this index. */ /* */ /* offsets :: A table of element offsets in the index. Must be */ /* loaded explicitly. */ /* */ /* bytes :: If the index is loaded in memory, its bytes. */ /* */ typedef struct CFF_IndexRec_ { FT_Stream stream; FT_ULong start; FT_UInt count; FT_Byte off_size; FT_ULong data_offset; FT_ULong data_size; FT_ULong* offsets; FT_Byte* bytes; } CFF_IndexRec, *CFF_Index; typedef struct CFF_EncodingRec_ { FT_UInt format; FT_ULong offset; FT_UInt count; FT_UShort sids [256]; /* avoid dynamic allocations */ FT_UShort codes[256]; } CFF_EncodingRec, *CFF_Encoding; typedef struct CFF_CharsetRec_ { FT_UInt format; FT_ULong offset; FT_UShort* sids; FT_UShort* cids; /* the inverse mapping of `sids'; only needed */ /* for CID-keyed fonts */ FT_UInt max_cid; FT_UInt num_glyphs; } CFF_CharsetRec, *CFF_Charset; typedef struct CFF_FontRecDictRec_ { FT_UInt version; FT_UInt notice; FT_UInt copyright; FT_UInt full_name; FT_UInt family_name; FT_UInt weight; FT_Bool is_fixed_pitch; FT_Fixed italic_angle; FT_Fixed underline_position; FT_Fixed underline_thickness; FT_Int paint_type; FT_Int charstring_type; FT_Matrix font_matrix; FT_Bool has_font_matrix; FT_ULong units_per_em; /* temporarily used as scaling value also */ FT_Vector font_offset; FT_ULong unique_id; FT_BBox font_bbox; FT_Pos stroke_width; FT_ULong charset_offset; FT_ULong encoding_offset; FT_ULong charstrings_offset; FT_ULong private_offset; FT_ULong private_size; FT_Long synthetic_base; FT_UInt embedded_postscript; /* these should only be used for the top-level font dictionary */ FT_UInt cid_registry; FT_UInt cid_ordering; FT_Long cid_supplement; FT_Long cid_font_version; FT_Long cid_font_revision; FT_Long cid_font_type; FT_ULong cid_count; FT_ULong cid_uid_base; FT_ULong cid_fd_array_offset; FT_ULong cid_fd_select_offset; FT_UInt cid_font_name; } CFF_FontRecDictRec, *CFF_FontRecDict; typedef struct CFF_PrivateRec_ { FT_Byte num_blue_values; FT_Byte num_other_blues; FT_Byte num_family_blues; FT_Byte num_family_other_blues; FT_Pos blue_values[14]; FT_Pos other_blues[10]; FT_Pos family_blues[14]; FT_Pos family_other_blues[10]; FT_Fixed blue_scale; FT_Pos blue_shift; FT_Pos blue_fuzz; FT_Pos standard_width; FT_Pos standard_height; FT_Byte num_snap_widths; FT_Byte num_snap_heights; FT_Pos snap_widths[13]; FT_Pos snap_heights[13]; FT_Bool force_bold; FT_Fixed force_bold_threshold; FT_Int lenIV; FT_Int language_group; FT_Fixed expansion_factor; FT_Long initial_random_seed; FT_ULong local_subrs_offset; FT_Pos default_width; FT_Pos nominal_width; } CFF_PrivateRec, *CFF_Private; typedef struct CFF_FDSelectRec_ { FT_Byte format; FT_UInt range_count; /* that's the table, taken from the file `as is' */ FT_Byte* data; FT_UInt data_size; /* small cache for format 3 only */ FT_UInt cache_first; FT_UInt cache_count; FT_Byte cache_fd; } CFF_FDSelectRec, *CFF_FDSelect; /* A SubFont packs a font dict and a private dict together. They are */ /* needed to support CID-keyed CFF fonts. */ typedef struct CFF_SubFontRec_ { CFF_FontRecDictRec font_dict; CFF_PrivateRec private_dict; CFF_IndexRec local_subrs_index; FT_Byte** local_subrs; /* array of pointers into Local Subrs INDEX data */ } CFF_SubFontRec, *CFF_SubFont; #define CFF_MAX_CID_FONTS 256 typedef struct CFF_FontRec_ { FT_Stream stream; FT_Memory memory; FT_UInt num_faces; FT_UInt num_glyphs; FT_Byte version_major; FT_Byte version_minor; FT_Byte header_size; FT_Byte absolute_offsize; CFF_IndexRec name_index; CFF_IndexRec top_dict_index; CFF_IndexRec global_subrs_index; CFF_EncodingRec encoding; CFF_CharsetRec charset; CFF_IndexRec charstrings_index; CFF_IndexRec font_dict_index; CFF_IndexRec private_index; CFF_IndexRec local_subrs_index; FT_String* font_name; /* array of pointers into Global Subrs INDEX data */ FT_Byte** global_subrs; /* array of pointers into String INDEX data stored at string_pool */ FT_UInt num_strings; FT_Byte** strings; FT_Byte* string_pool; CFF_SubFontRec top_font; FT_UInt num_subfonts; CFF_SubFont subfonts[CFF_MAX_CID_FONTS]; CFF_FDSelectRec fd_select; /* interface to PostScript hinter */ PSHinter_Service pshinter; /* interface to Postscript Names service */ FT_Service_PsCMaps psnames; /* since version 2.3.0 */ PS_FontInfoRec* font_info; /* font info dictionary */ /* since version 2.3.6 */ FT_String* registry; FT_String* ordering; /* since version 2.4.12 */ FT_Generic cf2_instance; } CFF_FontRec, *CFF_Font; FT_END_HEADER #endif /* __CFFTYPES_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cff/cfftypes.h
C
apache-2.0
9,195
# # FreeType 2 CFF module definition # # Copyright 1996-2000, 2006 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += CFF_DRIVER define CFF_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, cff_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)cff $(ECHO_DRIVER_DESC)OpenType fonts with extension *.otf$(ECHO_DRIVER_DONE) endef # EOF
YifuLiu/AliOS-Things
components/freetype/src/cff/module.mk
Makefile
apache-2.0
658
# # FreeType 2 OpenType/CFF driver configuration rules # # Copyright 1996-2001, 2003, 2011, 2013 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # OpenType driver directory # CFF_DIR := $(SRC_DIR)/cff CFF_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(CFF_DIR)) # CFF driver sources (i.e., C files) # CFF_DRV_SRC := $(CFF_DIR)/cffcmap.c \ $(CFF_DIR)/cffdrivr.c \ $(CFF_DIR)/cffgload.c \ $(CFF_DIR)/cffload.c \ $(CFF_DIR)/cffobjs.c \ $(CFF_DIR)/cffparse.c \ $(CFF_DIR)/cffpic.c \ $(CFF_DIR)/cf2arrst.c \ $(CFF_DIR)/cf2blues.c \ $(CFF_DIR)/cf2error.c \ $(CFF_DIR)/cf2font.c \ $(CFF_DIR)/cf2ft.c \ $(CFF_DIR)/cf2hints.c \ $(CFF_DIR)/cf2intrp.c \ $(CFF_DIR)/cf2read.c \ $(CFF_DIR)/cf2stack.c # CFF driver headers # CFF_DRV_H := $(CFF_DRV_SRC:%.c=%.h) \ $(CFF_DIR)/cfferrs.h \ $(CFF_DIR)/cfftoken.h \ $(CFF_DIR)/cfftypes.h \ $(CFF_DIR)/cf2fixed.h \ $(CFF_DIR)/cf2glue.h \ $(CFF_DIR)/cf2types.h # CFF driver object(s) # # CFF_DRV_OBJ_M is used during `multi' builds # CFF_DRV_OBJ_S is used during `single' builds # CFF_DRV_OBJ_M := $(CFF_DRV_SRC:$(CFF_DIR)/%.c=$(OBJ_DIR)/%.$O) CFF_DRV_OBJ_S := $(OBJ_DIR)/cff.$O # CFF driver source file for single build # CFF_DRV_SRC_S := $(CFF_DIR)/cff.c # CFF driver - single object # $(CFF_DRV_OBJ_S): $(CFF_DRV_SRC_S) $(CFF_DRV_SRC) $(FREETYPE_H) $(CFF_DRV_H) $(CFF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(CFF_DRV_SRC_S)) # CFF driver - multiple objects # $(OBJ_DIR)/%.$O: $(CFF_DIR)/%.c $(FREETYPE_H) $(CFF_DRV_H) $(CFF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(CFF_DRV_OBJ_S) DRV_OBJS_M += $(CFF_DRV_OBJ_M) # EOF
YifuLiu/AliOS-Things
components/freetype/src/cff/rules.mk
Makefile
apache-2.0
2,266
/***************************************************************************/ /* */ /* ciderrs.h */ /* */ /* CID error codes (specification only). */ /* */ /* Copyright 2001, 2012 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to define the CID error enumeration constants. */ /* */ /*************************************************************************/ #ifndef __CIDERRS_H__ #define __CIDERRS_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX CID_Err_ #define FT_ERR_BASE FT_Mod_Err_CID #include FT_ERRORS_H #endif /* __CIDERRS_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/ciderrs.h
C
apache-2.0
1,892
/***************************************************************************/ /* */ /* cidgload.c */ /* */ /* CID-keyed Type1 Glyph Loader (body). */ /* */ /* Copyright 1996-2007, 2009, 2010, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include "cidload.h" #include "cidgload.h" #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_OUTLINE_H #include FT_INTERNAL_CALC_H #include "ciderrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cidgload FT_CALLBACK_DEF( FT_Error ) cid_load_glyph( T1_Decoder decoder, FT_UInt glyph_index ) { CID_Face face = (CID_Face)decoder->builder.face; CID_FaceInfo cid = &face->cid; FT_Byte* p; FT_UInt fd_select; FT_Stream stream = face->cid_stream; FT_Error error = FT_Err_Ok; FT_Byte* charstring = 0; FT_Memory memory = face->root.memory; FT_ULong glyph_length = 0; PSAux_Service psaux = (PSAux_Service)face->psaux; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Incremental_InterfaceRec *inc = face->root.internal->incremental_interface; #endif FT_TRACE1(( "cid_load_glyph: glyph index %d\n", glyph_index )); #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using */ /* the callback function. */ if ( inc ) { FT_Data glyph_data; error = inc->funcs->get_glyph_data( inc->object, glyph_index, &glyph_data ); if ( error ) goto Exit; p = (FT_Byte*)glyph_data.pointer; fd_select = (FT_UInt)cid_get_offset( &p, (FT_Byte)cid->fd_bytes ); if ( glyph_data.length != 0 ) { glyph_length = glyph_data.length - cid->fd_bytes; (void)FT_ALLOC( charstring, glyph_length ); if ( !error ) ft_memcpy( charstring, glyph_data.pointer + cid->fd_bytes, glyph_length ); } inc->funcs->free_glyph_data( inc->object, &glyph_data ); if ( error ) goto Exit; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /* For ordinary fonts read the CID font dictionary index */ /* and charstring offset from the CIDMap. */ { FT_UInt entry_len = cid->fd_bytes + cid->gd_bytes; FT_ULong off1; if ( FT_STREAM_SEEK( cid->data_offset + cid->cidmap_offset + glyph_index * entry_len ) || FT_FRAME_ENTER( 2 * entry_len ) ) goto Exit; p = (FT_Byte*)stream->cursor; fd_select = (FT_UInt) cid_get_offset( &p, (FT_Byte)cid->fd_bytes ); off1 = (FT_ULong)cid_get_offset( &p, (FT_Byte)cid->gd_bytes ); p += cid->fd_bytes; glyph_length = cid_get_offset( &p, (FT_Byte)cid->gd_bytes ) - off1; FT_FRAME_EXIT(); if ( fd_select >= (FT_UInt)cid->num_dicts ) { error = FT_THROW( Invalid_Offset ); goto Exit; } if ( glyph_length == 0 ) goto Exit; if ( FT_ALLOC( charstring, glyph_length ) ) goto Exit; if ( FT_STREAM_READ_AT( cid->data_offset + off1, charstring, glyph_length ) ) goto Exit; } /* Now set up the subrs array and parse the charstrings. */ { CID_FaceDict dict; CID_Subrs cid_subrs = face->subrs + fd_select; FT_Int cs_offset; /* Set up subrs */ decoder->num_subrs = cid_subrs->num_subrs; decoder->subrs = cid_subrs->code; decoder->subrs_len = 0; /* Set up font matrix */ dict = cid->font_dicts + fd_select; decoder->font_matrix = dict->font_matrix; decoder->font_offset = dict->font_offset; decoder->lenIV = dict->private_dict.lenIV; /* Decode the charstring. */ /* Adjustment for seed bytes. */ cs_offset = ( decoder->lenIV >= 0 ? decoder->lenIV : 0 ); /* Decrypt only if lenIV >= 0. */ if ( decoder->lenIV >= 0 ) psaux->t1_decrypt( charstring, glyph_length, 4330 ); error = decoder->funcs.parse_charstrings( decoder, charstring + cs_offset, (FT_Int)glyph_length - cs_offset ); } FT_FREE( charstring ); #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts can optionally override the metrics. */ if ( !error && inc && inc->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec metrics; metrics.bearing_x = FIXED_TO_INT( decoder->builder.left_bearing.x ); metrics.bearing_y = 0; metrics.advance = FIXED_TO_INT( decoder->builder.advance.x ); metrics.advance_v = FIXED_TO_INT( decoder->builder.advance.y ); error = inc->funcs->get_glyph_metrics( inc->object, glyph_index, FALSE, &metrics ); decoder->builder.left_bearing.x = INT_TO_FIXED( metrics.bearing_x ); decoder->builder.advance.x = INT_TO_FIXED( metrics.advance ); decoder->builder.advance.y = INT_TO_FIXED( metrics.advance_v ); } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ Exit: return error; } #if 0 /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** *********/ /********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/ /********** *********/ /********** The following code is in charge of computing *********/ /********** the maximum advance width of the font. It *********/ /********** quickly processes each glyph charstring to *********/ /********** extract the value from either a `sbw' or `seac' *********/ /********** operator. *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( FT_Error ) cid_face_compute_max_advance( CID_Face face, FT_Int* max_advance ) { FT_Error error; T1_DecoderRec decoder; FT_Int glyph_index; PSAux_Service psaux = (PSAux_Service)face->psaux; *max_advance = 0; /* Initialize load decoder */ error = psaux->t1_decoder_funcs->init( &decoder, (FT_Face)face, 0, /* size */ 0, /* glyph slot */ 0, /* glyph names! XXX */ 0, /* blend == 0 */ 0, /* hinting == 0 */ cid_load_glyph ); if ( error ) return error; /* TODO: initialize decoder.len_buildchar and decoder.buildchar */ /* if we ever support CID-keyed multiple master fonts */ decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; /* for each glyph, parse the glyph charstring and extract */ /* the advance width */ for ( glyph_index = 0; glyph_index < face->root.num_glyphs; glyph_index++ ) { /* now get load the unscaled outline */ error = cid_load_glyph( &decoder, glyph_index ); /* ignore the error if one occurred - skip to next glyph */ } *max_advance = FIXED_TO_INT( decoder.builder.advance.x ); psaux->t1_decoder_funcs->done( &decoder ); return FT_Err_Ok; } #endif /* 0 */ FT_LOCAL_DEF( FT_Error ) cid_slot_load_glyph( FT_GlyphSlot cidglyph, /* CID_GlyphSlot */ FT_Size cidsize, /* CID_Size */ FT_UInt glyph_index, FT_Int32 load_flags ) { CID_GlyphSlot glyph = (CID_GlyphSlot)cidglyph; FT_Error error; T1_DecoderRec decoder; CID_Face face = (CID_Face)cidglyph->face; FT_Bool hinting; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_Matrix font_matrix; FT_Vector font_offset; if ( glyph_index >= (FT_UInt)face->root.num_glyphs ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( load_flags & FT_LOAD_NO_RECURSE ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; glyph->x_scale = cidsize->metrics.x_scale; glyph->y_scale = cidsize->metrics.y_scale; cidglyph->outline.n_points = 0; cidglyph->outline.n_contours = 0; hinting = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 && ( load_flags & FT_LOAD_NO_HINTING ) == 0 ); cidglyph->format = FT_GLYPH_FORMAT_OUTLINE; error = psaux->t1_decoder_funcs->init( &decoder, cidglyph->face, cidsize, cidglyph, 0, /* glyph names -- XXX */ 0, /* blend == 0 */ hinting, FT_LOAD_TARGET_MODE( load_flags ), cid_load_glyph ); if ( error ) goto Exit; /* TODO: initialize decoder.len_buildchar and decoder.buildchar */ /* if we ever support CID-keyed multiple master fonts */ /* set up the decoder */ decoder.builder.no_recurse = FT_BOOL( ( ( load_flags & FT_LOAD_NO_RECURSE ) != 0 ) ); error = cid_load_glyph( &decoder, glyph_index ); if ( error ) goto Exit; font_matrix = decoder.font_matrix; font_offset = decoder.font_offset; /* save new glyph tables */ psaux->t1_decoder_funcs->done( &decoder ); /* now set the metrics -- this is rather simple, as */ /* the left side bearing is the xMin, and the top side */ /* bearing the yMax */ cidglyph->outline.flags &= FT_OUTLINE_OWNER; cidglyph->outline.flags |= FT_OUTLINE_REVERSE_FILL; /* for composite glyphs, return only left side bearing and */ /* advance width */ if ( load_flags & FT_LOAD_NO_RECURSE ) { FT_Slot_Internal internal = cidglyph->internal; cidglyph->metrics.horiBearingX = FIXED_TO_INT( decoder.builder.left_bearing.x ); cidglyph->metrics.horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); internal->glyph_matrix = font_matrix; internal->glyph_delta = font_offset; internal->glyph_transformed = 1; } else { FT_BBox cbox; FT_Glyph_Metrics* metrics = &cidglyph->metrics; FT_Vector advance; /* copy the _unscaled_ advance width */ metrics->horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); cidglyph->linearHoriAdvance = FIXED_TO_INT( decoder.builder.advance.x ); cidglyph->internal->glyph_transformed = 0; /* make up vertical ones */ metrics->vertAdvance = ( face->cid.font_bbox.yMax - face->cid.font_bbox.yMin ) >> 16; cidglyph->linearVertAdvance = metrics->vertAdvance; cidglyph->format = FT_GLYPH_FORMAT_OUTLINE; if ( cidsize->metrics.y_ppem < 24 ) cidglyph->outline.flags |= FT_OUTLINE_HIGH_PRECISION; /* apply the font matrix */ FT_Outline_Transform( &cidglyph->outline, &font_matrix ); FT_Outline_Translate( &cidglyph->outline, font_offset.x, font_offset.y ); advance.x = metrics->horiAdvance; advance.y = 0; FT_Vector_Transform( &advance, &font_matrix ); metrics->horiAdvance = advance.x + font_offset.x; advance.x = 0; advance.y = metrics->vertAdvance; FT_Vector_Transform( &advance, &font_matrix ); metrics->vertAdvance = advance.y + font_offset.y; if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 ) { /* scale the outline and the metrics */ FT_Int n; FT_Outline* cur = decoder.builder.base; FT_Vector* vec = cur->points; FT_Fixed x_scale = glyph->x_scale; FT_Fixed y_scale = glyph->y_scale; /* First of all, scale the points */ if ( !hinting || !decoder.builder.hints_funcs ) for ( n = cur->n_points; n > 0; n--, vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } /* Then scale the metrics */ metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale ); } /* compute the other metrics */ FT_Outline_Get_CBox( &cidglyph->outline, &cbox ); metrics->width = cbox.xMax - cbox.xMin; metrics->height = cbox.yMax - cbox.yMin; metrics->horiBearingX = cbox.xMin; metrics->horiBearingY = cbox.yMax; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* make up vertical ones */ ft_synthesize_vertical_metrics( metrics, metrics->vertAdvance ); } } Exit: return error; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidgload.c
C
apache-2.0
15,541
/***************************************************************************/ /* */ /* cidgload.h */ /* */ /* OpenType Glyph Loader (specification). */ /* */ /* Copyright 1996-2001, 2002, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CIDGLOAD_H__ #define __CIDGLOAD_H__ #include <ft2build.h> #include "cidobjs.h" FT_BEGIN_HEADER #if 0 /* Compute the maximum advance width of a font through quick parsing */ FT_LOCAL( FT_Error ) cid_face_compute_max_advance( CID_Face face, FT_Int* max_advance ); #endif /* 0 */ FT_LOCAL( FT_Error ) cid_slot_load_glyph( FT_GlyphSlot glyph, /* CID_Glyph_Slot */ FT_Size size, /* CID_Size */ FT_UInt glyph_index, FT_Int32 load_flags ); FT_END_HEADER #endif /* __CIDGLOAD_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidgload.h
C
apache-2.0
1,914
/***************************************************************************/ /* */ /* cidload.c */ /* */ /* CID-keyed Type1 font loader (body). */ /* */ /* Copyright 1996-2006, 2009, 2011-2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_CONFIG_CONFIG_H #include FT_MULTIPLE_MASTERS_H #include FT_INTERNAL_TYPE1_TYPES_H #include "cidload.h" #include "ciderrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cidload /* read a single offset */ FT_LOCAL_DEF( FT_Long ) cid_get_offset( FT_Byte* *start, FT_Byte offsize ) { FT_ULong result; FT_Byte* p = *start; for ( result = 0; offsize > 0; offsize-- ) { result <<= 8; result |= *p++; } *start = p; return (FT_Long)result; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE 1 SYMBOL PARSING *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static FT_Error cid_load_keyword( CID_Face face, CID_Loader* loader, const T1_Field keyword ) { FT_Error error; CID_Parser* parser = &loader->parser; FT_Byte* object; void* dummy_object; CID_FaceInfo cid = &face->cid; /* if the keyword has a dedicated callback, call it */ if ( keyword->type == T1_FIELD_TYPE_CALLBACK ) { keyword->reader( (FT_Face)face, parser ); error = parser->root.error; goto Exit; } /* we must now compute the address of our target object */ switch ( keyword->location ) { case T1_FIELD_LOCATION_CID_INFO: object = (FT_Byte*)cid; break; case T1_FIELD_LOCATION_FONT_INFO: object = (FT_Byte*)&cid->font_info; break; case T1_FIELD_LOCATION_FONT_EXTRA: object = (FT_Byte*)&face->font_extra; break; case T1_FIELD_LOCATION_BBOX: object = (FT_Byte*)&cid->font_bbox; break; default: { CID_FaceDict dict; if ( parser->num_dict < 0 || parser->num_dict >= cid->num_dicts ) { FT_ERROR(( "cid_load_keyword: invalid use of `%s'\n", keyword->ident )); error = FT_THROW( Syntax_Error ); goto Exit; } dict = cid->font_dicts + parser->num_dict; switch ( keyword->location ) { case T1_FIELD_LOCATION_PRIVATE: object = (FT_Byte*)&dict->private_dict; break; default: object = (FT_Byte*)dict; } } } dummy_object = object; /* now, load the keyword data in the object's field(s) */ if ( keyword->type == T1_FIELD_TYPE_INTEGER_ARRAY || keyword->type == T1_FIELD_TYPE_FIXED_ARRAY ) error = cid_parser_load_field_table( &loader->parser, keyword, &dummy_object ); else error = cid_parser_load_field( &loader->parser, keyword, &dummy_object ); Exit: return error; } FT_CALLBACK_DEF( FT_Error ) cid_parse_font_matrix( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { FT_Matrix* matrix; FT_Vector* offset; FT_Int result; dict = face->cid.font_dicts + parser->num_dict; matrix = &dict->font_matrix; offset = &dict->font_offset; result = cid_parser_to_fixed_array( parser, 6, temp, 3 ); if ( result < 6 ) return FT_THROW( Invalid_File_Format ); temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" )); return FT_THROW( Invalid_File_Format ); } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale ); /* we need to scale the values by 1.0/temp[3] */ if ( temp_scale != 0x10000L ) { temp[0] = FT_DivFix( temp[0], temp_scale ); temp[1] = FT_DivFix( temp[1], temp_scale ); temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; /* note that the font offsets are expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; } return FT_Err_Ok; } FT_CALLBACK_DEF( FT_Error ) parse_fd_array( CID_Face face, CID_Parser* parser ) { CID_FaceInfo cid = &face->cid; FT_Memory memory = face->root.memory; FT_Error error = FT_Err_Ok; FT_Long num_dicts; num_dicts = cid_parser_to_int( parser ); if ( !cid->font_dicts ) { FT_Int n; if ( FT_NEW_ARRAY( cid->font_dicts, num_dicts ) ) goto Exit; cid->num_dicts = (FT_UInt)num_dicts; /* don't forget to set a few defaults */ for ( n = 0; n < cid->num_dicts; n++ ) { CID_FaceDict dict = cid->font_dicts + n; /* default value for lenIV */ dict->private_dict.lenIV = 4; } } Exit: return error; } /* by mistake, `expansion_factor' appears both in PS_PrivateRec */ /* and CID_FaceDictRec (both are public header files and can't */ /* changed); we simply copy the value */ FT_CALLBACK_DEF( FT_Error ) parse_expansion_factor( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { dict = face->cid.font_dicts + parser->num_dict; dict->expansion_factor = cid_parser_to_fixed( parser, 0 ); dict->private_dict.expansion_factor = dict->expansion_factor; } return FT_Err_Ok; } static const T1_FieldRec cid_field_records[] = { #include "cidtoken.h" T1_FIELD_CALLBACK( "FDArray", parse_fd_array, 0 ) T1_FIELD_CALLBACK( "FontMatrix", cid_parse_font_matrix, 0 ) T1_FIELD_CALLBACK( "ExpansionFactor", parse_expansion_factor, 0 ) { 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 } }; static FT_Error cid_parse_dict( CID_Face face, CID_Loader* loader, FT_Byte* base, FT_Long size ) { CID_Parser* parser = &loader->parser; parser->root.cursor = base; parser->root.limit = base + size; parser->root.error = FT_Err_Ok; { FT_Byte* cur = base; FT_Byte* limit = cur + size; for (;;) { FT_Byte* newlimit; parser->root.cursor = cur; cid_parser_skip_spaces( parser ); if ( parser->root.cursor >= limit ) newlimit = limit - 1 - 17; else newlimit = parser->root.cursor - 17; /* look for `%ADOBeginFontDict' */ for ( ; cur < newlimit; cur++ ) { if ( *cur == '%' && ft_strncmp( (char*)cur, "%ADOBeginFontDict", 17 ) == 0 ) { /* if /FDArray was found, then cid->num_dicts is > 0, and */ /* we can start increasing parser->num_dict */ if ( face->cid.num_dicts > 0 ) parser->num_dict++; } } cur = parser->root.cursor; /* no error can occur in cid_parser_skip_spaces */ if ( cur >= limit ) break; cid_parser_skip_PS_token( parser ); if ( parser->root.cursor >= limit || parser->root.error ) break; /* look for immediates */ if ( *cur == '/' && cur + 2 < limit ) { FT_PtrDist len; cur++; len = parser->root.cursor - cur; if ( len > 0 && len < 22 ) { /* now compare the immediate name to the keyword table */ T1_Field keyword = (T1_Field)cid_field_records; for (;;) { FT_Byte* name; name = (FT_Byte*)keyword->ident; if ( !name ) break; if ( cur[0] == name[0] && len == (FT_PtrDist)ft_strlen( (const char*)name ) ) { FT_PtrDist n; for ( n = 1; n < len; n++ ) if ( cur[n] != name[n] ) break; if ( n >= len ) { /* we found it - run the parsing callback */ parser->root.error = cid_load_keyword( face, loader, keyword ); if ( parser->root.error ) return parser->root.error; break; } } keyword++; } } } cur = parser->root.cursor; } } return parser->root.error; } /* read the subrmap and the subrs of each font dict */ static FT_Error cid_read_subrs( CID_Face face ) { CID_FaceInfo cid = &face->cid; FT_Memory memory = face->root.memory; FT_Stream stream = face->cid_stream; FT_Error error; FT_Int n; CID_Subrs subr; FT_UInt max_offsets = 0; FT_ULong* offsets = 0; PSAux_Service psaux = (PSAux_Service)face->psaux; if ( FT_NEW_ARRAY( face->subrs, cid->num_dicts ) ) goto Exit; subr = face->subrs; for ( n = 0; n < cid->num_dicts; n++, subr++ ) { CID_FaceDict dict = cid->font_dicts + n; FT_Int lenIV = dict->private_dict.lenIV; FT_UInt count, num_subrs = dict->num_subrs; FT_ULong data_len; FT_Byte* p; /* Check for possible overflow. */ if ( num_subrs == FT_UINT_MAX ) { error = FT_THROW( Syntax_Error ); goto Fail; } /* reallocate offsets array if needed */ if ( num_subrs + 1 > max_offsets ) { FT_UInt new_max = FT_PAD_CEIL( num_subrs + 1, 4 ); if ( new_max <= max_offsets ) { error = FT_THROW( Syntax_Error ); goto Fail; } if ( FT_RENEW_ARRAY( offsets, max_offsets, new_max ) ) goto Fail; max_offsets = new_max; } /* read the subrmap's offsets */ if ( FT_STREAM_SEEK( cid->data_offset + dict->subrmap_offset ) || FT_FRAME_ENTER( ( num_subrs + 1 ) * dict->sd_bytes ) ) goto Fail; p = (FT_Byte*)stream->cursor; for ( count = 0; count <= num_subrs; count++ ) offsets[count] = cid_get_offset( &p, (FT_Byte)dict->sd_bytes ); FT_FRAME_EXIT(); /* offsets must be ordered */ for ( count = 1; count <= num_subrs; count++ ) if ( offsets[count - 1] > offsets[count] ) goto Fail; /* now, compute the size of subrs charstrings, */ /* allocate, and read them */ data_len = offsets[num_subrs] - offsets[0]; if ( FT_NEW_ARRAY( subr->code, num_subrs + 1 ) || FT_ALLOC( subr->code[0], data_len ) ) goto Fail; if ( FT_STREAM_SEEK( cid->data_offset + offsets[0] ) || FT_STREAM_READ( subr->code[0], data_len ) ) goto Fail; /* set up pointers */ for ( count = 1; count <= num_subrs; count++ ) { FT_ULong len; len = offsets[count] - offsets[count - 1]; subr->code[count] = subr->code[count - 1] + len; } /* decrypt subroutines, but only if lenIV >= 0 */ if ( lenIV >= 0 ) { for ( count = 0; count < num_subrs; count++ ) { FT_ULong len; len = offsets[count + 1] - offsets[count]; psaux->t1_decrypt( subr->code[count], len, 4330 ); } } subr->num_subrs = num_subrs; } Exit: FT_FREE( offsets ); return error; Fail: if ( face->subrs ) { for ( n = 0; n < cid->num_dicts; n++ ) { if ( face->subrs[n].code ) FT_FREE( face->subrs[n].code[0] ); FT_FREE( face->subrs[n].code ); } FT_FREE( face->subrs ); } goto Exit; } static void cid_init_loader( CID_Loader* loader, CID_Face face ) { FT_UNUSED( face ); FT_MEM_ZERO( loader, sizeof ( *loader ) ); } static void cid_done_loader( CID_Loader* loader ) { CID_Parser* parser = &loader->parser; /* finalize parser */ cid_parser_done( parser ); } static FT_Error cid_hex_to_binary( FT_Byte* data, FT_Long data_len, FT_ULong offset, CID_Face face ) { FT_Stream stream = face->root.stream; FT_Error error; FT_Byte buffer[256]; FT_Byte *p, *plimit; FT_Byte *d, *dlimit; FT_Byte val; FT_Bool upper_nibble, done; if ( FT_STREAM_SEEK( offset ) ) goto Exit; d = data; dlimit = d + data_len; p = buffer; plimit = p; upper_nibble = 1; done = 0; while ( d < dlimit ) { if ( p >= plimit ) { FT_ULong oldpos = FT_STREAM_POS(); FT_ULong size = stream->size - oldpos; if ( size == 0 ) { error = FT_THROW( Syntax_Error ); goto Exit; } if ( FT_STREAM_READ( buffer, 256 > size ? size : 256 ) ) goto Exit; p = buffer; plimit = p + FT_STREAM_POS() - oldpos; } if ( ft_isdigit( *p ) ) val = (FT_Byte)( *p - '0' ); else if ( *p >= 'a' && *p <= 'f' ) val = (FT_Byte)( *p - 'a' ); else if ( *p >= 'A' && *p <= 'F' ) val = (FT_Byte)( *p - 'A' + 10 ); else if ( *p == ' ' || *p == '\t' || *p == '\r' || *p == '\n' || *p == '\f' || *p == '\0' ) { p++; continue; } else if ( *p == '>' ) { val = 0; done = 1; } else { error = FT_THROW( Syntax_Error ); goto Exit; } if ( upper_nibble ) *d = (FT_Byte)( val << 4 ); else { *d = (FT_Byte)( *d + val ); d++; } upper_nibble = (FT_Byte)( 1 - upper_nibble ); if ( done ) break; p++; } error = FT_Err_Ok; Exit: return error; } FT_LOCAL_DEF( FT_Error ) cid_face_open( CID_Face face, FT_Int face_index ) { CID_Loader loader; CID_Parser* parser; FT_Memory memory = face->root.memory; FT_Error error; cid_init_loader( &loader, face ); parser = &loader.parser; error = cid_parser_new( parser, face->root.stream, face->root.memory, (PSAux_Service)face->psaux ); if ( error ) goto Exit; error = cid_parse_dict( face, &loader, parser->postscript, parser->postscript_len ); if ( error ) goto Exit; if ( face_index < 0 ) goto Exit; if ( FT_NEW( face->cid_stream ) ) goto Exit; if ( parser->binary_length ) { /* we must convert the data section from hexadecimal to binary */ if ( FT_ALLOC( face->binary_data, parser->binary_length ) || cid_hex_to_binary( face->binary_data, parser->binary_length, parser->data_offset, face ) ) goto Exit; FT_Stream_OpenMemory( face->cid_stream, face->binary_data, parser->binary_length ); face->cid.data_offset = 0; } else { *face->cid_stream = *face->root.stream; face->cid.data_offset = loader.parser.data_offset; } error = cid_read_subrs( face ); Exit: cid_done_loader( &loader ); return error; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidload.c
C
apache-2.0
18,571
/***************************************************************************/ /* */ /* cidload.h */ /* */ /* CID-keyed Type1 font loader (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CIDLOAD_H__ #define __CIDLOAD_H__ #include <ft2build.h> #include FT_INTERNAL_STREAM_H #include "cidparse.h" FT_BEGIN_HEADER typedef struct CID_Loader_ { CID_Parser parser; /* parser used to read the stream */ FT_Int num_chars; /* number of characters in encoding */ } CID_Loader; FT_LOCAL( FT_Long ) cid_get_offset( FT_Byte** start, FT_Byte offsize ); FT_LOCAL( FT_Error ) cid_face_open( CID_Face face, FT_Int face_index ); FT_END_HEADER #endif /* __CIDLOAD_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidload.h
C
apache-2.0
1,837
/***************************************************************************/ /* */ /* cidobjs.c */ /* */ /* CID objects manager (body). */ /* */ /* Copyright 1996-2006, 2008, 2010-2011, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include "cidgload.h" #include "cidload.h" #include FT_SERVICE_POSTSCRIPT_CMAPS_H #include FT_INTERNAL_POSTSCRIPT_AUX_H #include FT_INTERNAL_POSTSCRIPT_HINTS_H #include "ciderrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cidobjs /*************************************************************************/ /* */ /* SLOT FUNCTIONS */ /* */ /*************************************************************************/ FT_LOCAL_DEF( void ) cid_slot_done( FT_GlyphSlot slot ) { slot->internal->glyph_hints = 0; } FT_LOCAL_DEF( FT_Error ) cid_slot_init( FT_GlyphSlot slot ) { CID_Face face; PSHinter_Service pshinter; face = (CID_Face)slot->face; pshinter = (PSHinter_Service)face->pshinter; if ( pshinter ) { FT_Module module; module = FT_Get_Module( slot->face->driver->root.library, "pshinter" ); if ( module ) { T1_Hints_Funcs funcs; funcs = pshinter->get_t1_funcs( module ); slot->internal->glyph_hints = (void*)funcs; } } return 0; } /*************************************************************************/ /* */ /* SIZE FUNCTIONS */ /* */ /*************************************************************************/ static PSH_Globals_Funcs cid_size_get_globals_funcs( CID_Size size ) { CID_Face face = (CID_Face)size->root.face; PSHinter_Service pshinter = (PSHinter_Service)face->pshinter; FT_Module module; module = FT_Get_Module( size->root.face->driver->root.library, "pshinter" ); return ( module && pshinter && pshinter->get_globals_funcs ) ? pshinter->get_globals_funcs( module ) : 0; } FT_LOCAL_DEF( void ) cid_size_done( FT_Size cidsize ) /* CID_Size */ { CID_Size size = (CID_Size)cidsize; if ( cidsize->internal ) { PSH_Globals_Funcs funcs; funcs = cid_size_get_globals_funcs( size ); if ( funcs ) funcs->destroy( (PSH_Globals)cidsize->internal ); cidsize->internal = 0; } } FT_LOCAL_DEF( FT_Error ) cid_size_init( FT_Size cidsize ) /* CID_Size */ { CID_Size size = (CID_Size)cidsize; FT_Error error = FT_Err_Ok; PSH_Globals_Funcs funcs = cid_size_get_globals_funcs( size ); if ( funcs ) { PSH_Globals globals; CID_Face face = (CID_Face)cidsize->face; CID_FaceDict dict = face->cid.font_dicts + face->root.face_index; PS_Private priv = &dict->private_dict; error = funcs->create( cidsize->face->memory, priv, &globals ); if ( !error ) cidsize->internal = (FT_Size_Internal)(void*)globals; } return error; } FT_LOCAL( FT_Error ) cid_size_request( FT_Size size, FT_Size_Request req ) { PSH_Globals_Funcs funcs; FT_Request_Metrics( size->face, req ); funcs = cid_size_get_globals_funcs( (CID_Size)size ); if ( funcs ) funcs->set_scale( (PSH_Globals)size->internal, size->metrics.x_scale, size->metrics.y_scale, 0, 0 ); return FT_Err_Ok; } /*************************************************************************/ /* */ /* FACE FUNCTIONS */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* cid_face_done */ /* */ /* <Description> */ /* Finalizes a given face object. */ /* */ /* <Input> */ /* face :: A pointer to the face object to destroy. */ /* */ FT_LOCAL_DEF( void ) cid_face_done( FT_Face cidface ) /* CID_Face */ { CID_Face face = (CID_Face)cidface; FT_Memory memory; CID_FaceInfo cid; PS_FontInfo info; if ( !face ) return; cid = &face->cid; info = &cid->font_info; memory = cidface->memory; /* release subrs */ if ( face->subrs ) { FT_Int n; for ( n = 0; n < cid->num_dicts; n++ ) { CID_Subrs subr = face->subrs + n; if ( subr->code ) { FT_FREE( subr->code[0] ); FT_FREE( subr->code ); } } FT_FREE( face->subrs ); } /* release FontInfo strings */ FT_FREE( info->version ); FT_FREE( info->notice ); FT_FREE( info->full_name ); FT_FREE( info->family_name ); FT_FREE( info->weight ); /* release font dictionaries */ FT_FREE( cid->font_dicts ); cid->num_dicts = 0; /* release other strings */ FT_FREE( cid->cid_font_name ); FT_FREE( cid->registry ); FT_FREE( cid->ordering ); cidface->family_name = 0; cidface->style_name = 0; FT_FREE( face->binary_data ); FT_FREE( face->cid_stream ); } /*************************************************************************/ /* */ /* <Function> */ /* cid_face_init */ /* */ /* <Description> */ /* Initializes a given CID face object. */ /* */ /* <Input> */ /* stream :: The source font stream. */ /* */ /* face_index :: The index of the font face in the resource. */ /* */ /* num_params :: Number of additional generic parameters. Ignored. */ /* */ /* params :: Additional generic parameters. Ignored. */ /* */ /* <InOut> */ /* face :: The newly built face object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_LOCAL_DEF( FT_Error ) cid_face_init( FT_Stream stream, FT_Face cidface, /* CID_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { CID_Face face = (CID_Face)cidface; FT_Error error; PSAux_Service psaux; PSHinter_Service pshinter; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); cidface->num_faces = 1; psaux = (PSAux_Service)face->psaux; if ( !psaux ) { psaux = (PSAux_Service)FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); if ( !psaux ) { FT_ERROR(( "cid_face_init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } face->psaux = psaux; } pshinter = (PSHinter_Service)face->pshinter; if ( !pshinter ) { pshinter = (PSHinter_Service)FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "pshinter" ); face->pshinter = pshinter; } FT_TRACE2(( "CID driver\n" )); /* open the tokenizer; this will also check the font format */ if ( FT_STREAM_SEEK( 0 ) ) goto Exit; error = cid_face_open( face, face_index ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ /* XXX: handle CID fonts with more than a single face */ if ( face_index != 0 ) { FT_ERROR(( "cid_face_init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* now load the font program into the face object */ /* initialize the face object fields */ /* set up root face fields */ { CID_FaceInfo cid = &face->cid; PS_FontInfo info = &cid->font_info; cidface->num_glyphs = cid->cid_count; cidface->num_charmaps = 0; cidface->face_index = face_index; cidface->face_flags |= FT_FACE_FLAG_SCALABLE | /* scalable outlines */ FT_FACE_FLAG_HORIZONTAL | /* horizontal data */ FT_FACE_FLAG_HINTER; /* has native hinter */ if ( info->is_fixed_pitch ) cidface->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* XXX: TODO: add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a /FontName dictionary entry! */ cidface->family_name = info->family_name; /* assume "Regular" style if we don't know better */ cidface->style_name = (char *)"Regular"; if ( cidface->family_name ) { char* full = info->full_name; char* family = cidface->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) cidface->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( cid->cid_font_name ) cidface->family_name = cid->cid_font_name; } /* compute style flags */ cidface->style_flags = 0; if ( info->italic_angle ) cidface->style_flags |= FT_STYLE_FLAG_ITALIC; if ( info->weight ) { if ( !ft_strcmp( info->weight, "Bold" ) || !ft_strcmp( info->weight, "Black" ) ) cidface->style_flags |= FT_STYLE_FLAG_BOLD; } /* no embedded bitmap support */ cidface->num_fixed_sizes = 0; cidface->available_sizes = 0; cidface->bbox.xMin = cid->font_bbox.xMin >> 16; cidface->bbox.yMin = cid->font_bbox.yMin >> 16; /* no `U' suffix here to 0xFFFF! */ cidface->bbox.xMax = ( cid->font_bbox.xMax + 0xFFFF ) >> 16; cidface->bbox.yMax = ( cid->font_bbox.yMax + 0xFFFF ) >> 16; if ( !cidface->units_per_EM ) cidface->units_per_EM = 1000; cidface->ascender = (FT_Short)( cidface->bbox.yMax ); cidface->descender = (FT_Short)( cidface->bbox.yMin ); cidface->height = (FT_Short)( ( cidface->units_per_EM * 12 ) / 10 ); if ( cidface->height < cidface->ascender - cidface->descender ) cidface->height = (FT_Short)( cidface->ascender - cidface->descender ); cidface->underline_position = (FT_Short)info->underline_position; cidface->underline_thickness = (FT_Short)info->underline_thickness; } Exit: return error; } /*************************************************************************/ /* */ /* <Function> */ /* cid_driver_init */ /* */ /* <Description> */ /* Initializes a given CID driver object. */ /* */ /* <Input> */ /* driver :: A handle to the target driver object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_LOCAL_DEF( FT_Error ) cid_driver_init( FT_Module driver ) { FT_UNUSED( driver ); return FT_Err_Ok; } /*************************************************************************/ /* */ /* <Function> */ /* cid_driver_done */ /* */ /* <Description> */ /* Finalizes a given CID driver. */ /* */ /* <Input> */ /* driver :: A handle to the target CID driver. */ /* */ FT_LOCAL_DEF( void ) cid_driver_done( FT_Module driver ) { FT_UNUSED( driver ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidobjs.c
C
apache-2.0
16,890
/***************************************************************************/ /* */ /* cidobjs.h */ /* */ /* CID objects manager (specification). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CIDOBJS_H__ #define __CIDOBJS_H__ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_CONFIG_CONFIG_H #include FT_INTERNAL_TYPE1_TYPES_H FT_BEGIN_HEADER /* The following structures must be defined by the hinter */ typedef struct CID_Size_Hints_ CID_Size_Hints; typedef struct CID_Glyph_Hints_ CID_Glyph_Hints; /*************************************************************************/ /* */ /* <Type> */ /* CID_Driver */ /* */ /* <Description> */ /* A handle to a Type 1 driver object. */ /* */ typedef struct CID_DriverRec_* CID_Driver; /*************************************************************************/ /* */ /* <Type> */ /* CID_Size */ /* */ /* <Description> */ /* A handle to a Type 1 size object. */ /* */ typedef struct CID_SizeRec_* CID_Size; /*************************************************************************/ /* */ /* <Type> */ /* CID_GlyphSlot */ /* */ /* <Description> */ /* A handle to a Type 1 glyph slot object. */ /* */ typedef struct CID_GlyphSlotRec_* CID_GlyphSlot; /*************************************************************************/ /* */ /* <Type> */ /* CID_CharMap */ /* */ /* <Description> */ /* A handle to a Type 1 character mapping object. */ /* */ /* <Note> */ /* The Type 1 format doesn't use a charmap but an encoding table. */ /* The driver is responsible for making up charmap objects */ /* corresponding to these tables. */ /* */ typedef struct CID_CharMapRec_* CID_CharMap; /*************************************************************************/ /* */ /* HERE BEGINS THE TYPE 1 SPECIFIC STUFF */ /* */ /*************************************************************************/ typedef struct CID_SizeRec_ { FT_SizeRec root; FT_Bool valid; } CID_SizeRec; typedef struct CID_GlyphSlotRec_ { FT_GlyphSlotRec root; FT_Bool hint; FT_Bool scaled; FT_Fixed x_scale; FT_Fixed y_scale; } CID_GlyphSlotRec; FT_LOCAL( void ) cid_slot_done( FT_GlyphSlot slot ); FT_LOCAL( FT_Error ) cid_slot_init( FT_GlyphSlot slot ); FT_LOCAL( void ) cid_size_done( FT_Size size ); /* CID_Size */ FT_LOCAL( FT_Error ) cid_size_init( FT_Size size ); /* CID_Size */ FT_LOCAL( FT_Error ) cid_size_request( FT_Size size, /* CID_Size */ FT_Size_Request req ); FT_LOCAL( FT_Error ) cid_face_init( FT_Stream stream, FT_Face face, /* CID_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ); FT_LOCAL( void ) cid_face_done( FT_Face face ); /* CID_Face */ FT_LOCAL( FT_Error ) cid_driver_init( FT_Module driver ); FT_LOCAL( void ) cid_driver_done( FT_Module driver ); FT_END_HEADER #endif /* __CIDOBJS_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidobjs.h
C
apache-2.0
6,312
/***************************************************************************/ /* */ /* cidparse.c */ /* */ /* CID-keyed Type1 parser (body). */ /* */ /* Copyright 1996-2007, 2009, 2013, 2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_STREAM_H #include "cidparse.h" #include "ciderrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cidparse /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** INPUT STREAM PARSER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( FT_Error ) cid_parser_new( CID_Parser* parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ) { FT_Error error = FT_Err_Ok; FT_ULong base_offset, offset, ps_len; FT_Byte *cur, *limit; FT_Byte *arg1, *arg2; FT_MEM_ZERO( parser, sizeof ( *parser ) ); psaux->ps_parser_funcs->init( &parser->root, 0, 0, memory ); parser->stream = stream; base_offset = FT_STREAM_POS(); /* first of all, check the font format in the header */ if ( FT_FRAME_ENTER( 31 ) ) goto Exit; if ( ft_strncmp( (char *)stream->cursor, "%!PS-Adobe-3.0 Resource-CIDFont", 31 ) ) { FT_TRACE2(( " not a CID-keyed font\n" )); error = FT_THROW( Unknown_File_Format ); } FT_FRAME_EXIT(); if ( error ) goto Exit; Again: /* now, read the rest of the file until we find */ /* `StartData' or `/sfnts' */ { FT_Byte buffer[256 + 10]; FT_Long read_len = 256 + 10; /* same as signed FT_Stream->size */ FT_Byte* p = buffer; for ( offset = FT_STREAM_POS(); ; offset += 256 ) { FT_Long stream_len; /* same as signed FT_Stream->size */ stream_len = stream->size - FT_STREAM_POS(); if ( stream_len == 0 ) { FT_TRACE2(( "cid_parser_new: no `StartData' keyword found\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } read_len = FT_MIN( read_len, stream_len ); if ( FT_STREAM_READ( p, read_len ) ) goto Exit; if ( read_len < 256 ) p[read_len] = '\0'; limit = p + read_len - 10; for ( p = buffer; p < limit; p++ ) { if ( p[0] == 'S' && ft_strncmp( (char*)p, "StartData", 9 ) == 0 ) { /* save offset of binary data after `StartData' */ offset += (FT_ULong)( p - buffer + 10 ); goto Found; } else if ( p[1] == 's' && ft_strncmp( (char*)p, "/sfnts", 6 ) == 0 ) { offset += (FT_ULong)( p - buffer + 7 ); goto Found; } } FT_MEM_MOVE( buffer, p, 10 ); read_len = 256; p = buffer + 10; } } Found: /* We have found the start of the binary data or the `/sfnts' token. */ /* Now rewind and extract the frame corresponding to this PostScript */ /* section. */ ps_len = offset - base_offset; if ( FT_STREAM_SEEK( base_offset ) || FT_FRAME_EXTRACT( ps_len, parser->postscript ) ) goto Exit; parser->data_offset = offset; parser->postscript_len = ps_len; parser->root.base = parser->postscript; parser->root.cursor = parser->postscript; parser->root.limit = parser->root.cursor + ps_len; parser->num_dict = -1; /* Finally, we check whether `StartData' or `/sfnts' was real -- */ /* it could be in a comment or string. We also get the arguments */ /* of `StartData' to find out whether the data is represented in */ /* binary or hex format. */ arg1 = parser->root.cursor; cid_parser_skip_PS_token( parser ); cid_parser_skip_spaces ( parser ); arg2 = parser->root.cursor; cid_parser_skip_PS_token( parser ); cid_parser_skip_spaces ( parser ); limit = parser->root.limit; cur = parser->root.cursor; while ( cur < limit ) { if ( parser->root.error ) { error = parser->root.error; goto Exit; } if ( cur[0] == 'S' && ft_strncmp( (char*)cur, "StartData", 9 ) == 0 ) { if ( ft_strncmp( (char*)arg1, "(Hex)", 5 ) == 0 ) parser->binary_length = ft_atol( (const char *)arg2 ); goto Exit; } else if ( cur[1] == 's' && ft_strncmp( (char*)cur, "/sfnts", 6 ) == 0 ) { FT_TRACE2(( "cid_parser_new: cannot handle Type 11 fonts\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } cid_parser_skip_PS_token( parser ); cid_parser_skip_spaces ( parser ); arg1 = arg2; arg2 = cur; cur = parser->root.cursor; } /* we haven't found the correct `StartData'; go back and continue */ /* searching */ FT_FRAME_RELEASE( parser->postscript ); if ( !FT_STREAM_SEEK( offset ) ) goto Again; Exit: return error; } FT_LOCAL_DEF( void ) cid_parser_done( CID_Parser* parser ) { /* always free the private dictionary */ if ( parser->postscript ) { FT_Stream stream = parser->stream; FT_FRAME_RELEASE( parser->postscript ); } parser->root.funcs.done( &parser->root ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidparse.c
C
apache-2.0
7,596
/***************************************************************************/ /* */ /* cidparse.h */ /* */ /* CID-keyed Type1 parser (specification). */ /* */ /* Copyright 1996-2004, 2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CIDPARSE_H__ #define __CIDPARSE_H__ #include <ft2build.h> #include FT_INTERNAL_TYPE1_TYPES_H #include FT_INTERNAL_STREAM_H #include FT_INTERNAL_POSTSCRIPT_AUX_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Struct> */ /* CID_Parser */ /* */ /* <Description> */ /* A CID_Parser is an object used to parse a Type 1 fonts very */ /* quickly. */ /* */ /* <Fields> */ /* root :: The root PS_ParserRec fields. */ /* */ /* stream :: The current input stream. */ /* */ /* postscript :: A pointer to the data to be parsed. */ /* */ /* postscript_len :: The length of the data to be parsed. */ /* */ /* data_offset :: The start position of the binary data (i.e., the */ /* end of the data to be parsed. */ /* */ /* binary_length :: The length of the data after the `StartData' */ /* command if the data format is hexadecimal. */ /* */ /* cid :: A structure which holds the information about */ /* the current font. */ /* */ /* num_dict :: The number of font dictionaries. */ /* */ typedef struct CID_Parser_ { PS_ParserRec root; FT_Stream stream; FT_Byte* postscript; FT_Long postscript_len; FT_ULong data_offset; FT_Long binary_length; CID_FaceInfo cid; FT_Int num_dict; } CID_Parser; FT_LOCAL( FT_Error ) cid_parser_new( CID_Parser* parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ); FT_LOCAL( void ) cid_parser_done( CID_Parser* parser ); /*************************************************************************/ /* */ /* PARSING ROUTINES */ /* */ /*************************************************************************/ #define cid_parser_skip_spaces( p ) \ (p)->root.funcs.skip_spaces( &(p)->root ) #define cid_parser_skip_PS_token( p ) \ (p)->root.funcs.skip_PS_token( &(p)->root ) #define cid_parser_to_int( p ) (p)->root.funcs.to_int( &(p)->root ) #define cid_parser_to_fixed( p, t ) (p)->root.funcs.to_fixed( &(p)->root, t ) #define cid_parser_to_coord_array( p, m, c ) \ (p)->root.funcs.to_coord_array( &(p)->root, m, c ) #define cid_parser_to_fixed_array( p, m, f, t ) \ (p)->root.funcs.to_fixed_array( &(p)->root, m, f, t ) #define cid_parser_to_token( p, t ) \ (p)->root.funcs.to_token( &(p)->root, t ) #define cid_parser_to_token_array( p, t, m, c ) \ (p)->root.funcs.to_token_array( &(p)->root, t, m, c ) #define cid_parser_load_field( p, f, o ) \ (p)->root.funcs.load_field( &(p)->root, f, o, 0, 0 ) #define cid_parser_load_field_table( p, f, o ) \ (p)->root.funcs.load_field_table( &(p)->root, f, o, 0, 0 ) FT_END_HEADER #endif /* __CIDPARSE_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidparse.h
C
apache-2.0
5,821
/***************************************************************************/ /* */ /* cidriver.c */ /* */ /* CID driver interface (body). */ /* */ /* Copyright 1996-2004, 2006, 2008, 2009, 2011, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include "cidriver.h" #include "cidgload.h" #include FT_INTERNAL_DEBUG_H #include "ciderrs.h" #include FT_SERVICE_POSTSCRIPT_NAME_H #include FT_SERVICE_XFREE86_NAME_H #include FT_SERVICE_POSTSCRIPT_INFO_H #include FT_SERVICE_CID_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_ciddriver /* * POSTSCRIPT NAME SERVICE * */ static const char* cid_get_postscript_name( CID_Face face ) { const char* result = face->cid.cid_font_name; if ( result && result[0] == '/' ) result++; return result; } static const FT_Service_PsFontNameRec cid_service_ps_name = { (FT_PsName_GetFunc) cid_get_postscript_name }; /* * POSTSCRIPT INFO SERVICE * */ static FT_Error cid_ps_get_font_info( FT_Face face, PS_FontInfoRec* afont_info ) { *afont_info = ((CID_Face)face)->cid.font_info; return FT_Err_Ok; } static FT_Error cid_ps_get_font_extra( FT_Face face, PS_FontExtraRec* afont_extra ) { *afont_extra = ((CID_Face)face)->font_extra; return FT_Err_Ok; } static const FT_Service_PsInfoRec cid_service_ps_info = { (PS_GetFontInfoFunc) cid_ps_get_font_info, (PS_GetFontExtraFunc) cid_ps_get_font_extra, (PS_HasGlyphNamesFunc) NULL, /* unsupported with CID fonts */ (PS_GetFontPrivateFunc)NULL, /* unsupported */ (PS_GetFontValueFunc) NULL /* not implemented */ }; /* * CID INFO SERVICE * */ static FT_Error cid_get_ros( CID_Face face, const char* *registry, const char* *ordering, FT_Int *supplement ) { CID_FaceInfo cid = &face->cid; if ( registry ) *registry = cid->registry; if ( ordering ) *ordering = cid->ordering; if ( supplement ) *supplement = cid->supplement; return FT_Err_Ok; } static FT_Error cid_get_is_cid( CID_Face face, FT_Bool *is_cid ) { FT_Error error = FT_Err_Ok; FT_UNUSED( face ); if ( is_cid ) *is_cid = 1; /* cid driver is only used for CID keyed fonts */ return error; } static FT_Error cid_get_cid_from_glyph_index( CID_Face face, FT_UInt glyph_index, FT_UInt *cid ) { FT_Error error = FT_Err_Ok; FT_UNUSED( face ); if ( cid ) *cid = glyph_index; /* identity mapping */ return error; } static const FT_Service_CIDRec cid_service_cid_info = { (FT_CID_GetRegistryOrderingSupplementFunc)cid_get_ros, (FT_CID_GetIsInternallyCIDKeyedFunc) cid_get_is_cid, (FT_CID_GetCIDFromGlyphIndexFunc) cid_get_cid_from_glyph_index }; /* * SERVICE LIST * */ static const FT_ServiceDescRec cid_services[] = { { FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_CID }, { FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &cid_service_ps_name }, { FT_SERVICE_ID_POSTSCRIPT_INFO, &cid_service_ps_info }, { FT_SERVICE_ID_CID, &cid_service_cid_info }, { NULL, NULL } }; FT_CALLBACK_DEF( FT_Module_Interface ) cid_get_interface( FT_Module module, const char* cid_interface ) { FT_UNUSED( module ); return ft_service_list_lookup( cid_services, cid_interface ); } FT_CALLBACK_TABLE_DEF const FT_Driver_ClassRec t1cid_driver_class = { /* first of all, the FT_Module_Class fields */ { FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_SCALABLE | FT_MODULE_DRIVER_HAS_HINTER, sizeof ( FT_DriverRec ), "t1cid", /* module name */ 0x10000L, /* version 1.0 of driver */ 0x20000L, /* requires FreeType 2.0 */ 0, cid_driver_init, cid_driver_done, cid_get_interface }, /* then the other font drivers fields */ sizeof ( CID_FaceRec ), sizeof ( CID_SizeRec ), sizeof ( CID_GlyphSlotRec ), cid_face_init, cid_face_done, cid_size_init, cid_size_done, cid_slot_init, cid_slot_done, cid_slot_load_glyph, 0, /* FT_Face_GetKerningFunc */ 0, /* FT_Face_AttachFunc */ 0, /* FT_Face_GetAdvancesFunc */ cid_size_request, 0 /* FT_Size_SelectFunc */ }; /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidriver.c
C
apache-2.0
6,210
/***************************************************************************/ /* */ /* cidriver.h */ /* */ /* High-level CID driver interface (specification). */ /* */ /* Copyright 1996-2001, 2002 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __CIDRIVER_H__ #define __CIDRIVER_H__ #include <ft2build.h> #include FT_INTERNAL_DRIVER_H FT_BEGIN_HEADER #ifdef FT_CONFIG_OPTION_PIC #error "this module does not support PIC yet" #endif FT_CALLBACK_TABLE const FT_Driver_ClassRec t1cid_driver_class; FT_END_HEADER #endif /* __CIDRIVER_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidriver.h
C
apache-2.0
1,577
/***************************************************************************/ /* */ /* cidtoken.h */ /* */ /* CID token definitions (specification only). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2006, 2008, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #undef FT_STRUCTURE #define FT_STRUCTURE CID_FaceInfoRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_CID_INFO T1_FIELD_KEY ( "CIDFontName", cid_font_name, 0 ) T1_FIELD_FIXED ( "CIDFontVersion", cid_version, 0 ) T1_FIELD_NUM ( "CIDFontType", cid_font_type, 0 ) T1_FIELD_STRING( "Registry", registry, 0 ) T1_FIELD_STRING( "Ordering", ordering, 0 ) T1_FIELD_NUM ( "Supplement", supplement, 0 ) T1_FIELD_NUM ( "UIDBase", uid_base, 0 ) T1_FIELD_NUM ( "CIDMapOffset", cidmap_offset, 0 ) T1_FIELD_NUM ( "FDBytes", fd_bytes, 0 ) T1_FIELD_NUM ( "GDBytes", gd_bytes, 0 ) T1_FIELD_NUM ( "CIDCount", cid_count, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_FontInfoRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_INFO T1_FIELD_STRING( "version", version, 0 ) T1_FIELD_STRING( "Notice", notice, 0 ) T1_FIELD_STRING( "FullName", full_name, 0 ) T1_FIELD_STRING( "FamilyName", family_name, 0 ) T1_FIELD_STRING( "Weight", weight, 0 ) T1_FIELD_NUM ( "ItalicAngle", italic_angle, 0 ) T1_FIELD_BOOL ( "isFixedPitch", is_fixed_pitch, 0 ) T1_FIELD_NUM ( "UnderlinePosition", underline_position, 0 ) T1_FIELD_NUM ( "UnderlineThickness", underline_thickness, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_FontExtraRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_EXTRA T1_FIELD_NUM ( "FSType", fs_type, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE CID_FaceDictRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_DICT T1_FIELD_NUM ( "PaintType", paint_type, 0 ) T1_FIELD_NUM ( "FontType", font_type, 0 ) T1_FIELD_NUM ( "SubrMapOffset", subrmap_offset, 0 ) T1_FIELD_NUM ( "SDBytes", sd_bytes, 0 ) T1_FIELD_NUM ( "SubrCount", num_subrs, 0 ) T1_FIELD_NUM ( "lenBuildCharArray", len_buildchar, 0 ) T1_FIELD_FIXED( "ForceBoldThreshold", forcebold_threshold, 0 ) T1_FIELD_FIXED( "StrokeWidth", stroke_width, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_PrivateRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_PRIVATE T1_FIELD_NUM ( "UniqueID", unique_id, 0 ) T1_FIELD_NUM ( "lenIV", lenIV, 0 ) T1_FIELD_NUM ( "LanguageGroup", language_group, 0 ) T1_FIELD_NUM ( "password", password, 0 ) T1_FIELD_FIXED_1000( "BlueScale", blue_scale, 0 ) T1_FIELD_NUM ( "BlueShift", blue_shift, 0 ) T1_FIELD_NUM ( "BlueFuzz", blue_fuzz, 0 ) T1_FIELD_NUM_TABLE ( "BlueValues", blue_values, 14, 0 ) T1_FIELD_NUM_TABLE ( "OtherBlues", other_blues, 10, 0 ) T1_FIELD_NUM_TABLE ( "FamilyBlues", family_blues, 14, 0 ) T1_FIELD_NUM_TABLE ( "FamilyOtherBlues", family_other_blues, 10, 0 ) T1_FIELD_NUM_TABLE2( "StdHW", standard_width, 1, 0 ) T1_FIELD_NUM_TABLE2( "StdVW", standard_height, 1, 0 ) T1_FIELD_NUM_TABLE2( "MinFeature", min_feature, 2, 0 ) T1_FIELD_NUM_TABLE ( "StemSnapH", snap_widths, 12, 0 ) T1_FIELD_NUM_TABLE ( "StemSnapV", snap_heights, 12, 0 ) T1_FIELD_BOOL ( "ForceBold", force_bold, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE FT_BBox #undef T1CODE #define T1CODE T1_FIELD_LOCATION_BBOX T1_FIELD_BBOX( "FontBBox", xMin, 0 ) /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/cidtoken.h
C
apache-2.0
4,991
# # FreeType 2 CID module definition # # Copyright 1996-2000, 2006 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += TYPE1CID_DRIVER define TYPE1CID_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, t1cid_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)cid $(ECHO_DRIVER_DESC)Postscript CID-keyed fonts, no known extension$(ECHO_DRIVER_DONE) endef # EOF
YifuLiu/AliOS-Things
components/freetype/src/cid/module.mk
Makefile
apache-2.0
681
# # FreeType 2 CID driver configuration rules # # Copyright 1996-2000, 2001, 2003 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # CID driver directory # CID_DIR := $(SRC_DIR)/cid CID_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(CID_DIR)) # CID driver sources (i.e., C files) # CID_DRV_SRC := $(CID_DIR)/cidparse.c \ $(CID_DIR)/cidload.c \ $(CID_DIR)/cidriver.c \ $(CID_DIR)/cidgload.c \ $(CID_DIR)/cidobjs.c # CID driver headers # CID_DRV_H := $(CID_DRV_SRC:%.c=%.h) \ $(CID_DIR)/cidtoken.h \ $(CID_DIR)/ciderrs.h # CID driver object(s) # # CID_DRV_OBJ_M is used during `multi' builds # CID_DRV_OBJ_S is used during `single' builds # CID_DRV_OBJ_M := $(CID_DRV_SRC:$(CID_DIR)/%.c=$(OBJ_DIR)/%.$O) CID_DRV_OBJ_S := $(OBJ_DIR)/type1cid.$O # CID driver source file for single build # CID_DRV_SRC_S := $(CID_DIR)/type1cid.c # CID driver - single object # $(CID_DRV_OBJ_S): $(CID_DRV_SRC_S) $(CID_DRV_SRC) $(FREETYPE_H) $(CID_DRV_H) $(CID_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(CID_DRV_SRC_S)) # CID driver - multiple objects # $(OBJ_DIR)/%.$O: $(CID_DIR)/%.c $(FREETYPE_H) $(CID_DRV_H) $(CID_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(CID_DRV_OBJ_S) DRV_OBJS_M += $(CID_DRV_OBJ_M) # EOF
YifuLiu/AliOS-Things
components/freetype/src/cid/rules.mk
Makefile
apache-2.0
1,672
/***************************************************************************/ /* */ /* type1cid.c */ /* */ /* FreeType OpenType driver component (body only). */ /* */ /* Copyright 1996-2001 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #define FT_MAKE_OPTION_SINGLE_OBJECT #include <ft2build.h> #include "cidparse.c" #include "cidload.c" #include "cidobjs.c" #include "cidriver.c" #include "cidgload.c" /* END */
YifuLiu/AliOS-Things
components/freetype/src/cid/type1cid.c
C
apache-2.0
1,430
/***************************************************************************/ /* */ /* gxvalid.c */ /* */ /* FreeType validator for TrueTypeGX/AAT tables (body only). */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #define FT_MAKE_OPTION_SINGLE_OBJECT #include <ft2build.h> #include "gxvfeat.c" #include "gxvcommn.c" #include "gxvbsln.c" #include "gxvtrak.c" #include "gxvjust.c" #include "gxvmort.c" #include "gxvmort0.c" #include "gxvmort1.c" #include "gxvmort2.c" #include "gxvmort4.c" #include "gxvmort5.c" #include "gxvmorx.c" #include "gxvmorx0.c" #include "gxvmorx1.c" #include "gxvmorx2.c" #include "gxvmorx4.c" #include "gxvmorx5.c" #include "gxvkern.c" #include "gxvopbd.c" #include "gxvprop.c" #include "gxvlcar.c" #include "gxvmod.c" /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvalid.c
C
apache-2.0
1,794
/***************************************************************************/ /* */ /* gxvalid.h */ /* */ /* TrueTyeeGX/AAT table validation (specification only). */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __GXVALID_H__ #define __GXVALID_H__ #include <ft2build.h> #include FT_FREETYPE_H #include "gxverror.h" /* must come before FT_INTERNAL_VALIDATE_H */ #include FT_INTERNAL_VALIDATE_H #include FT_INTERNAL_STREAM_H FT_BEGIN_HEADER FT_LOCAL( void ) gxv_feat_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_bsln_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_trak_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_just_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_mort_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_morx_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_kern_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_kern_validate_classic( FT_Bytes table, FT_Face face, FT_Int dialect_flags, FT_Validator valid ); FT_LOCAL( void ) gxv_opbd_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_prop_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_LOCAL( void ) gxv_lcar_validate( FT_Bytes table, FT_Face face, FT_Validator valid ); FT_END_HEADER #endif /* __GXVALID_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvalid.h
C
apache-2.0
3,805
/***************************************************************************/ /* */ /* gxvbsln.c */ /* */ /* TrueTypeGX/AAT bsln table validation (body). */ /* */ /* Copyright 2004, 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvbsln /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define GXV_BSLN_VALUE_COUNT 32 #define GXV_BSLN_VALUE_EMPTY 0xFFFFU typedef struct GXV_bsln_DataRec_ { FT_Bytes ctlPoints_p; FT_UShort defaultBaseline; } GXV_bsln_DataRec, *GXV_bsln_Data; #define GXV_BSLN_DATA( field ) GXV_TABLE_DATA( bsln, field ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_bsln_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UShort v = value_p->u; FT_UShort* ctlPoints; FT_UNUSED( glyph ); GXV_NAME_ENTER( "lookup value" ); if ( v >= GXV_BSLN_VALUE_COUNT ) FT_INVALID_DATA; ctlPoints = (FT_UShort*)GXV_BSLN_DATA( ctlPoints_p ); if ( ctlPoints && ctlPoints[v] == GXV_BSLN_VALUE_EMPTY ) FT_INVALID_DATA; GXV_EXIT; } /* +===============+ --------+ | lookup header | | +===============+ | | BinSrchHeader | | +===============+ | | lastGlyph[0] | | +---------------+ | | firstGlyph[0] | | head of lookup table +---------------+ | + | offset[0] | -> | offset [byte] +===============+ | + | lastGlyph[1] | | (glyphID - firstGlyph) * 2 [byte] +---------------+ | | firstGlyph[1] | | +---------------+ | | offset[1] | | +===============+ | | ... | | 16bit value array | +===============+ | | value | <-------+ ... */ static GXV_LookupValueDesc gxv_bsln_LookupFmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ) { FT_Bytes p; FT_Bytes limit; FT_UShort offset; GXV_LookupValueDesc value; /* XXX: check range ? */ offset = (FT_UShort)( base_value_p->u + ( relative_gindex * sizeof ( FT_UShort ) ) ); p = valid->lookuptbl_head + offset; limit = lookuptbl_limit; GXV_LIMIT_CHECK( 2 ); value.u = FT_NEXT_USHORT( p ); return value; } static void gxv_bsln_parts_fmt0_validate( FT_Bytes tables, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = tables; GXV_NAME_ENTER( "parts format 0" ); /* deltas */ GXV_LIMIT_CHECK( 2 * GXV_BSLN_VALUE_COUNT ); valid->table_data = NULL; /* No ctlPoints here. */ GXV_EXIT; } static void gxv_bsln_parts_fmt1_validate( FT_Bytes tables, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = tables; GXV_NAME_ENTER( "parts format 1" ); /* deltas */ gxv_bsln_parts_fmt0_validate( p, limit, valid ); /* mappingData */ valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_bsln_LookupValue_validate; valid->lookupfmt4_trans = gxv_bsln_LookupFmt4_transit; gxv_LookupTable_validate( p + 2 * GXV_BSLN_VALUE_COUNT, limit, valid ); GXV_EXIT; } static void gxv_bsln_parts_fmt2_validate( FT_Bytes tables, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = tables; FT_UShort stdGlyph; FT_UShort ctlPoint; FT_Int i; FT_UShort defaultBaseline = GXV_BSLN_DATA( defaultBaseline ); GXV_NAME_ENTER( "parts format 2" ); GXV_LIMIT_CHECK( 2 + ( 2 * GXV_BSLN_VALUE_COUNT ) ); /* stdGlyph */ stdGlyph = FT_NEXT_USHORT( p ); GXV_TRACE(( " (stdGlyph = %u)\n", stdGlyph )); gxv_glyphid_validate( stdGlyph, valid ); /* Record the position of ctlPoints */ GXV_BSLN_DATA( ctlPoints_p ) = p; /* ctlPoints */ for ( i = 0; i < GXV_BSLN_VALUE_COUNT; i++ ) { ctlPoint = FT_NEXT_USHORT( p ); if ( ctlPoint == GXV_BSLN_VALUE_EMPTY ) { if ( i == defaultBaseline ) FT_INVALID_DATA; } else gxv_ctlPoint_validate( stdGlyph, (FT_Short)ctlPoint, valid ); } GXV_EXIT; } static void gxv_bsln_parts_fmt3_validate( FT_Bytes tables, FT_Bytes limit, GXV_Validator valid) { FT_Bytes p = tables; GXV_NAME_ENTER( "parts format 3" ); /* stdGlyph + ctlPoints */ gxv_bsln_parts_fmt2_validate( p, limit, valid ); /* mappingData */ valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_bsln_LookupValue_validate; valid->lookupfmt4_trans = gxv_bsln_LookupFmt4_transit; gxv_LookupTable_validate( p + ( 2 + 2 * GXV_BSLN_VALUE_COUNT ), limit, valid ); GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** bsln TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_bsln_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_bsln_DataRec bslnrec; GXV_bsln_Data bsln = &bslnrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_ULong version; FT_UShort format; FT_UShort defaultBaseline; GXV_Validate_Func fmt_funcs_table [] = { gxv_bsln_parts_fmt0_validate, gxv_bsln_parts_fmt1_validate, gxv_bsln_parts_fmt2_validate, gxv_bsln_parts_fmt3_validate, }; valid->root = ftvalid; valid->table_data = bsln; valid->face = face; FT_TRACE3(( "validating `bsln' table\n" )); GXV_INIT; GXV_LIMIT_CHECK( 4 + 2 + 2 ); version = FT_NEXT_ULONG( p ); format = FT_NEXT_USHORT( p ); defaultBaseline = FT_NEXT_USHORT( p ); /* only version 1.0 is defined (1996) */ if ( version != 0x00010000UL ) FT_INVALID_FORMAT; /* only format 1, 2, 3 are defined (1996) */ GXV_TRACE(( " (format = %d)\n", format )); if ( format > 3 ) FT_INVALID_FORMAT; if ( defaultBaseline > 31 ) FT_INVALID_FORMAT; bsln->defaultBaseline = defaultBaseline; fmt_funcs_table[format]( p, limit, valid ); FT_TRACE4(( "\n" )); } /* arch-tag: ebe81143-fdaa-4c68-a4d1-b57227daa3bc (do not change this comment) */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvbsln.c
C
apache-2.0
10,737
/***************************************************************************/ /* */ /* gxvcommn.c */ /* */ /* TrueTypeGX/AAT common tables validation (body). */ /* */ /* Copyright 2004, 2005, 2009, 2010, 2013 */ /* by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvcommon /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** 16bit offset sorter *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static int gxv_compare_ushort_offset( FT_UShort* a, FT_UShort* b ) { if ( *a < *b ) return -1; else if ( *a > *b ) return 1; else return 0; } FT_LOCAL_DEF( void ) gxv_set_length_by_ushort_offset( FT_UShort* offset, FT_UShort** length, FT_UShort* buff, FT_UInt nmemb, FT_UShort limit, GXV_Validator valid ) { FT_UInt i; for ( i = 0; i < nmemb; i++ ) *(length[i]) = 0; for ( i = 0; i < nmemb; i++ ) buff[i] = offset[i]; buff[nmemb] = limit; ft_qsort( buff, ( nmemb + 1 ), sizeof ( FT_UShort ), ( int(*)(const void*, const void*) )gxv_compare_ushort_offset ); if ( buff[nmemb] > limit ) FT_INVALID_OFFSET; for ( i = 0; i < nmemb; i++ ) { FT_UInt j; for ( j = 0; j < nmemb; j++ ) if ( buff[j] == offset[i] ) break; if ( j == nmemb ) FT_INVALID_OFFSET; *(length[i]) = (FT_UShort)( buff[j + 1] - buff[j] ); if ( 0 != offset[i] && 0 == *(length[i]) ) FT_INVALID_OFFSET; } } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** 32bit offset sorter *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static int gxv_compare_ulong_offset( FT_ULong* a, FT_ULong* b ) { if ( *a < *b ) return -1; else if ( *a > *b ) return 1; else return 0; } FT_LOCAL_DEF( void ) gxv_set_length_by_ulong_offset( FT_ULong* offset, FT_ULong** length, FT_ULong* buff, FT_UInt nmemb, FT_ULong limit, GXV_Validator valid) { FT_UInt i; for ( i = 0; i < nmemb; i++ ) *(length[i]) = 0; for ( i = 0; i < nmemb; i++ ) buff[i] = offset[i]; buff[nmemb] = limit; ft_qsort( buff, ( nmemb + 1 ), sizeof ( FT_ULong ), ( int(*)(const void*, const void*) )gxv_compare_ulong_offset ); if ( buff[nmemb] > limit ) FT_INVALID_OFFSET; for ( i = 0; i < nmemb; i++ ) { FT_UInt j; for ( j = 0; j < nmemb; j++ ) if ( buff[j] == offset[i] ) break; if ( j == nmemb ) FT_INVALID_OFFSET; *(length[i]) = buff[j + 1] - buff[j]; if ( 0 != offset[i] && 0 == *(length[i]) ) FT_INVALID_OFFSET; } } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** scan value array and get min & max *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_array_getlimits_byte( FT_Bytes table, FT_Bytes limit, FT_Byte* min, FT_Byte* max, GXV_Validator valid ) { FT_Bytes p = table; *min = 0xFF; *max = 0x00; while ( p < limit ) { FT_Byte val; GXV_LIMIT_CHECK( 1 ); val = FT_NEXT_BYTE( p ); *min = (FT_Byte)FT_MIN( *min, val ); *max = (FT_Byte)FT_MAX( *max, val ); } valid->subtable_length = p - table; } FT_LOCAL_DEF( void ) gxv_array_getlimits_ushort( FT_Bytes table, FT_Bytes limit, FT_UShort* min, FT_UShort* max, GXV_Validator valid ) { FT_Bytes p = table; *min = 0xFFFFU; *max = 0x0000; while ( p < limit ) { FT_UShort val; GXV_LIMIT_CHECK( 2 ); val = FT_NEXT_USHORT( p ); *min = (FT_Byte)FT_MIN( *min, val ); *max = (FT_Byte)FT_MAX( *max, val ); } valid->subtable_length = p - table; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** BINSEARCHHEADER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_BinSrchHeader_ { FT_UShort unitSize; FT_UShort nUnits; FT_UShort searchRange; FT_UShort entrySelector; FT_UShort rangeShift; } GXV_BinSrchHeader; static void gxv_BinSrchHeader_check_consistency( GXV_BinSrchHeader* binSrchHeader, GXV_Validator valid ) { FT_UShort searchRange; FT_UShort entrySelector; FT_UShort rangeShift; if ( binSrchHeader->unitSize == 0 ) FT_INVALID_DATA; if ( binSrchHeader->nUnits == 0 ) { if ( binSrchHeader->searchRange == 0 && binSrchHeader->entrySelector == 0 && binSrchHeader->rangeShift == 0 ) return; else FT_INVALID_DATA; } for ( searchRange = 1, entrySelector = 1; ( searchRange * 2 ) <= binSrchHeader->nUnits && searchRange < 0x8000U; searchRange *= 2, entrySelector++ ) ; entrySelector--; searchRange = (FT_UShort)( searchRange * binSrchHeader->unitSize ); rangeShift = (FT_UShort)( binSrchHeader->nUnits * binSrchHeader->unitSize - searchRange ); if ( searchRange != binSrchHeader->searchRange || entrySelector != binSrchHeader->entrySelector || rangeShift != binSrchHeader->rangeShift ) { GXV_TRACE(( "Inconsistency found in BinSrchHeader\n" )); GXV_TRACE(( "originally: unitSize=%d, nUnits=%d, " "searchRange=%d, entrySelector=%d, " "rangeShift=%d\n", binSrchHeader->unitSize, binSrchHeader->nUnits, binSrchHeader->searchRange, binSrchHeader->entrySelector, binSrchHeader->rangeShift )); GXV_TRACE(( "calculated: unitSize=%d, nUnits=%d, " "searchRange=%d, entrySelector=%d, " "rangeShift=%d\n", binSrchHeader->unitSize, binSrchHeader->nUnits, searchRange, entrySelector, rangeShift )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } } /* * parser & validator of BinSrchHeader * which is used in LookupTable format 2, 4, 6. * * Essential parameters (unitSize, nUnits) are returned by * given pointer, others (searchRange, entrySelector, rangeShift) * can be calculated by essential parameters, so they are just * validated and discarded. * * However, wrong values in searchRange, entrySelector, rangeShift * won't cause fatal errors, because these parameters might be * only used in old m68k font driver in MacOS. * -- suzuki toshiya <mpsuzuki@hiroshima-u.ac.jp> */ FT_LOCAL_DEF( void ) gxv_BinSrchHeader_validate( FT_Bytes table, FT_Bytes limit, FT_UShort* unitSize_p, FT_UShort* nUnits_p, GXV_Validator valid ) { FT_Bytes p = table; GXV_BinSrchHeader binSrchHeader; GXV_NAME_ENTER( "BinSrchHeader validate" ); if ( *unitSize_p == 0 ) { GXV_LIMIT_CHECK( 2 ); binSrchHeader.unitSize = FT_NEXT_USHORT( p ); } else binSrchHeader.unitSize = *unitSize_p; if ( *nUnits_p == 0 ) { GXV_LIMIT_CHECK( 2 ); binSrchHeader.nUnits = FT_NEXT_USHORT( p ); } else binSrchHeader.nUnits = *nUnits_p; GXV_LIMIT_CHECK( 2 + 2 + 2 ); binSrchHeader.searchRange = FT_NEXT_USHORT( p ); binSrchHeader.entrySelector = FT_NEXT_USHORT( p ); binSrchHeader.rangeShift = FT_NEXT_USHORT( p ); GXV_TRACE(( "nUnits %d\n", binSrchHeader.nUnits )); gxv_BinSrchHeader_check_consistency( &binSrchHeader, valid ); if ( *unitSize_p == 0 ) *unitSize_p = binSrchHeader.unitSize; if ( *nUnits_p == 0 ) *nUnits_p = binSrchHeader.nUnits; valid->subtable_length = p - table; GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** LOOKUP TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define GXV_LOOKUP_VALUE_LOAD( P, SIGNSPEC ) \ ( P += 2, gxv_lookup_value_load( P - 2, SIGNSPEC ) ) static GXV_LookupValueDesc gxv_lookup_value_load( FT_Bytes p, int signspec ) { GXV_LookupValueDesc v; if ( signspec == GXV_LOOKUPVALUE_UNSIGNED ) v.u = FT_NEXT_USHORT( p ); else v.s = FT_NEXT_SHORT( p ); return v; } #define GXV_UNITSIZE_VALIDATE( FORMAT, UNITSIZE, NUNITS, CORRECTSIZE ) \ FT_BEGIN_STMNT \ if ( UNITSIZE != CORRECTSIZE ) \ { \ FT_ERROR(( "unitSize=%d differs from" \ " expected unitSize=%d" \ " in LookupTable %s\n", \ UNITSIZE, CORRECTSIZE, FORMAT )); \ if ( UNITSIZE != 0 && NUNITS != 0 ) \ { \ FT_ERROR(( " cannot validate anymore\n" )); \ FT_INVALID_FORMAT; \ } \ else \ FT_ERROR(( " forcibly continues\n" )); \ } \ FT_END_STMNT /* ================= Simple Array Format 0 Lookup Table ================ */ static void gxv_LookupTable_fmt0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort i; GXV_LookupValueDesc value; GXV_NAME_ENTER( "LookupTable format 0" ); GXV_LIMIT_CHECK( 2 * valid->face->num_glyphs ); for ( i = 0; i < valid->face->num_glyphs; i++ ) { GXV_LIMIT_CHECK( 2 ); if ( p + 2 >= limit ) /* some fonts have too-short fmt0 array */ { GXV_TRACE(( "too short, glyphs %d - %d are missing\n", i, valid->face->num_glyphs )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); break; } value = GXV_LOOKUP_VALUE_LOAD( p, valid->lookupval_sign ); valid->lookupval_func( i, &value, valid ); } valid->subtable_length = p - table; GXV_EXIT; } /* ================= Segment Single Format 2 Loolup Table ============== */ /* * Apple spec says: * * To guarantee that a binary search terminates, you must include one or * more special `end of search table' values at the end of the data to * be searched. The number of termination values that need to be * included is table-specific. The value that indicates binary search * termination is 0xFFFF. * * The problem is that nUnits does not include this end-marker. It's * quite difficult to discriminate whether the following 0xFFFF comes from * the end-marker or some next data. * * -- suzuki toshiya <mpsuzuki@hiroshima-u.ac.jp> */ static void gxv_LookupTable_fmt2_skip_endmarkers( FT_Bytes table, FT_UShort unitSize, GXV_Validator valid ) { FT_Bytes p = table; while ( ( p + 4 ) < valid->root->limit ) { if ( p[0] != 0xFF || p[1] != 0xFF || /* lastGlyph */ p[2] != 0xFF || p[3] != 0xFF ) /* firstGlyph */ break; p += unitSize; } valid->subtable_length = p - table; } static void gxv_LookupTable_fmt2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort gid; FT_UShort unitSize; FT_UShort nUnits; FT_UShort unit; FT_UShort lastGlyph; FT_UShort firstGlyph; GXV_LookupValueDesc value; GXV_NAME_ENTER( "LookupTable format 2" ); unitSize = nUnits = 0; gxv_BinSrchHeader_validate( p, limit, &unitSize, &nUnits, valid ); p += valid->subtable_length; GXV_UNITSIZE_VALIDATE( "format2", unitSize, nUnits, 6 ); for ( unit = 0, gid = 0; unit < nUnits; unit++ ) { GXV_LIMIT_CHECK( 2 + 2 + 2 ); lastGlyph = FT_NEXT_USHORT( p ); firstGlyph = FT_NEXT_USHORT( p ); value = GXV_LOOKUP_VALUE_LOAD( p, valid->lookupval_sign ); gxv_glyphid_validate( firstGlyph, valid ); gxv_glyphid_validate( lastGlyph, valid ); if ( lastGlyph < gid ) { GXV_TRACE(( "reverse ordered segment specification:" " lastGlyph[%d]=%d < lastGlyph[%d]=%d\n", unit, lastGlyph, unit - 1 , gid )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } if ( lastGlyph < firstGlyph ) { GXV_TRACE(( "reverse ordered range specification at unit %d:", " lastGlyph %d < firstGlyph %d ", unit, lastGlyph, firstGlyph )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); if ( valid->root->level == FT_VALIDATE_TIGHT ) continue; /* ftxvalidator silently skips such an entry */ FT_TRACE4(( "continuing with exchanged values\n" )); gid = firstGlyph; firstGlyph = lastGlyph; lastGlyph = gid; } for ( gid = firstGlyph; gid <= lastGlyph; gid++ ) valid->lookupval_func( gid, &value, valid ); } gxv_LookupTable_fmt2_skip_endmarkers( p, unitSize, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } /* ================= Segment Array Format 4 Lookup Table =============== */ static void gxv_LookupTable_fmt4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort unit; FT_UShort gid; FT_UShort unitSize; FT_UShort nUnits; FT_UShort lastGlyph; FT_UShort firstGlyph; GXV_LookupValueDesc base_value; GXV_LookupValueDesc value; GXV_NAME_ENTER( "LookupTable format 4" ); unitSize = nUnits = 0; gxv_BinSrchHeader_validate( p, limit, &unitSize, &nUnits, valid ); p += valid->subtable_length; GXV_UNITSIZE_VALIDATE( "format4", unitSize, nUnits, 6 ); for ( unit = 0, gid = 0; unit < nUnits; unit++ ) { GXV_LIMIT_CHECK( 2 + 2 ); lastGlyph = FT_NEXT_USHORT( p ); firstGlyph = FT_NEXT_USHORT( p ); gxv_glyphid_validate( firstGlyph, valid ); gxv_glyphid_validate( lastGlyph, valid ); if ( lastGlyph < gid ) { GXV_TRACE(( "reverse ordered segment specification:" " lastGlyph[%d]=%d < lastGlyph[%d]=%d\n", unit, lastGlyph, unit - 1 , gid )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } if ( lastGlyph < firstGlyph ) { GXV_TRACE(( "reverse ordered range specification at unit %d:", " lastGlyph %d < firstGlyph %d ", unit, lastGlyph, firstGlyph )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); if ( valid->root->level == FT_VALIDATE_TIGHT ) continue; /* ftxvalidator silently skips such an entry */ FT_TRACE4(( "continuing with exchanged values\n" )); gid = firstGlyph; firstGlyph = lastGlyph; lastGlyph = gid; } GXV_LIMIT_CHECK( 2 ); base_value = GXV_LOOKUP_VALUE_LOAD( p, GXV_LOOKUPVALUE_UNSIGNED ); for ( gid = firstGlyph; gid <= lastGlyph; gid++ ) { value = valid->lookupfmt4_trans( (FT_UShort)( gid - firstGlyph ), &base_value, limit, valid ); valid->lookupval_func( gid, &value, valid ); } } gxv_LookupTable_fmt2_skip_endmarkers( p, unitSize, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } /* ================= Segment Table Format 6 Lookup Table =============== */ static void gxv_LookupTable_fmt6_skip_endmarkers( FT_Bytes table, FT_UShort unitSize, GXV_Validator valid ) { FT_Bytes p = table; while ( p < valid->root->limit ) { if ( p[0] != 0xFF || p[1] != 0xFF ) break; p += unitSize; } valid->subtable_length = p - table; } static void gxv_LookupTable_fmt6_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort unit; FT_UShort prev_glyph; FT_UShort unitSize; FT_UShort nUnits; FT_UShort glyph; GXV_LookupValueDesc value; GXV_NAME_ENTER( "LookupTable format 6" ); unitSize = nUnits = 0; gxv_BinSrchHeader_validate( p, limit, &unitSize, &nUnits, valid ); p += valid->subtable_length; GXV_UNITSIZE_VALIDATE( "format6", unitSize, nUnits, 4 ); for ( unit = 0, prev_glyph = 0; unit < nUnits; unit++ ) { GXV_LIMIT_CHECK( 2 + 2 ); glyph = FT_NEXT_USHORT( p ); value = GXV_LOOKUP_VALUE_LOAD( p, valid->lookupval_sign ); if ( gxv_glyphid_validate( glyph, valid ) ) GXV_TRACE(( " endmarker found within defined range" " (entry %d < nUnits=%d)\n", unit, nUnits )); if ( prev_glyph > glyph ) { GXV_TRACE(( "current gid 0x%04x < previous gid 0x%04x\n", glyph, prev_glyph )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } prev_glyph = glyph; valid->lookupval_func( glyph, &value, valid ); } gxv_LookupTable_fmt6_skip_endmarkers( p, unitSize, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } /* ================= Trimmed Array Format 8 Lookup Table =============== */ static void gxv_LookupTable_fmt8_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort i; GXV_LookupValueDesc value; FT_UShort firstGlyph; FT_UShort glyphCount; GXV_NAME_ENTER( "LookupTable format 8" ); /* firstGlyph + glyphCount */ GXV_LIMIT_CHECK( 2 + 2 ); firstGlyph = FT_NEXT_USHORT( p ); glyphCount = FT_NEXT_USHORT( p ); gxv_glyphid_validate( firstGlyph, valid ); gxv_glyphid_validate( (FT_UShort)( firstGlyph + glyphCount ), valid ); /* valueArray */ for ( i = 0; i < glyphCount; i++ ) { GXV_LIMIT_CHECK( 2 ); value = GXV_LOOKUP_VALUE_LOAD( p, valid->lookupval_sign ); valid->lookupval_func( (FT_UShort)( firstGlyph + i ), &value, valid ); } valid->subtable_length = p - table; GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_LookupTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort format; GXV_Validate_Func fmt_funcs_table[] = { gxv_LookupTable_fmt0_validate, /* 0 */ NULL, /* 1 */ gxv_LookupTable_fmt2_validate, /* 2 */ NULL, /* 3 */ gxv_LookupTable_fmt4_validate, /* 4 */ NULL, /* 5 */ gxv_LookupTable_fmt6_validate, /* 6 */ NULL, /* 7 */ gxv_LookupTable_fmt8_validate, /* 8 */ }; GXV_Validate_Func func; GXV_NAME_ENTER( "LookupTable" ); /* lookuptbl_head may be used in fmt4 transit function. */ valid->lookuptbl_head = table; /* format */ GXV_LIMIT_CHECK( 2 ); format = FT_NEXT_USHORT( p ); GXV_TRACE(( " (format %d)\n", format )); if ( format > 8 ) FT_INVALID_FORMAT; func = fmt_funcs_table[format]; if ( func == NULL ) FT_INVALID_FORMAT; func( p, limit, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Glyph ID *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( FT_Int ) gxv_glyphid_validate( FT_UShort gid, GXV_Validator valid ) { FT_Face face; if ( gid == 0xFFFFU ) { GXV_EXIT; return 1; } face = valid->face; if ( face->num_glyphs < gid ) { GXV_TRACE(( " gxv_glyphid_check() gid overflow: num_glyphs %d < %d\n", face->num_glyphs, gid )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } return 0; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CONTROL POINT *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_ctlPoint_validate( FT_UShort gid, FT_Short ctl_point, GXV_Validator valid ) { FT_Face face; FT_Error error; FT_GlyphSlot glyph; FT_Outline outline; short n_points; face = valid->face; error = FT_Load_Glyph( face, gid, FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM ); if ( error ) FT_INVALID_GLYPH_ID; glyph = face->glyph; outline = glyph->outline; n_points = outline.n_points; if ( !( ctl_point < n_points ) ) FT_INVALID_DATA; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** SFNT NAME *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_sfntName_validate( FT_UShort name_index, FT_UShort min_index, FT_UShort max_index, GXV_Validator valid ) { FT_SfntName name; FT_UInt i; FT_UInt nnames; GXV_NAME_ENTER( "sfntName" ); if ( name_index < min_index || max_index < name_index ) FT_INVALID_FORMAT; nnames = FT_Get_Sfnt_Name_Count( valid->face ); for ( i = 0; i < nnames; i++ ) { if ( FT_Get_Sfnt_Name( valid->face, i, &name ) != FT_Err_Ok ) continue ; if ( name.name_id == name_index ) goto Out; } GXV_TRACE(( " nameIndex = %d (UNTITLED)\n", name_index )); FT_INVALID_DATA; goto Exit; /* make compiler happy */ Out: FT_TRACE1(( " nameIndex = %d (", name_index )); GXV_TRACE_HEXDUMP_SFNTNAME( name ); FT_TRACE1(( ")\n" )); Exit: GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** STATE TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* -------------------------- Class Table --------------------------- */ /* * highestClass specifies how many classes are defined in this * Class Subtable. Apple spec does not mention whether undefined * holes in the class (e.g.: 0-3 are predefined, 4 is unused, 5 is used) * are permitted. At present, holes in a defined class are not checked. * -- suzuki toshiya <mpsuzuki@hiroshima-u.ac.jp> */ static void gxv_ClassTable_validate( FT_Bytes table, FT_UShort* length_p, FT_UShort stateSize, FT_Byte* maxClassID_p, GXV_Validator valid ) { FT_Bytes p = table; FT_Bytes limit = table + *length_p; FT_UShort firstGlyph; FT_UShort nGlyphs; GXV_NAME_ENTER( "ClassTable" ); *maxClassID_p = 3; /* Classes 0, 2, and 3 are predefined */ GXV_LIMIT_CHECK( 2 + 2 ); firstGlyph = FT_NEXT_USHORT( p ); nGlyphs = FT_NEXT_USHORT( p ); GXV_TRACE(( " (firstGlyph = %d, nGlyphs = %d)\n", firstGlyph, nGlyphs )); if ( !nGlyphs ) goto Out; gxv_glyphid_validate( (FT_UShort)( firstGlyph + nGlyphs ), valid ); { FT_Byte nGlyphInClass[256]; FT_Byte classID; FT_UShort i; ft_memset( nGlyphInClass, 0, 256 ); for ( i = 0; i < nGlyphs; i++ ) { GXV_LIMIT_CHECK( 1 ); classID = FT_NEXT_BYTE( p ); switch ( classID ) { /* following classes should not appear in class array */ case 0: /* end of text */ case 2: /* out of bounds */ case 3: /* end of line */ FT_INVALID_DATA; break; case 1: /* out of bounds */ default: /* user-defined: 4 - ( stateSize - 1 ) */ if ( classID >= stateSize ) FT_INVALID_DATA; /* assign glyph to undefined state */ nGlyphInClass[classID]++; break; } } *length_p = (FT_UShort)( p - table ); /* scan max ClassID in use */ for ( i = 0; i < stateSize; i++ ) if ( ( 3 < i ) && ( nGlyphInClass[i] > 0 ) ) *maxClassID_p = (FT_Byte)i; /* XXX: Check Range? */ } Out: GXV_TRACE(( "Declared stateSize=0x%02x, Used maxClassID=0x%02x\n", stateSize, *maxClassID_p )); GXV_EXIT; } /* --------------------------- State Array ----------------------------- */ static void gxv_StateArray_validate( FT_Bytes table, FT_UShort* length_p, FT_Byte maxClassID, FT_UShort stateSize, FT_Byte* maxState_p, FT_Byte* maxEntry_p, GXV_Validator valid ) { FT_Bytes p = table; FT_Bytes limit = table + *length_p; FT_Byte clazz; FT_Byte entry; FT_UNUSED( stateSize ); /* for the non-debugging case */ GXV_NAME_ENTER( "StateArray" ); GXV_TRACE(( "parse %d bytes by stateSize=%d maxClassID=%d\n", (int)(*length_p), stateSize, (int)(maxClassID) )); /* * 2 states are predefined and must be described in StateArray: * state 0 (start of text), 1 (start of line) */ GXV_LIMIT_CHECK( ( 1 + maxClassID ) * 2 ); *maxState_p = 0; *maxEntry_p = 0; /* read if enough to read another state */ while ( p + ( 1 + maxClassID ) <= limit ) { (*maxState_p)++; for ( clazz = 0; clazz <= maxClassID; clazz++ ) { entry = FT_NEXT_BYTE( p ); *maxEntry_p = (FT_Byte)FT_MAX( *maxEntry_p, entry ); } } GXV_TRACE(( "parsed: maxState=%d, maxEntry=%d\n", *maxState_p, *maxEntry_p )); *length_p = (FT_UShort)( p - table ); GXV_EXIT; } /* --------------------------- Entry Table ----------------------------- */ static void gxv_EntryTable_validate( FT_Bytes table, FT_UShort* length_p, FT_Byte maxEntry, FT_UShort stateArray, FT_UShort stateArray_length, FT_Byte maxClassID, FT_Bytes statetable_table, FT_Bytes statetable_limit, GXV_Validator valid ) { FT_Bytes p = table; FT_Bytes limit = table + *length_p; FT_Byte entry; FT_Byte state; FT_Int entrySize = 2 + 2 + GXV_GLYPHOFFSET_SIZE( statetable ); GXV_XStateTable_GlyphOffsetDesc glyphOffset; GXV_NAME_ENTER( "EntryTable" ); GXV_TRACE(( "maxEntry=%d entrySize=%d\n", maxEntry, entrySize )); if ( ( maxEntry + 1 ) * entrySize > *length_p ) { GXV_SET_ERR_IF_PARANOID( FT_INVALID_TOO_SHORT ); /* ftxvalidator and FontValidator both warn and continue */ maxEntry = (FT_Byte)( *length_p / entrySize - 1 ); GXV_TRACE(( "too large maxEntry, shrinking to %d fit EntryTable length\n", maxEntry )); } for ( entry = 0; entry <= maxEntry; entry++ ) { FT_UShort newState; FT_UShort flags; GXV_LIMIT_CHECK( 2 + 2 ); newState = FT_NEXT_USHORT( p ); flags = FT_NEXT_USHORT( p ); if ( newState < stateArray || stateArray + stateArray_length < newState ) { GXV_TRACE(( " newState offset 0x%04x is out of stateArray\n", newState )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); continue; } if ( 0 != ( ( newState - stateArray ) % ( 1 + maxClassID ) ) ) { GXV_TRACE(( " newState offset 0x%04x is not aligned to %d-classes\n", newState, 1 + maxClassID )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); continue; } state = (FT_Byte)( ( newState - stateArray ) / ( 1 + maxClassID ) ); switch ( GXV_GLYPHOFFSET_FMT( statetable ) ) { case GXV_GLYPHOFFSET_NONE: glyphOffset.uc = 0; /* make compiler happy */ break; case GXV_GLYPHOFFSET_UCHAR: glyphOffset.uc = FT_NEXT_BYTE( p ); break; case GXV_GLYPHOFFSET_CHAR: glyphOffset.c = FT_NEXT_CHAR( p ); break; case GXV_GLYPHOFFSET_USHORT: glyphOffset.u = FT_NEXT_USHORT( p ); break; case GXV_GLYPHOFFSET_SHORT: glyphOffset.s = FT_NEXT_SHORT( p ); break; case GXV_GLYPHOFFSET_ULONG: glyphOffset.ul = FT_NEXT_ULONG( p ); break; case GXV_GLYPHOFFSET_LONG: glyphOffset.l = FT_NEXT_LONG( p ); break; default: GXV_SET_ERR_IF_PARANOID( FT_INVALID_FORMAT ); goto Exit; } if ( NULL != valid->statetable.entry_validate_func ) valid->statetable.entry_validate_func( state, flags, &glyphOffset, statetable_table, statetable_limit, valid ); } Exit: *length_p = (FT_UShort)( p - table ); GXV_EXIT; } /* =========================== State Table ============================= */ FT_LOCAL_DEF( void ) gxv_StateTable_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ) { FT_UShort o[3]; FT_UShort* l[3]; FT_UShort buff[4]; o[0] = classTable; o[1] = stateArray; o[2] = entryTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; gxv_set_length_by_ushort_offset( o, l, buff, 3, table_size, valid ); } FT_LOCAL_DEF( void ) gxv_StateTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_UShort stateSize; FT_UShort classTable; /* offset to Class(Sub)Table */ FT_UShort stateArray; /* offset to StateArray */ FT_UShort entryTable; /* offset to EntryTable */ FT_UShort classTable_length; FT_UShort stateArray_length; FT_UShort entryTable_length; FT_Byte maxClassID; FT_Byte maxState; FT_Byte maxEntry; GXV_StateTable_Subtable_Setup_Func setup_func; FT_Bytes p = table; GXV_NAME_ENTER( "StateTable" ); GXV_TRACE(( "StateTable header\n" )); GXV_LIMIT_CHECK( 2 + 2 + 2 + 2 ); stateSize = FT_NEXT_USHORT( p ); classTable = FT_NEXT_USHORT( p ); stateArray = FT_NEXT_USHORT( p ); entryTable = FT_NEXT_USHORT( p ); GXV_TRACE(( "stateSize=0x%04x\n", stateSize )); GXV_TRACE(( "offset to classTable=0x%04x\n", classTable )); GXV_TRACE(( "offset to stateArray=0x%04x\n", stateArray )); GXV_TRACE(( "offset to entryTable=0x%04x\n", entryTable )); if ( stateSize > 0xFF ) FT_INVALID_DATA; if ( valid->statetable.optdata_load_func != NULL ) valid->statetable.optdata_load_func( p, limit, valid ); if ( valid->statetable.subtable_setup_func != NULL) setup_func = valid->statetable.subtable_setup_func; else setup_func = gxv_StateTable_subtable_setup; setup_func( (FT_UShort)( limit - table ), classTable, stateArray, entryTable, &classTable_length, &stateArray_length, &entryTable_length, valid ); GXV_TRACE(( "StateTable Subtables\n" )); if ( classTable != 0 ) gxv_ClassTable_validate( table + classTable, &classTable_length, stateSize, &maxClassID, valid ); else maxClassID = (FT_Byte)( stateSize - 1 ); if ( stateArray != 0 ) gxv_StateArray_validate( table + stateArray, &stateArray_length, maxClassID, stateSize, &maxState, &maxEntry, valid ); else { #if 0 maxState = 1; /* 0:start of text, 1:start of line are predefined */ #endif maxEntry = 0; } if ( maxEntry > 0 && entryTable == 0 ) FT_INVALID_OFFSET; if ( entryTable != 0 ) gxv_EntryTable_validate( table + entryTable, &entryTable_length, maxEntry, stateArray, stateArray_length, maxClassID, table, limit, valid ); GXV_EXIT; } /* ================= eXtended State Table (for morx) =================== */ FT_LOCAL_DEF( void ) gxv_XStateTable_subtable_setup( FT_ULong table_size, FT_ULong classTable, FT_ULong stateArray, FT_ULong entryTable, FT_ULong* classTable_length_p, FT_ULong* stateArray_length_p, FT_ULong* entryTable_length_p, GXV_Validator valid ) { FT_ULong o[3]; FT_ULong* l[3]; FT_ULong buff[4]; o[0] = classTable; o[1] = stateArray; o[2] = entryTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; gxv_set_length_by_ulong_offset( o, l, buff, 3, table_size, valid ); } static void gxv_XClassTable_lookupval_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); if ( value_p->u >= valid->xstatetable.nClasses ) FT_INVALID_DATA; if ( value_p->u > valid->xstatetable.maxClassID ) valid->xstatetable.maxClassID = value_p->u; } /* +===============+ --------+ | lookup header | | +===============+ | | BinSrchHeader | | +===============+ | | lastGlyph[0] | | +---------------+ | | firstGlyph[0] | | head of lookup table +---------------+ | + | offset[0] | -> | offset [byte] +===============+ | + | lastGlyph[1] | | (glyphID - firstGlyph) * 2 [byte] +---------------+ | | firstGlyph[1] | | +---------------+ | | offset[1] | | +===============+ | | .... | | 16bit value array | +===============+ | | value | <-------+ .... */ static GXV_LookupValueDesc gxv_XClassTable_lookupfmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ) { FT_Bytes p; FT_Bytes limit; FT_UShort offset; GXV_LookupValueDesc value; /* XXX: check range? */ offset = (FT_UShort)( base_value_p->u + relative_gindex * sizeof ( FT_UShort ) ); p = valid->lookuptbl_head + offset; limit = lookuptbl_limit; GXV_LIMIT_CHECK ( 2 ); value.u = FT_NEXT_USHORT( p ); return value; } static void gxv_XStateArray_validate( FT_Bytes table, FT_ULong* length_p, FT_UShort maxClassID, FT_ULong stateSize, FT_UShort* maxState_p, FT_UShort* maxEntry_p, GXV_Validator valid ) { FT_Bytes p = table; FT_Bytes limit = table + *length_p; FT_UShort clazz; FT_UShort entry; FT_UNUSED( stateSize ); /* for the non-debugging case */ GXV_NAME_ENTER( "XStateArray" ); GXV_TRACE(( "parse % 3d bytes by stateSize=% 3d maxClassID=% 3d\n", (int)(*length_p), stateSize, (int)(maxClassID) )); /* * 2 states are predefined and must be described: * state 0 (start of text), 1 (start of line) */ GXV_LIMIT_CHECK( ( 1 + maxClassID ) * 2 * 2 ); *maxState_p = 0; *maxEntry_p = 0; /* read if enough to read another state */ while ( p + ( ( 1 + maxClassID ) * 2 ) <= limit ) { (*maxState_p)++; for ( clazz = 0; clazz <= maxClassID; clazz++ ) { entry = FT_NEXT_USHORT( p ); *maxEntry_p = (FT_UShort)FT_MAX( *maxEntry_p, entry ); } } GXV_TRACE(( "parsed: maxState=%d, maxEntry=%d\n", *maxState_p, *maxEntry_p )); *length_p = p - table; GXV_EXIT; } static void gxv_XEntryTable_validate( FT_Bytes table, FT_ULong* length_p, FT_UShort maxEntry, FT_ULong stateArray_length, FT_UShort maxClassID, FT_Bytes xstatetable_table, FT_Bytes xstatetable_limit, GXV_Validator valid ) { FT_Bytes p = table; FT_Bytes limit = table + *length_p; FT_UShort entry; FT_UShort state; FT_Int entrySize = 2 + 2 + GXV_GLYPHOFFSET_SIZE( xstatetable ); GXV_NAME_ENTER( "XEntryTable" ); GXV_TRACE(( "maxEntry=%d entrySize=%d\n", maxEntry, entrySize )); if ( ( p + ( maxEntry + 1 ) * entrySize ) > limit ) FT_INVALID_TOO_SHORT; for (entry = 0; entry <= maxEntry ; entry++ ) { FT_UShort newState_idx; FT_UShort flags; GXV_XStateTable_GlyphOffsetDesc glyphOffset; GXV_LIMIT_CHECK( 2 + 2 ); newState_idx = FT_NEXT_USHORT( p ); flags = FT_NEXT_USHORT( p ); if ( stateArray_length < (FT_ULong)( newState_idx * 2 ) ) { GXV_TRACE(( " newState index 0x%04x points out of stateArray\n", newState_idx )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } state = (FT_UShort)( newState_idx / ( 1 + maxClassID ) ); if ( 0 != ( newState_idx % ( 1 + maxClassID ) ) ) { FT_TRACE4(( "-> new state = %d (supposed)\n" "but newState index 0x%04x is not aligned to %d-classes\n", state, newState_idx, 1 + maxClassID )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } switch ( GXV_GLYPHOFFSET_FMT( xstatetable ) ) { case GXV_GLYPHOFFSET_NONE: glyphOffset.uc = 0; /* make compiler happy */ break; case GXV_GLYPHOFFSET_UCHAR: glyphOffset.uc = FT_NEXT_BYTE( p ); break; case GXV_GLYPHOFFSET_CHAR: glyphOffset.c = FT_NEXT_CHAR( p ); break; case GXV_GLYPHOFFSET_USHORT: glyphOffset.u = FT_NEXT_USHORT( p ); break; case GXV_GLYPHOFFSET_SHORT: glyphOffset.s = FT_NEXT_SHORT( p ); break; case GXV_GLYPHOFFSET_ULONG: glyphOffset.ul = FT_NEXT_ULONG( p ); break; case GXV_GLYPHOFFSET_LONG: glyphOffset.l = FT_NEXT_LONG( p ); break; default: GXV_SET_ERR_IF_PARANOID( FT_INVALID_FORMAT ); goto Exit; } if ( NULL != valid->xstatetable.entry_validate_func ) valid->xstatetable.entry_validate_func( state, flags, &glyphOffset, xstatetable_table, xstatetable_limit, valid ); } Exit: *length_p = p - table; GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_XStateTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { /* StateHeader members */ FT_ULong classTable; /* offset to Class(Sub)Table */ FT_ULong stateArray; /* offset to StateArray */ FT_ULong entryTable; /* offset to EntryTable */ FT_ULong classTable_length; FT_ULong stateArray_length; FT_ULong entryTable_length; FT_UShort maxState; FT_UShort maxEntry; GXV_XStateTable_Subtable_Setup_Func setup_func; FT_Bytes p = table; GXV_NAME_ENTER( "XStateTable" ); GXV_TRACE(( "XStateTable header\n" )); GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 ); valid->xstatetable.nClasses = FT_NEXT_ULONG( p ); classTable = FT_NEXT_ULONG( p ); stateArray = FT_NEXT_ULONG( p ); entryTable = FT_NEXT_ULONG( p ); GXV_TRACE(( "nClasses =0x%08x\n", valid->xstatetable.nClasses )); GXV_TRACE(( "offset to classTable=0x%08x\n", classTable )); GXV_TRACE(( "offset to stateArray=0x%08x\n", stateArray )); GXV_TRACE(( "offset to entryTable=0x%08x\n", entryTable )); if ( valid->xstatetable.nClasses > 0xFFFFU ) FT_INVALID_DATA; GXV_TRACE(( "StateTable Subtables\n" )); if ( valid->xstatetable.optdata_load_func != NULL ) valid->xstatetable.optdata_load_func( p, limit, valid ); if ( valid->xstatetable.subtable_setup_func != NULL ) setup_func = valid->xstatetable.subtable_setup_func; else setup_func = gxv_XStateTable_subtable_setup; setup_func( limit - table, classTable, stateArray, entryTable, &classTable_length, &stateArray_length, &entryTable_length, valid ); if ( classTable != 0 ) { valid->xstatetable.maxClassID = 0; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_XClassTable_lookupval_validate; valid->lookupfmt4_trans = gxv_XClassTable_lookupfmt4_transit; gxv_LookupTable_validate( table + classTable, table + classTable + classTable_length, valid ); #if 0 if ( valid->subtable_length < classTable_length ) classTable_length = valid->subtable_length; #endif } else { /* XXX: check range? */ valid->xstatetable.maxClassID = (FT_UShort)( valid->xstatetable.nClasses - 1 ); } if ( stateArray != 0 ) gxv_XStateArray_validate( table + stateArray, &stateArray_length, valid->xstatetable.maxClassID, valid->xstatetable.nClasses, &maxState, &maxEntry, valid ); else { #if 0 maxState = 1; /* 0:start of text, 1:start of line are predefined */ #endif maxEntry = 0; } if ( maxEntry > 0 && entryTable == 0 ) FT_INVALID_OFFSET; if ( entryTable != 0 ) gxv_XEntryTable_validate( table + entryTable, &entryTable_length, maxEntry, stateArray_length, valid->xstatetable.maxClassID, table, limit, valid ); GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Table overlapping *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static int gxv_compare_ranges( FT_Bytes table1_start, FT_ULong table1_length, FT_Bytes table2_start, FT_ULong table2_length ) { if ( table1_start == table2_start ) { if ( ( table1_length == 0 || table2_length == 0 ) ) goto Out; } else if ( table1_start < table2_start ) { if ( ( table1_start + table1_length ) <= table2_start ) goto Out; } else if ( table1_start > table2_start ) { if ( ( table1_start >= table2_start + table2_length ) ) goto Out; } return 1; Out: return 0; } FT_LOCAL_DEF( void ) gxv_odtect_add_range( FT_Bytes start, FT_ULong length, const FT_String* name, GXV_odtect_Range odtect ) { odtect->range[odtect->nRanges].start = start; odtect->range[odtect->nRanges].length = length; odtect->range[odtect->nRanges].name = (FT_String*)name; odtect->nRanges++; } FT_LOCAL_DEF( void ) gxv_odtect_validate( GXV_odtect_Range odtect, GXV_Validator valid ) { FT_UInt i, j; GXV_NAME_ENTER( "check overlap among multi ranges" ); for ( i = 0; i < odtect->nRanges; i++ ) for ( j = 0; j < i; j++ ) if ( 0 != gxv_compare_ranges( odtect->range[i].start, odtect->range[i].length, odtect->range[j].start, odtect->range[j].length ) ) { #ifdef FT_DEBUG_LEVEL_TRACE if ( odtect->range[i].name || odtect->range[j].name ) GXV_TRACE(( "found overlap between range %d and range %d\n", i, j )); else GXV_TRACE(( "found overlap between `%s' and `%s\'\n", odtect->range[i].name, odtect->range[j].name )); #endif FT_INVALID_OFFSET; } GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvcommn.c
C
apache-2.0
55,100
/***************************************************************************/ /* */ /* gxvcommn.h */ /* */ /* TrueTypeGX/AAT common tables validation (specification). */ /* */ /* Copyright 2004, 2005, 2012 */ /* by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ /* * keywords in variable naming * --------------------------- * table: Of type FT_Bytes, pointing to the start of this table/subtable. * limit: Of type FT_Bytes, pointing to the end of this table/subtable, * including padding for alignment. * offset: Of type FT_UInt, the number of octets from the start to target. * length: Of type FT_UInt, the number of octets from the start to the * end in this table/subtable, including padding for alignment. * * _MIN, _MAX: Should be added to the tail of macros, as INT_MIN, etc. */ #ifndef __GXVCOMMN_H__ #define __GXVCOMMN_H__ #include <ft2build.h> #include "gxvalid.h" #include FT_INTERNAL_DEBUG_H #include FT_SFNT_NAMES_H FT_BEGIN_HEADER /* some variables are not evaluated or only used in trace */ #ifdef FT_DEBUG_LEVEL_TRACE #define GXV_LOAD_TRACE_VARS #else #undef GXV_LOAD_TRACE_VARS #endif #undef GXV_LOAD_UNUSED_VARS /* debug purpose */ #define IS_PARANOID_VALIDATION ( valid->root->level >= FT_VALIDATE_PARANOID ) #define GXV_SET_ERR_IF_PARANOID( err ) { if ( IS_PARANOID_VALIDATION ) ( err ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** VALIDATION *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_ValidatorRec_* GXV_Validator; #define DUMMY_LIMIT 0 typedef void (*GXV_Validate_Func)( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); /* ====================== LookupTable Validator ======================== */ typedef union GXV_LookupValueDesc_ { FT_UShort u; FT_Short s; } GXV_LookupValueDesc; typedef const GXV_LookupValueDesc* GXV_LookupValueCPtr; typedef enum GXV_LookupValue_SignSpec_ { GXV_LOOKUPVALUE_UNSIGNED = 0, GXV_LOOKUPVALUE_SIGNED } GXV_LookupValue_SignSpec; typedef void (*GXV_Lookup_Value_Validate_Func)( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ); typedef GXV_LookupValueDesc (*GXV_Lookup_Fmt4_Transit_Func)( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ); /* ====================== StateTable Validator ========================= */ typedef enum GXV_GlyphOffset_Format_ { GXV_GLYPHOFFSET_NONE = -1, GXV_GLYPHOFFSET_UCHAR = 2, GXV_GLYPHOFFSET_CHAR, GXV_GLYPHOFFSET_USHORT = 4, GXV_GLYPHOFFSET_SHORT, GXV_GLYPHOFFSET_ULONG = 8, GXV_GLYPHOFFSET_LONG } GXV_GlyphOffset_Format; #define GXV_GLYPHOFFSET_FMT( table ) \ ( valid->table.entry_glyphoffset_fmt ) #define GXV_GLYPHOFFSET_SIZE( table ) \ ( valid->table.entry_glyphoffset_fmt / 2 ) /* ----------------------- 16bit StateTable ---------------------------- */ typedef union GXV_StateTable_GlyphOffsetDesc_ { FT_Byte uc; FT_UShort u; /* same as GXV_LookupValueDesc */ FT_ULong ul; FT_Char c; FT_Short s; /* same as GXV_LookupValueDesc */ FT_Long l; } GXV_StateTable_GlyphOffsetDesc; typedef const GXV_StateTable_GlyphOffsetDesc* GXV_StateTable_GlyphOffsetCPtr; typedef void (*GXV_StateTable_Subtable_Setup_Func)( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ); typedef void (*GXV_StateTable_Entry_Validate_Func)( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes statetable_table, FT_Bytes statetable_limit, GXV_Validator valid ); typedef void (*GXV_StateTable_OptData_Load_Func)( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); typedef struct GXV_StateTable_ValidatorRec_ { GXV_GlyphOffset_Format entry_glyphoffset_fmt; void* optdata; GXV_StateTable_Subtable_Setup_Func subtable_setup_func; GXV_StateTable_Entry_Validate_Func entry_validate_func; GXV_StateTable_OptData_Load_Func optdata_load_func; } GXV_StateTable_ValidatorRec, *GXV_StateTable_ValidatorRecData; /* ---------------------- 32bit XStateTable ---------------------------- */ typedef GXV_StateTable_GlyphOffsetDesc GXV_XStateTable_GlyphOffsetDesc; typedef const GXV_XStateTable_GlyphOffsetDesc* GXV_XStateTable_GlyphOffsetCPtr; typedef void (*GXV_XStateTable_Subtable_Setup_Func)( FT_ULong table_size, FT_ULong classTable, FT_ULong stateArray, FT_ULong entryTable, FT_ULong* classTable_length_p, FT_ULong* stateArray_length_p, FT_ULong* entryTable_length_p, GXV_Validator valid ); typedef void (*GXV_XStateTable_Entry_Validate_Func)( FT_UShort state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes xstatetable_table, FT_Bytes xstatetable_limit, GXV_Validator valid ); typedef GXV_StateTable_OptData_Load_Func GXV_XStateTable_OptData_Load_Func; typedef struct GXV_XStateTable_ValidatorRec_ { int entry_glyphoffset_fmt; void* optdata; GXV_XStateTable_Subtable_Setup_Func subtable_setup_func; GXV_XStateTable_Entry_Validate_Func entry_validate_func; GXV_XStateTable_OptData_Load_Func optdata_load_func; FT_ULong nClasses; FT_UShort maxClassID; } GXV_XStateTable_ValidatorRec, *GXV_XStateTable_ValidatorRecData; /* ===================================================================== */ typedef struct GXV_ValidatorRec_ { FT_Validator root; FT_Face face; void* table_data; FT_ULong subtable_length; GXV_LookupValue_SignSpec lookupval_sign; GXV_Lookup_Value_Validate_Func lookupval_func; GXV_Lookup_Fmt4_Transit_Func lookupfmt4_trans; FT_Bytes lookuptbl_head; FT_UShort min_gid; FT_UShort max_gid; GXV_StateTable_ValidatorRec statetable; GXV_XStateTable_ValidatorRec xstatetable; #ifdef FT_DEBUG_LEVEL_TRACE FT_UInt debug_indent; const FT_String* debug_function_name[3]; #endif } GXV_ValidatorRec; #define GXV_TABLE_DATA( tag, field ) \ ( ( (GXV_ ## tag ## _Data)valid->table_data )->field ) #undef FT_INVALID_ #define FT_INVALID_( _prefix, _error ) \ ft_validator_error( valid->root, _prefix ## _error ) #define GXV_LIMIT_CHECK( _count ) \ FT_BEGIN_STMNT \ if ( p + _count > ( limit? limit : valid->root->limit ) ) \ FT_INVALID_TOO_SHORT; \ FT_END_STMNT #ifdef FT_DEBUG_LEVEL_TRACE #define GXV_INIT valid->debug_indent = 0 #define GXV_NAME_ENTER( name ) \ FT_BEGIN_STMNT \ valid->debug_indent += 2; \ FT_TRACE4(( "%*.s", valid->debug_indent, 0 )); \ FT_TRACE4(( "%s table\n", name )); \ FT_END_STMNT #define GXV_EXIT valid->debug_indent -= 2 #define GXV_TRACE( s ) \ FT_BEGIN_STMNT \ FT_TRACE4(( "%*.s", valid->debug_indent, 0 )); \ FT_TRACE4( s ); \ FT_END_STMNT #else /* !FT_DEBUG_LEVEL_TRACE */ #define GXV_INIT do { } while ( 0 ) #define GXV_NAME_ENTER( name ) do { } while ( 0 ) #define GXV_EXIT do { } while ( 0 ) #define GXV_TRACE( s ) do { } while ( 0 ) #endif /* !FT_DEBUG_LEVEL_TRACE */ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** 32bit alignment checking *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define GXV_32BIT_ALIGNMENT_VALIDATE( a ) \ FT_BEGIN_STMNT \ { \ if ( (a) & 3 ) \ FT_INVALID_OFFSET; \ } \ FT_END_STMNT /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Dumping Binary Data *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define GXV_TRACE_HEXDUMP( p, len ) \ FT_BEGIN_STMNT \ { \ FT_Bytes b; \ \ \ for ( b = p; b < (FT_Bytes)p + len; b++ ) \ FT_TRACE1(("\\x%02x", *b)) ; \ } \ FT_END_STMNT #define GXV_TRACE_HEXDUMP_C( p, len ) \ FT_BEGIN_STMNT \ { \ FT_Bytes b; \ \ \ for ( b = p; b < (FT_Bytes)p + len; b++ ) \ if ( 0x40 < *b && *b < 0x7e ) \ FT_TRACE1(("%c", *b)) ; \ else \ FT_TRACE1(("\\x%02x", *b)) ; \ } \ FT_END_STMNT #define GXV_TRACE_HEXDUMP_SFNTNAME( n ) \ GXV_TRACE_HEXDUMP( n.string, n.string_len ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** LOOKUP TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( void ) gxv_BinSrchHeader_validate( FT_Bytes p, FT_Bytes limit, FT_UShort* unitSize_p, FT_UShort* nUnits_p, GXV_Validator valid ); FT_LOCAL( void ) gxv_LookupTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Glyph ID *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( FT_Int ) gxv_glyphid_validate( FT_UShort gid, GXV_Validator valid ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CONTROL POINT *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( void ) gxv_ctlPoint_validate( FT_UShort gid, FT_Short ctl_point, GXV_Validator valid ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** SFNT NAME *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( void ) gxv_sfntName_validate( FT_UShort name_index, FT_UShort min_index, FT_UShort max_index, GXV_Validator valid ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** STATE TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( void ) gxv_StateTable_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ); FT_LOCAL( void ) gxv_XStateTable_subtable_setup( FT_ULong table_size, FT_ULong classTable, FT_ULong stateArray, FT_ULong entryTable, FT_ULong* classTable_length_p, FT_ULong* stateArray_length_p, FT_ULong* entryTable_length_p, GXV_Validator valid ); FT_LOCAL( void ) gxv_StateTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_XStateTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY MACROS AND FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL( void ) gxv_array_getlimits_byte( FT_Bytes table, FT_Bytes limit, FT_Byte* min, FT_Byte* max, GXV_Validator valid ); FT_LOCAL( void ) gxv_array_getlimits_ushort( FT_Bytes table, FT_Bytes limit, FT_UShort* min, FT_UShort* max, GXV_Validator valid ); FT_LOCAL( void ) gxv_set_length_by_ushort_offset( FT_UShort* offset, FT_UShort** length, FT_UShort* buff, FT_UInt nmemb, FT_UShort limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_set_length_by_ulong_offset( FT_ULong* offset, FT_ULong** length, FT_ULong* buff, FT_UInt nmemb, FT_ULong limit, GXV_Validator valid); #define GXV_SUBTABLE_OFFSET_CHECK( _offset ) \ FT_BEGIN_STMNT \ if ( (_offset) > valid->subtable_length ) \ FT_INVALID_OFFSET; \ FT_END_STMNT #define GXV_SUBTABLE_LIMIT_CHECK( _count ) \ FT_BEGIN_STMNT \ if ( ( p + (_count) - valid->subtable_start ) > \ valid->subtable_length ) \ FT_INVALID_TOO_SHORT; \ FT_END_STMNT #define GXV_USHORT_TO_SHORT( _us ) \ ( ( 0x8000U < ( _us ) ) ? ( ( _us ) - 0x8000U ) : ( _us ) ) #define GXV_STATETABLE_HEADER_SIZE ( 2 + 2 + 2 + 2 ) #define GXV_STATEHEADER_SIZE GXV_STATETABLE_HEADER_SIZE #define GXV_XSTATETABLE_HEADER_SIZE ( 4 + 4 + 4 + 4 ) #define GXV_XSTATEHEADER_SIZE GXV_XSTATETABLE_HEADER_SIZE /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Table overlapping *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_odtect_DataRec_ { FT_Bytes start; FT_ULong length; FT_String* name; } GXV_odtect_DataRec, *GXV_odtect_Data; typedef struct GXV_odtect_RangeRec_ { FT_UInt nRanges; GXV_odtect_Data range; } GXV_odtect_RangeRec, *GXV_odtect_Range; FT_LOCAL( void ) gxv_odtect_add_range( FT_Bytes start, FT_ULong length, const FT_String* name, GXV_odtect_Range odtect ); FT_LOCAL( void ) gxv_odtect_validate( GXV_odtect_Range odtect, GXV_Validator valid ); #define GXV_ODTECT( n, odtect ) \ GXV_odtect_DataRec odtect ## _range[n]; \ GXV_odtect_RangeRec odtect ## _rec = { 0, NULL }; \ GXV_odtect_Range odtect = NULL #define GXV_ODTECT_INIT( odtect ) \ FT_BEGIN_STMNT \ odtect ## _rec.nRanges = 0; \ odtect ## _rec.range = odtect ## _range; \ odtect = & odtect ## _rec; \ FT_END_STMNT /* */ FT_END_HEADER #endif /* __GXVCOMMN_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvcommn.h
C
apache-2.0
23,810
/***************************************************************************/ /* */ /* gxverror.h */ /* */ /* TrueTypeGX/AAT validation module error codes (specification only). */ /* */ /* Copyright 2004, 2005, 2012-2013 */ /* by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to define the OpenType validation module error */ /* enumeration constants. */ /* */ /*************************************************************************/ #ifndef __GXVERROR_H__ #define __GXVERROR_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX GXV_Err_ #define FT_ERR_BASE FT_Mod_Err_GXvalid #include FT_ERRORS_H #endif /* __GXVERROR_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxverror.h
C
apache-2.0
2,602
/***************************************************************************/ /* */ /* gxvfeat.c */ /* */ /* TrueTypeGX/AAT feat table validation (body). */ /* */ /* Copyright 2004, 2005, 2008, 2012 by */ /* suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" #include "gxvfeat.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvfeat /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_feat_DataRec_ { FT_UInt reserved_size; FT_UShort feature; FT_UShort setting; } GXV_feat_DataRec, *GXV_feat_Data; #define GXV_FEAT_DATA( field ) GXV_TABLE_DATA( feat, field ) typedef enum GXV_FeatureFlagsMask_ { GXV_FEAT_MASK_EXCLUSIVE_SETTINGS = 0x8000U, GXV_FEAT_MASK_DYNAMIC_DEFAULT = 0x4000, GXV_FEAT_MASK_UNUSED = 0x3F00, GXV_FEAT_MASK_DEFAULT_SETTING = 0x00FF } GXV_FeatureFlagsMask; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_feat_registry_validate( FT_UShort feature, FT_UShort nSettings, FT_Bool exclusive, GXV_Validator valid ) { GXV_NAME_ENTER( "feature in registry" ); GXV_TRACE(( " (feature = %u)\n", feature )); if ( feature >= gxv_feat_registry_length ) { GXV_TRACE(( "feature number %d is out of range %d\n", feature, gxv_feat_registry_length )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); goto Exit; } if ( gxv_feat_registry[feature].existence == 0 ) { GXV_TRACE(( "feature number %d is in defined range but doesn't exist\n", feature )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); goto Exit; } if ( gxv_feat_registry[feature].apple_reserved ) { /* Don't use here. Apple is reserved. */ GXV_TRACE(( "feature number %d is reserved by Apple\n", feature )); if ( valid->root->level >= FT_VALIDATE_TIGHT ) FT_INVALID_DATA; } if ( nSettings != gxv_feat_registry[feature].nSettings ) { GXV_TRACE(( "feature %d: nSettings %d != defined nSettings %d\n", feature, nSettings, gxv_feat_registry[feature].nSettings )); if ( valid->root->level >= FT_VALIDATE_TIGHT ) FT_INVALID_DATA; } if ( exclusive != gxv_feat_registry[feature].exclusive ) { GXV_TRACE(( "exclusive flag %d differs from predefined value\n", exclusive )); if ( valid->root->level >= FT_VALIDATE_TIGHT ) FT_INVALID_DATA; } Exit: GXV_EXIT; } static void gxv_feat_name_index_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_Short nameIndex; GXV_NAME_ENTER( "nameIndex" ); GXV_LIMIT_CHECK( 2 ); nameIndex = FT_NEXT_SHORT ( p ); GXV_TRACE(( " (nameIndex = %d)\n", nameIndex )); gxv_sfntName_validate( (FT_UShort)nameIndex, 255, 32768U, valid ); GXV_EXIT; } static void gxv_feat_setting_validate( FT_Bytes table, FT_Bytes limit, FT_Bool exclusive, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort setting; GXV_NAME_ENTER( "setting" ); GXV_LIMIT_CHECK( 2 ); setting = FT_NEXT_USHORT( p ); /* If we have exclusive setting, the setting should be odd. */ if ( exclusive && ( setting & 1 ) == 0 ) FT_INVALID_DATA; gxv_feat_name_index_validate( p, limit, valid ); GXV_FEAT_DATA( setting ) = setting; GXV_EXIT; } static void gxv_feat_name_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UInt reserved_size = GXV_FEAT_DATA( reserved_size ); FT_UShort feature; FT_UShort nSettings; FT_ULong settingTable; FT_UShort featureFlags; FT_Bool exclusive; FT_Int last_setting; FT_UInt i; GXV_NAME_ENTER( "name" ); /* feature + nSettings + settingTable + featureFlags */ GXV_LIMIT_CHECK( 2 + 2 + 4 + 2 ); feature = FT_NEXT_USHORT( p ); GXV_FEAT_DATA( feature ) = feature; nSettings = FT_NEXT_USHORT( p ); settingTable = FT_NEXT_ULONG ( p ); featureFlags = FT_NEXT_USHORT( p ); if ( settingTable < reserved_size ) FT_INVALID_OFFSET; if ( ( featureFlags & GXV_FEAT_MASK_UNUSED ) == 0 ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); exclusive = FT_BOOL( featureFlags & GXV_FEAT_MASK_EXCLUSIVE_SETTINGS ); if ( exclusive ) { FT_Byte dynamic_default; if ( featureFlags & GXV_FEAT_MASK_DYNAMIC_DEFAULT ) dynamic_default = (FT_Byte)( featureFlags & GXV_FEAT_MASK_DEFAULT_SETTING ); else dynamic_default = 0; /* If exclusive, check whether default setting is in the range. */ if ( !( dynamic_default < nSettings ) ) FT_INVALID_FORMAT; } gxv_feat_registry_validate( feature, nSettings, exclusive, valid ); gxv_feat_name_index_validate( p, limit, valid ); p = valid->root->base + settingTable; for ( last_setting = -1, i = 0; i < nSettings; i++ ) { gxv_feat_setting_validate( p, limit, exclusive, valid ); if ( (FT_Int)GXV_FEAT_DATA( setting ) <= last_setting ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_FORMAT ); last_setting = (FT_Int)GXV_FEAT_DATA( setting ); /* setting + nameIndex */ p += ( 2 + 2 ); } GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** feat TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_feat_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_feat_DataRec featrec; GXV_feat_Data feat = &featrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_UInt featureNameCount; FT_UInt i; FT_Int last_feature; valid->root = ftvalid; valid->table_data = feat; valid->face = face; FT_TRACE3(( "validating `feat' table\n" )); GXV_INIT; feat->reserved_size = 0; /* version + featureNameCount + none_0 + none_1 */ GXV_LIMIT_CHECK( 4 + 2 + 2 + 4 ); feat->reserved_size += 4 + 2 + 2 + 4; if ( FT_NEXT_ULONG( p ) != 0x00010000UL ) /* Version */ FT_INVALID_FORMAT; featureNameCount = FT_NEXT_USHORT( p ); GXV_TRACE(( " (featureNameCount = %d)\n", featureNameCount )); if ( !( IS_PARANOID_VALIDATION ) ) p += 6; /* skip (none) and (none) */ else { if ( FT_NEXT_USHORT( p ) != 0 ) FT_INVALID_DATA; if ( FT_NEXT_ULONG( p ) != 0 ) FT_INVALID_DATA; } feat->reserved_size += featureNameCount * ( 2 + 2 + 4 + 2 + 2 ); for ( last_feature = -1, i = 0; i < featureNameCount; i++ ) { gxv_feat_name_validate( p, limit, valid ); if ( (FT_Int)GXV_FEAT_DATA( feature ) <= last_feature ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_FORMAT ); last_feature = GXV_FEAT_DATA( feature ); p += 2 + 2 + 4 + 2 + 2; } FT_TRACE4(( "\n" )); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvfeat.c
C
apache-2.0
11,134
/***************************************************************************/ /* */ /* gxvfeat.h */ /* */ /* TrueTypeGX/AAT feat table validation (specification). */ /* */ /* Copyright 2004, 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __GXVFEAT_H__ #define __GXVFEAT_H__ #include "gxvalid.h" #include "gxvcommn.h" /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Registry predefined by Apple *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* TODO: More compact format */ typedef struct GXV_Feature_RegistryRec_ { FT_Bool existence; FT_Bool apple_reserved; FT_Bool exclusive; FT_Byte nSettings; } GX_Feature_RegistryRec; #define gxv_feat_registry_length \ ( sizeof ( gxv_feat_registry ) / \ sizeof ( GX_Feature_RegistryRec ) ) static GX_Feature_RegistryRec gxv_feat_registry[] = { /* Generated from gxvfgen.c */ {1, 0, 0, 1}, /* All Typographic Features */ {1, 0, 0, 8}, /* Ligatures */ {1, 0, 1, 3}, /* Cursive Connection */ {1, 0, 1, 6}, /* Letter Case */ {1, 0, 0, 1}, /* Vertical Substitution */ {1, 0, 0, 1}, /* Linguistic Rearrangement */ {1, 0, 1, 2}, /* Number Spacing */ {1, 1, 0, 0}, /* Apple Reserved 1 */ {1, 0, 0, 5}, /* Smart Swashes */ {1, 0, 1, 3}, /* Diacritics */ {1, 0, 1, 4}, /* Vertical Position */ {1, 0, 1, 3}, /* Fractions */ {1, 1, 0, 0}, /* Apple Reserved 2 */ {1, 0, 0, 1}, /* Overlapping Characters */ {1, 0, 0, 6}, /* Typographic Extras */ {1, 0, 0, 5}, /* Mathematical Extras */ {1, 0, 1, 7}, /* Ornament Sets */ {1, 0, 1, 1}, /* Character Alternatives */ {1, 0, 1, 5}, /* Design Complexity */ {1, 0, 1, 6}, /* Style Options */ {1, 0, 1, 11}, /* Character Shape */ {1, 0, 1, 2}, /* Number Case */ {1, 0, 1, 4}, /* Text Spacing */ {1, 0, 1, 10}, /* Transliteration */ {1, 0, 1, 9}, /* Annotation */ {1, 0, 1, 2}, /* Kana Spacing */ {1, 0, 1, 2}, /* Ideographic Spacing */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {0, 0, 0, 0}, /* __EMPTY__ */ {1, 0, 1, 4}, /* Text Spacing */ {1, 0, 1, 2}, /* Kana Spacing */ {1, 0, 1, 2}, /* Ideographic Spacing */ {1, 0, 1, 4}, /* CJK Roman Spacing */ }; #endif /* __GXVFEAT_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvfeat.h
C
apache-2.0
6,993
/***************************************************************************/ /* */ /* gxfgen.c */ /* */ /* Generate feature registry data for gxv `feat' validator. */ /* This program is derived from gxfeatreg.c in gxlayout. */ /* */ /* Copyright 2004, 2005, 2006 by Masatake YAMATO and Redhat K.K. */ /* */ /* This file may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxfeatreg.c */ /* */ /* Database of font features pre-defined by Apple Computer, Inc. */ /* http://developer.apple.com/fonts/Registry/ */ /* (body). */ /* */ /* Copyright 2003 by */ /* Masatake YAMATO and Redhat K.K. */ /* */ /* This file may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* Development of gxfeatreg.c is supported by */ /* Information-technology Promotion Agency, Japan. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* This file is compiled as a stand-alone executable. */ /* This file is never compiled into `libfreetype2'. */ /* The output of this file is used in `gxvfeat.c'. */ /* ----------------------------------------------------------------------- */ /* Compile: gcc `pkg-config --cflags freetype2` gxvfgen.c -o gxvfgen */ /* Run: ./gxvfgen > tmp.c */ /* */ /***************************************************************************/ /*******************************************************************/ /* WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING */ /*******************************************************************/ /* * If you add a new setting to a feature, check the number of settings * in the feature. If the number is greater than the value defined as * FEATREG_MAX_SETTING, update the value. */ #define FEATREG_MAX_SETTING 12 /*******************************************************************/ /* WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING */ /*******************************************************************/ #include <stdio.h> #include <string.h> /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define APPLE_RESERVED "Apple Reserved" #define APPLE_RESERVED_LENGTH 14 typedef struct GX_Feature_RegistryRec_ { const char* feat_name; char exclusive; char* setting_name[FEATREG_MAX_SETTING]; } GX_Feature_RegistryRec; #define EMPTYFEAT {0, 0, {NULL}} static GX_Feature_RegistryRec featreg_table[] = { { /* 0 */ "All Typographic Features", 0, { "All Type Features", NULL } }, { /* 1 */ "Ligatures", 0, { "Required Ligatures", "Common Ligatures", "Rare Ligatures", "Logos", "Rebus Pictures", "Diphthong Ligatures", "Squared Ligatures", "Squared Ligatures, Abbreviated", NULL } }, { /* 2 */ "Cursive Connection", 1, { "Unconnected", "Partially Connected", "Cursive", NULL } }, { /* 3 */ "Letter Case", 1, { "Upper & Lower Case", "All Caps", "All Lower Case", "Small Caps", "Initial Caps", "Initial Caps & Small Caps", NULL } }, { /* 4 */ "Vertical Substitution", 0, { /* "Substitute Vertical Forms", */ "Turns on the feature", NULL } }, { /* 5 */ "Linguistic Rearrangement", 0, { /* "Linguistic Rearrangement", */ "Turns on the feature", NULL } }, { /* 6 */ "Number Spacing", 1, { "Monospaced Numbers", "Proportional Numbers", NULL } }, { /* 7 */ APPLE_RESERVED " 1", 0, {NULL} }, { /* 8 */ "Smart Swashes", 0, { "Word Initial Swashes", "Word Final Swashes", "Line Initial Swashes", "Line Final Swashes", "Non-Final Swashes", NULL } }, { /* 9 */ "Diacritics", 1, { "Show Diacritics", "Hide Diacritics", "Decompose Diacritics", NULL } }, { /* 10 */ "Vertical Position", 1, { /* "Normal Position", */ "No Vertical Position", "Superiors", "Inferiors", "Ordinals", NULL } }, { /* 11 */ "Fractions", 1, { "No Fractions", "Vertical Fractions", "Diagonal Fractions", NULL } }, { /* 12 */ APPLE_RESERVED " 2", 0, {NULL} }, { /* 13 */ "Overlapping Characters", 0, { /* "Prevent Overlap", */ "Turns on the feature", NULL } }, { /* 14 */ "Typographic Extras", 0, { "Hyphens to Em Dash", "Hyphens to En Dash", "Unslashed Zero", "Form Interrobang", "Smart Quotes", "Periods to Ellipsis", NULL } }, { /* 15 */ "Mathematical Extras", 0, { "Hyphens to Minus", "Asterisk to Multiply", "Slash to Divide", "Inequality Ligatures", "Exponents", NULL } }, { /* 16 */ "Ornament Sets", 1, { "No Ornaments", "Dingbats", "Pi Characters", "Fleurons", "Decorative Borders", "International Symbols", "Math Symbols", NULL } }, { /* 17 */ "Character Alternatives", 1, { "No Alternates", /* TODO */ NULL } }, { /* 18 */ "Design Complexity", 1, { "Design Level 1", "Design Level 2", "Design Level 3", "Design Level 4", "Design Level 5", /* TODO */ NULL } }, { /* 19 */ "Style Options", 1, { "No Style Options", "Display Text", "Engraved Text", "Illuminated Caps", "Tilling Caps", "Tall Caps", NULL } }, { /* 20 */ "Character Shape", 1, { "Traditional Characters", "Simplified Characters", "JIS 1978 Characters", "JIS 1983 Characters", "JIS 1990 Characters", "Traditional Characters, Alternative Set 1", "Traditional Characters, Alternative Set 2", "Traditional Characters, Alternative Set 3", "Traditional Characters, Alternative Set 4", "Traditional Characters, Alternative Set 5", "Expert Characters", NULL /* count => 12 */ } }, { /* 21 */ "Number Case", 1, { "Lower Case Numbers", "Upper Case Numbers", NULL } }, { /* 22 */ "Text Spacing", 1, { "Proportional", "Monospaced", "Half-width", "Normal", NULL } }, /* Here after Newer */ { /* 23 */ "Transliteration", 1, { "No Transliteration", "Hanja To Hangul", "Hiragana to Katakana", "Katakana to Hiragana", "Kana to Romanization", "Romanization to Hiragana", "Romanization to Katakana", "Hanja to Hangul, Alternative Set 1", "Hanja to Hangul, Alternative Set 2", "Hanja to Hangul, Alternative Set 3", NULL } }, { /* 24 */ "Annotation", 1, { "No Annotation", "Box Annotation", "Rounded Box Annotation", "Circle Annotation", "Inverted Circle Annotation", "Parenthesis Annotation", "Period Annotation", "Roman Numeral Annotation", "Diamond Annotation", NULL } }, { /* 25 */ "Kana Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 26 */ "Ideographic Spacing", 1, { "Full Width", "Proportional", NULL } }, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 27-30 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 31-35 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 36-40 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 40-45 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 46-50 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 51-55 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 56-60 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 61-65 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 66-70 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 71-75 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 76-80 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 81-85 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 86-90 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 91-95 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 96-98 */ EMPTYFEAT, /* 99 */ { /* 100 => 22 */ "Text Spacing", 1, { "Proportional", "Monospaced", "Half-width", "Normal", NULL } }, { /* 101 => 25 */ "Kana Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 102 => 26 */ "Ideographic Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 103 */ "CJK Roman Spacing", 1, { "Half-width", "Proportional", "Default Roman", "Full-width Roman", NULL } }, { /* 104 => 1 */ "All Typographic Features", 0, { "All Type Features", NULL } } }; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Generator *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ int main( void ) { int i; printf( " {\n" ); printf( " /* Generated from %s */\n", __FILE__ ); for ( i = 0; i < sizeof ( featreg_table ) / sizeof ( GX_Feature_RegistryRec ); i++ ) { const char* feat_name; int nSettings; feat_name = featreg_table[i].feat_name; for ( nSettings = 0; featreg_table[i].setting_name[nSettings]; nSettings++) ; /* Do nothing */ printf( " {%1d, %1d, %1d, %2d}, /* %s */\n", feat_name ? 1 : 0, ( feat_name && ( ft_strncmp( feat_name, APPLE_RESERVED, APPLE_RESERVED_LENGTH ) == 0 ) ) ? 1 : 0, featreg_table[i].exclusive ? 1 : 0, nSettings, feat_name ? feat_name : "__EMPTY__" ); } printf( " };\n" ); return 0; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvfgen.c
C
apache-2.0
15,595
/***************************************************************************/ /* */ /* gxvjust.c */ /* */ /* TrueTypeGX/AAT just table validation (body). */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" #include FT_SFNT_NAMES_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvjust /* * referred `just' table format specification: * http://developer.apple.com/fonts/TTRefMan/RM06/Chap6just.html * last updated 2000. * ---------------------------------------------- * [JUST HEADER]: GXV_JUST_HEADER_SIZE * version (fixed: 32bit) = 0x00010000 * format (uint16: 16bit) = 0 is only defined (2000) * horizOffset (uint16: 16bit) * vertOffset (uint16: 16bit) * ---------------------------------------------- */ typedef struct GXV_just_DataRec_ { FT_UShort wdc_offset_max; FT_UShort wdc_offset_min; FT_UShort pc_offset_max; FT_UShort pc_offset_min; } GXV_just_DataRec, *GXV_just_Data; #define GXV_JUST_DATA( a ) GXV_TABLE_DATA( just, a ) /* GX just table does not define their subset of GID */ static void gxv_just_check_max_gid( FT_UShort gid, const FT_String* msg_tag, GXV_Validator valid ) { if ( gid < valid->face->num_glyphs ) return; GXV_TRACE(( "just table includes too large %s" " GID=%d > %d (in maxp)\n", msg_tag, gid, valid->face->num_glyphs )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } static void gxv_just_wdp_entry_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong justClass; #ifdef GXV_LOAD_UNUSED_VARS FT_Fixed beforeGrowLimit; FT_Fixed beforeShrinkGrowLimit; FT_Fixed afterGrowLimit; FT_Fixed afterShrinkGrowLimit; FT_UShort growFlags; FT_UShort shrinkFlags; #endif GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 + 4 + 2 + 2 ); justClass = FT_NEXT_ULONG( p ); #ifndef GXV_LOAD_UNUSED_VARS p += 4 + 4 + 4 + 4 + 2 + 2; #else beforeGrowLimit = FT_NEXT_ULONG( p ); beforeShrinkGrowLimit = FT_NEXT_ULONG( p ); afterGrowLimit = FT_NEXT_ULONG( p ); afterShrinkGrowLimit = FT_NEXT_ULONG( p ); growFlags = FT_NEXT_USHORT( p ); shrinkFlags = FT_NEXT_USHORT( p ); #endif /* According to Apple spec, only 7bits in justClass is used */ if ( ( justClass & 0xFFFFFF80 ) != 0 ) { GXV_TRACE(( "just table includes non-zero value" " in unused justClass higher bits" " of WidthDeltaPair" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } valid->subtable_length = p - table; } static void gxv_just_wdc_entry_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong count, i; GXV_LIMIT_CHECK( 4 ); count = FT_NEXT_ULONG( p ); for ( i = 0; i < count; i++ ) { GXV_TRACE(( "validating wdc pair %d/%d\n", i + 1, count )); gxv_just_wdp_entry_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; } static void gxv_just_widthDeltaClusters_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table ; FT_Bytes wdc_end = table + GXV_JUST_DATA( wdc_offset_max ); FT_UInt i; GXV_NAME_ENTER( "just justDeltaClusters" ); if ( limit <= wdc_end ) FT_INVALID_OFFSET; for ( i = 0; p <= wdc_end; i++ ) { gxv_just_wdc_entry_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_actSubrecord_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_Fixed lowerLimit; FT_Fixed upperLimit; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort order; #endif FT_UShort decomposedCount; FT_UInt i; GXV_LIMIT_CHECK( 4 + 4 + 2 + 2 ); lowerLimit = FT_NEXT_ULONG( p ); upperLimit = FT_NEXT_ULONG( p ); #ifdef GXV_LOAD_UNUSED_VARS order = FT_NEXT_USHORT( p ); #else p += 2; #endif decomposedCount = FT_NEXT_USHORT( p ); if ( lowerLimit >= upperLimit ) { GXV_TRACE(( "just table includes invalid range spec:" " lowerLimit(%d) > upperLimit(%d)\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } for ( i = 0; i < decomposedCount; i++ ) { FT_UShort glyphs; GXV_LIMIT_CHECK( 2 ); glyphs = FT_NEXT_USHORT( p ); gxv_just_check_max_gid( glyphs, "type0:glyphs", valid ); } valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort addGlyph; GXV_LIMIT_CHECK( 2 ); addGlyph = FT_NEXT_USHORT( p ); gxv_just_check_max_gid( addGlyph, "type1:addGlyph", valid ); valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; #ifdef GXV_LOAD_UNUSED_VARS FT_Fixed substThreshhold; /* Apple misspelled "Threshhold" */ #endif FT_UShort addGlyph; FT_UShort substGlyph; GXV_LIMIT_CHECK( 4 + 2 + 2 ); #ifdef GXV_LOAD_UNUSED_VARS substThreshhold = FT_NEXT_ULONG( p ); #else p += 4; #endif addGlyph = FT_NEXT_USHORT( p ); substGlyph = FT_NEXT_USHORT( p ); if ( addGlyph != 0xFFFF ) gxv_just_check_max_gid( addGlyph, "type2:addGlyph", valid ); gxv_just_check_max_gid( substGlyph, "type2:substGlyph", valid ); valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong variantsAxis; FT_Fixed minimumLimit; FT_Fixed noStretchValue; FT_Fixed maximumLimit; GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 ); variantsAxis = FT_NEXT_ULONG( p ); minimumLimit = FT_NEXT_ULONG( p ); noStretchValue = FT_NEXT_ULONG( p ); maximumLimit = FT_NEXT_ULONG( p ); valid->subtable_length = p - table; if ( variantsAxis != 0x64756374 ) /* 'duct' */ GXV_TRACE(( "variantsAxis 0x%08x is non default value", variantsAxis )); if ( minimumLimit > noStretchValue ) GXV_TRACE(( "type4:minimumLimit 0x%08x > noStretchValue 0x%08x\n", minimumLimit, noStretchValue )); else if ( noStretchValue > maximumLimit ) GXV_TRACE(( "type4:noStretchValue 0x%08x > maximumLimit 0x%08x\n", noStretchValue, maximumLimit )); else if ( !IS_PARANOID_VALIDATION ) return; FT_INVALID_DATA; } static void gxv_just_actSubrecord_type5_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort flags; FT_UShort glyph; GXV_LIMIT_CHECK( 2 + 2 ); flags = FT_NEXT_USHORT( p ); glyph = FT_NEXT_USHORT( p ); if ( flags ) GXV_TRACE(( "type5: nonzero value 0x%04x in unused flags\n", flags )); gxv_just_check_max_gid( glyph, "type5:glyph", valid ); valid->subtable_length = p - table; } /* parse single actSubrecord */ static void gxv_just_actSubrecord_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort actionClass; FT_UShort actionType; FT_ULong actionLength; GXV_NAME_ENTER( "just actSubrecord" ); GXV_LIMIT_CHECK( 2 + 2 + 4 ); actionClass = FT_NEXT_USHORT( p ); actionType = FT_NEXT_USHORT( p ); actionLength = FT_NEXT_ULONG( p ); /* actionClass is related with justClass using 7bit only */ if ( ( actionClass & 0xFF80 ) != 0 ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); if ( actionType == 0 ) gxv_just_actSubrecord_type0_validate( p, limit, valid ); else if ( actionType == 1 ) gxv_just_actSubrecord_type1_validate( p, limit, valid ); else if ( actionType == 2 ) gxv_just_actSubrecord_type2_validate( p, limit, valid ); else if ( actionType == 3 ) ; /* Stretch glyph action: no actionData */ else if ( actionType == 4 ) gxv_just_actSubrecord_type4_validate( p, limit, valid ); else if ( actionType == 5 ) gxv_just_actSubrecord_type5_validate( p, limit, valid ); else FT_INVALID_DATA; valid->subtable_length = actionLength; GXV_EXIT; } static void gxv_just_pcActionRecord_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong actionCount; FT_ULong i; GXV_LIMIT_CHECK( 4 ); actionCount = FT_NEXT_ULONG( p ); GXV_TRACE(( "actionCount = %d\n", actionCount )); for ( i = 0; i < actionCount; i++ ) { gxv_just_actSubrecord_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_pcTable_LookupValue_entry_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); if ( value_p->u > GXV_JUST_DATA( pc_offset_max ) ) GXV_JUST_DATA( pc_offset_max ) = value_p->u; if ( value_p->u < GXV_JUST_DATA( pc_offset_max ) ) GXV_JUST_DATA( pc_offset_min ) = value_p->u; } static void gxv_just_pcLookupTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "just pcLookupTable" ); GXV_JUST_DATA( pc_offset_max ) = 0x0000; GXV_JUST_DATA( pc_offset_min ) = 0xFFFFU; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_just_pcTable_LookupValue_entry_validate; gxv_LookupTable_validate( p, limit, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } static void gxv_just_postcompTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "just postcompTable" ); gxv_just_pcLookupTable_validate( p, limit, valid ); p += valid->subtable_length; gxv_just_pcActionRecord_validate( p, limit, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_classTable_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS /* TODO: validate markClass & currentClass */ FT_UShort setMark; FT_UShort dontAdvance; FT_UShort markClass; FT_UShort currentClass; #endif FT_UNUSED( state ); FT_UNUSED( glyphOffset_p ); FT_UNUSED( table ); FT_UNUSED( limit ); FT_UNUSED( valid ); #ifndef GXV_LOAD_UNUSED_VARS FT_UNUSED( flags ); #else setMark = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); markClass = (FT_UShort)( ( flags >> 7 ) & 0x7F ); currentClass = (FT_UShort)( flags & 0x7F ); #endif } static void gxv_just_justClassTable_validate ( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort length; FT_UShort coverage; FT_ULong subFeatureFlags; GXV_NAME_ENTER( "just justClassTable" ); GXV_LIMIT_CHECK( 2 + 2 + 4 ); length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); subFeatureFlags = FT_NEXT_ULONG( p ); GXV_TRACE(( " justClassTable: coverage = 0x%04x (%s) ", coverage )); if ( ( coverage & 0x4000 ) == 0 ) GXV_TRACE(( "ascending\n" )); else GXV_TRACE(( "descending\n" )); if ( subFeatureFlags ) GXV_TRACE(( " justClassTable: nonzero value (0x%08x)" " in unused subFeatureFlags\n", subFeatureFlags )); valid->statetable.optdata = NULL; valid->statetable.optdata_load_func = NULL; valid->statetable.subtable_setup_func = NULL; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_just_classTable_entry_validate; gxv_StateTable_validate( p, table + length, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } static void gxv_just_wdcTable_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); if ( value_p->u > GXV_JUST_DATA( wdc_offset_max ) ) GXV_JUST_DATA( wdc_offset_max ) = value_p->u; if ( value_p->u < GXV_JUST_DATA( wdc_offset_min ) ) GXV_JUST_DATA( wdc_offset_min ) = value_p->u; } static void gxv_just_justData_lookuptable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_JUST_DATA( wdc_offset_max ) = 0x0000; GXV_JUST_DATA( wdc_offset_min ) = 0xFFFFU; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_just_wdcTable_LookupValue_validate; gxv_LookupTable_validate( p, limit, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } /* * gxv_just_justData_validate() parses and validates horizData, vertData. */ static void gxv_just_justData_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { /* * following 3 offsets are measured from the start of `just' * (which table points to), not justData */ FT_UShort justClassTableOffset; FT_UShort wdcTableOffset; FT_UShort pcTableOffset; FT_Bytes p = table; GXV_ODTECT( 4, odtect ); GXV_NAME_ENTER( "just justData" ); GXV_ODTECT_INIT( odtect ); GXV_LIMIT_CHECK( 2 + 2 + 2 ); justClassTableOffset = FT_NEXT_USHORT( p ); wdcTableOffset = FT_NEXT_USHORT( p ); pcTableOffset = FT_NEXT_USHORT( p ); GXV_TRACE(( " (justClassTableOffset = 0x%04x)\n", justClassTableOffset )); GXV_TRACE(( " (wdcTableOffset = 0x%04x)\n", wdcTableOffset )); GXV_TRACE(( " (pcTableOffset = 0x%04x)\n", pcTableOffset )); gxv_just_justData_lookuptable_validate( p, limit, valid ); gxv_odtect_add_range( p, valid->subtable_length, "just_LookupTable", odtect ); if ( wdcTableOffset ) { gxv_just_widthDeltaClusters_validate( valid->root->base + wdcTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + wdcTableOffset, valid->subtable_length, "just_wdcTable", odtect ); } if ( pcTableOffset ) { gxv_just_postcompTable_validate( valid->root->base + pcTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + pcTableOffset, valid->subtable_length, "just_pcTable", odtect ); } if ( justClassTableOffset ) { gxv_just_justClassTable_validate( valid->root->base + justClassTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + justClassTableOffset, valid->subtable_length, "just_justClassTable", odtect ); } gxv_odtect_validate( odtect, valid ); GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_just_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { FT_Bytes p = table; FT_Bytes limit = 0; GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_just_DataRec justrec; GXV_just_Data just = &justrec; FT_ULong version; FT_UShort format; FT_UShort horizOffset; FT_UShort vertOffset; GXV_ODTECT( 3, odtect ); GXV_ODTECT_INIT( odtect ); valid->root = ftvalid; valid->table_data = just; valid->face = face; FT_TRACE3(( "validating `just' table\n" )); GXV_INIT; limit = valid->root->limit; GXV_LIMIT_CHECK( 4 + 2 + 2 + 2 ); version = FT_NEXT_ULONG( p ); format = FT_NEXT_USHORT( p ); horizOffset = FT_NEXT_USHORT( p ); vertOffset = FT_NEXT_USHORT( p ); gxv_odtect_add_range( table, p - table, "just header", odtect ); /* Version 1.0 (always:2000) */ GXV_TRACE(( " (version = 0x%08x)\n", version )); if ( version != 0x00010000UL ) FT_INVALID_FORMAT; /* format 0 (always:2000) */ GXV_TRACE(( " (format = 0x%04x)\n", format )); if ( format != 0x0000 ) FT_INVALID_FORMAT; GXV_TRACE(( " (horizOffset = %d)\n", horizOffset )); GXV_TRACE(( " (vertOffset = %d)\n", vertOffset )); /* validate justData */ if ( 0 < horizOffset ) { gxv_just_justData_validate( table + horizOffset, limit, valid ); gxv_odtect_add_range( table + horizOffset, valid->subtable_length, "horizJustData", odtect ); } if ( 0 < vertOffset ) { gxv_just_justData_validate( table + vertOffset, limit, valid ); gxv_odtect_add_range( table + vertOffset, valid->subtable_length, "vertJustData", odtect ); } gxv_odtect_validate( odtect, valid ); FT_TRACE4(( "\n" )); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvjust.c
C
apache-2.0
21,301
/***************************************************************************/ /* */ /* gxvkern.c */ /* */ /* TrueTypeGX/AAT kern table validation (body). */ /* */ /* Copyright 2004-2007, 2013 */ /* by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" #include FT_SFNT_NAMES_H #include FT_SERVICE_GX_VALIDATE_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvkern /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef enum GXV_kern_Version_ { KERN_VERSION_CLASSIC = 0x0000, KERN_VERSION_NEW = 0x0001 } GXV_kern_Version; typedef enum GXV_kern_Dialect_ { KERN_DIALECT_UNKNOWN = 0, KERN_DIALECT_MS = FT_VALIDATE_MS, KERN_DIALECT_APPLE = FT_VALIDATE_APPLE, KERN_DIALECT_ANY = FT_VALIDATE_CKERN } GXV_kern_Dialect; typedef struct GXV_kern_DataRec_ { GXV_kern_Version version; void *subtable_data; GXV_kern_Dialect dialect_request; } GXV_kern_DataRec, *GXV_kern_Data; #define GXV_KERN_DATA( field ) GXV_TABLE_DATA( kern, field ) #define KERN_IS_CLASSIC( valid ) \ ( KERN_VERSION_CLASSIC == GXV_KERN_DATA( version ) ) #define KERN_IS_NEW( valid ) \ ( KERN_VERSION_NEW == GXV_KERN_DATA( version ) ) #define KERN_DIALECT( valid ) \ GXV_KERN_DATA( dialect_request ) #define KERN_ALLOWS_MS( valid ) \ ( KERN_DIALECT( valid ) & KERN_DIALECT_MS ) #define KERN_ALLOWS_APPLE( valid ) \ ( KERN_DIALECT( valid ) & KERN_DIALECT_APPLE ) #define GXV_KERN_HEADER_SIZE ( KERN_IS_NEW( valid ) ? 8 : 4 ) #define GXV_KERN_SUBTABLE_HEADER_SIZE ( KERN_IS_NEW( valid ) ? 8 : 6 ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** SUBTABLE VALIDATORS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* ============================= format 0 ============================== */ static void gxv_kern_subtable_fmt0_pairs_validate( FT_Bytes table, FT_Bytes limit, FT_UShort nPairs, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort i; FT_UShort last_gid_left = 0; FT_UShort last_gid_right = 0; FT_UNUSED( limit ); GXV_NAME_ENTER( "kern format 0 pairs" ); for ( i = 0; i < nPairs; i++ ) { FT_UShort gid_left; FT_UShort gid_right; #ifdef GXV_LOAD_UNUSED_VARS FT_Short kernValue; #endif /* left */ gid_left = FT_NEXT_USHORT( p ); gxv_glyphid_validate( gid_left, valid ); /* right */ gid_right = FT_NEXT_USHORT( p ); gxv_glyphid_validate( gid_right, valid ); /* Pairs of left and right GIDs must be unique and sorted. */ GXV_TRACE(( "left gid = %u, right gid = %u\n", gid_left, gid_right )); if ( gid_left == last_gid_left ) { if ( last_gid_right < gid_right ) last_gid_right = gid_right; else FT_INVALID_DATA; } else if ( last_gid_left < gid_left ) { last_gid_left = gid_left; last_gid_right = gid_right; } else FT_INVALID_DATA; /* skip the kern value */ #ifdef GXV_LOAD_UNUSED_VARS kernValue = FT_NEXT_SHORT( p ); #else p += 2; #endif } GXV_EXIT; } static void gxv_kern_subtable_fmt0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table + GXV_KERN_SUBTABLE_HEADER_SIZE; FT_UShort nPairs; FT_UShort unitSize; GXV_NAME_ENTER( "kern subtable format 0" ); unitSize = 2 + 2 + 2; nPairs = 0; /* nPairs, searchRange, entrySelector, rangeShift */ GXV_LIMIT_CHECK( 2 + 2 + 2 + 2 ); gxv_BinSrchHeader_validate( p, limit, &unitSize, &nPairs, valid ); p += 2 + 2 + 2 + 2; gxv_kern_subtable_fmt0_pairs_validate( p, limit, nPairs, valid ); GXV_EXIT; } /* ============================= format 1 ============================== */ typedef struct GXV_kern_fmt1_StateOptRec_ { FT_UShort valueTable; FT_UShort valueTable_length; } GXV_kern_fmt1_StateOptRec, *GXV_kern_fmt1_StateOptRecData; static void gxv_kern_subtable_fmt1_valueTable_load( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_kern_fmt1_StateOptRecData optdata = (GXV_kern_fmt1_StateOptRecData)valid->statetable.optdata; GXV_LIMIT_CHECK( 2 ); optdata->valueTable = FT_NEXT_USHORT( p ); } /* * passed tables_size covers whole StateTable, including kern fmt1 header */ static void gxv_kern_subtable_fmt1_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ) { FT_UShort o[4]; FT_UShort *l[4]; FT_UShort buff[5]; GXV_kern_fmt1_StateOptRecData optdata = (GXV_kern_fmt1_StateOptRecData)valid->statetable.optdata; o[0] = classTable; o[1] = stateArray; o[2] = entryTable; o[3] = optdata->valueTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; l[3] = &(optdata->valueTable_length); gxv_set_length_by_ushort_offset( o, l, buff, 4, table_size, valid ); } /* * passed table & limit are of whole StateTable, not including subtables */ static void gxv_kern_subtable_fmt1_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_UShort push; FT_UShort dontAdvance; #endif FT_UShort valueOffset; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort kernAction; FT_UShort kernValue; #endif FT_UNUSED( state ); FT_UNUSED( glyphOffset_p ); #ifdef GXV_LOAD_UNUSED_VARS push = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); #endif valueOffset = (FT_UShort)( flags & 0x3FFF ); { GXV_kern_fmt1_StateOptRecData vt_rec = (GXV_kern_fmt1_StateOptRecData)valid->statetable.optdata; FT_Bytes p; if ( valueOffset < vt_rec->valueTable ) FT_INVALID_OFFSET; p = table + valueOffset; limit = table + vt_rec->valueTable + vt_rec->valueTable_length; GXV_LIMIT_CHECK( 2 + 2 ); #ifdef GXV_LOAD_UNUSED_VARS kernAction = FT_NEXT_USHORT( p ); kernValue = FT_NEXT_USHORT( p ); #endif } } static void gxv_kern_subtable_fmt1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_kern_fmt1_StateOptRec vt_rec; GXV_NAME_ENTER( "kern subtable format 1" ); valid->statetable.optdata = &vt_rec; valid->statetable.optdata_load_func = gxv_kern_subtable_fmt1_valueTable_load; valid->statetable.subtable_setup_func = gxv_kern_subtable_fmt1_subtable_setup; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_kern_subtable_fmt1_entry_validate; gxv_StateTable_validate( p, limit, valid ); GXV_EXIT; } /* ================ Data for Class-Based Subtables 2, 3 ================ */ typedef enum GXV_kern_ClassSpec_ { GXV_KERN_CLS_L = 0, GXV_KERN_CLS_R } GXV_kern_ClassSpec; /* ============================= format 2 ============================== */ /* ---------------------- format 2 specific data ----------------------- */ typedef struct GXV_kern_subtable_fmt2_DataRec_ { FT_UShort rowWidth; FT_UShort array; FT_UShort offset_min[2]; FT_UShort offset_max[2]; const FT_String* class_tag[2]; GXV_odtect_Range odtect; } GXV_kern_subtable_fmt2_DataRec, *GXV_kern_subtable_fmt2_Data; #define GXV_KERN_FMT2_DATA( field ) \ ( ( (GXV_kern_subtable_fmt2_DataRec *) \ ( GXV_KERN_DATA( subtable_data ) ) )->field ) /* -------------------------- utility functions ----------------------- */ static void gxv_kern_subtable_fmt2_clstbl_validate( FT_Bytes table, FT_Bytes limit, GXV_kern_ClassSpec spec, GXV_Validator valid ) { const FT_String* tag = GXV_KERN_FMT2_DATA( class_tag[spec] ); GXV_odtect_Range odtect = GXV_KERN_FMT2_DATA( odtect ); FT_Bytes p = table; FT_UShort firstGlyph; FT_UShort nGlyphs; GXV_NAME_ENTER( "kern format 2 classTable" ); GXV_LIMIT_CHECK( 2 + 2 ); firstGlyph = FT_NEXT_USHORT( p ); nGlyphs = FT_NEXT_USHORT( p ); GXV_TRACE(( " %s firstGlyph=%d, nGlyphs=%d\n", tag, firstGlyph, nGlyphs )); gxv_glyphid_validate( firstGlyph, valid ); gxv_glyphid_validate( (FT_UShort)( firstGlyph + nGlyphs - 1 ), valid ); gxv_array_getlimits_ushort( p, p + ( 2 * nGlyphs ), &( GXV_KERN_FMT2_DATA( offset_min[spec] ) ), &( GXV_KERN_FMT2_DATA( offset_max[spec] ) ), valid ); gxv_odtect_add_range( table, 2 * nGlyphs, tag, odtect ); GXV_EXIT; } static void gxv_kern_subtable_fmt2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { GXV_ODTECT( 3, odtect ); GXV_kern_subtable_fmt2_DataRec fmt2_rec = { 0, 0, { 0, 0 }, { 0, 0 }, { "leftClass", "rightClass" }, NULL }; FT_Bytes p = table + GXV_KERN_SUBTABLE_HEADER_SIZE; FT_UShort leftOffsetTable; FT_UShort rightOffsetTable; GXV_NAME_ENTER( "kern subtable format 2" ); GXV_ODTECT_INIT( odtect ); fmt2_rec.odtect = odtect; GXV_KERN_DATA( subtable_data ) = &fmt2_rec; GXV_LIMIT_CHECK( 2 + 2 + 2 + 2 ); GXV_KERN_FMT2_DATA( rowWidth ) = FT_NEXT_USHORT( p ); leftOffsetTable = FT_NEXT_USHORT( p ); rightOffsetTable = FT_NEXT_USHORT( p ); GXV_KERN_FMT2_DATA( array ) = FT_NEXT_USHORT( p ); GXV_TRACE(( "rowWidth = %d\n", GXV_KERN_FMT2_DATA( rowWidth ) )); GXV_LIMIT_CHECK( leftOffsetTable ); GXV_LIMIT_CHECK( rightOffsetTable ); GXV_LIMIT_CHECK( GXV_KERN_FMT2_DATA( array ) ); gxv_kern_subtable_fmt2_clstbl_validate( table + leftOffsetTable, limit, GXV_KERN_CLS_L, valid ); gxv_kern_subtable_fmt2_clstbl_validate( table + rightOffsetTable, limit, GXV_KERN_CLS_R, valid ); if ( GXV_KERN_FMT2_DATA( offset_min[GXV_KERN_CLS_L] ) + GXV_KERN_FMT2_DATA( offset_min[GXV_KERN_CLS_R] ) < GXV_KERN_FMT2_DATA( array ) ) FT_INVALID_OFFSET; gxv_odtect_add_range( table + GXV_KERN_FMT2_DATA( array ), GXV_KERN_FMT2_DATA( offset_max[GXV_KERN_CLS_L] ) + GXV_KERN_FMT2_DATA( offset_max[GXV_KERN_CLS_R] ) - GXV_KERN_FMT2_DATA( array ), "array", odtect ); gxv_odtect_validate( odtect, valid ); GXV_EXIT; } /* ============================= format 3 ============================== */ static void gxv_kern_subtable_fmt3_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table + GXV_KERN_SUBTABLE_HEADER_SIZE; FT_UShort glyphCount; FT_Byte kernValueCount; FT_Byte leftClassCount; FT_Byte rightClassCount; FT_Byte flags; GXV_NAME_ENTER( "kern subtable format 3" ); GXV_LIMIT_CHECK( 2 + 1 + 1 + 1 + 1 ); glyphCount = FT_NEXT_USHORT( p ); kernValueCount = FT_NEXT_BYTE( p ); leftClassCount = FT_NEXT_BYTE( p ); rightClassCount = FT_NEXT_BYTE( p ); flags = FT_NEXT_BYTE( p ); if ( valid->face->num_glyphs != glyphCount ) { GXV_TRACE(( "maxGID=%d, but glyphCount=%d\n", valid->face->num_glyphs, glyphCount )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } if ( flags != 0 ) GXV_TRACE(( "kern subtable fmt3 has nonzero value" " (%d) in unused flag\n", flags )); /* * just skip kernValue[kernValueCount] */ GXV_LIMIT_CHECK( 2 * kernValueCount ); p += 2 * kernValueCount; /* * check leftClass[gid] < leftClassCount */ { FT_Byte min, max; GXV_LIMIT_CHECK( glyphCount ); gxv_array_getlimits_byte( p, p + glyphCount, &min, &max, valid ); p += valid->subtable_length; if ( leftClassCount < max ) FT_INVALID_DATA; } /* * check rightClass[gid] < rightClassCount */ { FT_Byte min, max; GXV_LIMIT_CHECK( glyphCount ); gxv_array_getlimits_byte( p, p + glyphCount, &min, &max, valid ); p += valid->subtable_length; if ( rightClassCount < max ) FT_INVALID_DATA; } /* * check kernIndex[i, j] < kernValueCount */ { FT_UShort i, j; for ( i = 0; i < leftClassCount; i++ ) { for ( j = 0; j < rightClassCount; j++ ) { GXV_LIMIT_CHECK( 1 ); if ( kernValueCount < FT_NEXT_BYTE( p ) ) FT_INVALID_OFFSET; } } } valid->subtable_length = p - table; GXV_EXIT; } static FT_Bool gxv_kern_coverage_new_apple_validate( FT_UShort coverage, FT_UShort* format, GXV_Validator valid ) { /* new Apple-dialect */ #ifdef GXV_LOAD_TRACE_VARS FT_Bool kernVertical; FT_Bool kernCrossStream; FT_Bool kernVariation; #endif FT_UNUSED( valid ); /* reserved bits = 0 */ if ( coverage & 0x1FFC ) return FALSE; #ifdef GXV_LOAD_TRACE_VARS kernVertical = FT_BOOL( ( coverage >> 15 ) & 1 ); kernCrossStream = FT_BOOL( ( coverage >> 14 ) & 1 ); kernVariation = FT_BOOL( ( coverage >> 13 ) & 1 ); #endif *format = (FT_UShort)( coverage & 0x0003 ); GXV_TRACE(( "new Apple-dialect: " "horizontal=%d, cross-stream=%d, variation=%d, format=%d\n", !kernVertical, kernCrossStream, kernVariation, *format )); GXV_TRACE(( "kerning values in Apple format subtable are ignored\n" )); return TRUE; } static FT_Bool gxv_kern_coverage_classic_apple_validate( FT_UShort coverage, FT_UShort* format, GXV_Validator valid ) { /* classic Apple-dialect */ #ifdef GXV_LOAD_TRACE_VARS FT_Bool horizontal; FT_Bool cross_stream; #endif /* check expected flags, but don't check if MS-dialect is impossible */ if ( !( coverage & 0xFD00 ) && KERN_ALLOWS_MS( valid ) ) return FALSE; /* reserved bits = 0 */ if ( coverage & 0x02FC ) return FALSE; #ifdef GXV_LOAD_TRACE_VARS horizontal = FT_BOOL( ( coverage >> 15 ) & 1 ); cross_stream = FT_BOOL( ( coverage >> 13 ) & 1 ); #endif *format = (FT_UShort)( coverage & 0x0003 ); GXV_TRACE(( "classic Apple-dialect: " "horizontal=%d, cross-stream=%d, format=%d\n", horizontal, cross_stream, *format )); /* format 1 requires GX State Machine, too new for classic */ if ( *format == 1 ) return FALSE; GXV_TRACE(( "kerning values in Apple format subtable are ignored\n" )); return TRUE; } static FT_Bool gxv_kern_coverage_classic_microsoft_validate( FT_UShort coverage, FT_UShort* format, GXV_Validator valid ) { /* classic Microsoft-dialect */ #ifdef GXV_LOAD_TRACE_VARS FT_Bool horizontal; FT_Bool minimum; FT_Bool cross_stream; FT_Bool override; #endif FT_UNUSED( valid ); /* reserved bits = 0 */ if ( coverage & 0xFDF0 ) return FALSE; #ifdef GXV_LOAD_TRACE_VARS horizontal = FT_BOOL( coverage & 1 ); minimum = FT_BOOL( ( coverage >> 1 ) & 1 ); cross_stream = FT_BOOL( ( coverage >> 2 ) & 1 ); override = FT_BOOL( ( coverage >> 3 ) & 1 ); #endif *format = (FT_UShort)( ( coverage >> 8 ) & 0x0003 ); GXV_TRACE(( "classic Microsoft-dialect: " "horizontal=%d, minimum=%d, cross-stream=%d, " "override=%d, format=%d\n", horizontal, minimum, cross_stream, override, *format )); if ( *format == 2 ) GXV_TRACE(( "kerning values in Microsoft format 2 subtable are ignored\n" )); return TRUE; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** MAIN *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static GXV_kern_Dialect gxv_kern_coverage_validate( FT_UShort coverage, FT_UShort* format, GXV_Validator valid ) { GXV_kern_Dialect result = KERN_DIALECT_UNKNOWN; GXV_NAME_ENTER( "validating coverage" ); GXV_TRACE(( "interprete coverage 0x%04x by Apple style\n", coverage )); if ( KERN_IS_NEW( valid ) ) { if ( gxv_kern_coverage_new_apple_validate( coverage, format, valid ) ) { result = KERN_DIALECT_APPLE; goto Exit; } } if ( KERN_IS_CLASSIC( valid ) && KERN_ALLOWS_APPLE( valid ) ) { if ( gxv_kern_coverage_classic_apple_validate( coverage, format, valid ) ) { result = KERN_DIALECT_APPLE; goto Exit; } } if ( KERN_IS_CLASSIC( valid ) && KERN_ALLOWS_MS( valid ) ) { if ( gxv_kern_coverage_classic_microsoft_validate( coverage, format, valid ) ) { result = KERN_DIALECT_MS; goto Exit; } } GXV_TRACE(( "cannot interprete coverage, broken kern subtable\n" )); Exit: GXV_EXIT; return result; } static void gxv_kern_subtable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; #ifdef GXV_LOAD_TRACE_VARS FT_UShort version = 0; /* MS only: subtable version, unused */ #endif FT_ULong length; /* MS: 16bit, Apple: 32bit*/ FT_UShort coverage; #ifdef GXV_LOAD_TRACE_VARS FT_UShort tupleIndex = 0; /* Apple only */ #endif FT_UShort u16[2]; FT_UShort format = 255; /* subtable format */ GXV_NAME_ENTER( "kern subtable" ); GXV_LIMIT_CHECK( 2 + 2 + 2 ); u16[0] = FT_NEXT_USHORT( p ); /* Apple: length_hi MS: version */ u16[1] = FT_NEXT_USHORT( p ); /* Apple: length_lo MS: length */ coverage = FT_NEXT_USHORT( p ); switch ( gxv_kern_coverage_validate( coverage, &format, valid ) ) { case KERN_DIALECT_MS: #ifdef GXV_LOAD_TRACE_VARS version = u16[0]; #endif length = u16[1]; #ifdef GXV_LOAD_TRACE_VARS tupleIndex = 0; #endif GXV_TRACE(( "Subtable version = %d\n", version )); GXV_TRACE(( "Subtable length = %d\n", length )); break; case KERN_DIALECT_APPLE: #ifdef GXV_LOAD_TRACE_VARS version = 0; #endif length = ( u16[0] << 16 ) + u16[1]; #ifdef GXV_LOAD_TRACE_VARS tupleIndex = 0; #endif GXV_TRACE(( "Subtable length = %d\n", length )); if ( KERN_IS_NEW( valid ) ) { GXV_LIMIT_CHECK( 2 ); #ifdef GXV_LOAD_TRACE_VARS tupleIndex = FT_NEXT_USHORT( p ); #else p += 2; #endif GXV_TRACE(( "Subtable tupleIndex = %d\n", tupleIndex )); } break; default: length = u16[1]; GXV_TRACE(( "cannot detect subtable dialect, " "just skip %d byte\n", length )); goto Exit; } /* formats 1, 2, 3 require the position of the start of this subtable */ if ( format == 0 ) gxv_kern_subtable_fmt0_validate( table, table + length, valid ); else if ( format == 1 ) gxv_kern_subtable_fmt1_validate( table, table + length, valid ); else if ( format == 2 ) gxv_kern_subtable_fmt2_validate( table, table + length, valid ); else if ( format == 3 ) gxv_kern_subtable_fmt3_validate( table, table + length, valid ); else FT_INVALID_DATA; Exit: valid->subtable_length = length; GXV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** kern TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_kern_validate_generic( FT_Bytes table, FT_Face face, FT_Bool classic_only, GXV_kern_Dialect dialect_request, FT_Validator ftvalid ) { GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_kern_DataRec kernrec; GXV_kern_Data kern = &kernrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_ULong nTables = 0; FT_UInt i; valid->root = ftvalid; valid->table_data = kern; valid->face = face; FT_TRACE3(( "validating `kern' table\n" )); GXV_INIT; KERN_DIALECT( valid ) = dialect_request; GXV_LIMIT_CHECK( 2 ); GXV_KERN_DATA( version ) = (GXV_kern_Version)FT_NEXT_USHORT( p ); GXV_TRACE(( "version 0x%04x (higher 16bit)\n", GXV_KERN_DATA( version ) )); if ( 0x0001 < GXV_KERN_DATA( version ) ) FT_INVALID_FORMAT; else if ( KERN_IS_CLASSIC( valid ) ) { GXV_LIMIT_CHECK( 2 ); nTables = FT_NEXT_USHORT( p ); } else if ( KERN_IS_NEW( valid ) ) { if ( classic_only ) FT_INVALID_FORMAT; if ( 0x0000 != FT_NEXT_USHORT( p ) ) FT_INVALID_FORMAT; GXV_LIMIT_CHECK( 4 ); nTables = FT_NEXT_ULONG( p ); } for ( i = 0; i < nTables; i++ ) { GXV_TRACE(( "validating subtable %d/%d\n", i, nTables )); /* p should be 32bit-aligned? */ gxv_kern_subtable_validate( p, 0, valid ); p += valid->subtable_length; } FT_TRACE4(( "\n" )); } FT_LOCAL_DEF( void ) gxv_kern_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { gxv_kern_validate_generic( table, face, 0, KERN_DIALECT_ANY, ftvalid ); } FT_LOCAL_DEF( void ) gxv_kern_validate_classic( FT_Bytes table, FT_Face face, FT_Int dialect_flags, FT_Validator ftvalid ) { GXV_kern_Dialect dialect_request; dialect_request = (GXV_kern_Dialect)dialect_flags; gxv_kern_validate_generic( table, face, 1, dialect_request, ftvalid ); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvkern.c
C
apache-2.0
28,223
/***************************************************************************/ /* */ /* gxvlcar.c */ /* */ /* TrueTypeGX/AAT lcar table validation (body). */ /* */ /* Copyright 2004, 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvlcar /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_lcar_DataRec_ { FT_UShort format; } GXV_lcar_DataRec, *GXV_lcar_Data; #define GXV_LCAR_DATA( FIELD ) GXV_TABLE_DATA( lcar, FIELD ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_lcar_partial_validate( FT_UShort partial, FT_UShort glyph, GXV_Validator valid ) { GXV_NAME_ENTER( "partial" ); if ( GXV_LCAR_DATA( format ) != 1 ) goto Exit; gxv_ctlPoint_validate( glyph, partial, valid ); Exit: GXV_EXIT; } static void gxv_lcar_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_Bytes p = valid->root->base + value_p->u; FT_Bytes limit = valid->root->limit; FT_UShort count; FT_Short partial; FT_UShort i; GXV_NAME_ENTER( "element in lookupTable" ); GXV_LIMIT_CHECK( 2 ); count = FT_NEXT_USHORT( p ); GXV_LIMIT_CHECK( 2 * count ); for ( i = 0; i < count; i++ ) { partial = FT_NEXT_SHORT( p ); gxv_lcar_partial_validate( partial, glyph, valid ); } GXV_EXIT; } /* +------ lcar --------------------+ | | | +===============+ | | | looup header | | | +===============+ | | | BinSrchHeader | | | +===============+ | | | lastGlyph[0] | | | +---------------+ | | | firstGlyph[0] | | head of lcar sfnt table | +---------------+ | + | | offset[0] | -> | offset [byte] | +===============+ | + | | lastGlyph[1] | | (glyphID - firstGlyph) * 2 [byte] | +---------------+ | | | firstGlyph[1] | | | +---------------+ | | | offset[1] | | | +===============+ | | | | .... | | | | 16bit value array | | +===============+ | +------| value | <-------+ | .... | | | | | +----> lcar values...handled by lcar callback function */ static GXV_LookupValueDesc gxv_lcar_LookupFmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ) { FT_Bytes p; FT_Bytes limit; FT_UShort offset; GXV_LookupValueDesc value; FT_UNUSED( lookuptbl_limit ); /* XXX: check range? */ offset = (FT_UShort)( base_value_p->u + relative_gindex * sizeof ( FT_UShort ) ); p = valid->root->base + offset; limit = valid->root->limit; GXV_LIMIT_CHECK ( 2 ); value.u = FT_NEXT_USHORT( p ); return value; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** lcar TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_lcar_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { FT_Bytes p = table; FT_Bytes limit = 0; GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_lcar_DataRec lcarrec; GXV_lcar_Data lcar = &lcarrec; FT_Fixed version; valid->root = ftvalid; valid->table_data = lcar; valid->face = face; FT_TRACE3(( "validating `lcar' table\n" )); GXV_INIT; GXV_LIMIT_CHECK( 4 + 2 ); version = FT_NEXT_ULONG( p ); GXV_LCAR_DATA( format ) = FT_NEXT_USHORT( p ); if ( version != 0x00010000UL) FT_INVALID_FORMAT; if ( GXV_LCAR_DATA( format ) > 1 ) FT_INVALID_FORMAT; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_lcar_LookupValue_validate; valid->lookupfmt4_trans = gxv_lcar_LookupFmt4_transit; gxv_LookupTable_validate( p, limit, valid ); FT_TRACE4(( "\n" )); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvlcar.c
C
apache-2.0
8,239
/***************************************************************************/ /* */ /* gxvmod.c */ /* */ /* FreeType's TrueTypeGX/AAT validation module implementation (body). */ /* */ /* Copyright 2004-2006, 2013 */ /* by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_TRUETYPE_TABLES_H #include FT_TRUETYPE_TAGS_H #include FT_GX_VALIDATE_H #include FT_INTERNAL_OBJECTS_H #include FT_SERVICE_GX_VALIDATE_H #include "gxvmod.h" #include "gxvalid.h" #include "gxvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmodule static FT_Error gxv_load_table( FT_Face face, FT_Tag tag, FT_Byte* volatile* table, FT_ULong* table_len ) { FT_Error error; FT_Memory memory = FT_FACE_MEMORY( face ); error = FT_Load_Sfnt_Table( face, tag, 0, NULL, table_len ); if ( FT_ERR_EQ( error, Table_Missing ) ) return FT_Err_Ok; if ( error ) goto Exit; if ( FT_ALLOC( *table, *table_len ) ) goto Exit; error = FT_Load_Sfnt_Table( face, tag, 0, *table, table_len ); Exit: return error; } #define GXV_TABLE_DECL( _sfnt ) \ FT_Byte* volatile _sfnt = NULL; \ FT_ULong len_ ## _sfnt = 0 #define GXV_TABLE_LOAD( _sfnt ) \ if ( ( FT_VALIDATE_ ## _sfnt ## _INDEX < table_count ) && \ ( gx_flags & FT_VALIDATE_ ## _sfnt ) ) \ { \ error = gxv_load_table( face, TTAG_ ## _sfnt, \ &_sfnt, &len_ ## _sfnt ); \ if ( error ) \ goto Exit; \ } #define GXV_TABLE_VALIDATE( _sfnt ) \ if ( _sfnt ) \ { \ ft_validator_init( &valid, _sfnt, _sfnt + len_ ## _sfnt, \ FT_VALIDATE_DEFAULT ); \ if ( ft_setjmp( valid.jump_buffer ) == 0 ) \ gxv_ ## _sfnt ## _validate( _sfnt, face, &valid ); \ error = valid.error; \ if ( error ) \ goto Exit; \ } #define GXV_TABLE_SET( _sfnt ) \ if ( FT_VALIDATE_ ## _sfnt ## _INDEX < table_count ) \ tables[FT_VALIDATE_ ## _sfnt ## _INDEX] = (FT_Bytes)_sfnt static FT_Error gxv_validate( FT_Face face, FT_UInt gx_flags, FT_Bytes tables[FT_VALIDATE_GX_LENGTH], FT_UInt table_count ) { FT_Memory volatile memory = FT_FACE_MEMORY( face ); FT_Error error = FT_Err_Ok; FT_ValidatorRec volatile valid; FT_UInt i; GXV_TABLE_DECL( feat ); GXV_TABLE_DECL( bsln ); GXV_TABLE_DECL( trak ); GXV_TABLE_DECL( just ); GXV_TABLE_DECL( mort ); GXV_TABLE_DECL( morx ); GXV_TABLE_DECL( kern ); GXV_TABLE_DECL( opbd ); GXV_TABLE_DECL( prop ); GXV_TABLE_DECL( lcar ); for ( i = 0; i < table_count; i++ ) tables[i] = 0; /* load tables */ GXV_TABLE_LOAD( feat ); GXV_TABLE_LOAD( bsln ); GXV_TABLE_LOAD( trak ); GXV_TABLE_LOAD( just ); GXV_TABLE_LOAD( mort ); GXV_TABLE_LOAD( morx ); GXV_TABLE_LOAD( kern ); GXV_TABLE_LOAD( opbd ); GXV_TABLE_LOAD( prop ); GXV_TABLE_LOAD( lcar ); /* validate tables */ GXV_TABLE_VALIDATE( feat ); GXV_TABLE_VALIDATE( bsln ); GXV_TABLE_VALIDATE( trak ); GXV_TABLE_VALIDATE( just ); GXV_TABLE_VALIDATE( mort ); GXV_TABLE_VALIDATE( morx ); GXV_TABLE_VALIDATE( kern ); GXV_TABLE_VALIDATE( opbd ); GXV_TABLE_VALIDATE( prop ); GXV_TABLE_VALIDATE( lcar ); /* Set results */ GXV_TABLE_SET( feat ); GXV_TABLE_SET( mort ); GXV_TABLE_SET( morx ); GXV_TABLE_SET( bsln ); GXV_TABLE_SET( just ); GXV_TABLE_SET( kern ); GXV_TABLE_SET( opbd ); GXV_TABLE_SET( trak ); GXV_TABLE_SET( prop ); GXV_TABLE_SET( lcar ); Exit: if ( error ) { FT_FREE( feat ); FT_FREE( bsln ); FT_FREE( trak ); FT_FREE( just ); FT_FREE( mort ); FT_FREE( morx ); FT_FREE( kern ); FT_FREE( opbd ); FT_FREE( prop ); FT_FREE( lcar ); } return error; } static FT_Error classic_kern_validate( FT_Face face, FT_UInt ckern_flags, FT_Bytes* ckern_table ) { FT_Memory volatile memory = FT_FACE_MEMORY( face ); FT_Byte* volatile ckern = NULL; FT_ULong len_ckern = 0; /* without volatile on `error' GCC 4.1.1. emits: */ /* warning: variable 'error' might be clobbered by 'longjmp' or 'vfork' */ /* this warning seems spurious but --- */ FT_Error volatile error; FT_ValidatorRec volatile valid; *ckern_table = NULL; error = gxv_load_table( face, TTAG_kern, &ckern, &len_ckern ); if ( error ) goto Exit; if ( ckern ) { ft_validator_init( &valid, ckern, ckern + len_ckern, FT_VALIDATE_DEFAULT ); if ( ft_setjmp( valid.jump_buffer ) == 0 ) gxv_kern_validate_classic( ckern, face, ckern_flags & FT_VALIDATE_CKERN, &valid ); error = valid.error; if ( error ) goto Exit; } *ckern_table = ckern; Exit: if ( error ) FT_FREE( ckern ); return error; } static const FT_Service_GXvalidateRec gxvalid_interface = { gxv_validate }; static const FT_Service_CKERNvalidateRec ckernvalid_interface = { classic_kern_validate }; static const FT_ServiceDescRec gxvalid_services[] = { { FT_SERVICE_ID_GX_VALIDATE, &gxvalid_interface }, { FT_SERVICE_ID_CLASSICKERN_VALIDATE, &ckernvalid_interface }, { NULL, NULL } }; static FT_Pointer gxvalid_get_service( FT_Module module, const char* service_id ) { FT_UNUSED( module ); return ft_service_list_lookup( gxvalid_services, service_id ); } FT_CALLBACK_TABLE_DEF const FT_Module_Class gxv_module_class = { 0, sizeof ( FT_ModuleRec ), "gxvalid", 0x10000L, 0x20000L, 0, /* module-specific interface */ (FT_Module_Constructor)0, (FT_Module_Destructor) 0, (FT_Module_Requester) gxvalid_get_service }; /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmod.c
C
apache-2.0
9,052
/***************************************************************************/ /* */ /* gxvmod.h */ /* */ /* FreeType's TrueTypeGX/AAT validation module implementation */ /* (specification). */ /* */ /* Copyright 2004, 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __GXVMOD_H__ #define __GXVMOD_H__ #include <ft2build.h> #include FT_MODULE_H FT_BEGIN_HEADER #ifdef FT_CONFIG_OPTION_PIC #error "this module does not support PIC yet" #endif FT_EXPORT_VAR( const FT_Module_Class ) gxv_module_class; FT_END_HEADER #endif /* __GXVMOD_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmod.h
C
apache-2.0
2,178
/***************************************************************************/ /* */ /* gxvmort.c */ /* */ /* TrueTypeGX/AAT mort table validation (body). */ /* */ /* Copyright 2005, 2013 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" #include "gxvfeat.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort static void gxv_mort_feature_validate( GXV_mort_feature f, GXV_Validator valid ) { if ( f->featureType >= gxv_feat_registry_length ) { GXV_TRACE(( "featureType %d is out of registered range, " "setting %d is unchecked\n", f->featureType, f->featureSetting )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } else if ( !gxv_feat_registry[f->featureType].existence ) { GXV_TRACE(( "featureType %d is within registered area " "but undefined, setting %d is unchecked\n", f->featureType, f->featureSetting )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } else { FT_Byte nSettings_max; /* nSettings in gxvfeat.c is halved for exclusive on/off settings */ nSettings_max = gxv_feat_registry[f->featureType].nSettings; if ( gxv_feat_registry[f->featureType].exclusive ) nSettings_max = (FT_Byte)( 2 * nSettings_max ); GXV_TRACE(( "featureType %d is registered", f->featureType )); GXV_TRACE(( "setting %d", f->featureSetting )); if ( f->featureSetting > nSettings_max ) { GXV_TRACE(( "out of defined range %d", nSettings_max )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } GXV_TRACE(( "\n" )); } /* TODO: enableFlags must be unique value in specified chain? */ } /* * nFeatureFlags is typed to FT_ULong to accept that in * mort (typed FT_UShort) and morx (typed FT_ULong). */ FT_LOCAL_DEF( void ) gxv_mort_featurearray_validate( FT_Bytes table, FT_Bytes limit, FT_ULong nFeatureFlags, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong i; GXV_mort_featureRec f = GXV_MORT_FEATURE_OFF; GXV_NAME_ENTER( "mort feature list" ); for ( i = 0; i < nFeatureFlags; i++ ) { GXV_LIMIT_CHECK( 2 + 2 + 4 + 4 ); f.featureType = FT_NEXT_USHORT( p ); f.featureSetting = FT_NEXT_USHORT( p ); f.enableFlags = FT_NEXT_ULONG( p ); f.disableFlags = FT_NEXT_ULONG( p ); gxv_mort_feature_validate( &f, valid ); } if ( !IS_GXV_MORT_FEATURE_OFF( f ) ) FT_INVALID_DATA; valid->subtable_length = p - table; GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_mort_coverage_validate( FT_UShort coverage, GXV_Validator valid ) { FT_UNUSED( valid ); #ifdef FT_DEBUG_LEVEL_TRACE if ( coverage & 0x8000U ) GXV_TRACE(( " this subtable is for vertical text only\n" )); else GXV_TRACE(( " this subtable is for horizontal text only\n" )); if ( coverage & 0x4000 ) GXV_TRACE(( " this subtable is applied to glyph array " "in descending order\n" )); else GXV_TRACE(( " this subtable is applied to glyph array " "in ascending order\n" )); if ( coverage & 0x2000 ) GXV_TRACE(( " this subtable is forcibly applied to " "vertical/horizontal text\n" )); if ( coverage & 0x1FF8 ) GXV_TRACE(( " coverage has non-zero bits in reserved area\n" )); #endif } static void gxv_mort_subtables_validate( FT_Bytes table, FT_Bytes limit, FT_UShort nSubtables, GXV_Validator valid ) { FT_Bytes p = table; GXV_Validate_Func fmt_funcs_table[] = { gxv_mort_subtable_type0_validate, /* 0 */ gxv_mort_subtable_type1_validate, /* 1 */ gxv_mort_subtable_type2_validate, /* 2 */ NULL, /* 3 */ gxv_mort_subtable_type4_validate, /* 4 */ gxv_mort_subtable_type5_validate, /* 5 */ }; FT_UShort i; GXV_NAME_ENTER( "subtables in a chain" ); for ( i = 0; i < nSubtables; i++ ) { GXV_Validate_Func func; FT_UShort length; FT_UShort coverage; #ifdef GXV_LOAD_UNUSED_VARS FT_ULong subFeatureFlags; #endif FT_UInt type; FT_UInt rest; GXV_LIMIT_CHECK( 2 + 2 + 4 ); length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); #ifdef GXV_LOAD_UNUSED_VARS subFeatureFlags = FT_NEXT_ULONG( p ); #else p += 4; #endif GXV_TRACE(( "validating chain subtable %d/%d (%d bytes)\n", i + 1, nSubtables, length )); type = coverage & 0x0007; rest = length - ( 2 + 2 + 4 ); GXV_LIMIT_CHECK( rest ); gxv_mort_coverage_validate( coverage, valid ); if ( type > 5 ) FT_INVALID_FORMAT; func = fmt_funcs_table[type]; if ( func == NULL ) GXV_TRACE(( "morx type %d is reserved\n", type )); func( p, p + rest, valid ); p += rest; /* TODO: validate subFeatureFlags */ } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_mort_chain_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; #ifdef GXV_LOAD_UNUSED_VARS FT_ULong defaultFlags; #endif FT_ULong chainLength; FT_UShort nFeatureFlags; FT_UShort nSubtables; GXV_NAME_ENTER( "mort chain header" ); GXV_LIMIT_CHECK( 4 + 4 + 2 + 2 ); #ifdef GXV_LOAD_UNUSED_VARS defaultFlags = FT_NEXT_ULONG( p ); #else p += 4; #endif chainLength = FT_NEXT_ULONG( p ); nFeatureFlags = FT_NEXT_USHORT( p ); nSubtables = FT_NEXT_USHORT( p ); gxv_mort_featurearray_validate( p, table + chainLength, nFeatureFlags, valid ); p += valid->subtable_length; gxv_mort_subtables_validate( p, table + chainLength, nSubtables, valid ); valid->subtable_length = chainLength; /* TODO: validate defaultFlags */ GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_mort_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_ULong version; FT_ULong nChains; FT_ULong i; valid->root = ftvalid; valid->face = face; limit = valid->root->limit; FT_TRACE3(( "validating `mort' table\n" )); GXV_INIT; GXV_LIMIT_CHECK( 4 + 4 ); version = FT_NEXT_ULONG( p ); nChains = FT_NEXT_ULONG( p ); if (version != 0x00010000UL) FT_INVALID_FORMAT; for ( i = 0; i < nChains; i++ ) { GXV_TRACE(( "validating chain %d/%d\n", i + 1, nChains )); GXV_32BIT_ALIGNMENT_VALIDATE( p - table ); gxv_mort_chain_validate( p, limit, valid ); p += valid->subtable_length; } FT_TRACE4(( "\n" )); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort.c
C
apache-2.0
9,347
/***************************************************************************/ /* */ /* gxvmort.h */ /* */ /* TrueTypeGX/AAT common definition for mort table (specification). */ /* */ /* Copyright 2004, 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __GXVMORT_H__ #define __GXVMORT_H__ #include "gxvalid.h" #include "gxvcommn.h" #include FT_SFNT_NAMES_H typedef struct GXV_mort_featureRec_ { FT_UShort featureType; FT_UShort featureSetting; FT_ULong enableFlags; FT_ULong disableFlags; } GXV_mort_featureRec, *GXV_mort_feature; #define GXV_MORT_FEATURE_OFF {0, 1, 0x00000000UL, 0x00000000UL} #define IS_GXV_MORT_FEATURE_OFF( f ) \ ( (f).featureType == 0 || \ (f).featureSetting == 1 || \ (f).enableFlags == 0x00000000UL || \ (f).disableFlags == 0x00000000UL ) FT_LOCAL( void ) gxv_mort_featurearray_validate( FT_Bytes table, FT_Bytes limit, FT_ULong nFeatureFlags, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_coverage_validate( FT_UShort coverage, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_subtable_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_subtable_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_subtable_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_subtable_type4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_mort_subtable_type5_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); #endif /* __GXVMORT_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort.h
C
apache-2.0
3,846
/***************************************************************************/ /* */ /* gxvmort0.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type0 (Indic Script Rearrangement) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort static const char* GXV_Mort_IndicScript_Msg[] = { "no change", "Ax => xA", "xD => Dx", "AxD => DxA", "ABx => xAB", "ABx => xBA", "xCD => CDx", "xCD => DCx", "AxCD => CDxA", "AxCD => DCxA", "ABxD => DxAB", "ABxD => DxBA", "ABxCD => CDxAB", "ABxCD => CDxBA", "ABxCD => DCxAB", "ABxCD => DCxBA", }; static void gxv_mort_subtable_type0_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_UShort markFirst; FT_UShort dontAdvance; FT_UShort markLast; FT_UShort reserved; FT_UShort verb = 0; FT_UNUSED( state ); FT_UNUSED( table ); FT_UNUSED( limit ); FT_UNUSED( GXV_Mort_IndicScript_Msg[verb] ); /* for the non-debugging */ FT_UNUSED( glyphOffset_p ); /* case */ markFirst = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); markLast = (FT_UShort)( ( flags >> 13 ) & 1 ); reserved = (FT_UShort)( flags & 0x1FF0 ); verb = (FT_UShort)( flags & 0x000F ); GXV_TRACE(( " IndicScript MorphRule for glyphOffset 0x%04x", glyphOffset_p->u )); GXV_TRACE(( " markFirst=%01d", markFirst )); GXV_TRACE(( " dontAdvance=%01d", dontAdvance )); GXV_TRACE(( " markLast=%01d", markLast )); GXV_TRACE(( " %02d", verb )); GXV_TRACE(( " %s\n", GXV_Mort_IndicScript_Msg[verb] )); if ( markFirst > 0 && markLast > 0 ) { GXV_TRACE(( " [odd] a glyph is marked as the first and last" " in Indic rearrangement\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } if ( markFirst > 0 && dontAdvance > 0 ) { GXV_TRACE(( " [odd] the first glyph is marked as dontAdvance" " in Indic rearrangement\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } if ( 0 < reserved ) { GXV_TRACE(( " non-zero bits found in reserved range\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } else GXV_TRACE(( "\n" )); } FT_LOCAL_DEF( void ) gxv_mort_subtable_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "mort chain subtable type0 (Indic-Script Rearrangement)" ); GXV_LIMIT_CHECK( GXV_STATETABLE_HEADER_SIZE ); valid->statetable.optdata = NULL; valid->statetable.optdata_load_func = NULL; valid->statetable.subtable_setup_func = NULL; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_mort_subtable_type0_entry_validate; gxv_StateTable_validate( p, limit, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort0.c
C
apache-2.0
5,487
/***************************************************************************/ /* */ /* gxvmort1.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type1 (Contextual Substitution) subtable. */ /* */ /* Copyright 2005, 2007 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort typedef struct GXV_mort_subtable_type1_StateOptRec_ { FT_UShort substitutionTable; FT_UShort substitutionTable_length; } GXV_mort_subtable_type1_StateOptRec, *GXV_mort_subtable_type1_StateOptRecData; #define GXV_MORT_SUBTABLE_TYPE1_HEADER_SIZE \ ( GXV_STATETABLE_HEADER_SIZE + 2 ) static void gxv_mort_subtable_type1_substitutionTable_load( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_mort_subtable_type1_StateOptRecData optdata = (GXV_mort_subtable_type1_StateOptRecData)valid->statetable.optdata; GXV_LIMIT_CHECK( 2 ); optdata->substitutionTable = FT_NEXT_USHORT( p ); } static void gxv_mort_subtable_type1_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ) { FT_UShort o[4]; FT_UShort *l[4]; FT_UShort buff[5]; GXV_mort_subtable_type1_StateOptRecData optdata = (GXV_mort_subtable_type1_StateOptRecData)valid->statetable.optdata; o[0] = classTable; o[1] = stateArray; o[2] = entryTable; o[3] = optdata->substitutionTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; l[3] = &( optdata->substitutionTable_length ); gxv_set_length_by_ushort_offset( o, l, buff, 4, table_size, valid ); } static void gxv_mort_subtable_type1_offset_to_subst_validate( FT_Short wordOffset, const FT_String* tag, FT_Byte state, GXV_Validator valid ) { FT_UShort substTable; FT_UShort substTable_limit; FT_UNUSED( tag ); FT_UNUSED( state ); substTable = ((GXV_mort_subtable_type1_StateOptRec *) (valid->statetable.optdata))->substitutionTable; substTable_limit = (FT_UShort)( substTable + ((GXV_mort_subtable_type1_StateOptRec *) (valid->statetable.optdata))->substitutionTable_length ); valid->min_gid = (FT_UShort)( ( substTable - wordOffset * 2 ) / 2 ); valid->max_gid = (FT_UShort)( ( substTable_limit - wordOffset * 2 ) / 2 ); valid->max_gid = (FT_UShort)( FT_MAX( valid->max_gid, valid->face->num_glyphs ) ); /* XXX: check range? */ /* TODO: min_gid & max_gid comparison with ClassTable contents */ } static void gxv_mort_subtable_type1_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_UShort setMark; FT_UShort dontAdvance; #endif FT_UShort reserved; FT_Short markOffset; FT_Short currentOffset; FT_UNUSED( table ); FT_UNUSED( limit ); #ifdef GXV_LOAD_UNUSED_VARS setMark = (FT_UShort)( flags >> 15 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); #endif reserved = (FT_Short)( flags & 0x3FFF ); markOffset = (FT_Short)( glyphOffset_p->ul >> 16 ); currentOffset = (FT_Short)( glyphOffset_p->ul ); if ( 0 < reserved ) { GXV_TRACE(( " non-zero bits found in reserved range\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } gxv_mort_subtable_type1_offset_to_subst_validate( markOffset, "markOffset", state, valid ); gxv_mort_subtable_type1_offset_to_subst_validate( currentOffset, "currentOffset", state, valid ); } static void gxv_mort_subtable_type1_substTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort num_gids = (FT_UShort)( ((GXV_mort_subtable_type1_StateOptRec *) (valid->statetable.optdata))->substitutionTable_length / 2 ); FT_UShort i; GXV_NAME_ENTER( "validating contents of substitutionTable" ); for ( i = 0; i < num_gids ; i ++ ) { FT_UShort dst_gid; GXV_LIMIT_CHECK( 2 ); dst_gid = FT_NEXT_USHORT( p ); if ( dst_gid >= 0xFFFFU ) continue; if ( dst_gid < valid->min_gid || valid->max_gid < dst_gid ) { GXV_TRACE(( "substTable include a strange gid[%d]=%d >" " out of define range (%d..%d)\n", i, dst_gid, valid->min_gid, valid->max_gid )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } } GXV_EXIT; } /* * subtable for Contextual glyph substitution is a modified StateTable. * In addition to classTable, stateArray, and entryTable, the field * `substitutionTable' is added. */ FT_LOCAL_DEF( void ) gxv_mort_subtable_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_mort_subtable_type1_StateOptRec st_rec; GXV_NAME_ENTER( "mort chain subtable type1 (Contextual Glyph Subst)" ); GXV_LIMIT_CHECK( GXV_MORT_SUBTABLE_TYPE1_HEADER_SIZE ); valid->statetable.optdata = &st_rec; valid->statetable.optdata_load_func = gxv_mort_subtable_type1_substitutionTable_load; valid->statetable.subtable_setup_func = gxv_mort_subtable_type1_subtable_setup; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_ULONG; valid->statetable.entry_validate_func = gxv_mort_subtable_type1_entry_validate; gxv_StateTable_validate( p, limit, valid ); gxv_mort_subtable_type1_substTable_validate( table + st_rec.substitutionTable, table + st_rec.substitutionTable + st_rec.substitutionTable_length, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort1.c
C
apache-2.0
9,239
/***************************************************************************/ /* */ /* gxvmort2.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type2 (Ligature Substitution) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort typedef struct GXV_mort_subtable_type2_StateOptRec_ { FT_UShort ligActionTable; FT_UShort componentTable; FT_UShort ligatureTable; FT_UShort ligActionTable_length; FT_UShort componentTable_length; FT_UShort ligatureTable_length; } GXV_mort_subtable_type2_StateOptRec, *GXV_mort_subtable_type2_StateOptRecData; #define GXV_MORT_SUBTABLE_TYPE2_HEADER_SIZE \ ( GXV_STATETABLE_HEADER_SIZE + 2 + 2 + 2 ) static void gxv_mort_subtable_type2_opttable_load( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_mort_subtable_type2_StateOptRecData optdata = (GXV_mort_subtable_type2_StateOptRecData)valid->statetable.optdata; GXV_LIMIT_CHECK( 2 + 2 + 2 ); optdata->ligActionTable = FT_NEXT_USHORT( p ); optdata->componentTable = FT_NEXT_USHORT( p ); optdata->ligatureTable = FT_NEXT_USHORT( p ); GXV_TRACE(( "offset to ligActionTable=0x%04x\n", optdata->ligActionTable )); GXV_TRACE(( "offset to componentTable=0x%04x\n", optdata->componentTable )); GXV_TRACE(( "offset to ligatureTable=0x%04x\n", optdata->ligatureTable )); } static void gxv_mort_subtable_type2_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort *classTable_length_p, FT_UShort *stateArray_length_p, FT_UShort *entryTable_length_p, GXV_Validator valid ) { FT_UShort o[6]; FT_UShort *l[6]; FT_UShort buff[7]; GXV_mort_subtable_type2_StateOptRecData optdata = (GXV_mort_subtable_type2_StateOptRecData)valid->statetable.optdata; GXV_NAME_ENTER( "subtable boundaries setup" ); o[0] = classTable; o[1] = stateArray; o[2] = entryTable; o[3] = optdata->ligActionTable; o[4] = optdata->componentTable; o[5] = optdata->ligatureTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; l[3] = &(optdata->ligActionTable_length); l[4] = &(optdata->componentTable_length); l[5] = &(optdata->ligatureTable_length); gxv_set_length_by_ushort_offset( o, l, buff, 6, table_size, valid ); GXV_TRACE(( "classTable: offset=0x%04x length=0x%04x\n", classTable, *classTable_length_p )); GXV_TRACE(( "stateArray: offset=0x%04x length=0x%04x\n", stateArray, *stateArray_length_p )); GXV_TRACE(( "entryTable: offset=0x%04x length=0x%04x\n", entryTable, *entryTable_length_p )); GXV_TRACE(( "ligActionTable: offset=0x%04x length=0x%04x\n", optdata->ligActionTable, optdata->ligActionTable_length )); GXV_TRACE(( "componentTable: offset=0x%04x length=0x%04x\n", optdata->componentTable, optdata->componentTable_length )); GXV_TRACE(( "ligatureTable: offset=0x%04x length=0x%04x\n", optdata->ligatureTable, optdata->ligatureTable_length )); GXV_EXIT; } static void gxv_mort_subtable_type2_ligActionOffset_validate( FT_Bytes table, FT_UShort ligActionOffset, GXV_Validator valid ) { /* access ligActionTable */ GXV_mort_subtable_type2_StateOptRecData optdata = (GXV_mort_subtable_type2_StateOptRecData)valid->statetable.optdata; FT_Bytes lat_base = table + optdata->ligActionTable; FT_Bytes p = table + ligActionOffset; FT_Bytes lat_limit = lat_base + optdata->ligActionTable; GXV_32BIT_ALIGNMENT_VALIDATE( ligActionOffset ); if ( p < lat_base ) { GXV_TRACE(( "too short offset 0x%04x: p < lat_base (%d byte rewind)\n", ligActionOffset, lat_base - p )); /* FontValidator, ftxvalidator, ftxdumperfuser warn but continue */ GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } else if ( lat_limit < p ) { GXV_TRACE(( "too large offset 0x%04x: lat_limit < p (%d byte overrun)\n", ligActionOffset, p - lat_limit )); /* FontValidator, ftxvalidator, ftxdumperfuser warn but continue */ GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } else { /* validate entry in ligActionTable */ FT_ULong lig_action; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort last; FT_UShort store; #endif FT_ULong offset; lig_action = FT_NEXT_ULONG( p ); #ifdef GXV_LOAD_UNUSED_VARS last = (FT_UShort)( ( lig_action >> 31 ) & 1 ); store = (FT_UShort)( ( lig_action >> 30 ) & 1 ); #endif /* Apple spec defines this offset as a word offset */ offset = lig_action & 0x3FFFFFFFUL; if ( offset * 2 < optdata->ligatureTable ) { GXV_TRACE(( "too short offset 0x%08x:" " 2 x offset < ligatureTable (%d byte rewind)\n", offset, optdata->ligatureTable - offset * 2 )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } else if ( offset * 2 > optdata->ligatureTable + optdata->ligatureTable_length ) { GXV_TRACE(( "too long offset 0x%08x:" " 2 x offset > ligatureTable + ligatureTable_length" " (%d byte overrun)\n", offset, optdata->ligatureTable + optdata->ligatureTable_length - offset * 2 )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET ); } } } static void gxv_mort_subtable_type2_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_UShort setComponent; FT_UShort dontAdvance; #endif FT_UShort offset; FT_UNUSED( state ); FT_UNUSED( glyphOffset_p ); FT_UNUSED( limit ); #ifdef GXV_LOAD_UNUSED_VARS setComponent = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); #endif offset = (FT_UShort)( flags & 0x3FFFU ); if ( 0 < offset ) gxv_mort_subtable_type2_ligActionOffset_validate( table, offset, valid ); } static void gxv_mort_subtable_type2_ligatureTable_validate( FT_Bytes table, GXV_Validator valid ) { GXV_mort_subtable_type2_StateOptRecData optdata = (GXV_mort_subtable_type2_StateOptRecData)valid->statetable.optdata; FT_Bytes p = table + optdata->ligatureTable; FT_Bytes limit = table + optdata->ligatureTable + optdata->ligatureTable_length; GXV_NAME_ENTER( "mort chain subtable type2 - substitutionTable" ); if ( 0 != optdata->ligatureTable ) { /* Apple does not give specification of ligatureTable format */ while ( p < limit ) { FT_UShort lig_gid; GXV_LIMIT_CHECK( 2 ); lig_gid = FT_NEXT_USHORT( p ); if ( valid->face->num_glyphs < lig_gid ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } } GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_mort_subtable_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_mort_subtable_type2_StateOptRec lig_rec; GXV_NAME_ENTER( "mort chain subtable type2 (Ligature Substitution)" ); GXV_LIMIT_CHECK( GXV_MORT_SUBTABLE_TYPE2_HEADER_SIZE ); valid->statetable.optdata = &lig_rec; valid->statetable.optdata_load_func = gxv_mort_subtable_type2_opttable_load; valid->statetable.subtable_setup_func = gxv_mort_subtable_type2_subtable_setup; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_mort_subtable_type2_entry_validate; gxv_StateTable_validate( p, limit, valid ); p += valid->subtable_length; gxv_mort_subtable_type2_ligatureTable_validate( table, valid ); valid->subtable_length = p - table; GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort2.c
C
apache-2.0
11,137
/***************************************************************************/ /* */ /* gxvmort4.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type4 (Non-Contextual Glyph Substitution) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort static void gxv_mort_subtable_type4_lookupval_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); gxv_glyphid_validate( value_p->u, valid ); } /* +===============+ --------+ | lookup header | | +===============+ | | BinSrchHeader | | +===============+ | | lastGlyph[0] | | +---------------+ | | firstGlyph[0] | | head of lookup table +---------------+ | + | offset[0] | -> | offset [byte] +===============+ | + | lastGlyph[1] | | (glyphID - firstGlyph) * 2 [byte] +---------------+ | | firstGlyph[1] | | +---------------+ | | offset[1] | | +===============+ | | .... | | 16bit value array | +===============+ | | value | <-------+ .... */ static GXV_LookupValueDesc gxv_mort_subtable_type4_lookupfmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ) { FT_Bytes p; FT_Bytes limit; FT_UShort offset; GXV_LookupValueDesc value; /* XXX: check range? */ offset = (FT_UShort)( base_value_p->u + relative_gindex * sizeof ( FT_UShort ) ); p = valid->lookuptbl_head + offset; limit = lookuptbl_limit; GXV_LIMIT_CHECK( 2 ); value.u = FT_NEXT_USHORT( p ); return value; } FT_LOCAL_DEF( void ) gxv_mort_subtable_type4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "mort chain subtable type4 " "(Non-Contextual Glyph Substitution)" ); valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_mort_subtable_type4_lookupval_validate; valid->lookupfmt4_trans = gxv_mort_subtable_type4_lookupfmt4_transit; gxv_LookupTable_validate( p, limit, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort4.c
C
apache-2.0
4,909
/***************************************************************************/ /* */ /* gxvmort5.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type5 (Contextual Glyph Insertion) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort /* * mort subtable type5 (Contextual Glyph Insertion) * has the format of StateTable with insertion-glyph-list, * but without name. The offset is given by glyphOffset in * entryTable. There is no table location declaration * like xxxTable. */ typedef struct GXV_mort_subtable_type5_StateOptRec_ { FT_UShort classTable; FT_UShort stateArray; FT_UShort entryTable; #define GXV_MORT_SUBTABLE_TYPE5_HEADER_SIZE GXV_STATETABLE_HEADER_SIZE FT_UShort* classTable_length_p; FT_UShort* stateArray_length_p; FT_UShort* entryTable_length_p; } GXV_mort_subtable_type5_StateOptRec, *GXV_mort_subtable_type5_StateOptRecData; FT_LOCAL_DEF( void ) gxv_mort_subtable_type5_subtable_setup( FT_UShort table_size, FT_UShort classTable, FT_UShort stateArray, FT_UShort entryTable, FT_UShort* classTable_length_p, FT_UShort* stateArray_length_p, FT_UShort* entryTable_length_p, GXV_Validator valid ) { GXV_mort_subtable_type5_StateOptRecData optdata = (GXV_mort_subtable_type5_StateOptRecData)valid->statetable.optdata; gxv_StateTable_subtable_setup( table_size, classTable, stateArray, entryTable, classTable_length_p, stateArray_length_p, entryTable_length_p, valid ); optdata->classTable = classTable; optdata->stateArray = stateArray; optdata->entryTable = entryTable; optdata->classTable_length_p = classTable_length_p; optdata->stateArray_length_p = stateArray_length_p; optdata->entryTable_length_p = entryTable_length_p; } static void gxv_mort_subtable_type5_InsertList_validate( FT_UShort offset, FT_UShort count, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { /* * We don't know the range of insertion-glyph-list. * Set range by whole of state table. */ FT_Bytes p = table + offset; GXV_mort_subtable_type5_StateOptRecData optdata = (GXV_mort_subtable_type5_StateOptRecData)valid->statetable.optdata; if ( optdata->classTable < offset && offset < optdata->classTable + *(optdata->classTable_length_p) ) GXV_TRACE(( " offset runs into ClassTable" )); if ( optdata->stateArray < offset && offset < optdata->stateArray + *(optdata->stateArray_length_p) ) GXV_TRACE(( " offset runs into StateArray" )); if ( optdata->entryTable < offset && offset < optdata->entryTable + *(optdata->entryTable_length_p) ) GXV_TRACE(( " offset runs into EntryTable" )); #ifndef GXV_LOAD_TRACE_VARS GXV_LIMIT_CHECK( count * 2 ); #else while ( p < table + offset + ( count * 2 ) ) { FT_UShort insert_glyphID; GXV_LIMIT_CHECK( 2 ); insert_glyphID = FT_NEXT_USHORT( p ); GXV_TRACE(( " 0x%04x", insert_glyphID )); } GXV_TRACE(( "\n" )); #endif } static void gxv_mort_subtable_type5_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_Bool setMark; FT_Bool dontAdvance; FT_Bool currentIsKashidaLike; FT_Bool markedIsKashidaLike; FT_Bool currentInsertBefore; FT_Bool markedInsertBefore; #endif FT_Byte currentInsertCount; FT_Byte markedInsertCount; FT_UShort currentInsertList; FT_UShort markedInsertList; FT_UNUSED( state ); #ifdef GXV_LOAD_UNUSED_VARS setMark = FT_BOOL( ( flags >> 15 ) & 1 ); dontAdvance = FT_BOOL( ( flags >> 14 ) & 1 ); currentIsKashidaLike = FT_BOOL( ( flags >> 13 ) & 1 ); markedIsKashidaLike = FT_BOOL( ( flags >> 12 ) & 1 ); currentInsertBefore = FT_BOOL( ( flags >> 11 ) & 1 ); markedInsertBefore = FT_BOOL( ( flags >> 10 ) & 1 ); #endif currentInsertCount = (FT_Byte)( ( flags >> 5 ) & 0x1F ); markedInsertCount = (FT_Byte)( flags & 0x001F ); currentInsertList = (FT_UShort)( glyphOffset->ul >> 16 ); markedInsertList = (FT_UShort)( glyphOffset->ul ); if ( 0 != currentInsertList && 0 != currentInsertCount ) { gxv_mort_subtable_type5_InsertList_validate( currentInsertList, currentInsertCount, table, limit, valid ); } if ( 0 != markedInsertList && 0 != markedInsertCount ) { gxv_mort_subtable_type5_InsertList_validate( markedInsertList, markedInsertCount, table, limit, valid ); } } FT_LOCAL_DEF( void ) gxv_mort_subtable_type5_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_mort_subtable_type5_StateOptRec et_rec; GXV_mort_subtable_type5_StateOptRecData et = &et_rec; GXV_NAME_ENTER( "mort chain subtable type5 (Glyph Insertion)" ); GXV_LIMIT_CHECK( GXV_MORT_SUBTABLE_TYPE5_HEADER_SIZE ); valid->statetable.optdata = et; valid->statetable.optdata_load_func = NULL; valid->statetable.subtable_setup_func = gxv_mort_subtable_type5_subtable_setup; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_ULONG; valid->statetable.entry_validate_func = gxv_mort_subtable_type5_entry_validate; gxv_StateTable_validate( p, limit, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmort5.c
C
apache-2.0
9,162
/***************************************************************************/ /* */ /* gxvmorx.c */ /* */ /* TrueTypeGX/AAT morx table validation (body). */ /* */ /* Copyright 2005, 2008, 2013 by */ /* suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmorx.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmorx static void gxv_morx_subtables_validate( FT_Bytes table, FT_Bytes limit, FT_UShort nSubtables, GXV_Validator valid ) { FT_Bytes p = table; GXV_Validate_Func fmt_funcs_table[] = { gxv_morx_subtable_type0_validate, /* 0 */ gxv_morx_subtable_type1_validate, /* 1 */ gxv_morx_subtable_type2_validate, /* 2 */ NULL, /* 3 */ gxv_morx_subtable_type4_validate, /* 4 */ gxv_morx_subtable_type5_validate, /* 5 */ }; FT_UShort i; GXV_NAME_ENTER( "subtables in a chain" ); for ( i = 0; i < nSubtables; i++ ) { GXV_Validate_Func func; FT_ULong length; FT_ULong coverage; #ifdef GXV_LOAD_UNUSED_VARS FT_ULong subFeatureFlags; #endif FT_ULong type; FT_ULong rest; GXV_LIMIT_CHECK( 4 + 4 + 4 ); length = FT_NEXT_ULONG( p ); coverage = FT_NEXT_ULONG( p ); #ifdef GXV_LOAD_UNUSED_VARS subFeatureFlags = FT_NEXT_ULONG( p ); #else p += 4; #endif GXV_TRACE(( "validating chain subtable %d/%d (%d bytes)\n", i + 1, nSubtables, length )); type = coverage & 0x0007; rest = length - ( 4 + 4 + 4 ); GXV_LIMIT_CHECK( rest ); /* morx coverage consists of mort_coverage & 16bit padding */ gxv_mort_coverage_validate( (FT_UShort)( ( coverage >> 16 ) | coverage ), valid ); if ( type > 5 ) FT_INVALID_FORMAT; func = fmt_funcs_table[type]; if ( func == NULL ) GXV_TRACE(( "morx type %d is reserved\n", type )); func( p, p + rest, valid ); /* TODO: subFeatureFlags should be unique in a table? */ p += rest; } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_morx_chain_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; #ifdef GXV_LOAD_UNUSED_VARS FT_ULong defaultFlags; #endif FT_ULong chainLength; FT_ULong nFeatureFlags; FT_ULong nSubtables; GXV_NAME_ENTER( "morx chain header" ); GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 ); #ifdef GXV_LOAD_UNUSED_VARS defaultFlags = FT_NEXT_ULONG( p ); #else p += 4; #endif chainLength = FT_NEXT_ULONG( p ); nFeatureFlags = FT_NEXT_ULONG( p ); nSubtables = FT_NEXT_ULONG( p ); /* feature-array of morx is same with that of mort */ gxv_mort_featurearray_validate( p, limit, nFeatureFlags, valid ); p += valid->subtable_length; if ( nSubtables >= 0x10000L ) FT_INVALID_DATA; gxv_morx_subtables_validate( p, table + chainLength, (FT_UShort)nSubtables, valid ); valid->subtable_length = chainLength; /* TODO: defaultFlags should be compared with the flags in tables */ GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_morx_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_ULong version; FT_ULong nChains; FT_ULong i; valid->root = ftvalid; valid->face = face; FT_TRACE3(( "validating `morx' table\n" )); GXV_INIT; GXV_LIMIT_CHECK( 4 + 4 ); version = FT_NEXT_ULONG( p ); nChains = FT_NEXT_ULONG( p ); if ( version != 0x00020000UL ) FT_INVALID_FORMAT; for ( i = 0; i < nChains; i++ ) { GXV_TRACE(( "validating chain %d/%d\n", i + 1, nChains )); GXV_32BIT_ALIGNMENT_VALIDATE( p - table ); gxv_morx_chain_validate( p, limit, valid ); p += valid->subtable_length; } FT_TRACE4(( "\n" )); } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmorx.c
C
apache-2.0
6,391
/***************************************************************************/ /* */ /* gxvmorx.h */ /* */ /* TrueTypeGX/AAT common definition for morx table (specification). */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __GXVMORX_H__ #define __GXVMORX_H__ #include "gxvalid.h" #include "gxvcommn.h" #include "gxvmort.h" #include FT_SFNT_NAMES_H FT_LOCAL( void ) gxv_morx_subtable_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_morx_subtable_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_morx_subtable_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_morx_subtable_type4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); FT_LOCAL( void ) gxv_morx_subtable_type5_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ); #endif /* __GXVMORX_H__ */ /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmorx.h
C
apache-2.0
2,955
/***************************************************************************/ /* */ /* gxvmorx0.c */ /* */ /* TrueTypeGX/AAT morx table validation */ /* body for type0 (Indic Script Rearrangement) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmorx.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmorx static void gxv_morx_subtable_type0_entry_validate( FT_UShort state, FT_UShort flags, GXV_XStateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS FT_UShort markFirst; FT_UShort dontAdvance; FT_UShort markLast; #endif FT_UShort reserved; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort verb; #endif FT_UNUSED( state ); FT_UNUSED( glyphOffset_p ); FT_UNUSED( table ); FT_UNUSED( limit ); #ifdef GXV_LOAD_UNUSED_VARS markFirst = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); markLast = (FT_UShort)( ( flags >> 13 ) & 1 ); #endif reserved = (FT_UShort)( flags & 0x1FF0 ); #ifdef GXV_LOAD_UNUSED_VARS verb = (FT_UShort)( flags & 0x000F ); #endif if ( 0 < reserved ) { GXV_TRACE(( " non-zero bits found in reserved range\n" )); FT_INVALID_DATA; } } FT_LOCAL_DEF( void ) gxv_morx_subtable_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "morx chain subtable type0 (Indic-Script Rearrangement)" ); GXV_LIMIT_CHECK( GXV_STATETABLE_HEADER_SIZE ); valid->xstatetable.optdata = NULL; valid->xstatetable.optdata_load_func = NULL; valid->xstatetable.subtable_setup_func = NULL; valid->xstatetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->xstatetable.entry_validate_func = gxv_morx_subtable_type0_entry_validate; gxv_XStateTable_validate( p, limit, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmorx0.c
C
apache-2.0
4,284
/***************************************************************************/ /* */ /* gxvmorx1.c */ /* */ /* TrueTypeGX/AAT morx table validation */ /* body for type1 (Contextual Substitution) subtable. */ /* */ /* Copyright 2005, 2007 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmorx.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmorx typedef struct GXV_morx_subtable_type1_StateOptRec_ { FT_ULong substitutionTable; FT_ULong substitutionTable_length; FT_UShort substitutionTable_num_lookupTables; } GXV_morx_subtable_type1_StateOptRec, *GXV_morx_subtable_type1_StateOptRecData; #define GXV_MORX_SUBTABLE_TYPE1_HEADER_SIZE \ ( GXV_STATETABLE_HEADER_SIZE + 2 ) static void gxv_morx_subtable_type1_substitutionTable_load( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_morx_subtable_type1_StateOptRecData optdata = (GXV_morx_subtable_type1_StateOptRecData)valid->xstatetable.optdata; GXV_LIMIT_CHECK( 2 ); optdata->substitutionTable = FT_NEXT_USHORT( p ); } static void gxv_morx_subtable_type1_subtable_setup( FT_ULong table_size, FT_ULong classTable, FT_ULong stateArray, FT_ULong entryTable, FT_ULong* classTable_length_p, FT_ULong* stateArray_length_p, FT_ULong* entryTable_length_p, GXV_Validator valid ) { FT_ULong o[4]; FT_ULong *l[4]; FT_ULong buff[5]; GXV_morx_subtable_type1_StateOptRecData optdata = (GXV_morx_subtable_type1_StateOptRecData)valid->xstatetable.optdata; o[0] = classTable; o[1] = stateArray; o[2] = entryTable; o[3] = optdata->substitutionTable; l[0] = classTable_length_p; l[1] = stateArray_length_p; l[2] = entryTable_length_p; l[3] = &(optdata->substitutionTable_length); gxv_set_length_by_ulong_offset( o, l, buff, 4, table_size, valid ); } static void gxv_morx_subtable_type1_entry_validate( FT_UShort state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_TRACE_VARS FT_UShort setMark; FT_UShort dontAdvance; #endif FT_UShort reserved; FT_Short markIndex; FT_Short currentIndex; GXV_morx_subtable_type1_StateOptRecData optdata = (GXV_morx_subtable_type1_StateOptRecData)valid->xstatetable.optdata; FT_UNUSED( state ); FT_UNUSED( table ); FT_UNUSED( limit ); #ifdef GXV_LOAD_TRACE_VARS setMark = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); #endif reserved = (FT_UShort)( flags & 0x3FFF ); markIndex = (FT_Short)( glyphOffset_p->ul >> 16 ); currentIndex = (FT_Short)( glyphOffset_p->ul ); GXV_TRACE(( " setMark=%01d dontAdvance=%01d\n", setMark, dontAdvance )); if ( 0 < reserved ) { GXV_TRACE(( " non-zero bits found in reserved range\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } GXV_TRACE(( "markIndex = %d, currentIndex = %d\n", markIndex, currentIndex )); if ( optdata->substitutionTable_num_lookupTables < markIndex + 1 ) optdata->substitutionTable_num_lookupTables = (FT_Short)( markIndex + 1 ); if ( optdata->substitutionTable_num_lookupTables < currentIndex + 1 ) optdata->substitutionTable_num_lookupTables = (FT_Short)( currentIndex + 1 ); } static void gxv_morx_subtable_type1_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); /* for the non-debugging case */ GXV_TRACE(( "morx subtable type1 subst.: %d -> %d\n", glyph, value_p->u )); if ( value_p->u > valid->face->num_glyphs ) FT_INVALID_GLYPH_ID; } static GXV_LookupValueDesc gxv_morx_subtable_type1_LookupFmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator valid ) { FT_Bytes p; FT_Bytes limit; FT_UShort offset; GXV_LookupValueDesc value; /* XXX: check range? */ offset = (FT_UShort)( base_value_p->u + relative_gindex * sizeof ( FT_UShort ) ); p = valid->lookuptbl_head + offset; limit = lookuptbl_limit; GXV_LIMIT_CHECK ( 2 ); value.u = FT_NEXT_USHORT( p ); return value; } /* * TODO: length should be limit? **/ static void gxv_morx_subtable_type1_substitutionTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort i; GXV_morx_subtable_type1_StateOptRecData optdata = (GXV_morx_subtable_type1_StateOptRecData)valid->xstatetable.optdata; /* TODO: calculate offset/length for each lookupTables */ valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_morx_subtable_type1_LookupValue_validate; valid->lookupfmt4_trans = gxv_morx_subtable_type1_LookupFmt4_transit; for ( i = 0; i < optdata->substitutionTable_num_lookupTables; i++ ) { FT_ULong offset; GXV_LIMIT_CHECK( 4 ); offset = FT_NEXT_ULONG( p ); gxv_LookupTable_validate( table + offset, limit, valid ); } /* TODO: overlapping of lookupTables in substitutionTable */ } /* * subtable for Contextual glyph substitution is a modified StateTable. * In addition to classTable, stateArray, entryTable, the field * `substitutionTable' is added. */ FT_LOCAL_DEF( void ) gxv_morx_subtable_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_morx_subtable_type1_StateOptRec st_rec; GXV_NAME_ENTER( "morx chain subtable type1 (Contextual Glyph Subst)" ); GXV_LIMIT_CHECK( GXV_MORX_SUBTABLE_TYPE1_HEADER_SIZE ); st_rec.substitutionTable_num_lookupTables = 0; valid->xstatetable.optdata = &st_rec; valid->xstatetable.optdata_load_func = gxv_morx_subtable_type1_substitutionTable_load; valid->xstatetable.subtable_setup_func = gxv_morx_subtable_type1_subtable_setup; valid->xstatetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_ULONG; valid->xstatetable.entry_validate_func = gxv_morx_subtable_type1_entry_validate; gxv_XStateTable_validate( p, limit, valid ); gxv_morx_subtable_type1_substitutionTable_validate( table + st_rec.substitutionTable, table + st_rec.substitutionTable + st_rec.substitutionTable_length, valid ); GXV_EXIT; } /* END */
YifuLiu/AliOS-Things
components/freetype/src/gxvalid/gxvmorx1.c
C
apache-2.0
9,589