Debian Codegraph @

tools/fonts/TestSVGTypeface.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 #include "tools/fonts/TestSVGTypeface.h"
9
10 #if defined(SK_ENABLE_SVG)
11
12 #include "include/codec/SkEncodedImageFormat.h"
13 #include "include/core/SkArc.h"
14 #include "include/core/SkBitmap.h"
15 #include "include/core/SkCanvas.h"
16 #include "include/core/SkColor.h"
17 #include "include/core/SkData.h"
18 #include "include/core/SkDrawable.h"
19 #include "include/core/SkFontStyle.h"
20 #include "include/core/SkImage.h"
21 #include "include/core/SkImageInfo.h"
22 #include "include/core/SkMatrix.h"
23 #include "include/core/SkPath.h"
24 #include "include/core/SkPathEffect.h"
25 #include "include/core/SkPathUtils.h"
26 #include "include/core/SkPixmap.h"
27 #include "include/core/SkRRect.h"
28 #include "include/core/SkSize.h"
29 #include "include/core/SkStream.h"
30 #include "include/core/SkSurface.h"
31 #include "include/encode/SkPngEncoder.h"
32 #include "include/pathops/SkPathOps.h"
33 #include "include/private/base/SkTDArray.h"
34 #include "include/private/base/SkTemplates.h"
35 #include "include/utils/SkNoDrawCanvas.h"
36 #include "modules/svg/include/SkSVGDOM.h"
37 #include "modules/svg/include/SkSVGNode.h"
38 #include "src/base/SkUtils.h"
39 #include "src/core/SkAdvancedTypefaceMetrics.h"
40 #include "src/core/SkFontDescriptor.h"
41 #include "src/core/SkFontPriv.h"
42 #include "src/core/SkGeometry.h"
43 #include "src/core/SkGlyph.h"
44 #include "src/core/SkMask.h"
45 #include "src/core/SkPaintPriv.h"
46 #include "src/core/SkPathPriv.h"
47 #include "src/core/SkPointPriv.h"
48 #include "src/core/SkScalerContext.h"
49 #include "src/sfnt/SkOTUtils.h"
50 #include "tools/Resources.h"
51
52 #include <utility>
53
54 using namespace skia_private;
55
56 class SkDescriptor;
57
58 TestSVGTypeface::TestSVGTypeface(const char* name, const SkFontStyle& style,
59 int upem, const SkFontMetrics& fontMetrics,
60 SkSpan<const SkSVGTestTypefaceGlyphData> data)
61 : SkTypeface(style, false)
62 , fName(name)
63 , fUpem(upem)
64 , fFontMetrics(fontMetrics)
65 , fGlyphs(new Glyph[data.size()])
66 , fGlyphCount(data.size()) {
67 for (size_t i = 0; i < data.size(); ++i) {
68 const SkSVGTestTypefaceGlyphData& datum = data[i];
69 fCMap.set(datum.fUnicode, i);
70 fGlyphs[i].fAdvance = datum.fAdvance;
71 fGlyphs[i].fOrigin = datum.fOrigin;
72 fGlyphs[i].fResourcePath = datum.fSvgResourcePath;
73 }
74 }
75
76 template <typename Fn>
77 void TestSVGTypeface::Glyph::withSVG(Fn&& fn) const {
78 SkAutoMutexExclusive lock(fSvgMutex);
79
80 if (!fParsedSvg) {
81 fParsedSvg = true;
82
83 std::unique_ptr<SkStreamAsset> stream = GetResourceAsStream(fResourcePath);
84 if (!stream) {
85 return;
86 }
87
88 // We expressly *do not want* to set a SkFontMgr when parsing these SVGs.
89 // 1) The SVGs we are processing have no <text> tags in them.
90 // 2) Trying to use ToolUtils::TestFontMgr() is a problem because the portable
91 // SkFontMgr *calls* this function as it creates the typefaces.
92 sk_sp<SkSVGDOM> svg = SkSVGDOM::MakeFromStream(*stream);
93 if (!svg) {
94 return;
95 }
96
97 if (svg->containerSize().isEmpty()) {
98 return;
99 }
100
101 fSvg = std::move(svg);
102 }
103
104 if (fSvg) {
105 fn(*fSvg);
106 }
107 }
108
109 SkSize TestSVGTypeface::Glyph::size() const {
110 SkSize size = SkSize::MakeEmpty();
111 this->withSVG([&](const SkSVGDOM& svg){
112 size = svg.containerSize();
113 });
114 return size;
115 }
116
117 void TestSVGTypeface::Glyph::render(SkCanvas* canvas) const {
118 this->withSVG([&](const SkSVGDOM& svg){
119 svg.render(canvas);
120 });
121 }
122
123 TestSVGTypeface::~TestSVGTypeface() {}
124
125 TestSVGTypeface::Glyph::Glyph() : fOrigin{0, 0}, fAdvance(0) {}
126 TestSVGTypeface::Glyph::~Glyph() {}
127
128 SkVector TestSVGTypeface::getAdvance(SkGlyphID glyphID) const {
129 glyphID = glyphID < fGlyphCount ? glyphID : 0;
130 return {fGlyphs[glyphID].fAdvance, 0};
131 }
132
133 void TestSVGTypeface::getFontMetrics(SkFontMetrics* metrics) const { *metrics = fFontMetrics; }
134
135 void TestSVGTypeface::onFilterRec(SkScalerContextRec* rec) const {
136 rec->setHinting(SkFontHinting::kNone);
137 }
138
139 void TestSVGTypeface::getGlyphToUnicodeMap(SkSpan<SkUnichar> glyphToUnicode) const {
140 SkDEBUGCODE(unsigned glyphCount = this->countGlyphs());
141 fCMap.foreach ([=](const SkUnichar& c, const SkGlyphID& g) {
142 SkASSERT(g < glyphCount);
143 SkASSERT(g < glyphToUnicode.size());
144 glyphToUnicode[g] = c;
145 });
146 }
147
148 std::unique_ptr<SkAdvancedTypefaceMetrics> TestSVGTypeface::onGetAdvancedMetrics() const {
149 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
150 info->fPostScriptName = fName;
151 return info;
152 }
153
154 void TestSVGTypeface::onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const {
155 desc->setFamilyName(fName.c_str());
156 desc->setStyle(this->fontStyle());
157 *serialize = true;
158 }
159
160 void TestSVGTypeface::onCharsToGlyphs(SkSpan<const SkUnichar> uni, SkSpan<SkGlyphID> glyphs) const {
161 SkASSERT(uni.size() == glyphs.size());
162 for (size_t i = 0; i < uni.size(); i++) {
163 SkGlyphID* g = fCMap.find(uni[i]);
164 glyphs[i] = g ? *g : 0;
165 }
166 }
167
168 void TestSVGTypeface::onGetFamilyName(SkString* familyName) const { *familyName = fName; }
169
170 bool TestSVGTypeface::onGetPostScriptName(SkString*) const { return false; }
171
172 SkTypeface::LocalizedStrings* TestSVGTypeface::onCreateFamilyNameIterator() const {
173 SkString familyName(fName);
174 SkString language("und"); // undetermined
175 return new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
176 }
177
178 class SkTestSVGScalerContext : public SkScalerContext {
179 public:
180 SkTestSVGScalerContext(TestSVGTypeface& face,
181 const SkScalerContextEffects& effects,
182 const SkDescriptor* desc)
183 : SkScalerContext(face, effects, desc)
184 , fMatrix(fRec.getSingleMatrix())
185 {
186 SkScalar upem = this->getTestSVGTypeface()->fUpem;
187 fMatrix.preScale(1.f / upem, 1.f / upem);
188 }
189
190 protected:
191 TestSVGTypeface* getTestSVGTypeface() const {
192 return static_cast<TestSVGTypeface*>(this->getTypeface());
193 }
194
195 SkVector computeAdvance(SkGlyphID glyphID) {
196 auto advance = this->getTestSVGTypeface()->getAdvance(glyphID);
197 return fMatrix.mapPoint(advance);
198 }
199
200 GlyphMetrics generateMetrics(const SkGlyph& glyph, SkArenaAlloc*) override {
201 SkGlyphID glyphID = glyph.getGlyphID();
202 glyphID = glyphID < this->getTestSVGTypeface()->fGlyphCount ? glyphID : 0;
203
204 GlyphMetrics mx(SkMask::kARGB32_Format);
205 mx.neverRequestPath = true;
206 mx.advance = this->computeAdvance(glyph.getGlyphID());
207
208 TestSVGTypeface::Glyph& glyphData = this->getTestSVGTypeface()->fGlyphs[glyphID];
209
210 SkSize containerSize = glyphData.size();
211 SkRect newBounds = SkRect::MakeXYWH(glyphData.fOrigin.fX,
212 -glyphData.fOrigin.fY,
213 containerSize.fWidth,
214 containerSize.fHeight);
215 fMatrix.mapRect(&newBounds);
216 SkScalar dx = SkFixedToScalar(glyph.getSubXFixed());
217 SkScalar dy = SkFixedToScalar(glyph.getSubYFixed());
218 newBounds.offset(dx, dy);
219 newBounds.roundOut(&mx.bounds);
220 return mx;
221 }
222
223 void generateImage(const SkGlyph& glyph, void* imageBuffer) override {
224 SkGlyphID glyphID = glyph.getGlyphID();
225 glyphID = glyphID < this->getTestSVGTypeface()->fGlyphCount ? glyphID : 0;
226
227 SkBitmap bm;
228 // TODO: this should be SkImageInfo::MakeS32 when that passes all the tests.
229 bm.installPixels(SkImageInfo::MakeN32(glyph.width(), glyph.height(), kPremul_SkAlphaType),
230 imageBuffer, glyph.rowBytes());
231 bm.eraseColor(0);
232
233 TestSVGTypeface::Glyph& glyphData = this->getTestSVGTypeface()->fGlyphs[glyphID];
234
235 SkScalar dx = SkFixedToScalar(glyph.getSubXFixed());
236 SkScalar dy = SkFixedToScalar(glyph.getSubYFixed());
237
238 SkCanvas canvas(bm);
239 canvas.translate(-glyph.left(), -glyph.top());
240 canvas.translate(dx, dy);
241 canvas.concat(fMatrix);
242 canvas.translate(glyphData.fOrigin.fX, -glyphData.fOrigin.fY);
243
244 glyphData.render(&canvas);
245 }
246
247 std::optional<SkScalerContext::GeneratedPath> generatePath(const SkGlyph& glyph) override {
248 // Should never get here since generateMetrics always sets the path to not exist.
249 SK_ABORT("Path requested, but it should have been indicated that there isn't one.");
250 return {};
251 }
252
253 struct SVGGlyphDrawable : public SkDrawable {
254 SkTestSVGScalerContext* fSelf;
255 SkGlyph fGlyph;
256 SVGGlyphDrawable(SkTestSVGScalerContext* self, const SkGlyph& glyph)
257 : fSelf(self), fGlyph(glyph) {}
258 SkRect onGetBounds() override { return fGlyph.rect(); }
259 size_t onApproximateBytesUsed() override { return sizeof(SVGGlyphDrawable); }
260
261 void onDraw(SkCanvas* canvas) override {
262 SkGlyphID glyphID = fGlyph.getGlyphID();
263 glyphID = glyphID < fSelf->getTestSVGTypeface()->fGlyphCount ? glyphID : 0;
264
265 TestSVGTypeface::Glyph& glyphData = fSelf->getTestSVGTypeface()->fGlyphs[glyphID];
266
267 SkScalar dx = SkFixedToScalar(fGlyph.getSubXFixed());
268 SkScalar dy = SkFixedToScalar(fGlyph.getSubYFixed());
269
270 canvas->translate(dx, dy);
271 canvas->concat(fSelf->fMatrix);
272 canvas->translate(glyphData.fOrigin.fX, -glyphData.fOrigin.fY);
273
274 glyphData.render(canvas);
275 }
276 };
277 sk_sp<SkDrawable> generateDrawable(const SkGlyph& glyph) override {
278 return sk_sp<SVGGlyphDrawable>(new SVGGlyphDrawable(this, glyph));
279 }
280
281 void generateFontMetrics(SkFontMetrics* metrics) override {
282 this->getTestSVGTypeface()->getFontMetrics(metrics);
283 SkFontPriv::ScaleFontMetrics(metrics, fMatrix.getScaleY());
284 }
285
286 private:
287 SkMatrix fMatrix;
288 };
289
290 std::unique_ptr<SkScalerContext> TestSVGTypeface::onCreateScalerContext(
291 const SkScalerContextEffects& e, const SkDescriptor* desc) const
292 {
293 return std::make_unique<SkTestSVGScalerContext>(*const_cast<TestSVGTypeface*>(this), e, desc);
294 }
295
296 class DefaultTypeface : public TestSVGTypeface {
297 using TestSVGTypeface::TestSVGTypeface;
298
299 bool getPathOp(SkColor color, SkPathOp* op) const override {
300 if ((SkColorGetR(color) + SkColorGetG(color) + SkColorGetB(color)) / 3 > 0x20) {
301 *op = SkPathOp::kDifference_SkPathOp;
302 } else {
303 *op = SkPathOp::kUnion_SkPathOp;
304 }
305 return true;
306 }
307
308 static constexpr SkTypeface::FactoryId FactoryId = SkSetFourByteTag('d','s','v','g');
309 static constexpr const char gHeaderString[] = "SkTestSVGTypefaceDefault01";
310 static constexpr const size_t kHeaderSize = sizeof(gHeaderString);
311
312 std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
313 SkDynamicMemoryWStream wstream;
314 wstream.write(gHeaderString, kHeaderSize);
315 return wstream.detachAsStream();
316 }
317
318 static sk_sp<SkTypeface> MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
319 const SkFontArguments&) {
320 char header[kHeaderSize];
321 if (stream->read(header, kHeaderSize) != kHeaderSize ||
322 0 != memcmp(header, gHeaderString, kHeaderSize))
323 {
324 return nullptr;
325 }
326 return TestSVGTypeface::Default();
327 }
328
329 void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
330 TestSVGTypeface::onGetFontDescriptor(desc, serialize);
331 desc->setFactoryId(FactoryId);
332 }
333 public:
334 struct Register { Register() { SkTypeface::Register(FactoryId, &MakeFromStream); } };
335 };
336 static DefaultTypeface::Register defaultTypefaceRegister;
337 sk_sp<TestSVGTypeface> TestSVGTypeface::Default() {
338 // Recommended that the first four be .notdef, .null, CR, space
339 constexpr const static SkSVGTestTypefaceGlyphData glyphs[] = {
340 {"fonts/svg/notdef.svg", {100, 800}, 800, 0x0}, // .notdef
341 {"fonts/svg/empty.svg", {0, 0}, 800, 0x0020}, // space
342 {"fonts/svg/diamond.svg", {100, 800}, 800, 0x2662}, // ♢
343 {"fonts/svg/smile.svg", {0, 800}, 800, 0x1F600}, // 😀
344 };
345 SkFontMetrics metrics;
346 metrics.fFlags = SkFontMetrics::kUnderlineThicknessIsValid_Flag |
347 SkFontMetrics::kUnderlinePositionIsValid_Flag |
348 SkFontMetrics::kStrikeoutThicknessIsValid_Flag |
349 SkFontMetrics::kStrikeoutPositionIsValid_Flag;
350 metrics.fTop = -800;
351 metrics.fAscent = -800;
352 metrics.fDescent = 200;
353 metrics.fBottom = 200;
354 metrics.fLeading = 100;
355 metrics.fAvgCharWidth = 1000;
356 metrics.fMaxCharWidth = 1000;
357 metrics.fXMin = 0;
358 metrics.fXMax = 1000;
359 metrics.fXHeight = 500;
360 metrics.fCapHeight = 700;
361 metrics.fUnderlineThickness = 40;
362 metrics.fUnderlinePosition = 20;
363 metrics.fStrikeoutThickness = 20;
364 metrics.fStrikeoutPosition = -400;
365
366 return sk_sp<TestSVGTypeface>(
367 new DefaultTypeface("Emoji", SkFontStyle::Normal(), 1000, metrics, glyphs));
368 }
369
370 class PlanetTypeface : public TestSVGTypeface {
371 using TestSVGTypeface::TestSVGTypeface;
372
373 bool getPathOp(SkColor color, SkPathOp* op) const override {
374 *op = SkPathOp::kUnion_SkPathOp;
375 return true;
376 }
377
378 static constexpr SkTypeface::FactoryId FactoryId = SkSetFourByteTag('p','s','v','g');
379 static constexpr const char gHeaderString[] = "SkTestSVGTypefacePlanet01";
380 static constexpr const size_t kHeaderSize = sizeof(gHeaderString);
381
382 std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
383 SkDynamicMemoryWStream wstream;
384 wstream.write(gHeaderString, kHeaderSize);
385 return wstream.detachAsStream();
386 }
387
388 static sk_sp<SkTypeface> MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
389 const SkFontArguments&) {
390 char header[kHeaderSize];
391 if (stream->read(header, kHeaderSize) != kHeaderSize ||
392 0 != memcmp(header, gHeaderString, kHeaderSize))
393 {
394 return nullptr;
395 }
396 return TestSVGTypeface::Planets();
397 }
398
399 void onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const override {
400 TestSVGTypeface::onGetFontDescriptor(desc, isLocal);
401 desc->setFactoryId(FactoryId);
402 }
403 public:
404 struct Register { Register() { SkTypeface::Register(FactoryId, &MakeFromStream); } };
405 };
406 static PlanetTypeface::Register planetTypefaceRegister;
407 sk_sp<TestSVGTypeface> TestSVGTypeface::Planets() {
408 // Recommended that the first four be .notdef, .null, CR, space
409 constexpr const static SkSVGTestTypefaceGlyphData glyphs[] = {
410 {"fonts/svg/planets/pluto.svg", {0, 20}, 60, 0x0}, // .notdef
411 {"fonts/svg/empty.svg", {0, 0}, 400, 0x0020}, // space
412 {"fonts/svg/planets/mercury.svg", {0, 45}, 120, 0x263F}, // ☿
413 {"fonts/svg/planets/venus.svg", {0, 100}, 240, 0x2640}, // ♀
414 {"fonts/svg/planets/earth.svg", {0, 100}, 240, 0x2641}, // ♁
415 {"fonts/svg/planets/mars.svg", {0, 50}, 130, 0x2642}, // ♂
416 {"fonts/svg/planets/jupiter.svg", {0, 1000}, 2200, 0x2643}, // ♃
417 {"fonts/svg/planets/saturn.svg", {-300, 1500}, 2600, 0x2644}, // ♄
418 {"fonts/svg/planets/uranus.svg", {0, 375}, 790, 0x2645}, // ♅
419 {"fonts/svg/planets/neptune.svg", {0, 350}, 740, 0x2646}, // ♆
420 };
421 SkFontMetrics metrics;
422 metrics.fFlags = SkFontMetrics::kUnderlineThicknessIsValid_Flag |
423 SkFontMetrics::kUnderlinePositionIsValid_Flag |
424 SkFontMetrics::kStrikeoutThicknessIsValid_Flag |
425 SkFontMetrics::kStrikeoutPositionIsValid_Flag;
426 metrics.fTop = -1500;
427 metrics.fAscent = -200;
428 metrics.fDescent = 50;
429 metrics.fBottom = 1558;
430 metrics.fLeading = 10;
431 metrics.fAvgCharWidth = 200;
432 metrics.fMaxCharWidth = 200;
433 metrics.fXMin = -300;
434 metrics.fXMax = 2566;
435 metrics.fXHeight = 100;
436 metrics.fCapHeight = 180;
437 metrics.fUnderlineThickness = 8;
438 metrics.fUnderlinePosition = 2;
439 metrics.fStrikeoutThickness = 2;
440 metrics.fStrikeoutPosition = -80;
441
442 return sk_sp<TestSVGTypeface>(
443 new PlanetTypeface("Planets", SkFontStyle::Normal(), 200, metrics, glyphs));
444 }
445
446 void TestSVGTypeface::exportTtxCommon(SkWStream* out,
447 const char* type,
448 const TArray<GlyfInfo>* glyfInfo) const {
449 int totalGlyphs = fGlyphCount;
450 out->writeText(" <GlyphOrder>\n");
451 for (int i = 0; i < fGlyphCount; ++i) {
452 out->writeText(" <GlyphID name=\"glyf");
453 out->writeHexAsText(i, 4);
454 out->writeText("\"/>\n");
455 }
456 if (glyfInfo) {
457 for (int i = 0; i < fGlyphCount; ++i) {
458 for (int j = 0; j < (*glyfInfo)[i].fLayers.size(); ++j) {
459 out->writeText(" <GlyphID name=\"glyf");
460 out->writeHexAsText(i, 4);
461 out->writeText("l");
462 out->writeHexAsText(j, 4);
463 out->writeText("\"/>\n");
464 ++totalGlyphs;
465 }
466 }
467 }
468 out->writeText(" </GlyphOrder>\n");
469
470 out->writeText(" <head>\n");
471 out->writeText(" <tableVersion value=\"1.0\"/>\n");
472 out->writeText(" <fontRevision value=\"1.0\"/>\n");
473 out->writeText(" <checkSumAdjustment value=\"0xa9c3274\"/>\n");
474 out->writeText(" <magicNumber value=\"0x5f0f3cf5\"/>\n");
475 out->writeText(" <flags value=\"00000000 00011011\"/>\n");
476 out->writeText(" <unitsPerEm value=\"");
477 out->writeDecAsText(fUpem);
478 out->writeText("\"/>\n");
479 out->writeText(" <created value=\"Thu Feb 15 12:55:49 2018\"/>\n");
480 out->writeText(" <modified value=\"Thu Feb 15 12:55:49 2018\"/>\n");
481 // TODO: not recalculated for bitmap fonts?
482 out->writeText(" <xMin value=\"");
483 out->writeScalarAsText(fFontMetrics.fXMin);
484 out->writeText("\"/>\n");
485 out->writeText(" <yMin value=\"");
486 out->writeScalarAsText(-fFontMetrics.fBottom);
487 out->writeText("\"/>\n");
488 out->writeText(" <xMax value=\"");
489 out->writeScalarAsText(fFontMetrics.fXMax);
490 out->writeText("\"/>\n");
491 out->writeText(" <yMax value=\"");
492 out->writeScalarAsText(-fFontMetrics.fTop);
493 out->writeText("\"/>\n");
494
495 char macStyle[16] = {
496 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
497 if (this->fontStyle().weight() >= SkFontStyle::Bold().weight()) {
498 macStyle[0xF - 0x0] = '1'; // Bold
499 }
500 switch (this->fontStyle().slant()) {
501 case SkFontStyle::kUpright_Slant: break;
502 case SkFontStyle::kItalic_Slant:
503 macStyle[0xF - 0x1] = '1'; // Italic
504 break;
505 case SkFontStyle::kOblique_Slant:
506 macStyle[0xF - 0x1] = '1'; // Italic
507 break;
508 default: SK_ABORT("Unknown slant.");
509 }
510 if (this->fontStyle().width() <= SkFontStyle::kCondensed_Width) {
511 macStyle[0xF - 0x5] = '1'; // Condensed
512 } else if (this->fontStyle().width() >= SkFontStyle::kExpanded_Width) {
513 macStyle[0xF - 0x6] = '1'; // Extended
514 }
515 out->writeText(" <macStyle value=\"");
516 out->write(macStyle, 8);
517 out->writeText(" ");
518 out->write(macStyle + 8, 8);
519 out->writeText("\"/>\n");
520 out->writeText(" <lowestRecPPEM value=\"8\"/>\n");
521 out->writeText(" <fontDirectionHint value=\"2\"/>\n");
522 out->writeText(" <indexToLocFormat value=\"0\"/>\n");
523 out->writeText(" <glyphDataFormat value=\"0\"/>\n");
524 out->writeText(" </head>\n");
525
526 out->writeText(" <hhea>\n");
527 out->writeText(" <tableVersion value=\"0x00010000\"/>\n");
528 out->writeText(" <ascent value=\"");
529 out->writeDecAsText(-fFontMetrics.fAscent);
530 out->writeText("\"/>\n");
531 out->writeText(" <descent value=\"");
532 out->writeDecAsText(-fFontMetrics.fDescent);
533 out->writeText("\"/>\n");
534 out->writeText(" <lineGap value=\"");
535 out->writeDecAsText(fFontMetrics.fLeading);
536 out->writeText("\"/>\n");
537 out->writeText(" <advanceWidthMax value=\"0\"/>\n");
538 out->writeText(" <minLeftSideBearing value=\"0\"/>\n");
539 out->writeText(" <minRightSideBearing value=\"0\"/>\n");
540 out->writeText(" <xMaxExtent value=\"");
541 out->writeScalarAsText(fFontMetrics.fXMax - fFontMetrics.fXMin);
542 out->writeText("\"/>\n");
543 out->writeText(" <caretSlopeRise value=\"1\"/>\n");
544 out->writeText(" <caretSlopeRun value=\"0\"/>\n");
545 out->writeText(" <caretOffset value=\"0\"/>\n");
546 out->writeText(" <reserved0 value=\"0\"/>\n");
547 out->writeText(" <reserved1 value=\"0\"/>\n");
548 out->writeText(" <reserved2 value=\"0\"/>\n");
549 out->writeText(" <reserved3 value=\"0\"/>\n");
550 out->writeText(" <metricDataFormat value=\"0\"/>\n");
551 out->writeText(" <numberOfHMetrics value=\"0\"/>\n");
552 out->writeText(" </hhea>\n");
553
554 // Some of this table is going to be re-calculated, but we have to write it out anyway.
555 out->writeText(" <maxp>\n");
556 out->writeText(" <tableVersion value=\"0x10000\"/>\n");
557 out->writeText(" <numGlyphs value=\"");
558 out->writeDecAsText(totalGlyphs);
559 out->writeText("\"/>\n");
560 out->writeText(" <maxPoints value=\"4\"/>\n");
561 out->writeText(" <maxContours value=\"1\"/>\n");
562 out->writeText(" <maxCompositePoints value=\"0\"/>\n");
563 out->writeText(" <maxCompositeContours value=\"0\"/>\n");
564 out->writeText(" <maxZones value=\"1\"/>\n");
565 out->writeText(" <maxTwilightPoints value=\"0\"/>\n");
566 out->writeText(" <maxStorage value=\"0\"/>\n");
567 out->writeText(" <maxFunctionDefs value=\"10\"/>\n");
568 out->writeText(" <maxInstructionDefs value=\"0\"/>\n");
569 out->writeText(" <maxStackElements value=\"512\"/>\n");
570 out->writeText(" <maxSizeOfInstructions value=\"24\"/>\n");
571 out->writeText(" <maxComponentElements value=\"0\"/>\n");
572 out->writeText(" <maxComponentDepth value=\"0\"/>\n");
573 out->writeText(" </maxp>\n");
574
575 out->writeText(" <OS_2>\n");
576 out->writeText(" <version value=\"4\"/>\n");
577 out->writeText(" <xAvgCharWidth value=\"");
578 out->writeScalarAsText(fFontMetrics.fAvgCharWidth);
579 out->writeText("\"/>\n");
580 out->writeText(" <usWeightClass value=\"");
581 out->writeDecAsText(this->fontStyle().weight());
582 out->writeText("\"/>\n");
583 out->writeText(" <usWidthClass value=\"");
584 out->writeDecAsText(this->fontStyle().width());
585 out->writeText("\"/>\n");
586 out->writeText(" <fsType value=\"00000000 00000000\"/>\n");
587 out->writeText(" <ySubscriptXSize value=\"665\"/>\n");
588 out->writeText(" <ySubscriptYSize value=\"716\"/>\n");
589 out->writeText(" <ySubscriptXOffset value=\"0\"/>\n");
590 out->writeText(" <ySubscriptYOffset value=\"143\"/>\n");
591 out->writeText(" <ySuperscriptXSize value=\"665\"/>\n");
592 out->writeText(" <ySuperscriptYSize value=\"716\"/>\n");
593 out->writeText(" <ySuperscriptXOffset value=\"0\"/>\n");
594 out->writeText(" <ySuperscriptYOffset value=\"491\"/>\n");
595 out->writeText(" <yStrikeoutSize value=\"");
596 out->writeScalarAsText(fFontMetrics.fStrikeoutThickness);
597 out->writeText("\"/>\n");
598 out->writeText(" <yStrikeoutPosition value=\"");
599 out->writeScalarAsText(-fFontMetrics.fStrikeoutPosition);
600 out->writeText("\"/>\n");
601 out->writeText(" <sFamilyClass value=\"0\"/>\n");
602 out->writeText(" <panose>\n");
603 out->writeText(" <bFamilyType value=\"0\"/>\n");
604 out->writeText(" <bSerifStyle value=\"0\"/>\n");
605 out->writeText(" <bWeight value=\"0\"/>\n");
606 out->writeText(" <bProportion value=\"0\"/>\n");
607 out->writeText(" <bContrast value=\"0\"/>\n");
608 out->writeText(" <bStrokeVariation value=\"0\"/>\n");
609 out->writeText(" <bArmStyle value=\"0\"/>\n");
610 out->writeText(" <bLetterForm value=\"0\"/>\n");
611 out->writeText(" <bMidline value=\"0\"/>\n");
612 out->writeText(" <bXHeight value=\"0\"/>\n");
613 out->writeText(" </panose>\n");
614 out->writeText(" <ulUnicodeRange1 value=\"00000000 00000000 00000000 00000001\"/>\n");
615 out->writeText(" <ulUnicodeRange2 value=\"00010000 00000000 00000000 00000000\"/>\n");
616 out->writeText(" <ulUnicodeRange3 value=\"00000000 00000000 00000000 00000000\"/>\n");
617 out->writeText(" <ulUnicodeRange4 value=\"00000000 00000000 00000000 00000000\"/>\n");
618 out->writeText(" <achVendID value=\"Skia\"/>\n");
619 char fsSelection[16] = {
620 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
621 fsSelection[0xF - 0x7] = '1'; // Use typo metrics
622 if (this->fontStyle().weight() >= SkFontStyle::Bold().weight()) {
623 fsSelection[0xF - 0x5] = '1'; // Bold
624 }
625 switch (this->fontStyle().slant()) {
626 case SkFontStyle::kUpright_Slant:
627 if (this->fontStyle().weight() < SkFontStyle::Bold().weight()) {
628 fsSelection[0xF - 0x6] = '1'; // Not bold or italic, is regular
629 }
630 break;
631 case SkFontStyle::kItalic_Slant:
632 fsSelection[0xF - 0x0] = '1'; // Italic
633 break;
634 case SkFontStyle::kOblique_Slant:
635 fsSelection[0xF - 0x0] = '1'; // Italic
636 fsSelection[0xF - 0x9] = '1'; // Oblique
637 break;
638 default: SK_ABORT("Unknown slant.");
639 }
640 out->writeText(" <fsSelection value=\"");
641 out->write(fsSelection, 8);
642 out->writeText(" ");
643 out->write(fsSelection + 8, 8);
644 out->writeText("\"/>\n");
645 out->writeText(" <usFirstCharIndex value=\"0\"/>\n");
646 out->writeText(" <usLastCharIndex value=\"0\"/>\n");
647 out->writeText(" <sTypoAscender value=\"");
648 out->writeScalarAsText(-fFontMetrics.fAscent);
649 out->writeText("\"/>\n");
650 out->writeText(" <sTypoDescender value=\"");
651 out->writeScalarAsText(-fFontMetrics.fDescent);
652 out->writeText("\"/>\n");
653 out->writeText(" <sTypoLineGap value=\"");
654 out->writeScalarAsText(fFontMetrics.fLeading);
655 out->writeText("\"/>\n");
656 out->writeText(" <usWinAscent value=\"");
657 out->writeScalarAsText(-fFontMetrics.fAscent);
658 out->writeText("\"/>\n");
659 out->writeText(" <usWinDescent value=\"");
660 out->writeScalarAsText(fFontMetrics.fDescent);
661 out->writeText("\"/>\n");
662 out->writeText(" <ulCodePageRange1 value=\"00000000 00000000 00000000 00000000\"/>\n");
663 out->writeText(" <ulCodePageRange2 value=\"00000000 00000000 00000000 00000000\"/>\n");
664 out->writeText(" <sxHeight value=\"");
665 out->writeScalarAsText(fFontMetrics.fXHeight);
666 out->writeText("\"/>\n");
667 out->writeText(" <sCapHeight value=\"");
668 out->writeScalarAsText(fFontMetrics.fCapHeight);
669 out->writeText("\"/>\n");
670 out->writeText(" <usDefaultChar value=\"0\"/>\n");
671 out->writeText(" <usBreakChar value=\"32\"/>\n");
672 out->writeText(" <usMaxContext value=\"0\"/>\n");
673 out->writeText(" </OS_2>\n");
674
675 out->writeText(" <hmtx>\n");
676 for (int i = 0; i < fGlyphCount; ++i) {
677 out->writeText(" <mtx name=\"glyf");
678 out->writeHexAsText(i, 4);
679 out->writeText("\" width=\"");
680 out->writeDecAsText(fGlyphs[i].fAdvance);
681 out->writeText("\" lsb=\"");
682 int lsb = fGlyphs[i].fOrigin.fX;
683 if (glyfInfo) {
684 lsb += (*glyfInfo)[i].fBounds.fLeft;
685 }
686 out->writeDecAsText(lsb);
687 out->writeText("\"/>\n");
688 }
689 if (glyfInfo) {
690 for (int i = 0; i < fGlyphCount; ++i) {
691 for (int j = 0; j < (*glyfInfo)[i].fLayers.size(); ++j) {
692 out->writeText(" <mtx name=\"glyf");
693 out->writeHexAsText(i, 4);
694 out->writeText("l");
695 out->writeHexAsText(j, 4);
696 out->writeText("\" width=\"");
697 out->writeDecAsText(fGlyphs[i].fAdvance);
698 out->writeText("\" lsb=\"");
699 int32_t lsb = fGlyphs[i].fOrigin.fX + (*glyfInfo)[i].fLayers[j].fBounds.fLeft;
700 out->writeDecAsText(lsb);
701 out->writeText("\"/>\n");
702 }
703 }
704 }
705 out->writeText(" </hmtx>\n");
706
707 bool hasNonBMP = false;
708 out->writeText(" <cmap>\n");
709 out->writeText(" <tableVersion version=\"0\"/>\n");
710 out->writeText(" <cmap_format_4 platformID=\"3\" platEncID=\"1\" language=\"0\">\n");
711 fCMap.foreach ([&out, &hasNonBMP](const SkUnichar& c, const SkGlyphID& g) {
712 if (0xFFFF < c) {
713 hasNonBMP = true;
714 return;
715 }
716 out->writeText(" <map code=\"0x");
717 out->writeHexAsText(c, 4);
718 out->writeText("\" name=\"glyf");
719 out->writeHexAsText(g, 4);
720 out->writeText("\"/>\n");
721 });
722 out->writeText(" </cmap_format_4>\n");
723 if (hasNonBMP) {
724 out->writeText(
725 " <cmap_format_12 platformID=\"3\" platEncID=\"10\" format=\"12\" "
726 "reserved=\"0\" length=\"1\" language=\"0\" nGroups=\"0\">\n");
727 fCMap.foreach ([&out](const SkUnichar& c, const SkGlyphID& g) {
728 out->writeText(" <map code=\"0x");
729 out->writeHexAsText(c, 6);
730 out->writeText("\" name=\"glyf");
731 out->writeHexAsText(g, 4);
732 out->writeText("\"/>\n");
733 });
734 out->writeText(" </cmap_format_12>\n");
735 }
736 out->writeText(" </cmap>\n");
737
738 out->writeText(" <name>\n");
739 out->writeText(
740 " <namerecord nameID=\"1\" platformID=\"3\" platEncID=\"1\" langID=\"0x409\">\n");
741 out->writeText(" ");
742 out->writeText(fName.c_str());
743 out->writeText(" ");
744 out->writeText(type);
745 out->writeText("\n");
746 out->writeText(" </namerecord>\n");
747 out->writeText(
748 " <namerecord nameID=\"2\" platformID=\"3\" platEncID=\"1\" langID=\"0x409\">\n");
749 out->writeText(" Regular\n");
750 out->writeText(" </namerecord>\n");
751 out->writeText(
752 " <namerecord nameID=\"6\" platformID=\"3\" platEncID=\"1\" langID=\"0x409\">\n");
753 out->writeText(" ");
754 out->writeText(fName.c_str());
755 out->writeText("_");
756 out->writeText(type);
757 out->writeText("\n");
758 out->writeText(" </namerecord>\n");
759 out->writeText(" </name>\n");
760
761 out->writeText(" <post>\n");
762 out->writeText(" <formatType value=\"3.0\"/>\n");
763 out->writeText(" <italicAngle value=\"0.0\"/>\n");
764 out->writeText(" <underlinePosition value=\"");
765 out->writeScalarAsText(fFontMetrics.fUnderlinePosition);
766 out->writeText("\"/>\n");
767 out->writeText(" <underlineThickness value=\"");
768 out->writeScalarAsText(fFontMetrics.fUnderlineThickness);
769 out->writeText("\"/>\n");
770 out->writeText(" <isFixedPitch value=\"0\"/>\n");
771 out->writeText(" <minMemType42 value=\"0\"/>\n");
772 out->writeText(" <maxMemType42 value=\"0\"/>\n");
773 out->writeText(" <minMemType1 value=\"0\"/>\n");
774 out->writeText(" <maxMemType1 value=\"0\"/>\n");
775 out->writeText(" </post>\n");
776 }
777
778 void TestSVGTypeface::exportTtxCbdt(SkWStream* out, SkSpan<unsigned> strikeSizes) const {
779 SkPaint paint;
780 SkFont font;
781 font.setTypeface(sk_ref_sp(const_cast<TestSVGTypeface*>(this)));
782 SkString name;
783 this->getFamilyName(&name);
784
785 // The CBDT/CBLC format is quite restrictive. Only write strikes which fully fit.
786 STArray<8, int> goodStrikeSizes;
787 for (size_t strikeIndex = 0; strikeIndex < strikeSizes.size(); ++strikeIndex) {
788 font.setSize(strikeSizes[strikeIndex]);
789
790 // CBLC limits
791 SkFontMetrics fm;
792 font.getMetrics(&fm);
793 if (!SkTFitsIn<int8_t>((int)(-fm.fTop)) || !SkTFitsIn<int8_t>((int)(-fm.fBottom)) ||
794 !SkTFitsIn<uint8_t>((int)(fm.fXMax - fm.fXMin))) {
795 SkDebugf("Metrics too big cbdt font size %f for %s.\n", font.getSize(), name.c_str());
796 continue;
797 }
798
799 // CBDT limits
800 auto exceedsCbdtLimits = [&]() {
801 for (int i = 0; i < fGlyphCount; ++i) {
802 SkGlyphID gid = i;
803 SkScalar advance;
804 SkRect bounds;
805 font.getWidthsBounds({&gid, 1}, {&advance, 1}, {&bounds, 1}, nullptr);
806 SkIRect ibounds = bounds.roundOut();
807 if (!SkTFitsIn<int8_t>(ibounds.fLeft) || !SkTFitsIn<int8_t>(ibounds.fTop) ||
808 !SkTFitsIn<uint8_t>(ibounds.width()) || !SkTFitsIn<uint8_t>(ibounds.height()) ||
809 !SkTFitsIn<uint8_t>((int)advance)) {
810 return true;
811 }
812 }
813 return false;
814 };
815 if (exceedsCbdtLimits()) {
816 SkDebugf("Glyphs too big cbdt font size %f for %s.\n", font.getSize(), name.c_str());
817 continue;
818 }
819
820 goodStrikeSizes.emplace_back(strikeSizes[strikeIndex]);
821 }
822
823 if (goodStrikeSizes.empty()) {
824 SkDebugf("No strike size fit for cbdt font for %s.\n", name.c_str());
825 return;
826 }
827
828 out->writeText("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
829 out->writeText("<ttFont sfntVersion=\"\\x00\\x01\\x00\\x00\" ttLibVersion=\"3.19\">\n");
830 this->exportTtxCommon(out, "CBDT");
831
832 out->writeText(" <CBDT>\n");
833 out->writeText(" <header version=\"2.0\"/>\n");
834 for (int strikeIndex = 0; strikeIndex < goodStrikeSizes.size(); ++strikeIndex) {
835 font.setSize(goodStrikeSizes[strikeIndex]);
836
837 out->writeText(" <strikedata index=\"");
838 out->writeDecAsText(strikeIndex);
839 out->writeText("\">\n");
840 for (int i = 0; i < fGlyphCount; ++i) {
841 SkGlyphID gid = i;
842 SkScalar advance;
843 SkRect bounds;
844 font.getWidthsBounds({&gid, 1}, {&advance, 1}, {&bounds, 1}, nullptr);
845 SkIRect ibounds = bounds.roundOut();
846 if (ibounds.isEmpty()) {
847 continue;
848 }
849 SkImageInfo image_info = SkImageInfo::MakeN32Premul(ibounds.width(), ibounds.height());
850 sk_sp<SkSurface> surface(SkSurfaces::Raster(image_info));
851 SkASSERT(surface);
852 SkCanvas* canvas = surface->getCanvas();
853 canvas->clear(0);
854 SkPixmap pix;
855 surface->peekPixels(&pix);
856 canvas->drawSimpleText(&gid,
857 sizeof(gid),
858 SkTextEncoding::kGlyphID,
859 -bounds.fLeft,
860 -bounds.fTop,
861 font,
862 paint);
863
864 sk_sp<SkImage> image = surface->makeImageSnapshot();
865 sk_sp<SkData> data = SkPngEncoder::Encode(nullptr, image.get(), {});
866
867 out->writeText(" <cbdt_bitmap_format_17 name=\"glyf");
868 out->writeHexAsText(i, 4);
869 out->writeText("\">\n");
870 out->writeText(" <SmallGlyphMetrics>\n");
871 out->writeText(" <height value=\"");
872 out->writeDecAsText(image->height());
873 out->writeText("\"/>\n");
874 out->writeText(" <width value=\"");
875 out->writeDecAsText(image->width());
876 out->writeText("\"/>\n");
877 out->writeText(" <BearingX value=\"");
878 out->writeDecAsText(ibounds.fLeft);
879 out->writeText("\"/>\n");
880 out->writeText(" <BearingY value=\"");
881 out->writeDecAsText(-ibounds.fTop);
882 out->writeText("\"/>\n");
883 out->writeText(" <Advance value=\"");
884 out->writeDecAsText((int)advance);
885 out->writeText("\"/>\n");
886 out->writeText(" </SmallGlyphMetrics>\n");
887 out->writeText(" <rawimagedata>");
888 uint8_t const* bytes = data->bytes();
889 for (size_t j = 0; j < data->size(); ++j) {
890 if ((j % 0x10) == 0x0) {
891 out->writeText("\n ");
892 } else if (((j - 1) % 0x4) == 0x3) {
893 out->writeText(" ");
894 }
895 out->writeHexAsText(bytes[j], 2);
896 }
897 out->writeText("\n");
898 out->writeText(" </rawimagedata>\n");
899 out->writeText(" </cbdt_bitmap_format_17>\n");
900 }
901 out->writeText(" </strikedata>\n");
902 }
903 out->writeText(" </CBDT>\n");
904
905 SkFontMetrics fm;
906 out->writeText(" <CBLC>\n");
907 out->writeText(" <header version=\"2.0\"/>\n");
908 for (int strikeIndex = 0; strikeIndex < goodStrikeSizes.size(); ++strikeIndex) {
909 font.setSize(goodStrikeSizes[strikeIndex]);
910 font.getMetrics(&fm);
911 out->writeText(" <strike index=\"");
912 out->writeDecAsText(strikeIndex);
913 out->writeText("\">\n");
914 out->writeText(" <bitmapSizeTable>\n");
915 out->writeText(" <sbitLineMetrics direction=\"hori\">\n");
916 out->writeText(" <ascender value=\"");
917 out->writeDecAsText((int)(-fm.fTop));
918 out->writeText("\"/>\n");
919 out->writeText(" <descender value=\"");
920 out->writeDecAsText((int)(-fm.fBottom));
921 out->writeText("\"/>\n");
922 out->writeText(" <widthMax value=\"");
923 out->writeDecAsText((int)(fm.fXMax - fm.fXMin));
924 out->writeText("\"/>\n");
925 out->writeText(" <caretSlopeNumerator value=\"0\"/>\n");
926 out->writeText(" <caretSlopeDenominator value=\"0\"/>\n");
927 out->writeText(" <caretOffset value=\"0\"/>\n");
928 out->writeText(" <minOriginSB value=\"0\"/>\n");
929 out->writeText(" <minAdvanceSB value=\"0\"/>\n");
930 out->writeText(" <maxBeforeBL value=\"0\"/>\n");
931 out->writeText(" <minAfterBL value=\"0\"/>\n");
932 out->writeText(" <pad1 value=\"0\"/>\n");
933 out->writeText(" <pad2 value=\"0\"/>\n");
934 out->writeText(" </sbitLineMetrics>\n");
935 out->writeText(" <sbitLineMetrics direction=\"vert\">\n");
936 out->writeText(" <ascender value=\"");
937 out->writeDecAsText((int)(-fm.fTop));
938 out->writeText("\"/>\n");
939 out->writeText(" <descender value=\"");
940 out->writeDecAsText((int)(-fm.fBottom));
941 out->writeText("\"/>\n");
942 out->writeText(" <widthMax value=\"");
943 out->writeDecAsText((int)(fm.fXMax - fm.fXMin));
944 out->writeText("\"/>\n");
945 out->writeText(" <caretSlopeNumerator value=\"0\"/>\n");
946 out->writeText(" <caretSlopeDenominator value=\"0\"/>\n");
947 out->writeText(" <caretOffset value=\"0\"/>\n");
948 out->writeText(" <minOriginSB value=\"0\"/>\n");
949 out->writeText(" <minAdvanceSB value=\"0\"/>\n");
950 out->writeText(" <maxBeforeBL value=\"0\"/>\n");
951 out->writeText(" <minAfterBL value=\"0\"/>\n");
952 out->writeText(" <pad1 value=\"0\"/>\n");
953 out->writeText(" <pad2 value=\"0\"/>\n");
954 out->writeText(" </sbitLineMetrics>\n");
955 out->writeText(" <colorRef value=\"0\"/>\n");
956 out->writeText(" <startGlyphIndex value=\"1\"/>\n");
957 out->writeText(" <endGlyphIndex value=\"1\"/>\n");
958 out->writeText(" <ppemX value=\"");
959 out->writeDecAsText(goodStrikeSizes[strikeIndex]);
960 out->writeText("\"/>\n");
961 out->writeText(" <ppemY value=\"");
962 out->writeDecAsText(goodStrikeSizes[strikeIndex]);
963 out->writeText("\"/>\n");
964 out->writeText(" <bitDepth value=\"32\"/>\n");
965 out->writeText(" <flags value=\"1\"/>\n");
966 out->writeText(" </bitmapSizeTable>\n");
967 out->writeText(
968 " <eblc_index_sub_table_1 imageFormat=\"17\" firstGlyphIndex=\"1\" "
969 "lastGlyphIndex=\"1\">\n");
970 for (int i = 0; i < fGlyphCount; ++i) {
971 SkGlyphID gid = i;
972 SkRect bounds = font.getBounds(gid, nullptr);
973 if (bounds.isEmpty()) {
974 continue;
975 }
976 out->writeText(" <glyphLoc name=\"glyf");
977 out->writeHexAsText(i, 4);
978 out->writeText("\"/>\n");
979 }
980 out->writeText(" </eblc_index_sub_table_1>\n");
981 out->writeText(" </strike>\n");
982 }
983 out->writeText(" </CBLC>\n");
984
985 out->writeText("</ttFont>\n");
986 }
987
988 /**
989 * UnitsPerEm is generally 1000 here. Versions of macOS older than 10.13
990 * have problems in CoreText determining the glyph bounds of bitmap glyphs
991 * with unitsPerEm set to 1024 or numbers not divisible by 100 when the
992 * contour is not closed. The bounds of sbix fonts on macOS appear to be those
993 * of the outline in the 'glyf' table. If this countour is closed it will be
994 * drawn, as the 'glyf' outline is to be drawn on top of any bitmap. (There is
995 * a bit which is supposed to control this, but it cannot be relied on.) So
996 * make the glyph contour a degenerate line with points at the edge of the
997 * bounding box of the glyph.
998 *
999 * See the SBIX slide in viewer for how positioning and bounds work. CoreText sbix is buggy in the
1000 * way it applies the glyf bbox values (only to one side).
1001 * The bbox in DWrite is ((0, 0),(png.width, png.height)) + originOffset
1002 * The bbox in FreeType is ((0, 0),(png.width, png.height)) + (lsb, bbox.yMin) + originOffset.
1003 * The bbox in CoreText is ((lsb, bbox.yMin), (lsb + bbox.xMax - bbox.xMin, bbox.yMax))
1004 * In FreeType and DWrite the originOffsetX/Y apply to the bitmap and bounds.
1005 * In CoreText the originOffsetX/Y apply only to the bitmap (and not the bounds).
1006 *
1007 * The only way to create a compatibly positioned sbix bitmap glyph is to set
1008 * lsb = 0, bbox = ((0,0),png.size), originOffset = (0,0) and pad the png with transparent pixels.
1009 * This of course can only move the image up and to the right.
1010 *
1011 * To work with just CoreText and FreeType 2.12.0+ (DWrite having no offset)
1012 * lsb = x, bbox = ((0, y),(png.width, png.height + y)), originOffset = (0,0)
1013 * Which this does, since DWrite should be adding the lsb and bbox.yMin.
1014 */
1015 void TestSVGTypeface::exportTtxSbix(SkWStream* out, SkSpan<unsigned> strikeSizes) const {
1016 out->writeText("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1017 out->writeText("<ttFont sfntVersion=\"\\x00\\x01\\x00\\x00\" ttLibVersion=\"3.19\">\n");
1018 this->exportTtxCommon(out, "sbix");
1019
1020 SkPaint paint;
1021 SkFont font;
1022 font.setTypeface(sk_ref_sp(const_cast<TestSVGTypeface*>(this)));
1023
1024 out->writeText(" <glyf>\n");
1025 for (int i = 0; i < fGlyphCount; ++i) {
1026 const TestSVGTypeface::Glyph& glyphData = this->fGlyphs[i];
1027
1028 SkSize containerSize = glyphData.size();
1029 SkRect bounds = SkRect::MakeXYWH(glyphData.fOrigin.fX, -glyphData.fOrigin.fY,
1030 containerSize.fWidth, containerSize.fHeight);
1031 SkIRect ibounds = bounds.roundOut();
1032 out->writeText(" <TTGlyph name=\"glyf");
1033 out->writeHexAsText(i, 4);
1034 out->writeText("\" xMin=\"");
1035 out->writeDecAsText(/*ibounds.fLeft*/0); //hmtx::lsb already has this from common
1036 out->writeText("\" yMin=\"");
1037 out->writeDecAsText(-ibounds.fBottom);
1038 out->writeText("\" xMax=\"");
1039 out->writeDecAsText(ibounds.fRight - ibounds.fLeft);
1040 out->writeText("\" yMax=\"");
1041 out->writeDecAsText(-ibounds.fTop);
1042 out->writeText("\">\n");
1043 out->writeText(" <contour>\n");
1044 out->writeText(" <pt x=\"");
1045 out->writeDecAsText(/*ibounds.fLeft*/0);
1046 out->writeText("\" y=\"");
1047 out->writeDecAsText(-ibounds.fBottom);
1048 out->writeText("\" on=\"1\"/>\n");
1049 out->writeText(" </contour>\n");
1050 out->writeText(" <contour>\n");
1051 out->writeText(" <pt x=\"");
1052 out->writeDecAsText(ibounds.fRight - ibounds.fLeft);
1053 out->writeText("\" y=\"");
1054 out->writeDecAsText(-ibounds.fTop);
1055 out->writeText("\" on=\"1\"/>\n");
1056 out->writeText(" </contour>\n");
1057 out->writeText(" <instructions/>\n");
1058 out->writeText(" </TTGlyph>\n");
1059 }
1060 out->writeText(" </glyf>\n");
1061
1062 // The loca table will be re-calculated, but if we don't write one we don't get one.
1063 out->writeText(" <loca/>\n");
1064
1065 out->writeText(" <sbix>\n");
1066 out->writeText(" <version value=\"1\"/>\n");
1067 out->writeText(" <flags value=\"00000000 00000001\"/>\n");
1068 for (size_t strikeIndex = 0; strikeIndex < strikeSizes.size(); ++strikeIndex) {
1069 font.setSize(strikeSizes[strikeIndex]);
1070 out->writeText(" <strike>\n");
1071 out->writeText(" <ppem value=\"");
1072 out->writeDecAsText(strikeSizes[strikeIndex]);
1073 out->writeText("\"/>\n");
1074 out->writeText(" <resolution value=\"72\"/>\n");
1075 for (int i = 0; i < fGlyphCount; ++i) {
1076 SkGlyphID gid = i;
1077 SkScalar advance;
1078 SkRect bounds;
1079 font.getWidthsBounds({&gid, 1}, {&advance, 1}, {&bounds, 1}, nullptr);
1080 SkIRect ibounds = bounds.roundOut();
1081 if (ibounds.isEmpty()) {
1082 continue;
1083 }
1084 SkImageInfo image_info = SkImageInfo::MakeN32Premul(ibounds.width(), ibounds.height());
1085 sk_sp<SkSurface> surface(SkSurfaces::Raster(image_info));
1086 SkASSERT(surface);
1087 SkCanvas* canvas = surface->getCanvas();
1088 canvas->clear(0);
1089 SkPixmap pix;
1090 surface->peekPixels(&pix);
1091 canvas->drawSimpleText(&gid,
1092 sizeof(gid),
1093 SkTextEncoding::kGlyphID,
1094 -bounds.fLeft,
1095 -bounds.fTop,
1096 font,
1097 paint);
1098
1099 sk_sp<SkImage> image = surface->makeImageSnapshot();
1100 sk_sp<SkData> data = SkPngEncoder::Encode(nullptr, image.get(), {});
1101
1102 out->writeText(" <glyph name=\"glyf");
1103 out->writeHexAsText(i, 4);
1104
1105 // DirectWrite and CoreGraphics use positive values of originOffsetY to push the
1106 // image visually up (but from different origins).
1107 // FreeType used positive values to push the image down until 2.12.0.
1108 // However, in a bitmap only font there is little reason for these to not be zero.
1109 out->writeText("\" graphicType=\"png \" originOffsetX=\"0\" originOffsetY=\"0\">\n");
1110
1111 out->writeText(" <hexdata>");
1112 uint8_t const* bytes = data->bytes();
1113 for (size_t j = 0; j < data->size(); ++j) {
1114 if ((j % 0x10) == 0x0) {
1115 out->writeText("\n ");
1116 } else if (((j - 1) % 0x4) == 0x3) {
1117 out->writeText(" ");
1118 }
1119 out->writeHexAsText(bytes[j], 2);
1120 }
1121 out->writeText("\n");
1122 out->writeText(" </hexdata>\n");
1123 out->writeText(" </glyph>\n");
1124 }
1125 out->writeText(" </strike>\n");
1126 }
1127 out->writeText(" </sbix>\n");
1128 out->writeText("</ttFont>\n");
1129 }
1130
1131 namespace {
1132
1133 void convert_noninflect_cubic_to_quads(const SkPoint p[4],
1134 SkScalar toleranceSqd,
1135 TArray<SkPoint, true>* quads,
1136 int sublevel = 0) {
1137 // Notation: Point a is always p[0]. Point b is p[1] unless p[1] == p[0], in which case it is
1138 // p[2]. Point d is always p[3]. Point c is p[2] unless p[2] == p[3], in which case it is p[1].
1139
1140 SkVector ab = p[1] - p[0];
1141 SkVector dc = p[2] - p[3];
1142
1143 if (SkPointPriv::LengthSqd(ab) < SK_ScalarNearlyZero) {
1144 if (SkPointPriv::LengthSqd(dc) < SK_ScalarNearlyZero) {
1145 SkPoint* degQuad = quads->push_back_n(3);
1146 degQuad[0] = p[0];
1147 degQuad[1] = p[0];
1148 degQuad[2] = p[3];
1149 return;
1150 }
1151 ab = p[2] - p[0];
1152 }
1153 if (SkPointPriv::LengthSqd(dc) < SK_ScalarNearlyZero) {
1154 dc = p[1] - p[3];
1155 }
1156
1157 static const SkScalar kLengthScale = 3 * SK_Scalar1 / 2;
1158 static const int kMaxSubdivs = 10;
1159
1160 ab.scale(kLengthScale);
1161 dc.scale(kLengthScale);
1162
1163 // e0 and e1 are extrapolations along vectors ab and dc.
1164 SkVector c0 = p[0];
1165 c0 += ab;
1166 SkVector c1 = p[3];
1167 c1 += dc;
1168
1169 SkScalar dSqd = sublevel > kMaxSubdivs ? 0 : SkPointPriv::DistanceToSqd(c0, c1);
1170 if (dSqd < toleranceSqd) {
1171 SkPoint cAvg = c0;
1172 cAvg += c1;
1173 cAvg.scale(SK_ScalarHalf);
1174
1175 SkPoint* pts = quads->push_back_n(3);
1176 pts[0] = p[0];
1177 pts[1] = cAvg;
1178 pts[2] = p[3];
1179 return;
1180 }
1181 SkPoint choppedPts[7];
1182 SkChopCubicAtHalf(p, choppedPts);
1183 convert_noninflect_cubic_to_quads(choppedPts + 0, toleranceSqd, quads, sublevel + 1);
1184 convert_noninflect_cubic_to_quads(choppedPts + 3, toleranceSqd, quads, sublevel + 1);
1185 }
1186
1187 void convertCubicToQuads(const SkPoint p[4], SkScalar tolScale, TArray<SkPoint, true>* quads) {
1188 if (!p[0].isFinite() || !p[1].isFinite() || !p[2].isFinite() || !p[3].isFinite()) {
1189 return;
1190 }
1191 SkPoint chopped[10];
1192 int count = SkChopCubicAtInflections(p, chopped);
1193
1194 const SkScalar tolSqd = SkScalarSquare(tolScale);
1195
1196 for (int i = 0; i < count; ++i) {
1197 SkPoint* cubic = chopped + 3 * i;
1198 convert_noninflect_cubic_to_quads(cubic, tolSqd, quads);
1199 }
1200 }
1201
1202 SkPath path_to_quads(const SkPath& path) {
1203 SkPathBuilder quadPath;
1204 TArray<SkPoint, true> qPts;
1205 SkAutoConicToQuads converter;
1206 const SkPoint* quadPts;
1207 for (auto [verb, pts, w] : SkPathPriv::Iterate(path)) {
1208 switch (verb) {
1209 case SkPathVerb::kMove: quadPath.moveTo(pts[0]); break;
1210 case SkPathVerb::kLine: quadPath.lineTo(pts[1]); break;
1211 case SkPathVerb::kQuad:
1212 quadPath.quadTo(pts[1].fX, pts[1].fY, pts[2].fX, pts[2].fY);
1213 break;
1214 case SkPathVerb::kCubic:
1215 qPts.clear();
1216 convertCubicToQuads(pts, SK_Scalar1, &qPts);
1217 for (int i = 0; i < qPts.size(); i += 3) {
1218 quadPath.quadTo(
1219 qPts[i + 1].fX, qPts[i + 1].fY, qPts[i + 2].fX, qPts[i + 2].fY);
1220 }
1221 break;
1222 case SkPathVerb::kConic:
1223 quadPts = converter.computeQuads(pts, *w, SK_Scalar1);
1224 for (int i = 0; i < converter.countQuads(); ++i) {
1225 quadPath.quadTo(quadPts[i * 2 + 1], quadPts[i * 2 + 2]);
1226 }
1227 break;
1228 case SkPathVerb::kClose: quadPath.close(); break;
1229 }
1230 }
1231 return quadPath.detach();
1232 }
1233
1234 class SkCOLRCanvas : public SkNoDrawCanvas {
1235 public:
1236 SkCOLRCanvas(SkRect glyphBounds,
1237 const TestSVGTypeface& typeface,
1238 SkGlyphID glyphId,
1239 TestSVGTypeface::GlyfInfo* glyf,
1240 THashMap<SkColor, int>* colors,
1241 SkWStream* out)
1242 : SkNoDrawCanvas(glyphBounds.roundOut().width(), glyphBounds.roundOut().height())
1243 , fBaselineOffset(glyphBounds.top())
1244 , fTypeface(typeface)
1245 , fGlyphId(glyphId)
1246 , fGlyf(glyf)
1247 , fColors(colors)
1248 , fOut(out)
1249 , fLayerId(0) {}
1250
1251 void writePoint(SkScalar x, SkScalar y, bool on) {
1252 fOut->writeText(" <pt x=\"");
1253 fOut->writeDecAsText(SkScalarRoundToInt(x));
1254 fOut->writeText("\" y=\"");
1255 fOut->writeDecAsText(SkScalarRoundToInt(y));
1256 fOut->writeText("\" on=\"");
1257 fOut->write8(on ? '1' : '0');
1258 fOut->writeText("\"/>\n");
1259 }
1260 SkIRect writePath(const SkPath& path, bool layer) {
1261 // Convert to quads.
1262 SkPath quads = path_to_quads(path);
1263
1264 SkRect bounds = quads.computeTightBounds();
1265 SkIRect ibounds = bounds.roundOut();
1266 // The bounds will be re-calculated anyway.
1267 fOut->writeText(" <TTGlyph name=\"glyf");
1268 fOut->writeHexAsText(fGlyphId, 4);
1269 if (layer) {
1270 fOut->writeText("l");
1271 fOut->writeHexAsText(fLayerId, 4);
1272 }
1273 fOut->writeText("\" xMin=\"");
1274 fOut->writeDecAsText(ibounds.fLeft);
1275 fOut->writeText("\" yMin=\"");
1276 fOut->writeDecAsText(ibounds.fTop);
1277 fOut->writeText("\" xMax=\"");
1278 fOut->writeDecAsText(ibounds.fRight);
1279 fOut->writeText("\" yMax=\"");
1280 fOut->writeDecAsText(ibounds.fBottom);
1281 fOut->writeText("\">\n");
1282
1283 bool contourOpen = false;
1284 for (auto [verb, pts, w] : SkPathPriv::Iterate(quads)) {
1285 switch (verb) {
1286 case SkPathVerb::kMove:
1287 if (contourOpen) {
1288 fOut->writeText(" </contour>\n");
1289 contourOpen = false;
1290 }
1291 break;
1292 case SkPathVerb::kLine:
1293 if (!contourOpen) {
1294 fOut->writeText(" <contour>\n");
1295 this->writePoint(pts[0].fX, pts[0].fY, true);
1296 contourOpen = true;
1297 }
1298 this->writePoint(pts[1].fX, pts[1].fY, true);
1299 break;
1300 case SkPathVerb::kQuad:
1301 if (!contourOpen) {
1302 fOut->writeText(" <contour>\n");
1303 this->writePoint(pts[0].fX, pts[0].fY, true);
1304 contourOpen = true;
1305 }
1306 this->writePoint(pts[1].fX, pts[1].fY, false);
1307 this->writePoint(pts[2].fX, pts[2].fY, true);
1308 break;
1309 case SkPathVerb::kClose:
1310 if (contourOpen) {
1311 fOut->writeText(" </contour>\n");
1312 contourOpen = false;
1313 }
1314 break;
1315 default: SkDEBUGFAIL("bad verb"); return ibounds;
1316 }
1317 }
1318 if (contourOpen) {
1319 fOut->writeText(" </contour>\n");
1320 }
1321
1322 // Required to write out an instructions tag.
1323 fOut->writeText(" <instructions/>\n");
1324 fOut->writeText(" </TTGlyph>\n");
1325 return ibounds;
1326 }
1327
1328 void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
1329 this->drawPath(SkPath::Rect(rect), paint);
1330 }
1331
1332 void onDrawOval(const SkRect& oval, const SkPaint& paint) override {
1333 this->drawPath(SkPath::Oval(oval), paint);
1334 }
1335
1336 void onDrawArc(const SkRect& oval,
1337 SkScalar startAngle,
1338 SkScalar sweepAngle,
1339 bool useCenter,
1340 const SkPaint& paint) override {
1341 bool fillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
1342 SkPath path = SkPathPriv::CreateDrawArcPath(
1343 SkArc::Make(oval, startAngle, sweepAngle, useCenter), fillNoPathEffect);
1344 this->drawPath(path, paint);
1345 }
1346
1347 void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
1348 this->drawPath(SkPath::RRect(rrect), paint);
1349 }
1350
1351 void onDrawPath(const SkPath& platonicPath, const SkPaint& originalPaint) override {
1352 SkPaint paint = originalPaint;
1353 SkPath path = platonicPath;
1354
1355 // Apply the path effect.
1356 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
1357 SkPathBuilder builder;
1358 bool fill = skpathutils::FillPathWithPaint(path, paint, &builder);
1359 path = builder.detach();
1360
1361 paint.setPathEffect(nullptr);
1362 if (fill) {
1363 paint.setStyle(SkPaint::kFill_Style);
1364 } else {
1365 paint.setStyle(SkPaint::kStroke_Style);
1366 paint.setStrokeWidth(0);
1367 }
1368 }
1369
1370 // Apply the matrix.
1371 SkMatrix m = this->getTotalMatrix();
1372 // If done to the canvas then everything would get clipped out.
1373 m.postTranslate(0, fBaselineOffset); // put the baseline at 0
1374 m.postScale(1, -1); // and flip it since OpenType is y-up.
1375 path = path.makeTransform(m);
1376
1377 // While creating the default glyf, union with dark colors and intersect with bright colors.
1378 SkColor color = paint.getColor();
1379 SkPathOp op;
1380 if (fTypeface.getPathOp(color, &op)) {
1381 fBasePath.add(path, op);
1382 }
1383 SkIRect bounds = this->writePath(path, true);
1384
1385 // The CPAL table has the concept of a 'current color' which is index 0xFFFF.
1386 // Mark any layer drawn in 'currentColor' as having this special index.
1387 // The value of 'currentColor' here should a color which causes this layer to union into the
1388 // default glyf.
1389 constexpr SkColor currentColor = 0xFF2B0000;
1390
1391 int colorIndex;
1392 if (color == currentColor) {
1393 colorIndex = 0xFFFF;
1394 } else {
1395 int* colorIndexPtr = fColors->find(color);
1396 if (colorIndexPtr) {
1397 colorIndex = *colorIndexPtr;
1398 } else {
1399 colorIndex = fColors->count();
1400 fColors->set(color, colorIndex);
1401 }
1402 }
1403 fGlyf->fLayers.emplace_back(colorIndex, bounds);
1404
1405 ++fLayerId;
1406 }
1407
1408 void finishGlyph() {
1409 SkPath baseGlyph = fBasePath.resolve().value_or(SkPath());
1410 fGlyf->fBounds = this->writePath(baseGlyph, false);
1411 }
1412
1413 private:
1414 SkScalar fBaselineOffset;
1415 const TestSVGTypeface& fTypeface;
1416 SkGlyphID fGlyphId;
1417 TestSVGTypeface::GlyfInfo* fGlyf;
1418 THashMap<SkColor, int>* fColors;
1419 SkWStream* const fOut;
1420 SkOpBuilder fBasePath;
1421 int fLayerId;
1422 };
1423
1424 } // namespace
1425
1426 void TestSVGTypeface::exportTtxColr(SkWStream* out) const {
1427 out->writeText("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1428 out->writeText("<ttFont sfntVersion=\"\\x00\\x01\\x00\\x00\" ttLibVersion=\"3.19\">\n");
1429
1430 THashMap<SkColor, int> colors;
1431 TArray<GlyfInfo> glyfInfos(fGlyphCount);
1432
1433 // Need to know all the glyphs up front for the common tables.
1434 SkDynamicMemoryWStream glyfOut;
1435 glyfOut.writeText(" <glyf>\n");
1436 for (int i = 0; i < fGlyphCount; ++i) {
1437 const TestSVGTypeface::Glyph& glyphData = this->fGlyphs[i];
1438
1439 SkSize containerSize = glyphData.size();
1440 SkRect bounds = SkRect::MakeXYWH(glyphData.fOrigin.fX,
1441 -glyphData.fOrigin.fY,
1442 containerSize.fWidth,
1443 containerSize.fHeight);
1444 SkCOLRCanvas canvas(bounds, *this, i, &glyfInfos.emplace_back(), &colors, &glyfOut);
1445 glyphData.render(&canvas);
1446 canvas.finishGlyph();
1447 }
1448 glyfOut.writeText(" </glyf>\n");
1449
1450 this->exportTtxCommon(out, "COLR", &glyfInfos);
1451
1452 // The loca table will be re-calculated, but if we don't write one we don't get one.
1453 out->writeText(" <loca/>\n");
1454
1455 std::unique_ptr<SkStreamAsset> glyfStream = glyfOut.detachAsStream();
1456 out->writeStream(glyfStream.get(), glyfStream->getLength());
1457
1458 out->writeText(" <COLR>\n");
1459 out->writeText(" <version value=\"0\"/>\n");
1460 for (int i = 0; i < fGlyphCount; ++i) {
1461 if (glyfInfos[i].fLayers.empty()) {
1462 continue;
1463 }
1464 if (glyfInfos[i].fBounds.isEmpty()) {
1465 SkDebugf("Glyph %d is empty but has layers.\n", i);
1466 }
1467 out->writeText(" <ColorGlyph name=\"glyf");
1468 out->writeHexAsText(i, 4);
1469 out->writeText("\">\n");
1470 for (int j = 0; j < glyfInfos[i].fLayers.size(); ++j) {
1471 const int colorIndex = glyfInfos[i].fLayers[j].fLayerColorIndex;
1472 out->writeText(" <layer colorID=\"");
1473 out->writeDecAsText(colorIndex);
1474 out->writeText("\" name=\"glyf");
1475 out->writeHexAsText(i, 4);
1476 out->writeText("l");
1477 out->writeHexAsText(j, 4);
1478 out->writeText("\"/>\n");
1479 }
1480 out->writeText(" </ColorGlyph>\n");
1481 }
1482 out->writeText(" </COLR>\n");
1483
1484 // The colors must be written in order, the 'index' is ignored by ttx.
1485 AutoTMalloc<SkColor> colorsInOrder(colors.count());
1486 colors.foreach ([&colorsInOrder](const SkColor& c, const int* i) { colorsInOrder[*i] = c; });
1487 out->writeText(" <CPAL>\n");
1488 out->writeText(" <version value=\"0\"/>\n");
1489 out->writeText(" <numPaletteEntries value=\"");
1490 out->writeDecAsText(colors.count());
1491 out->writeText("\"/>\n");
1492 out->writeText(" <palette index=\"0\">\n");
1493 for (int i = 0; i < colors.count(); ++i) {
1494 SkColor c = colorsInOrder[i];
1495 out->writeText(" <color index=\"");
1496 out->writeDecAsText(i);
1497 out->writeText("\" value=\"#");
1498 out->writeHexAsText(SkColorGetR(c), 2);
1499 out->writeHexAsText(SkColorGetG(c), 2);
1500 out->writeHexAsText(SkColorGetB(c), 2);
1501 out->writeHexAsText(SkColorGetA(c), 2);
1502 out->writeText("\"/>\n");
1503 }
1504 out->writeText(" </palette>\n");
1505 out->writeText(" </CPAL>\n");
1506
1507 out->writeText("</ttFont>\n");
1508 }
1509 #endif // SK_ENABLE_SVG