blob: e9f0a3735fa50adb128e9f9c07bd68ff5c49dab1 [file] [log] [blame]
Xavier Phane29cdaf2020-03-26 16:15:14 +00001/*
2 * Copyright 2019 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
Florin Malitab3418102020-10-15 18:10:29 -04008#include "modules/svg/include/SkSVGText.h"
Xavier Phane29cdaf2020-03-26 16:15:14 +00009
Florin Malitadec78022020-12-17 16:36:54 -050010#include <limits>
Florin Malita7dc984a2020-12-08 11:37:15 -050011
Xavier Phane29cdaf2020-03-26 16:15:14 +000012#include "include/core/SkCanvas.h"
Florin Malitafc0ea0a2021-01-12 13:27:01 -050013#include "include/core/SkContourMeasure.h"
Florin Malita512ff752020-12-06 11:50:52 -050014#include "include/core/SkFont.h"
Florin Malita39fe8c82020-10-20 10:43:03 -040015#include "include/core/SkFontMgr.h"
Tyler Freemane9663db2020-04-14 14:37:13 -070016#include "include/core/SkFontStyle.h"
Florin Malitaf661ec72021-01-26 08:49:10 -050017#include "include/core/SkPathBuilder.h"
Florin Malitae5a21712020-12-30 11:08:53 -050018#include "include/core/SkRSXform.h"
Tyler Freemane9663db2020-04-14 14:37:13 -070019#include "include/core/SkString.h"
Florin Malita7dc984a2020-12-08 11:37:15 -050020#include "modules/skshaper/include/SkShaper.h"
Florin Malitab3418102020-10-15 18:10:29 -040021#include "modules/svg/include/SkSVGRenderContext.h"
22#include "modules/svg/include/SkSVGValue.h"
Florin Malitadec78022020-12-17 16:36:54 -050023#include "modules/svg/src/SkSVGTextPriv.h"
Florin Malitaf9652242021-01-25 14:12:26 -050024#include "src/core/SkTextBlobPriv.h"
Florin Malita9c1f1be2020-12-09 13:02:50 -050025#include "src/utils/SkUTF.h"
Xavier Phane29cdaf2020-03-26 16:15:14 +000026
Florin Malita512ff752020-12-06 11:50:52 -050027namespace {
Xavier Phane29cdaf2020-03-26 16:15:14 +000028
Florin Malita512ff752020-12-06 11:50:52 -050029static SkFont ResolveFont(const SkSVGRenderContext& ctx) {
Florin Malita39fe8c82020-10-20 10:43:03 -040030 auto weight = [](const SkSVGFontWeight& w) {
31 switch (w.type()) {
32 case SkSVGFontWeight::Type::k100: return SkFontStyle::kThin_Weight;
33 case SkSVGFontWeight::Type::k200: return SkFontStyle::kExtraLight_Weight;
34 case SkSVGFontWeight::Type::k300: return SkFontStyle::kLight_Weight;
35 case SkSVGFontWeight::Type::k400: return SkFontStyle::kNormal_Weight;
36 case SkSVGFontWeight::Type::k500: return SkFontStyle::kMedium_Weight;
37 case SkSVGFontWeight::Type::k600: return SkFontStyle::kSemiBold_Weight;
38 case SkSVGFontWeight::Type::k700: return SkFontStyle::kBold_Weight;
39 case SkSVGFontWeight::Type::k800: return SkFontStyle::kExtraBold_Weight;
40 case SkSVGFontWeight::Type::k900: return SkFontStyle::kBlack_Weight;
41 case SkSVGFontWeight::Type::kNormal: return SkFontStyle::kNormal_Weight;
42 case SkSVGFontWeight::Type::kBold: return SkFontStyle::kBold_Weight;
43 case SkSVGFontWeight::Type::kBolder: return SkFontStyle::kExtraBold_Weight;
44 case SkSVGFontWeight::Type::kLighter: return SkFontStyle::kLight_Weight;
45 case SkSVGFontWeight::Type::kInherit: {
46 SkASSERT(false);
47 return SkFontStyle::kNormal_Weight;
48 }
49 }
50 SkUNREACHABLE;
51 };
52
53 auto slant = [](const SkSVGFontStyle& s) {
54 switch (s.type()) {
55 case SkSVGFontStyle::Type::kNormal: return SkFontStyle::kUpright_Slant;
56 case SkSVGFontStyle::Type::kItalic: return SkFontStyle::kItalic_Slant;
57 case SkSVGFontStyle::Type::kOblique: return SkFontStyle::kOblique_Slant;
58 case SkSVGFontStyle::Type::kInherit: {
59 SkASSERT(false);
60 return SkFontStyle::kUpright_Slant;
61 }
62 }
63 SkUNREACHABLE;
64 };
65
66 const auto& family = ctx.presentationContext().fInherited.fFontFamily->family();
67 const SkFontStyle style(weight(*ctx.presentationContext().fInherited.fFontWeight),
68 SkFontStyle::kNormal_Width,
69 slant(*ctx.presentationContext().fInherited.fFontStyle));
70
71 const auto size =
72 ctx.lengthContext().resolve(ctx.presentationContext().fInherited.fFontSize->size(),
73 SkSVGLengthContext::LengthType::kVertical);
74
Florin Malita7006e152020-11-10 15:24:59 -050075 // TODO: we likely want matchFamilyStyle here, but switching away from legacyMakeTypeface
76 // changes all the results when using the default fontmgr.
77 auto tf = ctx.fontMgr()->legacyMakeTypeface(family.c_str(), style);
78
79 SkFont font(std::move(tf), size);
Florin Malita39fe8c82020-10-20 10:43:03 -040080 font.setHinting(SkFontHinting::kNone);
81 font.setSubpixel(true);
82 font.setLinearMetrics(true);
83 font.setBaselineSnap(false);
84 font.setEdging(SkFont::Edging::kAntiAlias);
85
86 return font;
87}
88
Florin Malitadec78022020-12-17 16:36:54 -050089static std::vector<float> ResolveLengths(const SkSVGLengthContext& lctx,
90 const std::vector<SkSVGLength>& lengths,
91 SkSVGLengthContext::LengthType lt) {
92 std::vector<float> resolved;
93 resolved.reserve(lengths.size());
94
95 for (const auto& l : lengths) {
96 resolved.push_back(lctx.resolve(l, lt));
97 }
98
99 return resolved;
100}
101
102static float ComputeAlignmentFactor(const SkSVGPresentationContext& pctx) {
103 switch (pctx.fInherited.fTextAnchor->type()) {
Florin Malita7dc984a2020-12-08 11:37:15 -0500104 case SkSVGTextAnchor::Type::kStart : return 0.0f;
105 case SkSVGTextAnchor::Type::kMiddle: return -0.5f;
106 case SkSVGTextAnchor::Type::kEnd : return -1.0f;
107 case SkSVGTextAnchor::Type::kInherit:
108 SkASSERT(false);
109 return 0.0f;
110 }
111 SkUNREACHABLE;
112}
113
Florin Malita512ff752020-12-06 11:50:52 -0500114} // namespace
115
Florin Malitadec78022020-12-17 16:36:54 -0500116SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
117 const SkSVGLengthContext& lctx,
118 SkSVGTextContext* tctx,
119 size_t charIndexOffset)
120 : fTextContext(tctx)
121 , fParent(tctx->fPosResolver)
122 , fCharIndexOffset(charIndexOffset)
123 , fX(ResolveLengths(lctx, txt.getX(), SkSVGLengthContext::LengthType::kHorizontal))
124 , fY(ResolveLengths(lctx, txt.getY(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita735ac972020-12-22 11:23:32 -0500125 , fDx(ResolveLengths(lctx, txt.getDx(), SkSVGLengthContext::LengthType::kHorizontal))
126 , fDy(ResolveLengths(lctx, txt.getDy(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita2d059fc2021-01-05 11:53:15 -0500127 , fRotate(txt.getRotate())
Florin Malitadec78022020-12-17 16:36:54 -0500128{
129 fTextContext->fPosResolver = this;
130}
Florin Malita7dc984a2020-12-08 11:37:15 -0500131
Florin Malitadec78022020-12-17 16:36:54 -0500132SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
133 const SkSVGLengthContext& lctx,
134 SkSVGTextContext* tctx)
135 : ScopedPosResolver(txt, lctx, tctx, tctx->fCurrentCharIndex) {}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500136
Florin Malitadec78022020-12-17 16:36:54 -0500137SkSVGTextContext::ScopedPosResolver::~ScopedPosResolver() {
138 fTextContext->fPosResolver = fParent;
139}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500140
Florin Malitadec78022020-12-17 16:36:54 -0500141SkSVGTextContext::PosAttrs SkSVGTextContext::ScopedPosResolver::resolve(size_t charIndex) const {
142 PosAttrs attrs;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500143
Florin Malitadec78022020-12-17 16:36:54 -0500144 if (charIndex < fLastPosIndex) {
145 SkASSERT(charIndex >= fCharIndexOffset);
146 const auto localCharIndex = charIndex - fCharIndexOffset;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500147
Florin Malitadec78022020-12-17 16:36:54 -0500148 const auto hasAllLocal = localCharIndex < fX.size() &&
Florin Malita735ac972020-12-22 11:23:32 -0500149 localCharIndex < fY.size() &&
150 localCharIndex < fDx.size() &&
Florin Malita2d059fc2021-01-05 11:53:15 -0500151 localCharIndex < fDy.size() &&
152 localCharIndex < fRotate.size();
Florin Malitadec78022020-12-17 16:36:54 -0500153 if (!hasAllLocal && fParent) {
154 attrs = fParent->resolve(charIndex);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500155 }
156
Florin Malitadec78022020-12-17 16:36:54 -0500157 if (localCharIndex < fX.size()) {
158 attrs[PosAttrs::kX] = fX[localCharIndex];
159 }
160 if (localCharIndex < fY.size()) {
161 attrs[PosAttrs::kY] = fY[localCharIndex];
Florin Malita7dc984a2020-12-08 11:37:15 -0500162 }
Florin Malita735ac972020-12-22 11:23:32 -0500163 if (localCharIndex < fDx.size()) {
164 attrs[PosAttrs::kDx] = fDx[localCharIndex];
165 }
166 if (localCharIndex < fDy.size()) {
167 attrs[PosAttrs::kDy] = fDy[localCharIndex];
168 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500169
Florin Malita2d059fc2021-01-05 11:53:15 -0500170 // Rotation semantics are interestingly different [1]:
171 //
172 // - values are not cumulative
173 // - if explicit values are present at any level in the ancestor chain, those take
174 // precedence (closest ancestor)
175 // - last specified value applies to all remaining chars (closest ancestor)
176 // - these rules apply at node scope (not chunk scope)
177 //
178 // This means we need to discriminate between explicit rotation (rotate value provided for
179 // current char) and implicit rotation (ancestor has some values - but not for the requested
180 // char - we use the last specified value).
181 //
182 // [1] https://www.w3.org/TR/SVG11/text.html#TSpanElementRotateAttribute
183 if (!fRotate.empty()) {
184 if (localCharIndex < fRotate.size()) {
185 // Explicit rotation value overrides anything in the ancestor chain.
186 attrs[PosAttrs::kRotate] = fRotate[localCharIndex];
187 attrs.setImplicitRotate(false);
188 } else if (!attrs.has(PosAttrs::kRotate) || attrs.isImplicitRotate()){
189 // Local implicit rotation (last specified value) overrides ancestor implicit
190 // rotation.
191 attrs[PosAttrs::kRotate] = fRotate.back();
192 attrs.setImplicitRotate(true);
193 }
194 }
195
Florin Malitadec78022020-12-17 16:36:54 -0500196 if (!attrs.hasAny()) {
197 // Once we stop producing explicit position data, there is no reason to
198 // continue trying for higher indices. We can suppress future lookups.
199 fLastPosIndex = charIndex;
200 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500201 }
202
Florin Malitadec78022020-12-17 16:36:54 -0500203 return attrs;
204}
205
Florin Malita2d059fc2021-01-05 11:53:15 -0500206void SkSVGTextContext::ShapeBuffer::append(SkUnichar ch, PositionAdjustment pos) {
Florin Malita735ac972020-12-22 11:23:32 -0500207 // relative pos adjustments are cumulative
208 if (!fUtf8PosAdjust.empty()) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500209 pos.offset += fUtf8PosAdjust.back().offset;
Florin Malita735ac972020-12-22 11:23:32 -0500210 }
211
212 char utf8_buf[SkUTF::kMaxBytesInUTF8Sequence];
213 const auto utf8_len = SkToInt(SkUTF::ToUTF8(ch, utf8_buf));
214 fUtf8 .push_back_n(utf8_len, utf8_buf);
215 fUtf8PosAdjust.push_back_n(utf8_len, pos);
216}
217
218void SkSVGTextContext::shapePendingBuffer(const SkFont& font) {
219 // TODO: directionality hints?
220 const auto LTR = true;
221
222 // Initiate shaping: this will generate a series of runs via callbacks.
223 fShaper->shape(fShapeBuffer.fUtf8.data(), fShapeBuffer.fUtf8.size(),
224 font, LTR, SK_ScalarMax, this);
225 fShapeBuffer.reset();
226}
227
Florin Malitac55c8c12021-01-25 10:37:22 -0500228SkSVGTextContext::SkSVGTextContext(const SkSVGRenderContext& ctx, const ShapedTextCallback& cb,
229 const SkSVGTextPath* tpath)
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500230 : fRenderContext(ctx)
Florin Malitac55c8c12021-01-25 10:37:22 -0500231 , fCallback(cb)
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500232 , fShaper(SkShaper::Make(ctx.fontMgr()))
233 , fChunkAlignmentFactor(ComputeAlignmentFactor(ctx.presentationContext()))
234{
235 if (tpath) {
236 fPathData = std::make_unique<PathData>(ctx, *tpath);
237
238 // https://www.w3.org/TR/SVG11/text.html#TextPathElementStartOffsetAttribute
239 auto resolve_offset = [this](const SkSVGLength& offset) {
240 if (offset.unit() != SkSVGLength::Unit::kPercentage) {
241 // "If a <length> other than a percentage is given, then the ‘startOffset’
242 // represents a distance along the path measured in the current user coordinate
243 // system."
244 return fRenderContext.lengthContext()
245 .resolve(offset, SkSVGLengthContext::LengthType::kHorizontal);
246 }
247
248 // "If a percentage is given, then the ‘startOffset’ represents a percentage distance
249 // along the entire path."
250 return offset.value() * fPathData->length() / 100;
251 };
252
253 // startOffset acts as an initial absolute position
254 fChunkPos.fX = resolve_offset(tpath->getStartOffset());
255 }
256}
257
258SkSVGTextContext::~SkSVGTextContext() {
259 this->flushChunk(fRenderContext);
260}
Florin Malitadec78022020-12-17 16:36:54 -0500261
Florin Malitac55c8c12021-01-25 10:37:22 -0500262void SkSVGTextContext::shapeFragment(const SkString& txt, const SkSVGRenderContext& ctx,
263 SkSVGXmlSpace xs) {
Florin Malitadec78022020-12-17 16:36:54 -0500264 // https://www.w3.org/TR/SVG11/text.html#WhiteSpace
265 // https://www.w3.org/TR/2008/REC-xml-20081126/#NT-S
266 auto filterWSDefault = [this](SkUnichar ch) -> SkUnichar {
267 // Remove all newline chars.
268 if (ch == '\n') {
269 return -1;
270 }
271
272 // Convert tab chars to space.
273 if (ch == '\t') {
274 ch = ' ';
275 }
276
277 // Consolidate contiguous space chars and strip leading spaces (fPrevCharSpace
278 // starts off as true).
279 if (fPrevCharSpace && ch == ' ') {
280 return -1;
281 }
282
283 // TODO: Strip trailing WS? Doing this across chunks would require another buffering
284 // layer. In general, trailing WS should have no rendering side effects. Skipping
285 // for now.
286 return ch;
287 };
288 auto filterWSPreserve = [](SkUnichar ch) -> SkUnichar {
289 // Convert newline and tab chars to space.
290 if (ch == '\n' || ch == '\t') {
291 ch = ' ';
292 }
293 return ch;
Florin Malita7dc984a2020-12-08 11:37:15 -0500294 };
295
Florin Malitadec78022020-12-17 16:36:54 -0500296 // Stash paints for access from SkShaper callbacks.
297 fCurrentFill = ctx.fillPaint();
298 fCurrentStroke = ctx.strokePaint();
Florin Malita7dc984a2020-12-08 11:37:15 -0500299
Florin Malitadec78022020-12-17 16:36:54 -0500300 const auto font = ResolveFont(ctx);
Florin Malita735ac972020-12-22 11:23:32 -0500301 fShapeBuffer.reserve(txt.size());
Florin Malitadec78022020-12-17 16:36:54 -0500302
303 const char* ch_ptr = txt.c_str();
304 const char* ch_end = ch_ptr + txt.size();
305
306 while (ch_ptr < ch_end) {
307 auto ch = SkUTF::NextUTF8(&ch_ptr, ch_end);
308 ch = (xs == SkSVGXmlSpace::kDefault)
309 ? filterWSDefault(ch)
310 : filterWSPreserve(ch);
311
312 if (ch < 0) {
313 // invalid utf or char filtered out
314 continue;
315 }
316
317 SkASSERT(fPosResolver);
318 const auto pos = fPosResolver->resolve(fCurrentCharIndex++);
319
320 // Absolute position adjustments define a new chunk.
321 // (https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction)
322 if (pos.has(PosAttrs::kX) || pos.has(PosAttrs::kY)) {
Florin Malita735ac972020-12-22 11:23:32 -0500323 this->shapePendingBuffer(font);
Florin Malitadec78022020-12-17 16:36:54 -0500324 this->flushChunk(ctx);
325
326 // New chunk position.
327 if (pos.has(PosAttrs::kX)) {
328 fChunkPos.fX = pos[PosAttrs::kX];
329 }
330 if (pos.has(PosAttrs::kY)) {
331 fChunkPos.fY = pos[PosAttrs::kY];
332 }
333 }
334
Florin Malita735ac972020-12-22 11:23:32 -0500335 fShapeBuffer.append(ch, {
Florin Malita2d059fc2021-01-05 11:53:15 -0500336 {
337 pos.has(PosAttrs::kDx) ? pos[PosAttrs::kDx] : 0,
338 pos.has(PosAttrs::kDy) ? pos[PosAttrs::kDy] : 0,
339 },
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500340 pos.has(PosAttrs::kRotate) ? SkDegreesToRadians(pos[PosAttrs::kRotate]) : 0,
Florin Malita735ac972020-12-22 11:23:32 -0500341 });
Florin Malitadec78022020-12-17 16:36:54 -0500342
343 fPrevCharSpace = (ch == ' ');
Florin Malita7dc984a2020-12-08 11:37:15 -0500344 }
Florin Malitadec78022020-12-17 16:36:54 -0500345
Florin Malita735ac972020-12-22 11:23:32 -0500346 this->shapePendingBuffer(font);
347
348 // Note: at this point we have shaped and buffered RunRecs for the current fragment.
349 // The active text chunk continues until an explicit or implicit flush.
Florin Malitadec78022020-12-17 16:36:54 -0500350}
351
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500352SkSVGTextContext::PathData::PathData(const SkSVGRenderContext& ctx, const SkSVGTextPath& tpath)
353{
Tyler Dennistone71f5472021-01-27 13:30:59 -0500354 const auto ref = ctx.findNodeById(tpath.getHref());
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500355 if (!ref) {
356 return;
357 }
Florin Malitadec78022020-12-17 16:36:54 -0500358
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500359 SkContourMeasureIter cmi(ref->asPath(ctx), false);
360 while (sk_sp<SkContourMeasure> contour = cmi.next()) {
361 fLength += contour->length();
362 fContours.push_back(std::move(contour));
363 }
364}
365
366SkMatrix SkSVGTextContext::PathData::getMatrixAt(float offset) const {
367 if (offset >= 0) {
368 for (const auto& contour : fContours) {
369 const auto contour_len = contour->length();
370 if (offset < contour_len) {
371 SkMatrix m;
372 return contour->getMatrix(offset, &m) ? m : SkMatrix::I();
373 }
374 offset -= contour_len;
375 }
376 }
377
378 // Quick & dirty way to "skip" rendering of glyphs off path.
379 return SkMatrix::Translate(std::numeric_limits<float>::infinity(),
380 std::numeric_limits<float>::infinity());
381}
382
383SkRSXform SkSVGTextContext::computeGlyphXform(SkGlyphID glyph, const SkFont& font,
384 const SkPoint& glyph_pos,
385 const PositionAdjustment& pos_adjust) const {
386 SkPoint pos = fChunkPos + glyph_pos + pos_adjust.offset + fChunkAdvance * fChunkAlignmentFactor;
387 if (!fPathData) {
388 return SkRSXform::MakeFromRadians(/*scale=*/ 1, pos_adjust.rotation, pos.fX, pos.fY, 0, 0);
389 }
390
391 // We're in a textPath scope, reposition the glyph on path.
392 // (https://www.w3.org/TR/SVG11/text.html#TextpathLayoutRules)
393
394 // Path positioning is based on the glyph center (horizontal component).
395 float glyph_width;
396 font.getWidths(&glyph, 1, &glyph_width);
397 auto path_offset = pos.fX + glyph_width * .5f;
398
399 // In addition to the path matrix, the final glyph matrix also includes:
400 //
401 // -- vertical position adjustment "dy" ("dx" is factored into path_offset)
402 // -- glyph origin adjustment (undoing the glyph center offset above)
403 // -- explicit rotation adjustment (composing with the path glyph rotation)
404 const auto m = fPathData->getMatrixAt(path_offset) *
405 SkMatrix::Translate(-glyph_width * .5f, pos_adjust.offset.fY) *
406 SkMatrix::RotateRad(pos_adjust.rotation);
407
408 return SkRSXform::Make(m.getScaleX(), m.getSkewY(), m.getTranslateX(), m.getTranslateY());
409}
410
411void SkSVGTextContext::flushChunk(const SkSVGRenderContext& ctx) {
Florin Malitadec78022020-12-17 16:36:54 -0500412 SkTextBlobBuilder blobBuilder;
413
414 for (const auto& run : fRuns) {
Florin Malitae5a21712020-12-30 11:08:53 -0500415 const auto& buf = blobBuilder.allocRunRSXform(run.font, SkToInt(run.glyphCount));
416 std::copy(run.glyphs.get(), run.glyphs.get() + run.glyphCount, buf.glyphs);
417 for (size_t i = 0; i < run.glyphCount; ++i) {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500418 buf.xforms()[i] = this->computeGlyphXform(run.glyphs[i],
419 run.font,
420 run.glyphPos[i],
421 run.glyhPosAdjust[i]);
Florin Malitae5a21712020-12-30 11:08:53 -0500422 }
Florin Malitadec78022020-12-17 16:36:54 -0500423
Florin Malitac55c8c12021-01-25 10:37:22 -0500424 fCallback(ctx, blobBuilder.make(), run.fillPaint.get(), run.strokePaint.get());
Florin Malita7dc984a2020-12-08 11:37:15 -0500425 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500426
Florin Malitadec78022020-12-17 16:36:54 -0500427 fChunkPos += fChunkAdvance;
428 fChunkAdvance = {0,0};
429 fChunkAlignmentFactor = ComputeAlignmentFactor(ctx.presentationContext());
Florin Malita7dc984a2020-12-08 11:37:15 -0500430
Florin Malitadec78022020-12-17 16:36:54 -0500431 fRuns.clear();
432}
Florin Malita7dc984a2020-12-08 11:37:15 -0500433
Florin Malitadec78022020-12-17 16:36:54 -0500434SkShaper::RunHandler::Buffer SkSVGTextContext::runBuffer(const RunInfo& ri) {
435 SkASSERT(ri.glyphCount);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500436
Florin Malitadec78022020-12-17 16:36:54 -0500437 fRuns.push_back({
438 ri.fFont,
Florin Malitabde06cc2021-01-19 10:12:37 -0500439 fCurrentFill.isValid() ? std::make_unique<SkPaint>(*fCurrentFill) : nullptr,
440 fCurrentStroke.isValid() ? std::make_unique<SkPaint>(*fCurrentStroke) : nullptr,
Florin Malita736c9922021-01-05 10:51:33 -0500441 std::make_unique<SkGlyphID[] >(ri.glyphCount),
442 std::make_unique<SkPoint[] >(ri.glyphCount),
443 std::make_unique<PositionAdjustment[]>(ri.glyphCount),
Florin Malitadec78022020-12-17 16:36:54 -0500444 ri.glyphCount,
445 ri.fAdvance,
446 });
447
Florin Malita735ac972020-12-22 11:23:32 -0500448 // Ensure sufficient space to temporarily fetch cluster information.
449 fShapeClusterBuffer.resize(std::max(fShapeClusterBuffer.size(), ri.glyphCount));
450
Florin Malitadec78022020-12-17 16:36:54 -0500451 return {
452 fRuns.back().glyphs.get(),
453 fRuns.back().glyphPos.get(),
454 nullptr,
Florin Malita735ac972020-12-22 11:23:32 -0500455 fShapeClusterBuffer.data(),
Florin Malitadec78022020-12-17 16:36:54 -0500456 fChunkAdvance,
457 };
458}
459
460void SkSVGTextContext::commitRunBuffer(const RunInfo& ri) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500461 const auto& current_run = fRuns.back();
462
Florin Malita736c9922021-01-05 10:51:33 -0500463 // stash position adjustments
Florin Malita735ac972020-12-22 11:23:32 -0500464 for (size_t i = 0; i < ri.glyphCount; ++i) {
465 const auto utf8_index = fShapeClusterBuffer[i];
Florin Malita736c9922021-01-05 10:51:33 -0500466 current_run.glyhPosAdjust[i] = fShapeBuffer.fUtf8PosAdjust[SkToInt(utf8_index)];
Florin Malita735ac972020-12-22 11:23:32 -0500467 }
468
Florin Malita736c9922021-01-05 10:51:33 -0500469 // Offset adjustments are cumulative - we only need to advance the current chunk
Florin Malita735ac972020-12-22 11:23:32 -0500470 // with the last value.
Florin Malita2d059fc2021-01-05 11:53:15 -0500471 fChunkAdvance += ri.fAdvance + fShapeBuffer.fUtf8PosAdjust.back().offset;
Florin Malitadec78022020-12-17 16:36:54 -0500472}
Florin Malita512ff752020-12-06 11:50:52 -0500473
Florin Malitaadc68892020-12-15 10:52:26 -0500474void SkSVGTextFragment::renderText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
475 SkSVGXmlSpace xs) const {
Florin Malita48fb05b2021-04-30 14:22:33 -0400476 // N.B.: unlike regular elements, text fragments do not establish a new OBB scope -- they
477 // always defer to the root <text> element for OBB resolution.
478 SkSVGRenderContext localContext(ctx);
Florin Malitaadc68892020-12-15 10:52:26 -0500479
480 if (this->onPrepareToRender(&localContext)) {
Florin Malitac55c8c12021-01-25 10:37:22 -0500481 this->onShapeText(localContext, tctx, xs);
Florin Malitaadc68892020-12-15 10:52:26 -0500482 }
483}
484
485SkPath SkSVGTextFragment::onAsPath(const SkSVGRenderContext&) const {
486 // TODO
487 return SkPath();
488}
489
Florin Malita512ff752020-12-06 11:50:52 -0500490void SkSVGTextContainer::appendChild(sk_sp<SkSVGNode> child) {
Florin Malita302ea2e2021-01-24 12:04:17 -0500491 // Only allow text content child nodes.
Florin Malita512ff752020-12-06 11:50:52 -0500492 switch (child->tag()) {
Florin Malita512ff752020-12-06 11:50:52 -0500493 case SkSVGTag::kTextLiteral:
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500494 case SkSVGTag::kTextPath:
Florin Malita512ff752020-12-06 11:50:52 -0500495 case SkSVGTag::kTSpan:
Florin Malitaadc68892020-12-15 10:52:26 -0500496 fChildren.push_back(
497 sk_sp<SkSVGTextFragment>(static_cast<SkSVGTextFragment*>(child.release())));
Florin Malita512ff752020-12-06 11:50:52 -0500498 break;
499 default:
500 break;
501 }
502}
503
Florin Malitac55c8c12021-01-25 10:37:22 -0500504void SkSVGTextContainer::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
505 SkSVGXmlSpace) const {
Florin Malita302ea2e2021-01-24 12:04:17 -0500506 SkASSERT(tctx);
Florin Malita4ea46b72021-01-14 12:17:36 -0500507
Florin Malitadec78022020-12-17 16:36:54 -0500508 const SkSVGTextContext::ScopedPosResolver resolver(*this, ctx.lengthContext(), tctx);
509
Florin Malitaadc68892020-12-15 10:52:26 -0500510 for (const auto& frag : fChildren) {
511 // Containers always override xml:space with the local value.
512 frag->renderText(ctx, tctx, this->getXmlSpace());
513 }
Florin Malita9c1f1be2020-12-09 13:02:50 -0500514}
515
516// https://www.w3.org/TR/SVG11/text.html#WhiteSpace
517template <>
518bool SkSVGAttributeParser::parse(SkSVGXmlSpace* xs) {
519 static constexpr std::tuple<const char*, SkSVGXmlSpace> gXmlSpaceMap[] = {
520 {"default" , SkSVGXmlSpace::kDefault },
521 {"preserve", SkSVGXmlSpace::kPreserve},
522 };
523
524 return this->parseEnumMap(gXmlSpaceMap, xs) && this->parseEOSToken();
525}
526
Florin Malita512ff752020-12-06 11:50:52 -0500527bool SkSVGTextContainer::parseAndSetAttribute(const char* name, const char* value) {
528 return INHERITED::parseAndSetAttribute(name, value) ||
Florin Malitadec78022020-12-17 16:36:54 -0500529 this->setX(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("x", name, value)) ||
530 this->setY(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("y", name, value)) ||
Florin Malita735ac972020-12-22 11:23:32 -0500531 this->setDx(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dx", name, value)) ||
532 this->setDy(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dy", name, value)) ||
Florin Malita2d059fc2021-01-05 11:53:15 -0500533 this->setRotate(SkSVGAttributeParser::parse<std::vector<SkSVGNumberType>>("rotate",
534 name,
535 value)) ||
Florin Malita9c1f1be2020-12-09 13:02:50 -0500536 this->setXmlSpace(SkSVGAttributeParser::parse<SkSVGXmlSpace>("xml:space", name, value));
Florin Malita512ff752020-12-06 11:50:52 -0500537}
538
Florin Malitac55c8c12021-01-25 10:37:22 -0500539void SkSVGTextLiteral::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
540 SkSVGXmlSpace xs) const {
Florin Malitaadc68892020-12-15 10:52:26 -0500541 SkASSERT(tctx);
Florin Malita512ff752020-12-06 11:50:52 -0500542
Florin Malitac55c8c12021-01-25 10:37:22 -0500543 tctx->shapeFragment(this->getText(), ctx, xs);
Xavier Phane29cdaf2020-03-26 16:15:14 +0000544}
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500545
Florin Malita302ea2e2021-01-24 12:04:17 -0500546void SkSVGText::onRender(const SkSVGRenderContext& ctx) const {
Florin Malitac55c8c12021-01-25 10:37:22 -0500547 const SkSVGTextContext::ShapedTextCallback render_text = [](const SkSVGRenderContext& ctx,
548 const sk_sp<SkTextBlob>& blob,
549 const SkPaint* fill,
550 const SkPaint* stroke) {
551 if (fill) {
552 ctx.canvas()->drawTextBlob(blob, 0, 0, *fill);
553 }
554 if (stroke) {
555 ctx.canvas()->drawTextBlob(blob, 0, 0, *stroke);
556 }
557 };
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500558
Florin Malitac55c8c12021-01-25 10:37:22 -0500559 // Root <text> nodes establish a text layout context.
560 SkSVGTextContext tctx(ctx, render_text);
561
562 this->onShapeText(ctx, &tctx, this->getXmlSpace());
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500563}
564
Florin Malitaf9652242021-01-25 14:12:26 -0500565SkRect SkSVGText::onObjectBoundingBox(const SkSVGRenderContext& ctx) const {
566 SkRect bounds = SkRect::MakeEmpty();
567
568 const SkSVGTextContext::ShapedTextCallback compute_bounds =
569 [&bounds](const SkSVGRenderContext& ctx, const sk_sp<SkTextBlob>& blob, const SkPaint*,
570 const SkPaint*) {
571 if (!blob) {
572 return;
573 }
574
575 SkAutoSTArray<64, SkRect> glyphBounds;
576
577 SkTextBlobRunIterator it(blob.get());
578
579 for (SkTextBlobRunIterator it(blob.get()); !it.done(); it.next()) {
580 glyphBounds.reset(SkToInt(it.glyphCount()));
581 it.font().getBounds(it.glyphs(), it.glyphCount(), glyphBounds.get(), nullptr);
582
583 SkASSERT(it.positioning() == SkTextBlobRunIterator::kRSXform_Positioning);
584 SkMatrix m;
585 for (uint32_t i = 0; i < it.glyphCount(); ++i) {
586 m.setRSXform(it.xforms()[i]);
587 bounds.join(m.mapRect(glyphBounds[i]));
588 }
589 }
590 };
591
592 {
593 SkSVGTextContext tctx(ctx, compute_bounds);
594 this->onShapeText(ctx, &tctx, this->getXmlSpace());
595 }
596
597 return bounds;
598}
599
Florin Malitaf661ec72021-01-26 08:49:10 -0500600SkPath SkSVGText::onAsPath(const SkSVGRenderContext& ctx) const {
601 SkPathBuilder builder;
602
603 const SkSVGTextContext::ShapedTextCallback as_path =
604 [&builder](const SkSVGRenderContext& ctx, const sk_sp<SkTextBlob>& blob, const SkPaint*,
605 const SkPaint*) {
606 if (!blob) {
607 return;
608 }
609
610 SkTextBlobRunIterator it(blob.get());
611 for (SkTextBlobRunIterator it(blob.get()); !it.done(); it.next()) {
612 struct GetPathsCtx {
613 SkPathBuilder& builder;
614 const SkRSXform* xform;
615 } get_paths_ctx {builder, it.xforms()};
616
617 it.font().getPaths(it.glyphs(), it.glyphCount(), [](const SkPath* path,
618 const SkMatrix& matrix,
619 void* raw_ctx) {
620 auto* get_paths_ctx = static_cast<GetPathsCtx*>(raw_ctx);
621 const auto& glyph_rsx = *get_paths_ctx->xform++;
622
623 if (!path) {
624 return;
625 }
626
627 SkMatrix glyph_matrix;
628 glyph_matrix.setRSXform(glyph_rsx);
629 glyph_matrix.preConcat(matrix);
630
631 get_paths_ctx->builder.addPath(path->makeTransform(glyph_matrix));
632 }, &get_paths_ctx);
633 }
634 };
635
636 {
637 SkSVGTextContext tctx(ctx, as_path);
638 this->onShapeText(ctx, &tctx, this->getXmlSpace());
639 }
640
641 auto path = builder.detach();
642 this->mapToParent(&path);
643
644 return path;
645}
646
Florin Malitac55c8c12021-01-25 10:37:22 -0500647void SkSVGTextPath::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* parent_tctx,
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500648 SkSVGXmlSpace xs) const {
Florin Malitac55c8c12021-01-25 10:37:22 -0500649 SkASSERT(parent_tctx);
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500650
Florin Malitac55c8c12021-01-25 10:37:22 -0500651 // textPath nodes establish a new text layout context.
652 SkSVGTextContext tctx(ctx, parent_tctx->getCallback(), this);
653
654 this->INHERITED::onShapeText(ctx, &tctx, xs);
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500655}
656
657bool SkSVGTextPath::parseAndSetAttribute(const char* name, const char* value) {
658 return INHERITED::parseAndSetAttribute(name, value) ||
659 this->setHref(SkSVGAttributeParser::parse<SkSVGIRI>("xlink:href", name, value)) ||
660 this->setStartOffset(SkSVGAttributeParser::parse<SkSVGLength>("startOffset", name, value));
661}