blob: a5f16094f5708e5841a731476936202bbea42917 [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 Malitaf9652242021-01-25 14:12:26 -050023#include "src/core/SkTextBlobPriv.h"
Florin Malita9c1f1be2020-12-09 13:02:50 -050024#include "src/utils/SkUTF.h"
Xavier Phane29cdaf2020-03-26 16:15:14 +000025
Florin Malita512ff752020-12-06 11:50:52 -050026namespace {
Xavier Phane29cdaf2020-03-26 16:15:14 +000027
Florin Malita512ff752020-12-06 11:50:52 -050028static SkFont ResolveFont(const SkSVGRenderContext& ctx) {
Florin Malita39fe8c82020-10-20 10:43:03 -040029 auto weight = [](const SkSVGFontWeight& w) {
30 switch (w.type()) {
31 case SkSVGFontWeight::Type::k100: return SkFontStyle::kThin_Weight;
32 case SkSVGFontWeight::Type::k200: return SkFontStyle::kExtraLight_Weight;
33 case SkSVGFontWeight::Type::k300: return SkFontStyle::kLight_Weight;
34 case SkSVGFontWeight::Type::k400: return SkFontStyle::kNormal_Weight;
35 case SkSVGFontWeight::Type::k500: return SkFontStyle::kMedium_Weight;
36 case SkSVGFontWeight::Type::k600: return SkFontStyle::kSemiBold_Weight;
37 case SkSVGFontWeight::Type::k700: return SkFontStyle::kBold_Weight;
38 case SkSVGFontWeight::Type::k800: return SkFontStyle::kExtraBold_Weight;
39 case SkSVGFontWeight::Type::k900: return SkFontStyle::kBlack_Weight;
40 case SkSVGFontWeight::Type::kNormal: return SkFontStyle::kNormal_Weight;
41 case SkSVGFontWeight::Type::kBold: return SkFontStyle::kBold_Weight;
42 case SkSVGFontWeight::Type::kBolder: return SkFontStyle::kExtraBold_Weight;
43 case SkSVGFontWeight::Type::kLighter: return SkFontStyle::kLight_Weight;
44 case SkSVGFontWeight::Type::kInherit: {
45 SkASSERT(false);
46 return SkFontStyle::kNormal_Weight;
47 }
48 }
49 SkUNREACHABLE;
50 };
51
52 auto slant = [](const SkSVGFontStyle& s) {
53 switch (s.type()) {
54 case SkSVGFontStyle::Type::kNormal: return SkFontStyle::kUpright_Slant;
55 case SkSVGFontStyle::Type::kItalic: return SkFontStyle::kItalic_Slant;
56 case SkSVGFontStyle::Type::kOblique: return SkFontStyle::kOblique_Slant;
57 case SkSVGFontStyle::Type::kInherit: {
58 SkASSERT(false);
59 return SkFontStyle::kUpright_Slant;
60 }
61 }
62 SkUNREACHABLE;
63 };
64
65 const auto& family = ctx.presentationContext().fInherited.fFontFamily->family();
66 const SkFontStyle style(weight(*ctx.presentationContext().fInherited.fFontWeight),
67 SkFontStyle::kNormal_Width,
68 slant(*ctx.presentationContext().fInherited.fFontStyle));
69
70 const auto size =
71 ctx.lengthContext().resolve(ctx.presentationContext().fInherited.fFontSize->size(),
72 SkSVGLengthContext::LengthType::kVertical);
73
Florin Malita7006e152020-11-10 15:24:59 -050074 // TODO: we likely want matchFamilyStyle here, but switching away from legacyMakeTypeface
75 // changes all the results when using the default fontmgr.
76 auto tf = ctx.fontMgr()->legacyMakeTypeface(family.c_str(), style);
77
78 SkFont font(std::move(tf), size);
Florin Malita39fe8c82020-10-20 10:43:03 -040079 font.setHinting(SkFontHinting::kNone);
80 font.setSubpixel(true);
81 font.setLinearMetrics(true);
82 font.setBaselineSnap(false);
83 font.setEdging(SkFont::Edging::kAntiAlias);
84
85 return font;
86}
87
Florin Malitadec78022020-12-17 16:36:54 -050088static std::vector<float> ResolveLengths(const SkSVGLengthContext& lctx,
89 const std::vector<SkSVGLength>& lengths,
90 SkSVGLengthContext::LengthType lt) {
91 std::vector<float> resolved;
92 resolved.reserve(lengths.size());
93
94 for (const auto& l : lengths) {
95 resolved.push_back(lctx.resolve(l, lt));
96 }
97
98 return resolved;
99}
100
101static float ComputeAlignmentFactor(const SkSVGPresentationContext& pctx) {
102 switch (pctx.fInherited.fTextAnchor->type()) {
Florin Malita7dc984a2020-12-08 11:37:15 -0500103 case SkSVGTextAnchor::Type::kStart : return 0.0f;
104 case SkSVGTextAnchor::Type::kMiddle: return -0.5f;
105 case SkSVGTextAnchor::Type::kEnd : return -1.0f;
106 case SkSVGTextAnchor::Type::kInherit:
107 SkASSERT(false);
108 return 0.0f;
109 }
110 SkUNREACHABLE;
111}
112
Florin Malita512ff752020-12-06 11:50:52 -0500113} // namespace
114
Florin Malitadec78022020-12-17 16:36:54 -0500115SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
116 const SkSVGLengthContext& lctx,
117 SkSVGTextContext* tctx,
118 size_t charIndexOffset)
119 : fTextContext(tctx)
120 , fParent(tctx->fPosResolver)
121 , fCharIndexOffset(charIndexOffset)
122 , fX(ResolveLengths(lctx, txt.getX(), SkSVGLengthContext::LengthType::kHorizontal))
123 , fY(ResolveLengths(lctx, txt.getY(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita735ac972020-12-22 11:23:32 -0500124 , fDx(ResolveLengths(lctx, txt.getDx(), SkSVGLengthContext::LengthType::kHorizontal))
125 , fDy(ResolveLengths(lctx, txt.getDy(), SkSVGLengthContext::LengthType::kVertical))
Florin Malita2d059fc2021-01-05 11:53:15 -0500126 , fRotate(txt.getRotate())
Florin Malitadec78022020-12-17 16:36:54 -0500127{
128 fTextContext->fPosResolver = this;
129}
Florin Malita7dc984a2020-12-08 11:37:15 -0500130
Florin Malitadec78022020-12-17 16:36:54 -0500131SkSVGTextContext::ScopedPosResolver::ScopedPosResolver(const SkSVGTextContainer& txt,
132 const SkSVGLengthContext& lctx,
133 SkSVGTextContext* tctx)
134 : ScopedPosResolver(txt, lctx, tctx, tctx->fCurrentCharIndex) {}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500135
Florin Malitadec78022020-12-17 16:36:54 -0500136SkSVGTextContext::ScopedPosResolver::~ScopedPosResolver() {
137 fTextContext->fPosResolver = fParent;
138}
Florin Malita9c1f1be2020-12-09 13:02:50 -0500139
Florin Malitadec78022020-12-17 16:36:54 -0500140SkSVGTextContext::PosAttrs SkSVGTextContext::ScopedPosResolver::resolve(size_t charIndex) const {
141 PosAttrs attrs;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500142
Florin Malitadec78022020-12-17 16:36:54 -0500143 if (charIndex < fLastPosIndex) {
144 SkASSERT(charIndex >= fCharIndexOffset);
145 const auto localCharIndex = charIndex - fCharIndexOffset;
Florin Malita9c1f1be2020-12-09 13:02:50 -0500146
Florin Malitadec78022020-12-17 16:36:54 -0500147 const auto hasAllLocal = localCharIndex < fX.size() &&
Florin Malita735ac972020-12-22 11:23:32 -0500148 localCharIndex < fY.size() &&
149 localCharIndex < fDx.size() &&
Florin Malita2d059fc2021-01-05 11:53:15 -0500150 localCharIndex < fDy.size() &&
151 localCharIndex < fRotate.size();
Florin Malitadec78022020-12-17 16:36:54 -0500152 if (!hasAllLocal && fParent) {
153 attrs = fParent->resolve(charIndex);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500154 }
155
Florin Malitadec78022020-12-17 16:36:54 -0500156 if (localCharIndex < fX.size()) {
157 attrs[PosAttrs::kX] = fX[localCharIndex];
158 }
159 if (localCharIndex < fY.size()) {
160 attrs[PosAttrs::kY] = fY[localCharIndex];
Florin Malita7dc984a2020-12-08 11:37:15 -0500161 }
Florin Malita735ac972020-12-22 11:23:32 -0500162 if (localCharIndex < fDx.size()) {
163 attrs[PosAttrs::kDx] = fDx[localCharIndex];
164 }
165 if (localCharIndex < fDy.size()) {
166 attrs[PosAttrs::kDy] = fDy[localCharIndex];
167 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500168
Florin Malita2d059fc2021-01-05 11:53:15 -0500169 // Rotation semantics are interestingly different [1]:
170 //
171 // - values are not cumulative
172 // - if explicit values are present at any level in the ancestor chain, those take
173 // precedence (closest ancestor)
174 // - last specified value applies to all remaining chars (closest ancestor)
175 // - these rules apply at node scope (not chunk scope)
176 //
177 // This means we need to discriminate between explicit rotation (rotate value provided for
178 // current char) and implicit rotation (ancestor has some values - but not for the requested
179 // char - we use the last specified value).
180 //
181 // [1] https://www.w3.org/TR/SVG11/text.html#TSpanElementRotateAttribute
182 if (!fRotate.empty()) {
183 if (localCharIndex < fRotate.size()) {
184 // Explicit rotation value overrides anything in the ancestor chain.
185 attrs[PosAttrs::kRotate] = fRotate[localCharIndex];
186 attrs.setImplicitRotate(false);
187 } else if (!attrs.has(PosAttrs::kRotate) || attrs.isImplicitRotate()){
188 // Local implicit rotation (last specified value) overrides ancestor implicit
189 // rotation.
190 attrs[PosAttrs::kRotate] = fRotate.back();
191 attrs.setImplicitRotate(true);
192 }
193 }
194
Florin Malitadec78022020-12-17 16:36:54 -0500195 if (!attrs.hasAny()) {
196 // Once we stop producing explicit position data, there is no reason to
197 // continue trying for higher indices. We can suppress future lookups.
198 fLastPosIndex = charIndex;
199 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500200 }
201
Florin Malitadec78022020-12-17 16:36:54 -0500202 return attrs;
203}
204
Florin Malita2d059fc2021-01-05 11:53:15 -0500205void SkSVGTextContext::ShapeBuffer::append(SkUnichar ch, PositionAdjustment pos) {
Florin Malita735ac972020-12-22 11:23:32 -0500206 // relative pos adjustments are cumulative
207 if (!fUtf8PosAdjust.empty()) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500208 pos.offset += fUtf8PosAdjust.back().offset;
Florin Malita735ac972020-12-22 11:23:32 -0500209 }
210
211 char utf8_buf[SkUTF::kMaxBytesInUTF8Sequence];
212 const auto utf8_len = SkToInt(SkUTF::ToUTF8(ch, utf8_buf));
213 fUtf8 .push_back_n(utf8_len, utf8_buf);
214 fUtf8PosAdjust.push_back_n(utf8_len, pos);
215}
216
217void SkSVGTextContext::shapePendingBuffer(const SkFont& font) {
218 // TODO: directionality hints?
219 const auto LTR = true;
220
221 // Initiate shaping: this will generate a series of runs via callbacks.
222 fShaper->shape(fShapeBuffer.fUtf8.data(), fShapeBuffer.fUtf8.size(),
223 font, LTR, SK_ScalarMax, this);
224 fShapeBuffer.reset();
225}
226
Florin Malitac55c8c12021-01-25 10:37:22 -0500227SkSVGTextContext::SkSVGTextContext(const SkSVGRenderContext& ctx, const ShapedTextCallback& cb,
228 const SkSVGTextPath* tpath)
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500229 : fRenderContext(ctx)
Florin Malitac55c8c12021-01-25 10:37:22 -0500230 , fCallback(cb)
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500231 , fShaper(SkShaper::Make(ctx.fontMgr()))
232 , fChunkAlignmentFactor(ComputeAlignmentFactor(ctx.presentationContext()))
233{
234 if (tpath) {
235 fPathData = std::make_unique<PathData>(ctx, *tpath);
236
237 // https://www.w3.org/TR/SVG11/text.html#TextPathElementStartOffsetAttribute
238 auto resolve_offset = [this](const SkSVGLength& offset) {
239 if (offset.unit() != SkSVGLength::Unit::kPercentage) {
240 // "If a <length> other than a percentage is given, then the ‘startOffset’
241 // represents a distance along the path measured in the current user coordinate
242 // system."
243 return fRenderContext.lengthContext()
244 .resolve(offset, SkSVGLengthContext::LengthType::kHorizontal);
245 }
246
247 // "If a percentage is given, then the ‘startOffset’ represents a percentage distance
248 // along the entire path."
249 return offset.value() * fPathData->length() / 100;
250 };
251
252 // startOffset acts as an initial absolute position
253 fChunkPos.fX = resolve_offset(tpath->getStartOffset());
254 }
255}
256
257SkSVGTextContext::~SkSVGTextContext() {
258 this->flushChunk(fRenderContext);
259}
Florin Malitadec78022020-12-17 16:36:54 -0500260
Florin Malitac55c8c12021-01-25 10:37:22 -0500261void SkSVGTextContext::shapeFragment(const SkString& txt, const SkSVGRenderContext& ctx,
262 SkSVGXmlSpace xs) {
Florin Malitadec78022020-12-17 16:36:54 -0500263 // https://www.w3.org/TR/SVG11/text.html#WhiteSpace
264 // https://www.w3.org/TR/2008/REC-xml-20081126/#NT-S
265 auto filterWSDefault = [this](SkUnichar ch) -> SkUnichar {
266 // Remove all newline chars.
267 if (ch == '\n') {
268 return -1;
269 }
270
271 // Convert tab chars to space.
272 if (ch == '\t') {
273 ch = ' ';
274 }
275
276 // Consolidate contiguous space chars and strip leading spaces (fPrevCharSpace
277 // starts off as true).
278 if (fPrevCharSpace && ch == ' ') {
279 return -1;
280 }
281
282 // TODO: Strip trailing WS? Doing this across chunks would require another buffering
283 // layer. In general, trailing WS should have no rendering side effects. Skipping
284 // for now.
285 return ch;
286 };
287 auto filterWSPreserve = [](SkUnichar ch) -> SkUnichar {
288 // Convert newline and tab chars to space.
289 if (ch == '\n' || ch == '\t') {
290 ch = ' ';
291 }
292 return ch;
Florin Malita7dc984a2020-12-08 11:37:15 -0500293 };
294
Florin Malitadec78022020-12-17 16:36:54 -0500295 // Stash paints for access from SkShaper callbacks.
296 fCurrentFill = ctx.fillPaint();
297 fCurrentStroke = ctx.strokePaint();
Florin Malita7dc984a2020-12-08 11:37:15 -0500298
Florin Malitadec78022020-12-17 16:36:54 -0500299 const auto font = ResolveFont(ctx);
Florin Malita735ac972020-12-22 11:23:32 -0500300 fShapeBuffer.reserve(txt.size());
Florin Malitadec78022020-12-17 16:36:54 -0500301
302 const char* ch_ptr = txt.c_str();
303 const char* ch_end = ch_ptr + txt.size();
304
305 while (ch_ptr < ch_end) {
306 auto ch = SkUTF::NextUTF8(&ch_ptr, ch_end);
307 ch = (xs == SkSVGXmlSpace::kDefault)
308 ? filterWSDefault(ch)
309 : filterWSPreserve(ch);
310
311 if (ch < 0) {
312 // invalid utf or char filtered out
313 continue;
314 }
315
316 SkASSERT(fPosResolver);
317 const auto pos = fPosResolver->resolve(fCurrentCharIndex++);
318
319 // Absolute position adjustments define a new chunk.
320 // (https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction)
321 if (pos.has(PosAttrs::kX) || pos.has(PosAttrs::kY)) {
Florin Malita735ac972020-12-22 11:23:32 -0500322 this->shapePendingBuffer(font);
Florin Malitadec78022020-12-17 16:36:54 -0500323 this->flushChunk(ctx);
324
325 // New chunk position.
326 if (pos.has(PosAttrs::kX)) {
327 fChunkPos.fX = pos[PosAttrs::kX];
328 }
329 if (pos.has(PosAttrs::kY)) {
330 fChunkPos.fY = pos[PosAttrs::kY];
331 }
332 }
333
Florin Malita735ac972020-12-22 11:23:32 -0500334 fShapeBuffer.append(ch, {
Florin Malita2d059fc2021-01-05 11:53:15 -0500335 {
336 pos.has(PosAttrs::kDx) ? pos[PosAttrs::kDx] : 0,
337 pos.has(PosAttrs::kDy) ? pos[PosAttrs::kDy] : 0,
338 },
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500339 pos.has(PosAttrs::kRotate) ? SkDegreesToRadians(pos[PosAttrs::kRotate]) : 0,
Florin Malita735ac972020-12-22 11:23:32 -0500340 });
Florin Malitadec78022020-12-17 16:36:54 -0500341
342 fPrevCharSpace = (ch == ' ');
Florin Malita7dc984a2020-12-08 11:37:15 -0500343 }
Florin Malitadec78022020-12-17 16:36:54 -0500344
Florin Malita735ac972020-12-22 11:23:32 -0500345 this->shapePendingBuffer(font);
346
347 // Note: at this point we have shaped and buffered RunRecs for the current fragment.
348 // The active text chunk continues until an explicit or implicit flush.
Florin Malitadec78022020-12-17 16:36:54 -0500349}
350
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500351SkSVGTextContext::PathData::PathData(const SkSVGRenderContext& ctx, const SkSVGTextPath& tpath)
352{
353 const auto ref = ctx.findNodeById(tpath.getHref().fIRI);
354 if (!ref) {
355 return;
356 }
Florin Malitadec78022020-12-17 16:36:54 -0500357
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500358 SkContourMeasureIter cmi(ref->asPath(ctx), false);
359 while (sk_sp<SkContourMeasure> contour = cmi.next()) {
360 fLength += contour->length();
361 fContours.push_back(std::move(contour));
362 }
363}
364
365SkMatrix SkSVGTextContext::PathData::getMatrixAt(float offset) const {
366 if (offset >= 0) {
367 for (const auto& contour : fContours) {
368 const auto contour_len = contour->length();
369 if (offset < contour_len) {
370 SkMatrix m;
371 return contour->getMatrix(offset, &m) ? m : SkMatrix::I();
372 }
373 offset -= contour_len;
374 }
375 }
376
377 // Quick & dirty way to "skip" rendering of glyphs off path.
378 return SkMatrix::Translate(std::numeric_limits<float>::infinity(),
379 std::numeric_limits<float>::infinity());
380}
381
382SkRSXform SkSVGTextContext::computeGlyphXform(SkGlyphID glyph, const SkFont& font,
383 const SkPoint& glyph_pos,
384 const PositionAdjustment& pos_adjust) const {
385 SkPoint pos = fChunkPos + glyph_pos + pos_adjust.offset + fChunkAdvance * fChunkAlignmentFactor;
386 if (!fPathData) {
387 return SkRSXform::MakeFromRadians(/*scale=*/ 1, pos_adjust.rotation, pos.fX, pos.fY, 0, 0);
388 }
389
390 // We're in a textPath scope, reposition the glyph on path.
391 // (https://www.w3.org/TR/SVG11/text.html#TextpathLayoutRules)
392
393 // Path positioning is based on the glyph center (horizontal component).
394 float glyph_width;
395 font.getWidths(&glyph, 1, &glyph_width);
396 auto path_offset = pos.fX + glyph_width * .5f;
397
398 // In addition to the path matrix, the final glyph matrix also includes:
399 //
400 // -- vertical position adjustment "dy" ("dx" is factored into path_offset)
401 // -- glyph origin adjustment (undoing the glyph center offset above)
402 // -- explicit rotation adjustment (composing with the path glyph rotation)
403 const auto m = fPathData->getMatrixAt(path_offset) *
404 SkMatrix::Translate(-glyph_width * .5f, pos_adjust.offset.fY) *
405 SkMatrix::RotateRad(pos_adjust.rotation);
406
407 return SkRSXform::Make(m.getScaleX(), m.getSkewY(), m.getTranslateX(), m.getTranslateY());
408}
409
410void SkSVGTextContext::flushChunk(const SkSVGRenderContext& ctx) {
Florin Malitadec78022020-12-17 16:36:54 -0500411 SkTextBlobBuilder blobBuilder;
412
413 for (const auto& run : fRuns) {
Florin Malitae5a21712020-12-30 11:08:53 -0500414 const auto& buf = blobBuilder.allocRunRSXform(run.font, SkToInt(run.glyphCount));
415 std::copy(run.glyphs.get(), run.glyphs.get() + run.glyphCount, buf.glyphs);
416 for (size_t i = 0; i < run.glyphCount; ++i) {
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500417 buf.xforms()[i] = this->computeGlyphXform(run.glyphs[i],
418 run.font,
419 run.glyphPos[i],
420 run.glyhPosAdjust[i]);
Florin Malitae5a21712020-12-30 11:08:53 -0500421 }
Florin Malitadec78022020-12-17 16:36:54 -0500422
Florin Malitac55c8c12021-01-25 10:37:22 -0500423 fCallback(ctx, blobBuilder.make(), run.fillPaint.get(), run.strokePaint.get());
Florin Malita7dc984a2020-12-08 11:37:15 -0500424 }
Florin Malita7dc984a2020-12-08 11:37:15 -0500425
Florin Malitadec78022020-12-17 16:36:54 -0500426 fChunkPos += fChunkAdvance;
427 fChunkAdvance = {0,0};
428 fChunkAlignmentFactor = ComputeAlignmentFactor(ctx.presentationContext());
Florin Malita7dc984a2020-12-08 11:37:15 -0500429
Florin Malitadec78022020-12-17 16:36:54 -0500430 fRuns.clear();
431}
Florin Malita7dc984a2020-12-08 11:37:15 -0500432
Florin Malitadec78022020-12-17 16:36:54 -0500433SkShaper::RunHandler::Buffer SkSVGTextContext::runBuffer(const RunInfo& ri) {
434 SkASSERT(ri.glyphCount);
Florin Malita9c1f1be2020-12-09 13:02:50 -0500435
Florin Malitadec78022020-12-17 16:36:54 -0500436 fRuns.push_back({
437 ri.fFont,
Florin Malitabde06cc2021-01-19 10:12:37 -0500438 fCurrentFill.isValid() ? std::make_unique<SkPaint>(*fCurrentFill) : nullptr,
439 fCurrentStroke.isValid() ? std::make_unique<SkPaint>(*fCurrentStroke) : nullptr,
Florin Malita736c9922021-01-05 10:51:33 -0500440 std::make_unique<SkGlyphID[] >(ri.glyphCount),
441 std::make_unique<SkPoint[] >(ri.glyphCount),
442 std::make_unique<PositionAdjustment[]>(ri.glyphCount),
Florin Malitadec78022020-12-17 16:36:54 -0500443 ri.glyphCount,
444 ri.fAdvance,
445 });
446
Florin Malita735ac972020-12-22 11:23:32 -0500447 // Ensure sufficient space to temporarily fetch cluster information.
448 fShapeClusterBuffer.resize(std::max(fShapeClusterBuffer.size(), ri.glyphCount));
449
Florin Malitadec78022020-12-17 16:36:54 -0500450 return {
451 fRuns.back().glyphs.get(),
452 fRuns.back().glyphPos.get(),
453 nullptr,
Florin Malita735ac972020-12-22 11:23:32 -0500454 fShapeClusterBuffer.data(),
Florin Malitadec78022020-12-17 16:36:54 -0500455 fChunkAdvance,
456 };
457}
458
459void SkSVGTextContext::commitRunBuffer(const RunInfo& ri) {
Florin Malita2d059fc2021-01-05 11:53:15 -0500460 const auto& current_run = fRuns.back();
461
Florin Malita736c9922021-01-05 10:51:33 -0500462 // stash position adjustments
Florin Malita735ac972020-12-22 11:23:32 -0500463 for (size_t i = 0; i < ri.glyphCount; ++i) {
464 const auto utf8_index = fShapeClusterBuffer[i];
Florin Malita736c9922021-01-05 10:51:33 -0500465 current_run.glyhPosAdjust[i] = fShapeBuffer.fUtf8PosAdjust[SkToInt(utf8_index)];
Florin Malita735ac972020-12-22 11:23:32 -0500466 }
467
Florin Malita736c9922021-01-05 10:51:33 -0500468 // Offset adjustments are cumulative - we only need to advance the current chunk
Florin Malita735ac972020-12-22 11:23:32 -0500469 // with the last value.
Florin Malita2d059fc2021-01-05 11:53:15 -0500470 fChunkAdvance += ri.fAdvance + fShapeBuffer.fUtf8PosAdjust.back().offset;
Florin Malitadec78022020-12-17 16:36:54 -0500471}
Florin Malita512ff752020-12-06 11:50:52 -0500472
Florin Malitaadc68892020-12-15 10:52:26 -0500473void SkSVGTextFragment::renderText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
474 SkSVGXmlSpace xs) const {
475 SkSVGRenderContext localContext(ctx, this);
476
477 if (this->onPrepareToRender(&localContext)) {
Florin Malitac55c8c12021-01-25 10:37:22 -0500478 this->onShapeText(localContext, tctx, xs);
Florin Malitaadc68892020-12-15 10:52:26 -0500479 }
480}
481
482SkPath SkSVGTextFragment::onAsPath(const SkSVGRenderContext&) const {
483 // TODO
484 return SkPath();
485}
486
Florin Malita512ff752020-12-06 11:50:52 -0500487void SkSVGTextContainer::appendChild(sk_sp<SkSVGNode> child) {
Florin Malita302ea2e2021-01-24 12:04:17 -0500488 // Only allow text content child nodes.
Florin Malita512ff752020-12-06 11:50:52 -0500489 switch (child->tag()) {
Florin Malita512ff752020-12-06 11:50:52 -0500490 case SkSVGTag::kTextLiteral:
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500491 case SkSVGTag::kTextPath:
Florin Malita512ff752020-12-06 11:50:52 -0500492 case SkSVGTag::kTSpan:
Florin Malitaadc68892020-12-15 10:52:26 -0500493 fChildren.push_back(
494 sk_sp<SkSVGTextFragment>(static_cast<SkSVGTextFragment*>(child.release())));
Florin Malita512ff752020-12-06 11:50:52 -0500495 break;
496 default:
497 break;
498 }
499}
500
Florin Malitac55c8c12021-01-25 10:37:22 -0500501void SkSVGTextContainer::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
502 SkSVGXmlSpace) const {
Florin Malita302ea2e2021-01-24 12:04:17 -0500503 SkASSERT(tctx);
Florin Malita4ea46b72021-01-14 12:17:36 -0500504
Florin Malitadec78022020-12-17 16:36:54 -0500505 const SkSVGTextContext::ScopedPosResolver resolver(*this, ctx.lengthContext(), tctx);
506
Florin Malitaadc68892020-12-15 10:52:26 -0500507 for (const auto& frag : fChildren) {
508 // Containers always override xml:space with the local value.
509 frag->renderText(ctx, tctx, this->getXmlSpace());
510 }
Florin Malita9c1f1be2020-12-09 13:02:50 -0500511}
512
513// https://www.w3.org/TR/SVG11/text.html#WhiteSpace
514template <>
515bool SkSVGAttributeParser::parse(SkSVGXmlSpace* xs) {
516 static constexpr std::tuple<const char*, SkSVGXmlSpace> gXmlSpaceMap[] = {
517 {"default" , SkSVGXmlSpace::kDefault },
518 {"preserve", SkSVGXmlSpace::kPreserve},
519 };
520
521 return this->parseEnumMap(gXmlSpaceMap, xs) && this->parseEOSToken();
522}
523
Florin Malita512ff752020-12-06 11:50:52 -0500524bool SkSVGTextContainer::parseAndSetAttribute(const char* name, const char* value) {
525 return INHERITED::parseAndSetAttribute(name, value) ||
Florin Malitadec78022020-12-17 16:36:54 -0500526 this->setX(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("x", name, value)) ||
527 this->setY(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("y", name, value)) ||
Florin Malita735ac972020-12-22 11:23:32 -0500528 this->setDx(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dx", name, value)) ||
529 this->setDy(SkSVGAttributeParser::parse<std::vector<SkSVGLength>>("dy", name, value)) ||
Florin Malita2d059fc2021-01-05 11:53:15 -0500530 this->setRotate(SkSVGAttributeParser::parse<std::vector<SkSVGNumberType>>("rotate",
531 name,
532 value)) ||
Florin Malita9c1f1be2020-12-09 13:02:50 -0500533 this->setXmlSpace(SkSVGAttributeParser::parse<SkSVGXmlSpace>("xml:space", name, value));
Florin Malita512ff752020-12-06 11:50:52 -0500534}
535
Florin Malitac55c8c12021-01-25 10:37:22 -0500536void SkSVGTextLiteral::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* tctx,
537 SkSVGXmlSpace xs) const {
Florin Malitaadc68892020-12-15 10:52:26 -0500538 SkASSERT(tctx);
Florin Malita512ff752020-12-06 11:50:52 -0500539
Florin Malitac55c8c12021-01-25 10:37:22 -0500540 tctx->shapeFragment(this->getText(), ctx, xs);
Xavier Phane29cdaf2020-03-26 16:15:14 +0000541}
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500542
Florin Malita302ea2e2021-01-24 12:04:17 -0500543void SkSVGText::onRender(const SkSVGRenderContext& ctx) const {
Florin Malitac55c8c12021-01-25 10:37:22 -0500544 const SkSVGTextContext::ShapedTextCallback render_text = [](const SkSVGRenderContext& ctx,
545 const sk_sp<SkTextBlob>& blob,
546 const SkPaint* fill,
547 const SkPaint* stroke) {
548 if (fill) {
549 ctx.canvas()->drawTextBlob(blob, 0, 0, *fill);
550 }
551 if (stroke) {
552 ctx.canvas()->drawTextBlob(blob, 0, 0, *stroke);
553 }
554 };
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500555
Florin Malitac55c8c12021-01-25 10:37:22 -0500556 // Root <text> nodes establish a text layout context.
557 SkSVGTextContext tctx(ctx, render_text);
558
559 this->onShapeText(ctx, &tctx, this->getXmlSpace());
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500560}
561
Florin Malitaf9652242021-01-25 14:12:26 -0500562SkRect SkSVGText::onObjectBoundingBox(const SkSVGRenderContext& ctx) const {
563 SkRect bounds = SkRect::MakeEmpty();
564
565 const SkSVGTextContext::ShapedTextCallback compute_bounds =
566 [&bounds](const SkSVGRenderContext& ctx, const sk_sp<SkTextBlob>& blob, const SkPaint*,
567 const SkPaint*) {
568 if (!blob) {
569 return;
570 }
571
572 SkAutoSTArray<64, SkRect> glyphBounds;
573
574 SkTextBlobRunIterator it(blob.get());
575
576 for (SkTextBlobRunIterator it(blob.get()); !it.done(); it.next()) {
577 glyphBounds.reset(SkToInt(it.glyphCount()));
578 it.font().getBounds(it.glyphs(), it.glyphCount(), glyphBounds.get(), nullptr);
579
580 SkASSERT(it.positioning() == SkTextBlobRunIterator::kRSXform_Positioning);
581 SkMatrix m;
582 for (uint32_t i = 0; i < it.glyphCount(); ++i) {
583 m.setRSXform(it.xforms()[i]);
584 bounds.join(m.mapRect(glyphBounds[i]));
585 }
586 }
587 };
588
589 {
590 SkSVGTextContext tctx(ctx, compute_bounds);
591 this->onShapeText(ctx, &tctx, this->getXmlSpace());
592 }
593
594 return bounds;
595}
596
Florin Malitac55c8c12021-01-25 10:37:22 -0500597void SkSVGTextPath::onShapeText(const SkSVGRenderContext& ctx, SkSVGTextContext* parent_tctx,
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500598 SkSVGXmlSpace xs) const {
Florin Malitac55c8c12021-01-25 10:37:22 -0500599 SkASSERT(parent_tctx);
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500600
Florin Malitac55c8c12021-01-25 10:37:22 -0500601 // textPath nodes establish a new text layout context.
602 SkSVGTextContext tctx(ctx, parent_tctx->getCallback(), this);
603
604 this->INHERITED::onShapeText(ctx, &tctx, xs);
Florin Malitafc0ea0a2021-01-12 13:27:01 -0500605}
606
607bool SkSVGTextPath::parseAndSetAttribute(const char* name, const char* value) {
608 return INHERITED::parseAndSetAttribute(name, value) ||
609 this->setHref(SkSVGAttributeParser::parse<SkSVGIRI>("xlink:href", name, value)) ||
610 this->setStartOffset(SkSVGAttributeParser::parse<SkSVGLength>("startOffset", name, value));
611}