• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The PDFium Authors
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 "core/fxge/cfx_font.h"
8 
9 #include <stdint.h>
10 
11 #include <algorithm>
12 #include <limits>
13 #include <memory>
14 #include <utility>
15 
16 #include "build/build_config.h"
17 #include "core/fxcrt/check.h"
18 #include "core/fxcrt/data_vector.h"
19 #include "core/fxcrt/fx_codepage.h"
20 #include "core/fxcrt/fx_stream.h"
21 #include "core/fxcrt/numerics/safe_conversions.h"
22 #include "core/fxcrt/span.h"
23 #include "core/fxcrt/unowned_ptr.h"
24 #include "core/fxge/cfx_fontcache.h"
25 #include "core/fxge/cfx_fontmapper.h"
26 #include "core/fxge/cfx_fontmgr.h"
27 #include "core/fxge/cfx_gemodule.h"
28 #include "core/fxge/cfx_glyphcache.h"
29 #include "core/fxge/cfx_path.h"
30 #include "core/fxge/cfx_substfont.h"
31 #include "core/fxge/fx_font.h"
32 #include "core/fxge/scoped_font_transform.h"
33 
34 namespace {
35 
36 const CFX_Font::CharsetFontMap kDefaultTTFMap[] = {
37     {static_cast<int>(FX_Charset::kANSI), CFX_Font::kDefaultAnsiFontName},
38     {static_cast<int>(FX_Charset::kChineseSimplified), "SimSun"},
39     {static_cast<int>(FX_Charset::kChineseTraditional), "MingLiU"},
40     {static_cast<int>(FX_Charset::kShiftJIS), "MS Gothic"},
41     {static_cast<int>(FX_Charset::kHangul), "Batang"},
42     {static_cast<int>(FX_Charset::kMSWin_Cyrillic), "Arial"},
43 #if BUILDFLAG(IS_WIN)
44     {static_cast<int>(FX_Charset::kMSWin_EasternEuropean), "Tahoma"},
45 #else
46     {static_cast<int>(FX_Charset::kMSWin_EasternEuropean), "Arial"},
47 #endif
48     {static_cast<int>(FX_Charset::kMSWin_Arabic), "Arial"},
49     // TODO(crbug.com/348468114): Remove sentinel value when
50     // FPDF_GetDefaultTTFMap() gets removed.
51     {-1, nullptr}};
52 
FXRectFromFTPos(FT_Pos left,FT_Pos top,FT_Pos right,FT_Pos bottom)53 FX_RECT FXRectFromFTPos(FT_Pos left, FT_Pos top, FT_Pos right, FT_Pos bottom) {
54   return FX_RECT(pdfium::checked_cast<int32_t>(left),
55                  pdfium::checked_cast<int32_t>(top),
56                  pdfium::checked_cast<int32_t>(right),
57                  pdfium::checked_cast<int32_t>(bottom));
58 }
59 
ScaledFXRectFromFTPos(FT_Pos left,FT_Pos top,FT_Pos right,FT_Pos bottom,int x_scale,int y_scale)60 FX_RECT ScaledFXRectFromFTPos(FT_Pos left,
61                               FT_Pos top,
62                               FT_Pos right,
63                               FT_Pos bottom,
64                               int x_scale,
65                               int y_scale) {
66   if (x_scale == 0 || y_scale == 0)
67     return FXRectFromFTPos(left, top, right, bottom);
68 
69   return FXRectFromFTPos(left * 1000 / x_scale, top * 1000 / y_scale,
70                          right * 1000 / x_scale, bottom * 1000 / y_scale);
71 }
72 
73 #ifdef PDF_ENABLE_XFA
FTStreamRead(FXFT_StreamRec * stream,unsigned long offset,unsigned char * buffer,unsigned long count)74 unsigned long FTStreamRead(FXFT_StreamRec* stream,
75                            unsigned long offset,
76                            unsigned char* buffer,
77                            unsigned long count) {
78   if (count == 0)
79     return 0;
80 
81   IFX_SeekableReadStream* pFile =
82       static_cast<IFX_SeekableReadStream*>(stream->descriptor.pointer);
83 
84   // SAFETY: caller ensures `buffer` points to at least `count` bytes.
85   return pFile && pFile->ReadBlockAtOffset(
86                       UNSAFE_BUFFERS(pdfium::make_span(buffer, count)), offset)
87              ? count
88              : 0;
89 }
90 
FTStreamClose(FXFT_StreamRec * stream)91 void FTStreamClose(FXFT_StreamRec* stream) {}
92 #endif  // PDF_ENABLE_XFA
93 
ShouldAppendStyle(const ByteString & style)94 bool ShouldAppendStyle(const ByteString& style) {
95   return !style.IsEmpty() && style != "Regular";
96 }
97 
98 }  // namespace
99 
100 // static
101 const char CFX_Font::kUntitledFontName[] = "Untitled";
102 
103 // static
104 const char CFX_Font::kDefaultAnsiFontName[] = "Helvetica";
105 
106 // static
107 const char CFX_Font::kUniversalDefaultFontName[] = "Arial Unicode MS";
108 
109 // static
GetDefaultTTFMapSpan()110 pdfium::span<const CFX_Font::CharsetFontMap> CFX_Font::GetDefaultTTFMapSpan() {
111   auto map_with_sentinel_value = pdfium::make_span(kDefaultTTFMap);
112   return map_with_sentinel_value.first(map_with_sentinel_value.size() - 1);
113 }
114 
115 // static
GetDefaultFontNameByCharset(FX_Charset nCharset)116 ByteString CFX_Font::GetDefaultFontNameByCharset(FX_Charset nCharset) {
117   for (const auto& entry : GetDefaultTTFMapSpan()) {
118     if (static_cast<int>(nCharset) == entry.charset) {
119       return entry.fontname;
120     }
121   }
122   return kUniversalDefaultFontName;
123 }
124 
125 // static
GetCharSetFromUnicode(uint16_t word)126 FX_Charset CFX_Font::GetCharSetFromUnicode(uint16_t word) {
127   // to avoid CJK Font to show ASCII
128   if (word < 0x7F)
129     return FX_Charset::kANSI;
130 
131   // find new charset
132   if ((word >= 0x4E00 && word <= 0x9FA5) ||
133       (word >= 0xE7C7 && word <= 0xE7F3) ||
134       (word >= 0x3000 && word <= 0x303F) ||
135       (word >= 0x2000 && word <= 0x206F)) {
136     return FX_Charset::kChineseSimplified;
137   }
138 
139   if (((word >= 0x3040) && (word <= 0x309F)) ||
140       ((word >= 0x30A0) && (word <= 0x30FF)) ||
141       ((word >= 0x31F0) && (word <= 0x31FF)) ||
142       ((word >= 0xFF00) && (word <= 0xFFEF))) {
143     return FX_Charset::kShiftJIS;
144   }
145 
146   if (((word >= 0xAC00) && (word <= 0xD7AF)) ||
147       ((word >= 0x1100) && (word <= 0x11FF)) ||
148       ((word >= 0x3130) && (word <= 0x318F))) {
149     return FX_Charset::kHangul;
150   }
151 
152   if (word >= 0x0E00 && word <= 0x0E7F)
153     return FX_Charset::kThai;
154 
155   if ((word >= 0x0370 && word <= 0x03FF) || (word >= 0x1F00 && word <= 0x1FFF))
156     return FX_Charset::kMSWin_Greek;
157 
158   if ((word >= 0x0600 && word <= 0x06FF) || (word >= 0xFB50 && word <= 0xFEFC))
159     return FX_Charset::kMSWin_Arabic;
160 
161   if (word >= 0x0590 && word <= 0x05FF)
162     return FX_Charset::kMSWin_Hebrew;
163 
164   if (word >= 0x0400 && word <= 0x04FF)
165     return FX_Charset::kMSWin_Cyrillic;
166 
167   if (word >= 0x0100 && word <= 0x024F)
168     return FX_Charset::kMSWin_EasternEuropean;
169 
170   if (word >= 0x1E00 && word <= 0x1EFF)
171     return FX_Charset::kMSWin_Vietnamese;
172 
173   return FX_Charset::kANSI;
174 }
175 
176 CFX_Font::CFX_Font() = default;
177 
GetSubstFontItalicAngle() const178 int CFX_Font::GetSubstFontItalicAngle() const {
179   CFX_SubstFont* subst_font = GetSubstFont();
180   return subst_font ? subst_font->m_ItalicAngle : 0;
181 }
182 
183 #ifdef PDF_ENABLE_XFA
LoadFile(RetainPtr<IFX_SeekableReadStream> pFile,int nFaceIndex)184 bool CFX_Font::LoadFile(RetainPtr<IFX_SeekableReadStream> pFile,
185                         int nFaceIndex) {
186   m_ObjectTag = 0;
187 
188   auto pStreamRec = std::make_unique<FXFT_StreamRec>();
189   pStreamRec->base = nullptr;
190   pStreamRec->size = static_cast<unsigned long>(pFile->GetSize());
191   pStreamRec->pos = 0;
192   pStreamRec->descriptor.pointer = static_cast<void*>(pFile.Get());
193   pStreamRec->close = FTStreamClose;
194   pStreamRec->read = FTStreamRead;
195 
196   FT_Open_Args args;
197   args.flags = FT_OPEN_STREAM;
198   args.stream = pStreamRec.get();
199 
200   m_Face = CFX_Face::Open(CFX_GEModule::Get()->GetFontMgr()->GetFTLibrary(),
201                           &args, nFaceIndex);
202   if (!m_Face)
203     return false;
204 
205   m_pOwnedFile = std::move(pFile);
206   m_pOwnedStreamRec = std::move(pStreamRec);
207   m_Face->SetPixelSize(0, 64);
208   return true;
209 }
210 
211 #if !BUILDFLAG(IS_WIN)
SetFace(RetainPtr<CFX_Face> face)212 void CFX_Font::SetFace(RetainPtr<CFX_Face> face) {
213   ClearGlyphCache();
214   m_ObjectTag = 0;
215   m_Face = face;
216 }
217 
SetSubstFont(std::unique_ptr<CFX_SubstFont> subst)218 void CFX_Font::SetSubstFont(std::unique_ptr<CFX_SubstFont> subst) {
219   m_pSubstFont = std::move(subst);
220 }
221 #endif  // !BUILDFLAG(IS_WIN)
222 #endif  // PDF_ENABLE_XFA
223 
~CFX_Font()224 CFX_Font::~CFX_Font() {
225   m_FontData = {};  // m_FontData can't outive m_Face.
226   m_Face.Reset();
227 
228 #if BUILDFLAG(IS_APPLE)
229   ReleasePlatformResource();
230 #endif
231 }
232 
LoadSubst(const ByteString & face_name,bool bTrueType,uint32_t flags,int weight,int italic_angle,FX_CodePage code_page,bool bVertical)233 void CFX_Font::LoadSubst(const ByteString& face_name,
234                          bool bTrueType,
235                          uint32_t flags,
236                          int weight,
237                          int italic_angle,
238                          FX_CodePage code_page,
239                          bool bVertical) {
240   m_bVertical = bVertical;
241   m_ObjectTag = 0;
242   m_pSubstFont = std::make_unique<CFX_SubstFont>();
243   m_Face = CFX_GEModule::Get()->GetFontMgr()->GetBuiltinMapper()->FindSubstFont(
244       face_name, bTrueType, flags, weight, italic_angle, code_page,
245       m_pSubstFont.get());
246   if (m_Face) {
247     m_FontData = m_Face->GetData();
248   }
249 }
250 
GetGlyphWidth(uint32_t glyph_index) const251 int CFX_Font::GetGlyphWidth(uint32_t glyph_index) const {
252   return GetGlyphWidth(glyph_index, 0, 0);
253 }
254 
GetGlyphWidth(uint32_t glyph_index,int dest_width,int weight) const255 int CFX_Font::GetGlyphWidth(uint32_t glyph_index,
256                             int dest_width,
257                             int weight) const {
258   return GetOrCreateGlyphCache()->GetGlyphWidth(this, glyph_index, dest_width,
259                                                 weight);
260 }
261 
GetGlyphWidthImpl(uint32_t glyph_index,int dest_width,int weight) const262 int CFX_Font::GetGlyphWidthImpl(uint32_t glyph_index,
263                                 int dest_width,
264                                 int weight) const {
265   if (!m_Face)
266     return 0;
267 
268   return m_Face->GetGlyphWidth(glyph_index, dest_width, weight,
269                                m_pSubstFont.get());
270 }
271 
LoadEmbedded(pdfium::span<const uint8_t> src_span,bool force_vertical,uint64_t object_tag)272 bool CFX_Font::LoadEmbedded(pdfium::span<const uint8_t> src_span,
273                             bool force_vertical,
274                             uint64_t object_tag) {
275   m_bVertical = force_vertical;
276   m_ObjectTag = object_tag;
277   m_FontDataAllocation = DataVector<uint8_t>(src_span.begin(), src_span.end());
278   m_Face = CFX_GEModule::Get()->GetFontMgr()->NewFixedFace(
279       nullptr, m_FontDataAllocation, 0);
280   m_FontData = m_FontDataAllocation;
281   return !!m_Face;
282 }
283 
IsTTFont() const284 bool CFX_Font::IsTTFont() const {
285   return m_Face && m_Face->IsTtOt();
286 }
287 
GetAscent() const288 int CFX_Font::GetAscent() const {
289   if (!m_Face) {
290     return 0;
291   }
292   return NormalizeFontMetric(m_Face->GetAscender(), m_Face->GetUnitsPerEm());
293 }
294 
GetDescent() const295 int CFX_Font::GetDescent() const {
296   if (!m_Face) {
297     return 0;
298   }
299   return NormalizeFontMetric(m_Face->GetDescender(), m_Face->GetUnitsPerEm());
300 }
301 
GetGlyphBBox(uint32_t glyph_index)302 std::optional<FX_RECT> CFX_Font::GetGlyphBBox(uint32_t glyph_index) {
303   if (!m_Face)
304     return std::nullopt;
305 
306   if (m_Face->IsTricky()) {
307     int error = FT_Set_Char_Size(m_Face->GetRec(), 0, 1000 * 64, 72, 72);
308     if (error)
309       return std::nullopt;
310 
311     error = FT_Load_Glyph(m_Face->GetRec(), glyph_index,
312                           FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH);
313     if (error)
314       return std::nullopt;
315 
316     FT_Glyph glyph;
317     error = FT_Get_Glyph(m_Face->GetRec()->glyph, &glyph);
318     if (error)
319       return std::nullopt;
320 
321     FT_BBox cbox;
322     FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, &cbox);
323     int pixel_size_x = m_Face->GetRec()->size->metrics.x_ppem;
324     int pixel_size_y = m_Face->GetRec()->size->metrics.y_ppem;
325     FX_RECT result = ScaledFXRectFromFTPos(
326         cbox.xMin, cbox.yMax, cbox.xMax, cbox.yMin, pixel_size_x, pixel_size_y);
327     result.top = std::min(result.top, static_cast<int>(m_Face->GetAscender()));
328     result.bottom =
329         std::max(result.bottom, static_cast<int>(m_Face->GetDescender()));
330     FT_Done_Glyph(glyph);
331     if (!m_Face->SetPixelSize(0, 64)) {
332       return std::nullopt;
333     }
334     return result;
335   }
336   constexpr int kFlag = FT_LOAD_NO_SCALE | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
337   if (FT_Load_Glyph(m_Face->GetRec(), glyph_index, kFlag) != 0)
338     return std::nullopt;
339   int em = m_Face->GetUnitsPerEm();
340   return ScaledFXRectFromFTPos(FXFT_Get_Glyph_HoriBearingX(m_Face->GetRec()),
341                                FXFT_Get_Glyph_HoriBearingY(m_Face->GetRec()) -
342                                    FXFT_Get_Glyph_Height(m_Face->GetRec()),
343                                FXFT_Get_Glyph_HoriBearingX(m_Face->GetRec()) +
344                                    FXFT_Get_Glyph_Width(m_Face->GetRec()),
345                                FXFT_Get_Glyph_HoriBearingY(m_Face->GetRec()),
346                                em, em);
347 }
348 
IsItalic() const349 bool CFX_Font::IsItalic() const {
350   if (!m_Face)
351     return false;
352   if (m_Face->IsItalic()) {
353     return true;
354   }
355 
356   ByteString str = m_Face->GetStyleName();
357   str.MakeLower();
358   return str.Contains("italic");
359 }
360 
IsBold() const361 bool CFX_Font::IsBold() const {
362   return m_Face && m_Face->IsBold();
363 }
364 
IsFixedWidth() const365 bool CFX_Font::IsFixedWidth() const {
366   return m_Face && m_Face->IsFixedWidth();
367 }
368 
369 #if defined(PDF_USE_SKIA)
IsSubstFontBold() const370 bool CFX_Font::IsSubstFontBold() const {
371   CFX_SubstFont* subst_font = GetSubstFont();
372   return subst_font && subst_font->GetOriginalWeight() >= FXFONT_FW_BOLD;
373 }
374 #endif
375 
GetPsName() const376 ByteString CFX_Font::GetPsName() const {
377   if (!m_Face)
378     return ByteString();
379 
380   ByteString psName = FT_Get_Postscript_Name(m_Face->GetRec());
381   if (psName.IsEmpty())
382     psName = kUntitledFontName;
383   return psName;
384 }
385 
GetFamilyName() const386 ByteString CFX_Font::GetFamilyName() const {
387   if (!m_Face && !m_pSubstFont)
388     return ByteString();
389   if (m_Face)
390     return m_Face->GetFamilyName();
391   return m_pSubstFont->m_Family;
392 }
393 
GetFamilyNameOrUntitled() const394 ByteString CFX_Font::GetFamilyNameOrUntitled() const {
395   ByteString facename = GetFamilyName();
396   return facename.IsEmpty() ? kUntitledFontName : facename;
397 }
398 
GetBaseFontName() const399 ByteString CFX_Font::GetBaseFontName() const {
400   ByteString psname = GetPsName();
401   if (!psname.IsEmpty() && psname != kUntitledFontName)
402     return psname;
403   if (m_Face) {
404     ByteString style = m_Face->GetStyleName();
405     ByteString facename = GetFamilyNameOrUntitled();
406     if (IsTTFont())
407       facename.Remove(' ');
408     if (ShouldAppendStyle(style))
409       facename += (IsTTFont() ? "," : " ") + style;
410     return facename;
411   }
412   if (m_pSubstFont)
413     return m_pSubstFont->m_Family;
414   return ByteString();
415 }
416 
GetRawBBox() const417 std::optional<FX_RECT> CFX_Font::GetRawBBox() const {
418   if (!m_Face)
419     return std::nullopt;
420   return m_Face->GetBBox();
421 }
422 
GetBBox() const423 std::optional<FX_RECT> CFX_Font::GetBBox() const {
424   std::optional<FX_RECT> result = GetRawBBox();
425   if (!result.has_value())
426     return result;
427 
428   int em = m_Face->GetUnitsPerEm();
429   if (em != 0) {
430     FX_RECT& bbox = result.value();
431     bbox.left = pdfium::saturated_cast<int32_t>((bbox.left * 1000.0f) / em);
432     bbox.top = pdfium::saturated_cast<int32_t>((bbox.top * 1000.0f) / em);
433     bbox.right = pdfium::saturated_cast<int32_t>((bbox.right * 1000.0f) / em);
434     bbox.bottom = pdfium::saturated_cast<int32_t>((bbox.bottom * 1000.0f) / em);
435   }
436   return result;
437 }
438 
GetOrCreateGlyphCache() const439 RetainPtr<CFX_GlyphCache> CFX_Font::GetOrCreateGlyphCache() const {
440   if (!m_GlyphCache)
441     m_GlyphCache = CFX_GEModule::Get()->GetFontCache()->GetGlyphCache(this);
442   return m_GlyphCache;
443 }
444 
ClearGlyphCache()445 void CFX_Font::ClearGlyphCache() {
446   m_GlyphCache = nullptr;
447 }
448 
LoadGlyphPathImpl(uint32_t glyph_index,int dest_width) const449 std::unique_ptr<CFX_Path> CFX_Font::LoadGlyphPathImpl(uint32_t glyph_index,
450                                                       int dest_width) const {
451   if (!m_Face)
452     return nullptr;
453 
454   return m_Face->LoadGlyphPath(glyph_index, dest_width, m_bVertical,
455                                m_pSubstFont.get());
456 }
457 
LoadGlyphBitmap(uint32_t glyph_index,bool bFontStyle,const CFX_Matrix & matrix,int dest_width,int anti_alias,CFX_TextRenderOptions * text_options) const458 const CFX_GlyphBitmap* CFX_Font::LoadGlyphBitmap(
459     uint32_t glyph_index,
460     bool bFontStyle,
461     const CFX_Matrix& matrix,
462     int dest_width,
463     int anti_alias,
464     CFX_TextRenderOptions* text_options) const {
465   return GetOrCreateGlyphCache()->LoadGlyphBitmap(this, glyph_index, bFontStyle,
466                                                   matrix, dest_width,
467                                                   anti_alias, text_options);
468 }
469 
LoadGlyphPath(uint32_t glyph_index,int dest_width) const470 const CFX_Path* CFX_Font::LoadGlyphPath(uint32_t glyph_index,
471                                         int dest_width) const {
472   return GetOrCreateGlyphCache()->LoadGlyphPath(this, glyph_index, dest_width);
473 }
474 
475 #if defined(PDF_USE_SKIA)
GetDeviceCache() const476 CFX_TypeFace* CFX_Font::GetDeviceCache() const {
477   return GetOrCreateGlyphCache()->GetDeviceCache(this);
478 }
479 #endif
480