blob: 6560a6c495136b94509a994fe62ad7bf41e105ce [file] [log] [blame]
Ben Wagnera25fbef2017-08-30 13:56:19 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Ben Wagner17774242018-08-07 14:31:33 -04008#include "SkFontArguments.h"
Ben Wagner67e3a302017-09-05 14:46:19 -04009#include "SkFontMgr.h"
Hal Canary0e07ad72018-02-08 13:06:56 -050010#include "SkLoadICU.h"
Ben Wagner17774242018-08-07 14:31:33 -040011#include "SkMalloc.h"
Hal Canary0e07ad72018-02-08 13:06:56 -050012#include "SkOnce.h"
Hal Canary2a1848d2018-11-26 17:23:24 -050013#include "SkFont.h"
Ben Wagner17774242018-08-07 14:31:33 -040014#include "SkPoint.h"
15#include "SkRefCnt.h"
16#include "SkScalar.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040017#include "SkShaper.h"
18#include "SkStream.h"
Ben Wagner17774242018-08-07 14:31:33 -040019#include "SkString.h"
20#include "SkTArray.h"
Ben Wagner8d45a382017-11-16 10:08:28 -050021#include "SkTDPQueue.h"
Ben Wagner17774242018-08-07 14:31:33 -040022#include "SkTFitsIn.h"
Ben Wagner8d45a382017-11-16 10:08:28 -050023#include "SkTLazy.h"
Ben Wagnere0001732017-08-31 16:26:26 -040024#include "SkTemplates.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040025#include "SkTo.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040026#include "SkTypeface.h"
Ben Wagner17774242018-08-07 14:31:33 -040027#include "SkTypes.h"
28#include "SkUTF.h"
29
30#include <hb.h>
31#include <hb-ot.h>
32#include <unicode/brkiter.h>
33#include <unicode/locid.h>
34#include <unicode/stringpiece.h>
35#include <unicode/ubidi.h>
36#include <unicode/unistr.h>
37#include <unicode/urename.h>
38#include <unicode/utext.h>
39#include <unicode/utypes.h>
40
41#include <memory>
42#include <utility>
43#include <cstring>
Ben Wagnera25fbef2017-08-30 13:56:19 -040044
Ben Wagnera25fbef2017-08-30 13:56:19 -040045namespace {
46template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<void, T, P>>;
47using HBBlob = resource<hb_blob_t , hb_blob_destroy >;
48using HBFace = resource<hb_face_t , hb_face_destroy >;
49using HBFont = resource<hb_font_t , hb_font_destroy >;
50using HBBuffer = resource<hb_buffer_t, hb_buffer_destroy>;
51using ICUBiDi = resource<UBiDi , ubidi_close >;
52
53HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
54 size_t size = asset->getLength();
55 HBBlob blob;
56 if (const void* base = asset->getMemoryBase()) {
57 blob.reset(hb_blob_create((char*)base, SkToUInt(size),
58 HB_MEMORY_MODE_READONLY, asset.release(),
59 [](void* p) { delete (SkStreamAsset*)p; }));
60 } else {
61 // SkDebugf("Extra SkStreamAsset copy\n");
62 void* ptr = size ? sk_malloc_throw(size) : nullptr;
63 asset->read(ptr, size);
64 blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
65 HB_MEMORY_MODE_READONLY, ptr, sk_free));
66 }
67 SkASSERT(blob);
68 hb_blob_make_immutable(blob.get());
69 return blob;
70}
Ben Wagnera25fbef2017-08-30 13:56:19 -040071
Ben Wagner8d45a382017-11-16 10:08:28 -050072HBFont create_hb_font(SkTypeface* tf) {
Hal Canary0dfa2082018-10-31 13:02:49 -040073 if (!tf) {
74 return nullptr;
75 }
Ben Wagnera25fbef2017-08-30 13:56:19 -040076 int index;
Hal Canaryddef43f2018-11-16 10:53:51 -050077 std::unique_ptr<SkStreamAsset> typefaceAsset(tf->openStream(&index));
78 if (!typefaceAsset) {
79 SkString name;
80 tf->getFamilyName(&name);
81 SkDebugf("Typeface '%s' has no data :(\n", name.c_str());
82 return nullptr;
83 }
84 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
Ben Wagnera25fbef2017-08-30 13:56:19 -040085 HBFace face(hb_face_create(blob.get(), (unsigned)index));
86 SkASSERT(face);
87 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -040088 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -040089 }
90 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnere0001732017-08-31 16:26:26 -040091 hb_face_set_upem(face.get(), tf->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -040092
Ben Wagnere0001732017-08-31 16:26:26 -040093 HBFont font(hb_font_create(face.get()));
94 SkASSERT(font);
95 if (!font) {
96 return nullptr;
97 }
Ben Wagnere0001732017-08-31 16:26:26 -040098 hb_ot_font_set_funcs(font.get());
99 int axis_count = tf->getVariationDesignPosition(nullptr, 0);
100 if (axis_count > 0) {
101 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
102 if (tf->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
103 hb_font_set_variations(font.get(),
104 reinterpret_cast<hb_variation_t*>(axis_values.get()),
105 axis_count);
106 }
107 }
108 return font;
109}
110
Hal Canaryf107a2f2018-07-25 16:52:48 -0400111/** this version replaces invalid utf-8 sequences with code point U+FFFD. */
112static inline SkUnichar utf8_next(const char** ptr, const char* end) {
113 SkUnichar val = SkUTF::NextUTF8(ptr, end);
114 if (val < 0) {
115 return 0xFFFD; // REPLACEMENT CHARACTER
116 }
117 return val;
118}
119
Ben Wagner8d45a382017-11-16 10:08:28 -0500120class RunIterator {
121public:
122 virtual ~RunIterator() {}
123 virtual void consume() = 0;
124 // Pointer one past the last (utf8) element in the current run.
125 virtual const char* endOfCurrentRun() const = 0;
126 virtual bool atEnd() const = 0;
127 bool operator<(const RunIterator& that) const {
128 return this->endOfCurrentRun() < that.endOfCurrentRun();
129 }
130};
131
132class BiDiRunIterator : public RunIterator {
133public:
134 static SkTLazy<BiDiRunIterator> Make(const char* utf8, size_t utf8Bytes, UBiDiLevel level) {
135 SkTLazy<BiDiRunIterator> ret;
136
137 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
138 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
139 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
140 SkDebugf("Bidi error: text too long");
141 return ret;
142 }
143 icu::UnicodeString utf16 = icu::UnicodeString::fromUTF8(icu::StringPiece(utf8, utf8Bytes));
144
145 UErrorCode status = U_ZERO_ERROR;
146 ICUBiDi bidi(ubidi_openSized(utf16.length(), 0, &status));
147 if (U_FAILURE(status)) {
148 SkDebugf("Bidi error: %s", u_errorName(status));
149 return ret;
150 }
151 SkASSERT(bidi);
152
153 // The required lifetime of utf16 isn't well documented.
154 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
155 ubidi_setPara(bidi.get(), utf16.getBuffer(), utf16.length(), level, nullptr, &status);
156 if (U_FAILURE(status)) {
157 SkDebugf("Bidi error: %s", u_errorName(status));
158 return ret;
159 }
160
Hal Canary4014ba62018-07-24 11:33:21 -0400161 ret.init(utf8, utf8 + utf8Bytes, std::move(bidi));
Ben Wagner8d45a382017-11-16 10:08:28 -0500162 return ret;
163 }
Hal Canary4014ba62018-07-24 11:33:21 -0400164 BiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500165 : fBidi(std::move(bidi))
166 , fEndOfCurrentRun(utf8)
Hal Canary4014ba62018-07-24 11:33:21 -0400167 , fEndOfAllRuns(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500168 , fUTF16LogicalPosition(0)
169 , fLevel(UBIDI_DEFAULT_LTR)
170 {}
171 void consume() override {
172 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
173 int32_t endPosition = ubidi_getLength(fBidi.get());
174 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400175 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
176 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500177 UBiDiLevel level;
178 while (fUTF16LogicalPosition < endPosition) {
179 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
180 if (level != fLevel) {
181 break;
182 }
Hal Canaryf107a2f2018-07-25 16:52:48 -0400183 u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
184 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500185 }
186 }
187 const char* endOfCurrentRun() const override {
188 return fEndOfCurrentRun;
189 }
190 bool atEnd() const override {
191 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
192 }
193
194 UBiDiLevel currentLevel() const {
195 return fLevel;
196 }
197private:
198 ICUBiDi fBidi;
199 const char* fEndOfCurrentRun;
Hal Canary4014ba62018-07-24 11:33:21 -0400200 const char* fEndOfAllRuns;
Ben Wagner8d45a382017-11-16 10:08:28 -0500201 int32_t fUTF16LogicalPosition;
202 UBiDiLevel fLevel;
203};
204
205class ScriptRunIterator : public RunIterator {
206public:
207 static SkTLazy<ScriptRunIterator> Make(const char* utf8, size_t utf8Bytes,
208 hb_unicode_funcs_t* hbUnicode)
209 {
210 SkTLazy<ScriptRunIterator> ret;
211 ret.init(utf8, utf8Bytes, hbUnicode);
212 return ret;
213 }
214 ScriptRunIterator(const char* utf8, size_t utf8Bytes, hb_unicode_funcs_t* hbUnicode)
215 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
216 , fHBUnicode(hbUnicode)
217 , fCurrentScript(HB_SCRIPT_UNKNOWN)
218 {}
219 void consume() override {
220 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400221 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500222 fCurrentScript = hb_unicode_script(fHBUnicode, u);
223 while (fCurrent < fEnd) {
224 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400225 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500226 const hb_script_t script = hb_unicode_script(fHBUnicode, u);
227 if (script != fCurrentScript) {
228 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
229 fCurrentScript = script;
230 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
231 continue;
232 } else {
233 fCurrent = prev;
234 break;
235 }
236 }
237 }
238 if (fCurrentScript == HB_SCRIPT_INHERITED) {
239 fCurrentScript = HB_SCRIPT_COMMON;
240 }
241 }
242 const char* endOfCurrentRun() const override {
243 return fCurrent;
244 }
245 bool atEnd() const override {
246 return fCurrent == fEnd;
247 }
248
249 hb_script_t currentScript() const {
250 return fCurrentScript;
251 }
252private:
253 const char* fCurrent;
254 const char* fEnd;
255 hb_unicode_funcs_t* fHBUnicode;
256 hb_script_t fCurrentScript;
257};
258
259class FontRunIterator : public RunIterator {
260public:
261 static SkTLazy<FontRunIterator> Make(const char* utf8, size_t utf8Bytes,
262 sk_sp<SkTypeface> typeface,
263 hb_font_t* hbFace,
264 sk_sp<SkFontMgr> fallbackMgr)
265 {
266 SkTLazy<FontRunIterator> ret;
267 ret.init(utf8, utf8Bytes, std::move(typeface), hbFace, std::move(fallbackMgr));
268 return ret;
269 }
270 FontRunIterator(const char* utf8, size_t utf8Bytes, sk_sp<SkTypeface> typeface,
271 hb_font_t* hbFace, sk_sp<SkFontMgr> fallbackMgr)
272 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
273 , fFallbackMgr(std::move(fallbackMgr))
274 , fHBFont(hbFace), fTypeface(std::move(typeface))
275 , fFallbackHBFont(nullptr), fFallbackTypeface(nullptr)
276 , fCurrentHBFont(fHBFont), fCurrentTypeface(fTypeface.get())
277 {}
278 void consume() override {
279 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400280 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500281 // If the starting typeface can handle this character, use it.
282 if (fTypeface->charsToGlyphs(&u, SkTypeface::kUTF32_Encoding, nullptr, 1)) {
Ben Wagnera900ad52018-08-31 17:48:19 -0400283 fCurrentTypeface = fTypeface.get();
284 fCurrentHBFont = fHBFont;
285 // If the current fallback can handle this character, use it.
286 } else if (fFallbackTypeface &&
287 fFallbackTypeface->charsToGlyphs(&u, SkTypeface::kUTF32_Encoding, nullptr, 1))
288 {
289 fCurrentTypeface = fFallbackTypeface.get();
290 fCurrentHBFont = fFallbackHBFont.get();
Ben Wagner8d45a382017-11-16 10:08:28 -0500291 // If not, try to find a fallback typeface
292 } else {
293 fFallbackTypeface.reset(fFallbackMgr->matchFamilyStyleCharacter(
294 nullptr, fTypeface->fontStyle(), nullptr, 0, u));
Ben Wagner8d45a382017-11-16 10:08:28 -0500295 fFallbackHBFont = create_hb_font(fFallbackTypeface.get());
296 fCurrentTypeface = fFallbackTypeface.get();
297 fCurrentHBFont = fFallbackHBFont.get();
Ben Wagner8d45a382017-11-16 10:08:28 -0500298 }
299
300 while (fCurrent < fEnd) {
301 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400302 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500303
Ben Wagnera900ad52018-08-31 17:48:19 -0400304 // If not using initial typeface and initial typeface has this character, stop fallback.
305 if (fCurrentTypeface != fTypeface.get() &&
Ben Wagner8d45a382017-11-16 10:08:28 -0500306 fTypeface->charsToGlyphs(&u, SkTypeface::kUTF32_Encoding, nullptr, 1))
307 {
308 fCurrent = prev;
309 return;
310 }
311 // If the current typeface cannot handle this character, stop using it.
312 if (!fCurrentTypeface->charsToGlyphs(&u, SkTypeface::kUTF32_Encoding, nullptr, 1)) {
313 fCurrent = prev;
314 return;
315 }
316 }
317 }
318 const char* endOfCurrentRun() const override {
319 return fCurrent;
320 }
321 bool atEnd() const override {
322 return fCurrent == fEnd;
323 }
324
325 SkTypeface* currentTypeface() const {
326 return fCurrentTypeface;
327 }
328 hb_font_t* currentHBFont() const {
329 return fCurrentHBFont;
330 }
331private:
332 const char* fCurrent;
333 const char* fEnd;
334 sk_sp<SkFontMgr> fFallbackMgr;
335 hb_font_t* fHBFont;
336 sk_sp<SkTypeface> fTypeface;
337 HBFont fFallbackHBFont;
338 sk_sp<SkTypeface> fFallbackTypeface;
339 hb_font_t* fCurrentHBFont;
340 SkTypeface* fCurrentTypeface;
341};
342
343class RunIteratorQueue {
344public:
345 void insert(RunIterator* runIterator) {
346 fRunIterators.insert(runIterator);
347 }
348
349 bool advanceRuns() {
350 const RunIterator* leastRun = fRunIterators.peek();
351 if (leastRun->atEnd()) {
352 SkASSERT(this->allRunsAreAtEnd());
353 return false;
354 }
355 const char* leastEnd = leastRun->endOfCurrentRun();
356 RunIterator* currentRun = nullptr;
357 SkDEBUGCODE(const char* previousEndOfCurrentRun);
358 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
359 fRunIterators.pop();
360 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
361 currentRun->consume();
362 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
363 fRunIterators.insert(currentRun);
364 }
365 return true;
366 }
367
368 const char* endOfCurrentRun() const {
369 return fRunIterators.peek()->endOfCurrentRun();
370 }
371
372private:
373 bool allRunsAreAtEnd() const {
374 for (int i = 0; i < fRunIterators.count(); ++i) {
375 if (!fRunIterators.at(i)->atEnd()) {
376 return false;
377 }
378 }
379 return true;
380 }
381
382 static bool CompareRunIterator(RunIterator* const& a, RunIterator* const& b) {
383 return *a < *b;
384 }
385 SkTDPQueue<RunIterator*, CompareRunIterator> fRunIterators;
386};
387
388struct ShapedGlyph {
389 SkGlyphID fID;
390 uint32_t fCluster;
391 SkPoint fOffset;
392 SkVector fAdvance;
393 bool fMayLineBreakBefore;
394 bool fMustLineBreakBefore;
395 bool fHasVisual;
396};
397struct ShapedRun {
Mike Reed6d595682018-12-05 17:28:14 -0500398 ShapedRun(const char* utf8Start, const char* utf8End, int numGlyphs, const SkFont& font,
Ben Wagner8d45a382017-11-16 10:08:28 -0500399 UBiDiLevel level, std::unique_ptr<ShapedGlyph[]> glyphs)
Mike Reed6d595682018-12-05 17:28:14 -0500400 : fUtf8Start(utf8Start), fUtf8End(utf8End), fNumGlyphs(numGlyphs), fFont(font)
Ben Wagner8d45a382017-11-16 10:08:28 -0500401 , fLevel(level), fGlyphs(std::move(glyphs))
402 {}
403
404 const char* fUtf8Start;
405 const char* fUtf8End;
406 int fNumGlyphs;
Mike Reed6d595682018-12-05 17:28:14 -0500407 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500408 UBiDiLevel fLevel;
409 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -0500410 SkVector fAdvance = { 0, 0 };
Ben Wagner8d45a382017-11-16 10:08:28 -0500411};
412
413static constexpr bool is_LTR(UBiDiLevel level) {
414 return (level & 1) == 0;
415}
416
Florin Malita950243d2019-01-11 11:08:35 -0500417static void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
418 const ShapedRun& run, int start, int end,
Florin Malita9867f612018-12-12 10:54:49 -0500419 SkPoint* p) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500420 unsigned len = end - start;
Florin Malita9867f612018-12-12 10:54:49 -0500421
Florin Malita950243d2019-01-11 11:08:35 -0500422 const auto buffer = handler->newRunBuffer(runInfo, run.fFont, len, run.fUtf8End - run.fUtf8Start);
Florin Malita9867f612018-12-12 10:54:49 -0500423 SkASSERT(buffer.glyphs);
424 SkASSERT(buffer.positions);
425
426 if (buffer.utf8text) {
427 memcpy(buffer.utf8text, run.fUtf8Start, run.fUtf8End - run.fUtf8Start);
428 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500429
430 for (unsigned i = 0; i < len; i++) {
431 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
432 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? start + i : end - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500433 buffer.glyphs[i] = glyph.fID;
434 buffer.positions[i] = SkPoint::Make(p->fX + glyph.fOffset.fX, p->fY - glyph.fOffset.fY);
435 if (buffer.clusters) {
436 buffer.clusters[i] = glyph.fCluster;
437 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500438 p->fX += glyph.fAdvance.fX;
439 p->fY += glyph.fAdvance.fY;
440 }
441}
442
443struct ShapedRunGlyphIterator {
444 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
445 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
446 { }
447
448 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
449 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
450 bool operator==(const ShapedRunGlyphIterator& that) const {
451 return fRuns == that.fRuns &&
452 fRunIndex == that.fRunIndex &&
453 fGlyphIndex == that.fGlyphIndex;
454 }
455 bool operator!=(const ShapedRunGlyphIterator& that) const {
456 return fRuns != that.fRuns ||
457 fRunIndex != that.fRunIndex ||
458 fGlyphIndex != that.fGlyphIndex;
459 }
460
461 ShapedGlyph* next() {
462 const SkTArray<ShapedRun>& runs = *fRuns;
463 SkASSERT(fRunIndex < runs.count());
464 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
465
466 ++fGlyphIndex;
467 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
468 fGlyphIndex = 0;
469 ++fRunIndex;
470 if (fRunIndex >= runs.count()) {
471 return nullptr;
472 }
473 }
474 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
475 }
476
477 ShapedGlyph* current() {
478 const SkTArray<ShapedRun>& runs = *fRuns;
479 if (fRunIndex >= runs.count()) {
480 return nullptr;
481 }
482 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
483 }
484
485 const SkTArray<ShapedRun>* fRuns;
486 int fRunIndex;
487 int fGlyphIndex;
488};
489
490} // namespace
491
492struct SkShaper::Impl {
493 HBFont fHarfBuzzFont;
494 HBBuffer fBuffer;
495 sk_sp<SkTypeface> fTypeface;
496 std::unique_ptr<icu::BreakIterator> fBreakIterator;
497};
498
Ben Wagnere0001732017-08-31 16:26:26 -0400499SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) {
Hal Canary0e07ad72018-02-08 13:06:56 -0500500 SkOnce once;
501 once([] { SkLoadICU(); });
502
Ben Wagnere0001732017-08-31 16:26:26 -0400503 fImpl->fTypeface = tf ? std::move(tf) : SkTypeface::MakeDefault();
504 fImpl->fHarfBuzzFont = create_hb_font(fImpl->fTypeface.get());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400505 SkASSERT(fImpl->fHarfBuzzFont);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400506 fImpl->fBuffer.reset(hb_buffer_create());
Ben Wagner8d45a382017-11-16 10:08:28 -0500507 SkASSERT(fImpl->fBuffer);
508
509 icu::Locale thai("th");
510 UErrorCode status = U_ZERO_ERROR;
511 fImpl->fBreakIterator.reset(icu::BreakIterator::createLineInstance(thai, status));
512 if (U_FAILURE(status)) {
513 SkDebugf("Could not create break iterator: %s", u_errorName(status));
514 SK_ABORT("");
515 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400516}
517
518SkShaper::~SkShaper() {}
519
Ben Wagner8d45a382017-11-16 10:08:28 -0500520bool SkShaper::good() const {
521 return fImpl->fHarfBuzzFont &&
522 fImpl->fBuffer &&
523 fImpl->fTypeface &&
524 fImpl->fBreakIterator;
525}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400526
Florin Malita950243d2019-01-11 11:08:35 -0500527SkPoint SkShaper::shape(RunHandler* handler,
Hal Canary2a1848d2018-11-26 17:23:24 -0500528 const SkFont& srcPaint,
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500529 const char* utf8,
530 size_t utf8Bytes,
531 bool leftToRight,
532 SkPoint point,
533 SkScalar width) const {
Ben Wagner67e3a302017-09-05 14:46:19 -0400534 sk_sp<SkFontMgr> fontMgr = SkFontMgr::RefDefault();
Florin Malita9867f612018-12-12 10:54:49 -0500535 SkASSERT(handler);
Ben Wagner8d45a382017-11-16 10:08:28 -0500536 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400537 //hb_script_t script = ...
Ben Wagnera25fbef2017-08-30 13:56:19 -0400538
Ben Wagner8d45a382017-11-16 10:08:28 -0500539 SkTArray<ShapedRun> runs;
540{
541 RunIteratorQueue runSegmenter;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400542
Ben Wagner8d45a382017-11-16 10:08:28 -0500543 SkTLazy<BiDiRunIterator> maybeBidi(BiDiRunIterator::Make(utf8, utf8Bytes, defaultLevel));
544 BiDiRunIterator* bidi = maybeBidi.getMaybeNull();
545 if (!bidi) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500546 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400547 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500548 runSegmenter.insert(bidi);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400549
Ben Wagner8d45a382017-11-16 10:08:28 -0500550 hb_unicode_funcs_t* hbUnicode = hb_buffer_get_unicode_funcs(fImpl->fBuffer.get());
551 SkTLazy<ScriptRunIterator> maybeScript(ScriptRunIterator::Make(utf8, utf8Bytes, hbUnicode));
552 ScriptRunIterator* script = maybeScript.getMaybeNull();
553 if (!script) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500554 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400555 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500556 runSegmenter.insert(script);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400557
Ben Wagner8d45a382017-11-16 10:08:28 -0500558 SkTLazy<FontRunIterator> maybeFont(FontRunIterator::Make(utf8, utf8Bytes,
559 fImpl->fTypeface,
560 fImpl->fHarfBuzzFont.get(),
561 std::move(fontMgr)));
562 FontRunIterator* font = maybeFont.getMaybeNull();
563 if (!font) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500564 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400565 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500566 runSegmenter.insert(font);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400567
Ben Wagner8d45a382017-11-16 10:08:28 -0500568 icu::BreakIterator& breakIterator = *fImpl->fBreakIterator;
569 {
570 UErrorCode status = U_ZERO_ERROR;
571 UText utf8UText = UTEXT_INITIALIZER;
572 utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
573 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
574 if (U_FAILURE(status)) {
575 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500576 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -0500577 }
578 breakIterator.setText(&utf8UText, status);
579 //utext_close(&utf8UText);
580 if (U_FAILURE(status)) {
581 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500582 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -0500583 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400584 }
585
Ben Wagner8d45a382017-11-16 10:08:28 -0500586 const char* utf8Start = nullptr;
587 const char* utf8End = utf8;
588 while (runSegmenter.advanceRuns()) {
589 utf8Start = utf8End;
590 utf8End = runSegmenter.endOfCurrentRun();
591
592 hb_buffer_t* buffer = fImpl->fBuffer.get();
593 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
594 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
595 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
596
Ben Wagnerc0c99b32018-08-07 10:14:18 -0400597 // Add precontext.
598 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
599
Ben Wagner8d45a382017-11-16 10:08:28 -0500600 // Populate the hb_buffer directly with utf8 cluster indexes.
601 const char* utf8Current = utf8Start;
602 while (utf8Current < utf8End) {
603 unsigned int cluster = utf8Current - utf8Start;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400604 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
Ben Wagner8d45a382017-11-16 10:08:28 -0500605 hb_buffer_add(buffer, u, cluster);
606 }
607
Ben Wagnerc0c99b32018-08-07 10:14:18 -0400608 // Add postcontext.
609 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
610
Ben Wagner8d45a382017-11-16 10:08:28 -0500611 size_t utf8runLength = utf8End - utf8Start;
612 if (!SkTFitsIn<int>(utf8runLength)) {
613 SkDebugf("Shaping error: utf8 too long");
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500614 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -0500615 }
616 hb_buffer_set_script(buffer, script->currentScript());
617 hb_direction_t direction = is_LTR(bidi->currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
618 hb_buffer_set_direction(buffer, direction);
619 // TODO: language
620 hb_buffer_guess_segment_properties(buffer);
621 // TODO: features
Hal Canary0dfa2082018-10-31 13:02:49 -0400622 if (!font->currentHBFont()) {
623 continue;
624 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500625 hb_shape(font->currentHBFont(), buffer, nullptr, 0);
626 unsigned len = hb_buffer_get_length(buffer);
627 if (len == 0) {
628 continue;
629 }
630
631 if (direction == HB_DIRECTION_RTL) {
632 // Put the clusters back in logical order.
633 // Note that the advances remain ltr.
634 hb_buffer_reverse(buffer);
635 }
636 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
637 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
638
639 if (!SkTFitsIn<int>(len)) {
640 SkDebugf("Shaping error: too many glyphs");
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500641 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -0500642 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400643
Hal Canary2a1848d2018-11-26 17:23:24 -0500644 SkFont paint(srcPaint);
Ben Wagner8d45a382017-11-16 10:08:28 -0500645 paint.setTypeface(sk_ref_sp(font->currentTypeface()));
646 ShapedRun& run = runs.emplace_back(utf8Start, utf8End, len, paint, bidi->currentLevel(),
647 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]));
648 int scaleX, scaleY;
649 hb_font_get_scale(font->currentHBFont(), &scaleX, &scaleY);
Mike Reed6d595682018-12-05 17:28:14 -0500650 double textSizeY = run.fFont.getSize() / scaleY;
651 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
Florin Malita950243d2019-01-11 11:08:35 -0500652 SkVector runAdvance = { 0, 0 };
Ben Wagner8d45a382017-11-16 10:08:28 -0500653 for (unsigned i = 0; i < len; i++) {
654 ShapedGlyph& glyph = run.fGlyphs[i];
655 glyph.fID = info[i].codepoint;
656 glyph.fCluster = info[i].cluster;
657 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
658 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
659 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
660 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
661 glyph.fHasVisual = true; //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
662 //info->mask safe_to_break;
663 glyph.fMustLineBreakBefore = false;
Florin Malita950243d2019-01-11 11:08:35 -0500664
665 runAdvance += glyph.fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500666 }
Florin Malita950243d2019-01-11 11:08:35 -0500667 run.fAdvance = runAdvance;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400668
Ben Wagner8d45a382017-11-16 10:08:28 -0500669 int32_t clusterOffset = utf8Start - utf8;
670 uint32_t previousCluster = 0xFFFFFFFF;
671 for (unsigned i = 0; i < len; ++i) {
672 ShapedGlyph& glyph = run.fGlyphs[i];
673 int32_t glyphCluster = glyph.fCluster + clusterOffset;
674 int32_t breakIteratorCurrent = breakIterator.current();
675 while (breakIteratorCurrent != icu::BreakIterator::DONE &&
676 breakIteratorCurrent < glyphCluster)
677 {
678 breakIteratorCurrent = breakIterator.next();
Ben Wagner2868b782017-08-31 14:12:27 -0400679 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500680 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
681 breakIteratorCurrent == glyphCluster;
682 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400683 }
684 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500685}
686
687// Iterate over the glyphs in logical order to mark line endings.
688{
689 SkScalar widthSoFar = 0;
690 bool previousBreakValid = false; // Set when previousBreak is set to a valid candidate break.
691 bool canAddBreakNow = false; // Disallow line breaks before the first glyph of a run.
692 ShapedRunGlyphIterator previousBreak(runs);
693 ShapedRunGlyphIterator glyphIterator(runs);
694 while (ShapedGlyph* glyph = glyphIterator.current()) {
695 if (canAddBreakNow && glyph->fMayLineBreakBefore) {
696 previousBreakValid = true;
697 previousBreak = glyphIterator;
698 }
699 SkScalar glyphWidth = glyph->fAdvance.fX;
Ben Wagnera900ad52018-08-31 17:48:19 -0400700 // TODO: if the glyph is non-visible it can be added.
Ben Wagner8d45a382017-11-16 10:08:28 -0500701 if (widthSoFar + glyphWidth < width) {
702 widthSoFar += glyphWidth;
703 glyphIterator.next();
704 canAddBreakNow = true;
705 continue;
706 }
707
Ben Wagnera900ad52018-08-31 17:48:19 -0400708 // TODO: for both of these emergency break cases
709 // don't break grapheme clusters and pull in any zero width or non-visible
Ben Wagner8d45a382017-11-16 10:08:28 -0500710 if (widthSoFar == 0) {
711 // Adding just this glyph is too much, just break with this glyph
712 glyphIterator.next();
713 previousBreak = glyphIterator;
714 } else if (!previousBreakValid) {
Ben Wagnera900ad52018-08-31 17:48:19 -0400715 // No break opportunity found yet, just break without this glyph
Ben Wagner8d45a382017-11-16 10:08:28 -0500716 previousBreak = glyphIterator;
717 }
718 glyphIterator = previousBreak;
719 glyph = glyphIterator.current();
720 if (glyph) {
721 glyph->fMustLineBreakBefore = true;
722 }
723 widthSoFar = 0;
724 previousBreakValid = false;
725 canAddBreakNow = false;
726 }
727}
728
729// Reorder the runs and glyphs per line and write them out.
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500730 SkPoint currentPoint = point;
Ben Wagner8d45a382017-11-16 10:08:28 -0500731{
732 ShapedRunGlyphIterator previousBreak(runs);
733 ShapedRunGlyphIterator glyphIterator(runs);
734 SkScalar maxAscent = 0;
735 SkScalar maxDescent = 0;
736 SkScalar maxLeading = 0;
737 int previousRunIndex = -1;
Florin Malita950243d2019-01-11 11:08:35 -0500738 size_t lineIndex = 0;
Ben Wagner8d45a382017-11-16 10:08:28 -0500739 while (glyphIterator.current()) {
740 int runIndex = glyphIterator.fRunIndex;
741 int glyphIndex = glyphIterator.fGlyphIndex;
742 ShapedGlyph* nextGlyph = glyphIterator.next();
743
744 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -0500745 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -0500746 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -0500747 maxAscent = SkTMin(maxAscent, metrics.fAscent);
748 maxDescent = SkTMax(maxDescent, metrics.fDescent);
749 maxLeading = SkTMax(maxLeading, metrics.fLeading);
750 previousRunIndex = runIndex;
751 }
752
753 // Nothing can be written until the baseline is known.
754 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
755 continue;
756 }
757
758 currentPoint.fY -= maxAscent;
759
760 int numRuns = runIndex - previousBreak.fRunIndex + 1;
761 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
762 for (int i = 0; i < numRuns; ++i) {
763 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
764 }
765 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
766 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
767
768 for (int i = 0; i < numRuns; ++i) {
769 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
770
771 int startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
772 ? previousBreak.fGlyphIndex
773 : 0;
774 int endGlyphIndex = (logicalIndex == runIndex)
775 ? glyphIndex + 1
776 : runs[logicalIndex].fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -0500777
778 const auto& run = runs[logicalIndex];
779 const RunHandler::RunInfo info = {
780 lineIndex,
781 run.fAdvance,
782 maxAscent,
783 maxDescent,
784 maxLeading,
785 };
786 append(handler, info, run, startGlyphIndex, endGlyphIndex, &currentPoint);
Ben Wagner8d45a382017-11-16 10:08:28 -0500787 }
788
789 currentPoint.fY += maxDescent + maxLeading;
790 currentPoint.fX = point.fX;
791 maxAscent = 0;
792 maxDescent = 0;
793 maxLeading = 0;
794 previousRunIndex = -1;
Florin Malita950243d2019-01-11 11:08:35 -0500795 ++lineIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -0500796 previousBreak = glyphIterator;
797 }
798}
799
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500800 return currentPoint;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400801}