Repository navigation
Expand file tree
/
Copy pathRun.cpp
More file actions
453 lines (397 loc) · 15.5 KB
/
Copy pathRun.cpp
File metadata and controls
453 lines (397 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright 2019 Google LLC
#include "include/core/SkFontMetrics.h"
#include "include/core/SkTextBlob.h"
#include "include/private/SkFloatingPoint.h"
#include "include/private/SkMalloc.h"
#include "include/private/SkTo.h"
#include "modules/skparagraph/include/DartTypes.h"
#include "modules/skparagraph/include/TextStyle.h"
#include "modules/skparagraph/src/ParagraphImpl.h"
#include "modules/skparagraph/src/Run.h"
#include "modules/skshaper/include/SkShaper.h"
#include "src/core/SkFloatBits.h"
#include "src/core/SkUTF.h"
#include <cstring>
#include <new>
namespace skia {
namespace textlayout {
sk_sp<Run::GlyphData> Run::GlyphData::Make(size_t n, bool hasOffsets) {
// Positions, cluster indexes, glyphs, then offsets. The arrays never grow after this.
static_assert(alignof(GlyphData) >= alignof(SkPoint));
static_assert(alignof(SkPoint) == alignof(uint32_t) && alignof(uint32_t) >= alignof(SkGlyphID));
void* mem = sk_malloc_throw(sizeof(GlyphData) + (n + 1) * (sizeof(SkPoint) + sizeof(uint32_t)) +
(hasOffsets ? SkAlign2(n) : n) * sizeof(SkGlyphID) +
(hasOffsets ? n * sizeof(SkPoint) : 0));
GlyphData* data = new (mem) GlyphData;
data->fSize = n;
data->fHasOffsets = hasOffsets;
return sk_sp<GlyphData>(data);
}
Run::Run(ParagraphImpl* owner,
const SkShaper::RunHandler::RunInfo& info,
size_t firstChar,
SkScalar heightMultiplier,
bool useHalfLeading,
SkScalar baselineShift,
size_t index,
SkScalar offsetX)
: fOwner(owner)
, fTextRange(firstChar + info.utf8Range.begin(), firstChar + info.utf8Range.end())
, fClusterRange(EMPTY_CLUSTERS)
, fFont(info.fFont)
, fClusterStart(firstChar)
, fHeightMultiplier(heightMultiplier)
, fUseHalfLeading(useHalfLeading)
, fBaselineShift(baselineShift)
{
fBidiLevel = info.fBidiLevel;
fScript = info.fScript;
fLanguage = info.fLanguage;
fAdvance = info.fAdvance;
fIndex = index;
fUtf8Range = info.utf8Range;
fOffset = SkVector::Make(offsetX, 0);
info.fFont.getMetrics(&fFontMetrics);
this->calculateMetrics();
fEllipsis = false;
fPlaceholderIndex = std::numeric_limits<size_t>::max();
}
void Run::setEndOfRun() {
// To make edge cases easier:
fGlyphData->positions()[this->size()] = fOffset + fAdvance;
fGlyphData->clusterIndexes()[this->size()] =
this->leftToRight() ? fUtf8Range.end() : fUtf8Range.begin();
}
void Run::allocateGlyphData(size_t glyphCount, bool hasOffsets) {
fGlyphData = GlyphData::Make(glyphCount, hasOffsets);
this->setEndOfRun();
}
SkShaper::RunHandler::Buffer Run::newRunBuffer(ShapingBuffer* buffer, size_t glyphCount) {
// Most runs have no offsets, so first make the glyph data without them.
this->allocateGlyphData(glyphCount, /*hasOffsets=*/false);
if (buffer->fOffsets.size() < SkToInt(glyphCount)) {
buffer->fOffsets.resize_back(SkToInt(glyphCount));
}
return {fGlyphData->glyphs(),
fGlyphData->positions(),
buffer->fOffsets.data(),
fGlyphData->clusterIndexes(),
fOffset};
}
void Run::commit(const ShapingBuffer& buffer) {
const size_t n = this->size();
const SkPoint* offsets = buffer.fOffsets.data();
// The bits of all offsets; -0.0 counts as zero. No branches, so it vectorizes.
uint32_t bits = 0;
for (size_t i = 0; i < n; ++i) {
bits |= SkFloat2Bits(offsets[i].fX) | SkFloat2Bits(offsets[i].fY);
}
if ((bits & 0x7fffffff) == 0) {
return;
}
// Most runs do not get here: only marks and some kerning have offsets.
sk_sp<GlyphData> data = GlyphData::Make(n, /*hasOffsets=*/true);
// The positions, cluster indexes and glyphs are in the same place in both blocks.
memcpy(data->positions(),
fGlyphData->positions(),
(n + 1) * (sizeof(SkPoint) + sizeof(uint32_t)) + n * sizeof(SkGlyphID));
memcpy(data->offsets(), offsets, n * sizeof(SkPoint));
fGlyphData = std::move(data);
}
void Run::calculateMetrics() {
fCorrectAscent = fFontMetrics.fAscent - fFontMetrics.fLeading * 0.5;
fCorrectDescent = fFontMetrics.fDescent + fFontMetrics.fLeading * 0.5;
fCorrectLeading = 0;
if (SkScalarNearlyZero(fHeightMultiplier)) {
return;
}
const auto runHeight = fHeightMultiplier * fFont.getSize();
const auto fontIntrinsicHeight = fCorrectDescent - fCorrectAscent;
if (fUseHalfLeading) {
const auto extraLeading = (runHeight - fontIntrinsicHeight) / 2;
fCorrectAscent -= extraLeading;
fCorrectDescent += extraLeading;
} else {
const auto multiplier = runHeight / fontIntrinsicHeight;
fCorrectAscent *= multiplier;
fCorrectDescent *= multiplier;
}
// fCorrectAscent and fCorrectDescent stay unshifted; correctAscent() and correctDescent()
// apply fBaselineShift on read
}
void Run::copyTo(SkTextBlobBuilder& builder, size_t pos, size_t size) const {
SkASSERT(pos + size <= this->size());
const auto& blobBuffer = builder.allocRunPos(fFont, SkToInt(size));
sk_careful_memcpy(blobBuffer.glyphs, fGlyphData->glyphs() + pos, size * sizeof(SkGlyphID));
const SkPoint* offsets = fGlyphData->offsets();
for (size_t i = 0; i < size; ++i) {
SkPoint point = fGlyphData->positions()[i + pos];
if (!fJustificationShifts.empty()) {
point.fX += fJustificationShifts[i + pos].fX;
}
if (offsets) {
point += offsets[i + pos];
}
blobBuffer.points()[i] = point;
}
}
// Find a cluster range from text range (within one run)
// Cluster range is normalized ([start:end) start < end regardless of TextDirection
// Boolean value in triple indicates whether the cluster range was found or not
std::tuple<bool, ClusterIndex, ClusterIndex> Run::findLimitingClusters(TextRange text) const {
if (text.width() == 0) {
// Special Flutter case for "\n" and "...\n"
if (text.end > this->fTextRange.start) {
ClusterIndex index = fOwner->clusterIndex(text.end - 1);
return std::make_tuple(true, index, index);
} else {
return std::make_tuple(false, 0, 0);
}
}
ClusterRange clusterRange;
bool found = true;
// Deal with the case when either start or end are not align with glyph cluster edge
// In such case we shift the text range to the right
// (cutting from the left and adding to the right)
if (leftToRight()) {
// LTR: [start:end)
found = clusterRange.start != fClusterRange.end;
clusterRange.start = fOwner->clusterIndex(text.start);
clusterRange.end = fOwner->clusterIndex(text.end - 1);
} else {
// RTL: (start:end]
clusterRange.start = fOwner->clusterIndex(text.end);
clusterRange.end = fOwner->clusterIndex(text.start + 1);
found = clusterRange.end != fClusterRange.start;
}
return std::make_tuple(
found,
clusterRange.start,
clusterRange.end);
}
std::tuple<bool, TextIndex, TextIndex> Run::findLimitingGlyphClusters(TextRange text) const {
TextIndex start = fOwner->findPreviousGlyphClusterBoundary(text.start);
TextIndex end = fOwner->findNextGlyphClusterBoundary(text.end);
return std::make_tuple(true, start, end);
}
// Adjust the text to grapheme edges so the first grapheme start is in the text and the last grapheme start is in the text
// It actually means that the first grapheme is entirely in the text and the last grapheme does not have to be
// 12345 234 2:2 -> 2,5 4:4
std::tuple<bool, TextIndex, TextIndex> Run::findLimitingGraphemes(TextRange text) const {
TextIndex start = fOwner->findPreviousGraphemeBoundary(text.start);
TextIndex end = fOwner->findNextGraphemeBoundary(text.end);
return std::make_tuple(true, start, end);
}
void Run::iterateThroughClusters(const ClusterVisitor& visitor) {
for (size_t index = 0; index < fClusterRange.width(); ++index) {
auto correctIndex = leftToRight() ? fClusterRange.start + index : fClusterRange.end - index - 1;
auto cluster = &fOwner->cluster(correctIndex);
visitor(cluster);
}
}
void Run::addSpacesAtTheEnd(SkScalar space, Cluster* cluster) {
// Increment the run width
fAdvance.fX += space;
// Increment the cluster width
cluster->space(space);
}
SkScalar Run::addLetterSpacesEvenly(SkScalar space) {
SkScalar shift = 0;
for (size_t i = 0; i < this->size(); ++i) {
this->addX(i, shift);
shift += space;
}
this->addX(this->size(), shift);
fAdvance.fX += shift;
return shift;
}
SkScalar Run::addLetterSpacesEvenly(SkScalar space, Cluster* cluster) {
// Offset all the glyphs in the cluster
SkScalar shift = 0;
for (size_t i = cluster->startPos(); i < cluster->endPos(); ++i) {
this->addX(i, shift);
shift += space;
}
if (this->size() == cluster->endPos()) {
// To make calculations easier
this->addX(cluster->endPos(), shift);
}
// Increment the run width
fAdvance.fX += shift;
// Increment the cluster width
cluster->space(shift);
cluster->setHalfLetterSpacing(space / 2);
return shift;
}
bool Run::isCursiveScript() const {
switch (this->fScript) {
case SkSetFourByteTag('A', 'r', 'a', 'b'): // ARABIC
case SkSetFourByteTag('R', 'o', 'h', 'g'): // HANIFI_ROHINGYA
case SkSetFourByteTag('M', 'a', 'n', 'd'): // MANDAIC
case SkSetFourByteTag('M', 'o', 'n', 'g'): // MONGOLIAN
case SkSetFourByteTag('N', 'k', 'o', 'o'): // NKO
case SkSetFourByteTag('P', 'h', 'a', 'g'): // PHAGS_PA
case SkSetFourByteTag('S', 'y', 'r', 'c'): // SYRIAC
return true;
default:
return false;
}
}
void Run::shift(const Cluster* cluster, SkScalar offset) {
if (offset == 0) {
return;
}
for (size_t i = cluster->startPos(); i < cluster->endPos(); ++i) {
this->addX(i, offset);
}
if (this->size() == cluster->endPos()) {
// To make calculations easier
this->addX(cluster->endPos(), offset);
}
}
void Run::extend(const Cluster* cluster, SkScalar offset) {
// Extend the cluster at the end
this->addX(cluster->endPos(), offset);
}
void Run::updateMetrics(InternalLineMetrics* endlineMetrics) {
SkASSERT(isPlaceholder());
auto placeholderStyle = this->placeholderStyle();
// Difference between the placeholder baseline and the line bottom
SkScalar baselineAdjustment = 0;
switch (placeholderStyle->fBaseline) {
case TextBaseline::kAlphabetic:
break;
case TextBaseline::kIdeographic:
baselineAdjustment = endlineMetrics->deltaBaselines() / 2;
break;
}
auto height = placeholderStyle->fHeight;
auto offset = placeholderStyle->fBaselineOffset;
fFontMetrics.fLeading = 0;
switch (placeholderStyle->fAlignment) {
case PlaceholderAlignment::kBaseline:
fFontMetrics.fAscent = baselineAdjustment - offset;
fFontMetrics.fDescent = baselineAdjustment + height - offset;
break;
case PlaceholderAlignment::kAboveBaseline:
fFontMetrics.fAscent = baselineAdjustment - height;
fFontMetrics.fDescent = baselineAdjustment;
break;
case PlaceholderAlignment::kBelowBaseline:
fFontMetrics.fAscent = baselineAdjustment;
fFontMetrics.fDescent = baselineAdjustment + height;
break;
case PlaceholderAlignment::kTop:
fFontMetrics.fDescent = height + fFontMetrics.fAscent;
break;
case PlaceholderAlignment::kBottom:
fFontMetrics.fAscent = fFontMetrics.fDescent - height;
break;
case PlaceholderAlignment::kMiddle:
auto mid = (-fFontMetrics.fDescent - fFontMetrics.fAscent)/2.0;
fFontMetrics.fDescent = height/2.0 - mid;
fFontMetrics.fAscent = - height/2.0 - mid;
break;
}
this->calculateMetrics();
// Make sure the placeholder can fit the line
endlineMetrics->add(this);
}
SkScalar Cluster::sizeToChar(TextIndex ch) const {
if (ch <= fTextRange.start || ch >= fTextRange.end) {
return 0;
}
if (fOwner != nullptr && fRunIndex != EMPTY_RUN && fWidth > 0) {
// Scale cluster width by standalone glyph advances so multi-character
// ligatures (such as "ffi") split proportionally to their component characters.
// Combining marks lack kGraphemeStart and contribute zero horizontal advance
const Run& run = fOwner->run(fRunIndex);
const SkFont& font = run.font();
const char* text = fOwner->text().data();
const char* ptr = text + fTextRange.start;
const char* end = text + fTextRange.end;
const char* split = text + ch;
SkScalar prefixWidth = 0;
SkScalar totalWidth = 0;
while (ptr < end) {
const char* charStart = ptr;
SkUnichar u = SkUTF::NextUTF8(&ptr, end);
if (u < 0) {
break;
}
if (!fOwner->codeUnitHasProperty(charStart - text,
SkUnicode::CodeUnitFlags::kGraphemeStart)) {
continue;
}
SkScalar w = font.measureText(charStart, ptr - charStart, SkTextEncoding::kUTF8);
if (charStart < split) {
prefixWidth += w;
}
totalWidth += w;
}
if (totalWidth > 0) {
return SkDoubleToScalar(fWidth * (prefixWidth / totalWidth));
}
return 0;
}
auto shift = ch - fTextRange.start;
auto ratio = shift * 1.0 / fTextRange.width();
return SkDoubleToScalar(fWidth * ratio);
}
SkScalar Cluster::sizeFromChar(TextIndex ch) const {
if (ch < fTextRange.start || ch + 1 >= fTextRange.end) {
return 0;
}
return fWidth - sizeToChar(ch + 1);
}
size_t Cluster::roundPos(SkScalar s) const {
auto ratio = (s * 1.0) / fWidth;
return sk_double_floor2int(ratio * size());
}
SkScalar Cluster::trimmedWidth(size_t pos) const {
// Find the width until the pos and return the min between trimmedWidth and the width(pos)
// We don't have to take in account cluster shift since it's the same for 0 and for pos
auto& run = fOwner->run(fRunIndex);
return std::min(run.positionX(pos) - run.positionX(fStart), fWidth);
}
SkScalar Run::positionX(size_t pos) const {
return posX(pos) + (fJustificationShifts.empty() ? 0 : fJustificationShifts[pos].fY);
}
PlaceholderStyle* Run::placeholderStyle() const {
if (isPlaceholder()) {
return &fOwner->placeholders()[fPlaceholderIndex].fStyle;
} else {
return nullptr;
}
}
bool Run::isResolved() const {
for (auto glyph : this->glyphs()) {
if (glyph == 0) {
return false;
}
}
return true;
}
Run* Cluster::runOrNull() const {
if (fRunIndex >= fOwner->runs().size()) {
return nullptr;
}
return &fOwner->run(fRunIndex);
}
Run& Cluster::run() const {
SkASSERT(fRunIndex < fOwner->runs().size());
return fOwner->run(fRunIndex);
}
SkFont Cluster::font() const {
SkASSERT(fRunIndex < fOwner->runs().size());
return fOwner->run(fRunIndex).font();
}
bool Cluster::isSoftBreak() const {
return fOwner->codeUnitHasProperty(fTextRange.end,
SkUnicode::CodeUnitFlags::kSoftLineBreakBefore);
}
bool Cluster::isGraphemeBreak() const {
return fOwner->codeUnitHasProperty(fTextRange.end, SkUnicode::CodeUnitFlags::kGraphemeStart);
}
} // namespace textlayout
} // namespace skia