• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "xfa/fgas/font/cfgas_fontmgr.h"
8 
9 #include <algorithm>
10 #include <memory>
11 #include <utility>
12 
13 #include "core/fxcrt/cfx_memorystream.h"
14 #include "core/fxcrt/fx_codepage.h"
15 #include "core/fxge/cfx_font.h"
16 #include "core/fxge/cfx_fontmapper.h"
17 #include "core/fxge/cfx_fontmgr.h"
18 #include "core/fxge/cfx_gemodule.h"
19 #include "core/fxge/fx_font.h"
20 #include "core/fxge/ifx_systemfontinfo.h"
21 #include "third_party/base/ptr_util.h"
22 #include "third_party/base/stl_util.h"
23 #include "xfa/fgas/font/cfgas_gefont.h"
24 #include "xfa/fgas/font/fgas_fontutils.h"
25 
26 #if _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
27 
28 namespace {
29 
30 struct FX_CHARSET_MAP {
31   uint16_t charset;
32   uint16_t codepage;
33 };
34 
35 const FX_CHARSET_MAP g_FXCharset2CodePageTable[] = {
36     {FX_CHARSET_ANSI, FX_CODEPAGE_MSWin_WesternEuropean},
37     {FX_CHARSET_Default, FX_CODEPAGE_DefANSI},
38     {FX_CHARSET_Symbol, FX_CODEPAGE_Symbol},
39     {FX_CHARSET_MAC_Roman, FX_CODEPAGE_MAC_Roman},
40     {FX_CHARSET_MAC_ShiftJIS, FX_CODEPAGE_MAC_ShiftJIS},
41     {FX_CHARSET_MAC_Korean, FX_CODEPAGE_MAC_Korean},
42     {FX_CHARSET_MAC_ChineseSimplified, FX_CODEPAGE_MAC_ChineseSimplified},
43     {FX_CHARSET_MAC_ChineseTraditional, FX_CODEPAGE_MAC_ChineseTraditional},
44     {FX_CHARSET_MAC_Hebrew, FX_CODEPAGE_MAC_Hebrew},
45     {FX_CHARSET_MAC_Arabic, FX_CODEPAGE_MAC_Arabic},
46     {FX_CHARSET_MAC_Greek, FX_CODEPAGE_MAC_Greek},
47     {FX_CHARSET_MAC_Turkish, FX_CODEPAGE_MAC_Turkish},
48     {FX_CHARSET_MAC_Thai, FX_CODEPAGE_MAC_Thai},
49     {FX_CHARSET_MAC_EasternEuropean, FX_CODEPAGE_MAC_EasternEuropean},
50     {FX_CHARSET_MAC_Cyrillic, FX_CODEPAGE_MAC_Cyrillic},
51     {FX_CHARSET_ShiftJIS, FX_CODEPAGE_ShiftJIS},
52     {FX_CHARSET_Hangul, FX_CODEPAGE_Hangul},
53     {FX_CHARSET_Johab, FX_CODEPAGE_Johab},
54     {FX_CHARSET_ChineseSimplified, FX_CODEPAGE_ChineseSimplified},
55     {FX_CHARSET_ChineseTraditional, FX_CODEPAGE_ChineseTraditional},
56     {FX_CHARSET_MSWin_Greek, FX_CODEPAGE_MSWin_Greek},
57     {FX_CHARSET_MSWin_Turkish, FX_CODEPAGE_MSWin_Turkish},
58     {FX_CHARSET_MSWin_Vietnamese, FX_CODEPAGE_MSWin_Vietnamese},
59     {FX_CHARSET_MSWin_Hebrew, FX_CODEPAGE_MSWin_Hebrew},
60     {FX_CHARSET_MSWin_Arabic, FX_CODEPAGE_MSWin_Arabic},
61     {FX_CHARSET_MSWin_Baltic, FX_CODEPAGE_MSWin_Baltic},
62     {FX_CHARSET_MSWin_Cyrillic, FX_CODEPAGE_MSWin_Cyrillic},
63     {FX_CHARSET_Thai, FX_CODEPAGE_MSDOS_Thai},
64     {FX_CHARSET_MSWin_EasternEuropean, FX_CODEPAGE_MSWin_EasternEuropean},
65     {FX_CHARSET_US, FX_CODEPAGE_MSDOS_US},
66     {FX_CHARSET_OEM, FX_CODEPAGE_MSDOS_WesternEuropean},
67 };
68 
GetCodePageFromCharset(uint8_t charset)69 uint16_t GetCodePageFromCharset(uint8_t charset) {
70   int32_t iEnd = sizeof(g_FXCharset2CodePageTable) / sizeof(FX_CHARSET_MAP) - 1;
71   ASSERT(iEnd >= 0);
72 
73   int32_t iStart = 0, iMid;
74   do {
75     iMid = (iStart + iEnd) / 2;
76     const FX_CHARSET_MAP& cp = g_FXCharset2CodePageTable[iMid];
77     if (charset == cp.charset)
78       return cp.codepage;
79     if (charset < cp.charset)
80       iEnd = iMid - 1;
81     else
82       iStart = iMid + 1;
83   } while (iStart <= iEnd);
84   return 0xFFFF;
85 }
86 
GetSimilarityScore(FX_FONTDESCRIPTOR const * pFont,uint32_t dwFontStyles)87 int32_t GetSimilarityScore(FX_FONTDESCRIPTOR const* pFont,
88                            uint32_t dwFontStyles) {
89   int32_t iValue = 0;
90   if (FontStyleIsSymbolic(dwFontStyles) ==
91       FontStyleIsSymbolic(pFont->dwFontStyles)) {
92     iValue += 64;
93   }
94   if (FontStyleIsFixedPitch(dwFontStyles) ==
95       FontStyleIsFixedPitch(pFont->dwFontStyles)) {
96     iValue += 32;
97   }
98   if (FontStyleIsSerif(dwFontStyles) == FontStyleIsSerif(pFont->dwFontStyles))
99     iValue += 16;
100   if (FontStyleIsScript(dwFontStyles) == FontStyleIsScript(pFont->dwFontStyles))
101     iValue += 8;
102   return iValue;
103 }
104 
MatchDefaultFont(FX_FONTMATCHPARAMS * pParams,const std::deque<FX_FONTDESCRIPTOR> & fonts)105 const FX_FONTDESCRIPTOR* MatchDefaultFont(
106     FX_FONTMATCHPARAMS* pParams,
107     const std::deque<FX_FONTDESCRIPTOR>& fonts) {
108   const FX_FONTDESCRIPTOR* pBestFont = nullptr;
109   int32_t iBestSimilar = 0;
110   for (const auto& font : fonts) {
111     if (FontStyleIsBold(font.dwFontStyles) &&
112         FontStyleIsItalic(font.dwFontStyles)) {
113       continue;
114     }
115 
116     if (pParams->pwsFamily) {
117       if (FXSYS_wcsicmp(pParams->pwsFamily, font.wsFontFace))
118         continue;
119       if (font.uCharSet == FX_CHARSET_Symbol)
120         return &font;
121     }
122     if (font.uCharSet == FX_CHARSET_Symbol)
123       continue;
124     if (pParams->wCodePage != 0xFFFF) {
125       if (GetCodePageFromCharset(font.uCharSet) != pParams->wCodePage)
126         continue;
127     } else {
128       if (pParams->dwUSB < 128) {
129         uint32_t dwByte = pParams->dwUSB / 32;
130         uint32_t dwUSB = 1 << (pParams->dwUSB % 32);
131         if ((font.FontSignature.fsUsb[dwByte] & dwUSB) == 0)
132           continue;
133       }
134     }
135     if (pParams->matchParagraphStyle) {
136       if ((font.dwFontStyles & 0x0F) == (pParams->dwFontStyles & 0x0F))
137         return &font;
138       continue;
139     }
140     if (pParams->pwsFamily) {
141       if (FXSYS_wcsicmp(pParams->pwsFamily, font.wsFontFace) == 0)
142         return &font;
143     }
144     int32_t iSimilarValue = GetSimilarityScore(&font, pParams->dwFontStyles);
145     if (iBestSimilar < iSimilarValue) {
146       iBestSimilar = iSimilarValue;
147       pBestFont = &font;
148     }
149   }
150   return iBestSimilar < 1 ? nullptr : pBestFont;
151 }
152 
GetGdiFontStyles(const LOGFONTW & lf)153 uint32_t GetGdiFontStyles(const LOGFONTW& lf) {
154   uint32_t dwStyles = 0;
155   if ((lf.lfPitchAndFamily & 0x03) == FIXED_PITCH)
156     dwStyles |= FXFONT_FIXED_PITCH;
157   uint8_t nFamilies = lf.lfPitchAndFamily & 0xF0;
158   if (nFamilies == FF_ROMAN)
159     dwStyles |= FXFONT_SERIF;
160   if (nFamilies == FF_SCRIPT)
161     dwStyles |= FXFONT_SCRIPT;
162   if (lf.lfCharSet == SYMBOL_CHARSET)
163     dwStyles |= FXFONT_SYMBOLIC;
164   return dwStyles;
165 }
166 
GdiFontEnumProc(ENUMLOGFONTEX * lpelfe,NEWTEXTMETRICEX * lpntme,DWORD dwFontType,LPARAM lParam)167 int32_t CALLBACK GdiFontEnumProc(ENUMLOGFONTEX* lpelfe,
168                                  NEWTEXTMETRICEX* lpntme,
169                                  DWORD dwFontType,
170                                  LPARAM lParam) {
171   if (dwFontType != TRUETYPE_FONTTYPE)
172     return 1;
173   const LOGFONTW& lf = ((LPENUMLOGFONTEXW)lpelfe)->elfLogFont;
174   if (lf.lfFaceName[0] == L'@')
175     return 1;
176   FX_FONTDESCRIPTOR* pFont = FX_Alloc(FX_FONTDESCRIPTOR, 1);
177   memset(pFont, 0, sizeof(FX_FONTDESCRIPTOR));
178   pFont->uCharSet = lf.lfCharSet;
179   pFont->dwFontStyles = GetGdiFontStyles(lf);
180   FXSYS_wcsncpy(pFont->wsFontFace, (const wchar_t*)lf.lfFaceName, 31);
181   pFont->wsFontFace[31] = 0;
182   memcpy(&pFont->FontSignature, &lpntme->ntmFontSig,
183          sizeof(lpntme->ntmFontSig));
184   reinterpret_cast<std::deque<FX_FONTDESCRIPTOR>*>(lParam)->push_back(*pFont);
185   FX_Free(pFont);
186   return 1;
187 }
188 
EnumGdiFonts(std::deque<FX_FONTDESCRIPTOR> * fonts,const wchar_t * pwsFaceName,wchar_t wUnicode)189 void EnumGdiFonts(std::deque<FX_FONTDESCRIPTOR>* fonts,
190                   const wchar_t* pwsFaceName,
191                   wchar_t wUnicode) {
192   HDC hDC = ::GetDC(nullptr);
193   LOGFONTW lfFind;
194   memset(&lfFind, 0, sizeof(lfFind));
195   lfFind.lfCharSet = DEFAULT_CHARSET;
196   if (pwsFaceName) {
197     FXSYS_wcsncpy(lfFind.lfFaceName, pwsFaceName, 31);
198     lfFind.lfFaceName[31] = 0;
199   }
200   EnumFontFamiliesExW(hDC, (LPLOGFONTW)&lfFind, (FONTENUMPROCW)GdiFontEnumProc,
201                       (LPARAM)fonts, 0);
202   ::ReleaseDC(nullptr, hDC);
203 }
204 
205 }  // namespace
206 
CFGAS_FontMgr()207 CFGAS_FontMgr::CFGAS_FontMgr() : m_pEnumerator(EnumGdiFonts), m_FontFaces(100) {
208   if (m_pEnumerator)
209     m_pEnumerator(&m_FontFaces, nullptr, 0xFEFF);
210 }
211 
~CFGAS_FontMgr()212 CFGAS_FontMgr::~CFGAS_FontMgr() {}
213 
EnumFonts()214 bool CFGAS_FontMgr::EnumFonts() {
215   return true;
216 }
217 
FindFont(const wchar_t * pszFontFamily,uint32_t dwFontStyles,bool matchParagraphStyle,uint16_t wCodePage,uint32_t dwUSB,wchar_t wUnicode)218 const FX_FONTDESCRIPTOR* CFGAS_FontMgr::FindFont(const wchar_t* pszFontFamily,
219                                                  uint32_t dwFontStyles,
220                                                  bool matchParagraphStyle,
221                                                  uint16_t wCodePage,
222                                                  uint32_t dwUSB,
223                                                  wchar_t wUnicode) {
224   FX_FONTMATCHPARAMS params;
225   memset(&params, 0, sizeof(params));
226   params.dwUSB = dwUSB;
227   params.wUnicode = wUnicode;
228   params.wCodePage = wCodePage;
229   params.pwsFamily = pszFontFamily;
230   params.dwFontStyles = dwFontStyles;
231   params.matchParagraphStyle = matchParagraphStyle;
232   const FX_FONTDESCRIPTOR* pDesc = MatchDefaultFont(&params, m_FontFaces);
233   if (pDesc)
234     return pDesc;
235 
236   if (!pszFontFamily || !m_pEnumerator)
237     return nullptr;
238 
239   std::deque<FX_FONTDESCRIPTOR> namedFonts;
240   m_pEnumerator(&namedFonts, pszFontFamily, wUnicode);
241   params.pwsFamily = nullptr;
242   pDesc = MatchDefaultFont(&params, namedFonts);
243   if (!pDesc)
244     return nullptr;
245 
246   auto it = std::find(m_FontFaces.rbegin(), m_FontFaces.rend(), *pDesc);
247   if (it != m_FontFaces.rend())
248     return &*it;
249 
250   m_FontFaces.push_back(*pDesc);
251   return &m_FontFaces.back();
252 }
253 
254 #else  // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
255 
256 namespace {
257 
258 constexpr const char* g_FontFolders[] = {
259 #if _FX_PLATFORM_ == _FX_PLATFORM_LINUX_
260     "/usr/share/fonts", "/usr/share/X11/fonts/Type1",
261     "/usr/share/X11/fonts/TTF", "/usr/local/share/fonts",
262 #elif _FX_PLATFORM_ == _FX_PLATFORM_APPLE_
263     "~/Library/Fonts", "/Library/Fonts", "/System/Library/Fonts",
264 #elif _FX_PLATFORM_ == _FX_PLATFORM_ANDROID_
265     "/system/fonts",
266 #endif
267 };
268 
269 const uint16_t g_CodePages[] = {FX_CODEPAGE_MSWin_WesternEuropean,
270                                 FX_CODEPAGE_MSWin_EasternEuropean,
271                                 FX_CODEPAGE_MSWin_Cyrillic,
272                                 FX_CODEPAGE_MSWin_Greek,
273                                 FX_CODEPAGE_MSWin_Turkish,
274                                 FX_CODEPAGE_MSWin_Hebrew,
275                                 FX_CODEPAGE_MSWin_Arabic,
276                                 FX_CODEPAGE_MSWin_Baltic,
277                                 FX_CODEPAGE_MSWin_Vietnamese,
278                                 FX_CODEPAGE_DefANSI,
279                                 FX_CODEPAGE_DefANSI,
280                                 FX_CODEPAGE_DefANSI,
281                                 FX_CODEPAGE_DefANSI,
282                                 FX_CODEPAGE_DefANSI,
283                                 FX_CODEPAGE_DefANSI,
284                                 FX_CODEPAGE_DefANSI,
285                                 FX_CODEPAGE_MSDOS_Thai,
286                                 FX_CODEPAGE_ShiftJIS,
287                                 FX_CODEPAGE_ChineseSimplified,
288                                 FX_CODEPAGE_Hangul,
289                                 FX_CODEPAGE_ChineseTraditional,
290                                 FX_CODEPAGE_Johab,
291                                 FX_CODEPAGE_DefANSI,
292                                 FX_CODEPAGE_DefANSI,
293                                 FX_CODEPAGE_DefANSI,
294                                 FX_CODEPAGE_DefANSI,
295                                 FX_CODEPAGE_DefANSI,
296                                 FX_CODEPAGE_DefANSI,
297                                 FX_CODEPAGE_DefANSI,
298                                 FX_CODEPAGE_DefANSI,
299                                 FX_CODEPAGE_DefANSI,
300                                 FX_CODEPAGE_DefANSI,
301                                 FX_CODEPAGE_DefANSI,
302                                 FX_CODEPAGE_DefANSI,
303                                 FX_CODEPAGE_DefANSI,
304                                 FX_CODEPAGE_DefANSI,
305                                 FX_CODEPAGE_DefANSI,
306                                 FX_CODEPAGE_DefANSI,
307                                 FX_CODEPAGE_DefANSI,
308                                 FX_CODEPAGE_DefANSI,
309                                 FX_CODEPAGE_DefANSI,
310                                 FX_CODEPAGE_DefANSI,
311                                 FX_CODEPAGE_DefANSI,
312                                 FX_CODEPAGE_DefANSI,
313                                 FX_CODEPAGE_DefANSI,
314                                 FX_CODEPAGE_DefANSI,
315                                 FX_CODEPAGE_DefANSI,
316                                 FX_CODEPAGE_DefANSI,
317                                 FX_CODEPAGE_MSDOS_Greek2,
318                                 FX_CODEPAGE_MSDOS_Russian,
319                                 FX_CODEPAGE_MSDOS_Norwegian,
320                                 FX_CODEPAGE_MSDOS_Arabic,
321                                 FX_CODEPAGE_MSDOS_FrenchCanadian,
322                                 FX_CODEPAGE_MSDOS_Hebrew,
323                                 FX_CODEPAGE_MSDOS_Icelandic,
324                                 FX_CODEPAGE_MSDOS_Portuguese,
325                                 FX_CODEPAGE_MSDOS_Turkish,
326                                 FX_CODEPAGE_MSDOS_Cyrillic,
327                                 FX_CODEPAGE_MSDOS_EasternEuropean,
328                                 FX_CODEPAGE_MSDOS_Baltic,
329                                 FX_CODEPAGE_MSDOS_Greek1,
330                                 FX_CODEPAGE_Arabic_ASMO708,
331                                 FX_CODEPAGE_MSDOS_WesternEuropean,
332                                 FX_CODEPAGE_MSDOS_US};
333 
FX_GetCodePageBit(uint16_t wCodePage)334 uint16_t FX_GetCodePageBit(uint16_t wCodePage) {
335   for (size_t i = 0; i < FX_ArraySize(g_CodePages); ++i) {
336     if (g_CodePages[i] == wCodePage)
337       return static_cast<uint16_t>(i);
338   }
339   return static_cast<uint16_t>(-1);
340 }
341 
FX_GetUnicodeBit(wchar_t wcUnicode)342 uint16_t FX_GetUnicodeBit(wchar_t wcUnicode) {
343   const FGAS_FONTUSB* x = FGAS_GetUnicodeBitField(wcUnicode);
344   return x ? x->wBitField : 999;
345 }
346 
GetUInt8(const uint8_t * p)347 inline uint8_t GetUInt8(const uint8_t* p) {
348   return p[0];
349 }
350 
GetUInt16(const uint8_t * p)351 inline uint16_t GetUInt16(const uint8_t* p) {
352   return static_cast<uint16_t>(p[0] << 8 | p[1]);
353 }
354 
355 struct FX_BIT2CHARSET {
356   uint16_t wBit;
357   uint16_t wCharset;
358 };
359 
360 const FX_BIT2CHARSET g_FX_Bit2Charset[4][16] = {
361     {{1 << 0, FX_CHARSET_ANSI},
362      {1 << 1, FX_CHARSET_MSWin_EasternEuropean},
363      {1 << 2, FX_CHARSET_MSWin_Cyrillic},
364      {1 << 3, FX_CHARSET_MSWin_Greek},
365      {1 << 4, FX_CHARSET_MSWin_Turkish},
366      {1 << 5, FX_CHARSET_MSWin_Hebrew},
367      {1 << 6, FX_CHARSET_MSWin_Arabic},
368      {1 << 7, FX_CHARSET_MSWin_Baltic},
369      {1 << 8, FX_CHARSET_MSWin_Vietnamese},
370      {1 << 9, FX_CHARSET_Default},
371      {1 << 10, FX_CHARSET_Default},
372      {1 << 11, FX_CHARSET_Default},
373      {1 << 12, FX_CHARSET_Default},
374      {1 << 13, FX_CHARSET_Default},
375      {1 << 14, FX_CHARSET_Default},
376      {1 << 15, FX_CHARSET_Default}},
377     {{1 << 0, FX_CHARSET_Thai},
378      {1 << 1, FX_CHARSET_ShiftJIS},
379      {1 << 2, FX_CHARSET_ChineseSimplified},
380      {1 << 3, FX_CHARSET_Hangul},
381      {1 << 4, FX_CHARSET_ChineseTraditional},
382      {1 << 5, FX_CHARSET_Johab},
383      {1 << 6, FX_CHARSET_Default},
384      {1 << 7, FX_CHARSET_Default},
385      {1 << 8, FX_CHARSET_Default},
386      {1 << 9, FX_CHARSET_Default},
387      {1 << 10, FX_CHARSET_Default},
388      {1 << 11, FX_CHARSET_Default},
389      {1 << 12, FX_CHARSET_Default},
390      {1 << 13, FX_CHARSET_Default},
391      {1 << 14, FX_CHARSET_OEM},
392      {1 << 15, FX_CHARSET_Symbol}},
393     {{1 << 0, FX_CHARSET_Default},
394      {1 << 1, FX_CHARSET_Default},
395      {1 << 2, FX_CHARSET_Default},
396      {1 << 3, FX_CHARSET_Default},
397      {1 << 4, FX_CHARSET_Default},
398      {1 << 5, FX_CHARSET_Default},
399      {1 << 6, FX_CHARSET_Default},
400      {1 << 7, FX_CHARSET_Default},
401      {1 << 8, FX_CHARSET_Default},
402      {1 << 9, FX_CHARSET_Default},
403      {1 << 10, FX_CHARSET_Default},
404      {1 << 11, FX_CHARSET_Default},
405      {1 << 12, FX_CHARSET_Default},
406      {1 << 13, FX_CHARSET_Default},
407      {1 << 14, FX_CHARSET_Default},
408      {1 << 15, FX_CHARSET_Default}},
409     {{1 << 0, FX_CHARSET_Default},
410      {1 << 1, FX_CHARSET_Default},
411      {1 << 2, FX_CHARSET_Default},
412      {1 << 3, FX_CHARSET_Default},
413      {1 << 4, FX_CHARSET_Default},
414      {1 << 5, FX_CHARSET_Default},
415      {1 << 6, FX_CHARSET_Default},
416      {1 << 7, FX_CHARSET_Default},
417      {1 << 8, FX_CHARSET_Default},
418      {1 << 9, FX_CHARSET_Default},
419      {1 << 10, FX_CHARSET_Default},
420      {1 << 11, FX_CHARSET_Default},
421      {1 << 12, FX_CHARSET_Default},
422      {1 << 13, FX_CHARSET_Default},
423      {1 << 14, FX_CHARSET_Default},
424      {1 << 15, FX_CHARSET_US}}};
425 
426 constexpr wchar_t kFolderSeparator = L'/';
427 
428 extern "C" {
429 
ftStreamRead(FXFT_Stream stream,unsigned long offset,unsigned char * buffer,unsigned long count)430 unsigned long ftStreamRead(FXFT_Stream stream,
431                            unsigned long offset,
432                            unsigned char* buffer,
433                            unsigned long count) {
434   if (count == 0)
435     return 0;
436 
437   IFX_SeekableReadStream* pFile =
438       static_cast<IFX_SeekableReadStream*>(stream->descriptor.pointer);
439   if (!pFile->ReadBlock(buffer, offset, count))
440     return 0;
441 
442   return count;
443 }
444 
ftStreamClose(FXFT_Stream stream)445 void ftStreamClose(FXFT_Stream stream) {}
446 
447 };  // extern "C"
448 
449 }  // namespace
450 
CFX_FontDescriptor()451 CFX_FontDescriptor::CFX_FontDescriptor()
452     : m_nFaceIndex(0), m_dwFontStyles(0), m_dwUsb(), m_dwCsb() {}
453 
~CFX_FontDescriptor()454 CFX_FontDescriptor::~CFX_FontDescriptor() {}
455 
CFX_FontSourceEnum_File()456 CFX_FontSourceEnum_File::CFX_FontSourceEnum_File() {
457   for (size_t i = 0; i < FX_ArraySize(g_FontFolders); ++i)
458     m_FolderPaths.push_back(g_FontFolders[i]);
459 }
460 
~CFX_FontSourceEnum_File()461 CFX_FontSourceEnum_File::~CFX_FontSourceEnum_File() {}
462 
GetNextFile()463 ByteString CFX_FontSourceEnum_File::GetNextFile() {
464   FX_FileHandle* pCurHandle =
465       !m_FolderQueue.empty() ? m_FolderQueue.back().pFileHandle : nullptr;
466   if (!pCurHandle) {
467     if (m_FolderPaths.empty())
468       return "";
469     pCurHandle = FX_OpenFolder(m_FolderPaths.back().c_str());
470     HandleParentPath hpp;
471     hpp.pFileHandle = pCurHandle;
472     hpp.bsParentPath = m_FolderPaths.back();
473     m_FolderQueue.push_back(hpp);
474   }
475   ByteString bsName;
476   bool bFolder;
477   ByteString bsFolderSeparator =
478       ByteString::FromUnicode(WideString(kFolderSeparator));
479   while (true) {
480     if (!FX_GetNextFile(pCurHandle, &bsName, &bFolder)) {
481       FX_CloseFolder(pCurHandle);
482       if (!m_FolderQueue.empty())
483         m_FolderQueue.pop_back();
484       if (m_FolderQueue.empty()) {
485         if (!m_FolderPaths.empty())
486           m_FolderPaths.pop_back();
487         return !m_FolderPaths.empty() ? GetNextFile() : "";
488       }
489       pCurHandle = m_FolderQueue.back().pFileHandle;
490       continue;
491     }
492     if (bsName == "." || bsName == "..")
493       continue;
494     if (bFolder) {
495       HandleParentPath hpp;
496       hpp.bsParentPath =
497           m_FolderQueue.back().bsParentPath + bsFolderSeparator + bsName;
498       hpp.pFileHandle = FX_OpenFolder(hpp.bsParentPath.c_str());
499       if (!hpp.pFileHandle)
500         continue;
501       m_FolderQueue.push_back(hpp);
502       pCurHandle = hpp.pFileHandle;
503       continue;
504     }
505     bsName = m_FolderQueue.back().bsParentPath + bsFolderSeparator + bsName;
506     break;
507   }
508   return bsName;
509 }
510 
HasStartPosition()511 bool CFX_FontSourceEnum_File::HasStartPosition() {
512   m_wsNext = GetNextFile().UTF8Decode();
513   return m_wsNext.GetLength() != 0;
514 }
515 
516 // <next exists, stream for next>
517 std::pair<bool, RetainPtr<IFX_SeekableStream>>
GetNext()518 CFX_FontSourceEnum_File::GetNext() {
519   if (m_wsNext.GetLength() == 0)
520     return {false, nullptr};
521 
522   auto stream = IFX_SeekableStream::CreateFromFilename(m_wsNext.c_str(),
523                                                        FX_FILEMODE_ReadOnly);
524   m_wsNext = GetNextFile().UTF8Decode();
525   return {true, stream};
526 }
527 
CFGAS_FontMgr()528 CFGAS_FontMgr::CFGAS_FontMgr()
529     : m_pFontSource(pdfium::MakeUnique<CFX_FontSourceEnum_File>()) {}
530 
~CFGAS_FontMgr()531 CFGAS_FontMgr::~CFGAS_FontMgr() {}
532 
EnumFontsFromFontMapper()533 bool CFGAS_FontMgr::EnumFontsFromFontMapper() {
534   CFX_FontMapper* pFontMapper =
535       CFX_GEModule::Get()->GetFontMgr()->GetBuiltinMapper();
536   if (!pFontMapper)
537     return false;
538 
539   IFX_SystemFontInfo* pSystemFontInfo = pFontMapper->GetSystemFontInfo();
540   if (!pSystemFontInfo)
541     return false;
542 
543   pSystemFontInfo->EnumFontList(pFontMapper);
544   for (int32_t i = 0; i < pFontMapper->GetFaceSize(); ++i) {
545     RetainPtr<IFX_SeekableReadStream> pFontStream =
546         CreateFontStream(pFontMapper, pSystemFontInfo, i);
547     if (!pFontStream)
548       continue;
549 
550     WideString wsFaceName =
551         WideString::FromLocal(pFontMapper->GetFaceName(i).c_str());
552     RegisterFaces(pFontStream, &wsFaceName);
553   }
554   return !m_InstalledFonts.empty();
555 }
556 
EnumFontsFromFiles()557 bool CFGAS_FontMgr::EnumFontsFromFiles() {
558   CFX_GEModule::Get()->GetFontMgr()->InitFTLibrary();
559   if (!m_pFontSource->HasStartPosition())
560     return !m_InstalledFonts.empty();
561 
562   bool has_next;
563   RetainPtr<IFX_SeekableStream> stream;
564   std::tie(has_next, stream) = m_pFontSource->GetNext();
565   while (has_next) {
566     if (stream)
567       RegisterFaces(stream, nullptr);
568     std::tie(has_next, stream) = m_pFontSource->GetNext();
569   }
570   return !m_InstalledFonts.empty();
571 }
572 
EnumFonts()573 bool CFGAS_FontMgr::EnumFonts() {
574   return EnumFontsFromFontMapper() || EnumFontsFromFiles();
575 }
576 
VerifyUnicode(CFX_FontDescriptor * pDesc,wchar_t wcUnicode)577 bool CFGAS_FontMgr::VerifyUnicode(CFX_FontDescriptor* pDesc,
578                                   wchar_t wcUnicode) {
579   RetainPtr<IFX_SeekableReadStream> pFileRead =
580       CreateFontStream(pDesc->m_wsFaceName.UTF8Encode());
581   if (!pFileRead)
582     return false;
583 
584   FXFT_Face pFace = LoadFace(pFileRead, pDesc->m_nFaceIndex);
585   FT_Error retCharmap = FXFT_Select_Charmap(pFace, FXFT_ENCODING_UNICODE);
586   FT_Error retIndex = FXFT_Get_Char_Index(pFace, wcUnicode);
587   if (!pFace)
588     return false;
589 
590   if (FXFT_Get_Face_External_Stream(pFace))
591     FXFT_Clear_Face_External_Stream(pFace);
592 
593   FXFT_Done_Face(pFace);
594   return !retCharmap && retIndex;
595 }
596 
LoadFont(const WideString & wsFaceName,int32_t iFaceIndex,int32_t * pFaceCount)597 RetainPtr<CFGAS_GEFont> CFGAS_FontMgr::LoadFont(const WideString& wsFaceName,
598                                                 int32_t iFaceIndex,
599                                                 int32_t* pFaceCount) {
600   CFX_FontMgr* pFontMgr = CFX_GEModule::Get()->GetFontMgr();
601   CFX_FontMapper* pFontMapper = pFontMgr->GetBuiltinMapper();
602   if (!pFontMapper)
603     return nullptr;
604 
605   IFX_SystemFontInfo* pSystemFontInfo = pFontMapper->GetSystemFontInfo();
606   if (!pSystemFontInfo)
607     return nullptr;
608 
609   RetainPtr<IFX_SeekableReadStream> pFontStream =
610       CreateFontStream(wsFaceName.UTF8Encode());
611   if (!pFontStream)
612     return nullptr;
613 
614   auto pInternalFont = pdfium::MakeUnique<CFX_Font>();
615   if (!pInternalFont->LoadFile(pFontStream, iFaceIndex))
616     return nullptr;
617 
618   RetainPtr<CFGAS_GEFont> pFont =
619       CFGAS_GEFont::LoadFont(std::move(pInternalFont), this);
620   if (!pFont)
621     return nullptr;
622 
623   m_IFXFont2FileRead[pFont] = pFontStream;
624   if (pFaceCount)
625     *pFaceCount = pFont->GetDevFont()->GetFace()->num_faces;
626   return pFont;
627 }
628 
LoadFace(const RetainPtr<IFX_SeekableReadStream> & pFontStream,int32_t iFaceIndex)629 FXFT_Face CFGAS_FontMgr::LoadFace(
630     const RetainPtr<IFX_SeekableReadStream>& pFontStream,
631     int32_t iFaceIndex) {
632   if (!pFontStream)
633     return nullptr;
634 
635   CFX_FontMgr* pFontMgr = CFX_GEModule::Get()->GetFontMgr();
636   pFontMgr->InitFTLibrary();
637 
638   FXFT_Library library = pFontMgr->GetFTLibrary();
639   if (!library)
640     return nullptr;
641 
642   // TODO(palmer): This memory will be freed with |ft_free| (which is |free|).
643   // Ultimately, we want to change this to:
644   //   FXFT_Stream ftStream = FX_Alloc(FXFT_StreamRec, 1);
645   // https://bugs.chromium.org/p/pdfium/issues/detail?id=690
646   FXFT_Stream ftStream =
647       static_cast<FXFT_Stream>(ft_scalloc(sizeof(FXFT_StreamRec), 1));
648   memset(ftStream, 0, sizeof(FXFT_StreamRec));
649   ftStream->base = nullptr;
650   ftStream->descriptor.pointer = static_cast<void*>(pFontStream.Get());
651   ftStream->pos = 0;
652   ftStream->size = static_cast<unsigned long>(pFontStream->GetSize());
653   ftStream->read = ftStreamRead;
654   ftStream->close = ftStreamClose;
655 
656   FXFT_Open_Args ftArgs;
657   memset(&ftArgs, 0, sizeof(FXFT_Open_Args));
658   ftArgs.flags |= FT_OPEN_STREAM;
659   ftArgs.stream = ftStream;
660 
661   FXFT_Face pFace = nullptr;
662   if (FXFT_Open_Face(library, &ftArgs, iFaceIndex, &pFace)) {
663     ft_sfree(ftStream);
664     return nullptr;
665   }
666 
667   FXFT_Set_Pixel_Sizes(pFace, 0, 64);
668   return pFace;
669 }
670 
CreateFontStream(CFX_FontMapper * pFontMapper,IFX_SystemFontInfo * pSystemFontInfo,uint32_t index)671 RetainPtr<IFX_SeekableReadStream> CFGAS_FontMgr::CreateFontStream(
672     CFX_FontMapper* pFontMapper,
673     IFX_SystemFontInfo* pSystemFontInfo,
674     uint32_t index) {
675   void* hFont = pSystemFontInfo->MapFont(
676       0, 0, FX_CHARSET_Default, 0, pFontMapper->GetFaceName(index).c_str());
677   if (!hFont)
678     return nullptr;
679 
680   uint32_t dwFileSize = pSystemFontInfo->GetFontData(hFont, 0, nullptr, 0);
681   if (dwFileSize == 0)
682     return nullptr;
683 
684   uint8_t* pBuffer = FX_Alloc(uint8_t, dwFileSize + 1);
685   dwFileSize = pSystemFontInfo->GetFontData(hFont, 0, pBuffer, dwFileSize);
686 
687   return pdfium::MakeRetain<CFX_MemoryStream>(pBuffer, dwFileSize, true);
688 }
689 
CreateFontStream(const ByteString & bsFaceName)690 RetainPtr<IFX_SeekableReadStream> CFGAS_FontMgr::CreateFontStream(
691     const ByteString& bsFaceName) {
692   CFX_FontMgr* pFontMgr = CFX_GEModule::Get()->GetFontMgr();
693   CFX_FontMapper* pFontMapper = pFontMgr->GetBuiltinMapper();
694   if (!pFontMapper)
695     return nullptr;
696 
697   IFX_SystemFontInfo* pSystemFontInfo = pFontMapper->GetSystemFontInfo();
698   if (!pSystemFontInfo)
699     return nullptr;
700 
701   pSystemFontInfo->EnumFontList(pFontMapper);
702   for (int32_t i = 0; i < pFontMapper->GetFaceSize(); ++i) {
703     if (pFontMapper->GetFaceName(i) == bsFaceName)
704       return CreateFontStream(pFontMapper, pSystemFontInfo, i);
705   }
706   return nullptr;
707 }
708 
MatchFonts(std::vector<CFX_FontDescriptorInfo> * pMatchedFonts,uint16_t wCodePage,uint32_t dwFontStyles,const WideString & FontName,wchar_t wcUnicode)709 void CFGAS_FontMgr::MatchFonts(
710     std::vector<CFX_FontDescriptorInfo>* pMatchedFonts,
711     uint16_t wCodePage,
712     uint32_t dwFontStyles,
713     const WideString& FontName,
714     wchar_t wcUnicode) {
715   pMatchedFonts->clear();
716   for (const auto& pFont : m_InstalledFonts) {
717     int32_t nPenalty =
718         CalcPenalty(pFont.get(), wCodePage, dwFontStyles, FontName, wcUnicode);
719     if (nPenalty >= 0xffff)
720       continue;
721     pMatchedFonts->push_back({pFont.get(), nPenalty});
722     if (pMatchedFonts->size() == 0xffff)
723       break;
724   }
725   std::sort(pMatchedFonts->begin(), pMatchedFonts->end());
726 }
727 
CalcPenalty(CFX_FontDescriptor * pInstalled,uint16_t wCodePage,uint32_t dwFontStyles,const WideString & FontName,wchar_t wcUnicode)728 int32_t CFGAS_FontMgr::CalcPenalty(CFX_FontDescriptor* pInstalled,
729                                    uint16_t wCodePage,
730                                    uint32_t dwFontStyles,
731                                    const WideString& FontName,
732                                    wchar_t wcUnicode) {
733   int32_t nPenalty = 30000;
734   if (FontName.GetLength() != 0) {
735     if (FontName != pInstalled->m_wsFaceName) {
736       size_t i;
737       for (i = 0; i < pInstalled->m_wsFamilyNames.size(); ++i) {
738         if (pInstalled->m_wsFamilyNames[i] == FontName)
739           break;
740       }
741       if (i == pInstalled->m_wsFamilyNames.size())
742         nPenalty += 0xFFFF;
743       else
744         nPenalty -= 28000;
745     } else {
746       nPenalty -= 30000;
747     }
748     if (30000 == nPenalty &&
749         0 == IsPartName(pInstalled->m_wsFaceName, FontName)) {
750       size_t i;
751       for (i = 0; i < pInstalled->m_wsFamilyNames.size(); i++) {
752         if (IsPartName(pInstalled->m_wsFamilyNames[i], FontName) != 0)
753           break;
754       }
755       if (i == pInstalled->m_wsFamilyNames.size())
756         nPenalty += 0xFFFF;
757       else
758         nPenalty -= 26000;
759     } else {
760       nPenalty -= 27000;
761     }
762   }
763   uint32_t dwStyleMask = pInstalled->m_dwFontStyles ^ dwFontStyles;
764   if (FontStyleIsBold(dwStyleMask))
765     nPenalty += 4500;
766   if (FontStyleIsFixedPitch(dwStyleMask))
767     nPenalty += 10000;
768   if (FontStyleIsItalic(dwStyleMask))
769     nPenalty += 10000;
770   if (FontStyleIsSerif(dwStyleMask))
771     nPenalty += 500;
772   if (FontStyleIsSymbolic(dwStyleMask))
773     nPenalty += 0xFFFF;
774   if (nPenalty >= 0xFFFF)
775     return 0xFFFF;
776 
777   uint16_t wBit = (wCodePage == FX_CODEPAGE_DefANSI || wCodePage == 0xFFFF)
778                       ? static_cast<uint16_t>(-1)
779                       : FX_GetCodePageBit(wCodePage);
780   if (wBit != static_cast<uint16_t>(-1)) {
781     ASSERT(wBit < 64);
782     if ((pInstalled->m_dwCsb[wBit / 32] & (1 << (wBit % 32))) == 0)
783       nPenalty += 0xFFFF;
784     else
785       nPenalty -= 60000;
786   }
787   wBit = (wcUnicode == 0 || wcUnicode == 0xFFFE) ? static_cast<uint16_t>(999)
788                                                  : FX_GetUnicodeBit(wcUnicode);
789   if (wBit != static_cast<uint16_t>(999)) {
790     ASSERT(wBit < 128);
791     if ((pInstalled->m_dwUsb[wBit / 32] & (1 << (wBit % 32))) == 0)
792       nPenalty += 0xFFFF;
793     else
794       nPenalty -= 60000;
795   }
796   return nPenalty;
797 }
798 
RegisterFace(FXFT_Face pFace,const WideString * pFaceName)799 void CFGAS_FontMgr::RegisterFace(FXFT_Face pFace, const WideString* pFaceName) {
800   if ((pFace->face_flags & FT_FACE_FLAG_SCALABLE) == 0)
801     return;
802 
803   auto pFont = pdfium::MakeUnique<CFX_FontDescriptor>();
804   pFont->m_dwFontStyles |= FXFT_Is_Face_Bold(pFace) ? FXFONT_BOLD : 0;
805   pFont->m_dwFontStyles |= FXFT_Is_Face_Italic(pFace) ? FXFONT_ITALIC : 0;
806   pFont->m_dwFontStyles |= GetFlags(pFace);
807 
808   std::vector<uint16_t> charsets = GetCharsets(pFace);
809   GetUSBCSB(pFace, pFont->m_dwUsb, pFont->m_dwCsb);
810 
811   FT_ULong dwTag;
812   FT_ENC_TAG(dwTag, 'n', 'a', 'm', 'e');
813 
814   std::vector<uint8_t> table;
815   unsigned long nLength = 0;
816   unsigned int error = FXFT_Load_Sfnt_Table(pFace, dwTag, 0, nullptr, &nLength);
817   if (error == 0 && nLength != 0) {
818     table.resize(nLength);
819     if (FXFT_Load_Sfnt_Table(pFace, dwTag, 0, table.data(), nullptr))
820       table.clear();
821   }
822   GetNames(table.empty() ? nullptr : table.data(), pFont->m_wsFamilyNames);
823   pFont->m_wsFamilyNames.push_back(ByteString(pFace->family_name).UTF8Decode());
824   pFont->m_wsFaceName =
825       pFaceName ? *pFaceName
826                 : WideString::FromLocal(FXFT_Get_Postscript_Name(pFace));
827   pFont->m_nFaceIndex = pFace->face_index;
828   m_InstalledFonts.push_back(std::move(pFont));
829 }
830 
RegisterFaces(const RetainPtr<IFX_SeekableReadStream> & pFontStream,const WideString * pFaceName)831 void CFGAS_FontMgr::RegisterFaces(
832     const RetainPtr<IFX_SeekableReadStream>& pFontStream,
833     const WideString* pFaceName) {
834   int32_t index = 0;
835   int32_t num_faces = 0;
836   do {
837     FXFT_Face pFace = LoadFace(pFontStream, index++);
838     if (!pFace)
839       continue;
840     // All faces keep number of faces. It can be retrieved from any one face.
841     if (num_faces == 0)
842       num_faces = pFace->num_faces;
843     RegisterFace(pFace, pFaceName);
844     if (FXFT_Get_Face_External_Stream(pFace))
845       FXFT_Clear_Face_External_Stream(pFace);
846     FXFT_Done_Face(pFace);
847   } while (index < num_faces);
848 }
849 
GetFlags(FXFT_Face pFace)850 uint32_t CFGAS_FontMgr::GetFlags(FXFT_Face pFace) {
851   uint32_t flag = 0;
852   if (FT_IS_FIXED_WIDTH(pFace))
853     flag |= FXFONT_FIXED_PITCH;
854   TT_OS2* pOS2 = (TT_OS2*)FT_Get_Sfnt_Table(pFace, ft_sfnt_os2);
855   if (!pOS2)
856     return flag;
857 
858   if (pOS2->ulCodePageRange1 & (1 << 31))
859     flag |= FXFONT_SYMBOLIC;
860   if (pOS2->panose[0] == 2) {
861     uint8_t uSerif = pOS2->panose[1];
862     if ((uSerif > 1 && uSerif < 10) || uSerif > 13)
863       flag |= FXFONT_SERIF;
864   }
865   return flag;
866 }
867 
GetNames(const uint8_t * name_table,std::vector<WideString> & Names)868 void CFGAS_FontMgr::GetNames(const uint8_t* name_table,
869                              std::vector<WideString>& Names) {
870   if (!name_table)
871     return;
872 
873   uint8_t* lpTable = (uint8_t*)name_table;
874   WideString wsFamily;
875   uint8_t* sp = lpTable + 2;
876   uint8_t* lpNameRecord = lpTable + 6;
877   uint16_t nNameCount = GetUInt16(sp);
878   uint8_t* lpStr = lpTable + GetUInt16(sp + 2);
879   for (uint16_t j = 0; j < nNameCount; j++) {
880     uint16_t nNameID = GetUInt16(lpNameRecord + j * 12 + 6);
881     if (nNameID != 1)
882       continue;
883 
884     uint16_t nPlatformID = GetUInt16(lpNameRecord + j * 12 + 0);
885     uint16_t nNameLength = GetUInt16(lpNameRecord + j * 12 + 8);
886     uint16_t nNameOffset = GetUInt16(lpNameRecord + j * 12 + 10);
887     wsFamily.clear();
888     if (nPlatformID != 1) {
889       for (uint16_t k = 0; k < nNameLength / 2; k++) {
890         wchar_t wcTemp = GetUInt16(lpStr + nNameOffset + k * 2);
891         wsFamily += wcTemp;
892       }
893       Names.push_back(wsFamily);
894       continue;
895     }
896     for (uint16_t k = 0; k < nNameLength; k++) {
897       wchar_t wcTemp = GetUInt8(lpStr + nNameOffset + k);
898       wsFamily += wcTemp;
899     }
900     Names.push_back(wsFamily);
901   }
902 }
903 
GetCharsets(FXFT_Face pFace) const904 std::vector<uint16_t> CFGAS_FontMgr::GetCharsets(FXFT_Face pFace) const {
905   std::vector<uint16_t> charsets;
906   TT_OS2* pOS2 = (TT_OS2*)FT_Get_Sfnt_Table(pFace, ft_sfnt_os2);
907   if (!pOS2) {
908     charsets.push_back(FX_CHARSET_Default);
909     return charsets;
910   }
911   uint16_t a[4] = {
912       pOS2->ulCodePageRange1 & 0xffff, (pOS2->ulCodePageRange1 >> 16) & 0xffff,
913       pOS2->ulCodePageRange2 & 0xffff, (pOS2->ulCodePageRange2 >> 16) & 0xffff};
914   for (int n = 0; n < 4; n++) {
915     for (int32_t i = 0; i < 16; i++) {
916       if ((a[n] & g_FX_Bit2Charset[n][i].wBit) != 0)
917         charsets.push_back(g_FX_Bit2Charset[n][i].wCharset);
918     }
919   }
920   return charsets;
921 }
922 
GetUSBCSB(FXFT_Face pFace,uint32_t * USB,uint32_t * CSB)923 void CFGAS_FontMgr::GetUSBCSB(FXFT_Face pFace, uint32_t* USB, uint32_t* CSB) {
924   TT_OS2* pOS2 = (TT_OS2*)FT_Get_Sfnt_Table(pFace, ft_sfnt_os2);
925   if (!pOS2) {
926     USB[0] = 0;
927     USB[1] = 0;
928     USB[2] = 0;
929     USB[3] = 0;
930     CSB[0] = 0;
931     CSB[1] = 0;
932     return;
933   }
934   USB[0] = pOS2->ulUnicodeRange1;
935   USB[1] = pOS2->ulUnicodeRange2;
936   USB[2] = pOS2->ulUnicodeRange3;
937   USB[3] = pOS2->ulUnicodeRange4;
938   CSB[0] = pOS2->ulCodePageRange1;
939   CSB[1] = pOS2->ulCodePageRange2;
940 }
941 
IsPartName(const WideString & Name1,const WideString & Name2)942 int32_t CFGAS_FontMgr::IsPartName(const WideString& Name1,
943                                   const WideString& Name2) {
944   if (Name1.Contains(Name2.c_str()))
945     return 1;
946   return 0;
947 }
948 
949 #endif  // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
950 
GetFontByCodePage(uint16_t wCodePage,uint32_t dwFontStyles,const wchar_t * pszFontFamily)951 RetainPtr<CFGAS_GEFont> CFGAS_FontMgr::GetFontByCodePage(
952     uint16_t wCodePage,
953     uint32_t dwFontStyles,
954     const wchar_t* pszFontFamily) {
955   ByteString bsHash = ByteString::Format("%d, %d", wCodePage, dwFontStyles);
956   bsHash += FX_UTF8Encode(WideStringView(pszFontFamily));
957   uint32_t dwHash = FX_HashCode_GetA(bsHash.AsStringView(), false);
958   std::vector<RetainPtr<CFGAS_GEFont>>* pFontArray = &m_Hash2Fonts[dwHash];
959   if (!pFontArray->empty())
960     return (*pFontArray)[0];
961 
962 #if _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
963   const FX_FONTDESCRIPTOR* pFD =
964       FindFont(pszFontFamily, dwFontStyles, true, wCodePage, 999, 0);
965   if (!pFD)
966     pFD = FindFont(nullptr, dwFontStyles, true, wCodePage, 999, 0);
967   if (!pFD)
968     pFD = FindFont(nullptr, dwFontStyles, false, wCodePage, 999, 0);
969   if (!pFD)
970     return nullptr;
971 
972   RetainPtr<CFGAS_GEFont> pFont =
973       CFGAS_GEFont::LoadFont(pFD->wsFontFace, dwFontStyles, wCodePage, this);
974 #else   // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
975   std::vector<CFX_FontDescriptorInfo>* sortedFontInfos =
976       m_Hash2CandidateList[dwHash].get();
977   if (!sortedFontInfos) {
978     auto pNewFonts = pdfium::MakeUnique<std::vector<CFX_FontDescriptorInfo>>();
979     sortedFontInfos = pNewFonts.get();
980     MatchFonts(sortedFontInfos, wCodePage, dwFontStyles,
981                WideString(pszFontFamily), 0);
982     m_Hash2CandidateList[dwHash] = std::move(pNewFonts);
983   }
984   if (sortedFontInfos->empty())
985     return nullptr;
986 
987   CFX_FontDescriptor* pDesc = (*sortedFontInfos)[0].pFont;
988   RetainPtr<CFGAS_GEFont> pFont =
989       LoadFont(pDesc->m_wsFaceName, pDesc->m_nFaceIndex, nullptr);
990 #endif  // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
991 
992   if (!pFont)
993     return nullptr;
994 
995   pFont->SetLogicalFontStyle(dwFontStyles);
996   pFontArray->push_back(pFont);
997   return pFont;
998 }
999 
GetFontByUnicode(wchar_t wUnicode,uint32_t dwFontStyles,const wchar_t * pszFontFamily)1000 RetainPtr<CFGAS_GEFont> CFGAS_FontMgr::GetFontByUnicode(
1001     wchar_t wUnicode,
1002     uint32_t dwFontStyles,
1003     const wchar_t* pszFontFamily) {
1004 #if _FX_PLATFORM_ != _FX_PLATFORM_WINDOWS_
1005   if (pdfium::ContainsKey(m_FailedUnicodesSet, wUnicode))
1006     return nullptr;
1007 #endif  // _FX_PLATFORM_ != _FX_PLATFORM_WINDOWS_
1008 
1009   const FGAS_FONTUSB* x = FGAS_GetUnicodeBitField(wUnicode);
1010   uint16_t wCodePage = x ? x->wCodePage : 0xFFFF;
1011   uint16_t wBitField = x ? x->wBitField : 0x03E7;
1012   ByteString bsHash;
1013   if (wCodePage == 0xFFFF) {
1014     bsHash =
1015         ByteString::Format("%d, %d, %d", wCodePage, wBitField, dwFontStyles);
1016   } else {
1017     bsHash = ByteString::Format("%d, %d", wCodePage, dwFontStyles);
1018   }
1019   bsHash += FX_UTF8Encode(WideStringView(pszFontFamily));
1020   uint32_t dwHash = FX_HashCode_GetA(bsHash.AsStringView(), false);
1021   std::vector<RetainPtr<CFGAS_GEFont>>* pFonts = &m_Hash2Fonts[dwHash];
1022   for (size_t i = 0; i < pFonts->size(); ++i) {
1023     if (VerifyUnicode((*pFonts)[i], wUnicode))
1024       return (*pFonts)[i];
1025   }
1026 #if _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1027   const FX_FONTDESCRIPTOR* pFD = FindFont(pszFontFamily, dwFontStyles, false,
1028                                           wCodePage, wBitField, wUnicode);
1029   if (!pFD && pszFontFamily) {
1030     pFD =
1031         FindFont(nullptr, dwFontStyles, false, wCodePage, wBitField, wUnicode);
1032   }
1033   if (!pFD)
1034     return nullptr;
1035 
1036   uint16_t newCodePage = GetCodePageFromCharset(pFD->uCharSet);
1037   const wchar_t* pFontFace = pFD->wsFontFace;
1038   RetainPtr<CFGAS_GEFont> pFont =
1039       CFGAS_GEFont::LoadFont(pFontFace, dwFontStyles, newCodePage, this);
1040   if (!pFont)
1041     return nullptr;
1042 
1043   pFont->SetLogicalFontStyle(dwFontStyles);
1044   pFonts->push_back(pFont);
1045   return pFont;
1046 #else   // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1047   std::vector<CFX_FontDescriptorInfo>* sortedFontInfos =
1048       m_Hash2CandidateList[dwHash].get();
1049   if (!sortedFontInfos) {
1050     auto pNewFonts = pdfium::MakeUnique<std::vector<CFX_FontDescriptorInfo>>();
1051     sortedFontInfos = pNewFonts.get();
1052     MatchFonts(sortedFontInfos, wCodePage, dwFontStyles,
1053                WideString(pszFontFamily), wUnicode);
1054     m_Hash2CandidateList[dwHash] = std::move(pNewFonts);
1055   }
1056   for (const auto& info : *sortedFontInfos) {
1057     CFX_FontDescriptor* pDesc = info.pFont;
1058     if (!VerifyUnicode(pDesc, wUnicode))
1059       continue;
1060     RetainPtr<CFGAS_GEFont> pFont =
1061         LoadFont(pDesc->m_wsFaceName, pDesc->m_nFaceIndex, nullptr);
1062     if (!pFont)
1063       continue;
1064     pFont->SetLogicalFontStyle(dwFontStyles);
1065     pFonts->push_back(pFont);
1066     return pFont;
1067   }
1068   if (!pszFontFamily)
1069     m_FailedUnicodesSet.insert(wUnicode);
1070   return nullptr;
1071 #endif  // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1072 }
1073 
VerifyUnicode(const RetainPtr<CFGAS_GEFont> & pFont,wchar_t wcUnicode)1074 bool CFGAS_FontMgr::VerifyUnicode(const RetainPtr<CFGAS_GEFont>& pFont,
1075                                   wchar_t wcUnicode) {
1076   if (!pFont)
1077     return false;
1078 
1079   FXFT_Face pFace = pFont->GetDevFont()->GetFace();
1080   FXFT_CharMap charmap = FXFT_Get_Face_Charmap(pFace);
1081   if (FXFT_Select_Charmap(pFace, FXFT_ENCODING_UNICODE) != 0)
1082     return false;
1083 
1084   if (FXFT_Get_Char_Index(pFace, wcUnicode) == 0) {
1085     FXFT_Set_Charmap(pFace, charmap);
1086     return false;
1087   }
1088   return true;
1089 }
1090 
LoadFont(const wchar_t * pszFontFamily,uint32_t dwFontStyles,uint16_t wCodePage)1091 RetainPtr<CFGAS_GEFont> CFGAS_FontMgr::LoadFont(const wchar_t* pszFontFamily,
1092                                                 uint32_t dwFontStyles,
1093                                                 uint16_t wCodePage) {
1094 #if _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1095   ByteString bsHash = ByteString::Format("%d, %d", wCodePage, dwFontStyles);
1096   bsHash += FX_UTF8Encode(WideStringView(pszFontFamily));
1097   uint32_t dwHash = FX_HashCode_GetA(bsHash.AsStringView(), false);
1098   std::vector<RetainPtr<CFGAS_GEFont>>* pFontArray = &m_Hash2Fonts[dwHash];
1099   if (!pFontArray->empty())
1100     return (*pFontArray)[0];
1101 
1102   const FX_FONTDESCRIPTOR* pFD =
1103       FindFont(pszFontFamily, dwFontStyles, true, wCodePage, 999, 0);
1104   if (!pFD)
1105     pFD = FindFont(pszFontFamily, dwFontStyles, false, wCodePage, 999, 0);
1106   if (!pFD)
1107     return nullptr;
1108 
1109   RetainPtr<CFGAS_GEFont> pFont =
1110       CFGAS_GEFont::LoadFont(pFD->wsFontFace, dwFontStyles, wCodePage, this);
1111   if (!pFont)
1112     return nullptr;
1113 
1114   pFont->SetLogicalFontStyle(dwFontStyles);
1115   pFontArray->push_back(pFont);
1116   return pFont;
1117 #else   // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1118   return GetFontByCodePage(wCodePage, dwFontStyles, pszFontFamily);
1119 #endif  // _FX_PLATFORM_ == _FX_PLATFORM_WINDOWS_
1120 }
1121 
RemoveFont(const RetainPtr<CFGAS_GEFont> & pEFont)1122 void CFGAS_FontMgr::RemoveFont(const RetainPtr<CFGAS_GEFont>& pEFont) {
1123   if (!pEFont)
1124     return;
1125 
1126 #if _FX_PLATFORM_ != _FX_PLATFORM_WINDOWS_
1127   m_IFXFont2FileRead.erase(pEFont);
1128 #endif  // _FX_PLATFORM_ != _FX_PLATFORM_WINDOWS_
1129 
1130   auto iter = m_Hash2Fonts.begin();
1131   while (iter != m_Hash2Fonts.end()) {
1132     auto old_iter = iter++;
1133     bool all_empty = true;
1134     for (size_t i = 0; i < old_iter->second.size(); i++) {
1135       if (old_iter->second[i] == pEFont)
1136         old_iter->second[i].Reset();
1137       else if (old_iter->second[i])
1138         all_empty = false;
1139     }
1140     if (all_empty)
1141       m_Hash2Fonts.erase(old_iter);
1142   }
1143 }
1144