Commit 89d02578 authored by Oleg.Korshul's avatar Oleg.Korshul Committed by Alexander Trofimov

пока нерабочая версия (включаю конвертер шрифтов). Завтра доделаю

git-svn-id: svn://fileserver/activex/AVS/Sources/TeamlabOffice/trunk/ServerComponents@63600 954022d7-b5bf-4e40-9824-e11837661b57
parent 1c98740b
...@@ -6241,6 +6241,7 @@ DesktopEditor/editor/build/windows/Test/next.bmp svn_mime_002dtype=application%2 ...@@ -6241,6 +6241,7 @@ DesktopEditor/editor/build/windows/Test/next.bmp svn_mime_002dtype=application%2
DesktopEditor/editor/build/windows/Test/open.bmp svn_mime_002dtype=application%2Foctet-stream DesktopEditor/editor/build/windows/Test/open.bmp svn_mime_002dtype=application%2Foctet-stream
DesktopEditor/editor/build/windows/Test/prev.bmp svn_mime_002dtype=application%2Foctet-stream DesktopEditor/editor/build/windows/Test/prev.bmp svn_mime_002dtype=application%2Foctet-stream
DesktopEditor/expat/lib/libexpat.lib svn_mime_002dtype=application%2Foctet-stream DesktopEditor/expat/lib/libexpat.lib svn_mime_002dtype=application%2Foctet-stream
DesktopEditor/fontengine/fontconverter svnc_tsvn_003alogminsize=5
DesktopEditor/freetype_names/FontMaps/Debug/FontMaps.exe svn_mime_002dtype=application%2Foctet-stream DesktopEditor/freetype_names/FontMaps/Debug/FontMaps.exe svn_mime_002dtype=application%2Foctet-stream
DesktopEditor/freetype_names/FontsDictionaryFiles/8514fix.fon svn_mime_002dtype=application%2Foctet-stream DesktopEditor/freetype_names/FontsDictionaryFiles/8514fix.fon svn_mime_002dtype=application%2Foctet-stream
DesktopEditor/freetype_names/FontsDictionaryFiles/8514fixe.fon svn_mime_002dtype=application%2Foctet-stream DesktopEditor/freetype_names/FontsDictionaryFiles/8514fixe.fon svn_mime_002dtype=application%2Foctet-stream
#ifndef _BUILD_FONT_CONVERTER_H
#define _BUILD_FONT_CONVERTER_H
#include <string>
class CFontConverter
{
public:
int ToOTF(std::wstring sFontIn, std::wstring sFontOut, unsigned int* pSymbols, int nCount, std::wstring sName, long nFlag);
int ToOTF2(std::wstring sFontIn, unsigned int* pSymbols, int nCount, std::wstring sName, long nFlag, long lFaceIndex, unsigned char*& pDstData, int& nDstLen);
};
#endif /* _BUILD_FONT_CONVERTER_H */
#ifndef _ASC_FONT_CONVERTER_CONSTS_H_
#define _ASC_FONT_CONVERTER_CONSTS_H_
namespace NSFontConverter
{
const long c_lFromAll = 0xFFFF; // Конвертировать из любого формата
const long c_lFromTT = 0x0010; // Конвертировать из TrueType формата
const long c_lFromT1 = 0x0020; // Конвертировать из Type 1 формата
const long c_lFromCFF = 0x0040; // Конвертировать из CFF формата
const long c_lFlagsGids = 0x0080;
}
#endif // _ASC_FONT_CONVERTER_CONSTS_H_
// FontConverter.cpp : Implementation of CFontConverter
#include "FontConverter.h"
// CFontConverter12
This diff is collapsed.
#ifndef _FONT_FILE_BASE_H
#define _FONT_FILE_BASE_H
#include <stdio.h>
#include "MemoryUtils.h"
//------------------------------------------------------------------------
typedef void (*FontFileOutputFunc)(void *pStream, char *sData, int nLen);
//------------------------------------------------------------------------
// CFontFileBase
//------------------------------------------------------------------------
class CFontFileBase
{
public:
virtual ~CFontFileBase()
{
if ( m_bFreeFileData )
MemUtilsFree( m_sFileData );
}
protected:
CFontFileBase(char *sFile, int nLen, BOOL bFreeFileData)
{
m_sFileData = m_sFile = (unsigned char *)sFile;
m_nLen = nLen;
m_bFreeFileData = bFreeFileData;
m_nPos = 0;
}
void Reset()
{
m_nPos = 0;
}
static char *ReadFile(wchar_t *wsFileName, int *pnFileLen)
{
FILE *pFile;
if ( !( pFile = _wfopen( wsFileName, _T("rb") ) ) )
return NULL;
fseek( pFile, 0, SEEK_END );
int nLen = (int)ftell( pFile );
fseek( pFile, 0, SEEK_SET );
char *sBuffer = (char *)MemUtilsMalloc( nLen );
if ( (int)fread( sBuffer, 1, nLen, pFile) != nLen )
{
MemUtilsFree( sBuffer );
fclose( pFile );
return NULL;
}
fclose( pFile );
*pnFileLen = nLen;
return sBuffer;
}
// S = signed / U = unsigned
// 8/16/32/Var = word length, in bytes
// BE = big endian
int GetS8 (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
int nRes = m_sFile[ nPos ];
if ( nRes & 0x80 )
nRes |= ~0xff;
return nRes;
}
int GetU8 (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
return m_sFile[ nPos ];
}
int GetS16BE (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + 1 >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
int nRes = m_sFile[nPos];
nRes = (nRes << 8) + m_sFile[ nPos + 1 ];
if ( nRes & 0x8000 )
nRes |= ~0xffff;
return nRes;
}
int GetU16BE (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + 1 >= m_nLen)
{
*pbSuccess = FALSE;
return 0;
}
int nRes = m_sFile[ nPos ];
nRes = (nRes << 8) + m_sFile[ nPos + 1 ];
return nRes;
}
int GetS32BE (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + 3 >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
int nRes = m_sFile[ nPos ];
nRes = (nRes << 8) + m_sFile[nPos + 1];
nRes = (nRes << 8) + m_sFile[nPos + 2];
nRes = (nRes << 8) + m_sFile[nPos + 3];
if ( nRes & 0x80000000 )
nRes |= ~0xffffffff;
return nRes;
}
unsigned int GetU32BE (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + 3 >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
unsigned int nRes = m_sFile[nPos];
nRes = (nRes << 8) + m_sFile[nPos + 1];
nRes = (nRes << 8) + m_sFile[nPos + 2];
nRes = (nRes << 8) + m_sFile[nPos + 3];
return nRes;
}
unsigned int GetU32LE (int nPos, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + 3 >= m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
unsigned int nRes = m_sFile[nPos + 3];
nRes = (nRes << 8) + m_sFile[nPos + 2];
nRes = (nRes << 8) + m_sFile[nPos + 1];
nRes = (nRes << 8) + m_sFile[nPos + 0];
return nRes;
}
unsigned int GetUVarBE(int nPos, int nSize, BOOL *pbSuccess)
{
*pbSuccess = TRUE;
if ( nPos < 0 || nPos + nSize > m_nLen )
{
*pbSuccess = FALSE;
return 0;
}
unsigned int nRes = 0;
for ( int nIndex = 0; nIndex < nSize; ++nIndex )
nRes = (nRes << 8) + m_sFile[nPos + nIndex];
return nRes;
}
BOOL CheckRegion(int nPos, int nSize)
{
return (nPos >= 0 && nPos + nSize >= nPos && nPos + nSize <= m_nLen);
}
int ReadS8 (BOOL *pbSuccess)
{
return GetS8( m_nPos++, pbSuccess );
}
int ReadU8 (BOOL *pbSuccess)
{
return GetU8( m_nPos++, pbSuccess );
}
unsigned int ReadU32BE(BOOL *pbSuccess)
{
unsigned int unResult = GetU32BE( m_nPos, pbSuccess );
m_nPos += 4;
return unResult;
}
unsigned int ReadU32LE(BOOL *pbSuccess)
{
unsigned int unResult = GetU32LE( m_nPos, pbSuccess );
m_nPos += 4;
return unResult;
}
int Read(void* pDestBuffer, int nSize)
{
if ( m_nPos + nSize >= m_nLen )
nSize = m_nLen - m_nPos - 1;
memcpy( pDestBuffer, (m_sFile + m_nPos), nSize );
m_nPos += nSize;
return nSize;
}
protected:
unsigned char *m_sFileData;
unsigned char *m_sFile;
int m_nLen;
BOOL m_bFreeFileData;
int m_nPos;
};
#endif /* _FONT_FILE_BASE_H */
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#ifndef _FONT_FILE_TRUETYPE_H
#define _FONT_FILE_TRUETYPE_H
#include "FontFileBase.h"
class StringExt;
class CHash;
//------------------------------------------------------------------------
#define ttcfTag 0x74746366
//------------------------------------------------------------------------
struct TrueTypeTable
{
unsigned int unTag;
unsigned int unChecksum;
int nOffset;
int nOrigOffset;
int nLen;
};
struct TrueTypeCmap
{
int nPlatform;
int nEncoding;
int nOffset;
int nLen;
int nFormat;
};
struct TrueTypeLoca
{
int nIndex;
int nOrigOffset;
int nNewOffset;
int nLen;
};
#define cffTag 0x43464620
#define maxpTag 0x6d617870
#define cmapTag 0x636d6170
#define glyfTag 0x676c7966
#define headTag 0x68656164
#define hheaTag 0x68686561
#define hmtxTag 0x686d7478
#define locaTag 0x6c6f6361
#define nameTag 0x6e616d65
#define os2Tag 0x4f532f32
#define postTag 0x706f7374
#define cvtTag 0x63767420
#define fpgmTag 0x6670676d
#define prepTag 0x70726570
static int CompareTrueTypeLocaOffset(const void *pL1, const void *pL2)
{
TrueTypeLoca *pLoca1 = (TrueTypeLoca *)pL1;
TrueTypeLoca *pLoca2 = (TrueTypeLoca *)pL2;
if ( pLoca1->nOrigOffset == pLoca2->nOrigOffset )
return pLoca1->nIndex - pLoca2->nIndex;
return pLoca1->nOrigOffset - pLoca2->nOrigOffset;
}
static int CompareTrueTypeLocaIndex(const void *pL1, const void *pL2)
{
TrueTypeLoca *pLoca1 = (TrueTypeLoca *)pL1;
TrueTypeLoca *pLoca2 = (TrueTypeLoca *)pL2;
return pLoca1->nIndex - pLoca2->nIndex;
}
static int CompareTrueTypeTableTag(const void *pTab1, const void *pTab2)
{
TrueTypeTable *pTable1 = (TrueTypeTable *)pTab1;
TrueTypeTable *pTable2 = (TrueTypeTable *)pTab2;
return (int)pTable1->unTag - (int)pTable2->unTag;
}
//------------------------------------------------------------------------
struct T42Table
{
char *sTag; // 4-байтовое название
BOOL bRequired; // Требуется ли по спецификации TrueType?
};
// TrueType tables to be embedded in Type 42 fonts.
// NB: the table names must be in alphabetical order here.
#define nT42Tables 11
static T42Table t42Tables[nT42Tables] =
{
{ "cvt ", TRUE },
{ "fpgm", TRUE },
{ "glyf", TRUE },
{ "head", TRUE },
{ "hhea", TRUE },
{ "hmtx", TRUE },
{ "loca", TRUE },
{ "maxp", TRUE },
{ "prep", TRUE },
{ "vhea", FALSE },
{ "vmtx", FALSE }
};
#define t42HeadTable 3
#define t42LocaTable 6
#define t42GlyfTable 2
#define t42VheaTable 9
#define t42VmtxTable 10
//------------------------------------------------------------------------
// CFontFileTrueType
//------------------------------------------------------------------------
class CFontFileTrueType: public CFontFileBase
{
public:
// Создаем объект TTF из буфера.
static CFontFileTrueType *LoadFromBuffer(char *sBuffer, int lenA);
// Создаем объект TTF из файла.
static CFontFileTrueType *LoadFromFile(wchar_t *wsFileName);
virtual ~CFontFileTrueType();
// TRUE, если данный OpenType фонт содержите данные формата CFF.
// FALSE,если это TrueType фонт ( или OpenType фонт с данными в формате TrueType).
BOOL IsOpenTypeCFF()
{
return m_bOpenTypeCFF;
}
int GetCmapsCount();
int GetCmapPlatform(int nIndex);
int GetCmapEncoding(int nIndex);
int FindCmap(int nPlatform, int nEncoding);
// Возвращает GID, соответствующий символу <nChar> в <nIndex>ной CMap.
unsigned short MapCodeToGID(int nCMapIndex, int nChar);
// Возвращает GID, соответствующий <sName> в таблице post. Возвращает 0,
// если символа с таким именем не нашли, или таблицы post нет.
int MapNameToGID(char *sName);
// Возвращает карту CIDs в GIDs, и возваращет количество элементов
// CIDs в *<pnCIDs>. Только для CID фонтов( OpenType CFF )
unsigned short *GetCIDToGIDMap(int *pnCIDs);
// Лицензионные ограничения на включение фонта( в соответствие со
// спецификацией True Type):
// * 4: таблицы OS/2 не найдена или некорректна
// * 3: разрешено устанавливать
// * 2: разрешено редактировать
// * 1: разрешено просматривать и печатать
// * 0: ограничено лицензией
int GetEmbeddingRestrictions();
// Convert to a Type 42 font, suitable for embedding in a PostScript
// file. <psName> will be used as the PostScript font name (so we
// don't need to depend on the 'name' table in the font). The
// <encoding> array specifies the mapping from char codes to names.
// If <encoding> is NULL, the encoding is unknown or undefined. The
// <codeToGID> array specifies the mapping from char codes to GIDs.
// (Not useful for OpenType CFF fonts.)
void ToType42(char *sPSName, char **ppEncoding, unsigned short *pCodeToGID, FontFileOutputFunc pOutputFunc, void *pOutputStream );
// Convert to a Type 1 font, suitable for embedding in a PostScript
// file. This is only useful with 8-bit fonts. If <newEncoding> is
// not NULL, it will be used in place of the encoding in the Type 1C
// font. If <ascii> is true the eexec section will be hex-encoded,
// otherwise it will be left as binary data. If <psName> is
// non-NULL, it will be used as the PostScript font name. (Only
// useful for OpenType CFF fonts.)
void ToType1(char *sPSName, char **ppNewEncoding, BOOL bASKII, FontFileOutputFunc pOutputFunc, void *pOutputStream );
// Convert to a Type 2 CIDFont, suitable for embedding in a
// PostScript file. <psName> will be used as the PostScript font
// name (so we don't need to depend on the 'name' table in the
// font). The <cidMap> array maps CIDs to GIDs; it has <nCIDs>
// entries. (Not useful for OpenType CFF fonts.)
void ToCIDType2(char *sPSName, unsigned short *pCIDMap, int nCIDCount, BOOL bNeedVerticalMetrics, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Convert to a Type 0 CIDFont, suitable for embedding in a
// PostScript file. <psName> will be used as the PostScript font
// name. (Only useful for OpenType CFF fonts.)
void ToCIDType0(char *sPSName, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Convert to a Type 0 (but non-CID) composite font, suitable for
// embedding in a PostScript file. <psName> will be used as the
// PostScript font name (so we don't need to depend on the 'name'
// table in the font). The <cidMap> array maps CIDs to GIDs; it has
// <nCIDs> entries. (Not useful for OpenType CFF fonts.)
void ToType0(char *sPSName, unsigned short *pCIDMap, int nCIDCount, BOOL bNeedVerticalMetrics, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Convert to a Type 0 (but non-CID) composite font, suitable for
// embedding in a PostScript file. <psName> will be used as the
// PostScript font name. (Only useful for OpenType CFF fonts.)
void ToType0(char *sPSName, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Записываем TrueTypeFont File, заполняя недостающие таблицы и корректируя
// различные ошибки. Если задан парметр <sName>, в шрифте переписываем таблицу
// 'name'. Если задан парамтре <pCodeToGID>, тогда в шрифте переписываем
// таблицу 'cmap'.
void WriteTTF(FontFileOutputFunc pOutputFunc, void *pOutputStream, char *sName = NULL, unsigned short *pCodeToGID = NULL, unsigned char *pUseGlyfs = NULL, long lGlyfsCount = 0) ;
private:
CFontFileTrueType(char *sFileName, int nLen, BOOL bFreeFileData);
void ConvertEncoding (char **ppEncoding, FontFileOutputFunc pOutputFunc, void *pOutputStream);
void ConvertCharStrings(char **ppEncoding, unsigned short *pnCodeToGID, FontFileOutputFunc pOutputFunc, void *pOutputStream);
void ConvertSfnts (FontFileOutputFunc pOutputFunc, void *pOutputStream, StringExt *seName, BOOL bNeedVerticalMetrics);
void DumpString(unsigned char *sString, int nLength, FontFileOutputFunc pOutputFunc, void *pOutputStream);
unsigned int ComputeTableChecksum(unsigned char *sData, int nLength);
void Parse();
void ReadPostTable();
int SeekTable(char *sTag);
private:
TrueTypeTable *m_pTables;
int m_nTablesCount;
TrueTypeCmap *m_pCMaps;
int m_nCMapsCount;
int m_nGlyphs;
int m_nLocaFormat;
int m_arrBBox[4];
CHash *m_pNameToGID;
BOOL m_bOpenTypeCFF;
BOOL m_bSuccess;
};
#endif /* _FONT_FILE_TRUETYPE_H */
This diff is collapsed.
#ifndef _FONT_FILE_TYPE1_H
#define _FONT_FILE_TYPE1_H
#include "Utils.h"
#include "FontFileBase.h"
#include "FontFileEncodings.h"
#define type1MaxBlueValues 14 // 7 пар
#define type1MaxOtherBlues 10 // 5 пар
#define type1MaxStemSnap 12
struct Type1PrivateDict
{
int arrnBlueValues[type1MaxBlueValues];
int nBlueValues;
int arrnOtherBlues[type1MaxOtherBlues];
int nOtherBlues;
int arrnFamilyBlues[type1MaxBlueValues];
int nFamilyBlues;
int arrnFamilyOtherBlues[type1MaxOtherBlues];
int nFamilyOtherBlues;
double dBlueScale;
int nBlueShift;
int nBlueFuzz;
double dStdHW;
BOOL bHasStdHW;
double dStdVW;
BOOL bHasStdVW;
double arrdStemSnapH[type1MaxStemSnap];
int nStemSnapH;
double arrdStemSnapV[type1MaxStemSnap];
int nStemSnapV;
BOOL bHasForceBold;
BOOL bForceBold;
int nLanguageGroup;
int nLenIV;
double dExpansionFactor;
};
struct Type1TopDict
{
// TO DO: дополнить данную структуру
double arrdFontMatrix[6];
double arrdFontBBox[4];
};
// команды
const int c_nType1hstem = 0x0001; // 'hstem'
const int c_nType1vstem = 0x0003; // 'vstem'
const int c_nType1vmoveto = 0x0004; // 'vmoveto'
const int c_nType1rlineto = 0x0005; // 'rlineto'
const int c_nType1hlineto = 0x0006; // 'hlineto'
const int c_nType1vlineto = 0x0007; // 'vlineto'
const int c_nType1rrcurveto = 0x0008; // 'rrcurveto'
const int c_nType1closepath = 0x0009; // 'closepath' не используется в Type2
const int c_nType1callsubr = 0x000A; // 'callsubr
const int c_nType1return = 0x000B; // 'return'
const int c_nType1dotsection = 0x000C; // 'dotsection' не используется в Type2
const int c_nType1vstem3 = 0x010C; // 'vstem'
const int c_nType1hstem3 = 0x020C; // 'hstem'
const int c_nType1seac = 0x060C; // 'seac' Type1 only
const int c_nType1sbw = 0x070C; // 'sbw' Type1 only
const int c_nType1sub = 0x0B0C; // 'sub'
const int c_nType1div = 0x0C0C; // 'div'
const int c_nType1callothersubr = 0x100C; // 'callothersubr'
const int c_nType1pop = 0x110C; // 'pop'
const int c_nType1setcurrentpoint = 0x210C; // 'setcurrentpoint' не используется в Type2
const int c_nType1hsbw = 0x000D; // 'hsbw'
const int c_nType1endchar = 0x000E; // 'endchar'
const int c_nType1rmoveto = 0x0015; // 'rmoveto'
const int c_nType1hmoveto = 0x0016; // 'hmoveto'
const int c_nType1vhcurveto = 0x001E; // 'vhcurveto'
const int c_nType1hvcurveto = 0x001F; // 'hvcurveto'
struct Type1CharstringItem
{
int nValue; // Значение
BOOL bCommand; // TRUE: значение - номер команды, FALSE: значение - параметр команды
Type1CharstringItem(int nVal, BOOL bCom)
{
nValue = nVal;
bCommand = bCom;
}
};
struct Type1Charstring
{
CSimpleArray<Type1CharstringItem> arrCharstring;
int nWidth;
int nLSB;
Type1Charstring()
{
nWidth = 0;
nLSB = 0;
}
Type1Charstring(CSimpleArray<Type1CharstringItem> &arrCs, int nW, int nL)
{
arrCharstring = arrCs;
nWidth = nW;
nLSB = nL;
}
};
struct Type1Glyph
{
CString sGlyph; // Type1 имя глифа
int nUnicode; // Юникодное значение глифа
Type1Charstring oData;
int nReserved; // Используем для SID при конвертации Type1->Type2
Type1Glyph(CString& sGlyf, int nUni, Type1Charstring &oCharstring)
{
sGlyph = sGlyf;
nUnicode = nUni;
oData = oCharstring;
nReserved = 0;
}
};
static int CompareType1Glyph(const void *pGlyph1, const void *pGlyph2)
{
Type1Glyph *pGlyf1 = (Type1Glyph *)pGlyph1;
Type1Glyph *pGlyf2 = (Type1Glyph *)pGlyph2;
return pGlyf1->nUnicode - pGlyf2->nUnicode;
}
//------------------------------------------------------------------------
// CFontFileType1
//------------------------------------------------------------------------
class CFontFileType1: public CFontFileBase
{
public:
static CFontFileType1 *LoadFromBuffer(char *sBuffer, int nLen);
static CFontFileType1 *LoadFromFile(wchar_t *wsFileName);
virtual ~CFontFileType1();
char *GetName();
char **GetEncoding();
void WriteEncoded(char **ppNewEncoding, FontFileOutputFunc pOutputFunc, void *pOutputStream);
void ToCFF(FontFileOutputFunc pOutputFunc, void *pOutputStream);
private:
CFontFileType1(char *sBuffer, int nLen, BOOL bFreeData);
void Parse();
void DecryptEexec(unsigned char** ppEexecBuffer, int nLen);
Type1Charstring DecodeCharString(unsigned char *sString, int nLen);
char *GetNextLine(char *sLine);
bool RemovePfbMarkers();
template<int nMax>
int ReadDoubleArray(unsigned char *sString, int nLen, double (&pArray)[nMax])
{
int nStart = 0;
while( sString[nStart] != '[' )
{
nStart++;
if ( nStart >= nLen )
return 0;
}
int nEnd = ++nStart;
while ( sString[nEnd] != ']' )
{
nEnd++;
if ( nEnd >= nLen )
return 0;
}
sString = sString + nStart;
nLen = nEnd - nStart;
int nCount = 0;
const int c_nNumLimit = 32;
unsigned char sBuffer[c_nNumLimit];
int nBufPos = 0;
bool bNewItem = true;
for ( int nIndex = 0; nIndex < nLen; ++nIndex )
{
unsigned char unChar = sString[nIndex];
if ( ' ' == unChar )
{
if ( !bNewItem )
bNewItem = true;
continue;
}
if ( bNewItem )
{
if ( nCount >= nMax )
break;
// Добавляем предыдущее число в массив
if ( nCount > 0 )
pArray[nCount - 1] = Utils::GetDouble( (const char *)sBuffer );
memset( sBuffer, 0x00, c_nNumLimit );
nBufPos = 0;
bNewItem = false;
nCount++;
}
sBuffer[nBufPos++] = unChar;
}
if ( 0 != sBuffer[0] && nCount > 0 )
pArray[nCount - 1] = Utils::GetDouble( (const char *)sBuffer );
return nCount;
}
template<int nMax>
int ReadIntArray (unsigned char *sString, int nLen, int (&pArray)[nMax])
{
int nStart = 0;
while( sString[nStart] != '[' )
{
nStart++;
if ( nStart >= nLen )
return 0;
}
int nEnd = ++nStart;
while ( sString[nEnd] != ']' )
{
nEnd++;
if ( nEnd >= nLen )
return 0;
}
sString = sString + nStart;
nLen = nEnd - nStart;
int nCount = 0;
const int c_nNumLimit = 32;
unsigned char sBuffer[c_nNumLimit];
int nBufPos = 0;
bool bNewItem = true;
for ( int nIndex = 0; nIndex < nLen; ++nIndex )
{
unsigned char unChar = sString[nIndex];
if ( ' ' == unChar )
{
if ( !bNewItem )
bNewItem = true;
continue;
}
if ( bNewItem )
{
if ( nCount >= nMax )
break;
// Добавляем предыдущее число в массив
if ( nCount > 0 )
pArray[nCount - 1] = Utils::GetInteger( (const char *)sBuffer );
memset( sBuffer, 0x00, c_nNumLimit );
nBufPos = 0;
bNewItem = false;
nCount++;
}
sBuffer[nBufPos++] = unChar;
}
if ( 0 != sBuffer[0] && nCount > 0 )
pArray[nCount - 1] = Utils::GetInteger( (const char *)sBuffer );
return nCount;
}
double ReadDouble (unsigned char *sString, int nMaxLen)
{
// Смещаемся к первому пробелу (после него идет значение)
int nPos = 0;
while ( ' ' == sString[nPos] && nPos < nMaxLen )
nPos++;
return Utils::GetDouble( (const char*)( sString + nPos ) );
}
int ReadInt (unsigned char *sString, int nMaxLen)
{
int nPos = 0;
while ( ' ' == sString[nPos] && nPos < nMaxLen )
nPos++;
return Utils::GetInteger( (const char*)( sString + nPos ) );
}
BOOL ReadBool (unsigned char *sString, int nMaxLen)
{
int nStartPos = 0;
while ( ' ' == sString[nStartPos] && nStartPos < nMaxLen )
nStartPos++;
if ( nStartPos >= nMaxLen - 4 )
return FALSE;
if ( 't' == sString[nStartPos + 0] &&
'r' == sString[nStartPos + 1] &&
'u' == sString[nStartPos + 2] &&
'e' == sString[nStartPos + 3] )
return TRUE;
return FALSE;
}
Type1Charstring FlattenCharstring(Type1Charstring& oCharstring, int nBias = 0);
void CFFCreateIndexHeader(FontFileOutputFunc pOutputFunc, void *pOutputStream, CSimpleArray<CString> aObjects);
void CFFCreateIndexHeader(FontFileOutputFunc pOutputFunc, void *pOutputStream, CSimpleArray<Type1Charstring> aObjects);
void CFFEncodeNumber (FontFileOutputFunc pOutputFunc, void *pOutputStream, int nValue, bool bForceLong = false);
void CFFEncodeNumber (FontFileOutputFunc pOutputFunc, void *pOutputStream, double dValue);
private:
char *m_sName;
char **m_arrEncoding;
BOOL m_bParsed;
Type1PrivateDict m_oPrivateDict;
Type1TopDict m_oTopDict;
CSimpleArray<Type1Glyph> m_arrCharstrings;
CSimpleArray<Type1Charstring> m_arrSubrs;
};
#endif /* _FONT_FILE_TYPE1_H */
This diff is collapsed.
#ifndef _FONT_FILE_TYPE1C_H
#define _FONT_FILE_TYPE1C_H
#include "FontFileBase.h"
class StringExt;
//------------------------------------------------------------------------
struct Type1CIndex
{
int nPos; // Позиция в файле от начала файла
int nCount; // Количество вхождений
int nOffsetSize; // Offset size
int nStartPos; // Начальная позиция index data - 1
int nEndPos; // Позиция следующего байта после Type1CIndex
};
struct Type1CIndexVal
{
int nPos; // Позиция в файле от начала файла
int nLen; // Длина в байтах
};
struct Type1CTopDict
{
int nFirstOperator;
int nVersionSID;
int nNoticeSID;
int nCopyrightSID;
int nFullNameSID;
int nFamilyNameSID;
int nWeightSID;
int nIsFixedPitch;
double dItalicAngle;
double dUnderlinePosition;
double dUnderlineThickness;
int nPaintType;
int nCharStringType;
double arrdFontMatrix[6];
BOOL bHasFontMatrix; // В CID фонтах возможно матрица фонта лежит в FD, а не в верхнем словаре
int nUniqueID;
double arrdFontBBox[4];
double dStrokeWidth;
int nCharsetOffset;
int nEncodingOffset;
int nCharStringsOffset;
int nPrivateSize;
int nPrivateOffset;
// CIDFont entries
int nRegistrySID;
int nOrderingSID;
int nSupplement;
int nFDArrayOffset;
int nFDSelectOffset;
};
#define type1CMaxBlueValues 14
#define type1CMaxOtherBlues 10
#define type1CMaxStemSnap 12
struct Type1CPrivateDict
{
double arrdFontMatrix[6];
BOOL bHasFontMatrix;
int arrnBlueValues[type1CMaxBlueValues];
int nBlueValues;
int arrnOtherBlues[type1CMaxOtherBlues];
int nOtherBlues;
int arrnFamilyBlues[type1CMaxBlueValues];
int nFamilyBlues;
int arrnFamilyOtherBlues[type1CMaxOtherBlues];
int nFamilyOtherBlues;
double dBlueScale;
int nBlueShift;
int nBlueFuzz;
double dStdHW;
BOOL bHasStdHW;
double dStdVW;
BOOL bHasStdVW;
double arrdStemSnapH[type1CMaxStemSnap];
int nStemSnapH;
double arrdStemSnapV[type1CMaxStemSnap];
int nStemSnapV;
BOOL bForceBold;
BOOL bHasForceBold;
double dForceBoldThreshold;
int nLanguageGroup;
double dExpansionFactor;
int nInitialRandomSeed;
int nSubrsOffset;
double dDefaultWidthX;
BOOL bDefaultWidthXFP;
double dNominalWidthX;
BOOL bNominalWidthXFP;
};
struct Type1COperator
{
BOOL bIsNumber; // true -> number, false -> operator
BOOL bIsFloat; // true -> floating point number, false -> int
union
{
double dNumber;
int nOperator;
};
};
struct Type1CEexecBuf
{
FontFileOutputFunc pOutputFunc;
void *pOutputStream;
BOOL bASKII; // ASCII кодировка?
unsigned short unEncryptionKey; // eexec encryption key
int nLine; // количество eexec-символов, оставшихся на текущей строке
};
//------------------------------------------------------------------------
// CFontFileType1C
//------------------------------------------------------------------------
class CFontFileType1C: public CFontFileBase
{
public:
static CFontFileType1C *LoadFromBuffer(char *sBuffer, int nLen);
static CFontFileType1C *LoadFromFile(wchar_t *wsFileName);
virtual ~CFontFileType1C();
char *GetName();
// Возвращаем кодировку, как массив 256 имен (некоторые могут быть
// NULL). Используется только для 8-битных фонтов.
char **GetEncoding();
unsigned short *GetCIDToGIDMap(int *arrCIDs);
// Convert to a Type 1 font, suitable for embedding in a PostScript
// file. This is only useful with 8-bit fonts. If <newEncoding> is
// not NULL, it will be used in place of the encoding in the Type 1C
// font. If <ascii> is true the eexec section will be hex-encoded,
// otherwise it will be left as binary data. If <psName> is non-NULL,
// it will be used as the PostScript font name.
void ToType1(char *sPSName, char **ppNewEncoding, BOOL bASKII, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Convert to a Type 0 CIDFont, suitable for embedding in a
// PostScript file. <psName> will be used as the PostScript font
// name.
void ToCIDType0(char *sPSName, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Convert to a Type 0 (but non-CID) composite font, suitable for
// embedding in a PostScript file. <psName> will be used as the
// PostScript font name.
void ToType0(char *sPSName, FontFileOutputFunc pOutputFunc, void *pOutputStream);
// Конвертируем в OpenType (CFF)
void ToOpenTypeCFF(FontFileOutputFunc pOutputFunc, void *pOutputStream, FT_Face pFace);
private:
CFontFileType1C(char *sBuffer, int nLen, BOOL bFreeData);
void EexecConvertGlyph(Type1CEexecBuf *pEexecBuf, char *sGlyphName, int nOffset, int nBytes, Type1CIndex *pSubrIndex, Type1CPrivateDict *pDict);
void ConvertGlyph(int nOffset, int nBytes, StringExt *seCharBuffer, Type1CIndex *pSubrIndex, Type1CPrivateDict *pDict, BOOL bTop);
void ConvertGlyphWidth(BOOL bUseOperation, StringExt *seCharBuffer, Type1CPrivateDict *pDict);
void ConvertNum(double dValue, BOOL bIsFloat, StringExt *seCharBuffer);
void EexecWrite(Type1CEexecBuf *pEexecBuf, char *sBuffer);
void EexecWriteCharString(Type1CEexecBuf *pEexecBuf, unsigned char *sBuffer, int nLen);
BOOL Parse();
void ReadTopDict();
void ReadFD(int nOffset, int nLength, Type1CPrivateDict *pDict);
void ReadPrivateDict(int nOffset, int nLength, Type1CPrivateDict *pDict);
void ReadFDSelect();
void BuildEncoding();
BOOL ReadCharset();
int GetOperator(int nPos, BOOL bCharString, BOOL *pbSuccess);
int GetDeltaIntArray(int *pArray, int nMaxLen);
int GetDeltaDoubleArray(double *pArray, int nMaxLen);
void GetIndex(int nPos, Type1CIndex *pIndex, BOOL *pbSuccess);
void GetIndexVal(Type1CIndex *pIndex, int nIndex, Type1CIndexVal *pIndexVal, BOOL *bSuccess);
char *GetString(int nSID, char *sBuffer, BOOL *pbSuccess);
unsigned int ComputeTTTableChecksum(unsigned char *sData, int nLength)
{
unsigned int nWord = 0;
unsigned int nChecksum = 0;
for ( int nIndex = 0; nIndex + 3 < nLength; nIndex += 4 )
{
nWord = ( ( sData[ nIndex ] & 0xff) << 24) + ((sData[ nIndex + 1 ] & 0xff) << 16) + ((sData[ nIndex + 2 ] & 0xff) << 8) + (sData[ nIndex + 3 ] & 0xff);
nChecksum += nWord;
}
if ( nLength & 3 )
{
nWord = 0;
int nTemp = nLength & ~3;
switch ( nLength & 3 )
{
case 3:
nWord |= (sData[nTemp + 2] & 0xff) << 8;
case 2:
nWord |= (sData[nTemp + 1] & 0xff) << 16;
case 1:
nWord |= (sData[nTemp] & 0xff) << 24;
break;
}
nChecksum += nWord;
}
return nChecksum;
}
private:
StringExt *m_seName;
char **m_arrEncoding;
Type1CIndex m_oNameIndex;
Type1CIndex m_oTopDictIndex;
Type1CIndex m_oStringIndex;
Type1CIndex m_oGsubrIndex;
Type1CIndex m_oCharStringsIndex;
Type1CTopDict m_oTopDict;
Type1CPrivateDict *m_pPrivateDicts;
int m_nGlyphsCount;
int m_nFDsCount;
unsigned char *m_pnFDSelect;
unsigned short *m_pnCharset;
int m_nGsubrBias;
BOOL m_bSuccessParsed;
Type1COperator m_arrOperators[49];
int m_nOperatorsCount;
int m_nHints; // для текущего символа
BOOL m_bFirstOperator;
BOOL m_bOpenPath; // true, если есть незакрытый пат
};
#endif /* _FONT_FILE_TYPE1C_H */
This diff is collapsed.
#ifndef _ASC_FONTCONVERTER_HASH_H_
#define _ASC_FONTCONVERTER_HASH_H_
namespace NSFontConverter
{
class StringExt;
struct THashBucket;
struct THashIter;
//------------------------------------------------------------------------
// CHash
//------------------------------------------------------------------------
class CHash
{
public:
CHash(bool bDeleteKeys = false);
~CHash();
void Add(StringExt *seKey, void *pValue);
void Add(StringExt *seKey, int nValue);
void Replace(StringExt *seKey, void *pValue);
void Replace(StringExt *seKey, int nValue);
void *Lookup(StringExt *seKey);
void *Lookup(char *sKey);
int LookupInt(StringExt *seKey);
int LookupInt(char *sKey);
void *Remove(StringExt *seKey);
void *Remove(char *seKey);
int RemoveInt(StringExt *seKey);
int RemoveInt(char *sKey);
int GetLength()
{
return m_nLength;
}
void StartIter(THashIter **ppIter);
bool GetNext(THashIter **ppIter, StringExt **pseKey, void **ppValue );
bool GetNext(THashIter **ppIter, StringExt **pseKey, int *pnValue );
void DeleteIter(THashIter **ppIter);
private:
void Expand();
THashBucket *Find(StringExt *seKey, int *pnHashIndex );
THashBucket *Find(char *sKey, int *pnHashIndex );
int Hash(StringExt *seKey);
int Hash(char *sKey);
private:
bool m_bDeleteKeys; // Будем ли удалять имена? set if key strings should be deleted
int m_nBucketsCount; // Количество наборов
int m_nLength; // Количество вхождений
THashBucket **m_ppTable;
};
#define DeleteCHash(hash, T) \
do { \
CHash *_hash = (hash); \
{ \
THashIter *_iter; \
StringExt *_key; \
void *_p; \
_hash->StartIter(&_iter); \
while (_hash->GetNext(&_iter, &_key, &_p)) { \
delete (T*)_p; \
} \
delete _hash; \
} \
} while(0)
}
#endif /* _ASC_FONTCONVERTER_HASH_H_ */
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment