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 "include/core/SkRSXform.h"
9#include "include/core/SkTextBlob.h"
10#include "include/core/SkTypeface.h"
11#include "src/core/SkFontPriv.h"
12#include "src/core/SkGlyphRun.h"
13#include "src/core/SkPaintPriv.h"
14#include "src/core/SkReadBuffer.h"
15#include "src/core/SkSafeMath.h"
16#include "src/core/SkStrikeCache.h"
17#include "src/core/SkStrikeSpec.h"
18#include "src/core/SkTextBlobPriv.h"
19#include "src/core/SkWriteBuffer.h"
20
21#include <atomic>
22#include <limits>
23#include <new>
24
25#if SK_SUPPORT_GPU
26#include "src/gpu/text/GrTextBlobCache.h"
27#endif
28
29namespace {
30struct RunFontStorageEquivalent {
31 SkScalar fSize, fScaleX;
32 void* fTypeface;
33 SkScalar fSkewX;
34 uint32_t fFlags;
35};
36static_assert(sizeof(SkFont) == sizeof(RunFontStorageEquivalent), "runfont_should_stay_packed");
37}
38
39size_t SkTextBlob::RunRecord::StorageSize(uint32_t glyphCount, uint32_t textSize,
40 SkTextBlob::GlyphPositioning positioning,
41 SkSafeMath* safe) {
42 static_assert(SkIsAlign4(sizeof(SkScalar)), "SkScalar size alignment");
43
44 auto glyphSize = safe->mul(glyphCount, sizeof(uint16_t)),
45 posSize = safe->mul(PosCount(glyphCount, positioning, safe), sizeof(SkScalar));
46
47 // RunRecord object + (aligned) glyph buffer + position buffer
48 auto size = sizeof(SkTextBlob::RunRecord);
49 size = safe->add(size, safe->alignUp(glyphSize, 4));
50 size = safe->add(size, posSize);
51
52 if (textSize) { // Extended run.
53 size = safe->add(size, sizeof(uint32_t));
54 size = safe->add(size, safe->mul(glyphCount, sizeof(uint32_t)));
55 size = safe->add(size, textSize);
56 }
57
58 return safe->alignUp(size, sizeof(void*));
59}
60
61const SkTextBlob::RunRecord* SkTextBlob::RunRecord::First(const SkTextBlob* blob) {
62 // The first record (if present) is stored following the blob object.
63 // (aligned up to make the RunRecord aligned too)
64 return reinterpret_cast<const RunRecord*>(SkAlignPtr((uintptr_t)(blob + 1)));
65}
66
67const SkTextBlob::RunRecord* SkTextBlob::RunRecord::Next(const RunRecord* run) {
68 return SkToBool(run->fFlags & kLast_Flag) ? nullptr : NextUnchecked(run);
69}
70
71namespace {
72struct RunRecordStorageEquivalent {
73 SkFont fFont;
74 SkPoint fOffset;
75 uint32_t fCount;
76 uint32_t fFlags;
77 SkDEBUGCODE(unsigned fMagic;)
78};
79}
80
81void SkTextBlob::RunRecord::validate(const uint8_t* storageTop) const {
82 SkASSERT(kRunRecordMagic == fMagic);
83 SkASSERT((uint8_t*)NextUnchecked(this) <= storageTop);
84
85 SkASSERT(glyphBuffer() + fCount <= (uint16_t*)posBuffer());
86 SkASSERT(posBuffer() + fCount * ScalarsPerGlyph(positioning())
87 <= (SkScalar*)NextUnchecked(this));
88 if (isExtended()) {
89 SkASSERT(textSize() > 0);
90 SkASSERT(textSizePtr() < (uint32_t*)NextUnchecked(this));
91 SkASSERT(clusterBuffer() < (uint32_t*)NextUnchecked(this));
92 SkASSERT(textBuffer() + textSize() <= (char*)NextUnchecked(this));
93 }
94 static_assert(sizeof(SkTextBlob::RunRecord) == sizeof(RunRecordStorageEquivalent),
95 "runrecord_should_stay_packed");
96}
97
98const SkTextBlob::RunRecord* SkTextBlob::RunRecord::NextUnchecked(const RunRecord* run) {
99 SkSafeMath safe;
100 auto res = reinterpret_cast<const RunRecord*>(
101 reinterpret_cast<const uint8_t*>(run)
102 + StorageSize(run->glyphCount(), run->textSize(), run->positioning(), &safe));
103 SkASSERT(safe);
104 return res;
105}
106
107size_t SkTextBlob::RunRecord::PosCount(uint32_t glyphCount,
108 SkTextBlob::GlyphPositioning positioning,
109 SkSafeMath* safe) {
110 return safe->mul(glyphCount, ScalarsPerGlyph(positioning));
111}
112
113uint32_t* SkTextBlob::RunRecord::textSizePtr() const {
114 // textSize follows the position buffer.
115 SkASSERT(isExtended());
116 SkSafeMath safe;
117 auto res = (uint32_t*)(&this->posBuffer()[PosCount(fCount, positioning(), &safe)]);
118 SkASSERT(safe);
119 return res;
120}
121
122void SkTextBlob::RunRecord::grow(uint32_t count) {
123 SkScalar* initialPosBuffer = posBuffer();
124 uint32_t initialCount = fCount;
125 fCount += count;
126
127 // Move the initial pos scalars to their new location.
128 size_t copySize = initialCount * sizeof(SkScalar) * ScalarsPerGlyph(positioning());
129 SkASSERT((uint8_t*)posBuffer() + copySize <= (uint8_t*)NextUnchecked(this));
130
131 // memmove, as the buffers may overlap
132 memmove(posBuffer(), initialPosBuffer, copySize);
133}
134
135static int32_t next_id() {
136 static std::atomic<int32_t> nextID{1};
137 int32_t id;
138 do {
139 id = nextID++;
140 } while (id == SK_InvalidGenID);
141 return id;
142}
143
144SkTextBlob::SkTextBlob(const SkRect& bounds)
145 : fBounds(bounds)
146 , fUniqueID(next_id())
147 , fCacheID(SK_InvalidUniqueID) {}
148
149SkTextBlob::~SkTextBlob() {
150#if SK_SUPPORT_GPU
151 if (SK_InvalidUniqueID != fCacheID.load()) {
152 GrTextBlobCache::PostPurgeBlobMessage(fUniqueID, fCacheID);
153 }
154#endif
155
156 const auto* run = RunRecord::First(this);
157 do {
158 const auto* nextRun = RunRecord::Next(run);
159 SkDEBUGCODE(run->validate((uint8_t*)this + fStorageSize);)
160 run->~RunRecord();
161 run = nextRun;
162 } while (run);
163}
164
165namespace {
166
167union PositioningAndExtended {
168 int32_t intValue;
169 struct {
170 uint8_t positioning;
171 uint8_t extended;
172 uint16_t padding;
173 };
174};
175
176static_assert(sizeof(PositioningAndExtended) == sizeof(int32_t), "");
177
178} // namespace
179
180enum SkTextBlob::GlyphPositioning : uint8_t {
181 kDefault_Positioning = 0, // Default glyph advances -- zero scalars per glyph.
182 kHorizontal_Positioning = 1, // Horizontal positioning -- one scalar per glyph.
183 kFull_Positioning = 2, // Point positioning -- two scalars per glyph.
184 kRSXform_Positioning = 3, // RSXform positioning -- four scalars per glyph.
185};
186
187unsigned SkTextBlob::ScalarsPerGlyph(GlyphPositioning pos) {
188 const uint8_t gScalarsPerPositioning[] = {
189 0, // kDefault_Positioning
190 1, // kHorizontal_Positioning
191 2, // kFull_Positioning
192 4, // kRSXform_Positioning
193 };
194 SkASSERT((unsigned)pos <= 3);
195 return gScalarsPerPositioning[pos];
196}
197
198void SkTextBlob::operator delete(void* p) {
199 sk_free(p);
200}
201
202void* SkTextBlob::operator new(size_t) {
203 SK_ABORT("All blobs are created by placement new.");
204}
205
206void* SkTextBlob::operator new(size_t, void* p) {
207 return p;
208}
209
210SkTextBlobRunIterator::SkTextBlobRunIterator(const SkTextBlob* blob)
211 : fCurrentRun(SkTextBlob::RunRecord::First(blob)) {
212 SkDEBUGCODE(fStorageTop = (uint8_t*)blob + blob->fStorageSize;)
213}
214
215void SkTextBlobRunIterator::next() {
216 SkASSERT(!this->done());
217
218 if (!this->done()) {
219 SkDEBUGCODE(fCurrentRun->validate(fStorageTop);)
220 fCurrentRun = SkTextBlob::RunRecord::Next(fCurrentRun);
221 }
222}
223
224SkTextBlobRunIterator::GlyphPositioning SkTextBlobRunIterator::positioning() const {
225 SkASSERT(!this->done());
226 static_assert(static_cast<GlyphPositioning>(SkTextBlob::kDefault_Positioning) ==
227 kDefault_Positioning, "");
228 static_assert(static_cast<GlyphPositioning>(SkTextBlob::kHorizontal_Positioning) ==
229 kHorizontal_Positioning, "");
230 static_assert(static_cast<GlyphPositioning>(SkTextBlob::kFull_Positioning) ==
231 kFull_Positioning, "");
232 static_assert(static_cast<GlyphPositioning>(SkTextBlob::kRSXform_Positioning) ==
233 kRSXform_Positioning, "");
234
235 return SkTo<GlyphPositioning>(fCurrentRun->positioning());
236}
237
238bool SkTextBlobRunIterator::isLCD() const {
239 return fCurrentRun->font().getEdging() == SkFont::Edging::kSubpixelAntiAlias;
240}
241
242SkTextBlobBuilder::SkTextBlobBuilder()
243 : fStorageSize(0)
244 , fStorageUsed(0)
245 , fRunCount(0)
246 , fDeferredBounds(false)
247 , fLastRun(0) {
248 fBounds.setEmpty();
249}
250
251SkTextBlobBuilder::~SkTextBlobBuilder() {
252 if (nullptr != fStorage.get()) {
253 // We are abandoning runs and must destruct the associated font data.
254 // The easiest way to accomplish that is to use the blob destructor.
255 this->make();
256 }
257}
258
259SkRect SkTextBlobBuilder::TightRunBounds(const SkTextBlob::RunRecord& run) {
260 const SkFont& font = run.font();
261 SkRect bounds;
262
263 if (SkTextBlob::kDefault_Positioning == run.positioning()) {
264 font.measureText(run.glyphBuffer(), run.glyphCount() * sizeof(uint16_t),
265 SkTextEncoding::kGlyphID, &bounds);
266 return bounds.makeOffset(run.offset().x(), run.offset().y());
267 }
268
269 SkAutoSTArray<16, SkRect> glyphBounds(run.glyphCount());
270 font.getBounds(run.glyphBuffer(), run.glyphCount(), glyphBounds.get(), nullptr);
271
272 SkASSERT(SkTextBlob::kFull_Positioning == run.positioning() ||
273 SkTextBlob::kHorizontal_Positioning == run.positioning());
274 // kFull_Positioning => [ x, y, x, y... ]
275 // kHorizontal_Positioning => [ x, x, x... ]
276 // (const y applied by runBounds.offset(run->offset()) later)
277 const SkScalar horizontalConstY = 0;
278 const SkScalar* glyphPosX = run.posBuffer();
279 const SkScalar* glyphPosY = (run.positioning() == SkTextBlob::kFull_Positioning) ?
280 glyphPosX + 1 : &horizontalConstY;
281 const unsigned posXInc = SkTextBlob::ScalarsPerGlyph(run.positioning());
282 const unsigned posYInc = (run.positioning() == SkTextBlob::kFull_Positioning) ?
283 posXInc : 0;
284
285 bounds.setEmpty();
286 for (unsigned i = 0; i < run.glyphCount(); ++i) {
287 bounds.join(glyphBounds[i].makeOffset(*glyphPosX, *glyphPosY));
288 glyphPosX += posXInc;
289 glyphPosY += posYInc;
290 }
291
292 SkASSERT((void*)glyphPosX <= SkTextBlob::RunRecord::Next(&run));
293
294 return bounds.makeOffset(run.offset().x(), run.offset().y());
295}
296
297static SkRect map_quad_to_rect(const SkRSXform& xform, const SkRect& rect) {
298 return SkMatrix().setRSXform(xform).mapRect(rect);
299}
300
301SkRect SkTextBlobBuilder::ConservativeRunBounds(const SkTextBlob::RunRecord& run) {
302 SkASSERT(run.glyphCount() > 0);
303 SkASSERT(SkTextBlob::kFull_Positioning == run.positioning() ||
304 SkTextBlob::kHorizontal_Positioning == run.positioning() ||
305 SkTextBlob::kRSXform_Positioning == run.positioning());
306
307 const SkRect fontBounds = SkFontPriv::GetFontBounds(run.font());
308 if (fontBounds.isEmpty()) {
309 // Empty font bounds are likely a font bug. TightBounds has a better chance of
310 // producing useful results in this case.
311 return TightRunBounds(run);
312 }
313
314 // Compute the glyph position bbox.
315 SkRect bounds;
316 switch (run.positioning()) {
317 case SkTextBlob::kHorizontal_Positioning: {
318 const SkScalar* glyphPos = run.posBuffer();
319 SkASSERT((void*)(glyphPos + run.glyphCount()) <= SkTextBlob::RunRecord::Next(&run));
320
321 SkScalar minX = *glyphPos;
322 SkScalar maxX = *glyphPos;
323 for (unsigned i = 1; i < run.glyphCount(); ++i) {
324 SkScalar x = glyphPos[i];
325 minX = std::min(x, minX);
326 maxX = std::max(x, maxX);
327 }
328
329 bounds.setLTRB(minX, 0, maxX, 0);
330 } break;
331 case SkTextBlob::kFull_Positioning: {
332 const SkPoint* glyphPosPts = run.pointBuffer();
333 SkASSERT((void*)(glyphPosPts + run.glyphCount()) <= SkTextBlob::RunRecord::Next(&run));
334
335 bounds.setBounds(glyphPosPts, run.glyphCount());
336 } break;
337 case SkTextBlob::kRSXform_Positioning: {
338 const SkRSXform* xform = run.xformBuffer();
339 SkASSERT((void*)(xform + run.glyphCount()) <= SkTextBlob::RunRecord::Next(&run));
340 bounds = map_quad_to_rect(xform[0], fontBounds);
341 for (unsigned i = 1; i < run.glyphCount(); ++i) {
342 bounds.join(map_quad_to_rect(xform[i], fontBounds));
343 }
344 } break;
345 default:
346 SK_ABORT("unsupported positioning mode");
347 }
348
349 if (run.positioning() != SkTextBlob::kRSXform_Positioning) {
350 // Expand by typeface glyph bounds.
351 bounds.fLeft += fontBounds.left();
352 bounds.fTop += fontBounds.top();
353 bounds.fRight += fontBounds.right();
354 bounds.fBottom += fontBounds.bottom();
355 }
356
357 // Offset by run position.
358 return bounds.makeOffset(run.offset().x(), run.offset().y());
359}
360
361void SkTextBlobBuilder::updateDeferredBounds() {
362 SkASSERT(!fDeferredBounds || fRunCount > 0);
363
364 if (!fDeferredBounds) {
365 return;
366 }
367
368 SkASSERT(fLastRun >= SkAlignPtr(sizeof(SkTextBlob)));
369 SkTextBlob::RunRecord* run = reinterpret_cast<SkTextBlob::RunRecord*>(fStorage.get() +
370 fLastRun);
371
372 // FIXME: we should also use conservative bounds for kDefault_Positioning.
373 SkRect runBounds = SkTextBlob::kDefault_Positioning == run->positioning() ?
374 TightRunBounds(*run) : ConservativeRunBounds(*run);
375 fBounds.join(runBounds);
376 fDeferredBounds = false;
377}
378
379void SkTextBlobBuilder::reserve(size_t size) {
380 SkSafeMath safe;
381
382 // We don't currently pre-allocate, but maybe someday...
383 if (safe.add(fStorageUsed, size) <= fStorageSize && safe) {
384 return;
385 }
386
387 if (0 == fRunCount) {
388 SkASSERT(nullptr == fStorage.get());
389 SkASSERT(0 == fStorageSize);
390 SkASSERT(0 == fStorageUsed);
391
392 // the first allocation also includes blob storage
393 // aligned up to a pointer alignment so SkTextBlob::RunRecords after it stay aligned.
394 fStorageUsed = SkAlignPtr(sizeof(SkTextBlob));
395 }
396
397 fStorageSize = safe.add(fStorageUsed, size);
398
399 // FYI: This relies on everything we store being relocatable, particularly SkPaint.
400 // Also, this is counting on the underlying realloc to throw when passed max().
401 fStorage.realloc(safe ? fStorageSize : std::numeric_limits<size_t>::max());
402}
403
404bool SkTextBlobBuilder::mergeRun(const SkFont& font, SkTextBlob::GlyphPositioning positioning,
405 uint32_t count, SkPoint offset) {
406 if (0 == fLastRun) {
407 SkASSERT(0 == fRunCount);
408 return false;
409 }
410
411 SkASSERT(fLastRun >= SkAlignPtr(sizeof(SkTextBlob)));
412 SkTextBlob::RunRecord* run = reinterpret_cast<SkTextBlob::RunRecord*>(fStorage.get() +
413 fLastRun);
414 SkASSERT(run->glyphCount() > 0);
415
416 if (run->textSize() != 0) {
417 return false;
418 }
419
420 if (run->positioning() != positioning
421 || run->font() != font
422 || (run->glyphCount() + count < run->glyphCount())) {
423 return false;
424 }
425
426 // we can merge same-font/same-positioning runs in the following cases:
427 // * fully positioned run following another fully positioned run
428 // * horizontally postioned run following another horizontally positioned run with the same
429 // y-offset
430 if (SkTextBlob::kFull_Positioning != positioning
431 && (SkTextBlob::kHorizontal_Positioning != positioning
432 || run->offset().y() != offset.y())) {
433 return false;
434 }
435
436 SkSafeMath safe;
437 size_t sizeDelta =
438 SkTextBlob::RunRecord::StorageSize(run->glyphCount() + count, 0, positioning, &safe) -
439 SkTextBlob::RunRecord::StorageSize(run->glyphCount() , 0, positioning, &safe);
440 if (!safe) {
441 return false;
442 }
443
444 this->reserve(sizeDelta);
445
446 // reserve may have realloced
447 run = reinterpret_cast<SkTextBlob::RunRecord*>(fStorage.get() + fLastRun);
448 uint32_t preMergeCount = run->glyphCount();
449 run->grow(count);
450
451 // Callers expect the buffers to point at the newly added slice, ant not at the beginning.
452 fCurrentRunBuffer.glyphs = run->glyphBuffer() + preMergeCount;
453 fCurrentRunBuffer.pos = run->posBuffer()
454 + preMergeCount * SkTextBlob::ScalarsPerGlyph(positioning);
455
456 fStorageUsed += sizeDelta;
457
458 SkASSERT(fStorageUsed <= fStorageSize);
459 run->validate(fStorage.get() + fStorageUsed);
460
461 return true;
462}
463
464void SkTextBlobBuilder::allocInternal(const SkFont& font,
465 SkTextBlob::GlyphPositioning positioning,
466 int count, int textSize, SkPoint offset,
467 const SkRect* bounds) {
468 if (count <= 0 || textSize < 0) {
469 fCurrentRunBuffer = { nullptr, nullptr, nullptr, nullptr };
470 return;
471 }
472
473 if (textSize != 0 || !this->mergeRun(font, positioning, count, offset)) {
474 this->updateDeferredBounds();
475
476 SkSafeMath safe;
477 size_t runSize = SkTextBlob::RunRecord::StorageSize(count, textSize, positioning, &safe);
478 if (!safe) {
479 fCurrentRunBuffer = { nullptr, nullptr, nullptr, nullptr };
480 return;
481 }
482
483 this->reserve(runSize);
484
485 SkASSERT(fStorageUsed >= SkAlignPtr(sizeof(SkTextBlob)));
486 SkASSERT(fStorageUsed + runSize <= fStorageSize);
487
488 SkTextBlob::RunRecord* run = new (fStorage.get() + fStorageUsed)
489 SkTextBlob::RunRecord(count, textSize, offset, font, positioning);
490 fCurrentRunBuffer.glyphs = run->glyphBuffer();
491 fCurrentRunBuffer.pos = run->posBuffer();
492 fCurrentRunBuffer.utf8text = run->textBuffer();
493 fCurrentRunBuffer.clusters = run->clusterBuffer();
494
495 fLastRun = fStorageUsed;
496 fStorageUsed += runSize;
497 fRunCount++;
498
499 SkASSERT(fStorageUsed <= fStorageSize);
500 run->validate(fStorage.get() + fStorageUsed);
501 }
502 SkASSERT(textSize > 0 || nullptr == fCurrentRunBuffer.utf8text);
503 SkASSERT(textSize > 0 || nullptr == fCurrentRunBuffer.clusters);
504 if (!fDeferredBounds) {
505 if (bounds) {
506 fBounds.join(*bounds);
507 } else {
508 fDeferredBounds = true;
509 }
510 }
511}
512
513// SkFont versions
514
515const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRun(const SkFont& font, int count,
516 SkScalar x, SkScalar y,
517 const SkRect* bounds) {
518 this->allocInternal(font, SkTextBlob::kDefault_Positioning, count, 0, {x, y}, bounds);
519 return fCurrentRunBuffer;
520}
521
522const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunPosH(const SkFont& font, int count,
523 SkScalar y,
524 const SkRect* bounds) {
525 this->allocInternal(font, SkTextBlob::kHorizontal_Positioning, count, 0, {0, y}, bounds);
526 return fCurrentRunBuffer;
527}
528
529const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunPos(const SkFont& font, int count,
530 const SkRect* bounds) {
531 this->allocInternal(font, SkTextBlob::kFull_Positioning, count, 0, {0, 0}, bounds);
532 return fCurrentRunBuffer;
533}
534
535const SkTextBlobBuilder::RunBuffer&
536SkTextBlobBuilder::allocRunRSXform(const SkFont& font, int count) {
537 this->allocInternal(font, SkTextBlob::kRSXform_Positioning, count, 0, {0, 0}, nullptr);
538 return fCurrentRunBuffer;
539}
540
541const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunText(const SkFont& font, int count,
542 SkScalar x, SkScalar y,
543 int textByteCount,
544 SkString lang,
545 const SkRect* bounds) {
546 this->allocInternal(font,
547 SkTextBlob::kDefault_Positioning,
548 count,
549 textByteCount,
550 SkPoint::Make(x, y),
551 bounds);
552 return fCurrentRunBuffer;
553}
554
555const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunTextPosH(const SkFont& font, int count,
556 SkScalar y,
557 int textByteCount,
558 SkString lang,
559 const SkRect* bounds) {
560 this->allocInternal(font,
561 SkTextBlob::kHorizontal_Positioning,
562 count,
563 textByteCount,
564 SkPoint::Make(0, y),
565 bounds);
566 return fCurrentRunBuffer;
567}
568
569const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunTextPos(const SkFont& font, int count,
570 int textByteCount,
571 SkString lang,
572 const SkRect *bounds) {
573 this->allocInternal(font,
574 SkTextBlob::kFull_Positioning,
575 count, textByteCount,
576 SkPoint::Make(0, 0),
577 bounds);
578 return fCurrentRunBuffer;
579}
580
581const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunRSXform(const SkFont& font, int count,
582 int textByteCount,
583 SkString lang,
584 const SkRect* bounds) {
585 this->allocInternal(font,
586 SkTextBlob::kRSXform_Positioning,
587 count,
588 textByteCount,
589 {0, 0},
590 bounds);
591 return fCurrentRunBuffer;
592}
593
594sk_sp<SkTextBlob> SkTextBlobBuilder::make() {
595 if (!fRunCount) {
596 // We don't instantiate empty blobs.
597 SkASSERT(!fStorage.get());
598 SkASSERT(fStorageUsed == 0);
599 SkASSERT(fStorageSize == 0);
600 SkASSERT(fLastRun == 0);
601 SkASSERT(fBounds.isEmpty());
602 return nullptr;
603 }
604
605 this->updateDeferredBounds();
606
607 // Tag the last run as such.
608 auto* lastRun = reinterpret_cast<SkTextBlob::RunRecord*>(fStorage.get() + fLastRun);
609 lastRun->fFlags |= SkTextBlob::RunRecord::kLast_Flag;
610
611 SkTextBlob* blob = new (fStorage.release()) SkTextBlob(fBounds);
612 SkDEBUGCODE(const_cast<SkTextBlob*>(blob)->fStorageSize = fStorageSize;)
613
614 SkDEBUGCODE(
615 SkSafeMath safe;
616 size_t validateSize = SkAlignPtr(sizeof(SkTextBlob));
617 for (const auto* run = SkTextBlob::RunRecord::First(blob); run;
618 run = SkTextBlob::RunRecord::Next(run)) {
619 validateSize += SkTextBlob::RunRecord::StorageSize(
620 run->fCount, run->textSize(), run->positioning(), &safe);
621 run->validate(reinterpret_cast<const uint8_t*>(blob) + fStorageUsed);
622 fRunCount--;
623 }
624 SkASSERT(validateSize == fStorageUsed);
625 SkASSERT(fRunCount == 0);
626 SkASSERT(safe);
627 )
628
629 fStorageUsed = 0;
630 fStorageSize = 0;
631 fRunCount = 0;
632 fLastRun = 0;
633 fBounds.setEmpty();
634
635 return sk_sp<SkTextBlob>(blob);
636}
637
638///////////////////////////////////////////////////////////////////////////////////////////////////
639
640void SkTextBlobPriv::Flatten(const SkTextBlob& blob, SkWriteBuffer& buffer) {
641 // seems like we could skip this, and just recompute bounds in unflatten, but
642 // some cc_unittests fail if we remove this...
643 buffer.writeRect(blob.bounds());
644
645 SkTextBlobRunIterator it(&blob);
646 while (!it.done()) {
647 SkASSERT(it.glyphCount() > 0);
648
649 buffer.write32(it.glyphCount());
650 PositioningAndExtended pe;
651 pe.intValue = 0;
652 pe.positioning = it.positioning();
653 SkASSERT((int32_t)it.positioning() == pe.intValue); // backwards compat.
654
655 uint32_t textSize = it.textSize();
656 pe.extended = textSize > 0;
657 buffer.write32(pe.intValue);
658 if (pe.extended) {
659 buffer.write32(textSize);
660 }
661 buffer.writePoint(it.offset());
662
663 SkFontPriv::Flatten(it.font(), buffer);
664
665 buffer.writeByteArray(it.glyphs(), it.glyphCount() * sizeof(uint16_t));
666 buffer.writeByteArray(it.pos(),
667 it.glyphCount() * sizeof(SkScalar) *
668 SkTextBlob::ScalarsPerGlyph(
669 SkTo<SkTextBlob::GlyphPositioning>(it.positioning())));
670 if (pe.extended) {
671 buffer.writeByteArray(it.clusters(), sizeof(uint32_t) * it.glyphCount());
672 buffer.writeByteArray(it.text(), it.textSize());
673 }
674
675 it.next();
676 }
677
678 // Marker for the last run (0 is not a valid glyph count).
679 buffer.write32(0);
680}
681
682sk_sp<SkTextBlob> SkTextBlobPriv::MakeFromBuffer(SkReadBuffer& reader) {
683 SkRect bounds;
684 reader.readRect(&bounds);
685
686 SkTextBlobBuilder blobBuilder;
687 SkSafeMath safe;
688 for (;;) {
689 int glyphCount = reader.read32();
690 if (glyphCount == 0) {
691 // End-of-runs marker.
692 break;
693 }
694
695 PositioningAndExtended pe;
696 pe.intValue = reader.read32();
697 const auto pos = SkTo<SkTextBlob::GlyphPositioning>(pe.positioning);
698 if (glyphCount <= 0 || pos > SkTextBlob::kRSXform_Positioning) {
699 return nullptr;
700 }
701 int textSize = pe.extended ? reader.read32() : 0;
702 if (textSize < 0) {
703 return nullptr;
704 }
705
706 SkPoint offset;
707 reader.readPoint(&offset);
708 SkFont font;
709 if (reader.isVersionLT(SkPicturePriv::kSerializeFonts_Version)) {
710 SkPaint paint;
711 reader.readPaint(&paint, &font);
712 } else {
713 SkFontPriv::Unflatten(&font, reader);
714 }
715
716 // Compute the expected size of the buffer and ensure we have enough to deserialize
717 // a run before allocating it.
718 const size_t glyphSize = safe.mul(glyphCount, sizeof(uint16_t)),
719 posSize =
720 safe.mul(glyphCount, safe.mul(sizeof(SkScalar),
721 SkTextBlob::ScalarsPerGlyph(pos))),
722 clusterSize = pe.extended ? safe.mul(glyphCount, sizeof(uint32_t)) : 0;
723 const size_t totalSize =
724 safe.add(safe.add(glyphSize, posSize), safe.add(clusterSize, textSize));
725
726 if (!reader.isValid() || !safe || totalSize > reader.available()) {
727 return nullptr;
728 }
729
730 const SkTextBlobBuilder::RunBuffer* buf = nullptr;
731 switch (pos) {
732 case SkTextBlob::kDefault_Positioning:
733 buf = &blobBuilder.allocRunText(font, glyphCount, offset.x(), offset.y(),
734 textSize, SkString(), &bounds);
735 break;
736 case SkTextBlob::kHorizontal_Positioning:
737 buf = &blobBuilder.allocRunTextPosH(font, glyphCount, offset.y(),
738 textSize, SkString(), &bounds);
739 break;
740 case SkTextBlob::kFull_Positioning:
741 buf = &blobBuilder.allocRunTextPos(font, glyphCount, textSize, SkString(), &bounds);
742 break;
743 case SkTextBlob::kRSXform_Positioning:
744 buf = &blobBuilder.allocRunRSXform(font, glyphCount, textSize, SkString(), &bounds);
745 break;
746 }
747
748 if (!buf->glyphs ||
749 !buf->pos ||
750 (pe.extended && (!buf->clusters || !buf->utf8text))) {
751 return nullptr;
752 }
753
754 if (!reader.readByteArray(buf->glyphs, glyphSize) ||
755 !reader.readByteArray(buf->pos, posSize)) {
756 return nullptr;
757 }
758
759 if (pe.extended) {
760 if (!reader.readByteArray(buf->clusters, clusterSize) ||
761 !reader.readByteArray(buf->utf8text, textSize)) {
762 return nullptr;
763 }
764 }
765 }
766
767 return blobBuilder.make();
768}
769
770sk_sp<SkTextBlob> SkTextBlob::MakeFromText(const void* text, size_t byteLength, const SkFont& font,
771 SkTextEncoding encoding) {
772 // Note: we deliberately promote this to fully positioned blobs, since we'd have to pay the
773 // same cost down stream (i.e. computing bounds), so its cheaper to pay the cost once now.
774 const int count = font.countText(text, byteLength, encoding);
775 if (count < 1) {
776 return nullptr;
777 }
778 SkTextBlobBuilder builder;
779 auto buffer = builder.allocRunPos(font, count);
780 font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
781 font.getPos(buffer.glyphs, count, buffer.points(), {0, 0});
782 return builder.make();
783}
784
785sk_sp<SkTextBlob> SkTextBlob::MakeFromPosText(const void* text, size_t byteLength,
786 const SkPoint pos[], const SkFont& font,
787 SkTextEncoding encoding) {
788 const int count = font.countText(text, byteLength, encoding);
789 if (count < 1) {
790 return nullptr;
791 }
792 SkTextBlobBuilder builder;
793 auto buffer = builder.allocRunPos(font, count);
794 font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
795 memcpy(buffer.points(), pos, count * sizeof(SkPoint));
796 return builder.make();
797}
798
799sk_sp<SkTextBlob> SkTextBlob::MakeFromPosTextH(const void* text, size_t byteLength,
800 const SkScalar xpos[], SkScalar constY,
801 const SkFont& font, SkTextEncoding encoding) {
802 const int count = font.countText(text, byteLength, encoding);
803 if (count < 1) {
804 return nullptr;
805 }
806 SkTextBlobBuilder builder;
807 auto buffer = builder.allocRunPosH(font, count, constY);
808 font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
809 memcpy(buffer.pos, xpos, count * sizeof(SkScalar));
810 return builder.make();
811}
812
813sk_sp<SkTextBlob> SkTextBlob::MakeFromRSXform(const void* text, size_t byteLength,
814 const SkRSXform xform[], const SkFont& font,
815 SkTextEncoding encoding) {
816 const int count = font.countText(text, byteLength, encoding);
817 if (count < 1) {
818 return nullptr;
819 }
820 SkTextBlobBuilder builder;
821 auto buffer = builder.allocRunRSXform(font, count);
822 font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
823 memcpy(buffer.xforms(), xform, count * sizeof(SkRSXform));
824 return builder.make();
825}
826
827sk_sp<SkData> SkTextBlob::serialize(const SkSerialProcs& procs) const {
828 SkBinaryWriteBuffer buffer;
829 buffer.setSerialProcs(procs);
830 SkTextBlobPriv::Flatten(*this, buffer);
831
832 size_t total = buffer.bytesWritten();
833 sk_sp<SkData> data = SkData::MakeUninitialized(total);
834 buffer.writeToMemory(data->writable_data());
835 return data;
836}
837
838sk_sp<SkTextBlob> SkTextBlob::Deserialize(const void* data, size_t length,
839 const SkDeserialProcs& procs) {
840 SkReadBuffer buffer(data, length);
841 buffer.setDeserialProcs(procs);
842 return SkTextBlobPriv::MakeFromBuffer(buffer);
843}
844
845///////////////////////////////////////////////////////////////////////////////////////////////////
846
847size_t SkTextBlob::serialize(const SkSerialProcs& procs, void* memory, size_t memory_size) const {
848 SkBinaryWriteBuffer buffer(memory, memory_size);
849 buffer.setSerialProcs(procs);
850 SkTextBlobPriv::Flatten(*this, buffer);
851 return buffer.usingInitialStorage() ? buffer.bytesWritten() : 0u;
852}
853
854///////////////////////////////////////////////////////////////////////////////////////////////////
855
856namespace {
857int get_glyph_run_intercepts(const SkGlyphRun& glyphRun,
858 const SkPaint& paint,
859 const SkScalar bounds[2],
860 SkScalar intervals[],
861 int* intervalCount) {
862 SkScalar scale = SK_Scalar1;
863 SkPaint interceptPaint{paint};
864 SkFont interceptFont{glyphRun.font()};
865
866 interceptPaint.setMaskFilter(nullptr); // don't want this affecting our path-cache lookup
867
868 // can't use our canonical size if we need to apply path effects
869 if (interceptPaint.getPathEffect() == nullptr) {
870 // If the wrong size is going to be used, don't hint anything.
871 interceptFont.setHinting(SkFontHinting::kNone);
872 interceptFont.setSubpixel(true);
873 scale = interceptFont.getSize() / SkFontPriv::kCanonicalTextSizeForPaths;
874 interceptFont.setSize(SkIntToScalar(SkFontPriv::kCanonicalTextSizeForPaths));
875 // Note: fScale can be zero here (even if it wasn't before the divide). It can also
876 // be very very small. We call sk_ieee_float_divide below to ensure IEEE divide behavior,
877 // since downstream we will check for the resulting coordinates being non-finite anyway.
878 // Thus we don't need to check for zero here.
879 if (interceptPaint.getStrokeWidth() > 0
880 && interceptPaint.getStyle() != SkPaint::kFill_Style) {
881 interceptPaint.setStrokeWidth(
882 sk_ieee_float_divide(interceptPaint.getStrokeWidth(), scale));
883 }
884 }
885
886 interceptPaint.setStyle(SkPaint::kFill_Style);
887 interceptPaint.setPathEffect(nullptr);
888
889 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeWithNoDevice(interceptFont, &interceptPaint);
890 SkBulkGlyphMetricsAndPaths metricsAndPaths{strikeSpec};
891
892 SkScalar xOffset = 0;
893 SkScalar xPos = xOffset;
894 SkScalar prevAdvance = 0;
895
896 const SkPoint* posCursor = glyphRun.positions().begin();
897 for (const SkGlyph* glyph : metricsAndPaths.glyphs(glyphRun.glyphsIDs())) {
898 SkPoint pos = *posCursor++;
899
900 xPos += prevAdvance * scale;
901 prevAdvance = glyph->advanceX();
902 if (glyph->path() != nullptr) {
903 // The typeface is scaled, so un-scale the bounds to be in the space of the typeface.
904 // Also ensure the bounds are properly offset by the vertical positioning of the glyph.
905 SkScalar scaledBounds[2] = {
906 (bounds[0] - pos.y()) / scale,
907 (bounds[1] - pos.y()) / scale
908 };
909 metricsAndPaths.findIntercepts(
910 scaledBounds, scale, pos.x(), glyph, intervals, intervalCount);
911 }
912 }
913 return *intervalCount;
914}
915} // namespace
916
917int SkTextBlob::getIntercepts(const SkScalar bounds[2], SkScalar intervals[],
918 const SkPaint* paint) const {
919
920 SkTLazy<SkPaint> defaultPaint;
921 if (paint == nullptr) {
922 defaultPaint.init();
923 paint = defaultPaint.get();
924 }
925
926 SkGlyphRunBuilder builder;
927 builder.textBlobToGlyphRunListIgnoringRSXForm(*paint, *this, SkPoint{0, 0});
928 auto glyphRunList = builder.useGlyphRunList();
929
930 int intervalCount = 0;
931 for (const SkGlyphRun& glyphRun : glyphRunList) {
932 intervalCount = get_glyph_run_intercepts(glyphRun, *paint, bounds, intervals, &intervalCount);
933 }
934
935 return intervalCount;
936}
937
938////////
939
940SkTextBlob::Iter::Iter(const SkTextBlob& blob) {
941 fRunRecord = RunRecord::First(&blob);
942}
943
944bool SkTextBlob::Iter::next(Run* rec) {
945 if (fRunRecord) {
946 if (rec) {
947 rec->fTypeface = fRunRecord->font().getTypeface();
948 rec->fGlyphCount = fRunRecord->glyphCount();
949 rec->fGlyphIndices = fRunRecord->glyphBuffer();
950 }
951 if (fRunRecord->isLastRun()) {
952 fRunRecord = nullptr;
953 } else {
954 fRunRecord = RunRecord::Next(fRunRecord);
955 }
956 return true;
957 }
958 return false;
959}
960