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 |
|---|---|---|---|---|---|
/***************************************************************************/
/* */
/* gxvmorx2.c */
/* */
/* TrueTypeGX/AAT morx table validation */
/* body for type2 (Ligature Substitution) subtable. */
/* */
/* 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 "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_type2_StateOptRec_
{
FT_ULong ligActionTable;
FT_ULong componentTable;
FT_ULong ligatureTable;
FT_ULong ligActionTable_length;
FT_ULong componentTable_length;
FT_ULong ligatureTable_length;
} GXV_morx_subtable_type2_StateOptRec,
*GXV_morx_subtable_type2_StateOptRecData;
#define GXV_MORX_SUBTABLE_TYPE2_HEADER_SIZE \
( GXV_XSTATETABLE_HEADER_SIZE + 4 + 4 + 4 )
static void
gxv_morx_subtable_type2_opttable_load( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table;
GXV_morx_subtable_type2_StateOptRecData optdata =
(GXV_morx_subtable_type2_StateOptRecData)valid->xstatetable.optdata;
GXV_LIMIT_CHECK( 4 + 4 + 4 );
optdata->ligActionTable = FT_NEXT_ULONG( p );
optdata->componentTable = FT_NEXT_ULONG( p );
optdata->ligatureTable = FT_NEXT_ULONG( p );
GXV_TRACE(( "offset to ligActionTable=0x%08x\n",
optdata->ligActionTable ));
GXV_TRACE(( "offset to componentTable=0x%08x\n",
optdata->componentTable ));
GXV_TRACE(( "offset to ligatureTable=0x%08x\n",
optdata->ligatureTable ));
}
static void
gxv_morx_subtable_type2_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[6];
FT_ULong* l[6];
FT_ULong buff[7];
GXV_morx_subtable_type2_StateOptRecData optdata =
(GXV_morx_subtable_type2_StateOptRecData)valid->xstatetable.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_ulong_offset( o, l, buff, 6, table_size, valid );
GXV_TRACE(( "classTable: offset=0x%08x length=0x%08x\n",
classTable, *classTable_length_p ));
GXV_TRACE(( "stateArray: offset=0x%08x length=0x%08x\n",
stateArray, *stateArray_length_p ));
GXV_TRACE(( "entryTable: offset=0x%08x length=0x%08x\n",
entryTable, *entryTable_length_p ));
GXV_TRACE(( "ligActionTable: offset=0x%08x length=0x%08x\n",
optdata->ligActionTable,
optdata->ligActionTable_length ));
GXV_TRACE(( "componentTable: offset=0x%08x length=0x%08x\n",
optdata->componentTable,
optdata->componentTable_length ));
GXV_TRACE(( "ligatureTable: offset=0x%08x length=0x%08x\n",
optdata->ligatureTable,
optdata->ligatureTable_length ));
GXV_EXIT;
}
#define GXV_MORX_LIGACTION_ENTRY_SIZE 4
static void
gxv_morx_subtable_type2_ligActionIndex_validate(
FT_Bytes table,
FT_UShort ligActionIndex,
GXV_Validator valid )
{
/* access ligActionTable */
GXV_morx_subtable_type2_StateOptRecData optdata =
(GXV_morx_subtable_type2_StateOptRecData)valid->xstatetable.optdata;
FT_Bytes lat_base = table + optdata->ligActionTable;
FT_Bytes p = lat_base +
ligActionIndex * GXV_MORX_LIGACTION_ENTRY_SIZE;
FT_Bytes lat_limit = lat_base + optdata->ligActionTable;
if ( p < lat_base )
{
GXV_TRACE(( "p < lat_base (%d byte rewind)\n", lat_base - p ));
FT_INVALID_OFFSET;
}
else if ( lat_limit < p )
{
GXV_TRACE(( "lat_limit < p (%d byte overrun)\n", p - lat_limit ));
FT_INVALID_OFFSET;
}
{
/* validate entry in ligActionTable */
FT_ULong lig_action;
#ifdef GXV_LOAD_UNUSED_VARS
FT_UShort last;
FT_UShort store;
#endif
FT_ULong offset;
FT_Long gid_limit;
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
offset = lig_action & 0x3FFFFFFFUL;
/* this offset is 30-bit signed value to add to GID */
/* it is different from the location offset in mort */
if ( ( offset & 0x3FFF0000UL ) == 0x3FFF0000UL )
{ /* negative offset */
gid_limit = valid->face->num_glyphs - ( offset & 0x0000FFFFUL );
if ( gid_limit > 0 )
return;
GXV_TRACE(( "ligature action table includes"
" too negative offset moving all GID"
" below defined range: 0x%04x\n",
offset & 0xFFFFU ));
GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET );
}
else if ( ( offset & 0x3FFF0000UL ) == 0x0000000UL )
{ /* positive offset */
if ( (FT_Long)offset < valid->face->num_glyphs )
return;
GXV_TRACE(( "ligature action table includes"
" too large offset moving all GID"
" over defined range: 0x%04x\n",
offset & 0xFFFFU ));
GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET );
}
GXV_TRACE(( "ligature action table includes"
" invalid offset to add to 16-bit GID:"
" 0x%08x\n", offset ));
GXV_SET_ERR_IF_PARANOID( FT_INVALID_OFFSET );
}
}
static void
gxv_morx_subtable_type2_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_UNUSED_VARS
FT_UShort setComponent;
FT_UShort dontAdvance;
FT_UShort performAction;
#endif
FT_UShort reserved;
FT_UShort ligActionIndex;
FT_UNUSED( state );
FT_UNUSED( limit );
#ifdef GXV_LOAD_UNUSED_VARS
setComponent = (FT_UShort)( ( flags >> 15 ) & 1 );
dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 );
performAction = (FT_UShort)( ( flags >> 13 ) & 1 );
#endif
reserved = (FT_UShort)( flags & 0x1FFF );
ligActionIndex = glyphOffset_p->u;
if ( reserved > 0 )
GXV_TRACE(( " reserved 14bit is non-zero\n" ));
if ( 0 < ligActionIndex )
gxv_morx_subtable_type2_ligActionIndex_validate(
table, ligActionIndex, valid );
}
static void
gxv_morx_subtable_type2_ligatureTable_validate( FT_Bytes table,
GXV_Validator valid )
{
GXV_morx_subtable_type2_StateOptRecData optdata =
(GXV_morx_subtable_type2_StateOptRecData)valid->xstatetable.optdata;
FT_Bytes p = table + optdata->ligatureTable;
FT_Bytes limit = table + optdata->ligatureTable
+ optdata->ligatureTable_length;
GXV_NAME_ENTER( "morx 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 ( lig_gid < valid->face->num_glyphs )
GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID );
}
}
GXV_EXIT;
}
FT_LOCAL_DEF( void )
gxv_morx_subtable_type2_validate( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table;
GXV_morx_subtable_type2_StateOptRec lig_rec;
GXV_NAME_ENTER( "morx chain subtable type2 (Ligature Substitution)" );
GXV_LIMIT_CHECK( GXV_MORX_SUBTABLE_TYPE2_HEADER_SIZE );
valid->xstatetable.optdata =
&lig_rec;
valid->xstatetable.optdata_load_func =
gxv_morx_subtable_type2_opttable_load;
valid->xstatetable.subtable_setup_func =
gxv_morx_subtable_type2_subtable_setup;
valid->xstatetable.entry_glyphoffset_fmt =
GXV_GLYPHOFFSET_USHORT;
valid->xstatetable.entry_validate_func =
gxv_morx_subtable_type2_entry_validate;
gxv_XStateTable_validate( p, limit, valid );
#if 0
p += valid->subtable_length;
#endif
gxv_morx_subtable_type2_ligatureTable_validate( table, valid );
GXV_EXIT;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/gxvmorx2.c | C | apache-2.0 | 11,439 |
/***************************************************************************/
/* */
/* gxvmorx4.c */
/* */
/* TrueTypeGX/AAT morx table validation */
/* body for "morx" 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 "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
FT_LOCAL_DEF( void )
gxv_morx_subtable_type4_validate( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
GXV_NAME_ENTER( "morx chain subtable type4 "
"(Non-Contextual Glyph Substitution)" );
gxv_mort_subtable_type4_validate( table, limit, valid );
GXV_EXIT;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/gxvmorx4.c | C | apache-2.0 | 2,830 |
/***************************************************************************/
/* */
/* gxvmorx5.c */
/* */
/* TrueTypeGX/AAT morx table validation */
/* body for type5 (Contextual Glyph Insertion) 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
/*
* `morx' subtable type5 (Contextual Glyph Insertion)
* has format of a StateTable with insertion-glyph-list
* without name. However, the 32bit offset from the head
* of subtable to the i-g-l is given after `entryTable',
* without variable name specification (the existence of
* this offset to the table is different from mort type5).
*/
typedef struct GXV_morx_subtable_type5_StateOptRec_
{
FT_ULong insertionGlyphList;
FT_ULong insertionGlyphList_length;
} GXV_morx_subtable_type5_StateOptRec,
*GXV_morx_subtable_type5_StateOptRecData;
#define GXV_MORX_SUBTABLE_TYPE5_HEADER_SIZE \
( GXV_STATETABLE_HEADER_SIZE + 4 )
static void
gxv_morx_subtable_type5_insertionGlyphList_load( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table;
GXV_morx_subtable_type5_StateOptRecData optdata =
(GXV_morx_subtable_type5_StateOptRecData)valid->xstatetable.optdata;
GXV_LIMIT_CHECK( 4 );
optdata->insertionGlyphList = FT_NEXT_ULONG( p );
}
static void
gxv_morx_subtable_type5_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_type5_StateOptRecData optdata =
(GXV_morx_subtable_type5_StateOptRecData)valid->xstatetable.optdata;
o[0] = classTable;
o[1] = stateArray;
o[2] = entryTable;
o[3] = optdata->insertionGlyphList;
l[0] = classTable_length_p;
l[1] = stateArray_length_p;
l[2] = entryTable_length_p;
l[3] = &(optdata->insertionGlyphList_length);
gxv_set_length_by_ulong_offset( o, l, buff, 4, table_size, valid );
}
static void
gxv_morx_subtable_type5_InsertList_validate( FT_UShort table_index,
FT_UShort count,
FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table + table_index * 2;
#ifndef GXV_LOAD_TRACE_VARS
GXV_LIMIT_CHECK( count * 2 );
#else
while ( p < table + count * 2 + table_index * 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_morx_subtable_type5_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_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_Byte 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_Byte) ( glyphOffset_p->ul >> 16 );
markedInsertList = (FT_UShort)( glyphOffset_p->ul );
if ( currentInsertList && 0 != currentInsertCount )
gxv_morx_subtable_type5_InsertList_validate( currentInsertList,
currentInsertCount,
table, limit,
valid );
if ( markedInsertList && 0 != markedInsertCount )
gxv_morx_subtable_type5_InsertList_validate( markedInsertList,
markedInsertCount,
table, limit,
valid );
}
FT_LOCAL_DEF( void )
gxv_morx_subtable_type5_validate( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table;
GXV_morx_subtable_type5_StateOptRec et_rec;
GXV_morx_subtable_type5_StateOptRecData et = &et_rec;
GXV_NAME_ENTER( "morx chain subtable type5 (Glyph Insertion)" );
GXV_LIMIT_CHECK( GXV_MORX_SUBTABLE_TYPE5_HEADER_SIZE );
valid->xstatetable.optdata =
et;
valid->xstatetable.optdata_load_func =
gxv_morx_subtable_type5_insertionGlyphList_load;
valid->xstatetable.subtable_setup_func =
gxv_morx_subtable_type5_subtable_setup;
valid->xstatetable.entry_glyphoffset_fmt =
GXV_GLYPHOFFSET_ULONG;
valid->xstatetable.entry_validate_func =
gxv_morx_subtable_type5_entry_validate;
gxv_XStateTable_validate( p, limit, valid );
GXV_EXIT;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/gxvmorx5.c | C | apache-2.0 | 8,426 |
/***************************************************************************/
/* */
/* gxvopbd.c */
/* */
/* TrueTypeGX/AAT opbd 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_gxvopbd
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** Data and Types *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct GXV_opbd_DataRec_
{
FT_UShort format;
FT_UShort valueOffset_min;
} GXV_opbd_DataRec, *GXV_opbd_Data;
#define GXV_OPBD_DATA( FIELD ) GXV_TABLE_DATA( opbd, FIELD )
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
gxv_opbd_LookupValue_validate( FT_UShort glyph,
GXV_LookupValueCPtr value_p,
GXV_Validator valid )
{
/* offset in LookupTable is measured from the head of opbd table */
FT_Bytes p = valid->root->base + value_p->u;
FT_Bytes limit = valid->root->limit;
FT_Short delta_value;
int i;
if ( value_p->u < GXV_OPBD_DATA( valueOffset_min ) )
GXV_OPBD_DATA( valueOffset_min ) = value_p->u;
for ( i = 0; i < 4; i++ )
{
GXV_LIMIT_CHECK( 2 );
delta_value = FT_NEXT_SHORT( p );
if ( GXV_OPBD_DATA( format ) ) /* format 1, value is ctrl pt. */
{
if ( delta_value == -1 )
continue;
gxv_ctlPoint_validate( glyph, delta_value, valid );
}
else /* format 0, value is distance */
continue;
}
}
/*
opbd ---------------------+
|
+===============+ |
| lookup header | |
+===============+ |
| BinSrchHeader | |
+===============+ |
| lastGlyph[0] | |
+---------------+ |
| firstGlyph[0] | | head of opbd sfnt table
+---------------+ | +
| offset[0] | -> | offset [byte]
+===============+ | +
| lastGlyph[1] | | (glyphID - firstGlyph) * 4 * sizeof(FT_Short) [byte]
+---------------+ |
| firstGlyph[1] | |
+---------------+ |
| offset[1] | |
+===============+ |
|
.... |
|
48bit value array |
+===============+ |
| value | <-------+
| |
| |
| |
+---------------+
.... */
static GXV_LookupValueDesc
gxv_opbd_LookupFmt4_transit( FT_UShort relative_gindex,
GXV_LookupValueCPtr base_value_p,
FT_Bytes lookuptbl_limit,
GXV_Validator valid )
{
GXV_LookupValueDesc value;
FT_UNUSED( lookuptbl_limit );
FT_UNUSED( valid );
/* XXX: check range? */
value.u = (FT_UShort)( base_value_p->u +
relative_gindex * 4 * sizeof ( FT_Short ) );
return value;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** opbd TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
gxv_opbd_validate( FT_Bytes table,
FT_Face face,
FT_Validator ftvalid )
{
GXV_ValidatorRec validrec;
GXV_Validator valid = &validrec;
GXV_opbd_DataRec opbdrec;
GXV_opbd_Data opbd = &opbdrec;
FT_Bytes p = table;
FT_Bytes limit = 0;
FT_ULong version;
valid->root = ftvalid;
valid->table_data = opbd;
valid->face = face;
FT_TRACE3(( "validating `opbd' table\n" ));
GXV_INIT;
GXV_OPBD_DATA( valueOffset_min ) = 0xFFFFU;
GXV_LIMIT_CHECK( 4 + 2 );
version = FT_NEXT_ULONG( p );
GXV_OPBD_DATA( format ) = FT_NEXT_USHORT( p );
/* only 0x00010000 is defined (1996) */
GXV_TRACE(( "(version=0x%08x)\n", version ));
if ( 0x00010000UL != version )
FT_INVALID_FORMAT;
/* only values 0 and 1 are defined (1996) */
GXV_TRACE(( "(format=0x%04x)\n", GXV_OPBD_DATA( format ) ));
if ( 0x0001 < GXV_OPBD_DATA( format ) )
FT_INVALID_FORMAT;
valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED;
valid->lookupval_func = gxv_opbd_LookupValue_validate;
valid->lookupfmt4_trans = gxv_opbd_LookupFmt4_transit;
gxv_LookupTable_validate( p, limit, valid );
p += valid->subtable_length;
if ( p > table + GXV_OPBD_DATA( valueOffset_min ) )
{
GXV_TRACE((
"found overlap between LookupTable and opbd_value array\n" ));
FT_INVALID_OFFSET;
}
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/gxvopbd.c | C | apache-2.0 | 8,318 |
/***************************************************************************/
/* */
/* gxvprop.c */
/* */
/* TrueTypeGX/AAT prop 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_gxvprop
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** Data and Types *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define GXV_PROP_HEADER_SIZE ( 4 + 2 + 2 )
#define GXV_PROP_SIZE_MIN GXV_PROP_HEADER_SIZE
typedef struct GXV_prop_DataRec_
{
FT_Fixed version;
} GXV_prop_DataRec, *GXV_prop_Data;
#define GXV_PROP_DATA( field ) GXV_TABLE_DATA( prop, field )
#define GXV_PROP_FLOATER 0x8000U
#define GXV_PROP_USE_COMPLEMENTARY_BRACKET 0x1000U
#define GXV_PROP_COMPLEMENTARY_BRACKET_OFFSET 0x0F00U
#define GXV_PROP_ATTACHING_TO_RIGHT 0x0080U
#define GXV_PROP_RESERVED 0x0060U
#define GXV_PROP_DIRECTIONALITY_CLASS 0x001FU
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
gxv_prop_zero_advance_validate( FT_UShort gid,
GXV_Validator valid )
{
FT_Face face;
FT_Error error;
FT_GlyphSlot glyph;
GXV_NAME_ENTER( "zero advance" );
face = valid->face;
error = FT_Load_Glyph( face,
gid,
FT_LOAD_IGNORE_TRANSFORM );
if ( error )
FT_INVALID_GLYPH_ID;
glyph = face->glyph;
if ( glyph->advance.x != (FT_Pos)0 ||
glyph->advance.y != (FT_Pos)0 )
{
GXV_TRACE(( " found non-zero advance in zero-advance glyph\n" ));
FT_INVALID_DATA;
}
GXV_EXIT;
}
/* Pass 0 as GLYPH to check the default property */
static void
gxv_prop_property_validate( FT_UShort property,
FT_UShort glyph,
GXV_Validator valid )
{
if ( glyph != 0 && ( property & GXV_PROP_FLOATER ) )
gxv_prop_zero_advance_validate( glyph, valid );
if ( property & GXV_PROP_USE_COMPLEMENTARY_BRACKET )
{
FT_UShort offset;
char complement;
offset = (FT_UShort)( property & GXV_PROP_COMPLEMENTARY_BRACKET_OFFSET );
if ( offset == 0 )
{
GXV_TRACE(( " found zero offset to property\n" ));
FT_INVALID_OFFSET;
}
complement = (char)( offset >> 8 );
if ( complement & 0x08 )
{
/* Top bit is set: negative */
/* Calculate the absolute offset */
complement = (char)( ( complement & 0x07 ) + 1 );
/* The gid for complement must be greater than 0 */
if ( glyph <= complement )
{
GXV_TRACE(( " found non-positive glyph complement\n" ));
FT_INVALID_DATA;
}
}
else
{
/* The gid for complement must be the face. */
gxv_glyphid_validate( (FT_UShort)( glyph + complement ), valid );
}
}
else
{
if ( property & GXV_PROP_COMPLEMENTARY_BRACKET_OFFSET )
GXV_TRACE(( "glyph %d cannot have complementary bracketing\n",
glyph ));
}
/* this is introduced in version 2.0 */
if ( property & GXV_PROP_ATTACHING_TO_RIGHT )
{
if ( GXV_PROP_DATA( version ) == 0x00010000UL )
{
GXV_TRACE(( " found older version (1.0) in new version table\n" ));
FT_INVALID_DATA;
}
}
if ( property & GXV_PROP_RESERVED )
{
GXV_TRACE(( " found non-zero bits in reserved bits\n" ));
FT_INVALID_DATA;
}
if ( ( property & GXV_PROP_DIRECTIONALITY_CLASS ) > 11 )
{
/* TODO: Too restricted. Use the validation level. */
if ( GXV_PROP_DATA( version ) == 0x00010000UL ||
GXV_PROP_DATA( version ) == 0x00020000UL )
{
GXV_TRACE(( " found too old version in directionality class\n" ));
FT_INVALID_DATA;
}
}
}
static void
gxv_prop_LookupValue_validate( FT_UShort glyph,
GXV_LookupValueCPtr value_p,
GXV_Validator valid )
{
gxv_prop_property_validate( value_p->u, glyph, 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_prop_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;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** prop TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
gxv_prop_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_prop_DataRec proprec;
GXV_prop_Data prop = &proprec;
FT_Fixed version;
FT_UShort format;
FT_UShort defaultProp;
valid->root = ftvalid;
valid->table_data = prop;
valid->face = face;
FT_TRACE3(( "validating `prop' table\n" ));
GXV_INIT;
GXV_LIMIT_CHECK( 4 + 2 + 2 );
version = FT_NEXT_ULONG( p );
format = FT_NEXT_USHORT( p );
defaultProp = FT_NEXT_USHORT( p );
GXV_TRACE(( " version 0x%08x\n", version ));
GXV_TRACE(( " format 0x%04x\n", format ));
GXV_TRACE(( " defaultProp 0x%04x\n", defaultProp ));
/* only versions 1.0, 2.0, 3.0 are defined (1996) */
if ( version != 0x00010000UL &&
version != 0x00020000UL &&
version != 0x00030000UL )
{
GXV_TRACE(( " found unknown version\n" ));
FT_INVALID_FORMAT;
}
/* only formats 0x0000, 0x0001 are defined (1996) */
if ( format > 1 )
{
GXV_TRACE(( " found unknown format\n" ));
FT_INVALID_FORMAT;
}
gxv_prop_property_validate( defaultProp, 0, valid );
if ( format == 0 )
{
FT_TRACE3(( "(format 0, no per-glyph properties, "
"remaining %d bytes are skipped)", limit - p ));
goto Exit;
}
/* format == 1 */
GXV_PROP_DATA( version ) = version;
valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED;
valid->lookupval_func = gxv_prop_LookupValue_validate;
valid->lookupfmt4_trans = gxv_prop_LookupFmt4_transit;
gxv_LookupTable_validate( p, limit, valid );
Exit:
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/gxvprop.c | C | apache-2.0 | 11,315 |
/***************************************************************************/
/* */
/* gxvtrak.c */
/* */
/* TrueTypeGX/AAT trak 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_gxvtrak
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** Data and Types *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*
* referred track table format specification:
* http://developer.apple.com/fonts/TTRefMan/RM06/Chap6trak.html
* last update was 1996.
* ----------------------------------------------
* [MINIMUM HEADER]: GXV_TRAK_SIZE_MIN
* version (fixed: 32bit) = 0x00010000
* format (uint16: 16bit) = 0 is only defined (1996)
* horizOffset (uint16: 16bit)
* vertOffset (uint16: 16bit)
* reserved (uint16: 16bit) = 0
* ----------------------------------------------
* [VARIABLE BODY]:
* horizData
* header ( 2 + 2 + 4
* trackTable + nTracks * ( 4 + 2 + 2 )
* sizeTable + nSizes * 4 )
* ----------------------------------------------
* vertData
* header ( 2 + 2 + 4
* trackTable + nTracks * ( 4 + 2 + 2 )
* sizeTable + nSizes * 4 )
* ----------------------------------------------
*/
typedef struct GXV_trak_DataRec_
{
FT_UShort trackValueOffset_min;
FT_UShort trackValueOffset_max;
} GXV_trak_DataRec, *GXV_trak_Data;
#define GXV_TRAK_DATA( FIELD ) GXV_TABLE_DATA( trak, FIELD )
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
gxv_trak_trackTable_validate( FT_Bytes table,
FT_Bytes limit,
FT_UShort nTracks,
GXV_Validator valid )
{
FT_Bytes p = table;
FT_Fixed track, t;
FT_UShort nameIndex;
FT_UShort offset;
FT_UShort i, j;
GXV_NAME_ENTER( "trackTable" );
GXV_TRAK_DATA( trackValueOffset_min ) = 0xFFFFU;
GXV_TRAK_DATA( trackValueOffset_max ) = 0x0000;
GXV_LIMIT_CHECK( nTracks * ( 4 + 2 + 2 ) );
for ( i = 0; i < nTracks; i ++ )
{
p = table + i * ( 4 + 2 + 2 );
track = FT_NEXT_LONG( p );
nameIndex = FT_NEXT_USHORT( p );
offset = FT_NEXT_USHORT( p );
if ( offset < GXV_TRAK_DATA( trackValueOffset_min ) )
GXV_TRAK_DATA( trackValueOffset_min ) = offset;
if ( offset > GXV_TRAK_DATA( trackValueOffset_max ) )
GXV_TRAK_DATA( trackValueOffset_max ) = offset;
gxv_sfntName_validate( nameIndex, 256, 32767, valid );
for ( j = i; j < nTracks; j ++ )
{
p = table + j * ( 4 + 2 + 2 );
t = FT_NEXT_LONG( p );
if ( t == track )
GXV_TRACE(( "duplicated entries found for track value 0x%x\n",
track ));
}
}
valid->subtable_length = p - table;
GXV_EXIT;
}
static void
gxv_trak_trackData_validate( FT_Bytes table,
FT_Bytes limit,
GXV_Validator valid )
{
FT_Bytes p = table;
FT_UShort nTracks;
FT_UShort nSizes;
FT_ULong sizeTableOffset;
GXV_ODTECT( 4, odtect );
GXV_ODTECT_INIT( odtect );
GXV_NAME_ENTER( "trackData" );
/* read the header of trackData */
GXV_LIMIT_CHECK( 2 + 2 + 4 );
nTracks = FT_NEXT_USHORT( p );
nSizes = FT_NEXT_USHORT( p );
sizeTableOffset = FT_NEXT_ULONG( p );
gxv_odtect_add_range( table, p - table, "trackData header", odtect );
/* validate trackTable */
gxv_trak_trackTable_validate( p, limit, nTracks, valid );
gxv_odtect_add_range( p, valid->subtable_length,
"trackTable", odtect );
/* sizeTable is array of FT_Fixed, don't check contents */
p = valid->root->base + sizeTableOffset;
GXV_LIMIT_CHECK( nSizes * 4 );
gxv_odtect_add_range( p, nSizes * 4, "sizeTable", odtect );
/* validate trackValueOffet */
p = valid->root->base + GXV_TRAK_DATA( trackValueOffset_min );
if ( limit - p < nTracks * nSizes * 2 )
GXV_TRACE(( "too short trackValue array\n" ));
p = valid->root->base + GXV_TRAK_DATA( trackValueOffset_max );
GXV_LIMIT_CHECK( nSizes * 2 );
gxv_odtect_add_range( valid->root->base
+ GXV_TRAK_DATA( trackValueOffset_min ),
GXV_TRAK_DATA( trackValueOffset_max )
- GXV_TRAK_DATA( trackValueOffset_min )
+ nSizes * 2,
"trackValue array", odtect );
gxv_odtect_validate( odtect, valid );
GXV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** trak TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
gxv_trak_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_trak_DataRec trakrec;
GXV_trak_Data trak = &trakrec;
FT_ULong version;
FT_UShort format;
FT_UShort horizOffset;
FT_UShort vertOffset;
FT_UShort reserved;
GXV_ODTECT( 3, odtect );
GXV_ODTECT_INIT( odtect );
valid->root = ftvalid;
valid->table_data = trak;
valid->face = face;
limit = valid->root->limit;
FT_TRACE3(( "validating `trak' table\n" ));
GXV_INIT;
GXV_LIMIT_CHECK( 4 + 2 + 2 + 2 + 2 );
version = FT_NEXT_ULONG( p );
format = FT_NEXT_USHORT( p );
horizOffset = FT_NEXT_USHORT( p );
vertOffset = FT_NEXT_USHORT( p );
reserved = FT_NEXT_USHORT( p );
GXV_TRACE(( " (version = 0x%08x)\n", version ));
GXV_TRACE(( " (format = 0x%04x)\n", format ));
GXV_TRACE(( " (horizOffset = 0x%04x)\n", horizOffset ));
GXV_TRACE(( " (vertOffset = 0x%04x)\n", vertOffset ));
GXV_TRACE(( " (reserved = 0x%04x)\n", reserved ));
/* Version 1.0 (always:1996) */
if ( version != 0x00010000UL )
FT_INVALID_FORMAT;
/* format 0 (always:1996) */
if ( format != 0x0000 )
FT_INVALID_FORMAT;
GXV_32BIT_ALIGNMENT_VALIDATE( horizOffset );
GXV_32BIT_ALIGNMENT_VALIDATE( vertOffset );
/* Reserved Fixed Value (always) */
if ( reserved != 0x0000 )
FT_INVALID_DATA;
/* validate trackData */
if ( 0 < horizOffset )
{
gxv_trak_trackData_validate( table + horizOffset, limit, valid );
gxv_odtect_add_range( table + horizOffset, valid->subtable_length,
"horizJustData", odtect );
}
if ( 0 < vertOffset )
{
gxv_trak_trackData_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/gxvtrak.c | C | apache-2.0 | 10,589 |
#
# FreeType 2 gxvalid module definition
#
# Copyright 2004, 2005, 2006
# 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.
FTMODULE_H_COMMANDS += GXVALID_MODULE
define GXVALID_MODULE
$(OPEN_DRIVER) FT_Module_Class, gxv_module_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)gxvalid $(ECHO_DRIVER_DESC)TrueTypeGX/AAT validation module$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/module.mk | Makefile | apache-2.0 | 717 |
#
# FreeType 2 TrueTypeGX/AAT validation driver configuration rules
#
# 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.
# GXV driver directory
#
GXV_DIR := $(SRC_DIR)/gxvalid
# compilation flags for the driver
#
GXV_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(GXV_DIR))
# GXV driver sources (i.e., C files)
#
GXV_DRV_SRC := $(GXV_DIR)/gxvcommn.c \
$(GXV_DIR)/gxvfeat.c \
$(GXV_DIR)/gxvbsln.c \
$(GXV_DIR)/gxvtrak.c \
$(GXV_DIR)/gxvopbd.c \
$(GXV_DIR)/gxvprop.c \
$(GXV_DIR)/gxvjust.c \
$(GXV_DIR)/gxvmort.c \
$(GXV_DIR)/gxvmort0.c \
$(GXV_DIR)/gxvmort1.c \
$(GXV_DIR)/gxvmort2.c \
$(GXV_DIR)/gxvmort4.c \
$(GXV_DIR)/gxvmort5.c \
$(GXV_DIR)/gxvmorx.c \
$(GXV_DIR)/gxvmorx0.c \
$(GXV_DIR)/gxvmorx1.c \
$(GXV_DIR)/gxvmorx2.c \
$(GXV_DIR)/gxvmorx4.c \
$(GXV_DIR)/gxvmorx5.c \
$(GXV_DIR)/gxvlcar.c \
$(GXV_DIR)/gxvkern.c \
$(GXV_DIR)/gxvmod.c
# GXV driver headers
#
GXV_DRV_H := $(GXV_DIR)/gxvalid.h \
$(GXV_DIR)/gxverror.h \
$(GXV_DIR)/gxvcommn.h \
$(GXV_DIR)/gxvfeat.h \
$(GXV_DIR)/gxvmod.h \
$(GXV_DIR)/gxvmort.h \
$(GXV_DIR)/gxvmorx.h
# GXV driver object(s)
#
# GXV_DRV_OBJ_M is used during `multi' builds.
# GXV_DRV_OBJ_S is used during `single' builds.
#
GXV_DRV_OBJ_M := $(GXV_DRV_SRC:$(GXV_DIR)/%.c=$(OBJ_DIR)/%.$O)
GXV_DRV_OBJ_S := $(OBJ_DIR)/gxvalid.$O
# GXV driver source file for single build
#
GXV_DRV_SRC_S := $(GXV_DIR)/gxvalid.c
# GXV driver - single object
#
$(GXV_DRV_OBJ_S): $(GXV_DRV_SRC_S) $(GXV_DRV_SRC) \
$(FREETYPE_H) $(GXV_DRV_H)
$(GXV_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(GXV_DRV_SRC_S))
# GXV driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(GXV_DIR)/%.c $(FREETYPE_H) $(GXV_DRV_H)
$(GXV_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(GXV_DRV_OBJ_S)
DRV_OBJS_M += $(GXV_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/gxvalid/rules.mk | Makefile | apache-2.0 | 2,600 |
/* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "zlib.h"
#define BASE 65521L /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
/* ========================================================================= */
ZEXPORT(uLong) adler32( /* adler, buf, len) */
uLong adler,
const Bytef *buf,
uInt len )
{
unsigned long s1 = adler & 0xffff;
unsigned long s2 = (adler >> 16) & 0xffff;
int k;
if (buf == Z_NULL) return 1L;
while (len > 0) {
k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16) {
DO16(buf);
buf += 16;
k -= 16;
}
if (k != 0) do {
s1 += *buf++;
s2 += s1;
} while (--k);
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/adler32.c | C | apache-2.0 | 1,267 |
/***************************************************************************/
/* */
/* ftgzip.c */
/* */
/* FreeType support for .gz compressed files. */
/* */
/* This optional component relies on zlib. It should mainly be used to */
/* parse compressed PCF fonts, as found with many X11 server */
/* distributions. */
/* */
/* Copyright 2002-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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_MEMORY_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_DEBUG_H
#include FT_GZIP_H
#include FT_CONFIG_STANDARD_LIBRARY_H
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX Gzip_Err_
#define FT_ERR_BASE FT_Mod_Err_Gzip
#include FT_ERRORS_H
#ifdef FT_CONFIG_OPTION_USE_ZLIB
#ifdef FT_CONFIG_OPTION_PIC
#error "gzip code does not support PIC yet"
#endif
#ifdef FT_CONFIG_OPTION_SYSTEM_ZLIB
#include <zlib.h>
#else /* !FT_CONFIG_OPTION_SYSTEM_ZLIB */
/* In this case, we include our own modified sources of the ZLib */
/* within the "ftgzip" component. The modifications were necessary */
/* to #include all files without conflicts, as well as preventing */
/* the definition of "extern" functions that may cause linking */
/* conflicts when a program is linked with both FreeType and the */
/* original ZLib. */
#define NO_DUMMY_DECL
#ifndef USE_ZLIB_ZCALLOC
#define MY_ZCALLOC /* prevent all zcalloc() & zfree() in zutils.c */
#endif
#include "zlib.h"
#undef SLOW
#define SLOW 1 /* we can't use asm-optimized sources here! */
#if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */
/* We disable the warning `conversion from XXX to YYY, */
/* possible loss of data' in order to compile cleanly with */
/* the maximum level of warnings: zlib is non-FreeType */
/* code. */
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif /* _MSC_VER */
/* Urgh. `inflate_mask' must not be declared twice -- C++ doesn't like
this. We temporarily disable it and load all necessary header files. */
#define NO_INFLATE_MASK
#include "zutil.h"
#include "inftrees.h"
#include "infblock.h"
#include "infcodes.h"
#include "infutil.h"
#undef NO_INFLATE_MASK
/* infutil.c must be included before infcodes.c */
#include "zutil.c"
#include "inftrees.c"
#include "infutil.c"
#include "infcodes.c"
#include "infblock.c"
#include "inflate.c"
#include "adler32.c"
#if defined( _MSC_VER )
#pragma warning( pop )
#endif
#endif /* !FT_CONFIG_OPTION_SYSTEM_ZLIB */
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** Z L I B 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' */
static voidpf
ft_gzip_alloc( FT_Memory memory,
uInt items,
uInt 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_gzip_free( FT_Memory memory,
voidpf address )
{
FT_MEM_FREE( address );
}
#if !defined( FT_CONFIG_OPTION_SYSTEM_ZLIB ) && !defined( USE_ZLIB_ZCALLOC )
local voidpf
zcalloc ( voidpf opaque,
unsigned items,
unsigned size )
{
return ft_gzip_alloc( (FT_Memory)opaque, items, size );
}
local void
zcfree( voidpf opaque,
voidpf ptr )
{
ft_gzip_free( (FT_Memory)opaque, ptr );
}
#endif /* !SYSTEM_ZLIB && !USE_ZLIB_ZCALLOC */
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** Z L I B F I L E D E S C R I P T O R *****/
/***** *****/
/***************************************************************************/
/***************************************************************************/
#define FT_GZIP_BUFFER_SIZE 4096
typedef struct FT_GZipFileRec_
{
FT_Stream source; /* parent/source stream */
FT_Stream stream; /* embedding stream */
FT_Memory memory; /* memory allocator */
z_stream zstream; /* zlib input stream */
FT_ULong start; /* starting position, after .gz header */
FT_Byte input[FT_GZIP_BUFFER_SIZE]; /* input read buffer */
FT_Byte buffer[FT_GZIP_BUFFER_SIZE]; /* output buffer */
FT_ULong pos; /* position in output */
FT_Byte* cursor;
FT_Byte* limit;
} FT_GZipFileRec, *FT_GZipFile;
/* gzip flag byte */
#define FT_GZIP_ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
#define FT_GZIP_HEAD_CRC 0x02 /* bit 1 set: header CRC present */
#define FT_GZIP_EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
#define FT_GZIP_ORIG_NAME 0x08 /* bit 3 set: original file name present */
#define FT_GZIP_COMMENT 0x10 /* bit 4 set: file comment present */
#define FT_GZIP_RESERVED 0xE0 /* bits 5..7: reserved */
/* check and skip .gz header - we don't support `transparent' compression */
static FT_Error
ft_gzip_check_header( FT_Stream stream )
{
FT_Error error;
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 method, and head[3] the flags */
if ( head[0] != 0x1f ||
head[1] != 0x8b ||
head[2] != Z_DEFLATED ||
(head[3] & FT_GZIP_RESERVED) )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* skip time, xflags and os code */
(void)FT_STREAM_SKIP( 6 );
/* skip the extra field */
if ( head[3] & FT_GZIP_EXTRA_FIELD )
{
FT_UInt len;
if ( FT_READ_USHORT_LE( len ) ||
FT_STREAM_SKIP( len ) )
goto Exit;
}
/* skip original file name */
if ( head[3] & FT_GZIP_ORIG_NAME )
for (;;)
{
FT_UInt c;
if ( FT_READ_BYTE( c ) )
goto Exit;
if ( c == 0 )
break;
}
/* skip .gz comment */
if ( head[3] & FT_GZIP_COMMENT )
for (;;)
{
FT_UInt c;
if ( FT_READ_BYTE( c ) )
goto Exit;
if ( c == 0 )
break;
}
/* skip CRC */
if ( head[3] & FT_GZIP_HEAD_CRC )
if ( FT_STREAM_SKIP( 2 ) )
goto Exit;
Exit:
return error;
}
static FT_Error
ft_gzip_file_init( FT_GZipFile zip,
FT_Stream stream,
FT_Stream source )
{
z_stream* zstream = &zip->zstream;
FT_Error error = FT_Err_Ok;
zip->stream = stream;
zip->source = source;
zip->memory = stream->memory;
zip->limit = zip->buffer + FT_GZIP_BUFFER_SIZE;
zip->cursor = zip->limit;
zip->pos = 0;
/* check and skip .gz header */
{
stream = source;
error = ft_gzip_check_header( stream );
if ( error )
goto Exit;
zip->start = FT_STREAM_POS();
}
/* initialize zlib -- there is no zlib header in the compressed stream */
zstream->zalloc = (alloc_func)ft_gzip_alloc;
zstream->zfree = (free_func) ft_gzip_free;
zstream->opaque = stream->memory;
zstream->avail_in = 0;
zstream->next_in = zip->buffer;
if ( inflateInit2( zstream, -MAX_WBITS ) != Z_OK ||
zstream->next_in == NULL )
error = FT_THROW( Invalid_File_Format );
Exit:
return error;
}
static void
ft_gzip_file_done( FT_GZipFile zip )
{
z_stream* zstream = &zip->zstream;
inflateEnd( zstream );
/* clear the rest */
zstream->zalloc = NULL;
zstream->zfree = NULL;
zstream->opaque = NULL;
zstream->next_in = NULL;
zstream->next_out = NULL;
zstream->avail_in = 0;
zstream->avail_out = 0;
zip->memory = NULL;
zip->source = NULL;
zip->stream = NULL;
}
static FT_Error
ft_gzip_file_reset( FT_GZipFile zip )
{
FT_Stream stream = zip->source;
FT_Error error;
if ( !FT_STREAM_SEEK( zip->start ) )
{
z_stream* zstream = &zip->zstream;
inflateReset( zstream );
zstream->avail_in = 0;
zstream->next_in = zip->input;
zstream->avail_out = 0;
zstream->next_out = zip->buffer;
zip->limit = zip->buffer + FT_GZIP_BUFFER_SIZE;
zip->cursor = zip->limit;
zip->pos = 0;
}
return error;
}
static FT_Error
ft_gzip_file_fill_input( FT_GZipFile zip )
{
z_stream* zstream = &zip->zstream;
FT_Stream stream = zip->source;
FT_ULong size;
if ( stream->read )
{
size = stream->read( stream, stream->pos, zip->input,
FT_GZIP_BUFFER_SIZE );
if ( size == 0 )
return FT_THROW( Invalid_Stream_Operation );
}
else
{
size = stream->size - stream->pos;
if ( size > FT_GZIP_BUFFER_SIZE )
size = FT_GZIP_BUFFER_SIZE;
if ( size == 0 )
return FT_THROW( Invalid_Stream_Operation );
FT_MEM_COPY( zip->input, stream->base + stream->pos, size );
}
stream->pos += size;
zstream->next_in = zip->input;
zstream->avail_in = size;
return FT_Err_Ok;
}
static FT_Error
ft_gzip_file_fill_output( FT_GZipFile zip )
{
z_stream* zstream = &zip->zstream;
FT_Error error = FT_Err_Ok;
zip->cursor = zip->buffer;
zstream->next_out = zip->cursor;
zstream->avail_out = FT_GZIP_BUFFER_SIZE;
while ( zstream->avail_out > 0 )
{
int err;
if ( zstream->avail_in == 0 )
{
error = ft_gzip_file_fill_input( zip );
if ( error )
break;
}
err = inflate( zstream, Z_NO_FLUSH );
if ( err == Z_STREAM_END )
{
zip->limit = zstream->next_out;
if ( zip->limit == zip->cursor )
error = FT_THROW( Invalid_Stream_Operation );
break;
}
else if ( err != Z_OK )
{
error = FT_THROW( Invalid_Stream_Operation );
break;
}
}
return error;
}
/* fill output buffer; `count' must be <= FT_GZIP_BUFFER_SIZE */
static FT_Error
ft_gzip_file_skip_output( FT_GZipFile 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_gzip_file_fill_output( zip );
if ( error )
break;
}
return error;
}
static FT_ULong
ft_gzip_file_io( FT_GZipFile 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_gzip_file_reset( zip );
if ( error )
goto Exit;
}
/* skip unwanted bytes */
if ( pos > zip->pos )
{
error = ft_gzip_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_gzip_file_fill_output( zip );
if ( error )
break;
}
Exit:
return result;
}
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** G Z E M B E D D I N G S T R E A M *****/
/***** *****/
/***************************************************************************/
/***************************************************************************/
static void
ft_gzip_stream_close( FT_Stream stream )
{
FT_GZipFile zip = (FT_GZipFile)stream->descriptor.pointer;
FT_Memory memory = stream->memory;
if ( zip )
{
/* finalize gzip file descriptor */
ft_gzip_file_done( zip );
FT_FREE( zip );
stream->descriptor.pointer = NULL;
}
}
static FT_ULong
ft_gzip_stream_io( FT_Stream stream,
FT_ULong pos,
FT_Byte* buffer,
FT_ULong count )
{
FT_GZipFile zip = (FT_GZipFile)stream->descriptor.pointer;
return ft_gzip_file_io( zip, pos, buffer, count );
}
static FT_ULong
ft_gzip_get_uncompressed_size( FT_Stream stream )
{
FT_Error error;
FT_ULong old_pos;
FT_ULong result = 0;
old_pos = stream->pos;
if ( !FT_Stream_Seek( stream, stream->size - 4 ) )
{
result = FT_Stream_ReadULong( stream, &error );
if ( error )
result = 0;
(void)FT_Stream_Seek( stream, old_pos );
}
return result;
}
/* documentation is in ftgzip.h */
FT_EXPORT_DEF( FT_Error )
FT_Stream_OpenGzip( FT_Stream stream,
FT_Stream source )
{
FT_Error error;
FT_Memory memory = source->memory;
FT_GZipFile zip = NULL;
/*
* check the header right now; this prevents allocating un-necessary
* objects when we don't need them
*/
error = ft_gzip_check_header( source );
if ( error )
goto Exit;
FT_ZERO( stream );
stream->memory = memory;
if ( !FT_QNEW( zip ) )
{
error = ft_gzip_file_init( zip, stream, source );
if ( error )
{
FT_FREE( zip );
goto Exit;
}
stream->descriptor.pointer = zip;
}
/*
* We use the following trick to try to dramatically improve the
* performance while dealing with small files. If the original stream
* size is less than a certain threshold, we try to load the whole font
* file into memory. This saves us from using the 32KB buffer needed
* to inflate the file, plus the two 4KB intermediate input/output
* buffers used in the `FT_GZipFile' structure.
*/
{
FT_ULong zip_size = ft_gzip_get_uncompressed_size( source );
if ( zip_size != 0 && zip_size < 40 * 1024 )
{
FT_Byte* zip_buff = NULL;
if ( !FT_ALLOC( zip_buff, zip_size ) )
{
FT_ULong count;
count = ft_gzip_file_io( zip, 0, zip_buff, zip_size );
if ( count == zip_size )
{
ft_gzip_file_done( zip );
FT_FREE( zip );
stream->descriptor.pointer = NULL;
stream->size = zip_size;
stream->pos = 0;
stream->base = zip_buff;
stream->read = NULL;
stream->close = ft_gzip_stream_close;
goto Exit;
}
ft_gzip_file_io( zip, 0, NULL, 0 );
FT_FREE( zip_buff );
}
error = FT_Err_Ok;
}
}
stream->size = 0x7FFFFFFFL; /* don't know the real size! */
stream->pos = 0;
stream->base = 0;
stream->read = ft_gzip_stream_io;
stream->close = ft_gzip_stream_close;
Exit:
return error;
}
/* documentation is in ftgzip.h */
FT_EXPORT_DEF( FT_Error )
FT_Gzip_Uncompress( FT_Memory memory,
FT_Byte* output,
FT_ULong* output_len,
const FT_Byte* input,
FT_ULong input_len )
{
z_stream stream;
int err;
/* this function is modeled after zlib's `uncompress' function */
stream.next_in = (Bytef*)input;
stream.avail_in = (uInt)input_len;
stream.next_out = output;
stream.avail_out = (uInt)*output_len;
stream.zalloc = (alloc_func)ft_gzip_alloc;
stream.zfree = (free_func) ft_gzip_free;
stream.opaque = memory;
err = inflateInit2( &stream, MAX_WBITS );
if ( err != Z_OK )
return FT_THROW( Invalid_Argument );
err = inflate( &stream, Z_FINISH );
if ( err != Z_STREAM_END )
{
inflateEnd( &stream );
if ( err == Z_OK )
err = Z_BUF_ERROR;
}
else
{
*output_len = stream.total_out;
err = inflateEnd( &stream );
}
if ( err == Z_MEM_ERROR )
return FT_THROW( Out_Of_Memory );
if ( err == Z_BUF_ERROR )
return FT_THROW( Array_Too_Large );
if ( err == Z_DATA_ERROR )
return FT_THROW( Invalid_Table );
return FT_Err_Ok;
}
#else /* !FT_CONFIG_OPTION_USE_ZLIB */
FT_EXPORT_DEF( FT_Error )
FT_Stream_OpenGzip( FT_Stream stream,
FT_Stream source )
{
FT_UNUSED( stream );
FT_UNUSED( source );
return FT_THROW( Unimplemented_Feature );
}
FT_EXPORT_DEF( FT_Error )
FT_Gzip_Uncompress( FT_Memory memory,
FT_Byte* output,
FT_ULong* output_len,
const FT_Byte* input,
FT_ULong input_len )
{
FT_UNUSED( memory );
FT_UNUSED( output );
FT_UNUSED( output_len );
FT_UNUSED( input );
FT_UNUSED( input_len );
return FT_THROW( Unimplemented_Feature );
}
#endif /* !FT_CONFIG_OPTION_USE_ZLIB */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/ftgzip.c | C | apache-2.0 | 19,846 |
/* infblock.c -- interpret and process block types to last block
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "infblock.h"
#include "inftrees.h"
#include "infcodes.h"
#include "infutil.h"
/* simplify the use of the inflate_huft type with some defines */
#define exop word.what.Exop
#define bits word.what.Bits
/* Table for deflate from PKZIP's appnote.txt. */
local const uInt border[] = { /* Order of the bit length code lengths */
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
/*
Notes beyond the 1.93a appnote.txt:
1. Distance pointers never point before the beginning of the output
stream.
2. Distance pointers can point back across blocks, up to 32k away.
3. There is an implied maximum of 7 bits for the bit length table and
15 bits for the actual data.
4. If only one code exists, then it is encoded using one bit. (Zero
would be more efficient, but perhaps a little confusing.) If two
codes exist, they are coded using one bit each (0 and 1).
5. There is no way of sending zero distance codes--a dummy must be
sent if there are none. (History: a pre 2.0 version of PKZIP would
store blocks with no distance codes, but this was discovered to be
too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
zero distance codes, which is sent as one code of zero bits in
length.
6. There are up to 286 literal/length codes. Code 256 represents the
end-of-block. Note however that the static length tree defines
288 codes just to fill out the Huffman codes. Codes 286 and 287
cannot be used though, since there is no length base or extra bits
defined for them. Similarily, there are up to 30 distance codes.
However, static trees define 32 codes (all 5 bits) to fill out the
Huffman codes, but the last two had better not show up in the data.
7. Unzip can check dynamic Huffman blocks for complete code sets.
The exception is that a single code would not be complete (see #4).
8. The five bits following the block type is really the number of
literal codes sent minus 257.
9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
(1+6+6). Therefore, to output three times the length, you output
three codes (1+1+1), whereas to output four times the same length,
you only need two codes (1+3). Hmm.
10. In the tree reconstruction algorithm, Code = Code + Increment
only if BitLength(i) is not zero. (Pretty obvious.)
11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
12. Note: length code 284 can represent 227-258, but length code 285
really is 258. The last length deserves its own, short code
since it gets used a lot in very redundant files. The length
258 is special since 258 - 3 (the min match length) is 255.
13. The literal/length and distance code bit lengths are read as a
single stream of lengths. It is possible (and advantageous) for
a repeat code (16, 17, or 18) to go across the boundary between
the two sets of lengths.
*/
local void inflate_blocks_reset( /* s, z, c) */
inflate_blocks_statef *s,
z_streamp z,
uLongf *c )
{
if (c != Z_NULL)
*c = s->check;
if (s->mode == BTREE || s->mode == DTREE)
ZFREE(z, s->sub.trees.blens);
if (s->mode == CODES)
inflate_codes_free(s->sub.decode.codes, z);
s->mode = TYPE;
s->bitk = 0;
s->bitb = 0;
s->read = s->write = s->window;
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(0L, (const Bytef *)Z_NULL, 0);
Tracev((stderr, "inflate: blocks reset\n"));
}
local inflate_blocks_statef *inflate_blocks_new( /* z, c, w) */
z_streamp z,
check_func c,
uInt w )
{
inflate_blocks_statef *s;
if ((s = (inflate_blocks_statef *)ZALLOC
(z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
return s;
if ((s->hufts =
(inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
{
ZFREE(z, s);
return Z_NULL;
}
if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL)
{
ZFREE(z, s->hufts);
ZFREE(z, s);
return Z_NULL;
}
s->end = s->window + w;
s->checkfn = c;
s->mode = TYPE;
Tracev((stderr, "inflate: blocks allocated\n"));
inflate_blocks_reset(s, z, Z_NULL);
return s;
}
local int inflate_blocks( /* s, z, r) */
inflate_blocks_statef *s,
z_streamp z,
int r )
{
uInt t; /* temporary storage */
uLong b; /* bit buffer */
uInt k; /* bits in bit buffer */
Bytef *p; /* input data pointer */
uInt n; /* bytes available there */
Bytef *q; /* output window write pointer */
uInt m; /* bytes to end of window or read pointer */
/* copy input/output information to locals (UPDATE macro restores) */
LOAD
/* process input based on current state */
while (1) switch (s->mode)
{
case TYPE:
NEEDBITS(3)
t = (uInt)b & 7;
s->last = t & 1;
switch (t >> 1)
{
case 0: /* stored */
Tracev((stderr, "inflate: stored block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
t = k & 7; /* go to byte boundary */
DUMPBITS(t)
s->mode = LENS; /* get length of stored block */
break;
case 1: /* fixed */
Tracev((stderr, "inflate: fixed codes block%s\n",
s->last ? " (last)" : ""));
{
uInt bl, bd;
inflate_huft *tl, *td;
inflate_trees_fixed(&bl, &bd, (const inflate_huft**)&tl,
(const inflate_huft**)&td, z);
s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
if (s->sub.decode.codes == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
}
DUMPBITS(3)
s->mode = CODES;
break;
case 2: /* dynamic */
Tracev((stderr, "inflate: dynamic codes block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
s->mode = TABLE;
break;
case 3: /* illegal */
DUMPBITS(3)
s->mode = BAD;
z->msg = (char*)"invalid block type";
r = Z_DATA_ERROR;
LEAVE
}
break;
case LENS:
NEEDBITS(32)
if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
{
s->mode = BAD;
z->msg = (char*)"invalid stored block lengths";
r = Z_DATA_ERROR;
LEAVE
}
s->sub.left = (uInt)b & 0xffff;
b = k = 0; /* dump bits */
Tracev((stderr, "inflate: stored length %u\n", s->sub.left));
s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
break;
case STORED:
if (n == 0)
LEAVE
NEEDOUT
t = s->sub.left;
if (t > n) t = n;
if (t > m) t = m;
zmemcpy(q, p, t);
p += t; n -= t;
q += t; m -= t;
if ((s->sub.left -= t) != 0)
break;
Tracev((stderr, "inflate: stored end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
s->mode = s->last ? DRY : TYPE;
break;
case TABLE:
NEEDBITS(14)
s->sub.trees.table = t = (uInt)b & 0x3fff;
#ifndef PKZIP_BUG_WORKAROUND
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
s->mode = BAD;
z->msg = (char*)"too many length or distance symbols";
r = Z_DATA_ERROR;
LEAVE
}
#endif
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
DUMPBITS(14)
s->sub.trees.index = 0;
Tracev((stderr, "inflate: table sizes ok\n"));
s->mode = BTREE;
case BTREE:
while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
{
NEEDBITS(3)
s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
DUMPBITS(3)
}
while (s->sub.trees.index < 19)
s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
s->sub.trees.bb = 7;
t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
&s->sub.trees.tb, s->hufts, z);
if (t != Z_OK)
{
r = t;
if (r == Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = BAD;
}
LEAVE
}
s->sub.trees.index = 0;
Tracev((stderr, "inflate: bits tree ok\n"));
s->mode = DTREE;
case DTREE:
while (s->sub.trees.index < (258 + (t & 0x1f) + ((t >> 5) & 0x1f)))
{
inflate_huft *h;
uInt i, j, c;
t = s->sub.trees.bb;
NEEDBITS(t)
h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
t = h->bits;
c = h->base;
if (c < 16)
{
DUMPBITS(t)
s->sub.trees.blens[s->sub.trees.index++] = c;
}
else /* c == 16..18 */
{
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
NEEDBITS(t + i)
DUMPBITS(t)
j += (uInt)b & inflate_mask[i];
DUMPBITS(i)
i = s->sub.trees.index;
t = s->sub.trees.table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
(c == 16 && i < 1))
{
ZFREE(z, s->sub.trees.blens);
s->mode = BAD;
z->msg = (char*)"invalid bit length repeat";
r = Z_DATA_ERROR;
LEAVE
}
c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
do {
s->sub.trees.blens[i++] = c;
} while (--j);
s->sub.trees.index = i;
}
t = s->sub.trees.table;
}
s->sub.trees.tb = Z_NULL;
{
uInt bl, bd;
inflate_huft *tl, *td;
inflate_codes_statef *c;
bl = 9; /* must be <= 9 for lookahead assumptions */
bd = 6; /* must be <= 9 for lookahead assumptions */
t = s->sub.trees.table;
t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
s->sub.trees.blens, &bl, &bd, &tl, &td,
s->hufts, z);
if (t != Z_OK)
{
if (t == (uInt)Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = BAD;
}
r = t;
LEAVE
}
Tracev((stderr, "inflate: trees ok\n"));
if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
s->sub.decode.codes = c;
}
ZFREE(z, s->sub.trees.blens);
s->mode = CODES;
case CODES:
UPDATE
if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
return inflate_flush(s, z, r);
r = Z_OK;
inflate_codes_free(s->sub.decode.codes, z);
LOAD
Tracev((stderr, "inflate: codes end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
if (!s->last)
{
s->mode = TYPE;
break;
}
s->mode = DRY;
case DRY:
FLUSH
if (s->read != s->write)
LEAVE
s->mode = DONE;
case DONE:
r = Z_STREAM_END;
LEAVE
case BAD:
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
#ifdef NEED_DUMMY_RETURN
return 0;
#endif
}
local int inflate_blocks_free( /* s, z) */
inflate_blocks_statef *s,
z_streamp z )
{
inflate_blocks_reset(s, z, Z_NULL);
ZFREE(z, s->window);
ZFREE(z, s->hufts);
ZFREE(z, s);
Tracev((stderr, "inflate: blocks freed\n"));
return Z_OK;
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infblock.c | C | apache-2.0 | 12,162 |
/* infblock.h -- header to use infblock.c
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
#ifndef _INFBLOCK_H
#define _INFBLOCK_H
struct inflate_blocks_state;
typedef struct inflate_blocks_state FAR inflate_blocks_statef;
local inflate_blocks_statef * inflate_blocks_new OF((
z_streamp z,
check_func c, /* check function */
uInt w)); /* window size */
local int inflate_blocks OF((
inflate_blocks_statef *,
z_streamp ,
int)); /* initial return code */
local void inflate_blocks_reset OF((
inflate_blocks_statef *,
z_streamp ,
uLongf *)); /* check value on output */
local int inflate_blocks_free OF((
inflate_blocks_statef *,
z_streamp));
#endif /* _INFBLOCK_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infblock.h | C | apache-2.0 | 1,051 |
/* infcodes.c -- process literals and length/distance pairs
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "inftrees.h"
#include "infblock.h"
#include "infcodes.h"
#include "infutil.h"
/* simplify the use of the inflate_huft type with some defines */
#define exop word.what.Exop
#define bits word.what.Bits
typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
START, /* x: set up for LEN */
LEN, /* i: get length/literal/eob next */
LENEXT, /* i: getting length extra (have base) */
DIST, /* i: get distance next */
DISTEXT, /* i: getting distance extra */
COPY, /* o: copying bytes in window, waiting for space */
LIT, /* o: got literal, waiting for output space */
WASH, /* o: got eob, possibly still output waiting */
END, /* x: got eob and all data flushed */
BADCODE} /* x: got error */
inflate_codes_mode;
/* inflate codes private state */
struct inflate_codes_state {
/* mode */
inflate_codes_mode mode; /* current inflate_codes mode */
/* mode dependent information */
uInt len;
union {
struct {
inflate_huft *tree; /* pointer into tree */
uInt need; /* bits needed */
} code; /* if LEN or DIST, where in tree */
uInt lit; /* if LIT, literal */
struct {
uInt get; /* bits to get for extra */
uInt dist; /* distance back to copy from */
} copy; /* if EXT or COPY, where and how much */
} sub; /* submode */
/* mode independent information */
Byte lbits; /* ltree bits decoded per branch */
Byte dbits; /* dtree bits decoder per branch */
inflate_huft *ltree; /* literal/length/eob tree */
inflate_huft *dtree; /* distance tree */
};
local inflate_codes_statef *inflate_codes_new( /* bl, bd, tl, td, z) */
uInt bl, uInt bd,
inflate_huft *tl,
inflate_huft *td, /* need separate declaration for Borland C++ */
z_streamp z )
{
inflate_codes_statef *c;
if ((c = (inflate_codes_statef *)
ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
{
c->mode = START;
c->lbits = (Byte)bl;
c->dbits = (Byte)bd;
c->ltree = tl;
c->dtree = td;
Tracev((stderr, "inflate: codes new\n"));
}
return c;
}
local int inflate_codes( /* s, z, r) */
inflate_blocks_statef *s,
z_streamp z,
int r )
{
uInt j; /* temporary storage */
inflate_huft *t; /* temporary pointer */
uInt e; /* extra bits or operation */
uLong b; /* bit buffer */
uInt k; /* bits in bit buffer */
Bytef *p; /* input data pointer */
uInt n; /* bytes available there */
Bytef *q; /* output window write pointer */
uInt m; /* bytes to end of window or read pointer */
Bytef *f; /* pointer to copy strings from */
inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
/* copy input/output information to locals (UPDATE macro restores) */
LOAD
/* process input and output based on current state */
while (1) switch (c->mode)
{ /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
case START: /* x: set up for LEN */
#ifndef SLOW
if (m >= 258 && n >= 10)
{
UPDATE
r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
LOAD
if (r != Z_OK)
{
c->mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
#endif /* !SLOW */
c->sub.code.need = c->lbits;
c->sub.code.tree = c->ltree;
c->mode = LEN;
case LEN: /* i: get length/literal/eob next */
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e == 0) /* literal */
{
c->sub.lit = t->base;
Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", t->base));
c->mode = LIT;
break;
}
if (e & 16) /* length */
{
c->sub.copy.get = e & 15;
c->len = t->base;
c->mode = LENEXT;
break;
}
if ((e & 64) == 0) /* next table */
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
if (e & 32) /* end of block */
{
Tracevv((stderr, "inflate: end of block\n"));
c->mode = WASH;
break;
}
c->mode = BADCODE; /* invalid code */
z->msg = (char*)"invalid literal/length code";
r = Z_DATA_ERROR;
LEAVE
case LENEXT: /* i: getting length extra (have base) */
j = c->sub.copy.get;
NEEDBITS(j)
c->len += (uInt)b & inflate_mask[j];
DUMPBITS(j)
c->sub.code.need = c->dbits;
c->sub.code.tree = c->dtree;
Tracevv((stderr, "inflate: length %u\n", c->len));
c->mode = DIST;
case DIST: /* i: get distance next */
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e & 16) /* distance */
{
c->sub.copy.get = e & 15;
c->sub.copy.dist = t->base;
c->mode = DISTEXT;
break;
}
if ((e & 64) == 0) /* next table */
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
c->mode = BADCODE; /* invalid code */
z->msg = (char*)"invalid distance code";
r = Z_DATA_ERROR;
LEAVE
case DISTEXT: /* i: getting distance extra */
j = c->sub.copy.get;
NEEDBITS(j)
c->sub.copy.dist += (uInt)b & inflate_mask[j];
DUMPBITS(j)
Tracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist));
c->mode = COPY;
case COPY: /* o: copying bytes in window, waiting for space */
f = q - c->sub.copy.dist;
while (f < s->window) /* modulo window size-"while" instead */
f += s->end - s->window; /* of "if" handles invalid distances */
while (c->len)
{
NEEDOUT
OUTBYTE(*f++)
if (f == s->end)
f = s->window;
c->len--;
}
c->mode = START;
break;
case LIT: /* o: got literal, waiting for output space */
NEEDOUT
OUTBYTE(c->sub.lit)
c->mode = START;
break;
case WASH: /* o: got eob, possibly more output */
if (k > 7) /* return unused byte, if any */
{
Assert(k < 16, "inflate_codes grabbed too many bytes")
k -= 8;
n++;
p--; /* can always return one */
}
FLUSH
if (s->read != s->write)
LEAVE
c->mode = END;
case END:
r = Z_STREAM_END;
LEAVE
case BADCODE: /* x: got error */
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
#ifdef NEED_DUMMY_RETURN
return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
#endif
}
local void inflate_codes_free( /* c, z) */
inflate_codes_statef *c,
z_streamp z )
{
ZFREE(z, c);
Tracev((stderr, "inflate: codes free\n"));
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infcodes.c | C | apache-2.0 | 7,646 |
/* infcodes.h -- header to use infcodes.c
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
#ifndef _INFCODES_H
#define _INFCODES_H
struct inflate_codes_state;
typedef struct inflate_codes_state FAR inflate_codes_statef;
local inflate_codes_statef *inflate_codes_new OF((
uInt, uInt,
inflate_huft *, inflate_huft *,
z_streamp ));
local int inflate_codes OF((
inflate_blocks_statef *,
z_streamp ,
int));
local void inflate_codes_free OF((
inflate_codes_statef *,
z_streamp ));
#endif /* _INFCODES_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infcodes.h | C | apache-2.0 | 799 |
/* inffixed.h -- table for decoding fixed codes
* Generated automatically by the maketree.c program
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
local const uInt fixed_bl = 9;
local const uInt fixed_bd = 5;
local const inflate_huft fixed_tl[] = {
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
};
local const inflate_huft fixed_td[] = {
{{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
{{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
{{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
{{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
{{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
{{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
{{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
{{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
};
| YifuLiu/AliOS-Things | components/freetype/src/gzip/inffixed.h | C | apache-2.0 | 8,952 |
/* inflate.c -- zlib interface to inflate modules
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "infblock.h"
#define DONE INFLATE_DONE
#define BAD INFLATE_BAD
typedef enum {
METHOD, /* waiting for method byte */
FLAG, /* waiting for flag byte */
DICT4, /* four dictionary check bytes to go */
DICT3, /* three dictionary check bytes to go */
DICT2, /* two dictionary check bytes to go */
DICT1, /* one dictionary check byte to go */
DICT0, /* waiting for inflateSetDictionary */
BLOCKS, /* decompressing blocks */
CHECK4, /* four check bytes to go */
CHECK3, /* three check bytes to go */
CHECK2, /* two check bytes to go */
CHECK1, /* one check byte to go */
DONE, /* finished check, done */
BAD} /* got an error--stay here */
inflate_mode;
/* inflate private state */
struct internal_state {
/* mode */
inflate_mode mode; /* current inflate mode */
/* mode dependent information */
union {
uInt method; /* if FLAGS, method byte */
struct {
uLong was; /* computed check value */
uLong need; /* stream check value */
} check; /* if CHECK, check values to compare */
uInt marker; /* if BAD, inflateSync's marker bytes count */
} sub; /* submode */
/* mode independent information */
int nowrap; /* flag for no wrapper */
uInt wbits; /* log2(window size) (8..15, defaults to 15) */
inflate_blocks_statef
*blocks; /* current inflate_blocks state */
};
ZEXPORT(int) inflateReset( /* z) */
z_streamp z )
{
if (z == Z_NULL || z->state == Z_NULL)
return Z_STREAM_ERROR;
z->total_in = z->total_out = 0;
z->msg = Z_NULL;
z->state->mode = z->state->nowrap ? BLOCKS : METHOD;
inflate_blocks_reset(z->state->blocks, z, Z_NULL);
Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
ZEXPORT(int) inflateEnd( /* z) */
z_streamp z )
{
if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
return Z_STREAM_ERROR;
if (z->state->blocks != Z_NULL)
inflate_blocks_free(z->state->blocks, z);
ZFREE(z, z->state);
z->state = Z_NULL;
Tracev((stderr, "inflate: end\n"));
return Z_OK;
}
ZEXPORT(int) inflateInit2_( /* z, w, version, stream_size) */
z_streamp z,
int w,
const char *version,
int stream_size )
{
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
stream_size != sizeof(z_stream))
return Z_VERSION_ERROR;
/* initialize state */
if (z == Z_NULL)
return Z_STREAM_ERROR;
z->msg = Z_NULL;
if (z->zalloc == Z_NULL)
{
z->zalloc = zcalloc;
z->opaque = (voidpf)0;
}
if (z->zfree == Z_NULL) z->zfree = zcfree;
if ((z->state = (struct internal_state FAR *)
ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
return Z_MEM_ERROR;
z->state->blocks = Z_NULL;
/* handle undocumented nowrap option (no zlib header or check) */
z->state->nowrap = 0;
if (w < 0)
{
w = - w;
z->state->nowrap = 1;
}
/* set window size */
if (w < 8 || w > 15)
{
inflateEnd(z);
return Z_STREAM_ERROR;
}
z->state->wbits = (uInt)w;
/* create inflate_blocks state */
if ((z->state->blocks =
inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
== Z_NULL)
{
inflateEnd(z);
return Z_MEM_ERROR;
}
Tracev((stderr, "inflate: allocated\n"));
/* reset state */
inflateReset(z);
return Z_OK;
}
#undef NEEDBYTE
#define NEEDBYTE {if(z->avail_in==0)return r;r=f;}
#undef NEXTBYTE
#define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
ZEXPORT(int) inflate( /* z, f) */
z_streamp z,
int f )
{
int r;
uInt b;
if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (1) switch (z->state->mode)
{
case METHOD:
NEEDBYTE
if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED)
{
z->state->mode = BAD;
z->msg = (char*)"unknown compression method";
z->state->sub.marker = 5; /* can't try inflateSync */
break;
}
if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
{
z->state->mode = BAD;
z->msg = (char*)"invalid window size";
z->state->sub.marker = 5; /* can't try inflateSync */
break;
}
z->state->mode = FLAG;
case FLAG:
NEEDBYTE
b = NEXTBYTE;
if (((z->state->sub.method << 8) + b) % 31)
{
z->state->mode = BAD;
z->msg = (char*)"incorrect header check";
z->state->sub.marker = 5; /* can't try inflateSync */
break;
}
Tracev((stderr, "inflate: zlib header ok\n"));
if (!(b & PRESET_DICT))
{
z->state->mode = BLOCKS;
break;
}
z->state->mode = DICT4;
case DICT4:
NEEDBYTE
z->state->sub.check.need = (uLong)NEXTBYTE << 24;
z->state->mode = DICT3;
case DICT3:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE << 16;
z->state->mode = DICT2;
case DICT2:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE << 8;
z->state->mode = DICT1;
case DICT1:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE;
z->adler = z->state->sub.check.need;
z->state->mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z->state->mode = BAD;
z->msg = (char*)"need dictionary";
z->state->sub.marker = 0; /* can try inflateSync */
return Z_STREAM_ERROR;
case BLOCKS:
r = inflate_blocks(z->state->blocks, z, r);
if (r == Z_DATA_ERROR)
{
z->state->mode = BAD;
z->state->sub.marker = 0; /* can try inflateSync */
break;
}
if (r == Z_OK)
r = f;
if (r != Z_STREAM_END)
return r;
r = f;
inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
if (z->state->nowrap)
{
z->state->mode = DONE;
break;
}
z->state->mode = CHECK4;
case CHECK4:
NEEDBYTE
z->state->sub.check.need = (uLong)NEXTBYTE << 24;
z->state->mode = CHECK3;
case CHECK3:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE << 16;
z->state->mode = CHECK2;
case CHECK2:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE << 8;
z->state->mode = CHECK1;
case CHECK1:
NEEDBYTE
z->state->sub.check.need += (uLong)NEXTBYTE;
if (z->state->sub.check.was != z->state->sub.check.need)
{
z->state->mode = BAD;
z->msg = (char*)"incorrect data check";
z->state->sub.marker = 5; /* can't try inflateSync */
break;
}
Tracev((stderr, "inflate: zlib check ok\n"));
z->state->mode = DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
#ifdef NEED_DUMMY_RETURN
return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
#endif
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/inflate.c | C | apache-2.0 | 7,277 |
/* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "inftrees.h"
#if !defined(BUILDFIXED) && !defined(STDC)
# define BUILDFIXED /* non ANSI compilers may not accept inffixed.h */
#endif
#if 0
local const char inflate_copyright[] =
" inflate 1.1.4 Copyright 1995-2002 Mark Adler ";
#endif
/*
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/* simplify the use of the inflate_huft type with some defines */
#define exop word.what.Exop
#define bits word.what.Bits
local int huft_build OF((
uIntf *, /* code lengths in bits */
uInt, /* number of codes */
uInt, /* number of "simple" codes */
const uIntf *, /* list of base values for non-simple codes */
const uIntf *, /* list of extra bits for non-simple codes */
inflate_huft * FAR*,/* result: starting table */
uIntf *, /* maximum lookup bits (returns actual) */
inflate_huft *, /* space for trees */
uInt *, /* hufts used in space */
uIntf * )); /* space for values */
/* Tables for deflate from PKZIP's appnote.txt. */
local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
/* see note #13 above about 258 */
local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
local const uInt cpdext[30] = { /* Extra bits for distance codes */
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
/*
Huffman code decoding is performed using a multi-level table lookup.
The fastest way to decode is to simply build a lookup table whose
size is determined by the longest code. However, the time it takes
to build this table can also be a factor if the data being decoded
is not very long. The most common codes are necessarily the
shortest codes, so those codes dominate the decoding time, and hence
the speed. The idea is you can have a shorter table that decodes the
shorter, more probable codes, and then point to subsidiary tables for
the longer codes. The time it costs to decode the longer codes is
then traded against the time it takes to make longer tables.
This results of this trade are in the variables lbits and dbits
below. lbits is the number of bits the first level table for literal/
length codes can decode in one step, and dbits is the same thing for
the distance codes. Subsequent tables are also less than or equal to
those sizes. These values may be adjusted either when all of the
codes are shorter than that, in which case the longest code length in
bits is used, or when the shortest code is *longer* than the requested
table size, in which case the length of the shortest code in bits is
used.
There are two different values for the two tables, since they code a
different number of possibilities each. The literal/length table
codes 286 possible values, or in a flat code, a little over eight
bits. The distance table codes 30 possible values, or a little less
than five bits, flat. The optimum values for speed end up being
about one bit more than those, so lbits is 8+1 and dbits is 5+1.
The optimum values may differ though from machine to machine, and
possibly even between compilers. Your mileage may vary.
*/
/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
#define BMAX 15 /* maximum bit length of any code */
local int huft_build( /* b, n, s, d, e, t, m, hp, hn, v) */
uIntf *b, /* code lengths in bits (all assumed <= BMAX) */
uInt n, /* number of codes (assumed <= 288) */
uInt s, /* number of simple-valued codes (0..s-1) */
const uIntf *d, /* list of base values for non-simple codes */
const uIntf *e, /* list of extra bits for non-simple codes */
inflate_huft * FAR *t, /* result: starting table */
uIntf *m, /* maximum lookup bits, returns actual */
inflate_huft *hp, /* space for trees */
uInt *hn, /* hufts used in space */
uIntf *v /* working area: values in order of bit length */
/* Given a list of code lengths and a maximum table size, make a set of
tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
if the given code set is incomplete (the tables are still built in this
case), or Z_DATA_ERROR if the input is invalid. */
)
{
uInt a; /* counter for codes of length k */
uInt c[BMAX+1]; /* bit length count table */
uInt f; /* i repeats in table every f entries */
int g; /* maximum code length */
int h; /* table level */
register uInt i; /* counter, current code */
register uInt j; /* counter */
register int k; /* number of bits in current code */
int l; /* bits per table (returned in m) */
uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */
register uIntf *p; /* pointer into c[], b[], or v[] */
inflate_huft *q; /* points to current table */
struct inflate_huft_s r; /* table entry for structure assignment */
inflate_huft *u[BMAX]; /* table stack */
register int w; /* bits before this table == (l * h) */
uInt x[BMAX+1]; /* bit offsets, then code stack */
uIntf *xp; /* pointer into x */
int y; /* number of dummy codes added */
uInt z; /* number of entries in current table */
/* Make compiler happy */
r.base = 0;
/* Generate counts for each bit length */
p = c;
#define C0 *p++ = 0;
#define C2 C0 C0 C0 C0
#define C4 C2 C2 C2 C2
C4 /* clear c[]--assume BMAX+1 is 16 */
p = b; i = n;
do {
c[*p++]++; /* assume all entries <= BMAX */
} while (--i);
if (c[0] == n) /* null input--all zero length codes */
{
*t = (inflate_huft *)Z_NULL;
*m = 0;
return Z_OK;
}
/* Find minimum and maximum length, bound *m by those */
l = *m;
for (j = 1; j <= BMAX; j++)
if (c[j])
break;
k = j; /* minimum code length */
if ((uInt)l < j)
l = j;
for (i = BMAX; i; i--)
if (c[i])
break;
g = i; /* maximum code length */
if ((uInt)l > i)
l = i;
*m = l;
/* Adjust last length count to fill out codes, if needed */
for (y = 1 << j; j < i; j++, y <<= 1)
if ((y -= c[j]) < 0)
return Z_DATA_ERROR;
if ((y -= c[i]) < 0)
return Z_DATA_ERROR;
c[i] += y;
/* Generate starting offsets into the value table for each length */
x[1] = j = 0;
p = c + 1; xp = x + 2;
while (--i) { /* note that i == g from above */
*xp++ = (j += *p++);
}
/* Make a table of values in order of bit lengths */
p = b; i = 0;
do {
if ((j = *p++) != 0)
v[x[j]++] = i;
} while (++i < n);
n = x[g]; /* set n to length of v */
/* Generate the Huffman codes and for each, make the table entries */
x[0] = i = 0; /* first Huffman code is zero */
p = v; /* grab values in bit order */
h = -1; /* no tables yet--level -1 */
w = -l; /* bits decoded == (l * h) */
u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */
q = (inflate_huft *)Z_NULL; /* ditto */
z = 0; /* ditto */
/* go through the bit lengths (k already is bits in shortest code) */
for (; k <= g; k++)
{
a = c[k];
while (a--)
{
/* here i is the Huffman code of length k bits for value *p */
/* make tables up to required level */
while (k > w + l)
{
h++;
w += l; /* previous table always l bits */
/* compute minimum size table less than or equal to l bits */
z = g - w;
z = z > (uInt)l ? (uInt)l : z; /* table size upper limit */
if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
{ /* too few codes for k-w bit table */
f -= a + 1; /* deduct codes from patterns left */
xp = c + k;
if (j < z)
while (++j < z) /* try smaller tables up to z bits */
{
if ((f <<= 1) <= *++xp)
break; /* enough codes to use up j bits */
f -= *xp; /* else deduct codes from patterns */
}
}
z = 1 << j; /* table entries for j-bit table */
/* allocate new table */
if (*hn + z > MANY) /* (note: doesn't matter for fixed) */
return Z_DATA_ERROR; /* overflow of MANY */
u[h] = q = hp + *hn;
*hn += z;
/* connect to last table, if there is one */
if (h)
{
x[h] = i; /* save pattern for backing up */
r.bits = (Byte)l; /* bits to dump before this table */
r.exop = (Byte)j; /* bits in this table */
j = i >> (w - l);
r.base = (uInt)(q - u[h-1] - j); /* offset to this table */
u[h-1][j] = r; /* connect to last table */
}
else
*t = q; /* first table is returned result */
}
/* set up table entry in r */
r.bits = (Byte)(k - w);
if (p >= v + n)
r.exop = 128 + 64; /* out of values--invalid code */
else if (*p < s)
{
r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
r.base = *p++; /* simple code is just the value */
}
else
{
r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
r.base = d[*p++ - s];
}
/* fill code-like entries with r */
f = 1 << (k - w);
for (j = i >> w; j < z; j += f)
q[j] = r;
/* backwards increment the k-bit code i */
for (j = 1 << (k - 1); i & j; j >>= 1)
i ^= j;
i ^= j;
/* backup over finished tables */
mask = (1 << w) - 1; /* needed on HP, cc -O bug */
while ((i & mask) != x[h])
{
h--; /* don't need to update q */
w -= l;
mask = (1 << w) - 1;
}
}
}
/* Return Z_BUF_ERROR if we were given an incomplete table */
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
local int inflate_trees_bits( /* c, bb, tb, hp, z) */
uIntf *c, /* 19 code lengths */
uIntf *bb, /* bits tree desired/actual depth */
inflate_huft * FAR *tb, /* bits tree result */
inflate_huft *hp, /* space for trees */
z_streamp z /* for messages */
)
{
int r;
uInt hn = 0; /* hufts used in space */
uIntf *v; /* work area for huft_build */
if ((v = (uIntf*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL,
tb, bb, hp, &hn, v);
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed dynamic bit lengths tree";
else if (r == Z_BUF_ERROR || *bb == 0)
{
z->msg = (char*)"incomplete dynamic bit lengths tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
local int inflate_trees_dynamic( /* nl, nd, c, bl, bd, tl, td, hp, z) */
uInt nl, /* number of literal/length codes */
uInt nd, /* number of distance codes */
uIntf *c, /* that many (total) code lengths */
uIntf *bl, /* literal desired/actual bit depth */
uIntf *bd, /* distance desired/actual bit depth */
inflate_huft * FAR *tl, /* literal/length tree result */
inflate_huft * FAR *td, /* distance tree result */
inflate_huft *hp, /* space for trees */
z_streamp z /* for messages */
)
{
int r;
uInt hn = 0; /* hufts used in space */
uIntf *v; /* work area for huft_build */
/* allocate work area */
if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
/* build literal/length tree */
r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
if (r != Z_OK || *bl == 0)
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed literal/length tree";
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"incomplete literal/length tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
/* build distance tree */
r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
if (r != Z_OK || (*bd == 0 && nl > 257))
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed distance tree";
else if (r == Z_BUF_ERROR) {
#if 0
{
#endif
#ifdef PKZIP_BUG_WORKAROUND
r = Z_OK;
}
#else
z->msg = (char*)"incomplete distance tree";
r = Z_DATA_ERROR;
}
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"empty distance tree with lengths";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
#endif
}
/* done */
ZFREE(z, v);
return Z_OK;
}
/* build fixed tables only once--keep them here */
#ifdef BUILDFIXED
local int fixed_built = 0;
#define FIXEDH 544 /* number of hufts used by fixed tables */
local inflate_huft fixed_mem[FIXEDH];
local uInt fixed_bl;
local uInt fixed_bd;
local inflate_huft *fixed_tl;
local inflate_huft *fixed_td;
#else
#include "inffixed.h"
#endif
local int inflate_trees_fixed( /* bl, bd, tl, td, z) */
uIntf *bl, /* literal desired/actual bit depth */
uIntf *bd, /* distance desired/actual bit depth */
const inflate_huft * FAR *tl, /* literal/length tree result */
const inflate_huft * FAR *td, /* distance tree result */
z_streamp z /* for memory allocation */
)
{
#ifdef BUILDFIXED
/* build fixed tables if not already */
if (!fixed_built)
{
int k; /* temporary variable */
uInt f = 0; /* number of hufts used in fixed_mem */
uIntf *c; /* length list for huft_build */
uIntf *v; /* work area for huft_build */
/* allocate memory */
if ((c = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
{
ZFREE(z, c);
return Z_MEM_ERROR;
}
/* literal table */
for (k = 0; k < 144; k++)
c[k] = 8;
for (; k < 256; k++)
c[k] = 9;
for (; k < 280; k++)
c[k] = 7;
for (; k < 288; k++)
c[k] = 8;
fixed_bl = 9;
huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl,
fixed_mem, &f, v);
/* distance table */
for (k = 0; k < 30; k++)
c[k] = 5;
fixed_bd = 5;
huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd,
fixed_mem, &f, v);
/* done */
ZFREE(z, v);
ZFREE(z, c);
fixed_built = 1;
}
#else
FT_UNUSED(z);
#endif
*bl = fixed_bl;
*bd = fixed_bd;
*tl = fixed_tl;
*td = fixed_td;
return Z_OK;
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/inftrees.c | C | apache-2.0 | 16,135 |
/* inftrees.h -- header to use inftrees.c
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* Huffman code lookup table entry--this entry is four bytes for machines
that have 16-bit pointers (e.g. PC's in the small or medium model). */
#ifndef _INFTREES_H
#define _INFTREES_H
typedef struct inflate_huft_s FAR inflate_huft;
struct inflate_huft_s {
union {
struct {
Byte Exop; /* number of extra bits or operation */
Byte Bits; /* number of bits in this code or subcode */
} what;
uInt pad; /* pad structure to a power of 2 (4 bytes for */
} word; /* 16-bit, 8 bytes for 32-bit int's) */
uInt base; /* literal, length base, distance base,
or table offset */
};
/* Maximum size of dynamic tree. The maximum found in a long but non-
exhaustive search was 1004 huft structures (850 for length/literals
and 154 for distances, the latter actually the result of an
exhaustive search). The actual maximum is not known, but the
value below is more than safe. */
#define MANY 1440
local int inflate_trees_bits OF((
uIntf *, /* 19 code lengths */
uIntf *, /* bits tree desired/actual depth */
inflate_huft * FAR *, /* bits tree result */
inflate_huft *, /* space for trees */
z_streamp)); /* for messages */
local int inflate_trees_dynamic OF((
uInt, /* number of literal/length codes */
uInt, /* number of distance codes */
uIntf *, /* that many (total) code lengths */
uIntf *, /* literal desired/actual bit depth */
uIntf *, /* distance desired/actual bit depth */
inflate_huft * FAR *, /* literal/length tree result */
inflate_huft * FAR *, /* distance tree result */
inflate_huft *, /* space for trees */
z_streamp)); /* for messages */
local int inflate_trees_fixed OF((
uIntf *, /* literal desired/actual bit depth */
uIntf *, /* distance desired/actual bit depth */
const inflate_huft * FAR *, /* literal/length tree result */
const inflate_huft * FAR *, /* distance tree result */
z_streamp)); /* for memory allocation */
#endif /* _INFTREES_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/inftrees.h | C | apache-2.0 | 2,682 |
/* inflate_util.c -- data and routines common to blocks and codes
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "infblock.h"
#include "inftrees.h"
#include "infcodes.h"
#include "infutil.h"
/* And'ing with mask[n] masks the lower n bits */
local const uInt inflate_mask[17] = {
0x0000,
0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
};
/* copy as much as possible from the sliding window to the output area */
local int inflate_flush( /* s, z, r) */
inflate_blocks_statef *s,
z_streamp z,
int r )
{
uInt n;
Bytef *p;
Bytef *q;
/* local copies of source and destination pointers */
p = z->next_out;
q = s->read;
/* compute number of bytes to copy as far as end of window */
n = (uInt)((q <= s->write ? s->write : s->end) - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
/* update counters */
z->avail_out -= n;
z->total_out += n;
/* update check information */
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
/* copy as far as end of window */
zmemcpy(p, q, n);
p += n;
q += n;
/* see if more to copy at beginning of window */
if (q == s->end)
{
/* wrap pointers */
q = s->window;
if (s->write == s->end)
s->write = s->window;
/* compute bytes to copy */
n = (uInt)(s->write - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
/* update counters */
z->avail_out -= n;
z->total_out += n;
/* update check information */
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
/* copy */
zmemcpy(p, q, n);
p += n;
q += n;
}
/* update pointers */
z->next_out = p;
s->read = q;
/* done */
return r;
}
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infutil.c | C | apache-2.0 | 1,957 |
/* infutil.h -- types and macros common to blocks and codes
* Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
#ifndef _INFUTIL_H
#define _INFUTIL_H
typedef enum {
TYPE, /* get type bits (3, including end bit) */
LENS, /* get lengths for stored */
STORED, /* processing stored block */
TABLE, /* get table lengths */
BTREE, /* get bit lengths tree for a dynamic block */
DTREE, /* get length, distance trees for a dynamic block */
CODES, /* processing fixed or dynamic block */
DRY, /* output remaining window bytes */
DONE, /* finished last block, done */
BAD} /* got a data error--stuck here */
inflate_block_mode;
/* inflate blocks semi-private state */
struct inflate_blocks_state {
/* mode */
inflate_block_mode mode; /* current inflate_block mode */
/* mode dependent information */
union {
uInt left; /* if STORED, bytes left to copy */
struct {
uInt table; /* table lengths (14 bits) */
uInt index; /* index into blens (or border) */
uIntf *blens; /* bit lengths of codes */
uInt bb; /* bit length tree depth */
inflate_huft *tb; /* bit length decoding tree */
} trees; /* if DTREE, decoding info for trees */
struct {
inflate_codes_statef
*codes;
} decode; /* if CODES, current state */
} sub; /* submode */
uInt last; /* true if this block is the last block */
/* mode independent information */
uInt bitk; /* bits in bit buffer */
uLong bitb; /* bit buffer */
inflate_huft *hufts; /* single malloc for tree space */
Bytef *window; /* sliding window */
Bytef *end; /* one byte after sliding window */
Bytef *read; /* window read pointer */
Bytef *write; /* window write pointer */
check_func checkfn; /* check function */
uLong check; /* check on output */
};
/* defines for inflate input/output */
/* update pointers and return */
#define UPDBITS {s->bitb=b;s->bitk=k;}
#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
#define UPDOUT {s->write=q;}
#define UPDATE {UPDBITS UPDIN UPDOUT}
#define LEAVE {UPDATE return inflate_flush(s,z,r);}
/* get bytes and bits */
#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
#define NEXTBYTE (n--,*p++)
#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
#define DUMPBITS(j) {b>>=(j);k-=(j);}
/* output bytes */
#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
#define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
/* load local pointers */
#define LOAD {LOADIN LOADOUT}
/* masks for lower bits (size given to avoid silly warnings with Visual C++) */
#ifndef NO_INFLATE_MASK
local uInt inflate_mask[17];
#endif
/* copy as much as possible from the sliding window to the output area */
local int inflate_flush OF((
inflate_blocks_statef *,
z_streamp ,
int));
#endif
| YifuLiu/AliOS-Things | components/freetype/src/gzip/infutil.h | C | apache-2.0 | 3,638 |
#
# FreeType 2 GZip support configuration rules
#
# Copyright 2002, 2003, 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.
# gzip driver directory
#
GZIP_DIR := $(SRC_DIR)/gzip
# compilation flags for the driver
#
ifeq ($(SYSTEM_ZLIB),)
GZIP_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(GZIP_DIR))
else
GZIP_COMPILE := $(FT_COMPILE)
endif
# gzip support sources
#
# All source and header files get loaded by `ftgzip.c' only if SYTEM_ZLIB is
# not defined (regardless whether we have a `single' or a `multi' build).
# However, it doesn't harm if we add everything as a dependency
# unconditionally.
#
GZIP_DRV_SRCS := $(GZIP_DIR)/adler32.c \
$(GZIP_DIR)/infblock.c \
$(GZIP_DIR)/infblock.h \
$(GZIP_DIR)/infcodes.c \
$(GZIP_DIR)/infcodes.h \
$(GZIP_DIR)/inffixed.h \
$(GZIP_DIR)/inflate.c \
$(GZIP_DIR)/inftrees.c \
$(GZIP_DIR)/inftrees.h \
$(GZIP_DIR)/infutil.c \
$(GZIP_DIR)/infutil.h \
$(GZIP_DIR)/zconf.h \
$(GZIP_DIR)/zlib.h \
$(GZIP_DIR)/zutil.c \
$(GZIP_DIR)/zutil.h
# gzip driver object(s)
#
# GZIP_DRV_OBJ is used during both `single' and `multi' builds
#
GZIP_DRV_OBJ := $(OBJ_DIR)/ftgzip.$O
# gzip main source file
#
GZIP_DRV_SRC := $(GZIP_DIR)/ftgzip.c
# gzip support - object
#
$(GZIP_DRV_OBJ): $(GZIP_DRV_SRC) $(GZIP_DRV_SRCS) $(FREETYPE_H)
$(GZIP_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(GZIP_DRV_SRC))
# update main driver object lists
#
DRV_OBJS_S += $(GZIP_DRV_OBJ)
DRV_OBJS_M += $(GZIP_DRV_OBJ)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/gzip/rules.mk | Makefile | apache-2.0 | 2,018 |
/* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#ifndef _ZCONF_H
#define _ZCONF_H
/*
* If you *really* need a unique prefix for all types and library functions,
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
*/
#ifdef Z_PREFIX
# define deflateInit_ z_deflateInit_
# define deflate z_deflate
# define deflateEnd z_deflateEnd
# define inflateInit_ z_inflateInit_
# define inflate z_inflate
# define inflateEnd z_inflateEnd
# define deflateInit2_ z_deflateInit2_
# define deflateSetDictionary z_deflateSetDictionary
# define deflateCopy z_deflateCopy
# define deflateReset z_deflateReset
# define deflateParams z_deflateParams
# define inflateInit2_ z_inflateInit2_
# define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint
# define inflateReset z_inflateReset
# define compress z_compress
# define compress2 z_compress2
# define uncompress z_uncompress
# define adler32 z_adler32
# define crc32 z_crc32
# define get_crc_table z_get_crc_table
# define Byte z_Byte
# define uInt z_uInt
# define uLong z_uLong
# define Bytef z_Bytef
# define charf z_charf
# define intf z_intf
# define uIntf z_uIntf
# define uLongf z_uLongf
# define voidpf z_voidpf
# define voidp z_voidp
#endif
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
# define WIN32
#endif
#if defined(__GNUC__) || defined(WIN32) || defined(__386__) || defined(i386)
# ifndef __32BIT__
# define __32BIT__
# endif
#endif
#if defined(__MSDOS__) && !defined(MSDOS)
# define MSDOS
#endif
/* WinCE doesn't have errno.h */
#ifdef _WIN32_WCE
# define NO_ERRNO_H
#endif
/*
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
* than 64k bytes at a time (needed on systems with 16-bit int).
*/
#if defined(MSDOS) && !defined(__32BIT__)
# define MAXSEG_64K
#endif
#ifdef MSDOS
# define UNALIGNED_OK
#endif
#if (defined(MSDOS) || defined(_WINDOWS) || defined(WIN32)) && !defined(STDC)
# define STDC
#endif
#if defined(__STDC__) || defined(__cplusplus) || defined(__OS2__)
# ifndef STDC
# define STDC
# endif
#endif
#ifndef STDC
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
# define const
# endif
#endif
/* Some Mac compilers merge all .h files incorrectly: */
#if defined(__MWERKS__) || defined(applec) ||defined(THINK_C) ||defined(__SC__)
# define NO_DUMMY_DECL
#endif
/* Old Borland C and LCC incorrectly complains about missing returns: */
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x500)
# define NEED_DUMMY_RETURN
#endif
#if defined(__LCC__)
# define NEED_DUMMY_RETURN
#endif
/* Maximum value for memLevel in deflateInit2 */
#ifndef MAX_MEM_LEVEL
# ifdef MAXSEG_64K
# define MAX_MEM_LEVEL 8
# else
# define MAX_MEM_LEVEL 9
# endif
#endif
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
* created by gzip. (Files created by minigzip can still be extracted by
* gzip.)
*/
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
/* The memory requirements for deflate are (in bytes):
(1 << (windowBits+2)) + (1 << (memLevel+9))
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes) 1 << windowBits
that is, 32K for windowBits=15 (default value) plus a few kilobytes
for small objects.
*/
/* Type declarations */
#ifndef OF /* function prototypes */
# ifdef STDC
# define OF(args) args
# else
# define OF(args) ()
# endif
#endif
/* The following definitions for FAR are needed only for MSDOS mixed
* model programming (small or medium model with some far allocations).
* This was tested only with MSC; for other MSDOS compilers you may have
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
* just define FAR to be empty.
*/
#if (defined(M_I86SM) || defined(M_I86MM)) && !defined(__32BIT__)
/* MSC small or medium model */
# define SMALL_MEDIUM
# ifdef _MSC_VER
# define FAR _far
# else
# define FAR far
# endif
#endif
#if defined(__BORLANDC__) && (defined(__SMALL__) || defined(__MEDIUM__))
# ifndef __32BIT__
# define SMALL_MEDIUM
# define FAR _far
# endif
#endif
/* Compile with -DZLIB_DLL for Windows DLL support */
#if defined(ZLIB_DLL)
# if defined(_WINDOWS) || defined(WINDOWS)
# ifdef FAR
# undef FAR
# endif
# include <windows.h>
# define ZEXPORT(x) x WINAPI
# ifdef WIN32
# define ZEXPORTVA(x) x WINAPIV
# else
# define ZEXPORTVA(x) x FAR _cdecl _export
# endif
# endif
# if defined (__BORLANDC__)
# if (__BORLANDC__ >= 0x0500) && defined (WIN32)
# include <windows.h>
# define ZEXPORT(x) x __declspec(dllexport) WINAPI
# define ZEXPORTRVA(x) x __declspec(dllexport) WINAPIV
# else
# if defined (_Windows) && defined (__DLL__)
# define ZEXPORT(x) x _export
# define ZEXPORTVA(x) x _export
# endif
# endif
# endif
#endif
#ifndef ZEXPORT
# define ZEXPORT(x) static x
#endif
#ifndef ZEXPORTVA
# define ZEXPORTVA(x) static x
#endif
#ifndef ZEXTERN
# define ZEXTERN(x) static x
#endif
#ifndef ZEXTERNDEF
# define ZEXTERNDEF(x) static x
#endif
#ifndef FAR
# define FAR
#endif
#if !defined(MACOS) && !defined(TARGET_OS_MAC)
typedef unsigned char Byte; /* 8 bits */
#endif
typedef unsigned int uInt; /* 16 bits or more */
typedef unsigned long uLong; /* 32 bits or more */
#ifdef SMALL_MEDIUM
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
# define Bytef Byte FAR
#else
typedef Byte FAR Bytef;
#endif
typedef char FAR charf;
typedef int FAR intf;
typedef uInt FAR uIntf;
typedef uLong FAR uLongf;
#ifdef STDC
typedef void FAR *voidpf;
typedef void *voidp;
#else
typedef Byte FAR *voidpf;
typedef Byte *voidp;
#endif
#ifdef HAVE_UNISTD_H
# include <sys/types.h> /* for off_t */
# include <unistd.h> /* for SEEK_* and off_t */
# define z_off_t off_t
#endif
#ifndef SEEK_SET
# define SEEK_SET 0 /* Seek from beginning of file. */
# define SEEK_CUR 1 /* Seek from current position. */
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif
#ifndef z_off_t
# define z_off_t long
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
# pragma map(deflateInit_,"DEIN")
# pragma map(deflateInit2_,"DEIN2")
# pragma map(deflateEnd,"DEEND")
# pragma map(inflateInit_,"ININ")
# pragma map(inflateInit2_,"ININ2")
# pragma map(inflateEnd,"INEND")
# pragma map(inflateSync,"INSY")
# pragma map(inflateSetDictionary,"INSEDI")
# pragma map(inflate_blocks,"INBL")
# pragma map(inflate_blocks_new,"INBLNE")
# pragma map(inflate_blocks_free,"INBLFR")
# pragma map(inflate_blocks_reset,"INBLRE")
# pragma map(inflate_codes_free,"INCOFR")
# pragma map(inflate_codes,"INCO")
# pragma map(inflate_fast,"INFA")
# pragma map(inflate_flush,"INFLU")
# pragma map(inflate_mask,"INMA")
# pragma map(inflate_set_dictionary,"INSEDI2")
# pragma map(inflate_copyright,"INCOPY")
# pragma map(inflate_trees_bits,"INTRBI")
# pragma map(inflate_trees_dynamic,"INTRDY")
# pragma map(inflate_trees_fixed,"INTRFI")
# pragma map(inflate_trees_free,"INTRFR")
#endif
#endif /* _ZCONF_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/zconf.h | C | apache-2.0 | 8,097 |
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.1.4, March 11th, 2002
Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
*/
#ifndef _ZLIB_H
#define _ZLIB_H
#include "zconf.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_VERSION "1.1.4"
/*
The 'zlib' compression library provides in-memory compression and
decompression functions, including integrity checks of the uncompressed
data. This version of the library supports only one compression method
(deflation) but other algorithms will be added later and will have the same
stream interface.
Compression can be done in a single step if the buffers are large
enough (for example if an input file is mmap'ed), or can be done by
repeated calls of the compression function. In the latter case, the
application must provide more input and/or consume the output
(providing more output space) before each call.
The library also supports reading and writing files in gzip (.gz) format
with an interface similar to that of stdio.
The library does not install any signal handler. The decoder checks
the consistency of the compressed data, so the library should never
crash even in case of corrupted input.
*/
typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
typedef void (*free_func) OF((voidpf opaque, voidpf address));
struct internal_state;
typedef struct z_stream_s {
Bytef *next_in; /* next input byte */
uInt avail_in; /* number of bytes available at next_in */
uLong total_in; /* total nb of input bytes read so far */
Bytef *next_out; /* next output byte should be put there */
uInt avail_out; /* remaining free space at next_out */
uLong total_out; /* total nb of bytes output so far */
char *msg; /* last error message, NULL if no error */
struct internal_state FAR *state; /* not visible by applications */
alloc_func zalloc; /* used to allocate the internal state */
free_func zfree; /* used to free the internal state */
voidpf opaque; /* private data object passed to zalloc and zfree */
int data_type; /* best guess about the data type: ascii or binary */
uLong adler; /* adler32 value of the uncompressed data */
uLong reserved; /* reserved for future use */
} z_stream;
typedef z_stream FAR *z_streamp;
/*
The application must update next_in and avail_in when avail_in has
dropped to zero. It must update next_out and avail_out when avail_out
has dropped to zero. The application must initialize zalloc, zfree and
opaque before calling the init function. All other fields are set by the
compression library and must not be updated by the application.
The opaque value provided by the application will be passed as the first
parameter for calls of zalloc and zfree. This can be useful for custom
memory management. The compression library attaches no meaning to the
opaque value.
zalloc must return Z_NULL if there is not enough memory for the object.
If zlib is used in a multi-threaded application, zalloc and zfree must be
thread safe.
On 16-bit systems, the functions zalloc and zfree must be able to allocate
exactly 65536 bytes, but will not be required to allocate more than this
if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
pointers returned by zalloc for objects of exactly 65536 bytes *must*
have their offset normalized to zero. The default allocation function
provided by this library ensures this (see zutil.c). To reduce memory
requirements and avoid any allocation of 64K objects, at the expense of
compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
The fields total_in and total_out can be used for statistics or
progress reports. After compression, total_in holds the total size of
the uncompressed data and may be saved for use in the decompressor
(particularly if the decompressor wants to decompress everything in
a single step).
*/
/* constants */
#define Z_NO_FLUSH 0
#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
/* Allowed flush values; see deflate() below for details */
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)
/* Return codes for the compression/decompression functions. Negative
* values are errors, positive values are used for special but normal events.
*/
#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)
/* compression levels */
#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_DEFAULT_STRATEGY 0
/* compression strategy; see deflateInit2() below for details */
#define Z_BINARY 0
#define Z_ASCII 1
#define Z_UNKNOWN 2
/* Possible values of the data_type field */
#define Z_DEFLATED 8
/* The deflate compression method (the only one supported in this version) */
#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
/* basic functions */
/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
If the first character differs, the library code actually used is
not compatible with the zlib.h header file used by the application.
This check is automatically made by deflateInit and inflateInit.
*/
/*
ZEXTERN(int) deflateInit OF((z_streamp strm, int level));
Initializes the internal stream state for compression. The fields
zalloc, zfree and opaque must be initialized before by the caller.
If zalloc and zfree are set to Z_NULL, deflateInit updates them to
use default allocation functions.
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
1 gives best speed, 9 gives best compression, 0 gives no compression at
all (the input data is simply copied a block at a time).
Z_DEFAULT_COMPRESSION requests a default compromise between speed and
compression (currently equivalent to level 6).
deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if level is not a valid compression level,
Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
with the version assumed by the caller (ZLIB_VERSION).
msg is set to null if there is no error message. deflateInit does not
perform any compression: this will be done by deflate().
*/
/*
deflate compresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may introduce some
output latency (reading input without producing any output) except when
forced to flush.
The detailed semantics are as follows. deflate performs one or both of the
following actions:
- Compress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), next_in and avail_in are updated and
processing will resume at this point for the next call of deflate().
- Provide more output starting at next_out and update next_out and avail_out
accordingly. This action is forced if the parameter flush is non zero.
Forcing flush frequently degrades the compression ratio, so this parameter
should be set only when necessary (in interactive applications).
Some output may be provided even if flush is not set.
Before the call of deflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming
more output, and updating avail_in or avail_out accordingly; avail_out
should never be zero before the call. The application can consume the
compressed output when it wants, for example when the output buffer is full
(avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
and with zero avail_out, it must be called again after making room in the
output buffer because there might be more output pending.
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
flushed to the output buffer and the output is aligned on a byte boundary, so
that the decompressor can get all input data available so far. (In particular
avail_in is zero after the call if enough output space has been provided
before the call.) Flushing may degrade compression for some compression
algorithms and so it should be used only when necessary.
If flush is set to Z_FULL_FLUSH, all output is flushed as with
Z_SYNC_FLUSH, and the compression state is reset so that decompression can
restart from this point if previous compressed data has been damaged or if
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
the compression.
If deflate returns with avail_out == 0, this function must be called again
with the same value of the flush parameter and more output space (updated
avail_out), until the flush is complete (deflate returns with non-zero
avail_out).
If the parameter flush is set to Z_FINISH, pending input is processed,
pending output is flushed and deflate returns with Z_STREAM_END if there
was enough output space; if deflate returns with Z_OK, this function must be
called again with Z_FINISH and more output space (updated avail_out) but no
more input data, until it returns with Z_STREAM_END or an error. After
deflate has returned Z_STREAM_END, the only possible operations on the
stream are deflateReset or deflateEnd.
Z_FINISH can be used immediately after deflateInit if all the compression
is to be done in a single step. In this case, avail_out must be at least
0.1% larger than avail_in plus 12 bytes. If deflate does not return
Z_STREAM_END, then it must be called again as described above.
deflate() sets strm->adler to the adler32 checksum of all input read
so far (that is, total_in bytes).
deflate() may update data_type if it can make a good guess about
the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
binary. This field is only for information purposes and does not affect
the compression algorithm in any manner.
deflate() returns Z_OK if some progress has been made (more input
processed or more output produced), Z_STREAM_END if all input has been
consumed and all output has been produced (only when flush is set to
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
(for example avail_in or avail_out was zero).
*/
/*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any
pending output.
deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
stream state was inconsistent, Z_DATA_ERROR if the stream was freed
prematurely (some input or output was discarded). In the error case,
msg may be set but then points to a static string (which must not be
deallocated).
*/
/*
ZEXTERN(int) inflateInit OF((z_streamp strm));
Initializes the internal stream state for decompression. The fields
next_in, avail_in, zalloc, zfree and opaque must be initialized before by
the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
value depends on the compression method), inflateInit determines the
compression method from the zlib header and allocates all data structures
accordingly; otherwise the allocation will be deferred to the first call of
inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
use default allocation functions.
inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
version assumed by the caller. msg is set to null if there is no error
message. inflateInit does not perform any decompression apart from reading
the zlib header if present: this will be done by inflate(). (So next_in and
avail_in may be modified, but next_out and avail_out are unchanged.)
*/
ZEXTERN(int) inflate OF((z_streamp strm, int flush));
/*
inflate decompresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may some
introduce some output latency (reading input without producing any output)
except when forced to flush.
The detailed semantics are as follows. inflate performs one or both of the
following actions:
- Decompress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), next_in is updated and processing
will resume at this point for the next call of inflate().
- Provide more output starting at next_out and update next_out and avail_out
accordingly. inflate() provides as much output as possible, until there
is no more input data or no more space in the output buffer (see below
about the flush parameter).
Before the call of inflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming
more output, and updating the next_* and avail_* values accordingly.
The application can consume the uncompressed output when it wants, for
example when the output buffer is full (avail_out == 0), or after each
call of inflate(). If inflate returns Z_OK and with zero avail_out, it
must be called again after making room in the output buffer because there
might be more output pending.
If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
output as possible to the output buffer. The flushing behavior of inflate is
not specified for values of the flush parameter other than Z_SYNC_FLUSH
and Z_FINISH, but the current implementation actually flushes as much output
as possible anyway.
inflate() should normally be called until it returns Z_STREAM_END or an
error. However if all decompression is to be performed in a single step
(a single call of inflate), the parameter flush should be set to
Z_FINISH. In this case all pending input is processed and all pending
output is flushed; avail_out must be large enough to hold all the
uncompressed data. (The size of the uncompressed data may have been saved
by the compressor for this purpose.) The next operation on this stream must
be inflateEnd to deallocate the decompression state. The use of Z_FINISH
is never required, but can be used to inform inflate that a faster routine
may be used for the single inflate() call.
If a preset dictionary is needed at this point (see inflateSetDictionary
below), inflate sets strm-adler to the adler32 checksum of the
dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
it sets strm->adler to the adler32 checksum of all output produced
so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
an error code as described below. At the end of the stream, inflate()
checks that its computed adler32 checksum is equal to that saved by the
compressor and returns Z_STREAM_END only if the checksum is correct.
inflate() returns Z_OK if some progress has been made (more input processed
or more output produced), Z_STREAM_END if the end of the compressed data has
been reached and all uncompressed output has been produced, Z_NEED_DICT if a
preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
corrupted (input stream not conforming to the zlib format or incorrect
adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
(for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if no progress is possible or if there was not
enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
case, the application may then call inflateSync to look for a good
compression block.
*/
ZEXTERN(int) inflateEnd OF((z_streamp strm));
/*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any
pending output.
inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
was inconsistent. In the error case, msg may be set but then points to a
static string (which must not be deallocated).
*/
/* Advanced functions */
/*
The following functions are needed only in some special applications.
*/
/*
ZEXTERN(int) deflateInit2 OF((z_streamp strm,
int level,
int method,
int windowBits,
int memLevel,
int strategy));
This is another version of deflateInit with more compression options. The
fields next_in, zalloc, zfree and opaque must be initialized before by
the caller.
The method parameter is the compression method. It must be Z_DEFLATED in
this version of the library.
The windowBits parameter is the base two logarithm of the window size
(the size of the history buffer). It should be in the range 8..15 for this
version of the library. Larger values of this parameter result in better
compression at the expense of memory usage. The default value is 15 if
deflateInit is used instead.
The memLevel parameter specifies how much memory should be allocated
for the internal compression state. memLevel=1 uses minimum memory but
is slow and reduces compression ratio; memLevel=9 uses maximum memory
for optimal speed. The default value is 8. See zconf.h for total memory
usage as a function of windowBits and memLevel.
The strategy parameter is used to tune the compression algorithm. Use the
value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
string match). Filtered data consists mostly of small values with a
somewhat random distribution. In this case, the compression algorithm is
tuned to compress them better. The effect of Z_FILTERED is to force more
Huffman coding and less string matching; it is somewhat intermediate
between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
the compression ratio but not the correctness of the compressed output even
if it is not set appropriately.
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
method). msg is set to null if there is no error message. deflateInit2 does
not perform any compression: this will be done by deflate().
*/
/*
Initializes the compression dictionary from the given byte sequence
without producing any compressed output. This function must be called
immediately after deflateInit, deflateInit2 or deflateReset, before any
call of deflate. The compressor and decompressor must use exactly the same
dictionary (see inflateSetDictionary).
The dictionary should consist of strings (byte sequences) that are likely
to be encountered later in the data to be compressed, with the most commonly
used strings preferably put towards the end of the dictionary. Using a
dictionary is most useful when the data to be compressed is short and can be
predicted with good accuracy; the data can then be compressed better than
with the default empty dictionary.
Depending on the size of the compression data structures selected by
deflateInit or deflateInit2, a part of the dictionary may in effect be
discarded, for example if the dictionary is larger than the window size in
deflate or deflate2. Thus the strings most likely to be useful should be
put at the end of the dictionary, not at the front.
Upon return of this function, strm->adler is set to the Adler32 value
of the dictionary; the decompressor may later use this value to determine
which dictionary has been used by the compressor. (The Adler32 value
applies to the whole dictionary even if only a subset of the dictionary is
actually used by the compressor.)
deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
parameter is invalid (such as NULL dictionary) or the stream state is
inconsistent (for example if deflate has already been called for this stream
or if the compression method is bsort). deflateSetDictionary does not
perform any compression: this will be done by deflate().
*/
/*
Sets the destination stream as a complete copy of the source stream.
This function can be useful when several compression strategies will be
tried, for example when there are several ways of pre-processing the input
data with a filter. The streams that will be discarded should then be freed
by calling deflateEnd. Note that deflateCopy duplicates the internal
compression state which can be quite large, so this strategy is slow and
can consume lots of memory.
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being NULL). msg is left unchanged in both source and
destination.
*/
/*
This function is equivalent to deflateEnd followed by deflateInit,
but does not free and reallocate all the internal compression state.
The stream will keep the same compression level and any other attributes
that may have been set by deflateInit2.
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being NULL).
*/
/*
Dynamically update the compression level and compression strategy. The
interpretation of level and strategy is as in deflateInit2. This can be
used to switch between compression and straight copy of the input data, or
to switch to a different kind of input data requiring a different
strategy. If the compression level is changed, the input available so far
is compressed with the old level (and may be flushed); the new level will
take effect only at the next call of deflate().
Before the call of deflateParams, the stream state must be set as for
a call of deflate(), since the currently available input may have to
be compressed and flushed. In particular, strm->avail_out must be non-zero.
deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
if strm->avail_out was zero.
*/
/*
ZEXTERN(int) inflateInit2 OF((z_streamp strm,
int windowBits));
This is another version of inflateInit with an extra parameter. The
fields next_in, avail_in, zalloc, zfree and opaque must be initialized
before by the caller.
The windowBits parameter is the base two logarithm of the maximum window
size (the size of the history buffer). It should be in the range 8..15 for
this version of the library. The default value is 15 if inflateInit is used
instead. If a compressed stream with a larger window size is given as
input, inflate() will return with the error code Z_DATA_ERROR instead of
trying to allocate a larger window.
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
memLevel). msg is set to null if there is no error message. inflateInit2
does not perform any decompression apart from reading the zlib header if
present: this will be done by inflate(). (So next_in and avail_in may be
modified, but next_out and avail_out are unchanged.)
*/
/*
Initializes the decompression dictionary from the given uncompressed byte
sequence. This function must be called immediately after a call of inflate
if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
can be determined from the Adler32 value returned by this call of
inflate. The compressor and decompressor must use exactly the same
dictionary (see deflateSetDictionary).
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
parameter is invalid (such as NULL dictionary) or the stream state is
inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
expected one (incorrect Adler32 value). inflateSetDictionary does not
perform any decompression: this will be done by subsequent calls of
inflate().
*/
/*
Skips invalid compressed data until a full flush point (see above the
description of deflate with Z_FULL_FLUSH) can be found, or until all
available input is skipped. No output is provided.
inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
if no more input was provided, Z_DATA_ERROR if no flush point has been found,
or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
case, the application may save the current current value of total_in which
indicates where valid compressed data was found. In the error case, the
application may repeatedly call inflateSync, providing more input each time,
until success or end of the input data.
*/
ZEXTERN(int) inflateReset OF((z_streamp strm));
/*
This function is equivalent to inflateEnd followed by inflateInit,
but does not free and reallocate all the internal decompression state.
The stream will keep attributes that may have been set by inflateInit2.
inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being NULL).
*/
/* utility functions */
/*
The following utility functions are implemented on top of the
basic stream-oriented functions. To simplify the interface, some
default options are assumed (compression level and memory usage,
standard memory allocation functions). The source code of these
utility functions can easily be modified if you need special options.
*/
/*
Compresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be at least 0.1% larger than
sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
compressed buffer.
This function can be used to compress a whole file at once if the
input file is mmap'ed.
compress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer.
*/
/*
Compresses the source buffer into the destination buffer. The level
parameter has the same meaning as in deflateInit. sourceLen is the byte
length of the source buffer. Upon entry, destLen is the total size of the
destination buffer, which must be at least 0.1% larger than sourceLen plus
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
Z_STREAM_ERROR if the level parameter is invalid.
*/
/*
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be large enough to hold the
entire uncompressed data. (The size of the uncompressed data must have
been saved previously by the compressor and transmitted to the decompressor
by some mechanism outside the scope of this compression library.)
Upon exit, destLen is the actual size of the compressed buffer.
This function can be used to decompress a whole file at once if the
input file is mmap'ed.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted.
*/
/*
Opens a gzip (.gz) file for reading or writing. The mode parameter
is as in fopen ("rb" or "wb") but can also include a compression level
("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
Huffman only compression as in "wb1h". (See the description
of deflateInit2 for more information about the strategy parameter.)
gzopen can be used to read a file which is not in gzip format; in this
case gzread will directly read from the file without decompression.
gzopen returns NULL if the file could not be opened or if there was
insufficient memory to allocate the (de)compression state; errno
can be checked to distinguish the two cases (if errno is zero, the
zlib error is Z_MEM_ERROR). */
/*
gzdopen() associates a gzFile with the file descriptor fd. File
descriptors are obtained from calls like open, dup, creat, pipe or
fileno (in the file has been previously opened with fopen).
The mode parameter is as in gzopen.
The next call of gzclose on the returned gzFile will also close the
file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
gzdopen returns NULL if there was insufficient memory to allocate
the (de)compression state.
*/
/*
Dynamically update the compression level or strategy. See the description
of deflateInit2 for the meaning of these parameters.
gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
opened for writing.
*/
/*
Reads the given number of uncompressed bytes from the compressed file.
If the input file was not in gzip format, gzread copies the given number
of bytes into the buffer.
gzread returns the number of uncompressed bytes actually read (0 for
end of file, -1 for error). */
/*
Writes the given number of uncompressed bytes into the compressed file.
gzwrite returns the number of uncompressed bytes actually written
(0 in case of error).
*/
/*
Converts, formats, and writes the args to the compressed file under
control of the format string, as in fprintf. gzprintf returns the number of
uncompressed bytes actually written (0 in case of error).
*/
/*
Writes the given null-terminated string to the compressed file, excluding
the terminating null character.
gzputs returns the number of characters written, or -1 in case of error.
*/
/*
Reads bytes from the compressed file until len-1 characters are read, or
a newline character is read and transferred to buf, or an end-of-file
condition is encountered. The string is then terminated with a null
character.
gzgets returns buf, or Z_NULL in case of error.
*/
/*
Writes c, converted to an unsigned char, into the compressed file.
gzputc returns the value that was written, or -1 in case of error.
*/
/*
Reads one byte from the compressed file. gzgetc returns this byte
or -1 in case of end of file or error.
*/
/*
Flushes all pending output into the compressed file. The parameter
flush is as in the deflate() function. The return value is the zlib
error number (see function gzerror below). gzflush returns Z_OK if
the flush parameter is Z_FINISH and all output could be flushed.
gzflush should be called only when strictly necessary because it can
degrade compression.
*/
/*
Sets the starting position for the next gzread or gzwrite on the
given compressed file. The offset represents a number of bytes in the
uncompressed data stream. The whence parameter is defined as in lseek(2);
the value SEEK_END is not supported.
If the file is opened for reading, this function is emulated but can be
extremely slow. If the file is opened for writing, only forward seeks are
supported; gzseek then compresses a sequence of zeroes up to the new
starting position.
gzseek returns the resulting offset location as measured in bytes from
the beginning of the uncompressed stream, or -1 in case of error, in
particular if the file is opened for writing and the new starting position
would be before the current position.
*/
/*
Rewinds the given file. This function is supported only for reading.
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
*/
/*
Returns the starting position for the next gzread or gzwrite on the
given compressed file. This position represents a number of bytes in the
uncompressed data stream.
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
*/
/*
Returns 1 when EOF has previously been detected reading the given
input stream, otherwise zero.
*/
/*
Flushes all pending output if necessary, closes the compressed file
and deallocates all the (de)compression state. The return value is the zlib
error number (see function gzerror below).
*/
/*
Returns the error message for the last error which occurred on the
given compressed file. errnum is set to zlib error number. If an
error occurred in the file system and not in the compression library,
errnum is set to Z_ERRNO and the application may consult errno
to get the exact error code.
*/
/* checksum functions */
/*
These functions are not related to compression but are exported
anyway because they might be useful in applications using the
compression library.
*/
ZEXTERN(uLong) adler32 OF((uLong adler, const Bytef *buf, uInt len));
/*
Update a running Adler-32 checksum with the bytes buf[0..len-1] and
return the updated checksum. If buf is NULL, this function returns
the required initial value for the checksum.
An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
much faster. Usage example:
uLong adler = adler32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
adler = adler32(adler, buffer, length);
}
if (adler != original_adler) error();
*/
/*
Update a running crc with the bytes buf[0..len-1] and return the updated
crc. If buf is NULL, this function returns the required initial value
for the crc. Pre- and post-conditioning (one's complement) is performed
within this function so it shouldn't be done by the application.
Usage example:
uLong crc = crc32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
crc = crc32(crc, buffer, length);
}
if (crc != original_crc) error();
*/
/* various hacks, don't look :) */
/* deflateInit and inflateInit are macros to allow checking the zlib version
* and the compiler's view of z_stream:
*/
ZEXTERN(int) inflateInit2_ OF((z_streamp strm, int windowBits,
const char *version, int stream_size));
#define deflateInit(strm, level) \
deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
#define inflateInit(strm) \
inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
(strategy), ZLIB_VERSION, sizeof(z_stream))
#define inflateInit2(strm, windowBits) \
inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
#ifdef __cplusplus
}
#endif
#endif /* _ZLIB_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/zlib.h | C++ | apache-2.0 | 37,304 |
/* zutil.c -- target dependent utility functions for the compression library
* Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "zutil.h"
#ifndef STDC
extern void exit OF((int));
#endif
#ifndef HAVE_MEMCPY
void zmemcpy(dest, source, len)
Bytef* dest;
const Bytef* source;
uInt len;
{
if (len == 0) return;
do {
*dest++ = *source++; /* ??? to be unrolled */
} while (--len != 0);
}
int zmemcmp(s1, s2, len)
const Bytef* s1;
const Bytef* s2;
uInt len;
{
uInt j;
for (j = 0; j < len; j++) {
if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
}
return 0;
}
void zmemzero(dest, len)
Bytef* dest;
uInt len;
{
if (len == 0) return;
do {
*dest++ = 0; /* ??? to be unrolled */
} while (--len != 0);
}
#endif
#if defined( MSDOS ) && defined( __TURBOC__ ) && !defined( MY_ZCALLOC )
#if (defined( __BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__)
/* Small and medium model in Turbo C are for now limited to near allocation
* with reduced MAX_WBITS and MAX_MEM_LEVEL
*/
# define MY_ZCALLOC
/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
* and farmalloc(64K) returns a pointer with an offset of 8, so we
* must fix the pointer. Warning: the pointer must be put back to its
* original form in order to free it, use zcfree().
*/
#define MAX_PTR 10
/* 10*64K = 640K */
local int next_ptr = 0;
typedef struct ptr_table_s {
voidpf org_ptr;
voidpf new_ptr;
} ptr_table;
local ptr_table table[MAX_PTR];
/* This table is used to remember the original form of pointers
* to large buffers (64K). Such pointers are normalized with a zero offset.
* Since MSDOS is not a preemptive multitasking OS, this table is not
* protected from concurrent access. This hack doesn't work anyway on
* a protected system like OS/2. Use Microsoft C instead.
*/
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
{
voidpf buf = opaque; /* just to make some compilers happy */
ulg bsize = (ulg)items*size;
/* If we allocate less than 65520 bytes, we assume that farmalloc
* will return a usable pointer which doesn't have to be normalized.
*/
if (bsize < 65520L) {
buf = farmalloc(bsize);
if (*(ush*)&buf != 0) return buf;
} else {
buf = farmalloc(bsize + 16L);
}
if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
table[next_ptr].org_ptr = buf;
/* Normalize the pointer to seg:0 */
*((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
*(ush*)&buf = 0;
table[next_ptr++].new_ptr = buf;
return buf;
}
void zcfree (voidpf opaque, voidpf ptr)
{
int n;
if (*(ush*)&ptr != 0) { /* object < 64K */
farfree(ptr);
return;
}
/* Find the original pointer */
for (n = 0; n < next_ptr; n++) {
if (ptr != table[n].new_ptr) continue;
farfree(table[n].org_ptr);
while (++n < next_ptr) {
table[n-1] = table[n];
}
next_ptr--;
return;
}
ptr = opaque; /* just to make some compilers happy */
Assert(0, "zcfree: ptr not found");
}
#endif
#endif /* MSDOS && __TURBOC__ */
#if defined(M_I86) && !defined(__32BIT__) && !defined( MY_ZCALLOC )
/* Microsoft C in 16-bit mode */
# define MY_ZCALLOC
#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
# define _halloc halloc
# define _hfree hfree
#endif
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
{
if (opaque) opaque = 0; /* to make compiler happy */
return _halloc((long)items, size);
}
void zcfree (voidpf opaque, voidpf ptr)
{
if (opaque) opaque = 0; /* to make compiler happy */
_hfree(ptr);
}
#endif /* MSC */
#ifndef MY_ZCALLOC /* Any system without a special alloc function */
#ifndef STDC
extern voidp ft_scalloc OF((uInt items, uInt size));
extern void ft_sfree OF((voidpf ptr));
#endif
voidpf zcalloc (opaque, items, size)
voidpf opaque;
unsigned items;
unsigned size;
{
if (opaque) items += size - size; /* make compiler happy */
return (voidpf)ft_scalloc(items, size);
}
void zcfree (opaque, ptr)
voidpf opaque;
voidpf ptr;
{
ft_sfree(ptr);
if (opaque) return; /* make compiler happy */
}
#endif /* MY_ZCALLOC */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/zutil.c | C | apache-2.0 | 4,370 |
/* zutil.h -- internal interface and configuration of the compression library
* Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef _Z_UTIL_H
#define _Z_UTIL_H
#include "zlib.h"
#ifdef STDC
# include <stddef.h>
# include <string.h>
# include <stdlib.h>
#endif
#ifdef NO_ERRNO_H
extern int errno;
#else
# include <errno.h>
#endif
#ifndef local
# define local static
#endif
/* compile with -Dlocal if your debugger can't find static symbols */
typedef unsigned char uch;
typedef uch FAR uchf;
typedef unsigned short ush;
typedef ush FAR ushf;
typedef unsigned long ulg;
#define ERR_RETURN(strm,err) \
return (strm->msg = (char*)ERR_MSG(err), (err))
/* To be used only when the state is known to be valid */
/* common constants */
#ifndef DEF_WBITS
# define DEF_WBITS MAX_WBITS
#endif
/* default windowBits for decompression. MAX_WBITS is for compression only */
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
/* default memLevel */
#define STORED_BLOCK 0
#define STATIC_TREES 1
#define DYN_TREES 2
/* The three kinds of block type */
#define MIN_MATCH 3
#define MAX_MATCH 258
/* The minimum and maximum match lengths */
#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
/* target dependencies */
#ifdef MSDOS
# define OS_CODE 0x00
# if defined(__TURBOC__) || defined(__BORLANDC__)
# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
/* Allow compilation with ANSI keywords only enabled */
void _Cdecl farfree( void *block );
void *_Cdecl farmalloc( unsigned long nbytes );
# else
# include <alloc.h>
# endif
# else /* MSC or DJGPP */
# endif
#endif
#ifdef OS2
# define OS_CODE 0x06
#endif
#ifdef WIN32 /* Window 95 & Windows NT */
# define OS_CODE 0x0b
#endif
#if defined(VAXC) || defined(VMS)
# define OS_CODE 0x02
# define F_OPEN(name, mode) \
ft_fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
#endif
#ifdef AMIGA
# define OS_CODE 0x01
#endif
#if defined(ATARI) || defined(atarist)
# define OS_CODE 0x05
#endif
#if defined(MACOS) || defined(TARGET_OS_MAC)
# define OS_CODE 0x07
# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
# include <unix.h> /* for fdopen */
# else
# ifndef fdopen
# define fdopen(fd,mode) NULL /* No fdopen() */
# endif
# endif
#endif
#ifdef __50SERIES /* Prime/PRIMOS */
# define OS_CODE 0x0F
#endif
#ifdef TOPS20
# define OS_CODE 0x0a
#endif
#if defined(_BEOS_) || defined(RISCOS)
# define fdopen(fd,mode) NULL /* No fdopen() */
#endif
#if (defined(_MSC_VER) && (_MSC_VER > 600))
# define fdopen(fd,type) _fdopen(fd,type)
#endif
/* Common defaults */
#ifndef OS_CODE
# define OS_CODE 0x03 /* assume Unix */
#endif
#ifndef F_OPEN
# define F_OPEN(name, mode) ft_fopen((name), (mode))
#endif
/* functions */
#ifdef HAVE_STRERROR
extern char *strerror OF((int));
# define zstrerror(errnum) strerror(errnum)
#else
# define zstrerror(errnum) ""
#endif
#if defined(pyr)
# define NO_MEMCPY
#endif
#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
/* Use our own functions for small and medium model with MSC <= 5.0.
* You may have to use the same strategy for Borland C (untested).
* The __SC__ check is for Symantec.
*/
# define NO_MEMCPY
#endif
#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
# define HAVE_MEMCPY
#endif
#ifdef HAVE_MEMCPY
# ifdef SMALL_MEDIUM /* MSDOS small or medium model */
# define zmemcpy _fmemcpy
# define zmemcmp _fmemcmp
# define zmemzero(dest, len) _fmemset(dest, 0, len)
# else
# define zmemcpy ft_memcpy
# define zmemcmp ft_memcmp
# define zmemzero(dest, len) ft_memset(dest, 0, len)
# endif
#else
extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
extern void zmemzero OF((Bytef* dest, uInt len));
#endif
#undef DEBUG
/* Diagnostic functions */
#ifdef DEBUG
# include <stdio.h>
extern int z_verbose;
extern void z_error OF((char *m));
# define Assert(cond,msg) {if(!(cond)) z_error(msg);}
# define Trace(x) {if (z_verbose>=0) fprintf x ;}
# define Tracev(x) {if (z_verbose>0) fprintf x ;}
# define Tracevv(x) {if (z_verbose>1) fprintf x ;}
# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
#else
# define Assert(cond,msg)
# define Trace(x)
# define Tracev(x)
# define Tracevv(x)
# define Tracec(c,x)
# define Tracecv(c,x)
#endif
typedef uLong (*check_func) OF((uLong check, const Bytef *buf,
uInt len));
local voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
local void zcfree OF((voidpf opaque, voidpf ptr));
#define ZALLOC(strm, items, size) \
(*((strm)->zalloc))((strm)->opaque, (items), (size))
#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
#endif /* _Z_UTIL_H */
| YifuLiu/AliOS-Things | components/freetype/src/gzip/zutil.h | C | apache-2.0 | 5,416 |
/***************************************************************************/
/* */
/* ftlzw.c */
/* */
/* FreeType support for .Z compressed files. */
/* */
/* This optional component relies on NetBSD's zopen(). It should mainly */
/* be used to parse compressed PCF fonts, as found with many X11 server */
/* distributions. */
/* */
/* Copyright 2004-2006, 2009, 2010, 2012, 2013 by */
/* Albert Chin-A-Young. */
/* */
/* Based on code in src/gzip/ftgzip.c, Copyright 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_INTERNAL_MEMORY_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_DEBUG_H
#include FT_LZW_H
#include FT_CONFIG_STANDARD_LIBRARY_H
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX LZW_Err_
#define FT_ERR_BASE FT_Mod_Err_LZW
#include FT_ERRORS_H
#ifdef FT_CONFIG_OPTION_USE_LZW
#ifdef FT_CONFIG_OPTION_PIC
#error "lzw code does not support PIC yet"
#endif
#include "ftzopen.h"
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** M E M O R Y M A N A G E M E N T *****/
/***** *****/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** F I L E D E S C R I P T O R *****/
/***** *****/
/***************************************************************************/
/***************************************************************************/
#define FT_LZW_BUFFER_SIZE 4096
typedef struct FT_LZWFileRec_
{
FT_Stream source; /* parent/source stream */
FT_Stream stream; /* embedding stream */
FT_Memory memory; /* memory allocator */
FT_LzwStateRec lzw; /* lzw decompressor state */
FT_Byte buffer[FT_LZW_BUFFER_SIZE]; /* output buffer */
FT_ULong pos; /* position in output */
FT_Byte* cursor;
FT_Byte* limit;
} FT_LZWFileRec, *FT_LZWFile;
/* check and skip .Z header */
static FT_Error
ft_lzw_check_header( FT_Stream stream )
{
FT_Error error;
FT_Byte head[2];
if ( FT_STREAM_SEEK( 0 ) ||
FT_STREAM_READ( head, 2 ) )
goto Exit;
/* head[0] && head[1] are the magic numbers */
if ( head[0] != 0x1f ||
head[1] != 0x9d )
error = FT_THROW( Invalid_File_Format );
Exit:
return error;
}
static FT_Error
ft_lzw_file_init( FT_LZWFile zip,
FT_Stream stream,
FT_Stream source )
{
FT_LzwState lzw = &zip->lzw;
FT_Error error;
zip->stream = stream;
zip->source = source;
zip->memory = stream->memory;
zip->limit = zip->buffer + FT_LZW_BUFFER_SIZE;
zip->cursor = zip->limit;
zip->pos = 0;
/* check and skip .Z header */
error = ft_lzw_check_header( source );
if ( error )
goto Exit;
/* initialize internal lzw variable */
ft_lzwstate_init( lzw, source );
Exit:
return error;
}
static void
ft_lzw_file_done( FT_LZWFile zip )
{
/* clear the rest */
ft_lzwstate_done( &zip->lzw );
zip->memory = NULL;
zip->source = NULL;
zip->stream = NULL;
}
static FT_Error
ft_lzw_file_reset( FT_LZWFile zip )
{
FT_Stream stream = zip->source;
FT_Error error;
if ( !FT_STREAM_SEEK( 0 ) )
{
ft_lzwstate_reset( &zip->lzw );
zip->limit = zip->buffer + FT_LZW_BUFFER_SIZE;
zip->cursor = zip->limit;
zip->pos = 0;
}
return error;
}
static FT_Error
ft_lzw_file_fill_output( FT_LZWFile zip )
{
FT_LzwState lzw = &zip->lzw;
FT_ULong count;
FT_Error error = FT_Err_Ok;
zip->cursor = zip->buffer;
count = ft_lzwstate_io( lzw, zip->buffer, FT_LZW_BUFFER_SIZE );
zip->limit = zip->cursor + count;
if ( count == 0 )
error = FT_THROW( Invalid_Stream_Operation );
return error;
}
/* fill output buffer; `count' must be <= FT_LZW_BUFFER_SIZE */
static FT_Error
ft_lzw_file_skip_output( FT_LZWFile zip,
FT_ULong count )
{
FT_Error error = FT_Err_Ok;
/* first, we skip what we can from the output buffer */
{
FT_ULong delta = (FT_ULong)( zip->limit - zip->cursor );
if ( delta >= count )
delta = count;
zip->cursor += delta;
zip->pos += delta;
count -= delta;
}
/* next, we skip as many bytes remaining as possible */
while ( count > 0 )
{
FT_ULong delta = FT_LZW_BUFFER_SIZE;
FT_ULong numread;
if ( delta > count )
delta = count;
numread = ft_lzwstate_io( &zip->lzw, NULL, delta );
if ( numread < delta )
{
/* not enough bytes */
error = FT_THROW( Invalid_Stream_Operation );
break;
}
zip->pos += delta;
count -= delta;
}
return error;
}
static FT_ULong
ft_lzw_file_io( FT_LZWFile zip,
FT_ULong pos,
FT_Byte* buffer,
FT_ULong count )
{
FT_ULong result = 0;
FT_Error error;
/* seeking backwards. */
if ( pos < zip->pos )
{
/* If the new position is within the output buffer, simply */
/* decrement pointers, otherwise we reset the stream completely! */
if ( ( zip->pos - pos ) <= (FT_ULong)( zip->cursor - zip->buffer ) )
{
zip->cursor -= zip->pos - pos;
zip->pos = pos;
}
else
{
error = ft_lzw_file_reset( zip );
if ( error )
goto Exit;
}
}
/* skip unwanted bytes */
if ( pos > zip->pos )
{
error = ft_lzw_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 + result, zip->cursor, delta );
result += delta;
zip->cursor += delta;
zip->pos += delta;
count -= delta;
if ( count == 0 )
break;
error = ft_lzw_file_fill_output( zip );
if ( error )
break;
}
Exit:
return result;
}
/***************************************************************************/
/***************************************************************************/
/***** *****/
/***** L Z W E M B E D D I N G S T R E A M *****/
/***** *****/
/***************************************************************************/
/***************************************************************************/
static void
ft_lzw_stream_close( FT_Stream stream )
{
FT_LZWFile zip = (FT_LZWFile)stream->descriptor.pointer;
FT_Memory memory = stream->memory;
if ( zip )
{
/* finalize lzw file descriptor */
ft_lzw_file_done( zip );
FT_FREE( zip );
stream->descriptor.pointer = NULL;
}
}
static FT_ULong
ft_lzw_stream_io( FT_Stream stream,
FT_ULong pos,
FT_Byte* buffer,
FT_ULong count )
{
FT_LZWFile zip = (FT_LZWFile)stream->descriptor.pointer;
return ft_lzw_file_io( zip, pos, buffer, count );
}
FT_EXPORT_DEF( FT_Error )
FT_Stream_OpenLZW( FT_Stream stream,
FT_Stream source )
{
FT_Error error;
FT_Memory memory = source->memory;
FT_LZWFile zip = NULL;
/*
* Check the header right now; this prevents allocation of a huge
* LZWFile object (400 KByte of heap memory) if not necessary.
*
* Did I mention that you should never use .Z compressed font
* files?
*/
error = ft_lzw_check_header( source );
if ( error )
goto Exit;
FT_ZERO( stream );
stream->memory = memory;
if ( !FT_NEW( zip ) )
{
error = ft_lzw_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_lzw_stream_io;
stream->close = ft_lzw_stream_close;
Exit:
return error;
}
#include "ftzopen.c"
#else /* !FT_CONFIG_OPTION_USE_LZW */
FT_EXPORT_DEF( FT_Error )
FT_Stream_OpenLZW( FT_Stream stream,
FT_Stream source )
{
FT_UNUSED( stream );
FT_UNUSED( source );
return FT_THROW( Unimplemented_Feature );
}
#endif /* !FT_CONFIG_OPTION_USE_LZW */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/lzw/ftlzw.c | C | apache-2.0 | 10,870 |
/***************************************************************************/
/* */
/* ftzopen.c */
/* */
/* FreeType support for .Z compressed files. */
/* */
/* This optional component relies on NetBSD's zopen(). It should mainly */
/* be used to parse compressed PCF fonts, as found with many X11 server */
/* distributions. */
/* */
/* Copyright 2005-2007, 2009, 2011 by David Turner. */
/* */
/* 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 "ftzopen.h"
#include FT_INTERNAL_MEMORY_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_DEBUG_H
static int
ft_lzwstate_refill( FT_LzwState state )
{
FT_ULong count;
if ( state->in_eof )
return -1;
count = FT_Stream_TryRead( state->source,
state->buf_tab,
state->num_bits ); /* WHY? */
state->buf_size = (FT_UInt)count;
state->buf_total += count;
state->in_eof = FT_BOOL( count < state->num_bits );
state->buf_offset = 0;
state->buf_size = ( state->buf_size << 3 ) - ( state->num_bits - 1 );
if ( count == 0 ) /* end of file */
return -1;
return 0;
}
static FT_Int32
ft_lzwstate_get_code( FT_LzwState state )
{
FT_UInt num_bits = state->num_bits;
FT_Int offset = state->buf_offset;
FT_Byte* p;
FT_Int result;
if ( state->buf_clear ||
offset >= state->buf_size ||
state->free_ent >= state->free_bits )
{
if ( state->free_ent >= state->free_bits )
{
state->num_bits = ++num_bits;
state->free_bits = state->num_bits < state->max_bits
? (FT_UInt)( ( 1UL << num_bits ) - 256 )
: state->max_free + 1;
}
if ( state->buf_clear )
{
state->num_bits = num_bits = LZW_INIT_BITS;
state->free_bits = (FT_UInt)( ( 1UL << num_bits ) - 256 );
state->buf_clear = 0;
}
if ( ft_lzwstate_refill( state ) < 0 )
return -1;
offset = 0;
}
state->buf_offset = offset + num_bits;
p = &state->buf_tab[offset >> 3];
offset &= 7;
result = *p++ >> offset;
offset = 8 - offset;
num_bits -= offset;
if ( num_bits >= 8 )
{
result |= *p++ << offset;
offset += 8;
num_bits -= 8;
}
if ( num_bits > 0 )
result |= ( *p & LZW_MASK( num_bits ) ) << offset;
return result;
}
/* grow the character stack */
static int
ft_lzwstate_stack_grow( FT_LzwState state )
{
if ( state->stack_top >= state->stack_size )
{
FT_Memory memory = state->memory;
FT_Error error;
FT_Offset old_size = state->stack_size;
FT_Offset new_size = old_size;
new_size = new_size + ( new_size >> 1 ) + 4;
if ( state->stack == state->stack_0 )
{
state->stack = NULL;
old_size = 0;
}
/* requirement of the character stack larger than 1<<LZW_MAX_BITS */
/* implies bug in the decompression code */
if ( new_size > ( 1 << LZW_MAX_BITS ) )
{
new_size = 1 << LZW_MAX_BITS;
if ( new_size == old_size )
return -1;
}
if ( FT_RENEW_ARRAY( state->stack, old_size, new_size ) )
return -1;
state->stack_size = new_size;
}
return 0;
}
/* grow the prefix/suffix arrays */
static int
ft_lzwstate_prefix_grow( FT_LzwState state )
{
FT_UInt old_size = state->prefix_size;
FT_UInt new_size = old_size;
FT_Memory memory = state->memory;
FT_Error error;
if ( new_size == 0 ) /* first allocation -> 9 bits */
new_size = 512;
else
new_size += new_size >> 2; /* don't grow too fast */
/*
* Note that the `suffix' array is located in the same memory block
* pointed to by `prefix'.
*
* I know that sizeof(FT_Byte) == 1 by definition, but it is clearer
* to write it literally.
*
*/
if ( FT_REALLOC_MULT( state->prefix, old_size, new_size,
sizeof ( FT_UShort ) + sizeof ( FT_Byte ) ) )
return -1;
/* now adjust `suffix' and move the data accordingly */
state->suffix = (FT_Byte*)( state->prefix + new_size );
FT_MEM_MOVE( state->suffix,
state->prefix + old_size,
old_size * sizeof ( FT_Byte ) );
state->prefix_size = new_size;
return 0;
}
FT_LOCAL_DEF( void )
ft_lzwstate_reset( FT_LzwState state )
{
state->in_eof = 0;
state->buf_offset = 0;
state->buf_size = 0;
state->buf_clear = 0;
state->buf_total = 0;
state->stack_top = 0;
state->num_bits = LZW_INIT_BITS;
state->phase = FT_LZW_PHASE_START;
}
FT_LOCAL_DEF( void )
ft_lzwstate_init( FT_LzwState state,
FT_Stream source )
{
FT_ZERO( state );
state->source = source;
state->memory = source->memory;
state->prefix = NULL;
state->suffix = NULL;
state->prefix_size = 0;
state->stack = state->stack_0;
state->stack_size = sizeof ( state->stack_0 );
ft_lzwstate_reset( state );
}
FT_LOCAL_DEF( void )
ft_lzwstate_done( FT_LzwState state )
{
FT_Memory memory = state->memory;
ft_lzwstate_reset( state );
if ( state->stack != state->stack_0 )
FT_FREE( state->stack );
FT_FREE( state->prefix );
state->suffix = NULL;
FT_ZERO( state );
}
#define FTLZW_STACK_PUSH( c ) \
FT_BEGIN_STMNT \
if ( state->stack_top >= state->stack_size && \
ft_lzwstate_stack_grow( state ) < 0 ) \
goto Eof; \
\
state->stack[state->stack_top++] = (FT_Byte)(c); \
FT_END_STMNT
FT_LOCAL_DEF( FT_ULong )
ft_lzwstate_io( FT_LzwState state,
FT_Byte* buffer,
FT_ULong out_size )
{
FT_ULong result = 0;
FT_UInt old_char = state->old_char;
FT_UInt old_code = state->old_code;
FT_UInt in_code = state->in_code;
if ( out_size == 0 )
goto Exit;
switch ( state->phase )
{
case FT_LZW_PHASE_START:
{
FT_Byte max_bits;
FT_Int32 c;
/* skip magic bytes, and read max_bits + block_flag */
if ( FT_Stream_Seek( state->source, 2 ) != 0 ||
FT_Stream_TryRead( state->source, &max_bits, 1 ) != 1 )
goto Eof;
state->max_bits = max_bits & LZW_BIT_MASK;
state->block_mode = max_bits & LZW_BLOCK_MASK;
state->max_free = (FT_UInt)( ( 1UL << state->max_bits ) - 256 );
if ( state->max_bits > LZW_MAX_BITS )
goto Eof;
state->num_bits = LZW_INIT_BITS;
state->free_ent = ( state->block_mode ? LZW_FIRST
: LZW_CLEAR ) - 256;
in_code = 0;
state->free_bits = state->num_bits < state->max_bits
? (FT_UInt)( ( 1UL << state->num_bits ) - 256 )
: state->max_free + 1;
c = ft_lzwstate_get_code( state );
if ( c < 0 || c > 255 )
goto Eof;
old_code = old_char = (FT_UInt)c;
if ( buffer )
buffer[result] = (FT_Byte)old_char;
if ( ++result >= out_size )
goto Exit;
state->phase = FT_LZW_PHASE_CODE;
}
/* fall-through */
case FT_LZW_PHASE_CODE:
{
FT_Int32 c;
FT_UInt code;
NextCode:
c = ft_lzwstate_get_code( state );
if ( c < 0 )
goto Eof;
code = (FT_UInt)c;
if ( code == LZW_CLEAR && state->block_mode )
{
/* why not LZW_FIRST-256 ? */
state->free_ent = ( LZW_FIRST - 1 ) - 256;
state->buf_clear = 1;
/* not quite right, but at least more predictable */
old_code = 0;
old_char = 0;
goto NextCode;
}
in_code = code; /* save code for later */
if ( code >= 256U )
{
/* special case for KwKwKwK */
if ( code - 256U >= state->free_ent )
{
/* corrupted LZW stream */
if ( code - 256U > state->free_ent )
goto Eof;
FTLZW_STACK_PUSH( old_char );
code = old_code;
}
while ( code >= 256U )
{
if ( !state->prefix )
goto Eof;
FTLZW_STACK_PUSH( state->suffix[code - 256] );
code = state->prefix[code - 256];
}
}
old_char = code;
FTLZW_STACK_PUSH( old_char );
state->phase = FT_LZW_PHASE_STACK;
}
/* fall-through */
case FT_LZW_PHASE_STACK:
{
while ( state->stack_top > 0 )
{
--state->stack_top;
if ( buffer )
buffer[result] = state->stack[state->stack_top];
if ( ++result == out_size )
goto Exit;
}
/* now create new entry */
if ( state->free_ent < state->max_free )
{
if ( state->free_ent >= state->prefix_size &&
ft_lzwstate_prefix_grow( state ) < 0 )
goto Eof;
FT_ASSERT( state->free_ent < state->prefix_size );
state->prefix[state->free_ent] = (FT_UShort)old_code;
state->suffix[state->free_ent] = (FT_Byte) old_char;
state->free_ent += 1;
}
old_code = in_code;
state->phase = FT_LZW_PHASE_CODE;
goto NextCode;
}
default: /* state == EOF */
;
}
Exit:
state->old_code = old_code;
state->old_char = old_char;
state->in_code = in_code;
return result;
Eof:
state->phase = FT_LZW_PHASE_EOF;
goto Exit;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/lzw/ftzopen.c | C | apache-2.0 | 11,034 |
/***************************************************************************/
/* */
/* ftzopen.h */
/* */
/* FreeType support for .Z compressed files. */
/* */
/* This optional component relies on NetBSD's zopen(). It should mainly */
/* be used to parse compressed PCF fonts, as found with many X11 server */
/* distributions. */
/* */
/* Copyright 2005, 2006, 2007, 2008 by David Turner. */
/* */
/* 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 __FT_ZOPEN_H__
#define __FT_ZOPEN_H__
#include <ft2build.h>
#include FT_FREETYPE_H
/*
* This is a complete re-implementation of the LZW file reader,
* since the old one was incredibly badly written, using
* 400 KByte of heap memory before decompressing anything.
*
*/
#define FT_LZW_IN_BUFF_SIZE 64
#define FT_LZW_DEFAULT_STACK_SIZE 64
#define LZW_INIT_BITS 9
#define LZW_MAX_BITS 16
#define LZW_CLEAR 256
#define LZW_FIRST 257
#define LZW_BIT_MASK 0x1f
#define LZW_BLOCK_MASK 0x80
#define LZW_MASK( n ) ( ( 1U << (n) ) - 1U )
typedef enum FT_LzwPhase_
{
FT_LZW_PHASE_START = 0,
FT_LZW_PHASE_CODE,
FT_LZW_PHASE_STACK,
FT_LZW_PHASE_EOF
} FT_LzwPhase;
/*
* state of LZW decompressor
*
* small technical note
* --------------------
*
* We use a few tricks in this implementation that are explained here to
* ease debugging and maintenance.
*
* - First of all, the `prefix' and `suffix' arrays contain the suffix
* and prefix for codes over 256; this means that
*
* prefix_of(code) == state->prefix[code-256]
* suffix_of(code) == state->suffix[code-256]
*
* Each prefix is a 16-bit code, and each suffix an 8-bit byte.
*
* Both arrays are stored in a single memory block, pointed to by
* `state->prefix'. This means that the following equality is always
* true:
*
* state->suffix == (FT_Byte*)(state->prefix + state->prefix_size)
*
* Of course, state->prefix_size is the number of prefix/suffix slots
* in the arrays, corresponding to codes 256..255+prefix_size.
*
* - `free_ent' is the index of the next free entry in the `prefix'
* and `suffix' arrays. This means that the corresponding `next free
* code' is really `256+free_ent'.
*
* Moreover, `max_free' is the maximum value that `free_ent' can reach.
*
* `max_free' corresponds to `(1 << max_bits) - 256'. Note that this
* value is always <= 0xFF00, which means that both `free_ent' and
* `max_free' can be stored in an FT_UInt variable, even on 16-bit
* machines.
*
* If `free_ent == max_free', you cannot add new codes to the
* prefix/suffix table.
*
* - `num_bits' is the current number of code bits, starting at 9 and
* growing each time `free_ent' reaches the value of `free_bits'. The
* latter is computed as follows
*
* if num_bits < max_bits:
* free_bits = (1 << num_bits)-256
* else:
* free_bits = max_free + 1
*
* Since the value of `max_free + 1' can never be reached by
* `free_ent', `num_bits' cannot grow larger than `max_bits'.
*/
typedef struct FT_LzwStateRec_
{
FT_LzwPhase phase;
FT_Int in_eof;
FT_Byte buf_tab[16];
FT_Int buf_offset;
FT_Int buf_size;
FT_Bool buf_clear;
FT_Offset buf_total;
FT_UInt max_bits; /* max code bits, from file header */
FT_Int block_mode; /* block mode flag, from file header */
FT_UInt max_free; /* (1 << max_bits) - 256 */
FT_UInt num_bits; /* current code bit number */
FT_UInt free_ent; /* index of next free entry */
FT_UInt free_bits; /* if reached by free_ent, increment num_bits */
FT_UInt old_code;
FT_UInt old_char;
FT_UInt in_code;
FT_UShort* prefix; /* always dynamically allocated / reallocated */
FT_Byte* suffix; /* suffix = (FT_Byte*)(prefix + prefix_size) */
FT_UInt prefix_size; /* number of slots in `prefix' or `suffix' */
FT_Byte* stack; /* character stack */
FT_UInt stack_top;
FT_Offset stack_size;
FT_Byte stack_0[FT_LZW_DEFAULT_STACK_SIZE]; /* minimize heap alloc */
FT_Stream source; /* source stream */
FT_Memory memory;
} FT_LzwStateRec, *FT_LzwState;
FT_LOCAL( void )
ft_lzwstate_init( FT_LzwState state,
FT_Stream source );
FT_LOCAL( void )
ft_lzwstate_done( FT_LzwState state );
FT_LOCAL( void )
ft_lzwstate_reset( FT_LzwState state );
FT_LOCAL( FT_ULong )
ft_lzwstate_io( FT_LzwState state,
FT_Byte* buffer,
FT_ULong out_size );
/* */
#endif /* __FT_ZOPEN_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/lzw/ftzopen.h | C | apache-2.0 | 5,941 |
#
# FreeType 2 LZW support configuration rules
#
# Copyright 2004, 2005, 2006 by
# Albert Chin-A-Young.
#
# Based on src/lzw/rules.mk, Copyright 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.
# LZW driver directory
#
LZW_DIR := $(SRC_DIR)/lzw
# compilation flags for the driver
#
LZW_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(LZW_DIR))
# LZW support sources (i.e., C files)
#
LZW_DRV_SRC := $(LZW_DIR)/ftlzw.c
# LZW support headers
#
LZW_DRV_H := $(LZW_DIR)/ftzopen.h \
$(LZW_DIR)/ftzopen.c
# LZW driver object(s)
#
# LZW_DRV_OBJ_M is used during `multi' builds
# LZW_DRV_OBJ_S is used during `single' builds
#
LZW_DRV_OBJ_M := $(OBJ_DIR)/ftlzw.$O
LZW_DRV_OBJ_S := $(OBJ_DIR)/ftlzw.$O
# LZW support source file for single build
#
LZW_DRV_SRC_S := $(LZW_DIR)/ftlzw.c
# LZW support - single object
#
$(LZW_DRV_OBJ_S): $(LZW_DRV_SRC_S) $(LZW_DRV_SRC) $(FREETYPE_H) $(LZW_DRV_H)
$(LZW_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(LZW_DRV_SRC_S))
# LZW support - multiple objects
#
$(OBJ_DIR)/%.$O: $(LZW_DIR)/%.c $(FREETYPE_H) $(LZW_DRV_H)
$(LZW_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(LZW_DRV_OBJ_S)
DRV_OBJS_M += $(LZW_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/lzw/rules.mk | Makefile | apache-2.0 | 1,552 |
#
# FreeType 2 otvalid module definition
#
# Copyright 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.
FTMODULE_H_COMMANDS += OTVALID_MODULE
define OTVALID_MODULE
$(OPEN_DRIVER) FT_Module_Class, otv_module_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)otvalid $(ECHO_DRIVER_DESC)OpenType validation module$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/module.mk | Makefile | apache-2.0 | 653 |
/***************************************************************************/
/* */
/* otvalid.c */
/* */
/* FreeType validator for OpenType tables (body only). */
/* */
/* Copyright 2004, 2007 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 "otvbase.c"
#include "otvcommn.c"
#include "otvgdef.c"
#include "otvgpos.c"
#include "otvgsub.c"
#include "otvjstf.c"
#include "otvmath.c"
#include "otvmod.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvalid.c | C | apache-2.0 | 1,489 |
/***************************************************************************/
/* */
/* otvalid.h */
/* */
/* OpenType table validation (specification only). */
/* */
/* Copyright 2004, 2008 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 __OTVALID_H__
#define __OTVALID_H__
#include <ft2build.h>
#include FT_FREETYPE_H
#include "otverror.h" /* must come before FT_INTERNAL_VALIDATE_H */
#include FT_INTERNAL_VALIDATE_H
#include FT_INTERNAL_STREAM_H
FT_BEGIN_HEADER
FT_LOCAL( void )
otv_BASE_validate( FT_Bytes table,
FT_Validator valid );
/* GSUB and GPOS tables should already be validated; */
/* if missing, set corresponding argument to 0 */
FT_LOCAL( void )
otv_GDEF_validate( FT_Bytes table,
FT_Bytes gsub,
FT_Bytes gpos,
FT_UInt glyph_count,
FT_Validator valid );
FT_LOCAL( void )
otv_GPOS_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator valid );
FT_LOCAL( void )
otv_GSUB_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator valid );
/* GSUB and GPOS tables should already be validated; */
/* if missing, set corresponding argument to 0 */
FT_LOCAL( void )
otv_JSTF_validate( FT_Bytes table,
FT_Bytes gsub,
FT_Bytes gpos,
FT_UInt glyph_count,
FT_Validator valid );
FT_LOCAL( void )
otv_MATH_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator ftvalid );
FT_END_HEADER
#endif /* __OTVALID_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvalid.h | C | apache-2.0 | 2,832 |
/***************************************************************************/
/* */
/* otvbase.c */
/* */
/* OpenType BASE table validation (body). */
/* */
/* Copyright 2004, 2007 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 "otvalid.h"
#include "otvcommn.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_otvbase
static void
otv_BaseCoord_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BaseCoordFormat;
OTV_NAME_ENTER( "BaseCoord" );
OTV_LIMIT_CHECK( 4 );
BaseCoordFormat = FT_NEXT_USHORT( p );
p += 2; /* skip Coordinate */
OTV_TRACE(( " (format %d)\n", BaseCoordFormat ));
switch ( BaseCoordFormat )
{
case 1: /* BaseCoordFormat1 */
break;
case 2: /* BaseCoordFormat2 */
OTV_LIMIT_CHECK( 4 ); /* ReferenceGlyph, BaseCoordPoint */
break;
case 3: /* BaseCoordFormat3 */
OTV_LIMIT_CHECK( 2 );
/* DeviceTable */
otv_Device_validate( table + FT_NEXT_USHORT( p ), valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
static void
otv_BaseTagList_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BaseTagCount;
OTV_NAME_ENTER( "BaseTagList" );
OTV_LIMIT_CHECK( 2 );
BaseTagCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BaseTagCount = %d)\n", BaseTagCount ));
OTV_LIMIT_CHECK( BaseTagCount * 4 ); /* BaselineTag */
OTV_EXIT;
}
static void
otv_BaseValues_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BaseCoordCount;
OTV_NAME_ENTER( "BaseValues" );
OTV_LIMIT_CHECK( 4 );
p += 2; /* skip DefaultIndex */
BaseCoordCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BaseCoordCount = %d)\n", BaseCoordCount ));
OTV_LIMIT_CHECK( BaseCoordCount * 2 );
/* BaseCoord */
for ( ; BaseCoordCount > 0; BaseCoordCount-- )
otv_BaseCoord_validate( table + FT_NEXT_USHORT( p ), valid );
OTV_EXIT;
}
static void
otv_MinMax_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt table_size;
FT_UInt FeatMinMaxCount;
OTV_OPTIONAL_TABLE( MinCoord );
OTV_OPTIONAL_TABLE( MaxCoord );
OTV_NAME_ENTER( "MinMax" );
OTV_LIMIT_CHECK( 6 );
OTV_OPTIONAL_OFFSET( MinCoord );
OTV_OPTIONAL_OFFSET( MaxCoord );
FeatMinMaxCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (FeatMinMaxCount = %d)\n", FeatMinMaxCount ));
table_size = FeatMinMaxCount * 8 + 6;
OTV_SIZE_CHECK( MinCoord );
if ( MinCoord )
otv_BaseCoord_validate( table + MinCoord, valid );
OTV_SIZE_CHECK( MaxCoord );
if ( MaxCoord )
otv_BaseCoord_validate( table + MaxCoord, valid );
OTV_LIMIT_CHECK( FeatMinMaxCount * 8 );
/* FeatMinMaxRecord */
for ( ; FeatMinMaxCount > 0; FeatMinMaxCount-- )
{
p += 4; /* skip FeatureTableTag */
OTV_OPTIONAL_OFFSET( MinCoord );
OTV_OPTIONAL_OFFSET( MaxCoord );
OTV_SIZE_CHECK( MinCoord );
if ( MinCoord )
otv_BaseCoord_validate( table + MinCoord, valid );
OTV_SIZE_CHECK( MaxCoord );
if ( MaxCoord )
otv_BaseCoord_validate( table + MaxCoord, valid );
}
OTV_EXIT;
}
static void
otv_BaseScript_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt table_size;
FT_UInt BaseLangSysCount;
OTV_OPTIONAL_TABLE( BaseValues );
OTV_OPTIONAL_TABLE( DefaultMinMax );
OTV_NAME_ENTER( "BaseScript" );
OTV_LIMIT_CHECK( 6 );
OTV_OPTIONAL_OFFSET( BaseValues );
OTV_OPTIONAL_OFFSET( DefaultMinMax );
BaseLangSysCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BaseLangSysCount = %d)\n", BaseLangSysCount ));
table_size = BaseLangSysCount * 6 + 6;
OTV_SIZE_CHECK( BaseValues );
if ( BaseValues )
otv_BaseValues_validate( table + BaseValues, valid );
OTV_SIZE_CHECK( DefaultMinMax );
if ( DefaultMinMax )
otv_MinMax_validate( table + DefaultMinMax, valid );
OTV_LIMIT_CHECK( BaseLangSysCount * 6 );
/* BaseLangSysRecord */
for ( ; BaseLangSysCount > 0; BaseLangSysCount-- )
{
p += 4; /* skip BaseLangSysTag */
otv_MinMax_validate( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
static void
otv_BaseScriptList_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BaseScriptCount;
OTV_NAME_ENTER( "BaseScriptList" );
OTV_LIMIT_CHECK( 2 );
BaseScriptCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BaseScriptCount = %d)\n", BaseScriptCount ));
OTV_LIMIT_CHECK( BaseScriptCount * 6 );
/* BaseScriptRecord */
for ( ; BaseScriptCount > 0; BaseScriptCount-- )
{
p += 4; /* skip BaseScriptTag */
/* BaseScript */
otv_BaseScript_validate( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
static void
otv_Axis_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt table_size;
OTV_OPTIONAL_TABLE( BaseTagList );
OTV_NAME_ENTER( "Axis" );
OTV_LIMIT_CHECK( 4 );
OTV_OPTIONAL_OFFSET( BaseTagList );
table_size = 4;
OTV_SIZE_CHECK( BaseTagList );
if ( BaseTagList )
otv_BaseTagList_validate( table + BaseTagList, valid );
/* BaseScriptList */
otv_BaseScriptList_validate( table + FT_NEXT_USHORT( p ), valid );
OTV_EXIT;
}
FT_LOCAL_DEF( void )
otv_BASE_validate( FT_Bytes table,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt table_size;
OTV_OPTIONAL_TABLE( HorizAxis );
OTV_OPTIONAL_TABLE( VertAxis );
valid->root = ftvalid;
FT_TRACE3(( "validating BASE table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 6 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
table_size = 6;
OTV_OPTIONAL_OFFSET( HorizAxis );
OTV_SIZE_CHECK( HorizAxis );
if ( HorizAxis )
otv_Axis_validate( table + HorizAxis, valid );
OTV_OPTIONAL_OFFSET( VertAxis );
OTV_SIZE_CHECK( VertAxis );
if ( VertAxis )
otv_Axis_validate( table + VertAxis, valid );
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvbase.c | C | apache-2.0 | 8,196 |
/***************************************************************************/
/* */
/* otvcommn.c */
/* */
/* OpenType common tables validation (body). */
/* */
/* Copyright 2004, 2005, 2006, 2007 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 "otvcommn.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_otvcommon
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** COVERAGE TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
otv_Coverage_validate( FT_Bytes table,
OTV_Validator valid,
FT_Int expected_count )
{
FT_Bytes p = table;
FT_UInt CoverageFormat;
FT_UInt total = 0;
OTV_NAME_ENTER( "Coverage" );
OTV_LIMIT_CHECK( 4 );
CoverageFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", CoverageFormat ));
switch ( CoverageFormat )
{
case 1: /* CoverageFormat1 */
{
FT_UInt GlyphCount;
FT_UInt i;
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
OTV_LIMIT_CHECK( GlyphCount * 2 ); /* GlyphArray */
for ( i = 0; i < GlyphCount; ++i )
{
FT_UInt gid;
gid = FT_NEXT_USHORT( p );
if ( gid >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
}
total = GlyphCount;
}
break;
case 2: /* CoverageFormat2 */
{
FT_UInt n, RangeCount;
FT_UInt Start, End, StartCoverageIndex, last = 0;
RangeCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (RangeCount = %d)\n", RangeCount ));
OTV_LIMIT_CHECK( RangeCount * 6 );
/* RangeRecord */
for ( n = 0; n < RangeCount; n++ )
{
Start = FT_NEXT_USHORT( p );
End = FT_NEXT_USHORT( p );
StartCoverageIndex = FT_NEXT_USHORT( p );
if ( Start > End || StartCoverageIndex != total )
FT_INVALID_DATA;
if ( End >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
if ( n > 0 && Start <= last )
FT_INVALID_DATA;
total += End - Start + 1;
last = End;
}
}
break;
default:
FT_INVALID_FORMAT;
}
/* Generally, a coverage table offset has an associated count field. */
/* The number of glyphs in the table should match this field. If */
/* there is no associated count, a value of -1 tells us not to check. */
if ( expected_count != -1 && (FT_UInt)expected_count != total )
FT_INVALID_DATA;
OTV_EXIT;
}
FT_LOCAL_DEF( FT_UInt )
otv_Coverage_get_first( FT_Bytes table )
{
FT_Bytes p = table;
p += 4; /* skip CoverageFormat and Glyph/RangeCount */
return FT_NEXT_USHORT( p );
}
FT_LOCAL_DEF( FT_UInt )
otv_Coverage_get_last( FT_Bytes table )
{
FT_Bytes p = table;
FT_UInt CoverageFormat = FT_NEXT_USHORT( p );
FT_UInt count = FT_NEXT_USHORT( p ); /* Glyph/RangeCount */
FT_UInt result = 0;
switch ( CoverageFormat )
{
case 1:
p += ( count - 1 ) * 2;
result = FT_NEXT_USHORT( p );
break;
case 2:
p += ( count - 1 ) * 6 + 2;
result = FT_NEXT_USHORT( p );
break;
default:
;
}
return result;
}
FT_LOCAL_DEF( FT_UInt )
otv_Coverage_get_count( FT_Bytes table )
{
FT_Bytes p = table;
FT_UInt CoverageFormat = FT_NEXT_USHORT( p );
FT_UInt count = FT_NEXT_USHORT( p ); /* Glyph/RangeCount */
FT_UInt result = 0;
switch ( CoverageFormat )
{
case 1:
return count;
case 2:
{
FT_UInt Start, End;
for ( ; count > 0; count-- )
{
Start = FT_NEXT_USHORT( p );
End = FT_NEXT_USHORT( p );
p += 2; /* skip StartCoverageIndex */
result += End - Start + 1;
}
}
break;
default:
;
}
return result;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CLASS DEFINITION TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
otv_ClassDef_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt ClassFormat;
OTV_NAME_ENTER( "ClassDef" );
OTV_LIMIT_CHECK( 4 );
ClassFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", ClassFormat ));
switch ( ClassFormat )
{
case 1: /* ClassDefFormat1 */
{
FT_UInt StartGlyph;
FT_UInt GlyphCount;
OTV_LIMIT_CHECK( 4 );
StartGlyph = FT_NEXT_USHORT( p );
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
OTV_LIMIT_CHECK( GlyphCount * 2 ); /* ClassValueArray */
if ( StartGlyph + GlyphCount - 1 >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
}
break;
case 2: /* ClassDefFormat2 */
{
FT_UInt n, ClassRangeCount;
FT_UInt Start, End, last = 0;
ClassRangeCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ClassRangeCount = %d)\n", ClassRangeCount ));
OTV_LIMIT_CHECK( ClassRangeCount * 6 );
/* ClassRangeRecord */
for ( n = 0; n < ClassRangeCount; n++ )
{
Start = FT_NEXT_USHORT( p );
End = FT_NEXT_USHORT( p );
p += 2; /* skip Class */
if ( Start > End || ( n > 0 && Start <= last ) )
FT_INVALID_DATA;
if ( End >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
last = End;
}
}
break;
default:
FT_INVALID_FORMAT;
}
/* no need to check glyph indices used as input to class definition */
/* tables since even invalid glyph indices return a meaningful result */
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** DEVICE TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
otv_Device_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt StartSize, EndSize, DeltaFormat, count;
OTV_NAME_ENTER( "Device" );
OTV_LIMIT_CHECK( 8 );
StartSize = FT_NEXT_USHORT( p );
EndSize = FT_NEXT_USHORT( p );
DeltaFormat = FT_NEXT_USHORT( p );
if ( DeltaFormat < 1 || DeltaFormat > 3 )
FT_INVALID_FORMAT;
if ( EndSize < StartSize )
FT_INVALID_DATA;
count = EndSize - StartSize + 1;
OTV_LIMIT_CHECK( ( 1 << DeltaFormat ) * count / 8 ); /* DeltaValue */
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LOOKUPS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->type_count */
/* uses valid->type_funcs */
FT_LOCAL_DEF( void )
otv_Lookup_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt LookupType, SubTableCount;
OTV_Validate_Func validate;
OTV_NAME_ENTER( "Lookup" );
OTV_LIMIT_CHECK( 6 );
LookupType = FT_NEXT_USHORT( p );
p += 2; /* skip LookupFlag */
SubTableCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (type %d)\n", LookupType ));
if ( LookupType == 0 || LookupType > valid->type_count )
FT_INVALID_DATA;
validate = valid->type_funcs[LookupType - 1];
OTV_TRACE(( " (SubTableCount = %d)\n", SubTableCount ));
OTV_LIMIT_CHECK( SubTableCount * 2 );
/* SubTable */
for ( ; SubTableCount > 0; SubTableCount-- )
validate( table + FT_NEXT_USHORT( p ), valid );
OTV_EXIT;
}
/* uses valid->lookup_count */
FT_LOCAL_DEF( void )
otv_LookupList_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt LookupCount;
OTV_NAME_ENTER( "LookupList" );
OTV_LIMIT_CHECK( 2 );
LookupCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LookupCount = %d)\n", LookupCount ));
OTV_LIMIT_CHECK( LookupCount * 2 );
valid->lookup_count = LookupCount;
/* Lookup */
for ( ; LookupCount > 0; LookupCount-- )
otv_Lookup_validate( table + FT_NEXT_USHORT( p ), valid );
OTV_EXIT;
}
static FT_UInt
otv_LookupList_get_count( FT_Bytes table )
{
return FT_NEXT_USHORT( table );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** FEATURES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->lookup_count */
FT_LOCAL_DEF( void )
otv_Feature_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt LookupCount;
OTV_NAME_ENTER( "Feature" );
OTV_LIMIT_CHECK( 4 );
p += 2; /* skip FeatureParams (unused) */
LookupCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LookupCount = %d)\n", LookupCount ));
OTV_LIMIT_CHECK( LookupCount * 2 );
/* LookupListIndex */
for ( ; LookupCount > 0; LookupCount-- )
if ( FT_NEXT_USHORT( p ) >= valid->lookup_count )
FT_INVALID_DATA;
OTV_EXIT;
}
static FT_UInt
otv_Feature_get_count( FT_Bytes table )
{
return FT_NEXT_USHORT( table );
}
/* sets valid->lookup_count */
FT_LOCAL_DEF( void )
otv_FeatureList_validate( FT_Bytes table,
FT_Bytes lookups,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt FeatureCount;
OTV_NAME_ENTER( "FeatureList" );
OTV_LIMIT_CHECK( 2 );
FeatureCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (FeatureCount = %d)\n", FeatureCount ));
OTV_LIMIT_CHECK( FeatureCount * 2 );
valid->lookup_count = otv_LookupList_get_count( lookups );
/* FeatureRecord */
for ( ; FeatureCount > 0; FeatureCount-- )
{
p += 4; /* skip FeatureTag */
/* Feature */
otv_Feature_validate( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LANGUAGE SYSTEM *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->extra1 (number of features) */
FT_LOCAL_DEF( void )
otv_LangSys_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt ReqFeatureIndex;
FT_UInt FeatureCount;
OTV_NAME_ENTER( "LangSys" );
OTV_LIMIT_CHECK( 6 );
p += 2; /* skip LookupOrder (unused) */
ReqFeatureIndex = FT_NEXT_USHORT( p );
FeatureCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ReqFeatureIndex = %d)\n", ReqFeatureIndex ));
OTV_TRACE(( " (FeatureCount = %d)\n", FeatureCount ));
if ( ReqFeatureIndex != 0xFFFFU && ReqFeatureIndex >= valid->extra1 )
FT_INVALID_DATA;
OTV_LIMIT_CHECK( FeatureCount * 2 );
/* FeatureIndex */
for ( ; FeatureCount > 0; FeatureCount-- )
if ( FT_NEXT_USHORT( p ) >= valid->extra1 )
FT_INVALID_DATA;
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** SCRIPTS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
otv_Script_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_UInt DefaultLangSys, LangSysCount;
FT_Bytes p = table;
OTV_NAME_ENTER( "Script" );
OTV_LIMIT_CHECK( 4 );
DefaultLangSys = FT_NEXT_USHORT( p );
LangSysCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LangSysCount = %d)\n", LangSysCount ));
if ( DefaultLangSys != 0 )
otv_LangSys_validate( table + DefaultLangSys, valid );
OTV_LIMIT_CHECK( LangSysCount * 6 );
/* LangSysRecord */
for ( ; LangSysCount > 0; LangSysCount-- )
{
p += 4; /* skip LangSysTag */
/* LangSys */
otv_LangSys_validate( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
/* sets valid->extra1 (number of features) */
FT_LOCAL_DEF( void )
otv_ScriptList_validate( FT_Bytes table,
FT_Bytes features,
OTV_Validator valid )
{
FT_UInt ScriptCount;
FT_Bytes p = table;
OTV_NAME_ENTER( "ScriptList" );
OTV_LIMIT_CHECK( 2 );
ScriptCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ScriptCount = %d)\n", ScriptCount ));
OTV_LIMIT_CHECK( ScriptCount * 6 );
valid->extra1 = otv_Feature_get_count( features );
/* ScriptRecord */
for ( ; ScriptCount > 0; ScriptCount-- )
{
p += 4; /* skip ScriptTag */
otv_Script_validate( table + FT_NEXT_USHORT( p ), valid ); /* Script */
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*
u: uint16
ux: unit16 [x]
s: struct
sx: struct [x]
sxy: struct [x], using external y count
x: uint16 x
C: Coverage
O: Offset
On: Offset (NULL)
Ox: Offset [x]
Onx: Offset (NULL) [x]
*/
FT_LOCAL_DEF( void )
otv_x_Ox( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Count;
OTV_Validate_Func func;
OTV_ENTER;
OTV_LIMIT_CHECK( 2 );
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", Count ));
OTV_LIMIT_CHECK( Count * 2 );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
for ( ; Count > 0; Count-- )
func( table + FT_NEXT_USHORT( p ), valid );
valid->nesting_level--;
OTV_EXIT;
}
FT_LOCAL_DEF( void )
otv_u_C_x_Ox( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Count, Coverage;
OTV_Validate_Func func;
OTV_ENTER;
p += 2; /* skip Format */
OTV_LIMIT_CHECK( 4 );
Coverage = FT_NEXT_USHORT( p );
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", Count ));
otv_Coverage_validate( table + Coverage, valid, Count );
OTV_LIMIT_CHECK( Count * 2 );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
for ( ; Count > 0; Count-- )
func( table + FT_NEXT_USHORT( p ), valid );
valid->nesting_level--;
OTV_EXIT;
}
/* uses valid->extra1 (if > 0: array value limit) */
FT_LOCAL_DEF( void )
otv_x_ux( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Count;
OTV_ENTER;
OTV_LIMIT_CHECK( 2 );
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", Count ));
OTV_LIMIT_CHECK( Count * 2 );
if ( valid->extra1 )
{
for ( ; Count > 0; Count-- )
if ( FT_NEXT_USHORT( p ) >= valid->extra1 )
FT_INVALID_DATA;
}
OTV_EXIT;
}
/* `ux' in the function's name is not really correct since only x-1 */
/* elements are tested */
/* uses valid->extra1 (array value limit) */
FT_LOCAL_DEF( void )
otv_x_y_ux_sy( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Count1, Count2;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
Count1 = FT_NEXT_USHORT( p );
Count2 = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count1 = %d)\n", Count1 ));
OTV_TRACE(( " (Count2 = %d)\n", Count2 ));
if ( Count1 == 0 )
FT_INVALID_DATA;
OTV_LIMIT_CHECK( ( Count1 - 1 ) * 2 + Count2 * 4 );
p += ( Count1 - 1 ) * 2;
for ( ; Count2 > 0; Count2-- )
{
if ( FT_NEXT_USHORT( p ) >= Count1 )
FT_INVALID_DATA;
if ( FT_NEXT_USHORT( p ) >= valid->extra1 )
FT_INVALID_DATA;
}
OTV_EXIT;
}
/* `uy' in the function's name is not really correct since only y-1 */
/* elements are tested */
/* uses valid->extra1 (array value limit) */
FT_LOCAL_DEF( void )
otv_x_ux_y_uy_z_uz_p_sp( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BacktrackCount, InputCount, LookaheadCount;
FT_UInt Count;
OTV_ENTER;
OTV_LIMIT_CHECK( 2 );
BacktrackCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BacktrackCount = %d)\n", BacktrackCount ));
OTV_LIMIT_CHECK( BacktrackCount * 2 + 2 );
p += BacktrackCount * 2;
InputCount = FT_NEXT_USHORT( p );
if ( InputCount == 0 )
FT_INVALID_DATA;
OTV_TRACE(( " (InputCount = %d)\n", InputCount ));
OTV_LIMIT_CHECK( InputCount * 2 );
p += ( InputCount - 1 ) * 2;
LookaheadCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LookaheadCount = %d)\n", LookaheadCount ));
OTV_LIMIT_CHECK( LookaheadCount * 2 + 2 );
p += LookaheadCount * 2;
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", Count ));
OTV_LIMIT_CHECK( Count * 4 );
for ( ; Count > 0; Count-- )
{
if ( FT_NEXT_USHORT( p ) >= InputCount )
FT_INVALID_DATA;
if ( FT_NEXT_USHORT( p ) >= valid->extra1 )
FT_INVALID_DATA;
}
OTV_EXIT;
}
/* sets valid->extra1 (valid->lookup_count) */
FT_LOCAL_DEF( void )
otv_u_O_O_x_Onx( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Coverage, ClassDef, ClassSetCount;
OTV_Validate_Func func;
OTV_ENTER;
p += 2; /* skip Format */
OTV_LIMIT_CHECK( 6 );
Coverage = FT_NEXT_USHORT( p );
ClassDef = FT_NEXT_USHORT( p );
ClassSetCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ClassSetCount = %d)\n", ClassSetCount ));
otv_Coverage_validate( table + Coverage, valid, -1 );
otv_ClassDef_validate( table + ClassDef, valid );
OTV_LIMIT_CHECK( ClassSetCount * 2 );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
valid->extra1 = valid->lookup_count;
for ( ; ClassSetCount > 0; ClassSetCount-- )
{
FT_UInt offset = FT_NEXT_USHORT( p );
if ( offset )
func( table + offset, valid );
}
valid->nesting_level--;
OTV_EXIT;
}
/* uses valid->lookup_count */
FT_LOCAL_DEF( void )
otv_u_x_y_Ox_sy( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt GlyphCount, Count, count1;
OTV_ENTER;
p += 2; /* skip Format */
OTV_LIMIT_CHECK( 4 );
GlyphCount = FT_NEXT_USHORT( p );
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
OTV_TRACE(( " (Count = %d)\n", Count ));
OTV_LIMIT_CHECK( GlyphCount * 2 + Count * 4 );
for ( count1 = GlyphCount; count1 > 0; count1-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
for ( ; Count > 0; Count-- )
{
if ( FT_NEXT_USHORT( p ) >= GlyphCount )
FT_INVALID_DATA;
if ( FT_NEXT_USHORT( p ) >= valid->lookup_count )
FT_INVALID_DATA;
}
OTV_EXIT;
}
/* sets valid->extra1 (valid->lookup_count) */
FT_LOCAL_DEF( void )
otv_u_O_O_O_O_x_Onx( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Coverage;
FT_UInt BacktrackClassDef, InputClassDef, LookaheadClassDef;
FT_UInt ChainClassSetCount;
OTV_Validate_Func func;
OTV_ENTER;
p += 2; /* skip Format */
OTV_LIMIT_CHECK( 10 );
Coverage = FT_NEXT_USHORT( p );
BacktrackClassDef = FT_NEXT_USHORT( p );
InputClassDef = FT_NEXT_USHORT( p );
LookaheadClassDef = FT_NEXT_USHORT( p );
ChainClassSetCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ChainClassSetCount = %d)\n", ChainClassSetCount ));
otv_Coverage_validate( table + Coverage, valid, -1 );
otv_ClassDef_validate( table + BacktrackClassDef, valid );
otv_ClassDef_validate( table + InputClassDef, valid );
otv_ClassDef_validate( table + LookaheadClassDef, valid );
OTV_LIMIT_CHECK( ChainClassSetCount * 2 );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
valid->extra1 = valid->lookup_count;
for ( ; ChainClassSetCount > 0; ChainClassSetCount-- )
{
FT_UInt offset = FT_NEXT_USHORT( p );
if ( offset )
func( table + offset, valid );
}
valid->nesting_level--;
OTV_EXIT;
}
/* uses valid->lookup_count */
FT_LOCAL_DEF( void )
otv_u_x_Ox_y_Oy_z_Oz_p_sp( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt BacktrackGlyphCount, InputGlyphCount, LookaheadGlyphCount;
FT_UInt count1, count2;
OTV_ENTER;
p += 2; /* skip Format */
OTV_LIMIT_CHECK( 2 );
BacktrackGlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BacktrackGlyphCount = %d)\n", BacktrackGlyphCount ));
OTV_LIMIT_CHECK( BacktrackGlyphCount * 2 + 2 );
for ( ; BacktrackGlyphCount > 0; BacktrackGlyphCount-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
InputGlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (InputGlyphCount = %d)\n", InputGlyphCount ));
OTV_LIMIT_CHECK( InputGlyphCount * 2 + 2 );
for ( count1 = InputGlyphCount; count1 > 0; count1-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
LookaheadGlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LookaheadGlyphCount = %d)\n", LookaheadGlyphCount ));
OTV_LIMIT_CHECK( LookaheadGlyphCount * 2 + 2 );
for ( ; LookaheadGlyphCount > 0; LookaheadGlyphCount-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
count2 = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", count2 ));
OTV_LIMIT_CHECK( count2 * 4 );
for ( ; count2 > 0; count2-- )
{
if ( FT_NEXT_USHORT( p ) >= InputGlyphCount )
FT_INVALID_DATA;
if ( FT_NEXT_USHORT( p ) >= valid->lookup_count )
FT_INVALID_DATA;
}
OTV_EXIT;
}
FT_LOCAL_DEF( FT_UInt )
otv_GSUBGPOS_get_Lookup_count( FT_Bytes table )
{
FT_Bytes p = table + 8;
return otv_LookupList_get_count( table + FT_NEXT_USHORT( p ) );
}
FT_LOCAL_DEF( FT_UInt )
otv_GSUBGPOS_have_MarkAttachmentType_flag( FT_Bytes table )
{
FT_Bytes p, lookup;
FT_UInt count;
if ( !table )
return 0;
/* LookupList */
p = table + 8;
table += FT_NEXT_USHORT( p );
/* LookupCount */
p = table;
count = FT_NEXT_USHORT( p );
for ( ; count > 0; count-- )
{
FT_Bytes oldp;
/* Lookup */
lookup = table + FT_NEXT_USHORT( p );
oldp = p;
/* LookupFlag */
p = lookup + 2;
if ( FT_NEXT_USHORT( p ) & 0xFF00U )
return 1;
p = oldp;
}
return 0;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvcommn.c | C | apache-2.0 | 28,026 |
/***************************************************************************/
/* */
/* otvcommn.h */
/* */
/* OpenType common tables validation (specification). */
/* */
/* Copyright 2004, 2005, 2007, 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. */
/* */
/***************************************************************************/
#ifndef __OTVCOMMN_H__
#define __OTVCOMMN_H__
#include <ft2build.h>
#include "otvalid.h"
#include FT_INTERNAL_DEBUG_H
FT_BEGIN_HEADER
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** VALIDATION *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct OTV_ValidatorRec_* OTV_Validator;
typedef void (*OTV_Validate_Func)( FT_Bytes table,
OTV_Validator valid );
typedef struct OTV_ValidatorRec_
{
FT_Validator root;
FT_UInt type_count;
OTV_Validate_Func* type_funcs;
FT_UInt lookup_count;
FT_UInt glyph_count;
FT_UInt nesting_level;
OTV_Validate_Func func[3];
FT_UInt extra1; /* for passing parameters */
FT_UInt extra2;
FT_Bytes extra3;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_UInt debug_indent;
const FT_String* debug_function_name[3];
#endif
} OTV_ValidatorRec;
#undef FT_INVALID_
#define FT_INVALID_( _prefix, _error ) \
ft_validator_error( valid->root, _prefix ## _error )
#define OTV_OPTIONAL_TABLE( _table ) FT_UShort _table; \
FT_Bytes _table ## _p
#define OTV_OPTIONAL_OFFSET( _offset ) \
FT_BEGIN_STMNT \
_offset ## _p = p; \
_offset = FT_NEXT_USHORT( p ); \
FT_END_STMNT
#define OTV_LIMIT_CHECK( _count ) \
FT_BEGIN_STMNT \
if ( p + (_count) > valid->root->limit ) \
FT_INVALID_TOO_SHORT; \
FT_END_STMNT
#define OTV_SIZE_CHECK( _size ) \
FT_BEGIN_STMNT \
if ( _size > 0 && _size < table_size ) \
{ \
if ( valid->root->level == FT_VALIDATE_PARANOID ) \
FT_INVALID_OFFSET; \
else \
{ \
/* strip off `const' */ \
FT_Byte* pp = (FT_Byte*)_size ## _p; \
\
\
FT_TRACE3(( "\n" \
"Invalid offset to optional table `%s'" \
" set to zero.\n" \
"\n", #_size )); \
\
/* always assume 16bit entities */ \
_size = pp[0] = pp[1] = 0; \
} \
} \
FT_END_STMNT
#define OTV_NAME_(x) #x
#define OTV_NAME(x) OTV_NAME_(x)
#define OTV_FUNC_(x) x##Func
#define OTV_FUNC(x) OTV_FUNC_(x)
#ifdef FT_DEBUG_LEVEL_TRACE
#define OTV_NEST1( x ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
valid->debug_function_name[0] = OTV_NAME( x ); \
FT_END_STMNT
#define OTV_NEST2( x, y ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
valid->func[1] = OTV_FUNC( y ); \
valid->debug_function_name[0] = OTV_NAME( x ); \
valid->debug_function_name[1] = OTV_NAME( y ); \
FT_END_STMNT
#define OTV_NEST3( x, y, z ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
valid->func[1] = OTV_FUNC( y ); \
valid->func[2] = OTV_FUNC( z ); \
valid->debug_function_name[0] = OTV_NAME( x ); \
valid->debug_function_name[1] = OTV_NAME( y ); \
valid->debug_function_name[2] = OTV_NAME( z ); \
FT_END_STMNT
#define OTV_INIT valid->debug_indent = 0
#define OTV_ENTER \
FT_BEGIN_STMNT \
valid->debug_indent += 2; \
FT_TRACE4(( "%*.s", valid->debug_indent, 0 )); \
FT_TRACE4(( "%s table\n", \
valid->debug_function_name[valid->nesting_level] )); \
FT_END_STMNT
#define OTV_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 OTV_EXIT valid->debug_indent -= 2
#define OTV_TRACE( s ) \
FT_BEGIN_STMNT \
FT_TRACE4(( "%*.s", valid->debug_indent, 0 )); \
FT_TRACE4( s ); \
FT_END_STMNT
#else /* !FT_DEBUG_LEVEL_TRACE */
#define OTV_NEST1( x ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
FT_END_STMNT
#define OTV_NEST2( x, y ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
valid->func[1] = OTV_FUNC( y ); \
FT_END_STMNT
#define OTV_NEST3( x, y, z ) \
FT_BEGIN_STMNT \
valid->nesting_level = 0; \
valid->func[0] = OTV_FUNC( x ); \
valid->func[1] = OTV_FUNC( y ); \
valid->func[2] = OTV_FUNC( z ); \
FT_END_STMNT
#define OTV_INIT do { } while ( 0 )
#define OTV_ENTER do { } while ( 0 )
#define OTV_NAME_ENTER( name ) do { } while ( 0 )
#define OTV_EXIT do { } while ( 0 )
#define OTV_TRACE( s ) do { } while ( 0 )
#endif /* !FT_DEBUG_LEVEL_TRACE */
#define OTV_RUN valid->func[0]
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** COVERAGE TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_Coverage_validate( FT_Bytes table,
OTV_Validator valid,
FT_Int expected_count );
/* return first covered glyph */
FT_LOCAL( FT_UInt )
otv_Coverage_get_first( FT_Bytes table );
/* return last covered glyph */
FT_LOCAL( FT_UInt )
otv_Coverage_get_last( FT_Bytes table );
/* return number of covered glyphs */
FT_LOCAL( FT_UInt )
otv_Coverage_get_count( FT_Bytes table );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CLASS DEFINITION TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_ClassDef_validate( FT_Bytes table,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** DEVICE TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_Device_validate( FT_Bytes table,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LOOKUPS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_Lookup_validate( FT_Bytes table,
OTV_Validator valid );
FT_LOCAL( void )
otv_LookupList_validate( FT_Bytes table,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** FEATURES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_Feature_validate( FT_Bytes table,
OTV_Validator valid );
/* lookups must already be validated */
FT_LOCAL( void )
otv_FeatureList_validate( FT_Bytes table,
FT_Bytes lookups,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LANGUAGE SYSTEM *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_LangSys_validate( FT_Bytes table,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** SCRIPTS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
otv_Script_validate( FT_Bytes table,
OTV_Validator valid );
/* features must already be validated */
FT_LOCAL( void )
otv_ScriptList_validate( FT_Bytes table,
FT_Bytes features,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define ChainPosClassSetFunc otv_x_Ox
#define ChainPosRuleSetFunc otv_x_Ox
#define ChainSubClassSetFunc otv_x_Ox
#define ChainSubRuleSetFunc otv_x_Ox
#define JstfLangSysFunc otv_x_Ox
#define JstfMaxFunc otv_x_Ox
#define LigGlyphFunc otv_x_Ox
#define LigatureArrayFunc otv_x_Ox
#define LigatureSetFunc otv_x_Ox
#define PosClassSetFunc otv_x_Ox
#define PosRuleSetFunc otv_x_Ox
#define SubClassSetFunc otv_x_Ox
#define SubRuleSetFunc otv_x_Ox
FT_LOCAL( void )
otv_x_Ox ( FT_Bytes table,
OTV_Validator valid );
#define AlternateSubstFormat1Func otv_u_C_x_Ox
#define ChainContextPosFormat1Func otv_u_C_x_Ox
#define ChainContextSubstFormat1Func otv_u_C_x_Ox
#define ContextPosFormat1Func otv_u_C_x_Ox
#define ContextSubstFormat1Func otv_u_C_x_Ox
#define LigatureSubstFormat1Func otv_u_C_x_Ox
#define MultipleSubstFormat1Func otv_u_C_x_Ox
FT_LOCAL( void )
otv_u_C_x_Ox( FT_Bytes table,
OTV_Validator valid );
#define AlternateSetFunc otv_x_ux
#define AttachPointFunc otv_x_ux
#define ExtenderGlyphFunc otv_x_ux
#define JstfGPOSModListFunc otv_x_ux
#define JstfGSUBModListFunc otv_x_ux
#define SequenceFunc otv_x_ux
FT_LOCAL( void )
otv_x_ux( FT_Bytes table,
OTV_Validator valid );
#define PosClassRuleFunc otv_x_y_ux_sy
#define PosRuleFunc otv_x_y_ux_sy
#define SubClassRuleFunc otv_x_y_ux_sy
#define SubRuleFunc otv_x_y_ux_sy
FT_LOCAL( void )
otv_x_y_ux_sy( FT_Bytes table,
OTV_Validator valid );
#define ChainPosClassRuleFunc otv_x_ux_y_uy_z_uz_p_sp
#define ChainPosRuleFunc otv_x_ux_y_uy_z_uz_p_sp
#define ChainSubClassRuleFunc otv_x_ux_y_uy_z_uz_p_sp
#define ChainSubRuleFunc otv_x_ux_y_uy_z_uz_p_sp
FT_LOCAL( void )
otv_x_ux_y_uy_z_uz_p_sp( FT_Bytes table,
OTV_Validator valid );
#define ContextPosFormat2Func otv_u_O_O_x_Onx
#define ContextSubstFormat2Func otv_u_O_O_x_Onx
FT_LOCAL( void )
otv_u_O_O_x_Onx( FT_Bytes table,
OTV_Validator valid );
#define ContextPosFormat3Func otv_u_x_y_Ox_sy
#define ContextSubstFormat3Func otv_u_x_y_Ox_sy
FT_LOCAL( void )
otv_u_x_y_Ox_sy( FT_Bytes table,
OTV_Validator valid );
#define ChainContextPosFormat2Func otv_u_O_O_O_O_x_Onx
#define ChainContextSubstFormat2Func otv_u_O_O_O_O_x_Onx
FT_LOCAL( void )
otv_u_O_O_O_O_x_Onx( FT_Bytes table,
OTV_Validator valid );
#define ChainContextPosFormat3Func otv_u_x_Ox_y_Oy_z_Oz_p_sp
#define ChainContextSubstFormat3Func otv_u_x_Ox_y_Oy_z_Oz_p_sp
FT_LOCAL( void )
otv_u_x_Ox_y_Oy_z_Oz_p_sp( FT_Bytes table,
OTV_Validator valid );
FT_LOCAL( FT_UInt )
otv_GSUBGPOS_get_Lookup_count( FT_Bytes table );
FT_LOCAL( FT_UInt )
otv_GSUBGPOS_have_MarkAttachmentType_flag( FT_Bytes table );
/* */
FT_END_HEADER
#endif /* __OTVCOMMN_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvcommn.h | C | apache-2.0 | 18,027 |
/***************************************************************************/
/* */
/* otverror.h */
/* */
/* OpenType validation module error codes (specification only). */
/* */
/* Copyright 2004, 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 file is used to define the OpenType validation module error */
/* enumeration constants. */
/* */
/*************************************************************************/
#ifndef __OTVERROR_H__
#define __OTVERROR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX OTV_Err_
#define FT_ERR_BASE FT_Mod_Err_OTvalid
#include FT_ERRORS_H
#endif /* __OTVERROR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otverror.h | C | apache-2.0 | 1,977 |
/***************************************************************************/
/* */
/* otvgdef.c */
/* */
/* OpenType GDEF table validation (body). */
/* */
/* Copyright 2004, 2005, 2007 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 "otvalid.h"
#include "otvcommn.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_otvgdef
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define AttachListFunc otv_O_x_Ox
#define LigCaretListFunc otv_O_x_Ox
/* sets valid->extra1 (0) */
static void
otv_O_x_Ox( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_Bytes Coverage;
FT_UInt GlyphCount;
OTV_Validate_Func func;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
Coverage = table + FT_NEXT_USHORT( p );
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
otv_Coverage_validate( Coverage, valid, GlyphCount );
if ( GlyphCount != otv_Coverage_get_count( Coverage ) )
FT_INVALID_DATA;
OTV_LIMIT_CHECK( GlyphCount * 2 );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
valid->extra1 = 0;
for ( ; GlyphCount > 0; GlyphCount-- )
func( table + FT_NEXT_USHORT( p ), valid );
valid->nesting_level--;
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LIGATURE CARETS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define CaretValueFunc otv_CaretValue_validate
static void
otv_CaretValue_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt CaretValueFormat;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
CaretValueFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format = %d)\n", CaretValueFormat ));
switch ( CaretValueFormat )
{
case 1: /* CaretValueFormat1 */
/* skip Coordinate, no test */
break;
case 2: /* CaretValueFormat2 */
/* skip CaretValuePoint, no test */
break;
case 3: /* CaretValueFormat3 */
p += 2; /* skip Coordinate */
OTV_LIMIT_CHECK( 2 );
/* DeviceTable */
otv_Device_validate( table + FT_NEXT_USHORT( p ), valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GDEF TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->glyph_count */
FT_LOCAL_DEF( void )
otv_GDEF_validate( FT_Bytes table,
FT_Bytes gsub,
FT_Bytes gpos,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt table_size;
FT_Bool need_MarkAttachClassDef;
OTV_OPTIONAL_TABLE( GlyphClassDef );
OTV_OPTIONAL_TABLE( AttachListOffset );
OTV_OPTIONAL_TABLE( LigCaretListOffset );
OTV_OPTIONAL_TABLE( MarkAttachClassDef );
valid->root = ftvalid;
FT_TRACE3(( "validating GDEF table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 12 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
/* MarkAttachClassDef has been added to the OpenType */
/* specification without increasing GDEF's version, */
/* so we use this ugly hack to find out whether the */
/* table is needed actually. */
need_MarkAttachClassDef = FT_BOOL(
otv_GSUBGPOS_have_MarkAttachmentType_flag( gsub ) ||
otv_GSUBGPOS_have_MarkAttachmentType_flag( gpos ) );
if ( need_MarkAttachClassDef )
table_size = 12; /* OpenType >= 1.2 */
else
table_size = 10; /* OpenType < 1.2 */
valid->glyph_count = glyph_count;
OTV_OPTIONAL_OFFSET( GlyphClassDef );
OTV_SIZE_CHECK( GlyphClassDef );
if ( GlyphClassDef )
otv_ClassDef_validate( table + GlyphClassDef, valid );
OTV_OPTIONAL_OFFSET( AttachListOffset );
OTV_SIZE_CHECK( AttachListOffset );
if ( AttachListOffset )
{
OTV_NEST2( AttachList, AttachPoint );
OTV_RUN( table + AttachListOffset, valid );
}
OTV_OPTIONAL_OFFSET( LigCaretListOffset );
OTV_SIZE_CHECK( LigCaretListOffset );
if ( LigCaretListOffset )
{
OTV_NEST3( LigCaretList, LigGlyph, CaretValue );
OTV_RUN( table + LigCaretListOffset, valid );
}
if ( need_MarkAttachClassDef )
{
OTV_OPTIONAL_OFFSET( MarkAttachClassDef );
OTV_SIZE_CHECK( MarkAttachClassDef );
if ( MarkAttachClassDef )
otv_ClassDef_validate( table + MarkAttachClassDef, valid );
}
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvgdef.c | C | apache-2.0 | 7,654 |
/***************************************************************************/
/* */
/* otvgpos.c */
/* */
/* OpenType GPOS table validation (body). */
/* */
/* Copyright 2002, 2004, 2005, 2006, 2007, 2008 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 "otvalid.h"
#include "otvcommn.h"
#include "otvgpos.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_otvgpos
static void
otv_Anchor_validate( FT_Bytes table,
OTV_Validator valid );
static void
otv_MarkArray_validate( FT_Bytes table,
OTV_Validator valid );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define BaseArrayFunc otv_x_sxy
#define LigatureAttachFunc otv_x_sxy
#define Mark2ArrayFunc otv_x_sxy
/* uses valid->extra1 (counter) */
/* uses valid->extra2 (boolean to handle NULL anchor field) */
static void
otv_x_sxy( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Count, count1, table_size;
OTV_ENTER;
OTV_LIMIT_CHECK( 2 );
Count = FT_NEXT_USHORT( p );
OTV_TRACE(( " (Count = %d)\n", Count ));
OTV_LIMIT_CHECK( Count * valid->extra1 * 2 );
table_size = Count * valid->extra1 * 2 + 2;
for ( ; Count > 0; Count-- )
for ( count1 = valid->extra1; count1 > 0; count1-- )
{
OTV_OPTIONAL_TABLE( anchor_offset );
OTV_OPTIONAL_OFFSET( anchor_offset );
if ( valid->extra2 )
{
OTV_SIZE_CHECK( anchor_offset );
if ( anchor_offset )
otv_Anchor_validate( table + anchor_offset, valid );
}
else
otv_Anchor_validate( table + anchor_offset, valid );
}
OTV_EXIT;
}
#define MarkBasePosFormat1Func otv_u_O_O_u_O_O
#define MarkLigPosFormat1Func otv_u_O_O_u_O_O
#define MarkMarkPosFormat1Func otv_u_O_O_u_O_O
/* sets valid->extra1 (class count) */
static void
otv_u_O_O_u_O_O( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt Coverage1, Coverage2, ClassCount;
FT_UInt Array1, Array2;
OTV_Validate_Func func;
OTV_ENTER;
p += 2; /* skip PosFormat */
OTV_LIMIT_CHECK( 10 );
Coverage1 = FT_NEXT_USHORT( p );
Coverage2 = FT_NEXT_USHORT( p );
ClassCount = FT_NEXT_USHORT( p );
Array1 = FT_NEXT_USHORT( p );
Array2 = FT_NEXT_USHORT( p );
otv_Coverage_validate( table + Coverage1, valid, -1 );
otv_Coverage_validate( table + Coverage2, valid, -1 );
otv_MarkArray_validate( table + Array1, valid );
valid->nesting_level++;
func = valid->func[valid->nesting_level];
valid->extra1 = ClassCount;
func( table + Array2, valid );
valid->nesting_level--;
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** VALUE RECORDS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static FT_UInt
otv_value_length( FT_UInt format )
{
FT_UInt count;
count = ( ( format & 0xAA ) >> 1 ) + ( format & 0x55 );
count = ( ( count & 0xCC ) >> 2 ) + ( count & 0x33 );
count = ( ( count & 0xF0 ) >> 4 ) + ( count & 0x0F );
return count * 2;
}
/* uses valid->extra3 (pointer to base table) */
static void
otv_ValueRecord_validate( FT_Bytes table,
FT_UInt format,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt count;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Int loop;
FT_ULong res = 0;
OTV_NAME_ENTER( "ValueRecord" );
/* display `format' in dual representation */
for ( loop = 7; loop >= 0; loop-- )
{
res <<= 4;
res += ( format >> loop ) & 1;
}
OTV_TRACE(( " (format 0b%08lx)\n", res ));
#endif
if ( format >= 0x100 )
FT_INVALID_FORMAT;
for ( count = 4; count > 0; count-- )
{
if ( format & 1 )
{
/* XPlacement, YPlacement, XAdvance, YAdvance */
OTV_LIMIT_CHECK( 2 );
p += 2;
}
format >>= 1;
}
for ( count = 4; count > 0; count-- )
{
if ( format & 1 )
{
FT_PtrDist table_size;
OTV_OPTIONAL_TABLE( device );
/* XPlaDevice, YPlaDevice, XAdvDevice, YAdvDevice */
OTV_LIMIT_CHECK( 2 );
OTV_OPTIONAL_OFFSET( device );
/* XXX: this value is usually too small, especially if the current */
/* ValueRecord is part of an array -- getting the correct table */
/* size is probably not worth the trouble */
table_size = p - valid->extra3;
OTV_SIZE_CHECK( device );
if ( device )
otv_Device_validate( valid->extra3 + device, valid );
}
format >>= 1;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** ANCHORS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_Anchor_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt AnchorFormat;
OTV_NAME_ENTER( "Anchor");
OTV_LIMIT_CHECK( 6 );
AnchorFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", AnchorFormat ));
p += 4; /* skip XCoordinate and YCoordinate */
switch ( AnchorFormat )
{
case 1:
break;
case 2:
OTV_LIMIT_CHECK( 2 ); /* AnchorPoint */
break;
case 3:
{
FT_UInt table_size;
OTV_OPTIONAL_TABLE( XDeviceTable );
OTV_OPTIONAL_TABLE( YDeviceTable );
OTV_LIMIT_CHECK( 4 );
OTV_OPTIONAL_OFFSET( XDeviceTable );
OTV_OPTIONAL_OFFSET( YDeviceTable );
table_size = 6 + 4;
OTV_SIZE_CHECK( XDeviceTable );
if ( XDeviceTable )
otv_Device_validate( table + XDeviceTable, valid );
OTV_SIZE_CHECK( YDeviceTable );
if ( YDeviceTable )
otv_Device_validate( table + YDeviceTable, valid );
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MARK ARRAYS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_MarkArray_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt MarkCount;
OTV_NAME_ENTER( "MarkArray" );
OTV_LIMIT_CHECK( 2 );
MarkCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (MarkCount = %d)\n", MarkCount ));
OTV_LIMIT_CHECK( MarkCount * 4 );
/* MarkRecord */
for ( ; MarkCount > 0; MarkCount-- )
{
p += 2; /* skip Class */
/* MarkAnchor */
otv_Anchor_validate( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 1 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra3 (pointer to base table) */
static void
otv_SinglePos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "SinglePos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
valid->extra3 = table;
switch ( PosFormat )
{
case 1: /* SinglePosFormat1 */
{
FT_UInt Coverage, ValueFormat;
OTV_LIMIT_CHECK( 4 );
Coverage = FT_NEXT_USHORT( p );
ValueFormat = FT_NEXT_USHORT( p );
otv_Coverage_validate( table + Coverage, valid, -1 );
otv_ValueRecord_validate( p, ValueFormat, valid ); /* Value */
}
break;
case 2: /* SinglePosFormat2 */
{
FT_UInt Coverage, ValueFormat, ValueCount, len_value;
OTV_LIMIT_CHECK( 6 );
Coverage = FT_NEXT_USHORT( p );
ValueFormat = FT_NEXT_USHORT( p );
ValueCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ValueCount = %d)\n", ValueCount ));
len_value = otv_value_length( ValueFormat );
otv_Coverage_validate( table + Coverage, valid, ValueCount );
OTV_LIMIT_CHECK( ValueCount * len_value );
/* Value */
for ( ; ValueCount > 0; ValueCount-- )
{
otv_ValueRecord_validate( p, ValueFormat, valid );
p += len_value;
}
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 2 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_PairSet_validate( FT_Bytes table,
FT_UInt format1,
FT_UInt format2,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt value_len1, value_len2, PairValueCount;
OTV_NAME_ENTER( "PairSet" );
OTV_LIMIT_CHECK( 2 );
PairValueCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (PairValueCount = %d)\n", PairValueCount ));
value_len1 = otv_value_length( format1 );
value_len2 = otv_value_length( format2 );
OTV_LIMIT_CHECK( PairValueCount * ( value_len1 + value_len2 + 2 ) );
/* PairValueRecord */
for ( ; PairValueCount > 0; PairValueCount-- )
{
p += 2; /* skip SecondGlyph */
if ( format1 )
otv_ValueRecord_validate( p, format1, valid ); /* Value1 */
p += value_len1;
if ( format2 )
otv_ValueRecord_validate( p, format2, valid ); /* Value2 */
p += value_len2;
}
OTV_EXIT;
}
/* sets valid->extra3 (pointer to base table) */
static void
otv_PairPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "PairPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
valid->extra3 = table;
switch ( PosFormat )
{
case 1: /* PairPosFormat1 */
{
FT_UInt Coverage, ValueFormat1, ValueFormat2, PairSetCount;
OTV_LIMIT_CHECK( 8 );
Coverage = FT_NEXT_USHORT( p );
ValueFormat1 = FT_NEXT_USHORT( p );
ValueFormat2 = FT_NEXT_USHORT( p );
PairSetCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (PairSetCount = %d)\n", PairSetCount ));
otv_Coverage_validate( table + Coverage, valid, -1 );
OTV_LIMIT_CHECK( PairSetCount * 2 );
/* PairSetOffset */
for ( ; PairSetCount > 0; PairSetCount-- )
otv_PairSet_validate( table + FT_NEXT_USHORT( p ),
ValueFormat1, ValueFormat2, valid );
}
break;
case 2: /* PairPosFormat2 */
{
FT_UInt Coverage, ValueFormat1, ValueFormat2, ClassDef1, ClassDef2;
FT_UInt ClassCount1, ClassCount2, len_value1, len_value2, count;
OTV_LIMIT_CHECK( 14 );
Coverage = FT_NEXT_USHORT( p );
ValueFormat1 = FT_NEXT_USHORT( p );
ValueFormat2 = FT_NEXT_USHORT( p );
ClassDef1 = FT_NEXT_USHORT( p );
ClassDef2 = FT_NEXT_USHORT( p );
ClassCount1 = FT_NEXT_USHORT( p );
ClassCount2 = FT_NEXT_USHORT( p );
OTV_TRACE(( " (ClassCount1 = %d)\n", ClassCount1 ));
OTV_TRACE(( " (ClassCount2 = %d)\n", ClassCount2 ));
len_value1 = otv_value_length( ValueFormat1 );
len_value2 = otv_value_length( ValueFormat2 );
otv_Coverage_validate( table + Coverage, valid, -1 );
otv_ClassDef_validate( table + ClassDef1, valid );
otv_ClassDef_validate( table + ClassDef2, valid );
OTV_LIMIT_CHECK( ClassCount1 * ClassCount2 *
( len_value1 + len_value2 ) );
/* Class1Record */
for ( ; ClassCount1 > 0; ClassCount1-- )
{
/* Class2Record */
for ( count = ClassCount2; count > 0; count-- )
{
if ( ValueFormat1 )
/* Value1 */
otv_ValueRecord_validate( p, ValueFormat1, valid );
p += len_value1;
if ( ValueFormat2 )
/* Value2 */
otv_ValueRecord_validate( p, ValueFormat2, valid );
p += len_value2;
}
}
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 3 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_CursivePos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "CursivePos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1: /* CursivePosFormat1 */
{
FT_UInt table_size;
FT_UInt Coverage, EntryExitCount;
OTV_OPTIONAL_TABLE( EntryAnchor );
OTV_OPTIONAL_TABLE( ExitAnchor );
OTV_LIMIT_CHECK( 4 );
Coverage = FT_NEXT_USHORT( p );
EntryExitCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (EntryExitCount = %d)\n", EntryExitCount ));
otv_Coverage_validate( table + Coverage, valid, EntryExitCount );
OTV_LIMIT_CHECK( EntryExitCount * 4 );
table_size = EntryExitCount * 4 + 4;
/* EntryExitRecord */
for ( ; EntryExitCount > 0; EntryExitCount-- )
{
OTV_OPTIONAL_OFFSET( EntryAnchor );
OTV_OPTIONAL_OFFSET( ExitAnchor );
OTV_SIZE_CHECK( EntryAnchor );
if ( EntryAnchor )
otv_Anchor_validate( table + EntryAnchor, valid );
OTV_SIZE_CHECK( ExitAnchor );
if ( ExitAnchor )
otv_Anchor_validate( table + ExitAnchor, valid );
}
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 4 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* UNDOCUMENTED (in OpenType 1.5): */
/* BaseRecord tables can contain NULL pointers. */
/* sets valid->extra2 (1) */
static void
otv_MarkBasePos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "MarkBasePos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1:
valid->extra2 = 1;
OTV_NEST2( MarkBasePosFormat1, BaseArray );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 5 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra2 (1) */
static void
otv_MarkLigPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "MarkLigPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1:
valid->extra2 = 1;
OTV_NEST3( MarkLigPosFormat1, LigatureArray, LigatureAttach );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 6 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra2 (0) */
static void
otv_MarkMarkPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "MarkMarkPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1:
valid->extra2 = 0;
OTV_NEST2( MarkMarkPosFormat1, Mark2Array );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 7 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (lookup count) */
static void
otv_ContextPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "ContextPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
valid->extra1 = valid->lookup_count;
OTV_NEST3( ContextPosFormat1, PosRuleSet, PosRule );
OTV_RUN( table, valid );
break;
case 2:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
OTV_NEST3( ContextPosFormat2, PosClassSet, PosClassRule );
OTV_RUN( table, valid );
break;
case 3:
OTV_NEST1( ContextPosFormat3 );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 8 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (lookup count) */
static void
otv_ChainContextPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "ChainContextPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
valid->extra1 = valid->lookup_count;
OTV_NEST3( ChainContextPosFormat1,
ChainPosRuleSet, ChainPosRule );
OTV_RUN( table, valid );
break;
case 2:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
OTV_NEST3( ChainContextPosFormat2,
ChainPosClassSet, ChainPosClassRule );
OTV_RUN( table, valid );
break;
case 3:
OTV_NEST1( ChainContextPosFormat3 );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS LOOKUP TYPE 9 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->type_funcs */
static void
otv_ExtensionPos_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt PosFormat;
OTV_NAME_ENTER( "ExtensionPos" );
OTV_LIMIT_CHECK( 2 );
PosFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", PosFormat ));
switch ( PosFormat )
{
case 1: /* ExtensionPosFormat1 */
{
FT_UInt ExtensionLookupType;
FT_ULong ExtensionOffset;
OTV_Validate_Func validate;
OTV_LIMIT_CHECK( 6 );
ExtensionLookupType = FT_NEXT_USHORT( p );
ExtensionOffset = FT_NEXT_ULONG( p );
if ( ExtensionLookupType == 0 || ExtensionLookupType >= 9 )
FT_INVALID_DATA;
validate = valid->type_funcs[ExtensionLookupType - 1];
validate( table + ExtensionOffset, valid );
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
static const OTV_Validate_Func otv_gpos_validate_funcs[9] =
{
otv_SinglePos_validate,
otv_PairPos_validate,
otv_CursivePos_validate,
otv_MarkBasePos_validate,
otv_MarkLigPos_validate,
otv_MarkMarkPos_validate,
otv_ContextPos_validate,
otv_ChainContextPos_validate,
otv_ExtensionPos_validate
};
/* sets valid->type_count */
/* sets valid->type_funcs */
FT_LOCAL_DEF( void )
otv_GPOS_subtable_validate( FT_Bytes table,
OTV_Validator valid )
{
valid->type_count = 9;
valid->type_funcs = (OTV_Validate_Func*)otv_gpos_validate_funcs;
otv_Lookup_validate( table, valid );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GPOS TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->glyph_count */
FT_LOCAL_DEF( void )
otv_GPOS_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt ScriptList, FeatureList, LookupList;
valid->root = ftvalid;
FT_TRACE3(( "validating GPOS table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 10 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
ScriptList = FT_NEXT_USHORT( p );
FeatureList = FT_NEXT_USHORT( p );
LookupList = FT_NEXT_USHORT( p );
valid->type_count = 9;
valid->type_funcs = (OTV_Validate_Func*)otv_gpos_validate_funcs;
valid->glyph_count = glyph_count;
otv_LookupList_validate( table + LookupList,
valid );
otv_FeatureList_validate( table + FeatureList, table + LookupList,
valid );
otv_ScriptList_validate( table + ScriptList, table + FeatureList,
valid );
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvgpos.c | C | apache-2.0 | 29,754 |
/***************************************************************************/
/* */
/* otvgpos.h */
/* */
/* OpenType GPOS table validator (specification). */
/* */
/* Copyright 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 __OTVGPOS_H__
#define __OTVGPOS_H__
FT_BEGIN_HEADER
FT_LOCAL( void )
otv_GPOS_subtable_validate( FT_Bytes table,
OTV_Validator valid );
FT_END_HEADER
#endif /* __OTVGPOS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvgpos.h | C | apache-2.0 | 1,495 |
/***************************************************************************/
/* */
/* otvgsub.c */
/* */
/* OpenType GSUB table validation (body). */
/* */
/* Copyright 2004, 2005, 2007 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 "otvalid.h"
#include "otvcommn.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_otvgsub
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 1 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->glyph_count */
static void
otv_SingleSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "SingleSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1: /* SingleSubstFormat1 */
{
FT_Bytes Coverage;
FT_Int DeltaGlyphID;
FT_Long idx;
OTV_LIMIT_CHECK( 4 );
Coverage = table + FT_NEXT_USHORT( p );
DeltaGlyphID = FT_NEXT_SHORT( p );
otv_Coverage_validate( Coverage, valid, -1 );
idx = otv_Coverage_get_first( Coverage ) + DeltaGlyphID;
if ( idx < 0 )
FT_INVALID_DATA;
idx = otv_Coverage_get_last( Coverage ) + DeltaGlyphID;
if ( (FT_UInt)idx >= valid->glyph_count )
FT_INVALID_DATA;
}
break;
case 2: /* SingleSubstFormat2 */
{
FT_UInt Coverage, GlyphCount;
OTV_LIMIT_CHECK( 4 );
Coverage = FT_NEXT_USHORT( p );
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
otv_Coverage_validate( table + Coverage, valid, GlyphCount );
OTV_LIMIT_CHECK( GlyphCount * 2 );
/* Substitute */
for ( ; GlyphCount > 0; GlyphCount-- )
if ( FT_NEXT_USHORT( p ) >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 2 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (glyph count) */
static void
otv_MultipleSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "MultipleSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1:
valid->extra1 = valid->glyph_count;
OTV_NEST2( MultipleSubstFormat1, Sequence );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 3 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (glyph count) */
static void
otv_AlternateSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "AlternateSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1:
valid->extra1 = valid->glyph_count;
OTV_NEST2( AlternateSubstFormat1, AlternateSet );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 4 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define LigatureFunc otv_Ligature_validate
/* uses valid->glyph_count */
static void
otv_Ligature_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt LigatureGlyph, CompCount;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
LigatureGlyph = FT_NEXT_USHORT( p );
if ( LigatureGlyph >= valid->glyph_count )
FT_INVALID_DATA;
CompCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (CompCount = %d)\n", CompCount ));
if ( CompCount == 0 )
FT_INVALID_DATA;
CompCount--;
OTV_LIMIT_CHECK( CompCount * 2 ); /* Component */
/* no need to check the Component glyph indices */
OTV_EXIT;
}
static void
otv_LigatureSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "LigatureSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1:
OTV_NEST3( LigatureSubstFormat1, LigatureSet, Ligature );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 5 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (lookup count) */
static void
otv_ContextSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "ContextSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
valid->extra1 = valid->lookup_count;
OTV_NEST3( ContextSubstFormat1, SubRuleSet, SubRule );
OTV_RUN( table, valid );
break;
case 2:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
OTV_NEST3( ContextSubstFormat2, SubClassSet, SubClassRule );
OTV_RUN( table, valid );
break;
case 3:
OTV_NEST1( ContextSubstFormat3 );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 6 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->extra1 (lookup count) */
static void
otv_ChainContextSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "ChainContextSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
valid->extra1 = valid->lookup_count;
OTV_NEST3( ChainContextSubstFormat1,
ChainSubRuleSet, ChainSubRule );
OTV_RUN( table, valid );
break;
case 2:
/* no need to check glyph indices/classes used as input for these */
/* context rules since even invalid glyph indices/classes return */
/* meaningful results */
OTV_NEST3( ChainContextSubstFormat2,
ChainSubClassSet, ChainSubClassRule );
OTV_RUN( table, valid );
break;
case 3:
OTV_NEST1( ChainContextSubstFormat3 );
OTV_RUN( table, valid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 7 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->type_funcs */
static void
otv_ExtensionSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt SubstFormat;
OTV_NAME_ENTER( "ExtensionSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1: /* ExtensionSubstFormat1 */
{
FT_UInt ExtensionLookupType;
FT_ULong ExtensionOffset;
OTV_Validate_Func validate;
OTV_LIMIT_CHECK( 6 );
ExtensionLookupType = FT_NEXT_USHORT( p );
ExtensionOffset = FT_NEXT_ULONG( p );
if ( ExtensionLookupType == 0 ||
ExtensionLookupType == 7 ||
ExtensionLookupType > 8 )
FT_INVALID_DATA;
validate = valid->type_funcs[ExtensionLookupType - 1];
validate( table + ExtensionOffset, valid );
}
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB LOOKUP TYPE 8 *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* uses valid->glyph_count */
static void
otv_ReverseChainSingleSubst_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table, Coverage;
FT_UInt SubstFormat;
FT_UInt BacktrackGlyphCount, LookaheadGlyphCount, GlyphCount;
OTV_NAME_ENTER( "ReverseChainSingleSubst" );
OTV_LIMIT_CHECK( 2 );
SubstFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format %d)\n", SubstFormat ));
switch ( SubstFormat )
{
case 1: /* ReverseChainSingleSubstFormat1 */
OTV_LIMIT_CHECK( 4 );
Coverage = table + FT_NEXT_USHORT( p );
BacktrackGlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (BacktrackGlyphCount = %d)\n", BacktrackGlyphCount ));
otv_Coverage_validate( Coverage, valid, -1 );
OTV_LIMIT_CHECK( BacktrackGlyphCount * 2 + 2 );
for ( ; BacktrackGlyphCount > 0; BacktrackGlyphCount-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
LookaheadGlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (LookaheadGlyphCount = %d)\n", LookaheadGlyphCount ));
OTV_LIMIT_CHECK( LookaheadGlyphCount * 2 + 2 );
for ( ; LookaheadGlyphCount > 0; LookaheadGlyphCount-- )
otv_Coverage_validate( table + FT_NEXT_USHORT( p ), valid, -1 );
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
if ( GlyphCount != otv_Coverage_get_count( Coverage ) )
FT_INVALID_DATA;
OTV_LIMIT_CHECK( GlyphCount * 2 );
/* Substitute */
for ( ; GlyphCount > 0; GlyphCount-- )
if ( FT_NEXT_USHORT( p ) >= valid->glyph_count )
FT_INVALID_DATA;
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
static const OTV_Validate_Func otv_gsub_validate_funcs[8] =
{
otv_SingleSubst_validate,
otv_MultipleSubst_validate,
otv_AlternateSubst_validate,
otv_LigatureSubst_validate,
otv_ContextSubst_validate,
otv_ChainContextSubst_validate,
otv_ExtensionSubst_validate,
otv_ReverseChainSingleSubst_validate
};
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GSUB TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->type_count */
/* sets valid->type_funcs */
/* sets valid->glyph_count */
FT_LOCAL_DEF( void )
otv_GSUB_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt ScriptList, FeatureList, LookupList;
valid->root = ftvalid;
FT_TRACE3(( "validating GSUB table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 10 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
ScriptList = FT_NEXT_USHORT( p );
FeatureList = FT_NEXT_USHORT( p );
LookupList = FT_NEXT_USHORT( p );
valid->type_count = 8;
valid->type_funcs = (OTV_Validate_Func*)otv_gsub_validate_funcs;
valid->glyph_count = glyph_count;
otv_LookupList_validate( table + LookupList,
valid );
otv_FeatureList_validate( table + FeatureList, table + LookupList,
valid );
otv_ScriptList_validate( table + ScriptList, table + FeatureList,
valid );
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvgsub.c | C | apache-2.0 | 18,031 |
/***************************************************************************/
/* */
/* otvjstf.c */
/* */
/* OpenType JSTF table validation (body). */
/* */
/* Copyright 2004, 2007 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 "otvalid.h"
#include "otvcommn.h"
#include "otvgpos.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_otvjstf
#define JstfPriorityFunc otv_JstfPriority_validate
#define JstfLookupFunc otv_GPOS_subtable_validate
/* uses valid->extra1 (GSUB lookup count) */
/* uses valid->extra2 (GPOS lookup count) */
/* sets valid->extra1 (counter) */
static void
otv_JstfPriority_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt table_size;
FT_UInt gsub_lookup_count, gpos_lookup_count;
OTV_OPTIONAL_TABLE( ShrinkageEnableGSUB );
OTV_OPTIONAL_TABLE( ShrinkageDisableGSUB );
OTV_OPTIONAL_TABLE( ShrinkageEnableGPOS );
OTV_OPTIONAL_TABLE( ShrinkageDisableGPOS );
OTV_OPTIONAL_TABLE( ExtensionEnableGSUB );
OTV_OPTIONAL_TABLE( ExtensionDisableGSUB );
OTV_OPTIONAL_TABLE( ExtensionEnableGPOS );
OTV_OPTIONAL_TABLE( ExtensionDisableGPOS );
OTV_OPTIONAL_TABLE( ShrinkageJstfMax );
OTV_OPTIONAL_TABLE( ExtensionJstfMax );
OTV_ENTER;
OTV_TRACE(( "JstfPriority table\n" ));
OTV_LIMIT_CHECK( 20 );
gsub_lookup_count = valid->extra1;
gpos_lookup_count = valid->extra2;
table_size = 20;
valid->extra1 = gsub_lookup_count;
OTV_OPTIONAL_OFFSET( ShrinkageEnableGSUB );
OTV_SIZE_CHECK( ShrinkageEnableGSUB );
if ( ShrinkageEnableGSUB )
otv_x_ux( table + ShrinkageEnableGSUB, valid );
OTV_OPTIONAL_OFFSET( ShrinkageDisableGSUB );
OTV_SIZE_CHECK( ShrinkageDisableGSUB );
if ( ShrinkageDisableGSUB )
otv_x_ux( table + ShrinkageDisableGSUB, valid );
valid->extra1 = gpos_lookup_count;
OTV_OPTIONAL_OFFSET( ShrinkageEnableGPOS );
OTV_SIZE_CHECK( ShrinkageEnableGPOS );
if ( ShrinkageEnableGPOS )
otv_x_ux( table + ShrinkageEnableGPOS, valid );
OTV_OPTIONAL_OFFSET( ShrinkageDisableGPOS );
OTV_SIZE_CHECK( ShrinkageDisableGPOS );
if ( ShrinkageDisableGPOS )
otv_x_ux( table + ShrinkageDisableGPOS, valid );
OTV_OPTIONAL_OFFSET( ShrinkageJstfMax );
OTV_SIZE_CHECK( ShrinkageJstfMax );
if ( ShrinkageJstfMax )
{
/* XXX: check lookup types? */
OTV_NEST2( JstfMax, JstfLookup );
OTV_RUN( table + ShrinkageJstfMax, valid );
}
valid->extra1 = gsub_lookup_count;
OTV_OPTIONAL_OFFSET( ExtensionEnableGSUB );
OTV_SIZE_CHECK( ExtensionEnableGSUB );
if ( ExtensionEnableGSUB )
otv_x_ux( table + ExtensionEnableGSUB, valid );
OTV_OPTIONAL_OFFSET( ExtensionDisableGSUB );
OTV_SIZE_CHECK( ExtensionDisableGSUB );
if ( ExtensionDisableGSUB )
otv_x_ux( table + ExtensionDisableGSUB, valid );
valid->extra1 = gpos_lookup_count;
OTV_OPTIONAL_OFFSET( ExtensionEnableGPOS );
OTV_SIZE_CHECK( ExtensionEnableGPOS );
if ( ExtensionEnableGPOS )
otv_x_ux( table + ExtensionEnableGPOS, valid );
OTV_OPTIONAL_OFFSET( ExtensionDisableGPOS );
OTV_SIZE_CHECK( ExtensionDisableGPOS );
if ( ExtensionDisableGPOS )
otv_x_ux( table + ExtensionDisableGPOS, valid );
OTV_OPTIONAL_OFFSET( ExtensionJstfMax );
OTV_SIZE_CHECK( ExtensionJstfMax );
if ( ExtensionJstfMax )
{
/* XXX: check lookup types? */
OTV_NEST2( JstfMax, JstfLookup );
OTV_RUN( table + ExtensionJstfMax, valid );
}
valid->extra1 = gsub_lookup_count;
valid->extra2 = gpos_lookup_count;
OTV_EXIT;
}
/* sets valid->extra (glyph count) */
/* sets valid->func1 (otv_JstfPriority_validate) */
static void
otv_JstfScript_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt table_size;
FT_UInt JstfLangSysCount;
OTV_OPTIONAL_TABLE( ExtGlyph );
OTV_OPTIONAL_TABLE( DefJstfLangSys );
OTV_NAME_ENTER( "JstfScript" );
OTV_LIMIT_CHECK( 6 );
OTV_OPTIONAL_OFFSET( ExtGlyph );
OTV_OPTIONAL_OFFSET( DefJstfLangSys );
JstfLangSysCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (JstfLangSysCount = %d)\n", JstfLangSysCount ));
table_size = JstfLangSysCount * 6 + 6;
OTV_SIZE_CHECK( ExtGlyph );
if ( ExtGlyph )
{
valid->extra1 = valid->glyph_count;
OTV_NEST1( ExtenderGlyph );
OTV_RUN( table + ExtGlyph, valid );
}
OTV_SIZE_CHECK( DefJstfLangSys );
if ( DefJstfLangSys )
{
OTV_NEST2( JstfLangSys, JstfPriority );
OTV_RUN( table + DefJstfLangSys, valid );
}
OTV_LIMIT_CHECK( 6 * JstfLangSysCount );
/* JstfLangSysRecord */
OTV_NEST2( JstfLangSys, JstfPriority );
for ( ; JstfLangSysCount > 0; JstfLangSysCount-- )
{
p += 4; /* skip JstfLangSysTag */
OTV_RUN( table + FT_NEXT_USHORT( p ), valid );
}
OTV_EXIT;
}
/* sets valid->extra1 (GSUB lookup count) */
/* sets valid->extra2 (GPOS lookup count) */
/* sets valid->glyph_count */
FT_LOCAL_DEF( void )
otv_JSTF_validate( FT_Bytes table,
FT_Bytes gsub,
FT_Bytes gpos,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt JstfScriptCount;
valid->root = ftvalid;
FT_TRACE3(( "validating JSTF table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 6 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
JstfScriptCount = FT_NEXT_USHORT( p );
FT_TRACE3(( " (JstfScriptCount = %d)\n", JstfScriptCount ));
OTV_LIMIT_CHECK( JstfScriptCount * 6 );
if ( gsub )
valid->extra1 = otv_GSUBGPOS_get_Lookup_count( gsub );
else
valid->extra1 = 0;
if ( gpos )
valid->extra2 = otv_GSUBGPOS_get_Lookup_count( gpos );
else
valid->extra2 = 0;
valid->glyph_count = glyph_count;
/* JstfScriptRecord */
for ( ; JstfScriptCount > 0; JstfScriptCount-- )
{
p += 4; /* skip JstfScriptTag */
/* JstfScript */
otv_JstfScript_validate( table + FT_NEXT_USHORT( p ), valid );
}
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvjstf.c | C | apache-2.0 | 7,956 |
/***************************************************************************/
/* */
/* otvmath.c */
/* */
/* OpenType MATH table validation (body). */
/* */
/* Copyright 2007, 2008 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* Written by George Williams. */
/* */
/* 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 "otvalid.h"
#include "otvcommn.h"
#include "otvgpos.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_otvmath
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH TYPOGRAPHIC CONSTANTS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_MathConstants_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt i;
FT_UInt table_size;
OTV_OPTIONAL_TABLE( DeviceTableOffset );
OTV_NAME_ENTER( "MathConstants" );
/* 56 constants, 51 have device tables */
OTV_LIMIT_CHECK( 2 * ( 56 + 51 ) );
table_size = 2 * ( 56 + 51 );
p += 4 * 2; /* First 4 constants have no device tables */
for ( i = 0; i < 51; ++i )
{
p += 2; /* skip the value */
OTV_OPTIONAL_OFFSET( DeviceTableOffset );
OTV_SIZE_CHECK( DeviceTableOffset );
if ( DeviceTableOffset )
otv_Device_validate( table + DeviceTableOffset, valid );
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH ITALICS CORRECTION *****/
/***** MATH TOP ACCENT ATTACHMENT *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_MathItalicsCorrectionInfo_validate( FT_Bytes table,
OTV_Validator valid,
FT_Int isItalic )
{
FT_Bytes p = table;
FT_UInt i, cnt, table_size ;
OTV_OPTIONAL_TABLE( Coverage );
OTV_OPTIONAL_TABLE( DeviceTableOffset );
FT_UNUSED( isItalic ); /* only used if tracing is active */
OTV_NAME_ENTER( isItalic ? "MathItalicsCorrectionInfo"
: "MathTopAccentAttachment" );
OTV_LIMIT_CHECK( 4 );
OTV_OPTIONAL_OFFSET( Coverage );
cnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 4 * cnt );
table_size = 4 + 4 * cnt;
OTV_SIZE_CHECK( Coverage );
otv_Coverage_validate( table + Coverage, valid, cnt );
for ( i = 0; i < cnt; ++i )
{
p += 2; /* Skip the value */
OTV_OPTIONAL_OFFSET( DeviceTableOffset );
OTV_SIZE_CHECK( DeviceTableOffset );
if ( DeviceTableOffset )
otv_Device_validate( table + DeviceTableOffset, valid );
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH KERNING *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_MathKern_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt i, cnt, table_size;
OTV_OPTIONAL_TABLE( DeviceTableOffset );
/* OTV_NAME_ENTER( "MathKern" );*/
OTV_LIMIT_CHECK( 2 );
cnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 4 * cnt + 2 );
table_size = 4 + 4 * cnt;
/* Heights */
for ( i = 0; i < cnt; ++i )
{
p += 2; /* Skip the value */
OTV_OPTIONAL_OFFSET( DeviceTableOffset );
OTV_SIZE_CHECK( DeviceTableOffset );
if ( DeviceTableOffset )
otv_Device_validate( table + DeviceTableOffset, valid );
}
/* One more Kerning value */
for ( i = 0; i < cnt + 1; ++i )
{
p += 2; /* Skip the value */
OTV_OPTIONAL_OFFSET( DeviceTableOffset );
OTV_SIZE_CHECK( DeviceTableOffset );
if ( DeviceTableOffset )
otv_Device_validate( table + DeviceTableOffset, valid );
}
OTV_EXIT;
}
static void
otv_MathKernInfo_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt i, j, cnt, table_size;
OTV_OPTIONAL_TABLE( Coverage );
OTV_OPTIONAL_TABLE( MKRecordOffset );
OTV_NAME_ENTER( "MathKernInfo" );
OTV_LIMIT_CHECK( 4 );
OTV_OPTIONAL_OFFSET( Coverage );
cnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 8 * cnt );
table_size = 4 + 8 * cnt;
OTV_SIZE_CHECK( Coverage );
otv_Coverage_validate( table + Coverage, valid, cnt );
for ( i = 0; i < cnt; ++i )
{
for ( j = 0; j < 4; ++j )
{
OTV_OPTIONAL_OFFSET( MKRecordOffset );
OTV_SIZE_CHECK( MKRecordOffset );
if ( MKRecordOffset )
otv_MathKern_validate( table + MKRecordOffset, valid );
}
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH GLYPH INFO *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_MathGlyphInfo_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt MathItalicsCorrectionInfo, MathTopAccentAttachment;
FT_UInt ExtendedShapeCoverage, MathKernInfo;
OTV_NAME_ENTER( "MathGlyphInfo" );
OTV_LIMIT_CHECK( 8 );
MathItalicsCorrectionInfo = FT_NEXT_USHORT( p );
MathTopAccentAttachment = FT_NEXT_USHORT( p );
ExtendedShapeCoverage = FT_NEXT_USHORT( p );
MathKernInfo = FT_NEXT_USHORT( p );
if ( MathItalicsCorrectionInfo )
otv_MathItalicsCorrectionInfo_validate(
table + MathItalicsCorrectionInfo, valid, TRUE );
/* Italic correction and Top Accent Attachment have the same format */
if ( MathTopAccentAttachment )
otv_MathItalicsCorrectionInfo_validate(
table + MathTopAccentAttachment, valid, FALSE );
if ( ExtendedShapeCoverage )
{
OTV_NAME_ENTER( "ExtendedShapeCoverage" );
otv_Coverage_validate( table + ExtendedShapeCoverage, valid, -1 );
OTV_EXIT;
}
if ( MathKernInfo )
otv_MathKernInfo_validate( table + MathKernInfo, valid );
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH GLYPH CONSTRUCTION *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
otv_GlyphAssembly_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt pcnt, table_size;
FT_UInt i;
OTV_OPTIONAL_TABLE( DeviceTableOffset );
/* OTV_NAME_ENTER( "GlyphAssembly" ); */
OTV_LIMIT_CHECK( 6 );
p += 2; /* Skip the Italics Correction value */
OTV_OPTIONAL_OFFSET( DeviceTableOffset );
pcnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 8 * pcnt );
table_size = 6 + 8 * pcnt;
OTV_SIZE_CHECK( DeviceTableOffset );
if ( DeviceTableOffset )
otv_Device_validate( table + DeviceTableOffset, valid );
for ( i = 0; i < pcnt; ++i )
{
FT_UInt gid;
gid = FT_NEXT_USHORT( p );
if ( gid >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
p += 2*4; /* skip the Start, End, Full, and Flags fields */
}
/* OTV_EXIT; */
}
static void
otv_MathGlyphConstruction_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt vcnt, table_size;
FT_UInt i;
OTV_OPTIONAL_TABLE( GlyphAssembly );
/* OTV_NAME_ENTER( "MathGlyphConstruction" ); */
OTV_LIMIT_CHECK( 4 );
OTV_OPTIONAL_OFFSET( GlyphAssembly );
vcnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 4 * vcnt );
table_size = 4 + 4 * vcnt;
for ( i = 0; i < vcnt; ++i )
{
FT_UInt gid;
gid = FT_NEXT_USHORT( p );
if ( gid >= valid->glyph_count )
FT_INVALID_GLYPH_ID;
p += 2; /* skip the size */
}
OTV_SIZE_CHECK( GlyphAssembly );
if ( GlyphAssembly )
otv_GlyphAssembly_validate( table+GlyphAssembly, valid );
/* OTV_EXIT; */
}
static void
otv_MathVariants_validate( FT_Bytes table,
OTV_Validator valid )
{
FT_Bytes p = table;
FT_UInt vcnt, hcnt, i, table_size;
OTV_OPTIONAL_TABLE( VCoverage );
OTV_OPTIONAL_TABLE( HCoverage );
OTV_OPTIONAL_TABLE( Offset );
OTV_NAME_ENTER( "MathVariants" );
OTV_LIMIT_CHECK( 10 );
p += 2; /* Skip the MinConnectorOverlap constant */
OTV_OPTIONAL_OFFSET( VCoverage );
OTV_OPTIONAL_OFFSET( HCoverage );
vcnt = FT_NEXT_USHORT( p );
hcnt = FT_NEXT_USHORT( p );
OTV_LIMIT_CHECK( 2 * vcnt + 2 * hcnt );
table_size = 10 + 2 * vcnt + 2 * hcnt;
OTV_SIZE_CHECK( VCoverage );
if ( VCoverage )
otv_Coverage_validate( table + VCoverage, valid, vcnt );
OTV_SIZE_CHECK( HCoverage );
if ( HCoverage )
otv_Coverage_validate( table + HCoverage, valid, hcnt );
for ( i = 0; i < vcnt; ++i )
{
OTV_OPTIONAL_OFFSET( Offset );
OTV_SIZE_CHECK( Offset );
otv_MathGlyphConstruction_validate( table + Offset, valid );
}
for ( i = 0; i < hcnt; ++i )
{
OTV_OPTIONAL_OFFSET( Offset );
OTV_SIZE_CHECK( Offset );
otv_MathGlyphConstruction_validate( table + Offset, valid );
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MATH TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets valid->glyph_count */
FT_LOCAL_DEF( void )
otv_MATH_validate( FT_Bytes table,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec validrec;
OTV_Validator valid = &validrec;
FT_Bytes p = table;
FT_UInt MathConstants, MathGlyphInfo, MathVariants;
valid->root = ftvalid;
FT_TRACE3(( "validating MATH table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 10 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
MathConstants = FT_NEXT_USHORT( p );
MathGlyphInfo = FT_NEXT_USHORT( p );
MathVariants = FT_NEXT_USHORT( p );
valid->glyph_count = glyph_count;
otv_MathConstants_validate( table + MathConstants,
valid );
otv_MathGlyphInfo_validate( table + MathGlyphInfo,
valid );
otv_MathVariants_validate ( table + MathVariants,
valid );
FT_TRACE4(( "\n" ));
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvmath.c | C | apache-2.0 | 14,589 |
/***************************************************************************/
/* */
/* otvmod.c */
/* */
/* FreeType's OpenType validation module implementation (body). */
/* */
/* Copyright 2004-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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_TRUETYPE_TABLES_H
#include FT_TRUETYPE_TAGS_H
#include FT_OPENTYPE_VALIDATE_H
#include FT_INTERNAL_OBJECTS_H
#include FT_SERVICE_OPENTYPE_VALIDATE_H
#include "otvmod.h"
#include "otvalid.h"
#include "otvcommn.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_otvmodule
static FT_Error
otv_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;
}
static FT_Error
otv_validate( FT_Face volatile face,
FT_UInt ot_flags,
FT_Bytes *ot_base,
FT_Bytes *ot_gdef,
FT_Bytes *ot_gpos,
FT_Bytes *ot_gsub,
FT_Bytes *ot_jstf )
{
FT_Error error = FT_Err_Ok;
FT_Byte* volatile base;
FT_Byte* volatile gdef;
FT_Byte* volatile gpos;
FT_Byte* volatile gsub;
FT_Byte* volatile jstf;
FT_Byte* volatile math;
FT_ULong len_base, len_gdef, len_gpos, len_gsub, len_jstf;
FT_ULong len_math;
FT_UInt num_glyphs = (FT_UInt)face->num_glyphs;
FT_ValidatorRec volatile valid;
base = gdef = gpos = gsub = jstf = math = NULL;
len_base = len_gdef = len_gpos = len_gsub = len_jstf = len_math = 0;
/*
* XXX: OpenType tables cannot handle 32-bit glyph index,
* although broken TrueType can have 32-bit glyph index.
*/
if ( face->num_glyphs > 0xFFFFL )
{
FT_TRACE1(( "otv_validate: Invalid glyphs index (0x0000FFFF - 0x%08x) ",
face->num_glyphs ));
FT_TRACE1(( "are not handled by OpenType tables\n" ));
num_glyphs = 0xFFFF;
}
/* load tables */
if ( ot_flags & FT_VALIDATE_BASE )
{
error = otv_load_table( face, TTAG_BASE, &base, &len_base );
if ( error )
goto Exit;
}
if ( ot_flags & FT_VALIDATE_GDEF )
{
error = otv_load_table( face, TTAG_GDEF, &gdef, &len_gdef );
if ( error )
goto Exit;
}
if ( ot_flags & FT_VALIDATE_GPOS )
{
error = otv_load_table( face, TTAG_GPOS, &gpos, &len_gpos );
if ( error )
goto Exit;
}
if ( ot_flags & FT_VALIDATE_GSUB )
{
error = otv_load_table( face, TTAG_GSUB, &gsub, &len_gsub );
if ( error )
goto Exit;
}
if ( ot_flags & FT_VALIDATE_JSTF )
{
error = otv_load_table( face, TTAG_JSTF, &jstf, &len_jstf );
if ( error )
goto Exit;
}
if ( ot_flags & FT_VALIDATE_MATH )
{
error = otv_load_table( face, TTAG_MATH, &math, &len_math );
if ( error )
goto Exit;
}
/* validate tables */
if ( base )
{
ft_validator_init( &valid, base, base + len_base, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_BASE_validate( base, &valid );
error = valid.error;
if ( error )
goto Exit;
}
if ( gpos )
{
ft_validator_init( &valid, gpos, gpos + len_gpos, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_GPOS_validate( gpos, num_glyphs, &valid );
error = valid.error;
if ( error )
goto Exit;
}
if ( gsub )
{
ft_validator_init( &valid, gsub, gsub + len_gsub, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_GSUB_validate( gsub, num_glyphs, &valid );
error = valid.error;
if ( error )
goto Exit;
}
if ( gdef )
{
ft_validator_init( &valid, gdef, gdef + len_gdef, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_GDEF_validate( gdef, gsub, gpos, num_glyphs, &valid );
error = valid.error;
if ( error )
goto Exit;
}
if ( jstf )
{
ft_validator_init( &valid, jstf, jstf + len_jstf, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_JSTF_validate( jstf, gsub, gpos, num_glyphs, &valid );
error = valid.error;
if ( error )
goto Exit;
}
if ( math )
{
ft_validator_init( &valid, math, math + len_math, FT_VALIDATE_DEFAULT );
if ( ft_setjmp( valid.jump_buffer ) == 0 )
otv_MATH_validate( math, num_glyphs, &valid );
error = valid.error;
if ( error )
goto Exit;
}
*ot_base = (FT_Bytes)base;
*ot_gdef = (FT_Bytes)gdef;
*ot_gpos = (FT_Bytes)gpos;
*ot_gsub = (FT_Bytes)gsub;
*ot_jstf = (FT_Bytes)jstf;
Exit:
if ( error )
{
FT_Memory memory = FT_FACE_MEMORY( face );
FT_FREE( base );
FT_FREE( gdef );
FT_FREE( gpos );
FT_FREE( gsub );
FT_FREE( jstf );
}
{
FT_Memory memory = FT_FACE_MEMORY( face );
FT_FREE( math ); /* Can't return this as API is frozen */
}
return error;
}
static
const FT_Service_OTvalidateRec otvalid_interface =
{
otv_validate
};
static
const FT_ServiceDescRec otvalid_services[] =
{
{ FT_SERVICE_ID_OPENTYPE_VALIDATE, &otvalid_interface },
{ NULL, NULL }
};
static FT_Pointer
otvalid_get_service( FT_Module module,
const char* service_id )
{
FT_UNUSED( module );
return ft_service_list_lookup( otvalid_services, service_id );
}
FT_CALLBACK_TABLE_DEF
const FT_Module_Class otv_module_class =
{
0,
sizeof ( FT_ModuleRec ),
"otvalid",
0x10000L,
0x20000L,
0, /* module-specific interface */
(FT_Module_Constructor)0,
(FT_Module_Destructor) 0,
(FT_Module_Requester) otvalid_get_service
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvmod.c | C | apache-2.0 | 7,986 |
/***************************************************************************/
/* */
/* otvmod.h */
/* */
/* FreeType's OpenType validation module implementation */
/* (specification). */
/* */
/* Copyright 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 __OTVMOD_H__
#define __OTVMOD_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 ) otv_module_class;
FT_END_HEADER
#endif /* __OTVMOD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/otvmod.h | C | apache-2.0 | 1,632 |
#
# FreeType 2 OpenType validation driver configuration rules
#
# Copyright 2004, 2007 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.
# OTV driver directory
#
OTV_DIR := $(SRC_DIR)/otvalid
# compilation flags for the driver
#
OTV_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(OTV_DIR))
# OTV driver sources (i.e., C files)
#
OTV_DRV_SRC := $(OTV_DIR)/otvbase.c \
$(OTV_DIR)/otvcommn.c \
$(OTV_DIR)/otvgdef.c \
$(OTV_DIR)/otvgpos.c \
$(OTV_DIR)/otvgsub.c \
$(OTV_DIR)/otvjstf.c \
$(OTV_DIR)/otvmath.c \
$(OTV_DIR)/otvmod.c
# OTV driver headers
#
OTV_DRV_H := $(OTV_DIR)/otvalid.h \
$(OTV_DIR)/otvcommn.h \
$(OTV_DIR)/otverror.h \
$(OTV_DIR)/otvgpos.h \
$(OTV_DIR)/otvmod.h
# OTV driver object(s)
#
# OTV_DRV_OBJ_M is used during `multi' builds.
# OTV_DRV_OBJ_S is used during `single' builds.
#
OTV_DRV_OBJ_M := $(OTV_DRV_SRC:$(OTV_DIR)/%.c=$(OBJ_DIR)/%.$O)
OTV_DRV_OBJ_S := $(OBJ_DIR)/otvalid.$O
# OTV driver source file for single build
#
OTV_DRV_SRC_S := $(OTV_DIR)/otvalid.c
# OTV driver - single object
#
$(OTV_DRV_OBJ_S): $(OTV_DRV_SRC_S) $(OTV_DRV_SRC) \
$(FREETYPE_H) $(OTV_DRV_H)
$(OTV_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(OTV_DRV_SRC_S))
# OTV driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(OTV_DIR)/%.c $(FREETYPE_H) $(OTV_DRV_H)
$(OTV_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(OTV_DRV_OBJ_S)
DRV_OBJS_M += $(OTV_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/otvalid/rules.mk | Makefile | apache-2.0 | 1,926 |
#
# FreeType 2 PCF module definition
#
# Copyright 2000, 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 += PCF_DRIVER
define PCF_DRIVER
$(OPEN_DRIVER) FT_Driver_ClassRec, pcf_driver_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)pcf $(ECHO_DRIVER_DESC)pcf bitmap fonts$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/pcf/module.mk | Makefile | apache-2.0 | 1,366 |
/* pcf.c
FreeType font driver for pcf fonts
Copyright 2000-2001, 2003 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 "pcfutil.c"
#include "pcfread.c"
#include "pcfdrivr.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcf.c | C | apache-2.0 | 1,275 |
/* pcf.h
FreeType font driver for pcf fonts
Copyright (C) 2000, 2001, 2002, 2003, 2006, 2010 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 __PCF_H__
#define __PCF_H__
#include <ft2build.h>
#include FT_INTERNAL_DRIVER_H
#include FT_INTERNAL_STREAM_H
FT_BEGIN_HEADER
typedef struct PCF_TableRec_
{
FT_ULong type;
FT_ULong format;
FT_ULong size;
FT_ULong offset;
} PCF_TableRec, *PCF_Table;
typedef struct PCF_TocRec_
{
FT_ULong version;
FT_ULong count;
PCF_Table tables;
} PCF_TocRec, *PCF_Toc;
typedef struct PCF_ParsePropertyRec_
{
FT_Long name;
FT_Byte isString;
FT_Long value;
} PCF_ParsePropertyRec, *PCF_ParseProperty;
typedef struct PCF_PropertyRec_
{
FT_String* name;
FT_Byte isString;
union
{
FT_String* atom;
FT_Long l;
FT_ULong ul;
} value;
} PCF_PropertyRec, *PCF_Property;
typedef struct PCF_Compressed_MetricRec_
{
FT_Byte leftSideBearing;
FT_Byte rightSideBearing;
FT_Byte characterWidth;
FT_Byte ascent;
FT_Byte descent;
} PCF_Compressed_MetricRec, *PCF_Compressed_Metric;
typedef struct PCF_MetricRec_
{
FT_Short leftSideBearing;
FT_Short rightSideBearing;
FT_Short characterWidth;
FT_Short ascent;
FT_Short descent;
FT_Short attributes;
FT_ULong bits;
} PCF_MetricRec, *PCF_Metric;
typedef struct PCF_AccelRec_
{
FT_Byte noOverlap;
FT_Byte constantMetrics;
FT_Byte terminalFont;
FT_Byte constantWidth;
FT_Byte inkInside;
FT_Byte inkMetrics;
FT_Byte drawDirection;
FT_Long fontAscent;
FT_Long fontDescent;
FT_Long maxOverlap;
PCF_MetricRec minbounds;
PCF_MetricRec maxbounds;
PCF_MetricRec ink_minbounds;
PCF_MetricRec ink_maxbounds;
} PCF_AccelRec, *PCF_Accel;
typedef struct PCF_EncodingRec_
{
FT_Long enc;
FT_UShort glyph;
} PCF_EncodingRec, *PCF_Encoding;
typedef struct PCF_FaceRec_
{
FT_FaceRec root;
FT_StreamRec comp_stream;
FT_Stream comp_source;
char* charset_encoding;
char* charset_registry;
PCF_TocRec toc;
PCF_AccelRec accel;
int nprops;
PCF_Property properties;
FT_Long nmetrics;
PCF_Metric metrics;
FT_Long nencodings;
PCF_Encoding encodings;
FT_Short defaultChar;
FT_ULong bitmapsFormat;
FT_CharMap charmap_handle;
FT_CharMapRec charmap; /* a single charmap per face */
} PCF_FaceRec, *PCF_Face;
/* macros for pcf font format */
#define LSBFirst 0
#define MSBFirst 1
#define PCF_FILE_VERSION ( ( 'p' << 24 ) | \
( 'c' << 16 ) | \
( 'f' << 8 ) | 1 )
#define PCF_FORMAT_MASK 0xFFFFFF00UL
#define PCF_DEFAULT_FORMAT 0x00000000UL
#define PCF_INKBOUNDS 0x00000200UL
#define PCF_ACCEL_W_INKBOUNDS 0x00000100UL
#define PCF_COMPRESSED_METRICS 0x00000100UL
#define PCF_FORMAT_MATCH( a, b ) \
( ( (a) & PCF_FORMAT_MASK ) == ( (b) & PCF_FORMAT_MASK ) )
#define PCF_GLYPH_PAD_MASK ( 3 << 0 )
#define PCF_BYTE_MASK ( 1 << 2 )
#define PCF_BIT_MASK ( 1 << 3 )
#define PCF_SCAN_UNIT_MASK ( 3 << 4 )
#define PCF_BYTE_ORDER( f ) \
( ( (f) & PCF_BYTE_MASK ) ? MSBFirst : LSBFirst )
#define PCF_BIT_ORDER( f ) \
( ( (f) & PCF_BIT_MASK ) ? MSBFirst : LSBFirst )
#define PCF_GLYPH_PAD_INDEX( f ) \
( (f) & PCF_GLYPH_PAD_MASK )
#define PCF_GLYPH_PAD( f ) \
( 1 << PCF_GLYPH_PAD_INDEX( f ) )
#define PCF_SCAN_UNIT_INDEX( f ) \
( ( (f) & PCF_SCAN_UNIT_MASK ) >> 4 )
#define PCF_SCAN_UNIT( f ) \
( 1 << PCF_SCAN_UNIT_INDEX( f ) )
#define PCF_FORMAT_BITS( f ) \
( (f) & ( PCF_GLYPH_PAD_MASK | \
PCF_BYTE_MASK | \
PCF_BIT_MASK | \
PCF_SCAN_UNIT_MASK ) )
#define PCF_SIZE_TO_INDEX( s ) ( (s) == 4 ? 2 : (s) == 2 ? 1 : 0 )
#define PCF_INDEX_TO_SIZE( b ) ( 1 << b )
#define PCF_FORMAT( bit, byte, glyph, scan ) \
( ( PCF_SIZE_TO_INDEX( scan ) << 4 ) | \
( ( (bit) == MSBFirst ? 1 : 0 ) << 3 ) | \
( ( (byte) == MSBFirst ? 1 : 0 ) << 2 ) | \
( PCF_SIZE_TO_INDEX( glyph ) << 0 ) )
#define PCF_PROPERTIES ( 1 << 0 )
#define PCF_ACCELERATORS ( 1 << 1 )
#define PCF_METRICS ( 1 << 2 )
#define PCF_BITMAPS ( 1 << 3 )
#define PCF_INK_METRICS ( 1 << 4 )
#define PCF_BDF_ENCODINGS ( 1 << 5 )
#define PCF_SWIDTHS ( 1 << 6 )
#define PCF_GLYPH_NAMES ( 1 << 7 )
#define PCF_BDF_ACCELERATORS ( 1 << 8 )
#define GLYPHPADOPTIONS 4 /* I'm not sure about this */
FT_LOCAL( FT_Error )
pcf_load_font( FT_Stream,
PCF_Face );
FT_END_HEADER
#endif /* __PCF_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcf.h | C | apache-2.0 | 6,092 |
/* pcfdrivr.c
FreeType font driver for pcf files
Copyright (C) 2000-2004, 2006-2011, 2013 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_GZIP_H
#include FT_LZW_H
#include FT_BZIP2_H
#include FT_ERRORS_H
#include FT_BDF_H
#include FT_TRUETYPE_IDS_H
#include "pcf.h"
#include "pcfdrivr.h"
#include "pcfread.h"
#include "pcferror.h"
#include "pcfutil.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pcfread
#include FT_SERVICE_BDF_H
#include FT_SERVICE_XFREE86_NAME_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_pcfdriver
typedef struct PCF_CMapRec_
{
FT_CMapRec root;
FT_UInt num_encodings;
PCF_Encoding encodings;
} PCF_CMapRec, *PCF_CMap;
FT_CALLBACK_DEF( FT_Error )
pcf_cmap_init( FT_CMap pcfcmap, /* PCF_CMap */
FT_Pointer init_data )
{
PCF_CMap cmap = (PCF_CMap)pcfcmap;
PCF_Face face = (PCF_Face)FT_CMAP_FACE( pcfcmap );
FT_UNUSED( init_data );
cmap->num_encodings = (FT_UInt)face->nencodings;
cmap->encodings = face->encodings;
return FT_Err_Ok;
}
FT_CALLBACK_DEF( void )
pcf_cmap_done( FT_CMap pcfcmap ) /* PCF_CMap */
{
PCF_CMap cmap = (PCF_CMap)pcfcmap;
cmap->encodings = NULL;
cmap->num_encodings = 0;
}
FT_CALLBACK_DEF( FT_UInt )
pcf_cmap_char_index( FT_CMap pcfcmap, /* PCF_CMap */
FT_UInt32 charcode )
{
PCF_CMap cmap = (PCF_CMap)pcfcmap;
PCF_Encoding encodings = cmap->encodings;
FT_UInt min, max, mid;
FT_UInt result = 0;
min = 0;
max = cmap->num_encodings;
while ( min < max )
{
FT_ULong code;
mid = ( min + max ) >> 1;
code = encodings[mid].enc;
if ( charcode == code )
{
result = encodings[mid].glyph + 1;
break;
}
if ( charcode < code )
max = mid;
else
min = mid + 1;
}
return result;
}
FT_CALLBACK_DEF( FT_UInt )
pcf_cmap_char_next( FT_CMap pcfcmap, /* PCF_CMap */
FT_UInt32 *acharcode )
{
PCF_CMap cmap = (PCF_CMap)pcfcmap;
PCF_Encoding encodings = cmap->encodings;
FT_UInt min, max, mid;
FT_ULong charcode = *acharcode + 1;
FT_UInt result = 0;
min = 0;
max = cmap->num_encodings;
while ( min < max )
{
FT_ULong code;
mid = ( min + max ) >> 1;
code = encodings[mid].enc;
if ( charcode == code )
{
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(( "pcf_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 pcf_cmap_class =
{
sizeof ( PCF_CMapRec ),
pcf_cmap_init,
pcf_cmap_done,
pcf_cmap_char_index,
pcf_cmap_char_next,
NULL, NULL, NULL, NULL, NULL
};
FT_CALLBACK_DEF( void )
PCF_Face_Done( FT_Face pcfface ) /* PCF_Face */
{
PCF_Face face = (PCF_Face)pcfface;
FT_Memory memory;
if ( !face )
return;
memory = FT_FACE_MEMORY( face );
FT_FREE( face->encodings );
FT_FREE( face->metrics );
/* free properties */
if ( face->properties )
{
FT_Int i;
for ( i = 0; i < face->nprops; i++ )
{
PCF_Property prop = &face->properties[i];
if ( prop )
{
FT_FREE( prop->name );
if ( prop->isString )
FT_FREE( prop->value.atom );
}
}
FT_FREE( face->properties );
}
FT_FREE( face->toc.tables );
FT_FREE( pcfface->family_name );
FT_FREE( pcfface->style_name );
FT_FREE( pcfface->available_sizes );
FT_FREE( face->charset_encoding );
FT_FREE( face->charset_registry );
/* close compressed stream if any */
if ( pcfface->stream == &face->comp_stream )
{
FT_Stream_Close( &face->comp_stream );
pcfface->stream = face->comp_source;
}
}
FT_CALLBACK_DEF( FT_Error )
PCF_Face_Init( FT_Stream stream,
FT_Face pcfface, /* PCF_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
PCF_Face face = (PCF_Face)pcfface;
FT_Error error;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_TRACE2(( "PCF driver\n" ));
error = pcf_load_font( stream, face );
if ( error )
{
PCF_Face_Done( pcfface );
#if defined( FT_CONFIG_OPTION_USE_ZLIB ) || \
defined( FT_CONFIG_OPTION_USE_LZW ) || \
defined( FT_CONFIG_OPTION_USE_BZIP2 )
#ifdef FT_CONFIG_OPTION_USE_ZLIB
{
FT_Error error2;
/* this didn't work, try gzip support! */
error2 = FT_Stream_OpenGzip( &face->comp_stream, stream );
if ( FT_ERR_EQ( error2, Unimplemented_Feature ) )
goto Fail;
error = error2;
}
#endif /* FT_CONFIG_OPTION_USE_ZLIB */
#ifdef FT_CONFIG_OPTION_USE_LZW
if ( error )
{
FT_Error error3;
/* this didn't work, try LZW support! */
error3 = FT_Stream_OpenLZW( &face->comp_stream, stream );
if ( FT_ERR_EQ( error3, Unimplemented_Feature ) )
goto Fail;
error = error3;
}
#endif /* FT_CONFIG_OPTION_USE_LZW */
#ifdef FT_CONFIG_OPTION_USE_BZIP2
if ( error )
{
FT_Error error4;
/* this didn't work, try Bzip2 support! */
error4 = FT_Stream_OpenBzip2( &face->comp_stream, stream );
if ( FT_ERR_EQ( error4, Unimplemented_Feature ) )
goto Fail;
error = error4;
}
#endif /* FT_CONFIG_OPTION_USE_BZIP2 */
if ( error )
goto Fail;
face->comp_source = stream;
pcfface->stream = &face->comp_stream;
stream = pcfface->stream;
error = pcf_load_font( stream, face );
if ( error )
goto Fail;
#else /* !(FT_CONFIG_OPTION_USE_ZLIB ||
FT_CONFIG_OPTION_USE_LZW ||
FT_CONFIG_OPTION_USE_BZIP2) */
goto Fail;
#endif
}
/* PCF 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(( "PCF_Face_Init: invalid face index\n" ));
PCF_Face_Done( pcfface );
return FT_THROW( Invalid_Argument );
}
/* set up charmap */
{
FT_String *charset_registry = face->charset_registry;
FT_String *charset_encoding = face->charset_encoding;
FT_Bool unicode_charmap = 0;
if ( charset_registry && charset_encoding )
{
char* s = charset_registry;
/* Uh, oh, compare first letters manually to avoid dependency
on locales. */
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( &pcf_cmap_class, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if ( pcfface->num_charmaps )
pcfface->charmap = pcfface->charmaps[0];
#endif
}
}
Exit:
return error;
Fail:
FT_TRACE2(( " not a PCF file\n" ));
PCF_Face_Done( pcfface );
error = FT_THROW( Unknown_File_Format ); /* error */
goto Exit;
}
FT_CALLBACK_DEF( FT_Error )
PCF_Size_Select( FT_Size size,
FT_ULong strike_index )
{
PCF_Accel accel = &( (PCF_Face)size->face )->accel;
FT_Select_Metrics( size->face, strike_index );
size->metrics.ascender = accel->fontAscent << 6;
size->metrics.descender = -accel->fontDescent << 6;
size->metrics.max_advance = accel->maxbounds.characterWidth << 6;
return FT_Err_Ok;
}
FT_CALLBACK_DEF( FT_Error )
PCF_Size_Request( FT_Size size,
FT_Size_Request req )
{
PCF_Face face = (PCF_Face)size->face;
FT_Bitmap_Size* bsize = size->face->available_sizes;
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 == ( face->accel.fontAscent +
face->accel.fontDescent ) )
error = FT_Err_Ok;
break;
default:
error = FT_THROW( Unimplemented_Feature );
break;
}
if ( error )
return error;
else
return PCF_Size_Select( size, 0 );
}
FT_CALLBACK_DEF( FT_Error )
PCF_Glyph_Load( FT_GlyphSlot slot,
FT_Size size,
FT_UInt glyph_index,
FT_Int32 load_flags )
{
PCF_Face face = (PCF_Face)FT_SIZE_FACE( size );
FT_Stream stream;
FT_Error error = FT_Err_Ok;
FT_Bitmap* bitmap = &slot->bitmap;
PCF_Metric metric;
FT_Offset bytes;
FT_UNUSED( load_flags );
FT_TRACE1(( "PCF_Glyph_Load: glyph index %d\n", glyph_index ));
if ( !face || glyph_index >= (FT_UInt)face->root.num_glyphs )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
stream = face->root.stream;
if ( glyph_index > 0 )
glyph_index--;
metric = face->metrics + glyph_index;
bitmap->rows = metric->ascent + metric->descent;
bitmap->width = metric->rightSideBearing - metric->leftSideBearing;
bitmap->num_grays = 1;
bitmap->pixel_mode = FT_PIXEL_MODE_MONO;
FT_TRACE6(( "BIT_ORDER %d ; BYTE_ORDER %d ; GLYPH_PAD %d\n",
PCF_BIT_ORDER( face->bitmapsFormat ),
PCF_BYTE_ORDER( face->bitmapsFormat ),
PCF_GLYPH_PAD( face->bitmapsFormat ) ));
switch ( PCF_GLYPH_PAD( face->bitmapsFormat ) )
{
case 1:
bitmap->pitch = ( bitmap->width + 7 ) >> 3;
break;
case 2:
bitmap->pitch = ( ( bitmap->width + 15 ) >> 4 ) << 1;
break;
case 4:
bitmap->pitch = ( ( bitmap->width + 31 ) >> 5 ) << 2;
break;
case 8:
bitmap->pitch = ( ( bitmap->width + 63 ) >> 6 ) << 3;
break;
default:
return FT_THROW( Invalid_File_Format );
}
/* XXX: to do: are there cases that need repadding the bitmap? */
bytes = bitmap->pitch * bitmap->rows;
error = ft_glyphslot_alloc_bitmap( slot, (FT_ULong)bytes );
if ( error )
goto Exit;
if ( FT_STREAM_SEEK( metric->bits ) ||
FT_STREAM_READ( bitmap->buffer, bytes ) )
goto Exit;
if ( PCF_BIT_ORDER( face->bitmapsFormat ) != MSBFirst )
BitOrderInvert( bitmap->buffer, bytes );
if ( ( PCF_BYTE_ORDER( face->bitmapsFormat ) !=
PCF_BIT_ORDER( face->bitmapsFormat ) ) )
{
switch ( PCF_SCAN_UNIT( face->bitmapsFormat ) )
{
case 1:
break;
case 2:
TwoByteSwap( bitmap->buffer, bytes );
break;
case 4:
FourByteSwap( bitmap->buffer, bytes );
break;
}
}
slot->format = FT_GLYPH_FORMAT_BITMAP;
slot->bitmap_left = metric->leftSideBearing;
slot->bitmap_top = metric->ascent;
slot->metrics.horiAdvance = metric->characterWidth << 6;
slot->metrics.horiBearingX = metric->leftSideBearing << 6;
slot->metrics.horiBearingY = metric->ascent << 6;
slot->metrics.width = ( metric->rightSideBearing -
metric->leftSideBearing ) << 6;
slot->metrics.height = bitmap->rows << 6;
ft_synthesize_vertical_metrics( &slot->metrics,
( face->accel.fontAscent +
face->accel.fontDescent ) << 6 );
Exit:
return error;
}
/*
*
* BDF SERVICE
*
*/
static FT_Error
pcf_get_bdf_property( PCF_Face face,
const char* prop_name,
BDF_PropertyRec *aproperty )
{
PCF_Property prop;
prop = pcf_find_property( face, prop_name );
if ( prop != NULL )
{
if ( prop->isString )
{
aproperty->type = BDF_PROPERTY_TYPE_ATOM;
aproperty->u.atom = prop->value.atom;
}
else
{
if ( prop->value.l > 0x7FFFFFFFL || prop->value.l < ( -1 - 0x7FFFFFFFL ) )
{
FT_TRACE1(( "pcf_get_bdf_property: " ));
FT_TRACE1(( "too large integer 0x%x is truncated\n" ));
}
/* Apparently, the PCF driver loads all properties as signed integers!
* This really doesn't seem to be a problem, because this is
* sufficient for any meaningful values.
*/
aproperty->type = BDF_PROPERTY_TYPE_INTEGER;
aproperty->u.integer = (FT_Int32)prop->value.l;
}
return 0;
}
return FT_THROW( Invalid_Argument );
}
static FT_Error
pcf_get_charset_id( PCF_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 pcf_service_bdf =
{
(FT_BDF_GetCharsetIdFunc)pcf_get_charset_id,
(FT_BDF_GetPropertyFunc) pcf_get_bdf_property
};
/*
*
* SERVICE LIST
*
*/
static const FT_ServiceDescRec pcf_services[] =
{
{ FT_SERVICE_ID_BDF, &pcf_service_bdf },
{ FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_PCF },
{ NULL, NULL }
};
FT_CALLBACK_DEF( FT_Module_Interface )
pcf_driver_requester( FT_Module module,
const char* name )
{
FT_UNUSED( module );
return ft_service_list_lookup( pcf_services, name );
}
FT_CALLBACK_TABLE_DEF
const FT_Driver_ClassRec pcf_driver_class =
{
{
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_NO_OUTLINES,
sizeof ( FT_DriverRec ),
"pcf",
0x10000L,
0x20000L,
0,
0, /* FT_Module_Constructor */
0, /* FT_Module_Destructor */
pcf_driver_requester
},
sizeof ( PCF_FaceRec ),
sizeof ( FT_SizeRec ),
sizeof ( FT_GlyphSlotRec ),
PCF_Face_Init,
PCF_Face_Done,
0, /* FT_Size_InitFunc */
0, /* FT_Size_DoneFunc */
0, /* FT_Slot_InitFunc */
0, /* FT_Slot_DoneFunc */
PCF_Glyph_Load,
0, /* FT_Face_GetKerningFunc */
0, /* FT_Face_AttachFunc */
0, /* FT_Face_GetAdvancesFunc */
PCF_Size_Request,
PCF_Size_Select
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfdrivr.c | C | apache-2.0 | 17,860 |
/* pcfdrivr.h
FreeType font driver for pcf fonts
Copyright 2000-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.
*/
#ifndef __PCFDRIVR_H__
#define __PCFDRIVR_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_EXPORT_VAR( const FT_Driver_ClassRec ) pcf_driver_class;
FT_END_HEADER
#endif /* __PCFDRIVR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfdrivr.h | C | apache-2.0 | 1,463 |
/***************************************************************************/
/* */
/* pcferror.h */
/* */
/* PCF 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 PCF error enumeration constants. */
/* */
/*************************************************************************/
#ifndef __PCFERROR_H__
#define __PCFERROR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX PCF_Err_
#define FT_ERR_BASE FT_Mod_Err_PCF
#include FT_ERRORS_H
#endif /* __PCFERROR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcferror.h | C | apache-2.0 | 1,895 |
/* pcfread.c
FreeType font driver for pcf fonts
Copyright 2000-2010, 2012, 2013 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 "pcf.h"
#include "pcfread.h"
#include "pcferror.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_pcfread
#ifdef FT_DEBUG_LEVEL_TRACE
static const char* const tableNames[] =
{
"prop", "accl", "mtrcs", "bmps", "imtrcs",
"enc", "swidth", "names", "accel"
};
#endif
static
const FT_Frame_Field pcf_toc_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_TocRec
FT_FRAME_START( 8 ),
FT_FRAME_ULONG_LE( version ),
FT_FRAME_ULONG_LE( count ),
FT_FRAME_END
};
static
const FT_Frame_Field pcf_table_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_TableRec
FT_FRAME_START( 16 ),
FT_FRAME_ULONG_LE( type ),
FT_FRAME_ULONG_LE( format ),
FT_FRAME_ULONG_LE( size ),
FT_FRAME_ULONG_LE( offset ),
FT_FRAME_END
};
static FT_Error
pcf_read_TOC( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
PCF_Toc toc = &face->toc;
PCF_Table tables;
FT_Memory memory = FT_FACE( face )->memory;
FT_UInt n;
if ( FT_STREAM_SEEK ( 0 ) ||
FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) )
return FT_THROW( Cannot_Open_Resource );
if ( toc->version != PCF_FILE_VERSION ||
toc->count > FT_ARRAY_MAX( face->toc.tables ) ||
toc->count == 0 )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) )
return FT_THROW( Out_Of_Memory );
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) )
goto Exit;
tables++;
}
/* Sort tables and check for overlaps. Because they are almost */
/* always ordered already, an in-place bubble sort with simultaneous */
/* boundary checking seems appropriate. */
tables = face->toc.tables;
for ( n = 0; n < toc->count - 1; n++ )
{
FT_UInt i, have_change;
have_change = 0;
for ( i = 0; i < toc->count - 1 - n; i++ )
{
PCF_TableRec tmp;
if ( tables[i].offset > tables[i + 1].offset )
{
tmp = tables[i];
tables[i] = tables[i + 1];
tables[i + 1] = tmp;
have_change = 1;
}
if ( ( tables[i].size > tables[i + 1].offset ) ||
( tables[i].offset > tables[i + 1].offset - tables[i].size ) )
return FT_THROW( Invalid_Offset );
}
if ( !have_change )
break;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_UInt i, j;
const char* name = "?";
FT_TRACE4(( "pcf_read_TOC:\n" ));
FT_TRACE4(( " number of tables: %ld\n", face->toc.count ));
tables = face->toc.tables;
for ( i = 0; i < toc->count; i++ )
{
for ( j = 0; j < sizeof ( tableNames ) / sizeof ( tableNames[0] );
j++ )
if ( tables[i].type == (FT_UInt)( 1 << j ) )
name = tableNames[j];
FT_TRACE4(( " %d: type=%s, format=0x%X, "
"size=%ld (0x%lX), offset=%ld (0x%lX)\n",
i, name,
tables[i].format,
tables[i].size, tables[i].size,
tables[i].offset, tables[i].offset ));
}
}
#endif
return FT_Err_Ok;
Exit:
FT_FREE( face->toc.tables );
return error;
}
#define PCF_METRIC_SIZE 12
static
const FT_Frame_Field pcf_metric_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_MetricRec
FT_FRAME_START( PCF_METRIC_SIZE ),
FT_FRAME_SHORT_LE( leftSideBearing ),
FT_FRAME_SHORT_LE( rightSideBearing ),
FT_FRAME_SHORT_LE( characterWidth ),
FT_FRAME_SHORT_LE( ascent ),
FT_FRAME_SHORT_LE( descent ),
FT_FRAME_SHORT_LE( attributes ),
FT_FRAME_END
};
static
const FT_Frame_Field pcf_metric_msb_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_MetricRec
FT_FRAME_START( PCF_METRIC_SIZE ),
FT_FRAME_SHORT( leftSideBearing ),
FT_FRAME_SHORT( rightSideBearing ),
FT_FRAME_SHORT( characterWidth ),
FT_FRAME_SHORT( ascent ),
FT_FRAME_SHORT( descent ),
FT_FRAME_SHORT( attributes ),
FT_FRAME_END
};
#define PCF_COMPRESSED_METRIC_SIZE 5
static
const FT_Frame_Field pcf_compressed_metric_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_Compressed_MetricRec
FT_FRAME_START( PCF_COMPRESSED_METRIC_SIZE ),
FT_FRAME_BYTE( leftSideBearing ),
FT_FRAME_BYTE( rightSideBearing ),
FT_FRAME_BYTE( characterWidth ),
FT_FRAME_BYTE( ascent ),
FT_FRAME_BYTE( descent ),
FT_FRAME_END
};
static FT_Error
pcf_get_metric( FT_Stream stream,
FT_ULong format,
PCF_Metric metric )
{
FT_Error error = FT_Err_Ok;
if ( PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
{
const FT_Frame_Field* fields;
/* parsing normal metrics */
fields = PCF_BYTE_ORDER( format ) == MSBFirst
? pcf_metric_msb_header
: pcf_metric_header;
/* the following sets `error' but doesn't return in case of failure */
(void)FT_STREAM_READ_FIELDS( fields, metric );
}
else
{
PCF_Compressed_MetricRec compr;
/* parsing compressed metrics */
if ( FT_STREAM_READ_FIELDS( pcf_compressed_metric_header, &compr ) )
goto Exit;
metric->leftSideBearing = (FT_Short)( compr.leftSideBearing - 0x80 );
metric->rightSideBearing = (FT_Short)( compr.rightSideBearing - 0x80 );
metric->characterWidth = (FT_Short)( compr.characterWidth - 0x80 );
metric->ascent = (FT_Short)( compr.ascent - 0x80 );
metric->descent = (FT_Short)( compr.descent - 0x80 );
metric->attributes = 0;
}
Exit:
return error;
}
static FT_Error
pcf_seek_to_table_type( FT_Stream stream,
PCF_Table tables,
FT_ULong ntables, /* same as PCF_Toc->count */
FT_ULong type,
FT_ULong *aformat,
FT_ULong *asize )
{
FT_Error error = FT_ERR( Invalid_File_Format );
FT_ULong i;
for ( i = 0; i < ntables; i++ )
if ( tables[i].type == type )
{
if ( stream->pos > tables[i].offset )
{
error = FT_THROW( Invalid_Stream_Skip );
goto Fail;
}
if ( FT_STREAM_SKIP( tables[i].offset - stream->pos ) )
{
error = FT_THROW( Invalid_Stream_Skip );
goto Fail;
}
*asize = tables[i].size;
*aformat = tables[i].format;
return FT_Err_Ok;
}
Fail:
*asize = 0;
return error;
}
static FT_Bool
pcf_has_table_type( PCF_Table tables,
FT_ULong ntables, /* same as PCF_Toc->count */
FT_ULong type )
{
FT_ULong i;
for ( i = 0; i < ntables; i++ )
if ( tables[i].type == type )
return TRUE;
return FALSE;
}
#define PCF_PROPERTY_SIZE 9
static
const FT_Frame_Field pcf_property_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_ParsePropertyRec
FT_FRAME_START( PCF_PROPERTY_SIZE ),
FT_FRAME_LONG_LE( name ),
FT_FRAME_BYTE ( isString ),
FT_FRAME_LONG_LE( value ),
FT_FRAME_END
};
static
const FT_Frame_Field pcf_property_msb_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_ParsePropertyRec
FT_FRAME_START( PCF_PROPERTY_SIZE ),
FT_FRAME_LONG( name ),
FT_FRAME_BYTE( isString ),
FT_FRAME_LONG( value ),
FT_FRAME_END
};
FT_LOCAL_DEF( PCF_Property )
pcf_find_property( PCF_Face face,
const FT_String* prop )
{
PCF_Property properties = face->properties;
FT_Bool found = 0;
int i;
for ( i = 0 ; i < face->nprops && !found; i++ )
{
if ( !ft_strcmp( properties[i].name, prop ) )
found = 1;
}
if ( found )
return properties + i - 1;
else
return NULL;
}
static FT_Error
pcf_get_properties( FT_Stream stream,
PCF_Face face )
{
PCF_ParseProperty props = 0;
PCF_Property properties = NULL;
FT_ULong nprops, i;
FT_ULong format, size;
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong string_size;
FT_String* strings = 0;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_PROPERTIES,
&format,
&size );
if ( error )
goto Bail;
if ( FT_READ_ULONG_LE( format ) )
goto Bail;
FT_TRACE4(( "pcf_get_properties:\n" ));
FT_TRACE4(( " format = %ld\n", format ));
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
goto Bail;
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_ULONG( nprops );
else
(void)FT_READ_ULONG_LE( nprops );
if ( error )
goto Bail;
FT_TRACE4(( " nprop = %d (truncate %d props)\n",
(int)nprops, nprops - (int)nprops ));
nprops = (int)nprops;
/* rough estimate */
if ( nprops > size / PCF_PROPERTY_SIZE )
{
error = FT_THROW( Invalid_Table );
goto Bail;
}
face->nprops = (int)nprops;
if ( FT_NEW_ARRAY( props, nprops ) )
goto Bail;
for ( i = 0; i < nprops; i++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
if ( FT_STREAM_READ_FIELDS( pcf_property_msb_header, props + i ) )
goto Bail;
}
else
{
if ( FT_STREAM_READ_FIELDS( pcf_property_header, props + i ) )
goto Bail;
}
}
/* pad the property array */
/* */
/* clever here - nprops is the same as the number of odd-units read, */
/* as only isStringProp are odd length (Keith Packard) */
/* */
if ( nprops & 3 )
{
i = 4 - ( nprops & 3 );
if ( FT_STREAM_SKIP( i ) )
{
error = FT_THROW( Invalid_Stream_Skip );
goto Bail;
}
}
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_ULONG( string_size );
else
(void)FT_READ_ULONG_LE( string_size );
if ( error )
goto Bail;
FT_TRACE4(( " string_size = %ld\n", string_size ));
/* rough estimate */
if ( string_size > size - nprops * PCF_PROPERTY_SIZE )
{
error = FT_THROW( Invalid_Table );
goto Bail;
}
/* allocate one more byte so that we have a final null byte */
if ( FT_NEW_ARRAY( strings, string_size + 1 ) )
goto Bail;
error = FT_Stream_Read( stream, (FT_Byte*)strings, string_size );
if ( error )
goto Bail;
if ( FT_NEW_ARRAY( properties, nprops ) )
goto Bail;
face->properties = properties;
for ( i = 0; i < nprops; i++ )
{
FT_Long name_offset = props[i].name;
if ( ( name_offset < 0 ) ||
( (FT_ULong)name_offset > string_size ) )
{
error = FT_THROW( Invalid_Offset );
goto Bail;
}
if ( FT_STRDUP( properties[i].name, strings + name_offset ) )
goto Bail;
FT_TRACE4(( " %s:", properties[i].name ));
properties[i].isString = props[i].isString;
if ( props[i].isString )
{
FT_Long value_offset = props[i].value;
if ( ( value_offset < 0 ) ||
( (FT_ULong)value_offset > string_size ) )
{
error = FT_THROW( Invalid_Offset );
goto Bail;
}
if ( FT_STRDUP( properties[i].value.atom, strings + value_offset ) )
goto Bail;
FT_TRACE4(( " `%s'\n", properties[i].value.atom ));
}
else
{
properties[i].value.l = props[i].value;
FT_TRACE4(( " %d\n", properties[i].value.l ));
}
}
error = FT_Err_Ok;
Bail:
FT_FREE( props );
FT_FREE( strings );
return error;
}
static FT_Error
pcf_get_metrics( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
PCF_Metric metrics = 0;
FT_ULong nmetrics, i;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_METRICS,
&format,
&size );
if ( error )
return error;
if ( FT_READ_ULONG_LE( format ) )
goto Bail;
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) &&
!PCF_FORMAT_MATCH( format, PCF_COMPRESSED_METRICS ) )
return FT_THROW( Invalid_File_Format );
if ( PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_ULONG( nmetrics );
else
(void)FT_READ_ULONG_LE( nmetrics );
}
else
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_USHORT( nmetrics );
else
(void)FT_READ_USHORT_LE( nmetrics );
}
if ( error )
return FT_THROW( Invalid_File_Format );
face->nmetrics = nmetrics;
if ( !nmetrics )
return FT_THROW( Invalid_Table );
FT_TRACE4(( "pcf_get_metrics:\n" ));
FT_TRACE4(( " number of metrics: %d\n", nmetrics ));
/* rough estimate */
if ( PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
{
if ( nmetrics > size / PCF_METRIC_SIZE )
return FT_THROW( Invalid_Table );
}
else
{
if ( nmetrics > size / PCF_COMPRESSED_METRIC_SIZE )
return FT_THROW( Invalid_Table );
}
if ( FT_NEW_ARRAY( face->metrics, nmetrics ) )
return FT_THROW( Out_Of_Memory );
metrics = face->metrics;
for ( i = 0; i < nmetrics; i++ )
{
error = pcf_get_metric( stream, format, metrics + i );
metrics[i].bits = 0;
FT_TRACE5(( " idx %d: width=%d, "
"lsb=%d, rsb=%d, ascent=%d, descent=%d, swidth=%d\n",
i,
( metrics + i )->characterWidth,
( metrics + i )->leftSideBearing,
( metrics + i )->rightSideBearing,
( metrics + i )->ascent,
( metrics + i )->descent,
( metrics + i )->attributes ));
if ( error )
break;
}
if ( error )
FT_FREE( face->metrics );
Bail:
return error;
}
static FT_Error
pcf_get_bitmaps( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_Long* offsets = NULL;
FT_Long bitmapSizes[GLYPHPADOPTIONS];
FT_ULong format, size;
FT_ULong nbitmaps, i, sizebitmaps = 0;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BITMAPS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 8 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
nbitmaps = FT_GET_ULONG();
else
nbitmaps = FT_GET_ULONG_LE();
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
FT_TRACE4(( "pcf_get_bitmaps:\n" ));
FT_TRACE4(( " number of bitmaps: %d\n", nbitmaps ));
/* XXX: PCF_Face->nmetrics is singed FT_Long, see pcf.h */
if ( face->nmetrics < 0 || nbitmaps != ( FT_ULong )face->nmetrics )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( offsets, nbitmaps ) )
return error;
for ( i = 0; i < nbitmaps; i++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_LONG( offsets[i] );
else
(void)FT_READ_LONG_LE( offsets[i] );
FT_TRACE5(( " bitmap %d: offset %ld (0x%lX)\n",
i, offsets[i], offsets[i] ));
}
if ( error )
goto Bail;
for ( i = 0; i < GLYPHPADOPTIONS; i++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
(void)FT_READ_LONG( bitmapSizes[i] );
else
(void)FT_READ_LONG_LE( bitmapSizes[i] );
if ( error )
goto Bail;
sizebitmaps = bitmapSizes[PCF_GLYPH_PAD_INDEX( format )];
FT_TRACE4(( " padding %d implies a size of %ld\n", i, bitmapSizes[i] ));
}
FT_TRACE4(( " %d bitmaps, padding index %ld\n",
nbitmaps,
PCF_GLYPH_PAD_INDEX( format ) ));
FT_TRACE4(( " bitmap size = %d\n", sizebitmaps ));
FT_UNUSED( sizebitmaps ); /* only used for debugging */
for ( i = 0; i < nbitmaps; i++ )
{
/* rough estimate */
if ( ( offsets[i] < 0 ) ||
( (FT_ULong)offsets[i] > size ) )
{
FT_TRACE0(( "pcf_get_bitmaps:"
" invalid offset to bitmap data of glyph %d\n", i ));
}
else
face->metrics[i].bits = stream->pos + offsets[i];
}
face->bitmapsFormat = format;
Bail:
FT_FREE( offsets );
return error;
}
static FT_Error
pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
firstCol, lastCol, firstRow, lastRow ));
nencoding = ( lastCol - firstCol + 1 ) * ( lastRow - firstRow + 1 );
if ( FT_NEW_ARRAY( encoding, nencoding ) )
return FT_THROW( Out_Of_Memory );
error = FT_Stream_EnterFrame( stream, 2 * nencoding );
if ( error )
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
static
const FT_Frame_Field pcf_accel_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_AccelRec
FT_FRAME_START( 20 ),
FT_FRAME_BYTE ( noOverlap ),
FT_FRAME_BYTE ( constantMetrics ),
FT_FRAME_BYTE ( terminalFont ),
FT_FRAME_BYTE ( constantWidth ),
FT_FRAME_BYTE ( inkInside ),
FT_FRAME_BYTE ( inkMetrics ),
FT_FRAME_BYTE ( drawDirection ),
FT_FRAME_SKIP_BYTES( 1 ),
FT_FRAME_LONG_LE ( fontAscent ),
FT_FRAME_LONG_LE ( fontDescent ),
FT_FRAME_LONG_LE ( maxOverlap ),
FT_FRAME_END
};
static
const FT_Frame_Field pcf_accel_msb_header[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PCF_AccelRec
FT_FRAME_START( 20 ),
FT_FRAME_BYTE ( noOverlap ),
FT_FRAME_BYTE ( constantMetrics ),
FT_FRAME_BYTE ( terminalFont ),
FT_FRAME_BYTE ( constantWidth ),
FT_FRAME_BYTE ( inkInside ),
FT_FRAME_BYTE ( inkMetrics ),
FT_FRAME_BYTE ( drawDirection ),
FT_FRAME_SKIP_BYTES( 1 ),
FT_FRAME_LONG ( fontAscent ),
FT_FRAME_LONG ( fontDescent ),
FT_FRAME_LONG ( maxOverlap ),
FT_FRAME_END
};
static FT_Error
pcf_get_accel( FT_Stream stream,
PCF_Face face,
FT_ULong type )
{
FT_ULong format, size;
FT_Error error;
PCF_Accel accel = &face->accel;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
type,
&format,
&size );
if ( error )
goto Bail;
if ( FT_READ_ULONG_LE( format ) )
goto Bail;
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) &&
!PCF_FORMAT_MATCH( format, PCF_ACCEL_W_INKBOUNDS ) )
goto Bail;
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
if ( FT_STREAM_READ_FIELDS( pcf_accel_msb_header, accel ) )
goto Bail;
}
else
{
if ( FT_STREAM_READ_FIELDS( pcf_accel_header, accel ) )
goto Bail;
}
error = pcf_get_metric( stream,
format & ( ~PCF_FORMAT_MASK ),
&(accel->minbounds) );
if ( error )
goto Bail;
error = pcf_get_metric( stream,
format & ( ~PCF_FORMAT_MASK ),
&(accel->maxbounds) );
if ( error )
goto Bail;
if ( PCF_FORMAT_MATCH( format, PCF_ACCEL_W_INKBOUNDS ) )
{
error = pcf_get_metric( stream,
format & ( ~PCF_FORMAT_MASK ),
&(accel->ink_minbounds) );
if ( error )
goto Bail;
error = pcf_get_metric( stream,
format & ( ~PCF_FORMAT_MASK ),
&(accel->ink_maxbounds) );
if ( error )
goto Bail;
}
else
{
accel->ink_minbounds = accel->minbounds; /* I'm not sure about this */
accel->ink_maxbounds = accel->maxbounds;
}
Bail:
return error;
}
static FT_Error
pcf_interpret_style( PCF_Face pcf )
{
FT_Error error = FT_Err_Ok;
FT_Face face = FT_FACE( pcf );
FT_Memory memory = face->memory;
PCF_Property prop;
size_t nn, len;
char* strings[4] = { NULL, NULL, NULL, NULL };
size_t lengths[4];
face->style_flags = 0;
prop = pcf_find_property( pcf, "SLANT" );
if ( prop && prop->isString &&
( *(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 = pcf_find_property( pcf, "WEIGHT_NAME" );
if ( prop && prop->isString &&
( *(prop->value.atom) == 'B' || *(prop->value.atom) == 'b' ) )
{
face->style_flags |= FT_STYLE_FLAG_BOLD;
strings[1] = (char*)"Bold";
}
prop = pcf_find_property( pcf, "SETWIDTH_NAME" );
if ( prop && prop->isString &&
*(prop->value.atom) &&
!( *(prop->value.atom) == 'N' || *(prop->value.atom) == 'n' ) )
strings[3] = (char*)( prop->value.atom );
prop = pcf_find_property( pcf, "ADD_STYLE_NAME" );
if ( prop && prop->isString &&
*(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_LOCAL_DEF( FT_Error )
pcf_load_font( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_Bool hasBDFAccelerators;
error = pcf_read_TOC( stream, face );
if ( error )
goto Exit;
error = pcf_get_properties( stream, face );
if ( error )
goto Exit;
/* Use the old accelerators if no BDF accelerators are in the file. */
hasBDFAccelerators = pcf_has_table_type( face->toc.tables,
face->toc.count,
PCF_BDF_ACCELERATORS );
if ( !hasBDFAccelerators )
{
error = pcf_get_accel( stream, face, PCF_ACCELERATORS );
if ( error )
goto Exit;
}
/* metrics */
error = pcf_get_metrics( stream, face );
if ( error )
goto Exit;
/* bitmaps */
error = pcf_get_bitmaps( stream, face );
if ( error )
goto Exit;
/* encodings */
error = pcf_get_encodings( stream, face );
if ( error )
goto Exit;
/* BDF style accelerators (i.e. bounds based on encoded glyphs) */
if ( hasBDFAccelerators )
{
error = pcf_get_accel( stream, face, PCF_BDF_ACCELERATORS );
if ( error )
goto Exit;
}
/* XXX: TO DO: inkmetrics and glyph_names are missing */
/* now construct the face object */
{
FT_Face root = FT_FACE( face );
PCF_Property prop;
root->num_faces = 1;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_FIXED_SIZES |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_FAST_GLYPHS;
if ( face->accel.constantWidth )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
if ( ( error = pcf_interpret_style( face ) ) != 0 )
goto Exit;
prop = pcf_find_property( face, "FAMILY_NAME" );
if ( prop && prop->isString )
{
if ( FT_STRDUP( root->family_name, prop->value.atom ) )
goto Exit;
}
else
root->family_name = NULL;
/*
* Note: We shift all glyph indices by +1 since we must
* respect the convention that glyph 0 always corresponds
* to the `missing glyph'.
*
* This implies bumping the number of `available' glyphs by 1.
*/
root->num_glyphs = face->nmetrics + 1;
root->num_fixed_sizes = 1;
if ( FT_NEW_ARRAY( root->available_sizes, 1 ) )
goto Exit;
{
FT_Bitmap_Size* bsize = root->available_sizes;
FT_Short resolution_x = 0, resolution_y = 0;
FT_MEM_ZERO( bsize, sizeof ( FT_Bitmap_Size ) );
#if 0
bsize->height = face->accel.maxbounds.ascent << 6;
#endif
bsize->height = (FT_Short)( face->accel.fontAscent +
face->accel.fontDescent );
prop = pcf_find_property( face, "AVERAGE_WIDTH" );
if ( prop )
bsize->width = (FT_Short)( ( prop->value.l + 5 ) / 10 );
else
bsize->width = (FT_Short)( bsize->height * 2/3 );
prop = pcf_find_property( face, "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 );
prop = pcf_find_property( face, "PIXEL_SIZE" );
if ( prop )
bsize->y_ppem = (FT_Short)prop->value.l << 6;
prop = pcf_find_property( face, "RESOLUTION_X" );
if ( prop )
resolution_x = (FT_Short)prop->value.l;
prop = pcf_find_property( face, "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;
}
/* set up charset */
{
PCF_Property charset_registry = 0, charset_encoding = 0;
charset_registry = pcf_find_property( face, "CHARSET_REGISTRY" );
charset_encoding = pcf_find_property( face, "CHARSET_ENCODING" );
if ( charset_registry && charset_registry->isString &&
charset_encoding && charset_encoding->isString )
{
if ( FT_STRDUP( face->charset_encoding,
charset_encoding->value.atom ) ||
FT_STRDUP( face->charset_registry,
charset_registry->value.atom ) )
goto Exit;
}
}
}
Exit:
if ( error )
{
/* This is done to respect the behaviour of the original */
/* PCF font driver. */
error = FT_THROW( Invalid_File_Format );
}
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfread.c | C | apache-2.0 | 33,703 |
/* pcfread.h
FreeType font driver for pcf fonts
Copyright 2003 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 __PCFREAD_H__
#define __PCFREAD_H__
#include <ft2build.h>
FT_BEGIN_HEADER
FT_LOCAL( PCF_Property )
pcf_find_property( PCF_Face face,
const FT_String* prop );
FT_END_HEADER
#endif /* __PCFREAD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfread.h | C | apache-2.0 | 1,392 |
/*
Copyright 1990, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
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
OPEN GROUP 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.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/lib/font/util/utilbitmap.c,v 1.3 1999/08/22 08:58:58 dawes Exp $ */
/*
* Author: Keith Packard, MIT X Consortium
*/
/* Modified for use with FreeType */
#include <ft2build.h>
#include "pcfutil.h"
/*
* Invert bit order within each BYTE of an array.
*/
FT_LOCAL_DEF( void )
BitOrderInvert( unsigned char* buf,
size_t nbytes )
{
for ( ; nbytes > 0; nbytes--, buf++ )
{
unsigned int val = *buf;
val = ( ( val >> 1 ) & 0x55 ) | ( ( val << 1 ) & 0xAA );
val = ( ( val >> 2 ) & 0x33 ) | ( ( val << 2 ) & 0xCC );
val = ( ( val >> 4 ) & 0x0F ) | ( ( val << 4 ) & 0xF0 );
*buf = (unsigned char)val;
}
}
/*
* Invert byte order within each 16-bits of an array.
*/
FT_LOCAL_DEF( void )
TwoByteSwap( unsigned char* buf,
size_t nbytes )
{
for ( ; nbytes >= 2; nbytes -= 2, buf += 2 )
{
unsigned char c;
c = buf[0];
buf[0] = buf[1];
buf[1] = c;
}
}
/*
* Invert byte order within each 32-bits of an array.
*/
FT_LOCAL_DEF( void )
FourByteSwap( unsigned char* buf,
size_t nbytes )
{
for ( ; nbytes >= 4; nbytes -= 4, buf += 4 )
{
unsigned char c;
c = buf[0];
buf[0] = buf[3];
buf[3] = c;
c = buf[1];
buf[1] = buf[2];
buf[2] = c;
}
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfutil.c | C | apache-2.0 | 2,596 |
/* pcfutil.h
FreeType font driver for pcf fonts
Copyright 2000, 2001, 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 __PCFUTIL_H__
#define __PCFUTIL_H__
#include <ft2build.h>
#include FT_CONFIG_CONFIG_H
FT_BEGIN_HEADER
FT_LOCAL( void )
BitOrderInvert( unsigned char* buf,
size_t nbytes );
FT_LOCAL( void )
TwoByteSwap( unsigned char* buf,
size_t nbytes );
FT_LOCAL( void )
FourByteSwap( unsigned char* buf,
size_t nbytes );
FT_END_HEADER
#endif /* __PCFUTIL_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pcf/pcfutil.h | C | apache-2.0 | 1,612 |
#
# FreeType 2 pcf driver configuration rules
#
# Copyright (C) 2000, 2001, 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.
# pcf driver directory
#
PCF_DIR := $(SRC_DIR)/pcf
PCF_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(PCF_DIR))
# pcf driver sources (i.e., C files)
#
PCF_DRV_SRC := $(PCF_DIR)/pcfdrivr.c \
$(PCF_DIR)/pcfread.c \
$(PCF_DIR)/pcfutil.c
# pcf driver headers
#
PCF_DRV_H := $(PCF_DRV_SRC:%.c=%.h) \
$(PCF_DIR)/pcf.h \
$(PCF_DIR)/pcferror.h
# pcf driver object(s)
#
# PCF_DRV_OBJ_M is used during `multi' builds
# PCF_DRV_OBJ_S is used during `single' builds
#
PCF_DRV_OBJ_M := $(PCF_DRV_SRC:$(PCF_DIR)/%.c=$(OBJ_DIR)/%.$O)
PCF_DRV_OBJ_S := $(OBJ_DIR)/pcf.$O
# pcf driver source file for single build
#
PCF_DRV_SRC_S := $(PCF_DIR)/pcf.c
# pcf driver - single object
#
$(PCF_DRV_OBJ_S): $(PCF_DRV_SRC_S) $(PCF_DRV_SRC) $(FREETYPE_H) $(PCF_DRV_H)
$(PCF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(PCF_DRV_SRC_S))
# pcf driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(PCF_DIR)/%.c $(FREETYPE_H) $(PCF_DRV_H)
$(PCF_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(PCF_DRV_OBJ_S)
DRV_OBJS_M += $(PCF_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/pcf/rules.mk | Makefile | apache-2.0 | 2,322 |
#
# FreeType 2 PFR module definition
#
# Copyright 2002, 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 += PFR_DRIVER
define PFR_DRIVER
$(OPEN_DRIVER) FT_Driver_ClassRec, pfr_driver_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)pfr $(ECHO_DRIVER_DESC)PFR/TrueDoc font files with extension *.pfr$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/pfr/module.mk | Makefile | apache-2.0 | 661 |
/***************************************************************************/
/* */
/* pfr.c */
/* */
/* FreeType PFR driver component. */
/* */
/* Copyright 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. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "pfrload.c"
#include "pfrgload.c"
#include "pfrcmap.c"
#include "pfrobjs.c"
#include "pfrdrivr.c"
#include "pfrsbit.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfr.c | C | apache-2.0 | 1,449 |
/***************************************************************************/
/* */
/* pfrcmap.c */
/* */
/* FreeType PFR cmap handling (body). */
/* */
/* Copyright 2002, 2007, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include "pfrcmap.h"
#include "pfrobjs.h"
#include "pfrerror.h"
FT_CALLBACK_DEF( FT_Error )
pfr_cmap_init( PFR_CMap cmap )
{
FT_Error error = FT_Err_Ok;
PFR_Face face = (PFR_Face)FT_CMAP_FACE( cmap );
cmap->num_chars = face->phy_font.num_chars;
cmap->chars = face->phy_font.chars;
/* just for safety, check that the character entries are correctly */
/* sorted in increasing character code order */
{
FT_UInt n;
for ( n = 1; n < cmap->num_chars; n++ )
{
if ( cmap->chars[n - 1].char_code >= cmap->chars[n].char_code )
{
error = FT_THROW( Invalid_Table );
goto Exit;
}
}
}
Exit:
return error;
}
FT_CALLBACK_DEF( void )
pfr_cmap_done( PFR_CMap cmap )
{
cmap->chars = NULL;
cmap->num_chars = 0;
}
FT_CALLBACK_DEF( FT_UInt )
pfr_cmap_char_index( PFR_CMap cmap,
FT_UInt32 char_code )
{
FT_UInt min = 0;
FT_UInt max = cmap->num_chars;
while ( min < max )
{
PFR_Char gchar;
FT_UInt mid;
mid = min + ( max - min ) / 2;
gchar = cmap->chars + mid;
if ( gchar->char_code == char_code )
return mid + 1;
if ( gchar->char_code < char_code )
min = mid + 1;
else
max = mid;
}
return 0;
}
FT_CALLBACK_DEF( FT_UInt32 )
pfr_cmap_char_next( PFR_CMap cmap,
FT_UInt32 *pchar_code )
{
FT_UInt result = 0;
FT_UInt32 char_code = *pchar_code + 1;
Restart:
{
FT_UInt min = 0;
FT_UInt max = cmap->num_chars;
FT_UInt mid;
PFR_Char gchar;
while ( min < max )
{
mid = min + ( ( max - min ) >> 1 );
gchar = cmap->chars + mid;
if ( gchar->char_code == char_code )
{
result = mid;
if ( result != 0 )
{
result++;
goto Exit;
}
char_code++;
goto Restart;
}
if ( gchar->char_code < char_code )
min = mid+1;
else
max = mid;
}
/* we didn't find it, but we have a pair just above it */
char_code = 0;
if ( min < cmap->num_chars )
{
gchar = cmap->chars + min;
result = min;
if ( result != 0 )
{
result++;
char_code = gchar->char_code;
}
}
}
Exit:
*pchar_code = char_code;
return result;
}
FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec
pfr_cmap_class_rec =
{
sizeof ( PFR_CMapRec ),
(FT_CMap_InitFunc) pfr_cmap_init,
(FT_CMap_DoneFunc) pfr_cmap_done,
(FT_CMap_CharIndexFunc)pfr_cmap_char_index,
(FT_CMap_CharNextFunc) pfr_cmap_char_next,
NULL, NULL, NULL, NULL, NULL
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrcmap.c | C | apache-2.0 | 4,182 |
/***************************************************************************/
/* */
/* pfrcmap.h */
/* */
/* FreeType PFR cmap handling (specification). */
/* */
/* Copyright 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 __PFRCMAP_H__
#define __PFRCMAP_H__
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include "pfrtypes.h"
FT_BEGIN_HEADER
typedef struct PFR_CMapRec_
{
FT_CMapRec cmap;
FT_UInt num_chars;
PFR_Char chars;
} PFR_CMapRec, *PFR_CMap;
FT_CALLBACK_TABLE const FT_CMap_ClassRec pfr_cmap_class_rec;
FT_END_HEADER
#endif /* __PFRCMAP_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrcmap.h | C | apache-2.0 | 1,647 |
/***************************************************************************/
/* */
/* pfrdrivr.c */
/* */
/* FreeType PFR driver interface (body). */
/* */
/* Copyright 2002-2004, 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 FT_SERVICE_PFR_H
#include FT_SERVICE_XFREE86_NAME_H
#include "pfrdrivr.h"
#include "pfrobjs.h"
#include "pfrerror.h"
FT_CALLBACK_DEF( FT_Error )
pfr_get_kerning( FT_Face pfrface, /* PFR_Face */
FT_UInt left,
FT_UInt right,
FT_Vector *avector )
{
PFR_Face face = (PFR_Face)pfrface;
PFR_PhyFont phys = &face->phy_font;
pfr_face_get_kerning( pfrface, left, right, avector );
/* convert from metrics to outline units when necessary */
if ( phys->outline_resolution != phys->metrics_resolution )
{
if ( avector->x != 0 )
avector->x = FT_MulDiv( avector->x, phys->outline_resolution,
phys->metrics_resolution );
if ( avector->y != 0 )
avector->y = FT_MulDiv( avector->x, phys->outline_resolution,
phys->metrics_resolution );
}
return FT_Err_Ok;
}
/*
* PFR METRICS SERVICE
*
*/
FT_CALLBACK_DEF( FT_Error )
pfr_get_advance( FT_Face pfrface, /* PFR_Face */
FT_UInt gindex,
FT_Pos *anadvance )
{
PFR_Face face = (PFR_Face)pfrface;
FT_Error error = FT_ERR( Invalid_Argument );
*anadvance = 0;
if ( !gindex )
goto Exit;
gindex--;
if ( face )
{
PFR_PhyFont phys = &face->phy_font;
if ( gindex < phys->num_chars )
{
*anadvance = phys->chars[gindex].advance;
error = FT_Err_Ok;
}
}
Exit:
return error;
}
FT_CALLBACK_DEF( FT_Error )
pfr_get_metrics( FT_Face pfrface, /* PFR_Face */
FT_UInt *anoutline_resolution,
FT_UInt *ametrics_resolution,
FT_Fixed *ametrics_x_scale,
FT_Fixed *ametrics_y_scale )
{
PFR_Face face = (PFR_Face)pfrface;
PFR_PhyFont phys = &face->phy_font;
FT_Fixed x_scale, y_scale;
FT_Size size = face->root.size;
if ( anoutline_resolution )
*anoutline_resolution = phys->outline_resolution;
if ( ametrics_resolution )
*ametrics_resolution = phys->metrics_resolution;
x_scale = 0x10000L;
y_scale = 0x10000L;
if ( size )
{
x_scale = FT_DivFix( size->metrics.x_ppem << 6,
phys->metrics_resolution );
y_scale = FT_DivFix( size->metrics.y_ppem << 6,
phys->metrics_resolution );
}
if ( ametrics_x_scale )
*ametrics_x_scale = x_scale;
if ( ametrics_y_scale )
*ametrics_y_scale = y_scale;
return FT_Err_Ok;
}
FT_CALLBACK_TABLE_DEF
const FT_Service_PfrMetricsRec pfr_metrics_service_rec =
{
pfr_get_metrics,
pfr_face_get_kerning,
pfr_get_advance
};
/*
* SERVICE LIST
*
*/
static const FT_ServiceDescRec pfr_services[] =
{
{ FT_SERVICE_ID_PFR_METRICS, &pfr_metrics_service_rec },
{ FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_PFR },
{ NULL, NULL }
};
FT_CALLBACK_DEF( FT_Module_Interface )
pfr_get_service( FT_Module module,
const FT_String* service_id )
{
FT_UNUSED( module );
return ft_service_list_lookup( pfr_services, service_id );
}
FT_CALLBACK_TABLE_DEF
const FT_Driver_ClassRec pfr_driver_class =
{
{
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_SCALABLE,
sizeof ( FT_DriverRec ),
"pfr",
0x10000L,
0x20000L,
NULL,
0, /* FT_Module_Constructor */
0, /* FT_Module_Destructor */
pfr_get_service
},
sizeof ( PFR_FaceRec ),
sizeof ( PFR_SizeRec ),
sizeof ( PFR_SlotRec ),
pfr_face_init,
pfr_face_done,
0, /* FT_Size_InitFunc */
0, /* FT_Size_DoneFunc */
pfr_slot_init,
pfr_slot_done,
pfr_slot_load,
pfr_get_kerning,
0, /* FT_Face_AttachFunc */
0, /* FT_Face_GetAdvancesFunc */
0, /* FT_Size_RequestFunc */
0, /* FT_Size_SelectFunc */
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrdrivr.c | C | apache-2.0 | 5,558 |
/***************************************************************************/
/* */
/* pfrdrivr.h */
/* */
/* High-level Type PFR driver interface (specification). */
/* */
/* Copyright 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 __PFRDRIVR_H__
#define __PFRDRIVR_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_EXPORT_VAR( const FT_Driver_ClassRec ) pfr_driver_class;
FT_END_HEADER
#endif /* __PFRDRIVR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrdrivr.h | C | apache-2.0 | 1,573 |
/***************************************************************************/
/* */
/* pfrerror.h */
/* */
/* PFR error codes (specification only). */
/* */
/* Copyright 2002, 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 PFR error enumeration constants. */
/* */
/*************************************************************************/
#ifndef __PFRERROR_H__
#define __PFRERROR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX PFR_Err_
#define FT_ERR_BASE FT_Mod_Err_PFR
#include FT_ERRORS_H
#endif /* __PFRERROR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrerror.h | C | apache-2.0 | 1,895 |
/***************************************************************************/
/* */
/* pfrgload.c */
/* */
/* FreeType PFR glyph loader (body). */
/* */
/* Copyright 2002, 2003, 2005, 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 "pfrgload.h"
#include "pfrsbit.h"
#include "pfrload.h" /* for macro definitions */
#include FT_INTERNAL_DEBUG_H
#include "pfrerror.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pfr
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR GLYPH BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
pfr_glyph_init( PFR_Glyph glyph,
FT_GlyphLoader loader )
{
FT_ZERO( glyph );
glyph->loader = loader;
glyph->path_begun = 0;
FT_GlyphLoader_Rewind( loader );
}
FT_LOCAL_DEF( void )
pfr_glyph_done( PFR_Glyph glyph )
{
FT_Memory memory = glyph->loader->memory;
FT_FREE( glyph->x_control );
glyph->y_control = NULL;
glyph->max_xy_control = 0;
#if 0
glyph->num_x_control = 0;
glyph->num_y_control = 0;
#endif
FT_FREE( glyph->subs );
glyph->max_subs = 0;
glyph->num_subs = 0;
glyph->loader = NULL;
glyph->path_begun = 0;
}
/* close current contour, if any */
static void
pfr_glyph_close_contour( PFR_Glyph glyph )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Int last, first;
if ( !glyph->path_begun )
return;
/* compute first and last point indices in current glyph outline */
last = outline->n_points - 1;
first = 0;
if ( outline->n_contours > 0 )
first = outline->contours[outline->n_contours - 1];
/* if the last point falls on the same location than the first one */
/* we need to delete it */
if ( last > first )
{
FT_Vector* p1 = outline->points + first;
FT_Vector* p2 = outline->points + last;
if ( p1->x == p2->x && p1->y == p2->y )
{
outline->n_points--;
last--;
}
}
/* don't add empty contours */
if ( last >= first )
outline->contours[outline->n_contours++] = (short)last;
glyph->path_begun = 0;
}
/* reset glyph to start the loading of a new glyph */
static void
pfr_glyph_start( PFR_Glyph glyph )
{
glyph->path_begun = 0;
}
static FT_Error
pfr_glyph_line_to( PFR_Glyph glyph,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Error error;
/* check that we have begun a new path */
if ( !glyph->path_begun )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_line_to: invalid glyph data\n" ));
goto Exit;
}
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 1, 0 );
if ( !error )
{
FT_UInt n = outline->n_points;
outline->points[n] = *to;
outline->tags [n] = FT_CURVE_TAG_ON;
outline->n_points++;
}
Exit:
return error;
}
static FT_Error
pfr_glyph_curve_to( PFR_Glyph glyph,
FT_Vector* control1,
FT_Vector* control2,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Error error;
/* check that we have begun a new path */
if ( !glyph->path_begun )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_line_to: invalid glyph data\n" ));
goto Exit;
}
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 3, 0 );
if ( !error )
{
FT_Vector* vec = outline->points + outline->n_points;
FT_Byte* tag = (FT_Byte*)outline->tags + outline->n_points;
vec[0] = *control1;
vec[1] = *control2;
vec[2] = *to;
tag[0] = FT_CURVE_TAG_CUBIC;
tag[1] = FT_CURVE_TAG_CUBIC;
tag[2] = FT_CURVE_TAG_ON;
outline->n_points = (FT_Short)( outline->n_points + 3 );
}
Exit:
return error;
}
static FT_Error
pfr_glyph_move_to( PFR_Glyph glyph,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Error error;
/* close current contour if any */
pfr_glyph_close_contour( glyph );
/* indicate that a new contour has started */
glyph->path_begun = 1;
/* check that there is space for a new contour and a new point */
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 1, 1 );
if ( !error )
/* add new start point */
error = pfr_glyph_line_to( glyph, to );
return error;
}
static void
pfr_glyph_end( PFR_Glyph glyph )
{
/* close current contour if any */
pfr_glyph_close_contour( glyph );
/* merge the current glyph into the stack */
FT_GlyphLoader_Add( glyph->loader );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR GLYPH LOADER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* load a simple glyph */
static FT_Error
pfr_glyph_load_simple( PFR_Glyph glyph,
FT_Byte* p,
FT_Byte* limit )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory = glyph->loader->memory;
FT_UInt flags, x_count, y_count, i, count, mask;
FT_Int x;
PFR_CHECK( 1 );
flags = PFR_NEXT_BYTE( p );
/* test for composite glyphs */
if ( flags & PFR_GLYPH_IS_COMPOUND )
goto Failure;
x_count = 0;
y_count = 0;
if ( flags & PFR_GLYPH_1BYTE_XYCOUNT )
{
PFR_CHECK( 1 );
count = PFR_NEXT_BYTE( p );
x_count = count & 15;
y_count = count >> 4;
}
else
{
if ( flags & PFR_GLYPH_XCOUNT )
{
PFR_CHECK( 1 );
x_count = PFR_NEXT_BYTE( p );
}
if ( flags & PFR_GLYPH_YCOUNT )
{
PFR_CHECK( 1 );
y_count = PFR_NEXT_BYTE( p );
}
}
count = x_count + y_count;
/* re-allocate array when necessary */
if ( count > glyph->max_xy_control )
{
FT_UInt new_max = FT_PAD_CEIL( count, 8 );
if ( FT_RENEW_ARRAY( glyph->x_control,
glyph->max_xy_control,
new_max ) )
goto Exit;
glyph->max_xy_control = new_max;
}
glyph->y_control = glyph->x_control + x_count;
mask = 0;
x = 0;
for ( i = 0; i < count; i++ )
{
if ( ( i & 7 ) == 0 )
{
PFR_CHECK( 1 );
mask = PFR_NEXT_BYTE( p );
}
if ( mask & 1 )
{
PFR_CHECK( 2 );
x = PFR_NEXT_SHORT( p );
}
else
{
PFR_CHECK( 1 );
x += PFR_NEXT_BYTE( p );
}
glyph->x_control[i] = x;
mask >>= 1;
}
/* XXX: for now we ignore the secondary stroke and edge definitions */
/* since we don't want to support native PFR hinting */
/* */
if ( flags & PFR_GLYPH_EXTRA_ITEMS )
{
error = pfr_extra_items_skip( &p, limit );
if ( error )
goto Exit;
}
pfr_glyph_start( glyph );
/* now load a simple glyph */
{
FT_Vector pos[4];
FT_Vector* cur;
pos[0].x = pos[0].y = 0;
pos[3] = pos[0];
for (;;)
{
FT_UInt format, format_low, args_format = 0, args_count, n;
/***************************************************************/
/* read instruction */
/* */
PFR_CHECK( 1 );
format = PFR_NEXT_BYTE( p );
format_low = format & 15;
switch ( format >> 4 )
{
case 0: /* end glyph */
FT_TRACE6(( "- end glyph" ));
args_count = 0;
break;
case 1: /* general line operation */
FT_TRACE6(( "- general line" ));
goto Line1;
case 4: /* move to inside contour */
FT_TRACE6(( "- move to inside" ));
goto Line1;
case 5: /* move to outside contour */
FT_TRACE6(( "- move to outside" ));
Line1:
args_format = format_low;
args_count = 1;
break;
case 2: /* horizontal line to */
FT_TRACE6(( "- horizontal line to cx.%d", format_low ));
if ( format_low >= x_count )
goto Failure;
pos[0].x = glyph->x_control[format_low];
pos[0].y = pos[3].y;
pos[3] = pos[0];
args_count = 0;
break;
case 3: /* vertical line to */
FT_TRACE6(( "- vertical line to cy.%d", format_low ));
if ( format_low >= y_count )
goto Failure;
pos[0].x = pos[3].x;
pos[0].y = glyph->y_control[format_low];
pos[3] = pos[0];
args_count = 0;
break;
case 6: /* horizontal to vertical curve */
FT_TRACE6(( "- hv curve " ));
args_format = 0xB8E;
args_count = 3;
break;
case 7: /* vertical to horizontal curve */
FT_TRACE6(( "- vh curve" ));
args_format = 0xE2B;
args_count = 3;
break;
default: /* general curve to */
FT_TRACE6(( "- general curve" ));
args_count = 4;
args_format = format_low;
}
/***********************************************************/
/* now read arguments */
/* */
cur = pos;
for ( n = 0; n < args_count; n++ )
{
FT_UInt idx;
FT_Int delta;
/* read the X argument */
switch ( args_format & 3 )
{
case 0: /* 8-bit index */
PFR_CHECK( 1 );
idx = PFR_NEXT_BYTE( p );
if ( idx >= x_count )
goto Failure;
cur->x = glyph->x_control[idx];
FT_TRACE7(( " cx#%d", idx ));
break;
case 1: /* 16-bit value */
PFR_CHECK( 2 );
cur->x = PFR_NEXT_SHORT( p );
FT_TRACE7(( " x.%d", cur->x ));
break;
case 2: /* 8-bit delta */
PFR_CHECK( 1 );
delta = PFR_NEXT_INT8( p );
cur->x = pos[3].x + delta;
FT_TRACE7(( " dx.%d", delta ));
break;
default:
FT_TRACE7(( " |" ));
cur->x = pos[3].x;
}
/* read the Y argument */
switch ( ( args_format >> 2 ) & 3 )
{
case 0: /* 8-bit index */
PFR_CHECK( 1 );
idx = PFR_NEXT_BYTE( p );
if ( idx >= y_count )
goto Failure;
cur->y = glyph->y_control[idx];
FT_TRACE7(( " cy#%d", idx ));
break;
case 1: /* 16-bit absolute value */
PFR_CHECK( 2 );
cur->y = PFR_NEXT_SHORT( p );
FT_TRACE7(( " y.%d", cur->y ));
break;
case 2: /* 8-bit delta */
PFR_CHECK( 1 );
delta = PFR_NEXT_INT8( p );
cur->y = pos[3].y + delta;
FT_TRACE7(( " dy.%d", delta ));
break;
default:
FT_TRACE7(( " -" ));
cur->y = pos[3].y;
}
/* read the additional format flag for the general curve */
if ( n == 0 && args_count == 4 )
{
PFR_CHECK( 1 );
args_format = PFR_NEXT_BYTE( p );
args_count--;
}
else
args_format >>= 4;
/* save the previous point */
pos[3] = cur[0];
cur++;
}
FT_TRACE7(( "\n" ));
/***********************************************************/
/* finally, execute instruction */
/* */
switch ( format >> 4 )
{
case 0: /* end glyph => EXIT */
pfr_glyph_end( glyph );
goto Exit;
case 1: /* line operations */
case 2:
case 3:
error = pfr_glyph_line_to( glyph, pos );
goto Test_Error;
case 4: /* move to inside contour */
case 5: /* move to outside contour */
error = pfr_glyph_move_to( glyph, pos );
goto Test_Error;
default: /* curve operations */
error = pfr_glyph_curve_to( glyph, pos, pos + 1, pos + 2 );
Test_Error: /* test error condition */
if ( error )
goto Exit;
}
} /* for (;;) */
}
Exit:
return error;
Failure:
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_simple: invalid glyph data\n" ));
goto Exit;
}
/* load a composite/compound glyph */
static FT_Error
pfr_glyph_load_compound( PFR_Glyph glyph,
FT_Byte* p,
FT_Byte* limit )
{
FT_Error error = FT_Err_Ok;
FT_GlyphLoader loader = glyph->loader;
FT_Memory memory = loader->memory;
PFR_SubGlyph subglyph;
FT_UInt flags, i, count, org_count;
FT_Int x_pos, y_pos;
PFR_CHECK( 1 );
flags = PFR_NEXT_BYTE( p );
/* test for composite glyphs */
if ( !( flags & PFR_GLYPH_IS_COMPOUND ) )
goto Failure;
count = flags & 0x3F;
/* ignore extra items when present */
/* */
if ( flags & PFR_GLYPH_EXTRA_ITEMS )
{
error = pfr_extra_items_skip( &p, limit );
if (error) goto Exit;
}
/* we can't rely on the FT_GlyphLoader to load sub-glyphs, because */
/* the PFR format is dumb, using direct file offsets to point to the */
/* sub-glyphs (instead of glyph indices). Sigh. */
/* */
/* For now, we load the list of sub-glyphs into a different array */
/* but this will prevent us from using the auto-hinter at its best */
/* quality. */
/* */
org_count = glyph->num_subs;
if ( org_count + count > glyph->max_subs )
{
FT_UInt new_max = ( org_count + count + 3 ) & (FT_UInt)-4;
/* we arbitrarily limit the number of subglyphs */
/* to avoid endless recursion */
if ( new_max > 64 )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_compound:"
" too many compound glyphs components\n" ));
goto Exit;
}
if ( FT_RENEW_ARRAY( glyph->subs, glyph->max_subs, new_max ) )
goto Exit;
glyph->max_subs = new_max;
}
subglyph = glyph->subs + org_count;
for ( i = 0; i < count; i++, subglyph++ )
{
FT_UInt format;
x_pos = 0;
y_pos = 0;
PFR_CHECK( 1 );
format = PFR_NEXT_BYTE( p );
/* read scale when available */
subglyph->x_scale = 0x10000L;
if ( format & PFR_SUBGLYPH_XSCALE )
{
PFR_CHECK( 2 );
subglyph->x_scale = PFR_NEXT_SHORT( p ) << 4;
}
subglyph->y_scale = 0x10000L;
if ( format & PFR_SUBGLYPH_YSCALE )
{
PFR_CHECK( 2 );
subglyph->y_scale = PFR_NEXT_SHORT( p ) << 4;
}
/* read offset */
switch ( format & 3 )
{
case 1:
PFR_CHECK( 2 );
x_pos = PFR_NEXT_SHORT( p );
break;
case 2:
PFR_CHECK( 1 );
x_pos += PFR_NEXT_INT8( p );
break;
default:
;
}
switch ( ( format >> 2 ) & 3 )
{
case 1:
PFR_CHECK( 2 );
y_pos = PFR_NEXT_SHORT( p );
break;
case 2:
PFR_CHECK( 1 );
y_pos += PFR_NEXT_INT8( p );
break;
default:
;
}
subglyph->x_delta = x_pos;
subglyph->y_delta = y_pos;
/* read glyph position and size now */
if ( format & PFR_SUBGLYPH_2BYTE_SIZE )
{
PFR_CHECK( 2 );
subglyph->gps_size = PFR_NEXT_USHORT( p );
}
else
{
PFR_CHECK( 1 );
subglyph->gps_size = PFR_NEXT_BYTE( p );
}
if ( format & PFR_SUBGLYPH_3BYTE_OFFSET )
{
PFR_CHECK( 3 );
subglyph->gps_offset = PFR_NEXT_LONG( p );
}
else
{
PFR_CHECK( 2 );
subglyph->gps_offset = PFR_NEXT_USHORT( p );
}
glyph->num_subs++;
}
Exit:
return error;
Failure:
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_compound: invalid glyph data\n" ));
goto Exit;
}
static FT_Error
pfr_glyph_load_rec( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size )
{
FT_Error error;
FT_Byte* p;
FT_Byte* limit;
if ( FT_STREAM_SEEK( gps_offset + offset ) ||
FT_FRAME_ENTER( size ) )
goto Exit;
p = (FT_Byte*)stream->cursor;
limit = p + size;
if ( size > 0 && *p & PFR_GLYPH_IS_COMPOUND )
{
FT_Int n, old_count, count;
FT_GlyphLoader loader = glyph->loader;
FT_Outline* base = &loader->base.outline;
old_count = glyph->num_subs;
/* this is a compound glyph - load it */
error = pfr_glyph_load_compound( glyph, p, limit );
FT_FRAME_EXIT();
if ( error )
goto Exit;
count = glyph->num_subs - old_count;
FT_TRACE4(( "compound glyph with %d elements (offset %lu):\n",
count, offset ));
/* now, load each individual glyph */
for ( n = 0; n < count; n++ )
{
FT_Int i, old_points, num_points;
PFR_SubGlyph subglyph;
FT_TRACE4(( " subglyph %d:\n", n ));
subglyph = glyph->subs + old_count + n;
old_points = base->n_points;
error = pfr_glyph_load_rec( glyph, stream, gps_offset,
subglyph->gps_offset,
subglyph->gps_size );
if ( error )
break;
/* note that `glyph->subs' might have been re-allocated */
subglyph = glyph->subs + old_count + n;
num_points = base->n_points - old_points;
/* translate and eventually scale the new glyph points */
if ( subglyph->x_scale != 0x10000L || subglyph->y_scale != 0x10000L )
{
FT_Vector* vec = base->points + old_points;
for ( i = 0; i < num_points; i++, vec++ )
{
vec->x = FT_MulFix( vec->x, subglyph->x_scale ) +
subglyph->x_delta;
vec->y = FT_MulFix( vec->y, subglyph->y_scale ) +
subglyph->y_delta;
}
}
else
{
FT_Vector* vec = loader->base.outline.points + old_points;
for ( i = 0; i < num_points; i++, vec++ )
{
vec->x += subglyph->x_delta;
vec->y += subglyph->y_delta;
}
}
/* proceed to next sub-glyph */
}
FT_TRACE4(( "end compound glyph with %d elements\n", count ));
}
else
{
FT_TRACE4(( "simple glyph (offset %lu)\n", offset ));
/* load a simple glyph */
error = pfr_glyph_load_simple( glyph, p, limit );
FT_FRAME_EXIT();
}
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
pfr_glyph_load( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size )
{
/* initialize glyph loader */
FT_GlyphLoader_Rewind( glyph->loader );
glyph->num_subs = 0;
/* load the glyph, recursively when needed */
return pfr_glyph_load_rec( glyph, stream, gps_offset, offset, size );
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrgload.c | C | apache-2.0 | 22,763 |
/***************************************************************************/
/* */
/* pfrgload.h */
/* */
/* FreeType PFR glyph loader (specification). */
/* */
/* Copyright 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 __PFRGLOAD_H__
#define __PFRGLOAD_H__
#include "pfrtypes.h"
FT_BEGIN_HEADER
FT_LOCAL( void )
pfr_glyph_init( PFR_Glyph glyph,
FT_GlyphLoader loader );
FT_LOCAL( void )
pfr_glyph_done( PFR_Glyph glyph );
FT_LOCAL( FT_Error )
pfr_glyph_load( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size );
FT_END_HEADER
#endif /* __PFRGLOAD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrgload.h | C | apache-2.0 | 1,771 |
/***************************************************************************/
/* */
/* pfrload.c */
/* */
/* FreeType PFR loader (body). */
/* */
/* Copyright 2002-2005, 2007, 2009, 2010, 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 "pfrload.h"
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include "pfrerror.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pfr
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** EXTRA ITEMS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( FT_Error )
pfr_extra_items_skip( FT_Byte* *pp,
FT_Byte* limit )
{
return pfr_extra_items_parse( pp, limit, NULL, NULL );
}
FT_LOCAL_DEF( FT_Error )
pfr_extra_items_parse( FT_Byte* *pp,
FT_Byte* limit,
PFR_ExtraItem item_list,
FT_Pointer item_data )
{
FT_Error error = FT_Err_Ok;
FT_Byte* p = *pp;
FT_UInt num_items, item_type, item_size;
PFR_CHECK( 1 );
num_items = PFR_NEXT_BYTE( p );
for ( ; num_items > 0; num_items-- )
{
PFR_CHECK( 2 );
item_size = PFR_NEXT_BYTE( p );
item_type = PFR_NEXT_BYTE( p );
PFR_CHECK( item_size );
if ( item_list )
{
PFR_ExtraItem extra = item_list;
for ( extra = item_list; extra->parser != NULL; extra++ )
{
if ( extra->type == item_type )
{
error = extra->parser( p, p + item_size, item_data );
if ( error ) goto Exit;
break;
}
}
}
p += item_size;
}
Exit:
*pp = p;
return error;
Too_Short:
FT_ERROR(( "pfr_extra_items_parse: invalid extra items table\n" ));
error = FT_THROW( Invalid_Table );
goto Exit;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR HEADER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static const FT_Frame_Field pfr_header_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE PFR_HeaderRec
FT_FRAME_START( 58 ),
FT_FRAME_ULONG ( signature ),
FT_FRAME_USHORT( version ),
FT_FRAME_USHORT( signature2 ),
FT_FRAME_USHORT( header_size ),
FT_FRAME_USHORT( log_dir_size ),
FT_FRAME_USHORT( log_dir_offset ),
FT_FRAME_USHORT( log_font_max_size ),
FT_FRAME_UOFF3 ( log_font_section_size ),
FT_FRAME_UOFF3 ( log_font_section_offset ),
FT_FRAME_USHORT( phy_font_max_size ),
FT_FRAME_UOFF3 ( phy_font_section_size ),
FT_FRAME_UOFF3 ( phy_font_section_offset ),
FT_FRAME_USHORT( gps_max_size ),
FT_FRAME_UOFF3 ( gps_section_size ),
FT_FRAME_UOFF3 ( gps_section_offset ),
FT_FRAME_BYTE ( max_blue_values ),
FT_FRAME_BYTE ( max_x_orus ),
FT_FRAME_BYTE ( max_y_orus ),
FT_FRAME_BYTE ( phy_font_max_size_high ),
FT_FRAME_BYTE ( color_flags ),
FT_FRAME_UOFF3 ( bct_max_size ),
FT_FRAME_UOFF3 ( bct_set_max_size ),
FT_FRAME_UOFF3 ( phy_bct_set_max_size ),
FT_FRAME_USHORT( num_phy_fonts ),
FT_FRAME_BYTE ( max_vert_stem_snap ),
FT_FRAME_BYTE ( max_horz_stem_snap ),
FT_FRAME_USHORT( max_chars ),
FT_FRAME_END
};
FT_LOCAL_DEF( FT_Error )
pfr_header_load( PFR_Header header,
FT_Stream stream )
{
FT_Error error = FT_Err_Ok;
/* read header directly */
if ( !FT_STREAM_SEEK( 0 ) &&
!FT_STREAM_READ_FIELDS( pfr_header_fields, header ) )
{
/* make a few adjustments to the header */
header->phy_font_max_size +=
(FT_UInt32)header->phy_font_max_size_high << 16;
}
return error;
}
FT_LOCAL_DEF( FT_Bool )
pfr_header_check( PFR_Header header )
{
FT_Bool result = 1;
/* check signature and header size */
if ( header->signature != 0x50465230L || /* "PFR0" */
header->version > 4 ||
header->header_size < 58 ||
header->signature2 != 0x0d0a ) /* CR/LF */
{
result = 0;
}
return result;
}
/***********************************************************************/
/***********************************************************************/
/***** *****/
/***** PFR LOGICAL FONTS *****/
/***** *****/
/***********************************************************************/
/***********************************************************************/
FT_LOCAL_DEF( FT_Error )
pfr_log_font_count( FT_Stream stream,
FT_UInt32 section_offset,
FT_UInt *acount )
{
FT_Error error;
FT_UInt count;
FT_UInt result = 0;
if ( FT_STREAM_SEEK( section_offset ) || FT_READ_USHORT( count ) )
goto Exit;
result = count;
Exit:
*acount = result;
return error;
}
FT_LOCAL_DEF( FT_Error )
pfr_log_font_load( PFR_LogFont log_font,
FT_Stream stream,
FT_UInt idx,
FT_UInt32 section_offset,
FT_Bool size_increment )
{
FT_UInt num_log_fonts;
FT_UInt flags;
FT_UInt32 offset;
FT_UInt32 size;
FT_Error error;
if ( FT_STREAM_SEEK( section_offset ) ||
FT_READ_USHORT( num_log_fonts ) )
goto Exit;
if ( idx >= num_log_fonts )
return FT_THROW( Invalid_Argument );
if ( FT_STREAM_SKIP( idx * 5 ) ||
FT_READ_USHORT( size ) ||
FT_READ_UOFF3 ( offset ) )
goto Exit;
/* save logical font size and offset */
log_font->size = size;
log_font->offset = offset;
/* now, check the rest of the table before loading it */
{
FT_Byte* p;
FT_Byte* limit;
FT_UInt local;
if ( FT_STREAM_SEEK( offset ) || FT_FRAME_ENTER( size ) )
goto Exit;
p = stream->cursor;
limit = p + size;
PFR_CHECK(13);
log_font->matrix[0] = PFR_NEXT_LONG( p );
log_font->matrix[1] = PFR_NEXT_LONG( p );
log_font->matrix[2] = PFR_NEXT_LONG( p );
log_font->matrix[3] = PFR_NEXT_LONG( p );
flags = PFR_NEXT_BYTE( p );
local = 0;
if ( flags & PFR_LOG_STROKE )
{
local++;
if ( flags & PFR_LOG_2BYTE_STROKE )
local++;
if ( (flags & PFR_LINE_JOIN_MASK) == PFR_LINE_JOIN_MITER )
local += 3;
}
if ( flags & PFR_LOG_BOLD )
{
local++;
if ( flags & PFR_LOG_2BYTE_BOLD )
local++;
}
PFR_CHECK( local );
if ( flags & PFR_LOG_STROKE )
{
log_font->stroke_thickness = ( flags & PFR_LOG_2BYTE_STROKE )
? PFR_NEXT_SHORT( p )
: PFR_NEXT_BYTE( p );
if ( ( flags & PFR_LINE_JOIN_MASK ) == PFR_LINE_JOIN_MITER )
log_font->miter_limit = PFR_NEXT_LONG( p );
}
if ( flags & PFR_LOG_BOLD )
{
log_font->bold_thickness = ( flags & PFR_LOG_2BYTE_BOLD )
? PFR_NEXT_SHORT( p )
: PFR_NEXT_BYTE( p );
}
if ( flags & PFR_LOG_EXTRA_ITEMS )
{
error = pfr_extra_items_skip( &p, limit );
if (error) goto Fail;
}
PFR_CHECK(5);
log_font->phys_size = PFR_NEXT_USHORT( p );
log_font->phys_offset = PFR_NEXT_ULONG( p );
if ( size_increment )
{
PFR_CHECK( 1 );
log_font->phys_size += (FT_UInt32)PFR_NEXT_BYTE( p ) << 16;
}
}
Fail:
FT_FRAME_EXIT();
Exit:
return error;
Too_Short:
FT_ERROR(( "pfr_log_font_load: invalid logical font table\n" ));
error = FT_THROW( Invalid_Table );
goto Fail;
}
/***********************************************************************/
/***********************************************************************/
/***** *****/
/***** PFR PHYSICAL FONTS *****/
/***** *****/
/***********************************************************************/
/***********************************************************************/
/* load bitmap strikes lists */
FT_CALLBACK_DEF( FT_Error )
pfr_extra_item_load_bitmap_info( FT_Byte* p,
FT_Byte* limit,
PFR_PhyFont phy_font )
{
FT_Memory memory = phy_font->memory;
PFR_Strike strike;
FT_UInt flags0;
FT_UInt n, count, size1;
FT_Error error = FT_Err_Ok;
PFR_CHECK( 5 );
p += 3; /* skip bctSize */
flags0 = PFR_NEXT_BYTE( p );
count = PFR_NEXT_BYTE( p );
/* re-allocate when needed */
if ( phy_font->num_strikes + count > phy_font->max_strikes )
{
FT_UInt new_max = FT_PAD_CEIL( phy_font->num_strikes + count, 4 );
if ( FT_RENEW_ARRAY( phy_font->strikes,
phy_font->num_strikes,
new_max ) )
goto Exit;
phy_font->max_strikes = new_max;
}
size1 = 1 + 1 + 1 + 2 + 2 + 1;
if ( flags0 & PFR_STRIKE_2BYTE_XPPM )
size1++;
if ( flags0 & PFR_STRIKE_2BYTE_YPPM )
size1++;
if ( flags0 & PFR_STRIKE_3BYTE_SIZE )
size1++;
if ( flags0 & PFR_STRIKE_3BYTE_OFFSET )
size1++;
if ( flags0 & PFR_STRIKE_2BYTE_COUNT )
size1++;
strike = phy_font->strikes + phy_font->num_strikes;
PFR_CHECK( count * size1 );
for ( n = 0; n < count; n++, strike++ )
{
strike->x_ppm = ( flags0 & PFR_STRIKE_2BYTE_XPPM )
? PFR_NEXT_USHORT( p )
: PFR_NEXT_BYTE( p );
strike->y_ppm = ( flags0 & PFR_STRIKE_2BYTE_YPPM )
? PFR_NEXT_USHORT( p )
: PFR_NEXT_BYTE( p );
strike->flags = PFR_NEXT_BYTE( p );
strike->bct_size = ( flags0 & PFR_STRIKE_3BYTE_SIZE )
? PFR_NEXT_ULONG( p )
: PFR_NEXT_USHORT( p );
strike->bct_offset = ( flags0 & PFR_STRIKE_3BYTE_OFFSET )
? PFR_NEXT_ULONG( p )
: PFR_NEXT_USHORT( p );
strike->num_bitmaps = ( flags0 & PFR_STRIKE_2BYTE_COUNT )
? PFR_NEXT_USHORT( p )
: PFR_NEXT_BYTE( p );
}
phy_font->num_strikes += count;
Exit:
return error;
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_extra_item_load_bitmap_info:"
" invalid bitmap info table\n" ));
goto Exit;
}
/* Load font ID. This is a so-called "unique" name that is rather
* long and descriptive (like "Tiresias ScreenFont v7.51").
*
* Note that a PFR font's family name is contained in an *undocumented*
* string of the "auxiliary data" portion of a physical font record. This
* may also contain the "real" style name!
*
* If no family name is present, the font ID is used instead for the
* family.
*/
FT_CALLBACK_DEF( FT_Error )
pfr_extra_item_load_font_id( FT_Byte* p,
FT_Byte* limit,
PFR_PhyFont phy_font )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory = phy_font->memory;
FT_PtrDist len = limit - p;
if ( phy_font->font_id != NULL )
goto Exit;
if ( FT_ALLOC( phy_font->font_id, len + 1 ) )
goto Exit;
/* copy font ID name, and terminate it for safety */
FT_MEM_COPY( phy_font->font_id, p, len );
phy_font->font_id[len] = 0;
Exit:
return error;
}
/* load stem snap tables */
FT_CALLBACK_DEF( FT_Error )
pfr_extra_item_load_stem_snaps( FT_Byte* p,
FT_Byte* limit,
PFR_PhyFont phy_font )
{
FT_UInt count, num_vert, num_horz;
FT_Int* snaps = NULL;
FT_Error error = FT_Err_Ok;
FT_Memory memory = phy_font->memory;
if ( phy_font->vertical.stem_snaps != NULL )
goto Exit;
PFR_CHECK( 1 );
count = PFR_NEXT_BYTE( p );
num_vert = count & 15;
num_horz = count >> 4;
count = num_vert + num_horz;
PFR_CHECK( count * 2 );
if ( FT_NEW_ARRAY( snaps, count ) )
goto Exit;
phy_font->vertical.stem_snaps = snaps;
phy_font->horizontal.stem_snaps = snaps + num_vert;
for ( ; count > 0; count--, snaps++ )
*snaps = FT_NEXT_SHORT( p );
Exit:
return error;
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_exta_item_load_stem_snaps:"
" invalid stem snaps table\n" ));
goto Exit;
}
/* load kerning pair data */
FT_CALLBACK_DEF( FT_Error )
pfr_extra_item_load_kerning_pairs( FT_Byte* p,
FT_Byte* limit,
PFR_PhyFont phy_font )
{
PFR_KernItem item = NULL;
FT_Error error = FT_Err_Ok;
FT_Memory memory = phy_font->memory;
FT_TRACE2(( "pfr_extra_item_load_kerning_pairs()\n" ));
if ( FT_NEW( item ) )
goto Exit;
PFR_CHECK( 4 );
item->pair_count = PFR_NEXT_BYTE( p );
item->base_adj = PFR_NEXT_SHORT( p );
item->flags = PFR_NEXT_BYTE( p );
item->offset = phy_font->offset + ( p - phy_font->cursor );
#ifndef PFR_CONFIG_NO_CHECKS
item->pair_size = 3;
if ( item->flags & PFR_KERN_2BYTE_CHAR )
item->pair_size += 2;
if ( item->flags & PFR_KERN_2BYTE_ADJ )
item->pair_size += 1;
PFR_CHECK( item->pair_count * item->pair_size );
#endif
/* load first and last pairs into the item to speed up */
/* lookup later... */
if ( item->pair_count > 0 )
{
FT_UInt char1, char2;
FT_Byte* q;
if ( item->flags & PFR_KERN_2BYTE_CHAR )
{
q = p;
char1 = PFR_NEXT_USHORT( q );
char2 = PFR_NEXT_USHORT( q );
item->pair1 = PFR_KERN_INDEX( char1, char2 );
q = p + item->pair_size * ( item->pair_count - 1 );
char1 = PFR_NEXT_USHORT( q );
char2 = PFR_NEXT_USHORT( q );
item->pair2 = PFR_KERN_INDEX( char1, char2 );
}
else
{
q = p;
char1 = PFR_NEXT_BYTE( q );
char2 = PFR_NEXT_BYTE( q );
item->pair1 = PFR_KERN_INDEX( char1, char2 );
q = p + item->pair_size * ( item->pair_count - 1 );
char1 = PFR_NEXT_BYTE( q );
char2 = PFR_NEXT_BYTE( q );
item->pair2 = PFR_KERN_INDEX( char1, char2 );
}
/* add new item to the current list */
item->next = NULL;
*phy_font->kern_items_tail = item;
phy_font->kern_items_tail = &item->next;
phy_font->num_kern_pairs += item->pair_count;
}
else
{
/* empty item! */
FT_FREE( item );
}
Exit:
return error;
Too_Short:
FT_FREE( item );
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_extra_item_load_kerning_pairs:"
" invalid kerning pairs table\n" ));
goto Exit;
}
static const PFR_ExtraItemRec pfr_phy_font_extra_items[] =
{
{ 1, (PFR_ExtraItem_ParseFunc)pfr_extra_item_load_bitmap_info },
{ 2, (PFR_ExtraItem_ParseFunc)pfr_extra_item_load_font_id },
{ 3, (PFR_ExtraItem_ParseFunc)pfr_extra_item_load_stem_snaps },
{ 4, (PFR_ExtraItem_ParseFunc)pfr_extra_item_load_kerning_pairs },
{ 0, NULL }
};
/* Loads a name from the auxiliary data. Since this extracts undocumented
* strings from the font file, we need to be careful here.
*/
static FT_Error
pfr_aux_name_load( FT_Byte* p,
FT_UInt len,
FT_Memory memory,
FT_String* *astring )
{
FT_Error error = FT_Err_Ok;
FT_String* result = NULL;
FT_UInt n, ok;
if ( len > 0 && p[len - 1] == 0 )
len--;
/* check that each character is ASCII for making sure not to
load garbage
*/
ok = ( len > 0 );
for ( n = 0; n < len; n++ )
if ( p[n] < 32 || p[n] > 127 )
{
ok = 0;
break;
}
if ( ok )
{
if ( FT_ALLOC( result, len + 1 ) )
goto Exit;
FT_MEM_COPY( result, p, len );
result[len] = 0;
}
Exit:
*astring = result;
return error;
}
FT_LOCAL_DEF( void )
pfr_phy_font_done( PFR_PhyFont phy_font,
FT_Memory memory )
{
FT_FREE( phy_font->font_id );
FT_FREE( phy_font->family_name );
FT_FREE( phy_font->style_name );
FT_FREE( phy_font->vertical.stem_snaps );
phy_font->vertical.num_stem_snaps = 0;
phy_font->horizontal.stem_snaps = NULL;
phy_font->horizontal.num_stem_snaps = 0;
FT_FREE( phy_font->strikes );
phy_font->num_strikes = 0;
phy_font->max_strikes = 0;
FT_FREE( phy_font->chars );
phy_font->num_chars = 0;
phy_font->chars_offset = 0;
FT_FREE( phy_font->blue_values );
phy_font->num_blue_values = 0;
{
PFR_KernItem item, next;
item = phy_font->kern_items;
while ( item )
{
next = item->next;
FT_FREE( item );
item = next;
}
phy_font->kern_items = NULL;
phy_font->kern_items_tail = NULL;
}
phy_font->num_kern_pairs = 0;
}
FT_LOCAL_DEF( FT_Error )
pfr_phy_font_load( PFR_PhyFont phy_font,
FT_Stream stream,
FT_UInt32 offset,
FT_UInt32 size )
{
FT_Error error;
FT_Memory memory = stream->memory;
FT_UInt flags;
FT_ULong num_aux;
FT_Byte* p;
FT_Byte* limit;
phy_font->memory = memory;
phy_font->offset = offset;
phy_font->kern_items = NULL;
phy_font->kern_items_tail = &phy_font->kern_items;
if ( FT_STREAM_SEEK( offset ) || FT_FRAME_ENTER( size ) )
goto Exit;
phy_font->cursor = stream->cursor;
p = stream->cursor;
limit = p + size;
PFR_CHECK( 15 );
phy_font->font_ref_number = PFR_NEXT_USHORT( p );
phy_font->outline_resolution = PFR_NEXT_USHORT( p );
phy_font->metrics_resolution = PFR_NEXT_USHORT( p );
phy_font->bbox.xMin = PFR_NEXT_SHORT( p );
phy_font->bbox.yMin = PFR_NEXT_SHORT( p );
phy_font->bbox.xMax = PFR_NEXT_SHORT( p );
phy_font->bbox.yMax = PFR_NEXT_SHORT( p );
phy_font->flags = flags = PFR_NEXT_BYTE( p );
/* get the standard advance for non-proportional fonts */
if ( !(flags & PFR_PHY_PROPORTIONAL) )
{
PFR_CHECK( 2 );
phy_font->standard_advance = PFR_NEXT_SHORT( p );
}
/* load the extra items when present */
if ( flags & PFR_PHY_EXTRA_ITEMS )
{
error = pfr_extra_items_parse( &p, limit,
pfr_phy_font_extra_items, phy_font );
if ( error )
goto Fail;
}
/* In certain fonts, the auxiliary bytes contain interesting */
/* information. These are not in the specification but can be */
/* guessed by looking at the content of a few PFR0 fonts. */
PFR_CHECK( 3 );
num_aux = PFR_NEXT_ULONG( p );
if ( num_aux > 0 )
{
FT_Byte* q = p;
FT_Byte* q2;
PFR_CHECK( num_aux );
p += num_aux;
while ( num_aux > 0 )
{
FT_UInt length, type;
if ( q + 4 > p )
break;
length = PFR_NEXT_USHORT( q );
if ( length < 4 || length > num_aux )
break;
q2 = q + length - 2;
type = PFR_NEXT_USHORT( q );
switch ( type )
{
case 1:
/* this seems to correspond to the font's family name,
* padded to 16-bits with one zero when necessary
*/
error = pfr_aux_name_load( q, length - 4U, memory,
&phy_font->family_name );
if ( error )
goto Exit;
break;
case 2:
if ( q + 32 > q2 )
break;
q += 10;
phy_font->ascent = PFR_NEXT_SHORT( q );
phy_font->descent = PFR_NEXT_SHORT( q );
phy_font->leading = PFR_NEXT_SHORT( q );
break;
case 3:
/* this seems to correspond to the font's style name,
* padded to 16-bits with one zero when necessary
*/
error = pfr_aux_name_load( q, length - 4U, memory,
&phy_font->style_name );
if ( error )
goto Exit;
break;
default:
;
}
q = q2;
num_aux -= length;
}
}
/* read the blue values */
{
FT_UInt n, count;
PFR_CHECK( 1 );
phy_font->num_blue_values = count = PFR_NEXT_BYTE( p );
PFR_CHECK( count * 2 );
if ( FT_NEW_ARRAY( phy_font->blue_values, count ) )
goto Fail;
for ( n = 0; n < count; n++ )
phy_font->blue_values[n] = PFR_NEXT_SHORT( p );
}
PFR_CHECK( 8 );
phy_font->blue_fuzz = PFR_NEXT_BYTE( p );
phy_font->blue_scale = PFR_NEXT_BYTE( p );
phy_font->vertical.standard = PFR_NEXT_USHORT( p );
phy_font->horizontal.standard = PFR_NEXT_USHORT( p );
/* read the character descriptors */
{
FT_UInt n, count, Size;
phy_font->num_chars = count = PFR_NEXT_USHORT( p );
phy_font->chars_offset = offset + ( p - stream->cursor );
if ( FT_NEW_ARRAY( phy_font->chars, count ) )
goto Fail;
Size = 1 + 1 + 2;
if ( flags & PFR_PHY_2BYTE_CHARCODE )
Size += 1;
if ( flags & PFR_PHY_PROPORTIONAL )
Size += 2;
if ( flags & PFR_PHY_ASCII_CODE )
Size += 1;
if ( flags & PFR_PHY_2BYTE_GPS_SIZE )
Size += 1;
if ( flags & PFR_PHY_3BYTE_GPS_OFFSET )
Size += 1;
PFR_CHECK( count * Size );
for ( n = 0; n < count; n++ )
{
PFR_Char cur = &phy_font->chars[n];
cur->char_code = ( flags & PFR_PHY_2BYTE_CHARCODE )
? PFR_NEXT_USHORT( p )
: PFR_NEXT_BYTE( p );
cur->advance = ( flags & PFR_PHY_PROPORTIONAL )
? PFR_NEXT_SHORT( p )
: (FT_Int) phy_font->standard_advance;
#if 0
cur->ascii = ( flags & PFR_PHY_ASCII_CODE )
? PFR_NEXT_BYTE( p )
: 0;
#else
if ( flags & PFR_PHY_ASCII_CODE )
p += 1;
#endif
cur->gps_size = ( flags & PFR_PHY_2BYTE_GPS_SIZE )
? PFR_NEXT_USHORT( p )
: PFR_NEXT_BYTE( p );
cur->gps_offset = ( flags & PFR_PHY_3BYTE_GPS_OFFSET )
? PFR_NEXT_ULONG( p )
: PFR_NEXT_USHORT( p );
}
}
/* that's it! */
Fail:
FT_FRAME_EXIT();
/* save position of bitmap info */
phy_font->bct_offset = FT_STREAM_POS();
phy_font->cursor = NULL;
Exit:
return error;
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_phy_font_load: invalid physical font table\n" ));
goto Fail;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrload.c | C | apache-2.0 | 25,606 |
/***************************************************************************/
/* */
/* pfrload.h */
/* */
/* FreeType PFR loader (specification). */
/* */
/* Copyright 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 __PFRLOAD_H__
#define __PFRLOAD_H__
#include "pfrobjs.h"
#include FT_INTERNAL_STREAM_H
FT_BEGIN_HEADER
#ifdef PFR_CONFIG_NO_CHECKS
#define PFR_CHECK( x ) do { } while ( 0 )
#else
#define PFR_CHECK( x ) do \
{ \
if ( p + (x) > limit ) \
goto Too_Short; \
} while ( 0 )
#endif
#define PFR_NEXT_BYTE( p ) FT_NEXT_BYTE( p )
#define PFR_NEXT_INT8( p ) FT_NEXT_CHAR( p )
#define PFR_NEXT_SHORT( p ) FT_NEXT_SHORT( p )
#define PFR_NEXT_USHORT( p ) FT_NEXT_USHORT( p )
#define PFR_NEXT_LONG( p ) FT_NEXT_OFF3( p )
#define PFR_NEXT_ULONG( p ) FT_NEXT_UOFF3( p )
/* handling extra items */
typedef FT_Error
(*PFR_ExtraItem_ParseFunc)( FT_Byte* p,
FT_Byte* limit,
FT_Pointer data );
typedef struct PFR_ExtraItemRec_
{
FT_UInt type;
PFR_ExtraItem_ParseFunc parser;
} PFR_ExtraItemRec;
typedef const struct PFR_ExtraItemRec_* PFR_ExtraItem;
FT_LOCAL( FT_Error )
pfr_extra_items_skip( FT_Byte* *pp,
FT_Byte* limit );
FT_LOCAL( FT_Error )
pfr_extra_items_parse( FT_Byte* *pp,
FT_Byte* limit,
PFR_ExtraItem item_list,
FT_Pointer item_data );
/* load a PFR header */
FT_LOCAL( FT_Error )
pfr_header_load( PFR_Header header,
FT_Stream stream );
/* check a PFR header */
FT_LOCAL( FT_Bool )
pfr_header_check( PFR_Header header );
/* return number of logical fonts in this file */
FT_LOCAL( FT_Error )
pfr_log_font_count( FT_Stream stream,
FT_UInt32 log_section_offset,
FT_UInt *acount );
/* load a pfr logical font entry */
FT_LOCAL( FT_Error )
pfr_log_font_load( PFR_LogFont log_font,
FT_Stream stream,
FT_UInt face_index,
FT_UInt32 section_offset,
FT_Bool size_increment );
/* load a physical font entry */
FT_LOCAL( FT_Error )
pfr_phy_font_load( PFR_PhyFont phy_font,
FT_Stream stream,
FT_UInt32 offset,
FT_UInt32 size );
/* finalize a physical font */
FT_LOCAL( void )
pfr_phy_font_done( PFR_PhyFont phy_font,
FT_Memory memory );
/* */
FT_END_HEADER
#endif /* __PFRLOAD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrload.h | C | apache-2.0 | 3,870 |
/***************************************************************************/
/* */
/* pfrobjs.c */
/* */
/* FreeType PFR object methods (body). */
/* */
/* Copyright 2002-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 "pfrobjs.h"
#include "pfrload.h"
#include "pfrgload.h"
#include "pfrcmap.h"
#include "pfrsbit.h"
#include FT_OUTLINE_H
#include FT_INTERNAL_DEBUG_H
#include FT_TRUETYPE_IDS_H
#include "pfrerror.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pfr
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** FACE OBJECT METHODS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
pfr_face_done( FT_Face pfrface ) /* PFR_Face */
{
PFR_Face face = (PFR_Face)pfrface;
FT_Memory memory;
if ( !face )
return;
memory = pfrface->driver->root.memory;
/* we don't want dangling pointers */
pfrface->family_name = NULL;
pfrface->style_name = NULL;
/* finalize the physical font record */
pfr_phy_font_done( &face->phy_font, FT_FACE_MEMORY( face ) );
/* no need to finalize the logical font or the header */
FT_FREE( pfrface->available_sizes );
}
FT_LOCAL_DEF( FT_Error )
pfr_face_init( FT_Stream stream,
FT_Face pfrface,
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
PFR_Face face = (PFR_Face)pfrface;
FT_Error error;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_TRACE2(( "PFR driver\n" ));
/* load the header and check it */
error = pfr_header_load( &face->header, stream );
if ( error )
goto Exit;
if ( !pfr_header_check( &face->header ) )
{
FT_TRACE2(( " not a PFR font\n" ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* check face index */
{
FT_UInt num_faces;
error = pfr_log_font_count( stream,
face->header.log_dir_offset,
&num_faces );
if ( error )
goto Exit;
pfrface->num_faces = num_faces;
}
if ( face_index < 0 )
goto Exit;
if ( face_index >= pfrface->num_faces )
{
FT_ERROR(( "pfr_face_init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* load the face */
error = pfr_log_font_load(
&face->log_font, stream, face_index,
face->header.log_dir_offset,
FT_BOOL( face->header.phy_font_max_size_high != 0 ) );
if ( error )
goto Exit;
/* now load the physical font descriptor */
error = pfr_phy_font_load( &face->phy_font, stream,
face->log_font.phys_offset,
face->log_font.phys_size );
if ( error )
goto Exit;
/* now set up all root face fields */
{
PFR_PhyFont phy_font = &face->phy_font;
pfrface->face_index = face_index;
pfrface->num_glyphs = phy_font->num_chars + 1;
pfrface->face_flags |= FT_FACE_FLAG_SCALABLE;
/* if all characters point to the same gps_offset 0, we */
/* assume that the font only contains bitmaps */
{
FT_UInt nn;
for ( nn = 0; nn < phy_font->num_chars; nn++ )
if ( phy_font->chars[nn].gps_offset != 0 )
break;
if ( nn == phy_font->num_chars )
{
if ( phy_font->num_strikes > 0 )
pfrface->face_flags = 0; /* not scalable */
else
{
FT_ERROR(( "pfr_face_init: font doesn't contain glyphs\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
}
}
if ( (phy_font->flags & PFR_PHY_PROPORTIONAL) == 0 )
pfrface->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
if ( phy_font->flags & PFR_PHY_VERTICAL )
pfrface->face_flags |= FT_FACE_FLAG_VERTICAL;
else
pfrface->face_flags |= FT_FACE_FLAG_HORIZONTAL;
if ( phy_font->num_strikes > 0 )
pfrface->face_flags |= FT_FACE_FLAG_FIXED_SIZES;
if ( phy_font->num_kern_pairs > 0 )
pfrface->face_flags |= FT_FACE_FLAG_KERNING;
/* If no family name was found in the "undocumented" auxiliary
* data, use the font ID instead. This sucks but is better than
* nothing.
*/
pfrface->family_name = phy_font->family_name;
if ( pfrface->family_name == NULL )
pfrface->family_name = phy_font->font_id;
/* note that the style name can be NULL in certain PFR fonts,
* probably meaning "Regular"
*/
pfrface->style_name = phy_font->style_name;
pfrface->num_fixed_sizes = 0;
pfrface->available_sizes = 0;
pfrface->bbox = phy_font->bbox;
pfrface->units_per_EM = (FT_UShort)phy_font->outline_resolution;
pfrface->ascender = (FT_Short) phy_font->bbox.yMax;
pfrface->descender = (FT_Short) phy_font->bbox.yMin;
pfrface->height = (FT_Short)( ( pfrface->units_per_EM * 12 ) / 10 );
if ( pfrface->height < pfrface->ascender - pfrface->descender )
pfrface->height = (FT_Short)(pfrface->ascender - pfrface->descender);
if ( phy_font->num_strikes > 0 )
{
FT_UInt n, count = phy_font->num_strikes;
FT_Bitmap_Size* size;
PFR_Strike strike;
FT_Memory memory = pfrface->stream->memory;
if ( FT_NEW_ARRAY( pfrface->available_sizes, count ) )
goto Exit;
size = pfrface->available_sizes;
strike = phy_font->strikes;
for ( n = 0; n < count; n++, size++, strike++ )
{
size->height = (FT_UShort)strike->y_ppm;
size->width = (FT_UShort)strike->x_ppm;
size->size = strike->y_ppm << 6;
size->x_ppem = strike->x_ppm << 6;
size->y_ppem = strike->y_ppm << 6;
}
pfrface->num_fixed_sizes = count;
}
/* now compute maximum advance width */
if ( ( phy_font->flags & PFR_PHY_PROPORTIONAL ) == 0 )
pfrface->max_advance_width = (FT_Short)phy_font->standard_advance;
else
{
FT_Int max = 0;
FT_UInt count = phy_font->num_chars;
PFR_Char gchar = phy_font->chars;
for ( ; count > 0; count--, gchar++ )
{
if ( max < gchar->advance )
max = gchar->advance;
}
pfrface->max_advance_width = (FT_Short)max;
}
pfrface->max_advance_height = pfrface->height;
pfrface->underline_position = (FT_Short)( -pfrface->units_per_EM / 10 );
pfrface->underline_thickness = (FT_Short)( pfrface->units_per_EM / 30 );
/* create charmap */
{
FT_CharMapRec charmap;
charmap.face = pfrface;
charmap.platform_id = TT_PLATFORM_MICROSOFT;
charmap.encoding_id = TT_MS_ID_UNICODE_CS;
charmap.encoding = FT_ENCODING_UNICODE;
error = FT_CMap_New( &pfr_cmap_class_rec, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if ( pfrface->num_charmaps )
pfrface->charmap = pfrface->charmaps[0];
#endif
}
/* check whether we've loaded any kerning pairs */
if ( phy_font->num_kern_pairs )
pfrface->face_flags |= FT_FACE_FLAG_KERNING;
}
Exit:
return error;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** SLOT OBJECT METHOD *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( FT_Error )
pfr_slot_init( FT_GlyphSlot pfrslot ) /* PFR_Slot */
{
PFR_Slot slot = (PFR_Slot)pfrslot;
FT_GlyphLoader loader = pfrslot->internal->loader;
pfr_glyph_init( &slot->glyph, loader );
return 0;
}
FT_LOCAL_DEF( void )
pfr_slot_done( FT_GlyphSlot pfrslot ) /* PFR_Slot */
{
PFR_Slot slot = (PFR_Slot)pfrslot;
pfr_glyph_done( &slot->glyph );
}
FT_LOCAL_DEF( FT_Error )
pfr_slot_load( FT_GlyphSlot pfrslot, /* PFR_Slot */
FT_Size pfrsize, /* PFR_Size */
FT_UInt gindex,
FT_Int32 load_flags )
{
PFR_Slot slot = (PFR_Slot)pfrslot;
PFR_Size size = (PFR_Size)pfrsize;
FT_Error error;
PFR_Face face = (PFR_Face)pfrslot->face;
PFR_Char gchar;
FT_Outline* outline = &pfrslot->outline;
FT_ULong gps_offset;
FT_TRACE1(( "pfr_slot_load: glyph index %d\n", gindex ));
if ( gindex > 0 )
gindex--;
if ( !face || gindex >= face->phy_font.num_chars )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* try to load an embedded bitmap */
if ( ( load_flags & ( FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP ) ) == 0 )
{
error = pfr_slot_load_bitmap( slot, size, gindex );
if ( error == 0 )
goto Exit;
}
if ( load_flags & FT_LOAD_SBITS_ONLY )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
gchar = face->phy_font.chars + gindex;
pfrslot->format = FT_GLYPH_FORMAT_OUTLINE;
outline->n_points = 0;
outline->n_contours = 0;
gps_offset = face->header.gps_section_offset;
/* load the glyph outline (FT_LOAD_NO_RECURSE isn't supported) */
error = pfr_glyph_load( &slot->glyph, face->root.stream,
gps_offset, gchar->gps_offset, gchar->gps_size );
if ( !error )
{
FT_BBox cbox;
FT_Glyph_Metrics* metrics = &pfrslot->metrics;
FT_Pos advance;
FT_Int em_metrics, em_outline;
FT_Bool scaling;
scaling = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 );
/* copy outline data */
*outline = slot->glyph.loader->base.outline;
outline->flags &= ~FT_OUTLINE_OWNER;
outline->flags |= FT_OUTLINE_REVERSE_FILL;
if ( size && pfrsize->metrics.y_ppem < 24 )
outline->flags |= FT_OUTLINE_HIGH_PRECISION;
/* compute the advance vector */
metrics->horiAdvance = 0;
metrics->vertAdvance = 0;
advance = gchar->advance;
em_metrics = face->phy_font.metrics_resolution;
em_outline = face->phy_font.outline_resolution;
if ( em_metrics != em_outline )
advance = FT_MulDiv( advance, em_outline, em_metrics );
if ( face->phy_font.flags & PFR_PHY_VERTICAL )
metrics->vertAdvance = advance;
else
metrics->horiAdvance = advance;
pfrslot->linearHoriAdvance = metrics->horiAdvance;
pfrslot->linearVertAdvance = metrics->vertAdvance;
/* make-up vertical metrics(?) */
metrics->vertBearingX = 0;
metrics->vertBearingY = 0;
#if 0 /* some fonts seem to be broken here! */
/* Apply the font matrix, if any. */
/* TODO: Test existing fonts with unusual matrix */
/* whether we have to adjust Units per EM. */
{
FT_Matrix font_matrix;
font_matrix.xx = face->log_font.matrix[0] << 8;
font_matrix.yx = face->log_font.matrix[1] << 8;
font_matrix.xy = face->log_font.matrix[2] << 8;
font_matrix.yy = face->log_font.matrix[3] << 8;
FT_Outline_Transform( outline, &font_matrix );
}
#endif
/* scale when needed */
if ( scaling )
{
FT_Int n;
FT_Fixed x_scale = pfrsize->metrics.x_scale;
FT_Fixed y_scale = pfrsize->metrics.y_scale;
FT_Vector* vec = outline->points;
/* scale outline points */
for ( n = 0; n < outline->n_points; n++, vec++ )
{
vec->x = FT_MulFix( vec->x, x_scale );
vec->y = FT_MulFix( vec->y, y_scale );
}
/* scale the advance */
metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale );
metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale );
}
/* compute the rest of the metrics */
FT_Outline_Get_CBox( outline, &cbox );
metrics->width = cbox.xMax - cbox.xMin;
metrics->height = cbox.yMax - cbox.yMin;
metrics->horiBearingX = cbox.xMin;
metrics->horiBearingY = cbox.yMax - metrics->height;
}
Exit:
return error;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** KERNING METHOD *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( FT_Error )
pfr_face_get_kerning( FT_Face pfrface, /* PFR_Face */
FT_UInt glyph1,
FT_UInt glyph2,
FT_Vector* kerning )
{
PFR_Face face = (PFR_Face)pfrface;
FT_Error error = FT_Err_Ok;
PFR_PhyFont phy_font = &face->phy_font;
FT_UInt32 code1, code2, pair;
kerning->x = 0;
kerning->y = 0;
if ( glyph1 > 0 )
glyph1--;
if ( glyph2 > 0 )
glyph2--;
/* convert glyph indices to character codes */
if ( glyph1 > phy_font->num_chars ||
glyph2 > phy_font->num_chars )
goto Exit;
code1 = phy_font->chars[glyph1].char_code;
code2 = phy_font->chars[glyph2].char_code;
pair = PFR_KERN_INDEX( code1, code2 );
/* now search the list of kerning items */
{
PFR_KernItem item = phy_font->kern_items;
FT_Stream stream = pfrface->stream;
for ( ; item; item = item->next )
{
if ( pair >= item->pair1 && pair <= item->pair2 )
goto FoundPair;
}
goto Exit;
FoundPair: /* we found an item, now parse it and find the value if any */
if ( FT_STREAM_SEEK( item->offset ) ||
FT_FRAME_ENTER( item->pair_count * item->pair_size ) )
goto Exit;
{
FT_UInt count = item->pair_count;
FT_UInt size = item->pair_size;
FT_UInt power = (FT_UInt)ft_highpow2( (FT_UInt32)count );
FT_UInt probe = power * size;
FT_UInt extra = count - power;
FT_Byte* base = stream->cursor;
FT_Bool twobytes = FT_BOOL( item->flags & 1 );
FT_Bool twobyte_adj = FT_BOOL( item->flags & 2 );
FT_Byte* p;
FT_UInt32 cpair;
if ( extra > 0 )
{
p = base + extra * size;
if ( twobytes )
cpair = FT_NEXT_ULONG( p );
else
cpair = PFR_NEXT_KPAIR( p );
if ( cpair == pair )
goto Found;
if ( cpair < pair )
{
if ( twobyte_adj )
p += 2;
else
p++;
base = p;
}
}
while ( probe > size )
{
probe >>= 1;
p = base + probe;
if ( twobytes )
cpair = FT_NEXT_ULONG( p );
else
cpair = PFR_NEXT_KPAIR( p );
if ( cpair == pair )
goto Found;
if ( cpair < pair )
base += probe;
}
p = base;
if ( twobytes )
cpair = FT_NEXT_ULONG( p );
else
cpair = PFR_NEXT_KPAIR( p );
if ( cpair == pair )
{
FT_Int value;
Found:
if ( twobyte_adj )
value = FT_PEEK_SHORT( p );
else
value = p[0];
kerning->x = item->base_adj + value;
}
}
FT_FRAME_EXIT();
}
Exit:
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrobjs.c | C | apache-2.0 | 17,871 |
/***************************************************************************/
/* */
/* pfrobjs.h */
/* */
/* FreeType PFR object methods (specification). */
/* */
/* 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. */
/* */
/***************************************************************************/
#ifndef __PFROBJS_H__
#define __PFROBJS_H__
#include "pfrtypes.h"
FT_BEGIN_HEADER
typedef struct PFR_FaceRec_* PFR_Face;
typedef struct PFR_SizeRec_* PFR_Size;
typedef struct PFR_SlotRec_* PFR_Slot;
typedef struct PFR_FaceRec_
{
FT_FaceRec root;
PFR_HeaderRec header;
PFR_LogFontRec log_font;
PFR_PhyFontRec phy_font;
} PFR_FaceRec;
typedef struct PFR_SizeRec_
{
FT_SizeRec root;
} PFR_SizeRec;
typedef struct PFR_SlotRec_
{
FT_GlyphSlotRec root;
PFR_GlyphRec glyph;
} PFR_SlotRec;
FT_LOCAL( FT_Error )
pfr_face_init( FT_Stream stream,
FT_Face face, /* PFR_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params );
FT_LOCAL( void )
pfr_face_done( FT_Face face ); /* PFR_Face */
FT_LOCAL( FT_Error )
pfr_face_get_kerning( FT_Face face, /* PFR_Face */
FT_UInt glyph1,
FT_UInt glyph2,
FT_Vector* kerning );
FT_LOCAL( FT_Error )
pfr_slot_init( FT_GlyphSlot slot ); /* PFR_Slot */
FT_LOCAL( void )
pfr_slot_done( FT_GlyphSlot slot ); /* PFR_Slot */
FT_LOCAL( FT_Error )
pfr_slot_load( FT_GlyphSlot slot, /* PFR_Slot */
FT_Size size, /* PFR_Size */
FT_UInt gindex,
FT_Int32 load_flags );
FT_END_HEADER
#endif /* __PFROBJS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrobjs.h | C | apache-2.0 | 2,846 |
/***************************************************************************/
/* */
/* pfrsbit.c */
/* */
/* FreeType PFR bitmap loader (body). */
/* */
/* Copyright 2002, 2003, 2006, 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 "pfrsbit.h"
#include "pfrload.h"
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include "pfrerror.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pfr
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR BIT WRITER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct PFR_BitWriter_
{
FT_Byte* line; /* current line start */
FT_Int pitch; /* line size in bytes */
FT_Int width; /* width in pixels/bits */
FT_Int rows; /* number of remaining rows to scan */
FT_Int total; /* total number of bits to draw */
} PFR_BitWriterRec, *PFR_BitWriter;
static void
pfr_bitwriter_init( PFR_BitWriter writer,
FT_Bitmap* target,
FT_Bool decreasing )
{
writer->line = target->buffer;
writer->pitch = target->pitch;
writer->width = target->width;
writer->rows = target->rows;
writer->total = writer->width * writer->rows;
if ( !decreasing )
{
writer->line += writer->pitch * ( target->rows-1 );
writer->pitch = -writer->pitch;
}
}
static void
pfr_bitwriter_decode_bytes( PFR_BitWriter writer,
FT_Byte* p,
FT_Byte* limit )
{
FT_Int n, reload;
FT_Int left = writer->width;
FT_Byte* cur = writer->line;
FT_UInt mask = 0x80;
FT_UInt val = 0;
FT_UInt c = 0;
n = (FT_Int)( limit - p ) * 8;
if ( n > writer->total )
n = writer->total;
reload = n & 7;
for ( ; n > 0; n-- )
{
if ( ( n & 7 ) == reload )
val = *p++;
if ( val & 0x80 )
c |= mask;
val <<= 1;
mask >>= 1;
if ( --left <= 0 )
{
cur[0] = (FT_Byte)c;
left = writer->width;
mask = 0x80;
writer->line += writer->pitch;
cur = writer->line;
c = 0;
}
else if ( mask == 0 )
{
cur[0] = (FT_Byte)c;
mask = 0x80;
c = 0;
cur ++;
}
}
if ( mask != 0x80 )
cur[0] = (FT_Byte)c;
}
static void
pfr_bitwriter_decode_rle1( PFR_BitWriter writer,
FT_Byte* p,
FT_Byte* limit )
{
FT_Int n, phase, count, counts[2], reload;
FT_Int left = writer->width;
FT_Byte* cur = writer->line;
FT_UInt mask = 0x80;
FT_UInt c = 0;
n = writer->total;
phase = 1;
counts[0] = 0;
counts[1] = 0;
count = 0;
reload = 1;
for ( ; n > 0; n-- )
{
if ( reload )
{
do
{
if ( phase )
{
FT_Int v;
if ( p >= limit )
break;
v = *p++;
counts[0] = v >> 4;
counts[1] = v & 15;
phase = 0;
count = counts[0];
}
else
{
phase = 1;
count = counts[1];
}
} while ( count == 0 );
}
if ( phase )
c |= mask;
mask >>= 1;
if ( --left <= 0 )
{
cur[0] = (FT_Byte) c;
left = writer->width;
mask = 0x80;
writer->line += writer->pitch;
cur = writer->line;
c = 0;
}
else if ( mask == 0 )
{
cur[0] = (FT_Byte)c;
mask = 0x80;
c = 0;
cur ++;
}
reload = ( --count <= 0 );
}
if ( mask != 0x80 )
cur[0] = (FT_Byte) c;
}
static void
pfr_bitwriter_decode_rle2( PFR_BitWriter writer,
FT_Byte* p,
FT_Byte* limit )
{
FT_Int n, phase, count, reload;
FT_Int left = writer->width;
FT_Byte* cur = writer->line;
FT_UInt mask = 0x80;
FT_UInt c = 0;
n = writer->total;
phase = 1;
count = 0;
reload = 1;
for ( ; n > 0; n-- )
{
if ( reload )
{
do
{
if ( p >= limit )
break;
count = *p++;
phase = phase ^ 1;
} while ( count == 0 );
}
if ( phase )
c |= mask;
mask >>= 1;
if ( --left <= 0 )
{
cur[0] = (FT_Byte) c;
c = 0;
mask = 0x80;
left = writer->width;
writer->line += writer->pitch;
cur = writer->line;
}
else if ( mask == 0 )
{
cur[0] = (FT_Byte)c;
c = 0;
mask = 0x80;
cur ++;
}
reload = ( --count <= 0 );
}
if ( mask != 0x80 )
cur[0] = (FT_Byte) c;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** BITMAP DATA DECODING *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
pfr_lookup_bitmap_data( FT_Byte* base,
FT_Byte* limit,
FT_UInt count,
FT_UInt flags,
FT_UInt char_code,
FT_ULong* found_offset,
FT_ULong* found_size )
{
FT_UInt left, right, char_len;
FT_Bool two = FT_BOOL( flags & 1 );
FT_Byte* buff;
char_len = 4;
if ( two ) char_len += 1;
if ( flags & 2 ) char_len += 1;
if ( flags & 4 ) char_len += 1;
left = 0;
right = count;
while ( left < right )
{
FT_UInt middle, code;
middle = ( left + right ) >> 1;
buff = base + middle * char_len;
/* check that we are not outside of the table -- */
/* this is possible with broken fonts... */
if ( buff + char_len > limit )
goto Fail;
if ( two )
code = PFR_NEXT_USHORT( buff );
else
code = PFR_NEXT_BYTE( buff );
if ( code == char_code )
goto Found_It;
if ( code < char_code )
left = middle;
else
right = middle;
}
Fail:
/* Not found */
*found_size = 0;
*found_offset = 0;
return;
Found_It:
if ( flags & 2 )
*found_size = PFR_NEXT_USHORT( buff );
else
*found_size = PFR_NEXT_BYTE( buff );
if ( flags & 4 )
*found_offset = PFR_NEXT_ULONG( buff );
else
*found_offset = PFR_NEXT_USHORT( buff );
}
/* load bitmap metrics. "*padvance" must be set to the default value */
/* before calling this function... */
/* */
static FT_Error
pfr_load_bitmap_metrics( FT_Byte** pdata,
FT_Byte* limit,
FT_Long scaled_advance,
FT_Long *axpos,
FT_Long *aypos,
FT_UInt *axsize,
FT_UInt *aysize,
FT_Long *aadvance,
FT_UInt *aformat )
{
FT_Error error = FT_Err_Ok;
FT_Byte flags;
FT_Char b;
FT_Byte* p = *pdata;
FT_Long xpos, ypos, advance;
FT_UInt xsize, ysize;
PFR_CHECK( 1 );
flags = PFR_NEXT_BYTE( p );
xpos = 0;
ypos = 0;
xsize = 0;
ysize = 0;
advance = 0;
switch ( flags & 3 )
{
case 0:
PFR_CHECK( 1 );
b = PFR_NEXT_INT8( p );
xpos = b >> 4;
ypos = ( (FT_Char)( b << 4 ) ) >> 4;
break;
case 1:
PFR_CHECK( 2 );
xpos = PFR_NEXT_INT8( p );
ypos = PFR_NEXT_INT8( p );
break;
case 2:
PFR_CHECK( 4 );
xpos = PFR_NEXT_SHORT( p );
ypos = PFR_NEXT_SHORT( p );
break;
case 3:
PFR_CHECK( 6 );
xpos = PFR_NEXT_LONG( p );
ypos = PFR_NEXT_LONG( p );
break;
default:
;
}
flags >>= 2;
switch ( flags & 3 )
{
case 0:
/* blank image */
xsize = 0;
ysize = 0;
break;
case 1:
PFR_CHECK( 1 );
b = PFR_NEXT_BYTE( p );
xsize = ( b >> 4 ) & 0xF;
ysize = b & 0xF;
break;
case 2:
PFR_CHECK( 2 );
xsize = PFR_NEXT_BYTE( p );
ysize = PFR_NEXT_BYTE( p );
break;
case 3:
PFR_CHECK( 4 );
xsize = PFR_NEXT_USHORT( p );
ysize = PFR_NEXT_USHORT( p );
break;
default:
;
}
flags >>= 2;
switch ( flags & 3 )
{
case 0:
advance = scaled_advance;
break;
case 1:
PFR_CHECK( 1 );
advance = PFR_NEXT_INT8( p ) << 8;
break;
case 2:
PFR_CHECK( 2 );
advance = PFR_NEXT_SHORT( p );
break;
case 3:
PFR_CHECK( 3 );
advance = PFR_NEXT_LONG( p );
break;
default:
;
}
*axpos = xpos;
*aypos = ypos;
*axsize = xsize;
*aysize = ysize;
*aadvance = advance;
*aformat = flags >> 2;
*pdata = p;
Exit:
return error;
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_load_bitmap_metrics: invalid glyph data\n" ));
goto Exit;
}
static FT_Error
pfr_load_bitmap_bits( FT_Byte* p,
FT_Byte* limit,
FT_UInt format,
FT_Bool decreasing,
FT_Bitmap* target )
{
FT_Error error = FT_Err_Ok;
PFR_BitWriterRec writer;
if ( target->rows > 0 && target->width > 0 )
{
pfr_bitwriter_init( &writer, target, decreasing );
switch ( format )
{
case 0: /* packed bits */
pfr_bitwriter_decode_bytes( &writer, p, limit );
break;
case 1: /* RLE1 */
pfr_bitwriter_decode_rle1( &writer, p, limit );
break;
case 2: /* RLE2 */
pfr_bitwriter_decode_rle2( &writer, p, limit );
break;
default:
FT_ERROR(( "pfr_read_bitmap_data: invalid image type\n" ));
error = FT_THROW( Invalid_File_Format );
}
}
return error;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** BITMAP LOADING *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( FT_Error )
pfr_slot_load_bitmap( PFR_Slot glyph,
PFR_Size size,
FT_UInt glyph_index )
{
FT_Error error;
PFR_Face face = (PFR_Face) glyph->root.face;
FT_Stream stream = face->root.stream;
PFR_PhyFont phys = &face->phy_font;
FT_ULong gps_offset;
FT_ULong gps_size;
PFR_Char character;
PFR_Strike strike;
character = &phys->chars[glyph_index];
/* Look-up a bitmap strike corresponding to the current */
/* character dimensions */
{
FT_UInt n;
strike = phys->strikes;
for ( n = 0; n < phys->num_strikes; n++ )
{
if ( strike->x_ppm == (FT_UInt)size->root.metrics.x_ppem &&
strike->y_ppm == (FT_UInt)size->root.metrics.y_ppem )
{
goto Found_Strike;
}
strike++;
}
/* couldn't find it */
return FT_THROW( Invalid_Argument );
}
Found_Strike:
/* Now lookup the glyph's position within the file */
{
FT_UInt char_len;
char_len = 4;
if ( strike->flags & 1 ) char_len += 1;
if ( strike->flags & 2 ) char_len += 1;
if ( strike->flags & 4 ) char_len += 1;
/* Access data directly in the frame to speed lookups */
if ( FT_STREAM_SEEK( phys->bct_offset + strike->bct_offset ) ||
FT_FRAME_ENTER( char_len * strike->num_bitmaps ) )
goto Exit;
pfr_lookup_bitmap_data( stream->cursor,
stream->limit,
strike->num_bitmaps,
strike->flags,
character->char_code,
&gps_offset,
&gps_size );
FT_FRAME_EXIT();
if ( gps_size == 0 )
{
/* Could not find a bitmap program string for this glyph */
error = FT_THROW( Invalid_Argument );
goto Exit;
}
}
/* get the bitmap metrics */
{
FT_Long xpos = 0, ypos = 0, advance = 0;
FT_UInt xsize = 0, ysize = 0, format = 0;
FT_Byte* p;
/* compute linear advance */
advance = character->advance;
if ( phys->metrics_resolution != phys->outline_resolution )
advance = FT_MulDiv( advance,
phys->outline_resolution,
phys->metrics_resolution );
glyph->root.linearHoriAdvance = advance;
/* compute default advance, i.e., scaled advance. This can be */
/* overridden in the bitmap header of certain glyphs. */
advance = FT_MulDiv( (FT_Fixed)size->root.metrics.x_ppem << 8,
character->advance,
phys->metrics_resolution );
if ( FT_STREAM_SEEK( face->header.gps_section_offset + gps_offset ) ||
FT_FRAME_ENTER( gps_size ) )
goto Exit;
p = stream->cursor;
error = pfr_load_bitmap_metrics( &p, stream->limit,
advance,
&xpos, &ypos,
&xsize, &ysize,
&advance, &format );
/*
* XXX: on 16bit system, we return an error for huge bitmap
* which causes a size truncation, because truncated
* size properties makes bitmap glyph broken.
*/
if ( xpos > FT_INT_MAX || ( ypos + ysize ) > FT_INT_MAX )
{
FT_TRACE1(( "pfr_slot_load_bitmap:" ));
FT_TRACE1(( "huge bitmap glyph %dx%d over FT_GlyphSlot\n",
xpos, ypos ));
error = FT_THROW( Invalid_Pixel_Size );
}
if ( !error )
{
glyph->root.format = FT_GLYPH_FORMAT_BITMAP;
/* Set up glyph bitmap and metrics */
/* XXX: needs casts to fit FT_Bitmap.{width|rows|pitch} */
glyph->root.bitmap.width = (FT_Int)xsize;
glyph->root.bitmap.rows = (FT_Int)ysize;
glyph->root.bitmap.pitch = (FT_Int)( xsize + 7 ) >> 3;
glyph->root.bitmap.pixel_mode = FT_PIXEL_MODE_MONO;
/* XXX: needs casts to fit FT_Glyph_Metrics.{width|height} */
glyph->root.metrics.width = (FT_Pos)xsize << 6;
glyph->root.metrics.height = (FT_Pos)ysize << 6;
glyph->root.metrics.horiBearingX = xpos << 6;
glyph->root.metrics.horiBearingY = ypos << 6;
glyph->root.metrics.horiAdvance = FT_PIX_ROUND( ( advance >> 2 ) );
glyph->root.metrics.vertBearingX = - glyph->root.metrics.width >> 1;
glyph->root.metrics.vertBearingY = 0;
glyph->root.metrics.vertAdvance = size->root.metrics.height;
/* XXX: needs casts fit FT_GlyphSlotRec.bitmap_{left|top} */
glyph->root.bitmap_left = (FT_Int)xpos;
glyph->root.bitmap_top = (FT_Int)(ypos + ysize);
/* Allocate and read bitmap data */
{
FT_ULong len = glyph->root.bitmap.pitch * ysize;
error = ft_glyphslot_alloc_bitmap( &glyph->root, len );
if ( !error )
{
error = pfr_load_bitmap_bits(
p,
stream->limit,
format,
FT_BOOL(face->header.color_flags & 2),
&glyph->root.bitmap );
}
}
}
FT_FRAME_EXIT();
}
Exit:
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrsbit.c | C | apache-2.0 | 18,430 |
/***************************************************************************/
/* */
/* pfrsbit.h */
/* */
/* FreeType PFR bitmap loader (specification). */
/* */
/* Copyright 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 __PFRSBIT_H__
#define __PFRSBIT_H__
#include "pfrobjs.h"
FT_BEGIN_HEADER
FT_LOCAL( FT_Error )
pfr_slot_load_bitmap( PFR_Slot glyph,
PFR_Size size,
FT_UInt glyph_index );
FT_END_HEADER
#endif /* __PFR_SBIT_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrsbit.h | C | apache-2.0 | 1,543 |
/***************************************************************************/
/* */
/* pfrtypes.h */
/* */
/* FreeType PFR data structures (specification only). */
/* */
/* Copyright 2002, 2003, 2005, 2007 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 __PFRTYPES_H__
#define __PFRTYPES_H__
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
FT_BEGIN_HEADER
/************************************************************************/
/* the PFR Header structure */
typedef struct PFR_HeaderRec_
{
FT_UInt32 signature;
FT_UInt version;
FT_UInt signature2;
FT_UInt header_size;
FT_UInt log_dir_size;
FT_UInt log_dir_offset;
FT_UInt log_font_max_size;
FT_UInt32 log_font_section_size;
FT_UInt32 log_font_section_offset;
FT_UInt32 phy_font_max_size;
FT_UInt32 phy_font_section_size;
FT_UInt32 phy_font_section_offset;
FT_UInt gps_max_size;
FT_UInt32 gps_section_size;
FT_UInt32 gps_section_offset;
FT_UInt max_blue_values;
FT_UInt max_x_orus;
FT_UInt max_y_orus;
FT_UInt phy_font_max_size_high;
FT_UInt color_flags;
FT_UInt32 bct_max_size;
FT_UInt32 bct_set_max_size;
FT_UInt32 phy_bct_set_max_size;
FT_UInt num_phy_fonts;
FT_UInt max_vert_stem_snap;
FT_UInt max_horz_stem_snap;
FT_UInt max_chars;
} PFR_HeaderRec, *PFR_Header;
/* used in `color_flags' field of the PFR_Header */
typedef enum PFR_HeaderFlags_
{
PFR_FLAG_BLACK_PIXEL = 1,
PFR_FLAG_INVERT_BITMAP = 2
} PFR_HeaderFlags;
/************************************************************************/
typedef struct PFR_LogFontRec_
{
FT_UInt32 size;
FT_UInt32 offset;
FT_Int32 matrix[4];
FT_UInt stroke_flags;
FT_Int stroke_thickness;
FT_Int bold_thickness;
FT_Int32 miter_limit;
FT_UInt32 phys_size;
FT_UInt32 phys_offset;
} PFR_LogFontRec, *PFR_LogFont;
typedef enum PFR_LogFlags_
{
PFR_LOG_EXTRA_ITEMS = 0x40,
PFR_LOG_2BYTE_BOLD = 0x20,
PFR_LOG_BOLD = 0x10,
PFR_LOG_2BYTE_STROKE = 8,
PFR_LOG_STROKE = 4,
PFR_LINE_JOIN_MASK = 3
} PFR_LogFlags;
typedef enum PFR_LineJoinFlags_
{
PFR_LINE_JOIN_MITER = 0,
PFR_LINE_JOIN_ROUND = 1,
PFR_LINE_JOIN_BEVEL = 2
} PFR_LineJoinFlags;
/************************************************************************/
typedef enum PFR_BitmapFlags_
{
PFR_BITMAP_3BYTE_OFFSET = 4,
PFR_BITMAP_2BYTE_SIZE = 2,
PFR_BITMAP_2BYTE_CHARCODE = 1
} PFR_BitmapFlags;
typedef struct PFR_BitmapCharRec_
{
FT_UInt char_code;
FT_UInt gps_size;
FT_UInt32 gps_offset;
} PFR_BitmapCharRec, *PFR_BitmapChar;
typedef enum PFR_StrikeFlags_
{
PFR_STRIKE_2BYTE_COUNT = 0x10,
PFR_STRIKE_3BYTE_OFFSET = 0x08,
PFR_STRIKE_3BYTE_SIZE = 0x04,
PFR_STRIKE_2BYTE_YPPM = 0x02,
PFR_STRIKE_2BYTE_XPPM = 0x01
} PFR_StrikeFlags;
typedef struct PFR_StrikeRec_
{
FT_UInt x_ppm;
FT_UInt y_ppm;
FT_UInt flags;
FT_UInt32 gps_size;
FT_UInt32 gps_offset;
FT_UInt32 bct_size;
FT_UInt32 bct_offset;
/* optional */
FT_UInt num_bitmaps;
PFR_BitmapChar bitmaps;
} PFR_StrikeRec, *PFR_Strike;
/************************************************************************/
typedef struct PFR_CharRec_
{
FT_UInt char_code;
FT_Int advance;
FT_UInt gps_size;
FT_UInt32 gps_offset;
} PFR_CharRec, *PFR_Char;
/************************************************************************/
typedef struct PFR_DimensionRec_
{
FT_UInt standard;
FT_UInt num_stem_snaps;
FT_Int* stem_snaps;
} PFR_DimensionRec, *PFR_Dimension;
/************************************************************************/
typedef struct PFR_KernItemRec_* PFR_KernItem;
typedef struct PFR_KernItemRec_
{
PFR_KernItem next;
FT_Byte pair_count;
FT_Byte flags;
FT_Short base_adj;
FT_UInt pair_size;
FT_Offset offset;
FT_UInt32 pair1;
FT_UInt32 pair2;
} PFR_KernItemRec;
#define PFR_KERN_INDEX( g1, g2 ) \
( ( (FT_UInt32)(g1) << 16 ) | (FT_UInt16)(g2) )
#define PFR_KERN_PAIR_INDEX( pair ) \
PFR_KERN_INDEX( (pair)->glyph1, (pair)->glyph2 )
#define PFR_NEXT_KPAIR( p ) ( p += 2, \
( (FT_UInt32)p[-2] << 16 ) | p[-1] )
/************************************************************************/
typedef struct PFR_PhyFontRec_
{
FT_Memory memory;
FT_UInt32 offset;
FT_UInt font_ref_number;
FT_UInt outline_resolution;
FT_UInt metrics_resolution;
FT_BBox bbox;
FT_UInt flags;
FT_UInt standard_advance;
FT_Int ascent; /* optional, bbox.yMax if not present */
FT_Int descent; /* optional, bbox.yMin if not present */
FT_Int leading; /* optional, 0 if not present */
PFR_DimensionRec horizontal;
PFR_DimensionRec vertical;
FT_String* font_id;
FT_String* family_name;
FT_String* style_name;
FT_UInt num_strikes;
FT_UInt max_strikes;
PFR_StrikeRec* strikes;
FT_UInt num_blue_values;
FT_Int *blue_values;
FT_UInt blue_fuzz;
FT_UInt blue_scale;
FT_UInt num_chars;
FT_Offset chars_offset;
PFR_Char chars;
FT_UInt num_kern_pairs;
PFR_KernItem kern_items;
PFR_KernItem* kern_items_tail;
/* not part of the spec, but used during load */
FT_Long bct_offset;
FT_Byte* cursor;
} PFR_PhyFontRec, *PFR_PhyFont;
typedef enum PFR_PhyFlags_
{
PFR_PHY_EXTRA_ITEMS = 0x80,
PFR_PHY_3BYTE_GPS_OFFSET = 0x20,
PFR_PHY_2BYTE_GPS_SIZE = 0x10,
PFR_PHY_ASCII_CODE = 0x08,
PFR_PHY_PROPORTIONAL = 0x04,
PFR_PHY_2BYTE_CHARCODE = 0x02,
PFR_PHY_VERTICAL = 0x01
} PFR_PhyFlags;
typedef enum PFR_KernFlags_
{
PFR_KERN_2BYTE_CHAR = 0x01,
PFR_KERN_2BYTE_ADJ = 0x02
} PFR_KernFlags;
/************************************************************************/
typedef enum PFR_GlyphFlags_
{
PFR_GLYPH_IS_COMPOUND = 0x80,
PFR_GLYPH_EXTRA_ITEMS = 0x08,
PFR_GLYPH_1BYTE_XYCOUNT = 0x04,
PFR_GLYPH_XCOUNT = 0x02,
PFR_GLYPH_YCOUNT = 0x01
} PFR_GlyphFlags;
/* controlled coordinate */
typedef struct PFR_CoordRec_
{
FT_UInt org;
FT_UInt cur;
} PFR_CoordRec, *PFR_Coord;
typedef struct PFR_SubGlyphRec_
{
FT_Fixed x_scale;
FT_Fixed y_scale;
FT_Int x_delta;
FT_Int y_delta;
FT_UInt32 gps_offset;
FT_UInt gps_size;
} PFR_SubGlyphRec, *PFR_SubGlyph;
typedef enum PFR_SubgGlyphFlags_
{
PFR_SUBGLYPH_3BYTE_OFFSET = 0x80,
PFR_SUBGLYPH_2BYTE_SIZE = 0x40,
PFR_SUBGLYPH_YSCALE = 0x20,
PFR_SUBGLYPH_XSCALE = 0x10
} PFR_SubGlyphFlags;
typedef struct PFR_GlyphRec_
{
FT_Byte format;
#if 0
FT_UInt num_x_control;
FT_UInt num_y_control;
#endif
FT_UInt max_xy_control;
FT_Pos* x_control;
FT_Pos* y_control;
FT_UInt num_subs;
FT_UInt max_subs;
PFR_SubGlyphRec* subs;
FT_GlyphLoader loader;
FT_Bool path_begun;
} PFR_GlyphRec, *PFR_Glyph;
FT_END_HEADER
#endif /* __PFRTYPES_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pfr/pfrtypes.h | C | apache-2.0 | 8,925 |
#
# FreeType 2 PFR driver configuration rules
#
# Copyright 2002, 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.
# pfr driver directory
#
PFR_DIR := $(SRC_DIR)/pfr
# compilation flags for the driver
#
PFR_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(PFR_DIR))
# pfr driver sources (i.e., C files)
#
PFR_DRV_SRC := $(PFR_DIR)/pfrload.c \
$(PFR_DIR)/pfrgload.c \
$(PFR_DIR)/pfrcmap.c \
$(PFR_DIR)/pfrdrivr.c \
$(PFR_DIR)/pfrsbit.c \
$(PFR_DIR)/pfrobjs.c
# pfr driver headers
#
PFR_DRV_H := $(PFR_DRV_SRC:%.c=%.h) \
$(PFR_DIR)/pfrerror.h \
$(PFR_DIR)/pfrtypes.h
# Pfr driver object(s)
#
# PFR_DRV_OBJ_M is used during `multi' builds
# PFR_DRV_OBJ_S is used during `single' builds
#
PFR_DRV_OBJ_M := $(PFR_DRV_SRC:$(PFR_DIR)/%.c=$(OBJ_DIR)/%.$O)
PFR_DRV_OBJ_S := $(OBJ_DIR)/pfr.$O
# pfr driver source file for single build
#
PFR_DRV_SRC_S := $(PFR_DIR)/pfr.c
# pfr driver - single object
#
$(PFR_DRV_OBJ_S): $(PFR_DRV_SRC_S) $(PFR_DRV_SRC) $(FREETYPE_H) $(PFR_DRV_H)
$(PFR_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(PFR_DRV_SRC_S))
# pfr driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(PFR_DIR)/%.c $(FREETYPE_H) $(PFR_DRV_H)
$(PFR_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(PFR_DRV_OBJ_S)
DRV_OBJS_M += $(PFR_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/pfr/rules.mk | Makefile | apache-2.0 | 1,728 |
/***************************************************************************/
/* */
/* afmparse.c */
/* */
/* AFM parser (body). */
/* */
/* Copyright 2006-2010, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include "afmparse.h"
#include "psconv.h"
#include "psauxerr.h"
/***************************************************************************/
/* */
/* AFM_Stream */
/* */
/* The use of AFM_Stream is largely inspired by parseAFM.[ch] from t1lib. */
/* */
/* */
enum
{
AFM_STREAM_STATUS_NORMAL,
AFM_STREAM_STATUS_EOC,
AFM_STREAM_STATUS_EOL,
AFM_STREAM_STATUS_EOF
};
typedef struct AFM_StreamRec_
{
FT_Byte* cursor;
FT_Byte* base;
FT_Byte* limit;
FT_Int status;
} AFM_StreamRec;
#ifndef EOF
#define EOF -1
#endif
/* this works because empty lines are ignored */
#define AFM_IS_NEWLINE( ch ) ( (ch) == '\r' || (ch) == '\n' )
#define AFM_IS_EOF( ch ) ( (ch) == EOF || (ch) == '\x1a' )
#define AFM_IS_SPACE( ch ) ( (ch) == ' ' || (ch) == '\t' )
/* column separator; there is no `column' in the spec actually */
#define AFM_IS_SEP( ch ) ( (ch) == ';' )
#define AFM_GETC() \
( ( (stream)->cursor < (stream)->limit ) ? *(stream)->cursor++ \
: EOF )
#define AFM_STREAM_KEY_BEGIN( stream ) \
(char*)( (stream)->cursor - 1 )
#define AFM_STREAM_KEY_LEN( stream, key ) \
( (char*)(stream)->cursor - key - 1 )
#define AFM_STATUS_EOC( stream ) \
( (stream)->status >= AFM_STREAM_STATUS_EOC )
#define AFM_STATUS_EOL( stream ) \
( (stream)->status >= AFM_STREAM_STATUS_EOL )
#define AFM_STATUS_EOF( stream ) \
( (stream)->status >= AFM_STREAM_STATUS_EOF )
static int
afm_stream_skip_spaces( AFM_Stream stream )
{
int ch = 0; /* make stupid compiler happy */
if ( AFM_STATUS_EOC( stream ) )
return ';';
while ( 1 )
{
ch = AFM_GETC();
if ( !AFM_IS_SPACE( ch ) )
break;
}
if ( AFM_IS_NEWLINE( ch ) )
stream->status = AFM_STREAM_STATUS_EOL;
else if ( AFM_IS_SEP( ch ) )
stream->status = AFM_STREAM_STATUS_EOC;
else if ( AFM_IS_EOF( ch ) )
stream->status = AFM_STREAM_STATUS_EOF;
return ch;
}
/* read a key or value in current column */
static char*
afm_stream_read_one( AFM_Stream stream )
{
char* str;
afm_stream_skip_spaces( stream );
if ( AFM_STATUS_EOC( stream ) )
return NULL;
str = AFM_STREAM_KEY_BEGIN( stream );
while ( 1 )
{
int ch = AFM_GETC();
if ( AFM_IS_SPACE( ch ) )
break;
else if ( AFM_IS_NEWLINE( ch ) )
{
stream->status = AFM_STREAM_STATUS_EOL;
break;
}
else if ( AFM_IS_SEP( ch ) )
{
stream->status = AFM_STREAM_STATUS_EOC;
break;
}
else if ( AFM_IS_EOF( ch ) )
{
stream->status = AFM_STREAM_STATUS_EOF;
break;
}
}
return str;
}
/* read a string (i.e., read to EOL) */
static char*
afm_stream_read_string( AFM_Stream stream )
{
char* str;
afm_stream_skip_spaces( stream );
if ( AFM_STATUS_EOL( stream ) )
return NULL;
str = AFM_STREAM_KEY_BEGIN( stream );
/* scan to eol */
while ( 1 )
{
int ch = AFM_GETC();
if ( AFM_IS_NEWLINE( ch ) )
{
stream->status = AFM_STREAM_STATUS_EOL;
break;
}
else if ( AFM_IS_EOF( ch ) )
{
stream->status = AFM_STREAM_STATUS_EOF;
break;
}
}
return str;
}
/*************************************************************************/
/* */
/* AFM_Parser */
/* */
/* */
/* all keys defined in Ch. 7-10 of 5004.AFM_Spec.pdf */
typedef enum AFM_Token_
{
AFM_TOKEN_ASCENDER,
AFM_TOKEN_AXISLABEL,
AFM_TOKEN_AXISTYPE,
AFM_TOKEN_B,
AFM_TOKEN_BLENDAXISTYPES,
AFM_TOKEN_BLENDDESIGNMAP,
AFM_TOKEN_BLENDDESIGNPOSITIONS,
AFM_TOKEN_C,
AFM_TOKEN_CC,
AFM_TOKEN_CH,
AFM_TOKEN_CAPHEIGHT,
AFM_TOKEN_CHARWIDTH,
AFM_TOKEN_CHARACTERSET,
AFM_TOKEN_CHARACTERS,
AFM_TOKEN_DESCENDER,
AFM_TOKEN_ENCODINGSCHEME,
AFM_TOKEN_ENDAXIS,
AFM_TOKEN_ENDCHARMETRICS,
AFM_TOKEN_ENDCOMPOSITES,
AFM_TOKEN_ENDDIRECTION,
AFM_TOKEN_ENDFONTMETRICS,
AFM_TOKEN_ENDKERNDATA,
AFM_TOKEN_ENDKERNPAIRS,
AFM_TOKEN_ENDTRACKKERN,
AFM_TOKEN_ESCCHAR,
AFM_TOKEN_FAMILYNAME,
AFM_TOKEN_FONTBBOX,
AFM_TOKEN_FONTNAME,
AFM_TOKEN_FULLNAME,
AFM_TOKEN_ISBASEFONT,
AFM_TOKEN_ISCIDFONT,
AFM_TOKEN_ISFIXEDPITCH,
AFM_TOKEN_ISFIXEDV,
AFM_TOKEN_ITALICANGLE,
AFM_TOKEN_KP,
AFM_TOKEN_KPH,
AFM_TOKEN_KPX,
AFM_TOKEN_KPY,
AFM_TOKEN_L,
AFM_TOKEN_MAPPINGSCHEME,
AFM_TOKEN_METRICSSETS,
AFM_TOKEN_N,
AFM_TOKEN_NOTICE,
AFM_TOKEN_PCC,
AFM_TOKEN_STARTAXIS,
AFM_TOKEN_STARTCHARMETRICS,
AFM_TOKEN_STARTCOMPOSITES,
AFM_TOKEN_STARTDIRECTION,
AFM_TOKEN_STARTFONTMETRICS,
AFM_TOKEN_STARTKERNDATA,
AFM_TOKEN_STARTKERNPAIRS,
AFM_TOKEN_STARTKERNPAIRS0,
AFM_TOKEN_STARTKERNPAIRS1,
AFM_TOKEN_STARTTRACKKERN,
AFM_TOKEN_STDHW,
AFM_TOKEN_STDVW,
AFM_TOKEN_TRACKKERN,
AFM_TOKEN_UNDERLINEPOSITION,
AFM_TOKEN_UNDERLINETHICKNESS,
AFM_TOKEN_VV,
AFM_TOKEN_VVECTOR,
AFM_TOKEN_VERSION,
AFM_TOKEN_W,
AFM_TOKEN_W0,
AFM_TOKEN_W0X,
AFM_TOKEN_W0Y,
AFM_TOKEN_W1,
AFM_TOKEN_W1X,
AFM_TOKEN_W1Y,
AFM_TOKEN_WX,
AFM_TOKEN_WY,
AFM_TOKEN_WEIGHT,
AFM_TOKEN_WEIGHTVECTOR,
AFM_TOKEN_XHEIGHT,
N_AFM_TOKENS,
AFM_TOKEN_UNKNOWN
} AFM_Token;
static const char* const afm_key_table[N_AFM_TOKENS] =
{
"Ascender",
"AxisLabel",
"AxisType",
"B",
"BlendAxisTypes",
"BlendDesignMap",
"BlendDesignPositions",
"C",
"CC",
"CH",
"CapHeight",
"CharWidth",
"CharacterSet",
"Characters",
"Descender",
"EncodingScheme",
"EndAxis",
"EndCharMetrics",
"EndComposites",
"EndDirection",
"EndFontMetrics",
"EndKernData",
"EndKernPairs",
"EndTrackKern",
"EscChar",
"FamilyName",
"FontBBox",
"FontName",
"FullName",
"IsBaseFont",
"IsCIDFont",
"IsFixedPitch",
"IsFixedV",
"ItalicAngle",
"KP",
"KPH",
"KPX",
"KPY",
"L",
"MappingScheme",
"MetricsSets",
"N",
"Notice",
"PCC",
"StartAxis",
"StartCharMetrics",
"StartComposites",
"StartDirection",
"StartFontMetrics",
"StartKernData",
"StartKernPairs",
"StartKernPairs0",
"StartKernPairs1",
"StartTrackKern",
"StdHW",
"StdVW",
"TrackKern",
"UnderlinePosition",
"UnderlineThickness",
"VV",
"VVector",
"Version",
"W",
"W0",
"W0X",
"W0Y",
"W1",
"W1X",
"W1Y",
"WX",
"WY",
"Weight",
"WeightVector",
"XHeight"
};
/*
* `afm_parser_read_vals' and `afm_parser_next_key' provide
* high-level operations to an AFM_Stream. The rest of the
* parser functions should use them without accessing the
* AFM_Stream directly.
*/
FT_LOCAL_DEF( FT_Int )
afm_parser_read_vals( AFM_Parser parser,
AFM_Value vals,
FT_UInt n )
{
AFM_Stream stream = parser->stream;
char* str;
FT_UInt i;
if ( n > AFM_MAX_ARGUMENTS )
return 0;
for ( i = 0; i < n; i++ )
{
FT_Offset len;
AFM_Value val = vals + i;
if ( val->type == AFM_VALUE_TYPE_STRING )
str = afm_stream_read_string( stream );
else
str = afm_stream_read_one( stream );
if ( !str )
break;
len = AFM_STREAM_KEY_LEN( stream, str );
switch ( val->type )
{
case AFM_VALUE_TYPE_STRING:
case AFM_VALUE_TYPE_NAME:
{
FT_Memory memory = parser->memory;
FT_Error error;
if ( !FT_QALLOC( val->u.s, len + 1 ) )
{
ft_memcpy( val->u.s, str, len );
val->u.s[len] = '\0';
}
}
break;
case AFM_VALUE_TYPE_FIXED:
val->u.f = PS_Conv_ToFixed( (FT_Byte**)(void*)&str,
(FT_Byte*)str + len, 0 );
break;
case AFM_VALUE_TYPE_INTEGER:
val->u.i = PS_Conv_ToInt( (FT_Byte**)(void*)&str,
(FT_Byte*)str + len );
break;
case AFM_VALUE_TYPE_BOOL:
val->u.b = FT_BOOL( len == 4 &&
!ft_strncmp( str, "true", 4 ) );
break;
case AFM_VALUE_TYPE_INDEX:
if ( parser->get_index )
val->u.i = parser->get_index( str, len, parser->user_data );
else
val->u.i = 0;
break;
}
}
return i;
}
FT_LOCAL_DEF( char* )
afm_parser_next_key( AFM_Parser parser,
FT_Bool line,
FT_Offset* len )
{
AFM_Stream stream = parser->stream;
char* key = 0; /* make stupid compiler happy */
if ( line )
{
while ( 1 )
{
/* skip current line */
if ( !AFM_STATUS_EOL( stream ) )
afm_stream_read_string( stream );
stream->status = AFM_STREAM_STATUS_NORMAL;
key = afm_stream_read_one( stream );
/* skip empty line */
if ( !key &&
!AFM_STATUS_EOF( stream ) &&
AFM_STATUS_EOL( stream ) )
continue;
break;
}
}
else
{
while ( 1 )
{
/* skip current column */
while ( !AFM_STATUS_EOC( stream ) )
afm_stream_read_one( stream );
stream->status = AFM_STREAM_STATUS_NORMAL;
key = afm_stream_read_one( stream );
/* skip empty column */
if ( !key &&
!AFM_STATUS_EOF( stream ) &&
AFM_STATUS_EOC( stream ) )
continue;
break;
}
}
if ( len )
*len = ( key ) ? (FT_Offset)AFM_STREAM_KEY_LEN( stream, key )
: 0;
return key;
}
static AFM_Token
afm_tokenize( const char* key,
FT_Offset len )
{
int n;
for ( n = 0; n < N_AFM_TOKENS; n++ )
{
if ( *( afm_key_table[n] ) == *key )
{
for ( ; n < N_AFM_TOKENS; n++ )
{
if ( *( afm_key_table[n] ) != *key )
return AFM_TOKEN_UNKNOWN;
if ( ft_strncmp( afm_key_table[n], key, len ) == 0 )
return (AFM_Token) n;
}
}
}
return AFM_TOKEN_UNKNOWN;
}
FT_LOCAL_DEF( FT_Error )
afm_parser_init( AFM_Parser parser,
FT_Memory memory,
FT_Byte* base,
FT_Byte* limit )
{
AFM_Stream stream = NULL;
FT_Error error = FT_Err_Ok;
if ( FT_NEW( stream ) )
return error;
stream->cursor = stream->base = base;
stream->limit = limit;
/* don't skip the first line during the first call */
stream->status = AFM_STREAM_STATUS_EOL;
parser->memory = memory;
parser->stream = stream;
parser->FontInfo = NULL;
parser->get_index = NULL;
return FT_Err_Ok;
}
FT_LOCAL( void )
afm_parser_done( AFM_Parser parser )
{
FT_Memory memory = parser->memory;
FT_FREE( parser->stream );
}
FT_LOCAL_DEF( FT_Error )
afm_parser_read_int( AFM_Parser parser,
FT_Int* aint )
{
AFM_ValueRec val;
val.type = AFM_VALUE_TYPE_INTEGER;
if ( afm_parser_read_vals( parser, &val, 1 ) == 1 )
{
*aint = val.u.i;
return FT_Err_Ok;
}
else
return FT_THROW( Syntax_Error );
}
static FT_Error
afm_parse_track_kern( AFM_Parser parser )
{
AFM_FontInfo fi = parser->FontInfo;
AFM_TrackKern tk;
char* key;
FT_Offset len;
int n = -1;
if ( afm_parser_read_int( parser, &fi->NumTrackKern ) )
goto Fail;
if ( fi->NumTrackKern )
{
FT_Memory memory = parser->memory;
FT_Error error = FT_Err_Ok;
if ( FT_QNEW_ARRAY( fi->TrackKerns, fi->NumTrackKern ) )
return error;
}
while ( ( key = afm_parser_next_key( parser, 1, &len ) ) != 0 )
{
AFM_ValueRec shared_vals[5];
switch ( afm_tokenize( key, len ) )
{
case AFM_TOKEN_TRACKKERN:
n++;
if ( n >= fi->NumTrackKern )
goto Fail;
tk = fi->TrackKerns + n;
shared_vals[0].type = AFM_VALUE_TYPE_INTEGER;
shared_vals[1].type = AFM_VALUE_TYPE_FIXED;
shared_vals[2].type = AFM_VALUE_TYPE_FIXED;
shared_vals[3].type = AFM_VALUE_TYPE_FIXED;
shared_vals[4].type = AFM_VALUE_TYPE_FIXED;
if ( afm_parser_read_vals( parser, shared_vals, 5 ) != 5 )
goto Fail;
tk->degree = shared_vals[0].u.i;
tk->min_ptsize = shared_vals[1].u.f;
tk->min_kern = shared_vals[2].u.f;
tk->max_ptsize = shared_vals[3].u.f;
tk->max_kern = shared_vals[4].u.f;
break;
case AFM_TOKEN_ENDTRACKKERN:
case AFM_TOKEN_ENDKERNDATA:
case AFM_TOKEN_ENDFONTMETRICS:
fi->NumTrackKern = n + 1;
return FT_Err_Ok;
case AFM_TOKEN_UNKNOWN:
break;
default:
goto Fail;
}
}
Fail:
return FT_THROW( Syntax_Error );
}
#undef KERN_INDEX
#define KERN_INDEX( g1, g2 ) ( ( (FT_ULong)g1 << 16 ) | g2 )
/* compare two kerning pairs */
FT_CALLBACK_DEF( int )
afm_compare_kern_pairs( const void* a,
const void* b )
{
AFM_KernPair kp1 = (AFM_KernPair)a;
AFM_KernPair kp2 = (AFM_KernPair)b;
FT_ULong index1 = KERN_INDEX( kp1->index1, kp1->index2 );
FT_ULong index2 = KERN_INDEX( kp2->index1, kp2->index2 );
if ( index1 > index2 )
return 1;
else if ( index1 < index2 )
return -1;
else
return 0;
}
static FT_Error
afm_parse_kern_pairs( AFM_Parser parser )
{
AFM_FontInfo fi = parser->FontInfo;
AFM_KernPair kp;
char* key;
FT_Offset len;
int n = -1;
if ( afm_parser_read_int( parser, &fi->NumKernPair ) )
goto Fail;
if ( fi->NumKernPair )
{
FT_Memory memory = parser->memory;
FT_Error error = FT_Err_Ok;
if ( FT_QNEW_ARRAY( fi->KernPairs, fi->NumKernPair ) )
return error;
}
while ( ( key = afm_parser_next_key( parser, 1, &len ) ) != 0 )
{
AFM_Token token = afm_tokenize( key, len );
switch ( token )
{
case AFM_TOKEN_KP:
case AFM_TOKEN_KPX:
case AFM_TOKEN_KPY:
{
FT_Int r;
AFM_ValueRec shared_vals[4];
n++;
if ( n >= fi->NumKernPair )
goto Fail;
kp = fi->KernPairs + n;
shared_vals[0].type = AFM_VALUE_TYPE_INDEX;
shared_vals[1].type = AFM_VALUE_TYPE_INDEX;
shared_vals[2].type = AFM_VALUE_TYPE_INTEGER;
shared_vals[3].type = AFM_VALUE_TYPE_INTEGER;
r = afm_parser_read_vals( parser, shared_vals, 4 );
if ( r < 3 )
goto Fail;
kp->index1 = shared_vals[0].u.i;
kp->index2 = shared_vals[1].u.i;
if ( token == AFM_TOKEN_KPY )
{
kp->x = 0;
kp->y = shared_vals[2].u.i;
}
else
{
kp->x = shared_vals[2].u.i;
kp->y = ( token == AFM_TOKEN_KP && r == 4 )
? shared_vals[3].u.i : 0;
}
}
break;
case AFM_TOKEN_ENDKERNPAIRS:
case AFM_TOKEN_ENDKERNDATA:
case AFM_TOKEN_ENDFONTMETRICS:
fi->NumKernPair = n + 1;
ft_qsort( fi->KernPairs, fi->NumKernPair,
sizeof ( AFM_KernPairRec ),
afm_compare_kern_pairs );
return FT_Err_Ok;
case AFM_TOKEN_UNKNOWN:
break;
default:
goto Fail;
}
}
Fail:
return FT_THROW( Syntax_Error );
}
static FT_Error
afm_parse_kern_data( AFM_Parser parser )
{
FT_Error error;
char* key;
FT_Offset len;
while ( ( key = afm_parser_next_key( parser, 1, &len ) ) != 0 )
{
switch ( afm_tokenize( key, len ) )
{
case AFM_TOKEN_STARTTRACKKERN:
error = afm_parse_track_kern( parser );
if ( error )
return error;
break;
case AFM_TOKEN_STARTKERNPAIRS:
case AFM_TOKEN_STARTKERNPAIRS0:
error = afm_parse_kern_pairs( parser );
if ( error )
return error;
break;
case AFM_TOKEN_ENDKERNDATA:
case AFM_TOKEN_ENDFONTMETRICS:
return FT_Err_Ok;
case AFM_TOKEN_UNKNOWN:
break;
default:
goto Fail;
}
}
Fail:
return FT_THROW( Syntax_Error );
}
static FT_Error
afm_parser_skip_section( AFM_Parser parser,
FT_UInt n,
AFM_Token end_section )
{
char* key;
FT_Offset len;
while ( n-- > 0 )
{
key = afm_parser_next_key( parser, 1, NULL );
if ( !key )
goto Fail;
}
while ( ( key = afm_parser_next_key( parser, 1, &len ) ) != 0 )
{
AFM_Token token = afm_tokenize( key, len );
if ( token == end_section || token == AFM_TOKEN_ENDFONTMETRICS )
return FT_Err_Ok;
}
Fail:
return FT_THROW( Syntax_Error );
}
FT_LOCAL_DEF( FT_Error )
afm_parser_parse( AFM_Parser parser )
{
FT_Memory memory = parser->memory;
AFM_FontInfo fi = parser->FontInfo;
FT_Error error = FT_ERR( Syntax_Error );
char* key;
FT_Offset len;
FT_Int metrics_sets = 0;
if ( !fi )
return FT_THROW( Invalid_Argument );
key = afm_parser_next_key( parser, 1, &len );
if ( !key || len != 16 ||
ft_strncmp( key, "StartFontMetrics", 16 ) != 0 )
return FT_THROW( Unknown_File_Format );
while ( ( key = afm_parser_next_key( parser, 1, &len ) ) != 0 )
{
AFM_ValueRec shared_vals[4];
switch ( afm_tokenize( key, len ) )
{
case AFM_TOKEN_METRICSSETS:
if ( afm_parser_read_int( parser, &metrics_sets ) )
goto Fail;
if ( metrics_sets != 0 && metrics_sets != 2 )
{
error = FT_THROW( Unimplemented_Feature );
goto Fail;
}
break;
case AFM_TOKEN_ISCIDFONT:
shared_vals[0].type = AFM_VALUE_TYPE_BOOL;
if ( afm_parser_read_vals( parser, shared_vals, 1 ) != 1 )
goto Fail;
fi->IsCIDFont = shared_vals[0].u.b;
break;
case AFM_TOKEN_FONTBBOX:
shared_vals[0].type = AFM_VALUE_TYPE_FIXED;
shared_vals[1].type = AFM_VALUE_TYPE_FIXED;
shared_vals[2].type = AFM_VALUE_TYPE_FIXED;
shared_vals[3].type = AFM_VALUE_TYPE_FIXED;
if ( afm_parser_read_vals( parser, shared_vals, 4 ) != 4 )
goto Fail;
fi->FontBBox.xMin = shared_vals[0].u.f;
fi->FontBBox.yMin = shared_vals[1].u.f;
fi->FontBBox.xMax = shared_vals[2].u.f;
fi->FontBBox.yMax = shared_vals[3].u.f;
break;
case AFM_TOKEN_ASCENDER:
shared_vals[0].type = AFM_VALUE_TYPE_FIXED;
if ( afm_parser_read_vals( parser, shared_vals, 1 ) != 1 )
goto Fail;
fi->Ascender = shared_vals[0].u.f;
break;
case AFM_TOKEN_DESCENDER:
shared_vals[0].type = AFM_VALUE_TYPE_FIXED;
if ( afm_parser_read_vals( parser, shared_vals, 1 ) != 1 )
goto Fail;
fi->Descender = shared_vals[0].u.f;
break;
case AFM_TOKEN_STARTCHARMETRICS:
{
FT_Int n = 0;
if ( afm_parser_read_int( parser, &n ) )
goto Fail;
error = afm_parser_skip_section( parser, n,
AFM_TOKEN_ENDCHARMETRICS );
if ( error )
return error;
}
break;
case AFM_TOKEN_STARTKERNDATA:
error = afm_parse_kern_data( parser );
if ( error )
goto Fail;
/* fall through since we only support kern data */
case AFM_TOKEN_ENDFONTMETRICS:
return FT_Err_Ok;
default:
break;
}
}
Fail:
FT_FREE( fi->TrackKerns );
fi->NumTrackKern = 0;
FT_FREE( fi->KernPairs );
fi->NumKernPair = 0;
fi->IsCIDFont = 0;
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/afmparse.c | C | apache-2.0 | 22,589 |
/***************************************************************************/
/* */
/* afmparse.h */
/* */
/* AFM parser (specification). */
/* */
/* Copyright 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 __AFMPARSE_H__
#define __AFMPARSE_H__
#include <ft2build.h>
#include FT_INTERNAL_POSTSCRIPT_AUX_H
FT_BEGIN_HEADER
FT_LOCAL( FT_Error )
afm_parser_init( AFM_Parser parser,
FT_Memory memory,
FT_Byte* base,
FT_Byte* limit );
FT_LOCAL( void )
afm_parser_done( AFM_Parser parser );
FT_LOCAL( FT_Error )
afm_parser_parse( AFM_Parser parser );
enum AFM_ValueType_
{
AFM_VALUE_TYPE_STRING,
AFM_VALUE_TYPE_NAME,
AFM_VALUE_TYPE_FIXED, /* real number */
AFM_VALUE_TYPE_INTEGER,
AFM_VALUE_TYPE_BOOL,
AFM_VALUE_TYPE_INDEX /* glyph index */
};
typedef struct AFM_ValueRec_
{
enum AFM_ValueType_ type;
union
{
char* s;
FT_Fixed f;
FT_Int i;
FT_Bool b;
} u;
} AFM_ValueRec, *AFM_Value;
#define AFM_MAX_ARGUMENTS 5
FT_LOCAL( FT_Int )
afm_parser_read_vals( AFM_Parser parser,
AFM_Value vals,
FT_UInt n );
/* read the next key from the next line or column */
FT_LOCAL( char* )
afm_parser_next_key( AFM_Parser parser,
FT_Bool line,
FT_Offset* len );
FT_END_HEADER
#endif /* __AFMPARSE_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/afmparse.h | C | apache-2.0 | 2,556 |
#
# FreeType 2 PSaux 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 += PSAUX_MODULE
define PSAUX_MODULE
$(OPEN_DRIVER) FT_Module_Class, psaux_module_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)psaux $(ECHO_DRIVER_DESC)Postscript Type 1 & Type 2 helper module$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/psaux/module.mk | Makefile | apache-2.0 | 668 |
/***************************************************************************/
/* */
/* psaux.c */
/* */
/* FreeType auxiliary PostScript driver component (body only). */
/* */
/* Copyright 1996-2001, 2002, 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. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "psobjs.c"
#include "psauxmod.c"
#include "t1decode.c"
#include "t1cmap.c"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "afmparse.c"
#endif
#include "psconv.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psaux.c | C | apache-2.0 | 1,489 |
/***************************************************************************/
/* */
/* psauxerr.h */
/* */
/* PS auxiliary module 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 PS auxiliary module error enumeration */
/* constants. */
/* */
/*************************************************************************/
#ifndef __PSAUXERR_H__
#define __PSAUXERR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX PSaux_Err_
#define FT_ERR_BASE FT_Mod_Err_PSaux
#include FT_ERRORS_H
#endif /* __PSAUXERR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psauxerr.h | C | apache-2.0 | 1,977 |
/***************************************************************************/
/* */
/* psauxmod.c */
/* */
/* FreeType auxiliary PostScript module implementation (body). */
/* */
/* Copyright 2000-2001, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include "psauxmod.h"
#include "psobjs.h"
#include "t1decode.h"
#include "t1cmap.h"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "afmparse.h"
#endif
FT_CALLBACK_TABLE_DEF
const PS_Table_FuncsRec ps_table_funcs =
{
ps_table_new,
ps_table_done,
ps_table_add,
ps_table_release
};
FT_CALLBACK_TABLE_DEF
const PS_Parser_FuncsRec ps_parser_funcs =
{
ps_parser_init,
ps_parser_done,
ps_parser_skip_spaces,
ps_parser_skip_PS_token,
ps_parser_to_int,
ps_parser_to_fixed,
ps_parser_to_bytes,
ps_parser_to_coord_array,
ps_parser_to_fixed_array,
ps_parser_to_token,
ps_parser_to_token_array,
ps_parser_load_field,
ps_parser_load_field_table
};
FT_CALLBACK_TABLE_DEF
const T1_Builder_FuncsRec t1_builder_funcs =
{
t1_builder_init,
t1_builder_done,
t1_builder_check_points,
t1_builder_add_point,
t1_builder_add_point1,
t1_builder_add_contour,
t1_builder_start_point,
t1_builder_close_contour
};
FT_CALLBACK_TABLE_DEF
const T1_Decoder_FuncsRec t1_decoder_funcs =
{
t1_decoder_init,
t1_decoder_done,
t1_decoder_parse_charstrings
};
#ifndef T1_CONFIG_OPTION_NO_AFM
FT_CALLBACK_TABLE_DEF
const AFM_Parser_FuncsRec afm_parser_funcs =
{
afm_parser_init,
afm_parser_done,
afm_parser_parse
};
#endif
FT_CALLBACK_TABLE_DEF
const T1_CMap_ClassesRec t1_cmap_classes =
{
&t1_cmap_standard_class_rec,
&t1_cmap_expert_class_rec,
&t1_cmap_custom_class_rec,
&t1_cmap_unicode_class_rec
};
static
const PSAux_Interface psaux_interface =
{
&ps_table_funcs,
&ps_parser_funcs,
&t1_builder_funcs,
&t1_decoder_funcs,
t1_decrypt,
(const T1_CMap_ClassesRec*) &t1_cmap_classes,
#ifndef T1_CONFIG_OPTION_NO_AFM
&afm_parser_funcs,
#else
0,
#endif
};
FT_CALLBACK_TABLE_DEF
const FT_Module_Class psaux_module_class =
{
0,
sizeof ( FT_ModuleRec ),
"psaux",
0x20000L,
0x20000L,
&psaux_interface, /* module-specific interface */
(FT_Module_Constructor)0,
(FT_Module_Destructor) 0,
(FT_Module_Requester) 0
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psauxmod.c | C | apache-2.0 | 3,444 |
/***************************************************************************/
/* */
/* psauxmod.h */
/* */
/* FreeType auxiliary PostScript module implementation (specification). */
/* */
/* Copyright 2000-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. */
/* */
/***************************************************************************/
#ifndef __PSAUXMOD_H__
#define __PSAUXMOD_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 ) psaux_driver_class;
FT_END_HEADER
#endif /* __PSAUXMOD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psauxmod.h | C | apache-2.0 | 1,562 |
/***************************************************************************/
/* */
/* psconv.c */
/* */
/* Some convenience conversions (body). */
/* */
/* Copyright 2006, 2008, 2009, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include FT_INTERNAL_DEBUG_H
#include "psconv.h"
#include "psauxerr.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_psconv
/* The following array is used by various functions to quickly convert */
/* digits (both decimal and non-decimal) into numbers. */
#if 'A' == 65
/* ASCII */
static const FT_Char ft_char_table[128] =
{
/* 0x00 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 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, -1, -1, -1, -1, -1,
-1, 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, -1, -1, -1, -1, -1,
};
/* no character >= 0x80 can represent a valid number */
#define OP >=
#endif /* 'A' == 65 */
#if 'A' == 193
/* EBCDIC */
static const FT_Char ft_char_table[128] =
{
/* 0x80 */
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, -1, -1, -1, -1, -1,
-1, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1,
-1, -1, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, -1, -1, -1, -1, -1,
-1, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1,
-1, -1, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
};
/* no character < 0x80 can represent a valid number */
#define OP <
#endif /* 'A' == 193 */
FT_LOCAL_DEF( FT_Long )
PS_Conv_Strtol( FT_Byte** cursor,
FT_Byte* limit,
FT_Long base )
{
FT_Byte* p = *cursor;
FT_Long num = 0;
FT_Bool sign = 0;
FT_Bool have_overflow = 0;
FT_Long num_limit;
FT_Char c_limit;
if ( p >= limit )
goto Bad;
if ( base < 2 || base > 36 )
{
FT_TRACE4(( "!!!INVALID BASE:!!!" ));
return 0;
}
if ( *p == '-' || *p == '+' )
{
sign = FT_BOOL( *p == '-' );
p++;
if ( p == limit )
goto Bad;
}
num_limit = 0x7FFFFFFFL / base;
c_limit = (FT_Char)( 0x7FFFFFFFL % base );
for ( ; p < limit; p++ )
{
FT_Char c;
if ( IS_PS_SPACE( *p ) || *p OP 0x80 )
break;
c = ft_char_table[*p & 0x7f];
if ( c < 0 || c >= base )
break;
if ( num > num_limit || ( num == num_limit && c > c_limit ) )
have_overflow = 1;
else
num = num * base + c;
}
*cursor = p;
if ( have_overflow )
{
num = 0x7FFFFFFFL;
FT_TRACE4(( "!!!OVERFLOW:!!!" ));
}
if ( sign )
num = -num;
return num;
Bad:
FT_TRACE4(( "!!!END OF DATA:!!!" ));
return 0;
}
FT_LOCAL_DEF( FT_Long )
PS_Conv_ToInt( FT_Byte** cursor,
FT_Byte* limit )
{
FT_Byte* p = *cursor;
FT_Byte* curp;
FT_Long num;
curp = p;
num = PS_Conv_Strtol( &p, limit, 10 );
if ( p == curp )
return 0;
if ( p < limit && *p == '#' )
{
p++;
curp = p;
num = PS_Conv_Strtol( &p, limit, num );
if ( p == curp )
return 0;
}
*cursor = p;
return num;
}
FT_LOCAL_DEF( FT_Fixed )
PS_Conv_ToFixed( FT_Byte** cursor,
FT_Byte* limit,
FT_Long power_ten )
{
FT_Byte* p = *cursor;
FT_Byte* curp;
FT_Fixed integral = 0;
FT_Long decimal = 0;
FT_Long divider = 1;
FT_Bool sign = 0;
FT_Bool have_overflow = 0;
FT_Bool have_underflow = 0;
if ( p >= limit )
goto Bad;
if ( *p == '-' || *p == '+' )
{
sign = FT_BOOL( *p == '-' );
p++;
if ( p == limit )
goto Bad;
}
/* read the integer part */
if ( *p != '.' )
{
curp = p;
integral = PS_Conv_ToInt( &p, limit );
if ( p == curp )
return 0;
if ( integral > 0x7FFF )
have_overflow = 1;
else
integral = (FT_Fixed)( (FT_UInt32)integral << 16 );
}
/* read the decimal part */
if ( p < limit && *p == '.' )
{
p++;
for ( ; p < limit; p++ )
{
FT_Char c;
if ( IS_PS_SPACE( *p ) || *p OP 0x80 )
break;
c = ft_char_table[*p & 0x7f];
if ( c < 0 || c >= 10 )
break;
if ( decimal < 0xCCCCCCCL )
{
decimal = decimal * 10 + c;
if ( !integral && power_ten > 0 )
power_ten--;
else
divider *= 10;
}
}
}
/* read exponent, if any */
if ( p + 1 < limit && ( *p == 'e' || *p == 'E' ) )
{
FT_Long exponent;
p++;
curp = p;
exponent = PS_Conv_ToInt( &p, limit );
if ( curp == p )
return 0;
/* arbitrarily limit exponent */
if ( exponent > 1000 )
have_overflow = 1;
else if ( exponent < -1000 )
have_underflow = 1;
else
power_ten += exponent;
}
*cursor = p;
if ( !integral && !decimal )
return 0;
if ( have_overflow )
goto Overflow;
if ( have_underflow )
goto Underflow;
while ( power_ten > 0 )
{
if ( integral >= 0xCCCCCCCL )
goto Overflow;
integral *= 10;
if ( decimal >= 0xCCCCCCCL )
{
if ( divider == 1 )
goto Overflow;
divider /= 10;
}
else
decimal *= 10;
power_ten--;
}
while ( power_ten < 0 )
{
integral /= 10;
if ( divider < 0xCCCCCCCL )
divider *= 10;
else
decimal /= 10;
if ( !integral && !decimal )
goto Underflow;
power_ten++;
}
if ( decimal )
{
decimal = FT_DivFix( decimal, divider );
/* it's not necessary to check this addition for overflow */
/* due to the structure of the real number representation */
integral += decimal;
}
Exit:
if ( sign )
integral = -integral;
return integral;
Bad:
FT_TRACE4(( "!!!END OF DATA:!!!" ));
return 0;
Overflow:
integral = 0x7FFFFFFFL;
FT_TRACE4(( "!!!OVERFLOW:!!!" ));
goto Exit;
Underflow:
FT_TRACE4(( "!!!UNDERFLOW:!!!" ));
return 0;
}
#if 0
FT_LOCAL_DEF( FT_UInt )
PS_Conv_StringDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n )
{
FT_Byte* p;
FT_UInt r = 0;
for ( p = *cursor; r < n && p < limit; p++ )
{
FT_Byte b;
if ( *p != '\\' )
{
buffer[r++] = *p;
continue;
}
p++;
switch ( *p )
{
case 'n':
b = '\n';
break;
case 'r':
b = '\r';
break;
case 't':
b = '\t';
break;
case 'b':
b = '\b';
break;
case 'f':
b = '\f';
break;
case '\r':
p++;
if ( *p != '\n' )
{
b = *p;
break;
}
/* no break */
case '\n':
continue;
break;
default:
if ( IS_PS_DIGIT( *p ) )
{
b = *p - '0';
p++;
if ( IS_PS_DIGIT( *p ) )
{
b = b * 8 + *p - '0';
p++;
if ( IS_PS_DIGIT( *p ) )
b = b * 8 + *p - '0';
else
{
buffer[r++] = b;
b = *p;
}
}
else
{
buffer[r++] = b;
b = *p;
}
}
else
b = *p;
break;
}
buffer[r++] = b;
}
*cursor = p;
return r;
}
#endif /* 0 */
FT_LOCAL_DEF( FT_UInt )
PS_Conv_ASCIIHexDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n )
{
FT_Byte* p;
FT_UInt r = 0;
FT_UInt w = 0;
FT_UInt pad = 0x01;
n *= 2;
#if 1
p = *cursor;
if ( p >= limit )
return 0;
if ( n > (FT_UInt)( limit - p ) )
n = (FT_UInt)( limit - p );
/* we try to process two nibbles at a time to be as fast as possible */
for ( ; r < n; r++ )
{
FT_UInt c = p[r];
if ( IS_PS_SPACE( c ) )
continue;
if ( c OP 0x80 )
break;
c = ft_char_table[c & 0x7F];
if ( (unsigned)c >= 16 )
break;
pad = ( pad << 4 ) | c;
if ( pad & 0x100 )
{
buffer[w++] = (FT_Byte)pad;
pad = 0x01;
}
}
if ( pad != 0x01 )
buffer[w++] = (FT_Byte)( pad << 4 );
*cursor = p + r;
return w;
#else /* 0 */
for ( r = 0; r < n; r++ )
{
FT_Char c;
if ( IS_PS_SPACE( *p ) )
continue;
if ( *p OP 0x80 )
break;
c = ft_char_table[*p & 0x7f];
if ( (unsigned)c >= 16 )
break;
if ( r & 1 )
{
*buffer = (FT_Byte)(*buffer + c);
buffer++;
}
else
*buffer = (FT_Byte)(c << 4);
r++;
}
*cursor = p;
return ( r + 1 ) / 2;
#endif /* 0 */
}
FT_LOCAL_DEF( FT_UInt )
PS_Conv_EexecDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n,
FT_UShort* seed )
{
FT_Byte* p;
FT_UInt r;
FT_UInt s = *seed;
#if 1
p = *cursor;
if ( p >= limit )
return 0;
if ( n > (FT_UInt)(limit - p) )
n = (FT_UInt)(limit - p);
for ( r = 0; r < n; r++ )
{
FT_UInt val = p[r];
FT_UInt b = ( val ^ ( s >> 8 ) );
s = ( (val + s)*52845U + 22719 ) & 0xFFFFU;
buffer[r] = (FT_Byte) b;
}
*cursor = p + n;
*seed = (FT_UShort)s;
#else /* 0 */
for ( r = 0, p = *cursor; r < n && p < limit; r++, p++ )
{
FT_Byte b = (FT_Byte)( *p ^ ( s >> 8 ) );
s = (FT_UShort)( ( *p + s ) * 52845U + 22719 );
*buffer++ = b;
}
*cursor = p;
*seed = s;
#endif /* 0 */
return r;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psconv.c | C | apache-2.0 | 12,307 |
/***************************************************************************/
/* */
/* psconv.h */
/* */
/* Some convenience conversions (specification). */
/* */
/* Copyright 2006, 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. */
/* */
/***************************************************************************/
#ifndef __PSCONV_H__
#define __PSCONV_H__
#include <ft2build.h>
#include FT_INTERNAL_POSTSCRIPT_AUX_H
FT_BEGIN_HEADER
FT_LOCAL( FT_Long )
PS_Conv_Strtol( FT_Byte** cursor,
FT_Byte* limit,
FT_Long base );
FT_LOCAL( FT_Long )
PS_Conv_ToInt( FT_Byte** cursor,
FT_Byte* limit );
FT_LOCAL( FT_Fixed )
PS_Conv_ToFixed( FT_Byte** cursor,
FT_Byte* limit,
FT_Long power_ten );
#if 0
FT_LOCAL( FT_UInt )
PS_Conv_StringDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n );
#endif
FT_LOCAL( FT_UInt )
PS_Conv_ASCIIHexDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n );
FT_LOCAL( FT_UInt )
PS_Conv_EexecDecode( FT_Byte** cursor,
FT_Byte* limit,
FT_Byte* buffer,
FT_Offset n,
FT_UShort* seed );
FT_END_HEADER
#endif /* __PSCONV_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psconv.h | C | apache-2.0 | 2,434 |
/***************************************************************************/
/* */
/* psobjs.c */
/* */
/* Auxiliary functions for PostScript fonts (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_POSTSCRIPT_AUX_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_CALC_H
#include "psobjs.h"
#include "psconv.h"
#include "psauxerr.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_psobjs
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PS_TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* ps_table_new */
/* */
/* <Description> */
/* Initializes a PS_Table. */
/* */
/* <InOut> */
/* table :: The address of the target table. */
/* */
/* <Input> */
/* count :: The table size = the maximum number of elements. */
/* */
/* memory :: The memory object to use for all subsequent */
/* reallocations. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
ps_table_new( PS_Table table,
FT_Int count,
FT_Memory memory )
{
FT_Error error;
table->memory = memory;
if ( FT_NEW_ARRAY( table->elements, count ) ||
FT_NEW_ARRAY( table->lengths, count ) )
goto Exit;
table->max_elems = count;
table->init = 0xDEADBEEFUL;
table->num_elems = 0;
table->block = 0;
table->capacity = 0;
table->cursor = 0;
*(PS_Table_FuncsRec*)&table->funcs = ps_table_funcs;
Exit:
if ( error )
FT_FREE( table->elements );
return error;
}
static void
shift_elements( PS_Table table,
FT_Byte* old_base )
{
FT_PtrDist delta = table->block - old_base;
FT_Byte** offset = table->elements;
FT_Byte** limit = offset + table->max_elems;
for ( ; offset < limit; offset++ )
{
if ( offset[0] )
offset[0] += delta;
}
}
static FT_Error
reallocate_t1_table( PS_Table table,
FT_Offset new_size )
{
FT_Memory memory = table->memory;
FT_Byte* old_base = table->block;
FT_Error error = FT_Err_Ok;
/* allocate new base block */
if ( FT_ALLOC( table->block, new_size ) )
{
table->block = old_base;
return error;
}
/* copy elements and shift offsets */
if ( old_base )
{
FT_MEM_COPY( table->block, old_base, table->capacity );
shift_elements( table, old_base );
FT_FREE( old_base );
}
table->capacity = new_size;
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* <Function> */
/* ps_table_add */
/* */
/* <Description> */
/* Adds an object to a PS_Table, possibly growing its memory block. */
/* */
/* <InOut> */
/* table :: The target table. */
/* */
/* <Input> */
/* idx :: The index of the object in the table. */
/* */
/* object :: The address of the object to copy in memory. */
/* */
/* length :: The length in bytes of the source object. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. An error is returned if a */
/* reallocation fails. */
/* */
FT_LOCAL_DEF( FT_Error )
ps_table_add( PS_Table table,
FT_Int idx,
void* object,
FT_PtrDist length )
{
if ( idx < 0 || idx >= table->max_elems )
{
FT_ERROR(( "ps_table_add: invalid index\n" ));
return FT_THROW( Invalid_Argument );
}
if ( length < 0 )
{
FT_ERROR(( "ps_table_add: invalid length\n" ));
return FT_THROW( Invalid_Argument );
}
/* grow the base block if needed */
if ( table->cursor + length > table->capacity )
{
FT_Error error;
FT_Offset new_size = table->capacity;
FT_PtrDist in_offset;
in_offset = (FT_Byte*)object - table->block;
if ( in_offset < 0 || (FT_Offset)in_offset >= table->capacity )
in_offset = -1;
while ( new_size < table->cursor + length )
{
/* increase size by 25% and round up to the nearest multiple
of 1024 */
new_size += ( new_size >> 2 ) + 1;
new_size = FT_PAD_CEIL( new_size, 1024 );
}
error = reallocate_t1_table( table, new_size );
if ( error )
return error;
if ( in_offset >= 0 )
object = table->block + in_offset;
}
/* add the object to the base block and adjust offset */
table->elements[idx] = table->block + table->cursor;
table->lengths [idx] = length;
FT_MEM_COPY( table->block + table->cursor, object, length );
table->cursor += length;
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* <Function> */
/* ps_table_done */
/* */
/* <Description> */
/* Finalizes a PS_TableRec (i.e., reallocate it to its current */
/* cursor). */
/* */
/* <InOut> */
/* table :: The target table. */
/* */
/* <Note> */
/* This function does NOT release the heap's memory block. It is up */
/* to the caller to clean it, or reference it in its own structures. */
/* */
FT_LOCAL_DEF( void )
ps_table_done( PS_Table table )
{
FT_Memory memory = table->memory;
FT_Error error;
FT_Byte* old_base = table->block;
/* should never fail, because rec.cursor <= rec.size */
if ( !old_base )
return;
if ( FT_ALLOC( table->block, table->cursor ) )
return;
FT_MEM_COPY( table->block, old_base, table->cursor );
shift_elements( table, old_base );
table->capacity = table->cursor;
FT_FREE( old_base );
FT_UNUSED( error );
}
FT_LOCAL_DEF( void )
ps_table_release( PS_Table table )
{
FT_Memory memory = table->memory;
if ( (FT_ULong)table->init == 0xDEADBEEFUL )
{
FT_FREE( table->block );
FT_FREE( table->elements );
FT_FREE( table->lengths );
table->init = 0;
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* first character must be already part of the comment */
static void
skip_comment( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
while ( cur < limit )
{
if ( IS_PS_NEWLINE( *cur ) )
break;
cur++;
}
*acur = cur;
}
static void
skip_spaces( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
while ( cur < limit )
{
if ( !IS_PS_SPACE( *cur ) )
{
if ( *cur == '%' )
/* According to the PLRM, a comment is equal to a space. */
skip_comment( &cur, limit );
else
break;
}
cur++;
}
*acur = cur;
}
#define IS_OCTAL_DIGIT( c ) ( '0' <= (c) && (c) <= '7' )
/* first character must be `('; */
/* *acur is positioned at the character after the closing `)' */
static FT_Error
skip_literal_string( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Int embed = 0;
FT_Error error = FT_ERR( Invalid_File_Format );
unsigned int i;
while ( cur < limit )
{
FT_Byte c = *cur;
++cur;
if ( c == '\\' )
{
/* Red Book 3rd ed., section `Literal Text Strings', p. 29: */
/* A backslash can introduce three different types */
/* of escape sequences: */
/* - a special escaped char like \r, \n, etc. */
/* - a one-, two-, or three-digit octal number */
/* - none of the above in which case the backslash is ignored */
if ( cur == limit )
/* error (or to be ignored?) */
break;
switch ( *cur )
{
/* skip `special' escape */
case 'n':
case 'r':
case 't':
case 'b':
case 'f':
case '\\':
case '(':
case ')':
++cur;
break;
default:
/* skip octal escape or ignore backslash */
for ( i = 0; i < 3 && cur < limit; ++i )
{
if ( !IS_OCTAL_DIGIT( *cur ) )
break;
++cur;
}
}
}
else if ( c == '(' )
embed++;
else if ( c == ')' )
{
embed--;
if ( embed == 0 )
{
error = FT_Err_Ok;
break;
}
}
}
*acur = cur;
return error;
}
/* first character must be `<' */
static FT_Error
skip_string( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Error err = FT_Err_Ok;
while ( ++cur < limit )
{
/* All whitespace characters are ignored. */
skip_spaces( &cur, limit );
if ( cur >= limit )
break;
if ( !IS_PS_XDIGIT( *cur ) )
break;
}
if ( cur < limit && *cur != '>' )
{
FT_ERROR(( "skip_string: missing closing delimiter `>'\n" ));
err = FT_THROW( Invalid_File_Format );
}
else
cur++;
*acur = cur;
return err;
}
/* first character must be the opening brace that */
/* starts the procedure */
/* NB: [ and ] need not match: */
/* `/foo {[} def' is a valid PostScript fragment, */
/* even within a Type1 font */
static FT_Error
skip_procedure( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur;
FT_Int embed = 0;
FT_Error error = FT_Err_Ok;
FT_ASSERT( **acur == '{' );
for ( cur = *acur; cur < limit && error == FT_Err_Ok; ++cur )
{
switch ( *cur )
{
case '{':
++embed;
break;
case '}':
--embed;
if ( embed == 0 )
{
++cur;
goto end;
}
break;
case '(':
error = skip_literal_string( &cur, limit );
break;
case '<':
error = skip_string( &cur, limit );
break;
case '%':
skip_comment( &cur, limit );
break;
}
}
end:
if ( embed != 0 )
error = FT_THROW( Invalid_File_Format );
*acur = cur;
return error;
}
/***********************************************************************/
/* */
/* All exported parsing routines handle leading whitespace and stop at */
/* the first character which isn't part of the just handled token. */
/* */
/***********************************************************************/
FT_LOCAL_DEF( void )
ps_parser_skip_PS_token( PS_Parser parser )
{
/* Note: PostScript allows any non-delimiting, non-whitespace */
/* character in a name (PS Ref Manual, 3rd ed, p31). */
/* PostScript delimiters are (, ), <, >, [, ], {, }, /, and %. */
FT_Byte* cur = parser->cursor;
FT_Byte* limit = parser->limit;
FT_Error error = FT_Err_Ok;
skip_spaces( &cur, limit ); /* this also skips comments */
if ( cur >= limit )
goto Exit;
/* self-delimiting, single-character tokens */
if ( *cur == '[' || *cur == ']' )
{
cur++;
goto Exit;
}
/* skip balanced expressions (procedures and strings) */
if ( *cur == '{' ) /* {...} */
{
error = skip_procedure( &cur, limit );
goto Exit;
}
if ( *cur == '(' ) /* (...) */
{
error = skip_literal_string( &cur, limit );
goto Exit;
}
if ( *cur == '<' ) /* <...> */
{
if ( cur + 1 < limit && *(cur + 1) == '<' ) /* << */
{
cur++;
cur++;
}
else
error = skip_string( &cur, limit );
goto Exit;
}
if ( *cur == '>' )
{
cur++;
if ( cur >= limit || *cur != '>' ) /* >> */
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" unexpected closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
goto Exit;
}
if ( *cur == '/' )
cur++;
/* anything else */
while ( cur < limit )
{
/* *cur might be invalid (e.g., ')' or '}'), but this */
/* is handled by the test `cur == parser->cursor' below */
if ( IS_PS_DELIM( *cur ) )
break;
cur++;
}
Exit:
if ( cur < limit && cur == parser->cursor )
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" current token is `%c' which is self-delimiting\n"
" "
" but invalid at this point\n",
*cur ));
error = FT_THROW( Invalid_File_Format );
}
parser->error = error;
parser->cursor = cur;
}
FT_LOCAL_DEF( void )
ps_parser_skip_spaces( PS_Parser parser )
{
skip_spaces( &parser->cursor, parser->limit );
}
/* `token' here means either something between balanced delimiters */
/* or the next token; the delimiters are not removed. */
FT_LOCAL_DEF( void )
ps_parser_to_token( PS_Parser parser,
T1_Token token )
{
FT_Byte* cur;
FT_Byte* limit;
FT_Int embed;
token->type = T1_TOKEN_TYPE_NONE;
token->start = 0;
token->limit = 0;
/* first of all, skip leading whitespace */
ps_parser_skip_spaces( parser );
cur = parser->cursor;
limit = parser->limit;
if ( cur >= limit )
return;
switch ( *cur )
{
/************* check for literal string *****************/
case '(':
token->type = T1_TOKEN_TYPE_STRING;
token->start = cur;
if ( skip_literal_string( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for programs/array *****************/
case '{':
token->type = T1_TOKEN_TYPE_ARRAY;
token->start = cur;
if ( skip_procedure( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for table/array ********************/
/* XXX: in theory we should also look for "<<" */
/* since this is semantically equivalent to "["; */
/* in practice it doesn't matter (?) */
case '[':
token->type = T1_TOKEN_TYPE_ARRAY;
embed = 1;
token->start = cur++;
/* we need this to catch `[ ]' */
parser->cursor = cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
while ( cur < limit && !parser->error )
{
/* XXX: this is wrong because it does not */
/* skip comments, procedures, and strings */
if ( *cur == '[' )
embed++;
else if ( *cur == ']' )
{
embed--;
if ( embed <= 0 )
{
token->limit = ++cur;
break;
}
}
parser->cursor = cur;
ps_parser_skip_PS_token( parser );
/* we need this to catch `[XXX ]' */
ps_parser_skip_spaces ( parser );
cur = parser->cursor;
}
break;
/* ************ otherwise, it is any token **************/
default:
token->start = cur;
token->type = ( *cur == '/' ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY );
ps_parser_skip_PS_token( parser );
cur = parser->cursor;
if ( !parser->error )
token->limit = cur;
}
if ( !token->limit )
{
token->start = 0;
token->type = T1_TOKEN_TYPE_NONE;
}
parser->cursor = cur;
}
/* NB: `tokens' can be NULL if we only want to count */
/* the number of array elements */
FT_LOCAL_DEF( void )
ps_parser_to_token_array( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens )
{
T1_TokenRec master;
*pnum_tokens = -1;
/* this also handles leading whitespace */
ps_parser_to_token( parser, &master );
if ( master.type == T1_TOKEN_TYPE_ARRAY )
{
FT_Byte* old_cursor = parser->cursor;
FT_Byte* old_limit = parser->limit;
T1_Token cur = tokens;
T1_Token limit = cur + max_tokens;
/* don't include outermost delimiters */
parser->cursor = master.start + 1;
parser->limit = master.limit - 1;
while ( parser->cursor < parser->limit )
{
T1_TokenRec token;
ps_parser_to_token( parser, &token );
if ( !token.type )
break;
if ( tokens != NULL && cur < limit )
*cur = token;
cur++;
}
*pnum_tokens = (FT_Int)( cur - tokens );
parser->cursor = old_cursor;
parser->limit = old_limit;
}
}
/* first character must be a delimiter or a part of a number */
/* NB: `coords' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_coords' */
static FT_Int
ps_tocoordarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_coords,
FT_Short* coords )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* check for the beginning of an array; otherwise, only one number */
/* will be read */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the coordinates */
while ( cur < limit )
{
FT_Short dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( coords != NULL && count >= max_coords )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( coords != NULL ? &coords[count] : &dummy ) =
(FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
/* first character must be a delimiter or a part of a number */
/* NB: `values' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_values' */
/* */
/* return number of successfully parsed values */
static FT_Int
ps_tofixedarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* Check for the beginning of an array. Otherwise, only one number */
/* will be read. */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the values */
while ( cur < limit )
{
FT_Fixed dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( values != NULL && count >= max_values )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( values != NULL ? &values[count] : &dummy ) =
PS_Conv_ToFixed( &cur, limit, power_ten );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
#if 0
static FT_String*
ps_tostring( FT_Byte** cursor,
FT_Byte* limit,
FT_Memory memory )
{
FT_Byte* cur = *cursor;
FT_PtrDist len = 0;
FT_Int count;
FT_String* result;
FT_Error error;
/* XXX: some stupid fonts have a `Notice' or `Copyright' string */
/* that simply doesn't begin with an opening parenthesis, even */
/* though they have a closing one! E.g. "amuncial.pfb" */
/* */
/* We must deal with these ill-fated cases there. Note that */
/* these fonts didn't work with the old Type 1 driver as the */
/* notice/copyright was not recognized as a valid string token */
/* and made the old token parser commit errors. */
while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) )
cur++;
if ( cur + 1 >= limit )
return 0;
if ( *cur == '(' )
cur++; /* skip the opening parenthesis, if there is one */
*cursor = cur;
count = 0;
/* then, count its length */
for ( ; cur < limit; cur++ )
{
if ( *cur == '(' )
count++;
else if ( *cur == ')' )
{
count--;
if ( count < 0 )
break;
}
}
len = cur - *cursor;
if ( cur >= limit || FT_ALLOC( result, len + 1 ) )
return 0;
/* now copy the string */
FT_MEM_COPY( result, *cursor, len );
result[len] = '\0';
*cursor = cur;
return result;
}
#endif /* 0 */
static int
ps_tobool( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Bool result = 0;
/* return 1 if we find `true', 0 otherwise */
if ( cur + 3 < limit &&
cur[0] == 't' &&
cur[1] == 'r' &&
cur[2] == 'u' &&
cur[3] == 'e' )
{
result = 1;
cur += 5;
}
else if ( cur + 4 < limit &&
cur[0] == 'f' &&
cur[1] == 'a' &&
cur[2] == 'l' &&
cur[3] == 's' &&
cur[4] == 'e' )
{
result = 0;
cur += 6;
}
*acur = cur;
return result;
}
/* load a simple field (i.e. non-table) into the current list of objects */
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec token;
FT_Byte* cur;
FT_Byte* limit;
FT_UInt count;
FT_UInt idx;
FT_Error error;
T1_FieldType type;
/* this also skips leading whitespace */
ps_parser_to_token( parser, &token );
if ( !token.type )
goto Fail;
count = 1;
idx = 0;
cur = token.start;
limit = token.limit;
type = field->type;
/* we must detect arrays in /FontBBox */
if ( type == T1_FIELD_TYPE_BBOX )
{
T1_TokenRec token2;
FT_Byte* old_cur = parser->cursor;
FT_Byte* old_limit = parser->limit;
/* don't include delimiters */
parser->cursor = token.start + 1;
parser->limit = token.limit - 1;
ps_parser_to_token( parser, &token2 );
parser->cursor = old_cur;
parser->limit = old_limit;
if ( token2.type == T1_TOKEN_TYPE_ARRAY )
{
type = T1_FIELD_TYPE_MM_BBOX;
goto FieldArray;
}
}
else if ( token.type == T1_TOKEN_TYPE_ARRAY )
{
count = max_objects;
FieldArray:
/* if this is an array and we have no blend, an error occurs */
if ( max_objects == 0 )
goto Fail;
idx = 1;
/* don't include delimiters */
cur++;
limit--;
}
for ( ; count > 0; count--, idx++ )
{
FT_Byte* q = (FT_Byte*)objects[idx] + field->offset;
FT_Long val;
FT_String* string;
skip_spaces( &cur, limit );
switch ( type )
{
case T1_FIELD_TYPE_BOOL:
val = ps_tobool( &cur, limit );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED:
val = PS_Conv_ToFixed( &cur, limit, 0 );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED_1000:
val = PS_Conv_ToFixed( &cur, limit, 3 );
goto Store_Integer;
case T1_FIELD_TYPE_INTEGER:
val = PS_Conv_ToInt( &cur, limit );
/* fall through */
Store_Integer:
switch ( field->size )
{
case (8 / FT_CHAR_BIT):
*(FT_Byte*)q = (FT_Byte)val;
break;
case (16 / FT_CHAR_BIT):
*(FT_UShort*)q = (FT_UShort)val;
break;
case (32 / FT_CHAR_BIT):
*(FT_UInt32*)q = (FT_UInt32)val;
break;
default: /* for 64-bit systems */
*(FT_Long*)q = val;
}
break;
case T1_FIELD_TYPE_STRING:
case T1_FIELD_TYPE_KEY:
{
FT_Memory memory = parser->memory;
FT_UInt len = (FT_UInt)( limit - cur );
if ( cur >= limit )
break;
/* we allow both a string or a name */
/* for cases like /FontName (foo) def */
if ( token.type == T1_TOKEN_TYPE_KEY )
{
/* don't include leading `/' */
len--;
cur++;
}
else if ( token.type == T1_TOKEN_TYPE_STRING )
{
/* don't include delimiting parentheses */
/* XXX we don't handle <<...>> here */
/* XXX should we convert octal escapes? */
/* if so, what encoding should we use? */
cur++;
len -= 2;
}
else
{
FT_ERROR(( "ps_parser_load_field:"
" expected a name or string\n"
" "
" but found token of type %d instead\n",
token.type ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* for this to work (FT_String**)q must have been */
/* initialized to NULL */
if ( *(FT_String**)q != NULL )
{
FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n",
field->ident ));
FT_FREE( *(FT_String**)q );
*(FT_String**)q = NULL;
}
if ( FT_ALLOC( string, len + 1 ) )
goto Exit;
FT_MEM_COPY( string, cur, len );
string[len] = 0;
*(FT_String**)q = string;
}
break;
case T1_FIELD_TYPE_BBOX:
{
FT_Fixed temp[4];
FT_BBox* bbox = (FT_BBox*)q;
FT_Int result;
result = ps_tofixedarray( &cur, limit, 4, temp, 0 );
if ( result < 4 )
{
FT_ERROR(( "ps_parser_load_field:"
" expected four integers in bounding box\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
bbox->xMin = FT_RoundFix( temp[0] );
bbox->yMin = FT_RoundFix( temp[1] );
bbox->xMax = FT_RoundFix( temp[2] );
bbox->yMax = FT_RoundFix( temp[3] );
}
break;
case T1_FIELD_TYPE_MM_BBOX:
{
FT_Memory memory = parser->memory;
FT_Fixed* temp;
FT_Int result;
FT_UInt i;
if ( FT_NEW_ARRAY( temp, max_objects * 4 ) )
goto Exit;
for ( i = 0; i < 4; i++ )
{
result = ps_tofixedarray( &cur, limit, max_objects,
temp + i * max_objects, 0 );
if ( result < 0 || (FT_UInt)result < max_objects )
{
FT_ERROR(( "ps_parser_load_field:"
" expected %d integers in the %s subarray\n"
" "
" of /FontBBox in the /Blend dictionary\n",
max_objects,
i == 0 ? "first"
: ( i == 1 ? "second"
: ( i == 2 ? "third"
: "fourth" ) ) ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
skip_spaces( &cur, limit );
}
for ( i = 0; i < max_objects; i++ )
{
FT_BBox* bbox = (FT_BBox*)objects[i];
bbox->xMin = FT_RoundFix( temp[i ] );
bbox->yMin = FT_RoundFix( temp[i + max_objects] );
bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] );
bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] );
}
FT_FREE( temp );
}
break;
default:
/* an error occurred */
goto Fail;
}
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
error = FT_Err_Ok;
Exit:
return error;
Fail:
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
#define T1_MAX_TABLE_ELEMENTS 32
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field_table( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS];
T1_Token token;
FT_Int num_elements;
FT_Error error = FT_Err_Ok;
FT_Byte* old_cursor;
FT_Byte* old_limit;
T1_FieldRec fieldrec = *(T1_Field)field;
fieldrec.type = T1_FIELD_TYPE_INTEGER;
if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY ||
field->type == T1_FIELD_TYPE_BBOX )
fieldrec.type = T1_FIELD_TYPE_FIXED;
ps_parser_to_token_array( parser, elements,
T1_MAX_TABLE_ELEMENTS, &num_elements );
if ( num_elements < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( (FT_UInt)num_elements > field->array_max )
num_elements = field->array_max;
old_cursor = parser->cursor;
old_limit = parser->limit;
/* we store the elements count if necessary; */
/* we further assume that `count_offset' can't be zero */
if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 )
*(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) =
(FT_Byte)num_elements;
/* we now load each element, adjusting the field.offset on each one */
token = elements;
for ( ; num_elements > 0; num_elements--, token++ )
{
parser->cursor = token->start;
parser->limit = token->limit;
ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 );
fieldrec.offset += fieldrec.size;
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
parser->cursor = old_cursor;
parser->limit = old_limit;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Long )
ps_parser_to_int( PS_Parser parser )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToInt( &parser->cursor, parser->limit );
}
/* first character must be `<' if `delimiters' is non-zero */
FT_LOCAL_DEF( FT_Error )
ps_parser_to_bytes( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_Long* pnum_bytes,
FT_Bool delimiters )
{
FT_Error error = FT_Err_Ok;
FT_Byte* cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
if ( cur >= parser->limit )
goto Exit;
if ( delimiters )
{
if ( *cur != '<' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
*pnum_bytes = PS_Conv_ASCIIHexDecode( &cur,
parser->limit,
bytes,
max_bytes );
if ( delimiters )
{
if ( cur < parser->limit && *cur != '>' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
parser->cursor = cur;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Fixed )
ps_parser_to_fixed( PS_Parser parser,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_coord_array( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords )
{
ps_parser_skip_spaces( parser );
return ps_tocoordarray( &parser->cursor, parser->limit,
max_coords, coords );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_fixed_array( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return ps_tofixedarray( &parser->cursor, parser->limit,
max_values, values, power_ten );
}
#if 0
FT_LOCAL_DEF( FT_String* )
T1_ToString( PS_Parser parser )
{
return ps_tostring( &parser->cursor, parser->limit, parser->memory );
}
FT_LOCAL_DEF( FT_Bool )
T1_ToBool( PS_Parser parser )
{
return ps_tobool( &parser->cursor, parser->limit );
}
#endif /* 0 */
FT_LOCAL_DEF( void )
ps_parser_init( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory )
{
parser->error = FT_Err_Ok;
parser->base = base;
parser->limit = limit;
parser->cursor = base;
parser->memory = memory;
parser->funcs = ps_parser_funcs;
}
FT_LOCAL_DEF( void )
ps_parser_done( PS_Parser parser )
{
FT_UNUSED( parser );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* t1_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 should be applied. */
/* */
FT_LOCAL_DEF( void )
t1_builder_init( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot glyph,
FT_Bool hinting )
{
builder->parse_state = T1_Parse_Start;
builder->load_points = 1;
builder->face = face;
builder->glyph = glyph;
builder->memory = face->memory;
if ( glyph )
{
FT_GlyphLoader loader = glyph->internal->loader;
builder->loader = loader;
builder->base = &loader->base.outline;
builder->current = &loader->current.outline;
FT_GlyphLoader_Rewind( loader );
builder->hints_globals = size->internal;
builder->hints_funcs = 0;
if ( hinting )
builder->hints_funcs = glyph->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;
builder->funcs = t1_builder_funcs;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_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. */
/* */
FT_LOCAL_DEF( void )
t1_builder_done( T1_Builder builder )
{
FT_GlyphSlot glyph = builder->glyph;
if ( glyph )
glyph->outline = *builder->base;
}
/* check that there is enough space for `count' more points */
FT_LOCAL_DEF( FT_Error )
t1_builder_check_points( T1_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 )
t1_builder_add_point( T1_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;
point->x = FIXED_TO_INT( x );
point->y = FIXED_TO_INT( y );
*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 )
t1_builder_add_point1( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error;
error = t1_builder_check_points( builder, 1 );
if ( !error )
t1_builder_add_point( builder, x, y, 1 );
return error;
}
/* check space for a new contour, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Error error;
/* this might happen in invalid fonts */
if ( !outline )
{
FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" ));
return FT_THROW( Invalid_File_Format );
}
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 )
t1_builder_start_point( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error = FT_ERR( Invalid_File_Format );
/* test whether we are building a new contour */
if ( builder->parse_state == T1_Parse_Have_Path )
error = FT_Err_Ok;
else
{
builder->parse_state = T1_Parse_Have_Path;
error = t1_builder_add_contour( builder );
if ( !error )
error = t1_builder_add_point1( builder, x, y );
}
return error;
}
/* close the current contour */
FT_LOCAL_DEF( void )
t1_builder_close_contour( T1_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 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 the first and the last point is 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 );
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** OTHER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
t1_decrypt( FT_Byte* buffer,
FT_Offset length,
FT_UShort seed )
{
PS_Conv_EexecDecode( &buffer,
buffer + length,
buffer,
length,
&seed );
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psobjs.c | C | apache-2.0 | 49,844 |
/***************************************************************************/
/* */
/* psobjs.h */
/* */
/* Auxiliary functions for PostScript fonts (specification). */
/* */
/* Copyright 1996-2001, 2002, 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. */
/* */
/***************************************************************************/
#ifndef __PSOBJS_H__
#define __PSOBJS_H__
#include <ft2build.h>
#include FT_INTERNAL_POSTSCRIPT_AUX_H
FT_BEGIN_HEADER
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1_TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_CALLBACK_TABLE
const PS_Table_FuncsRec ps_table_funcs;
FT_CALLBACK_TABLE
const PS_Parser_FuncsRec ps_parser_funcs;
FT_CALLBACK_TABLE
const T1_Builder_FuncsRec t1_builder_funcs;
FT_LOCAL( FT_Error )
ps_table_new( PS_Table table,
FT_Int count,
FT_Memory memory );
FT_LOCAL( FT_Error )
ps_table_add( PS_Table table,
FT_Int idx,
void* object,
FT_PtrDist length );
FT_LOCAL( void )
ps_table_done( PS_Table table );
FT_LOCAL( void )
ps_table_release( PS_Table table );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
ps_parser_skip_spaces( PS_Parser parser );
FT_LOCAL( void )
ps_parser_skip_PS_token( PS_Parser parser );
FT_LOCAL( void )
ps_parser_to_token( PS_Parser parser,
T1_Token token );
FT_LOCAL( void )
ps_parser_to_token_array( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens );
FT_LOCAL( FT_Error )
ps_parser_load_field( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags );
FT_LOCAL( FT_Error )
ps_parser_load_field_table( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags );
FT_LOCAL( FT_Long )
ps_parser_to_int( PS_Parser parser );
FT_LOCAL( FT_Error )
ps_parser_to_bytes( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_Long* pnum_bytes,
FT_Bool delimiters );
FT_LOCAL( FT_Fixed )
ps_parser_to_fixed( PS_Parser parser,
FT_Int power_ten );
FT_LOCAL( FT_Int )
ps_parser_to_coord_array( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords );
FT_LOCAL( FT_Int )
ps_parser_to_fixed_array( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten );
FT_LOCAL( void )
ps_parser_init( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory );
FT_LOCAL( void )
ps_parser_done( PS_Parser parser );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
t1_builder_init( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot glyph,
FT_Bool hinting );
FT_LOCAL( void )
t1_builder_done( T1_Builder builder );
FT_LOCAL( FT_Error )
t1_builder_check_points( T1_Builder builder,
FT_Int count );
FT_LOCAL( void )
t1_builder_add_point( T1_Builder builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag );
FT_LOCAL( FT_Error )
t1_builder_add_point1( T1_Builder builder,
FT_Pos x,
FT_Pos y );
FT_LOCAL( FT_Error )
t1_builder_add_contour( T1_Builder builder );
FT_LOCAL( FT_Error )
t1_builder_start_point( T1_Builder builder,
FT_Pos x,
FT_Pos y );
FT_LOCAL( void )
t1_builder_close_contour( T1_Builder builder );
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** OTHER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL( void )
t1_decrypt( FT_Byte* buffer,
FT_Offset length,
FT_UShort seed );
FT_END_HEADER
#endif /* __PSOBJS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/psobjs.h | C | apache-2.0 | 7,461 |
#
# FreeType 2 PSaux driver configuration rules
#
# Copyright 1996-2000, 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.
# PSAUX driver directory
#
PSAUX_DIR := $(SRC_DIR)/psaux
# compilation flags for the driver
#
PSAUX_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(PSAUX_DIR))
# PSAUX driver sources (i.e., C files)
#
PSAUX_DRV_SRC := $(PSAUX_DIR)/psobjs.c \
$(PSAUX_DIR)/t1decode.c \
$(PSAUX_DIR)/t1cmap.c \
$(PSAUX_DIR)/afmparse.c \
$(PSAUX_DIR)/psconv.c \
$(PSAUX_DIR)/psauxmod.c
# PSAUX driver headers
#
PSAUX_DRV_H := $(PSAUX_DRV_SRC:%c=%h) \
$(PSAUX_DIR)/psauxerr.h
# PSAUX driver object(s)
#
# PSAUX_DRV_OBJ_M is used during `multi' builds.
# PSAUX_DRV_OBJ_S is used during `single' builds.
#
PSAUX_DRV_OBJ_M := $(PSAUX_DRV_SRC:$(PSAUX_DIR)/%.c=$(OBJ_DIR)/%.$O)
PSAUX_DRV_OBJ_S := $(OBJ_DIR)/psaux.$O
# PSAUX driver source file for single build
#
PSAUX_DRV_SRC_S := $(PSAUX_DIR)/psaux.c
# PSAUX driver - single object
#
$(PSAUX_DRV_OBJ_S): $(PSAUX_DRV_SRC_S) $(PSAUX_DRV_SRC) \
$(FREETYPE_H) $(PSAUX_DRV_H)
$(PSAUX_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(PSAUX_DRV_SRC_S))
# PSAUX driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(PSAUX_DIR)/%.c $(FREETYPE_H) $(PSAUX_DRV_H)
$(PSAUX_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(PSAUX_DRV_OBJ_S)
DRV_OBJS_M += $(PSAUX_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/psaux/rules.mk | Makefile | apache-2.0 | 1,828 |
/***************************************************************************/
/* */
/* t1cmap.c */
/* */
/* Type 1 character map support (body). */
/* */
/* Copyright 2002, 2003, 2006, 2007, 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. */
/* */
/***************************************************************************/
#include "t1cmap.h"
#include FT_INTERNAL_DEBUG_H
#include "psauxerr.h"
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 STANDARD (AND EXPERT) ENCODING CMAPS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
t1_cmap_std_init( T1_CMapStd cmap,
FT_Int is_expert )
{
T1_Face face = (T1_Face)FT_CMAP_FACE( cmap );
FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)face->psnames;
cmap->num_glyphs = face->type1.num_glyphs;
cmap->glyph_names = (const char* const*)face->type1.glyph_names;
cmap->sid_to_string = psnames->adobe_std_strings;
cmap->code_to_sid = is_expert ? psnames->adobe_expert_encoding
: psnames->adobe_std_encoding;
FT_ASSERT( cmap->code_to_sid != NULL );
}
FT_CALLBACK_DEF( void )
t1_cmap_std_done( T1_CMapStd cmap )
{
cmap->num_glyphs = 0;
cmap->glyph_names = NULL;
cmap->sid_to_string = NULL;
cmap->code_to_sid = NULL;
}
FT_CALLBACK_DEF( FT_UInt )
t1_cmap_std_char_index( T1_CMapStd cmap,
FT_UInt32 char_code )
{
FT_UInt result = 0;
if ( char_code < 256 )
{
FT_UInt code, n;
const char* glyph_name;
/* convert character code to Adobe SID string */
code = cmap->code_to_sid[char_code];
glyph_name = cmap->sid_to_string( code );
/* look for the corresponding glyph name */
for ( n = 0; n < cmap->num_glyphs; n++ )
{
const char* gname = cmap->glyph_names[n];
if ( gname && gname[0] == glyph_name[0] &&
ft_strcmp( gname, glyph_name ) == 0 )
{
result = n;
break;
}
}
}
return result;
}
FT_CALLBACK_DEF( FT_UInt32 )
t1_cmap_std_char_next( T1_CMapStd cmap,
FT_UInt32 *pchar_code )
{
FT_UInt result = 0;
FT_UInt32 char_code = *pchar_code + 1;
while ( char_code < 256 )
{
result = t1_cmap_std_char_index( cmap, char_code );
if ( result != 0 )
goto Exit;
char_code++;
}
char_code = 0;
Exit:
*pchar_code = char_code;
return result;
}
FT_CALLBACK_DEF( FT_Error )
t1_cmap_standard_init( T1_CMapStd cmap )
{
t1_cmap_std_init( cmap, 0 );
return 0;
}
FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec
t1_cmap_standard_class_rec =
{
sizeof ( T1_CMapStdRec ),
(FT_CMap_InitFunc) t1_cmap_standard_init,
(FT_CMap_DoneFunc) t1_cmap_std_done,
(FT_CMap_CharIndexFunc)t1_cmap_std_char_index,
(FT_CMap_CharNextFunc) t1_cmap_std_char_next,
NULL, NULL, NULL, NULL, NULL
};
FT_CALLBACK_DEF( FT_Error )
t1_cmap_expert_init( T1_CMapStd cmap )
{
t1_cmap_std_init( cmap, 1 );
return 0;
}
FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec
t1_cmap_expert_class_rec =
{
sizeof ( T1_CMapStdRec ),
(FT_CMap_InitFunc) t1_cmap_expert_init,
(FT_CMap_DoneFunc) t1_cmap_std_done,
(FT_CMap_CharIndexFunc)t1_cmap_std_char_index,
(FT_CMap_CharNextFunc) t1_cmap_std_char_next,
NULL, NULL, NULL, NULL, NULL
};
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 CUSTOM ENCODING CMAP *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_CALLBACK_DEF( FT_Error )
t1_cmap_custom_init( T1_CMapCustom cmap )
{
T1_Face face = (T1_Face)FT_CMAP_FACE( cmap );
T1_Encoding encoding = &face->type1.encoding;
cmap->first = encoding->code_first;
cmap->count = (FT_UInt)( encoding->code_last - cmap->first );
cmap->indices = encoding->char_index;
FT_ASSERT( cmap->indices != NULL );
FT_ASSERT( encoding->code_first <= encoding->code_last );
return 0;
}
FT_CALLBACK_DEF( void )
t1_cmap_custom_done( T1_CMapCustom cmap )
{
cmap->indices = NULL;
cmap->first = 0;
cmap->count = 0;
}
FT_CALLBACK_DEF( FT_UInt )
t1_cmap_custom_char_index( T1_CMapCustom cmap,
FT_UInt32 char_code )
{
FT_UInt result = 0;
if ( ( char_code >= cmap->first ) &&
( char_code < ( cmap->first + cmap->count ) ) )
result = cmap->indices[char_code];
return result;
}
FT_CALLBACK_DEF( FT_UInt32 )
t1_cmap_custom_char_next( T1_CMapCustom cmap,
FT_UInt32 *pchar_code )
{
FT_UInt result = 0;
FT_UInt32 char_code = *pchar_code;
++char_code;
if ( char_code < cmap->first )
char_code = cmap->first;
for ( ; char_code < ( cmap->first + cmap->count ); char_code++ )
{
result = cmap->indices[char_code];
if ( result != 0 )
goto Exit;
}
char_code = 0;
Exit:
*pchar_code = char_code;
return result;
}
FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec
t1_cmap_custom_class_rec =
{
sizeof ( T1_CMapCustomRec ),
(FT_CMap_InitFunc) t1_cmap_custom_init,
(FT_CMap_DoneFunc) t1_cmap_custom_done,
(FT_CMap_CharIndexFunc)t1_cmap_custom_char_index,
(FT_CMap_CharNextFunc) t1_cmap_custom_char_next,
NULL, NULL, NULL, NULL, NULL
};
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 SYNTHETIC UNICODE ENCODING CMAP *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_CALLBACK_DEF( const char * )
psaux_get_glyph_name( T1_Face face,
FT_UInt idx )
{
return face->type1.glyph_names[idx];
}
FT_CALLBACK_DEF( FT_Error )
t1_cmap_unicode_init( PS_Unicodes unicodes )
{
T1_Face face = (T1_Face)FT_CMAP_FACE( unicodes );
FT_Memory memory = FT_FACE_MEMORY( face );
FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)face->psnames;
return psnames->unicodes_init( memory,
unicodes,
face->type1.num_glyphs,
(PS_GetGlyphNameFunc)&psaux_get_glyph_name,
(PS_FreeGlyphNameFunc)NULL,
(FT_Pointer)face );
}
FT_CALLBACK_DEF( void )
t1_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 )
t1_cmap_unicode_char_index( PS_Unicodes unicodes,
FT_UInt32 char_code )
{
T1_Face face = (T1_Face)FT_CMAP_FACE( unicodes );
FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)face->psnames;
return psnames->unicodes_char_index( unicodes, char_code );
}
FT_CALLBACK_DEF( FT_UInt32 )
t1_cmap_unicode_char_next( PS_Unicodes unicodes,
FT_UInt32 *pchar_code )
{
T1_Face face = (T1_Face)FT_CMAP_FACE( unicodes );
FT_Service_PsCMaps psnames = (FT_Service_PsCMaps)face->psnames;
return psnames->unicodes_char_next( unicodes, pchar_code );
}
FT_CALLBACK_TABLE_DEF const FT_CMap_ClassRec
t1_cmap_unicode_class_rec =
{
sizeof ( PS_UnicodesRec ),
(FT_CMap_InitFunc) t1_cmap_unicode_init,
(FT_CMap_DoneFunc) t1_cmap_unicode_done,
(FT_CMap_CharIndexFunc)t1_cmap_unicode_char_index,
(FT_CMap_CharNextFunc) t1_cmap_unicode_char_next,
NULL, NULL, NULL, NULL, NULL
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/t1cmap.c | C | apache-2.0 | 9,913 |
/***************************************************************************/
/* */
/* t1cmap.h */
/* */
/* Type 1 character map 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 __T1CMAP_H__
#define __T1CMAP_H__
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_TYPE1_TYPES_H
FT_BEGIN_HEADER
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 STANDARD (AND EXPERT) ENCODING CMAPS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* standard (and expert) encoding cmaps */
typedef struct T1_CMapStdRec_* T1_CMapStd;
typedef struct T1_CMapStdRec_
{
FT_CMapRec cmap;
const FT_UShort* code_to_sid;
PS_Adobe_Std_StringsFunc sid_to_string;
FT_UInt num_glyphs;
const char* const* glyph_names;
} T1_CMapStdRec;
FT_CALLBACK_TABLE const FT_CMap_ClassRec
t1_cmap_standard_class_rec;
FT_CALLBACK_TABLE const FT_CMap_ClassRec
t1_cmap_expert_class_rec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 CUSTOM ENCODING CMAP *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct T1_CMapCustomRec_* T1_CMapCustom;
typedef struct T1_CMapCustomRec_
{
FT_CMapRec cmap;
FT_UInt first;
FT_UInt count;
FT_UShort* indices;
} T1_CMapCustomRec;
FT_CALLBACK_TABLE const FT_CMap_ClassRec
t1_cmap_custom_class_rec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 SYNTHETIC UNICODE ENCODING CMAP *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* unicode (synthetic) cmaps */
FT_CALLBACK_TABLE const FT_CMap_ClassRec
t1_cmap_unicode_class_rec;
/* */
FT_END_HEADER
#endif /* __T1CMAP_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/t1cmap.h | C | apache-2.0 | 4,004 |
/***************************************************************************/
/* */
/* t1decode.c */
/* */
/* PostScript Type 1 decoding routines (body). */
/* */
/* Copyright 2000-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_CALC_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
#include FT_OUTLINE_H
#include "t1decode.h"
#include "psobjs.h"
#include "psauxerr.h"
/* ensure proper sign extension */
#define Fix2Int( f ) ( (FT_Int)(FT_Short)( (f) >> 16 ) )
/*************************************************************************/
/* */
/* 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_t1decode
typedef enum T1_Operator_
{
op_none = 0,
op_endchar,
op_hsbw,
op_seac,
op_sbw,
op_closepath,
op_hlineto,
op_hmoveto,
op_hvcurveto,
op_rlineto,
op_rmoveto,
op_rrcurveto,
op_vhcurveto,
op_vlineto,
op_vmoveto,
op_dotsection,
op_hstem,
op_hstem3,
op_vstem,
op_vstem3,
op_div,
op_callothersubr,
op_callsubr,
op_pop,
op_return,
op_setcurrentpoint,
op_unknown15,
op_max /* never remove this one */
} T1_Operator;
static
const FT_Int t1_args_count[op_max] =
{
0, /* none */
0, /* endchar */
2, /* hsbw */
5, /* seac */
4, /* sbw */
0, /* closepath */
1, /* hlineto */
1, /* hmoveto */
4, /* hvcurveto */
2, /* rlineto */
2, /* rmoveto */
6, /* rrcurveto */
4, /* vhcurveto */
1, /* vlineto */
1, /* vmoveto */
0, /* dotsection */
2, /* hstem */
6, /* hstem3 */
2, /* vstem */
6, /* vstem3 */
2, /* div */
-1, /* callothersubr */
1, /* callsubr */
0, /* pop */
0, /* return */
2, /* setcurrentpoint */
2 /* opcode 15 (undocumented and obsolete) */
};
/*************************************************************************/
/* */
/* <Function> */
/* t1_lookup_glyph_by_stdcharcode */
/* */
/* <Description> */
/* Looks up a given glyph by its StandardEncoding charcode. Used to */
/* implement the SEAC Type 1 operator. */
/* */
/* <Input> */
/* face :: The current face object. */
/* */
/* charcode :: The character code to look for. */
/* */
/* <Return> */
/* A glyph index in the font face. Returns -1 if the corresponding */
/* glyph wasn't found. */
/* */
static FT_Int
t1_lookup_glyph_by_stdcharcode( T1_Decoder decoder,
FT_Int charcode )
{
FT_UInt n;
const FT_String* glyph_name;
FT_Service_PsCMaps psnames = decoder->psnames;
/* check range of standard char code */
if ( charcode < 0 || charcode > 255 )
return -1;
glyph_name = psnames->adobe_std_strings(
psnames->adobe_std_encoding[charcode]);
for ( n = 0; n < decoder->num_glyphs; n++ )
{
FT_String* name = (FT_String*)decoder->glyph_names[n];
if ( name &&
name[0] == glyph_name[0] &&
ft_strcmp( name, glyph_name ) == 0 )
return n;
}
return -1;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1operator_seac */
/* */
/* <Description> */
/* Implements the `seac' Type 1 operator for a Type 1 decoder. */
/* */
/* <Input> */
/* decoder :: The current CID decoder. */
/* */
/* asb :: The accent's side bearing. */
/* */
/* adx :: The horizontal offset of the accent. */
/* */
/* ady :: The vertical offset of the accent. */
/* */
/* bchar :: The base character's StandardEncoding charcode. */
/* */
/* achar :: The accent character's StandardEncoding charcode. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
static FT_Error
t1operator_seac( T1_Decoder decoder,
FT_Pos asb,
FT_Pos adx,
FT_Pos ady,
FT_Int bchar,
FT_Int achar )
{
FT_Error error;
FT_Int bchar_index, achar_index;
#if 0
FT_Int n_base_points;
FT_Outline* base = decoder->builder.base;
#endif
FT_Vector left_bearing, advance;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
T1_Face face = (T1_Face)decoder->builder.face;
#endif
if ( decoder->seac )
{
FT_ERROR(( "t1operator_seac: invalid nested seac\n" ));
return FT_THROW( Syntax_Error );
}
if ( decoder->builder.metrics_only )
{
FT_ERROR(( "t1operator_seac: unexpected seac\n" ));
return FT_THROW( Syntax_Error );
}
/* seac weirdness */
adx += decoder->builder.left_bearing.x;
/* `glyph_names' is set to 0 for CID fonts which do not */
/* include an encoding. How can we deal with these? */
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( decoder->glyph_names == 0 &&
!face->root.internal->incremental_interface )
#else
if ( decoder->glyph_names == 0 )
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
{
FT_ERROR(( "t1operator_seac:"
" glyph names table not available in this font\n" ));
return FT_THROW( Syntax_Error );
}
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( face->root.internal->incremental_interface )
{
/* the caller must handle the font encoding also */
bchar_index = bchar;
achar_index = achar;
}
else
#endif
{
bchar_index = t1_lookup_glyph_by_stdcharcode( decoder, bchar );
achar_index = t1_lookup_glyph_by_stdcharcode( decoder, achar );
}
if ( bchar_index < 0 || achar_index < 0 )
{
FT_ERROR(( "t1operator_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 ( decoder->builder.no_recurse )
{
FT_GlyphSlot glyph = (FT_GlyphSlot)decoder->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)FIXED_TO_INT( adx - asb );
subg->arg2 = (FT_Int)FIXED_TO_INT( ady );
/* 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;
goto Exit;
}
/* First load `bchar' in builder */
/* now load the unscaled outline */
FT_GlyphLoader_Prepare( decoder->builder.loader ); /* prepare loader */
/* the seac operator must not be nested */
decoder->seac = TRUE;
error = t1_decoder_parse_glyph( decoder, bchar_index );
decoder->seac = FALSE;
if ( error )
goto Exit;
/* save the left bearing and width of the base character */
/* as they will be erased by the next load. */
left_bearing = decoder->builder.left_bearing;
advance = decoder->builder.advance;
decoder->builder.left_bearing.x = 0;
decoder->builder.left_bearing.y = 0;
decoder->builder.pos_x = adx - asb;
decoder->builder.pos_y = ady;
/* Now load `achar' on top of */
/* the base outline */
/* the seac operator must not be nested */
decoder->seac = TRUE;
error = t1_decoder_parse_glyph( decoder, achar_index );
decoder->seac = FALSE;
if ( error )
goto Exit;
/* restore the left side bearing and */
/* advance width of the base character */
decoder->builder.left_bearing = left_bearing;
decoder->builder.advance = advance;
decoder->builder.pos_x = 0;
decoder->builder.pos_y = 0;
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_decoder_parse_charstrings */
/* */
/* <Description> */
/* Parses a given Type 1 charstrings program. */
/* */
/* <Input> */
/* decoder :: The current Type 1 decoder. */
/* */
/* charstring_base :: The base address 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 )
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* 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;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
ft_memset( &decoder->buildchar[0],
0,
sizeof ( decoder->buildchar[0] ) * decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %ld", value ));
else
FT_TRACE4(( " %ld", Fix2Int( value ) ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( decoder->flex_state == 0 ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 6 ) )
!= FT_Err_Ok )
goto Fail;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( decoder->flex_state == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
break;
case 3: /* change hints */
if ( arg_cnt != 1 )
goto Unexpected_OtherSubr;
known_othersubr_result_cnt = 1;
if ( hinter )
hinter->reset( hinter->hints, builder->current->n_points );
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_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 );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; ++i )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( ( error = t1_builder_add_point1( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
++top;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( idx < 0 || idx >= (FT_Int)decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
/* parse a single Type 1 glyph */
FT_LOCAL_DEF( FT_Error )
t1_decoder_parse_glyph( T1_Decoder decoder,
FT_UInt glyph )
{
return decoder->parse_callback( decoder, glyph );
}
/* initialize T1 decoder */
FT_LOCAL_DEF( FT_Error )
t1_decoder_init( T1_Decoder decoder,
FT_Face face,
FT_Size size,
FT_GlyphSlot slot,
FT_Byte** glyph_names,
PS_Blend blend,
FT_Bool hinting,
FT_Render_Mode hint_mode,
T1_Decoder_Callback parse_callback )
{
FT_MEM_ZERO( decoder, sizeof ( *decoder ) );
/* retrieve PSNames interface from list of current modules */
{
FT_Service_PsCMaps psnames = 0;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
if ( !psnames )
{
FT_ERROR(( "t1_decoder_init:"
" the `psnames' module is not available\n" ));
return FT_THROW( Unimplemented_Feature );
}
decoder->psnames = psnames;
}
t1_builder_init( &decoder->builder, face, size, slot, hinting );
/* decoder->buildchar and decoder->len_buildchar have to be */
/* initialized by the caller since we cannot know the length */
/* of the BuildCharArray */
decoder->num_glyphs = (FT_UInt)face->num_glyphs;
decoder->glyph_names = glyph_names;
decoder->hint_mode = hint_mode;
decoder->blend = blend;
decoder->parse_callback = parse_callback;
decoder->funcs = t1_decoder_funcs;
return FT_Err_Ok;
}
/* finalize T1 decoder */
FT_LOCAL_DEF( void )
t1_decoder_done( T1_Decoder decoder )
{
t1_builder_done( &decoder->builder );
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/t1decode.c | C | apache-2.0 | 51,012 |
/***************************************************************************/
/* */
/* t1decode.h */
/* */
/* PostScript Type 1 decoding routines (specification). */
/* */
/* Copyright 2000-2001, 2002, 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. */
/* */
/***************************************************************************/
#ifndef __T1DECODE_H__
#define __T1DECODE_H__
#include <ft2build.h>
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include FT_INTERNAL_TYPE1_TYPES_H
FT_BEGIN_HEADER
FT_CALLBACK_TABLE
const T1_Decoder_FuncsRec t1_decoder_funcs;
FT_LOCAL( FT_Error )
t1_decoder_parse_glyph( T1_Decoder decoder,
FT_UInt glyph_index );
FT_LOCAL( FT_Error )
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* base,
FT_UInt len );
FT_LOCAL( FT_Error )
t1_decoder_init( T1_Decoder decoder,
FT_Face face,
FT_Size size,
FT_GlyphSlot slot,
FT_Byte** glyph_names,
PS_Blend blend,
FT_Bool hinting,
FT_Render_Mode hint_mode,
T1_Decoder_Callback parse_glyph );
FT_LOCAL( void )
t1_decoder_done( T1_Decoder decoder );
FT_END_HEADER
#endif /* __T1DECODE_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/psaux/t1decode.h | C | apache-2.0 | 2,368 |
#
# FreeType 2 PSHinter module definition
#
# Copyright 1996-2001, 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 += PSHINTER_MODULE
define PSHINTER_MODULE
$(OPEN_DRIVER) FT_Module_Class, pshinter_module_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)pshinter $(ECHO_DRIVER_DESC)Postscript hinter module$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/module.mk | Makefile | apache-2.0 | 664 |
/***************************************************************************/
/* */
/* pshalgo.c */
/* */
/* PostScript hinting algorithm (body). */
/* */
/* Copyright 2001-2010, 2012-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_OBJECTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_CALC_H
#include "pshalgo.h"
#include "pshnterr.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pshalgo2
#ifdef DEBUG_HINTER
PSH_Hint_Table ps_debug_hint_table = 0;
PSH_HintFunc ps_debug_hint_func = 0;
PSH_Glyph ps_debug_glyph = 0;
#endif
#define COMPUTE_INFLEXS /* compute inflection points to optimize `S' */
/* and similar glyphs */
#define STRONGER /* slightly increase the contrast of smooth */
/* hinting */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** BASIC HINTS RECORDINGS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* return true if two stem hints overlap */
static FT_Int
psh_hint_overlap( PSH_Hint hint1,
PSH_Hint hint2 )
{
return hint1->org_pos + hint1->org_len >= hint2->org_pos &&
hint2->org_pos + hint2->org_len >= hint1->org_pos;
}
/* destroy hints table */
static void
psh_hint_table_done( PSH_Hint_Table table,
FT_Memory memory )
{
FT_FREE( table->zones );
table->num_zones = 0;
table->zone = 0;
FT_FREE( table->sort );
FT_FREE( table->hints );
table->num_hints = 0;
table->max_hints = 0;
table->sort_global = 0;
}
/* deactivate all hints in a table */
static void
psh_hint_table_deactivate( PSH_Hint_Table table )
{
FT_UInt count = table->max_hints;
PSH_Hint hint = table->hints;
for ( ; count > 0; count--, hint++ )
{
psh_hint_deactivate( hint );
hint->order = -1;
}
}
/* internal function to record a new hint */
static void
psh_hint_table_record( PSH_Hint_Table table,
FT_UInt idx )
{
PSH_Hint hint = table->hints + idx;
if ( idx >= table->max_hints )
{
FT_TRACE0(( "psh_hint_table_record: invalid hint index %d\n", idx ));
return;
}
/* ignore active hints */
if ( psh_hint_is_active( hint ) )
return;
psh_hint_activate( hint );
/* now scan the current active hint set to check */
/* whether `hint' overlaps with another hint */
{
PSH_Hint* sorted = table->sort_global;
FT_UInt count = table->num_hints;
PSH_Hint hint2;
hint->parent = 0;
for ( ; count > 0; count--, sorted++ )
{
hint2 = sorted[0];
if ( psh_hint_overlap( hint, hint2 ) )
{
hint->parent = hint2;
break;
}
}
}
if ( table->num_hints < table->max_hints )
table->sort_global[table->num_hints++] = hint;
else
FT_TRACE0(( "psh_hint_table_record: too many sorted hints! BUG!\n" ));
}
static void
psh_hint_table_record_mask( PSH_Hint_Table table,
PS_Mask hint_mask )
{
FT_Int mask = 0, val = 0;
FT_Byte* cursor = hint_mask->bytes;
FT_UInt idx, limit;
limit = hint_mask->num_bits;
for ( idx = 0; idx < limit; idx++ )
{
if ( mask == 0 )
{
val = *cursor++;
mask = 0x80;
}
if ( val & mask )
psh_hint_table_record( table, idx );
mask >>= 1;
}
}
/* create hints table */
static FT_Error
psh_hint_table_init( PSH_Hint_Table table,
PS_Hint_Table hints,
PS_Mask_Table hint_masks,
PS_Mask_Table counter_masks,
FT_Memory memory )
{
FT_UInt count;
FT_Error error;
FT_UNUSED( counter_masks );
count = hints->num_hints;
/* allocate our tables */
if ( FT_NEW_ARRAY( table->sort, 2 * count ) ||
FT_NEW_ARRAY( table->hints, count ) ||
FT_NEW_ARRAY( table->zones, 2 * count + 1 ) )
goto Exit;
table->max_hints = count;
table->sort_global = table->sort + count;
table->num_hints = 0;
table->num_zones = 0;
table->zone = 0;
/* initialize the `table->hints' array */
{
PSH_Hint write = table->hints;
PS_Hint read = hints->hints;
for ( ; count > 0; count--, write++, read++ )
{
write->org_pos = read->pos;
write->org_len = read->len;
write->flags = read->flags;
}
}
/* we now need to determine the initial `parent' stems; first */
/* activate the hints that are given by the initial hint masks */
if ( hint_masks )
{
PS_Mask mask = hint_masks->masks;
count = hint_masks->num_masks;
table->hint_masks = hint_masks;
for ( ; count > 0; count--, mask++ )
psh_hint_table_record_mask( table, mask );
}
/* finally, do a linear parse in case some hints were left alone */
if ( table->num_hints != table->max_hints )
{
FT_UInt idx;
FT_TRACE0(( "psh_hint_table_init: missing/incorrect hint masks\n" ));
count = table->max_hints;
for ( idx = 0; idx < count; idx++ )
psh_hint_table_record( table, idx );
}
Exit:
return error;
}
static void
psh_hint_table_activate_mask( PSH_Hint_Table table,
PS_Mask hint_mask )
{
FT_Int mask = 0, val = 0;
FT_Byte* cursor = hint_mask->bytes;
FT_UInt idx, limit, count;
limit = hint_mask->num_bits;
count = 0;
psh_hint_table_deactivate( table );
for ( idx = 0; idx < limit; idx++ )
{
if ( mask == 0 )
{
val = *cursor++;
mask = 0x80;
}
if ( val & mask )
{
PSH_Hint hint = &table->hints[idx];
if ( !psh_hint_is_active( hint ) )
{
FT_UInt count2;
#if 0
PSH_Hint* sort = table->sort;
PSH_Hint hint2;
for ( count2 = count; count2 > 0; count2--, sort++ )
{
hint2 = sort[0];
if ( psh_hint_overlap( hint, hint2 ) )
FT_TRACE0(( "psh_hint_table_activate_mask:"
" found overlapping hints\n" ))
}
#else
count2 = 0;
#endif
if ( count2 == 0 )
{
psh_hint_activate( hint );
if ( count < table->max_hints )
table->sort[count++] = hint;
else
FT_TRACE0(( "psh_hint_tableactivate_mask:"
" too many active hints\n" ));
}
}
}
mask >>= 1;
}
table->num_hints = count;
/* now, sort the hints; they are guaranteed to not overlap */
/* so we can compare their "org_pos" field directly */
{
FT_Int i1, i2;
PSH_Hint hint1, hint2;
PSH_Hint* sort = table->sort;
/* a simple bubble sort will do, since in 99% of cases, the hints */
/* will be already sorted -- and the sort will be linear */
for ( i1 = 1; i1 < (FT_Int)count; i1++ )
{
hint1 = sort[i1];
for ( i2 = i1 - 1; i2 >= 0; i2-- )
{
hint2 = sort[i2];
if ( hint2->org_pos < hint1->org_pos )
break;
sort[i2 + 1] = hint2;
sort[i2] = hint1;
}
}
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HINTS GRID-FITTING AND OPTIMIZATION *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#if 1
static FT_Pos
psh_dimension_quantize_len( PSH_Dimension dim,
FT_Pos len,
FT_Bool do_snapping )
{
if ( len <= 64 )
len = 64;
else
{
FT_Pos delta = len - dim->stdw.widths[0].cur;
if ( delta < 0 )
delta = -delta;
if ( delta < 40 )
{
len = dim->stdw.widths[0].cur;
if ( len < 48 )
len = 48;
}
if ( len < 3 * 64 )
{
delta = ( len & 63 );
len &= -64;
if ( delta < 10 )
len += delta;
else if ( delta < 32 )
len += 10;
else if ( delta < 54 )
len += 54;
else
len += delta;
}
else
len = FT_PIX_ROUND( len );
}
if ( do_snapping )
len = FT_PIX_ROUND( len );
return len;
}
#endif /* 0 */
#ifdef DEBUG_HINTER
static void
ps_simple_scale( PSH_Hint_Table table,
FT_Fixed scale,
FT_Fixed delta,
FT_Int dimension )
{
FT_UInt count;
for ( count = 0; count < table->max_hints; count++ )
{
PSH_Hint hint = table->hints + count;
hint->cur_pos = FT_MulFix( hint->org_pos, scale ) + delta;
hint->cur_len = FT_MulFix( hint->org_len, scale );
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
}
}
#endif /* DEBUG_HINTER */
static FT_Fixed
psh_hint_snap_stem_side_delta( FT_Fixed pos,
FT_Fixed len )
{
FT_Fixed delta1 = FT_PIX_ROUND( pos ) - pos;
FT_Fixed delta2 = FT_PIX_ROUND( pos + len ) - pos - len;
if ( FT_ABS( delta1 ) <= FT_ABS( delta2 ) )
return delta1;
else
return delta2;
}
static void
psh_hint_align( PSH_Hint hint,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( !psh_hint_is_fitted( hint ) )
{
FT_Pos pos = FT_MulFix( hint->org_pos, scale ) + delta;
FT_Pos len = FT_MulFix( hint->org_len, scale );
FT_Int do_snapping;
FT_Pos fit_len;
PSH_AlignmentRec align;
/* ignore stem alignments when requested through the hint flags */
if ( ( dimension == 0 && !glyph->do_horz_hints ) ||
( dimension == 1 && !glyph->do_vert_hints ) )
{
hint->cur_pos = pos;
hint->cur_len = len;
psh_hint_set_fitted( hint );
return;
}
/* perform stem snapping when requested - this is necessary
* for monochrome and LCD hinting modes only
*/
do_snapping = ( dimension == 0 && glyph->do_horz_snapping ) ||
( dimension == 1 && glyph->do_vert_snapping );
hint->cur_len = fit_len = len;
/* check blue zones for horizontal stems */
align.align = PSH_BLUE_ALIGN_NONE;
align.align_bot = align.align_top = 0;
if ( dimension == 1 )
psh_blues_snap_stem( &globals->blues,
hint->org_pos + hint->org_len,
hint->org_pos,
&align );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
/* the top of the stem is aligned against a blue zone */
hint->cur_pos = align.align_top - fit_len;
break;
case PSH_BLUE_ALIGN_BOT:
/* the bottom of the stem is aligned against a blue zone */
hint->cur_pos = align.align_bot;
break;
case PSH_BLUE_ALIGN_TOP | PSH_BLUE_ALIGN_BOT:
/* both edges of the stem are aligned against blue zones */
hint->cur_pos = align.align_bot;
hint->cur_len = align.align_top - align.align_bot;
break;
default:
{
PSH_Hint parent = hint->parent;
if ( parent )
{
FT_Pos par_org_center, par_cur_center;
FT_Pos cur_org_center, cur_delta;
/* ensure that parent is already fitted */
if ( !psh_hint_is_fitted( parent ) )
psh_hint_align( parent, globals, dimension, glyph );
/* keep original relation between hints, this is, use the */
/* scaled distance between the centers of the hints to */
/* compute the new position */
par_org_center = parent->org_pos + ( parent->org_len >> 1 );
par_cur_center = parent->cur_pos + ( parent->cur_len >> 1 );
cur_org_center = hint->org_pos + ( hint->org_len >> 1 );
cur_delta = FT_MulFix( cur_org_center - par_org_center, scale );
pos = par_cur_center + cur_delta - ( len >> 1 );
}
hint->cur_pos = pos;
hint->cur_len = fit_len;
/* Stem adjustment tries to snap stem widths to standard
* ones. This is important to prevent unpleasant rounding
* artefacts.
*/
if ( glyph->do_stem_adjust )
{
if ( len <= 64 )
{
/* the stem is less than one pixel; we will center it
* around the nearest pixel center
*/
if ( len >= 32 )
{
/* This is a special case where we also widen the stem
* and align it to the pixel grid.
*
* stem_center = pos + (len/2)
* nearest_pixel_center = FT_ROUND(stem_center-32)+32
* new_pos = nearest_pixel_center-32
* = FT_ROUND(stem_center-32)
* = FT_FLOOR(stem_center-32+32)
* = FT_FLOOR(stem_center)
* new_len = 64
*/
pos = FT_PIX_FLOOR( pos + ( len >> 1 ) );
len = 64;
}
else if ( len > 0 )
{
/* This is a very small stem; we simply align it to the
* pixel grid, trying to find the minimum displacement.
*
* left = pos
* right = pos + len
* left_nearest_edge = ROUND(pos)
* right_nearest_edge = ROUND(right)
*
* if ( ABS(left_nearest_edge - left) <=
* ABS(right_nearest_edge - right) )
* new_pos = left
* else
* new_pos = right
*/
FT_Pos left_nearest = FT_PIX_ROUND( pos );
FT_Pos right_nearest = FT_PIX_ROUND( pos + len );
FT_Pos left_disp = left_nearest - pos;
FT_Pos right_disp = right_nearest - ( pos + len );
if ( left_disp < 0 )
left_disp = -left_disp;
if ( right_disp < 0 )
right_disp = -right_disp;
if ( left_disp <= right_disp )
pos = left_nearest;
else
pos = right_nearest;
}
else
{
/* this is a ghost stem; we simply round it */
pos = FT_PIX_ROUND( pos );
}
}
else
{
len = psh_dimension_quantize_len( dim, len, 0 );
}
}
/* now that we have a good hinted stem width, try to position */
/* the stem along a pixel grid integer coordinate */
hint->cur_pos = pos + psh_hint_snap_stem_side_delta( pos, len );
hint->cur_len = len;
}
}
if ( do_snapping )
{
pos = hint->cur_pos;
len = hint->cur_len;
if ( len < 64 )
len = 64;
else
len = FT_PIX_ROUND( len );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
hint->cur_pos = align.align_top - len;
hint->cur_len = len;
break;
case PSH_BLUE_ALIGN_BOT:
hint->cur_len = len;
break;
case PSH_BLUE_ALIGN_BOT | PSH_BLUE_ALIGN_TOP:
/* don't touch */
break;
default:
hint->cur_len = len;
if ( len & 64 )
pos = FT_PIX_FLOOR( pos + ( len >> 1 ) ) + 32;
else
pos = FT_PIX_ROUND( pos + ( len >> 1 ) );
hint->cur_pos = pos - ( len >> 1 );
hint->cur_len = len;
}
}
psh_hint_set_fitted( hint );
#ifdef DEBUG_HINTER
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
#endif
}
}
#if 0 /* not used for now, experimental */
/*
* A variant to perform "light" hinting (i.e. FT_RENDER_MODE_LIGHT)
* of stems
*/
static void
psh_hint_align_light( PSH_Hint hint,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( !psh_hint_is_fitted( hint ) )
{
FT_Pos pos = FT_MulFix( hint->org_pos, scale ) + delta;
FT_Pos len = FT_MulFix( hint->org_len, scale );
FT_Pos fit_len;
PSH_AlignmentRec align;
/* ignore stem alignments when requested through the hint flags */
if ( ( dimension == 0 && !glyph->do_horz_hints ) ||
( dimension == 1 && !glyph->do_vert_hints ) )
{
hint->cur_pos = pos;
hint->cur_len = len;
psh_hint_set_fitted( hint );
return;
}
fit_len = len;
hint->cur_len = fit_len;
/* check blue zones for horizontal stems */
align.align = PSH_BLUE_ALIGN_NONE;
align.align_bot = align.align_top = 0;
if ( dimension == 1 )
psh_blues_snap_stem( &globals->blues,
hint->org_pos + hint->org_len,
hint->org_pos,
&align );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
/* the top of the stem is aligned against a blue zone */
hint->cur_pos = align.align_top - fit_len;
break;
case PSH_BLUE_ALIGN_BOT:
/* the bottom of the stem is aligned against a blue zone */
hint->cur_pos = align.align_bot;
break;
case PSH_BLUE_ALIGN_TOP | PSH_BLUE_ALIGN_BOT:
/* both edges of the stem are aligned against blue zones */
hint->cur_pos = align.align_bot;
hint->cur_len = align.align_top - align.align_bot;
break;
default:
{
PSH_Hint parent = hint->parent;
if ( parent )
{
FT_Pos par_org_center, par_cur_center;
FT_Pos cur_org_center, cur_delta;
/* ensure that parent is already fitted */
if ( !psh_hint_is_fitted( parent ) )
psh_hint_align_light( parent, globals, dimension, glyph );
par_org_center = parent->org_pos + ( parent->org_len / 2 );
par_cur_center = parent->cur_pos + ( parent->cur_len / 2 );
cur_org_center = hint->org_pos + ( hint->org_len / 2 );
cur_delta = FT_MulFix( cur_org_center - par_org_center, scale );
pos = par_cur_center + cur_delta - ( len >> 1 );
}
/* Stems less than one pixel wide are easy -- we want to
* make them as dark as possible, so they must fall within
* one pixel. If the stem is split between two pixels
* then snap the edge that is nearer to the pixel boundary
* to the pixel boundary.
*/
if ( len <= 64 )
{
if ( ( pos + len + 63 ) / 64 != pos / 64 + 1 )
pos += psh_hint_snap_stem_side_delta ( pos, len );
}
/* Position stems other to minimize the amount of mid-grays.
* There are, in general, two positions that do this,
* illustrated as A) and B) below.
*
* + + + +
*
* A) |--------------------------------|
* B) |--------------------------------|
* C) |--------------------------------|
*
* Position A) (split the excess stem equally) should be better
* for stems of width N + f where f < 0.5.
*
* Position B) (split the deficiency equally) should be better
* for stems of width N + f where f > 0.5.
*
* It turns out though that minimizing the total number of lit
* pixels is also important, so position C), with one edge
* aligned with a pixel boundary is actually preferable
* to A). There are also more possibile positions for C) than
* for A) or B), so it involves less distortion of the overall
* character shape.
*/
else /* len > 64 */
{
FT_Fixed frac_len = len & 63;
FT_Fixed center = pos + ( len >> 1 );
FT_Fixed delta_a, delta_b;
if ( ( len / 64 ) & 1 )
{
delta_a = FT_PIX_FLOOR( center ) + 32 - center;
delta_b = FT_PIX_ROUND( center ) - center;
}
else
{
delta_a = FT_PIX_ROUND( center ) - center;
delta_b = FT_PIX_FLOOR( center ) + 32 - center;
}
/* We choose between B) and C) above based on the amount
* of fractinal stem width; for small amounts, choose
* C) always, for large amounts, B) always, and inbetween,
* pick whichever one involves less stem movement.
*/
if ( frac_len < 32 )
{
pos += psh_hint_snap_stem_side_delta ( pos, len );
}
else if ( frac_len < 48 )
{
FT_Fixed side_delta = psh_hint_snap_stem_side_delta ( pos,
len );
if ( FT_ABS( side_delta ) < FT_ABS( delta_b ) )
pos += side_delta;
else
pos += delta_b;
}
else
{
pos += delta_b;
}
}
hint->cur_pos = pos;
}
} /* switch */
psh_hint_set_fitted( hint );
#ifdef DEBUG_HINTER
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
#endif
}
}
#endif /* 0 */
static void
psh_hint_table_align_hints( PSH_Hint_Table table,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Hint hint;
FT_UInt count;
#ifdef DEBUG_HINTER
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( ps_debug_no_vert_hints && dimension == 0 )
{
ps_simple_scale( table, scale, delta, dimension );
return;
}
if ( ps_debug_no_horz_hints && dimension == 1 )
{
ps_simple_scale( table, scale, delta, dimension );
return;
}
#endif /* DEBUG_HINTER*/
hint = table->hints;
count = table->max_hints;
for ( ; count > 0; count--, hint++ )
psh_hint_align( hint, globals, dimension, glyph );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** POINTS INTERPOLATION ROUTINES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define PSH_ZONE_MIN -3200000L
#define PSH_ZONE_MAX +3200000L
#define xxDEBUG_ZONES
#ifdef DEBUG_ZONES
#include FT_CONFIG_STANDARD_LIBRARY_H
static void
psh_print_zone( PSH_Zone zone )
{
printf( "zone [scale,delta,min,max] = [%.3f,%.3f,%d,%d]\n",
zone->scale / 65536.0,
zone->delta / 64.0,
zone->min,
zone->max );
}
#else
#define psh_print_zone( x ) do { } while ( 0 )
#endif /* DEBUG_ZONES */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HINTER GLYPH MANAGEMENT *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#if 1
#define psh_corner_is_flat ft_corner_is_flat
#define psh_corner_orientation ft_corner_orientation
#else
FT_LOCAL_DEF( FT_Int )
psh_corner_is_flat( FT_Pos x_in,
FT_Pos y_in,
FT_Pos x_out,
FT_Pos y_out )
{
FT_Pos ax = x_in;
FT_Pos ay = y_in;
FT_Pos d_in, d_out, d_corner;
if ( ax < 0 )
ax = -ax;
if ( ay < 0 )
ay = -ay;
d_in = ax + ay;
ax = x_out;
if ( ax < 0 )
ax = -ax;
ay = y_out;
if ( ay < 0 )
ay = -ay;
d_out = ax + ay;
ax = x_out + x_in;
if ( ax < 0 )
ax = -ax;
ay = y_out + y_in;
if ( ay < 0 )
ay = -ay;
d_corner = ax + ay;
return ( d_in + d_out - d_corner ) < ( d_corner >> 4 );
}
static FT_Int
psh_corner_orientation( FT_Pos in_x,
FT_Pos in_y,
FT_Pos out_x,
FT_Pos out_y )
{
FT_Int result;
/* deal with the trivial cases quickly */
if ( in_y == 0 )
{
if ( in_x >= 0 )
result = out_y;
else
result = -out_y;
}
else if ( in_x == 0 )
{
if ( in_y >= 0 )
result = -out_x;
else
result = out_x;
}
else if ( out_y == 0 )
{
if ( out_x >= 0 )
result = in_y;
else
result = -in_y;
}
else if ( out_x == 0 )
{
if ( out_y >= 0 )
result = -in_x;
else
result = in_x;
}
else /* general case */
{
long long delta = (long long)in_x * out_y - (long long)in_y * out_x;
if ( delta == 0 )
result = 0;
else
result = 1 - 2 * ( delta < 0 );
}
return result;
}
#endif /* !1 */
#ifdef COMPUTE_INFLEXS
/* compute all inflex points in a given glyph */
static void
psh_glyph_compute_inflections( PSH_Glyph glyph )
{
FT_UInt n;
for ( n = 0; n < glyph->num_contours; n++ )
{
PSH_Point first, start, end, before, after;
FT_Pos in_x, in_y, out_x, out_y;
FT_Int orient_prev, orient_cur;
FT_Int finished = 0;
/* we need at least 4 points to create an inflection point */
if ( glyph->contours[n].count < 4 )
continue;
/* compute first segment in contour */
first = glyph->contours[n].start;
start = end = first;
do
{
end = end->next;
if ( end == first )
goto Skip;
in_x = end->org_u - start->org_u;
in_y = end->org_v - start->org_v;
} while ( in_x == 0 && in_y == 0 );
/* extend the segment start whenever possible */
before = start;
do
{
do
{
start = before;
before = before->prev;
if ( before == first )
goto Skip;
out_x = start->org_u - before->org_u;
out_y = start->org_v - before->org_v;
} while ( out_x == 0 && out_y == 0 );
orient_prev = psh_corner_orientation( in_x, in_y, out_x, out_y );
} while ( orient_prev == 0 );
first = start;
in_x = out_x;
in_y = out_y;
/* now, process all segments in the contour */
do
{
/* first, extend current segment's end whenever possible */
after = end;
do
{
do
{
end = after;
after = after->next;
if ( after == first )
finished = 1;
out_x = after->org_u - end->org_u;
out_y = after->org_v - end->org_v;
} while ( out_x == 0 && out_y == 0 );
orient_cur = psh_corner_orientation( in_x, in_y, out_x, out_y );
} while ( orient_cur == 0 );
if ( ( orient_cur ^ orient_prev ) < 0 )
{
do
{
psh_point_set_inflex( start );
start = start->next;
}
while ( start != end );
psh_point_set_inflex( start );
}
start = end;
end = after;
orient_prev = orient_cur;
in_x = out_x;
in_y = out_y;
} while ( !finished );
Skip:
;
}
}
#endif /* COMPUTE_INFLEXS */
static void
psh_glyph_done( PSH_Glyph glyph )
{
FT_Memory memory = glyph->memory;
psh_hint_table_done( &glyph->hint_tables[1], memory );
psh_hint_table_done( &glyph->hint_tables[0], memory );
FT_FREE( glyph->points );
FT_FREE( glyph->contours );
glyph->num_points = 0;
glyph->num_contours = 0;
glyph->memory = 0;
}
static int
psh_compute_dir( FT_Pos dx,
FT_Pos dy )
{
FT_Pos ax, ay;
int result = PSH_DIR_NONE;
ax = FT_ABS( dx );
ay = FT_ABS( dy );
if ( ay * 12 < ax )
{
/* |dy| <<< |dx| means a near-horizontal segment */
result = ( dx >= 0 ) ? PSH_DIR_RIGHT : PSH_DIR_LEFT;
}
else if ( ax * 12 < ay )
{
/* |dx| <<< |dy| means a near-vertical segment */
result = ( dy >= 0 ) ? PSH_DIR_UP : PSH_DIR_DOWN;
}
return result;
}
/* load outline point coordinates into hinter glyph */
static void
psh_glyph_load_points( PSH_Glyph glyph,
FT_Int dimension )
{
FT_Vector* vec = glyph->outline->points;
PSH_Point point = glyph->points;
FT_UInt count = glyph->num_points;
for ( ; count > 0; count--, point++, vec++ )
{
point->flags2 = 0;
point->hint = NULL;
if ( dimension == 0 )
{
point->org_u = vec->x;
point->org_v = vec->y;
}
else
{
point->org_u = vec->y;
point->org_v = vec->x;
}
#ifdef DEBUG_HINTER
point->org_x = vec->x;
point->org_y = vec->y;
#endif
}
}
/* save hinted point coordinates back to outline */
static void
psh_glyph_save_points( PSH_Glyph glyph,
FT_Int dimension )
{
FT_UInt n;
PSH_Point point = glyph->points;
FT_Vector* vec = glyph->outline->points;
char* tags = glyph->outline->tags;
for ( n = 0; n < glyph->num_points; n++ )
{
if ( dimension == 0 )
vec[n].x = point->cur_u;
else
vec[n].y = point->cur_u;
if ( psh_point_is_strong( point ) )
tags[n] |= (char)( ( dimension == 0 ) ? 32 : 64 );
#ifdef DEBUG_HINTER
if ( dimension == 0 )
{
point->cur_x = point->cur_u;
point->flags_x = point->flags2 | point->flags;
}
else
{
point->cur_y = point->cur_u;
point->flags_y = point->flags2 | point->flags;
}
#endif
point++;
}
}
static FT_Error
psh_glyph_init( PSH_Glyph glyph,
FT_Outline* outline,
PS_Hints ps_hints,
PSH_Globals globals )
{
FT_Error error;
FT_Memory memory;
/* clear all fields */
FT_MEM_ZERO( glyph, sizeof ( *glyph ) );
memory = glyph->memory = globals->memory;
/* allocate and setup points + contours arrays */
if ( FT_NEW_ARRAY( glyph->points, outline->n_points ) ||
FT_NEW_ARRAY( glyph->contours, outline->n_contours ) )
goto Exit;
glyph->num_points = outline->n_points;
glyph->num_contours = outline->n_contours;
{
FT_UInt first = 0, next, n;
PSH_Point points = glyph->points;
PSH_Contour contour = glyph->contours;
for ( n = 0; n < glyph->num_contours; n++ )
{
FT_Int count;
PSH_Point point;
next = outline->contours[n] + 1;
count = next - first;
contour->start = points + first;
contour->count = (FT_UInt)count;
if ( count > 0 )
{
point = points + first;
point->prev = points + next - 1;
point->contour = contour;
for ( ; count > 1; count-- )
{
point[0].next = point + 1;
point[1].prev = point;
point++;
point->contour = contour;
}
point->next = points + first;
}
contour++;
first = next;
}
}
{
PSH_Point points = glyph->points;
PSH_Point point = points;
FT_Vector* vec = outline->points;
FT_UInt n;
for ( n = 0; n < glyph->num_points; n++, point++ )
{
FT_Int n_prev = (FT_Int)( point->prev - points );
FT_Int n_next = (FT_Int)( point->next - points );
FT_Pos dxi, dyi, dxo, dyo;
if ( !( outline->tags[n] & FT_CURVE_TAG_ON ) )
point->flags = PSH_POINT_OFF;
dxi = vec[n].x - vec[n_prev].x;
dyi = vec[n].y - vec[n_prev].y;
point->dir_in = (FT_Char)psh_compute_dir( dxi, dyi );
dxo = vec[n_next].x - vec[n].x;
dyo = vec[n_next].y - vec[n].y;
point->dir_out = (FT_Char)psh_compute_dir( dxo, dyo );
/* detect smooth points */
if ( point->flags & PSH_POINT_OFF )
point->flags |= PSH_POINT_SMOOTH;
else if ( point->dir_in == point->dir_out )
{
if ( point->dir_out != PSH_DIR_NONE ||
psh_corner_is_flat( dxi, dyi, dxo, dyo ) )
point->flags |= PSH_POINT_SMOOTH;
}
}
}
glyph->outline = outline;
glyph->globals = globals;
#ifdef COMPUTE_INFLEXS
psh_glyph_load_points( glyph, 0 );
psh_glyph_compute_inflections( glyph );
#endif /* COMPUTE_INFLEXS */
/* now deal with hints tables */
error = psh_hint_table_init( &glyph->hint_tables [0],
&ps_hints->dimension[0].hints,
&ps_hints->dimension[0].masks,
&ps_hints->dimension[0].counters,
memory );
if ( error )
goto Exit;
error = psh_hint_table_init( &glyph->hint_tables [1],
&ps_hints->dimension[1].hints,
&ps_hints->dimension[1].masks,
&ps_hints->dimension[1].counters,
memory );
if ( error )
goto Exit;
Exit:
return error;
}
/* compute all extrema in a glyph for a given dimension */
static void
psh_glyph_compute_extrema( PSH_Glyph glyph )
{
FT_UInt n;
/* first of all, compute all local extrema */
for ( n = 0; n < glyph->num_contours; n++ )
{
PSH_Point first = glyph->contours[n].start;
PSH_Point point, before, after;
if ( glyph->contours[n].count == 0 )
continue;
point = first;
before = point;
do
{
before = before->prev;
if ( before == first )
goto Skip;
} while ( before->org_u == point->org_u );
first = point = before->next;
for (;;)
{
after = point;
do
{
after = after->next;
if ( after == first )
goto Next;
} while ( after->org_u == point->org_u );
if ( before->org_u < point->org_u )
{
if ( after->org_u < point->org_u )
{
/* local maximum */
goto Extremum;
}
}
else /* before->org_u > point->org_u */
{
if ( after->org_u > point->org_u )
{
/* local minimum */
Extremum:
do
{
psh_point_set_extremum( point );
point = point->next;
} while ( point != after );
}
}
before = after->prev;
point = after;
} /* for */
Next:
;
}
/* for each extremum, determine its direction along the */
/* orthogonal axis */
for ( n = 0; n < glyph->num_points; n++ )
{
PSH_Point point, before, after;
point = &glyph->points[n];
before = point;
after = point;
if ( psh_point_is_extremum( point ) )
{
do
{
before = before->prev;
if ( before == point )
goto Skip;
} while ( before->org_v == point->org_v );
do
{
after = after->next;
if ( after == point )
goto Skip;
} while ( after->org_v == point->org_v );
}
if ( before->org_v < point->org_v &&
after->org_v > point->org_v )
{
psh_point_set_positive( point );
}
else if ( before->org_v > point->org_v &&
after->org_v < point->org_v )
{
psh_point_set_negative( point );
}
Skip:
;
}
}
/* major_dir is the direction for points on the bottom/left of the stem; */
/* Points on the top/right of the stem will have a direction of */
/* -major_dir. */
static void
psh_hint_table_find_strong_points( PSH_Hint_Table table,
PSH_Point point,
FT_UInt count,
FT_Int threshold,
FT_Int major_dir )
{
PSH_Hint* sort = table->sort;
FT_UInt num_hints = table->num_hints;
for ( ; count > 0; count--, point++ )
{
FT_Int point_dir = 0;
FT_Pos org_u = point->org_u;
if ( psh_point_is_strong( point ) )
continue;
if ( PSH_DIR_COMPARE( point->dir_in, major_dir ) )
point_dir = point->dir_in;
else if ( PSH_DIR_COMPARE( point->dir_out, major_dir ) )
point_dir = point->dir_out;
if ( point_dir )
{
if ( point_dir == major_dir )
{
FT_UInt nn;
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos;
if ( d < threshold && -d < threshold )
{
psh_point_set_strong( point );
point->flags2 |= PSH_POINT_EDGE_MIN;
point->hint = hint;
break;
}
}
}
else if ( point_dir == -major_dir )
{
FT_UInt nn;
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos - hint->org_len;
if ( d < threshold && -d < threshold )
{
psh_point_set_strong( point );
point->flags2 |= PSH_POINT_EDGE_MAX;
point->hint = hint;
break;
}
}
}
}
#if 1
else if ( psh_point_is_extremum( point ) )
{
/* treat extrema as special cases for stem edge alignment */
FT_UInt nn, min_flag, max_flag;
if ( major_dir == PSH_DIR_HORIZONTAL )
{
min_flag = PSH_POINT_POSITIVE;
max_flag = PSH_POINT_NEGATIVE;
}
else
{
min_flag = PSH_POINT_NEGATIVE;
max_flag = PSH_POINT_POSITIVE;
}
if ( point->flags2 & min_flag )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos;
if ( d < threshold && -d < threshold )
{
point->flags2 |= PSH_POINT_EDGE_MIN;
point->hint = hint;
psh_point_set_strong( point );
break;
}
}
}
else if ( point->flags2 & max_flag )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos - hint->org_len;
if ( d < threshold && -d < threshold )
{
point->flags2 |= PSH_POINT_EDGE_MAX;
point->hint = hint;
psh_point_set_strong( point );
break;
}
}
}
if ( point->hint == NULL )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
if ( org_u >= hint->org_pos &&
org_u <= hint->org_pos + hint->org_len )
{
point->hint = hint;
break;
}
}
}
}
#endif /* 1 */
}
}
/* the accepted shift for strong points in fractional pixels */
#define PSH_STRONG_THRESHOLD 32
/* the maximum shift value in font units */
#define PSH_STRONG_THRESHOLD_MAXIMUM 30
/* find strong points in a glyph */
static void
psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
/* the `endchar' op can reduce the number of points */
first = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
FT_UInt next;
FT_Int count;
next = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
count = next - first;
if ( count > 0 )
{
PSH_Point point = glyph->points + first;
psh_hint_table_activate_mask( table, mask );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
/* find points in a glyph which are in a blue zone and have `in' or */
/* `out' tangents parallel to the horizontal axis */
static void
psh_glyph_find_blue_points( PSH_Blues blues,
PSH_Glyph glyph )
{
PSH_Blue_Table table;
PSH_Blue_Zone zone;
FT_UInt glyph_count = glyph->num_points;
FT_UInt blue_count;
PSH_Point point = glyph->points;
for ( ; glyph_count > 0; glyph_count--, point++ )
{
FT_Pos y;
/* check tangents */
if ( !PSH_DIR_COMPARE( point->dir_in, PSH_DIR_HORIZONTAL ) &&
!PSH_DIR_COMPARE( point->dir_out, PSH_DIR_HORIZONTAL ) )
continue;
/* skip strong points */
if ( psh_point_is_strong( point ) )
continue;
y = point->org_u;
/* look up top zones */
table = &blues->normal_top;
blue_count = table->count;
zone = table->zones;
for ( ; blue_count > 0; blue_count--, zone++ )
{
FT_Pos delta = y - zone->org_bottom;
if ( delta < -blues->blue_fuzz )
break;
if ( y <= zone->org_top + blues->blue_fuzz )
if ( blues->no_overshoots || delta <= blues->blue_threshold )
{
point->cur_u = zone->cur_bottom;
psh_point_set_strong( point );
psh_point_set_fitted( point );
}
}
/* look up bottom zones */
table = &blues->normal_bottom;
blue_count = table->count;
zone = table->zones + blue_count - 1;
for ( ; blue_count > 0; blue_count--, zone-- )
{
FT_Pos delta = zone->org_top - y;
if ( delta < -blues->blue_fuzz )
break;
if ( y >= zone->org_bottom - blues->blue_fuzz )
if ( blues->no_overshoots || delta < blues->blue_threshold )
{
point->cur_u = zone->cur_top;
psh_point_set_strong( point );
psh_point_set_fitted( point );
}
}
}
}
/* interpolate strong points with the help of hinted coordinates */
static void
psh_glyph_interpolate_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
{
PSH_Hint hint = point->hint;
if ( hint )
{
FT_Pos delta;
if ( psh_point_is_edge_min( point ) )
point->cur_u = hint->cur_pos;
else if ( psh_point_is_edge_max( point ) )
point->cur_u = hint->cur_pos + hint->cur_len;
else
{
delta = point->org_u - hint->org_pos;
if ( delta <= 0 )
point->cur_u = hint->cur_pos + FT_MulFix( delta, scale );
else if ( delta >= hint->org_len )
point->cur_u = hint->cur_pos + hint->cur_len +
FT_MulFix( delta - hint->org_len, scale );
else /* hint->org_len > 0 */
point->cur_u = hint->cur_pos +
FT_MulDiv( delta, hint->cur_len,
hint->org_len );
}
psh_point_set_fitted( point );
}
}
}
#define PSH_MAX_STRONG_INTERNAL 16
static void
psh_glyph_interpolate_normal_points( PSH_Glyph glyph,
FT_Int dimension )
{
#if 1
/* first technique: a point is strong if it is a local extremum */
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Memory memory = glyph->memory;
PSH_Point* strongs = NULL;
PSH_Point strongs_0[PSH_MAX_STRONG_INTERNAL];
FT_UInt num_strongs = 0;
PSH_Point points = glyph->points;
PSH_Point points_end = points + glyph->num_points;
PSH_Point point;
/* first count the number of strong points */
for ( point = points; point < points_end; point++ )
{
if ( psh_point_is_strong( point ) )
num_strongs++;
}
if ( num_strongs == 0 ) /* nothing to do here */
return;
/* allocate an array to store a list of points, */
/* stored in increasing org_u order */
if ( num_strongs <= PSH_MAX_STRONG_INTERNAL )
strongs = strongs_0;
else
{
FT_Error error;
if ( FT_NEW_ARRAY( strongs, num_strongs ) )
return;
}
num_strongs = 0;
for ( point = points; point < points_end; point++ )
{
PSH_Point* insert;
if ( !psh_point_is_strong( point ) )
continue;
for ( insert = strongs + num_strongs; insert > strongs; insert-- )
{
if ( insert[-1]->org_u <= point->org_u )
break;
insert[0] = insert[-1];
}
insert[0] = point;
num_strongs++;
}
/* now try to interpolate all normal points */
for ( point = points; point < points_end; point++ )
{
if ( psh_point_is_strong( point ) )
continue;
/* sometimes, some local extrema are smooth points */
if ( psh_point_is_smooth( point ) )
{
if ( point->dir_in == PSH_DIR_NONE ||
point->dir_in != point->dir_out )
continue;
if ( !psh_point_is_extremum( point ) &&
!psh_point_is_inflex( point ) )
continue;
point->flags &= ~PSH_POINT_SMOOTH;
}
/* find best enclosing point coordinates then interpolate */
{
PSH_Point before, after;
FT_UInt nn;
for ( nn = 0; nn < num_strongs; nn++ )
if ( strongs[nn]->org_u > point->org_u )
break;
if ( nn == 0 ) /* point before the first strong point */
{
after = strongs[0];
point->cur_u = after->cur_u +
FT_MulFix( point->org_u - after->org_u,
scale );
}
else
{
before = strongs[nn - 1];
for ( nn = num_strongs; nn > 0; nn-- )
if ( strongs[nn - 1]->org_u < point->org_u )
break;
if ( nn == num_strongs ) /* point is after last strong point */
{
before = strongs[nn - 1];
point->cur_u = before->cur_u +
FT_MulFix( point->org_u - before->org_u,
scale );
}
else
{
FT_Pos u;
after = strongs[nn];
/* now interpolate point between before and after */
u = point->org_u;
if ( u == before->org_u )
point->cur_u = before->cur_u;
else if ( u == after->org_u )
point->cur_u = after->cur_u;
else
point->cur_u = before->cur_u +
FT_MulDiv( u - before->org_u,
after->cur_u - before->cur_u,
after->org_u - before->org_u );
}
}
psh_point_set_fitted( point );
}
}
if ( strongs != strongs_0 )
FT_FREE( strongs );
#endif /* 1 */
}
/* interpolate other points */
static void
psh_glyph_interpolate_other_points( PSH_Glyph glyph,
FT_Int dimension )
{
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
PSH_Contour contour = glyph->contours;
FT_UInt num_contours = glyph->num_contours;
for ( ; num_contours > 0; num_contours--, contour++ )
{
PSH_Point start = contour->start;
PSH_Point first, next, point;
FT_UInt fit_count;
/* count the number of strong points in this contour */
next = start + contour->count;
fit_count = 0;
first = 0;
for ( point = start; point < next; point++ )
if ( psh_point_is_fitted( point ) )
{
if ( !first )
first = point;
fit_count++;
}
/* if there are less than 2 fitted points in the contour, we */
/* simply scale and eventually translate the contour points */
if ( fit_count < 2 )
{
if ( fit_count == 1 )
delta = first->cur_u - FT_MulFix( first->org_u, scale );
for ( point = start; point < next; point++ )
if ( point != first )
point->cur_u = FT_MulFix( point->org_u, scale ) + delta;
goto Next_Contour;
}
/* there are more than 2 strong points in this contour; we */
/* need to interpolate weak points between them */
start = first;
do
{
/* skip consecutive fitted points */
for (;;)
{
next = first->next;
if ( next == start )
goto Next_Contour;
if ( !psh_point_is_fitted( next ) )
break;
first = next;
}
/* find next fitted point after unfitted one */
for (;;)
{
next = next->next;
if ( psh_point_is_fitted( next ) )
break;
}
/* now interpolate between them */
{
FT_Pos org_a, org_ab, cur_a, cur_ab;
FT_Pos org_c, org_ac, cur_c;
FT_Fixed scale_ab;
if ( first->org_u <= next->org_u )
{
org_a = first->org_u;
cur_a = first->cur_u;
org_ab = next->org_u - org_a;
cur_ab = next->cur_u - cur_a;
}
else
{
org_a = next->org_u;
cur_a = next->cur_u;
org_ab = first->org_u - org_a;
cur_ab = first->cur_u - cur_a;
}
scale_ab = 0x10000L;
if ( org_ab > 0 )
scale_ab = FT_DivFix( cur_ab, org_ab );
point = first->next;
do
{
org_c = point->org_u;
org_ac = org_c - org_a;
if ( org_ac <= 0 )
{
/* on the left of the interpolation zone */
cur_c = cur_a + FT_MulFix( org_ac, scale );
}
else if ( org_ac >= org_ab )
{
/* on the right on the interpolation zone */
cur_c = cur_a + cur_ab + FT_MulFix( org_ac - org_ab, scale );
}
else
{
/* within the interpolation zone */
cur_c = cur_a + FT_MulFix( org_ac, scale_ab );
}
point->cur_u = cur_c;
point = point->next;
} while ( point != next );
}
/* keep going until all points in the contours have been processed */
first = next;
} while ( first != start );
Next_Contour:
;
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HIGH-LEVEL INTERFACE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_Error
ps_hints_apply( PS_Hints ps_hints,
FT_Outline* outline,
PSH_Globals globals,
FT_Render_Mode hint_mode )
{
PSH_GlyphRec glyphrec;
PSH_Glyph glyph = &glyphrec;
FT_Error error;
#ifdef DEBUG_HINTER
FT_Memory memory;
#endif
FT_Int dimension;
/* something to do? */
if ( outline->n_points == 0 || outline->n_contours == 0 )
return FT_Err_Ok;
#ifdef DEBUG_HINTER
memory = globals->memory;
if ( ps_debug_glyph )
{
psh_glyph_done( ps_debug_glyph );
FT_FREE( ps_debug_glyph );
}
if ( FT_NEW( glyph ) )
return error;
ps_debug_glyph = glyph;
#endif /* DEBUG_HINTER */
error = psh_glyph_init( glyph, outline, ps_hints, globals );
if ( error )
goto Exit;
/* try to optimize the y_scale so that the top of non-capital letters
* is aligned on a pixel boundary whenever possible
*/
{
PSH_Dimension dim_x = &glyph->globals->dimension[0];
PSH_Dimension dim_y = &glyph->globals->dimension[1];
FT_Fixed x_scale = dim_x->scale_mult;
FT_Fixed y_scale = dim_y->scale_mult;
FT_Fixed old_x_scale = x_scale;
FT_Fixed old_y_scale = y_scale;
FT_Fixed scaled;
FT_Fixed fitted;
FT_Bool rescale = FALSE;
scaled = FT_MulFix( globals->blues.normal_top.zones->org_ref, y_scale );
fitted = FT_PIX_ROUND( scaled );
if ( fitted != 0 && scaled != fitted )
{
rescale = TRUE;
y_scale = FT_MulDiv( y_scale, fitted, scaled );
if ( fitted < scaled )
x_scale -= x_scale / 50;
psh_globals_set_scale( glyph->globals, x_scale, y_scale, 0, 0 );
}
glyph->do_horz_hints = 1;
glyph->do_vert_hints = 1;
glyph->do_horz_snapping = FT_BOOL( hint_mode == FT_RENDER_MODE_MONO ||
hint_mode == FT_RENDER_MODE_LCD );
glyph->do_vert_snapping = FT_BOOL( hint_mode == FT_RENDER_MODE_MONO ||
hint_mode == FT_RENDER_MODE_LCD_V );
glyph->do_stem_adjust = FT_BOOL( hint_mode != FT_RENDER_MODE_LIGHT );
for ( dimension = 0; dimension < 2; dimension++ )
{
/* load outline coordinates into glyph */
psh_glyph_load_points( glyph, dimension );
/* compute local extrema */
psh_glyph_compute_extrema( glyph );
/* compute aligned stem/hints positions */
psh_hint_table_align_hints( &glyph->hint_tables[dimension],
glyph->globals,
dimension,
glyph );
/* find strong points, align them, then interpolate others */
psh_glyph_find_strong_points( glyph, dimension );
if ( dimension == 1 )
psh_glyph_find_blue_points( &globals->blues, glyph );
psh_glyph_interpolate_strong_points( glyph, dimension );
psh_glyph_interpolate_normal_points( glyph, dimension );
psh_glyph_interpolate_other_points( glyph, dimension );
/* save hinted coordinates back to outline */
psh_glyph_save_points( glyph, dimension );
if ( rescale )
psh_globals_set_scale( glyph->globals,
old_x_scale, old_y_scale, 0, 0 );
}
}
Exit:
#ifndef DEBUG_HINTER
psh_glyph_done( glyph );
#endif
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshalgo.c | C | apache-2.0 | 61,747 |
/***************************************************************************/
/* */
/* pshalgo.h */
/* */
/* PostScript hinting algorithm (specification). */
/* */
/* Copyright 2001-2003, 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 __PSHALGO_H__
#define __PSHALGO_H__
#include "pshrec.h"
#include "pshglob.h"
FT_BEGIN_HEADER
/* handle to Hint structure */
typedef struct PSH_HintRec_* PSH_Hint;
/* hint bit-flags */
typedef enum PSH_Hint_Flags_
{
PSH_HINT_GHOST = PS_HINT_FLAG_GHOST,
PSH_HINT_BOTTOM = PS_HINT_FLAG_BOTTOM,
PSH_HINT_ACTIVE = 4,
PSH_HINT_FITTED = 8
} PSH_Hint_Flags;
#define psh_hint_is_active( x ) ( ( (x)->flags & PSH_HINT_ACTIVE ) != 0 )
#define psh_hint_is_ghost( x ) ( ( (x)->flags & PSH_HINT_GHOST ) != 0 )
#define psh_hint_is_fitted( x ) ( ( (x)->flags & PSH_HINT_FITTED ) != 0 )
#define psh_hint_activate( x ) (x)->flags |= PSH_HINT_ACTIVE
#define psh_hint_deactivate( x ) (x)->flags &= ~PSH_HINT_ACTIVE
#define psh_hint_set_fitted( x ) (x)->flags |= PSH_HINT_FITTED
/* hint structure */
typedef struct PSH_HintRec_
{
FT_Int org_pos;
FT_Int org_len;
FT_Pos cur_pos;
FT_Pos cur_len;
FT_UInt flags;
PSH_Hint parent;
FT_Int order;
} PSH_HintRec;
/* this is an interpolation zone used for strong points; */
/* weak points are interpolated according to their strong */
/* neighbours */
typedef struct PSH_ZoneRec_
{
FT_Fixed scale;
FT_Fixed delta;
FT_Pos min;
FT_Pos max;
} PSH_ZoneRec, *PSH_Zone;
typedef struct PSH_Hint_TableRec_
{
FT_UInt max_hints;
FT_UInt num_hints;
PSH_Hint hints;
PSH_Hint* sort;
PSH_Hint* sort_global;
FT_UInt num_zones;
PSH_ZoneRec* zones;
PSH_Zone zone;
PS_Mask_Table hint_masks;
PS_Mask_Table counter_masks;
} PSH_Hint_TableRec, *PSH_Hint_Table;
typedef struct PSH_PointRec_* PSH_Point;
typedef struct PSH_ContourRec_* PSH_Contour;
enum
{
PSH_DIR_NONE = 4,
PSH_DIR_UP = -1,
PSH_DIR_DOWN = 1,
PSH_DIR_LEFT = -2,
PSH_DIR_RIGHT = 2
};
#define PSH_DIR_HORIZONTAL 2
#define PSH_DIR_VERTICAL 1
#define PSH_DIR_COMPARE( d1, d2 ) ( (d1) == (d2) || (d1) == -(d2) )
#define PSH_DIR_IS_HORIZONTAL( d ) PSH_DIR_COMPARE( d, PSH_DIR_HORIZONTAL )
#define PSH_DIR_IS_VERTICAL( d ) PSH_DIR_COMPARE( d, PSH_DIR_VERTICAL )
/* the following bit-flags are computed once by the glyph */
/* analyzer, for both dimensions */
enum
{
PSH_POINT_OFF = 1, /* point is off the curve */
PSH_POINT_SMOOTH = 2, /* point is smooth */
PSH_POINT_INFLEX = 4 /* point is inflection */
};
#define psh_point_is_smooth( p ) ( (p)->flags & PSH_POINT_SMOOTH )
#define psh_point_is_off( p ) ( (p)->flags & PSH_POINT_OFF )
#define psh_point_is_inflex( p ) ( (p)->flags & PSH_POINT_INFLEX )
#define psh_point_set_smooth( p ) (p)->flags |= PSH_POINT_SMOOTH
#define psh_point_set_off( p ) (p)->flags |= PSH_POINT_OFF
#define psh_point_set_inflex( p ) (p)->flags |= PSH_POINT_INFLEX
/* the following bit-flags are re-computed for each dimension */
enum
{
PSH_POINT_STRONG = 16, /* point is strong */
PSH_POINT_FITTED = 32, /* point is already fitted */
PSH_POINT_EXTREMUM = 64, /* point is local extremum */
PSH_POINT_POSITIVE = 128, /* extremum has positive contour flow */
PSH_POINT_NEGATIVE = 256, /* extremum has negative contour flow */
PSH_POINT_EDGE_MIN = 512, /* point is aligned to left/bottom stem edge */
PSH_POINT_EDGE_MAX = 1024 /* point is aligned to top/right stem edge */
};
#define psh_point_is_strong( p ) ( (p)->flags2 & PSH_POINT_STRONG )
#define psh_point_is_fitted( p ) ( (p)->flags2 & PSH_POINT_FITTED )
#define psh_point_is_extremum( p ) ( (p)->flags2 & PSH_POINT_EXTREMUM )
#define psh_point_is_positive( p ) ( (p)->flags2 & PSH_POINT_POSITIVE )
#define psh_point_is_negative( p ) ( (p)->flags2 & PSH_POINT_NEGATIVE )
#define psh_point_is_edge_min( p ) ( (p)->flags2 & PSH_POINT_EDGE_MIN )
#define psh_point_is_edge_max( p ) ( (p)->flags2 & PSH_POINT_EDGE_MAX )
#define psh_point_set_strong( p ) (p)->flags2 |= PSH_POINT_STRONG
#define psh_point_set_fitted( p ) (p)->flags2 |= PSH_POINT_FITTED
#define psh_point_set_extremum( p ) (p)->flags2 |= PSH_POINT_EXTREMUM
#define psh_point_set_positive( p ) (p)->flags2 |= PSH_POINT_POSITIVE
#define psh_point_set_negative( p ) (p)->flags2 |= PSH_POINT_NEGATIVE
#define psh_point_set_edge_min( p ) (p)->flags2 |= PSH_POINT_EDGE_MIN
#define psh_point_set_edge_max( p ) (p)->flags2 |= PSH_POINT_EDGE_MAX
typedef struct PSH_PointRec_
{
PSH_Point prev;
PSH_Point next;
PSH_Contour contour;
FT_UInt flags;
FT_UInt flags2;
FT_Char dir_in;
FT_Char dir_out;
PSH_Hint hint;
FT_Pos org_u;
FT_Pos org_v;
FT_Pos cur_u;
#ifdef DEBUG_HINTER
FT_Pos org_x;
FT_Pos cur_x;
FT_Pos org_y;
FT_Pos cur_y;
FT_UInt flags_x;
FT_UInt flags_y;
#endif
} PSH_PointRec;
typedef struct PSH_ContourRec_
{
PSH_Point start;
FT_UInt count;
} PSH_ContourRec;
typedef struct PSH_GlyphRec_
{
FT_UInt num_points;
FT_UInt num_contours;
PSH_Point points;
PSH_Contour contours;
FT_Memory memory;
FT_Outline* outline;
PSH_Globals globals;
PSH_Hint_TableRec hint_tables[2];
FT_Bool vertical;
FT_Int major_dir;
FT_Int minor_dir;
FT_Bool do_horz_hints;
FT_Bool do_vert_hints;
FT_Bool do_horz_snapping;
FT_Bool do_vert_snapping;
FT_Bool do_stem_adjust;
} PSH_GlyphRec, *PSH_Glyph;
#ifdef DEBUG_HINTER
extern PSH_Hint_Table ps_debug_hint_table;
typedef void
(*PSH_HintFunc)( PSH_Hint hint,
FT_Bool vertical );
extern PSH_HintFunc ps_debug_hint_func;
extern PSH_Glyph ps_debug_glyph;
#endif
extern FT_Error
ps_hints_apply( PS_Hints ps_hints,
FT_Outline* outline,
PSH_Globals globals,
FT_Render_Mode hint_mode );
FT_END_HEADER
#endif /* __PSHALGO_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshalgo.h | C | apache-2.0 | 7,634 |
/***************************************************************************/
/* */
/* pshglob.c */
/* */
/* PostScript hinter global hinting management (body). */
/* Inspired by the new auto-hinter module. */
/* */
/* Copyright 2001-2004, 2006, 2010, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_INTERNAL_OBJECTS_H
#include "pshglob.h"
#ifdef DEBUG_HINTER
PSH_Globals ps_debug_globals = 0;
#endif
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** STANDARD WIDTHS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* scale the widths/heights table */
static void
psh_globals_scale_widths( PSH_Globals globals,
FT_UInt direction )
{
PSH_Dimension dim = &globals->dimension[direction];
PSH_Widths stdw = &dim->stdw;
FT_UInt count = stdw->count;
PSH_Width width = stdw->widths;
PSH_Width stand = width; /* standard width/height */
FT_Fixed scale = dim->scale_mult;
if ( count > 0 )
{
width->cur = FT_MulFix( width->org, scale );
width->fit = FT_PIX_ROUND( width->cur );
width++;
count--;
for ( ; count > 0; count--, width++ )
{
FT_Pos w, dist;
w = FT_MulFix( width->org, scale );
dist = w - stand->cur;
if ( dist < 0 )
dist = -dist;
if ( dist < 128 )
w = stand->cur;
width->cur = w;
width->fit = FT_PIX_ROUND( w );
}
}
}
#if 0
/* org_width is is font units, result in device pixels, 26.6 format */
FT_LOCAL_DEF( FT_Pos )
psh_dimension_snap_width( PSH_Dimension dimension,
FT_Int org_width )
{
FT_UInt n;
FT_Pos width = FT_MulFix( org_width, dimension->scale_mult );
FT_Pos best = 64 + 32 + 2;
FT_Pos reference = width;
for ( n = 0; n < dimension->stdw.count; n++ )
{
FT_Pos w;
FT_Pos dist;
w = dimension->stdw.widths[n].cur;
dist = width - w;
if ( dist < 0 )
dist = -dist;
if ( dist < best )
{
best = dist;
reference = w;
}
}
if ( width >= reference )
{
width -= 0x21;
if ( width < reference )
width = reference;
}
else
{
width += 0x21;
if ( width > reference )
width = reference;
}
return width;
}
#endif /* 0 */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** BLUE ZONES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
psh_blues_set_zones_0( PSH_Blues target,
FT_Bool is_others,
FT_UInt read_count,
FT_Short* read,
PSH_Blue_Table top_table,
PSH_Blue_Table bot_table )
{
FT_UInt count_top = top_table->count;
FT_UInt count_bot = bot_table->count;
FT_Bool first = 1;
FT_UNUSED( target );
for ( ; read_count > 1; read_count -= 2 )
{
FT_Int reference, delta;
FT_UInt count;
PSH_Blue_Zone zones, zone;
FT_Bool top;
/* read blue zone entry, and select target top/bottom zone */
top = 0;
if ( first || is_others )
{
reference = read[1];
delta = read[0] - reference;
zones = bot_table->zones;
count = count_bot;
first = 0;
}
else
{
reference = read[0];
delta = read[1] - reference;
zones = top_table->zones;
count = count_top;
top = 1;
}
/* insert into sorted table */
zone = zones;
for ( ; count > 0; count--, zone++ )
{
if ( reference < zone->org_ref )
break;
if ( reference == zone->org_ref )
{
FT_Int delta0 = zone->org_delta;
/* we have two zones on the same reference position -- */
/* only keep the largest one */
if ( delta < 0 )
{
if ( delta < delta0 )
zone->org_delta = delta;
}
else
{
if ( delta > delta0 )
zone->org_delta = delta;
}
goto Skip;
}
}
for ( ; count > 0; count-- )
zone[count] = zone[count-1];
zone->org_ref = reference;
zone->org_delta = delta;
if ( top )
count_top++;
else
count_bot++;
Skip:
read += 2;
}
top_table->count = count_top;
bot_table->count = count_bot;
}
/* Re-read blue zones from the original fonts and store them into out */
/* private structure. This function re-orders, sanitizes and */
/* fuzz-expands the zones as well. */
static void
psh_blues_set_zones( PSH_Blues target,
FT_UInt count,
FT_Short* blues,
FT_UInt count_others,
FT_Short* other_blues,
FT_Int fuzz,
FT_Int family )
{
PSH_Blue_Table top_table, bot_table;
FT_Int count_top, count_bot;
if ( family )
{
top_table = &target->family_top;
bot_table = &target->family_bottom;
}
else
{
top_table = &target->normal_top;
bot_table = &target->normal_bottom;
}
/* read the input blue zones, and build two sorted tables */
/* (one for the top zones, the other for the bottom zones) */
top_table->count = 0;
bot_table->count = 0;
/* first, the blues */
psh_blues_set_zones_0( target, 0,
count, blues, top_table, bot_table );
psh_blues_set_zones_0( target, 1,
count_others, other_blues, top_table, bot_table );
count_top = top_table->count;
count_bot = bot_table->count;
/* sanitize top table */
if ( count_top > 0 )
{
PSH_Blue_Zone zone = top_table->zones;
for ( count = count_top; count > 0; count--, zone++ )
{
FT_Int delta;
if ( count > 1 )
{
delta = zone[1].org_ref - zone[0].org_ref;
if ( zone->org_delta > delta )
zone->org_delta = delta;
}
zone->org_bottom = zone->org_ref;
zone->org_top = zone->org_delta + zone->org_ref;
}
}
/* sanitize bottom table */
if ( count_bot > 0 )
{
PSH_Blue_Zone zone = bot_table->zones;
for ( count = count_bot; count > 0; count--, zone++ )
{
FT_Int delta;
if ( count > 1 )
{
delta = zone[0].org_ref - zone[1].org_ref;
if ( zone->org_delta < delta )
zone->org_delta = delta;
}
zone->org_top = zone->org_ref;
zone->org_bottom = zone->org_delta + zone->org_ref;
}
}
/* expand top and bottom tables with blue fuzz */
{
FT_Int dim, top, bot, delta;
PSH_Blue_Zone zone;
zone = top_table->zones;
count = count_top;
for ( dim = 1; dim >= 0; dim-- )
{
if ( count > 0 )
{
/* expand the bottom of the lowest zone normally */
zone->org_bottom -= fuzz;
/* expand the top and bottom of intermediate zones; */
/* checking that the interval is smaller than the fuzz */
top = zone->org_top;
for ( count--; count > 0; count-- )
{
bot = zone[1].org_bottom;
delta = bot - top;
if ( delta < 2 * fuzz )
zone[0].org_top = zone[1].org_bottom = top + delta / 2;
else
{
zone[0].org_top = top + fuzz;
zone[1].org_bottom = bot - fuzz;
}
zone++;
top = zone->org_top;
}
/* expand the top of the highest zone normally */
zone->org_top = top + fuzz;
}
zone = bot_table->zones;
count = count_bot;
}
}
}
/* reset the blues table when the device transform changes */
static void
psh_blues_scale_zones( PSH_Blues blues,
FT_Fixed scale,
FT_Pos delta )
{
FT_UInt count;
FT_UInt num;
PSH_Blue_Table table = 0;
/* */
/* Determine whether we need to suppress overshoots or */
/* not. We simply need to compare the vertical scale */
/* parameter to the raw bluescale value. Here is why: */
/* */
/* We need to suppress overshoots for all pointsizes. */
/* At 300dpi that satisfies: */
/* */
/* pointsize < 240*bluescale + 0.49 */
/* */
/* This corresponds to: */
/* */
/* pixelsize < 1000*bluescale + 49/24 */
/* */
/* scale*EM_Size < 1000*bluescale + 49/24 */
/* */
/* However, for normal Type 1 fonts, EM_Size is 1000! */
/* We thus only check: */
/* */
/* scale < bluescale + 49/24000 */
/* */
/* which we shorten to */
/* */
/* "scale < bluescale" */
/* */
/* Note that `blue_scale' is stored 1000 times its real */
/* value, and that `scale' converts from font units to */
/* fractional pixels. */
/* */
/* 1000 / 64 = 125 / 8 */
if ( scale >= 0x20C49BAL )
blues->no_overshoots = FT_BOOL( scale < blues->blue_scale * 8 / 125 );
else
blues->no_overshoots = FT_BOOL( scale * 125 < blues->blue_scale * 8 );
/* */
/* The blue threshold is the font units distance under */
/* which overshoots are suppressed due to the BlueShift */
/* even if the scale is greater than BlueScale. */
/* */
/* It is the smallest distance such that */
/* */
/* dist <= BlueShift && dist*scale <= 0.5 pixels */
/* */
{
FT_Int threshold = blues->blue_shift;
while ( threshold > 0 && FT_MulFix( threshold, scale ) > 32 )
threshold--;
blues->blue_threshold = threshold;
}
for ( num = 0; num < 4; num++ )
{
PSH_Blue_Zone zone;
switch ( num )
{
case 0:
table = &blues->normal_top;
break;
case 1:
table = &blues->normal_bottom;
break;
case 2:
table = &blues->family_top;
break;
default:
table = &blues->family_bottom;
break;
}
zone = table->zones;
count = table->count;
for ( ; count > 0; count--, zone++ )
{
zone->cur_top = FT_MulFix( zone->org_top, scale ) + delta;
zone->cur_bottom = FT_MulFix( zone->org_bottom, scale ) + delta;
zone->cur_ref = FT_MulFix( zone->org_ref, scale ) + delta;
zone->cur_delta = FT_MulFix( zone->org_delta, scale );
/* round scaled reference position */
zone->cur_ref = FT_PIX_ROUND( zone->cur_ref );
#if 0
if ( zone->cur_ref > zone->cur_top )
zone->cur_ref -= 64;
else if ( zone->cur_ref < zone->cur_bottom )
zone->cur_ref += 64;
#endif
}
}
/* process the families now */
for ( num = 0; num < 2; num++ )
{
PSH_Blue_Zone zone1, zone2;
FT_UInt count1, count2;
PSH_Blue_Table normal, family;
switch ( num )
{
case 0:
normal = &blues->normal_top;
family = &blues->family_top;
break;
default:
normal = &blues->normal_bottom;
family = &blues->family_bottom;
}
zone1 = normal->zones;
count1 = normal->count;
for ( ; count1 > 0; count1--, zone1++ )
{
/* try to find a family zone whose reference position is less */
/* than 1 pixel far from the current zone */
zone2 = family->zones;
count2 = family->count;
for ( ; count2 > 0; count2--, zone2++ )
{
FT_Pos Delta;
Delta = zone1->org_ref - zone2->org_ref;
if ( Delta < 0 )
Delta = -Delta;
if ( FT_MulFix( Delta, scale ) < 64 )
{
zone1->cur_top = zone2->cur_top;
zone1->cur_bottom = zone2->cur_bottom;
zone1->cur_ref = zone2->cur_ref;
zone1->cur_delta = zone2->cur_delta;
break;
}
}
}
}
}
/* calculate the maximum height of given blue zones */
static FT_Short
psh_calc_max_height( FT_UInt num,
const FT_Short* values,
FT_Short cur_max )
{
FT_UInt count;
for ( count = 0; count < num; count += 2 )
{
FT_Short cur_height = values[count + 1] - values[count];
if ( cur_height > cur_max )
cur_max = cur_height;
}
return cur_max;
}
FT_LOCAL_DEF( void )
psh_blues_snap_stem( PSH_Blues blues,
FT_Int stem_top,
FT_Int stem_bot,
PSH_Alignment alignment )
{
PSH_Blue_Table table;
FT_UInt count;
FT_Pos delta;
PSH_Blue_Zone zone;
FT_Int no_shoots;
alignment->align = PSH_BLUE_ALIGN_NONE;
no_shoots = blues->no_overshoots;
/* look up stem top in top zones table */
table = &blues->normal_top;
count = table->count;
zone = table->zones;
for ( ; count > 0; count--, zone++ )
{
delta = stem_top - zone->org_bottom;
if ( delta < -blues->blue_fuzz )
break;
if ( stem_top <= zone->org_top + blues->blue_fuzz )
{
if ( no_shoots || delta <= blues->blue_threshold )
{
alignment->align |= PSH_BLUE_ALIGN_TOP;
alignment->align_top = zone->cur_ref;
}
break;
}
}
/* look up stem bottom in bottom zones table */
table = &blues->normal_bottom;
count = table->count;
zone = table->zones + count-1;
for ( ; count > 0; count--, zone-- )
{
delta = zone->org_top - stem_bot;
if ( delta < -blues->blue_fuzz )
break;
if ( stem_bot >= zone->org_bottom - blues->blue_fuzz )
{
if ( no_shoots || delta < blues->blue_threshold )
{
alignment->align |= PSH_BLUE_ALIGN_BOT;
alignment->align_bot = zone->cur_ref;
}
break;
}
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GLOBAL HINTS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static void
psh_globals_destroy( PSH_Globals globals )
{
if ( globals )
{
FT_Memory memory;
memory = globals->memory;
globals->dimension[0].stdw.count = 0;
globals->dimension[1].stdw.count = 0;
globals->blues.normal_top.count = 0;
globals->blues.normal_bottom.count = 0;
globals->blues.family_top.count = 0;
globals->blues.family_bottom.count = 0;
FT_FREE( globals );
#ifdef DEBUG_HINTER
ps_debug_globals = 0;
#endif
}
}
static FT_Error
psh_globals_new( FT_Memory memory,
T1_Private* priv,
PSH_Globals *aglobals )
{
PSH_Globals globals = NULL;
FT_Error error = FT_Err_Ok;
if ( !FT_NEW( globals ) )
{
FT_UInt count;
FT_Short* read;
globals->memory = memory;
/* copy standard widths */
{
PSH_Dimension dim = &globals->dimension[1];
PSH_Width write = dim->stdw.widths;
write->org = priv->standard_width[0];
write++;
read = priv->snap_widths;
for ( count = priv->num_snap_widths; count > 0; count-- )
{
write->org = *read;
write++;
read++;
}
dim->stdw.count = priv->num_snap_widths + 1;
}
/* copy standard heights */
{
PSH_Dimension dim = &globals->dimension[0];
PSH_Width write = dim->stdw.widths;
write->org = priv->standard_height[0];
write++;
read = priv->snap_heights;
for ( count = priv->num_snap_heights; count > 0; count-- )
{
write->org = *read;
write++;
read++;
}
dim->stdw.count = priv->num_snap_heights + 1;
}
/* copy blue zones */
psh_blues_set_zones( &globals->blues, priv->num_blue_values,
priv->blue_values, priv->num_other_blues,
priv->other_blues, priv->blue_fuzz, 0 );
psh_blues_set_zones( &globals->blues, priv->num_family_blues,
priv->family_blues, priv->num_family_other_blues,
priv->family_other_blues, priv->blue_fuzz, 1 );
/* limit the BlueScale value to `1 / max_of_blue_zone_heights' */
{
FT_Fixed max_scale;
FT_Short max_height = 1;
max_height = psh_calc_max_height( priv->num_blue_values,
priv->blue_values,
max_height );
max_height = psh_calc_max_height( priv->num_other_blues,
priv->other_blues,
max_height );
max_height = psh_calc_max_height( priv->num_family_blues,
priv->family_blues,
max_height );
max_height = psh_calc_max_height( priv->num_family_other_blues,
priv->family_other_blues,
max_height );
/* BlueScale is scaled 1000 times */
max_scale = FT_DivFix( 1000, max_height );
globals->blues.blue_scale = priv->blue_scale < max_scale
? priv->blue_scale
: max_scale;
}
globals->blues.blue_shift = priv->blue_shift;
globals->blues.blue_fuzz = priv->blue_fuzz;
globals->dimension[0].scale_mult = 0;
globals->dimension[0].scale_delta = 0;
globals->dimension[1].scale_mult = 0;
globals->dimension[1].scale_delta = 0;
#ifdef DEBUG_HINTER
ps_debug_globals = globals;
#endif
}
*aglobals = globals;
return error;
}
FT_LOCAL_DEF( FT_Error )
psh_globals_set_scale( PSH_Globals globals,
FT_Fixed x_scale,
FT_Fixed y_scale,
FT_Fixed x_delta,
FT_Fixed y_delta )
{
PSH_Dimension dim;
dim = &globals->dimension[0];
if ( x_scale != dim->scale_mult ||
x_delta != dim->scale_delta )
{
dim->scale_mult = x_scale;
dim->scale_delta = x_delta;
psh_globals_scale_widths( globals, 0 );
}
dim = &globals->dimension[1];
if ( y_scale != dim->scale_mult ||
y_delta != dim->scale_delta )
{
dim->scale_mult = y_scale;
dim->scale_delta = y_delta;
psh_globals_scale_widths( globals, 1 );
psh_blues_scale_zones( &globals->blues, y_scale, y_delta );
}
return 0;
}
FT_LOCAL_DEF( void )
psh_globals_funcs_init( PSH_Globals_FuncsRec* funcs )
{
funcs->create = psh_globals_new;
funcs->set_scale = psh_globals_set_scale;
funcs->destroy = psh_globals_destroy;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshglob.c | C | apache-2.0 | 23,075 |
/***************************************************************************/
/* */
/* pshglob.h */
/* */
/* PostScript hinter global hinting management. */
/* */
/* Copyright 2001, 2002, 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. */
/* */
/***************************************************************************/
#ifndef __PSHGLOB_H__
#define __PSHGLOB_H__
#include FT_FREETYPE_H
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
FT_BEGIN_HEADER
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GLOBAL HINTS INTERNALS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* @constant: */
/* PS_GLOBALS_MAX_BLUE_ZONES */
/* */
/* @description: */
/* The maximum number of blue zones in a font global hints structure. */
/* See @PS_Globals_BluesRec. */
/* */
#define PS_GLOBALS_MAX_BLUE_ZONES 16
/*************************************************************************/
/* */
/* @constant: */
/* PS_GLOBALS_MAX_STD_WIDTHS */
/* */
/* @description: */
/* The maximum number of standard and snap widths in either the */
/* horizontal or vertical direction. See @PS_Globals_WidthsRec. */
/* */
#define PS_GLOBALS_MAX_STD_WIDTHS 16
/* standard and snap width */
typedef struct PSH_WidthRec_
{
FT_Int org;
FT_Pos cur;
FT_Pos fit;
} PSH_WidthRec, *PSH_Width;
/* standard and snap widths table */
typedef struct PSH_WidthsRec_
{
FT_UInt count;
PSH_WidthRec widths[PS_GLOBALS_MAX_STD_WIDTHS];
} PSH_WidthsRec, *PSH_Widths;
typedef struct PSH_DimensionRec_
{
PSH_WidthsRec stdw;
FT_Fixed scale_mult;
FT_Fixed scale_delta;
} PSH_DimensionRec, *PSH_Dimension;
/* blue zone descriptor */
typedef struct PSH_Blue_ZoneRec_
{
FT_Int org_ref;
FT_Int org_delta;
FT_Int org_top;
FT_Int org_bottom;
FT_Pos cur_ref;
FT_Pos cur_delta;
FT_Pos cur_bottom;
FT_Pos cur_top;
} PSH_Blue_ZoneRec, *PSH_Blue_Zone;
typedef struct PSH_Blue_TableRec_
{
FT_UInt count;
PSH_Blue_ZoneRec zones[PS_GLOBALS_MAX_BLUE_ZONES];
} PSH_Blue_TableRec, *PSH_Blue_Table;
/* blue zones table */
typedef struct PSH_BluesRec_
{
PSH_Blue_TableRec normal_top;
PSH_Blue_TableRec normal_bottom;
PSH_Blue_TableRec family_top;
PSH_Blue_TableRec family_bottom;
FT_Fixed blue_scale;
FT_Int blue_shift;
FT_Int blue_threshold;
FT_Int blue_fuzz;
FT_Bool no_overshoots;
} PSH_BluesRec, *PSH_Blues;
/* font globals. */
/* dimension 0 => X coordinates + vertical hints/stems */
/* dimension 1 => Y coordinates + horizontal hints/stems */
typedef struct PSH_GlobalsRec_
{
FT_Memory memory;
PSH_DimensionRec dimension[2];
PSH_BluesRec blues;
} PSH_GlobalsRec;
#define PSH_BLUE_ALIGN_NONE 0
#define PSH_BLUE_ALIGN_TOP 1
#define PSH_BLUE_ALIGN_BOT 2
typedef struct PSH_AlignmentRec_
{
int align;
FT_Pos align_top;
FT_Pos align_bot;
} PSH_AlignmentRec, *PSH_Alignment;
FT_LOCAL( void )
psh_globals_funcs_init( PSH_Globals_FuncsRec* funcs );
#if 0
/* snap a stem width to fitter coordinates. `org_width' is in font */
/* units. The result is in device pixels (26.6 format). */
FT_LOCAL( FT_Pos )
psh_dimension_snap_width( PSH_Dimension dimension,
FT_Int org_width );
#endif
FT_LOCAL( FT_Error )
psh_globals_set_scale( PSH_Globals globals,
FT_Fixed x_scale,
FT_Fixed y_scale,
FT_Fixed x_delta,
FT_Fixed y_delta );
/* snap a stem to one or two blue zones */
FT_LOCAL( void )
psh_blues_snap_stem( PSH_Blues blues,
FT_Int stem_top,
FT_Int stem_bot,
PSH_Alignment alignment );
/* */
#ifdef DEBUG_HINTER
extern PSH_Globals ps_debug_globals;
#endif
FT_END_HEADER
#endif /* __PSHGLOB_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshglob.h | C | apache-2.0 | 6,404 |
/***************************************************************************/
/* */
/* pshinter.c */
/* */
/* FreeType PostScript Hinting module */
/* */
/* Copyright 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. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "pshpic.c"
#include "pshrec.c"
#include "pshglob.c"
#include "pshalgo.c"
#include "pshmod.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshinter.c | C | apache-2.0 | 1,424 |
/***************************************************************************/
/* */
/* pshmod.c */
/* */
/* FreeType PostScript hinter module implementation (body). */
/* */
/* Copyright 2001, 2002, 2007, 2009, 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. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include "pshrec.h"
#include "pshalgo.h"
#include "pshpic.h"
/* the Postscript Hinter module structure */
typedef struct PS_Hinter_Module_Rec_
{
FT_ModuleRec root;
PS_HintsRec ps_hints;
PSH_Globals_FuncsRec globals_funcs;
T1_Hints_FuncsRec t1_funcs;
T2_Hints_FuncsRec t2_funcs;
} PS_Hinter_ModuleRec, *PS_Hinter_Module;
/* finalize module */
FT_CALLBACK_DEF( void )
ps_hinter_done( PS_Hinter_Module module )
{
module->t1_funcs.hints = NULL;
module->t2_funcs.hints = NULL;
ps_hints_done( &module->ps_hints );
}
/* initialize module, create hints recorder and the interface */
FT_CALLBACK_DEF( FT_Error )
ps_hinter_init( PS_Hinter_Module module )
{
FT_Memory memory = module->root.memory;
void* ph = &module->ps_hints;
ps_hints_init( &module->ps_hints, memory );
psh_globals_funcs_init( &module->globals_funcs );
t1_hints_funcs_init( &module->t1_funcs );
module->t1_funcs.hints = (T1_Hints)ph;
t2_hints_funcs_init( &module->t2_funcs );
module->t2_funcs.hints = (T2_Hints)ph;
return 0;
}
/* returns global hints interface */
FT_CALLBACK_DEF( PSH_Globals_Funcs )
pshinter_get_globals_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->globals_funcs;
}
/* return Type 1 hints interface */
FT_CALLBACK_DEF( T1_Hints_Funcs )
pshinter_get_t1_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->t1_funcs;
}
/* return Type 2 hints interface */
FT_CALLBACK_DEF( T2_Hints_Funcs )
pshinter_get_t2_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->t2_funcs;
}
FT_DEFINE_PSHINTER_INTERFACE(
pshinter_interface,
pshinter_get_globals_funcs,
pshinter_get_t1_funcs,
pshinter_get_t2_funcs )
FT_DEFINE_MODULE(
pshinter_module_class,
0,
sizeof ( PS_Hinter_ModuleRec ),
"pshinter",
0x10000L,
0x20000L,
&PSHINTER_INTERFACE_GET, /* module-specific interface */
(FT_Module_Constructor)ps_hinter_init,
(FT_Module_Destructor) ps_hinter_done,
(FT_Module_Requester) NULL ) /* no additional interface for now */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshmod.c | C | apache-2.0 | 3,521 |
/***************************************************************************/
/* */
/* pshmod.h */
/* */
/* PostScript hinter module interface (specification). */
/* */
/* Copyright 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. */
/* */
/***************************************************************************/
#ifndef __PSHMOD_H__
#define __PSHMOD_H__
#include <ft2build.h>
#include FT_MODULE_H
FT_BEGIN_HEADER
FT_DECLARE_MODULE( pshinter_module_class )
FT_END_HEADER
#endif /* __PSHMOD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshmod.h | C | apache-2.0 | 1,458 |
/***************************************************************************/
/* */
/* pshnterr.h */
/* */
/* PS Hinter error codes (specification only). */
/* */
/* Copyright 2003, 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 PSHinter error enumeration constants. */
/* */
/*************************************************************************/
#ifndef __PSHNTERR_H__
#define __PSHNTERR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX PSH_Err_
#define FT_ERR_BASE FT_Mod_Err_PShinter
#include FT_ERRORS_H
#endif /* __PSHNTERR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshnterr.h | C | apache-2.0 | 1,900 |
/***************************************************************************/
/* */
/* pshpic.c */
/* */
/* The FreeType position independent code services for pshinter 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 "pshpic.h"
#include "pshnterr.h"
#ifdef FT_CONFIG_OPTION_PIC
/* forward declaration of PIC init functions from pshmod.c */
void
FT_Init_Class_pshinter_interface( FT_Library library,
PSHinter_Interface* clazz );
void
pshinter_module_class_pic_free( FT_Library library )
{
FT_PIC_Container* pic_container = &library->pic_container;
FT_Memory memory = library->memory;
if ( pic_container->pshinter )
{
FT_FREE( pic_container->pshinter );
pic_container->pshinter = NULL;
}
}
FT_Error
pshinter_module_class_pic_init( FT_Library library )
{
FT_PIC_Container* pic_container = &library->pic_container;
FT_Error error = FT_Err_Ok;
PSHinterPIC* 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->pshinter = container;
/* add call to initialization function when you add new scripts */
FT_Init_Class_pshinter_interface(
library, &container->pshinter_interface );
if ( error )
pshinter_module_class_pic_free( library );
return error;
}
#endif /* FT_CONFIG_OPTION_PIC */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshpic.c | C | apache-2.0 | 2,748 |
/***************************************************************************/
/* */
/* pshpic.h */
/* */
/* The FreeType position independent code services for pshinter 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 __PSHPIC_H__
#define __PSHPIC_H__
FT_BEGIN_HEADER
#include FT_INTERNAL_PIC_H
#ifndef FT_CONFIG_OPTION_PIC
#define PSHINTER_INTERFACE_GET pshinter_interface
#else /* FT_CONFIG_OPTION_PIC */
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
typedef struct PSHinterPIC_
{
PSHinter_Interface pshinter_interface;
} PSHinterPIC;
#define GET_PIC( lib ) ( (PSHinterPIC*)( (lib)->pic_container.pshinter ) )
#define PSHINTER_INTERFACE_GET ( GET_PIC( library )->pshinter_interface )
/* see pshpic.c for the implementation */
void
pshinter_module_class_pic_free( FT_Library library );
FT_Error
pshinter_module_class_pic_init( FT_Library library );
#endif /* FT_CONFIG_OPTION_PIC */
/* */
FT_END_HEADER
#endif /* __PSHPIC_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/pshinter/pshpic.h | C | apache-2.0 | 2,023 |