summaryrefslogtreecommitdiffstats
path: root/vcl/source/fontsubset
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:51:28 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:51:28 +0000
commit940b4d1848e8c70ab7642901a68594e8016caffc (patch)
treeeb72f344ee6c3d9b80a7ecc079ea79e9fba8676d /vcl/source/fontsubset
parentInitial commit. (diff)
downloadlibreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.tar.xz
libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.zip
Adding upstream version 1:7.0.4.upstream/1%7.0.4upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vcl/source/fontsubset')
-rw-r--r--vcl/source/fontsubset/cff.cxx2061
-rw-r--r--vcl/source/fontsubset/fontsubset.cxx163
-rw-r--r--vcl/source/fontsubset/list.cxx229
-rw-r--r--vcl/source/fontsubset/list.h89
-rw-r--r--vcl/source/fontsubset/sft.cxx2635
-rw-r--r--vcl/source/fontsubset/ttcr.cxx1505
-rw-r--r--vcl/source/fontsubset/ttcr.hxx220
-rw-r--r--vcl/source/fontsubset/xlat.cxx144
-rw-r--r--vcl/source/fontsubset/xlat.hxx40
9 files changed, 7086 insertions, 0 deletions
diff --git a/vcl/source/fontsubset/cff.cxx b/vcl/source/fontsubset/cff.cxx
new file mode 100644
index 000000000..dd7da8d92
--- /dev/null
+++ b/vcl/source/fontsubset/cff.cxx
@@ -0,0 +1,2061 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <cstdio>
+#include <cstring>
+#include <vector>
+#include <assert.h>
+
+#include <fontsubset.hxx>
+
+#include <o3tl/safeint.hxx>
+#include <strhelper.hxx>
+#include <sal/log.hxx>
+
+typedef sal_uInt8 U8;
+typedef sal_uInt16 U16;
+typedef sal_Int64 S64;
+
+typedef double RealType;
+typedef RealType ValType;
+
+static const char* pStringIds[] = {
+/*0*/ ".notdef", "space", "exclam", "quotedbl",
+ "numbersign", "dollar", "percent", "ampersand",
+ "quoteright", "parenleft", "parenright", "asterisk",
+ "plus", "comma", "hyphen", "period",
+/*16*/ "slash", "zero", "one", "two",
+ "three", "four", "five", "six",
+ "seven", "eight", "nine", "colon",
+ "semicolon", "less", "equal", "greater",
+/*32*/ "question", "at", "A", "B",
+ "C", "D", "E", "F",
+ "G", "H", "I", "J",
+ "K", "L", "M", "N",
+/*48*/ "O", "P", "Q", "R",
+ "S", "T", "U", "V",
+ "W", "X", "Y", "Z",
+ "bracketleft", "backslash", "bracketright", "asciicircum",
+/*64*/ "underscore", "quoteleft", "a", "b",
+ "c", "d", "e", "f",
+ "g", "h", "i", "j",
+ "k", "l", "m", "n",
+/*80*/ "o", "p", "q", "r",
+ "s", "t", "u", "v",
+ "w", "x", "y", "z",
+ "braceleft", "bar", "braceright", "asciitilde",
+/*96*/ "exclamdown", "cent", "sterlin", "fraction",
+ "yen", "florin", "section", "currency",
+ "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft",
+ "guilsinglright", "fi", "fl", "endash",
+/*112*/ "dagger", "daggerdbl", "periodcentered", "paragraph",
+ "bullet", "quotesinglbase", "quotedblbase", "quotedblright",
+ "guillemotright", "ellipsis", "perthousand", "questiondown",
+ "grave", "acute", "circumflex", "tilde",
+/*128*/ "macron", "breve", "dotaccent", "dieresis",
+ "ring", "cedilla", "hungarumlaut", "ogonek",
+ "caron", "emdash", "AE", "ordfeminine",
+ "Lslash", "Oslash", "OE", "ordmasculine",
+/*144*/ "ae", "dotlessi", "lslash", "oslash",
+ "oe", "germandbls", "onesuperior", "logicalnot",
+ "mu", "trademark", "Eth", "onehalf",
+ "plusminus", "Thorn", "onequarter", "divide",
+/*160*/ "brokenbar", "degree", "thorn", "threequarters",
+ "twosuperior", "registered", "minus", "eth",
+ "multiply", "threesuperior", "copyright", "Aacute",
+ "Acircumflex", "Adieresis", "Agrave", "Aring",
+/*176*/ "Atilde", "Ccedilla", "Eacute", "Ecircumflex",
+ "Edieresis", "Egrave", "Iacute", "Icircumflex",
+ "Idieresis", "Igrave", "Ntilde", "Oacute",
+ "Ocircumflex", "Odieresis", "Ograve", "Otilde",
+/*192*/ "Scaron", "Uacute", "Ucircumflex", "Udieresis",
+ "Ugrave", "Yacute", "Ydieresis", "Zcaron",
+ "aacute", "acircumflex", "adieresis", "agrave",
+ "aring", "atilde", "ccedilla", "eacute",
+/*208*/ "ecircumflex", "edieresis", "egrave", "iacute",
+ "icircumflex", "idieresis", "igrave", "ntilde",
+ "oacute", "ocircumflex", "odieresis", "ograve",
+ "otilde", "scaron", "uacute", "ucircumflex",
+/*224*/ "udieresis", "ugrave", "yacute", "ydieresis",
+ "zcaron", "exclamsmall", "Hungarumlautsmall","dollaroldstyle",
+ "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior",
+ "parenrightsuperior","twodotenleader", "onedotenleader", "zerooldstyle",
+/*240*/ "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle",
+ "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle",
+ "nineoldstile", "commasuperior", "threequartersemdash","periodsuperior",
+ "questionsmall", "asuperior", "bsuperior", "centsuperior",
+/*256*/ "dsuperior", "esuperior", "isuperior", "lsuperior",
+ "msuperior", "nsuperior", "osuperior", "rsuperior",
+ "ssuperior", "tsuperior", "ff", "ffi",
+ "ffl", "parenleftinferior","parenrightinferior","Circumflexsmall",
+/*272*/ "hyphensuperior","Gravesmall", "Asmall", "Bsmall",
+ "Csmall", "Dsmall", "Esmall", "Fsmall",
+ "Gsmall", "Hsmall", "Ismall", "Jsmall",
+ "Ksmall", "Lsmall", "Msmall", "Nsmall",
+/*288*/ "Osmall", "Psmall", "Qsmall", "Rsmall",
+ "Ssmall", "Tsmall", "Usmall", "Vsmall",
+ "Wsmall", "Xsmall", "Ysmall", "Zsmall",
+ "colonmonetary", "onefitted", "rupia", "Tildesmall",
+/*304*/ "exclamdownsmall","centoldstyle", "Lslashsmall", "Scaronsmall",
+ "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall",
+ "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior",
+ "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall",
+/*320*/ "oneeight", "threeeights", "fiveeights", "seveneights",
+ "onethird", "twothirds", "zerosuperior", "foursuperior",
+ "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior",
+ "ninesuperior", "zeroinferior", "oneinferior", "twoinferior",
+/*336*/ "threeinferior","fourinferior", "fiveinferior", "sixinferior",
+ "seveninferior", "eightinferior", "nineinferior", "centinferior",
+ "dollarinferior", "periodinferior", "commainferior", "Agravesmall",
+ "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall",
+/*352*/ "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall",
+ "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall",
+ "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall",
+ "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall",
+/*368*/ "Otildesmall", "Odieressissmall", "OEsmall", "Oslashsmall",
+ "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall",
+ "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000",
+ "001.001", "001.002", "001.003", "Black",
+/*384*/ "Bold", "Book", "Light", "Medium",
+ "Regular", "Roman", "Semibold"
+};
+
+// TOP DICT keywords (also covers PRIV DICT keywords)
+static const char* pDictOps[] = {
+ "sVersion", "sNotice", "sFullName", "sFamilyName",
+ "sWeight", "aFontBBox", "dBlueValues", "dOtherBlues",
+ "dFamilyBlues", "dFamilyOtherBlues", "nStdHW", "nStdVW",
+ "xESC", "nUniqueID", "aXUID", "nCharset",
+ "nEncoding", "nCharStrings", "PPrivate", "nSubrs",
+ "nDefaultWidthX", "nNominalWidthX", nullptr, nullptr,
+ nullptr, nullptr, nullptr, nullptr,
+ "shortint", "longint", "BCD", nullptr
+};
+
+// TOP DICT escapes (also covers PRIV DICT escapes)
+static const char* pDictEscs[] = {
+ "sCopyright", "bIsFixedPitch", "nItalicAngle", "nUnderlinePosition",
+ "nUnderlineThickness", "nPaintType", "tCharstringType", "aFontMatrix",
+ "nStrokeWidth", "nBlueScale", "nBlueShift", "nBlueFuzz",
+ "dStemSnapH", "dStemSnapV", "bForceBold", nullptr,
+ nullptr, "nLanguageGroup", "nExpansionFactor", "nInitialRandomSeed",
+ "nSyntheticBase", "sPostScript", "sBaseFontName", "dBaseFontBlend",
+ nullptr, nullptr, nullptr, nullptr,
+ nullptr, nullptr, "rROS", "nCIDFontVersion",
+ "nCIDFontRevision", "nCIDFontType", "nCIDCount", "nUIDBase",
+ "nFDArray", "nFDSelect", "sFontName"
+};
+
+namespace {
+
+namespace TYPE1OP
+{
+ enum OPS
+ {
+ HSTEM=1, VSTEM=3, VMOVETO=4, RLINETO=5,
+ HLINETO=6, VLINETO=7, RCURVETO=8, CLOSEPATH=9,
+ CALLSUBR=10, RETURN=11, T1ESC=12, HSBW=13,
+ ENDCHAR=14, RMOVETO=21, HMOVETO=22, VHCURVETO=30,
+ HVCURVETO=31
+ };
+
+ enum ESCS
+ {
+ DOTSECTION=0, VSTEM3=1, HSTEM3=2, SEAC=6,
+ SBW=7, ABS=9, ADD=10, SUB=11,
+ DIV=12, CALLOTHERSUBR=16, POP=17, SETCURRENTPOINT=33
+ };
+}
+
+namespace TYPE2OP
+{
+ enum OPS
+ {
+ HSTEM=1, VSTEM=3, VMOVETO=4, RLINETO=5,
+ HLINETO=6, VLINETO=7, RCURVETO=8, CALLSUBR=10,
+ RETURN=11, T2ESC=12, ENDCHAR=14, HSTEMHM=18,
+ HINTMASK=19, CNTRMASK=20, RMOVETO=21, HMOVETO=22,
+ VSTEMHM=23, RCURVELINE=24, RLINECURVE=25, VVCURVETO=26,
+ HHCURVETO=27, SHORTINT=28, CALLGSUBR=29, VHCURVETO=30,
+ HVCURVETO=31
+ };
+
+ enum ESCS
+ {
+ AND=3, OR=4, NOT=5, ABS=9,
+ ADD=10, SUB=11, DIV=12, NEG=14,
+ EQ=15, DROP=18, PUT=20, GET=21,
+ IFELSE=22, RANDOM=23, MUL=24, SQRT=26,
+ DUP=27, EXCH=28, INDEX=29, ROLL=30,
+ HFLEX=34, FLEX=35, HFLEX1=36, FLEX1=37
+ };
+}
+
+struct CffGlobal
+{
+ explicit CffGlobal();
+
+ int mnNameIdxBase;
+ int mnStringIdxBase;
+ bool mbCIDFont;
+ int mnCharStrBase;
+ int mnCharStrCount;
+ int mnCharsetBase;
+ int mnGlobalSubrBase;
+ int mnGlobalSubrCount;
+ int mnGlobalSubrBias;
+ int mnFDSelectBase;
+ int mnFontDictBase;
+ int mnFDAryCount;
+
+ std::vector<ValType> maFontBBox;
+ std::vector<ValType> maFontMatrix;
+
+ int mnFontNameSID;
+ int mnFullNameSID;
+};
+
+struct CffLocal
+{
+ explicit CffLocal();
+
+ int mnPrivDictBase;
+ int mnPrivDictSize;
+ int mnLocalSubrOffs;
+ int mnLocalSubrBase;
+ int mnLocalSubrBias;
+
+ ValType maNominalWidth;
+ ValType maDefaultWidth;
+
+ // ATM hinting related values
+ ValType maStemStdHW;
+ ValType maStemStdVW;
+ std::vector<ValType> maStemSnapH;
+ std::vector<ValType> maStemSnapV;
+ std::vector<ValType> maBlueValues;
+ std::vector<ValType> maOtherBlues;
+ std::vector<ValType> maFamilyBlues;
+ std::vector<ValType> maFamilyOtherBlues;
+ RealType mfBlueScale;
+ RealType mfBlueShift;
+ RealType mfBlueFuzz;
+ RealType mfExpFactor;
+ int mnLangGroup;
+ bool mbForceBold;
+};
+
+class CffSubsetterContext
+: private CffGlobal
+{
+public:
+ static const int NMAXSTACK = 48; // see CFF.appendixB
+ static const int NMAXHINTS = 2*96; // see CFF.appendixB
+ static const int NMAXTRANS = 32; // see CFF.appendixB
+
+ explicit CffSubsetterContext( const U8* pBasePtr, int nBaseLen);
+
+ bool initialCffRead();
+ void emitAsType1( class Type1Emitter&,
+ const sal_GlyphId* pGlyphIds, const U8* pEncoding,
+ sal_Int32* pGlyphWidths, int nGlyphCount, FontSubsetInfo& );
+
+private:
+ int convert2Type1Ops( CffLocal*, const U8* pType2Ops, int nType2Len, U8* pType1Ops);
+ void convertOneTypeOp();
+ void convertOneTypeEsc();
+ void callType2Subr( bool bGlobal, int nSubrNumber);
+ sal_Int32 getReadOfs() const { return static_cast<sal_Int32>(mpReadPtr - mpBasePtr);}
+
+ const U8* mpBasePtr;
+ const U8* mpBaseEnd;
+
+ const U8* mpReadPtr;
+ const U8* mpReadEnd;
+
+ U8* mpWritePtr;
+ bool mbNeedClose;
+ bool mbIgnoreHints;
+ sal_Int32 mnCntrMask;
+
+ int seekIndexData( int nIndexBase, int nDataIndex);
+ void seekIndexEnd( int nIndexBase);
+
+ CffLocal maCffLocal[256];
+ CffLocal* mpCffLocal;
+
+ void readDictOp();
+ RealType readRealVal();
+ const char* getString( int nStringID);
+ int getFDSelect( int nGlyphIndex) const;
+ int getGlyphSID( int nGlyphIndex) const;
+ const char* getGlyphName( int nGlyphIndex);
+
+ void read2push();
+ void writeType1Val( ValType);
+ void writeTypeOp( int nTypeOp);
+ void writeTypeEsc( int nTypeOp);
+ void writeCurveTo( int nStackPos, int nIX1, int nIY1, int nIX2, int nIY2, int nIX3, int nIY3);
+ void pop2MultiWrite( int nArgsPerTypo, int nTypeOp, int nTypeXor=0);
+ void popAll2Write( int nTypeOp);
+
+public: // TODO: is public really needed?
+ // accessing the value stack
+ // TODO: add more checks
+ void push( ValType nVal) { mnValStack[ mnStackIdx++] = nVal;}
+ ValType popVal() { return ((mnStackIdx>0) ? mnValStack[ --mnStackIdx] : 0);}
+ ValType getVal( int nIndex) const { return mnValStack[ nIndex];}
+ int popInt();
+ int size() const { return mnStackIdx;}
+ void clear() { mnStackIdx = 0;}
+
+ // accessing the charstring hints
+ void addHints( bool bVerticalHints);
+
+ // accessing other charstring specifics
+ void updateWidth( bool bUseFirstVal);
+
+private:
+ // typeop execution context
+ int mnStackIdx;
+ ValType mnValStack[ NMAXSTACK+4];
+ ValType mnTransVals[ NMAXTRANS];
+
+ int mnHintSize;
+ int mnHorzHintSize;
+ ValType mnHintStack[ NMAXHINTS];
+
+ ValType maCharWidth;
+};
+
+}
+
+CffSubsetterContext::CffSubsetterContext( const U8* pBasePtr, int nBaseLen)
+ : mpBasePtr( pBasePtr)
+ , mpBaseEnd( pBasePtr+nBaseLen)
+ , mpReadPtr(nullptr)
+ , mpReadEnd(nullptr)
+ , mpWritePtr(nullptr)
+ , mbNeedClose(false)
+ , mbIgnoreHints(false)
+ , mnCntrMask(0)
+ , mnStackIdx(0)
+ , mnValStack{}
+ , mnTransVals{}
+ , mnHintSize(0)
+ , mnHorzHintSize(0)
+ , mnHintStack{}
+ , maCharWidth(-1)
+{
+// setCharStringType( 1);
+ // TODO: new CffLocal[ mnFDAryCount];
+ mpCffLocal = &maCffLocal[0];
+}
+
+inline int CffSubsetterContext::popInt()
+{
+ const ValType aVal = popVal();
+ const int nInt = static_cast<int>(aVal);
+ assert( nInt == aVal);
+ return nInt;
+}
+
+inline void CffSubsetterContext::updateWidth( bool bUseFirstVal)
+{
+ // the first value is not a hint but the charwidth
+ if( maCharWidth>0 )
+ return;
+
+ if( bUseFirstVal) {
+ maCharWidth = mpCffLocal->maNominalWidth + mnValStack[0];
+ // remove bottom stack entry
+ --mnStackIdx;
+ for( int i = 0; i < mnStackIdx; ++i)
+ mnValStack[ i] = mnValStack[ i+1];
+ } else {
+ maCharWidth = mpCffLocal->maDefaultWidth;
+ }
+}
+
+void CffSubsetterContext::addHints( bool bVerticalHints)
+{
+ // the first charstring value may a charwidth instead of a charwidth
+ updateWidth( (mnStackIdx & 1) != 0);
+ // return early (e.g. no implicit hints for hintmask)
+ if( !mnStackIdx)
+ return;
+
+ // copy the remaining values to the hint arrays
+ // assert( (mnStackIdx & 1) == 0); // depends on called subrs
+ if( mnStackIdx & 1) --mnStackIdx;//#######
+ // TODO: if( !bSubr) assert( mnStackIdx >= 2);
+
+ assert( (mnHintSize + mnStackIdx) <= 2*NMAXHINTS);
+
+ ValType nHintOfs = 0;
+ for( int i = 0; i < mnStackIdx; ++i) {
+ nHintOfs += mnValStack[ i ];
+ mnHintStack[ mnHintSize++] = nHintOfs;
+ }
+
+ if( !bVerticalHints)
+ mnHorzHintSize = mnHintSize;
+
+ // clear all values from the stack
+ mnStackIdx = 0;
+}
+
+void CffSubsetterContext::readDictOp()
+{
+ const U8 c = *mpReadPtr;
+ if( c <= 21 ) {
+ int nOpId = *(mpReadPtr++);
+ const char* pCmdName = nullptr;
+ if( nOpId != 12)
+ pCmdName = pDictOps[nOpId];
+ else {
+ const U8 nExtId = *(mpReadPtr++);
+ if (nExtId < 39)
+ pCmdName = pDictEscs[nExtId];
+ nOpId = 900 + nExtId;
+ }
+
+ if (!pCmdName) // skip reserved operators
+ return;
+
+ //TODO: if( nStackIdx > 0)
+ int nInt = 0;
+ switch( *pCmdName) {
+ default: SAL_WARN("vcl.fonts", "unsupported DictOp.type='" << *pCmdName << "'."); break;
+ case 'b': // bool
+ nInt = popInt();
+ switch( nOpId) {
+ case 915: mpCffLocal->mbForceBold = nInt; break; // "ForceBold"
+ default: break; // TODO: handle more boolean dictops?
+ }
+ break;
+ case 'n': { // dict-op number
+ ValType nVal = popVal();
+ nInt = static_cast<int>(nVal);
+ switch( nOpId) {
+ case 10: mpCffLocal->maStemStdHW = nVal; break; // "StdHW"
+ case 11: mpCffLocal->maStemStdVW = nVal; break; // "StdVW"
+ case 15: mnCharsetBase = nInt; break; // "charset"
+ case 16: break; // "nEncoding"
+ case 17: mnCharStrBase = nInt; break; // "nCharStrings"
+ case 19: mpCffLocal->mnLocalSubrOffs = nInt; break;// "nSubrs"
+ case 20: mpCffLocal->maDefaultWidth = nVal; break; // "defaultWidthX"
+ case 21: mpCffLocal->maNominalWidth = nVal; break; // "nominalWidthX"
+ case 909: mpCffLocal->mfBlueScale = nVal; break; // "BlueScale"
+ case 910: mpCffLocal->mfBlueShift = nVal; break; // "BlueShift"
+ case 911: mpCffLocal->mfBlueFuzz = nVal; break; // "BlueFuzz"
+ case 912: mpCffLocal->mfExpFactor = nVal; break; // "ExpansionFactor"
+ case 917: mpCffLocal->mnLangGroup = nInt; break; // "LanguageGroup"
+ case 936: mnFontDictBase = nInt; break; // "nFDArray"
+ case 937: mnFDSelectBase = nInt; break; // "nFDSelect"
+ default: break; // TODO: handle more numeric dictops?
+ }
+ } break;
+ case 'a': { // array
+ switch( nOpId) {
+ case 5: maFontBBox.clear(); break; // "FontBBox"
+ case 907: maFontMatrix.clear(); break; // "FontMatrix"
+ default: break; // TODO: reset other arrays?
+ }
+ for( int i = 0; i < size(); ++i ) {
+ ValType nVal = getVal(i);
+ switch( nOpId) {
+ case 5: maFontBBox.push_back( nVal); break; // "FontBBox"
+ case 907: maFontMatrix.push_back( nVal); break; // "FontMatrix"
+ default: break; // TODO: handle more array dictops?
+ }
+ }
+ clear();
+ } break;
+ case 'd': { // delta array
+ ValType nVal = 0;
+ for( int i = 0; i < size(); ++i ) {
+ nVal += getVal(i);
+ switch( nOpId) {
+ case 6: mpCffLocal->maBlueValues.push_back( nVal); break; // "BlueValues"
+ case 7: mpCffLocal->maOtherBlues.push_back( nVal); break; // "OtherBlues"
+ case 8: mpCffLocal->maFamilyBlues.push_back( nVal); break; // "FamilyBlues"
+ case 9: mpCffLocal->maFamilyOtherBlues.push_back( nVal); break;// "FamilyOtherBlues"
+ case 912: mpCffLocal->maStemSnapH.push_back( nVal); break; // "StemSnapH"
+ case 913: mpCffLocal->maStemSnapV.push_back( nVal); break; // "StemSnapV"
+ default: break; // TODO: handle more delta-array dictops?
+ }
+ }
+ clear();
+ } break;
+ case 's': // stringid (SID)
+ nInt = popInt();
+ switch( nOpId ) {
+ case 2: mnFullNameSID = nInt; break; // "FullName"
+ case 3: break; // "FamilyName"
+ case 938: mnFontNameSID = nInt; break; // "FontName"
+ default: break; // TODO: handle more string dictops?
+ }
+ break;
+ case 'P': // private dict
+ mpCffLocal->mnPrivDictBase = popInt();
+ mpCffLocal->mnPrivDictSize = popInt();
+ break;
+ case 'r': { // ROS operands
+ popInt(); // TODO: use sid1
+ popInt(); // TODO: use sid2
+ popVal();
+ mbCIDFont = true;
+ } break;
+ case 't': // CharstringType
+ popInt();
+ break;
+ }
+ } else if( (c >= 32) || (c == 28) ) {
+// --mpReadPtr;
+ read2push();
+ } else if( c == 29 ) { // longint
+ ++mpReadPtr; // skip 29
+ sal_Int32 nS32 = mpReadPtr[0] << 24;
+ nS32 += mpReadPtr[1] << 16;
+ nS32 += mpReadPtr[2] << 8;
+ nS32 += mpReadPtr[3] << 0;
+ mpReadPtr += 4;
+ ValType nVal = static_cast<ValType>(nS32);
+ push( nVal );
+ } else if( c == 30) { // real number
+ ++mpReadPtr; // skip 30
+ const RealType fReal = readRealVal();
+ // push value onto stack
+ ValType nVal = fReal;
+ push( nVal);
+ }
+}
+
+void CffSubsetterContext::read2push()
+{
+ ValType aVal = 0;
+
+ const U8*& p = mpReadPtr;
+ const U8 c = *p;
+ if( c == 28 ) {
+ sal_Int16 nS16 = (p[1] << 8) + p[2];
+ aVal = nS16;
+ p += 3;
+ } else if( c <= 246 ) { // -107..+107
+ aVal = static_cast<ValType>(p[0] - 139);
+ p += 1;
+ } else if( c <= 250 ) { // +108..+1131
+ aVal = static_cast<ValType>(((p[0] << 8) + p[1]) - 63124);
+ p += 2;
+ } else if( c <= 254 ) { // -108..-1131
+ aVal = static_cast<ValType>(64148 - ((p[0] << 8) + p[1]));
+ p += 2;
+ } else /*if( c == 255)*/ { // Fixed16.16
+ int nS32 = (p[1] << 24) + (p[2] << 16) + (p[3] << 8) + p[4];
+ if( (sizeof(nS32) != 2) && (nS32 & (1U<<31)))
+ nS32 |= (~0U) << 31; // assuming 2s complement
+ aVal = static_cast<ValType>(nS32 * (1.0 / 0x10000));
+ p += 5;
+ }
+
+ push( aVal);
+}
+
+void CffSubsetterContext::writeType1Val( ValType aVal)
+{
+ U8* pOut = mpWritePtr;
+
+ int nInt = static_cast<int>(aVal);
+ if( (nInt >= -107) && (nInt <= +107)) {
+ *(pOut++) = static_cast<U8>(nInt + 139); // -107..+107
+ } else if( (nInt >= -1131) && (nInt <= +1131)) {
+ if( nInt >= 0)
+ nInt += 63124; // +108..+1131
+ else
+ nInt = 64148 - nInt; // -108..-1131
+ *(pOut++) = static_cast<U8>(nInt >> 8);
+ *(pOut++) = static_cast<U8>(nInt);
+ } else {
+ // numtype==255 means int32 for Type1, but 16.16 for Type2 charstrings!!!
+ *(pOut++) = 255;
+ *(pOut++) = static_cast<U8>(nInt >> 24);
+ *(pOut++) = static_cast<U8>(nInt >> 16);
+ *(pOut++) = static_cast<U8>(nInt >> 8);
+ *(pOut++) = static_cast<U8>(nInt);
+ }
+
+ mpWritePtr = pOut;
+}
+
+inline void CffSubsetterContext::writeTypeOp( int nTypeOp)
+{
+ *(mpWritePtr++) = static_cast<U8>(nTypeOp);
+}
+
+inline void CffSubsetterContext::writeTypeEsc( int nTypeEsc)
+{
+ *(mpWritePtr++) = TYPE1OP::T1ESC;
+ *(mpWritePtr++) = static_cast<U8>(nTypeEsc);
+}
+
+void CffSubsetterContext::pop2MultiWrite( int nArgsPerTypo, int nTypeOp, int nTypeXor)
+{
+ for( int i = 0; i < mnStackIdx;) {
+ for( int j = 0; j < nArgsPerTypo; ++j) {
+ const ValType aVal = mnValStack[i+j];
+ writeType1Val( aVal);
+ }
+ i += nArgsPerTypo;
+ writeTypeOp( nTypeOp);
+ nTypeOp ^= nTypeXor; // for toggling vlineto/hlineto
+ }
+ clear();
+}
+
+void CffSubsetterContext::popAll2Write( int nTypeOp)
+{
+ // pop in reverse order, then write
+ for( int i = 0; i < mnStackIdx; ++i) {
+ const ValType aVal = mnValStack[i];
+ writeType1Val( aVal);
+ }
+ clear();
+ writeTypeOp( nTypeOp);
+}
+
+void CffSubsetterContext::writeCurveTo( int nStackPos,
+ int nIX1, int nIY1, int nIX2, int nIY2, int nIX3, int nIY3)
+{
+ // get the values from the stack
+ const ValType nDX1 = nIX1 ? mnValStack[ nStackPos+nIX1 ] : 0;
+ const ValType nDY1 = nIY1 ? mnValStack[ nStackPos+nIY1 ] : 0;
+ const ValType nDX2 = nIX2 ? mnValStack[ nStackPos+nIX2 ] : 0;
+ const ValType nDY2 = nIY2 ? mnValStack[ nStackPos+nIY2 ] : 0;
+ const ValType nDX3 = nIX3 ? mnValStack[ nStackPos+nIX3 ] : 0;
+ const ValType nDY3 = nIY3 ? mnValStack[ nStackPos+nIY3 ] : 0;
+
+ // emit the curveto operator and operands
+ // TODO: determine the most efficient curveto operator
+ // TODO: depending on type1op or type2op target
+ writeType1Val( nDX1 );
+ writeType1Val( nDY1 );
+ writeType1Val( nDX2 );
+ writeType1Val( nDY2 );
+ writeType1Val( nDX3 );
+ writeType1Val( nDY3 );
+ writeTypeOp( TYPE1OP::RCURVETO );
+}
+
+void CffSubsetterContext::convertOneTypeOp()
+{
+ const int nType2Op = *(mpReadPtr++);
+
+ int i, nInt; // prevent WAE for declarations inside switch cases
+ // convert each T2op
+ switch( nType2Op) {
+ case TYPE2OP::T2ESC:
+ convertOneTypeEsc();
+ break;
+ case TYPE2OP::HSTEM:
+ case TYPE2OP::VSTEM:
+ addHints( nType2Op == TYPE2OP::VSTEM );
+ for( i = 0; i < mnHintSize; i+=2 ) {
+ writeType1Val( mnHintStack[i]);
+ writeType1Val( mnHintStack[i+1] - mnHintStack[i]);
+ writeTypeOp( nType2Op );
+ }
+ break;
+ case TYPE2OP::HSTEMHM:
+ case TYPE2OP::VSTEMHM:
+ addHints( nType2Op == TYPE2OP::VSTEMHM);
+ break;
+ case TYPE2OP::CNTRMASK:
+ // TODO: replace cntrmask with vstem3/hstem3
+ addHints( true);
+ {
+ U8 nMaskBit = 0;
+ U8 nMaskByte = 0;
+ for( i = 0; i < mnHintSize; i+=2, nMaskBit>>=1) {
+ if( !nMaskBit) {
+ nMaskByte = *(mpReadPtr++);
+ nMaskBit = 0x80;
+ }
+ if( !(nMaskByte & nMaskBit))
+ continue;
+ if( i >= 8*int(sizeof(mnCntrMask)))
+ mbIgnoreHints = true;
+ if( mbIgnoreHints)
+ continue;
+ mnCntrMask |= (1U << i);
+ }
+ }
+ break;
+ case TYPE2OP::HINTMASK:
+ addHints( true);
+ {
+ sal_Int32 nHintMask = 0;
+ int nCntrBits[2] = {0,0};
+ U8 nMaskBit = 0;
+ U8 nMaskByte = 0;
+ int const MASK_BITS = 8*sizeof(nHintMask);
+ for( i = 0; i < mnHintSize; i+=2, nMaskBit>>=1) {
+ if( !nMaskBit) {
+ nMaskByte = *(mpReadPtr++);
+ nMaskBit = 0x80;
+ }
+ if( !(nMaskByte & nMaskBit))
+ continue;
+ if( i >= MASK_BITS)
+ mbIgnoreHints = true;
+ if( mbIgnoreHints)
+ continue;
+ nHintMask |= (1U << i);
+ nCntrBits[ i < mnHorzHintSize] += (mnCntrMask >> i) & 1;
+ }
+
+ mbIgnoreHints |= (nCntrBits[0] && (nCntrBits[0] != 3));
+ mbIgnoreHints |= (nCntrBits[1] && (nCntrBits[1] != 3));
+ if( mbIgnoreHints)
+ break;
+
+ for( i = 0; i < mnHintSize; i+=2) {
+ if(i >= MASK_BITS || !(nHintMask & (1U << i)))
+ continue;
+ writeType1Val( mnHintStack[i]);
+ writeType1Val( mnHintStack[i+1] - mnHintStack[i]);
+ const bool bHorz = (i < mnHorzHintSize);
+ if( !nCntrBits[ bHorz])
+ writeTypeOp( bHorz ? TYPE1OP::HSTEM : TYPE1OP::VSTEM);
+ else if( !--nCntrBits[ bHorz])
+ writeTypeEsc( bHorz ? TYPE1OP::HSTEM3 : TYPE1OP::VSTEM3);
+ }
+ }
+ break;
+ case TYPE2OP::CALLSUBR:
+ case TYPE2OP::CALLGSUBR:
+ {
+ nInt = popInt();
+ const bool bGlobal = (nType2Op == TYPE2OP::CALLGSUBR);
+ callType2Subr( bGlobal, nInt);
+ }
+ break;
+ case TYPE2OP::RETURN:
+ // TODO: check that we are in a subroutine
+ return;
+ case TYPE2OP::VMOVETO:
+ case TYPE2OP::HMOVETO:
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() > 1);
+ mbNeedClose = true;
+ pop2MultiWrite( 1, nType2Op);
+ break;
+ case TYPE2OP::VLINETO:
+ case TYPE2OP::HLINETO:
+ pop2MultiWrite( 1, nType2Op,
+ TYPE1OP::VLINETO ^ TYPE1OP::HLINETO);
+ break;
+ case TYPE2OP::RMOVETO:
+ // TODO: convert rmoveto to vlineto/hlineto if possible
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() > 2);
+ mbNeedClose = true;
+ pop2MultiWrite( 2, nType2Op);
+ break;
+ case TYPE2OP::RLINETO:
+ // TODO: convert rlineto to vlineto/hlineto if possible
+ pop2MultiWrite( 2, nType2Op);
+ break;
+ case TYPE2OP::RCURVETO:
+ // TODO: convert rcurveto to vh/hv/hh/vv-curveto if possible
+ pop2MultiWrite( 6, nType2Op);
+ break;
+ case TYPE2OP::RCURVELINE:
+ i = 0;
+ while( (i += 6) <= mnStackIdx)
+ writeCurveTo( i, -6, -5, -4, -3, -2, -1 );
+ i -= 6;
+ while( (i += 2) <= mnStackIdx) {
+ writeType1Val( mnValStack[i-2]);
+ writeType1Val( mnValStack[i-1]);
+ writeTypeOp( TYPE2OP::RLINETO);
+ }
+ clear();
+ break;
+ case TYPE2OP::RLINECURVE:
+ i = 0;
+ while( (i += 2) <= mnStackIdx-6) {
+ writeType1Val( mnValStack[i-2]);
+ writeType1Val( mnValStack[i-1]);
+ writeTypeOp( TYPE2OP::RLINETO);
+ }
+ i -= 2;
+ while( (i += 6) <= mnStackIdx)
+ writeCurveTo( i, -6, -5, -4, -3, -2, -1 );
+ clear();
+ break;
+ case TYPE2OP::VHCURVETO:
+ case TYPE2OP::HVCURVETO:
+ {
+ bool bVert = (nType2Op == TYPE2OP::VHCURVETO);
+ i = 0;
+ nInt = 0;
+ if( mnStackIdx & 1 )
+ nInt = static_cast<int>(mnValStack[ --mnStackIdx ]);
+ while( (i += 4) <= mnStackIdx) {
+ // TODO: use writeCurveTo()
+ if( bVert ) writeType1Val( 0 );
+ writeType1Val( mnValStack[i-4] );
+ if( !bVert ) writeType1Val( 0);
+ writeType1Val( mnValStack[i-3] );
+ writeType1Val( mnValStack[i-2] );
+ if( !bVert ) writeType1Val( static_cast<ValType>((i==mnStackIdx) ? nInt : 0) );
+ writeType1Val( mnValStack[i-1] );
+ if( bVert ) writeType1Val( static_cast<ValType>((i==mnStackIdx) ? nInt : 0) );
+ bVert = !bVert;
+ writeTypeOp( TYPE2OP::RCURVETO);
+ }
+ }
+ clear();
+ break;
+ case TYPE2OP::HHCURVETO:
+ i = (mnStackIdx & 1);
+ while( (i += 4) <= mnStackIdx) {
+ if( i != 5)
+ writeCurveTo( i, -4, 0, -3, -2, -1, 0);
+ else
+ writeCurveTo( i, -4, -5, -3, -2, -1, 0);
+ }
+ clear();
+ break;
+ case TYPE2OP::VVCURVETO:
+ i = (mnStackIdx & 1);
+ while( (i += 4) <= mnStackIdx) {
+ if( i != 5)
+ writeCurveTo( i, 0, -4, -3, -2, 0, -1);
+ else
+ writeCurveTo( i, -5, -4, -3, -2, 0, -1);
+ }
+ clear();
+ break;
+ case TYPE2OP::ENDCHAR:
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() >= 1);
+ // mbNeedClose = true;
+ writeTypeOp( TYPE1OP::ENDCHAR);
+ break;
+ default:
+ if( ((nType2Op >= 32) && (nType2Op <= 255)) || (nType2Op == 28)) {
+ --mpReadPtr;
+ read2push();
+ } else {
+ popAll2Write( nType2Op);
+ assert(false && "TODO?");
+ }
+ break;
+ }
+}
+
+void CffSubsetterContext::convertOneTypeEsc()
+{
+ const int nType2Esc = *(mpReadPtr++);
+ ValType* pTop = &mnValStack[ mnStackIdx-1];
+ // convert each T2op
+ switch( nType2Esc) {
+ case TYPE2OP::AND:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = static_cast<ValType>(static_cast<int>(pTop[0]) & static_cast<int>(pTop[-1]));
+ --mnStackIdx;
+ break;
+ case TYPE2OP::OR:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = static_cast<ValType>(static_cast<int>(pTop[0]) | static_cast<int>(pTop[-1]));
+ --mnStackIdx;
+ break;
+ case TYPE2OP::NOT:
+ assert( mnStackIdx >= 1 );
+ pTop[0] = ValType(pTop[0] == 0);
+ break;
+ case TYPE2OP::ABS:
+ assert( mnStackIdx >= 1 );
+ if( pTop[0] >= 0)
+ break;
+ [[fallthrough]];
+ case TYPE2OP::NEG:
+ assert( mnStackIdx >= 1 );
+ pTop[0] = -pTop[0];
+ break;
+ case TYPE2OP::ADD:
+ assert( mnStackIdx >= 2 );
+ pTop[0] += pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::SUB:
+ assert( mnStackIdx >= 2 );
+ pTop[0] -= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::MUL:
+ assert( mnStackIdx >= 2 );
+ if( pTop[-1])
+ pTop[0] *= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::DIV:
+ assert( mnStackIdx >= 2 );
+ if( pTop[-1])
+ pTop[0] /= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::EQ:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = ValType(pTop[0] == pTop[-1]);
+ --mnStackIdx;
+ break;
+ case TYPE2OP::DROP:
+ assert( mnStackIdx >= 1 );
+ --mnStackIdx;
+ break;
+ case TYPE2OP::PUT: {
+ assert( mnStackIdx >= 2 );
+ const int nIdx = static_cast<int>(pTop[0]);
+ assert( nIdx >= 0 );
+ assert( nIdx < NMAXTRANS );
+ mnTransVals[ nIdx] = pTop[-1];
+ mnStackIdx -= 2;
+ break;
+ }
+ case TYPE2OP::GET: {
+ assert( mnStackIdx >= 1 );
+ const int nIdx = static_cast<int>(pTop[0]);
+ assert( nIdx >= 0 );
+ assert( nIdx < NMAXTRANS );
+ pTop[0] = mnTransVals[ nIdx ];
+ break;
+ }
+ case TYPE2OP::IFELSE: {
+ assert( mnStackIdx >= 4 );
+ if( pTop[-1] > pTop[0] )
+ pTop[-3] = pTop[-2];
+ mnStackIdx -= 3;
+ break;
+ }
+ case TYPE2OP::RANDOM:
+ pTop[+1] = 1234; // TODO
+ ++mnStackIdx;
+ break;
+ case TYPE2OP::SQRT:
+ // TODO: implement
+ break;
+ case TYPE2OP::DUP:
+ assert( mnStackIdx >= 1 );
+ pTop[+1] = pTop[0];
+ ++mnStackIdx;
+ break;
+ case TYPE2OP::EXCH: {
+ assert( mnStackIdx >= 2 );
+ const ValType nVal = pTop[0];
+ pTop[0] = pTop[-1];
+ pTop[-1] = nVal;
+ break;
+ }
+ case TYPE2OP::INDEX: {
+ assert( mnStackIdx >= 1 );
+ const int nVal = static_cast<int>(pTop[0]);
+ assert( nVal >= 0 );
+ assert( nVal < mnStackIdx-1 );
+ pTop[0] = pTop[-1-nVal];
+ break;
+ }
+ case TYPE2OP::ROLL: {
+ assert( mnStackIdx >= 1 );
+ const int nNum = static_cast<int>(pTop[0]);
+ assert( nNum >= 0);
+ assert( nNum < mnStackIdx-2 );
+ (void)nNum; // TODO: implement
+ // TODO: implement: const int nOfs = static_cast<int>(pTop[-1]);
+ mnStackIdx -= 2;
+ break;
+ }
+ case TYPE2OP::HFLEX1: {
+ assert( mnStackIdx == 9);
+
+ writeCurveTo( mnStackIdx, -9, -8, -7, -6, -5, 0);
+ writeCurveTo( mnStackIdx, -4, 0, -3, -2, -1, 0);
+ // TODO: emulate hflex1 using othersubr call
+
+ mnStackIdx -= 9;
+ }
+ break;
+ case TYPE2OP::HFLEX: {
+ assert( mnStackIdx == 7);
+ ValType* pX = &mnValStack[ mnStackIdx];
+
+ pX[+1] = -pX[-5]; // temp: +dy5==-dy2
+ writeCurveTo( mnStackIdx, -7, 0, -6, -5, -4, 0);
+ writeCurveTo( mnStackIdx, -3, 0, -2, +1, -1, 0);
+ // TODO: emulate hflex using othersubr call
+
+ mnStackIdx -= 7;
+ }
+ break;
+ case TYPE2OP::FLEX: {
+ assert( mnStackIdx == 13 );
+ writeCurveTo( mnStackIdx, -13, -12, -11, -10, -9, -8 );
+ writeCurveTo( mnStackIdx, -7, -6, -5, -4, -3, -2 );
+ // ignoring ValType nFlexDepth = mnValStack[ mnStackIdx-1 ];
+ mnStackIdx -= 13;
+ }
+ break;
+ case TYPE2OP::FLEX1: {
+ assert( mnStackIdx == 11 );
+ // write the first part of the flex1-hinted curve
+ writeCurveTo( mnStackIdx, -11, -10, -9, -8, -7, -6 );
+
+ // determine if nD6 is horizontal or vertical
+ const int i = mnStackIdx;
+ ValType nDeltaX = mnValStack[i-11] + mnValStack[i-9] + mnValStack[i-7] + mnValStack[i-5] + mnValStack[i-3];
+ if( nDeltaX < 0 ) nDeltaX = -nDeltaX;
+ ValType nDeltaY = mnValStack[i-10] + mnValStack[i-8] + mnValStack[i-6] + mnValStack[i-4] + mnValStack[i-2];
+ if( nDeltaY < 0 ) nDeltaY = -nDeltaY;
+ const bool bVertD6 = (nDeltaY > nDeltaX);
+
+ // write the second part of the flex1-hinted curve
+ if( !bVertD6 )
+ writeCurveTo( mnStackIdx, -5, -4, -3, -2, -1, 0);
+ else
+ writeCurveTo( mnStackIdx, -5, -4, -3, -2, 0, -1);
+ mnStackIdx -= 11;
+ }
+ break;
+ default:
+ SAL_WARN("vcl.fonts", "unhandled type2esc " << nType2Esc);
+ assert( false);
+ break;
+ }
+}
+
+void CffSubsetterContext::callType2Subr( bool bGlobal, int nSubrNumber)
+{
+ const U8* const pOldReadPtr = mpReadPtr;
+ const U8* const pOldReadEnd = mpReadEnd;
+
+ if( bGlobal ) {
+ nSubrNumber += mnGlobalSubrBias;
+ seekIndexData( mnGlobalSubrBase, nSubrNumber);
+ } else {
+ nSubrNumber += mpCffLocal->mnLocalSubrBias;
+ seekIndexData( mpCffLocal->mnLocalSubrBase, nSubrNumber);
+ }
+
+ while( mpReadPtr < mpReadEnd)
+ convertOneTypeOp();
+
+ mpReadPtr = pOldReadPtr;
+ mpReadEnd = pOldReadEnd;
+}
+
+static const int MAX_T1OPS_SIZE = 81920; // TODO: use dynamic value
+
+int CffSubsetterContext::convert2Type1Ops( CffLocal* pCffLocal, const U8* const pT2Ops, int nT2Len, U8* const pT1Ops)
+{
+ mpCffLocal = pCffLocal;
+
+ // prepare the charstring conversion
+ mpWritePtr = pT1Ops;
+ U8 aType1Ops[ MAX_T1OPS_SIZE];
+ if( !pT1Ops)
+ mpWritePtr = aType1Ops;
+ *const_cast<U8**>(&pT1Ops) = mpWritePtr;
+
+ // prepend random seed for T1crypt
+ *(mpWritePtr++) = 0x48;
+ *(mpWritePtr++) = 0x44;
+ *(mpWritePtr++) = 0x55;
+ *(mpWritePtr++) = ' ';
+
+ // convert the Type2 charstring to Type1
+ mpReadPtr = pT2Ops;
+ mpReadEnd = pT2Ops + nT2Len;
+ // prepend "hsbw" or "sbw"
+ // TODO: only emit hsbw when charwidth is known
+ writeType1Val(0); // TODO: aSubsetterContext.getLeftSideBearing();
+ U8* pCharWidthPtr=mpWritePtr; // need to overwrite that later
+ // pad out 5 bytes for the char width with default val 1000 (to be
+ // filled with the actual value below)
+ *(mpWritePtr++) = 255;
+ *(mpWritePtr++) = static_cast<U8>(0);
+ *(mpWritePtr++) = static_cast<U8>(0);
+ *(mpWritePtr++) = static_cast<U8>(250);
+ *(mpWritePtr++) = static_cast<U8>(124);
+ writeTypeOp(TYPE1OP::HSBW);
+ mbNeedClose = false;
+ mbIgnoreHints = false;
+ mnHintSize=mnHorzHintSize=mnStackIdx=0; maCharWidth=-1;//#######
+ mnCntrMask = 0;
+ while( mpReadPtr < mpReadEnd)
+ convertOneTypeOp();
+ if( maCharWidth != -1 )
+ {
+ // overwrite earlier charWidth value, which we only now have
+ // parsed out of mpReadPtr buffer (by way of
+ // convertOneTypeOp()s above)
+ const int nInt = static_cast<int>(maCharWidth);
+ *(pCharWidthPtr++) = 255;
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 24);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 16);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 8);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt);
+ }
+
+ const int nType1Len = mpWritePtr - pT1Ops;
+
+ // encrypt the Type1 charstring
+ unsigned nRDCryptR = 4330; // TODO: mnRDCryptSeed;
+ for( U8* p = pT1Ops; p < mpWritePtr; ++p) {
+ *p ^= (nRDCryptR >> 8);
+ nRDCryptR = (*p + nRDCryptR) * 52845 + 22719;
+ }
+
+ return nType1Len;
+}
+
+RealType CffSubsetterContext::readRealVal()
+{
+ // TODO: more thorough number validity test
+ bool bComma = false;
+ int nExpVal = 0;
+ int nExpSign = 0;
+ S64 nNumber = 0;
+ RealType fReal = +1.0;
+ for(;;){
+ const U8 c = *(mpReadPtr++); // read nibbles
+ // parse high nibble
+ const U8 nH = c >> 4U;
+ if( nH <= 9) {
+ nNumber = nNumber * 10 + nH;
+ --nExpVal;
+ } else if( nH == 10) { // comma
+ nExpVal = 0;
+ bComma = true;
+ } else if( nH == 11) { // +exp
+ fReal *= nNumber;
+ nExpSign = +1;
+ nNumber = 0;
+ } else if( nH == 12) { // -exp
+ fReal *= nNumber;
+ nExpSign = -1;
+ nNumber = 0;
+ } else if( nH == 13) { // reserved
+ // TODO: ignore or error?
+ } else if( nH == 14) // minus
+ fReal = -fReal;
+ else if( nH == 15) // end
+ break;
+ // parse low nibble
+ const U8 nL = c & 0x0F;
+ if( nL <= 9) {
+ nNumber = nNumber * 10 + nL;
+ --nExpVal;
+ } else if( nL == 10) { // comma
+ nExpVal = 0;
+ bComma = true;
+ } else if( nL == 11) { // +exp
+ fReal *= nNumber;
+ nNumber = 0;
+ nExpSign = +1;
+ } else if( nL == 12) { // -exp
+ fReal *= nNumber;
+ nNumber = 0;
+ nExpSign = -1;
+ } else if( nL == 13) { // reserved
+ // TODO: ignore or error?
+ } else if( nL == 14) // minus
+ fReal = -fReal;
+ else if( nL == 15) // end
+ break;
+ }
+
+ // merge exponents
+ if( !bComma)
+ nExpVal = 0;
+ if( !nExpSign) { fReal *= nNumber;}
+ else if( nExpSign > 0) { nExpVal += static_cast<int>(nNumber);}
+ else if( nExpSign < 0) { nExpVal -= static_cast<int>(nNumber);}
+
+ // apply exponents
+ if( !nExpVal) { /*nothing to apply*/}
+ else if( nExpVal > 0) { while( --nExpVal >= 0) fReal *= 10.0;}
+ else if( nExpVal < 0) { while( ++nExpVal <= 0) fReal /= 10.0;}
+ return fReal;
+}
+
+// prepare to access an element inside a CFF/CID index table
+int CffSubsetterContext::seekIndexData( int nIndexBase, int nDataIndex)
+{
+ assert( (nIndexBase > 0) && (mpBasePtr + nIndexBase + 3 <= mpBaseEnd));
+ if( nDataIndex < 0)
+ return -1;
+ mpReadPtr = mpBasePtr + nIndexBase;
+ const int nDataCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if( nDataIndex >= nDataCount)
+ return -1;
+ const int nDataOfsSz = mpReadPtr[2];
+ mpReadPtr += 3 + (nDataOfsSz * nDataIndex);
+ int nOfs1 = 0;
+ switch( nDataOfsSz) {
+ default: SAL_WARN("vcl.fonts", "\tINVALID nDataOfsSz=" << nDataOfsSz); return -1;
+ case 1: nOfs1 = mpReadPtr[0]; break;
+ case 2: nOfs1 = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nOfs1 = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2]; break;
+ case 4: nOfs1 = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+ mpReadPtr += nDataOfsSz;
+
+ int nOfs2 = 0;
+ switch( nDataOfsSz) {
+ case 1: nOfs2 = mpReadPtr[0]; break;
+ case 2: nOfs2 = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nOfs2 = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2]; break;
+ case 4: nOfs2 = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+
+ mpReadPtr = mpBasePtr + (nIndexBase + 2) + nDataOfsSz * (nDataCount + 1) + nOfs1;
+ mpReadEnd = mpReadPtr + (nOfs2 - nOfs1);
+ assert( nOfs1 >= 0);
+ assert( nOfs2 >= nOfs1);
+ assert( mpReadPtr <= mpBaseEnd);
+ assert( mpReadEnd <= mpBaseEnd);
+ return (nOfs2 - nOfs1);
+}
+
+// skip over a CFF/CID index table
+void CffSubsetterContext::seekIndexEnd( int nIndexBase)
+{
+ assert( (nIndexBase > 0) && (mpBasePtr + nIndexBase + 3 <= mpBaseEnd));
+ mpReadPtr = mpBasePtr + nIndexBase;
+ const int nDataCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ const int nDataOfsSz = mpReadPtr[2];
+ mpReadPtr += 3 + nDataOfsSz * nDataCount;
+ assert( mpReadPtr <= mpBaseEnd);
+ int nEndOfs = 0;
+ switch( nDataOfsSz) {
+ default: SAL_WARN("vcl.fonts", "\tINVALID nDataOfsSz=" << nDataOfsSz); return;
+ case 1: nEndOfs = mpReadPtr[0]; break;
+ case 2: nEndOfs = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nEndOfs = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2];break;
+ case 4: nEndOfs = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+ mpReadPtr += nDataOfsSz;
+ mpReadPtr += nEndOfs - 1;
+ mpReadEnd = mpBaseEnd;
+ assert( nEndOfs >= 0);
+ assert( mpReadEnd <= mpBaseEnd);
+}
+
+// initialize FONTDICT specific values
+CffLocal::CffLocal()
+: mnPrivDictBase( 0)
+, mnPrivDictSize( 0)
+, mnLocalSubrOffs( 0)
+, mnLocalSubrBase( 0)
+, mnLocalSubrBias( 0)
+, maNominalWidth( 0)
+, maDefaultWidth( 0)
+, maStemStdHW( 0)
+, maStemStdVW( 0)
+, mfBlueScale( 0.0)
+, mfBlueShift( 0.0)
+, mfBlueFuzz( 0.0)
+, mfExpFactor( 0.0)
+, mnLangGroup( 0)
+, mbForceBold( false)
+{
+}
+
+CffGlobal::CffGlobal()
+: mnNameIdxBase( 0)
+, mnStringIdxBase( 0)
+, mbCIDFont( false)
+, mnCharStrBase( 0)
+, mnCharStrCount( 0)
+, mnCharsetBase( 0)
+, mnGlobalSubrBase( 0)
+, mnGlobalSubrCount( 0)
+, mnGlobalSubrBias( 0)
+, mnFDSelectBase( 0)
+, mnFontDictBase( 0)
+, mnFDAryCount( 1)
+, mnFontNameSID( 0)
+, mnFullNameSID( 0)
+{
+}
+
+bool CffSubsetterContext::initialCffRead()
+{
+ // get the CFFHeader
+ mpReadPtr = mpBasePtr;
+ const U8 nVerMajor = *(mpReadPtr++);
+ const U8 nVerMinor = *(mpReadPtr++);
+ const U8 nHeaderSize = *(mpReadPtr++);
+ const U8 nOffsetSize = *(mpReadPtr++);
+ // TODO: is the version number useful for anything else?
+ assert( (nVerMajor == 1) && (nVerMinor == 0));
+ (void)(nVerMajor + nVerMinor + nOffsetSize); // avoid compiler warnings
+
+ // prepare access to the NameIndex
+ mnNameIdxBase = nHeaderSize;
+ mpReadPtr = mpBasePtr + nHeaderSize;
+ seekIndexEnd( mnNameIdxBase);
+
+ // get the TopDict index
+ const sal_Int32 nTopDictBase = getReadOfs();
+ const int nTopDictCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if( nTopDictCount) {
+ for( int i = 0; i < nTopDictCount; ++i) {
+ seekIndexData( nTopDictBase, i);
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ assert( mpReadPtr == mpReadEnd);
+ }
+ }
+
+ // prepare access to the String index
+ mnStringIdxBase = getReadOfs();
+ seekIndexEnd( mnStringIdxBase);
+
+ // prepare access to the GlobalSubr index
+ mnGlobalSubrBase = getReadOfs();
+ mnGlobalSubrCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ mnGlobalSubrBias = (mnGlobalSubrCount<1240)?107:(mnGlobalSubrCount<33900)?1131:32768;
+ // skip past the last GlobalSubr entry
+// seekIndexEnd( mnGlobalSubrBase);
+
+ // get/skip the Encodings (we got mnEncodingBase from TOPDICT)
+// seekEncodingsEnd( mnEncodingBase);
+ // get/skip the Charsets (we got mnCharsetBase from TOPDICT)
+// seekCharsetsEnd( mnCharStrBase);
+ // get/skip FDSelect (CID only) data
+
+ // prepare access to the CharStrings index (we got the base from TOPDICT)
+ mpReadPtr = mpBasePtr + mnCharStrBase;
+ mnCharStrCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+// seekIndexEnd( mnCharStrBase);
+
+ // read the FDArray index (CID only)
+ if( mbCIDFont) {
+// assert( mnFontDictBase == tellRel());
+ mpReadPtr = mpBasePtr + mnFontDictBase;
+ mnFDAryCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if (o3tl::make_unsigned(mnFDAryCount) >= SAL_N_ELEMENTS(maCffLocal))
+ {
+ SAL_INFO("vcl.fonts", "CffSubsetterContext: too many CFF in font");
+ return false;
+ }
+
+ // read FDArray details to get access to the PRIVDICTs
+ for( int i = 0; i < mnFDAryCount; ++i) {
+ mpCffLocal = &maCffLocal[i];
+ seekIndexData( mnFontDictBase, i);
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ assert( mpReadPtr == mpReadEnd);
+ }
+ }
+
+ for( int i = 0; i < mnFDAryCount; ++i) {
+ mpCffLocal = &maCffLocal[i];
+
+ // get the PrivateDict index
+ // (we got mnPrivDictSize and mnPrivDictBase from TOPDICT or FDArray)
+ if( mpCffLocal->mnPrivDictSize != 0) {
+ assert( mpCffLocal->mnPrivDictSize > 0);
+ // get the PrivDict data
+ mpReadPtr = mpBasePtr + mpCffLocal->mnPrivDictBase;
+ mpReadEnd = mpReadPtr + mpCffLocal->mnPrivDictSize;
+ assert( mpReadEnd <= mpBaseEnd);
+ // read PrivDict details
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ }
+
+ // prepare access to the LocalSubrs (we got mnLocalSubrOffs from PRIVDICT)
+ if( mpCffLocal->mnLocalSubrOffs) {
+ // read LocalSubrs summary
+ mpCffLocal->mnLocalSubrBase = mpCffLocal->mnPrivDictBase + mpCffLocal->mnLocalSubrOffs;
+ mpReadPtr = mpBasePtr + mpCffLocal->mnLocalSubrBase;
+ const int nSubrCount = (mpReadPtr[0] << 8) + mpReadPtr[1];
+ mpCffLocal->mnLocalSubrBias = (nSubrCount<1240)?107:(nSubrCount<33900)?1131:32768;
+// seekIndexEnd( mpCffLocal->mnLocalSubrBase);
+ }
+ }
+
+ // ignore the Notices info
+
+ return true;
+}
+
+// get a cstring from a StringID
+const char* CffSubsetterContext::getString( int nStringID)
+{
+ // get a standard string if possible
+ const static int nStdStrings = SAL_N_ELEMENTS(pStringIds);
+ if( (nStringID >= 0) && (nStringID < nStdStrings))
+ return pStringIds[ nStringID];
+
+ // else get the string from the StringIndex table
+ const U8* pReadPtr = mpReadPtr;
+ const U8* pReadEnd = mpReadEnd;
+ nStringID -= nStdStrings;
+ int nLen = seekIndexData( mnStringIdxBase, nStringID);
+ // assert( nLen >= 0);
+ // TODO: just return the undecorated name
+ // TODO: get rid of static char buffer
+ static char aNameBuf[ 2560];
+ if( nLen < 0) {
+ sprintf( aNameBuf, "name[%d].notfound!", nStringID);
+ } else {
+ const int nMaxLen = sizeof(aNameBuf) - 1;
+ if( nLen >= nMaxLen)
+ nLen = nMaxLen;
+ for( int i = 0; i < nLen; ++i)
+ aNameBuf[i] = *(mpReadPtr++);
+ aNameBuf[ nLen] = '\0';
+ }
+ mpReadPtr = pReadPtr;
+ mpReadEnd = pReadEnd;
+ return aNameBuf;
+}
+
+// access a CID's FDSelect table
+int CffSubsetterContext::getFDSelect( int nGlyphIndex) const
+{
+ assert( nGlyphIndex >= 0);
+ assert( nGlyphIndex < mnCharStrCount);
+ if( !mbCIDFont)
+ return 0;
+
+ const U8* pReadPtr = mpBasePtr + mnFDSelectBase;
+ const U8 nFDSelFormat = *(pReadPtr++);
+ switch( nFDSelFormat) {
+ case 0: { // FDSELECT format 0
+ pReadPtr += nGlyphIndex;
+ const U8 nFDIdx = *(pReadPtr++);
+ return nFDIdx;
+ } //break;
+ case 3: { // FDSELECT format 3
+ const U16 nRangeCount = (pReadPtr[0]<<8) + pReadPtr[1];
+ assert( nRangeCount > 0);
+ assert( nRangeCount <= mnCharStrCount);
+ U16 nPrev = (pReadPtr[2]<<8) + pReadPtr[3];
+ assert( nPrev == 0);
+ (void)nPrev;
+ pReadPtr += 4;
+ // TODO? binary search
+ for( int i = 0; i < nRangeCount; ++i) {
+ const U8 nFDIdx = pReadPtr[0];
+ const U16 nNext = (pReadPtr[1]<<8) + pReadPtr[2];
+ assert( nPrev < nNext);
+ if( nGlyphIndex < nNext)
+ return nFDIdx;
+ pReadPtr += 3;
+ nPrev = nNext;
+ }
+ } break;
+ default: // invalid FDselect format
+ SAL_WARN("vcl.fonts", "invalid CFF.FdselType=" << nFDSelFormat);
+ break;
+ }
+
+ assert( false);
+ return -1;
+}
+
+int CffSubsetterContext::getGlyphSID( int nGlyphIndex) const
+{
+ if( nGlyphIndex == 0)
+ return 0; // ".notdef"
+ assert( nGlyphIndex >= 0);
+ assert( nGlyphIndex < mnCharStrCount);
+ if( (nGlyphIndex < 0) || (nGlyphIndex >= mnCharStrCount))
+ return -1;
+
+ // get the SID/CID from the Charset table
+ const U8* pReadPtr = mpBasePtr + mnCharsetBase;
+ const U8 nCSetFormat = *(pReadPtr++);
+ int nGlyphsToSkip = nGlyphIndex - 1;
+ switch( nCSetFormat) {
+ case 0: // charset format 0
+ pReadPtr += 2 * nGlyphsToSkip;
+ nGlyphsToSkip = 0;
+ break;
+ case 1: // charset format 1
+ while( nGlyphsToSkip >= 0) {
+ const int nLeft = pReadPtr[2];
+ if( nGlyphsToSkip <= nLeft)
+ break;
+ nGlyphsToSkip -= nLeft + 1;
+ pReadPtr += 3;
+ }
+ break;
+ case 2: // charset format 2
+ while( nGlyphsToSkip >= 0) {
+ const int nLeft = (pReadPtr[2]<<8) + pReadPtr[3];
+ if( nGlyphsToSkip <= nLeft)
+ break;
+ nGlyphsToSkip -= nLeft + 1;
+ pReadPtr += 4;
+ }
+ break;
+ default:
+ SAL_WARN("vcl.fonts", "ILLEGAL CFF-Charset format " << nCSetFormat);
+ return -2;
+ }
+
+ int nSID = (pReadPtr[0]<<8) + pReadPtr[1];
+ nSID += nGlyphsToSkip;
+ // NOTE: for CID-fonts the resulting SID is interpreted as CID
+ return nSID;
+}
+
+// NOTE: the result becomes invalid with the next call to this method
+const char* CffSubsetterContext::getGlyphName( int nGlyphIndex)
+{
+ // the first glyph is always the .notdef glyph
+ const char* pGlyphName = ".notdef";
+ if( nGlyphIndex == 0)
+ return pGlyphName;
+
+ // prepare a result buffer
+ // TODO: get rid of static buffer
+ static char aDefaultGlyphName[64];
+ pGlyphName = aDefaultGlyphName;
+
+ // get the glyph specific name
+ const int nSID = getGlyphSID( nGlyphIndex);
+ if( nSID < 0) // default glyph name
+ sprintf( aDefaultGlyphName, "gly%03d", nGlyphIndex);
+ else if( mbCIDFont) // default glyph name in CIDs
+ sprintf( aDefaultGlyphName, "cid%03d", nSID);
+ else { // glyph name from string table
+ const char* pSidName = getString( nSID);
+ // check validity of glyph name
+ if( pSidName) {
+ const char* p = pSidName;
+ while( (*p >= '0') && (*p <= 'z')) ++p;
+ if( (p >= pSidName+1) && (*p == '\0'))
+ pGlyphName = pSidName;
+ }
+ // if needed invent a fallback name
+ if( pGlyphName != pSidName)
+ sprintf( aDefaultGlyphName, "bad%03d", nSID);
+ }
+
+ return pGlyphName;
+}
+
+namespace {
+
+class Type1Emitter
+{
+public:
+ explicit Type1Emitter( FILE* pOutFile, bool bPfbSubset);
+ ~Type1Emitter();
+ void setSubsetName( const char* );
+
+ size_t emitRawData( const char* pData, size_t nLength) const;
+ void emitAllRaw();
+ void emitAllHex();
+ void emitAllCrypted();
+ int tellPos() const;
+ void updateLen( int nTellPos, size_t nLength);
+ void emitValVector( const char* pLineHead, const char* pLineTail, const std::vector<ValType>&);
+private:
+ FILE* mpFileOut;
+ char maBuffer[MAX_T1OPS_SIZE]; // TODO: dynamic allocation
+ unsigned mnEECryptR;
+public:
+ char* mpPtr;
+
+ char maSubsetName[256];
+ bool mbPfbSubset;
+ int mnHexLineCol;
+};
+
+}
+
+Type1Emitter::Type1Emitter( FILE* pOutFile, bool bPfbSubset)
+: mpFileOut( pOutFile)
+, maBuffer{}
+, mnEECryptR( 55665) // default eexec seed, TODO: mnEECryptSeed
+, mpPtr( maBuffer)
+, mbPfbSubset( bPfbSubset)
+, mnHexLineCol( 0)
+{
+ maSubsetName[0] = '\0';
+}
+
+Type1Emitter::~Type1Emitter()
+{
+ if( !mpFileOut)
+ return;
+ mpFileOut = nullptr;
+}
+
+void Type1Emitter::setSubsetName( const char* pSubsetName)
+{
+ maSubsetName[0] = '\0';
+ if( pSubsetName)
+ strncpy( maSubsetName, pSubsetName, sizeof(maSubsetName) - 1);
+ maSubsetName[sizeof(maSubsetName)-1] = '\0';
+}
+
+int Type1Emitter::tellPos() const
+{
+ int nTellPos = ftell( mpFileOut);
+ return nTellPos;
+}
+
+void Type1Emitter::updateLen( int nTellPos, size_t nLength)
+{
+ // update PFB segment header length
+ U8 cData[4];
+ cData[0] = static_cast<U8>(nLength >> 0);
+ cData[1] = static_cast<U8>(nLength >> 8);
+ cData[2] = static_cast<U8>(nLength >> 16);
+ cData[3] = static_cast<U8>(nLength >> 24);
+ const long nCurrPos = ftell(mpFileOut);
+ if (nCurrPos < 0)
+ return;
+ if (fseek( mpFileOut, nTellPos, SEEK_SET) != 0)
+ return;
+ fwrite(cData, 1, sizeof(cData), mpFileOut);
+ (void)fseek(mpFileOut, nCurrPos, SEEK_SET);
+}
+
+inline size_t Type1Emitter::emitRawData(const char* pData, size_t nLength) const
+{
+ return fwrite( pData, 1, nLength, mpFileOut);
+}
+
+inline void Type1Emitter::emitAllRaw()
+{
+ // writeout raw data
+ assert( (mpPtr - maBuffer) < int(sizeof(maBuffer)));
+ emitRawData( maBuffer, mpPtr - maBuffer);
+ // reset the raw buffer
+ mpPtr = maBuffer;
+}
+
+inline void Type1Emitter::emitAllHex()
+{
+ assert( (mpPtr - maBuffer) < int(sizeof(maBuffer)));
+ for( const char* p = maBuffer; p < mpPtr;) {
+ // convert binary chunk to hex
+ char aHexBuf[0x4000];
+ char* pOut = aHexBuf;
+ while( (p < mpPtr) && (pOut < aHexBuf+sizeof(aHexBuf)-4)) {
+ // convert each byte to hex
+ char cNibble = (static_cast<unsigned char>(*p) >> 4) & 0x0F;
+ cNibble += (cNibble < 10) ? '0' : 'A'-10;
+ *(pOut++) = cNibble;
+ cNibble = *(p++) & 0x0F;
+ cNibble += (cNibble < 10) ? '0' : 'A'-10;
+ *(pOut++) = cNibble;
+ // limit the line length
+ if( (++mnHexLineCol & 0x3F) == 0)
+ *(pOut++) = '\n';
+ }
+ // writeout hex-converted chunk
+ emitRawData( aHexBuf, pOut-aHexBuf);
+ }
+ // reset the raw buffer
+ mpPtr = maBuffer;
+}
+
+void Type1Emitter::emitAllCrypted()
+{
+ // apply t1crypt
+ for( char* p = maBuffer; p < mpPtr; ++p) {
+ *p ^= (mnEECryptR >> 8);
+ mnEECryptR = (*reinterpret_cast<U8*>(p) + mnEECryptR) * 52845 + 22719;
+ }
+
+ // emit the t1crypt result
+ if( mbPfbSubset)
+ emitAllRaw();
+ else
+ emitAllHex();
+}
+
+// #i110387# quick-and-dirty double->ascii conversion
+// needed because sprintf/ecvt/etc. alone are too localized (LC_NUMERIC)
+// also strip off trailing zeros in fraction while we are at it
+static int dbl2str( char* pOut, double fVal)
+{
+ const int nLen = psp::getValueOfDouble( pOut, fVal, 6);
+ return nLen;
+}
+
+void Type1Emitter::emitValVector( const char* pLineHead, const char* pLineTail,
+ const std::vector<ValType>& rVector)
+{
+ // ignore empty vectors
+ if( rVector.empty())
+ return;
+
+ // emit the line head
+ mpPtr += sprintf( mpPtr, "%s", pLineHead);
+ // emit the vector values
+ std::vector<ValType>::value_type aVal = 0;
+ for( std::vector<ValType>::const_iterator it = rVector.begin();;) {
+ aVal = *it;
+ if( ++it == rVector.end() )
+ break;
+ mpPtr += dbl2str( mpPtr, aVal);
+ *(mpPtr++) = ' ';
+ }
+ // emit the last value
+ mpPtr += dbl2str( mpPtr, aVal);
+ // emit the line tail
+ mpPtr += sprintf( mpPtr, "%s", pLineTail);
+}
+
+void CffSubsetterContext::emitAsType1( Type1Emitter& rEmitter,
+ const sal_GlyphId* pReqGlyphIds, const U8* pReqEncoding,
+ sal_Int32* pGlyphWidths, int nGlyphCount, FontSubsetInfo& rFSInfo)
+{
+ // prepare some fontdirectory details
+ static const int nUniqueIdBase = 4100000; // using private-interchange UniqueIds
+ static int nUniqueId = nUniqueIdBase;
+ ++nUniqueId;
+
+ char* pFontName = rEmitter.maSubsetName;
+ if( !*pFontName ) {
+ if( mnFontNameSID) {
+ // get the fontname directly if available
+ strncpy( pFontName, getString( mnFontNameSID), sizeof(rEmitter.maSubsetName) - 1);
+ pFontName[sizeof(rEmitter.maSubsetName) - 1] = 0;
+ } else if( mnFullNameSID) {
+ // approximate fontname as fullname-whitespace
+ const char* pI = getString( mnFullNameSID);
+ char* pO = pFontName;
+ const char* pLimit = pFontName + sizeof(rEmitter.maSubsetName) - 1;
+ while( pO < pLimit) {
+ const char c = *(pI++);
+ if( c != ' ')
+ *(pO++) = c;
+ if( !c)
+ break;
+ }
+ *pO = '\0';
+ } else {
+ // fallback name of last resort
+ strncpy( pFontName, "DummyName", sizeof(rEmitter.maSubsetName));
+ }
+ }
+ const char* pFullName = pFontName;
+ const char* pFamilyName = pFontName;
+
+ char*& pOut = rEmitter.mpPtr; // convenience reference, TODO: cleanup
+
+ // create a PFB+Type1 header
+ if( rEmitter.mbPfbSubset ) {
+ static const char aPfbHeader[] = "\x80\x01\x00\x00\x00\x00";
+ rEmitter.emitRawData( aPfbHeader, sizeof(aPfbHeader)-1);
+ }
+
+ pOut += sprintf( pOut, "%%!FontType1-1.0: %s 001.003\n", rEmitter.maSubsetName);
+ // emit TOPDICT
+ pOut += sprintf( pOut,
+ "11 dict begin\n" // TODO: dynamic entry count for TOPDICT
+ "/FontType 1 def\n"
+ "/PaintType 0 def\n");
+ pOut += sprintf( pOut, "/FontName /%s def\n", rEmitter.maSubsetName);
+ pOut += sprintf( pOut, "/UniqueID %d def\n", nUniqueId);
+ // emit FontMatrix
+ if( maFontMatrix.size() == 6)
+ rEmitter.emitValVector( "/FontMatrix [", "]readonly def\n", maFontMatrix);
+ else // emit default FontMatrix if needed
+ pOut += sprintf( pOut, "/FontMatrix [0.001 0 0 0.001 0 0]readonly def\n");
+ // emit FontBBox
+ if( maFontBBox.size() == 4)
+ rEmitter.emitValVector( "/FontBBox {", "}readonly def\n", maFontBBox);
+ else // emit default FontBBox if needed
+ pOut += sprintf( pOut, "/FontBBox {0 0 999 999}readonly def\n");
+ // emit FONTINFO into TOPDICT
+ pOut += sprintf( pOut,
+ "/FontInfo 2 dict dup begin\n" // TODO: check fontinfo entry count
+ " /FullName (%s) readonly def\n"
+ " /FamilyName (%s) readonly def\n"
+ "end readonly def\n",
+ pFullName, pFamilyName);
+
+ pOut += sprintf( pOut,
+ "/Encoding 256 array\n"
+ "0 1 255 {1 index exch /.notdef put} for\n");
+ for( int i = 1; (i < nGlyphCount) && (i < 256); ++i) {
+ const char* pGlyphName = getGlyphName( pReqGlyphIds[i]);
+ pOut += sprintf( pOut, "dup %d /%s put\n", pReqEncoding[i], pGlyphName);
+ }
+ pOut += sprintf( pOut, "readonly def\n");
+ pOut += sprintf( pOut,
+ // TODO: more topdict entries
+ "currentdict end\n"
+ "currentfile eexec\n");
+
+ // emit PFB header
+ rEmitter.emitAllRaw();
+ if( rEmitter.mbPfbSubset) {
+ // update PFB header segment
+ const int nPfbHeaderLen = rEmitter.tellPos() - 6;
+ rEmitter.updateLen( 2, nPfbHeaderLen);
+
+ // prepare start of eexec segment
+ rEmitter.emitRawData( "\x80\x02\x00\x00\x00\x00", 6); // segment start
+ }
+ const int nEExecSegTell = rEmitter.tellPos();
+
+ // which always starts with a privdict
+ // count the privdict entries
+ int nPrivEntryCount = 9;
+ // emit blue hints only if non-default values
+ nPrivEntryCount += int(!mpCffLocal->maOtherBlues.empty());
+ nPrivEntryCount += int(!mpCffLocal->maFamilyBlues.empty());
+ nPrivEntryCount += int(!mpCffLocal->maFamilyOtherBlues.empty());
+ nPrivEntryCount += int(mpCffLocal->mfBlueScale != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mfBlueShift != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mfBlueFuzz != 0.0);
+ // emit stem hints only if non-default values
+ nPrivEntryCount += int(mpCffLocal->maStemStdHW != 0);
+ nPrivEntryCount += int(mpCffLocal->maStemStdVW != 0);
+ nPrivEntryCount += int(!mpCffLocal->maStemSnapH.empty());
+ nPrivEntryCount += int(!mpCffLocal->maStemSnapV.empty());
+ // emit other hints only if non-default values
+ nPrivEntryCount += int(mpCffLocal->mfExpFactor != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mnLangGroup != 0);
+ nPrivEntryCount += int(mpCffLocal->mnLangGroup == 1);
+ nPrivEntryCount += int(mpCffLocal->mbForceBold);
+ // emit the privdict header
+ pOut += sprintf( pOut,
+ "\110\104\125 "
+ "dup\n/Private %d dict dup begin\n"
+ "/RD{string currentfile exch readstring pop}executeonly def\n"
+ "/ND{noaccess def}executeonly def\n"
+ "/NP{noaccess put}executeonly def\n"
+ "/MinFeature{16 16}ND\n"
+ "/password 5839 def\n", // TODO: mnRDCryptSeed?
+ nPrivEntryCount);
+
+ // emit blue hint related privdict entries
+ if( !mpCffLocal->maBlueValues.empty())
+ rEmitter.emitValVector( "/BlueValues [", "]ND\n", mpCffLocal->maBlueValues);
+ else
+ pOut += sprintf( pOut, "/BlueValues []ND\n"); // default to empty BlueValues
+ rEmitter.emitValVector( "/OtherBlues [", "]ND\n", mpCffLocal->maOtherBlues);
+ rEmitter.emitValVector( "/FamilyBlues [", "]ND\n", mpCffLocal->maFamilyBlues);
+ rEmitter.emitValVector( "/FamilyOtherBlues [", "]ND\n", mpCffLocal->maFamilyOtherBlues);
+
+ if( mpCffLocal->mfBlueScale) {
+ pOut += sprintf( pOut, "/BlueScale ");
+ pOut += dbl2str( pOut, mpCffLocal->mfBlueScale);
+ pOut += sprintf( pOut, " def\n");
+ }
+ if( mpCffLocal->mfBlueShift) { // default BlueShift==7
+ pOut += sprintf( pOut, "/BlueShift ");
+ pOut += dbl2str( pOut, mpCffLocal->mfBlueShift);
+ pOut += sprintf( pOut, " def\n");
+ }
+ if( mpCffLocal->mfBlueFuzz) { // default BlueFuzz==1
+ pOut += sprintf( pOut, "/BlueFuzz ");
+ pOut += dbl2str( pOut, mpCffLocal->mfBlueFuzz);
+ pOut += sprintf( pOut, " def\n");
+ }
+
+ // emit stem hint related privdict entries
+ if( mpCffLocal->maStemStdHW) {
+ pOut += sprintf( pOut, "/StdHW [");
+ pOut += dbl2str( pOut, mpCffLocal->maStemStdHW);
+ pOut += sprintf( pOut, "] def\n");
+ }
+ if( mpCffLocal->maStemStdVW) {
+ pOut += sprintf( pOut, "/StdVW [");
+ pOut += dbl2str( pOut, mpCffLocal->maStemStdVW);
+ pOut += sprintf( pOut, "] def\n");
+ }
+ rEmitter.emitValVector( "/StemSnapH [", "]ND\n", mpCffLocal->maStemSnapH);
+ rEmitter.emitValVector( "/StemSnapV [", "]ND\n", mpCffLocal->maStemSnapV);
+
+ // emit other hints
+ if( mpCffLocal->mbForceBold)
+ pOut += sprintf( pOut, "/ForceBold true def\n");
+ if( mpCffLocal->mnLangGroup != 0)
+ pOut += sprintf( pOut, "/LanguageGroup %d def\n", mpCffLocal->mnLangGroup);
+ if( mpCffLocal->mnLangGroup == 1) // compatibility with ancient printers
+ pOut += sprintf( pOut, "/RndStemUp false def\n");
+ if( mpCffLocal->mfExpFactor) {
+ pOut += sprintf( pOut, "/ExpansionFactor ");
+ pOut += dbl2str( pOut, mpCffLocal->mfExpFactor);
+ pOut += sprintf( pOut, " def\n");
+ }
+
+ // emit remaining privdict entries
+ pOut += sprintf( pOut, "/UniqueID %d def\n", nUniqueId);
+ // TODO?: more privdict entries?
+
+ static const char aOtherSubrs[] =
+ "/OtherSubrs\n"
+ "% Dummy code for faking flex hints\n"
+ "[ {} {} {} {systemdict /internaldict known not {pop 3}\n"
+ "{1183615869 systemdict /internaldict get exec\n"
+ "dup /startlock known\n"
+ "{/startlock get exec}\n"
+ "{dup /strtlck known\n"
+ "{/strtlck get exec}\n"
+ "{pop 3}\nifelse}\nifelse}\nifelse\n} executeonly\n"
+ "] ND\n";
+ memcpy( pOut, aOtherSubrs, sizeof(aOtherSubrs)-1);
+ pOut += sizeof(aOtherSubrs)-1;
+
+ // emit used GlobalSubr charstrings
+ // these are the just the default subrs
+ // TODO: do we need them as the flex hints are resolved differently?
+ static const char aSubrs[] =
+ "/Subrs 5 array\n"
+ "dup 0 15 RD \x5F\x3D\x6B\xAC\x3C\xBD\x74\x3D\x3E\x17\xA0\x86\x58\x08\x85 NP\n"
+ "dup 1 9 RD \x5F\x3D\x6B\xD8\xA6\xB5\x68\xB6\xA2 NP\n"
+ "dup 2 9 RD \x5F\x3D\x6B\xAC\x39\x46\xB9\x43\xF9 NP\n"
+ "dup 3 5 RD \x5F\x3D\x6B\xAC\xB9 NP\n"
+ "dup 4 12 RD \x5F\x3D\x6B\xAC\x3E\x5D\x48\x54\x62\x76\x39\x03 NP\n"
+ "ND\n";
+ memcpy( pOut, aSubrs, sizeof(aSubrs)-1);
+ pOut += sizeof(aSubrs)-1;
+
+ // TODO: emit more GlobalSubr charstrings?
+ // TODO: emit used LocalSubr charstrings?
+
+ // emit the CharStrings for the requested glyphs
+ pOut += sprintf( pOut,
+ "2 index /CharStrings %d dict dup begin\n", nGlyphCount);
+ rEmitter.emitAllCrypted();
+ for( int i = 0; i < nGlyphCount; ++i) {
+ const int nCffGlyphId = pReqGlyphIds[i];
+ assert( (nCffGlyphId >= 0) && (nCffGlyphId < mnCharStrCount));
+ // get privdict context matching to the glyph
+ const int nFDSelect = getFDSelect( nCffGlyphId);
+ if( nFDSelect < 0)
+ continue;
+ mpCffLocal = &maCffLocal[ nFDSelect];
+ // convert the Type2op charstring to its Type1op counterpart
+ const int nT2Len = seekIndexData( mnCharStrBase, nCffGlyphId);
+ assert( nT2Len > 0);
+ U8 aType1Ops[ MAX_T1OPS_SIZE]; // TODO: dynamic allocation
+ const int nT1Len = convert2Type1Ops( mpCffLocal, mpReadPtr, nT2Len, aType1Ops);
+ // get the glyph name
+ const char* pGlyphName = getGlyphName( nCffGlyphId);
+ // emit the encrypted Type1op charstring
+ pOut += sprintf( pOut, "/%s %d RD ", pGlyphName, nT1Len);
+ memcpy( pOut, aType1Ops, nT1Len);
+ pOut += nT1Len;
+ pOut += sprintf( pOut, " ND\n");
+ rEmitter.emitAllCrypted();
+ // provide individual glyphwidths if requested
+ if( pGlyphWidths ) {
+ ValType aCharWidth = maCharWidth;
+ if( maFontMatrix.size() >= 4)
+ aCharWidth *= 1000.0F * maFontMatrix[0];
+ pGlyphWidths[i] = static_cast<sal_Int32>(aCharWidth);
+ }
+ }
+ pOut += sprintf( pOut, "end end\nreadonly put\nput\n");
+ pOut += sprintf( pOut, "dup/FontName get exch definefont pop\n");
+ pOut += sprintf( pOut, "mark currentfile closefile\n");
+ rEmitter.emitAllCrypted();
+
+ // mark stop of eexec encryption
+ if( rEmitter.mbPfbSubset) {
+ const int nEExecLen = rEmitter.tellPos() - nEExecSegTell;
+ rEmitter.updateLen( nEExecSegTell-4, nEExecLen);
+ }
+
+ // create PFB footer
+ static const char aPfxFooter[] = "\x80\x01\x14\x02\x00\x00\n" // TODO: check segment len
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "cleartomark\n"
+ "\x80\x03";
+ if( rEmitter.mbPfbSubset)
+ rEmitter.emitRawData( aPfxFooter, sizeof(aPfxFooter)-1);
+ else
+ rEmitter.emitRawData( aPfxFooter+6, sizeof(aPfxFooter)-9);
+
+ // provide details to the subset requesters, TODO: move into own method?
+ // note: Top and Bottom are flipped between Type1 and VCL
+ // note: the rest of VCL expects the details below to be scaled like for an emUnits==1000 font
+ ValType fXFactor = 1.0;
+ ValType fYFactor = 1.0;
+ if( maFontMatrix.size() >= 4) {
+ fXFactor = 1000.0F * maFontMatrix[0];
+ fYFactor = 1000.0F * maFontMatrix[3];
+ }
+ rFSInfo.m_aFontBBox = tools::Rectangle( Point( static_cast<sal_Int32>(maFontBBox[0] * fXFactor),
+ static_cast<sal_Int32>(maFontBBox[1] * fYFactor) ),
+ Point( static_cast<sal_Int32>(maFontBBox[2] * fXFactor),
+ static_cast<sal_Int32>(maFontBBox[3] * fYFactor) ) );
+ // PDF-Spec says the values below mean the ink bounds!
+ // TODO: use better approximations for these ink bounds
+ rFSInfo.m_nAscent = +rFSInfo.m_aFontBBox.Bottom(); // for capital letters
+ rFSInfo.m_nDescent = -rFSInfo.m_aFontBBox.Top(); // for all letters
+ rFSInfo.m_nCapHeight = rFSInfo.m_nAscent; // for top-flat capital letters
+
+ rFSInfo.m_nFontType = rEmitter.mbPfbSubset ? FontType::TYPE1_PFB : FontType::TYPE1_PFA;
+ rFSInfo.m_aPSName = OUString( rEmitter.maSubsetName, strlen(rEmitter.maSubsetName), RTL_TEXTENCODING_UTF8 );
+}
+
+bool FontSubsetInfo::CreateFontSubsetFromCff( sal_Int32* pOutGlyphWidths )
+{
+ CffSubsetterContext aCff( mpInFontBytes, mnInByteLength);
+ bool bRC = aCff.initialCffRead();
+ if (!bRC)
+ return bRC;
+
+ // emit Type1 subset from the CFF input
+ // TODO: also support CFF->CFF subsetting (when PDF-export and PS-printing need it)
+ const bool bPfbSubset(mnReqFontTypeMask & FontType::TYPE1_PFB);
+ Type1Emitter aType1Emitter( mpOutFile, bPfbSubset);
+ aType1Emitter.setSubsetName( mpReqFontName);
+ aCff.emitAsType1( aType1Emitter,
+ mpReqGlyphIds, mpReqEncodedIds,
+ pOutGlyphWidths, mnReqGlyphCount, *this);
+ return true;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/fontsubset.cxx b/vcl/source/fontsubset/fontsubset.cxx
new file mode 100644
index 000000000..8a4eeb9aa
--- /dev/null
+++ b/vcl/source/fontsubset/fontsubset.cxx
@@ -0,0 +1,163 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+
+#include <fontsubset.hxx>
+#include <sft.hxx>
+
+FontSubsetInfo::FontSubsetInfo()
+ : m_nAscent( 0)
+ , m_nDescent( 0)
+ , m_nCapHeight( 0)
+ , m_nFontType( FontType::NO_FONT)
+ , mpInFontBytes( nullptr)
+ , mnInByteLength( 0)
+ , meInFontType( FontType::NO_FONT)
+ , mpSftTTFont( nullptr)
+ , mnReqFontTypeMask( FontType::NO_FONT )
+ , mpOutFile(nullptr)
+ , mpReqFontName(nullptr)
+ , mpReqGlyphIds(nullptr)
+ , mpReqEncodedIds(nullptr)
+ , mnReqGlyphCount(0)
+{
+}
+
+FontSubsetInfo::~FontSubsetInfo()
+{
+}
+
+// prepare subsetting for fonts where the input font file is mapped
+void FontSubsetInfo::LoadFont(
+ FontType eInFontType,
+ const unsigned char* pInFontBytes, int nInByteLength)
+{
+ SAL_WARN_IF( (mpSftTTFont != nullptr), "vcl", "Subset from SFT and from mapped font-file requested");
+ meInFontType = eInFontType;
+ mpInFontBytes = pInFontBytes;
+ mnInByteLength = nInByteLength;
+}
+
+// prepare subsetting for fonts that are known to the SFT-parser
+void FontSubsetInfo::LoadFont( vcl::TrueTypeFont* pSftTTFont )
+{
+ SAL_WARN_IF( (mpInFontBytes != nullptr), "vcl", "Subset from SFT and from mapped font-file requested");
+ mpSftTTFont = pSftTTFont;
+ meInFontType = FontType::ANY_SFNT;
+}
+
+bool FontSubsetInfo::CreateFontSubset(
+ FontType nReqFontTypeMask,
+ FILE* pOutFile, const char* pReqFontName,
+ const sal_GlyphId* pReqGlyphIds, const sal_uInt8* pReqEncodedIds, int nReqGlyphCount,
+ sal_Int32* pOutGlyphWidths)
+{
+ // prepare request details needed by all underlying subsetters
+ mnReqFontTypeMask = nReqFontTypeMask;
+ mpOutFile = pOutFile;
+ mpReqFontName = pReqFontName;
+ mpReqGlyphIds = pReqGlyphIds;
+ mpReqEncodedIds = pReqEncodedIds;
+ mnReqGlyphCount = nReqGlyphCount;
+
+ // TODO: move the glyphid/encid/notdef reshuffling from the callers to here
+
+ // dispatch to underlying subsetters
+ bool bOK = false;
+
+ // TODO: better match available input-type to possible subset-types
+ switch( meInFontType) {
+ case FontType::SFNT_TTF:
+ case FontType::SFNT_CFF:
+ case FontType::ANY_SFNT:
+ bOK = CreateFontSubsetFromSfnt( pOutGlyphWidths);
+ break;
+ case FontType::CFF_FONT:
+ bOK = CreateFontSubsetFromCff( pOutGlyphWidths);
+ break;
+ case FontType::TYPE1_PFA:
+ case FontType::TYPE1_PFB:
+ case FontType::ANY_TYPE1:
+ bOK = CreateFontSubsetFromType1( pOutGlyphWidths);
+ break;
+ case FontType::NO_FONT:
+ default:
+ OSL_FAIL( "unhandled type in CreateFontSubset()");
+ break;
+ }
+
+ return bOK;
+}
+
+// TODO: move function to sft.cxx to replace dummy implementation
+bool FontSubsetInfo::CreateFontSubsetFromSfnt( sal_Int32* pOutGlyphWidths )
+{
+ // handle SFNT_CFF fonts
+ int nCffLength = 0;
+ const sal_uInt8* pCffBytes = nullptr;
+ if( GetSfntTable( mpSftTTFont, vcl::O_CFF, &pCffBytes, &nCffLength))
+ {
+ LoadFont( FontType::CFF_FONT, pCffBytes, nCffLength);
+ const bool bOK = CreateFontSubsetFromCff( pOutGlyphWidths);
+ return bOK;
+ }
+
+ // handle SFNT_TTF fonts
+ // by forwarding the subset request to AG's sft subsetter
+#if 1 // TODO: remove conversion tp 16bit glyphids when sft-subsetter has been updated
+ std::vector<sal_uInt16> aShortGlyphIds;
+ aShortGlyphIds.reserve(mnReqGlyphCount);
+ for (int i = 0; i < mnReqGlyphCount; ++i)
+ aShortGlyphIds.push_back(static_cast<sal_uInt16>(mpReqGlyphIds[i]));
+ // remove const_cast when sft-subsetter is const-correct
+ sal_uInt8* pEncArray = const_cast<sal_uInt8*>( mpReqEncodedIds );
+#endif
+ vcl::SFErrCodes nSFTErr = vcl::SFErrCodes::BadArg;
+ if( mnReqFontTypeMask & FontType::TYPE42_FONT )
+ {
+ nSFTErr = CreateT42FromTTGlyphs( mpSftTTFont, mpOutFile, mpReqFontName,
+ aShortGlyphIds.data(), pEncArray, mnReqGlyphCount );
+ }
+ else if( mnReqFontTypeMask & FontType::TYPE3_FONT )
+ {
+ nSFTErr = CreateT3FromTTGlyphs( mpSftTTFont, mpOutFile, mpReqFontName,
+ aShortGlyphIds.data(), pEncArray, mnReqGlyphCount,
+ 0 /* 0 = horizontal, 1 = vertical */ );
+ }
+ else if( mnReqFontTypeMask & FontType::SFNT_TTF )
+ {
+ // TODO: use CreateTTFromTTGlyphs()
+ // TODO: move functionality from callers here
+ }
+
+ return (nSFTErr != vcl::SFErrCodes::Ok);
+}
+
+// TODO: replace dummy implementation
+bool FontSubsetInfo::CreateFontSubsetFromType1( const sal_Int32* /*pOutGlyphWidths*/)
+{
+ SAL_WARN("vcl.fonts",
+ "CreateFontSubsetFromType1: replace dummy implementation.");
+ return false;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/list.cxx b/vcl/source/fontsubset/list.cxx
new file mode 100644
index 000000000..aca585678
--- /dev/null
+++ b/vcl/source/fontsubset/list.cxx
@@ -0,0 +1,229 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*[]---------------------------------------------------[]*/
+/*| |*/
+/*| list.c - bidirectional list class |*/
+/*| |*/
+/*| |*/
+/*| Author: Alexander Gelfenbain |*/
+/*[]---------------------------------------------------[]*/
+
+#include <assert.h>
+#include <cstdlib>
+
+#include "list.h"
+
+namespace {
+
+/*- private data types */
+struct lnode {
+ struct lnode *next;
+ struct lnode *prev;
+
+ void *value;
+
+};
+
+}
+
+struct list_ {
+ lnode *head, *tail, *cptr;
+ size_t aCount;
+ list_destructor eDtor;
+};
+
+/*- private methods */
+
+static lnode *newNode(void *el)
+{
+ lnode *ptr = static_cast<lnode *>(std::malloc(sizeof(lnode)));
+ assert(ptr != nullptr);
+
+ ptr->value = el;
+
+ return ptr;
+}
+
+static lnode *appendPrim(list pThis, void *el)
+{
+ lnode *ptr = newNode(el);
+ lnode **flink, *blink;
+
+ if (pThis->tail != nullptr) {
+ flink = &(pThis->tail->next);
+ blink = pThis->tail;
+ } else {
+ flink = &pThis->head;
+ blink = nullptr;
+ pThis->cptr = ptr; /*- list was empty - set current to this element */
+ }
+
+ *flink = ptr;
+ pThis->tail = ptr;
+
+ ptr->prev = blink;
+ ptr->next = nullptr;
+
+ pThis->aCount++;
+ return ptr;
+}
+
+/*- public methods */
+list listNewEmpty() /*- default ctor */
+{
+ list pThis = static_cast<list>(std::malloc(sizeof(struct list_)));
+ assert(pThis != nullptr);
+
+ pThis->aCount = 0;
+ pThis->eDtor = nullptr;
+ pThis->head = pThis->tail = pThis->cptr = nullptr;
+
+ return pThis;
+}
+
+void listDispose(list pThis) /*- dtor */
+{
+ assert(pThis != nullptr);
+ listClear(pThis);
+ std::free(pThis);
+}
+
+void listSetElementDtor(list pThis, list_destructor f)
+{
+ assert(pThis != nullptr);
+ pThis->eDtor = f;
+}
+
+/* calling this function on an empty list is a run-time error */
+void *listCurrent(list pThis)
+{
+ assert(pThis != nullptr);
+ assert(pThis->cptr != nullptr);
+ return pThis->cptr->value;
+}
+
+int listCount(list pThis)
+{
+ assert(pThis != nullptr);
+ return pThis->aCount;
+}
+
+int listIsEmpty(list pThis)
+{
+ assert(pThis != nullptr);
+ return pThis->aCount == 0;
+}
+
+int listNext(list pThis)
+{
+ return listSkipForward(pThis, 1);
+}
+
+int listSkipForward(list pThis, int n)
+{
+ int m = 0;
+ assert(pThis != nullptr);
+
+ if (pThis->cptr == nullptr) return 0;
+
+ while (n != 0) {
+ if (pThis->cptr->next == nullptr) break;
+ pThis->cptr = pThis->cptr->next;
+ n--;
+ m++;
+ }
+ return m;
+}
+
+int listToFirst(list pThis)
+{
+ assert(pThis != nullptr);
+
+ if (pThis->cptr != pThis->head) {
+ pThis->cptr = pThis->head;
+ return 1;
+ }
+ return 0;
+}
+
+int listToLast(list pThis)
+{
+ assert(pThis != nullptr);
+
+ if (pThis->cptr != pThis->tail) {
+ pThis->cptr = pThis->tail;
+ return 1;
+ }
+ return 0;
+}
+
+list listAppend(list pThis, void *el)
+{
+ assert(pThis != nullptr);
+
+ appendPrim(pThis, el);
+ return pThis;
+}
+
+list listRemove(list pThis)
+{
+ lnode *ptr = nullptr;
+ if (pThis->cptr == nullptr) return pThis;
+
+ if (pThis->cptr->next != nullptr) {
+ ptr = pThis->cptr->next;
+ pThis->cptr->next->prev = pThis->cptr->prev;
+ } else {
+ pThis->tail = pThis->cptr->prev;
+ }
+
+ if (pThis->cptr->prev != nullptr) {
+ if (ptr == nullptr) ptr = pThis->cptr->prev;
+ pThis->cptr->prev->next = pThis->cptr->next;
+ } else {
+ pThis->head = pThis->cptr->next;
+ }
+
+ if (pThis->eDtor) pThis->eDtor(pThis->cptr->value); /* call the dtor callback */
+
+ std::free(pThis->cptr);
+ pThis->aCount--;
+ pThis->cptr = ptr;
+ return pThis;
+}
+
+list listClear(list pThis)
+{
+ lnode *node = pThis->head, *ptr;
+
+ while (node) {
+ ptr = node->next;
+ if (pThis->eDtor) pThis->eDtor(node->value); /* call the dtor callback */
+ std::free(node);
+ pThis->aCount--;
+ node = ptr;
+ }
+
+ pThis->head = pThis->tail = pThis->cptr = nullptr;
+ assert(pThis->aCount == 0);
+ return pThis;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/list.h b/vcl/source/fontsubset/list.h
new file mode 100644
index 000000000..18fda151a
--- /dev/null
+++ b/vcl/source/fontsubset/list.h
@@ -0,0 +1,89 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*[]---------------------------------------------------[]*/
+/*| |*/
+/*| Implementation of the list data type |*/
+/*| |*/
+/*| |*/
+/*| Author: Alexander Gelfenbain |*/
+/*[]---------------------------------------------------[]*/
+
+#ifndef INCLUDED_VCL_INC_LIST_H
+#define INCLUDED_VCL_INC_LIST_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*
+ * List of void * pointers
+ */
+
+ typedef struct list_ *list;
+ typedef void (*list_destructor)(void *);
+
+/*- constructors and a destructor */
+ list listNewEmpty(void);
+#ifdef TEST
+ list listNewCopy(list);
+#endif
+ void listDispose(list);
+ void listSetElementDtor(list, list_destructor); /*- this function will be executed when the element is removed via listRemove() or listClear() */
+
+/*- queries */
+ void * listCurrent(list);
+ int listCount(list);
+ int listIsEmpty(list);
+#ifdef TEST
+ int listAtFirst(list);
+ int listAtLast(list);
+ int listPosition(list); /* Expensive! */
+#endif
+
+/*- positioning functions */
+/*- return the number of elements by which the current position in the list changes */
+ int listNext(list);
+ int listSkipForward(list, int n);
+ int listToFirst(list);
+ int listToLast(list);
+
+/*- adding and removing elements */
+ list listAppend(list, void *);
+#ifdef TEST
+ list listPrepend(list, void *);
+ list listInsertAfter(list, void *);
+ list listInsertBefore(list, void *);
+#endif
+ list listRemove(list); /* removes the current element */
+ list listClear(list); /* removes all elements */
+
+#ifdef TEST
+/*- forall */
+ void listForAll(list, void (*f)(void *));
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // INCLUDED_VCL_INC_LIST_H
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/sft.cxx b/vcl/source/fontsubset/sft.cxx
new file mode 100644
index 000000000..efba8ff59
--- /dev/null
+++ b/vcl/source/fontsubset/sft.cxx
@@ -0,0 +1,2635 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*
+ * Sun Font Tools
+ *
+ * Author: Alexander Gelfenbain
+ *
+ */
+
+#include <assert.h>
+
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#ifdef UNX
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+#include <sft.hxx>
+#include "ttcr.hxx"
+#include "xlat.hxx"
+#include <rtl/crc.h>
+#include <rtl/ustring.hxx>
+#include <sal/log.hxx>
+#include <o3tl/safeint.hxx>
+#include <osl/endian.h>
+#include <algorithm>
+
+namespace vcl
+{
+
+/*- module identification */
+
+static const char * const modname = "SunTypeTools-TT";
+static const char * const modver = "1.0";
+static const char * const modextra = "gelf";
+
+/*- private functions, constants and data types */
+
+namespace {
+
+enum PathSegmentType {
+ PS_NOOP = 0,
+ PS_MOVETO = 1,
+ PS_LINETO = 2,
+ PS_CURVETO = 3,
+ PS_CLOSEPATH = 4
+};
+
+struct PSPathElement
+{
+ PathSegmentType type;
+ int x1, y1;
+ int x2, y2;
+ int x3, y3;
+
+ explicit PSPathElement( PathSegmentType i_eType ) : type( i_eType ),
+ x1( 0 ), y1( 0 ),
+ x2( 0 ), y2( 0 ),
+ x3( 0 ), y3( 0 )
+ {
+ }
+};
+
+/*- In horizontal writing mode right sidebearing is calculated using this formula
+ *- rsb = aw - (lsb + xMax - xMin) -*/
+struct TTGlyphMetrics {
+ sal_Int16 xMin;
+ sal_Int16 yMin;
+ sal_Int16 xMax;
+ sal_Int16 yMax;
+ sal_uInt16 aw; /*- Advance Width (horizontal writing mode) */
+ sal_Int16 lsb; /*- Left sidebearing (horizontal writing mode) */
+ sal_uInt16 ah; /*- advance height (vertical writing mode) */
+};
+
+#define HFORMAT_LINELEN 64
+
+struct HexFmt {
+ FILE *o;
+ char buffer[HFORMAT_LINELEN];
+ size_t bufpos;
+ int total;
+};
+
+struct GlyphOffsets {
+ sal_uInt32 nGlyphs; /* number of glyphs in the font + 1 */
+ sal_uInt32 *offs; /* array of nGlyphs offsets */
+};
+
+}
+
+static void *smalloc(size_t size)
+{
+ void *res = malloc(size);
+ assert(res != nullptr);
+ return res;
+}
+
+static void *scalloc(size_t n, size_t size)
+{
+ void *res = calloc(n, size);
+ assert(res != nullptr);
+ return res;
+}
+
+/*- Data access methods for data stored in big-endian format */
+static sal_Int16 GetInt16(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_Int16 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+
+ return t;
+}
+
+static sal_uInt16 GetUInt16(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_uInt16 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+
+ return t;
+}
+
+static sal_Int32 GetInt32(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_Int32 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 |
+ (ptr+offset)[2] << 8 | (ptr+offset)[3];
+
+ return t;
+}
+
+static sal_uInt32 GetUInt32(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_uInt32 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 |
+ (ptr+offset)[2] << 8 | (ptr+offset)[3];
+
+ return t;
+}
+
+#if defined(OSL_BIGENDIAN)
+#define Int16FromMOTA(a) (a)
+#define Int32FromMOTA(a) (a)
+#else
+static sal_uInt16 Int16FromMOTA(sal_uInt16 a) {
+ return static_cast<sal_uInt16>(static_cast<sal_uInt8>(a >> 8) | (static_cast<sal_uInt8>(a) << 8));
+}
+static sal_uInt32 Int32FromMOTA(sal_uInt32 a) {
+ return ((a>>24)&0xFF) | (((a>>8)&0xFF00) | ((a&0xFF00)<<8) | ((a&0xFF)<<24));
+}
+#endif
+
+static F16Dot16 fixedMul(F16Dot16 a, F16Dot16 b)
+{
+ unsigned int a1, b1;
+ unsigned int a2, b2;
+ F16Dot16 res;
+ int sign;
+
+ sign = (a & 0x80000000) ^ (b & 0x80000000);
+ if (a < 0) a = -a;
+ if (b < 0) b = -b;
+
+ a1 = a >> 16;
+ b1 = a & 0xFFFF;
+ a2 = b >> 16;
+ b2 = b & 0xFFFF;
+
+ res = a1 * a2;
+
+ /* if (res > 0x7FFF) assert(!"fixedMul: F16Dot16 overflow"); */
+
+ res <<= 16;
+ res += a1 * b2 + b1 * a2 + ((b1 * b2) >> 16);
+
+ return sign ? -res : res;
+}
+
+static F16Dot16 fixedDiv(F16Dot16 a, F16Dot16 b)
+{
+ unsigned int f, r;
+ F16Dot16 res;
+ int sign;
+
+ sign = (a & 0x80000000) ^ (b & 0x80000000);
+ if (a < 0) a = -a;
+ if (b < 0) b = -b;
+
+ f = a / b;
+ r = a % b;
+
+ /* if (f > 0x7FFFF) assert(!"fixedDiv: F16Dot16 overflow"); */
+
+ while (r > 0xFFFF) {
+ r >>= 1;
+ b >>= 1;
+ }
+
+ res = (f << 16) + (r << 16) / b;
+
+ return sign ? -res : res;
+}
+
+/*- returns a * b / c -*/
+/* XXX provide a real implementation that preserves accuracy */
+static F16Dot16 fixedMulDiv(F16Dot16 a, F16Dot16 b, F16Dot16 c)
+{
+ F16Dot16 res;
+
+ res = fixedMul(a, b);
+ return fixedDiv(res, c);
+}
+
+/*- Translate units from TT to PS (standard 1/1000) -*/
+static int XUnits(int unitsPerEm, int n)
+{
+ return (n * 1000) / unitsPerEm;
+}
+
+static const sal_uInt8* getTable( TrueTypeFont const *ttf, sal_uInt32 ord)
+{
+ return ttf->tables[ord];
+}
+
+static sal_uInt32 getTableSize(TrueTypeFont const *ttf, sal_uInt32 ord)
+{
+ return ttf->tlens[ord];
+}
+
+static char toHex(sal_uInt8 nIndex)
+{
+ /* Hex Formatter functions */
+ static const char HexChars[] = "0123456789ABCDEF";
+ assert(nIndex < SAL_N_ELEMENTS(HexChars));
+ return HexChars[nIndex];
+}
+
+static HexFmt *HexFmtNew(FILE *outf)
+{
+ HexFmt* res = static_cast<HexFmt*>(smalloc(sizeof(HexFmt)));
+ res->bufpos = res->total = 0;
+ res->o = outf;
+ return res;
+}
+
+static bool HexFmtFlush(HexFmt *_this)
+{
+ bool bRet = true;
+ if (_this->bufpos) {
+ size_t nWritten = fwrite(_this->buffer, 1, _this->bufpos, _this->o);
+ bRet = nWritten == _this->bufpos;
+ _this->bufpos = 0;
+ }
+ return bRet;
+}
+
+static void HexFmtOpenString(HexFmt *_this)
+{
+ fputs("<\n", _this->o);
+}
+
+static void HexFmtCloseString(HexFmt *_this)
+{
+ HexFmtFlush(_this);
+ fputs("00\n>\n", _this->o);
+}
+
+static void HexFmtDispose(HexFmt *_this)
+{
+ HexFmtFlush(_this);
+ free(_this);
+}
+
+static void HexFmtBlockWrite(HexFmt *_this, const void *ptr, sal_uInt32 size)
+{
+ sal_uInt8 Ch;
+ sal_uInt32 i;
+
+ if (_this->total + size > 65534) {
+ HexFmtFlush(_this);
+ HexFmtCloseString(_this);
+ _this->total = 0;
+ HexFmtOpenString(_this);
+ }
+ for (i=0; i<size; i++) {
+ Ch = static_cast<sal_uInt8 const *>(ptr)[i];
+ _this->buffer[_this->bufpos++] = toHex(Ch >> 4);
+ _this->buffer[_this->bufpos++] = toHex(Ch & 0xF);
+ if (_this->bufpos == HFORMAT_LINELEN) {
+ HexFmtFlush(_this);
+ fputc('\n', _this->o);
+ }
+
+ }
+ _this->total += size;
+}
+
+/* Outline Extraction functions */
+
+/* fills the aw and lsb entries of the TTGlyphMetrics structure from hmtx table -*/
+static void GetMetrics(TrueTypeFont const *ttf, sal_uInt32 glyphID, TTGlyphMetrics *metrics)
+{
+ const sal_uInt8* table = getTable( ttf, O_hmtx );
+
+ metrics->aw = metrics->lsb = metrics->ah = 0;
+ if (!table || !ttf->numberOfHMetrics) return;
+
+ if (glyphID < ttf->numberOfHMetrics) {
+ metrics->aw = GetUInt16(table, 4 * glyphID);
+ metrics->lsb = GetInt16(table, 4 * glyphID + 2);
+ } else {
+ metrics->aw = GetUInt16(table, 4 * (ttf->numberOfHMetrics - 1));
+ metrics->lsb = GetInt16(table + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2);
+ }
+
+ table = getTable(ttf, O_vmtx);
+ if( !table || !ttf->numOfLongVerMetrics )
+ return;
+
+ if (glyphID < ttf->numOfLongVerMetrics) {
+ metrics->ah = GetUInt16(table, 4 * glyphID);
+ } else {
+ metrics->ah = GetUInt16(table, 4 * (ttf->numOfLongVerMetrics - 1));
+ }
+}
+
+static int GetTTGlyphOutline(TrueTypeFont *, sal_uInt32 , ControlPoint **, TTGlyphMetrics *, std::vector< sal_uInt32 >* );
+
+/* returns the number of control points, allocates the pointArray */
+static int GetSimpleTTOutline(TrueTypeFont const *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics)
+{
+ const sal_uInt8* table = getTable(ttf, O_glyf);
+ const sal_uInt32 nTableSize = getTableSize(ttf, O_glyf);
+ sal_uInt8 flag, n;
+ int i, j, z;
+
+ *pointArray = nullptr;
+
+ /* printf("GetSimpleTTOutline(%d)\n", glyphID); */
+
+ if( glyphID >= ttf->nglyphs ) /*- glyph is not present in the font */
+ return 0;
+ const sal_uInt8* ptr = table + ttf->goffsets[glyphID];
+ const sal_Int16 numberOfContours = GetInt16(ptr, GLYF_numberOfContours_offset);
+ if( numberOfContours <= 0 ) /*- glyph is not simple */
+ return 0;
+
+ if (metrics) { /*- GetCompoundTTOutline() calls this function with NULL metrics -*/
+ metrics->xMin = GetInt16(ptr, GLYF_xMin_offset);
+ metrics->yMin = GetInt16(ptr, GLYF_yMin_offset);
+ metrics->xMax = GetInt16(ptr, GLYF_xMax_offset);
+ metrics->yMax = GetInt16(ptr, GLYF_yMax_offset);
+ GetMetrics(ttf, glyphID, metrics);
+ }
+
+ /* determine the last point and be extra safe about it. But probably this code is not needed */
+ sal_uInt16 lastPoint=0;
+ const sal_Int32 nMaxContours = (nTableSize - 10)/2;
+ if (numberOfContours > nMaxContours)
+ return 0;
+ for (i=0; i<numberOfContours; i++)
+ {
+ const sal_uInt16 t = GetUInt16(ptr, 10+i*2);
+ if (t > lastPoint)
+ lastPoint = t;
+ }
+
+ sal_uInt16 instLen = GetUInt16(ptr, 10 + numberOfContours*2);
+ sal_uInt32 nOffset = 10 + 2 * numberOfContours + 2 + instLen;
+ if (nOffset > nTableSize)
+ return 0;
+ const sal_uInt8* p = ptr + nOffset;
+
+ const sal_uInt32 nBytesRemaining = nTableSize - nOffset;
+ const sal_uInt16 palen = lastPoint+1;
+
+ //at a minimum its one byte per entry
+ if (palen > nBytesRemaining || lastPoint > nBytesRemaining-1)
+ {
+ SAL_WARN("vcl.fonts", "Font " << OUString::createFromAscii(ttf->fname) <<
+ "claimed a palen of "
+ << palen << " but max bytes remaining is " << nBytesRemaining);
+ return 0;
+ }
+
+ ControlPoint* pa = static_cast<ControlPoint*>(calloc(palen, sizeof(ControlPoint)));
+
+ i = 0;
+ while (i <= lastPoint) {
+ flag = *p++;
+ pa[i++].flags = static_cast<sal_uInt32>(flag);
+ if (flag & 8) { /*- repeat flag */
+ n = *p++;
+ // coverity[tainted_data] - i > lastPoint extra checks the n loop bound
+ for (j=0; j<n; j++) {
+ if (i > lastPoint) { /*- if the font is really broken */
+ free(pa);
+ return 0;
+ }
+ pa[i++].flags = flag;
+ }
+ }
+ }
+
+ /*- Process the X coordinate */
+ z = 0;
+ for (i = 0; i <= lastPoint; i++) {
+ if (pa[i].flags & 0x02) {
+ if (pa[i].flags & 0x10) {
+ z += static_cast<int>(*p++);
+ } else {
+ z -= static_cast<int>(*p++);
+ }
+ } else if ( !(pa[i].flags & 0x10)) {
+ z += GetInt16(p, 0);
+ p += 2;
+ }
+ pa[i].x = static_cast<sal_Int16>(z);
+ }
+
+ /*- Process the Y coordinate */
+ z = 0;
+ for (i = 0; i <= lastPoint; i++) {
+ if (pa[i].flags & 0x04) {
+ if (pa[i].flags & 0x20) {
+ z += *p++;
+ } else {
+ z -= *p++;
+ }
+ } else if ( !(pa[i].flags & 0x20)) {
+ z += GetInt16(p, 0);
+ p += 2;
+ }
+ pa[i].y = static_cast<sal_Int16>(z);
+ }
+
+ for (i=0; i<numberOfContours; i++) {
+ sal_uInt16 offset = GetUInt16(ptr, 10 + i * 2);
+ SAL_WARN_IF(offset >= palen, "vcl.fonts", "Font " << OUString::createFromAscii(ttf->fname) <<
+ " contour " << i << " claimed an illegal offset of "
+ << offset << " but max offset is " << palen-1);
+ if (offset >= palen)
+ continue;
+ pa[offset].flags |= 0x00008000; /*- set the end contour flag */
+ }
+
+ *pointArray = pa;
+ return lastPoint + 1;
+}
+
+static F16Dot16 fromF2Dot14(sal_Int16 n)
+{
+ // Avoid undefined shift of negative values prior to C++2a:
+ return sal_uInt32(n) << 2;
+}
+
+static int GetCompoundTTOutline(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics, std::vector< sal_uInt32 >& glyphlist)
+{
+ sal_uInt16 flags, index;
+ sal_Int16 e, f;
+ const sal_uInt8* table = getTable( ttf, O_glyf );
+ std::vector<ControlPoint> myPoints;
+ ControlPoint *nextComponent, *pa;
+ int i, np;
+ F16Dot16 a = 0x10000, b = 0, c = 0, d = 0x10000, m, n, abs1, abs2, abs3;
+
+ *pointArray = nullptr;
+ /* printf("GetCompoundTTOutline(%d)\n", glyphID); */
+
+ if (glyphID >= ttf->nglyphs) /*- incorrect glyphID */
+ return 0;
+
+ const sal_uInt8* ptr = table + ttf->goffsets[glyphID];
+ if (GetInt16(ptr, GLYF_numberOfContours_offset) != -1) /* number of contours - glyph is not compound */
+ return 0;
+
+ if (metrics) {
+ metrics->xMin = GetInt16(ptr, GLYF_xMin_offset);
+ metrics->yMin = GetInt16(ptr, GLYF_yMin_offset);
+ metrics->xMax = GetInt16(ptr, GLYF_xMax_offset);
+ metrics->yMax = GetInt16(ptr, GLYF_yMax_offset);
+ GetMetrics(ttf, glyphID, metrics);
+ }
+
+ ptr += 10;
+
+ do {
+ flags = GetUInt16(ptr, 0);
+ /* printf("flags: 0x%X\n", flags); */
+ index = GetUInt16(ptr, 2);
+ ptr += 4;
+
+ if( std::find( glyphlist.begin(), glyphlist.end(), index ) != glyphlist.end() )
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_INFO("vcl.fonts", "Endless loop found in a compound glyph.");
+
+ std::ostringstream oss;
+ oss << index << " -> [";
+ for( const auto& rGlyph : glyphlist )
+ {
+ oss << (int) rGlyph << " ";
+ }
+ oss << "]";
+ SAL_INFO("vcl.fonts", oss.str());
+ /**/
+#endif
+ }
+
+ glyphlist.push_back( index );
+
+ if ((np = GetTTGlyphOutline(ttf, index, &nextComponent, nullptr, &glyphlist)) == 0)
+ {
+ /* XXX that probably indicates a corrupted font */
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "An empty compound!");
+ /* assert(!"An empty compound"); */
+#endif
+ }
+
+ if( ! glyphlist.empty() )
+ glyphlist.pop_back();
+
+ if ((flags & USE_MY_METRICS) && metrics)
+ GetMetrics(ttf, index, metrics);
+
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ e = GetInt16(ptr, 0);
+ f = GetInt16(ptr, 2);
+ /* printf("ARG_1_AND_2_ARE_WORDS: %d %d\n", e & 0xFFFF, f & 0xFFFF); */
+ ptr += 4;
+ } else {
+ if (flags & ARGS_ARE_XY_VALUES) { /* args are signed */
+ e = static_cast<sal_Int8>(*ptr++);
+ f = static_cast<sal_Int8>(*ptr++);
+ /* printf("ARGS_ARE_XY_VALUES: %d %d\n", e & 0xFF, f & 0xFF); */
+ } else { /* args are unsigned */
+ /* printf("!ARGS_ARE_XY_VALUES\n"); */
+ e = *ptr++;
+ f = *ptr++;
+ }
+
+ }
+
+ a = d = 0x10000;
+ b = c = 0;
+
+ if (flags & WE_HAVE_A_SCALE) {
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ d = a;
+ ptr += 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ d = fromF2Dot14(GetInt16(ptr, 2));
+ ptr += 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ b = fromF2Dot14(GetInt16(ptr, 2));
+ c = fromF2Dot14(GetInt16(ptr, 4));
+ d = fromF2Dot14(GetInt16(ptr, 6));
+ ptr += 8;
+ }
+
+ abs1 = (a < 0) ? -a : a;
+ abs2 = (b < 0) ? -b : b;
+ m = std::max(abs1, abs2);
+ abs3 = abs1 - abs2;
+ if (abs3 < 0) abs3 = -abs3;
+ if (abs3 <= 33) m *= 2;
+
+ abs1 = (c < 0) ? -c : c;
+ abs2 = (d < 0) ? -d : d;
+ n = std::max(abs1, abs2);
+ abs3 = abs1 - abs2;
+ if (abs3 < 0) abs3 = -abs3;
+ if (abs3 <= 33) n *= 2;
+
+ SAL_WARN_IF(np && !m, "vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fname) <<
+ ": divide by zero");
+
+ if (m != 0) {
+ for (i=0; i<np; i++) {
+ F16Dot16 t;
+ ControlPoint cp;
+ cp.flags = nextComponent[i].flags;
+ const sal_uInt16 x = nextComponent[i].x;
+ const sal_uInt16 y = nextComponent[i].y;
+ t = fixedMulDiv(a, x << 16, m) + fixedMulDiv(c, y << 16, m) + sal_Int32(sal_uInt16(e) << 16);
+ cp.x = static_cast<sal_Int16>(fixedMul(t, m) >> 16);
+ t = fixedMulDiv(b, x << 16, n) + fixedMulDiv(d, y << 16, n) + sal_Int32(sal_uInt16(f) << 16);
+ cp.y = static_cast<sal_Int16>(fixedMul(t, n) >> 16);
+
+ myPoints.push_back( cp );
+ }
+ }
+
+ free(nextComponent);
+
+ } while (flags & MORE_COMPONENTS);
+
+ // #i123417# some fonts like IFAOGrec have no outline points in some compound glyphs
+ // so this unlikely but possible scenario should be handled gracefully
+ if( myPoints.empty() )
+ return 0;
+
+ np = myPoints.size();
+ if (np > 0)
+ {
+ pa = static_cast<ControlPoint*>(calloc(np, sizeof(ControlPoint)));
+ assert(pa != nullptr);
+
+ memcpy(pa, myPoints.data(), np * sizeof(ControlPoint));
+
+ *pointArray = pa;
+ }
+ return np;
+}
+
+/* NOTE: GetTTGlyphOutline() returns -1 if the glyphID is incorrect,
+ * but Get{Simple|Compound}GlyphOutline returns 0 in such a case.
+ *
+ * NOTE: glyphlist is the stack of glyphs traversed while constructing
+ * a composite glyph. This is a safeguard against endless recursion
+ * in corrupted fonts.
+ */
+static int GetTTGlyphOutline(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics, std::vector< sal_uInt32 >* glyphlist)
+{
+ const sal_uInt8 *table = getTable( ttf, O_glyf );
+ sal_Int16 numberOfContours;
+ int res;
+ *pointArray = nullptr;
+
+ if (metrics) {
+ memset(metrics, 0, sizeof(TTGlyphMetrics)); /*- metrics is initialized to all zeroes */
+ }
+
+ if (glyphID >= ttf->nglyphs) return -1; /**/
+
+ const sal_uInt8* ptr = table + ttf->goffsets[glyphID];
+ int length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID];
+
+ if (length == 0) { /*- empty glyphs still have hmtx and vmtx metrics values */
+ if (metrics) GetMetrics(ttf, glyphID, metrics);
+ return 0;
+ }
+
+ numberOfContours = GetInt16(ptr, 0);
+
+ if (numberOfContours >= 0)
+ {
+ res=GetSimpleTTOutline(ttf, glyphID, pointArray, metrics);
+ }
+ else
+ {
+ std::vector< sal_uInt32 > aPrivList;
+ aPrivList.push_back( glyphID );
+ res = GetCompoundTTOutline(ttf, glyphID, pointArray, metrics, glyphlist ? *glyphlist : aPrivList );
+ }
+
+ return res;
+}
+
+/*- returns the number of items in the path -*/
+
+static int BSplineToPSPath(ControlPoint const *srcA, int srcCount, PSPathElement **path)
+{
+ std::vector< PSPathElement > aPathList;
+ int nPathCount = 0;
+ PSPathElement p( PS_NOOP );
+
+ int x0 = 0, y0 = 0, x1 = 0, y1 = 0, x2, y2, curx, cury;
+ bool lastOff = false; /*- last point was off-contour */
+ int scflag = 1; /*- start contour flag */
+ bool ecflag = false; /*- end contour flag */
+ int cp = 0; /*- current point */
+ int StartContour = 0, EndContour = 1;
+
+ *path = nullptr;
+
+ /* if (srcCount > 0) for(;;) */
+ while (srcCount > 0) { /*- srcCount does not get changed inside the loop. */
+ if (scflag) {
+ int l = cp;
+ StartContour = cp;
+ while (!(srcA[l].flags & 0x8000)) l++;
+ EndContour = l;
+ if (StartContour == EndContour) {
+ if (cp + 1 < srcCount) {
+ cp++;
+ continue;
+ } else {
+ break;
+ }
+ }
+ p = PSPathElement(PS_MOVETO);
+ if (!(srcA[cp].flags & 1)) {
+ if (!(srcA[EndContour].flags & 1)) {
+ p.x1 = x0 = (srcA[cp].x + srcA[EndContour].x + 1) / 2;
+ p.y1 = y0 = (srcA[cp].y + srcA[EndContour].y + 1) / 2;
+ } else {
+ p.x1 = x0 = srcA[EndContour].x;
+ p.y1 = y0 = srcA[EndContour].y;
+ }
+ } else {
+ p.x1 = x0 = srcA[cp].x;
+ p.y1 = y0 = srcA[cp].y;
+ cp++;
+ }
+ aPathList.push_back( p );
+ lastOff = false;
+ scflag = 0;
+ }
+
+ curx = srcA[cp].x;
+ cury = srcA[cp].y;
+
+ if (srcA[cp].flags & 1)
+ {
+ if (lastOff)
+ {
+ p = PSPathElement(PS_CURVETO);
+ p.x1 = x0 + (2 * (x1 - x0) + 1) / 3;
+ p.y1 = y0 + (2 * (y1 - y0) + 1) / 3;
+ p.x2 = x1 + (curx - x1 + 1) / 3;
+ p.y2 = y1 + (cury - y1 + 1) / 3;
+ p.x3 = curx;
+ p.y3 = cury;
+ aPathList.push_back( p );
+ }
+ else
+ {
+ if (!(x0 == curx && y0 == cury))
+ { /* eliminate empty lines */
+ p = PSPathElement(PS_LINETO);
+ p.x1 = curx;
+ p.y1 = cury;
+ aPathList.push_back( p );
+ }
+ }
+ x0 = curx; y0 = cury; lastOff = false;
+ }
+ else
+ {
+ if (lastOff)
+ {
+ x2 = (x1 + curx + 1) / 2;
+ y2 = (y1 + cury + 1) / 2;
+ p = PSPathElement(PS_CURVETO);
+ p.x1 = x0 + (2 * (x1 - x0) + 1) / 3;
+ p.y1 = y0 + (2 * (y1 - y0) + 1) / 3;
+ p.x2 = x1 + (x2 - x1 + 1) / 3;
+ p.y2 = y1 + (y2 - y1 + 1) / 3;
+ p.x3 = x2;
+ p.y3 = y2;
+ aPathList.push_back( p );
+ x0 = x2; y0 = y2;
+ x1 = curx; y1 = cury;
+ } else {
+ x1 = curx; y1 = cury;
+ }
+ lastOff = true;
+ }
+
+ if (ecflag) {
+ aPathList.emplace_back(PS_CLOSEPATH );
+ scflag = 1;
+ ecflag = false;
+ cp = EndContour + 1;
+ if (cp >= srcCount) break;
+ continue;
+ }
+
+ if (cp == EndContour) {
+ cp = StartContour;
+ ecflag = true;
+ } else {
+ cp++;
+ }
+ }
+
+ if( (nPathCount = static_cast<int>(aPathList.size())) > 0)
+ {
+ *path = static_cast<PSPathElement*>(calloc(nPathCount, sizeof(PSPathElement)));
+ assert(*path != nullptr);
+ memcpy( *path, aPathList.data(), nPathCount * sizeof(PSPathElement) );
+ }
+
+ return nPathCount;
+}
+
+/*- Extracts a string from the name table and allocates memory for it -*/
+
+static char *nameExtract( const sal_uInt8* name, int nTableSize, int n, int dbFlag, sal_Unicode** ucs2result )
+{
+ char *res;
+ const sal_uInt8* ptr = name + GetUInt16(name, 4) + GetUInt16(name + 6, 12 * n + 10);
+ int len = GetUInt16(name+6, 12 * n + 8);
+
+ // sanity check
+ const sal_uInt8* end_table = name+nTableSize;
+ const int available_space = ptr > end_table ? 0 : (end_table - ptr);
+ if( (len <= 0) || len > available_space)
+ {
+ if( ucs2result )
+ *ucs2result = nullptr;
+ return nullptr;
+ }
+
+ if( ucs2result )
+ *ucs2result = nullptr;
+ if (dbFlag) {
+ res = static_cast<char*>(malloc(1 + len/2));
+ assert(res != nullptr);
+ for (int i = 0; i < len/2; i++)
+ res[i] = *(ptr + i * 2 + 1);
+ res[len/2] = 0;
+ if( ucs2result )
+ {
+ *ucs2result = static_cast<sal_Unicode*>(malloc( len+2 ));
+ for (int i = 0; i < len/2; i++ )
+ (*ucs2result)[i] = GetUInt16( ptr, 2*i );
+ (*ucs2result)[len/2] = 0;
+ }
+ } else {
+ res = static_cast<char*>(malloc(1 + len));
+ assert(res != nullptr);
+ memcpy(res, ptr, len);
+ res[len] = 0;
+ }
+
+ return res;
+}
+
+static int findname( const sal_uInt8 *name, sal_uInt16 n, sal_uInt16 platformID,
+ sal_uInt16 encodingID, sal_uInt16 languageID, sal_uInt16 nameID )
+{
+ if (n == 0) return -1;
+
+ int l = 0, r = n-1;
+ sal_uInt32 t1, t2;
+ sal_uInt32 m1, m2;
+
+ m1 = (platformID << 16) | encodingID;
+ m2 = (languageID << 16) | nameID;
+
+ do {
+ const int i = (l + r) >> 1;
+ t1 = GetUInt32(name + 6, i * 12 + 0);
+ t2 = GetUInt32(name + 6, i * 12 + 4);
+
+ if (! ((m1 < t1) || ((m1 == t1) && (m2 < t2)))) l = i + 1;
+ if (! ((m1 > t1) || ((m1 == t1) && (m2 > t2)))) r = i - 1;
+ } while (l <= r);
+
+ if (l - r == 2) {
+ return l - 1;
+ }
+
+ return -1;
+}
+
+/* XXX marlett.ttf uses (3, 0, 1033) instead of (3, 1, 1033) and does not have any Apple tables.
+ * Fix: if (3, 1, 1033) is not found - need to check for (3, 0, 1033)
+ *
+ * /d/fonts/ttzh_tw/Big5/Hanyi/ma6b5p uses (1, 0, 19) for English strings, instead of (1, 0, 0)
+ * and does not have (3, 1, 1033)
+ * Fix: if (1, 0, 0) and (3, 1, 1033) are not found need to look for (1, 0, *) - that will
+ * require a change in algorithm
+ *
+ * /d/fonts/fdltest/Korean/h2drrm has unsorted names and an unknown (to me) Mac LanguageID,
+ * but (1, 0, 1042) strings usable
+ * Fix: change algorithm, and use (1, 0, *) if both standard Mac and MS strings are not found
+ */
+
+static void GetNames(TrueTypeFont *t)
+{
+ const sal_uInt8* table = getTable( t, O_name );
+ const sal_uInt32 nTableSize = getTableSize(t, O_name);
+
+ if (nTableSize < 6)
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "O_name table too small.");
+#endif
+ return;
+ }
+
+ sal_uInt16 n = GetUInt16(table, 2);
+
+ /* simple sanity check for name table entry count */
+ const size_t nMinRecordSize = 12;
+ const size_t nSpaceAvailable = nTableSize - 6;
+ const size_t nMaxRecords = nSpaceAvailable/nMinRecordSize;
+ if (n >= nMaxRecords)
+ n = 0;
+
+ int i, r;
+ bool bPSNameOK = true;
+
+ /* PostScript name: preferred Microsoft */
+ t->psname = nullptr;
+ if ((r = findname(table, n, 3, 1, 0x0409, 6)) != -1)
+ t->psname = nameExtract(table, nTableSize, r, 1, nullptr);
+ if ( ! t->psname && (r = findname(table, n, 1, 0, 0, 6)) != -1)
+ t->psname = nameExtract(table, nTableSize, r, 0, nullptr);
+ if ( ! t->psname && (r = findname(table, n, 3, 0, 0x0409, 6)) != -1)
+ {
+ // some symbol fonts like Marlett have a 3,0 name!
+ t->psname = nameExtract(table, nTableSize, r, 1, nullptr);
+ }
+ // for embedded font in Ghostscript PDFs
+ if ( ! t->psname && (r = findname(table, n, 2, 2, 0, 6)) != -1)
+ {
+ t->psname = nameExtract(table, nTableSize, r, 0, nullptr);
+ }
+ if ( ! t->psname )
+ {
+ if ( t->fname )
+ {
+ char* pReverse = t->fname + strlen(t->fname);
+ /* take only last token of filename */
+ while(pReverse != t->fname && *pReverse != '/') pReverse--;
+ if(*pReverse == '/') pReverse++;
+ t->psname = strdup(pReverse);
+ assert(t->psname != nullptr);
+ for (i=strlen(t->psname) - 1; i > 0; i--)
+ {
+ /*- Remove the suffix -*/
+ if (t->psname[i] == '.' ) {
+ t->psname[i] = 0;
+ break;
+ }
+ }
+ }
+ else
+ t->psname = strdup( "Unknown" );
+ }
+
+ /* Font family and subfamily names: preferred Apple */
+ t->family = nullptr;
+ if ((r = findname(table, n, 0, 0, 0, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( ! t->family && (r = findname(table, n, 3, 1, 0x0409, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( ! t->family && (r = findname(table, n, 1, 0, 0, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 0, nullptr);
+ if ( ! t->family && (r = findname(table, n, 3, 1, 0x0411, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( ! t->family && (r = findname(table, n, 3, 0, 0x0409, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( ! t->family )
+ {
+ t->family = strdup(t->psname);
+ assert(t->family != nullptr);
+ }
+
+ t->subfamily = nullptr;
+ t->usubfamily = nullptr;
+ if ((r = findname(table, n, 1, 0, 0, 2)) != -1)
+ t->subfamily = nameExtract(table, nTableSize, r, 0, &t->usubfamily);
+ if ( ! t->subfamily && (r = findname(table, n, 3, 1, 0x0409, 2)) != -1)
+ t->subfamily = nameExtract(table, nTableSize, r, 1, &t->usubfamily);
+ if ( ! t->subfamily )
+ {
+ t->subfamily = strdup("");
+ }
+
+ /* #i60349# sanity check psname
+ * psname practically has to be 7bit ASCII and should not contain spaces
+ * there is a class of broken fonts which do not fulfill that at all, so let's try
+ * if the family name is 7bit ASCII and take it instead if so
+ */
+ /* check psname */
+ for( i = 0; t->psname[i] != 0 && bPSNameOK; i++ )
+ if( t->psname[ i ] < 33 || (t->psname[ i ] & 0x80) )
+ bPSNameOK = false;
+ if( !bPSNameOK )
+ {
+ /* check if family is a suitable replacement */
+ if( t->ufamily && t->family )
+ {
+ bool bReplace = true;
+
+ for( i = 0; t->ufamily[ i ] != 0 && bReplace; i++ )
+ if( t->ufamily[ i ] < 33 || t->ufamily[ i ] > 127 )
+ bReplace = false;
+ if( bReplace )
+ {
+ free( t->psname );
+ t->psname = strdup( t->family );
+ }
+ }
+ }
+}
+
+namespace {
+
+enum cmapType {
+ CMAP_NOT_USABLE = -1,
+ CMAP_MS_Symbol = 10,
+ CMAP_MS_Unicode = 11,
+ CMAP_MS_ShiftJIS = 12,
+ CMAP_MS_PRC = 13,
+ CMAP_MS_Big5 = 14,
+ CMAP_MS_Wansung = 15,
+ CMAP_MS_Johab = 16
+};
+
+}
+
+#define MISSING_GLYPH_INDEX 0
+
+static sal_uInt32 getGlyph0(const sal_uInt8* cmap, sal_uInt32, sal_uInt32 c) {
+ if (c <= 255) {
+ return *(cmap + 6 + c);
+ } else {
+ return MISSING_GLYPH_INDEX;
+ }
+}
+
+namespace {
+
+struct subHeader2 {
+ sal_uInt16 firstCode;
+ sal_uInt16 entryCount;
+ sal_uInt16 idDelta;
+ sal_uInt16 idRangeOffset;
+};
+
+}
+
+static sal_uInt32 getGlyph2(const sal_uInt8 *cmap, const sal_uInt32 nMaxCmapSize, sal_uInt32 c) {
+ sal_uInt16 const *CMAP2 = reinterpret_cast<sal_uInt16 const *>(cmap);
+ sal_uInt8 theHighByte;
+
+ sal_uInt8 theLowByte;
+ subHeader2 const * subHeader2s;
+ sal_uInt16 const * subHeader2Keys;
+ sal_uInt16 firstCode;
+ int k = -1;
+ sal_uInt32 ToReturn;
+
+ theHighByte = static_cast<sal_uInt8>((c >> 8) & 0x00ff);
+ theLowByte = static_cast<sal_uInt8>(c & 0x00ff);
+ subHeader2Keys = CMAP2 + 3;
+ subHeader2s = reinterpret_cast<subHeader2 const *>(subHeader2Keys + 256);
+ if(reinterpret_cast<sal_uInt8 const *>(&subHeader2Keys[theHighByte]) - cmap < int(nMaxCmapSize - 2))
+ {
+ k = Int16FromMOTA(subHeader2Keys[theHighByte]) / 8;
+ // check if the subheader record fits into available space
+ if(reinterpret_cast<sal_uInt8 const *>(&subHeader2s[k]) - cmap >= int(nMaxCmapSize - sizeof(subHeader2)))
+ k = -1;
+ }
+
+ if(k == 0) {
+ firstCode = Int16FromMOTA(subHeader2s[0].firstCode);
+ if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) {
+ sal_uInt16 const * pGlyph = (&(subHeader2s[0].idRangeOffset))
+ + (Int16FromMOTA(subHeader2s[0].idRangeOffset)/2) /* + offset */
+ + theLowByte /* + to_look */
+ - firstCode
+ ;
+ if (reinterpret_cast<sal_uInt8 const *>(pGlyph) - cmap < int(nMaxCmapSize) - 4)
+ return *pGlyph;
+ else
+ return MISSING_GLYPH_INDEX;
+ } else {
+ return MISSING_GLYPH_INDEX;
+ }
+ } else if (k > 0) {
+ firstCode = Int16FromMOTA(subHeader2s[k].firstCode);
+ if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) {
+ ToReturn = *((&(subHeader2s[k].idRangeOffset))
+ + (Int16FromMOTA(subHeader2s[k].idRangeOffset)/2)
+ + theLowByte - firstCode);
+ if(ToReturn == 0) {
+ return MISSING_GLYPH_INDEX;
+ } else {
+ ToReturn += Int16FromMOTA(subHeader2s[k].idDelta);
+ return (ToReturn & 0xFFFF);
+ }
+ } else {
+ return MISSING_GLYPH_INDEX;
+ }
+ } else {
+ return MISSING_GLYPH_INDEX;
+ }
+}
+
+static sal_uInt32 getGlyph6(const sal_uInt8 *cmap, sal_uInt32, sal_uInt32 c) {
+ sal_uInt16 firstCode, lastCode, count;
+ sal_uInt16 const *CMAP6 = reinterpret_cast<sal_uInt16 const *>(cmap);
+
+ firstCode = Int16FromMOTA(*(CMAP6 + 3));
+ count = Int16FromMOTA(*(CMAP6 + 4));
+ lastCode = firstCode + count - 1;
+ if (c < firstCode || c > lastCode) {
+ return MISSING_GLYPH_INDEX;
+ } else {
+ return *((CMAP6 + 5)/*glyphIdArray*/ + (c - firstCode));
+ }
+}
+
+static sal_uInt16 GEbinsearch(sal_uInt16 const *ar, sal_uInt16 length, sal_uInt16 toSearch) {
+ signed int low, high, lastfound = 0xffff;
+ sal_uInt16 res;
+ if(length == sal_uInt16(0) || length == sal_uInt16(0xFFFF)) {
+ return sal_uInt16(0xFFFF);
+ }
+ low = 0;
+ high = length - 1;
+ while(high >= low) {
+ int mid = (high + low)/2;
+ res = Int16FromMOTA(*(ar+mid));
+ if(res >= toSearch) {
+ lastfound = mid;
+ high = --mid;
+ } else {
+ low = ++mid;
+ }
+ }
+ return static_cast<sal_uInt16>(lastfound);
+}
+
+static sal_uInt32 getGlyph4(const sal_uInt8 *cmap, const sal_uInt32 nMaxCmapSize, sal_uInt32 c) {
+ sal_uInt16 i;
+ int ToReturn;
+ sal_uInt16 segCount;
+ sal_uInt16 const * startCode;
+ sal_uInt16 const * endCode;
+ sal_uInt16 const * idDelta;
+ /* sal_uInt16 * glyphIdArray; */
+ sal_uInt16 const * idRangeOffset;
+ /*sal_uInt16 * glyphIndexArray;*/
+ sal_uInt16 const *CMAP4 = reinterpret_cast<sal_uInt16 const *>(cmap);
+ /* sal_uInt16 GEbinsearch(sal_uInt16 *ar, sal_uInt16 length, sal_uInt16 toSearch); */
+
+ segCount = Int16FromMOTA(*(CMAP4 + 3))/2;
+ endCode = CMAP4 + 7;
+ i = GEbinsearch(endCode, segCount, static_cast<sal_uInt16>(c));
+
+ if (i == sal_uInt16(0xFFFF)) {
+ return MISSING_GLYPH_INDEX;
+ }
+ startCode = endCode + segCount + 1;
+
+ if((reinterpret_cast<sal_uInt8 const *>(&startCode[i]) - cmap >= int(nMaxCmapSize - 2)) || Int16FromMOTA(startCode[i]) > c) {
+ return MISSING_GLYPH_INDEX;
+ }
+ idDelta = startCode + segCount;
+ idRangeOffset = idDelta + segCount;
+ /*glyphIndexArray = idRangeOffset + segCount;*/
+
+ if((reinterpret_cast<sal_uInt8 const *>(&idRangeOffset[i]) - cmap < int(nMaxCmapSize - 2)) && Int16FromMOTA(idRangeOffset[i]) != 0) {
+ sal_uInt16 const * pGlyphOffset = &(idRangeOffset[i]) + (Int16FromMOTA(idRangeOffset[i])/2 + (c - Int16FromMOTA(startCode[i])));
+ if(reinterpret_cast<sal_uInt8 const *>(pGlyphOffset) - cmap >= int(nMaxCmapSize - 2))
+ return MISSING_GLYPH_INDEX;
+ c = Int16FromMOTA(*pGlyphOffset);
+ }
+
+ ToReturn = (Int16FromMOTA(idDelta[i]) + c) & 0xFFFF;
+ return ToReturn;
+}
+
+static sal_uInt32 getGlyph12(const sal_uInt8 *pCmap, sal_uInt32, sal_uInt32 cChar) {
+ const sal_uInt32* pCMAP12 = reinterpret_cast<const sal_uInt32*>(pCmap);
+ int nLength = Int32FromMOTA( pCMAP12[1] );
+ int nGroups = Int32FromMOTA( pCMAP12[3] );
+ int nLower = 0;
+ int nUpper = nGroups;
+
+ if( nUpper > (nLength-16)/12 )
+ nUpper = (nLength-16)/12;
+
+ /* binary search in "segmented coverage" subtable */
+ while( nLower < nUpper ) {
+ int nIndex = (nLower + nUpper) / 2;
+ const sal_uInt32* pEntry = &pCMAP12[ 4 + 3*nIndex ];
+ sal_uInt32 cStart = Int32FromMOTA( pEntry[0] );
+ sal_uInt32 cLast = Int32FromMOTA( pEntry[1] );
+ if( cChar < cStart )
+ nUpper = nIndex;
+ else if( cChar > cLast )
+ nLower = nIndex + 1;
+ else { /* found matching entry! */
+ sal_uInt32 nGlyph = Int32FromMOTA( pEntry[2] );
+ nGlyph += cChar - cStart;
+ return nGlyph;
+ }
+ }
+
+ return MISSING_GLYPH_INDEX;
+}
+
+static void FindCmap(TrueTypeFont *ttf)
+{
+ const sal_uInt8* table = getTable(ttf, O_cmap);
+ sal_uInt32 table_size = getTableSize(ttf, O_cmap);
+ if (table_size < 4)
+ {
+ SAL_WARN("vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fname) <<
+ "cmap table size too short");
+ return;
+ }
+ sal_uInt16 ncmaps = GetUInt16(table, 2);
+ sal_uInt32 AppleUni = 0; // Apple Unicode
+ sal_uInt32 ThreeZero = 0; /* MS Symbol */
+ sal_uInt32 ThreeOne = 0; /* MS UCS-2 */
+ sal_uInt32 ThreeTwo = 0; /* MS ShiftJIS */
+ sal_uInt32 ThreeThree = 0; /* MS PRC */
+ sal_uInt32 ThreeFour = 0; /* MS Big5 */
+ sal_uInt32 ThreeFive = 0; /* MS Wansung */
+ sal_uInt32 ThreeSix = 0; /* MS Johab */
+
+ const sal_uInt32 remaining_table_size = table_size-4;
+ const sal_uInt32 nMinRecordSize = 8;
+ const sal_uInt32 nMaxRecords = remaining_table_size / nMinRecordSize;
+ if (ncmaps > nMaxRecords)
+ {
+ SAL_WARN("vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fname) <<
+ ": " << nMaxRecords << " max possible entries, but " <<
+ ncmaps << " claimed, truncating");
+ ncmaps = nMaxRecords;
+ }
+
+ for (unsigned int i = 0; i < ncmaps; i++) {
+ /* sanity check, cmap entry must lie within table */
+ sal_uInt32 nLargestFixedOffsetPos = 8 + i * 8;
+ sal_uInt32 nMinSize = nLargestFixedOffsetPos + sizeof(sal_uInt32);
+ if (nMinSize > table_size)
+ {
+ SAL_WARN( "vcl.fonts", "Font " << OUString::createFromAscii(ttf->fname) << " claimed to have "
+ << ncmaps << " cmaps, but only space for " << i);
+ break;
+ }
+
+ sal_uInt16 pID = GetUInt16(table, 4 + i * 8);
+ sal_uInt16 eID = GetUInt16(table, 6 + i * 8);
+ sal_uInt32 offset = GetUInt32(table, nLargestFixedOffsetPos);
+
+ /* sanity check, cmap must lie within file */
+ if( (table - ttf->ptr) + offset > static_cast<sal_uInt32>(ttf->fsize) )
+ continue;
+
+ /* Unicode tables in Apple fonts */
+ if (pID == 0) {
+ AppleUni = offset;
+ }
+
+ if (pID == 3) {
+ switch (eID) {
+ case 0: ThreeZero = offset; break;
+ case 10: // UCS-4
+ case 1: ThreeOne = offset; break;
+ case 2: ThreeTwo = offset; break;
+ case 3: ThreeThree = offset; break;
+ case 4: ThreeFour = offset; break;
+ case 5: ThreeFive = offset; break;
+ case 6: ThreeSix = offset; break;
+ }
+ }
+ }
+
+ // fall back to AppleUnicode if there are no ThreeOne/Threezero tables
+ if( AppleUni && !ThreeZero && !ThreeOne)
+ ThreeOne = AppleUni;
+
+ if (ThreeOne) {
+ ttf->cmapType = CMAP_MS_Unicode;
+ ttf->cmap = table + ThreeOne;
+ } else if (ThreeTwo) {
+ ttf->cmapType = CMAP_MS_ShiftJIS;
+ ttf->cmap = table + ThreeTwo;
+ } else if (ThreeThree) {
+ ttf->cmapType = CMAP_MS_PRC;
+ ttf->cmap = table + ThreeThree;
+ } else if (ThreeFour) {
+ ttf->cmapType = CMAP_MS_Big5;
+ ttf->cmap = table + ThreeFour;
+ } else if (ThreeFive) {
+ ttf->cmapType = CMAP_MS_Wansung;
+ ttf->cmap = table + ThreeFive;
+ } else if (ThreeSix) {
+ ttf->cmapType = CMAP_MS_Johab;
+ ttf->cmap = table + ThreeSix;
+ } else if (ThreeZero) {
+ ttf->cmapType = CMAP_MS_Symbol;
+ ttf->cmap = table + ThreeZero;
+ } else {
+ ttf->cmapType = CMAP_NOT_USABLE;
+ ttf->cmap = nullptr;
+ }
+
+ if (ttf->cmapType != CMAP_NOT_USABLE) {
+ if( (ttf->cmap - ttf->ptr + 2U) > static_cast<sal_uInt32>(ttf->fsize) ) {
+ ttf->cmapType = CMAP_NOT_USABLE;
+ ttf->cmap = nullptr;
+ }
+ }
+
+ if (ttf->cmapType != CMAP_NOT_USABLE) {
+ switch (GetUInt16(ttf->cmap, 0)) {
+ case 0: ttf->mapper = getGlyph0; break;
+ case 2: ttf->mapper = getGlyph2; break;
+ case 4: ttf->mapper = getGlyph4; break;
+ case 6: ttf->mapper = getGlyph6; break;
+ case 12: ttf->mapper= getGlyph12; break;
+ default:
+#if OSL_DEBUG_LEVEL > 1
+ /*- if the cmap table is really broken */
+ SAL_WARN("vcl.fonts", ttf->fname << ": "
+ << GetUInt16(ttf->cmap, 0)
+ << " is not a recognized cmap format..");
+#endif
+ ttf->cmapType = CMAP_NOT_USABLE;
+ ttf->cmap = nullptr;
+ ttf->mapper = nullptr;
+ }
+ }
+}
+
+/*- Public functions */
+
+int CountTTCFonts(const char* fname)
+{
+ int nFonts = 0;
+ sal_uInt8 buffer[12];
+ FILE* fd = fopen(fname, "rb");
+ if( fd ) {
+ if (fread(buffer, 1, 12, fd) == 12) {
+ if(GetUInt32(buffer, 0) == T_ttcf )
+ nFonts = GetUInt32(buffer, 8);
+ }
+ fclose(fd);
+ }
+ return nFonts;
+}
+
+static void allocTrueTypeFont( TrueTypeFont** ttf )
+{
+ *ttf = static_cast<TrueTypeFont*>(calloc(1,sizeof(TrueTypeFont)));
+ if( *ttf != nullptr )
+ {
+ (*ttf)->fname = nullptr;
+ (*ttf)->fsize = -1;
+ (*ttf)->ptr = nullptr;
+ (*ttf)->nglyphs = 0xFFFFFFFF;
+ }
+}
+
+/* forward declaration for the two entry points to use*/
+static SFErrCodes doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t );
+
+#if !defined(_WIN32)
+SFErrCodes OpenTTFontFile( const char* fname, sal_uInt32 facenum, TrueTypeFont** ttf )
+{
+ SFErrCodes ret;
+ int fd = -1;
+ struct stat st;
+
+ if (!fname || !*fname) return SFErrCodes::BadFile;
+
+ allocTrueTypeFont( ttf );
+ if( ! *ttf )
+ return SFErrCodes::Memory;
+
+ (*ttf)->fname = strdup(fname);
+ if( ! (*ttf)->fname )
+ {
+ ret = SFErrCodes::Memory;
+ goto cleanup;
+ }
+
+ fd = open(fname, O_RDONLY);
+
+ if (fd == -1) {
+ ret = SFErrCodes::BadFile;
+ goto cleanup;
+ }
+
+ if (fstat(fd, &st) == -1) {
+ ret = SFErrCodes::FileIo;
+ goto cleanup;
+ }
+
+ (*ttf)->fsize = st.st_size;
+
+ /* On Mac OS, most likely will happen if a Mac user renames a font file
+ * to be .ttf when it's really a Mac resource-based font.
+ * Size will be 0, but fonts smaller than 4 bytes would be broken anyway.
+ */
+ if ((*ttf)->fsize == 0) {
+ ret = SFErrCodes::BadFile;
+ goto cleanup;
+ }
+
+ if (((*ttf)->ptr = static_cast<sal_uInt8 *>(mmap(nullptr, (*ttf)->fsize, PROT_READ, MAP_SHARED, fd, 0))) == MAP_FAILED) {
+ ret = SFErrCodes::Memory;
+ goto cleanup;
+ }
+ close(fd);
+
+ return doOpenTTFont( facenum, *ttf );
+
+cleanup:
+ if (fd != -1) close(fd);
+ /*- t and t->fname have been allocated! */
+ free((*ttf)->fname);
+ free(*ttf);
+ *ttf = nullptr;
+ return ret;
+}
+#endif
+
+SFErrCodes OpenTTFontBuffer(const void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf)
+{
+ allocTrueTypeFont( ttf );
+ if( *ttf == nullptr )
+ return SFErrCodes::Memory;
+
+ (*ttf)->fname = nullptr;
+ (*ttf)->fsize = nLen;
+ (*ttf)->ptr = const_cast<sal_uInt8 *>(static_cast<sal_uInt8 const *>(pBuffer));
+
+ return doOpenTTFont( facenum, *ttf );
+}
+
+namespace {
+
+bool withinBounds(sal_uInt32 tdoffset, sal_uInt32 moreoffset, sal_uInt32 len, sal_uInt32 available)
+{
+ sal_uInt32 result;
+ if (o3tl::checked_add(tdoffset, moreoffset, result))
+ return false;
+ if (o3tl::checked_add(result, len, result))
+ return false;
+ return result <= available;
+}
+
+class TTFontCloser
+{
+ TrueTypeFont* m_font;
+public:
+ TTFontCloser(TrueTypeFont* t)
+ : m_font(t)
+ {
+ }
+ void clear() { m_font = nullptr; }
+ ~TTFontCloser()
+ {
+ if (m_font)
+ CloseTTFont(m_font);
+ }
+};
+
+}
+
+static SFErrCodes doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t )
+{
+ TTFontCloser aCloseGuard(t);
+
+ if (t->fsize < 4) {
+ return SFErrCodes::TtFormat;
+ }
+ int i;
+ sal_uInt32 length, tag;
+ sal_uInt32 tdoffset = 0; /* offset to TableDirectory in a TTC file. For TTF files is 0 */
+
+ sal_uInt32 TTCTag = GetInt32(t->ptr, 0);
+
+ if ((TTCTag == 0x00010000) || (TTCTag == T_true)) {
+ tdoffset = 0;
+ } else if (TTCTag == T_otto) { /* PS-OpenType font */
+ tdoffset = 0;
+ } else if (TTCTag == T_ttcf) { /* TrueType collection */
+ if (!withinBounds(12, 4 * facenum, sizeof(sal_uInt32), t->fsize)) {
+ return SFErrCodes::FontNo;
+ }
+ sal_uInt32 Version = GetUInt32(t->ptr, 4);
+ if (Version != 0x00010000 && Version != 0x00020000) {
+ return SFErrCodes::TtFormat;
+ }
+ if (facenum >= GetUInt32(t->ptr, 8)) {
+ return SFErrCodes::FontNo;
+ }
+ tdoffset = GetUInt32(t->ptr, 12 + 4 * facenum);
+ } else {
+ return SFErrCodes::TtFormat;
+ }
+
+ if (withinBounds(tdoffset, 0, 4 + sizeof(sal_uInt16), t->fsize)) {
+ t->ntables = GetUInt16(t->ptr + tdoffset, 4);
+ }
+
+ if (t->ntables >= 128 || t->ntables == 0) {
+ return SFErrCodes::TtFormat;
+ }
+
+ /* parse the tables */
+ for (i=0; i<static_cast<int>(t->ntables); i++) {
+ int nIndex;
+ const sal_uInt32 nStart = tdoffset + 12;
+ const sal_uInt32 nOffset = 16 * i;
+ if (withinBounds(nStart, nOffset, sizeof(sal_uInt32), t->fsize))
+ tag = GetUInt32(t->ptr + nStart, nOffset);
+ else
+ tag = static_cast<sal_uInt32>(-1);
+ switch( tag ) {
+ case T_maxp: nIndex = O_maxp; break;
+ case T_glyf: nIndex = O_glyf; break;
+ case T_head: nIndex = O_head; break;
+ case T_loca: nIndex = O_loca; break;
+ case T_name: nIndex = O_name; break;
+ case T_hhea: nIndex = O_hhea; break;
+ case T_hmtx: nIndex = O_hmtx; break;
+ case T_cmap: nIndex = O_cmap; break;
+ case T_vhea: nIndex = O_vhea; break;
+ case T_vmtx: nIndex = O_vmtx; break;
+ case T_OS2 : nIndex = O_OS2; break;
+ case T_post: nIndex = O_post; break;
+ case T_cvt : nIndex = O_cvt; break;
+ case T_prep: nIndex = O_prep; break;
+ case T_fpgm: nIndex = O_fpgm; break;
+ case T_gsub: nIndex = O_gsub; break;
+ case T_CFF: nIndex = O_CFF; break;
+ default: nIndex = -1; break;
+ }
+
+ if ((nIndex >= 0) && withinBounds(nStart, nOffset, 12 + sizeof(sal_uInt32), t->fsize)) {
+ sal_uInt32 nTableOffset = GetUInt32(t->ptr + nStart, nOffset + 8);
+ length = GetUInt32(t->ptr + nStart, nOffset + 12);
+ t->tables[nIndex] = t->ptr + nTableOffset;
+ t->tlens[nIndex] = length;
+ }
+ }
+
+ /* Fixup offsets when only a TTC extract was provided */
+ if( facenum == sal_uInt32(~0) ) {
+ sal_uInt8* pHead = const_cast<sal_uInt8*>(t->tables[O_head]);
+ if (!pHead) {
+ return SFErrCodes::TtFormat;
+ }
+ /* limit Head candidate to TTC extract's limits */
+ if( pHead > t->ptr + (t->fsize - 54) )
+ pHead = t->ptr + (t->fsize - 54);
+ /* TODO: find better method than searching head table's magic */
+ sal_uInt8* p = nullptr;
+ for( p = pHead + 12; p > t->ptr; --p ) {
+ if( p[0]==0x5F && p[1]==0x0F && p[2]==0x3C && p[3]==0xF5 ) {
+ int nDelta = (pHead + 12) - p;
+ if( nDelta )
+ for( int j = 0; j < NUM_TAGS; ++j )
+ if( t->tables[j] )
+ *reinterpret_cast<char const **>(&t->tables[j]) -= nDelta;
+ break;
+ }
+ }
+ if (p <= t->ptr) {
+ return SFErrCodes::TtFormat;
+ }
+ }
+
+ /* Check the table offsets after TTC correction */
+ for (i=0; i<NUM_TAGS; i++) {
+ /* sanity check: table must lay completely within the file
+ * at this point one could check the checksum of all contained
+ * tables, but this would be quite time intensive.
+ * Try to fix tables, so we can cope with minor problems.
+ */
+
+ if( t->tables[i] < t->ptr )
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN_IF(t->tables[i], "vcl.fonts", "font file " << t->fname
+ << " has bad table offset "
+ << (sal_uInt8*)t->tables[i]-t->ptr
+ << "d (tagnum=" << i << ").");
+#endif
+ t->tlens[i] = 0;
+ t->tables[i] = nullptr;
+ }
+ else if( const_cast<sal_uInt8*>(t->tables[i]) + t->tlens[i] > t->ptr + t->fsize )
+ {
+ sal_PtrDiff nMaxLen = (t->ptr + t->fsize) - t->tables[i];
+ if( nMaxLen < 0 )
+ nMaxLen = 0;
+ t->tlens[i] = nMaxLen;
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "font file " << t->fname
+ << " has too big table (tagnum=" << i << ").");
+#endif
+ }
+ }
+
+ /* At this point TrueTypeFont is constructed, now need to verify the font format
+ and read the basic font properties */
+
+ /* The following tables are absolutely required:
+ * maxp, head, name, cmap
+ */
+
+ if( !(getTable(t, O_maxp) && getTable(t, O_head) && getTable(t, O_name) && getTable(t, O_cmap)) ) {
+ return SFErrCodes::TtFormat;
+ }
+
+ const sal_uInt8* table = getTable(t, O_maxp);
+ sal_uInt32 table_size = getTableSize(t, O_maxp);
+ t->nglyphs = table_size >= 6 ? GetUInt16(table, 4) : 0;
+
+ table = getTable(t, O_head);
+ table_size = getTableSize(t, O_head);
+ if (table_size < HEAD_Length) {
+ return SFErrCodes::TtFormat;
+ }
+ t->unitsPerEm = GetUInt16(table, HEAD_unitsPerEm_offset);
+ int indexfmt = GetInt16(table, HEAD_indexToLocFormat_offset);
+
+ if( ((indexfmt != 0) && (indexfmt != 1)) || (t->unitsPerEm <= 0) ) {
+ return SFErrCodes::TtFormat;
+ }
+
+ if( getTable(t, O_glyf) && getTable(t, O_loca) ) /* TTF or TTF-OpenType */
+ {
+ int k = (getTableSize(t, O_loca) / (indexfmt ? 4 : 2)) - 1;
+ if( k < static_cast<int>(t->nglyphs) ) /* Hack for broken Chinese fonts */
+ t->nglyphs = k;
+
+ table = getTable(t, O_loca);
+ t->goffsets = static_cast<sal_uInt32 *>(calloc(1+t->nglyphs, sizeof(sal_uInt32)));
+ assert(t->goffsets != nullptr);
+
+ for( i = 0; i <= static_cast<int>(t->nglyphs); ++i )
+ t->goffsets[i] = indexfmt ? GetUInt32(table, i << 2) : static_cast<sal_uInt32>(GetUInt16(table, i << 1)) << 1;
+ } else if( getTable(t, O_CFF) ) { /* PS-OpenType */
+ int k = (getTableSize(t, O_CFF) / 2) - 1; /* set a limit here, presumably much lower than the table size, but establishes some sort of physical bound */
+ if( k < static_cast<int>(t->nglyphs) )
+ t->nglyphs = k;
+ t->goffsets = static_cast<sal_uInt32 *>(calloc(1+t->nglyphs, sizeof(sal_uInt32)));
+ /* TODO: implement to get subsetting */
+ assert(t->goffsets != nullptr);
+ } else {
+ // Bitmap font, accept for now.
+ t->goffsets = static_cast<sal_uInt32 *>(calloc(1+t->nglyphs, sizeof(sal_uInt32)));
+ /* TODO: implement to get subsetting */
+ assert(t->goffsets != nullptr);
+ }
+
+ table = getTable(t, O_hhea);
+ table_size = getTableSize(t, O_hhea);
+ t->numberOfHMetrics = (table && table_size >= 36) ? GetUInt16(table, 34) : 0;
+
+ table = getTable(t, O_vhea);
+ table_size = getTableSize(t, O_vhea);
+ t->numOfLongVerMetrics = (table && table_size >= 36) ? GetUInt16(table, 34) : 0;
+
+ GetNames(t);
+ FindCmap(t);
+
+ aCloseGuard.clear();
+
+ return SFErrCodes::Ok;
+}
+
+void CloseTTFont(TrueTypeFont *ttf)
+{
+#if !defined(_WIN32)
+ if( ttf->fname )
+ munmap(ttf->ptr, ttf->fsize);
+#endif
+ free(ttf->fname);
+ free(ttf->goffsets);
+ free(ttf->psname);
+ free(ttf->family);
+ if( ttf->ufamily )
+ free( ttf->ufamily );
+ free(ttf->subfamily);
+ if( ttf->usubfamily )
+ free( ttf->usubfamily );
+
+ free(ttf);
+}
+
+int GetTTGlyphPoints(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray)
+{
+ return GetTTGlyphOutline(ttf, glyphID, pointArray, nullptr, nullptr);
+}
+
+int GetTTGlyphComponents(TrueTypeFont *ttf, sal_uInt32 glyphID, std::vector< sal_uInt32 >& glyphlist)
+{
+ int n = 1;
+
+ if( glyphID >= ttf->nglyphs )
+ return 0;
+
+ const sal_uInt8* glyf = getTable(ttf, O_glyf);
+ const sal_uInt8* ptr = glyf + ttf->goffsets[glyphID];
+ const sal_uInt8* nptr = glyf + ttf->goffsets[glyphID+1];
+ if (nptr <= ptr)
+ return 0;
+
+ glyphlist.push_back( glyphID );
+
+ if (GetInt16(ptr, 0) == -1) {
+ sal_uInt16 flags, index;
+ ptr += 10;
+ do {
+ flags = GetUInt16(ptr, 0);
+ index = GetUInt16(ptr, 2);
+
+ ptr += 4;
+ n += GetTTGlyphComponents(ttf, index, glyphlist);
+
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ ptr += 4;
+ } else {
+ ptr += 2;
+ }
+
+ if (flags & WE_HAVE_A_SCALE) {
+ ptr += 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ ptr += 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ ptr += 8;
+ }
+ } while (flags & MORE_COMPONENTS);
+ }
+
+ return n;
+}
+
+SFErrCodes CreateT3FromTTGlyphs(TrueTypeFont *ttf, FILE *outf, const char *fname,
+ sal_uInt16 const *glyphArray, sal_uInt8 *encoding, int nGlyphs,
+ int wmode)
+{
+ ControlPoint *pa;
+ PSPathElement *path;
+ int i, j, n;
+ const sal_uInt8* table = getTable(ttf, O_head);
+ TTGlyphMetrics metrics;
+ int UPEm = ttf->unitsPerEm;
+
+ const char * const h01 = "%%!PS-AdobeFont-%d.%d-%d.%d\n";
+ const char * const h02 = "%% Creator: %s %s %s\n";
+ const char * const h09 = "%% Original font name: %s\n";
+
+ const char * const h10 =
+ "30 dict begin\n"
+ "/PaintType 0 def\n"
+ "/FontType 3 def\n"
+ "/StrokeWidth 0 def\n";
+
+ const char * const h11 = "/FontName (%s) cvn def\n";
+
+ /*
+ const char *h12 = "%/UniqueID %d def\n";
+ */
+ const char * const h13 = "/FontMatrix [.001 0 0 .001 0 0] def\n";
+ const char * const h14 = "/FontBBox [%d %d %d %d] def\n";
+
+ const char * const h15=
+ "/Encoding 256 array def\n"
+ " 0 1 255 {Encoding exch /.notdef put} for\n";
+
+ const char * const h16 = " Encoding %d /glyph%d put\n";
+ const char * const h17 = "/XUID [103 0 0 16#%08" SAL_PRIXUINT32 " %d 16#%08" SAL_PRIXUINT32 " 16#%08" SAL_PRIXUINT32 "] def\n";
+
+ const char * const h30 = "/CharProcs %d dict def\n";
+ const char * const h31 = " CharProcs begin\n";
+ const char * const h32 = " /.notdef {} def\n";
+ const char * const h33 = " /glyph%d {\n";
+ const char * const h34 = " } bind def\n";
+ const char * const h35 = " end\n";
+
+ const char * const h40 =
+ "/BuildGlyph {\n"
+ " exch /CharProcs get exch\n"
+ " 2 copy known not\n"
+ " {pop /.notdef} if\n"
+ " get exec\n"
+ "} bind def\n"
+ "/BuildChar {\n"
+ " 1 index /Encoding get exch get\n"
+ " 1 index /BuildGlyph get exec\n"
+ "} bind def\n"
+ "currentdict end\n";
+
+ const char * const h41 = "(%s) cvn exch definefont pop\n";
+
+ if (!((nGlyphs > 0) && (nGlyphs <= 256))) return SFErrCodes::GlyphNum;
+ if (!glyphArray) return SFErrCodes::BadArg;
+ if (!fname) fname = ttf->psname;
+
+ fprintf(outf, h01, GetInt16(table, 0), GetUInt16(table, 2), GetInt16(table, 4), GetUInt16(table, 6));
+ fprintf(outf, h02, modname, modver, modextra);
+ fprintf(outf, h09, ttf->psname);
+
+ fprintf(outf, "%s", h10);
+ fprintf(outf, h11, fname);
+/* fprintf(outf, h12, 4000000); */
+
+ /* XUID generation:
+ * 103 0 0 C1 C2 C3 C4
+ * C1 - CRC-32 of the entire source TrueType font
+ * C2 - number of glyphs in the subset
+ * C3 - CRC-32 of the glyph array
+ * C4 - CRC-32 of the encoding array
+ *
+ * All CRC-32 numbers are presented as hexadecimal numbers
+ */
+
+ fprintf(outf, h17, rtl_crc32(0, ttf->ptr, ttf->fsize), nGlyphs, rtl_crc32(0, glyphArray, nGlyphs * 2), rtl_crc32(0, encoding, nGlyphs));
+ fprintf(outf, "%s", h13);
+ fprintf(outf, h14, XUnits(UPEm, GetInt16(table, 36)), XUnits(UPEm, GetInt16(table, 38)), XUnits(UPEm, GetInt16(table, 40)), XUnits(UPEm, GetInt16(table, 42)));
+ fprintf(outf, "%s", h15);
+
+ for (i = 0; i < nGlyphs; i++) {
+ fprintf(outf, h16, encoding[i], i);
+ }
+
+ fprintf(outf, h30, nGlyphs+1);
+ fprintf(outf, "%s", h31);
+ fprintf(outf, "%s", h32);
+
+ for (i = 0; i < nGlyphs; i++) {
+ fprintf(outf, h33, i);
+ int r = GetTTGlyphOutline(ttf, glyphArray[i] < ttf->nglyphs ? glyphArray[i] : 0, &pa, &metrics, nullptr);
+
+ if (r > 0) {
+ n = BSplineToPSPath(pa, r, &path);
+ } else {
+ n = 0; /* glyph might have zero contours but valid metrics ??? */
+ path = nullptr;
+ if (r < 0) { /* glyph is not present in the font - pa array was not allocated, so no need to free it */
+ continue;
+ }
+ }
+ fprintf(outf, "\t%d %d %d %d %d %d setcachedevice\n",
+ wmode == 0 ? XUnits(UPEm, metrics.aw) : 0,
+ wmode == 0 ? 0 : -XUnits(UPEm, metrics.ah),
+ XUnits(UPEm, metrics.xMin),
+ XUnits(UPEm, metrics.yMin),
+ XUnits(UPEm, metrics.xMax),
+ XUnits(UPEm, metrics.yMax));
+
+ for (j = 0; j < n; j++)
+ {
+ switch (path[j].type)
+ {
+ case PS_MOVETO:
+ fprintf(outf, "\t%d %d moveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1));
+ break;
+
+ case PS_LINETO:
+ fprintf(outf, "\t%d %d lineto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1));
+ break;
+
+ case PS_CURVETO:
+ fprintf(outf, "\t%d %d %d %d %d %d curveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1), XUnits(UPEm, path[j].x2), XUnits(UPEm, path[j].y2), XUnits(UPEm, path[j].x3), XUnits(UPEm, path[j].y3));
+ break;
+
+ case PS_CLOSEPATH:
+ fprintf(outf, "\tclosepath\n");
+ break;
+ case PS_NOOP:
+ break;
+ }
+ }
+ if (n > 0) fprintf(outf, "\tfill\n"); /* if glyph is not a whitespace character */
+
+ fprintf(outf, "%s", h34);
+
+ free(pa);
+ free(path);
+ }
+ fprintf(outf, "%s", h35);
+
+ fprintf(outf, "%s", h40);
+ fprintf(outf, h41, fname);
+
+ return SFErrCodes::Ok;
+}
+
+SFErrCodes CreateTTFromTTGlyphs(TrueTypeFont *ttf,
+ const char *fname,
+ sal_uInt16 const *glyphArray,
+ sal_uInt8 const *encoding,
+ int nGlyphs)
+{
+ TrueTypeCreator *ttcr;
+ TrueTypeTable *head=nullptr, *hhea=nullptr, *maxp=nullptr, *cvt=nullptr, *prep=nullptr, *glyf=nullptr, *fpgm=nullptr, *cmap=nullptr, *name=nullptr, *post = nullptr, *os2 = nullptr;
+ int i;
+ SFErrCodes res;
+
+ TrueTypeCreatorNewEmpty(T_true, &ttcr);
+
+ /** name **/
+
+ NameRecord *names;
+ int n = GetTTNameRecords(ttf, &names);
+ name = TrueTypeTableNew_name(n, names);
+ DisposeNameRecords(names, n);
+
+ /** maxp **/
+ maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp));
+
+ /** hhea **/
+ const sal_uInt8* p = getTable(ttf, O_hhea);
+ if (p) {
+ hhea = TrueTypeTableNew_hhea(GetInt16(p, HHEA_ascender_offset), GetInt16(p, HHEA_descender_offset), GetInt16(p, HHEA_lineGap_offset), GetInt16(p, HHEA_caretSlopeRise_offset), GetInt16(p, HHEA_caretSlopeRun_offset));
+ } else {
+ hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0);
+ }
+
+ /** head **/
+
+ p = getTable(ttf, O_head);
+ assert(p != nullptr);
+ head = TrueTypeTableNew_head(GetInt32(p, HEAD_fontRevision_offset),
+ GetUInt16(p, HEAD_flags_offset),
+ GetUInt16(p, HEAD_unitsPerEm_offset),
+ p+HEAD_created_offset,
+ GetUInt16(p, HEAD_macStyle_offset),
+ GetUInt16(p, HEAD_lowestRecPPEM_offset),
+ GetInt16(p, HEAD_fontDirectionHint_offset));
+
+ /** glyf **/
+
+ glyf = TrueTypeTableNew_glyf();
+ sal_uInt32* gID = static_cast<sal_uInt32*>(scalloc(nGlyphs, sizeof(sal_uInt32)));
+
+ for (i = 0; i < nGlyphs; i++) {
+ gID[i] = glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf);
+ }
+
+ /** cmap **/
+ cmap = TrueTypeTableNew_cmap();
+
+ for (i=0; i < nGlyphs; i++) {
+ cmapAdd(cmap, 0x010000, encoding[i], gID[i]);
+ }
+
+ /** cvt **/
+ if ((p = getTable(ttf, O_cvt)) != nullptr) {
+ cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p);
+ }
+
+ /** prep **/
+ if ((p = getTable(ttf, O_prep)) != nullptr) {
+ prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p);
+ }
+
+ /** fpgm **/
+ if ((p = getTable(ttf, O_fpgm)) != nullptr) {
+ fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p);
+ }
+
+ /** post **/
+ if ((p = getTable(ttf, O_post)) != nullptr) {
+ post = TrueTypeTableNew_post(0x00030000,
+ GetInt32(p, POST_italicAngle_offset),
+ GetInt16(p, POST_underlinePosition_offset),
+ GetInt16(p, POST_underlineThickness_offset),
+ GetUInt32(p, POST_isFixedPitch_offset));
+ } else {
+ post = TrueTypeTableNew_post(0x00030000, 0, 0, 0, 0);
+ }
+
+ AddTable(ttcr, name); AddTable(ttcr, maxp); AddTable(ttcr, hhea);
+ AddTable(ttcr, head); AddTable(ttcr, glyf); AddTable(ttcr, cmap);
+ AddTable(ttcr, cvt ); AddTable(ttcr, prep); AddTable(ttcr, fpgm);
+ AddTable(ttcr, post); AddTable(ttcr, os2);
+
+ res = StreamToFile(ttcr, fname);
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN_IF(res != SFErrCodes::Ok, "vcl.fonts", "StreamToFile: error code: "
+ << (int) res << ".");
+#endif
+
+ TrueTypeCreatorDispose(ttcr);
+ free(gID);
+
+ return res;
+}
+
+static GlyphOffsets *GlyphOffsetsNew(sal_uInt8 *sfntP, sal_uInt32 sfntLen)
+{
+ GlyphOffsets* res = static_cast<GlyphOffsets*>(smalloc(sizeof(GlyphOffsets)));
+ sal_uInt8 *loca = nullptr;
+ sal_uInt16 numTables = GetUInt16(sfntP, 4);
+ sal_uInt32 locaLen = 0;
+ sal_Int16 indexToLocFormat = 0;
+
+ sal_uInt32 nMaxPossibleTables = sfntLen / (3*sizeof(sal_uInt32)); /*the three GetUInt32 calls*/
+ if (numTables > nMaxPossibleTables)
+ {
+ SAL_WARN( "vcl.fonts", "GlyphOffsetsNew claimed to have "
+ << numTables << " tables, but that's impossibly large");
+ numTables = nMaxPossibleTables;
+ }
+
+ for (sal_uInt16 i = 0; i < numTables; i++) {
+ sal_uInt32 nLargestFixedOffsetPos = 12 + 16 * i + 12;
+ sal_uInt32 nMinSize = nLargestFixedOffsetPos + sizeof(sal_uInt32);
+ if (nMinSize > sfntLen)
+ {
+ SAL_WARN( "vcl.fonts", "GlyphOffsetsNew claimed to have "
+ << numTables << " tables, but only space for " << i);
+ break;
+ }
+
+ sal_uInt32 tag = GetUInt32(sfntP, 12 + 16 * i);
+ sal_uInt32 off = GetUInt32(sfntP, 12 + 16 * i + 8);
+ sal_uInt32 len = GetUInt32(sfntP, nLargestFixedOffsetPos);
+
+ if (tag == T_loca) {
+ loca = sfntP + off;
+ locaLen = len;
+ } else if (tag == T_head) {
+ indexToLocFormat = GetInt16(sfntP + off, 50);
+ }
+ }
+
+ res->nGlyphs = locaLen / ((indexToLocFormat == 1) ? 4 : 2);
+ assert(res->nGlyphs != 0);
+ res->offs = static_cast<sal_uInt32*>(scalloc(res->nGlyphs, sizeof(sal_uInt32)));
+
+ for (sal_uInt32 i = 0; i < res->nGlyphs; i++) {
+ if (indexToLocFormat == 1) {
+ res->offs[i] = GetUInt32(loca, i * 4);
+ } else {
+ res->offs[i] = GetUInt16(loca, i * 2) << 1;
+ }
+ }
+ return res;
+}
+
+static void GlyphOffsetsDispose(GlyphOffsets *_this)
+{
+ if (_this) {
+ free(_this->offs);
+ free(_this);
+ }
+}
+
+static void DumpSfnts(FILE *outf, sal_uInt8 *sfntP, sal_uInt32 sfntLen)
+{
+ if (sfntLen < 12)
+ {
+ SAL_WARN( "vcl.fonts", "DumpSfnts sfntLen is too short: "
+ << sfntLen << " legal min is: " << 12);
+ return;
+ }
+
+ const sal_uInt32 nSpaceForTables = sfntLen - 12;
+ const sal_uInt32 nTableSize = 16;
+ const sal_uInt32 nMaxPossibleTables = nSpaceForTables/nTableSize;
+
+ HexFmt *h = HexFmtNew(outf);
+ sal_uInt16 i, numTables = GetUInt16(sfntP, 4);
+ GlyphOffsets *go = GlyphOffsetsNew(sfntP, sfntLen);
+ sal_uInt8 const pad[] = {0,0,0,0}; /* zeroes */
+
+ if (numTables > nMaxPossibleTables)
+ {
+ SAL_WARN( "vcl.fonts", "DumpSfnts claimed to have "
+ << numTables << " tables, but only space for " << nMaxPossibleTables);
+ numTables = nMaxPossibleTables;
+ }
+
+ assert(numTables <= 9); /* Type42 has 9 required tables */
+
+ sal_uInt32* offs = static_cast<sal_uInt32*>(scalloc(numTables, sizeof(sal_uInt32)));
+
+ fputs("/sfnts [", outf);
+ HexFmtOpenString(h);
+ HexFmtBlockWrite(h, sfntP, 12); /* stream out the Offset Table */
+ HexFmtBlockWrite(h, sfntP+12, 16 * numTables); /* stream out the Table Directory */
+
+ for (i=0; i<numTables; i++)
+ {
+ sal_uInt32 nLargestFixedOffsetPos = 12 + 16 * i + 12;
+ sal_uInt32 nMinSize = nLargestFixedOffsetPos + sizeof(sal_uInt32);
+ if (nMinSize > sfntLen)
+ {
+ SAL_WARN( "vcl.fonts", "DumpSfnts claimed to have "
+ << numTables << " tables, but only space for " << i);
+ break;
+ }
+
+ sal_uInt32 tag = GetUInt32(sfntP, 12 + 16 * i);
+ sal_uInt32 off = GetUInt32(sfntP, 12 + 16 * i + 8);
+ if (off > sfntLen)
+ {
+ SAL_WARN( "vcl.fonts", "DumpSfnts claims offset of "
+ << off << " but max possible is " << sfntLen);
+ break;
+ }
+ sal_uInt8 *pRecordStart = sfntP + off;
+ sal_uInt32 len = GetUInt32(sfntP, nLargestFixedOffsetPos);
+ sal_uInt32 nMaxLenPossible = sfntLen - off;
+ if (len > nMaxLenPossible)
+ {
+ SAL_WARN( "vcl.fonts", "DumpSfnts claims len of "
+ << len << " but only space for " << nMaxLenPossible);
+ break;
+ }
+
+ if (tag != T_glyf)
+ {
+ HexFmtBlockWrite(h, pRecordStart, len);
+ }
+ else
+ {
+ sal_uInt8 *glyf = pRecordStart;
+ for (sal_uInt32 j = 0; j < go->nGlyphs - 1; j++)
+ {
+ sal_uInt32 o = go->offs[j];
+ sal_uInt32 l = go->offs[j + 1] - o;
+ HexFmtBlockWrite(h, glyf + o, l);
+ }
+ }
+ HexFmtBlockWrite(h, pad, (4 - (len & 3)) & 3);
+ }
+ HexFmtCloseString(h);
+ fputs("] def\n", outf);
+ GlyphOffsetsDispose(go);
+ HexFmtDispose(h);
+ free(offs);
+}
+
+SFErrCodes CreateT42FromTTGlyphs(TrueTypeFont *ttf,
+ FILE *outf,
+ const char *psname,
+ sal_uInt16 const *glyphArray,
+ sal_uInt8 *encoding,
+ int nGlyphs)
+{
+ TrueTypeCreator *ttcr;
+ TrueTypeTable *head=nullptr, *hhea=nullptr, *maxp=nullptr, *cvt=nullptr, *prep=nullptr, *glyf=nullptr, *fpgm=nullptr;
+ int i;
+ SFErrCodes res;
+
+ sal_uInt16 ver;
+ sal_Int32 rev;
+
+ sal_uInt8 *sfntP;
+ sal_uInt32 sfntLen;
+ int UPEm = ttf->unitsPerEm;
+
+ if (nGlyphs >= 256) return SFErrCodes::GlyphNum;
+
+ assert(psname != nullptr);
+
+ TrueTypeCreatorNewEmpty(T_true, &ttcr);
+
+ /* head */
+ const sal_uInt8* p = getTable(ttf, O_head);
+ const sal_uInt8* headP = p;
+ assert(p != nullptr);
+ head = TrueTypeTableNew_head(GetInt32(p, HEAD_fontRevision_offset), GetUInt16(p, HEAD_flags_offset), GetUInt16(p, HEAD_unitsPerEm_offset), p+HEAD_created_offset, GetUInt16(p, HEAD_macStyle_offset), GetUInt16(p, HEAD_lowestRecPPEM_offset), GetInt16(p, HEAD_fontDirectionHint_offset));
+ ver = GetUInt16(p, HEAD_majorVersion_offset);
+ rev = GetInt32(p, HEAD_fontRevision_offset);
+
+ /** hhea **/
+ p = getTable(ttf, O_hhea);
+ if (p) {
+ hhea = TrueTypeTableNew_hhea(GetInt16(p, HHEA_ascender_offset), GetInt16(p, HHEA_descender_offset), GetInt16(p, HHEA_lineGap_offset), GetInt16(p, HHEA_caretSlopeRise_offset), GetInt16(p, HHEA_caretSlopeRun_offset));
+ } else {
+ hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0);
+ }
+
+ /** maxp **/
+ maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp));
+
+ /** cvt **/
+ if ((p = getTable(ttf, O_cvt)) != nullptr) {
+ cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p);
+ }
+
+ /** prep **/
+ if ((p = getTable(ttf, O_prep)) != nullptr) {
+ prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p);
+ }
+
+ /** fpgm **/
+ if ((p = getTable(ttf, O_fpgm)) != nullptr) {
+ fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p);
+ }
+
+ /** glyf **/
+ glyf = TrueTypeTableNew_glyf();
+ sal_uInt16* gID = static_cast<sal_uInt16*>(scalloc(nGlyphs, sizeof(sal_uInt32)));
+
+ for (i = 0; i < nGlyphs; i++) {
+ gID[i] = static_cast<sal_uInt16>(glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf));
+ }
+
+ AddTable(ttcr, head); AddTable(ttcr, hhea); AddTable(ttcr, maxp); AddTable(ttcr, cvt);
+ AddTable(ttcr, prep); AddTable(ttcr, glyf); AddTable(ttcr, fpgm);
+
+ if ((res = StreamToMemory(ttcr, &sfntP, &sfntLen)) != SFErrCodes::Ok) {
+ TrueTypeCreatorDispose(ttcr);
+ free(gID);
+ return res;
+ }
+
+ fprintf(outf, "%%!PS-TrueTypeFont-%d.%d-%d.%d\n", static_cast<int>(ver), static_cast<int>(ver & 0xFF), static_cast<int>(rev>>16), static_cast<int>(rev & 0xFFFF));
+ fprintf(outf, "%%%%Creator: %s %s %s\n", modname, modver, modextra);
+ fprintf(outf, "%%- Font subset generated from a source font file: '%s'\n", ttf->fname);
+ fprintf(outf, "%%- Original font name: %s\n", ttf->psname);
+ fprintf(outf, "%%- Original font family: %s\n", ttf->family);
+ fprintf(outf, "%%- Original font sub-family: %s\n", ttf->subfamily);
+ fprintf(outf, "11 dict begin\n");
+ fprintf(outf, "/FontName (%s) cvn def\n", psname);
+ fprintf(outf, "/PaintType 0 def\n");
+ fprintf(outf, "/FontMatrix [1 0 0 1 0 0] def\n");
+ fprintf(outf, "/FontBBox [%d %d %d %d] def\n", XUnits(UPEm, GetInt16(headP, HEAD_xMin_offset)), XUnits(UPEm, GetInt16(headP, HEAD_yMin_offset)), XUnits(UPEm, GetInt16(headP, HEAD_xMax_offset)), XUnits(UPEm, GetInt16(headP, HEAD_yMax_offset)));
+ fprintf(outf, "/FontType 42 def\n");
+ fprintf(outf, "/Encoding 256 array def\n");
+ fprintf(outf, " 0 1 255 {Encoding exch /.notdef put} for\n");
+
+ for (i = 1; i<nGlyphs; i++) {
+ fprintf(outf, "Encoding %d /glyph%u put\n", encoding[i], gID[i]);
+ }
+ fprintf(outf, "/XUID [103 0 1 16#%08X %u 16#%08X 16#%08X] def\n", static_cast<unsigned int>(rtl_crc32(0, ttf->ptr, ttf->fsize)), static_cast<unsigned int>(nGlyphs), static_cast<unsigned int>(rtl_crc32(0, glyphArray, nGlyphs * 2)), static_cast<unsigned int>(rtl_crc32(0, encoding, nGlyphs)));
+
+ DumpSfnts(outf, sfntP, sfntLen);
+
+ /* dump charstrings */
+ fprintf(outf, "/CharStrings %d dict dup begin\n", nGlyphs);
+ fprintf(outf, "/.notdef 0 def\n");
+ for (i = 1; i < static_cast<int>(glyfCount(glyf)); i++) {
+ fprintf(outf,"/glyph%d %d def\n", i, i);
+ }
+ fprintf(outf, "end readonly def\n");
+
+ fprintf(outf, "FontName currentdict end definefont pop\n");
+ TrueTypeCreatorDispose(ttcr);
+ free(gID);
+ free(sfntP);
+ return SFErrCodes::Ok;
+}
+
+#if defined(_WIN32) || defined(MACOSX) || defined(IOS)
+sal_uInt16 MapChar(TrueTypeFont const *ttf, sal_uInt16 ch)
+{
+ switch (ttf->cmapType) {
+ case CMAP_MS_Symbol:
+ {
+ const sal_uInt32 nMaxCmapSize = ttf->ptr + ttf->fsize - ttf->cmap;
+ if( ttf->mapper == getGlyph0 && ( ch & 0xf000 ) == 0xf000 )
+ ch &= 0x00ff;
+ return static_cast<sal_uInt16>(ttf->mapper(ttf->cmap, nMaxCmapSize, ch ));
+ }
+
+ case CMAP_MS_Unicode: break;
+ case CMAP_MS_ShiftJIS: ch = TranslateChar12(ch); break;
+ case CMAP_MS_PRC: ch = TranslateChar13(ch); break;
+ case CMAP_MS_Big5: ch = TranslateChar14(ch); break;
+ case CMAP_MS_Wansung: ch = TranslateChar15(ch); break;
+ case CMAP_MS_Johab: ch = TranslateChar16(ch); break;
+ default: return 0;
+ }
+ const sal_uInt32 nMaxCmapSize = ttf->ptr + ttf->fsize - ttf->cmap;
+ ch = static_cast<sal_uInt16>(ttf->mapper(ttf->cmap, nMaxCmapSize, ch));
+ return ch;
+}
+#endif
+
+
+int GetTTGlyphCount( TrueTypeFont const * ttf )
+{
+ return ttf->nglyphs;
+}
+
+bool GetSfntTable( TrueTypeFont const * ttf, int nSubtableIndex,
+ const sal_uInt8** ppRawBytes, int* pRawLength )
+{
+ if( (nSubtableIndex < 0) || (nSubtableIndex >= NUM_TAGS) )
+ return false;
+ *pRawLength = ttf->tlens[ nSubtableIndex ];
+ *ppRawBytes = ttf->tables[ nSubtableIndex ];
+ bool bOk = (*pRawLength > 0) && (*ppRawBytes != nullptr);
+ return bOk;
+}
+
+std::unique_ptr<sal_uInt16[]> GetTTSimpleGlyphMetrics(TrueTypeFont const *ttf, const sal_uInt16 *glyphArray, int nGlyphs, bool vertical)
+{
+ const sal_uInt8* pTable;
+ sal_uInt32 n;
+ int nTableSize;
+
+ if (!vertical) {
+ n = ttf->numberOfHMetrics;
+ pTable = getTable( ttf, O_hmtx );
+ nTableSize = getTableSize( ttf, O_hmtx );
+ } else {
+ n = ttf->numOfLongVerMetrics;
+ pTable = getTable( ttf, O_vmtx );
+ nTableSize = getTableSize( ttf, O_vmtx );
+ }
+
+ if (!nGlyphs || !glyphArray) return nullptr; /* invalid parameters */
+ if (!n || !pTable) return nullptr; /* the font does not contain the requested metrics */
+
+ std::unique_ptr<sal_uInt16[]> res(new sal_uInt16[nGlyphs]);
+
+ const int UPEm = ttf->unitsPerEm;
+ for( int i = 0; i < nGlyphs; ++i) {
+ int nAdvOffset;
+ sal_uInt16 glyphID = glyphArray[i];
+
+ if (glyphID < n) {
+ nAdvOffset = 4 * glyphID;
+ } else {
+ nAdvOffset = 4 * (n - 1);
+ }
+
+ if( nAdvOffset >= nTableSize)
+ res[i] = 0; /* better than a crash for buggy fonts */
+ else
+ res[i] = static_cast<sal_uInt16>(
+ XUnits( UPEm, GetUInt16( pTable, nAdvOffset) ) );
+ }
+
+ return res;
+}
+
+// TODO, clean up table parsing and re-use it elsewhere in this file.
+void GetTTFontMetrics(const uint8_t *pHhea, size_t nHhea,
+ const uint8_t *pOs2, size_t nOs2,
+ TTGlobalFontInfo *info)
+{
+ /* There are 3 different versions of OS/2 table: original (68 bytes long),
+ * Microsoft old (78 bytes long) and Microsoft new (86 bytes long,)
+ * Apple's documentation recommends looking at the table length.
+ */
+ if (nOs2 >= OS2_V0_length)
+ {
+ info->fsSelection = GetUInt16(pOs2, OS2_fsSelection_offset);
+ info->typoAscender = GetInt16(pOs2, OS2_typoAscender_offset);
+ info->typoDescender = GetInt16(pOs2, OS2_typoDescender_offset);
+ info->typoLineGap = GetInt16(pOs2, OS2_typoLineGap_offset);
+ info->winAscent = GetUInt16(pOs2, OS2_winAscent_offset);
+ info->winDescent = GetUInt16(pOs2, OS2_winDescent_offset);
+ }
+
+ if (nHhea >= HHEA_lineGap_offset + 2) {
+ info->ascender = GetInt16(pHhea, HHEA_ascender_offset);
+ info->descender = GetInt16(pHhea, HHEA_descender_offset);
+ info->linegap = GetInt16(pHhea, HHEA_lineGap_offset);
+ }
+}
+
+void GetTTGlobalFontInfo(TrueTypeFont *ttf, TTGlobalFontInfo *info)
+{
+ int UPEm = ttf->unitsPerEm;
+
+ memset(info, 0, sizeof(TTGlobalFontInfo));
+
+ info->family = ttf->family;
+ info->ufamily = ttf->ufamily;
+ info->subfamily = ttf->subfamily;
+ info->usubfamily = ttf->usubfamily;
+ info->psname = ttf->psname;
+ info->symbolEncoded = (ttf->cmapType == CMAP_MS_Symbol);
+
+ const sal_uInt8* table = getTable(ttf, O_OS2);
+ sal_uInt32 table_size = getTableSize(ttf, O_OS2);
+ if (table && table_size >= 42) {
+ info->weight = GetUInt16(table, OS2_usWeightClass_offset);
+ info->width = GetUInt16(table, OS2_usWidthClass_offset);
+
+ if (table_size >= OS2_V0_length) {
+ info->typoAscender = XUnits(UPEm,GetInt16(table, OS2_typoAscender_offset));
+ info->typoDescender = XUnits(UPEm, GetInt16(table, OS2_typoDescender_offset));
+ info->typoLineGap = XUnits(UPEm, GetInt16(table, OS2_typoLineGap_offset));
+ info->winAscent = XUnits(UPEm, GetUInt16(table, OS2_winAscent_offset));
+ info->winDescent = XUnits(UPEm, GetUInt16(table, OS2_winDescent_offset));
+ /* sanity check; some fonts treat winDescent as signed
+ * violating the standard */
+ if( info->winDescent > 5*UPEm )
+ info->winDescent = XUnits(UPEm, GetInt16(table, OS2_winDescent_offset));
+ }
+ memcpy(info->panose, table + OS2_panose_offset, OS2_panoseNbBytes_offset);
+ info->typeFlags = GetUInt16( table, OS2_fsType_offset );
+ }
+
+ table = getTable(ttf, O_post);
+ if (table && getTableSize(ttf, O_post) >= 12+sizeof(sal_uInt32)) {
+ info->pitch = GetUInt32(table, POST_isFixedPitch_offset);
+ info->italicAngle = GetInt32(table, POST_italicAngle_offset);
+ }
+
+ table = getTable(ttf, O_head); /* 'head' tables is always there */
+ table_size = getTableSize(ttf, O_head);
+ if (table_size >= 46) {
+ info->xMin = XUnits(UPEm, GetInt16(table, HEAD_xMin_offset));
+ info->yMin = XUnits(UPEm, GetInt16(table, HEAD_yMin_offset));
+ info->xMax = XUnits(UPEm, GetInt16(table, HEAD_xMax_offset));
+ info->yMax = XUnits(UPEm, GetInt16(table, HEAD_yMax_offset));
+ info->macStyle = GetUInt16(table, HEAD_macStyle_offset);
+ }
+
+ table = getTable(ttf, O_hhea);
+ table_size = getTableSize(ttf, O_hhea);
+ if (table && table_size >= 10) {
+ info->ascender = XUnits(UPEm, GetInt16(table, HHEA_ascender_offset));
+ info->descender = XUnits(UPEm, GetInt16(table, HHEA_descender_offset));
+ info->linegap = XUnits(UPEm, GetInt16(table, HHEA_lineGap_offset));
+ }
+}
+
+GlyphData *GetTTRawGlyphData(TrueTypeFont *ttf, sal_uInt32 glyphID)
+{
+ const sal_uInt8* glyf = getTable(ttf, O_glyf);
+ const sal_uInt8* hmtx = getTable(ttf, O_hmtx);
+ int n;
+
+ if( glyphID >= ttf->nglyphs )
+ return nullptr;
+
+ /* #127161# check the glyph offsets */
+ sal_uInt32 length = getTableSize( ttf, O_glyf );
+ if( length < ttf->goffsets[ glyphID+1 ] )
+ return nullptr;
+
+ length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID];
+
+ GlyphData* d = static_cast<GlyphData*>(malloc(sizeof(GlyphData))); assert(d != nullptr);
+
+ if (length > 0) {
+ const sal_uInt8* srcptr = glyf + ttf->goffsets[glyphID];
+ const size_t nChunkLen = ((length + 1) & ~1);
+ d->ptr = static_cast<sal_uInt8*>(malloc(nChunkLen)); assert(d->ptr != nullptr);
+ memcpy(d->ptr, srcptr, length);
+ memset(d->ptr + length, 0, nChunkLen - length);
+ d->compflag = (GetInt16( srcptr, 0 ) < 0);
+ } else {
+ d->ptr = nullptr;
+ d->compflag = false;
+ }
+
+ d->glyphID = glyphID;
+ d->nbytes = static_cast<sal_uInt16>((length + 1) & ~1);
+
+ /* now calculate npoints and ncontours */
+ ControlPoint *cp;
+ n = GetTTGlyphPoints(ttf, glyphID, &cp);
+ if (n > 0)
+ {
+ int m = 0;
+ for (int i = 0; i < n; i++)
+ {
+ if (cp[i].flags & 0x8000)
+ m++;
+ }
+ d->npoints = static_cast<sal_uInt16>(n);
+ d->ncontours = static_cast<sal_uInt16>(m);
+ free(cp);
+ } else {
+ d->npoints = 0;
+ d->ncontours = 0;
+ }
+
+ /* get advance width and left sidebearing */
+ if (glyphID < ttf->numberOfHMetrics) {
+ d->aw = GetUInt16(hmtx, 4 * glyphID);
+ d->lsb = GetInt16(hmtx, 4 * glyphID + 2);
+ } else {
+ d->aw = GetUInt16(hmtx, 4 * (ttf->numberOfHMetrics - 1));
+ d->lsb = GetInt16(hmtx + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2);
+ }
+
+ return d;
+}
+
+int GetTTNameRecords(TrueTypeFont const *ttf, NameRecord **nr)
+{
+ const sal_uInt8* table = getTable(ttf, O_name);
+ int nTableSize = getTableSize(ttf, O_name );
+
+ if (nTableSize < 6)
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "O_name table too small.");
+#endif
+ return 0;
+ }
+
+ sal_uInt16 n = GetUInt16(table, 2);
+ int nStrBase = GetUInt16(table, 4);
+ int i;
+
+ *nr = nullptr;
+ if (n == 0) return 0;
+
+ const sal_uInt32 remaining_table_size = nTableSize-6;
+ const sal_uInt32 nMinRecordSize = 12;
+ const sal_uInt32 nMaxRecords = remaining_table_size / nMinRecordSize;
+ if (n > nMaxRecords)
+ {
+ SAL_WARN("vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fname) <<
+ ": " << nMaxRecords << " max possible entries, but " <<
+ n << " claimed, truncating");
+ n = nMaxRecords;
+ }
+
+ NameRecord* rec = static_cast<NameRecord*>(calloc(n, sizeof(NameRecord)));
+ assert(rec);
+
+ for (i = 0; i < n; i++) {
+ int nLargestFixedOffsetPos = 6 + 10 + 12 * i;
+ int nMinSize = nLargestFixedOffsetPos + sizeof(sal_uInt16);
+ if (nMinSize > nTableSize)
+ {
+ SAL_WARN( "vcl.fonts", "Font " << OUString::createFromAscii(ttf->fname) << " claimed to have "
+ << n << " name records, but only space for " << i);
+ n = i;
+ break;
+ }
+
+ rec[i].platformID = GetUInt16(table, 6 + 0 + 12 * i);
+ rec[i].encodingID = GetUInt16(table, 6 + 2 + 12 * i);
+ rec[i].languageID = LanguageType(GetUInt16(table, 6 + 4 + 12 * i));
+ rec[i].nameID = GetUInt16(table, 6 + 6 + 12 * i);
+ rec[i].slen = GetUInt16(table, 6 + 8 + 12 * i);
+ int nStrOffset = GetUInt16(table, nLargestFixedOffsetPos);
+ if (rec[i].slen) {
+ if( nStrBase+nStrOffset+rec[i].slen >= nTableSize ) {
+ rec[i].sptr = nullptr;
+ rec[i].slen = 0;
+ continue;
+ }
+
+ const sal_uInt8* rec_string = table + nStrBase + nStrOffset;
+ // sanity check
+ const sal_uInt8* end_table = ttf->ptr + ttf->fsize;
+ const size_t available_space = rec_string > end_table ? 0 : (end_table - rec_string);
+ if (rec[i].slen <= available_space)
+ {
+ rec[i].sptr = static_cast<sal_uInt8 *>(malloc(rec[i].slen)); assert(rec[i].sptr != nullptr);
+ memcpy(rec[i].sptr, rec_string, rec[i].slen);
+ }
+ else
+ {
+ rec[i].sptr = nullptr;
+ rec[i].slen = 0;
+ }
+ } else {
+ rec[i].sptr = nullptr;
+ }
+ // some fonts have 3.0 names => fix them to 3.1
+ if( (rec[i].platformID == 3) && (rec[i].encodingID == 0) )
+ rec[i].encodingID = 1;
+ }
+
+ *nr = rec;
+ return n;
+}
+
+void DisposeNameRecords(NameRecord* nr, int n)
+{
+ int i;
+ for (i = 0; i < n; i++) {
+ if (nr[i].sptr) free(nr[i].sptr);
+ }
+ free(nr);
+}
+
+template<size_t N> static void
+append(std::bitset<N> & rSet, size_t const nOffset, sal_uInt32 const nValue)
+{
+ for (size_t i = 0; i < 32; ++i)
+ {
+ rSet.set(nOffset + i, (nValue & (1 << i)) != 0);
+ }
+}
+
+bool getTTCoverage(
+ std::optional<std::bitset<UnicodeCoverage::MAX_UC_ENUM>> &rUnicodeRange,
+ std::optional<std::bitset<CodePageCoverage::MAX_CP_ENUM>> &rCodePageRange,
+ const unsigned char* pTable, size_t nLength)
+{
+ bool bRet = false;
+ // parse OS/2 header
+ if (nLength >= OS2_Legacy_length)
+ {
+ rUnicodeRange = std::bitset<UnicodeCoverage::MAX_UC_ENUM>();
+ append(*rUnicodeRange, 0, GetUInt32(pTable, OS2_ulUnicodeRange1_offset));
+ append(*rUnicodeRange, 32, GetUInt32(pTable, OS2_ulUnicodeRange2_offset));
+ append(*rUnicodeRange, 64, GetUInt32(pTable, OS2_ulUnicodeRange3_offset));
+ append(*rUnicodeRange, 96, GetUInt32(pTable, OS2_ulUnicodeRange4_offset));
+ bRet = true;
+ if (nLength >= OS2_V1_length)
+ {
+ rCodePageRange = std::bitset<CodePageCoverage::MAX_CP_ENUM>();
+ append(*rCodePageRange, 0, GetUInt32(pTable, OS2_ulCodePageRange1_offset));
+ append(*rCodePageRange, 32, GetUInt32(pTable, OS2_ulCodePageRange2_offset));
+ }
+ }
+ return bRet;
+}
+
+} // namespace vcl
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/ttcr.cxx b/vcl/source/fontsubset/ttcr.cxx
new file mode 100644
index 000000000..62690a215
--- /dev/null
+++ b/vcl/source/fontsubset/ttcr.cxx
@@ -0,0 +1,1505 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*
+ * TrueTypeCreator method implementation
+ */
+
+#include <iomanip>
+#include <assert.h>
+
+#include <sal/log.hxx>
+
+#include "ttcr.hxx"
+#include "list.h"
+#include <string.h>
+
+namespace vcl
+{
+
+/*
+ * Private Data Types
+ */
+
+ struct TrueTypeCreator {
+ sal_uInt32 tag; /**< TrueType file tag */
+ list tables; /**< List of table tags and pointers */
+ };
+
+namespace {
+
+struct TableEntry {
+ sal_uInt32 tag;
+ sal_uInt32 length;
+ sal_uInt8 *data;
+};
+
+}
+
+/*- Data access macros for data stored in big-endian or little-endian format */
+static sal_Int16 GetInt16( const sal_uInt8* ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+ sal_Int16 t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+ return t;
+}
+
+static sal_uInt16 GetUInt16( const sal_uInt8* ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+ sal_uInt16 t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+ return t;
+}
+
+static void PutInt16(sal_Int16 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static void PutUInt16(sal_uInt16 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static void PutUInt32(sal_uInt32 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 24) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>((val >> 16) & 0xFF);
+ ptr[offset+2] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+3] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static int TableEntryCompareF(const void *l, const void *r)
+{
+ sal_uInt32 const ltag(static_cast<TableEntry const*>(l)->tag);
+ sal_uInt32 const rtag(static_cast<TableEntry const*>(r)->tag);
+ return (ltag == rtag) ? 0 : (ltag < rtag) ? -1 : 1;
+}
+
+static int NameRecordCompareF(const void *l, const void *r)
+{
+ NameRecord const *ll = static_cast<NameRecord const *>(l);
+ NameRecord const *rr = static_cast<NameRecord const *>(r);
+
+ if (ll->platformID != rr->platformID) {
+ return (ll->platformID < rr->platformID) ? -1 : 1;
+ } else if (ll->encodingID != rr->encodingID) {
+ return (ll->encodingID < rr->encodingID) ? -1 : 1;
+ } else if (ll->languageID != rr->languageID) {
+ return (ll->languageID < rr->languageID) ? -1 : 1;
+ } else if (ll->nameID != rr->nameID) {
+ return (ll->nameID < rr->nameID) ? -1 : 1;
+ }
+ return 0;
+}
+
+static sal_uInt32 CheckSum(sal_uInt32 *ptr, sal_uInt32 length)
+{
+ sal_uInt32 sum = 0;
+ sal_uInt32 *endptr = ptr + ((length + 3) & sal_uInt32(~3)) / 4;
+
+ while (ptr < endptr) sum += *ptr++;
+
+ return sum;
+}
+
+static void *smalloc(sal_uInt32 size)
+{
+ void *res = malloc(size);
+ assert(res != nullptr);
+ return res;
+}
+
+static void *scalloc(sal_uInt32 n, sal_uInt32 size)
+{
+ void *res = calloc(n, size);
+ assert(res != nullptr);
+ return res;
+}
+
+/*
+ * Public functions
+ */
+
+void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this)
+{
+ TrueTypeCreator* ptr = static_cast<TrueTypeCreator*>(smalloc(sizeof(TrueTypeCreator)));
+
+ ptr->tables = listNewEmpty();
+ listSetElementDtor(ptr->tables, TrueTypeTableDispose);
+
+ ptr->tag = tag;
+
+ *_this = ptr;
+}
+
+void AddTable(TrueTypeCreator *_this, TrueTypeTable *table)
+{
+ if (table != nullptr) {
+ listAppend(_this->tables, table);
+ }
+}
+
+void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag)
+{
+ if (listCount(_this->tables))
+ {
+ listToFirst(_this->tables);
+ int done = 0;
+ do {
+ if (static_cast<TrueTypeTable *>(listCurrent(_this->tables))->tag == tag)
+ {
+ listRemove(_this->tables);
+ }
+ else
+ {
+ if (listNext(_this->tables))
+ {
+ done = 1;
+ }
+ }
+ } while (!done);
+ }
+}
+
+static void ProcessTables(TrueTypeCreator *);
+
+SFErrCodes StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length)
+{
+ sal_uInt16 searchRange=1, entrySelector=0, rangeShift;
+ sal_uInt32 s, offset, checkSumAdjustment = 0;
+ sal_uInt32 *p;
+ sal_uInt8 *head = nullptr; /* saved pointer to the head table data for checkSumAdjustment calculation */
+
+ if (listIsEmpty(_this->tables)) return SFErrCodes::TtFormat;
+
+ ProcessTables(_this);
+
+ /* ProcessTables() adds 'loca' and 'hmtx' */
+
+ sal_uInt16 numTables = listCount(_this->tables);
+
+ TableEntry* te = static_cast<TableEntry*>(scalloc(numTables, sizeof(TableEntry)));
+ TableEntry* e = te;
+
+ listToFirst(_this->tables);
+ do {
+ GetRawData(static_cast<TrueTypeTable *>(listCurrent(_this->tables)), &e->data, &e->length, &e->tag);
+ ++e;
+ } while (listNext(_this->tables));
+
+ qsort(te, numTables, sizeof(TableEntry), TableEntryCompareF);
+
+ do {
+ searchRange *= 2;
+ entrySelector++;
+ } while (searchRange <= numTables);
+
+ searchRange *= 8;
+ entrySelector--;
+ rangeShift = numTables * 16 - searchRange;
+
+ s = offset = 12 + 16 * numTables;
+
+ for (int i = 0; i < numTables; ++i) {
+ s += (te[i].length + 3) & sal_uInt32(~3);
+ /* if ((te[i].length & 3) != 0) s += (4 - (te[i].length & 3)) & 3; */
+ }
+
+ sal_uInt8* ttf = static_cast<sal_uInt8*>(smalloc(s));
+
+ /* Offset Table */
+ PutUInt32(_this->tag, ttf, 0);
+ PutUInt16(numTables, ttf, 4);
+ PutUInt16(searchRange, ttf, 6);
+ PutUInt16(entrySelector, ttf, 8);
+ PutUInt16(rangeShift, ttf, 10);
+
+ /* Table Directory */
+ for (int i = 0; i < numTables; ++i) {
+ PutUInt32(te[i].tag, ttf + 12, 16 * i);
+ PutUInt32(CheckSum(reinterpret_cast<sal_uInt32 *>(te[i].data), te[i].length), ttf + 12, 16 * i + 4);
+ PutUInt32(offset, ttf + 12, 16 * i + 8);
+ PutUInt32(te[i].length, ttf + 12, 16 * i + 12);
+
+ if (te[i].tag == T_head) {
+ head = ttf + offset;
+ }
+
+ memcpy(ttf+offset, te[i].data, (te[i].length + 3) & sal_uInt32(~3) );
+ offset += (te[i].length + 3) & sal_uInt32(~3);
+ /* if ((te[i].length & 3) != 0) offset += (4 - (te[i].length & 3)) & 3; */
+ }
+
+ free(te);
+
+ p = reinterpret_cast<sal_uInt32 *>(ttf);
+ for (int i = 0; i < static_cast<int>(s) / 4; ++i) checkSumAdjustment += p[i];
+ PutUInt32(0xB1B0AFBA - checkSumAdjustment, head, 8);
+
+ *ptr = ttf;
+ *length = s;
+
+ return SFErrCodes::Ok;
+}
+
+SFErrCodes StreamToFile(TrueTypeCreator *_this, const char* fname)
+{
+ sal_uInt8 *ptr;
+ sal_uInt32 length;
+ SFErrCodes r;
+ FILE* fd;
+
+ if ((r = StreamToMemory(_this, &ptr, &length)) != SFErrCodes::Ok) return r;
+ r = SFErrCodes::BadFile;
+ if (fname)
+ {
+ fd = fopen(fname, "wb");
+ if (fd)
+ {
+ if (fwrite(ptr, 1, length, fd) != length) {
+ r = SFErrCodes::FileIo;
+ } else {
+ r = SFErrCodes::Ok;
+ }
+ fclose(fd);
+ }
+ }
+ free(ptr);
+ return r;
+}
+
+/*
+ * TrueTypeTable private methods
+ */
+
+/* Table data points to
+ * --------------------------------------------
+ * generic tdata_generic struct
+ * 'head' HEAD_Length bytes of memory
+ * 'hhea' HHEA_Length bytes of memory
+ * 'loca' tdata_loca struct
+ * 'maxp' MAXP_Version1Length bytes of memory
+ * 'glyf' list of GlyphData structs (defined in sft.h)
+ * 'name' list of NameRecord structs (defined in sft.h)
+ * 'post' tdata_post struct
+ *
+ */
+
+#define CMAP_SUBTABLE_INIT 10
+#define CMAP_SUBTABLE_INCR 10
+#define CMAP_PAIR_INIT 500
+#define CMAP_PAIR_INCR 500
+
+namespace {
+
+struct CmapSubTable {
+ sal_uInt32 id; /* subtable ID (platform/encoding ID) */
+ sal_uInt32 n; /* number of used translation pairs */
+ sal_uInt32 m; /* number of allocated translation pairs */
+ sal_uInt32 *xc; /* character array */
+ sal_uInt32 *xg; /* glyph array */
+};
+
+struct table_cmap {
+ sal_uInt32 n; /* number of used CMAP sub-tables */
+ sal_uInt32 m; /* number of allocated CMAP sub-tables */
+ CmapSubTable *s; /* sorted array of sub-tables */
+};
+
+struct tdata_generic {
+ sal_uInt32 tag;
+ sal_uInt32 nbytes;
+ sal_uInt8 *ptr;
+};
+
+struct tdata_loca {
+ sal_uInt32 nbytes; /* number of bytes in loca table */
+ sal_uInt8 *ptr; /* pointer to the data */
+};
+
+struct tdata_post {
+ sal_uInt32 format;
+ sal_uInt32 italicAngle;
+ sal_Int16 underlinePosition;
+ sal_Int16 underlineThickness;
+ sal_uInt32 isFixedPitch;
+ void *ptr; /* format-specific pointer */
+};
+
+}
+
+/* allocate memory for a TT table */
+static sal_uInt8 *ttmalloc(sal_uInt32 nbytes)
+{
+ sal_uInt32 n;
+
+ n = (nbytes + 3) & sal_uInt32(~3);
+ sal_uInt8* res = static_cast<sal_uInt8*>(calloc(n, 1));
+ assert(res != nullptr);
+
+ return res;
+}
+
+static void FreeGlyphData(void *ptr)
+{
+ GlyphData *p = static_cast<GlyphData *>(ptr);
+ if (p->ptr) free(p->ptr);
+ free(p);
+}
+
+static void TrueTypeTableDispose_generic(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) {
+ tdata_generic *pdata = static_cast<tdata_generic *>(_this->data);
+ if (pdata->nbytes) free(pdata->ptr);
+ free(_this->data);
+ }
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_head(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) free(_this->data);
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_hhea(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) free(_this->data);
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_loca(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) {
+ tdata_loca *p = static_cast<tdata_loca *>(_this->data);
+ if (p->ptr) free(p->ptr);
+ free(_this->data);
+ }
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_maxp(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) free(_this->data);
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_glyf(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) listDispose(static_cast<list>(_this->data));
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_cmap(TrueTypeTable *_this)
+{
+ if (_this) {
+ table_cmap *t = static_cast<table_cmap *>(_this->data);
+ if (t) {
+ CmapSubTable *s = t->s;
+ if (s) {
+ for (sal_uInt32 i = 0; i < t->m; i++) {
+ if (s[i].xc) free(s[i].xc);
+ if (s[i].xg) free(s[i].xg);
+ }
+ free(s);
+ }
+ free(t);
+ }
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_name(TrueTypeTable *_this)
+{
+ if (_this) {
+ if (_this->data) listDispose(static_cast<list>(_this->data));
+ free(_this);
+ }
+}
+
+static void TrueTypeTableDispose_post(TrueTypeTable *_this)
+{
+ if (_this) {
+ tdata_post *p = static_cast<tdata_post *>(_this->data);
+ if (p) {
+ if (p->format == 0x00030000) {
+ /* do nothing */
+ } else {
+ SAL_WARN("vcl.fonts", "Unsupported format of a 'post' table: "
+ << std::setfill('0')
+ << std::setw(8)
+ << std::hex
+ << std::uppercase
+ << static_cast<int>(p->format) << ".");
+ }
+ free(p);
+ }
+ free(_this);
+ }
+}
+
+/* destructor vtable */
+
+static struct {
+ sal_uInt32 tag;
+ void (*f)(TrueTypeTable *);
+} const vtable1[] =
+{
+ {0, TrueTypeTableDispose_generic},
+ {T_head, TrueTypeTableDispose_head},
+ {T_hhea, TrueTypeTableDispose_hhea},
+ {T_loca, TrueTypeTableDispose_loca},
+ {T_maxp, TrueTypeTableDispose_maxp},
+ {T_glyf, TrueTypeTableDispose_glyf},
+ {T_cmap, TrueTypeTableDispose_cmap},
+ {T_name, TrueTypeTableDispose_name},
+ {T_post, TrueTypeTableDispose_post}
+
+};
+
+static int GetRawData_generic(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ assert(_this != nullptr);
+ assert(_this->data != nullptr);
+
+ *ptr = static_cast<tdata_generic *>(_this->data)->ptr;
+ *len = static_cast<tdata_generic *>(_this->data)->nbytes;
+ *tag = static_cast<tdata_generic *>(_this->data)->tag;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_head(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ *len = HEAD_Length;
+ *ptr = static_cast<sal_uInt8 *>(_this->data);
+ *tag = T_head;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_hhea(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ *len = HHEA_Length;
+ *ptr = static_cast<sal_uInt8 *>(_this->data);
+ *tag = T_hhea;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_loca(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ tdata_loca *p;
+
+ assert(_this->data != nullptr);
+
+ p = static_cast<tdata_loca *>(_this->data);
+
+ if (p->nbytes == 0) return TTCR_ZEROGLYPHS;
+
+ *ptr = p->ptr;
+ *len = p->nbytes;
+ *tag = T_loca;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_maxp(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ *len = MAXP_Version1Length;
+ *ptr = static_cast<sal_uInt8 *>(_this->data);
+ *tag = T_maxp;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_glyf(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ sal_uInt32 n, nbytes = 0;
+ list l = static_cast<list>(_this->data);
+ /* sal_uInt16 curID = 0; */ /* to check if glyph IDs are sequential and start from zero */
+ sal_uInt8 *p;
+
+ *ptr = nullptr;
+ *len = 0;
+ *tag = 0;
+
+ if (listCount(l) == 0) return TTCR_ZEROGLYPHS;
+
+ listToFirst(l);
+ do {
+ /* if (((GlyphData *) listCurrent(l))->glyphID != curID++) return TTCR_GLYPHSEQ; */
+ nbytes += static_cast<GlyphData *>(listCurrent(l))->nbytes;
+ } while (listNext(l));
+
+ p = _this->rawdata = ttmalloc(nbytes);
+
+ listToFirst(l);
+ do {
+ n = static_cast<GlyphData *>(listCurrent(l))->nbytes;
+ if (n != 0) {
+ memcpy(p, static_cast<GlyphData *>(listCurrent(l))->ptr, n);
+ p += n;
+ }
+ } while (listNext(l));
+
+ *len = nbytes;
+ *ptr = _this->rawdata;
+ *tag = T_glyf;
+
+ return TTCR_OK;
+}
+
+/* cmap packers */
+static sal_uInt8 *PackCmapType0(CmapSubTable const *s, sal_uInt32 *length)
+{
+ sal_uInt8* ptr = static_cast<sal_uInt8*>(smalloc(262));
+ sal_uInt8 *p = ptr + 6;
+ sal_uInt32 i, j;
+ sal_uInt16 g;
+
+ PutUInt16(0, ptr, 0);
+ PutUInt16(262, ptr, 2);
+ PutUInt16(0, ptr, 4);
+
+ for (i = 0; i < 256; i++) {
+ g = 0;
+ for (j = 0; j < s->n; j++) {
+ if (s->xc[j] == i) {
+ g = static_cast<sal_uInt16>(s->xg[j]);
+ }
+ }
+ p[i] = static_cast<sal_uInt8>(g);
+ }
+ *length = 262;
+ return ptr;
+}
+
+static sal_uInt8 *PackCmapType6(CmapSubTable const *s, sal_uInt32 *length)
+{
+ sal_uInt8* ptr = static_cast<sal_uInt8*>(smalloc(s->n*2 + 10));
+ sal_uInt8 *p = ptr + 10;
+ sal_uInt32 i, j;
+ sal_uInt16 g;
+
+ PutUInt16(6, ptr, 0);
+ PutUInt16(static_cast<sal_uInt16>(s->n*2+10), ptr, 2);
+ PutUInt16(0, ptr, 4);
+ PutUInt16(0, ptr, 6);
+ PutUInt16(static_cast<sal_uInt16>(s->n), ptr, 8 );
+
+ for (i = 0; i < s->n; i++) {
+ g = 0;
+ for (j = 0; j < s->n; j++) {
+ if (s->xc[j] == i) {
+ g = static_cast<sal_uInt16>(s->xg[j]);
+ }
+ }
+ PutUInt16( g, p, 2*i );
+ }
+ *length = s->n*2+10;
+ return ptr;
+}
+
+/* XXX it only handles Format 0 encoding tables */
+static sal_uInt8 *PackCmap(CmapSubTable const *s, sal_uInt32 *length)
+{
+ if( s->xg[s->n-1] > 0xff )
+ return PackCmapType6(s, length);
+ else
+ return PackCmapType0(s, length);
+}
+
+static int GetRawData_cmap(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ table_cmap *t;
+ sal_uInt32 i;
+ sal_uInt32 tlen = 0;
+ sal_uInt32 l;
+ sal_uInt32 cmapsize;
+ sal_uInt8 *cmap;
+ sal_uInt32 coffset;
+
+ assert(_this != nullptr);
+ t = static_cast<table_cmap *>(_this->data);
+ assert(t != nullptr);
+ assert(t->n != 0);
+
+ sal_uInt8** subtables = static_cast<sal_uInt8**>(scalloc(t->n, sizeof(sal_uInt8 *)));
+ sal_uInt32* sizes = static_cast<sal_uInt32*>(scalloc(t->n, sizeof(sal_uInt32)));
+
+ for (i = 0; i < t->n; i++) {
+ subtables[i] = PackCmap(t->s+i, &l);
+ sizes[i] = l;
+ tlen += l;
+ }
+
+ cmapsize = tlen + 4 + 8 * t->n;
+ _this->rawdata = cmap = ttmalloc(cmapsize);
+
+ PutUInt16(0, cmap, 0);
+ PutUInt16(static_cast<sal_uInt16>(t->n), cmap, 2);
+ coffset = 4 + t->n * 8;
+
+ for (i = 0; i < t->n; i++) {
+ PutUInt16(static_cast<sal_uInt16>(t->s[i].id >> 16), cmap + 4, i * 8);
+ PutUInt16(static_cast<sal_uInt16>(t->s[i].id & 0xFF), cmap + 4, 2 + i * 8);
+ PutUInt32(coffset, cmap + 4, 4 + i * 8);
+ memcpy(cmap + coffset, subtables[i], sizes[i]);
+ free(subtables[i]);
+ coffset += sizes[i];
+ }
+
+ free(subtables);
+ free(sizes);
+
+ *ptr = cmap;
+ *len = cmapsize;
+ *tag = T_cmap;
+
+ return TTCR_OK;
+}
+
+static int GetRawData_name(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ list l;
+ sal_Int16 i=0, n; /* number of Name Records */
+ int stringLen = 0;
+ sal_uInt8 *p1, *p2;
+
+ *ptr = nullptr;
+ *len = 0;
+ *tag = 0;
+
+ assert(_this != nullptr);
+ l = static_cast<list>(_this->data);
+ assert(l != nullptr);
+
+ if ((n = static_cast<sal_Int16>(listCount(l))) == 0) return TTCR_NONAMES;
+
+ NameRecord* nr = static_cast<NameRecord*>(scalloc(n, sizeof(NameRecord)));
+
+ listToFirst(l);
+
+ do {
+ memcpy(nr+i, listCurrent(l), sizeof(NameRecord));
+ stringLen += nr[i].slen;
+ i++;
+ } while (listNext(l));
+
+ if (stringLen > 65535) {
+ free(nr);
+ return TTCR_NAMETOOLONG;
+ }
+
+ qsort(nr, n, sizeof(NameRecord), NameRecordCompareF);
+
+ int nameLen = stringLen + 12 * n + 6;
+ sal_uInt8* name = ttmalloc(nameLen);
+
+ PutUInt16(0, name, 0);
+ PutUInt16(n, name, 2);
+ PutUInt16(static_cast<sal_uInt16>(6 + 12 * n), name, 4);
+
+ p1 = name + 6;
+ p2 = p1 + 12 * n;
+
+ for (i = 0; i < n; i++) {
+ PutUInt16(nr[i].platformID, p1, 0);
+ PutUInt16(nr[i].encodingID, p1, 2);
+ PutUInt16(static_cast<sal_uInt16>(nr[i].languageID), p1, 4);
+ PutUInt16(nr[i].nameID, p1, 6);
+ PutUInt16(nr[i].slen, p1, 8);
+ PutUInt16(static_cast<sal_uInt16>(p2 - (name + 6 + 12 * n)), p1, 10);
+ if (nr[i].slen) {
+ memcpy(p2, nr[i].sptr, nr[i].slen);
+ }
+ /* {int j; for(j=0; j<nr[i].slen; j++) printf("%c", nr[i].sptr[j]); printf("\n"); }; */
+ p2 += nr[i].slen;
+ p1 += 12;
+ }
+
+ free(nr);
+ _this->rawdata = name;
+
+ *ptr = name;
+ *len = static_cast<sal_uInt16>(nameLen);
+ *tag = T_name;
+
+ /*{int j; for(j=0; j<nameLen; j++) printf("%c", name[j]); }; */
+
+ return TTCR_OK;
+}
+
+static int GetRawData_post(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ tdata_post *p = static_cast<tdata_post *>(_this->data);
+ sal_uInt8 *post = nullptr;
+ sal_uInt32 postLen = 0;
+ int ret;
+
+ if (_this->rawdata) free(_this->rawdata);
+
+ if (p->format == 0x00030000) {
+ postLen = 32;
+ post = ttmalloc(postLen);
+ PutUInt32(0x00030000, post, 0);
+ PutUInt32(p->italicAngle, post, 4);
+ PutUInt16(p->underlinePosition, post, 8);
+ PutUInt16(p->underlineThickness, post, 10);
+ PutUInt16(static_cast<sal_uInt16>(p->isFixedPitch), post, 12);
+ ret = TTCR_OK;
+ } else {
+ SAL_WARN("vcl.fonts", "Unrecognized format of a post table: "
+ << std::setfill('0')
+ << std::setw(8)
+ << std::hex
+ << std::uppercase
+ << static_cast<int>(p->format) << ".");
+ ret = TTCR_POSTFORMAT;
+ }
+
+ *ptr = _this->rawdata = post;
+ *len = postLen;
+ *tag = T_post;
+
+ return ret;
+}
+
+static struct {
+ sal_uInt32 tag;
+ int (*f)(TrueTypeTable *, sal_uInt8 **, sal_uInt32 *, sal_uInt32 *);
+} const vtable2[] =
+{
+ {0, GetRawData_generic},
+ {T_head, GetRawData_head},
+ {T_hhea, GetRawData_hhea},
+ {T_loca, GetRawData_loca},
+ {T_maxp, GetRawData_maxp},
+ {T_glyf, GetRawData_glyf},
+ {T_cmap, GetRawData_cmap},
+ {T_name, GetRawData_name},
+ {T_post, GetRawData_post}
+
+};
+
+/*
+ * TrueTypeTable public methods
+ */
+
+/* Note: Type42 fonts only need these tables:
+ * head, hhea, loca, maxp, cvt, prep, glyf, hmtx, fpgm
+ *
+ * Microsoft required tables
+ * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post, OS/2
+ *
+ * Apple required tables
+ * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post
+ *
+ */
+
+TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ const sal_uInt8* ptr)
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ tdata_generic* pdata = static_cast<tdata_generic*>(smalloc(sizeof(tdata_generic)));
+ pdata->nbytes = nbytes;
+ pdata->tag = tag;
+ if (nbytes) {
+ pdata->ptr = ttmalloc(nbytes);
+ memcpy(pdata->ptr, ptr, nbytes);
+ } else {
+ pdata->ptr = nullptr;
+ }
+
+ table->tag = 0;
+ table->data = pdata;
+ table->rawdata = nullptr;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision,
+ sal_uInt16 flags,
+ sal_uInt16 unitsPerEm,
+ const sal_uInt8* created,
+ sal_uInt16 macStyle,
+ sal_uInt16 lowestRecPPEM,
+ sal_Int16 fontDirectionHint)
+{
+ assert(created != nullptr);
+
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ sal_uInt8* ptr = ttmalloc(HEAD_Length);
+
+ PutUInt32(0x00010000, ptr, 0); /* version */
+ PutUInt32(fontRevision, ptr, 4);
+ PutUInt32(0x5F0F3CF5, ptr, 12); /* magic number */
+ PutUInt16(flags, ptr, 16);
+ PutUInt16(unitsPerEm, ptr, 18);
+ memcpy(ptr+20, created, 8); /* Created Long Date */
+ memset(ptr+28, 0, 8); /* Modified Long Date */
+ PutUInt16(macStyle, ptr, 44);
+ PutUInt16(lowestRecPPEM, ptr, 46);
+ PutUInt16(fontDirectionHint, ptr, 48);
+ PutUInt16(0, ptr, 52); /* glyph data format: 0 */
+
+ table->data = static_cast<void *>(ptr);
+ table->tag = T_head;
+ table->rawdata = nullptr;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender,
+ sal_Int16 descender,
+ sal_Int16 linegap,
+ sal_Int16 caretSlopeRise,
+ sal_Int16 caretSlopeRun)
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ sal_uInt8* ptr = ttmalloc(HHEA_Length);
+
+ PutUInt32(0x00010000, ptr, 0); /* version */
+ PutUInt16(ascender, ptr, 4);
+ PutUInt16(descender, ptr, 6);
+ PutUInt16(linegap, ptr, 8);
+ PutUInt16(caretSlopeRise, ptr, 18);
+ PutUInt16(caretSlopeRun, ptr, 20);
+ PutUInt16(0, ptr, 22); /* reserved 1 */
+ PutUInt16(0, ptr, 24); /* reserved 2 */
+ PutUInt16(0, ptr, 26); /* reserved 3 */
+ PutUInt16(0, ptr, 28); /* reserved 4 */
+ PutUInt16(0, ptr, 30); /* reserved 5 */
+ PutUInt16(0, ptr, 32); /* metricDataFormat */
+
+ table->data = static_cast<void *>(ptr);
+ table->tag = T_hhea;
+ table->rawdata = nullptr;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_loca()
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ table->data = smalloc(sizeof(tdata_loca));
+
+ static_cast<tdata_loca *>(table->data)->nbytes = 0;
+ static_cast<tdata_loca *>(table->data)->ptr = nullptr;
+
+ table->tag = T_loca;
+ table->rawdata = nullptr;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_maxp( const sal_uInt8* maxp, int size)
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ table->data = ttmalloc(MAXP_Version1Length);
+
+ if (maxp && size == MAXP_Version1Length) {
+ memcpy(table->data, maxp, MAXP_Version1Length);
+ }
+
+ table->tag = T_maxp;
+ table->rawdata = nullptr;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_glyf()
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ list l = listNewEmpty();
+
+ assert(l != nullptr);
+
+ listSetElementDtor(l, FreeGlyphData);
+
+ table->data = l;
+ table->rawdata = nullptr;
+ table->tag = T_glyf;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_cmap()
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ table_cmap* cmap = static_cast<table_cmap*>(smalloc(sizeof(table_cmap)));
+
+ cmap->n = 0;
+ cmap->m = CMAP_SUBTABLE_INIT;
+ cmap->s = static_cast<CmapSubTable *>(scalloc(CMAP_SUBTABLE_INIT, sizeof(CmapSubTable)));
+
+ table->data = cmap;
+
+ table->rawdata = nullptr;
+ table->tag = T_cmap;
+
+ return table;
+}
+
+static void DisposeNameRecord(void *ptr)
+{
+ if (ptr != nullptr) {
+ NameRecord *nr = static_cast<NameRecord *>(ptr);
+ if (nr->sptr) free(nr->sptr);
+ free(ptr);
+ }
+}
+
+static NameRecord* NameRecordNewCopy(NameRecord const *nr)
+{
+ NameRecord* p = static_cast<NameRecord*>(smalloc(sizeof(NameRecord)));
+
+ memcpy(p, nr, sizeof(NameRecord));
+
+ if (p->slen) {
+ p->sptr = static_cast<sal_uInt8*>(smalloc(p->slen));
+ memcpy(p->sptr, nr->sptr, p->slen);
+ }
+
+ return p;
+}
+
+TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord const *nr)
+{
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ list l = listNewEmpty();
+
+ assert(l != nullptr);
+
+ listSetElementDtor(l, DisposeNameRecord);
+
+ if (n != 0) {
+ int i;
+ for (i = 0; i < n; i++) {
+ listAppend(l, NameRecordNewCopy(nr+i));
+ }
+ }
+
+ table->data = l;
+ table->rawdata = nullptr;
+ table->tag = T_name;
+
+ return table;
+}
+
+TrueTypeTable *TrueTypeTableNew_post(sal_Int32 format,
+ sal_Int32 italicAngle,
+ sal_Int16 underlinePosition,
+ sal_Int16 underlineThickness,
+ sal_uInt32 isFixedPitch)
+{
+ assert(format == 0x00030000); /* Only format 3.0 is supported at this time */
+ TrueTypeTable* table = static_cast<TrueTypeTable*>(smalloc(sizeof(TrueTypeTable)));
+ tdata_post* post = static_cast<tdata_post*>(smalloc(sizeof(tdata_post)));
+
+ post->format = format;
+ post->italicAngle = italicAngle;
+ post->underlinePosition = underlinePosition;
+ post->underlineThickness = underlineThickness;
+ post->isFixedPitch = isFixedPitch;
+ post->ptr = nullptr;
+
+ table->data = post;
+ table->rawdata = nullptr;
+ table->tag = T_post;
+
+ return table;
+}
+
+int GetRawData(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag)
+{
+ /* XXX do a binary search */
+ assert(_this != nullptr);
+ assert(ptr != nullptr);
+ assert(len != nullptr);
+ assert(tag != nullptr);
+
+ *ptr = nullptr; *len = 0; *tag = 0;
+
+ if (_this->rawdata) {
+ free(_this->rawdata);
+ _this->rawdata = nullptr;
+ }
+
+ for(size_t i=0; i < SAL_N_ELEMENTS(vtable2); i++) {
+ if (_this->tag == vtable2[i].tag) {
+ return vtable2[i].f(_this, ptr, len, tag);
+ }
+ }
+
+ assert(!"Unknown TrueType table.");
+ return TTCR_UNKNOWN;
+}
+
+void cmapAdd(TrueTypeTable *table, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g)
+{
+ sal_uInt32 i, found;
+ table_cmap *t;
+ CmapSubTable *s;
+
+ assert(table != nullptr);
+ assert(table->tag == T_cmap);
+ t = static_cast<table_cmap *>(table->data); assert(t != nullptr);
+ s = t->s; assert(s != nullptr);
+
+ found = 0;
+
+ for (i = 0; i < t->n; i++) {
+ if (s[i].id == id) {
+ found = 1;
+ break;
+ }
+ }
+
+ if (!found) {
+ if (t->n == t->m) {
+ CmapSubTable* tmp = static_cast<CmapSubTable*>(scalloc(t->m + CMAP_SUBTABLE_INCR, sizeof(CmapSubTable)));
+ memcpy(tmp, s, sizeof(CmapSubTable) * t->m);
+ t->m += CMAP_SUBTABLE_INCR;
+ free(s);
+ s = tmp;
+ t->s = s;
+ }
+
+ for (i = 0; i < t->n; i++) {
+ if (s[i].id > id) break;
+ }
+
+ if (i < t->n) {
+ memmove(s+i+1, s+i, t->n-i);
+ }
+
+ t->n++;
+
+ s[i].id = id;
+ s[i].n = 0;
+ s[i].m = CMAP_PAIR_INIT;
+ s[i].xc = static_cast<sal_uInt32*>(scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)));
+ s[i].xg = static_cast<sal_uInt32*>(scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)));
+ }
+
+ if (s[i].n == s[i].m) {
+ sal_uInt32* tmp1 = static_cast<sal_uInt32*>(scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)));
+ sal_uInt32* tmp2 = static_cast<sal_uInt32*>(scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)));
+ assert(tmp1 != nullptr);
+ assert(tmp2 != nullptr);
+ memcpy(tmp1, s[i].xc, sizeof(sal_uInt32) * s[i].m);
+ memcpy(tmp2, s[i].xg, sizeof(sal_uInt32) * s[i].m);
+ s[i].m += CMAP_PAIR_INCR;
+ free(s[i].xc);
+ free(s[i].xg);
+ s[i].xc = tmp1;
+ s[i].xg = tmp2;
+ }
+
+ s[i].xc[s[i].n] = c;
+ s[i].xg[s[i].n] = g;
+ s[i].n++;
+}
+
+sal_uInt32 glyfAdd(TrueTypeTable *table, GlyphData *glyphdata, TrueTypeFont *fnt)
+{
+ list l;
+ sal_uInt32 currentID;
+ int ret, n, ncomponents;
+
+ assert(table != nullptr);
+ assert(table->tag == T_glyf);
+
+ if (!glyphdata) return sal_uInt32(~0);
+
+ std::vector< sal_uInt32 > glyphlist;
+
+ ncomponents = GetTTGlyphComponents(fnt, glyphdata->glyphID, glyphlist);
+
+ l = static_cast<list>(table->data);
+ if (listCount(l) > 0) {
+ listToLast(l);
+ ret = n = static_cast<GlyphData *>(listCurrent(l))->newID + 1;
+ } else {
+ ret = n = 0;
+ }
+ glyphdata->newID = n++;
+ listAppend(l, glyphdata);
+
+ if (ncomponents > 1 && glyphlist.size() > 1 )
+ {
+ std::vector< sal_uInt32 >::const_iterator it = glyphlist.begin();
+ ++it;
+ /* glyphData->glyphID is always the first glyph on the list */
+ do
+ {
+ int found = 0;
+ currentID = *it;
+ /* XXX expensive! should be rewritten with sorted arrays! */
+ listToFirst(l);
+ do {
+ if (static_cast<GlyphData *>(listCurrent(l))->glyphID == currentID) {
+ found = 1;
+ break;
+ }
+ } while (listNext(l));
+
+ if (!found) {
+ GlyphData *gd = GetTTRawGlyphData(fnt, currentID);
+ gd->newID = n++;
+ listAppend(l, gd);
+ }
+ } while( ++it != glyphlist.end() );
+ }
+
+ return ret;
+}
+
+sal_uInt32 glyfCount(const TrueTypeTable *table)
+{
+ assert(table != nullptr);
+ assert(table->tag == T_glyf);
+ return listCount(static_cast<list>(table->data));
+}
+
+static TrueTypeTable *FindTable(TrueTypeCreator *tt, sal_uInt32 tag)
+{
+ if (listIsEmpty(tt->tables)) return nullptr;
+
+ listToFirst(tt->tables);
+
+ do {
+ if (static_cast<TrueTypeTable *>(listCurrent(tt->tables))->tag == tag) {
+ return static_cast<TrueTypeTable*>(listCurrent(tt->tables));
+ }
+ } while (listNext(tt->tables));
+
+ return nullptr;
+}
+
+/* This function processes all the tables and synchronizes them before creating
+ * the output TrueType stream.
+ *
+ * *** It adds two TrueType tables to the font: 'loca' and 'hmtx' ***
+ *
+ * It does:
+ *
+ * - Re-numbers glyph IDs and creates 'glyf', 'loca', and 'hmtx' tables.
+ * - Calculates xMin, yMin, xMax, and yMax and stores values in 'head' table.
+ * - Stores indexToLocFormat in 'head'
+ * - updates 'maxp' table
+ * - Calculates advanceWidthMax, minLSB, minRSB, xMaxExtent and numberOfHMetrics
+ * in 'hhea' table
+ *
+ */
+static void ProcessTables(TrueTypeCreator *tt)
+{
+ TrueTypeTable *glyf, *loca, *head, *maxp, *hhea;
+ list glyphlist;
+ sal_uInt32 nGlyphs, locaLen = 0, glyfLen = 0;
+ sal_Int16 xMin = 0, yMin = 0, xMax = 0, yMax = 0;
+ sal_uInt32 i = 0;
+ sal_Int16 indexToLocFormat;
+ sal_uInt8 *hmtxPtr, *hheaPtr;
+ sal_uInt32 hmtxSize;
+ sal_uInt8 *p1, *p2;
+ sal_uInt16 maxPoints = 0, maxContours = 0, maxCompositePoints = 0, maxCompositeContours = 0;
+ int nlsb = 0;
+ sal_uInt32 *gid; /* array of old glyphIDs */
+
+ glyf = FindTable(tt, T_glyf);
+ glyphlist = static_cast<list>(glyf->data);
+ nGlyphs = listCount(glyphlist);
+ assert(nGlyphs != 0);
+ gid = static_cast<sal_uInt32*>(scalloc(nGlyphs, sizeof(sal_uInt32)));
+
+ RemoveTable(tt, T_loca);
+ RemoveTable(tt, T_hmtx);
+
+ /* XXX Need to make sure that composite glyphs do not break during glyph renumbering */
+
+ listToFirst(glyphlist);
+ do {
+ GlyphData *gd = static_cast<GlyphData *>(listCurrent(glyphlist));
+ sal_Int16 z;
+ glyfLen += gd->nbytes;
+ /* XXX if (gd->nbytes & 1) glyfLen++; */
+
+ assert(gd->newID == i);
+ gid[i++] = gd->glyphID;
+ /* gd->glyphID = i++; */
+
+ /* printf("IDs: %d %d.\n", gd->glyphID, gd->newID); */
+
+ if (gd->nbytes != 0) {
+ z = GetInt16(gd->ptr, 2);
+ if (z < xMin) xMin = z;
+
+ z = GetInt16(gd->ptr, 4);
+ if (z < yMin) yMin = z;
+
+ z = GetInt16(gd->ptr, 6);
+ if (z > xMax) xMax = z;
+
+ z = GetInt16(gd->ptr, 8);
+ if (z > yMax) yMax = z;
+ }
+
+ if (!gd->compflag) { /* non-composite glyph */
+ if (gd->npoints > maxPoints) maxPoints = gd->npoints;
+ if (gd->ncontours > maxContours) maxContours = gd->ncontours;
+ } else { /* composite glyph */
+ if (gd->npoints > maxCompositePoints) maxCompositePoints = gd->npoints;
+ if (gd->ncontours > maxCompositeContours) maxCompositeContours = gd->ncontours;
+ }
+
+ } while (listNext(glyphlist));
+
+ indexToLocFormat = (glyfLen / 2 > 0xFFFF) ? 1 : 0;
+ locaLen = indexToLocFormat ? (nGlyphs + 1) << 2 : (nGlyphs + 1) << 1;
+
+ sal_uInt8* glyfPtr = ttmalloc(glyfLen);
+ sal_uInt8* locaPtr = ttmalloc(locaLen);
+ TTSimpleGlyphMetrics* met = static_cast<TTSimpleGlyphMetrics*>(scalloc(nGlyphs, sizeof(TTSimpleGlyphMetrics)));
+ i = 0;
+
+ listToFirst(glyphlist);
+ p1 = glyfPtr;
+ p2 = locaPtr;
+ do {
+ GlyphData *gd = static_cast<GlyphData *>(listCurrent(glyphlist));
+
+ if (gd->compflag) { /* re-number all components */
+ sal_uInt16 flags, index;
+ sal_uInt8 *ptr = gd->ptr + 10;
+ do {
+ sal_uInt32 j;
+ flags = GetUInt16(ptr, 0);
+ index = GetUInt16(ptr, 2);
+ /* XXX use the sorted array of old to new glyphID mapping and do a binary search */
+ for (j = 0; j < nGlyphs; j++) {
+ if (gid[j] == index) {
+ break;
+ }
+ }
+ /* printf("X: %d -> %d.\n", index, j); */
+
+ PutUInt16(static_cast<sal_uInt16>(j), ptr, 2);
+
+ ptr += 4;
+
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ ptr += 4;
+ } else {
+ ptr += 2;
+ }
+
+ if (flags & WE_HAVE_A_SCALE) {
+ ptr += 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ ptr += 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ ptr += 8;
+ }
+ } while (flags & MORE_COMPONENTS);
+ }
+
+ if (gd->nbytes != 0) {
+ memcpy(p1, gd->ptr, gd->nbytes);
+ }
+ if (indexToLocFormat == 1) {
+ PutUInt32(p1 - glyfPtr, p2, 0);
+ p2 += 4;
+ } else {
+ PutUInt16(static_cast<sal_uInt16>((p1 - glyfPtr) >> 1), p2, 0);
+ p2 += 2;
+ }
+ p1 += gd->nbytes;
+
+ /* fill the array of metrics */
+ met[i].adv = gd->aw;
+ met[i].sb = gd->lsb;
+ i++;
+ } while (listNext(glyphlist));
+
+ free(gid);
+
+ if (indexToLocFormat == 1) {
+ PutUInt32(p1 - glyfPtr, p2, 0);
+ } else {
+ PutUInt16(static_cast<sal_uInt16>((p1 - glyfPtr) >> 1), p2, 0);
+ }
+
+ glyf->rawdata = glyfPtr;
+
+ loca = TrueTypeTableNew_loca(); assert(loca != nullptr);
+ static_cast<tdata_loca *>(loca->data)->ptr = locaPtr;
+ static_cast<tdata_loca *>(loca->data)->nbytes = locaLen;
+
+ AddTable(tt, loca);
+
+ head = FindTable(tt, T_head);
+ sal_uInt8* const pHeadData = static_cast<sal_uInt8*>(head->data);
+ PutInt16(xMin, pHeadData, HEAD_xMin_offset);
+ PutInt16(yMin, pHeadData, HEAD_yMin_offset);
+ PutInt16(xMax, pHeadData, HEAD_xMax_offset);
+ PutInt16(yMax, pHeadData, HEAD_yMax_offset);
+ PutInt16(indexToLocFormat, pHeadData, HEAD_indexToLocFormat_offset);
+
+ maxp = FindTable(tt, T_maxp);
+
+ sal_uInt8* const pMaxpData = static_cast<sal_uInt8*>(maxp->data);
+ PutUInt16(static_cast<sal_uInt16>(nGlyphs), pMaxpData, MAXP_numGlyphs_offset);
+ PutUInt16(maxPoints, pMaxpData, MAXP_maxPoints_offset);
+ PutUInt16(maxContours, pMaxpData, MAXP_maxContours_offset);
+ PutUInt16(maxCompositePoints, pMaxpData, MAXP_maxCompositePoints_offset);
+ PutUInt16(maxCompositeContours, pMaxpData, MAXP_maxCompositeContours_offset);
+
+ /*
+ * Generate an htmx table and update hhea table
+ */
+ hhea = FindTable(tt, T_hhea); assert(hhea != nullptr);
+ hheaPtr = static_cast<sal_uInt8 *>(hhea->data);
+ if (nGlyphs > 2) {
+ for (i = nGlyphs - 1; i > 0; i--) {
+ if (met[i].adv != met[i-1].adv) break;
+ }
+ nlsb = nGlyphs - 1 - i;
+ }
+ hmtxSize = (nGlyphs - nlsb) * 4 + nlsb * 2;
+ hmtxPtr = ttmalloc(hmtxSize);
+ p1 = hmtxPtr;
+
+ for (i = 0; i < nGlyphs; i++) {
+ if (i < nGlyphs - nlsb) {
+ PutUInt16(met[i].adv, p1, 0);
+ PutUInt16(met[i].sb, p1, 2);
+ p1 += 4;
+ } else {
+ PutUInt16(met[i].sb, p1, 0);
+ p1 += 2;
+ }
+ }
+
+ AddTable(tt, TrueTypeTableNew(T_hmtx, hmtxSize, hmtxPtr));
+ PutUInt16(static_cast<sal_uInt16>(nGlyphs - nlsb), hheaPtr, 34);
+ free(hmtxPtr);
+ free(met);
+}
+
+} // namespace vcl
+
+extern "C"
+{
+ /**
+ * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it.
+ */
+ void TrueTypeCreatorDispose(vcl::TrueTypeCreator *_this)
+ {
+ listDispose(_this->tables);
+ free(_this);
+ }
+
+ /**
+ * Destructor for the TrueTypeTable object.
+ */
+ void TrueTypeTableDispose(void * arg)
+ {
+ vcl::TrueTypeTable *_this = static_cast<vcl::TrueTypeTable *>(arg);
+ /* XXX do a binary search */
+ assert(_this != nullptr);
+
+ if (_this->rawdata) free(_this->rawdata);
+
+ for(size_t i=0; i < SAL_N_ELEMENTS(vcl::vtable1); i++) {
+ if (_this->tag == vcl::vtable1[i].tag) {
+ vcl::vtable1[i].f(_this);
+ return;
+ }
+ }
+ assert(!"Unknown TrueType table.");
+ }
+}
+
+#ifdef TEST_TTCR
+static sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) {
+ return (a << 24) | (b << 16) | (c << 8) | d;
+}
+
+int main()
+{
+ TrueTypeCreator *ttcr;
+ sal_uInt8 *t1, *t2, *t3, *t4, *t5, *t6;
+
+ TrueTypeCreatorNewEmpty(mkTag('t','r','u','e'), &ttcr);
+
+ t1 = malloc(1000); memset(t1, 'a', 1000);
+ t2 = malloc(2000); memset(t2, 'b', 2000);
+ t3 = malloc(3000); memset(t3, 'c', 3000);
+ t4 = malloc(4000); memset(t4, 'd', 4000);
+ t5 = malloc(5000); memset(t5, 'e', 5000);
+ t6 = malloc(6000); memset(t6, 'f', 6000);
+
+ AddTable(ttcr, TrueTypeTableNew(T_maxp, 1000, t1));
+ AddTable(ttcr, TrueTypeTableNew(T_OS2, 2000, t2));
+ AddTable(ttcr, TrueTypeTableNew(T_cmap, 3000, t3));
+ AddTable(ttcr, TrueTypeTableNew(T_loca, 4000, t4));
+ AddTable(ttcr, TrueTypeTableNew(T_hhea, 5000, t5));
+ AddTable(ttcr, TrueTypeTableNew(T_glyf, 6000, t6));
+
+ free(t1);
+ free(t2);
+ free(t3);
+ free(t4);
+ free(t5);
+ free(t6);
+
+ StreamToFile(ttcr, "ttcrout.ttf");
+
+ TrueTypeCreatorDispose(ttcr);
+ return 0;
+}
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/ttcr.hxx b/vcl/source/fontsubset/ttcr.hxx
new file mode 100644
index 000000000..26298f78c
--- /dev/null
+++ b/vcl/source/fontsubset/ttcr.hxx
@@ -0,0 +1,220 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/**
+ * @file ttcr.hxx
+ * @brief TrueType font creator
+ */
+
+#ifndef INCLUDED_VCL_SOURCE_FONTSUBSET_TTCR_HXX
+#define INCLUDED_VCL_SOURCE_FONTSUBSET_TTCR_HXX
+
+#include <sft.hxx>
+
+namespace vcl
+{
+ struct TrueTypeCreator;
+
+/* TrueType data types */
+ typedef struct {
+ sal_uInt16 aw;
+ sal_Int16 lsb;
+ } longHorMetrics;
+
+/* A generic base class for all TrueType tables */
+ struct TrueTypeTable {
+ sal_uInt32 tag; /* table tag */
+ sal_uInt8 *rawdata; /* raw data allocated by GetRawData_*() */
+ void *data; /* table specific data */
+ };
+
+/** Error codes for most functions */
+ enum TTCRErrCodes {
+ TTCR_OK, /**< no error */
+ TTCR_ZEROGLYPHS, /**< At least one glyph should be defined */
+ TTCR_UNKNOWN, /**< Unknown TrueType table */
+ TTCR_NONAMES, /**< 'name' table does not contain any names */
+ TTCR_NAMETOOLONG, /**< 'name' table is too long (string data > 64K) */
+ TTCR_POSTFORMAT /**< unsupported format of a 'post' table */
+ };
+
+/**
+ * TrueTypeCreator constructor.
+ * Allocates all internal structures.
+ */
+ void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this);
+
+/**
+ * Adds a TrueType table to the TrueType creator.
+ */
+ void AddTable(TrueTypeCreator *_this, TrueTypeTable *table);
+
+/**
+ * Removes a TrueType table from the TrueType creator if it is stored there.
+ * It also calls a TrueTypeTable destructor.
+ * Note: all generic tables (with tag 0) will be removed if this function is
+ * called with the second argument of 0.
+ * @return value of SFErrCodes type
+ */
+ void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag);
+
+/**
+ * Writes a TrueType font generated by the TrueTypeCreator to a segment of
+ * memory that this method allocates. When it is not needed anymore the caller
+ * is supposed to call free() on it.
+ * @return value of SFErrCodes type
+ */
+ SFErrCodes StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length);
+
+/**
+ * Writes a TrueType font generated by the TrueTypeCreator to a file
+ * @return value of SFErrCodes type
+ */
+ SFErrCodes StreamToFile(TrueTypeCreator *_this, const char* fname);
+
+/**
+ * This function converts the data of a TrueType table to a raw array of bytes.
+ * It may allocates the memory for it and returns the size of the raw data in bytes.
+ * If memory is allocated it does not need to be freed by the caller of this function,
+ * since the pointer to it is stored in the TrueTypeTable and it is freed by the destructor
+ * @return TTCRErrCode
+ *
+ */
+
+ int GetRawData(TrueTypeTable *, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag);
+
+/**
+ *
+ * Creates a new raw TrueType table. The difference between this constructor and
+ * TrueTypeTableNew_tag constructors is that the latter create structured tables
+ * while this constructor just copies memory pointed to by ptr to its buffer
+ * and stores its length. This constructor is suitable for data that is not
+ * supposed to be processed in any way, just written to the resulting TTF file.
+ */
+ TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ const sal_uInt8* ptr);
+
+/**
+ * Creates a new 'head' table for a TrueType font.
+ * Allocates memory for it. Since a lot of values in the 'head' table depend on the
+ * rest of the tables in the TrueType font this table should be the last one added
+ * to the font.
+ */
+ TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision,
+ sal_uInt16 flags,
+ sal_uInt16 unitsPerEm,
+ const sal_uInt8 *created,
+ sal_uInt16 macStyle,
+ sal_uInt16 lowestRecPPEM,
+ sal_Int16 fontDirectionHint);
+
+/**
+ * Creates a new 'hhea' table for a TrueType font.
+ * Allocates memory for it and stores it in the hhea pointer.
+ */
+ TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender,
+ sal_Int16 descender,
+ sal_Int16 linegap,
+ sal_Int16 caretSlopeRise,
+ sal_Int16 caretSlopeRun);
+
+/**
+ * Creates a new empty 'loca' table for a TrueType font.
+ *
+ * INTERNAL: gets called only from ProcessTables();
+ */
+ TrueTypeTable *TrueTypeTableNew_loca();
+
+/**
+ * Creates a new 'maxp' table based on an existing maxp table.
+ * If maxp is 0, a new empty maxp table is created
+ * size specifies the size of existing maxp table for
+ * error-checking purposes
+ */
+ TrueTypeTable *TrueTypeTableNew_maxp( const sal_uInt8* maxp, int size);
+
+/**
+ * Creates a new empty 'glyf' table.
+ */
+ TrueTypeTable *TrueTypeTableNew_glyf();
+
+/**
+ * Creates a new empty 'cmap' table.
+ */
+ TrueTypeTable *TrueTypeTableNew_cmap();
+
+/**
+ * Creates a new 'name' table. If n != 0 the table gets populated by
+ * the Name Records stored in the nr array. This function allocates
+ * memory for its own copy of NameRecords, so nr array has to
+ * be explicitly deallocated when it is not needed.
+ */
+ TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord const *nr);
+
+/**
+ * Creates a new 'post' table of one of the supported formats
+ */
+ TrueTypeTable *TrueTypeTableNew_post(sal_Int32 format,
+ sal_Int32 italicAngle,
+ sal_Int16 underlinePosition,
+ sal_Int16 underlineThickness,
+ sal_uInt32 isFixedPitch);
+
+// Table manipulation functions
+
+/**
+ * Add a character/glyph pair to a cmap table
+ */
+ void cmapAdd(TrueTypeTable *, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g);
+
+/**
+ * Add a glyph to a glyf table.
+ *
+ * @return glyphID of the glyph in the new font
+ *
+ * NOTE: This function does not duplicate GlyphData, so memory will be
+ * deallocated in the table destructor
+ */
+ sal_uInt32 glyfAdd(TrueTypeTable *, GlyphData *glyphdata, TrueTypeFont *fnt);
+
+/**
+ * Query the number of glyphs currently stored in the 'glyf' table
+ *
+ */
+ sal_uInt32 glyfCount(const TrueTypeTable *);
+
+} // namespace
+
+extern "C"
+{
+/**
+ * Destructor for the TrueTypeTable object.
+ */
+ void TrueTypeTableDispose(void *);
+
+/**
+ * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it.
+ */
+ void TrueTypeCreatorDispose(vcl::TrueTypeCreator *_this);
+}
+
+#endif // INCLUDED_VCL_SOURCE_FONTSUBSET_TTCR_HXX
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/xlat.cxx b/vcl/source/fontsubset/xlat.cxx
new file mode 100644
index 000000000..b7966f279
--- /dev/null
+++ b/vcl/source/fontsubset/xlat.cxx
@@ -0,0 +1,144 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <rtl/textcvt.h>
+#include "xlat.hxx"
+
+namespace {
+
+#define MAX_CVT_SELECT 6
+
+class ConverterCache
+{
+public:
+ explicit ConverterCache();
+ ~ConverterCache();
+ sal_uInt16 convertOne( int nSelect, sal_Unicode );
+private:
+ void ensureConverter( int nSelect );
+ rtl_UnicodeToTextConverter maConverterCache[ MAX_CVT_SELECT+1 ];
+ rtl_UnicodeToTextContext maContexts[ MAX_CVT_SELECT+1 ];
+};
+
+ConverterCache::ConverterCache()
+{
+ for( int i = 0; i <= MAX_CVT_SELECT; ++i)
+ {
+ maConverterCache[i] = nullptr;
+ maContexts[i] = nullptr;
+ }
+}
+
+ConverterCache::~ConverterCache()
+{
+ for( int i = 0; i <= MAX_CVT_SELECT; ++i)
+ {
+ if( !maContexts[i] )
+ continue;
+ rtl_destroyUnicodeToTextContext( maConverterCache[i], maContexts[i] );
+ rtl_destroyUnicodeToTextConverter( maConverterCache[i] );
+ }
+}
+
+void ConverterCache::ensureConverter( int nSelect )
+{
+ // SAL_WARN_IF( (2>nSelect) || (nSelect>MAX_CVT_SELECT)), "vcl", "invalid XLAT.Converter requested" );
+ rtl_UnicodeToTextContext aContext = maContexts[ nSelect ];
+ if( !aContext )
+ {
+ rtl_TextEncoding eRecodeFrom = RTL_TEXTENCODING_UNICODE;
+ switch( nSelect )
+ {
+ default: nSelect = 1; [[fallthrough]]; // to unicode recoding
+ case 1: eRecodeFrom = RTL_TEXTENCODING_UNICODE; break;
+ case 2: eRecodeFrom = RTL_TEXTENCODING_SHIFT_JIS; break;
+ case 3: eRecodeFrom = RTL_TEXTENCODING_GB_2312; break;
+ case 4: eRecodeFrom = RTL_TEXTENCODING_BIG5; break;
+ case 5: eRecodeFrom = RTL_TEXTENCODING_MS_949; break;
+ case 6: eRecodeFrom = RTL_TEXTENCODING_MS_1361; break;
+ }
+ rtl_UnicodeToTextConverter aRecodeConverter = rtl_createUnicodeToTextConverter( eRecodeFrom );
+ maConverterCache[ nSelect ] = aRecodeConverter;
+
+ aContext = rtl_createUnicodeToTextContext( aRecodeConverter );
+ maContexts[ nSelect ] = aContext;
+ }
+
+ rtl_resetUnicodeToTextContext( maConverterCache[ nSelect ], aContext );
+}
+
+sal_uInt16 ConverterCache::convertOne( int nSelect, sal_Unicode aChar )
+{
+ ensureConverter( nSelect );
+
+ sal_Unicode aUCS2Char = aChar;
+ char aTempArray[8];
+ sal_Size nTempSize;
+ sal_uInt32 nCvtInfo;
+
+ // TODO: use direct unicode->mbcs converter should there ever be one
+ int nCodeLen = rtl_convertUnicodeToText(
+ maConverterCache[ nSelect ], maContexts[ nSelect ],
+ &aUCS2Char, 1, aTempArray, sizeof(aTempArray),
+ RTL_UNICODETOTEXT_FLAGS_UNDEFINED_0
+ | RTL_UNICODETOTEXT_FLAGS_INVALID_0,
+ &nCvtInfo, &nTempSize );
+
+ sal_uInt16 aCode = aTempArray[0];
+ for( int i = 1; i < nCodeLen; ++i )
+ aCode = (aCode << 8) + (aTempArray[i] & 0xFF);
+ return aCode;
+}
+
+} // anonymous namespace
+
+namespace vcl
+{
+
+static ConverterCache aCC;
+
+sal_uInt16 TranslateChar12(sal_uInt16 src)
+{
+ return aCC.convertOne( 2, src);
+}
+
+sal_uInt16 TranslateChar13(sal_uInt16 src)
+{
+ return aCC.convertOne( 3, src);
+}
+
+sal_uInt16 TranslateChar14(sal_uInt16 src)
+{
+ return aCC.convertOne( 4, src);
+}
+
+sal_uInt16 TranslateChar15(sal_uInt16 src)
+{
+ return aCC.convertOne( 5, src);
+}
+
+sal_uInt16 TranslateChar16(sal_uInt16 src)
+{
+ return aCC.convertOne( 6, src);
+}
+
+
+} // namespace vcl
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/xlat.hxx b/vcl/source/fontsubset/xlat.hxx
new file mode 100644
index 000000000..c9994b48f
--- /dev/null
+++ b/vcl/source/fontsubset/xlat.hxx
@@ -0,0 +1,40 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*| Author: Alexander Gelfenbain |*/
+
+#ifndef INCLUDED_VCL_SOURCE_FONTSUBSET_XLAT_HXX
+#define INCLUDED_VCL_SOURCE_FONTSUBSET_XLAT_HXX
+
+#include <sal/types.h>
+
+namespace vcl
+{
+// TODO: sal_UCS4
+
+ sal_uInt16 TranslateChar12(sal_uInt16);
+ sal_uInt16 TranslateChar13(sal_uInt16);
+ sal_uInt16 TranslateChar14(sal_uInt16);
+ sal_uInt16 TranslateChar15(sal_uInt16);
+ sal_uInt16 TranslateChar16(sal_uInt16);
+}
+
+#endif // INCLUDED_VCL_SOURCE_FONTSUBSET_XLAT_HXX
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */