Debian Codegraph @

modules/skparagraph/src/ParagraphImpl.cpp

raw
1 // Copyright 2019 Google LLC.
2 #include "include/core/SkCanvas.h"
3 #include "include/core/SkFontMetrics.h"
4 #include "include/core/SkMatrix.h"
5 #include "include/core/SkPath.h"
6 #include "include/core/SkPathBuilder.h"
7 #include "include/core/SkPictureRecorder.h"
8 #include "include/core/SkSpan.h"
9 #include "include/core/SkTypeface.h"
10 #include "include/private/base/SkTFitsIn.h"
11 #include "include/private/base/SkTo.h"
12 #include "modules/skparagraph/include/Metrics.h"
13 #include "modules/skparagraph/include/Paragraph.h"
14 #include "modules/skparagraph/include/ParagraphPainter.h"
15 #include "modules/skparagraph/include/ParagraphStyle.h"
16 #include "modules/skparagraph/include/TextStyle.h"
17 #include "modules/skparagraph/src/OneLineShaper.h"
18 #include "modules/skparagraph/src/ParagraphImpl.h"
19 #include "modules/skparagraph/src/ParagraphPainterImpl.h"
20 #include "modules/skparagraph/src/Run.h"
21 #include "modules/skparagraph/src/TextLine.h"
22 #include "modules/skparagraph/src/TextWrapper.h"
23 #include "modules/skunicode/include/SkUnicode.h"
24 #include "src/base/SkUTF.h"
25 #include "src/core/SkTextBlobPriv.h"
26
27 #include <algorithm>
28 #include <cfloat>
29 #include <cmath>
30 #include <utility>
31
32 using namespace skia_private;
33
34 namespace skia {
35 namespace textlayout {
36
37 namespace {
38
39 SkScalar littleRound(SkScalar a) {
40 // This rounding is done to match Flutter tests. Must be removed..
41 auto val = std::fabs(a);
42 if (val < 10000) {
43 return SkScalarRoundToScalar(a * 100.0)/100.0;
44 } else if (val < 100000) {
45 return SkScalarRoundToScalar(a * 10.0)/10.0;
46 } else {
47 return SkScalarFloorToScalar(a);
48 }
49 }
50 } // namespace
51
52 TextRange operator*(const TextRange& a, const TextRange& b) {
53 if (a.start == b.start && a.end == b.end) return a;
54 auto begin = std::max(a.start, b.start);
55 auto end = std::min(a.end, b.end);
56 return end > begin ? TextRange(begin, end) : EMPTY_TEXT;
57 }
58
59 Paragraph::Paragraph(ParagraphStyle style, sk_sp<FontCollection> fonts)
60 : fFontCollection(std::move(fonts))
61 , fParagraphStyle(std::move(style))
62 , fAlphabeticBaseline(0)
63 , fIdeographicBaseline(0)
64 , fHeight(0)
65 , fWidth(0)
66 , fMaxIntrinsicWidth(0)
67 , fMinIntrinsicWidth(0)
68 , fLongestLine(0)
69 , fExceededMaxLines(0)
70 {
71 SkASSERT(fFontCollection);
72 }
73
74 ParagraphImpl::ParagraphImpl(const SkString& text,
75 ParagraphStyle style,
76 TArray<Block, true> blocks,
77 TArray<Placeholder, true> placeholders,
78 sk_sp<FontCollection> fonts,
79 sk_sp<SkUnicode> unicode)
80 : Paragraph(std::move(style), std::move(fonts))
81 , fTextStyles(std::move(blocks))
82 , fPlaceholders(std::move(placeholders))
83 , fText(text)
84 , fState(kUnknown)
85 , fUnresolvedGlyphs(0)
86 , fPicture(nullptr)
87 , fStrutMetrics(false)
88 , fOldWidth(0)
89 , fOldHeight(0)
90 , fUnicode(std::move(unicode))
91 , fHasLineBreaks(false)
92 , fHasWhitespacesInside(false)
93 , fTrailingSpaces(0)
94 {
95 SkASSERT(fUnicode);
96 }
97
98 ParagraphImpl::ParagraphImpl(const std::u16string& utf16text,
99 ParagraphStyle style,
100 TArray<Block, true> blocks,
101 TArray<Placeholder, true> placeholders,
102 sk_sp<FontCollection> fonts,
103 sk_sp<SkUnicode> unicode)
104 : ParagraphImpl(SkString(),
105 std::move(style),
106 std::move(blocks),
107 std::move(placeholders),
108 std::move(fonts),
109 std::move(unicode))
110 {
111 SkASSERT(fUnicode);
112 fText = SkUnicode::convertUtf16ToUtf8(utf16text);
113 }
114
115 ParagraphImpl::~ParagraphImpl() = default;
116
117 int32_t ParagraphImpl::unresolvedGlyphs() {
118 if (fState < kShaped) {
119 return -1;
120 }
121
122 return fUnresolvedGlyphs;
123 }
124
125 std::unordered_set<SkUnichar> ParagraphImpl::unresolvedCodepoints() {
126 return fUnresolvedCodepoints;
127 }
128
129 void ParagraphImpl::addUnresolvedCodepoints(TextRange textRange) {
130 fUnicode->forEachCodepoint(
131 &fText[textRange.start], textRange.width(),
132 [&](SkUnichar unichar, int32_t start, int32_t end, int32_t count) {
133 fUnresolvedCodepoints.emplace(unichar);
134 }
135 );
136 }
137
138 void ParagraphImpl::layout(SkScalar rawWidth) {
139 // TODO: This rounding is done to match Flutter tests. Must be removed...
140 auto floorWidth = rawWidth;
141 if (getApplyRoundingHack()) {
142 floorWidth = SkScalarFloorToScalar(floorWidth);
143 }
144
145 if ((!SkIsFinite(rawWidth) || fLongestLine <= floorWidth) &&
146 fState >= kLineBroken &&
147 fLines.size() == 1 && fLines.front().ellipsis() == nullptr) {
148 // Most common case: one line of text (and one line is never justified, so no cluster shifts)
149 // We cannot mark it as kLineBroken because the new width can be bigger than the old width
150 fWidth = floorWidth;
151 fState = kShaped;
152 } else if (fState >= kLineBroken && fOldWidth != floorWidth) {
153 // We can use the results from SkShaper but have to do EVERYTHING ELSE again
154 fState = kShaped;
155 } else {
156 // Nothing changed case: we can reuse the data from the last layout
157 }
158
159 if (fState < kShaped) {
160 // Check if we have the text in the cache and don't need to shape it again
161 if (!fFontCollection->getParagraphCache()->findParagraph(this)) {
162 if (fState < kIndexed) {
163 // This only happens once at the first layout; the text is immutable
164 // and there is no reason to repeat it
165 if (this->computeCodeUnitProperties()) {
166 fState = kIndexed;
167 }
168 }
169 this->fRuns.clear();
170 this->fClusters.clear();
171 this->fClustersIndexFromCodeUnit.clear();
172 this->fClustersIndexFromCodeUnit.push_back_n(fText.size() + 1, EMPTY_INDEX);
173 if (!this->shapeTextIntoEndlessLine()) {
174 this->resetContext();
175 // TODO: merge the two next calls - they always come together
176 this->resolveStrut();
177 this->computeEmptyMetrics();
178 this->fLines.clear();
179
180 // Set the important values that are not zero
181 fWidth = floorWidth;
182 fHeight = fEmptyMetrics.height();
183 if (fParagraphStyle.getStrutStyle().getStrutEnabled() &&
184 fParagraphStyle.getStrutStyle().getForceStrutHeight()) {
185 fHeight = fStrutMetrics.height();
186 }
187 fAlphabeticBaseline = fEmptyMetrics.alphabeticBaseline();
188 fIdeographicBaseline = fEmptyMetrics.ideographicBaseline();
189 fLongestLine = FLT_MIN - FLT_MAX; // That is what flutter has
190 fMinIntrinsicWidth = 0;
191 fMaxIntrinsicWidth = 0;
192 this->fOldWidth = floorWidth;
193 this->fOldHeight = this->fHeight;
194
195 return;
196 } else {
197 // Add the paragraph to the cache
198 fFontCollection->getParagraphCache()->updateParagraph(this);
199 }
200 }
201 fState = kShaped;
202 }
203
204 if (fState == kShaped) {
205 this->resetContext();
206 this->resolveStrut();
207 this->computeEmptyMetrics();
208 this->fLines.clear();
209 this->breakShapedTextIntoLines(floorWidth);
210 fState = kLineBroken;
211 }
212
213 if (fState == kLineBroken) {
214 // Build the picture lazily not until we actually have to paint (or never)
215 this->resetShifts();
216 this->formatLines(fWidth);
217 fState = kFormatted;
218 }
219
220 this->fOldWidth = floorWidth;
221 this->fOldHeight = this->fHeight;
222
223 if (getApplyRoundingHack()) {
224 // TODO: This rounding is done to match Flutter tests. Must be removed...
225 fMinIntrinsicWidth = littleRound(fMinIntrinsicWidth);
226 fMaxIntrinsicWidth = littleRound(fMaxIntrinsicWidth);
227 }
228
229 // TODO: This is strictly Flutter thing. Must be factored out into some flutter code
230 if (fParagraphStyle.getMaxLines() == 1 ||
231 (fParagraphStyle.unlimited_lines() && fParagraphStyle.ellipsized())) {
232 fMinIntrinsicWidth = fMaxIntrinsicWidth;
233 }
234
235 // TODO: Since min and max are calculated differently it's possible to get a rounding error
236 // that would make min > max. Sort it out later, make it the same for now
237 if (fMaxIntrinsicWidth < fMinIntrinsicWidth) {
238 fMaxIntrinsicWidth = fMinIntrinsicWidth;
239 }
240
241 //SkDebugf("layout('%s', %f): %f %f\n", fText.c_str(), rawWidth, fMinIntrinsicWidth, fMaxIntrinsicWidth);
242 }
243
244 void ParagraphImpl::paint(SkCanvas* canvas, SkScalar x, SkScalar y) {
245 CanvasParagraphPainter painter(canvas);
246 paint(&painter, x, y);
247 }
248
249 void ParagraphImpl::paint(ParagraphPainter* painter, SkScalar x, SkScalar y) {
250 for (auto& line : fLines) {
251 line.paint(painter, x, y);
252 }
253 }
254
255 void ParagraphImpl::resetContext() {
256 fAlphabeticBaseline = 0;
257 fHeight = 0;
258 fWidth = 0;
259 fIdeographicBaseline = 0;
260 fMaxIntrinsicWidth = 0;
261 fMinIntrinsicWidth = 0;
262 fLongestLine = 0;
263 fMaxWidthWithTrailingSpaces = 0;
264 fExceededMaxLines = false;
265 }
266
267 // shapeTextIntoEndlessLine is the thing that calls this method
268 bool ParagraphImpl::computeCodeUnitProperties() {
269
270 if (nullptr == fUnicode) {
271 return false;
272 }
273
274 // Get bidi regions
275 auto textDirection = fParagraphStyle.getTextDirection() == TextDirection::kLtr
276 ? SkUnicode::TextDirection::kLTR
277 : SkUnicode::TextDirection::kRTL;
278 if (!fUnicode->getBidiRegions(fText.c_str(), fText.size(), textDirection, &fBidiRegions)) {
279 return false;
280 }
281
282 // Collect all spaces and some extra information
283 // (and also substitute \t with a space while we are at it)
284 if (!fUnicode->computeCodeUnitFlags(&fText[0],
285 fText.size(),
286 this->paragraphStyle().getReplaceTabCharacters(),
287 &fCodeUnitProperties)) {
288 return false;
289 }
290
291 // Get some information about trailing spaces / hard line breaks
292 fTrailingSpaces = fText.size();
293 TextIndex firstWhitespace = EMPTY_INDEX;
294 for (int i = 0; i < fCodeUnitProperties.size(); ++i) {
295 auto flags = fCodeUnitProperties[i];
296 if (SkUnicode::hasPartOfWhiteSpaceBreakFlag(flags)) {
297 if (fTrailingSpaces == fText.size()) {
298 fTrailingSpaces = i;
299 }
300 if (firstWhitespace == EMPTY_INDEX) {
301 firstWhitespace = i;
302 }
303 } else {
304 fTrailingSpaces = fText.size();
305 }
306 if (SkUnicode::hasHardLineBreakFlag(flags)) {
307 fHasLineBreaks = true;
308 }
309 }
310
311 if (firstWhitespace < fTrailingSpaces) {
312 fHasWhitespacesInside = true;
313 }
314
315 return true;
316 }
317
318 static bool is_ascii_7bit_space(int c) {
319 SkASSERT(c >= 0 && c <= 127);
320
321 // Extracted from https://en.wikipedia.org/wiki/Whitespace_character
322 //
323 enum WS {
324 kHT = 9,
325 kLF = 10,
326 kVT = 11,
327 kFF = 12,
328 kCR = 13,
329 kSP = 32, // too big to use as shift
330 };
331 #define M(shift) (1 << (shift))
332 constexpr uint32_t kSpaceMask = M(kHT) | M(kLF) | M(kVT) | M(kFF) | M(kCR);
333 // we check for Space (32) explicitly, since it is too large to shift
334 return (c == kSP) || (c <= 31 && (kSpaceMask & M(c)));
335 #undef M
336 }
337
338 Cluster::Cluster(ParagraphImpl* owner,
339 RunIndex runIndex,
340 size_t start,
341 size_t end,
342 SkSpan<const char> text,
343 SkScalar width,
344 SkScalar height)
345 : fOwner(owner)
346 , fRunIndex(runIndex)
347 , fTextRange(text.begin() - fOwner->text().begin(), text.end() - fOwner->text().begin())
348 , fGraphemeRange(EMPTY_RANGE)
349 , fStart(start)
350 , fEnd(end)
351 , fWidth(width)
352 , fHeight(height)
353 , fHalfLetterSpacing(0.0)
354 , fIsIdeographic(false) {
355 size_t whiteSpacesBreakLen = 0;
356 size_t intraWordBreakLen = 0;
357
358 const char* ch = text.data();
359 const char* chEnd = ch + text.size();
360 if (chEnd - ch == 1 && *(const unsigned char*)ch <= 0x7F) {
361 // I am not even sure it's worth it if we do not save a unicode call
362 if (is_ascii_7bit_space(*ch)) {
363 ++whiteSpacesBreakLen;
364 }
365 } else {
366 for (auto i = fTextRange.start; i < fTextRange.end; ++i) {
367 if (fOwner->codeUnitHasProperty(i, SkUnicode::CodeUnitFlags::kPartOfWhiteSpaceBreak)) {
368 ++whiteSpacesBreakLen;
369 }
370 if (fOwner->codeUnitHasProperty(i, SkUnicode::CodeUnitFlags::kPartOfIntraWordBreak)) {
371 ++intraWordBreakLen;
372 }
373 if (fOwner->codeUnitHasProperty(i, SkUnicode::CodeUnitFlags::kIdeographic)) {
374 fIsIdeographic = true;
375 }
376 }
377 }
378
379 fIsWhiteSpaceBreak = whiteSpacesBreakLen == fTextRange.width();
380 fIsIntraWordBreak = intraWordBreakLen == fTextRange.width();
381 fIsHardBreak = fOwner->codeUnitHasProperty(fTextRange.end,
382 SkUnicode::CodeUnitFlags::kHardLineBreakBefore);
383 }
384
385 SkScalar Run::calculateWidth(size_t start, size_t end, bool clip) const {
386 SkASSERT(start <= end);
387 // clip |= end == size(); // Clip at the end of the run?
388 auto correction = 0.0f;
389 if (end > start && !fJustificationShifts.empty()) {
390 // This is not a typo: we are using Point as a pair of SkScalars
391 correction = fJustificationShifts[end - 1].fX -
392 fJustificationShifts[start].fY;
393 }
394 return posX(end) - posX(start) + correction;
395 }
396
397 // In some cases we apply spacing to glyphs first and then build the cluster table, in some we do
398 // the opposite - just to optimize the most common case.
399 void ParagraphImpl::applySpacingAndBuildClusterTable() {
400
401 // Check all text styles to see what we have to do (if anything)
402 size_t letterSpacingStyles = 0;
403 bool hasWordSpacing = false;
404 for (auto& block : fTextStyles) {
405 if (block.fRange.width() > 0) {
406 if (!SkScalarNearlyZero(block.fStyle.getLetterSpacing())) {
407 ++letterSpacingStyles;
408 }
409 if (!SkScalarNearlyZero(block.fStyle.getWordSpacing())) {
410 hasWordSpacing = true;
411 }
412 }
413 }
414
415 if (letterSpacingStyles == 0 && !hasWordSpacing) {
416 // We don't have to do anything about spacing (most common case)
417 this->buildClusterTable();
418 return;
419 }
420
421 if (letterSpacingStyles == 1 && !hasWordSpacing && fTextStyles.size() == 1 &&
422 fTextStyles[0].fRange.width() == fText.size() && fRuns.size() == 1) {
423 // We have to letter space the entire paragraph (second most common case)
424 auto& run = fRuns[0];
425 auto& style = fTextStyles[0].fStyle;
426 run.addLetterSpacesEvenly(style.getLetterSpacing());
427
428 this->buildClusterTable();
429
430 // This is something Flutter requires
431 for (auto& cluster : fClusters) {
432 cluster.setHalfLetterSpacing(style.getLetterSpacing() / 2);
433 }
434
435 return;
436 }
437
438 // The complex case: many text styles with spacing (possibly not adjusted to glyphs)
439 this->buildClusterTable();
440
441 // Walk through all the clusters in the direction of shaped text
442 // (we have to walk through the styles in the same order, too)
443 // Not breaking the iteration on every run!
444 SkScalar shift = 0;
445 bool soFarWhitespacesOnly = true;
446 bool wordSpacingPending = false;
447 Cluster* lastSpaceCluster = nullptr;
448 for (auto& run : fRuns) {
449
450 // Skip placeholder runs
451 if (run.isPlaceholder()) {
452 continue;
453 }
454
455 run.iterateThroughClusters([this, &run, &shift, &soFarWhitespacesOnly, &wordSpacingPending, &lastSpaceCluster](Cluster* cluster) {
456 // Shift the cluster (shift collected from the previous clusters)
457 run.shift(cluster, shift);
458
459 // Synchronize styles (one cluster can be covered by few styles)
460 Block* currentStyle = fTextStyles.begin();
461 while (!cluster->startsIn(currentStyle->fRange)) {
462 currentStyle++;
463 SkASSERT(currentStyle != fTextStyles.end());
464 }
465
466 SkASSERT(!currentStyle->fStyle.isPlaceholder());
467
468 // Process word spacing
469 if (currentStyle->fStyle.getWordSpacing() != 0) {
470 if (cluster->isWhitespaceBreak() && cluster->isSoftBreak()) {
471 if (!soFarWhitespacesOnly) {
472 lastSpaceCluster = cluster;
473 wordSpacingPending = true;
474 }
475 } else if (wordSpacingPending) {
476 SkScalar spacing = currentStyle->fStyle.getWordSpacing();
477 if (cluster->fRunIndex != lastSpaceCluster->fRunIndex) {
478 // If the last space cluster belongs to the previous run
479 // we have to extend that cluster and that run
480 lastSpaceCluster->run().addSpacesAtTheEnd(spacing, lastSpaceCluster);
481 lastSpaceCluster->run().extend(lastSpaceCluster, spacing);
482 } else {
483 run.addSpacesAtTheEnd(spacing, lastSpaceCluster);
484 }
485
486 run.shift(cluster, spacing);
487 shift += spacing;
488 wordSpacingPending = false;
489 }
490 }
491 // Process letter spacing (it will be cancelled out for Script languages
492 if ((currentStyle->fStyle.getLetterSpacing() != 0)) {
493 shift +=
494 run.addLetterSpacesEvenly(currentStyle->fStyle.getLetterSpacing(), cluster);
495 }
496
497 if (soFarWhitespacesOnly && !cluster->isWhitespaceBreak()) {
498 soFarWhitespacesOnly = false;
499 }
500 });
501 }
502 }
503
504 // Clusters in the order of the input text
505 void ParagraphImpl::buildClusterTable() {
506 // It's possible that one grapheme includes few runs; we cannot handle it
507 // so we break graphemes by the runs instead
508 // It's not the ideal solution and has to be revisited later
509 int cluster_count = 1;
510 for (auto& run : fRuns) {
511 cluster_count += run.isPlaceholder() ? 1 : run.size();
512 fCodeUnitProperties[run.fTextRange.start] |= SkUnicode::CodeUnitFlags::kGraphemeStart;
513 fCodeUnitProperties[run.fTextRange.start] |= SkUnicode::CodeUnitFlags::kGlyphClusterStart;
514 }
515 if (!fRuns.empty()) {
516 fCodeUnitProperties[fRuns.back().textRange().end] |= SkUnicode::CodeUnitFlags::kGraphemeStart;
517 fCodeUnitProperties[fRuns.back().textRange().end] |= SkUnicode::CodeUnitFlags::kGlyphClusterStart;
518 }
519 fClusters.reserve_exact(fClusters.size() + cluster_count);
520
521 // Walk through all the run in the direction of input text
522 for (auto& run : fRuns) {
523 auto runIndex = run.index();
524 auto runStart = fClusters.size();
525 if (run.isPlaceholder()) {
526 // Add info to cluster indexes table (text -> cluster)
527 for (auto i = run.textRange().start; i < run.textRange().end; ++i) {
528 fClustersIndexFromCodeUnit[i] = fClusters.size();
529 }
530 // There are no glyphs but we want to have one cluster
531 fClusters.emplace_back(this, runIndex, 0ul, 1ul, this->text(run.textRange()), run.advance().fX, run.advance().fY);
532 fCodeUnitProperties[run.textRange().start] |= SkUnicode::CodeUnitFlags::kSoftLineBreakBefore;
533 fCodeUnitProperties[run.textRange().end] |= SkUnicode::CodeUnitFlags::kSoftLineBreakBefore;
534 } else {
535 // Walk through the glyph in the direction of input text
536 run.iterateThroughClustersInTextOrder([runIndex, this](size_t glyphStart,
537 size_t glyphEnd,
538 size_t charStart,
539 size_t charEnd,
540 SkScalar width,
541 SkScalar height) {
542 SkASSERT(charEnd >= charStart);
543 // Add info to cluster indexes table (text -> cluster)
544 for (auto i = charStart; i < charEnd; ++i) {
545 fClustersIndexFromCodeUnit[i] = fClusters.size();
546 }
547 SkSpan<const char> text(fText.c_str() + charStart, charEnd - charStart);
548 fClusters.emplace_back(this, runIndex, glyphStart, glyphEnd, text, width, height);
549 fCodeUnitProperties[charStart] |= SkUnicode::CodeUnitFlags::kGlyphClusterStart;
550 });
551 }
552 fCodeUnitProperties[run.textRange().start] |= SkUnicode::CodeUnitFlags::kGlyphClusterStart;
553
554 run.setClusterRange(runStart, fClusters.size());
555 fMaxIntrinsicWidth += run.advance().fX;
556 }
557 fClustersIndexFromCodeUnit[fText.size()] = fClusters.size();
558 fClusters.emplace_back(this, EMPTY_RUN, 0, 0, this->text({fText.size(), fText.size()}), 0, 0);
559 }
560
561 bool ParagraphImpl::shapeTextIntoEndlessLine() {
562
563 if (fText.size() == 0) {
564 return false;
565 }
566
567 fUnresolvedCodepoints.clear();
568 fFontSwitches.clear();
569
570 OneLineShaper oneLineShaper(this);
571 auto result = oneLineShaper.shape();
572 fUnresolvedGlyphs = oneLineShaper.unresolvedGlyphs();
573
574 this->applySpacingAndBuildClusterTable();
575
576 return result;
577 }
578
579 void ParagraphImpl::breakShapedTextIntoLines(SkScalar maxWidth) {
580
581 if (!fHasLineBreaks &&
582 !fHasWhitespacesInside &&
583 fPlaceholders.size() == 1 &&
584 fRuns.size() == 1 && fRuns[0].fAdvance.fX <= maxWidth) {
585 // This is a short version of a line breaking when we know that:
586 // 1. We have only one line of text
587 // 2. It's shaped into a single run
588 // 3. There are no placeholders
589 // 4. There are no linebreaks (which will format text into multiple lines)
590 // 5. There are no whitespaces so the minIntrinsicWidth=maxIntrinsicWidth
591 // (To think about that, the last condition is not quite right;
592 // we should calculate minIntrinsicWidth by soft line breaks.
593 // However, it's how it's done in Flutter now)
594 auto& run = this->fRuns[0];
595 auto advance = run.advance();
596 auto textRange = TextRange(0, this->text().size());
597 auto textExcludingSpaces = TextRange(0, fTrailingSpaces);
598 InternalLineMetrics metrics(this->strutForceHeight());
599 metrics.add(&run);
600 auto disableFirstAscent = this->paragraphStyle().getTextHeightBehavior() &
601 TextHeightBehavior::kDisableFirstAscent;
602 auto disableLastDescent = this->paragraphStyle().getTextHeightBehavior() &
603 TextHeightBehavior::kDisableLastDescent;
604 if (disableFirstAscent) {
605 metrics.fAscent = metrics.fRawAscent;
606 }
607 if (disableLastDescent) {
608 metrics.fDescent = metrics.fRawDescent;
609 }
610 if (this->strutEnabled()) {
611 this->strutMetrics().updateLineMetrics(metrics);
612 }
613 ClusterIndex trailingSpaces = fClusters.size();
614 do {
615 --trailingSpaces;
616 auto& cluster = fClusters[trailingSpaces];
617 if (!cluster.isWhitespaceBreak()) {
618 ++trailingSpaces;
619 break;
620 }
621 advance.fX -= cluster.width();
622 } while (trailingSpaces != 0);
623
624 advance.fY = metrics.height();
625 auto clusterRange = ClusterRange(0, trailingSpaces);
626 auto clusterRangeWithGhosts = ClusterRange(0, this->clusters().size() - 1);
627 this->addLine(SkPoint::Make(0, 0), advance,
628 textExcludingSpaces, textRange, textRange,
629 clusterRange, clusterRangeWithGhosts, run.advance().x(),
630 metrics);
631
632 fLongestLine = nearlyZero(advance.fX) ? run.advance().fX : advance.fX;
633 fHeight = advance.fY;
634 fWidth = maxWidth;
635 fMaxIntrinsicWidth = run.advance().fX;
636 fMinIntrinsicWidth = advance.fX;
637 fAlphabeticBaseline = fLines.empty() ? fEmptyMetrics.alphabeticBaseline() : fLines.front().alphabeticBaseline();
638 fIdeographicBaseline = fLines.empty() ? fEmptyMetrics.ideographicBaseline() : fLines.front().ideographicBaseline();
639 fExceededMaxLines = false;
640 return;
641 }
642
643 TextWrapper textWrapper;
644 textWrapper.breakTextIntoLines(
645 this,
646 maxWidth,
647 [&](TextRange textExcludingSpaces,
648 TextRange text,
649 TextRange textWithNewlines,
650 ClusterRange clusters,
651 ClusterRange clustersWithGhosts,
652 SkScalar widthWithSpaces,
653 size_t startPos,
654 size_t endPos,
655 SkVector offset,
656 SkVector advance,
657 InternalLineMetrics metrics,
658 bool addEllipsis) {
659 // TODO: Take in account clipped edges
660 auto& line = this->addLine(offset, advance, textExcludingSpaces, text, textWithNewlines, clusters, clustersWithGhosts, widthWithSpaces, metrics);
661 if (addEllipsis) {
662 line.createEllipsis(maxWidth, this->getEllipsis(), true);
663 }
664 fLongestLine = std::max(fLongestLine, nearlyZero(line.width()) ? widthWithSpaces : line.width());
665 });
666
667 fHeight = textWrapper.height();
668 fWidth = maxWidth;
669 fMaxIntrinsicWidth = textWrapper.maxIntrinsicWidth();
670 fMinIntrinsicWidth = textWrapper.minIntrinsicWidth();
671 fAlphabeticBaseline = fLines.empty() ? fEmptyMetrics.alphabeticBaseline() : fLines.front().alphabeticBaseline();
672 fIdeographicBaseline = fLines.empty() ? fEmptyMetrics.ideographicBaseline() : fLines.front().ideographicBaseline();
673 fExceededMaxLines = textWrapper.exceededMaxLines();
674 }
675
676 void ParagraphImpl::formatLines(SkScalar maxWidth) {
677 auto effectiveAlign = fParagraphStyle.effective_align();
678 const bool isLeftAligned = effectiveAlign == TextAlign::kLeft
679 || (effectiveAlign == TextAlign::kJustify && fParagraphStyle.getTextDirection() == TextDirection::kLtr);
680
681 if (!SkIsFinite(maxWidth) && !isLeftAligned) {
682 // Special case: clean all text in case of maxWidth == INF & align != left
683 // We had to go through shaping though because we need all the measurement numbers
684 fLines.clear();
685 return;
686 }
687
688 for (auto& line : fLines) {
689 line.format(effectiveAlign, maxWidth);
690 }
691 }
692
693 void ParagraphImpl::resolveStrut() {
694 auto strutStyle = this->paragraphStyle().getStrutStyle();
695 if (!strutStyle.getStrutEnabled() || strutStyle.getFontSize() < 0) {
696 return;
697 }
698
699 std::vector<sk_sp<SkTypeface>> typefaces = fFontCollection->findTypefaces(strutStyle.getFontFamilies(), strutStyle.getFontStyle(), std::nullopt);
700 if (typefaces.empty()) {
701 SkDEBUGF("Could not resolve strut font\n");
702 return;
703 }
704
705 SkFont font(typefaces.front(), strutStyle.getFontSize());
706 SkFontMetrics metrics;
707 font.getMetrics(&metrics);
708 const SkScalar strutLeading = strutStyle.getLeading() < 0 ? 0 : strutStyle.getLeading() * strutStyle.getFontSize();
709
710 if (strutStyle.getHeightOverride()) {
711 SkScalar strutAscent = 0.0f;
712 SkScalar strutDescent = 0.0f;
713 // The half leading flag doesn't take effect unless there's height override.
714 if (strutStyle.getHalfLeading()) {
715 const auto occupiedHeight = metrics.fDescent - metrics.fAscent;
716 auto flexibleHeight = strutStyle.getHeight() * strutStyle.getFontSize() - occupiedHeight;
717 // Distribute the flexible height evenly over and under.
718 flexibleHeight /= 2;
719 strutAscent = metrics.fAscent - flexibleHeight;
720 strutDescent = metrics.fDescent + flexibleHeight;
721 } else {
722 const SkScalar strutMetricsHeight = metrics.fDescent - metrics.fAscent + metrics.fLeading;
723 const auto strutHeightMultiplier = strutMetricsHeight == 0
724 ? strutStyle.getHeight()
725 : strutStyle.getHeight() * strutStyle.getFontSize() / strutMetricsHeight;
726 strutAscent = metrics.fAscent * strutHeightMultiplier;
727 strutDescent = metrics.fDescent * strutHeightMultiplier;
728 }
729 fStrutMetrics = InternalLineMetrics(
730 strutAscent,
731 strutDescent,
732 strutLeading,
733 metrics.fAscent, metrics.fDescent, metrics.fLeading);
734 } else {
735 fStrutMetrics = InternalLineMetrics(
736 metrics.fAscent,
737 metrics.fDescent,
738 strutLeading);
739 }
740 fStrutMetrics.setForceStrut(this->paragraphStyle().getStrutStyle().getForceStrutHeight());
741 }
742
743 BlockRange ParagraphImpl::findAllBlocks(TextRange textRange) {
744 BlockIndex begin = EMPTY_BLOCK;
745 BlockIndex end = EMPTY_BLOCK;
746 for (int index = 0; index < fTextStyles.size(); ++index) {
747 auto& block = fTextStyles[index];
748 if (block.fRange.end <= textRange.start) {
749 continue;
750 }
751 if (block.fRange.start >= textRange.end) {
752 break;
753 }
754 if (begin == EMPTY_BLOCK) {
755 begin = index;
756 }
757 end = index;
758 }
759
760 if (begin == EMPTY_INDEX || end == EMPTY_INDEX) {
761 // It's possible if some text is not covered with any text style
762 // Not in Flutter but in direct use of SkParagraph
763 return EMPTY_RANGE;
764 }
765
766 return { begin, end + 1 };
767 }
768
769 TextLine& ParagraphImpl::addLine(SkVector offset,
770 SkVector advance,
771 TextRange textExcludingSpaces,
772 TextRange text,
773 TextRange textIncludingNewLines,
774 ClusterRange clusters,
775 ClusterRange clustersWithGhosts,
776 SkScalar widthWithSpaces,
777 InternalLineMetrics sizes) {
778 // Define a list of styles that covers the line
779 auto blocks = findAllBlocks(textExcludingSpaces);
780 return fLines.emplace_back(this, offset, advance, blocks,
781 textExcludingSpaces, text, textIncludingNewLines,
782 clusters, clustersWithGhosts, widthWithSpaces, sizes);
783 }
784
785 // Returns a vector of bounding boxes that enclose all text between
786 // start and end glyph indexes, including start and excluding end
787 std::vector<TextBox> ParagraphImpl::getRectsForRange(unsigned start,
788 unsigned end,
789 RectHeightStyle rectHeightStyle,
790 RectWidthStyle rectWidthStyle) {
791 std::vector<TextBox> results;
792 if (fText.isEmpty()) {
793 if (start == 0 && end > 0) {
794 // On account of implied "\n" that is always at the end of the text
795 //SkDebugf("getRectsForRange(%d, %d): %f\n", start, end, fHeight);
796 results.emplace_back(SkRect::MakeXYWH(0, 0, 0, fHeight), fParagraphStyle.getTextDirection());
797 }
798 return results;
799 }
800
801 this->ensureUTF16Mapping();
802
803 if (start >= end || start > SkToSizeT(fUTF8IndexForUTF16Index.size()) || end == 0) {
804 return results;
805 }
806
807 // Adjust the text to grapheme edges
808 // Apparently, text editor CAN move inside graphemes but CANNOT select a part of it.
809 // I don't know why - the solution I have here returns an empty box for every query that
810 // does not contain an end of a grapheme.
811 // Once a cursor is inside a complex grapheme I can press backspace and cause trouble.
812 // To avoid any problems, I will not allow any selection of a part of a grapheme.
813 // One flutter test fails because of it but the editing experience is correct
814 // (although you have to press the cursor many times before it moves to the next grapheme).
815 TextRange text(fText.size(), fText.size());
816 // TODO: This is probably a temp change that makes SkParagraph work as TxtLib
817 // (so we can compare the results). We now include in the selection box only the graphemes
818 // that belongs to the given [start:end) range entirely (not the ones that intersect with it)
819 if (start < SkToSizeT(fUTF8IndexForUTF16Index.size())) {
820 auto utf8 = fUTF8IndexForUTF16Index[start];
821 // If start points to a trailing surrogate, skip it
822 if (start > 0 && fUTF8IndexForUTF16Index[start - 1] == utf8) {
823 utf8 = fUTF8IndexForUTF16Index[start + 1];
824 }
825 text.start = this->findNextGraphemeBoundary(utf8);
826 }
827 if (end < SkToSizeT(fUTF8IndexForUTF16Index.size())) {
828 auto utf8 = this->findPreviousGraphemeBoundary(fUTF8IndexForUTF16Index[end]);
829 text.end = utf8;
830 }
831 //SkDebugf("getRectsForRange(%d,%d) -> (%d:%d)\n", start, end, text.start, text.end);
832 for (auto& line : fLines) {
833 auto lineText = line.textWithNewlines();
834 auto intersect = lineText * text;
835 if (intersect.empty() && lineText.start != text.start) {
836 continue;
837 }
838
839 line.getRectsForRange(intersect, rectHeightStyle, rectWidthStyle, results);
840 }
841 /*
842 SkDebugf("getRectsForRange(%d, %d)\n", start, end);
843 for (auto& r : results) {
844 r.rect.fLeft = littleRound(r.rect.fLeft);
845 r.rect.fRight = littleRound(r.rect.fRight);
846 r.rect.fTop = littleRound(r.rect.fTop);
847 r.rect.fBottom = littleRound(r.rect.fBottom);
848 SkDebugf("[%f:%f * %f:%f]\n", r.rect.fLeft, r.rect.fRight, r.rect.fTop, r.rect.fBottom);
849 }
850 */
851 return results;
852 }
853
854 std::vector<TextBox> ParagraphImpl::getRectsForPlaceholders() {
855 std::vector<TextBox> boxes;
856 if (fText.isEmpty()) {
857 return boxes;
858 }
859 if (fPlaceholders.size() == 1) {
860 // We always have one fake placeholder
861 return boxes;
862 }
863 for (auto& line : fLines) {
864 line.getRectsForPlaceholders(boxes);
865 }
866 /*
867 SkDebugf("getRectsForPlaceholders('%s'): %d\n", fText.c_str(), boxes.size());
868 for (auto& r : boxes) {
869 r.rect.fLeft = littleRound(r.rect.fLeft);
870 r.rect.fRight = littleRound(r.rect.fRight);
871 r.rect.fTop = littleRound(r.rect.fTop);
872 r.rect.fBottom = littleRound(r.rect.fBottom);
873 SkDebugf("[%f:%f * %f:%f] %s\n", r.rect.fLeft, r.rect.fRight, r.rect.fTop, r.rect.fBottom,
874 (r.direction == TextDirection::kLtr ? "left" : "right"));
875 }
876 */
877 return boxes;
878 }
879
880 // TODO: Optimize (save cluster <-> codepoint connection)
881 PositionWithAffinity ParagraphImpl::getGlyphPositionAtCoordinate(SkScalar dx, SkScalar dy) {
882
883 if (fText.isEmpty()) {
884 return {0, Affinity::kDownstream};
885 }
886
887 this->ensureUTF16Mapping();
888
889 for (auto& line : fLines) {
890 // Let's figure out if we can stop looking
891 auto offsetY = line.offset().fY;
892 if (dy >= offsetY + line.height() && &line != &fLines.back()) {
893 // This line is not good enough
894 continue;
895 }
896
897 // This is so far the the line vertically closest to our coordinates
898 // (or the first one, or the only one - all the same)
899
900 auto result = line.getGlyphPositionAtCoordinate(dx);
901 //SkDebugf("getGlyphPositionAtCoordinate(%f, %f): %d %s\n", dx, dy, result.position,
902 // result.affinity == Affinity::kUpstream ? "up" : "down");
903 return result;
904 }
905
906 return {0, Affinity::kDownstream};
907 }
908
909 // Finds the first and last glyphs that define a word containing
910 // the glyph at index offset.
911 // By "glyph" they mean a character index - indicated by Minikin's code
912 SkRange<size_t> ParagraphImpl::getWordBoundary(unsigned offset) {
913
914 if (fWords.empty()) {
915 if (!fUnicode->getWords(fText.c_str(), fText.size(), nullptr, &fWords)) {
916 return {0, 0 };
917 }
918 }
919
920 int32_t start = 0;
921 int32_t end = 0;
922 for (size_t i = 0; i < fWords.size(); ++i) {
923 auto word = fWords[i];
924 if (word <= offset) {
925 start = word;
926 end = word;
927 } else if (word > offset) {
928 end = word;
929 break;
930 }
931 }
932
933 //SkDebugf("getWordBoundary(%d): %d - %d\n", offset, start, end);
934 return { SkToU32(start), SkToU32(end) };
935 }
936
937 void ParagraphImpl::getLineMetrics(std::vector<LineMetrics>& metrics) {
938 metrics.clear();
939 for (auto& line : fLines) {
940 metrics.emplace_back(line.getMetrics());
941 }
942 }
943
944 SkSpan<const char> ParagraphImpl::text(TextRange textRange) {
945 SkASSERT(textRange.start <= fText.size() && textRange.end <= fText.size());
946 auto start = fText.c_str() + textRange.start;
947 return SkSpan<const char>(start, textRange.width());
948 }
949
950 SkSpan<Cluster> ParagraphImpl::clusters(ClusterRange clusterRange) {
951 SkASSERT(clusterRange.start < SkToSizeT(fClusters.size()) &&
952 clusterRange.end <= SkToSizeT(fClusters.size()));
953 return SkSpan<Cluster>(&fClusters[clusterRange.start], clusterRange.width());
954 }
955
956 Cluster& ParagraphImpl::cluster(ClusterIndex clusterIndex) {
957 SkASSERT(clusterIndex < SkToSizeT(fClusters.size()));
958 return fClusters[clusterIndex];
959 }
960
961 Run& ParagraphImpl::runByCluster(ClusterIndex clusterIndex) {
962 auto start = cluster(clusterIndex);
963 return this->run(start.fRunIndex);
964 }
965
966 SkSpan<Block> ParagraphImpl::blocks(BlockRange blockRange) {
967 SkASSERT(blockRange.start < SkToSizeT(fTextStyles.size()) &&
968 blockRange.end <= SkToSizeT(fTextStyles.size()));
969 return SkSpan<Block>(&fTextStyles[blockRange.start], blockRange.width());
970 }
971
972 Block& ParagraphImpl::block(BlockIndex blockIndex) {
973 SkASSERT(blockIndex < SkToSizeT(fTextStyles.size()));
974 return fTextStyles[blockIndex];
975 }
976
977 void ParagraphImpl::setState(InternalState state) {
978 if (fState <= state) {
979 fState = state;
980 return;
981 }
982
983 fState = state;
984 switch (fState) {
985 case kUnknown:
986 SkASSERT(false);
987 /*
988 // The text is immutable and so are all the text indexing properties
989 // taken from SkUnicode
990 fCodeUnitProperties.reset();
991 fWords.clear();
992 fBidiRegions.clear();
993 fUTF8IndexForUTF16Index.reset();
994 fUTF16IndexForUTF8Index.reset();
995 */
996 [[fallthrough]];
997
998 case kIndexed:
999 fRuns.clear();
1000 fClusters.clear();
1001 [[fallthrough]];
1002
1003 case kShaped:
1004 fLines.clear();
1005 [[fallthrough]];
1006
1007 case kLineBroken:
1008 fPicture = nullptr;
1009 [[fallthrough]];
1010
1011 default:
1012 break;
1013 }
1014 }
1015
1016 void ParagraphImpl::computeEmptyMetrics() {
1017
1018 // The empty metrics is used to define the height of the empty lines
1019 // Unfortunately, Flutter has 2 different cases for that:
1020 // 1. An empty line inside the text
1021 // 2. An empty paragraph
1022 // In the first case SkParagraph takes the metrics from the default paragraph style
1023 // In the second case it should take it from the current text style
1024 bool emptyParagraph = fRuns.empty();
1025 TextStyle textStyle = paragraphStyle().getTextStyle();
1026 if (emptyParagraph && !fTextStyles.empty()) {
1027 textStyle = fTextStyles.back().fStyle;
1028 }
1029
1030 auto typefaces = fontCollection()->findTypefaces(
1031 textStyle.getFontFamilies(), textStyle.getFontStyle(), textStyle.getFontArguments());
1032 auto typeface = typefaces.empty() ? nullptr : typefaces.front();
1033
1034 SkFont font(typeface, textStyle.getFontSize());
1035 fEmptyMetrics = InternalLineMetrics(font, paragraphStyle().getStrutStyle().getForceStrutHeight());
1036
1037 if (!paragraphStyle().getStrutStyle().getForceStrutHeight() &&
1038 textStyle.getHeightOverride()) {
1039 const auto intrinsicHeight = fEmptyMetrics.height();
1040 const auto strutHeight = textStyle.getHeight() * textStyle.getFontSize();
1041 if (paragraphStyle().getStrutStyle().getHalfLeading()) {
1042 fEmptyMetrics.update(
1043 fEmptyMetrics.ascent(),
1044 fEmptyMetrics.descent(),
1045 fEmptyMetrics.leading() + strutHeight - intrinsicHeight);
1046 } else {
1047 const auto multiplier = strutHeight / intrinsicHeight;
1048 fEmptyMetrics.update(
1049 fEmptyMetrics.ascent() * multiplier,
1050 fEmptyMetrics.descent() * multiplier,
1051 fEmptyMetrics.leading() * multiplier);
1052 }
1053 }
1054
1055 if (emptyParagraph) {
1056 // For an empty text we apply both TextHeightBehaviour flags
1057 // In case of non-empty paragraph TextHeightBehaviour flags will be applied at the appropriate place
1058 // We have to do it here because we skip wrapping for an empty text
1059 auto disableFirstAscent = (paragraphStyle().getTextHeightBehavior() & TextHeightBehavior::kDisableFirstAscent) == TextHeightBehavior::kDisableFirstAscent;
1060 auto disableLastDescent = (paragraphStyle().getTextHeightBehavior() & TextHeightBehavior::kDisableLastDescent) == TextHeightBehavior::kDisableLastDescent;
1061 fEmptyMetrics.update(
1062 disableFirstAscent ? fEmptyMetrics.rawAscent() : fEmptyMetrics.ascent(),
1063 disableLastDescent ? fEmptyMetrics.rawDescent() : fEmptyMetrics.descent(),
1064 fEmptyMetrics.leading());
1065 }
1066
1067 if (fParagraphStyle.getStrutStyle().getStrutEnabled()) {
1068 fStrutMetrics.updateLineMetrics(fEmptyMetrics);
1069 }
1070 }
1071
1072 SkString ParagraphImpl::getEllipsis() const {
1073
1074 auto ellipsis8 = fParagraphStyle.getEllipsis();
1075 auto ellipsis16 = fParagraphStyle.getEllipsisUtf16();
1076 if (!ellipsis8.isEmpty()) {
1077 return ellipsis8;
1078 } else {
1079 return SkUnicode::convertUtf16ToUtf8(fParagraphStyle.getEllipsisUtf16());
1080 }
1081 }
1082
1083 void ParagraphImpl::updateFontSize(size_t from, size_t to, SkScalar fontSize) {
1084
1085 SkASSERT(from == 0 && to == fText.size());
1086 auto defaultStyle = fParagraphStyle.getTextStyle();
1087 defaultStyle.setFontSize(fontSize);
1088 fParagraphStyle.setTextStyle(defaultStyle);
1089
1090 for (auto& textStyle : fTextStyles) {
1091 textStyle.fStyle.setFontSize(fontSize);
1092 }
1093
1094 fState = std::min(fState, kIndexed);
1095 fOldWidth = 0;
1096 fOldHeight = 0;
1097 }
1098
1099 void ParagraphImpl::updateTextAlign(TextAlign textAlign) {
1100 fParagraphStyle.setTextAlign(textAlign);
1101
1102 if (fState >= kLineBroken) {
1103 fState = kLineBroken;
1104 }
1105 }
1106
1107 void ParagraphImpl::updateForegroundPaint(size_t from, size_t to, SkPaint paint) {
1108 SkASSERT(from == 0 && to == fText.size());
1109 auto defaultStyle = fParagraphStyle.getTextStyle();
1110 defaultStyle.setForegroundColor(paint);
1111 fParagraphStyle.setTextStyle(defaultStyle);
1112
1113 for (auto& textStyle : fTextStyles) {
1114 textStyle.fStyle.setForegroundColor(paint);
1115 }
1116 }
1117
1118 void ParagraphImpl::updateBackgroundPaint(size_t from, size_t to, SkPaint paint) {
1119 SkASSERT(from == 0 && to == fText.size());
1120 auto defaultStyle = fParagraphStyle.getTextStyle();
1121 defaultStyle.setBackgroundColor(paint);
1122 fParagraphStyle.setTextStyle(defaultStyle);
1123
1124 for (auto& textStyle : fTextStyles) {
1125 textStyle.fStyle.setBackgroundColor(paint);
1126 }
1127 }
1128
1129 TArray<TextIndex> ParagraphImpl::countSurroundingGraphemes(TextRange textRange) const {
1130 textRange = textRange.intersection({0, fText.size()});
1131 TArray<TextIndex> graphemes;
1132 if ((fCodeUnitProperties[textRange.start] & SkUnicode::CodeUnitFlags::kGraphemeStart) == 0) {
1133 // Count the previous partial grapheme
1134 graphemes.emplace_back(textRange.start);
1135 }
1136 for (auto index = textRange.start; index < textRange.end; ++index) {
1137 if ((fCodeUnitProperties[index] & SkUnicode::CodeUnitFlags::kGraphemeStart) != 0) {
1138 graphemes.emplace_back(index);
1139 }
1140 }
1141 return graphemes;
1142 }
1143
1144 TextIndex ParagraphImpl::findPreviousGraphemeBoundary(TextIndex utf8) const {
1145 while (utf8 > 0 &&
1146 (fCodeUnitProperties[utf8] & SkUnicode::CodeUnitFlags::kGraphemeStart) == 0) {
1147 --utf8;
1148 }
1149 return utf8;
1150 }
1151
1152 TextIndex ParagraphImpl::findNextGraphemeBoundary(TextIndex utf8) const {
1153 while (utf8 < fText.size() &&
1154 (fCodeUnitProperties[utf8] & SkUnicode::CodeUnitFlags::kGraphemeStart) == 0) {
1155 ++utf8;
1156 }
1157 return utf8;
1158 }
1159
1160 TextIndex ParagraphImpl::findNextGlyphClusterBoundary(TextIndex utf8) const {
1161 while (utf8 < fText.size() &&
1162 (fCodeUnitProperties[utf8] & SkUnicode::CodeUnitFlags::kGlyphClusterStart) == 0) {
1163 ++utf8;
1164 }
1165 return utf8;
1166 }
1167
1168 TextIndex ParagraphImpl::findPreviousGlyphClusterBoundary(TextIndex utf8) const {
1169 while (utf8 > 0 &&
1170 (fCodeUnitProperties[utf8] & SkUnicode::CodeUnitFlags::kGlyphClusterStart) == 0) {
1171 --utf8;
1172 }
1173 return utf8;
1174 }
1175
1176 void ParagraphImpl::ensureUTF16Mapping() {
1177 fillUTF16MappingOnce([&] {
1178 SkUnicode::extractUtfConversionMapping(
1179 this->text(),
1180 [&](size_t index) { fUTF8IndexForUTF16Index.emplace_back(index); },
1181 [&](size_t index) { fUTF16IndexForUTF8Index.emplace_back(index); });
1182 });
1183 }
1184
1185 void ParagraphImpl::visit(const Visitor& visitor) {
1186 int lineNumber = 0;
1187 for (auto& line : fLines) {
1188 line.ensureTextBlobCachePopulated();
1189 for (auto& rec : line.fTextBlobCache) {
1190 if (rec.fBlob == nullptr) {
1191 continue;
1192 }
1193 SkTextBlob::Iter iter(*rec.fBlob);
1194 SkTextBlob::Iter::ExperimentalRun run;
1195
1196 STArray<128, uint32_t> clusterStorage;
1197 const Run* R = rec.fVisitor_Run;
1198 const uint32_t* clusterPtr = &R->fClusterIndexes[0];
1199
1200 if (R->fClusterStart > 0) {
1201 int count = R->fClusterIndexes.size();
1202 clusterStorage.reset(count);
1203 for (int i = 0; i < count; ++i) {
1204 clusterStorage[i] = R->fClusterStart + R->fClusterIndexes[i];
1205 }
1206 clusterPtr = &clusterStorage[0];
1207 }
1208 clusterPtr += rec.fVisitor_Pos;
1209
1210 while (iter.experimentalNext(&run)) {
1211 const Paragraph::VisitorInfo info = {
1212 run.font,
1213 rec.fOffset,
1214 rec.fClipRect.fRight,
1215 run.count,
1216 run.glyphs,
1217 run.positions,
1218 clusterPtr,
1219 0, // flags
1220 };
1221 visitor(lineNumber, &info);
1222 clusterPtr += run.count;
1223 }
1224 }
1225 visitor(lineNumber, nullptr); // signal end of line
1226 lineNumber += 1;
1227 }
1228 }
1229
1230 int ParagraphImpl::getLineNumberAt(TextIndex codeUnitIndex) const {
1231 if (codeUnitIndex >= fText.size()) {
1232 return -1;
1233 }
1234 size_t startLine = 0;
1235 size_t endLine = fLines.size() - 1;
1236 if (fLines.empty() || fLines[endLine].textWithNewlines().end <= codeUnitIndex) {
1237 return -1;
1238 }
1239
1240 while (endLine > startLine) {
1241 // startLine + 1 <= endLine, so we have startLine <= midLine <= endLine - 1.
1242 const size_t midLine = (endLine + startLine) / 2;
1243 const TextRange midLineRange = fLines[midLine].textWithNewlines();
1244 if (codeUnitIndex < midLineRange.start) {
1245 endLine = midLine - 1;
1246 } else if (midLineRange.end <= codeUnitIndex) {
1247 startLine = midLine + 1;
1248 } else {
1249 return midLine;
1250 }
1251 }
1252 SkASSERT(startLine == endLine);
1253 return startLine;
1254 }
1255
1256 int ParagraphImpl::getLineNumberAtUTF16Offset(size_t codeUnitIndex) {
1257 this->ensureUTF16Mapping();
1258 if (codeUnitIndex >= SkToSizeT(fUTF8IndexForUTF16Index.size())) {
1259 return -1;
1260 }
1261 const TextIndex utf8 = fUTF8IndexForUTF16Index[codeUnitIndex];
1262 return getLineNumberAt(utf8);
1263 }
1264
1265 bool ParagraphImpl::getLineMetricsAt(int lineNumber, LineMetrics* lineMetrics) const {
1266 if (lineNumber < 0 || lineNumber >= fLines.size()) {
1267 return false;
1268 }
1269 auto& line = fLines[lineNumber];
1270 if (lineMetrics) {
1271 *lineMetrics = line.getMetrics();
1272 }
1273 return true;
1274 }
1275
1276 TextRange ParagraphImpl::getActualTextRange(int lineNumber, bool includeSpaces) const {
1277 if (lineNumber < 0 || lineNumber >= fLines.size()) {
1278 return EMPTY_TEXT;
1279 }
1280 auto& line = fLines[lineNumber];
1281 return includeSpaces ? line.text() : line.trimmedText();
1282 }
1283
1284 bool ParagraphImpl::getGlyphClusterAt(TextIndex codeUnitIndex, GlyphClusterInfo* glyphInfo) {
1285 const int lineNumber = getLineNumberAt(codeUnitIndex);
1286 if (lineNumber == -1) {
1287 return false;
1288 }
1289 auto& line = fLines[lineNumber];
1290 for (auto c = line.clustersWithSpaces().start; c < line.clustersWithSpaces().end; ++c) {
1291 auto& cluster = fClusters[c];
1292 if (cluster.contains(codeUnitIndex)) {
1293 std::vector<TextBox> boxes;
1294 line.getRectsForRange(cluster.textRange(),
1295 RectHeightStyle::kTight,
1296 RectWidthStyle::kTight,
1297 boxes);
1298 if (!boxes.empty()) {
1299 if (glyphInfo) {
1300 *glyphInfo = {boxes[0].rect, cluster.textRange(), boxes[0].direction};
1301 }
1302 return true;
1303 }
1304 }
1305 }
1306 return false;
1307 }
1308
1309 bool ParagraphImpl::getClosestGlyphClusterAt(SkScalar dx,
1310 SkScalar dy,
1311 GlyphClusterInfo* glyphInfo) {
1312 const PositionWithAffinity res = this->getGlyphPositionAtCoordinate(dx, dy);
1313 SkASSERT(res.position != 0 || res.affinity != Affinity::kUpstream);
1314 const size_t utf16Offset = res.position + (res.affinity == Affinity::kDownstream ? 0 : -1);
1315 this->ensureUTF16Mapping();
1316 SkASSERT(utf16Offset < SkToSizeT(fUTF8IndexForUTF16Index.size()));
1317 return this->getGlyphClusterAt(fUTF8IndexForUTF16Index[utf16Offset], glyphInfo);
1318 }
1319
1320 bool ParagraphImpl::getGlyphInfoAtUTF16Offset(size_t codeUnitIndex, GlyphInfo* glyphInfo) {
1321 this->ensureUTF16Mapping();
1322 if (codeUnitIndex >= SkToSizeT(fUTF8IndexForUTF16Index.size())) {
1323 return false;
1324 }
1325 const TextIndex utf8 = fUTF8IndexForUTF16Index[codeUnitIndex];
1326 const int lineNumber = getLineNumberAt(utf8);
1327 if (lineNumber == -1) {
1328 return false;
1329 }
1330 if (glyphInfo == nullptr) {
1331 return true;
1332 }
1333 const TextLine& line = fLines[lineNumber];
1334 const TextIndex startIndex = findPreviousGraphemeBoundary(utf8);
1335 const TextIndex endIndex = findNextGraphemeBoundary(utf8 + 1);
1336 const ClusterIndex glyphClusterIndex = clusterIndex(utf8);
1337 const Cluster& glyphCluster = cluster(glyphClusterIndex);
1338
1339 // `startIndex` and `endIndex` must be on the same line.
1340 std::vector<TextBox> boxes;
1341 line.getRectsForRange({startIndex, endIndex}, RectHeightStyle::kTight, RectWidthStyle::kTight, boxes);
1342 // TODO: currently placeholders with height=0 and width=0 are ignored so boxes
1343 // can be empty. These placeholders should still be reported for their
1344 // offset information.
1345 if (glyphInfo && !boxes.empty()) {
1346 *glyphInfo = {
1347 boxes[0].rect,
1348 { fUTF16IndexForUTF8Index[startIndex], fUTF16IndexForUTF8Index[endIndex] },
1349 boxes[0].direction,
1350 glyphCluster.run().isEllipsis(),
1351 };
1352 }
1353 return true;
1354 }
1355
1356 bool ParagraphImpl::getClosestUTF16GlyphInfoAt(SkScalar dx, SkScalar dy, GlyphInfo* glyphInfo) {
1357 const PositionWithAffinity res = this->getGlyphPositionAtCoordinate(dx, dy);
1358 SkASSERT(res.position != 0 || res.affinity != Affinity::kUpstream);
1359 const size_t utf16Offset = res.position + (res.affinity == Affinity::kDownstream ? 0 : -1);
1360 return getGlyphInfoAtUTF16Offset(utf16Offset, glyphInfo);
1361 }
1362
1363 SkFont ParagraphImpl::getFontAt(TextIndex codeUnitIndex) const {
1364 for (auto& run : fRuns) {
1365 const auto textRange = run.textRange();
1366 if (textRange.start <= codeUnitIndex && codeUnitIndex < textRange.end) {
1367 return run.font();
1368 }
1369 }
1370 return SkFont();
1371 }
1372
1373 SkFont ParagraphImpl::getFontAtUTF16Offset(size_t codeUnitIndex) {
1374 ensureUTF16Mapping();
1375 if (codeUnitIndex >= SkToSizeT(fUTF8IndexForUTF16Index.size())) {
1376 return SkFont();
1377 }
1378 const TextIndex utf8 = fUTF8IndexForUTF16Index[codeUnitIndex];
1379 for (auto& run : fRuns) {
1380 const auto textRange = run.textRange();
1381 if (textRange.start <= utf8 && utf8 < textRange.end) {
1382 return run.font();
1383 }
1384 }
1385 return SkFont();
1386 }
1387
1388 std::vector<Paragraph::FontInfo> ParagraphImpl::getFonts() const {
1389 std::vector<FontInfo> results;
1390 for (auto& run : fRuns) {
1391 results.emplace_back(run.font(), run.textRange());
1392 }
1393 return results;
1394 }
1395
1396 void ParagraphImpl::extendedVisit(const ExtendedVisitor& visitor) {
1397 int lineNumber = 0;
1398 for (auto& line : fLines) {
1399 line.iterateThroughVisualRuns(
1400 false,
1401 [&](const Run* run,
1402 SkScalar runOffsetInLine,
1403 TextRange textRange,
1404 SkScalar* runWidthInLine) {
1405 *runWidthInLine = line.iterateThroughSingleRunByStyles(
1406 TextLine::TextAdjustment::GlyphCluster,
1407 run,
1408 runOffsetInLine,
1409 textRange,
1410 StyleType::kNone,
1411 [&](TextRange textRange,
1412 const TextStyle& style,
1413 const TextLine::ClipContext& context) {
1414 SkScalar correctedBaseline = SkScalarFloorToScalar(
1415 line.baseline() + style.getBaselineShift() + 0.5);
1416 SkPoint offset =
1417 SkPoint::Make(line.offset().fX + context.fTextShift,
1418 line.offset().fY + correctedBaseline);
1419 SkRect rect = context.clip.makeOffset(line.offset());
1420 AutoSTArray<16, SkRect> glyphBounds;
1421 glyphBounds.reset(SkToInt(run->size()));
1422 run->font().getBounds(run->glyphs(), glyphBounds, nullptr);
1423 STArray<128, uint32_t> clusterStorage;
1424 const uint32_t* clusterPtr = run->clusterIndexes().data();
1425 if (run->fClusterStart > 0) {
1426 clusterStorage.reset(context.size);
1427 for (size_t i = 0; i < context.size; ++i) {
1428 clusterStorage[i] =
1429 run->fClusterStart + run->fClusterIndexes[i];
1430 }
1431 clusterPtr = &clusterStorage[0];
1432 }
1433 const Paragraph::ExtendedVisitorInfo info = {
1434 run->font(),
1435 offset,
1436 SkSize::Make(rect.width(), rect.height()),
1437 SkToS16(context.size),
1438 &run->glyphs()[context.pos],
1439 &run->fPositions[context.pos],
1440 &glyphBounds[context.pos],
1441 clusterPtr,
1442 0, // flags
1443 };
1444 visitor(lineNumber, &info);
1445 });
1446 return true;
1447 });
1448 visitor(lineNumber, nullptr); // signal end of line
1449 lineNumber += 1;
1450 }
1451 }
1452
1453 int ParagraphImpl::getPath(int lineNumber, SkPath* dest) {
1454 SkPathBuilder builder;
1455 int notConverted = 0;
1456 auto& line = fLines[lineNumber];
1457 line.iterateThroughVisualRuns(
1458 false,
1459 [&](const Run* run,
1460 SkScalar runOffsetInLine,
1461 TextRange textRange,
1462 SkScalar* runWidthInLine) {
1463 *runWidthInLine = line.iterateThroughSingleRunByStyles(
1464 TextLine::TextAdjustment::GlyphCluster,
1465 run,
1466 runOffsetInLine,
1467 textRange,
1468 StyleType::kNone,
1469 [&](TextRange textRange,
1470 const TextStyle& style,
1471 const TextLine::ClipContext& context) {
1472 const SkFont& font = run->font();
1473 SkScalar correctedBaseline = SkScalarFloorToScalar(
1474 line.baseline() + style.getBaselineShift() + 0.5);
1475 SkPoint offset =
1476 SkPoint::Make(line.offset().fX + context.fTextShift,
1477 line.offset().fY + correctedBaseline);
1478 SkRect rect = context.clip.makeOffset(offset);
1479 struct Rec {
1480 SkPathBuilder* fBuilder;
1481 SkPoint fOffset;
1482 const SkPoint* fPos;
1483 int fNotConverted;
1484 } rec =
1485 {&builder, SkPoint::Make(rect.left(), rect.top()), &run->positions()[context.pos], 0};
1486 font.getPaths({&run->glyphs()[context.pos], context.size},
1487 [](const SkPath* path, const SkMatrix& mx, void* ctx) {
1488 Rec* rec = reinterpret_cast<Rec*>(ctx);
1489 if (path) {
1490 SkMatrix total = mx;
1491 total.postTranslate(rec->fPos->fX + rec->fOffset.fX,
1492 rec->fPos->fY + rec->fOffset.fY);
1493 rec->fBuilder->addPath(*path, total);
1494 } else {
1495 rec->fNotConverted++;
1496 }
1497 rec->fPos += 1; // move to the next glyph's position
1498 }, &rec);
1499 notConverted += rec.fNotConverted;
1500 });
1501 *dest = builder.detach();
1502 return true;
1503 });
1504
1505 return notConverted;
1506 }
1507
1508 SkPath Paragraph::GetPath(SkTextBlob* textBlob) {
1509 SkPathBuilder builder;
1510 SkTextBlobRunIterator iter(textBlob);
1511 while (!iter.done()) {
1512 SkFont font = iter.font();
1513 struct Rec { SkPathBuilder* fBuilder; SkPoint fOffset; const SkPoint* fPos; } rec =
1514 {&builder, {textBlob->bounds().left(), textBlob->bounds().top()},
1515 iter.points()};
1516 font.getPaths({iter.glyphs(), iter.glyphCount()},
1517 [](const SkPath* src, const SkMatrix& mx, void* ctx) {
1518 Rec* rec = (Rec*)ctx;
1519 if (src) {
1520 SkMatrix tmp(mx);
1521 tmp.postTranslate(rec->fPos->fX - rec->fOffset.fX,
1522 rec->fPos->fY - rec->fOffset.fY);
1523 rec->fBuilder->addPath(*src, tmp);
1524 }
1525 rec->fPos += 1;
1526 },
1527 &rec);
1528 iter.next();
1529 }
1530 return builder.detach();
1531 }
1532
1533 bool ParagraphImpl::containsEmoji(SkTextBlob* textBlob) {
1534 bool result = false;
1535 SkTextBlobRunIterator iter(textBlob);
1536 while (!iter.done() && !result) {
1537 // Walk through all the text by codepoints
1538 this->getUnicode()->forEachCodepoint(iter.text(), iter.textSize(),
1539 [&](SkUnichar unichar, int32_t start, int32_t end, int32_t count) {
1540 if (this->getUnicode()->isEmoji(unichar)) {
1541 result = true;
1542 }
1543 });
1544 iter.next();
1545 }
1546 return result;
1547 }
1548
1549 bool ParagraphImpl::containsColorFontOrBitmap(SkTextBlob* textBlob) {
1550 SkTextBlobRunIterator iter(textBlob);
1551 bool flag = false;
1552 while (!iter.done() && !flag) {
1553 iter.font().getPaths(
1554 {(const SkGlyphID*) iter.glyphs(), iter.glyphCount()},
1555 [](const SkPath* path, const SkMatrix& mx, void* ctx) {
1556 if (path == nullptr) {
1557 bool* flag1 = (bool*)ctx;
1558 *flag1 = true;
1559 }
1560 }, &flag);
1561 iter.next();
1562 }
1563 return flag;
1564 }
1565
1566 } // namespace textlayout
1567 } // namespace skia