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