blob: 17ed02ca5d98b7d04165a9d25cc1026d202439c2 [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 Malitae5a21712020-12-30 11:08:53 -050017#include "include/core/SkRSXform.h"
Tyler Freemane9663db2020-04-14 14:37:13 -070018#include "include/core/SkString.h"
Florin Malita7dc984a2020-12-08 11:37:15 -050019#include "modules/skshaper/include/SkShaper.h"
Florin Malitab3418102020-10-15 18:10:29 -040020#include "modules/svg/include/SkSVGRenderContext.h"
21#include "modules/svg/include/SkSVGValue.h"
Florin Malitadec78022020-12-17 16:36:54 -050022#include "modules/svg/src/SkSVGTextPriv.h"
Florin Malita9c1f1be2020-12-09 13:02:50 -050023#include "src/utils/SkUTF.h"
Xavier Phane29cdaf2020-03-26 16:15:14 +000024
Florin Malita512ff752020-12-06 11:50:52 -050025namespace {
Xavier Phane29cdaf2020-03-26 16:15:14 +000026
Florin Malita512ff752020-12-06 11:50:52 -050027static SkFont ResolveFont(const SkSVGRenderContext& ctx) {
Florin Malita39fe8c82020-10-20 10:43:03 -040028 auto weight = [](const SkSVGFontWeight& w) {
29 switch (w.type()) {
30 case SkSVGFontWeight::Type::k100: return SkFontStyle::kThin_Weight;
31 case SkSVGFontWeight::Type::k200: return SkFontStyle::kExtraLight_Weight;
32 case SkSVGFontWeight::Type::k300: return SkFontStyle::kLight_Weight;
33 case SkSVGFontWeight::Type::k400: return SkFontStyle::kNormal_Weight;
34 case SkSVGFontWeight::Type::k500: return SkFontStyle::kMedium_Weight;
35 case SkSVGFontWeight::Type::k600: return SkFontStyle::kSemiBold_Weight;
36 case SkSVGFontWeight::Type::k700: return SkFontStyle::kBold_Weight;
37 case SkSVGFontWeight::Type::k800: return SkFontStyle::kExtraBold_Weight;
38 case SkSVGFontWeight::Type::k900: return SkFontStyle::kBlack_Weight;
39 case SkSVGFontWeight::Type::kNormal: return SkFontStyle::kNormal_Weight;
40 case SkSVGFontWeight::Type::kBold: return SkFontStyle::kBold_Weight;
41 case SkSVGFontWeight::Type::kBolder: return SkFontStyle::kExtraBold_Weight;
42 case SkSVGFontWeight::Type::kLighter: return SkFontStyle::kLight_Weight;
43 case SkSVGFontWeight::Type::kInherit: {
44 SkASSERT(false);
45 return SkFontStyle::kNormal_Weight;
46 }
47 }
48 SkUNREACHABLE;
49 };
50
51 auto slant = [](const SkSVGFontStyle& s) {
52 switch (s.type()) {
53 case SkSVGFontStyle::Type::kNormal: return SkFontStyle::kUpright_Slant;
54 case SkSVGFontStyle::Type::kItalic: return SkFontStyle::kItalic_Slant;
55 case SkSVGFontStyle::Type::kOblique: return SkFontStyle::kOblique_Slant;
56 case SkSVGFontStyle::Type::kInherit: {
57 SkASSERT(false);
58 return SkFontStyle::kUpright_Slant;
59 }
60 }
61 SkUNREACHABLE;
62 };
63
64 const auto& family = ctx.presentationContext().fInherited.fFontFamily->family();
65 const SkFontStyle style(weight(*ctx.presentationContext().fInherited.fFontWeight),
66 SkFontStyle::kNormal_Width,
67 slant(*ctx.presentationContext().fInherited.fFontStyle));
68
69 const auto size =
70 ctx.lengthContext().resolve(ctx.presentationContext().fInherited.fFontSize->size(),
71 SkSVGLengthContext::LengthType::kVertical);
72
Florin Malita7006e152020-11-10 15:24:59 -050073 // TODO: we likely want matchFamilyStyle here, but switching away from legacyMakeTypeface
74 // changes all the results when using the default fontmgr.
75 auto tf = ctx.fontMgr()->legacyMakeTypeface(family.c_str(), style);
76
77 SkFont font(std::move(tf), size);
Florin Malita39fe8c82020-10-20 10:43:03 -040078 font.setHinting(SkFontHinting::kNone);
79 font.setSubpixel(true);
80 font.setLinearMetrics(true);
81 font.setBaselineSnap(false);
82 font.setEdging(SkFont::Edging::kAntiAlias);
83
84 return font;
85}
86
Florin Malitadec78022020-12-17 16:36:54 -050087static std::vector<float> ResolveLengths(const SkSVGLengthContext& lctx,
88 const std::vector<SkSVGLength>& lengths,
89 SkSVGLengthContext::LengthType lt) {
90 std::vector<float> resolved;
91 resolved.reserve(lengths.size());
92
93 for (const auto& l : lengths) {
94 resolved.push_back(lctx.resolve(l, lt));
95 }
96
97 return resolved;
98}
99
100static float ComputeAlignmentFactor(const SkSVGPresentationContext& pctx) {
101 switch (pctx.fInherited.fTextAnchor->type()) {
Florin Malita7dc984a2020-12-08 11:37:15 -0500102 case SkSVGTextAnchor::Type::kStart : return 0.0f;
103 case SkSVGTextAnchor::Type::kMiddle: return -0.5f;
104 case SkSVGTextAnchor::Type::kEnd : return -1.0f;
105 case SkSVGTextAnchor::Type::kInherit:
106 SkASSERT(false);
107 return 0.0f;
108 }
109 SkUNREACHABLE;
110}
111
Florin Malita512ff752020-12-06 11:50:52 -0500112} // namespace
113
Florin Malitadec78022020-12-17 16:36:54 -0500114SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
115 const SkSVGLengthContext& lctx,
116 SkSVGTextContext* tctx,
117 size_t charIndexOffset)
118 : fTextContext(tctx)
119 , fParent(tctx->fPosResolver)
120 , fCharIndexOffset(charIndexOffset)
121 , fX(ResolveLengths(lctx, txt.getX(), SkSVGLengthContext::LengthType::kHorizontal))
122 , fY(ResolveLengths(lctx, txt.getY(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita735ac972020-12-22 11:23:32 -0500123 , fDx(ResolveLengths(lctx, txt.getDx(), SkSVGLengthContext::LengthType::kHorizontal))
124 , fDy(ResolveLengths(lctx, txt.getDy(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita2d059fc2021-01-05 11:53:15 -0500125 , fRotate(txt.getRotate())
Florin Malitadec78022020-12-17 16:36:54 -0500126{
127 fTextContext->fPosResolver = this;
128}
Florin Malita7dc984a2020-12-08 11:37:15 -0500129
Florin Malitadec78022020-12-17 16:36:54 -0500130SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
131 const SkSVGLengthContext& lctx,
132 SkSVGTextContext* tctx)
133 : ScopedPosResolver(txt, lctx, tctx, tctx->fCurrentCharIndex) {}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500134
Florin Malitadec78022020-12-17 16:36:54 -0500135SkSVGTextContext::ScopedPosResolver::~ScopedPosResolver() {
136 fTextContext->fPosResolver = fParent;
137}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500138
Florin Malitadec78022020-12-17 16:36:54 -0500139SkSVGTextContext::PosAttrs SkSVGTextContext::ScopedPosResolver::resolve(size_t charIndex) const {
140 PosAttrs attrs;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500141
Florin Malitadec78022020-12-17 16:36:54 -0500142 if (charIndex < fLastPosIndex) {
143 SkASSERT(charIndex >= fCharIndexOffset);
144 const auto localCharIndex = charIndex - fCharIndexOffset;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500145
Florin Malitadec78022020-12-17 16:36:54 -0500146 const auto hasAllLocal = localCharIndex < fX.size() &&
Florin Malita735ac972020-12-22 11:23:32 -0500147 localCharIndex < fY.size() &&
148 localCharIndex < fDx.size() &&
Florin Malita2d059fc2021-01-05 11:53:15 -0500149 localCharIndex < fDy.size() &&
150 localCharIndex < fRotate.size();
Florin Malitadec78022020-12-17 16:36:54 -0500151 if (!hasAllLocal && fParent) {
152 attrs = fParent->resolve(charIndex);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500153 }
154
Florin Malitadec78022020-12-17 16:36:54 -0500155 if (localCharIndex < fX.size()) {
156 attrs[PosAttrs::kX] = fX[localCharIndex];
157 }
158 if (localCharIndex < fY.size()) {
159 attrs[PosAttrs::kY] = fY[localCharIndex];
Florin Malita7dc984a2020-12-08 11:37:15 -0500160 }
Florin Malita735ac972020-12-22 11:23:32 -0500161 if (localCharIndex < fDx.size()) {
162 attrs[PosAttrs::kDx] = fDx[localCharIndex];
163 }
164 if (localCharIndex < fDy.size()) {
165 attrs[PosAttrs::kDy] = fDy[localCharIndex];
166 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500167
Florin Malita2d059fc2021-01-05 11:53:15 -0500168 // Rotation semantics are interestingly different [1]:
169 //
170 // - values are not cumulative
171 // - if explicit values are present at any level in the ancestor chain, those take
172 // precedence (closest ancestor)
173 // - last specified value applies to all remaining chars (closest ancestor)
174 // - these rules apply at node scope (not chunk scope)
175 //
176 // This means we need to discriminate between explicit rotation (rotate value provided for
177 // current char) and implicit rotation (ancestor has some values - but not for the requested
178 // char - we use the last specified value).
179 //
180 // [1] https://www.w3.org/TR/SVG11/text.html#TSpanElementRotateAttribute
181 if (!fRotate.empty()) {
182 if (localCharIndex < fRotate.size()) {
183 // Explicit rotation value overrides anything in the ancestor chain.
184 attrs[PosAttrs::kRotate] = fRotate[localCharIndex];
185 attrs.setImplicitRotate(false);
186 } else if (!attrs.has(PosAttrs::kRotate) || attrs.isImplicitRotate()){
187 // Local implicit rotation (last specified value) overrides ancestor implicit
188 // rotation.
189 attrs[PosAttrs::kRotate] = fRotate.back();
190 attrs.setImplicitRotate(true);
191 }
192 }
193
Florin Malitadec78022020-12-17 16:36:54 -0500194 if (!attrs.hasAny()) {
195 // Once we stop producing explicit position data, there is no reason to
196 // continue trying for higher indices. We can suppress future lookups.
197 fLastPosIndex = charIndex;
198 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500199 }
200
Florin Malitadec78022020-12-17 16:36:54 -0500201 return attrs;
202}
203
Florin Malita2d059fc2021-01-05 11:53:15 -0500204void SkSVGTextContext::ShapeBuffer::append(SkUnichar ch, PositionAdjustment pos) {
Florin Malita735ac972020-12-22 11:23:32 -0500205 // relative pos adjustments are cumulative
206 if (!fUtf8PosAdjust.empty()) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500207 pos.offset += fUtf8PosAdjust.back().offset;
Florin Malita735ac972020-12-22 11:23:32 -0500208 }
209
210 char utf8_buf[SkUTF::kMaxBytesInUTF8Sequence];
211 const auto utf8_len = SkToInt(SkUTF::ToUTF8(ch, utf8_buf));
212 fUtf8 .push_back_n(utf8_len, utf8_buf);
213 fUtf8PosAdjust.push_back_n(utf8_len, pos);
214}
215
216void SkSVGTextContext::shapePendingBuffer(const SkFont& font) {
217 // TODO: directionality hints?
218 const auto LTR = true;
219
220 // Initiate shaping: this will generate a series of runs via callbacks.
221 fShaper->shape(fShapeBuffer.fUtf8.data(), fShapeBuffer.fUtf8.size(),
222 font, LTR, SK_ScalarMax, this);
223 fShapeBuffer.reset();
224}
225
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500226SkSVGTextContext::SkSVGTextContext(const SkSVGRenderContext& ctx, const SkSVGTextPath* tpath)
227 : fRenderContext(ctx)
228 , fShaper(SkShaper::Make(ctx.fontMgr()))
229 , fChunkAlignmentFactor(ComputeAlignmentFactor(ctx.presentationContext()))
230{
231 if (tpath) {
232 fPathData = std::make_unique<PathData>(ctx, *tpath);
233
234 // https://www.w3.org/TR/SVG11/text.html#TextPathElementStartOffsetAttribute
235 auto resolve_offset = [this](const SkSVGLength& offset) {
236 if (offset.unit() != SkSVGLength::Unit::kPercentage) {
237 // "If a <length> other than a percentage is given, then the ‘startOffset’
238 // represents a distance along the path measured in the current user coordinate
239 // system."
240 return fRenderContext.lengthContext()
241 .resolve(offset, SkSVGLengthContext::LengthType::kHorizontal);
242 }
243
244 // "If a percentage is given, then the ‘startOffset’ represents a percentage distance
245 // along the entire path."
246 return offset.value() * fPathData->length() / 100;
247 };
248
249 // startOffset acts as an initial absolute position
250 fChunkPos.fX = resolve_offset(tpath->getStartOffset());
251 }
252}
253
254SkSVGTextContext::~SkSVGTextContext() {
255 this->flushChunk(fRenderContext);
256}
Florin Malitadec78022020-12-17 16:36:54 -0500257
258void SkSVGTextContext::appendFragment(const SkString& txt, const SkSVGRenderContext& ctx,
259 SkSVGXmlSpace xs) {
260 // https://www.w3.org/TR/SVG11/text.html#WhiteSpace
261 // https://www.w3.org/TR/2008/REC-xml-20081126/#NT-S
262 auto filterWSDefault = [this](SkUnichar ch) -> SkUnichar {
263 // Remove all newline chars.
264 if (ch == '\n') {
265 return -1;
266 }
267
268 // Convert tab chars to space.
269 if (ch == '\t') {
270 ch = ' ';
271 }
272
273 // Consolidate contiguous space chars and strip leading spaces (fPrevCharSpace
274 // starts off as true).
275 if (fPrevCharSpace && ch == ' ') {
276 return -1;
277 }
278
279 // TODO: Strip trailing WS? Doing this across chunks would require another buffering
280 // layer. In general, trailing WS should have no rendering side effects. Skipping
281 // for now.
282 return ch;
283 };
284 auto filterWSPreserve = [](SkUnichar ch) -> SkUnichar {
285 // Convert newline and tab chars to space.
286 if (ch == '\n' || ch == '\t') {
287 ch = ' ';
288 }
289 return ch;
Florin Malita7dc984a2020-12-08 11:37:15 -0500290 };
291
Florin Malitadec78022020-12-17 16:36:54 -0500292 // Stash paints for access from SkShaper callbacks.
293 fCurrentFill = ctx.fillPaint();
294 fCurrentStroke = ctx.strokePaint();
Florin Malita7dc984a2020-12-08 11:37:15 -0500295
Florin Malitadec78022020-12-17 16:36:54 -0500296 const auto font = ResolveFont(ctx);
Florin Malita735ac972020-12-22 11:23:32 -0500297 fShapeBuffer.reserve(txt.size());
Florin Malitadec78022020-12-17 16:36:54 -0500298
299 const char* ch_ptr = txt.c_str();
300 const char* ch_end = ch_ptr + txt.size();
301
302 while (ch_ptr < ch_end) {
303 auto ch = SkUTF::NextUTF8(&ch_ptr, ch_end);
304 ch = (xs == SkSVGXmlSpace::kDefault)
305 ? filterWSDefault(ch)
306 : filterWSPreserve(ch);
307
308 if (ch < 0) {
309 // invalid utf or char filtered out
310 continue;
311 }
312
313 SkASSERT(fPosResolver);
314 const auto pos = fPosResolver->resolve(fCurrentCharIndex++);
315
316 // Absolute position adjustments define a new chunk.
317 // (https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction)
318 if (pos.has(PosAttrs::kX) || pos.has(PosAttrs::kY)) {
Florin Malita735ac972020-12-22 11:23:32 -0500319 this->shapePendingBuffer(font);
Florin Malitadec78022020-12-17 16:36:54 -0500320 this->flushChunk(ctx);
321
322 // New chunk position.
323 if (pos.has(PosAttrs::kX)) {
324 fChunkPos.fX = pos[PosAttrs::kX];
325 }
326 if (pos.has(PosAttrs::kY)) {
327 fChunkPos.fY = pos[PosAttrs::kY];
328 }
329 }
330
Florin Malita735ac972020-12-22 11:23:32 -0500331 fShapeBuffer.append(ch, {
Florin Malita2d059fc2021-01-05 11:53:15 -0500332 {
333 pos.has(PosAttrs::kDx) ? pos[PosAttrs::kDx] : 0,
334 pos.has(PosAttrs::kDy) ? pos[PosAttrs::kDy] : 0,
335 },
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500336 pos.has(PosAttrs::kRotate) ? SkDegreesToRadians(pos[PosAttrs::kRotate]) : 0,
Florin Malita735ac972020-12-22 11:23:32 -0500337 });
Florin Malitadec78022020-12-17 16:36:54 -0500338
339 fPrevCharSpace = (ch == ' ');
Florin Malita7dc984a2020-12-08 11:37:15 -0500340 }
Florin Malitadec78022020-12-17 16:36:54 -0500341
Florin Malita735ac972020-12-22 11:23:32 -0500342 this->shapePendingBuffer(font);
343
344 // Note: at this point we have shaped and buffered RunRecs for the current fragment.
345 // The active text chunk continues until an explicit or implicit flush.
Florin Malitadec78022020-12-17 16:36:54 -0500346}
347
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500348SkSVGTextContext::PathData::PathData(const SkSVGRenderContext& ctx, const SkSVGTextPath& tpath)
349{
350 const auto ref = ctx.findNodeById(tpath.getHref().fIRI);
351 if (!ref) {
352 return;
353 }
Florin Malitadec78022020-12-17 16:36:54 -0500354
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500355 SkContourMeasureIter cmi(ref->asPath(ctx), false);
356 while (sk_sp<SkContourMeasure> contour = cmi.next()) {
357 fLength += contour->length();
358 fContours.push_back(std::move(contour));
359 }
360}
361
362SkMatrix SkSVGTextContext::PathData::getMatrixAt(float offset) const {
363 if (offset >= 0) {
364 for (const auto& contour : fContours) {
365 const auto contour_len = contour->length();
366 if (offset < contour_len) {
367 SkMatrix m;
368 return contour->getMatrix(offset, &m) ? m : SkMatrix::I();
369 }
370 offset -= contour_len;
371 }
372 }
373
374 // Quick & dirty way to "skip" rendering of glyphs off path.
375 return SkMatrix::Translate(std::numeric_limits<float>::infinity(),
376 std::numeric_limits<float>::infinity());
377}
378
379SkRSXform SkSVGTextContext::computeGlyphXform(SkGlyphID glyph, const SkFont& font,
380 const SkPoint& glyph_pos,
381 const PositionAdjustment& pos_adjust) const {
382 SkPoint pos = fChunkPos + glyph_pos + pos_adjust.offset + fChunkAdvance * fChunkAlignmentFactor;
383 if (!fPathData) {
384 return SkRSXform::MakeFromRadians(/*scale=*/ 1, pos_adjust.rotation, pos.fX, pos.fY, 0, 0);
385 }
386
387 // We're in a textPath scope, reposition the glyph on path.
388 // (https://www.w3.org/TR/SVG11/text.html#TextpathLayoutRules)
389
390 // Path positioning is based on the glyph center (horizontal component).
391 float glyph_width;
392 font.getWidths(&glyph, 1, &glyph_width);
393 auto path_offset = pos.fX + glyph_width * .5f;
394
395 // In addition to the path matrix, the final glyph matrix also includes:
396 //
397 // -- vertical position adjustment "dy" ("dx" is factored into path_offset)
398 // -- glyph origin adjustment (undoing the glyph center offset above)
399 // -- explicit rotation adjustment (composing with the path glyph rotation)
400 const auto m = fPathData->getMatrixAt(path_offset) *
401 SkMatrix::Translate(-glyph_width * .5f, pos_adjust.offset.fY) *
402 SkMatrix::RotateRad(pos_adjust.rotation);
403
404 return SkRSXform::Make(m.getScaleX(), m.getSkewY(), m.getTranslateX(), m.getTranslateY());
405}
406
407void SkSVGTextContext::flushChunk(const SkSVGRenderContext& ctx) {
Florin Malitadec78022020-12-17 16:36:54 -0500408 SkTextBlobBuilder blobBuilder;
409
410 for (const auto& run : fRuns) {
Florin Malitae5a21712020-12-30 11:08:53 -0500411 const auto& buf = blobBuilder.allocRunRSXform(run.font, SkToInt(run.glyphCount));
412 std::copy(run.glyphs.get(), run.glyphs.get() + run.glyphCount, buf.glyphs);
413 for (size_t i = 0; i < run.glyphCount; ++i) {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500414 buf.xforms()[i] = this->computeGlyphXform(run.glyphs[i],
415 run.font,
416 run.glyphPos[i],
417 run.glyhPosAdjust[i]);
Florin Malitae5a21712020-12-30 11:08:53 -0500418 }
Florin Malitadec78022020-12-17 16:36:54 -0500419
420 // Technically, blobs with compatible paints could be merged --
421 // but likely not worth the effort.
422 const auto blob = blobBuilder.make();
423 if (run.fillPaint) {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500424 ctx.canvas()->drawTextBlob(blob, 0, 0, *run.fillPaint);
Florin Malitadec78022020-12-17 16:36:54 -0500425 }
426 if (run.strokePaint) {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500427 ctx.canvas()->drawTextBlob(blob, 0, 0, *run.strokePaint);
Florin Malitadec78022020-12-17 16:36:54 -0500428 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500429 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500430
Florin Malitadec78022020-12-17 16:36:54 -0500431 fChunkPos += fChunkAdvance;
432 fChunkAdvance = {0,0};
433 fChunkAlignmentFactor = ComputeAlignmentFactor(ctx.presentationContext());
Florin Malita7dc984a2020-12-08 11:37:15 -0500434
Florin Malitadec78022020-12-17 16:36:54 -0500435 fRuns.clear();
436}
Florin Malita7dc984a2020-12-08 11:37:15 -0500437
Florin Malitadec78022020-12-17 16:36:54 -0500438SkShaper::RunHandler::Buffer SkSVGTextContext::runBuffer(const RunInfo& ri) {
439 SkASSERT(ri.glyphCount);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500440
Florin Malitadec78022020-12-17 16:36:54 -0500441 fRuns.push_back({
442 ri.fFont,
Florin Malitabde06cc2021-01-19 10:12:37 -0500443 fCurrentFill.isValid() ? std::make_unique<SkPaint>(*fCurrentFill) : nullptr,
444 fCurrentStroke.isValid() ? std::make_unique<SkPaint>(*fCurrentStroke) : nullptr,
Florin Malita736c9922021-01-05 10:51:33 -0500445 std::make_unique<SkGlyphID[] >(ri.glyphCount),
446 std::make_unique<SkPoint[] >(ri.glyphCount),
447 std::make_unique<PositionAdjustment[]>(ri.glyphCount),
Florin Malitadec78022020-12-17 16:36:54 -0500448 ri.glyphCount,
449 ri.fAdvance,
450 });
451
Florin Malita735ac972020-12-22 11:23:32 -0500452 // Ensure sufficient space to temporarily fetch cluster information.
453 fShapeClusterBuffer.resize(std::max(fShapeClusterBuffer.size(), ri.glyphCount));
454
Florin Malitadec78022020-12-17 16:36:54 -0500455 return {
456 fRuns.back().glyphs.get(),
457 fRuns.back().glyphPos.get(),
458 nullptr,
Florin Malita735ac972020-12-22 11:23:32 -0500459 fShapeClusterBuffer.data(),
Florin Malitadec78022020-12-17 16:36:54 -0500460 fChunkAdvance,
461 };
462}
463
464void SkSVGTextContext::commitRunBuffer(const RunInfo& ri) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500465 const auto& current_run = fRuns.back();
466
Florin Malita736c9922021-01-05 10:51:33 -0500467 // stash position adjustments
Florin Malita735ac972020-12-22 11:23:32 -0500468 for (size_t i = 0; i < ri.glyphCount; ++i) {
469 const auto utf8_index = fShapeClusterBuffer[i];
Florin Malita736c9922021-01-05 10:51:33 -0500470 current_run.glyhPosAdjust[i] = fShapeBuffer.fUtf8PosAdjust[SkToInt(utf8_index)];
Florin Malita735ac972020-12-22 11:23:32 -0500471 }
472
Florin Malita736c9922021-01-05 10:51:33 -0500473 // Offset adjustments are cumulative - we only need to advance the current chunk
Florin Malita735ac972020-12-22 11:23:32 -0500474 // with the last value.
Florin Malita2d059fc2021-01-05 11:53:15 -0500475 fChunkAdvance += ri.fAdvance + fShapeBuffer.fUtf8PosAdjust.back().offset;
Florin Malitadec78022020-12-17 16:36:54 -0500476}
Florin Malita512ff752020-12-06 11:50:52 -0500477
Florin Malitaadc68892020-12-15 10:52:26 -0500478void SkSVGTextFragment::renderText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
479 SkSVGXmlSpace xs) const {
480 SkSVGRenderContext localContext(ctx, this);
481
482 if (this->onPrepareToRender(&localContext)) {
483 this->onRenderText(localContext, tctx, xs);
484 }
485}
486
487SkPath SkSVGTextFragment::onAsPath(const SkSVGRenderContext&) const {
488 // TODO
489 return SkPath();
490}
491
Florin Malita512ff752020-12-06 11:50:52 -0500492void SkSVGTextContainer::appendChild(sk_sp<SkSVGNode> child) {
493 // Only allow text nodes.
494 switch (child->tag()) {
495 case SkSVGTag::kText:
496 case SkSVGTag::kTextLiteral:
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500497 case SkSVGTag::kTextPath:
Florin Malita512ff752020-12-06 11:50:52 -0500498 case SkSVGTag::kTSpan:
Florin Malitaadc68892020-12-15 10:52:26 -0500499 fChildren.push_back(
500 sk_sp<SkSVGTextFragment>(static_cast<SkSVGTextFragment*>(child.release())));
Florin Malita512ff752020-12-06 11:50:52 -0500501 break;
502 default:
503 break;
504 }
505}
506
Florin Malitaadc68892020-12-15 10:52:26 -0500507void SkSVGTextContainer::onRenderText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
508 SkSVGXmlSpace) const {
Florin Malita4ea46b72021-01-14 12:17:36 -0500509 if (!tctx) {
510 // No text context => missing top-level <text> node.
511 return;
512 }
513
Florin Malitadec78022020-12-17 16:36:54 -0500514 const SkSVGTextContext::ScopedPosResolver resolver(*this, ctx.lengthContext(), tctx);
515
Florin Malitaadc68892020-12-15 10:52:26 -0500516 for (const auto& frag : fChildren) {
517 // Containers always override xml:space with the local value.
518 frag->renderText(ctx, tctx, this->getXmlSpace());
519 }
Florin Malita9c1f1be2020-12-09 13:02:50 -0500520}
521
522// https://www.w3.org/TR/SVG11/text.html#WhiteSpace
523template <>
524bool SkSVGAttributeParser::parse(SkSVGXmlSpace* xs) {
525 static constexpr std::tuple<const char*, SkSVGXmlSpace> gXmlSpaceMap[] = {
526 {"default" , SkSVGXmlSpace::kDefault },
527 {"preserve", SkSVGXmlSpace::kPreserve},
528 };
529
530 return this->parseEnumMap(gXmlSpaceMap, xs) && this->parseEOSToken();
531}
532
Florin Malita512ff752020-12-06 11:50:52 -0500533bool SkSVGTextContainer::parseAndSetAttribute(const char* name, const char* value) {
534 return INHERITED::parseAndSetAttribute(name, value) ||
Florin Malitadec78022020-12-17 16:36:54 -0500535 this->setX(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("x", name, value)) ||
536 this->setY(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("y", name, value)) ||
Florin Malita735ac972020-12-22 11:23:32 -0500537 this->setDx(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dx", name, value)) ||
538 this->setDy(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dy", name, value)) ||
Florin Malita2d059fc2021-01-05 11:53:15 -0500539 this->setRotate(SkSVGAttributeParser::parse<std::vector<SkSVGNumberType>>("rotate",
540 name,
541 value)) ||
Florin Malita9c1f1be2020-12-09 13:02:50 -0500542 this->setXmlSpace(SkSVGAttributeParser::parse<SkSVGXmlSpace>("xml:space", name, value));
Florin Malita512ff752020-12-06 11:50:52 -0500543}
544
Florin Malitaadc68892020-12-15 10:52:26 -0500545void SkSVGTextContainer::onRender(const SkSVGRenderContext& ctx) const {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500546 this->onRenderText(ctx, nullptr, this->getXmlSpace());
Florin Malita512ff752020-12-06 11:50:52 -0500547}
548
Florin Malitaadc68892020-12-15 10:52:26 -0500549void SkSVGTextLiteral::onRenderText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
550 SkSVGXmlSpace xs) const {
551 SkASSERT(tctx);
Florin Malita512ff752020-12-06 11:50:52 -0500552
Florin Malitaadc68892020-12-15 10:52:26 -0500553 tctx->appendFragment(this->getText(), ctx, xs);
Xavier Phane29cdaf2020-03-26 16:15:14 +0000554}
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500555
556void SkSVGText::onRenderText(const SkSVGRenderContext& ctx, SkSVGTextContext*,
557 SkSVGXmlSpace xs) const {
558 // Root text nodes establish a new text layout context.
559 SkSVGTextContext tctx(ctx);
560
561 this->INHERITED::onRenderText(ctx, &tctx, xs);
562}
563
564void SkSVGTextPath::onRenderText(const SkSVGRenderContext& ctx, SkSVGTextContext*,
565 SkSVGXmlSpace xs) const {
566 // Root text nodes establish a new text layout context.
567 SkSVGTextContext tctx(ctx, this);
568
569 this->INHERITED::onRenderText(ctx, &tctx, xs);
570}
571
572bool SkSVGTextPath::parseAndSetAttribute(const char* name, const char* value) {
573 return INHERITED::parseAndSetAttribute(name, value) ||
574 this->setHref(SkSVGAttributeParser::parse<SkSVGIRI>("xlink:href", name, value)) ||
575 this->setStartOffset(SkSVGAttributeParser::parse<SkSVGLength>("startOffset", name, value));
576}