1 /*
2 * Copyright 2014 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/core/SkBitmap.h"
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkColor.h"
11 #include "include/core/SkFont.h"
12 #include "include/core/SkFontArguments.h"
13 #include "include/core/SkFontMgr.h"
14 #include "include/core/SkFontStyle.h"
15 #include "include/core/SkPaint.h"
16 #include "include/core/SkPoint.h"
17 #include "include/core/SkRefCnt.h"
18 #include "include/core/SkScalar.h"
19 #include "include/core/SkStream.h"
20 #include "include/core/SkString.h"
21 #include "include/core/SkTypeface.h"
22 #include "include/core/SkTypes.h"
23 #include "include/ports/SkFontMgr_android.h"
24 #include "include/private/base/SkDebug.h"
25 #include "include/private/base/SkFixed.h"
26 #include "include/private/base/SkTArray.h"
27 #include "include/private/base/SkTDArray.h"
28 #include "src/core/SkOSFile.h"
29 #include "src/core/SkTHash.h"
30 #include "src/ports/SkFontMgr_android_parser.h"
31 #include "tests/Test.h"
32 #include "tools/Resources.h"
33 #include "tools/flags/CommandLineFlags.h"
34
35 #ifdef SK_TYPEFACE_FACTORY_FONTATIONS
36 #include "include/ports/SkFontScanner_Fontations.h"
37 #endif
38 #ifdef SK_TYPEFACE_FACTORY_FREETYPE
39 #include "include/ports/SkFontScanner_FreeType.h"
40 #endif
41
42 #include <algorithm>
43 #include <climits>
44 #include <cmath>
45 #include <cstdint>
46 #include <cstdio>
47 #include <memory>
48 #include <string>
49
DECLARE_bool(verboseFontMgr)50 DECLARE_bool(verboseFontMgr)
51
52 int CountFallbacks(SkTDArray<FontFamily*> fontFamilies) {
53 int countOfFallbackFonts = 0;
54 for (int i = 0; i < fontFamilies.size(); i++) {
55 if (fontFamilies[i]->fIsFallbackFont) {
56 countOfFallbackFonts++;
57 }
58 }
59 return countOfFallbackFonts;
60 }
61
62 //https://tools.ietf.org/html/rfc5234#appendix-B.1
isALPHA(int c)63 static bool isALPHA(int c) {
64 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
65 }
66
67 //https://tools.ietf.org/html/rfc5234#appendix-B.1
isDIGIT(int c)68 static bool isDIGIT(int c) {
69 return ('0' <= c && c <= '9');
70 }
71
ValidateLoadedFonts(SkTDArray<FontFamily * > fontFamilies,const char * firstExpectedFile,skiatest::Reporter * reporter)72 static void ValidateLoadedFonts(SkTDArray<FontFamily*> fontFamilies, const char* firstExpectedFile,
73 skiatest::Reporter* reporter) {
74 REPORTER_ASSERT(reporter, fontFamilies[0]->fNames.size() == 5);
75 REPORTER_ASSERT(reporter, !strcmp(fontFamilies[0]->fNames[0].c_str(), "sans-serif"));
76 REPORTER_ASSERT(reporter,
77 !strcmp(fontFamilies[0]->fFonts[0].fFileName.c_str(), firstExpectedFile));
78 REPORTER_ASSERT(reporter, !fontFamilies[0]->fIsFallbackFont);
79
80 // Check that the languages are all sane.
81 for (const auto& fontFamily : fontFamilies) {
82 for (const auto& lang : fontFamily->fLanguages) {
83 const SkString& langString = lang.getTag();
84 for (size_t i = 0; i < langString.size(); ++i) {
85 int c = langString[i];
86 REPORTER_ASSERT(reporter, isALPHA(c) || isDIGIT(c) || '-' == c);
87 }
88 }
89 }
90
91 // All file names in the test configuration files start with a capital letter.
92 // This is not a general requirement, but it is true of all the test configuration data.
93 // Verifying ensures the filenames have been read sanely and have not been 'sliced'.
94 for (int i = 0; i < fontFamilies.size(); ++i) {
95 FontFamily& family = *fontFamilies[i];
96 for (int j = 0; j < family.fFonts.size(); ++j) {
97 FontFileInfo& file = family.fFonts[j];
98 REPORTER_ASSERT(reporter, !file.fFileName.isEmpty() &&
99 file.fFileName[0] >= 'A' &&
100 file.fFileName[0] <= 'Z');
101 }
102 }
103 }
104
DumpFiles(const FontFamily & fontFamily)105 static void DumpFiles(const FontFamily& fontFamily) {
106 for (int j = 0; j < fontFamily.fFonts.size(); ++j) {
107 const FontFileInfo& ffi = fontFamily.fFonts[j];
108 SkDebugf(" file (%d) %s#%d", ffi.fWeight, ffi.fFileName.c_str(), ffi.fIndex);
109 for (const auto& coordinate : ffi.fVariationDesignPosition) {
110 SkDebugf(" @'%c%c%c%c'=%f",
111 (char)((coordinate.axis >> 24) & 0xFF),
112 (char)((coordinate.axis >> 16) & 0xFF),
113 (char)((coordinate.axis >> 8) & 0xFF),
114 (char)((coordinate.axis) & 0xFF),
115 coordinate.value);
116 }
117 SkDebugf("\n");
118 }
119 }
120
DumpLoadedFonts(SkTDArray<FontFamily * > fontFamilies,const char * label)121 static void DumpLoadedFonts(SkTDArray<FontFamily*> fontFamilies, const char* label) {
122 if (!FLAGS_verboseFontMgr) {
123 return;
124 }
125
126 SkDebugf("\n--- Dumping %s\n", label);
127 for (int i = 0; i < fontFamilies.size(); ++i) {
128 SkDebugf("Family %d:\n", i);
129 switch(fontFamilies[i]->fVariant) {
130 case kElegant_FontVariant: SkDebugf(" elegant\n"); break;
131 case kCompact_FontVariant: SkDebugf(" compact\n"); break;
132 default: break;
133 }
134 SkDebugf(" basePath %s\n", fontFamilies[i]->fBasePath.c_str());
135 if (!fontFamilies[i]->fLanguages.empty()) {
136 SkDebugf(" language");
137 for (const auto& lang : fontFamilies[i]->fLanguages) {
138 SkDebugf(" %s", lang.getTag().c_str());
139 }
140 SkDebugf("\n");
141 }
142 for (int j = 0; j < fontFamilies[i]->fNames.size(); ++j) {
143 SkDebugf(" name %s\n", fontFamilies[i]->fNames[j].c_str());
144 }
145 DumpFiles(*fontFamilies[i]);
146 for (const auto& [unused, fallbackFamily] : fontFamilies[i]->fallbackFamilies) {
147 SkDebugf(" Fallback for: %s\n", fallbackFamily->fFallbackFor.c_str());
148 DumpFiles(*fallbackFamily);
149 }
150 }
151 SkDebugf("\n\n");
152 }
153
test_parse_fixed_r(skiatest::Reporter * reporter,double low,double high,double inc)154 template <int N, typename T> static double test_parse_fixed_r(skiatest::Reporter* reporter,
155 double low, double high, double inc)
156 {
157 double SK_FixedMax_double = nextafter(1 << (sizeof(T) * CHAR_BIT - N - 1), 0.0);
158 double SK_FixedEpsilon_double = (1.0 / (1 << N));
159 double maxError = 0;
160 char buffer[64];
161 for (double f = low; f < high; f += inc) {
162 SkString s;
163 // 'sprintf' formatting as expected depends on the current locale being "C".
164 // We currently expect tests and tools to run in the "C" locale.
165 sprintf(buffer, "%.20f", f);
166 T fix;
167 bool b = parse_fixed<N>(buffer, &fix);
168 if (b) {
169 double f2 = fix * SK_FixedEpsilon_double;
170 double error = fabs(f - f2);
171 REPORTER_ASSERT(reporter, error <= SK_FixedEpsilon_double);
172 maxError = std::max(maxError, error);
173 } else {
174 REPORTER_ASSERT(reporter, f < -SK_FixedMax_double || SK_FixedMax_double < f);
175 }
176 }
177
178 //SkDebugf("maxError: %.20f\n", maxError);
179 return maxError;
180 }
181
test_parse_fixed(skiatest::Reporter * reporter)182 static void test_parse_fixed(skiatest::Reporter* reporter) {
183 test_parse_fixed_r<27, int32_t>(reporter, -8.1, -7.9, 0.000001);
184 test_parse_fixed_r<27, int32_t>(reporter, -0.1, 0.1, 0.000001);
185 test_parse_fixed_r<27, int32_t>(reporter, 7.9, 8.1, 0.000001);
186 test_parse_fixed_r<16, int32_t>(reporter, -0.125, 0.125, 1.0 / (1 << 19));
187 test_parse_fixed_r<16, int32_t>(reporter, -32768.125, -32766.875, 1.0 / (1 << 17));
188 test_parse_fixed_r<16, int32_t>(reporter, 32766.875, 32768.125, 1.0 / (1 << 17));
189 test_parse_fixed_r<16, int32_t>(reporter, -1.1, 1.1, 0.0001);
190
191 SkFixed fix;
192 REPORTER_ASSERT(reporter, !parse_fixed<27>("-17.1", &fix));
193 REPORTER_ASSERT(reporter, !parse_fixed<16>("32768", &fix));
194 REPORTER_ASSERT(reporter, !parse_fixed<16>("", &fix));
195 REPORTER_ASSERT(reporter, !parse_fixed<16>(".", &fix));
196 REPORTER_ASSERT(reporter, !parse_fixed<16>("123.", &fix));
197 REPORTER_ASSERT(reporter, !parse_fixed<16>("a", &fix));
198 REPORTER_ASSERT(reporter, !parse_fixed<16>(".123a", &fix));
199 }
200
201 #ifdef SK_TYPEFACE_FACTORY_FONTATIONS
202 #define DEF_TEST_FONTATIONS(name, reporter) \
203 DEF_TEST(name##Fontations, reporter) { name(reporter, SkFontScanner_Make_Fontations()); }
204 #else
205 #define DEF_TEST_FONTATIONS(name, reporter)
206 #endif
207
208 #define DEF_TEST_SCANNERS(name, reporter) \
209 static void name(skiatest::Reporter*, std::unique_ptr<SkFontScanner>); \
210 DEF_TEST(name, reporter) { name(reporter, SkFontScanner_Make_FreeType()); } \
211 DEF_TEST_FONTATIONS(name, reporter) \
212 void name(skiatest::Reporter* reporter, std::unique_ptr<SkFontScanner> fs)
213
DEF_TEST_SCANNERS(FontMgrAndroidParser,reporter)214 DEF_TEST_SCANNERS(FontMgrAndroidParser, reporter) {
215 test_parse_fixed(reporter);
216
217 bool resourcesMissing = false;
218
219 SkTDArray<FontFamily*> preV17FontFamilies;
220 SkFontMgr_Android_Parser::GetCustomFontFamilies(preV17FontFamilies,
221 SkString("/custom/font/path/"),
222 GetResourcePath("android_fonts/pre_v17/system_fonts.xml").c_str(),
223 GetResourcePath("android_fonts/pre_v17/fallback_fonts.xml").c_str());
224
225 if (preV17FontFamilies.size() > 0) {
226 REPORTER_ASSERT(reporter, preV17FontFamilies.size() == 14);
227 REPORTER_ASSERT(reporter, CountFallbacks(preV17FontFamilies) == 10);
228
229 DumpLoadedFonts(preV17FontFamilies, "pre version 17");
230 ValidateLoadedFonts(preV17FontFamilies, "Roboto-Regular.ttf", reporter);
231 } else {
232 resourcesMissing = true;
233 }
234 for (FontFamily* p : preV17FontFamilies) {
235 delete p;
236 }
237 preV17FontFamilies.reset();
238
239
240 SkTDArray<FontFamily*> v17FontFamilies;
241 SkFontMgr_Android_Parser::GetCustomFontFamilies(v17FontFamilies,
242 SkString("/custom/font/path/"),
243 GetResourcePath("android_fonts/v17/system_fonts.xml").c_str(),
244 GetResourcePath("android_fonts/v17/fallback_fonts.xml").c_str(),
245 GetResourcePath("android_fonts/v17").c_str());
246
247 if (v17FontFamilies.size() > 0) {
248 REPORTER_ASSERT(reporter, v17FontFamilies.size() == 56);
249 REPORTER_ASSERT(reporter, CountFallbacks(v17FontFamilies) == 46);
250
251 DumpLoadedFonts(v17FontFamilies, "version 17");
252 ValidateLoadedFonts(v17FontFamilies, "Roboto-Regular.ttf", reporter);
253 } else {
254 resourcesMissing = true;
255 }
256 for (FontFamily* p : v17FontFamilies) {
257 delete p;
258 }
259 v17FontFamilies.reset();
260
261
262 SkTDArray<FontFamily*> v22FontFamilies;
263 SkFontMgr_Android_Parser::GetCustomFontFamilies(v22FontFamilies,
264 SkString("/custom/font/path/"),
265 GetResourcePath("android_fonts/v22/fonts.xml").c_str(),
266 nullptr);
267
268 if (v22FontFamilies.size() > 0) {
269 REPORTER_ASSERT(reporter, v22FontFamilies.size() == 54);
270 REPORTER_ASSERT(reporter, CountFallbacks(v22FontFamilies) == 42);
271
272 DumpLoadedFonts(v22FontFamilies, "version 22");
273 ValidateLoadedFonts(v22FontFamilies, "Roboto-Thin.ttf", reporter);
274 } else {
275 resourcesMissing = true;
276 }
277 for (FontFamily* p : v22FontFamilies) {
278 delete p;
279 }
280 v22FontFamilies.reset();
281
282 if (resourcesMissing) {
283 SkDebugf("---- Resource files missing for FontConfigParser test\n");
284 }
285 }
286
DEF_TEST_SCANNERS(FontMgrAndroidLegacyMakeTypeface,reporter)287 DEF_TEST_SCANNERS(FontMgrAndroidLegacyMakeTypeface, reporter) {
288 constexpr char fontsXmlFilename[] = "fonts/fonts.xml";
289 SkString basePath = GetResourcePath("fonts/");
290 SkString fontsXml = GetResourcePath(fontsXmlFilename);
291
292 if (!sk_exists(fontsXml.c_str())) {
293 ERRORF(reporter, "file missing: %s\n", fontsXmlFilename);
294 return;
295 }
296
297 SkFontMgr_Android_CustomFonts custom;
298 custom.fSystemFontUse = SkFontMgr_Android_CustomFonts::kOnlyCustom;
299 custom.fBasePath = basePath.c_str();
300 custom.fFontsXml = fontsXml.c_str();
301 custom.fFallbackFontsXml = nullptr;
302 custom.fIsolated = false;
303
304 sk_sp<SkFontMgr> fm(SkFontMgr_New_Android(&custom, std::move(fs)));
305 sk_sp<SkTypeface> t(fm->legacyMakeTypeface("non-existent-font", SkFontStyle()));
306 REPORTER_ASSERT(reporter, nullptr == t);
307 }
308
bitmap_compare(const SkBitmap & ref,const SkBitmap & test)309 static int bitmap_compare(const SkBitmap& ref, const SkBitmap& test) {
310 int count = 0;
311 for (int y = 0; y < test.height(); ++y) {
312 for (int x = 0; x < test.width(); ++x) {
313 SkColor testColor = test.getColor(x, y);
314 SkColor refColor = ref.getColor(x, y);
315 if (refColor != testColor) {
316 ++count;
317 }
318 }
319 }
320 return count;
321 }
322
DEF_TEST_SCANNERS(FontMgrAndroidSystemVariableTypeface,reporter)323 DEF_TEST_SCANNERS(FontMgrAndroidSystemVariableTypeface, reporter) {
324 constexpr char fontsXmlFilename[] = "fonts/fonts.xml";
325 SkString basePath = GetResourcePath("fonts/");
326 SkString fontsXml = GetResourcePath(fontsXmlFilename);
327
328 if (!sk_exists(fontsXml.c_str())) {
329 ERRORF(reporter, "file missing: %s\n", fontsXmlFilename);
330 return;
331 }
332
333 SkFontMgr_Android_CustomFonts custom;
334 custom.fSystemFontUse = SkFontMgr_Android_CustomFonts::kOnlyCustom;
335 custom.fBasePath = basePath.c_str();
336 custom.fFontsXml = fontsXml.c_str();
337 custom.fFallbackFontsXml = nullptr;
338 custom.fIsolated = false;
339
340 sk_sp<SkFontMgr> fontMgr(SkFontMgr_New_Android(&custom, std::move(fs)));
341 // "sans-serif" in "fonts/fonts.xml" is "fonts/Distortable.ttf"
342 sk_sp<SkTypeface> typeface(fontMgr->legacyMakeTypeface("sans-serif", SkFontStyle()));
343
344 SkBitmap bitmapStream;
345 bitmapStream.allocN32Pixels(64, 64);
346 SkCanvas canvasStream(bitmapStream);
347 canvasStream.drawColor(SK_ColorWHITE);
348
349 SkBitmap bitmapClone;
350 bitmapClone.allocN32Pixels(64, 64);
351 SkCanvas canvasClone(bitmapClone);
352 canvasStream.drawColor(SK_ColorWHITE);
353
354 SkPaint paint;
355 paint.setColor(SK_ColorGRAY);
356 paint.setAntiAlias(true);
357 constexpr float kTextSize = 20;
358
359 std::unique_ptr<SkStreamAsset> distortableStream(
360 GetResourceAsStream("fonts/Distortable.ttf"));
361 if (!distortableStream) {
362 return;
363 }
364
365 SkPoint point = SkPoint::Make(20.0f, 20.0f);
366 SkFourByteTag tag = SkSetFourByteTag('w', 'g', 'h', 't');
367
368 for (int i = 0; i < 10; ++i) {
369 SkScalar styleValue =
370 SkDoubleToScalar(0.5 + i * ((2.0 - 0.5) / 10));
371 SkFontArguments::VariationPosition::Coordinate
372 coordinates[] = {{tag, styleValue}};
373 SkFontArguments::VariationPosition
374 position = {coordinates, std::size(coordinates)};
375
376 SkFont fontStream(
377 fontMgr->makeFromStream(distortableStream->duplicate(),
378 SkFontArguments().setVariationDesignPosition(position)),
379 kTextSize);
380 fontStream.setEdging(SkFont::Edging::kSubpixelAntiAlias);
381
382
383 SkFont fontClone(
384 typeface->makeClone(SkFontArguments().setVariationDesignPosition(position)), kTextSize);
385 fontClone.setEdging(SkFont::Edging::kSubpixelAntiAlias);
386
387 constexpr char text[] = "abc";
388
389 canvasStream.drawColor(SK_ColorWHITE);
390 canvasStream.drawString(text, point.fX, point.fY, fontStream, paint);
391
392 canvasClone.drawColor(SK_ColorWHITE);
393 canvasClone.drawString(text, point.fX, point.fY, fontClone, paint);
394
395 auto count = bitmap_compare(bitmapStream, bitmapClone);
396 REPORTER_ASSERT(reporter, count == 0);
397 }
398 }
399
DEF_TEST_SCANNERS(FontMgrAndroidSystemFallbackFor,reporter)400 DEF_TEST_SCANNERS(FontMgrAndroidSystemFallbackFor, reporter) {
401 constexpr char fontsXmlFilename[] = "fonts/fonts.xml";
402 SkString basePath = GetResourcePath("fonts/");
403 SkString fontsXml = GetResourcePath(fontsXmlFilename);
404
405 if (!sk_exists(fontsXml.c_str())) {
406 ERRORF(reporter, "file missing: %s\n", fontsXmlFilename);
407 return;
408 }
409
410 SkFontMgr_Android_CustomFonts custom;
411 custom.fSystemFontUse = SkFontMgr_Android_CustomFonts::kOnlyCustom;
412 custom.fBasePath = basePath.c_str();
413 custom.fFontsXml = fontsXml.c_str();
414 custom.fFallbackFontsXml = nullptr;
415 custom.fIsolated = false;
416
417 sk_sp<SkFontMgr> fontMgr(SkFontMgr_New_Android(&custom, std::move(fs)));
418 // "sans-serif" in "fonts/fonts.xml" is "fonts/Distortable.ttf", which doesn't have a '!'
419 // but "TestTTC" has a bold font which does have '!' and is marked as fallback for "sans-serif"
420 // and should take precedence over the same font marked as normal weight next to it.
421 sk_sp<SkTypeface> typeface(fontMgr->matchFamilyStyleCharacter(
422 "sans-serif", SkFontStyle(), nullptr, 0, '!'));
423
424 REPORTER_ASSERT(reporter, typeface->fontStyle() == SkFontStyle::Bold());
425 }
426