blob: 9cc1bb948bde956bbbc89265135837af0ec1702c [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/core/SkFont.h"
9#include "include/core/SkFontArguments.h"
10#include "include/core/SkFontMetrics.h"
11#include "include/core/SkFontMgr.h"
12#include "include/core/SkFontTypes.h"
13#include "include/core/SkPaint.h"
14#include "include/core/SkPoint.h"
15#include "include/core/SkRect.h"
16#include "include/core/SkRefCnt.h"
17#include "include/core/SkScalar.h"
18#include "include/core/SkStream.h"
19#include "include/core/SkTypeface.h"
20#include "include/core/SkTypes.h"
21#include "include/private/SkBitmaskEnum.h"
22#include "include/private/SkMalloc.h"
23#include "include/private/SkTArray.h"
24#include "include/private/SkTFitsIn.h"
25#include "include/private/SkTemplates.h"
26#include "include/private/SkTo.h"
27#include "modules/skshaper/include/SkShaper.h"
28#include "src/core/SkMakeUnique.h"
29#include "src/core/SkTDPQueue.h"
30#include "src/utils/SkUTF.h"
Ben Wagner17774242018-08-07 14:31:33 -040031
32#include <hb.h>
Ben Wagner1383a382019-04-03 17:53:53 -040033#include <hb-icu.h>
Ben Wagner17774242018-08-07 14:31:33 -040034#include <hb-ot.h>
Ben Wagner17774242018-08-07 14:31:33 -040035#include <unicode/ubidi.h>
Ben Wagner1383a382019-04-03 17:53:53 -040036#include <unicode/ubrk.h>
37#include <unicode/umachine.h>
Ben Wagner17774242018-08-07 14:31:33 -040038#include <unicode/urename.h>
Ben Wagner1383a382019-04-03 17:53:53 -040039#include <unicode/uscript.h>
40#include <unicode/ustring.h>
Ben Wagner17774242018-08-07 14:31:33 -040041#include <unicode/utext.h>
42#include <unicode/utypes.h>
43
Ben Wagner0ec8ec22018-09-04 18:17:13 -040044#include <cstring>
Ben Wagner17774242018-08-07 14:31:33 -040045#include <memory>
Ben Wagner1383a382019-04-03 17:53:53 -040046#include <type_traits>
Ben Wagner17774242018-08-07 14:31:33 -040047#include <utility>
Ben Wagnera25fbef2017-08-30 13:56:19 -040048
Hal Canary61021922019-02-06 12:29:11 -050049#if defined(SK_USING_THIRD_PARTY_ICU)
Hal Canary32498f02019-02-04 15:36:31 -050050#include "SkLoadICU.h"
Hal Canary61021922019-02-06 12:29:11 -050051#endif
Hal Canary32498f02019-02-04 15:36:31 -050052
Ben Wagner2fc14742019-02-06 16:37:44 -050053namespace skstd {
54template <> struct is_bitmask_enum<hb_buffer_flags_t> : std::true_type {};
55}
56
Ben Wagnera25fbef2017-08-30 13:56:19 -040057namespace {
58template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<void, T, P>>;
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -050059using HBBlob = resource<hb_blob_t , hb_blob_destroy >;
60using HBFace = resource<hb_face_t , hb_face_destroy >;
61using HBFont = resource<hb_font_t , hb_font_destroy >;
62using HBBuffer = resource<hb_buffer_t , hb_buffer_destroy>;
63using ICUBiDi = resource<UBiDi , ubidi_close >;
Ben Wagner0ec8ec22018-09-04 18:17:13 -040064using ICUBrk = resource<UBreakIterator, ubrk_close >;
Ben Wagnera25fbef2017-08-30 13:56:19 -040065
66HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
67 size_t size = asset->getLength();
68 HBBlob blob;
69 if (const void* base = asset->getMemoryBase()) {
70 blob.reset(hb_blob_create((char*)base, SkToUInt(size),
71 HB_MEMORY_MODE_READONLY, asset.release(),
72 [](void* p) { delete (SkStreamAsset*)p; }));
73 } else {
74 // SkDebugf("Extra SkStreamAsset copy\n");
75 void* ptr = size ? sk_malloc_throw(size) : nullptr;
76 asset->read(ptr, size);
77 blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
78 HB_MEMORY_MODE_READONLY, ptr, sk_free));
79 }
80 SkASSERT(blob);
81 hb_blob_make_immutable(blob.get());
82 return blob;
83}
Ben Wagnera25fbef2017-08-30 13:56:19 -040084
Ben Wagnerf61c9362019-02-13 12:01:45 -050085hb_position_t skhb_position(SkScalar value) {
86 // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
87 constexpr int kHbPosition1 = 1 << 16;
88 return SkScalarRoundToInt(value * kHbPosition1);
89}
90
91hb_bool_t skhb_glyph(hb_font_t* hb_font,
92 void* font_data,
93 hb_codepoint_t unicode,
94 hb_codepoint_t variation_selector,
95 hb_codepoint_t* glyph,
96 void* user_data) {
97 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
98
99 *glyph = font.unicharToGlyph(unicode);
100 return *glyph != 0;
101}
102
103hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
104 void* font_data,
105 hb_codepoint_t unicode,
106 hb_codepoint_t* glyph,
107 void* user_data) {
108 return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
109}
110
111unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
112 unsigned int count,
113 const hb_codepoint_t *unicodes,
114 unsigned int unicode_stride,
115 hb_codepoint_t *glyphs,
116 unsigned int glyph_stride,
117 void *user_data) {
118 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
119
120 // Batch call textToGlyphs since entry cost is not cheap.
121 // Copy requred because textToGlyphs is dense and hb is strided.
122 SkAutoSTMalloc<256, SkUnichar> unicode(count);
123 for (unsigned i = 0; i < count; i++) {
124 unicode[i] = *unicodes;
125 unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
126 }
127 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
Ben Wagner51e15a62019-05-07 15:38:46 -0400128 font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), SkTextEncoding::kUTF32,
Ben Wagnerf61c9362019-02-13 12:01:45 -0500129 glyph.get(), count);
130
131 // Copy the results back to the sparse array.
132 for (unsigned i = 0; i < count; i++) {
133 *glyphs = glyph[i];
134 glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
135 }
136 // TODO: supposed to return index of first 0?
137 return count;
138}
139
140hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
141 void* font_data,
142 hb_codepoint_t codepoint,
143 void* user_data) {
144 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
145
146 SkScalar advance;
147 SkGlyphID glyph = SkTo<SkGlyphID>(codepoint);
148
149 font.getWidths(&glyph, 1, &advance);
150 if (!font.isSubpixel()) {
151 advance = SkScalarRoundToInt(advance);
152 }
153 return skhb_position(advance);
154}
155
156void skhb_glyph_h_advances(hb_font_t* hb_font,
157 void* font_data,
158 unsigned count,
159 const hb_codepoint_t* glyphs,
160 unsigned int glyph_stride,
161 hb_position_t* advances,
162 unsigned int advance_stride,
163 void* user_data) {
164 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
165
166 // Batch call getWidths since entry cost is not cheap.
167 // Copy requred because getWidths is dense and hb is strided.
168 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
169 for (unsigned i = 0; i < count; i++) {
170 glyph[i] = *glyphs;
171 glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
172 }
173 SkAutoSTMalloc<256, SkScalar> advance(count);
174 font.getWidths(glyph.get(), count, advance.get());
175
176 if (!font.isSubpixel()) {
177 for (unsigned i = 0; i < count; i++) {
178 advance[i] = SkScalarRoundToInt(advance[i]);
179 }
180 }
181
182 // Copy the results back to the sparse array.
183 for (unsigned i = 0; i < count; i++) {
184 *advances = skhb_position(advance[i]);
185 advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
186 }
187}
188
189// HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
190// fallback mark positioning, i.e. the situation when the font does not have
191// mark anchors or other mark positioning rules, but instead HarfBuzz is
192// supposed to heuristically place combining marks around base glyphs. HarfBuzz
193// does this by measuring "ink boxes" of glyphs, and placing them according to
194// Unicode mark classes. Above, below, centered or left or right, etc.
195hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
196 void* font_data,
197 hb_codepoint_t codepoint,
198 hb_glyph_extents_t* extents,
199 void* user_data) {
200 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
201
202 SkASSERT(codepoint < 0xFFFFu);
203 SkASSERT(extents);
204
205 SkRect sk_bounds;
206 SkGlyphID glyph = codepoint;
207
208 font.getWidths(&glyph, 1, nullptr, &sk_bounds);
209 if (!font.isSubpixel()) {
210 sk_bounds.set(sk_bounds.roundOut());
211 }
212
213 // Skia is y-down but HarfBuzz is y-up.
214 extents->x_bearing = skhb_position(sk_bounds.fLeft);
215 extents->y_bearing = skhb_position(-sk_bounds.fTop);
216 extents->width = skhb_position(sk_bounds.width());
217 extents->height = skhb_position(-sk_bounds.height());
218 return true;
219}
220
Kevin Lubick867da4b2019-02-22 15:55:39 -0500221#define SK_HB_VERSION_CHECK(x, y, z) \
222 (HB_VERSION_MAJOR > (x)) || \
223 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR > (y)) || \
224 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
225
Ben Wagnerf61c9362019-02-13 12:01:45 -0500226hb_font_funcs_t* skhb_get_font_funcs() {
227 static hb_font_funcs_t* const funcs = []{
228 // HarfBuzz will use the default (parent) implementation if they aren't set.
229 hb_font_funcs_t* const funcs = hb_font_funcs_create();
230 hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
231 hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500232#if SK_HB_VERSION_CHECK(2, 0, 0)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500233 hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500234#else
235 sk_ignore_unused_variable(skhb_nominal_glyphs);
236#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500237 hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500238#if SK_HB_VERSION_CHECK(1, 8, 6)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500239 hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500240#else
241 sk_ignore_unused_variable(skhb_glyph_h_advances);
242#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500243 hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
244 hb_font_funcs_make_immutable(funcs);
245 return funcs;
246 }();
247 SkASSERT(funcs);
248 return funcs;
249}
250
251hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
252 SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
253
254 const size_t tableSize = typeface.getTableSize(tag);
255 if (!tableSize) {
Hal Canary0dfa2082018-10-31 13:02:49 -0400256 return nullptr;
257 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500258
259 void* buffer = sk_malloc_throw(tableSize);
260 if (!buffer) {
261 return nullptr;
262 }
263
264 size_t actualSize = typeface.getTableData(tag, 0, tableSize, buffer);
265 if (tableSize != actualSize) {
266 sk_free(buffer);
267 return nullptr;
268 }
269
270 return hb_blob_create(reinterpret_cast<char*>(buffer), tableSize,
271 HB_MEMORY_MODE_WRITABLE, buffer, sk_free);
272}
273
274HBFont create_hb_font(const SkFont& font) {
Ben Wagnera25fbef2017-08-30 13:56:19 -0400275 int index;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500276 std::unique_ptr<SkStreamAsset> typefaceAsset = font.getTypeface()->openStream(&index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500277 HBFace face;
Hal Canaryddef43f2018-11-16 10:53:51 -0500278 if (!typefaceAsset) {
Ben Wagnerf61c9362019-02-13 12:01:45 -0500279 face.reset(hb_face_create_for_tables(
280 skhb_get_table,
281 reinterpret_cast<void *>(font.refTypeface().release()),
282 [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
283 } else {
284 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
285 face.reset(hb_face_create(blob.get(), (unsigned)index));
Hal Canaryddef43f2018-11-16 10:53:51 -0500286 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400287 SkASSERT(face);
288 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -0400289 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400290 }
291 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500292 hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400293
Ben Wagnerf61c9362019-02-13 12:01:45 -0500294 HBFont otFont(hb_font_create(face.get()));
295 SkASSERT(otFont);
296 if (!otFont) {
Ben Wagnere0001732017-08-31 16:26:26 -0400297 return nullptr;
298 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500299 hb_ot_font_set_funcs(otFont.get());
300 int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
Ben Wagnere0001732017-08-31 16:26:26 -0400301 if (axis_count > 0) {
302 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500303 if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
304 hb_font_set_variations(otFont.get(),
Ben Wagnere0001732017-08-31 16:26:26 -0400305 reinterpret_cast<hb_variation_t*>(axis_values.get()),
306 axis_count);
307 }
308 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500309
310 // Creating a sub font means that non-available functions
311 // are found from the parent.
312 HBFont skFont(hb_font_create_sub_font(otFont.get()));
313 hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
314 reinterpret_cast<void *>(new SkFont(font)),
315 [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
316 int scale = skhb_position(font.getSize());
317 hb_font_set_scale(skFont.get(), scale, scale);
318
319 return skFont;
Ben Wagnere0001732017-08-31 16:26:26 -0400320}
321
Ben Wagner1383a382019-04-03 17:53:53 -0400322/** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
Hal Canaryf107a2f2018-07-25 16:52:48 -0400323static inline SkUnichar utf8_next(const char** ptr, const char* end) {
324 SkUnichar val = SkUTF::NextUTF8(ptr, end);
Ben Wagner1383a382019-04-03 17:53:53 -0400325 return val < 0 ? 0xFFFD : val;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400326}
327
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400328class IcuBiDiRunIterator final : public SkShaper::BiDiRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500329public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400330 IcuBiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500331 : fBidi(std::move(bidi))
332 , fEndOfCurrentRun(utf8)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400333 , fBegin(utf8)
334 , fEnd(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500335 , fUTF16LogicalPosition(0)
336 , fLevel(UBIDI_DEFAULT_LTR)
337 {}
338 void consume() override {
339 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
340 int32_t endPosition = ubidi_getLength(fBidi.get());
341 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400342 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400343 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500344 UBiDiLevel level;
345 while (fUTF16LogicalPosition < endPosition) {
346 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
347 if (level != fLevel) {
348 break;
349 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400350 u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400351 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500352 }
353 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400354 size_t endOfCurrentRun() const override {
355 return fEndOfCurrentRun - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500356 }
357 bool atEnd() const override {
358 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
359 }
360
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400361 UBiDiLevel currentLevel() const override {
Ben Wagner8d45a382017-11-16 10:08:28 -0500362 return fLevel;
363 }
364private:
365 ICUBiDi fBidi;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400366 char const * fEndOfCurrentRun;
367 char const * const fBegin;
368 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500369 int32_t fUTF16LogicalPosition;
370 UBiDiLevel fLevel;
371};
372
Ben Wagner1383a382019-04-03 17:53:53 -0400373class HbIcuScriptRunIterator final : public SkShaper::ScriptRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500374public:
Ben Wagner1383a382019-04-03 17:53:53 -0400375 HbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400376 : fCurrent(utf8), fBegin(utf8), fEnd(fCurrent + utf8Bytes)
Ben Wagner8d45a382017-11-16 10:08:28 -0500377 , fCurrentScript(HB_SCRIPT_UNKNOWN)
378 {}
Ben Wagner1383a382019-04-03 17:53:53 -0400379 static hb_script_t hb_script_from_icu(SkUnichar u) {
380 UErrorCode status = U_ZERO_ERROR;
381 UScriptCode scriptCode = uscript_getScript(u, &status);
382
383 if (U_FAILURE (status)) {
384 return HB_SCRIPT_UNKNOWN;
385 }
386
387 return hb_icu_script_to_script(scriptCode);
388 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500389 void consume() override {
390 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400391 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400392 fCurrentScript = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500393 while (fCurrent < fEnd) {
394 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400395 u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400396 const hb_script_t script = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500397 if (script != fCurrentScript) {
398 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
399 fCurrentScript = script;
400 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
401 continue;
402 } else {
403 fCurrent = prev;
404 break;
405 }
406 }
407 }
408 if (fCurrentScript == HB_SCRIPT_INHERITED) {
409 fCurrentScript = HB_SCRIPT_COMMON;
410 }
411 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400412 size_t endOfCurrentRun() const override {
413 return fCurrent - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500414 }
415 bool atEnd() const override {
416 return fCurrent == fEnd;
417 }
418
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400419 SkFourByteTag currentScript() const override {
420 return SkSetFourByteTag(HB_UNTAG(fCurrentScript));
Ben Wagner8d45a382017-11-16 10:08:28 -0500421 }
422private:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400423 char const * fCurrent;
424 char const * const fBegin;
425 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500426 hb_script_t fCurrentScript;
427};
428
Ben Wagner8d45a382017-11-16 10:08:28 -0500429class RunIteratorQueue {
430public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400431 void insert(SkShaper::RunIterator* runIterator) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500432 fRunIterators.insert(runIterator);
433 }
434
435 bool advanceRuns() {
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400436 const SkShaper::RunIterator* leastRun = fRunIterators.peek();
Ben Wagner8d45a382017-11-16 10:08:28 -0500437 if (leastRun->atEnd()) {
438 SkASSERT(this->allRunsAreAtEnd());
439 return false;
440 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400441 const size_t leastEnd = leastRun->endOfCurrentRun();
442 SkShaper::RunIterator* currentRun = nullptr;
443 SkDEBUGCODE(size_t previousEndOfCurrentRun);
Ben Wagner8d45a382017-11-16 10:08:28 -0500444 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
445 fRunIterators.pop();
446 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
447 currentRun->consume();
448 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
449 fRunIterators.insert(currentRun);
450 }
451 return true;
452 }
453
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400454 size_t endOfCurrentRun() const {
Ben Wagner8d45a382017-11-16 10:08:28 -0500455 return fRunIterators.peek()->endOfCurrentRun();
456 }
457
458private:
459 bool allRunsAreAtEnd() const {
460 for (int i = 0; i < fRunIterators.count(); ++i) {
461 if (!fRunIterators.at(i)->atEnd()) {
462 return false;
463 }
464 }
465 return true;
466 }
467
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400468 static bool CompareRunIterator(SkShaper::RunIterator* const& a, SkShaper::RunIterator* const& b) {
469 return a->endOfCurrentRun() < b->endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500470 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400471 SkTDPQueue<SkShaper::RunIterator*, CompareRunIterator> fRunIterators;
Ben Wagner8d45a382017-11-16 10:08:28 -0500472};
473
474struct ShapedGlyph {
475 SkGlyphID fID;
476 uint32_t fCluster;
477 SkPoint fOffset;
478 SkVector fAdvance;
479 bool fMayLineBreakBefore;
480 bool fMustLineBreakBefore;
481 bool fHasVisual;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400482 bool fGraphemeBreakBefore;
483 bool fUnsafeToBreak;
Ben Wagner8d45a382017-11-16 10:08:28 -0500484};
485struct ShapedRun {
Ben Wagner7415a422019-03-25 15:38:22 -0400486 ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, UBiDiLevel level,
487 std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
488 : fUtf8Range(utf8Range), fFont(font), fLevel(level)
489 , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
Ben Wagner8d45a382017-11-16 10:08:28 -0500490 {}
491
Ben Wagner7415a422019-03-25 15:38:22 -0400492 SkShaper::RunHandler::Range fUtf8Range;
Mike Reed6d595682018-12-05 17:28:14 -0500493 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500494 UBiDiLevel fLevel;
495 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Ben Wagner7415a422019-03-25 15:38:22 -0400496 size_t fNumGlyphs;
497 SkVector fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500498};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400499struct ShapedLine {
500 SkTArray<ShapedRun> runs;
501 SkVector fAdvance = { 0, 0 };
502};
Ben Wagner8d45a382017-11-16 10:08:28 -0500503
Ben Wagner1383a382019-04-03 17:53:53 -0400504constexpr bool is_LTR(UBiDiLevel level) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500505 return (level & 1) == 0;
506}
507
Ben Wagner1383a382019-04-03 17:53:53 -0400508void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400509 const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex) {
Ben Wagner7415a422019-03-25 15:38:22 -0400510 SkASSERT(startGlyphIndex <= endGlyphIndex);
511 const size_t glyphLen = endGlyphIndex - startGlyphIndex;
Florin Malita9867f612018-12-12 10:54:49 -0500512
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400513 const auto buffer = handler->runBuffer(runInfo);
Florin Malita9867f612018-12-12 10:54:49 -0500514 SkASSERT(buffer.glyphs);
515 SkASSERT(buffer.positions);
516
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400517 SkVector advance = {0,0};
Ben Wagner7415a422019-03-25 15:38:22 -0400518 for (size_t i = 0; i < glyphLen; i++) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500519 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
Ben Wagner7415a422019-03-25 15:38:22 -0400520 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
521 : endGlyphIndex - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500522 buffer.glyphs[i] = glyph.fID;
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400523 if (buffer.offsets) {
524 buffer.positions[i] = advance + buffer.point;
525 buffer.offsets[i] = glyph.fOffset; //TODO: invert glyph.fOffset.fY?
526 } else {
527 buffer.positions[i] = advance + buffer.point + glyph.fOffset; //TODO: invert glyph.fOffset.fY?
528 }
Florin Malita9867f612018-12-12 10:54:49 -0500529 if (buffer.clusters) {
530 buffer.clusters[i] = glyph.fCluster;
531 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400532 advance += glyph.fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500533 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400534 handler->commitRunBuffer(runInfo);
Ben Wagner8d45a382017-11-16 10:08:28 -0500535}
536
Ben Wagner1383a382019-04-03 17:53:53 -0400537void emit(const ShapedLine& line, SkShaper::RunHandler* handler) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400538 // Reorder the runs and glyphs per line and write them out.
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400539 handler->beginLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400540
541 int numRuns = line.runs.size();
542 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
543 for (int i = 0; i < numRuns; ++i) {
544 runLevels[i] = line.runs[i].fLevel;
545 }
546 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
547 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
548
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400549 for (int i = 0; i < numRuns; ++i) {
550 int logicalIndex = logicalFromVisual[i];
551
552 const auto& run = line.runs[logicalIndex];
553 const SkShaper::RunHandler::RunInfo info = {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400554 run.fFont,
555 run.fLevel,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400556 run.fAdvance,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400557 run.fNumGlyphs,
558 run.fUtf8Range
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400559 };
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400560 handler->runInfo(info);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400561 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400562 handler->commitRunInfo();
563 for (int i = 0; i < numRuns; ++i) {
564 int logicalIndex = logicalFromVisual[i];
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400565
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400566 const auto& run = line.runs[logicalIndex];
567 const SkShaper::RunHandler::RunInfo info = {
568 run.fFont,
569 run.fLevel,
570 run.fAdvance,
571 run.fNumGlyphs,
572 run.fUtf8Range
573 };
574 append(handler, info, run, 0, run.fNumGlyphs);
575 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400576
Florin Malita500133b2019-02-07 10:56:55 -0500577 handler->commitLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400578}
579
Ben Wagner8d45a382017-11-16 10:08:28 -0500580struct ShapedRunGlyphIterator {
581 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
582 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
583 { }
584
585 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
586 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
587 bool operator==(const ShapedRunGlyphIterator& that) const {
588 return fRuns == that.fRuns &&
589 fRunIndex == that.fRunIndex &&
590 fGlyphIndex == that.fGlyphIndex;
591 }
592 bool operator!=(const ShapedRunGlyphIterator& that) const {
593 return fRuns != that.fRuns ||
594 fRunIndex != that.fRunIndex ||
595 fGlyphIndex != that.fGlyphIndex;
596 }
597
598 ShapedGlyph* next() {
599 const SkTArray<ShapedRun>& runs = *fRuns;
600 SkASSERT(fRunIndex < runs.count());
601 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
602
603 ++fGlyphIndex;
604 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
605 fGlyphIndex = 0;
606 ++fRunIndex;
607 if (fRunIndex >= runs.count()) {
608 return nullptr;
609 }
610 }
611 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
612 }
613
614 ShapedGlyph* current() {
615 const SkTArray<ShapedRun>& runs = *fRuns;
616 if (fRunIndex >= runs.count()) {
617 return nullptr;
618 }
619 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
620 }
621
622 const SkTArray<ShapedRun>* fRuns;
623 int fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -0400624 size_t fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -0500625};
626
Ben Wagner51874e32019-04-04 15:21:20 -0400627class ShaperHarfBuzz : public SkShaper {
Ben Wagnerb0591942019-02-15 14:46:18 -0500628public:
Ben Wagner51874e32019-04-04 15:21:20 -0400629 ShaperHarfBuzz(HBBuffer, ICUBrk line, ICUBrk grapheme);
630protected:
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400631 ICUBrk fLineBreakIterator;
632 ICUBrk fGraphemeBreakIterator;
633
Ben Wagner51874e32019-04-04 15:21:20 -0400634 ShapedRun shape(const char* utf8, size_t utf8Bytes,
635 const char* utf8Start,
636 const char* utf8End,
637 const BiDiRunIterator&,
638 const LanguageRunIterator&,
639 const ScriptRunIterator&,
640 const FontRunIterator&) const;
641private:
642 HBBuffer fBuffer;
643
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400644 void shape(const char* utf8, size_t utf8Bytes,
645 const SkFont&,
646 bool leftToRight,
647 SkScalar width,
648 RunHandler*) const override;
Ben Wagnerb0591942019-02-15 14:46:18 -0500649
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400650 void shape(const char* utf8Text, size_t textBytes,
651 FontRunIterator&,
652 BiDiRunIterator&,
653 ScriptRunIterator&,
654 LanguageRunIterator&,
655 SkScalar width,
656 RunHandler*) const override;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400657
Ben Wagner51874e32019-04-04 15:21:20 -0400658 virtual void wrap(char const * const utf8, size_t utf8Bytes,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400659 const BiDiRunIterator&,
660 const LanguageRunIterator&,
661 const ScriptRunIterator&,
662 const FontRunIterator&,
663 RunIteratorQueue& runSegmenter,
664 SkScalar width,
Ben Wagner51874e32019-04-04 15:21:20 -0400665 RunHandler*) const = 0;
Ben Wagner8d45a382017-11-16 10:08:28 -0500666};
667
Ben Wagner51874e32019-04-04 15:21:20 -0400668class ShaperDrivenWrapper : public ShaperHarfBuzz {
669public:
670 using ShaperHarfBuzz::ShaperHarfBuzz;
671private:
672 void wrap(char const * const utf8, size_t utf8Bytes,
673 const BiDiRunIterator&,
674 const LanguageRunIterator&,
675 const ScriptRunIterator&,
676 const FontRunIterator&,
677 RunIteratorQueue& runSegmenter,
678 SkScalar width,
679 RunHandler*) const override;
680};
Ben Wagnerb0591942019-02-15 14:46:18 -0500681
Ben Wagner51874e32019-04-04 15:21:20 -0400682class ShapeThenWrap : public ShaperHarfBuzz {
683public:
684 using ShaperHarfBuzz::ShaperHarfBuzz;
685private:
686 void wrap(char const * const utf8, size_t utf8Bytes,
687 const BiDiRunIterator&,
688 const LanguageRunIterator&,
689 const ScriptRunIterator&,
690 const FontRunIterator&,
691 RunIteratorQueue& runSegmenter,
692 SkScalar width,
693 RunHandler*) const override;
694};
695
696static std::unique_ptr<SkShaper> MakeHarfBuzz(bool correct) {
697 #if defined(SK_USING_THIRD_PARTY_ICU)
Hal Canary61021922019-02-06 12:29:11 -0500698 if (!SkLoadICU()) {
Ben Wagner51874e32019-04-04 15:21:20 -0400699 SkDEBUGF("SkLoadICU() failed!\n");
700 return nullptr;
Hal Canary61021922019-02-06 12:29:11 -0500701 }
Ben Wagner51874e32019-04-04 15:21:20 -0400702 #endif
703 HBBuffer buffer(hb_buffer_create());
704 if (!buffer) {
705 SkDEBUGF("Could not create hb_buffer");
706 return nullptr;
707 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500708
Ben Wagner8d45a382017-11-16 10:08:28 -0500709 UErrorCode status = U_ZERO_ERROR;
Ben Wagner51874e32019-04-04 15:21:20 -0400710 ICUBrk lineBreakIterator(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
711 if (!lineBreakIterator || U_FAILURE(status)) {
712 SkDEBUGF("Could not create line break iterator: %s", u_errorName(status));
713 return nullptr;
Ben Wagner8d45a382017-11-16 10:08:28 -0500714 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400715
Ben Wagner51874e32019-04-04 15:21:20 -0400716 ICUBrk graphemeBreakIterator(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
717 if (!graphemeBreakIterator || U_FAILURE(status)) {
718 SkDEBUGF("Could not create grapheme break iterator: %s", u_errorName(status));
719 return nullptr;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400720 }
721
Ben Wagner51874e32019-04-04 15:21:20 -0400722 if (correct) {
723 return skstd::make_unique<ShaperDrivenWrapper>(
724 std::move(buffer), std::move(lineBreakIterator), std::move(graphemeBreakIterator));
725 } else {
726 return skstd::make_unique<ShapeThenWrap>(
727 std::move(buffer), std::move(lineBreakIterator), std::move(graphemeBreakIterator));
728 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400729}
730
Ben Wagner51874e32019-04-04 15:21:20 -0400731ShaperHarfBuzz::ShaperHarfBuzz(HBBuffer buffer, ICUBrk line, ICUBrk grapheme)
732 : fLineBreakIterator(std::move(line))
733 , fGraphemeBreakIterator(std::move(grapheme))
734 , fBuffer(std::move(buffer))
735{}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400736
Ben Wagner51874e32019-04-04 15:21:20 -0400737void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
738 const SkFont& srcFont,
739 bool leftToRight,
740 SkScalar width,
741 RunHandler* handler) const
Ben Wagner8d45a382017-11-16 10:08:28 -0500742{
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400743 SkASSERT(handler);
744 sk_sp<SkFontMgr> fontMgr = SkFontMgr::RefDefault();
745 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
746
Ben Wagner1383a382019-04-03 17:53:53 -0400747 std::unique_ptr<BiDiRunIterator> bidi(MakeIcuBiDiRunIterator(utf8, utf8Bytes, defaultLevel));
Ben Wagner8d45a382017-11-16 10:08:28 -0500748 if (!bidi) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400749 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400750 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400751
Ben Wagner1383a382019-04-03 17:53:53 -0400752 std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400753 if (!language) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400754 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400755 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400756
Ben Wagner1383a382019-04-03 17:53:53 -0400757 std::unique_ptr<ScriptRunIterator> script(MakeHbIcuScriptRunIterator(utf8, utf8Bytes));
Ben Wagner8d45a382017-11-16 10:08:28 -0500758 if (!script) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400759 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400760 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400761
Ben Wagner1383a382019-04-03 17:53:53 -0400762 std::unique_ptr<FontRunIterator> font(MakeFontMgrRunIterator(utf8, utf8Bytes,
763 srcFont, std::move(fontMgr)));
Ben Wagner8d45a382017-11-16 10:08:28 -0500764 if (!font) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400765 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400766 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400767
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400768 this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400769}
770
Ben Wagner51874e32019-04-04 15:21:20 -0400771void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
772 FontRunIterator& font,
773 BiDiRunIterator& bidi,
774 ScriptRunIterator& script,
775 LanguageRunIterator& language,
776 SkScalar width,
777 RunHandler* handler) const
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400778{
779 RunIteratorQueue runSegmenter;
780 runSegmenter.insert(&font);
781 runSegmenter.insert(&bidi);
782 runSegmenter.insert(&script);
783 runSegmenter.insert(&language);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400784
Ben Wagner51874e32019-04-04 15:21:20 -0400785 this->wrap(utf8, utf8Bytes, bidi, language, script, font, runSegmenter, width, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400786}
787
Ben Wagner51874e32019-04-04 15:21:20 -0400788void ShaperDrivenWrapper::wrap(char const * const utf8, size_t utf8Bytes,
789 const BiDiRunIterator& bidi,
790 const LanguageRunIterator& language,
791 const ScriptRunIterator& script,
792 const FontRunIterator& font,
793 RunIteratorQueue& runSegmenter,
794 SkScalar width,
795 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400796{
797 ShapedLine line;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400798
799 const char* utf8Start = nullptr;
800 const char* utf8End = utf8;
801 while (runSegmenter.advanceRuns()) { // For each item
802 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400803 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400804
Ben Wagner7415a422019-03-25 15:38:22 -0400805 ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400806 bool modelNeedsRegenerated = true;
Ben Wagner7415a422019-03-25 15:38:22 -0400807 int modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400808
809 struct TextProps {
810 int glyphLen = 0;
811 SkVector advance = {0, 0};
812 };
813 // map from character position to [safe to break, glyph position, advance]
814 std::unique_ptr<TextProps[]> modelText;
815 int modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400816 SkVector modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400817
818 while (utf8Start < utf8End) { // While there are still code points left in this item
819 size_t utf8runLength = utf8End - utf8Start;
820 if (modelNeedsRegenerated) {
821 model = shape(utf8, utf8Bytes,
822 utf8Start, utf8End,
823 bidi, language, script, font);
Ben Wagner7415a422019-03-25 15:38:22 -0400824 modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400825
826 SkVector advance = {0, 0};
827 modelText.reset(new TextProps[utf8runLength + 1]());
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500828 size_t modelStartCluster = utf8Start - utf8;
Ben Wagner7415a422019-03-25 15:38:22 -0400829 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
Ben Wagner84cc4612019-02-14 17:13:21 -0500830 SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
Ben Wagner2fe1e232019-02-14 17:37:02 -0500831 SkASSERT( model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400832 if (!model.fGlyphs[i].fUnsafeToBreak) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500833 modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
834 modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400835 }
836 advance += model.fGlyphs[i].fAdvance;
837 }
838 // Assume it is always safe to break after the end of an item
839 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
840 modelText[utf8runLength].advance = model.fAdvance;
841 modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400842 modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400843 modelNeedsRegenerated = false;
844 }
845
846 // TODO: break iterator per item, but just reset position if needed?
847 // Maybe break iterator with model?
848 UBreakIterator& breakIterator = *fLineBreakIterator;
849 {
850 UErrorCode status = U_ZERO_ERROR;
851 UText utf8UText = UTEXT_INITIALIZER;
852 utext_openUTF8(&utf8UText, utf8Start, utf8runLength, &status);
853 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
854 if (U_FAILURE(status)) {
855 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400856 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400857 }
858 ubrk_setUText(&breakIterator, &utf8UText, &status);
859 if (U_FAILURE(status)) {
860 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400861 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400862 }
863 }
864
Ben Wagner7415a422019-03-25 15:38:22 -0400865 ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
866 { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
867 bool bestIsInvalid = true;
868 bool bestUsesModelForGlyphs = false;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400869 SkScalar widthLeft = width - line.fAdvance.fX;
870
871 for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
872 breakIteratorCurrent != UBRK_DONE;
873 breakIteratorCurrent = ubrk_next(&breakIterator))
874 {
875 // TODO: if past a safe to break, future safe to break will be at least as long
876
877 // TODO: adjust breakIteratorCurrent by ignorable whitespace
Ben Wagner7415a422019-03-25 15:38:22 -0400878 bool candidateUsesModelForGlyphs = false;
879 ShapedRun candidate = [&](const TextProps& props){
880 if (props.glyphLen) {
881 candidateUsesModelForGlyphs = true;
882 return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400883 font.currentFont(), bidi.currentLevel(),
Ben Wagner7415a422019-03-25 15:38:22 -0400884 std::unique_ptr<ShapedGlyph[]>(),
885 props.glyphLen - modelGlyphOffset,
886 props.advance - modelAdvanceOffset);
887 } else {
888 return shape(utf8, utf8Bytes,
889 utf8Start, utf8Start + breakIteratorCurrent,
890 bidi, language, script, font);
891 }
892 }(modelText[breakIteratorCurrent + modelTextOffset]);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400893 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
894 if (run.fAdvance.fX < widthLeft) {
Ben Wagner7415a422019-03-25 15:38:22 -0400895 return run.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400896 } else {
897 return widthLeft - run.fAdvance.fX;
898 }
899 };
Ben Wagner7415a422019-03-25 15:38:22 -0400900 if (bestIsInvalid || score(best) < score(candidate)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400901 best = std::move(candidate);
Ben Wagner7415a422019-03-25 15:38:22 -0400902 bestIsInvalid = false;
903 bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400904 }
905 }
906
907 // If nothing fit (best score is negative) and the line is not empty
908 if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400909 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400910 line.runs.reset();
911 line.fAdvance = {0, 0};
912 } else {
Ben Wagner7415a422019-03-25 15:38:22 -0400913 if (bestUsesModelForGlyphs) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400914 best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
Ben Wagner7415a422019-03-25 15:38:22 -0400915 memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400916 best.fNumGlyphs * sizeof(ShapedGlyph));
Ben Wagner7415a422019-03-25 15:38:22 -0400917 modelGlyphOffset += best.fNumGlyphs;
918 modelTextOffset += best.fUtf8Range.size();
919 modelAdvanceOffset += best.fAdvance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400920 } else {
921 modelNeedsRegenerated = true;
922 }
Ben Wagner7415a422019-03-25 15:38:22 -0400923 utf8Start += best.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400924 line.fAdvance += best.fAdvance;
925 line.runs.emplace_back(std::move(best));
926
927 // If item broken, emit line (prevent remainder from accidentally fitting)
928 if (utf8Start != utf8End) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400929 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400930 line.runs.reset();
931 line.fAdvance = {0, 0};
932 }
933 }
934 }
935 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400936 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400937}
938
Ben Wagner51874e32019-04-04 15:21:20 -0400939void ShapeThenWrap::wrap(char const * const utf8, size_t utf8Bytes,
940 const BiDiRunIterator& bidi,
941 const LanguageRunIterator& language,
942 const ScriptRunIterator& script,
943 const FontRunIterator& font,
944 RunIteratorQueue& runSegmenter,
945 SkScalar width,
946 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400947{
948 SkTArray<ShapedRun> runs;
949{
950 UBreakIterator& lineBreakIterator = *fLineBreakIterator;
951 UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500952 {
953 UErrorCode status = U_ZERO_ERROR;
954 UText utf8UText = UTEXT_INITIALIZER;
955 utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
956 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
957 if (U_FAILURE(status)) {
958 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400959 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500960 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400961
962 ubrk_setUText(&lineBreakIterator, &utf8UText, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -0500963 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400964 SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400965 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400966 }
967 ubrk_setUText(&graphemeBreakIterator, &utf8UText, &status);
968 if (U_FAILURE(status)) {
969 SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400970 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500971 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400972 }
973
Ben Wagner8d45a382017-11-16 10:08:28 -0500974 const char* utf8Start = nullptr;
975 const char* utf8End = utf8;
976 while (runSegmenter.advanceRuns()) {
977 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400978 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500979
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400980 runs.emplace_back(shape(utf8, utf8Bytes,
981 utf8Start, utf8End,
982 bidi, language, script, font));
983 ShapedRun& run = runs.back();
Ben Wagnera25fbef2017-08-30 13:56:19 -0400984
Ben Wagner8d45a382017-11-16 10:08:28 -0500985 uint32_t previousCluster = 0xFFFFFFFF;
Ben Wagner7415a422019-03-25 15:38:22 -0400986 for (size_t i = 0; i < run.fNumGlyphs; ++i) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500987 ShapedGlyph& glyph = run.fGlyphs[i];
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500988 int32_t glyphCluster = glyph.fCluster;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400989
990 int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
991 while (lineBreakIteratorCurrent != UBRK_DONE &&
992 lineBreakIteratorCurrent < glyphCluster)
Ben Wagner8d45a382017-11-16 10:08:28 -0500993 {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400994 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
Ben Wagner2868b782017-08-31 14:12:27 -0400995 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500996 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400997 lineBreakIteratorCurrent == glyphCluster;
998
999 int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1000 while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1001 graphemeBreakIteratorCurrent < glyphCluster)
1002 {
1003 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1004 }
1005 glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1006 graphemeBreakIteratorCurrent == glyphCluster;
1007
Ben Wagner8d45a382017-11-16 10:08:28 -05001008 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001009 }
1010 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001011}
1012
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001013// Iterate over the glyphs in logical order to find potential line lengths.
Ben Wagner8d45a382017-11-16 10:08:28 -05001014{
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001015 /** The position of the beginning of the line. */
1016 ShapedRunGlyphIterator beginning(runs);
1017
1018 /** The position of the candidate line break. */
1019 ShapedRunGlyphIterator candidateLineBreak(runs);
1020 SkScalar candidateLineBreakWidth = 0;
1021
1022 /** The position of the candidate grapheme break. */
1023 ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1024 SkScalar candidateGraphemeBreakWidth = 0;
1025
1026 /** The position of the current location. */
1027 ShapedRunGlyphIterator current(runs);
1028 SkScalar currentWidth = 0;
1029 while (ShapedGlyph* glyph = current.current()) {
1030 // 'Break' at graphemes until a line boundary, then only at line boundaries.
1031 // Only break at graphemes if no line boundary is valid.
1032 if (current != beginning) {
1033 if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1034 // TODO: preserve line breaks <= grapheme breaks
1035 // and prevent line breaks inside graphemes
1036 candidateGraphemeBreak = current;
1037 candidateGraphemeBreakWidth = currentWidth;
1038 if (glyph->fMayLineBreakBefore) {
1039 candidateLineBreak = current;
1040 candidateLineBreakWidth = currentWidth;
1041 }
1042 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001043 }
1044
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001045 SkScalar glyphWidth = glyph->fAdvance.fX;
1046 // Break when overwidth, the glyph has a visual representation, and some space is used.
1047 if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1048 if (candidateLineBreak != beginning) {
1049 beginning = candidateLineBreak;
1050 currentWidth -= candidateLineBreakWidth;
1051 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1052 candidateLineBreakWidth = 0;
1053 } else if (candidateGraphemeBreak != beginning) {
1054 beginning = candidateGraphemeBreak;
1055 candidateLineBreak = beginning;
1056 currentWidth -= candidateGraphemeBreakWidth;
1057 candidateGraphemeBreakWidth = 0;
1058 candidateLineBreakWidth = 0;
1059 } else {
1060 SK_ABORT("");
1061 }
1062
1063 if (width < currentWidth) {
1064 if (width < candidateGraphemeBreakWidth) {
1065 candidateGraphemeBreak = candidateLineBreak;
1066 candidateGraphemeBreakWidth = candidateLineBreakWidth;
1067 }
1068 current = candidateGraphemeBreak;
1069 currentWidth = candidateGraphemeBreakWidth;
1070 }
1071
1072 glyph = beginning.current();
1073 if (glyph) {
1074 glyph->fMustLineBreakBefore = true;
1075 }
1076
1077 } else {
1078 current.next();
1079 currentWidth += glyphWidth;
Ben Wagner8d45a382017-11-16 10:08:28 -05001080 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001081 }
1082}
1083
1084// Reorder the runs and glyphs per line and write them out.
1085{
1086 ShapedRunGlyphIterator previousBreak(runs);
1087 ShapedRunGlyphIterator glyphIterator(runs);
Ben Wagner8d45a382017-11-16 10:08:28 -05001088 int previousRunIndex = -1;
1089 while (glyphIterator.current()) {
1090 int runIndex = glyphIterator.fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -04001091 size_t glyphIndex = glyphIterator.fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -05001092 ShapedGlyph* nextGlyph = glyphIterator.next();
1093
1094 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -05001095 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -05001096 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -05001097 previousRunIndex = runIndex;
1098 }
1099
1100 // Nothing can be written until the baseline is known.
1101 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1102 continue;
1103 }
1104
Ben Wagner8d45a382017-11-16 10:08:28 -05001105 int numRuns = runIndex - previousBreak.fRunIndex + 1;
1106 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1107 for (int i = 0; i < numRuns; ++i) {
1108 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1109 }
1110 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1111 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1112
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001113 // step through the runs in reverse visual order and the glyphs in reverse logical order
1114 // until a visible glyph is found and force them to the end of the visual line.
1115
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001116 handler->beginLine();
Ben Wagner8d45a382017-11-16 10:08:28 -05001117 for (int i = 0; i < numRuns; ++i) {
1118 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001119 const auto& run = runs[logicalIndex];
1120 const RunHandler::RunInfo info = {
1121 run.fFont,
1122 run.fLevel,
1123 run.fAdvance,
1124 run.fNumGlyphs,
1125 run.fUtf8Range
1126 };
1127 handler->runInfo(info);
1128 }
1129 handler->commitRunInfo();
1130 for (int i = 0; i < numRuns; ++i) {
1131 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1132 const auto& run = runs[logicalIndex];
1133 const RunHandler::RunInfo info = {
1134 run.fFont,
1135 run.fLevel,
1136 run.fAdvance,
1137 run.fNumGlyphs,
1138 run.fUtf8Range
1139 };
Ben Wagner8d45a382017-11-16 10:08:28 -05001140
Ben Wagner7415a422019-03-25 15:38:22 -04001141 size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1142 ? previousBreak.fGlyphIndex
1143 : 0;
1144 size_t endGlyphIndex = (logicalIndex == runIndex)
1145 ? glyphIndex + 1
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001146 : run.fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -05001147
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001148 append(handler, info, run, startGlyphIndex, endGlyphIndex);
Ben Wagner8d45a382017-11-16 10:08:28 -05001149 }
1150
Florin Malita500133b2019-02-07 10:56:55 -05001151 handler->commitLine();
1152
Ben Wagner8d45a382017-11-16 10:08:28 -05001153 previousRunIndex = -1;
1154 previousBreak = glyphIterator;
1155 }
1156}
Ben Wagnera25fbef2017-08-30 13:56:19 -04001157}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001158
1159
Ben Wagner51874e32019-04-04 15:21:20 -04001160ShapedRun ShaperHarfBuzz::shape(char const * const utf8,
Ben Wagner7415a422019-03-25 15:38:22 -04001161 size_t const utf8Bytes,
1162 char const * const utf8Start,
1163 char const * const utf8End,
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001164 const BiDiRunIterator& bidi,
1165 const LanguageRunIterator& language,
1166 const ScriptRunIterator& script,
1167 const FontRunIterator& font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001168{
Ben Wagner7415a422019-03-25 15:38:22 -04001169 size_t utf8runLength = utf8End - utf8Start;
1170 ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001171 font.currentFont(), bidi.currentLevel(), nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001172
1173 hb_buffer_t* buffer = fBuffer.get();
1174 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1175 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1176 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1177
Ben Wagner2fc14742019-02-06 16:37:44 -05001178 // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1179 hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1180
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001181 // Add precontext.
1182 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1183
1184 // Populate the hb_buffer directly with utf8 cluster indexes.
1185 const char* utf8Current = utf8Start;
1186 while (utf8Current < utf8End) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001187 unsigned int cluster = utf8Current - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001188 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1189 hb_buffer_add(buffer, u, cluster);
1190 }
1191
1192 // Add postcontext.
1193 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1194
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001195 hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001196 hb_buffer_set_direction(buffer, direction);
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001197 hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1198 hb_buffer_set_language(buffer, hb_language_from_string(language.currentLanguage(), -1));
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001199 hb_buffer_guess_segment_properties(buffer);
1200 // TODO: features
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001201
1202 // TODO: how to cache hbface (typeface) / hbfont (font)
1203 HBFont hbFont(create_hb_font(font.currentFont()));
1204 if (!hbFont) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001205 return run;
1206 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001207 hb_shape(hbFont.get(), buffer, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001208 unsigned len = hb_buffer_get_length(buffer);
1209 if (len == 0) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001210 return run;
1211 }
1212
1213 if (direction == HB_DIRECTION_RTL) {
1214 // Put the clusters back in logical order.
1215 // Note that the advances remain ltr.
1216 hb_buffer_reverse(buffer);
1217 }
1218 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1219 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1220
Ben Wagner7415a422019-03-25 15:38:22 -04001221 run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001222 font.currentFont(), bidi.currentLevel(),
Ben Wagner454e5fb2019-02-08 17:46:38 -05001223 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001224 int scaleX, scaleY;
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001225 hb_font_get_scale(hbFont.get(), &scaleX, &scaleY);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001226 double textSizeY = run.fFont.getSize() / scaleY;
1227 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1228 SkVector runAdvance = { 0, 0 };
1229 for (unsigned i = 0; i < len; i++) {
1230 ShapedGlyph& glyph = run.fGlyphs[i];
1231 glyph.fID = info[i].codepoint;
1232 glyph.fCluster = info[i].cluster;
1233 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1234 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1235 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1236 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1237
1238 SkRect bounds;
1239 SkScalar advance;
1240 SkPaint p;
1241 run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1242 glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
Kevin Lubick867da4b2019-02-22 15:55:39 -05001243#if SK_HB_VERSION_CHECK(1, 5, 0)
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001244 glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
Kevin Lubick867da4b2019-02-22 15:55:39 -05001245#else
1246 glyph.fUnsafeToBreak = false;
1247#endif
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001248 glyph.fMustLineBreakBefore = false;
1249
1250 runAdvance += glyph.fAdvance;
1251 }
1252 run.fAdvance = runAdvance;
1253
1254 return run;
1255}
Ben Wagner51874e32019-04-04 15:21:20 -04001256
1257} // namespace
1258
1259std::unique_ptr<SkShaper::BiDiRunIterator>
1260SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1261 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
1262 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
1263 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
1264 SkDEBUGF("Bidi error: text too long");
1265 return nullptr;
1266 }
1267
1268 UErrorCode status = U_ZERO_ERROR;
1269
1270 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
1271 int32_t utf16Units;
1272 u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
1273 status = U_ZERO_ERROR;
1274 std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
1275 u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
1276 if (U_FAILURE(status)) {
1277 SkDEBUGF("Invalid utf8 input: %s", u_errorName(status));
1278 return nullptr;
1279 }
1280
1281 ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
1282 if (U_FAILURE(status)) {
1283 SkDEBUGF("Bidi error: %s", u_errorName(status));
1284 return nullptr;
1285 }
1286 SkASSERT(bidi);
1287
1288 // The required lifetime of utf16 isn't well documented.
1289 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
1290 ubidi_setPara(bidi.get(), utf16.get(), utf16Units, bidiLevel, nullptr, &status);
1291 if (U_FAILURE(status)) {
1292 SkDEBUGF("Bidi error: %s", u_errorName(status));
1293 return nullptr;
1294 }
1295
1296 return skstd::make_unique<IcuBiDiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
1297}
1298
1299std::unique_ptr<SkShaper::ScriptRunIterator>
1300SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1301 return skstd::make_unique<HbIcuScriptRunIterator>(utf8, utf8Bytes);
1302}
1303
1304std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper() {
1305 return MakeHarfBuzz(true);
1306}
1307std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap() {
1308 return MakeHarfBuzz(false);
1309}