• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
29 namespace {
30 struct RunFontStorageEquivalent {
31     SkScalar fSize, fScaleX;
32     void*    fTypeface;
33     SkScalar fSkewX;
34     uint32_t fFlags;
35 };
36 static_assert(sizeof(SkFont) == sizeof(RunFontStorageEquivalent), "runfont_should_stay_packed");
37 }
38 
StorageSize(uint32_t glyphCount,uint32_t textSize,SkTextBlob::GlyphPositioning positioning,SkSafeMath * safe)39 size_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 
First(const SkTextBlob * blob)61 const 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 
Next(const RunRecord * run)67 const SkTextBlob::RunRecord* SkTextBlob::RunRecord::Next(const RunRecord* run) {
68     return SkToBool(run->fFlags & kLast_Flag) ? nullptr : NextUnchecked(run);
69 }
70 
71 namespace {
72 struct RunRecordStorageEquivalent {
73     SkFont   fFont;
74     SkPoint  fOffset;
75     uint32_t fCount;
76     uint32_t fFlags;
77     SkDEBUGCODE(unsigned fMagic;)
78 };
79 }
80 
validate(const uint8_t * storageTop) const81 void 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 
NextUnchecked(const RunRecord * run)98 const 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 
PosCount(uint32_t glyphCount,SkTextBlob::GlyphPositioning positioning,SkSafeMath * safe)107 size_t SkTextBlob::RunRecord::PosCount(uint32_t glyphCount,
108                                        SkTextBlob::GlyphPositioning positioning,
109                                        SkSafeMath* safe) {
110     return safe->mul(glyphCount, ScalarsPerGlyph(positioning));
111 }
112 
textSizePtr() const113 uint32_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 
grow(uint32_t count)122 void 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 
next_id()135 static 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 
SkTextBlob(const SkRect & bounds)144 SkTextBlob::SkTextBlob(const SkRect& bounds)
145     : fBounds(bounds)
146     , fUniqueID(next_id())
147     , fCacheID(SK_InvalidUniqueID) {}
148 
~SkTextBlob()149 SkTextBlob::~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 
165 namespace {
166 
167 union PositioningAndExtended {
168     int32_t intValue;
169     struct {
170         uint8_t  positioning;
171         uint8_t  extended;
172         uint16_t padding;
173     };
174 };
175 
176 static_assert(sizeof(PositioningAndExtended) == sizeof(int32_t), "");
177 
178 } // namespace
179 
180 enum 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 
ScalarsPerGlyph(GlyphPositioning pos)187 unsigned 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 
operator delete(void * p)198 void SkTextBlob::operator delete(void* p) {
199     sk_free(p);
200 }
201 
operator new(size_t)202 void* SkTextBlob::operator new(size_t) {
203     SK_ABORT("All blobs are created by placement new.");
204 }
205 
operator new(size_t,void * p)206 void* SkTextBlob::operator new(size_t, void* p) {
207     return p;
208 }
209 
SkTextBlobRunIterator(const SkTextBlob * blob)210 SkTextBlobRunIterator::SkTextBlobRunIterator(const SkTextBlob* blob)
211     : fCurrentRun(SkTextBlob::RunRecord::First(blob)) {
212     SkDEBUGCODE(fStorageTop = (uint8_t*)blob + blob->fStorageSize;)
213 }
214 
next()215 void 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 
positioning() const224 SkTextBlobRunIterator::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 
isLCD() const238 bool SkTextBlobRunIterator::isLCD() const {
239     return fCurrentRun->font().getEdging() == SkFont::Edging::kSubpixelAntiAlias;
240 }
241 
SkTextBlobBuilder()242 SkTextBlobBuilder::SkTextBlobBuilder()
243     : fStorageSize(0)
244     , fStorageUsed(0)
245     , fRunCount(0)
246     , fDeferredBounds(false)
247     , fLastRun(0) {
248     fBounds.setEmpty();
249 }
250 
~SkTextBlobBuilder()251 SkTextBlobBuilder::~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 
TightRunBounds(const SkTextBlob::RunRecord & run)259 SkRect 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 
map_quad_to_rect(const SkRSXform & xform,const SkRect & rect)297 static SkRect map_quad_to_rect(const SkRSXform& xform, const SkRect& rect) {
298     return SkMatrix().setRSXform(xform).mapRect(rect);
299 }
300 
ConservativeRunBounds(const SkTextBlob::RunRecord & run)301 SkRect 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 = SkMinScalar(x, minX);
326             maxX = SkMaxScalar(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 
updateDeferredBounds()361 void 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 
reserve(size_t size)379 void 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 
mergeRun(const SkFont & font,SkTextBlob::GlyphPositioning positioning,uint32_t count,SkPoint offset)404 bool 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 
allocInternal(const SkFont & font,SkTextBlob::GlyphPositioning positioning,int count,int textSize,SkPoint offset,const SkRect * bounds)464 void 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 
allocRun(const SkFont & font,int count,SkScalar x,SkScalar y,const SkRect * bounds)515 const 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 
allocRunPosH(const SkFont & font,int count,SkScalar y,const SkRect * bounds)522 const 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 
allocRunPos(const SkFont & font,int count,const SkRect * bounds)529 const 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 
535 const SkTextBlobBuilder::RunBuffer&
allocRunRSXform(const SkFont & font,int count)536 SkTextBlobBuilder::allocRunRSXform(const SkFont& font, int count) {
537     this->allocInternal(font, SkTextBlob::kRSXform_Positioning, count, 0, {0, 0}, nullptr);
538     return fCurrentRunBuffer;
539 }
540 
allocRunText(const SkFont & font,int count,SkScalar x,SkScalar y,int textByteCount,SkString lang,const SkRect * bounds)541 const 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 
allocRunTextPosH(const SkFont & font,int count,SkScalar y,int textByteCount,SkString lang,const SkRect * bounds)555 const 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 
allocRunTextPos(const SkFont & font,int count,int textByteCount,SkString lang,const SkRect * bounds)569 const 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 
allocRunRSXform(const SkFont & font,int count,int textByteCount,SkString lang,const SkRect * bounds)581 const 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 
make()594 sk_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 
Flatten(const SkTextBlob & blob,SkWriteBuffer & buffer)640 void 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 
MakeFromBuffer(SkReadBuffer & reader)682 sk_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 
MakeFromText(const void * text,size_t byteLength,const SkFont & font,SkTextEncoding encoding)770 sk_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     SkTextBlobBuilder builder;
776     auto buffer = builder.allocRunPos(font, count);
777     font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
778     font.getPos(buffer.glyphs, count, buffer.points(), {0, 0});
779     return builder.make();
780 }
781 
MakeFromPosText(const void * text,size_t byteLength,const SkPoint pos[],const SkFont & font,SkTextEncoding encoding)782 sk_sp<SkTextBlob> SkTextBlob::MakeFromPosText(const void* text, size_t byteLength,
783                                               const SkPoint pos[], const SkFont& font,
784                                               SkTextEncoding encoding) {
785     const int count = font.countText(text, byteLength, encoding);
786     SkTextBlobBuilder builder;
787     auto buffer = builder.allocRunPos(font, count);
788     font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
789     memcpy(buffer.points(), pos, count * sizeof(SkPoint));
790     return builder.make();
791 }
792 
MakeFromPosTextH(const void * text,size_t byteLength,const SkScalar xpos[],SkScalar constY,const SkFont & font,SkTextEncoding encoding)793 sk_sp<SkTextBlob> SkTextBlob::MakeFromPosTextH(const void* text, size_t byteLength,
794                                                const SkScalar xpos[], SkScalar constY,
795                                                const SkFont& font, SkTextEncoding encoding) {
796     const int count = font.countText(text, byteLength, encoding);
797     SkTextBlobBuilder builder;
798     auto buffer = builder.allocRunPosH(font, count, constY);
799     font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
800     memcpy(buffer.pos, xpos, count * sizeof(SkScalar));
801     return builder.make();
802 }
803 
MakeFromRSXform(const void * text,size_t byteLength,const SkRSXform xform[],const SkFont & font,SkTextEncoding encoding)804 sk_sp<SkTextBlob> SkTextBlob::MakeFromRSXform(const void* text, size_t byteLength,
805                                               const SkRSXform xform[], const SkFont& font,
806                                               SkTextEncoding encoding) {
807     const int count = font.countText(text, byteLength, encoding);
808     SkTextBlobBuilder builder;
809     auto buffer = builder.allocRunRSXform(font, count);
810     font.textToGlyphs(text, byteLength, encoding, buffer.glyphs, count);
811     memcpy(buffer.xforms(), xform, count * sizeof(SkRSXform));
812     return builder.make();
813 }
814 
serialize(const SkSerialProcs & procs) const815 sk_sp<SkData> SkTextBlob::serialize(const SkSerialProcs& procs) const {
816     SkBinaryWriteBuffer buffer;
817     buffer.setSerialProcs(procs);
818     SkTextBlobPriv::Flatten(*this, buffer);
819 
820     size_t total = buffer.bytesWritten();
821     sk_sp<SkData> data = SkData::MakeUninitialized(total);
822     buffer.writeToMemory(data->writable_data());
823     return data;
824 }
825 
Deserialize(const void * data,size_t length,const SkDeserialProcs & procs)826 sk_sp<SkTextBlob> SkTextBlob::Deserialize(const void* data, size_t length,
827                                           const SkDeserialProcs& procs) {
828     SkReadBuffer buffer(data, length);
829     buffer.setDeserialProcs(procs);
830     return SkTextBlobPriv::MakeFromBuffer(buffer);
831 }
832 
dump(std::string & desc,int depth) const833 void SkTextBlob::dump(std::string& desc, int depth) const {
834     std::string split(depth, '\t');
835     desc += split + "\n SkTextBlob:{ \n";
836     fBounds.dump(desc, depth + 1);
837     desc += split + "\t fUniqueID:" + std::to_string(fUniqueID) + "\n";
838     desc += split + "}\n";
839 }
840 
841 ///////////////////////////////////////////////////////////////////////////////////////////////////
842 
serialize(const SkSerialProcs & procs,void * memory,size_t memory_size) const843 size_t SkTextBlob::serialize(const SkSerialProcs& procs, void* memory, size_t memory_size) const {
844     SkBinaryWriteBuffer buffer(memory, memory_size);
845     buffer.setSerialProcs(procs);
846     SkTextBlobPriv::Flatten(*this, buffer);
847     return buffer.usingInitialStorage() ? buffer.bytesWritten() : 0u;
848 }
849 
850 ///////////////////////////////////////////////////////////////////////////////////////////////////
851 
852 namespace {
get_glyph_run_intercepts(const SkGlyphRun & glyphRun,const SkPaint & paint,const SkScalar bounds[2],SkScalar intervals[],int * intervalCount)853 int get_glyph_run_intercepts(const SkGlyphRun& glyphRun,
854                              const SkPaint& paint,
855                              const SkScalar bounds[2],
856                              SkScalar intervals[],
857                              int* intervalCount) {
858     SkScalar scale = SK_Scalar1;
859     SkPaint interceptPaint{paint};
860     SkFont interceptFont{glyphRun.font()};
861 
862     interceptPaint.setMaskFilter(nullptr);   // don't want this affecting our path-cache lookup
863 
864     // can't use our canonical size if we need to apply path effects
865     if (interceptPaint.getPathEffect() == nullptr) {
866         // If the wrong size is going to be used, don't hint anything.
867         interceptFont.setHinting(SkFontHinting::kNone);
868         interceptFont.setSubpixel(true);
869         scale = interceptFont.getSize() / SkFontPriv::kCanonicalTextSizeForPaths;
870         interceptFont.setSize(SkIntToScalar(SkFontPriv::kCanonicalTextSizeForPaths));
871         // Note: fScale can be zero here (even if it wasn't before the divide). It can also
872         // be very very small. We call sk_ieee_float_divide below to ensure IEEE divide behavior,
873         // since downstream we will check for the resulting coordinates being non-finite anyway.
874         // Thus we don't need to check for zero here.
875         if (interceptPaint.getStrokeWidth() > 0
876             && interceptPaint.getStyle() != SkPaint::kFill_Style) {
877             interceptPaint.setStrokeWidth(
878                     sk_ieee_float_divide(interceptPaint.getStrokeWidth(), scale));
879         }
880     }
881 
882     interceptPaint.setStyle(SkPaint::kFill_Style);
883     interceptPaint.setPathEffect(nullptr);
884 
885     SkStrikeSpec strikeSpec = SkStrikeSpec::MakeWithNoDevice(interceptFont, &interceptPaint);
886     auto cache = strikeSpec.findOrCreateExclusiveStrike();
887 
888     SkScalar xOffset = 0;
889     SkScalar xPos = xOffset;
890     SkScalar prevAdvance = 0;
891 
892     // The typeface is scaled, so un-scale the bounds to be in the space of the typeface.
893     SkScalar scaledBounds[2] = {bounds[0] / scale, bounds[1] / scale};
894 
895     const SkPoint* posCursor = glyphRun.positions().begin();
896     for (auto glyphID : glyphRun.glyphsIDs()) {
897         SkPoint pos = *posCursor++;
898 
899         SkGlyph* glyph = cache->glyph(glyphID);
900         xPos += prevAdvance * scale;
901         prevAdvance = glyph->advanceX();
902         if (cache->preparePath(glyph) != nullptr) {
903             cache->findIntercepts(scaledBounds, scale, pos.x(), glyph, intervals, intervalCount);
904         }
905     }
906     return *intervalCount;
907 }
908 }  // namespace
909 
getIntercepts(const SkScalar bounds[2],SkScalar intervals[],const SkPaint * paint) const910 int SkTextBlob::getIntercepts(const SkScalar bounds[2], SkScalar intervals[],
911                               const SkPaint* paint) const {
912 
913     SkTLazy<SkPaint> defaultPaint;
914     if (paint == nullptr) {
915         defaultPaint.init();
916         paint = defaultPaint.get();
917     }
918 
919     SkGlyphRunBuilder builder;
920     builder.textBlobToGlyphRunListIgnoringRSXForm(*paint, *this, SkPoint{0, 0});
921     auto glyphRunList = builder.useGlyphRunList();
922 
923     int intervalCount = 0;
924     for (const SkGlyphRun& glyphRun : glyphRunList) {
925         intervalCount = get_glyph_run_intercepts(glyphRun, *paint, bounds, intervals, &intervalCount);
926     }
927 
928     return intervalCount;
929 }
930