1 // Copyright 2019 Google LLC.
2
3 #include "modules/skparagraph/src/Iterators.h"
4 #include "modules/skparagraph/src/OneLineShaper.h"
5 #include "src/Run.h"
6 #include "src/utils/SkUTF.h"
7
8 #include <algorithm>
9 #include <cstdint>
10 #include <unordered_set>
11
12
nextUtf8Unit(const char ** ptr,const char * end)13 static inline SkUnichar nextUtf8Unit(const char** ptr, const char* end) {
14 SkUnichar val = SkUTF::NextUTF8(ptr, end);
15 return val < 0 ? 0xFFFD : val;
16 }
17
18 namespace skia {
19 namespace textlayout {
20
commitRunBuffer(const RunInfo &)21 void OneLineShaper::commitRunBuffer(const RunInfo&) {
22
23 fCurrentRun->commit();
24
25 auto oldUnresolvedCount = fUnresolvedBlocks.size();
26 /*
27 SkDebugf("Run [%zu:%zu)\n", fCurrentRun->fTextRange.start, fCurrentRun->fTextRange.end);
28 for (size_t i = 0; i < fCurrentRun->size(); ++i) {
29 SkDebugf("[%zu] %hu %u %f\n", i, fCurrentRun->fGlyphs[i], fCurrentRun->fClusterIndexes[i], fCurrentRun->fPositions[i].fX);
30 }
31 */
32 // Find all unresolved blocks
33 sortOutGlyphs([&](GlyphRange block){
34 if (block.width() == 0) {
35 return;
36 }
37 addUnresolvedWithRun(block);
38 });
39
40 // Fill all the gaps between unresolved blocks with resolved ones
41 if (oldUnresolvedCount == fUnresolvedBlocks.size()) {
42 // No unresolved blocks added - we resolved the block with one run entirely
43 addFullyResolved();
44 return;
45 } else if (oldUnresolvedCount == fUnresolvedBlocks.size() - 1) {
46 auto& unresolved = fUnresolvedBlocks.back();
47 if (fCurrentRun->textRange() == unresolved.fText) {
48 // Nothing was resolved; preserve the initial run if it makes sense
49 auto& front = fUnresolvedBlocks.front();
50 if (front.fRun != nullptr) {
51 unresolved.fRun = front.fRun;
52 unresolved.fGlyphs = front.fGlyphs;
53 }
54 return;
55 }
56 }
57
58 fillGaps(oldUnresolvedCount);
59 }
60
61 #ifdef SK_DEBUG
printState()62 void OneLineShaper::printState() {
63 SkDebugf("Resolved: %zu\n", fResolvedBlocks.size());
64 for (auto& resolved : fResolvedBlocks) {
65 if (resolved.fRun == nullptr) {
66 SkDebugf("[%zu:%zu) unresolved\n",
67 resolved.fText.start, resolved.fText.end);
68 continue;
69 }
70 SkString name("???");
71 if (resolved.fRun->fFont.getTypeface() != nullptr) {
72 resolved.fRun->fFont.getTypeface()->getFamilyName(&name);
73 }
74 SkDebugf("[%zu:%zu) ", resolved.fGlyphs.start, resolved.fGlyphs.end);
75 SkDebugf("[%zu:%zu) with %s\n",
76 resolved.fText.start, resolved.fText.end,
77 name.c_str());
78 }
79
80 auto size = fUnresolvedBlocks.size();
81 SkDebugf("Unresolved: %zu\n", size);
82 for (const auto& unresolved : fUnresolvedBlocks) {
83 SkDebugf("[%zu:%zu)\n", unresolved.fText.start, unresolved.fText.end);
84 }
85 }
86 #endif
87
fillGaps(size_t startingCount)88 void OneLineShaper::fillGaps(size_t startingCount) {
89 // Fill out gaps between all unresolved blocks
90 TextRange resolvedTextLimits = fCurrentRun->fTextRange;
91 if (!fCurrentRun->leftToRight()) {
92 std::swap(resolvedTextLimits.start, resolvedTextLimits.end);
93 }
94 TextIndex resolvedTextStart = resolvedTextLimits.start;
95 GlyphIndex resolvedGlyphsStart = 0;
96
97 auto begin = fUnresolvedBlocks.begin();
98 auto end = fUnresolvedBlocks.end();
99 begin += startingCount; // Skip the old ones, do the new ones
100 TextRange prevText = EMPTY_TEXT;
101 for (; begin != end; ++begin) {
102 auto& unresolved = *begin;
103
104 if (unresolved.fText == prevText) {
105 // Clean up repetitive blocks that appear inside the same grapheme block
106 unresolved.fText = EMPTY_TEXT;
107 continue;
108 } else {
109 prevText = unresolved.fText;
110 }
111
112 TextRange resolvedText(resolvedTextStart, fCurrentRun->leftToRight() ? unresolved.fText.start : unresolved.fText.end);
113 if (resolvedText.width() > 0) {
114 if (!fCurrentRun->leftToRight()) {
115 std::swap(resolvedText.start, resolvedText.end);
116 }
117
118 GlyphRange resolvedGlyphs(resolvedGlyphsStart, unresolved.fGlyphs.start);
119 RunBlock resolved(fCurrentRun, resolvedText, resolvedGlyphs, resolvedGlyphs.width());
120
121 if (resolvedGlyphs.width() == 0) {
122 // Extend the unresolved block with an empty resolved
123 if (unresolved.fText.end <= resolved.fText.start) {
124 unresolved.fText.end = resolved.fText.end;
125 }
126 if (unresolved.fText.start >= resolved.fText.end) {
127 unresolved.fText.start = resolved.fText.start;
128 }
129 } else {
130 fResolvedBlocks.emplace_back(resolved);
131 }
132 }
133 resolvedGlyphsStart = unresolved.fGlyphs.end;
134 resolvedTextStart = fCurrentRun->leftToRight()
135 ? unresolved.fText.end
136 : unresolved.fText.start;
137 }
138
139 TextRange resolvedText(resolvedTextStart,resolvedTextLimits.end);
140 if (resolvedText.width() > 0) {
141 if (!fCurrentRun->leftToRight()) {
142 std::swap(resolvedText.start, resolvedText.end);
143 }
144
145 GlyphRange resolvedGlyphs(resolvedGlyphsStart, fCurrentRun->size());
146 RunBlock resolved(fCurrentRun, resolvedText, resolvedGlyphs, resolvedGlyphs.width());
147 fResolvedBlocks.emplace_back(resolved);
148 }
149 }
150
151 #ifdef OHOS_SUPPORT
152 // 1. glyphs in run between [glyphStart, glyphEnd) are all equal to zero.
153 // 2. run is nullptr.
154 // 3. charStart flag has kCombine.
155 // one of the above conditions is met, will return true.
156 // anything else, return false.
isUnresolvedCombineGlyphRange(std::shared_ptr<Run> run,size_t glyphStart,size_t glyphEnd,size_t charStart) const157 bool OneLineShaper::isUnresolvedCombineGlyphRange(std::shared_ptr<Run> run, size_t glyphStart, size_t glyphEnd,
158 size_t charStart) const
159 {
160 if (run == nullptr ||
161 (fParagraph != nullptr && !fParagraph->codeUnitHasProperty(charStart, SkUnicode::kCombine))) {
162 return true;
163 }
164 size_t iterGlyphEnd = std::min(run->fGlyphs.size(), glyphEnd);
165 for (size_t glyph = glyphStart; glyph < iterGlyphEnd; ++glyph) {
166 if (run->fGlyphs[glyph] != 0) {
167 return false;
168 }
169 }
170
171 return true;
172 }
173
174 // split unresolvedBlock.
175 // extract resolvedBlock(which isUnresolvedGlyphRange is false), emplace back to stagedUnresolvedBlocks.
176 // the rest block emplace back to fUnresolvedBlocks without run.
splitUnresolvedBlockAndStageResolvedSubBlock(std::deque<RunBlock> & stagedUnresolvedBlocks,const RunBlock & unresolvedBlock)177 void OneLineShaper::splitUnresolvedBlockAndStageResolvedSubBlock(
178 std::deque<RunBlock>& stagedUnresolvedBlocks, const RunBlock& unresolvedBlock)
179 {
180 if (unresolvedBlock.fRun == nullptr) {
181 return;
182 }
183 std::shared_ptr<Run> run = unresolvedBlock.fRun;
184 bool hasUnresolvedText = false;
185 size_t curTextStart = EMPTY_INDEX;
186 size_t curGlyphEdge = EMPTY_INDEX;
187 run->iterateGlyphRangeInTextOrder(unresolvedBlock.fGlyphs,
188 [&stagedUnresolvedBlocks, &hasUnresolvedText, &curTextStart, &curGlyphEdge, run, this]
189 (size_t glyphStart, size_t glyphEnd, size_t charStart, size_t charEnd) {
190 if (!isUnresolvedCombineGlyphRange(run, glyphStart, glyphEnd, charStart)) {
191 if (curTextStart == EMPTY_INDEX) {
192 curTextStart = charStart;
193 }
194 if (curGlyphEdge == EMPTY_INDEX) {
195 curGlyphEdge = run->leftToRight() ? glyphStart : glyphEnd;
196 }
197 return;
198 }
199 hasUnresolvedText = true;
200 this->fUnresolvedBlocks.emplace_back(RunBlock(TextRange(charStart, charEnd)));
201 if (curTextStart == EMPTY_INDEX) {
202 return;
203 }
204 if (run->leftToRight()) {
205 stagedUnresolvedBlocks.emplace_back(
206 run, TextRange(curTextStart, charStart), GlyphRange(curGlyphEdge, glyphStart), 0);
207 } else {
208 stagedUnresolvedBlocks.emplace_back(
209 run, TextRange(curTextStart, charStart), GlyphRange(glyphEnd, curGlyphEdge), 0);
210 }
211 curTextStart = EMPTY_INDEX;
212 curGlyphEdge = EMPTY_INDEX;
213 });
214 if (!hasUnresolvedText) {
215 stagedUnresolvedBlocks.emplace_back(unresolvedBlock);
216 return;
217 }
218 if (curTextStart == EMPTY_INDEX) {
219 return;
220 }
221 if (run->leftToRight()) {
222 stagedUnresolvedBlocks.emplace_back(run, TextRange(curTextStart, unresolvedBlock.fText.end),
223 GlyphRange(curGlyphEdge, unresolvedBlock.fGlyphs.end), 0);
224 } else {
225 stagedUnresolvedBlocks.emplace_back(run, TextRange(curTextStart, unresolvedBlock.fText.end),
226 GlyphRange(unresolvedBlock.fGlyphs.start, curGlyphEdge), 0);
227 }
228 }
229
230 // shape unresolved text separately.
shapeUnresolvedTextSeparatelyFromUnresolvedBlock(const TextStyle & textStyle,const TypefaceVisitor & visitor)231 void OneLineShaper::shapeUnresolvedTextSeparatelyFromUnresolvedBlock(
232 const TextStyle& textStyle, const TypefaceVisitor& visitor)
233 {
234 if (fUnresolvedBlocks.empty()) {
235 return;
236 }
237 std::deque<OneLineShaper::RunBlock> stagedUnresolvedBlocks;
238 size_t unresolvedBlockCount = fUnresolvedBlocks.size();
239 while (unresolvedBlockCount-- > 0) {
240 RunBlock unresolvedBlock = fUnresolvedBlocks.front();
241 fUnresolvedBlocks.pop_front();
242
243 if (unresolvedBlock.fText.width() <= 1 || unresolvedBlock.fRun == nullptr) {
244 stagedUnresolvedBlocks.emplace_back(unresolvedBlock);
245 continue;
246 }
247
248 splitUnresolvedBlockAndStageResolvedSubBlock(stagedUnresolvedBlocks, unresolvedBlock);
249 }
250
251 this->matchResolvedFonts(textStyle, visitor);
252
253 while (!stagedUnresolvedBlocks.empty()) {
254 auto block = stagedUnresolvedBlocks.front();
255 stagedUnresolvedBlocks.pop_front();
256 fUnresolvedBlocks.emplace_back(block);
257 }
258 }
259 #endif
260
finish(const Block & block,SkScalar height,SkScalar & advanceX)261 void OneLineShaper::finish(const Block& block, SkScalar height, SkScalar& advanceX) {
262 auto blockText = block.fRange;
263
264 // Add all unresolved blocks to resolved blocks
265 while (!fUnresolvedBlocks.empty()) {
266 auto unresolved = fUnresolvedBlocks.front();
267 fUnresolvedBlocks.pop_front();
268 if (unresolved.fText.width() == 0) {
269 continue;
270 }
271 fResolvedBlocks.emplace_back(unresolved);
272 fUnresolvedGlyphs += unresolved.fGlyphs.width();
273 fParagraph->addUnresolvedCodepoints(unresolved.fText);
274 }
275
276 // Sort all pieces by text
277 std::sort(fResolvedBlocks.begin(), fResolvedBlocks.end(),
278 [](const RunBlock& a, const RunBlock& b) {
279 return a.fText.start < b.fText.start;
280 });
281
282 // Go through all of them
283 size_t lastTextEnd = blockText.start;
284 for (auto& resolvedBlock : fResolvedBlocks) {
285
286 if (resolvedBlock.fText.end <= blockText.start) {
287 continue;
288 }
289
290 if (resolvedBlock.fRun != nullptr) {
291 fParagraph->fFontSwitches.emplace_back(resolvedBlock.fText.start, resolvedBlock.fRun->fFont);
292 }
293
294 auto run = resolvedBlock.fRun;
295 auto glyphs = resolvedBlock.fGlyphs;
296 auto text = resolvedBlock.fText;
297 if (lastTextEnd != text.start) {
298 SkDEBUGF("Text ranges mismatch: ...:%zu] - [%zu:%zu] (%zu-%zu)\n",
299 lastTextEnd, text.start, text.end, glyphs.start, glyphs.end);
300 SkASSERT(false);
301 }
302 lastTextEnd = text.end;
303
304 if (resolvedBlock.isFullyResolved()) {
305 // Just move the entire run
306 resolvedBlock.fRun->fIndex = this->fParagraph->fRuns.size();
307 this->fParagraph->fRuns.emplace_back(*resolvedBlock.fRun);
308 resolvedBlock.fRun.reset();
309 continue;
310 } else if (run == nullptr) {
311 continue;
312 }
313
314 auto runAdvance = SkVector::Make(run->posX(glyphs.end) - run->posX(glyphs.start), run->fAdvance.fY);
315 const SkShaper::RunHandler::RunInfo info = {
316 run->fFont,
317 run->fBidiLevel,
318 runAdvance,
319 glyphs.width(),
320 SkShaper::RunHandler::Range(text.start - run->fClusterStart, text.width())
321 };
322 this->fParagraph->fRuns.emplace_back(
323 this->fParagraph,
324 info,
325 run->fClusterStart,
326 height,
327 block.fStyle.getHalfLeading(),
328 block.fStyle.getBaselineShift(),
329 this->fParagraph->fRuns.size(),
330 advanceX
331 );
332 auto piece = &this->fParagraph->fRuns.back();
333
334 // TODO: Optimize copying
335 SkPoint zero = {run->fPositions[glyphs.start].fX, 0};
336 for (size_t i = glyphs.start; i <= glyphs.end; ++i) {
337
338 auto index = i - glyphs.start;
339 if (i < glyphs.end) {
340 piece->fGlyphs[index] = run->fGlyphs[i];
341 }
342 piece->fClusterIndexes[index] = run->fClusterIndexes[i];
343 piece->fPositions[index] = run->fPositions[i] - zero;
344 piece->fOffsets[index] = run->fOffsets[i];
345 piece->addX(index, advanceX);
346 }
347
348 // Carve out the line text out of the entire run text
349 fAdvance.fX += runAdvance.fX;
350 fAdvance.fY = std::max(fAdvance.fY, runAdvance.fY);
351 }
352
353 advanceX = fAdvance.fX;
354 if (lastTextEnd != blockText.end) {
355 SkDEBUGF("Last range mismatch: %zu - %zu\n", lastTextEnd, blockText.end);
356 SkASSERT(false);
357 }
358 }
359
360 // Make it [left:right) regardless of a text direction
normalizeTextRange(GlyphRange glyphRange)361 TextRange OneLineShaper::normalizeTextRange(GlyphRange glyphRange) {
362
363 if (fCurrentRun->leftToRight()) {
364 return TextRange(clusterIndex(glyphRange.start), clusterIndex(glyphRange.end));
365 } else {
366 return TextRange(clusterIndex(glyphRange.end - 1),
367 glyphRange.start > 0
368 ? clusterIndex(glyphRange.start - 1)
369 : fCurrentRun->fTextRange.end);
370 }
371 }
372
addFullyResolved()373 void OneLineShaper::addFullyResolved() {
374 if (this->fCurrentRun->size() == 0) {
375 return;
376 }
377 RunBlock resolved(fCurrentRun,
378 this->fCurrentRun->fTextRange,
379 GlyphRange(0, this->fCurrentRun->size()),
380 this->fCurrentRun->size());
381 fResolvedBlocks.emplace_back(resolved);
382 }
383
addUnresolvedWithRun(GlyphRange glyphRange)384 void OneLineShaper::addUnresolvedWithRun(GlyphRange glyphRange) {
385 auto extendedText = this->clusteredText(glyphRange); // It also modifies glyphRange if needed
386 RunBlock unresolved(fCurrentRun, extendedText, glyphRange, 0);
387 if (unresolved.fGlyphs.width() == fCurrentRun->size()) {
388 SkASSERT(unresolved.fText.width() == fCurrentRun->fTextRange.width());
389 } else if (fUnresolvedBlocks.size() > 0) {
390 auto& lastUnresolved = fUnresolvedBlocks.back();
391 if (lastUnresolved.fRun != nullptr &&
392 lastUnresolved.fRun->fIndex == fCurrentRun->fIndex) {
393
394 if (lastUnresolved.fText.end == unresolved.fText.start) {
395 // Two pieces next to each other - can join them
396 lastUnresolved.fText.end = unresolved.fText.end;
397 lastUnresolved.fGlyphs.end = glyphRange.end;
398 return;
399 } else if(lastUnresolved.fText == unresolved.fText) {
400 // Nothing was resolved; ignore it
401 return;
402 } else if (lastUnresolved.fText.contains(unresolved.fText)) {
403 // We get here for the very first unresolved piece
404 return;
405 } else if (lastUnresolved.fText.intersects(unresolved.fText)) {
406 // Few pieces of the same unresolved text block can ignore the second one
407 lastUnresolved.fGlyphs.start = std::min(lastUnresolved.fGlyphs.start, glyphRange.start);
408 lastUnresolved.fGlyphs.end = std::max(lastUnresolved.fGlyphs.end, glyphRange.end);
409 lastUnresolved.fText = this->clusteredText(lastUnresolved.fGlyphs);
410 return;
411 }
412 }
413 }
414 fUnresolvedBlocks.emplace_back(unresolved);
415 }
416
417 // Glue whitespaces to the next/prev unresolved blocks
418 // (so we don't have chinese text with english whitespaces broken into millions of tiny runs)
sortOutGlyphs(std::function<void (GlyphRange)> && sortOutUnresolvedBLock)419 void OneLineShaper::sortOutGlyphs(std::function<void(GlyphRange)>&& sortOutUnresolvedBLock) {
420
421 GlyphRange block = EMPTY_RANGE;
422 bool graphemeResolved = false;
423 TextIndex graphemeStart = EMPTY_INDEX;
424 for (size_t i = 0; i < fCurrentRun->size(); ++i) {
425
426 ClusterIndex ci = clusterIndex(i);
427 // Removing all pretty optimizations for whitespaces
428 // because they get in a way of grapheme rounding
429 // Inspect the glyph
430 auto glyph = fCurrentRun->fGlyphs[i];
431
432 GraphemeIndex gi = fParagraph->findPreviousGraphemeBoundary(ci);
433 if ((fCurrentRun->leftToRight() ? gi > graphemeStart : gi < graphemeStart) || graphemeStart == EMPTY_INDEX) {
434 // This is the Flutter change
435 // Do not count control codepoints as unresolved
436 bool isControl8 = fParagraph->codeUnitHasProperty(ci,
437 SkUnicode::CodeUnitFlags::kControl);
438 // We only count glyph resolved if all the glyphs in its grapheme are resolved
439 graphemeResolved = glyph != 0 || isControl8;
440 graphemeStart = gi;
441 } else if (glyph == 0) {
442 // Found unresolved glyph - the entire grapheme is unresolved now
443 graphemeResolved = false;
444 }
445
446 if (!graphemeResolved) { // Unresolved glyph and not control codepoint
447 if (block.start == EMPTY_INDEX) {
448 // Start new unresolved block
449 block.start = i;
450 block.end = EMPTY_INDEX;
451 } else {
452 // Keep skipping unresolved block
453 }
454 } else { // Resolved glyph or control codepoint
455 if (block.start == EMPTY_INDEX) {
456 // Keep skipping resolved code points
457 } else {
458 // This is the end of unresolved block
459 block.end = i;
460 sortOutUnresolvedBLock(block);
461 block = EMPTY_RANGE;
462 }
463 }
464 }
465
466 // One last block could have been left
467 if (block.start != EMPTY_INDEX) {
468 block.end = fCurrentRun->size();
469 sortOutUnresolvedBLock(block);
470 }
471 }
472
generateBlockRange(const Block & block,const TextRange & textRange)473 BlockRange OneLineShaper::generateBlockRange(const Block& block, const TextRange& textRange)
474 {
475 size_t start = std::max(block.fRange.start, textRange.start);
476 size_t end = std::min(block.fRange.end, textRange.end);
477 if (fParagraph->fParagraphStyle.getMaxLines() == 1 &&
478 fParagraph->fParagraphStyle.getEllipsisMod() == EllipsisModal::MIDDLE &&
479 !fParagraph->getEllipsisState()) {
480 end = fParagraph->fText.size();
481 }
482 return BlockRange(start, end);
483 }
484
iterateThroughFontStyles(TextRange textRange,SkSpan<Block> styleSpan,const ShapeSingleFontVisitor & visitor)485 void OneLineShaper::iterateThroughFontStyles(TextRange textRange,
486 SkSpan<Block> styleSpan,
487 const ShapeSingleFontVisitor& visitor) {
488 Block combinedBlock;
489 SkTArray<SkShaper::Feature> features;
490
491 auto addFeatures = [&features](const Block& block) {
492 for (auto& ff : block.fStyle.getFontFeatures()) {
493 if (ff.fName.size() != 4) {
494 SkDEBUGF("Incorrect font feature: %s=%d\n", ff.fName.c_str(), ff.fValue);
495 continue;
496 }
497 SkShaper::Feature feature = {
498 SkSetFourByteTag(ff.fName[0], ff.fName[1], ff.fName[2], ff.fName[3]),
499 SkToU32(ff.fValue),
500 block.fRange.start,
501 block.fRange.end
502 };
503 features.emplace_back(feature);
504 }
505 // Disable ligatures if letter spacing is enabled.
506 if (block.fStyle.getLetterSpacing() > 0) {
507 features.emplace_back(SkShaper::Feature{
508 SkSetFourByteTag('l', 'i', 'g', 'a'), 0, block.fRange.start, block.fRange.end
509 });
510 }
511 };
512
513 for (auto& block : styleSpan) {
514 BlockRange blockRange = generateBlockRange(block, textRange);
515 if (blockRange.empty()) {
516 continue;
517 }
518 SkASSERT(combinedBlock.fRange.width() == 0 || combinedBlock.fRange.end == block.fRange.start);
519
520 if (!combinedBlock.fRange.empty()) {
521 if (block.fStyle.matchOneAttribute(StyleType::kFont, combinedBlock.fStyle)) {
522 combinedBlock.add(blockRange);
523 addFeatures(block);
524 continue;
525 }
526 // Resolve all characters in the block for this style
527 visitor(combinedBlock, features);
528 }
529
530 combinedBlock.fRange = blockRange;
531 combinedBlock.fStyle = block.fStyle;
532 features.reset();
533 addFeatures(block);
534 }
535
536 visitor(combinedBlock, features);
537 #ifdef SK_DEBUG
538 //printState();
539 #endif
540 }
541
matchResolvedFonts(const TextStyle & textStyle,const TypefaceVisitor & visitor)542 void OneLineShaper::matchResolvedFonts(const TextStyle& textStyle,
543 const TypefaceVisitor& visitor) {
544 #ifndef USE_SKIA_TXT
545 std::vector<sk_sp<SkTypeface>> typefaces = fParagraph->fFontCollection->findTypefaces(textStyle.getFontFamilies(), textStyle.getFontStyle(), textStyle.getFontArguments());
546 #else
547 std::vector<std::shared_ptr<RSTypeface>> typefaces = fParagraph->fFontCollection->findTypefaces(
548 textStyle.getFontFamilies(), textStyle.getFontStyle(), textStyle.getFontArguments());
549 #endif
550
551 for (const auto& typeface : typefaces) {
552 if (visitor(typeface) == Resolved::Everything) {
553 // Resolved everything
554 return;
555 }
556 }
557
558 if (fParagraph->fFontCollection->fontFallbackEnabled()) {
559 // Give fallback a clue
560 // Some unresolved subblocks might be resolved with different fallback fonts
561 std::vector<RunBlock> hopelessBlocks;
562 while (!fUnresolvedBlocks.empty()) {
563 auto unresolvedRange = fUnresolvedBlocks.front().fText;
564 auto unresolvedText = fParagraph->text(unresolvedRange);
565 const char* ch = unresolvedText.begin();
566 // We have the global cache for all already found typefaces for SkUnichar
567 // but we still need to keep track of all SkUnichars used in this unresolved block
568 SkTHashSet<SkUnichar> alreadyTriedCodepoints;
569 SkTHashSet<uint32_t> alreadyTriedTypefaces;
570 while (true) {
571
572 if (ch == unresolvedText.end()) {
573 // Not a single codepoint could be resolved but we finished the block
574 hopelessBlocks.push_back(fUnresolvedBlocks.front());
575 fUnresolvedBlocks.pop_front();
576 break;
577 }
578
579 // See if we can switch to the next DIFFERENT codepoint
580 SkUnichar unicode = -1;
581 while (ch != unresolvedText.end()) {
582 unicode = nextUtf8Unit(&ch, unresolvedText.end());
583 if (!alreadyTriedCodepoints.contains(unicode)) {
584 alreadyTriedCodepoints.add(unicode);
585 break;
586 }
587 }
588 SkASSERT(unicode != -1);
589
590 // First try to find in in a cache
591 #ifndef USE_SKIA_TXT
592 sk_sp<SkTypeface> typeface;
593 #else
594 std::shared_ptr<RSTypeface> typeface;
595 #endif
596 FontKey fontKey(unicode, textStyle.getFontStyle(), textStyle.getLocale());
597 auto found = fFallbackFonts.find(fontKey);
598 #ifndef USE_SKIA_TXT
599 if (found != nullptr) {
600 typeface = *found;
601 #else
602 if (found != fFallbackFonts.end()) {
603 typeface = found->second;
604 #endif
605 } else {
606 typeface = fParagraph->fFontCollection->defaultFallback(
607 unicode, textStyle.getFontStyle(), textStyle.getLocale());
608
609 if (typeface == nullptr) {
610 // There is no fallback font for this character, so move on to the next character.
611 continue;
612 }
613 #ifndef USE_SKIA_TXT
614 fFallbackFonts.set(fontKey, typeface);
615 #else
616 fFallbackFonts.emplace(fontKey, typeface);
617 #endif
618 }
619
620 // Check if we already tried this font on this text range
621 #ifndef USE_SKIA_TXT
622 if (!alreadyTriedTypefaces.contains(typeface->uniqueID())) {
623 alreadyTriedTypefaces.add(typeface->uniqueID());
624 #else
625 if (!alreadyTriedTypefaces.contains(typeface->GetUniqueID())) {
626 alreadyTriedTypefaces.add(typeface->GetUniqueID());
627 #endif
628 } else {
629 continue;
630 }
631
632 if (typeface && textStyle.getFontArguments()) {
633 typeface = fParagraph->fFontCollection->CloneTypeface(typeface, textStyle.getFontArguments());
634 }
635
636 auto resolvedBlocksBefore = fResolvedBlocks.size();
637 auto resolved = visitor(typeface);
638 if (resolved == Resolved::Everything) {
639 if (hopelessBlocks.empty()) {
640 // Resolved everything, no need to try another font
641 return;
642 } else if (resolvedBlocksBefore < fResolvedBlocks.size()) {
643 // There are some resolved blocks
644 resolved = Resolved::Something;
645 } else {
646 // All blocks are hopeless
647 resolved = Resolved::Nothing;
648 }
649 }
650
651 if (resolved == Resolved::Something) {
652 // Resolved something, no need to try another codepoint
653 break;
654 }
655 }
656 }
657
658 // Return hopeless blocks back
659 for (auto& block : hopelessBlocks) {
660 fUnresolvedBlocks.emplace_front(block);
661 }
662 }
663 }
664
665 bool OneLineShaper::iterateThroughShapingRegions(const ShapeVisitor& shape) {
666
667 size_t bidiIndex = 0;
668
669 SkScalar advanceX = 0;
670 for (auto& placeholder : fParagraph->fPlaceholders) {
671
672 if (placeholder.fTextBefore.width() > 0) {
673 // Shape the text by bidi regions
674 while (bidiIndex < fParagraph->fBidiRegions.size()) {
675 SkUnicode::BidiRegion& bidiRegion = fParagraph->fBidiRegions[bidiIndex];
676 auto start = std::max(bidiRegion.start, placeholder.fTextBefore.start);
677 auto end = std::min(bidiRegion.end, placeholder.fTextBefore.end);
678 if (fParagraph->fParagraphStyle.getMaxLines() == 1
679 && fParagraph->fParagraphStyle.getEllipsisMod() == EllipsisModal::MIDDLE
680 && !fParagraph->getEllipsisState()) {
681 end = fParagraph->fText.size();
682 }
683
684 // Set up the iterators (the style iterator points to a bigger region that it could
685 TextRange textRange(start, end);
686 auto blockRange = fParagraph->findAllBlocks(textRange);
687 if (!blockRange.empty()) {
688 SkSpan<Block> styleSpan(fParagraph->blocks(blockRange));
689
690 // Shape the text between placeholders
691 if (!shape(textRange, styleSpan, advanceX, start, bidiRegion.level)) {
692 return false;
693 }
694 }
695
696 if (end == bidiRegion.end) {
697 ++bidiIndex;
698 } else /*if (end == placeholder.fTextBefore.end)*/ {
699 break;
700 }
701 }
702 }
703
704 if (placeholder.fRange.width() == 0) {
705 continue;
706 }
707
708 // Get the placeholder font
709 auto typefaces = fParagraph->fFontCollection->findTypefaces(
710 placeholder.fTextStyle.getFontFamilies(),
711 placeholder.fTextStyle.getFontStyle(),
712 placeholder.fTextStyle.getFontArguments());
713 auto typeface = typefaces.size() ? typefaces.front() : nullptr;
714 #ifndef USE_SKIA_TXT
715 SkFont font(typeface, placeholder.fTextStyle.getFontSize());
716 #else
717 RSFont font(typeface, placeholder.fTextStyle.getFontSize(), 1, 0);
718 #endif
719
720 // "Shape" the placeholder
721 uint8_t bidiLevel = (bidiIndex < fParagraph->fBidiRegions.size())
722 ? fParagraph->fBidiRegions[bidiIndex].level
723 : 2;
724 const SkShaper::RunHandler::RunInfo runInfo = {
725 font,
726 bidiLevel,
727 SkPoint::Make(placeholder.fStyle.fWidth, placeholder.fStyle.fHeight),
728 1,
729 SkShaper::RunHandler::Range(0, placeholder.fRange.width())
730 };
731 auto& run = fParagraph->fRuns.emplace_back(this->fParagraph,
732 runInfo,
733 placeholder.fRange.start,
734 0.0f,
735 0.0f,
736 false,
737 fParagraph->fRuns.size(),
738 advanceX);
739
740 run.fPositions[0] = { advanceX, 0 };
741 run.fOffsets[0] = {0, 0};
742 run.fClusterIndexes[0] = 0;
743 run.fPlaceholderIndex = &placeholder - fParagraph->fPlaceholders.begin();
744 advanceX += placeholder.fStyle.fWidth;
745 }
746 return true;
747 }
748
749 bool OneLineShaper::shape() {
750
751 // The text can be broken into many shaping sequences
752 // (by place holders, possibly, by hard line breaks or tabs, too)
753 auto limitlessWidth = std::numeric_limits<SkScalar>::max();
754
755 auto result = iterateThroughShapingRegions(
756 [this, limitlessWidth]
757 (TextRange textRange, SkSpan<Block> styleSpan, SkScalar& advanceX, TextIndex textStart, uint8_t defaultBidiLevel) {
758
759 // Set up the shaper and shape the next
760 auto shaper = SkShaper::MakeShapeDontWrapOrReorder(fParagraph->fUnicode->copy());
761 if (shaper == nullptr) {
762 // For instance, loadICU does not work. We have to stop the process
763 return false;
764 }
765
766 iterateThroughFontStyles(textRange, styleSpan,
767 [this, &shaper, defaultBidiLevel, limitlessWidth, &advanceX]
768 (Block block, SkTArray<SkShaper::Feature> features) {
769 auto blockSpan = SkSpan<Block>(&block, 1);
770
771 // Start from the beginning (hoping that it's a simple case one block - one run)
772 fHeight = block.fStyle.getHeightOverride() ? block.fStyle.getHeight() : 0;
773 fUseHalfLeading = block.fStyle.getHalfLeading();
774 fBaselineShift = block.fStyle.getBaselineShift();
775 fAdvance = SkVector::Make(advanceX, 0);
776 fCurrentText = block.fRange;
777 fUnresolvedBlocks.emplace_back(RunBlock(block.fRange));
778
779 #ifdef OHOS_SUPPORT
780 #ifdef USE_SKIA_TXT
781 auto typefaceVisitor = [&](std::shared_ptr<RSTypeface> typeface) {
782 #else
783 auto typefaceVisitor = [&](sk_sp<SkTypeface> typeface) {
784 #endif
785 #else
786 this->matchResolvedFonts(block.fStyle, [&](sk_sp<SkTypeface> typeface) {
787 #endif
788 // Create one more font to try
789 #ifndef USE_SKIA_TXT
790 SkFont font(std::move(typeface), block.fStyle.getFontSize());
791 font.setEdging(SkFont::Edging::kAntiAlias);
792 font.setHinting(SkFontHinting::kNone);
793 font.setSubpixel(true);
794 font.setBaselineSnap(false);
795 #else
796 RSFont font(std::move(typeface), block.fStyle.getFontSize(), 1, 0);
797 font.SetEdging(RSDrawing::FontEdging::ANTI_ALIAS);
798 font.SetHinting(RSDrawing::FontHinting::NONE);
799 font.SetSubpixel(true);
800 font.SetBaselineSnap(false);
801 #endif
802
803 #ifdef OHOS_SUPPORT
804 scaleFontWithCompressionConfig(font, ScaleOP::COMPRESS);
805 #endif
806 // Apply fake bold and/or italic settings to the font if the
807 // typeface's attributes do not match the intended font style.
808 #ifndef USE_SKIA_TXT
809 int wantedWeight = block.fStyle.getFontStyle().weight();
810 bool fakeBold =
811 wantedWeight >= SkFontStyle::kSemiBold_Weight &&
812 wantedWeight - font.getTypeface()->fontStyle().weight() >= 200;
813 bool fakeItalic =
814 block.fStyle.getFontStyle().slant() == SkFontStyle::kItalic_Slant &&
815 font.getTypeface()->fontStyle().slant() != SkFontStyle::kItalic_Slant;
816 font.setEmbolden(fakeBold);
817 font.setSkewX(fakeItalic ? -SK_Scalar1 / 4 : 0);
818 #else
819 int wantedWeight = block.fStyle.getFontStyle().GetWeight();
820 bool fakeBold =
821 wantedWeight >= RSFontStyle::SEMI_BOLD_WEIGHT &&
822 wantedWeight - font.GetTypeface()->GetFontStyle().GetWeight() >= 200;
823 bool fakeItalic =
824 block.fStyle.getFontStyle().GetSlant() == RSFontStyle::ITALIC_SLANT &&
825 font.GetTypeface()->GetFontStyle().GetSlant() != RSFontStyle::ITALIC_SLANT;
826 font.SetEmbolden(fakeBold);
827 font.SetSkewX(fakeItalic ? -SK_Scalar1 / 4 : 0);
828 #endif
829
830 // Walk through all the currently unresolved blocks
831 // (ignoring those that appear later)
832 auto resolvedCount = fResolvedBlocks.size();
833 auto unresolvedCount = fUnresolvedBlocks.size();
834 while (unresolvedCount-- > 0) {
835 auto unresolvedRange = fUnresolvedBlocks.front().fText;
836 if (unresolvedRange == EMPTY_TEXT) {
837 // Duplicate blocks should be ignored
838 fUnresolvedBlocks.pop_front();
839 continue;
840 }
841 auto unresolvedText = fParagraph->text(unresolvedRange);
842
843 SkShaper::TrivialFontRunIterator fontIter(font, unresolvedText.size());
844 LangIterator langIter(unresolvedText, blockSpan,
845 fParagraph->paragraphStyle().getTextStyle());
846 SkShaper::TrivialBiDiRunIterator bidiIter(defaultBidiLevel, unresolvedText.size());
847 auto scriptIter = SkShaper::MakeSkUnicodeHbScriptRunIterator(
848 unresolvedText.begin(), unresolvedText.size());
849 fCurrentText = unresolvedRange;
850
851 // Map the block's features to subranges within the unresolved range.
852 SkTArray<SkShaper::Feature> adjustedFeatures(features.size());
853 for (const SkShaper::Feature& feature : features) {
854 SkRange<size_t> featureRange(feature.start, feature.end);
855 if (unresolvedRange.intersects(featureRange)) {
856 SkRange<size_t> adjustedRange = unresolvedRange.intersection(featureRange);
857 adjustedRange.Shift(-static_cast<std::make_signed_t<size_t>>(unresolvedRange.start));
858 adjustedFeatures.push_back({feature.tag, feature.value, adjustedRange.start, adjustedRange.end});
859 }
860 }
861
862 shaper->shape(unresolvedText.begin(), unresolvedText.size(),
863 fontIter, bidiIter,*scriptIter, langIter,
864 adjustedFeatures.data(), adjustedFeatures.size(),
865 limitlessWidth, this);
866
867 // Take off the queue the block we tried to resolved -
868 // whatever happened, we have now smaller pieces of it to deal with
869 fUnresolvedBlocks.pop_front();
870 }
871
872 if (fUnresolvedBlocks.empty()) {
873 // In some cases it does not mean everything
874 // (when we excluded some hopeless blocks from the list)
875 return Resolved::Everything;
876 } else if (resolvedCount < fResolvedBlocks.size()) {
877 return Resolved::Something;
878 } else {
879 return Resolved::Nothing;
880 }
881 #ifdef OHOS_SUPPORT
882 };
883 this->matchResolvedFonts(block.fStyle, typefaceVisitor);
884 this->shapeUnresolvedTextSeparatelyFromUnresolvedBlock(block.fStyle, typefaceVisitor);
885 #else
886 });
887 #endif
888 this->finish(block, fHeight, advanceX);
889 });
890
891 return true;
892 });
893
894 return result;
895 }
896
897 // When we extend TextRange to the grapheme edges, we also extend glyphs range
898 TextRange OneLineShaper::clusteredText(GlyphRange& glyphs) {
899
900 enum class Dir { left, right };
901 enum class Pos { inclusive, exclusive };
902
903 // [left: right)
904 auto findBaseChar = [&](TextIndex index, Dir dir) -> TextIndex {
905
906 if (dir == Dir::right) {
907 while (index < fCurrentRun->fTextRange.end) {
908 if (this->fParagraph->codeUnitHasProperty(index,
909 SkUnicode::CodeUnitFlags::kGraphemeStart)) {
910 return index;
911 }
912 ++index;
913 }
914 return fCurrentRun->fTextRange.end;
915 } else {
916 while (index > fCurrentRun->fTextRange.start) {
917 if (this->fParagraph->codeUnitHasProperty(index,
918 SkUnicode::CodeUnitFlags::kGraphemeStart)) {
919 return index;
920 }
921 --index;
922 }
923 return fCurrentRun->fTextRange.start;
924 }
925 };
926
927 TextRange textRange(normalizeTextRange(glyphs));
928 textRange.start = findBaseChar(textRange.start, Dir::left);
929 textRange.end = findBaseChar(textRange.end, Dir::right);
930
931 // Correct the glyphRange in case we extended the text to the grapheme edges
932 // TODO: code it without if (as a part of LTR/RTL refactoring)
933 if (fCurrentRun->leftToRight()) {
934 while (glyphs.start > 0 && clusterIndex(glyphs.start) > textRange.start) {
935 glyphs.start--;
936 }
937 while (glyphs.end < fCurrentRun->size() && clusterIndex(glyphs.end) < textRange.end) {
938 glyphs.end++;
939 }
940 } else {
941 while (glyphs.start > 0 && clusterIndex(glyphs.start - 1) < textRange.end) {
942 glyphs.start--;
943 }
944 while (glyphs.end < fCurrentRun->size() && clusterIndex(glyphs.end) > textRange.start) {
945 glyphs.end++;
946 }
947 }
948
949 return { textRange.start, textRange.end };
950 }
951
952 bool OneLineShaper::FontKey::operator==(const OneLineShaper::FontKey& other) const {
953 return fUnicode == other.fUnicode && fFontStyle == other.fFontStyle && fLocale == other.fLocale;
954 }
955
956 uint32_t OneLineShaper::FontKey::Hasher::operator()(const OneLineShaper::FontKey& key) const {
957 return SkGoodHash()(key.fUnicode) ^
958 SkGoodHash()(key.fFontStyle) ^
959 SkGoodHash()(key.fLocale);
960 }
961
962 } // namespace textlayout
963 } // namespace skia
964