Debian Codegraph @

podofo/test/unit/FontTest.cpp

raw
1 // SPDX-FileCopyrightText: 2009 Dominik Seichter <[email protected]>
2 // SPDX-FileCopyrightText: 2021 Francesco Pretto <[email protected]>
3 // SPDX-License-Identifier: MIT-0
4
5 #include <PdfTest.h>
6
7 #include <thread>
8
9 #include <podofo/private/FreetypePrivate.h>
10 #ifdef PODOFO_ENABLE_AFDKO
11 #include <podofo/private/FontUtilsAFDKO.h>
12 #endif
13
14 using namespace std;
15 using namespace PoDoFo;
16
17 TEST_CASE("TestEmbedFont")
18 {
19 PdfMemDocument doc;
20 doc.Load(TestUtils::GetTestInputFilePath("TestEmbedFont.pdf"));
21
22 unique_ptr<PdfFont> font;
23 (void)PdfFont::TryCreateFromObject(doc.GetObjects().MustGetObject(PdfReference(6, 0)), font);
24
25 // The font is not embedded in this document
26 REQUIRE(font->GetMetrics().GetOrLoadFontFileData().size() == 0);
27
28 // Create a substitute font from a font without a "/FontFile2" entry
29 PdfFont* substituteFont;
30 REQUIRE(font->TryCreateProxyFont(substituteFont));
31 // Add all used GIDs for this font. The following is hardcoded:
32 // this should require scanning of the entire document page contents
33 substituteFont->AddSubsetCIDs(PdfString::FromRaw("TEST"));
34
35 {
36 // Substitute existing font in the resources of the oage
37 auto& page = doc.GetPages().GetPageAt(0);
38 static_cast<PdfResourceOperations&>(page.GetResources()).AddResource(PdfResourceType::Font, "Ft0", substituteFont->GetObject());
39 }
40
41 doc.Save(TestUtils::GetTestOutputFilePath("TestEmbedFont.pdf"));
42
43 // Reload the file and verify the font has now font file data
44 doc.Load(TestUtils::GetTestOutputFilePath("TestEmbedFont.pdf"));
45 {
46 auto& page = doc.GetPages().GetPageAt(0);
47 auto fontObj = page.GetResources().GetResource(PdfResourceType::Font, "Ft0");
48 (void)PdfFont::TryCreateFromObject(*fontObj, font);
49 REQUIRE(font->GetMetrics().GetOrLoadFontFileData().size() != 0);
50 }
51 }
52
53 // Faces are created on a thread local FreeType library instance: freeing
54 // them after the creation thread was disposed must not access any storage
55 // that went away with that thread
56 TEST_CASE("TestFreeFontAfterCreationThreadDisposal")
57 {
58 unique_ptr<PdfMemDocument> doc;
59 thread creator([&doc]
60 {
61 doc.reset(new PdfMemDocument());
62 (void)doc->GetFonts().GetOrCreateFont(TestUtils::GetTestInputFilePath("Fonts", "LiberationSans-Regular.ttf"));
63 });
64 creator.join();
65
66 doc.reset();
67 }
68
69 TEST_CASE("TestCreateFontExtract")
70 {
71 PdfMemDocument doc;
72 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
73
74 // Play a bit with font path caching
75 auto fontPath1 = TestUtils::GetTestInputFilePath("Fonts", "LiberationSans-Regular.ttf");
76 auto fontPath2 = TestUtils::GetTestInputFilePath("Fonts", "..", "Fonts", "LiberationSans-Regular.ttf");
77 auto fontRef = &doc.GetFonts().GetOrCreateFont(fontPath1);
78 auto& font = doc.GetFonts().GetOrCreateFont(fontPath2);
79
80 PdfFont* fontFromBuffer;
81
82 {
83 charbuff fontbuffer;
84 utls::ReadTo(fontbuffer, TestUtils::GetTestInputFilePath("Fonts", "LiberationSans-Regular.ttf"));
85 fontFromBuffer = &doc.GetFonts().GetOrCreateFontFromBuffer(fontbuffer);
86 }
87
88 // The matched fonts should be the same one
89 REQUIRE(&font == fontRef);
90
91 {
92 PdfPainter painter;
93 painter.SetCanvas(page);
94
95 painter.TextState.SetFont(font, 30.0);
96 painter.DrawText("ěščř", 100, 600);
97
98 painter.TextState.SetFont(*fontFromBuffer, 30.0);
99 painter.DrawText("ěščř buffer", 100, 500);
100 painter.FinishDrawing();
101 }
102
103 auto outputpath = TestUtils::GetTestOutputFilePath("TestCreateFontExtract.pdf");
104
105 try
106 {
107 FileStreamDevice stream(outputpath, FileMode::Create);
108 doc.Save(stream);
109 }
110 catch (const PdfError& error)
111 {
112 // Don't continue further the test in this case
113 if (error.GetCode() == PdfErrorCode::UnsupportedFontFormat)
114 return;
115
116 throw;
117 }
118
119 // FIXME: The test crash if we tried to extract
120 // text directly on the original "doc" page
121
122 PdfMemDocument doc2;
123 doc2.Load(outputpath);
124
125 vector<PdfTextEntry> entries;
126 doc2.GetPages().GetPageAt(0).ExtractTextTo(entries);
127
128 REQUIRE(entries[0].Text == "ěščř");
129 REQUIRE(entries[0].X == 100);
130 REQUIRE(entries[0].Y == 600);
131
132 REQUIRE(entries[1].Text == "ěščř buffer");
133 REQUIRE(entries[1].X == 100);
134 REQUIRE(entries[1].Y == 500);
135 }
136
137 TEST_CASE("TestGetOrCreateFontAfterEmbedAndReset")
138 {
139 auto fontPath = TestUtils::GetTestInputFilePath("Fonts", "LiberationSans-Regular.ttf");
140
141 PdfMemDocument doc;
142 auto& font1 = doc.GetFonts().GetOrCreateFont(fontPath);
143 REQUIRE(font1.GetMetrics().GetFontName() == "LiberationSans");
144
145 doc.GetFonts().EmbedFonts();
146 doc.Reset();
147
148 auto& font2 = doc.GetFonts().GetOrCreateFont(fontPath);
149 REQUIRE(font2.GetMetrics().GetFontName() == "LiberationSans");
150 }
151
152 TEST_CASE("TestSimpleFontMetricsReferences")
153 {
154 PdfMemDocument doc;
155 doc.Load(TestUtils::GetTestInputFilePath("TestFontWidthsRef.pdf"));
156 auto& page = doc.GetPages().GetPageAt(0);
157 auto& resources = page.GetResources();
158
159 // /MediaBox[2] and /MediaBox[3] of the page are references
160 auto mediaBox = page.GetMediaBoxRaw();
161 ASSERT_EQUAL(mediaBox.X2, 595.0);
162 ASSERT_EQUAL(mediaBox.Y2, 842.0);
163
164 // "/Ft0" is a /TrueType font where /Widths[32], /Widths[33]
165 // and /FontBBox[0], /FontBBox[2] are references
166 unique_ptr<PdfFont> font;
167 REQUIRE(PdfFont::TryCreateFromObject(*resources.GetResource(PdfResourceType::Font, "Ft0"), font));
168 ASSERT_EQUAL(font->GetMetrics().GetGlyphWidth(32, PdfGlyphAccess::ReadMetrics), 0.278);
169 ASSERT_EQUAL(font->GetMetrics().GetGlyphWidth(33, PdfGlyphAccess::ReadMetrics), 0.333);
170 ASSERT_EQUAL(font->GetMetrics().GetGlyphWidth(34, PdfGlyphAccess::ReadMetrics), 0.474);
171
172 auto bbox = font->GetMetrics().GetBoundingBox();
173 ASSERT_EQUAL(bbox.X1, -0.628);
174 ASSERT_EQUAL(bbox.Y1, -0.376);
175 ASSERT_EQUAL(bbox.X2, 2.0);
176 ASSERT_EQUAL(bbox.Y2, 1.056);
177
178 // "/Ft1" is a Standard14 font, which parses /Widths on its own
179 unique_ptr<PdfFont> std14Font;
180 REQUIRE(PdfFont::TryCreateFromObject(*resources.GetResource(PdfResourceType::Font, "Ft1"), std14Font));
181 ASSERT_EQUAL(std14Font->GetMetrics().GetGlyphWidth(0, PdfGlyphAccess::ReadMetrics), 0.25);
182 ASSERT_EQUAL(std14Font->GetMetrics().GetGlyphWidth(1, PdfGlyphAccess::ReadMetrics), 0.555);
183 ASSERT_EQUAL(std14Font->GetMetrics().GetGlyphWidth(2, PdfGlyphAccess::ReadMetrics), 0.408);
184
185 // "/Ft2" is a Type3 font with a custom /FontMatrix, where
186 // /FontMatrix[0], /FontBBox[2] and /Widths[0] are references
187 unique_ptr<PdfFont> type3Font;
188 REQUIRE(PdfFont::TryCreateFromObject(*resources.GetResource(PdfResourceType::Font, "Ft2"), type3Font));
189 auto& type3Metrics = type3Font->GetMetrics();
190 ASSERT_EQUAL(type3Metrics.GetMatrix()[0], 0.01);
191
192 // The /FontMatrix scales both the widths and the bounding box
193 ASSERT_EQUAL(type3Metrics.GetGlyphWidth(0, PdfGlyphAccess::ReadMetrics), 0.5);
194
195 // The /Differences of the Type3 font encoding are "97 /spade 98 /bullet",
196 // where both names and the first code are references
197 auto& encoding = type3Font->GetEncoding();
198 REQUIRE(encoding.GetCodePoint(97) == U'♠');
199 }
200
201 TEST_CASE("TestCIDFontMetricsReferences")
202 {
203 PdfMemDocument doc;
204 doc.Load(TestUtils::GetTestInputFilePath("TestFontWidthsRefCID.pdf"));
205 auto& resources = doc.GetPages().GetPageAt(0).GetResources();
206
207 unique_ptr<PdfFont> font;
208 REQUIRE(PdfFont::TryCreateFromObject(*resources.GetResource(PdfResourceType::Font, "C0_0"), font));
209 auto& metrics = font->GetMetrics();
210
211 // CID 0 is not covered by /W and falls back to /DW
212 ASSERT_EQUAL(metrics.GetGlyphWidth(0, PdfGlyphAccess::ReadMetrics), 1.0);
213
214 // The sub-array of the range starting at CID 1 is a reference
215 ASSERT_EQUAL(metrics.GetGlyphWidth(1, PdfGlyphAccess::ReadMetrics), 0.207);
216 ASSERT_EQUAL(metrics.GetGlyphWidth(16, PdfGlyphAccess::ReadMetrics), 0.334);
217
218 // The first CID of the 17-26 range is a reference
219 ASSERT_EQUAL(metrics.GetGlyphWidth(17, PdfGlyphAccess::ReadMetrics), 0.462);
220 ASSERT_EQUAL(metrics.GetGlyphWidth(26, PdfGlyphAccess::ReadMetrics), 0.462);
221
222 // Both the last CID and the width of the 27-28 range are references
223 ASSERT_EQUAL(metrics.GetGlyphWidth(27, PdfGlyphAccess::ReadMetrics), 0.238);
224 ASSERT_EQUAL(metrics.GetGlyphWidth(28, PdfGlyphAccess::ReadMetrics), 0.238);
225
226 ASSERT_EQUAL(metrics.GetGlyphWidth(29, PdfGlyphAccess::ReadMetrics), 0.605);
227
228 // The first element of the sub-array starting at CID 32 is a reference
229 ASSERT_EQUAL(metrics.GetGlyphWidth(32, PdfGlyphAccess::ReadMetrics), 0.344);
230 ASSERT_EQUAL(metrics.GetGlyphWidth(33, PdfGlyphAccess::ReadMetrics), 0.748);
231
232 // /FontBBox[0] and /FontBBox[3] of the descriptor are references
233 auto bbox = metrics.GetBoundingBox();
234 ASSERT_EQUAL(bbox.X1, -0.025);
235 ASSERT_EQUAL(bbox.Y1, -0.254);
236 ASSERT_EQUAL(bbox.X2, 1.0);
237 ASSERT_EQUAL(bbox.Y2, 0.88);
238
239 // /Matrix[0], /Matrix[5] and /BBox[2], /BBox[3] of the form XObject are references
240 unique_ptr<PdfXObjectForm> form;
241 REQUIRE(PdfXObject::TryCreateFromObject<PdfXObjectForm>(
242 *resources.GetResource(PdfResourceType::XObject, "Fm0"), form));
243 ASSERT_EQUAL(form->GetMatrix()[0], 2.0);
244 ASSERT_EQUAL(form->GetMatrix()[5], 15.0);
245 ASSERT_EQUAL(form->GetRect().Width, 200.0);
246 ASSERT_EQUAL(form->GetRect().Height, 100.0);
247 }
248
249 #ifdef PODOFO_HAVE_FONTCONFIG
250
251 #include <fontconfig/fontconfig.h>
252
253 static bool getFontInfo(FcPattern* font, string& fontFamily, string& fontPath,
254 PdfFontStyle& style);
255 static void testSingleFont(FcPattern* font);
256
257 TEST_CASE("TestFontConfigMatch")
258 {
259 // Create a simple platform invariant FC config
260 string fontconf =
261 R"(<?xml version="1.0"?>
262 <!DOCTYPE fontconfig SYSTEM "fonts.dtd">
263 <fontconfig>
264 <dir>FONT_DIR</dir>
265 <dir prefix="xdg">fonts</dir>
266 <cachedir>FONT_CACHE_DIR</cachedir>
267 <cachedir prefix="xdg">fontconfig</cachedir>
268 </fontconfig>
269 )";
270
271 utls::Replace(fontconf, "FONT_DIR", TestUtils::GetTestInputFilePath("Fonts"));
272 utls::Replace(fontconf, "FONT_CACHE_DIR", TestUtils::GetTestOutputFilePath("TestFontConfig"));
273
274 PdfFontManager::SetFontConfigWrapper(std::make_shared<PdfFontConfigWrapper>(fontconf));
275
276 {
277 PdfFontSearchParams parmas;
278
279 auto metrics = PdfFontManager::SearchFontMetrics("NotoSans-Regular", parmas);
280 REQUIRE(metrics->GetFontName() == "NotoSans-Regular");
281
282 metrics = PdfFontManager::SearchFontMetrics("LiberationSans", parmas);
283 REQUIRE(metrics->GetFontName() == "LiberationSans");
284
285 metrics = PdfFontManager::SearchFontMetrics("Liberation Sans", parmas);
286 REQUIRE(metrics->GetFontName() == "LiberationSans");
287
288 metrics = PdfFontManager::SearchFontMetrics("LiberationMono", parmas);
289 REQUIRE(metrics->GetFontName() == "LiberationMono");
290
291 parmas.Style = PdfFontStyle::Italic;
292 metrics = PdfFontManager::SearchFontMetrics("LiberationSans", parmas);
293 REQUIRE(metrics->GetFontName() == "LiberationSans-Italic");
294
295 parmas.Style = PdfFontStyle::Bold;
296 metrics = PdfFontManager::SearchFontMetrics("Noto Sans", parmas);
297 REQUIRE(metrics->GetFontName() == "NotoSans-Bold");
298
299 parmas.MatchBehavior |= PdfFontMatchBehaviorFlags::SkipMatchPostScriptName;
300 metrics = PdfFontManager::SearchFontMetrics("LiberationSans", parmas);
301 REQUIRE(metrics->GetFontName() == "LiberationSans-Bold");
302 }
303 }
304
305 // Disable load all fonts for now
306 TEST_CASE("TestFonts", "[.]")
307 {
308 // Get all installed fonts
309 auto pattern = FcPatternCreate();
310 auto objectSet = FcObjectSetBuild(FC_FAMILY, FC_STYLE, FC_FILE, FC_SLANT, FC_WEIGHT, nullptr);
311 auto fontSet = FcFontList(nullptr, pattern, objectSet);
312
313 FcObjectSetDestroy(objectSet);
314 FcPatternDestroy(pattern);
315
316 if (fontSet == nullptr)
317 {
318 INFO("Unable to search for fonts");
319 return;
320 }
321
322 INFO(utls::Format("Testing {} fonts", fontSet->nfont));
323 for (int i = 0; i < fontSet->nfont; i++)
324 testSingleFont(fontSet->fonts[i]);
325
326 FcFontSetDestroy(fontSet);
327 }
328
329 void testSingleFont(FcPattern* font)
330 {
331 PdfMemDocument doc;
332 string fontFamily;
333 string fontPath;
334 PdfFontStyle style;
335 PdfFontConfigSearchParams fcParams;
336 auto& fcWrapper = PdfFontManager::GetFontConfigWrapper();
337
338 if (getFontInfo(font, fontFamily, fontPath, style))
339 {
340 unsigned faceIndex;
341 fcParams.Style = style;
342 fontPath = fcWrapper.SearchFontPath(fontFamily, fcParams, faceIndex);
343 if (fontPath.length() != 0)
344 {
345 PdfFontSearchParams params;
346 params.Style = style;
347 INFO(utls::Format("Font failed: {}", fontPath));
348 (void)doc.GetFonts().SearchFont(fontFamily, params);
349 }
350 }
351 }
352
353 bool getFontInfo(FcPattern* font, string& fontFamily, string& fontPath,
354 PdfFontStyle& style)
355 {
356 FcChar8* family = nullptr;
357 FcChar8* path = nullptr;
358 int slant;
359 int weight;
360 style = PdfFontStyle::Regular;
361
362 if (FcPatternGetString(font, FC_FAMILY, 0, &family) == FcResultMatch)
363 {
364 fontFamily = reinterpret_cast<char*>(family);
365 if (FcPatternGetString(font, FC_FILE, 0, &path) == FcResultMatch)
366 {
367 fontPath = reinterpret_cast<char*>(path);
368
369 if (FcPatternGetInteger(font, FC_SLANT, 0, &slant) == FcResultMatch)
370 {
371 if (slant == FC_SLANT_ITALIC || slant == FC_SLANT_OBLIQUE)
372 style |= PdfFontStyle::Italic;
373
374 if (FcPatternGetInteger(font, FC_WEIGHT, 0, &weight) == FcResultMatch)
375 {
376 if (weight >= FC_WEIGHT_BOLD)
377 style |= PdfFontStyle::Bold;
378
379 return true;
380 }
381 }
382 //free( file );
383 }
384 //free( family );
385 }
386
387 return false;
388 }
389
390 #endif // PODOFO_HAVE_FONTCONFIG
391
392 #ifdef PODOFO_ENABLE_AFDKO
393
394 TEST_CASE("TestConversionPBF2CFF")
395 {
396 {
397 charbuff font1;
398 utls::ReadTo(font1, TestUtils::GetTestInputFilePath("FontsType1", "Lato-Regular.pfb"));
399
400 charbuff cff;
401 afdko::ConvertFontType1ToCFF(font1, cff);
402
403 TestUtils::IsBufferEqual(cff, TestUtils::GetTestInputFilePath("FontsType1", "ConvCFF", "Lato-Regular.cff"));
404 }
405
406 {
407 charbuff font1;
408 utls::ReadTo(font1, TestUtils::GetTestInputFilePath("FontsType1", "lmb10.pfb"));
409
410 charbuff cff;
411 afdko::ConvertFontType1ToCFF(font1, cff);
412
413 TestUtils::IsBufferEqual(cff, TestUtils::GetTestInputFilePath("FontsType1", "ConvCFF", "lmb10.cff"));
414 }
415 }
416
417 TEST_CASE("TestSubsetCFFDegenerate")
418 {
419 charbuff font1;
420 utls::ReadTo(font1, TestUtils::GetTestInputFilePath("FontsType1", "Degenerate1Glyph.cff"));
421 auto metrics = PdfFontMetrics::CreateFromBuffer(font1);
422
423 vector<PdfCharGIDInfo> subsetInfos;
424 subsetInfos.push_back({ 1, 1, PdfGID(0, 0) });
425
426 PdfCIDSystemInfo cidInfo;
427 cidInfo.Registry = PdfString("Adobe");
428 cidInfo.Ordering = PdfString("Test");
429 cidInfo.Supplement = 0;
430
431 charbuff cff;
432 afdko::SubsetFontCFF(*metrics, subsetInfos, cidInfo, cff);
433
434 TestUtils::IsBufferEqual(cff, TestUtils::GetTestInputFilePath("FontsType1", "SubsetDegenerate1Glyph.cff"));
435 }
436
437 #endif // PODOFO_ENABLE_AFDKO