Debian Codegraph @

tools/fonts/create_test_font.cpp

raw
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 // Running create_test_font generates ./tools/fonts/test_font_index.inc
9 // and ./tools/fonts/test_font_<generic name>.inc which are read by
10 // ./tools/fonts/TestFontMgr.cpp
11
12 #include "include/core/SkFont.h"
13 #include "include/core/SkFontMetrics.h"
14 #include "include/core/SkFontMgr.h"
15 #include "include/core/SkFontStyle.h"
16 #include "include/core/SkPath.h"
17 #include "include/core/SkSpan.h"
18 #include "include/core/SkStream.h"
19 #include "include/core/SkTypeface.h"
20 #include "include/private/base/SkAssert.h"
21 #include "include/private/base/SkTDArray.h"
22 #include "src/base/SkUTF.h"
23 #include "src/core/SkOSFile.h"
24 #include "src/core/SkPathPriv.h"
25 #include "src/utils/SkOSPath.h"
26
27 #include <stdio.h>
28
29 #if defined(SK_FONTMGR_CORETEXT_AVAILABLE)
30 #include "include/ports/SkFontMgr_mac_ct.h"
31 #endif
32
33 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
34 #include "include/ports/SkFontMgr_fontconfig.h"
35 #include "include/ports/SkFontScanner_FreeType.h"
36 #endif
37
38 #if defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
39 #include "include/ports/SkFontMgr_empty.h"
40 #endif
41
42 namespace {
43
44 struct NamedFontStyle {
45 char const * const fName;
46 char const * const fIdentifierName;
47 SkFontStyle const fStyle;
48 };
49
50 struct FontDesc {
51 NamedFontStyle const fNamedStyle;
52 char const * const fFile;
53 };
54
55 struct FontFamilyDesc {
56 char const * const fGenericName;
57 char const * const fFamilyName;
58 char const * const fIdentifierName;
59 SkSpan<const FontDesc> const fFonts;
60 };
61
62 } // namespace
63
64 static FILE* font_header(const char* family) {
65 SkString outPath(SkOSPath::Join(".", "tools"));
66 outPath = SkOSPath::Join(outPath.c_str(), "fonts");
67 outPath = SkOSPath::Join(outPath.c_str(), "test_font_");
68 SkString fam(family);
69 do {
70 int dashIndex = fam.find("-");
71 if (dashIndex < 0) {
72 break;
73 }
74 fam.data()[dashIndex] = '_';
75 } while (true);
76 outPath.append(fam);
77 outPath.append(".inc");
78 FILE* out = fopen(outPath.c_str(), "w");
79
80 static const char kHeader[] =
81 "/*\n"
82 " * Copyright 2015 Google Inc.\n"
83 " *\n"
84 " * Use of this source code is governed by a BSD-style license that can be\n"
85 " * found in the LICENSE file.\n"
86 " */\n"
87 "\n"
88 "// Auto-generated by ";
89 fprintf(out, "%s%s\n\n", kHeader, SkOSPath::Basename(__FILE__).c_str());
90 return out;
91 }
92
93 enum {
94 kMaxLineLength = 80,
95 };
96
97 static ptrdiff_t last_line_length(const SkString& str) {
98 const char* first = str.c_str();
99 const char* last = first + str.size();
100 const char* ptr = last;
101 while (ptr > first && *--ptr != '\n')
102 ;
103 return last - ptr - 1;
104 }
105
106 static void output_fixed(SkScalar num, int emSize, SkString* out) {
107 uint32_t hex = (uint32_t)(num * 65536 / emSize);
108 out->appendf("0x%08x,", hex);
109 *out += (int) last_line_length(*out) >= kMaxLineLength ? '\n' : ' ';
110 }
111
112 static void output_scalar(SkScalar num, int emSize, SkString* out) {
113 num /= emSize;
114 if (num == (int) num) {
115 out->appendS32((int) num);
116 } else {
117 SkString str;
118 str.printf("%1.6g", num);
119 int width = (int) str.size();
120 const char* cStr = str.c_str();
121 while (cStr[width - 1] == '0') {
122 --width;
123 }
124 str.remove(width, str.size() - width);
125 out->appendf("%sf", str.c_str());
126 }
127 *out += ',';
128 *out += (int) last_line_length(*out) >= kMaxLineLength ? '\n' : ' ';
129 }
130
131 static int output_points(const SkPoint* pts, int emSize, int count, SkString* ptsOut) {
132 for (int index = 0; index < count; ++index) {
133 output_scalar(pts[index].fX, emSize, ptsOut);
134 output_scalar(pts[index].fY, emSize, ptsOut);
135 }
136 return count;
137 }
138
139 static void output_path_data(const SkFont& font,
140 int emSize, SkString* ptsOut, SkTDArray<SkPath::Verb>* verbs,
141 SkTDArray<unsigned>* charCodes, SkTDArray<SkScalar>* widths) {
142 for (SkUnichar index = 0x00; index < 0x7f; ++index) {
143 SkGlyphID glyphID = font.unicharToGlyph(index);
144 SkPath path = font.getPath(glyphID).value_or(SkPath());
145 for (auto [verb, pts, w] : SkPathPriv::Iterate(path)) {
146 *verbs->append() = (SkPath::Verb)verb;
147 switch (verb) {
148 case SkPathVerb::kMove:
149 output_points(&pts[0], emSize, 1, ptsOut);
150 break;
151 case SkPathVerb::kLine:
152 output_points(&pts[1], emSize, 1, ptsOut);
153 break;
154 case SkPathVerb::kQuad:
155 output_points(&pts[1], emSize, 2, ptsOut);
156 break;
157 case SkPathVerb::kCubic:
158 output_points(&pts[1], emSize, 3, ptsOut);
159 break;
160 case SkPathVerb::kClose:
161 break;
162 default:
163 SkDEBUGFAIL("bad verb");
164 SkASSERT(0);
165 }
166 }
167 *verbs->append() = SkPath::kDone_Verb;
168 *charCodes->append() = index;
169 SkScalar width = font.getWidth(glyphID);
170 // SkASSERT(floor(width) == width); // not true for Hiragino Maru Gothic Pro
171 *widths->append() = width;
172 if (0 == index) {
173 index = 0x1f; // skip the rest of the control codes
174 }
175 }
176 }
177
178 static int offset_str_len(unsigned num) {
179 if (num == (unsigned) -1) {
180 return 10;
181 }
182 unsigned result = 1;
183 unsigned ref = 10;
184 while (ref <= num) {
185 ++result;
186 ref *= 10;
187 }
188 return result;
189 }
190
191 static SkString strip_final(const SkString& str) {
192 SkString result(str);
193 if (result.endsWith("\n")) {
194 result.remove(result.size() - 1, 1);
195 }
196 if (result.endsWith(" ")) {
197 result.remove(result.size() - 1, 1);
198 }
199 if (result.endsWith(",")) {
200 result.remove(result.size() - 1, 1);
201 }
202 return result;
203 }
204
205 static void output_font(sk_sp<SkTypeface> face, const char* identifier, FILE* out) {
206 const int emSize = face->getUnitsPerEm() * 2;
207 SkFont font;
208 font.setEdging(SkFont::Edging::kAntiAlias);
209 font.setSize(emSize);
210 font.setTypeface(std::move(face));
211
212 SkTDArray<SkPath::Verb> verbs;
213 SkTDArray<unsigned> charCodes;
214 SkTDArray<SkScalar> widths;
215 SkString ptsOut;
216 output_path_data(font, emSize, &ptsOut, &verbs, &charCodes, &widths);
217 fprintf(out, "const SkScalar %sPoints[] = {\n", identifier);
218 ptsOut = strip_final(ptsOut);
219 fprintf(out, "%s", ptsOut.c_str());
220 fprintf(out, "\n};\n\n");
221 fprintf(out, "const unsigned char %sVerbs[] = {\n", identifier);
222 int verbCount = verbs.size();
223 int outChCount = 0;
224 for (int index = 0; index < verbCount;) {
225 SkPath::Verb verb = verbs[index];
226 SkASSERT(verb >= SkPath::kMove_Verb && verb <= SkPath::kDone_Verb);
227 SkASSERT(SkTFitsIn<uint8_t>(verb));
228 fprintf(out, "%u", verb);
229 if (++index < verbCount) {
230 outChCount += 3;
231 fprintf(out, "%c", ',');
232 if (outChCount >= kMaxLineLength) {
233 outChCount = 0;
234 fprintf(out, "%c", '\n');
235 } else {
236 fprintf(out, "%c", ' ');
237 }
238 }
239 }
240 fprintf(out, "\n};\n\n");
241
242 // all fonts are now 0x00, 0x20 - 0xFE
243 // don't need to generate or output character codes?
244 fprintf(out, "const SkUnichar %sCharCodes[] = {\n", identifier);
245 int offsetCount = charCodes.size();
246 for (int index = 0; index < offsetCount;) {
247 unsigned offset = charCodes[index];
248 fprintf(out, "%u", offset);
249 if (++index < offsetCount) {
250 outChCount += offset_str_len(offset) + 2;
251 fprintf(out, "%c", ',');
252 if (outChCount >= kMaxLineLength) {
253 outChCount = 0;
254 fprintf(out, "%c", '\n');
255 } else {
256 fprintf(out, "%c", ' ');
257 }
258 }
259 }
260 fprintf(out, "\n};\n\n");
261
262 SkString widthsStr;
263 fprintf(out, "const SkFixed %sWidths[] = {\n", identifier);
264 for (int index = 0; index < offsetCount; ++index) {
265 output_fixed(widths[index], emSize, &widthsStr);
266 }
267 widthsStr = strip_final(widthsStr);
268 fprintf(out, "%s\n};\n\n", widthsStr.c_str());
269
270 fprintf(out, "const size_t %sCharCodesCount = std::size(%sCharCodes);\n\n",
271 identifier, identifier);
272
273 SkFontMetrics metrics;
274 font.getMetrics(&metrics);
275 fprintf(out, "const SkFontMetrics %sMetrics = {\n", identifier);
276 SkString metricsStr;
277 metricsStr.printf("0x%08x, ", metrics.fFlags);
278 output_scalar(metrics.fTop, emSize, &metricsStr);
279 output_scalar(metrics.fAscent, emSize, &metricsStr);
280 output_scalar(metrics.fDescent, emSize, &metricsStr);
281 output_scalar(metrics.fBottom, emSize, &metricsStr);
282 output_scalar(metrics.fLeading, emSize, &metricsStr);
283 output_scalar(metrics.fAvgCharWidth, emSize, &metricsStr);
284 output_scalar(metrics.fMaxCharWidth, emSize, &metricsStr);
285 output_scalar(metrics.fXMin, emSize, &metricsStr);
286 output_scalar(metrics.fXMax, emSize, &metricsStr);
287 output_scalar(metrics.fXHeight, emSize, &metricsStr);
288 output_scalar(metrics.fCapHeight, emSize, &metricsStr);
289 output_scalar(metrics.fUnderlineThickness, emSize, &metricsStr);
290 output_scalar(metrics.fUnderlinePosition, emSize, &metricsStr);
291 output_scalar(metrics.fStrikeoutThickness, emSize, &metricsStr);
292 output_scalar(metrics.fStrikeoutPosition, emSize, &metricsStr);
293 metricsStr = strip_final(metricsStr);
294 fprintf(out, "%s\n};\n\n", metricsStr.c_str());
295 }
296
297 static SkString identifier(const FontFamilyDesc& family, const FontDesc& font) {
298 SkString id(family.fIdentifierName);
299 id.append(font.fNamedStyle.fIdentifierName);
300 return id;
301 }
302
303 static void generate_fonts(const char* basepath,
304 const SkSpan<const FontFamilyDesc>& families,
305 sk_sp<const SkFontMgr> mgr) {
306 SkASSERT_RELEASE(mgr);
307 FILE* out = nullptr;
308 for (const FontFamilyDesc& family : families) {
309 out = font_header(family.fGenericName);
310 for (const FontDesc& font : family.fFonts) {
311 SkString filepath(SkOSPath::Join(basepath, font.fFile));
312 SkASSERTF(sk_exists(filepath.c_str()), "The file %s does not exist.", filepath.c_str());
313 sk_sp<SkTypeface> resourceTypeface = mgr->makeFromFile(filepath.c_str(), 0);
314 SkASSERTF(resourceTypeface, "The file %s is not a font.", filepath.c_str());
315 output_font(std::move(resourceTypeface), identifier(family, font).c_str(), out);
316 }
317 fclose(out);
318 }
319 }
320
321 static const char* slant_to_string(SkFontStyle::Slant slant) {
322 switch (slant) {
323 case SkFontStyle::kUpright_Slant: return "SkFontStyle::kUpright_Slant";
324 case SkFontStyle::kItalic_Slant : return "SkFontStyle::kItalic_Slant" ;
325 case SkFontStyle::kOblique_Slant: return "SkFontStyle::kOblique_Slant";
326 default: SK_ABORT("Unknown slant");
327 }
328 }
329
330 static void generate_index(const SkSpan<const FontFamilyDesc>& families,
331 const FontDesc* defaultFont)
332 {
333 FILE* out = font_header("index");
334 fprintf(out, "static SkTestFontData gTestFonts[] = {\n");
335 for (const FontFamilyDesc& family : families) {
336 for (const FontDesc& font : family.fFonts) {
337 SkString identifierStr = identifier(family, font);
338 const char* identifier = identifierStr.c_str();
339 const SkFontStyle& style = font.fNamedStyle.fStyle;
340 fprintf(out,
341 " { %sPoints, %sVerbs,\n"
342 " %sCharCodes, %sCharCodesCount, %sWidths,\n"
343 " %sMetrics, \"Toy %s\", SkFontStyle(%d,%d,%s)\n"
344 " },\n",
345 identifier, identifier,
346 identifier, identifier, identifier,
347 identifier, family.fFamilyName,
348 style.weight(), style.width(), slant_to_string(style.slant()));
349 }
350 }
351 fprintf(out, "};\n\n");
352 fprintf(out,
353 "struct SubFont {\n"
354 " const char* fFamilyName;\n"
355 " const char* fStyleName;\n"
356 " SkFontStyle fStyle;\n"
357 " SkTestFontData& fFont;\n"
358 " const char* fFile;\n"
359 "};\n\n"
360 "const SubFont gSubFonts[] = {\n");
361 int defaultIndex = -1;
362 int testFontsIndex = 0;
363 for (const FontFamilyDesc& family : families) {
364 for (const FontDesc& font : family.fFonts) {
365 if (&font == defaultFont) {
366 defaultIndex = testFontsIndex;
367 }
368 const SkFontStyle& style = font.fNamedStyle.fStyle;
369 fprintf(out,
370 " { \"%s\", \"%s\", SkFontStyle(%d,%d,%s), gTestFonts[%d], \"%s\" },\n",
371 family.fGenericName, font.fNamedStyle.fName,
372 style.weight(), style.width(), slant_to_string(style.slant()),
373 testFontsIndex, font.fFile);
374 testFontsIndex++;
375 }
376 }
377 testFontsIndex = 0;
378 for (const FontFamilyDesc& family : families) {
379 for (const FontDesc& font : family.fFonts) {
380 fprintf(out,
381 " { \"Toy %s\", \"%s\", SkFontStyle(%d,%d,%s), gTestFonts[%d], \"%s\" },\n",
382 family.fFamilyName, font.fNamedStyle.fName,
383 font.fNamedStyle.fStyle.weight(), font.fNamedStyle.fStyle.width(),
384 slant_to_string(font.fNamedStyle.fStyle.slant()), testFontsIndex, font.fFile);
385 testFontsIndex++;
386 }
387 }
388 fprintf(out, "};\n\n");
389 SkASSERT(defaultIndex >= 0);
390 fprintf(out, "const size_t gDefaultFontIndex = %d;\n", defaultIndex);
391 fclose(out);
392 }
393
394 int main(int , char * const []) {
395 constexpr NamedFontStyle normal = {"Normal", "Normal", SkFontStyle::Normal() };
396 constexpr NamedFontStyle bold = {"Bold", "Bold", SkFontStyle::Bold() };
397 constexpr NamedFontStyle italic = {"Italic", "Italic", SkFontStyle::Italic() };
398 constexpr NamedFontStyle bolditalic = {"Bold Italic", "BoldItalic", SkFontStyle::BoldItalic()};
399
400 static constexpr FontDesc kMonoFonts[] = {
401 {normal, "LiberationMono-Regular.ttf"},
402 {bold, "LiberationMono-Bold.ttf"},
403 {italic, "LiberationMono-Italic.ttf"},
404 {bolditalic, "LiberationMono-BoldItalic.ttf"},
405 };
406
407 static constexpr FontDesc kSansFonts[] = {
408 {normal, "LiberationSans-Regular.ttf"},
409 {bold, "LiberationSans-Bold.ttf"},
410 {italic, "LiberationSans-Italic.ttf"},
411 {bolditalic, "LiberationSans-BoldItalic.ttf"},
412 };
413
414 static constexpr FontDesc kSerifFonts[] = {
415 {normal, "LiberationSerif-Regular.ttf"},
416 {bold, "LiberationSerif-Bold.ttf"},
417 {italic, "LiberationSerif-Italic.ttf"},
418 {bolditalic, "LiberationSerif-BoldItalic.ttf"},
419 };
420
421 static constexpr FontFamilyDesc kFamiliesData[] = {
422 {"monospace", "Liberation Mono", "LiberationMono", kMonoFonts},
423 {"sans-serif", "Liberation Sans", "LiberationSans", kSansFonts},
424 {"serif", "Liberation Serif", "LiberationSerif", kSerifFonts},
425 };
426
427 static constexpr SkSpan<const FontFamilyDesc> kFamilies(kFamiliesData);
428
429 sk_sp<SkFontMgr> mgr;
430 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
431 mgr = SkFontMgr_New_FontConfig(nullptr, SkFontScanner_Make_FreeType());
432 #elif defined(SK_FONTMGR_CORETEXT_AVAILABLE)
433 mgr = SkFontMgr_New_CoreText(nullptr);
434 #elif defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
435 mgr = SkFontMgr_New_Custom_Empty();
436 #else
437 SkDEBUGFAIL("Unsupported FontMgr");
438 #endif
439
440 #if defined(SK_BUILD_FOR_UNIX)
441 #define SK_FONT_FOLDER "/usr/share/fonts/truetype/liberation/"
442 #elif defined(SK_BUILD_FOR_MAC)
443 #define SK_FONT_FOLDER "/Library/Fonts/"
444 #else
445 #error "Unsupported OS"
446 #endif
447
448 generate_fonts(SK_FONT_FOLDER, kFamilies, mgr);
449 generate_index(kFamilies, &kFamilies[1].fFonts[0]);
450 return 0;
451 }