blob: 34b80c53c449b516fcf724d82fe00c50a7b9f505 [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 {
Ben Wagner723a8772019-08-16 11:36:58 -040058template <typename T, void(*P)(T*)> using resource =
59 std::unique_ptr<T, SkFunctionWrapper<skstd::remove_pointer_t<decltype(P)>, P>>;
60using HBBlob = resource<hb_blob_t , &hb_blob_destroy >;
61using HBFace = resource<hb_face_t , &hb_face_destroy >;
62using HBFont = resource<hb_font_t , &hb_font_destroy >;
63using HBBuffer = resource<hb_buffer_t , &hb_buffer_destroy>;
64using ICUBiDi = resource<UBiDi , &ubidi_close >;
65using ICUBrk = resource<UBreakIterator, &ubrk_close >;
66using ICUUText = std::unique_ptr<UText, SkFunctionWrapper<decltype(utext_close), utext_close>>;
Ben Wagnera25fbef2017-08-30 13:56:19 -040067
68HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
69 size_t size = asset->getLength();
70 HBBlob blob;
71 if (const void* base = asset->getMemoryBase()) {
72 blob.reset(hb_blob_create((char*)base, SkToUInt(size),
73 HB_MEMORY_MODE_READONLY, asset.release(),
74 [](void* p) { delete (SkStreamAsset*)p; }));
75 } else {
76 // SkDebugf("Extra SkStreamAsset copy\n");
77 void* ptr = size ? sk_malloc_throw(size) : nullptr;
78 asset->read(ptr, size);
79 blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
80 HB_MEMORY_MODE_READONLY, ptr, sk_free));
81 }
82 SkASSERT(blob);
83 hb_blob_make_immutable(blob.get());
84 return blob;
85}
Ben Wagnera25fbef2017-08-30 13:56:19 -040086
Ben Wagnerf61c9362019-02-13 12:01:45 -050087hb_position_t skhb_position(SkScalar value) {
88 // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
89 constexpr int kHbPosition1 = 1 << 16;
90 return SkScalarRoundToInt(value * kHbPosition1);
91}
92
93hb_bool_t skhb_glyph(hb_font_t* hb_font,
94 void* font_data,
95 hb_codepoint_t unicode,
96 hb_codepoint_t variation_selector,
97 hb_codepoint_t* glyph,
98 void* user_data) {
99 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
100
101 *glyph = font.unicharToGlyph(unicode);
102 return *glyph != 0;
103}
104
105hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
106 void* font_data,
107 hb_codepoint_t unicode,
108 hb_codepoint_t* glyph,
109 void* user_data) {
110 return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
111}
112
113unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
114 unsigned int count,
115 const hb_codepoint_t *unicodes,
116 unsigned int unicode_stride,
117 hb_codepoint_t *glyphs,
118 unsigned int glyph_stride,
119 void *user_data) {
120 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
121
122 // Batch call textToGlyphs since entry cost is not cheap.
123 // Copy requred because textToGlyphs is dense and hb is strided.
124 SkAutoSTMalloc<256, SkUnichar> unicode(count);
125 for (unsigned i = 0; i < count; i++) {
126 unicode[i] = *unicodes;
127 unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
128 }
129 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
Ben Wagner51e15a62019-05-07 15:38:46 -0400130 font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), SkTextEncoding::kUTF32,
Ben Wagnerf61c9362019-02-13 12:01:45 -0500131 glyph.get(), count);
132
133 // Copy the results back to the sparse array.
Ben Wagnerbedbb072019-07-31 15:21:03 -0400134 unsigned int done;
135 for (done = 0; done < count && glyph[done] != 0; done++) {
136 *glyphs = glyph[done];
Ben Wagnerf61c9362019-02-13 12:01:45 -0500137 glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
138 }
Ben Wagnerbedbb072019-07-31 15:21:03 -0400139 // return 'done' to allow HarfBuzz to synthesize with NFC and spaces, return 'count' to avoid
140 return done;
Ben Wagnerf61c9362019-02-13 12:01:45 -0500141}
142
143hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
144 void* font_data,
145 hb_codepoint_t codepoint,
146 void* user_data) {
147 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
148
149 SkScalar advance;
150 SkGlyphID glyph = SkTo<SkGlyphID>(codepoint);
151
152 font.getWidths(&glyph, 1, &advance);
153 if (!font.isSubpixel()) {
154 advance = SkScalarRoundToInt(advance);
155 }
156 return skhb_position(advance);
157}
158
159void skhb_glyph_h_advances(hb_font_t* hb_font,
160 void* font_data,
161 unsigned count,
162 const hb_codepoint_t* glyphs,
163 unsigned int glyph_stride,
164 hb_position_t* advances,
165 unsigned int advance_stride,
166 void* user_data) {
167 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
168
169 // Batch call getWidths since entry cost is not cheap.
170 // Copy requred because getWidths is dense and hb is strided.
171 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
172 for (unsigned i = 0; i < count; i++) {
173 glyph[i] = *glyphs;
174 glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
175 }
176 SkAutoSTMalloc<256, SkScalar> advance(count);
177 font.getWidths(glyph.get(), count, advance.get());
178
179 if (!font.isSubpixel()) {
180 for (unsigned i = 0; i < count; i++) {
181 advance[i] = SkScalarRoundToInt(advance[i]);
182 }
183 }
184
185 // Copy the results back to the sparse array.
186 for (unsigned i = 0; i < count; i++) {
187 *advances = skhb_position(advance[i]);
188 advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
189 }
190}
191
192// HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
193// fallback mark positioning, i.e. the situation when the font does not have
194// mark anchors or other mark positioning rules, but instead HarfBuzz is
195// supposed to heuristically place combining marks around base glyphs. HarfBuzz
196// does this by measuring "ink boxes" of glyphs, and placing them according to
197// Unicode mark classes. Above, below, centered or left or right, etc.
198hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
199 void* font_data,
200 hb_codepoint_t codepoint,
201 hb_glyph_extents_t* extents,
202 void* user_data) {
203 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
204
205 SkASSERT(codepoint < 0xFFFFu);
206 SkASSERT(extents);
207
208 SkRect sk_bounds;
209 SkGlyphID glyph = codepoint;
210
211 font.getWidths(&glyph, 1, nullptr, &sk_bounds);
212 if (!font.isSubpixel()) {
213 sk_bounds.set(sk_bounds.roundOut());
214 }
215
216 // Skia is y-down but HarfBuzz is y-up.
217 extents->x_bearing = skhb_position(sk_bounds.fLeft);
218 extents->y_bearing = skhb_position(-sk_bounds.fTop);
219 extents->width = skhb_position(sk_bounds.width());
220 extents->height = skhb_position(-sk_bounds.height());
221 return true;
222}
223
Kevin Lubick867da4b2019-02-22 15:55:39 -0500224#define SK_HB_VERSION_CHECK(x, y, z) \
225 (HB_VERSION_MAJOR > (x)) || \
226 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR > (y)) || \
227 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
228
Ben Wagnerf61c9362019-02-13 12:01:45 -0500229hb_font_funcs_t* skhb_get_font_funcs() {
230 static hb_font_funcs_t* const funcs = []{
231 // HarfBuzz will use the default (parent) implementation if they aren't set.
232 hb_font_funcs_t* const funcs = hb_font_funcs_create();
233 hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
234 hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500235#if SK_HB_VERSION_CHECK(2, 0, 0)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500236 hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500237#else
238 sk_ignore_unused_variable(skhb_nominal_glyphs);
239#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500240 hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500241#if SK_HB_VERSION_CHECK(1, 8, 6)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500242 hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500243#else
244 sk_ignore_unused_variable(skhb_glyph_h_advances);
245#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500246 hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
247 hb_font_funcs_make_immutable(funcs);
248 return funcs;
249 }();
250 SkASSERT(funcs);
251 return funcs;
252}
253
254hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
255 SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
256
Mike Reed6d907fa2019-07-24 14:51:34 -0400257 auto data = typeface.copyTableData(tag);
258 if (!data) {
Hal Canary0dfa2082018-10-31 13:02:49 -0400259 return nullptr;
260 }
Mike Reed6d907fa2019-07-24 14:51:34 -0400261 SkData* rawData = data.release();
262 return hb_blob_create(reinterpret_cast<char*>(rawData->writable_data()), rawData->size(),
263 HB_MEMORY_MODE_WRITABLE, rawData, [](void* ctx) {
264 ((SkData*)ctx)->unref();
265 });
Ben Wagnerf61c9362019-02-13 12:01:45 -0500266}
267
268HBFont create_hb_font(const SkFont& font) {
Ben Wagnere8db3252019-05-29 18:54:26 -0400269 SkASSERT(font.getTypeface());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400270 int index;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500271 std::unique_ptr<SkStreamAsset> typefaceAsset = font.getTypeface()->openStream(&index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500272 HBFace face;
Hal Canaryddef43f2018-11-16 10:53:51 -0500273 if (!typefaceAsset) {
Ben Wagnerf61c9362019-02-13 12:01:45 -0500274 face.reset(hb_face_create_for_tables(
275 skhb_get_table,
276 reinterpret_cast<void *>(font.refTypeface().release()),
277 [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
278 } else {
279 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
280 face.reset(hb_face_create(blob.get(), (unsigned)index));
Hal Canaryddef43f2018-11-16 10:53:51 -0500281 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400282 SkASSERT(face);
283 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -0400284 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400285 }
286 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500287 hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400288
Ben Wagnerf61c9362019-02-13 12:01:45 -0500289 HBFont otFont(hb_font_create(face.get()));
290 SkASSERT(otFont);
291 if (!otFont) {
Ben Wagnere0001732017-08-31 16:26:26 -0400292 return nullptr;
293 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500294 hb_ot_font_set_funcs(otFont.get());
295 int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
Ben Wagnere0001732017-08-31 16:26:26 -0400296 if (axis_count > 0) {
297 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500298 if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
299 hb_font_set_variations(otFont.get(),
Ben Wagnere0001732017-08-31 16:26:26 -0400300 reinterpret_cast<hb_variation_t*>(axis_values.get()),
301 axis_count);
302 }
303 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500304
305 // Creating a sub font means that non-available functions
306 // are found from the parent.
307 HBFont skFont(hb_font_create_sub_font(otFont.get()));
308 hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
309 reinterpret_cast<void *>(new SkFont(font)),
310 [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
311 int scale = skhb_position(font.getSize());
312 hb_font_set_scale(skFont.get(), scale, scale);
313
314 return skFont;
Ben Wagnere0001732017-08-31 16:26:26 -0400315}
316
Ben Wagner1383a382019-04-03 17:53:53 -0400317/** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
Hal Canaryf107a2f2018-07-25 16:52:48 -0400318static inline SkUnichar utf8_next(const char** ptr, const char* end) {
319 SkUnichar val = SkUTF::NextUTF8(ptr, end);
Ben Wagner1383a382019-04-03 17:53:53 -0400320 return val < 0 ? 0xFFFD : val;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400321}
322
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400323class IcuBiDiRunIterator final : public SkShaper::BiDiRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500324public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400325 IcuBiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500326 : fBidi(std::move(bidi))
327 , fEndOfCurrentRun(utf8)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400328 , fBegin(utf8)
329 , fEnd(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500330 , fUTF16LogicalPosition(0)
331 , fLevel(UBIDI_DEFAULT_LTR)
332 {}
333 void consume() override {
334 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
335 int32_t endPosition = ubidi_getLength(fBidi.get());
336 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400337 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400338 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500339 UBiDiLevel level;
340 while (fUTF16LogicalPosition < endPosition) {
341 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
342 if (level != fLevel) {
343 break;
344 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400345 u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400346 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500347 }
348 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400349 size_t endOfCurrentRun() const override {
350 return fEndOfCurrentRun - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500351 }
352 bool atEnd() const override {
353 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
354 }
355
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400356 UBiDiLevel currentLevel() const override {
Ben Wagner8d45a382017-11-16 10:08:28 -0500357 return fLevel;
358 }
359private:
360 ICUBiDi fBidi;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400361 char const * fEndOfCurrentRun;
362 char const * const fBegin;
363 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500364 int32_t fUTF16LogicalPosition;
365 UBiDiLevel fLevel;
366};
367
Ben Wagner1383a382019-04-03 17:53:53 -0400368class HbIcuScriptRunIterator final : public SkShaper::ScriptRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500369public:
Ben Wagner1383a382019-04-03 17:53:53 -0400370 HbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400371 : fCurrent(utf8), fBegin(utf8), fEnd(fCurrent + utf8Bytes)
Ben Wagner8d45a382017-11-16 10:08:28 -0500372 , fCurrentScript(HB_SCRIPT_UNKNOWN)
373 {}
Ben Wagner1383a382019-04-03 17:53:53 -0400374 static hb_script_t hb_script_from_icu(SkUnichar u) {
375 UErrorCode status = U_ZERO_ERROR;
376 UScriptCode scriptCode = uscript_getScript(u, &status);
377
378 if (U_FAILURE (status)) {
379 return HB_SCRIPT_UNKNOWN;
380 }
381
382 return hb_icu_script_to_script(scriptCode);
383 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500384 void consume() override {
385 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400386 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400387 fCurrentScript = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500388 while (fCurrent < fEnd) {
389 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400390 u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400391 const hb_script_t script = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500392 if (script != fCurrentScript) {
393 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
394 fCurrentScript = script;
395 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
396 continue;
397 } else {
398 fCurrent = prev;
399 break;
400 }
401 }
402 }
403 if (fCurrentScript == HB_SCRIPT_INHERITED) {
404 fCurrentScript = HB_SCRIPT_COMMON;
405 }
406 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400407 size_t endOfCurrentRun() const override {
408 return fCurrent - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500409 }
410 bool atEnd() const override {
411 return fCurrent == fEnd;
412 }
413
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400414 SkFourByteTag currentScript() const override {
415 return SkSetFourByteTag(HB_UNTAG(fCurrentScript));
Ben Wagner8d45a382017-11-16 10:08:28 -0500416 }
417private:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400418 char const * fCurrent;
419 char const * const fBegin;
420 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500421 hb_script_t fCurrentScript;
422};
423
Ben Wagner8d45a382017-11-16 10:08:28 -0500424class RunIteratorQueue {
425public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400426 void insert(SkShaper::RunIterator* runIterator) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500427 fRunIterators.insert(runIterator);
428 }
429
430 bool advanceRuns() {
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400431 const SkShaper::RunIterator* leastRun = fRunIterators.peek();
Ben Wagner8d45a382017-11-16 10:08:28 -0500432 if (leastRun->atEnd()) {
433 SkASSERT(this->allRunsAreAtEnd());
434 return false;
435 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400436 const size_t leastEnd = leastRun->endOfCurrentRun();
437 SkShaper::RunIterator* currentRun = nullptr;
438 SkDEBUGCODE(size_t previousEndOfCurrentRun);
Ben Wagner8d45a382017-11-16 10:08:28 -0500439 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
440 fRunIterators.pop();
441 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
442 currentRun->consume();
443 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
444 fRunIterators.insert(currentRun);
445 }
446 return true;
447 }
448
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400449 size_t endOfCurrentRun() const {
Ben Wagner8d45a382017-11-16 10:08:28 -0500450 return fRunIterators.peek()->endOfCurrentRun();
451 }
452
453private:
454 bool allRunsAreAtEnd() const {
455 for (int i = 0; i < fRunIterators.count(); ++i) {
456 if (!fRunIterators.at(i)->atEnd()) {
457 return false;
458 }
459 }
460 return true;
461 }
462
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400463 static bool CompareRunIterator(SkShaper::RunIterator* const& a, SkShaper::RunIterator* const& b) {
464 return a->endOfCurrentRun() < b->endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500465 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400466 SkTDPQueue<SkShaper::RunIterator*, CompareRunIterator> fRunIterators;
Ben Wagner8d45a382017-11-16 10:08:28 -0500467};
468
469struct ShapedGlyph {
470 SkGlyphID fID;
471 uint32_t fCluster;
472 SkPoint fOffset;
473 SkVector fAdvance;
474 bool fMayLineBreakBefore;
475 bool fMustLineBreakBefore;
476 bool fHasVisual;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400477 bool fGraphemeBreakBefore;
478 bool fUnsafeToBreak;
Ben Wagner8d45a382017-11-16 10:08:28 -0500479};
480struct ShapedRun {
Ben Wagner7415a422019-03-25 15:38:22 -0400481 ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, UBiDiLevel level,
482 std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
483 : fUtf8Range(utf8Range), fFont(font), fLevel(level)
484 , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
Ben Wagner8d45a382017-11-16 10:08:28 -0500485 {}
486
Ben Wagner7415a422019-03-25 15:38:22 -0400487 SkShaper::RunHandler::Range fUtf8Range;
Mike Reed6d595682018-12-05 17:28:14 -0500488 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500489 UBiDiLevel fLevel;
490 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Ben Wagner7415a422019-03-25 15:38:22 -0400491 size_t fNumGlyphs;
492 SkVector fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500493};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400494struct ShapedLine {
495 SkTArray<ShapedRun> runs;
496 SkVector fAdvance = { 0, 0 };
497};
Ben Wagner8d45a382017-11-16 10:08:28 -0500498
Ben Wagner1383a382019-04-03 17:53:53 -0400499constexpr bool is_LTR(UBiDiLevel level) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500500 return (level & 1) == 0;
501}
502
Ben Wagner1383a382019-04-03 17:53:53 -0400503void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400504 const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex) {
Ben Wagner7415a422019-03-25 15:38:22 -0400505 SkASSERT(startGlyphIndex <= endGlyphIndex);
506 const size_t glyphLen = endGlyphIndex - startGlyphIndex;
Florin Malita9867f612018-12-12 10:54:49 -0500507
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400508 const auto buffer = handler->runBuffer(runInfo);
Florin Malita9867f612018-12-12 10:54:49 -0500509 SkASSERT(buffer.glyphs);
510 SkASSERT(buffer.positions);
511
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400512 SkVector advance = {0,0};
Ben Wagner7415a422019-03-25 15:38:22 -0400513 for (size_t i = 0; i < glyphLen; i++) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500514 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
Ben Wagner7415a422019-03-25 15:38:22 -0400515 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
516 : endGlyphIndex - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500517 buffer.glyphs[i] = glyph.fID;
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400518 if (buffer.offsets) {
519 buffer.positions[i] = advance + buffer.point;
520 buffer.offsets[i] = glyph.fOffset; //TODO: invert glyph.fOffset.fY?
521 } else {
522 buffer.positions[i] = advance + buffer.point + glyph.fOffset; //TODO: invert glyph.fOffset.fY?
523 }
Florin Malita9867f612018-12-12 10:54:49 -0500524 if (buffer.clusters) {
525 buffer.clusters[i] = glyph.fCluster;
526 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400527 advance += glyph.fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500528 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400529 handler->commitRunBuffer(runInfo);
Ben Wagner8d45a382017-11-16 10:08:28 -0500530}
531
Ben Wagner1383a382019-04-03 17:53:53 -0400532void emit(const ShapedLine& line, SkShaper::RunHandler* handler) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400533 // Reorder the runs and glyphs per line and write them out.
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400534 handler->beginLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400535
536 int numRuns = line.runs.size();
537 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
538 for (int i = 0; i < numRuns; ++i) {
539 runLevels[i] = line.runs[i].fLevel;
540 }
541 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
542 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
543
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400544 for (int i = 0; i < numRuns; ++i) {
545 int logicalIndex = logicalFromVisual[i];
546
547 const auto& run = line.runs[logicalIndex];
548 const SkShaper::RunHandler::RunInfo info = {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400549 run.fFont,
550 run.fLevel,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400551 run.fAdvance,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400552 run.fNumGlyphs,
553 run.fUtf8Range
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400554 };
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400555 handler->runInfo(info);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400556 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400557 handler->commitRunInfo();
558 for (int i = 0; i < numRuns; ++i) {
559 int logicalIndex = logicalFromVisual[i];
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400560
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400561 const auto& run = line.runs[logicalIndex];
562 const SkShaper::RunHandler::RunInfo info = {
563 run.fFont,
564 run.fLevel,
565 run.fAdvance,
566 run.fNumGlyphs,
567 run.fUtf8Range
568 };
569 append(handler, info, run, 0, run.fNumGlyphs);
570 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400571
Florin Malita500133b2019-02-07 10:56:55 -0500572 handler->commitLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400573}
574
Ben Wagner8d45a382017-11-16 10:08:28 -0500575struct ShapedRunGlyphIterator {
576 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
577 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
578 { }
579
580 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
581 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
582 bool operator==(const ShapedRunGlyphIterator& that) const {
583 return fRuns == that.fRuns &&
584 fRunIndex == that.fRunIndex &&
585 fGlyphIndex == that.fGlyphIndex;
586 }
587 bool operator!=(const ShapedRunGlyphIterator& that) const {
588 return fRuns != that.fRuns ||
589 fRunIndex != that.fRunIndex ||
590 fGlyphIndex != that.fGlyphIndex;
591 }
592
593 ShapedGlyph* next() {
594 const SkTArray<ShapedRun>& runs = *fRuns;
595 SkASSERT(fRunIndex < runs.count());
596 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
597
598 ++fGlyphIndex;
599 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
600 fGlyphIndex = 0;
601 ++fRunIndex;
602 if (fRunIndex >= runs.count()) {
603 return nullptr;
604 }
605 }
606 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
607 }
608
609 ShapedGlyph* current() {
610 const SkTArray<ShapedRun>& runs = *fRuns;
611 if (fRunIndex >= runs.count()) {
612 return nullptr;
613 }
614 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
615 }
616
617 const SkTArray<ShapedRun>* fRuns;
618 int fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -0400619 size_t fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -0500620};
621
Ben Wagner51874e32019-04-04 15:21:20 -0400622class ShaperHarfBuzz : public SkShaper {
Ben Wagnerb0591942019-02-15 14:46:18 -0500623public:
Florin Malita42684332019-07-26 14:54:40 -0400624 ShaperHarfBuzz(HBBuffer, ICUBrk line, ICUBrk grapheme, sk_sp<SkFontMgr>);
625
Ben Wagner51874e32019-04-04 15:21:20 -0400626protected:
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400627 ICUBrk fLineBreakIterator;
628 ICUBrk fGraphemeBreakIterator;
629
Ben Wagner51874e32019-04-04 15:21:20 -0400630 ShapedRun shape(const char* utf8, size_t utf8Bytes,
631 const char* utf8Start,
632 const char* utf8End,
633 const BiDiRunIterator&,
634 const LanguageRunIterator&,
635 const ScriptRunIterator&,
636 const FontRunIterator&) const;
637private:
Florin Malita42684332019-07-26 14:54:40 -0400638 const sk_sp<SkFontMgr> fFontMgr;
639 HBBuffer fBuffer;
Ben Wagner51874e32019-04-04 15:21:20 -0400640
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400641 void shape(const char* utf8, size_t utf8Bytes,
642 const SkFont&,
643 bool leftToRight,
644 SkScalar width,
645 RunHandler*) const override;
Ben Wagnerb0591942019-02-15 14:46:18 -0500646
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400647 void shape(const char* utf8Text, size_t textBytes,
648 FontRunIterator&,
649 BiDiRunIterator&,
650 ScriptRunIterator&,
651 LanguageRunIterator&,
652 SkScalar width,
653 RunHandler*) const override;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400654
Ben Wagner51874e32019-04-04 15:21:20 -0400655 virtual void wrap(char const * const utf8, size_t utf8Bytes,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400656 const BiDiRunIterator&,
657 const LanguageRunIterator&,
658 const ScriptRunIterator&,
659 const FontRunIterator&,
660 RunIteratorQueue& runSegmenter,
661 SkScalar width,
Ben Wagner51874e32019-04-04 15:21:20 -0400662 RunHandler*) const = 0;
Ben Wagner8d45a382017-11-16 10:08:28 -0500663};
664
Ben Wagner51874e32019-04-04 15:21:20 -0400665class ShaperDrivenWrapper : public ShaperHarfBuzz {
666public:
667 using ShaperHarfBuzz::ShaperHarfBuzz;
668private:
669 void wrap(char const * const utf8, size_t utf8Bytes,
670 const BiDiRunIterator&,
671 const LanguageRunIterator&,
672 const ScriptRunIterator&,
673 const FontRunIterator&,
674 RunIteratorQueue& runSegmenter,
675 SkScalar width,
676 RunHandler*) const override;
677};
Ben Wagnerb0591942019-02-15 14:46:18 -0500678
Ben Wagner51874e32019-04-04 15:21:20 -0400679class ShapeThenWrap : public ShaperHarfBuzz {
680public:
681 using ShaperHarfBuzz::ShaperHarfBuzz;
682private:
683 void wrap(char const * const utf8, size_t utf8Bytes,
684 const BiDiRunIterator&,
685 const LanguageRunIterator&,
686 const ScriptRunIterator&,
687 const FontRunIterator&,
688 RunIteratorQueue& runSegmenter,
689 SkScalar width,
690 RunHandler*) const override;
691};
692
Ben Wagner6bb79bb2019-05-15 10:50:20 -0400693class ShapeDontWrapOrReorder : public ShaperHarfBuzz {
694public:
695 using ShaperHarfBuzz::ShaperHarfBuzz;
696private:
697 void wrap(char const * const utf8, size_t utf8Bytes,
698 const BiDiRunIterator&,
699 const LanguageRunIterator&,
700 const ScriptRunIterator&,
701 const FontRunIterator&,
702 RunIteratorQueue& runSegmenter,
703 SkScalar width,
704 RunHandler*) const override;
705};
706
Florin Malita42684332019-07-26 14:54:40 -0400707static std::unique_ptr<SkShaper> MakeHarfBuzz(sk_sp<SkFontMgr> fontmgr, bool correct) {
Ben Wagner51874e32019-04-04 15:21:20 -0400708 #if defined(SK_USING_THIRD_PARTY_ICU)
Hal Canary61021922019-02-06 12:29:11 -0500709 if (!SkLoadICU()) {
Ben Wagner51874e32019-04-04 15:21:20 -0400710 SkDEBUGF("SkLoadICU() failed!\n");
711 return nullptr;
Hal Canary61021922019-02-06 12:29:11 -0500712 }
Ben Wagner51874e32019-04-04 15:21:20 -0400713 #endif
714 HBBuffer buffer(hb_buffer_create());
715 if (!buffer) {
716 SkDEBUGF("Could not create hb_buffer");
717 return nullptr;
718 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500719
Ben Wagner8d45a382017-11-16 10:08:28 -0500720 UErrorCode status = U_ZERO_ERROR;
Ben Wagner51874e32019-04-04 15:21:20 -0400721 ICUBrk lineBreakIterator(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
722 if (!lineBreakIterator || U_FAILURE(status)) {
723 SkDEBUGF("Could not create line break iterator: %s", u_errorName(status));
724 return nullptr;
Ben Wagner8d45a382017-11-16 10:08:28 -0500725 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400726
Ben Wagner51874e32019-04-04 15:21:20 -0400727 ICUBrk graphemeBreakIterator(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
728 if (!graphemeBreakIterator || U_FAILURE(status)) {
729 SkDEBUGF("Could not create grapheme break iterator: %s", u_errorName(status));
730 return nullptr;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400731 }
732
Ben Wagner51874e32019-04-04 15:21:20 -0400733 if (correct) {
Florin Malita42684332019-07-26 14:54:40 -0400734 return skstd::make_unique<ShaperDrivenWrapper>(std::move(buffer),
735 std::move(lineBreakIterator),
736 std::move(graphemeBreakIterator),
737 std::move(fontmgr));
Ben Wagner51874e32019-04-04 15:21:20 -0400738 } else {
Florin Malita42684332019-07-26 14:54:40 -0400739 return skstd::make_unique<ShapeThenWrap>(std::move(buffer),
740 std::move(lineBreakIterator),
741 std::move(graphemeBreakIterator),
742 std::move(fontmgr));
Ben Wagner51874e32019-04-04 15:21:20 -0400743 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400744}
745
Florin Malita42684332019-07-26 14:54:40 -0400746ShaperHarfBuzz::ShaperHarfBuzz(HBBuffer buffer, ICUBrk line, ICUBrk grapheme,
747 sk_sp<SkFontMgr> fontmgr)
Ben Wagner51874e32019-04-04 15:21:20 -0400748 : fLineBreakIterator(std::move(line))
749 , fGraphemeBreakIterator(std::move(grapheme))
Florin Malita42684332019-07-26 14:54:40 -0400750 , fFontMgr(std::move(fontmgr))
Ben Wagner51874e32019-04-04 15:21:20 -0400751 , fBuffer(std::move(buffer))
752{}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400753
Ben Wagner51874e32019-04-04 15:21:20 -0400754void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
755 const SkFont& srcFont,
756 bool leftToRight,
757 SkScalar width,
758 RunHandler* handler) const
Ben Wagner8d45a382017-11-16 10:08:28 -0500759{
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400760 SkASSERT(handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400761 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
762
Ben Wagner1383a382019-04-03 17:53:53 -0400763 std::unique_ptr<BiDiRunIterator> bidi(MakeIcuBiDiRunIterator(utf8, utf8Bytes, defaultLevel));
Ben Wagner8d45a382017-11-16 10:08:28 -0500764 if (!bidi) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400765 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400766 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400767
Ben Wagner1383a382019-04-03 17:53:53 -0400768 std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400769 if (!language) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400770 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400771 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400772
Ben Wagner1383a382019-04-03 17:53:53 -0400773 std::unique_ptr<ScriptRunIterator> script(MakeHbIcuScriptRunIterator(utf8, utf8Bytes));
Ben Wagner8d45a382017-11-16 10:08:28 -0500774 if (!script) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400775 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400776 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400777
Florin Malita42684332019-07-26 14:54:40 -0400778 std::unique_ptr<FontRunIterator> font(
779 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
780 fFontMgr ? fFontMgr : SkFontMgr::RefDefault()));
Ben Wagner8d45a382017-11-16 10:08:28 -0500781 if (!font) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400782 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400783 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400784
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400785 this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400786}
787
Ben Wagner51874e32019-04-04 15:21:20 -0400788void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
789 FontRunIterator& font,
790 BiDiRunIterator& bidi,
791 ScriptRunIterator& script,
792 LanguageRunIterator& language,
793 SkScalar width,
794 RunHandler* handler) const
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400795{
796 RunIteratorQueue runSegmenter;
797 runSegmenter.insert(&font);
798 runSegmenter.insert(&bidi);
799 runSegmenter.insert(&script);
800 runSegmenter.insert(&language);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400801
Ben Wagner51874e32019-04-04 15:21:20 -0400802 this->wrap(utf8, utf8Bytes, bidi, language, script, font, runSegmenter, width, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400803}
804
Ben Wagner51874e32019-04-04 15:21:20 -0400805void ShaperDrivenWrapper::wrap(char const * const utf8, size_t utf8Bytes,
806 const BiDiRunIterator& bidi,
807 const LanguageRunIterator& language,
808 const ScriptRunIterator& script,
809 const FontRunIterator& font,
810 RunIteratorQueue& runSegmenter,
811 SkScalar width,
812 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400813{
814 ShapedLine line;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400815
816 const char* utf8Start = nullptr;
817 const char* utf8End = utf8;
818 while (runSegmenter.advanceRuns()) { // For each item
819 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400820 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400821
Ben Wagner7415a422019-03-25 15:38:22 -0400822 ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400823 bool modelNeedsRegenerated = true;
Ben Wagner7415a422019-03-25 15:38:22 -0400824 int modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400825
826 struct TextProps {
827 int glyphLen = 0;
828 SkVector advance = {0, 0};
829 };
830 // map from character position to [safe to break, glyph position, advance]
831 std::unique_ptr<TextProps[]> modelText;
832 int modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400833 SkVector modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400834
835 while (utf8Start < utf8End) { // While there are still code points left in this item
836 size_t utf8runLength = utf8End - utf8Start;
837 if (modelNeedsRegenerated) {
838 model = shape(utf8, utf8Bytes,
839 utf8Start, utf8End,
840 bidi, language, script, font);
Ben Wagner7415a422019-03-25 15:38:22 -0400841 modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400842
843 SkVector advance = {0, 0};
844 modelText.reset(new TextProps[utf8runLength + 1]());
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500845 size_t modelStartCluster = utf8Start - utf8;
Ben Wagner7415a422019-03-25 15:38:22 -0400846 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
Ben Wagner84cc4612019-02-14 17:13:21 -0500847 SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
Ben Wagner2fe1e232019-02-14 17:37:02 -0500848 SkASSERT( model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400849 if (!model.fGlyphs[i].fUnsafeToBreak) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500850 modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
851 modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400852 }
853 advance += model.fGlyphs[i].fAdvance;
854 }
855 // Assume it is always safe to break after the end of an item
856 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
857 modelText[utf8runLength].advance = model.fAdvance;
858 modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400859 modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400860 modelNeedsRegenerated = false;
861 }
862
863 // TODO: break iterator per item, but just reset position if needed?
864 // Maybe break iterator with model?
865 UBreakIterator& breakIterator = *fLineBreakIterator;
866 {
867 UErrorCode status = U_ZERO_ERROR;
Ben Wagner723a8772019-08-16 11:36:58 -0400868 UText sUtf8UText = UTEXT_INITIALIZER;
869 ICUUText utf8UText(utext_openUTF8(&sUtf8UText, utf8Start, utf8runLength, &status));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400870 if (U_FAILURE(status)) {
871 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400872 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400873 }
Ben Wagner723a8772019-08-16 11:36:58 -0400874 ubrk_setUText(&breakIterator, utf8UText.get(), &status);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400875 if (U_FAILURE(status)) {
876 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400877 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400878 }
879 }
880
Ben Wagner7415a422019-03-25 15:38:22 -0400881 ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
882 { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
883 bool bestIsInvalid = true;
884 bool bestUsesModelForGlyphs = false;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400885 SkScalar widthLeft = width - line.fAdvance.fX;
886
887 for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
888 breakIteratorCurrent != UBRK_DONE;
889 breakIteratorCurrent = ubrk_next(&breakIterator))
890 {
891 // TODO: if past a safe to break, future safe to break will be at least as long
892
893 // TODO: adjust breakIteratorCurrent by ignorable whitespace
Ben Wagner7415a422019-03-25 15:38:22 -0400894 bool candidateUsesModelForGlyphs = false;
895 ShapedRun candidate = [&](const TextProps& props){
896 if (props.glyphLen) {
897 candidateUsesModelForGlyphs = true;
898 return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400899 font.currentFont(), bidi.currentLevel(),
Ben Wagner7415a422019-03-25 15:38:22 -0400900 std::unique_ptr<ShapedGlyph[]>(),
901 props.glyphLen - modelGlyphOffset,
902 props.advance - modelAdvanceOffset);
903 } else {
904 return shape(utf8, utf8Bytes,
905 utf8Start, utf8Start + breakIteratorCurrent,
906 bidi, language, script, font);
907 }
908 }(modelText[breakIteratorCurrent + modelTextOffset]);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400909 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
910 if (run.fAdvance.fX < widthLeft) {
Ben Wagner7415a422019-03-25 15:38:22 -0400911 return run.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400912 } else {
913 return widthLeft - run.fAdvance.fX;
914 }
915 };
Ben Wagner7415a422019-03-25 15:38:22 -0400916 if (bestIsInvalid || score(best) < score(candidate)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400917 best = std::move(candidate);
Ben Wagner7415a422019-03-25 15:38:22 -0400918 bestIsInvalid = false;
919 bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400920 }
921 }
922
923 // If nothing fit (best score is negative) and the line is not empty
924 if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400925 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400926 line.runs.reset();
927 line.fAdvance = {0, 0};
928 } else {
Ben Wagner7415a422019-03-25 15:38:22 -0400929 if (bestUsesModelForGlyphs) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400930 best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
Ben Wagner7415a422019-03-25 15:38:22 -0400931 memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400932 best.fNumGlyphs * sizeof(ShapedGlyph));
Ben Wagner7415a422019-03-25 15:38:22 -0400933 modelGlyphOffset += best.fNumGlyphs;
934 modelTextOffset += best.fUtf8Range.size();
935 modelAdvanceOffset += best.fAdvance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400936 } else {
937 modelNeedsRegenerated = true;
938 }
Ben Wagner7415a422019-03-25 15:38:22 -0400939 utf8Start += best.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400940 line.fAdvance += best.fAdvance;
941 line.runs.emplace_back(std::move(best));
942
943 // If item broken, emit line (prevent remainder from accidentally fitting)
944 if (utf8Start != utf8End) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400945 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400946 line.runs.reset();
947 line.fAdvance = {0, 0};
948 }
949 }
950 }
951 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400952 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400953}
954
Ben Wagner51874e32019-04-04 15:21:20 -0400955void ShapeThenWrap::wrap(char const * const utf8, size_t utf8Bytes,
956 const BiDiRunIterator& bidi,
957 const LanguageRunIterator& language,
958 const ScriptRunIterator& script,
959 const FontRunIterator& font,
960 RunIteratorQueue& runSegmenter,
961 SkScalar width,
962 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400963{
964 SkTArray<ShapedRun> runs;
965{
966 UBreakIterator& lineBreakIterator = *fLineBreakIterator;
967 UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500968 {
969 UErrorCode status = U_ZERO_ERROR;
Ben Wagner723a8772019-08-16 11:36:58 -0400970 UText sUtf8UText = UTEXT_INITIALIZER;
971 ICUUText utf8UText(utext_openUTF8(&sUtf8UText, utf8, utf8Bytes, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500972 if (U_FAILURE(status)) {
973 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400974 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500975 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400976
Ben Wagner723a8772019-08-16 11:36:58 -0400977 ubrk_setUText(&lineBreakIterator, utf8UText.get(), &status);
Ben Wagner8d45a382017-11-16 10:08:28 -0500978 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400979 SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400980 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400981 }
Ben Wagner723a8772019-08-16 11:36:58 -0400982 ubrk_setUText(&graphemeBreakIterator, utf8UText.get(), &status);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400983 if (U_FAILURE(status)) {
984 SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400985 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500986 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400987 }
988
Ben Wagner8d45a382017-11-16 10:08:28 -0500989 const char* utf8Start = nullptr;
990 const char* utf8End = utf8;
991 while (runSegmenter.advanceRuns()) {
992 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400993 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500994
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400995 runs.emplace_back(shape(utf8, utf8Bytes,
996 utf8Start, utf8End,
997 bidi, language, script, font));
998 ShapedRun& run = runs.back();
Ben Wagnera25fbef2017-08-30 13:56:19 -0400999
Ben Wagner8d45a382017-11-16 10:08:28 -05001000 uint32_t previousCluster = 0xFFFFFFFF;
Ben Wagner7415a422019-03-25 15:38:22 -04001001 for (size_t i = 0; i < run.fNumGlyphs; ++i) {
Ben Wagner8d45a382017-11-16 10:08:28 -05001002 ShapedGlyph& glyph = run.fGlyphs[i];
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001003 int32_t glyphCluster = glyph.fCluster;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001004
1005 int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
1006 while (lineBreakIteratorCurrent != UBRK_DONE &&
1007 lineBreakIteratorCurrent < glyphCluster)
Ben Wagner8d45a382017-11-16 10:08:28 -05001008 {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001009 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
Ben Wagner2868b782017-08-31 14:12:27 -04001010 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001011 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001012 lineBreakIteratorCurrent == glyphCluster;
1013
1014 int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1015 while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1016 graphemeBreakIteratorCurrent < glyphCluster)
1017 {
1018 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1019 }
1020 glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1021 graphemeBreakIteratorCurrent == glyphCluster;
1022
Ben Wagner8d45a382017-11-16 10:08:28 -05001023 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001024 }
1025 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001026}
1027
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001028// Iterate over the glyphs in logical order to find potential line lengths.
Ben Wagner8d45a382017-11-16 10:08:28 -05001029{
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001030 /** The position of the beginning of the line. */
1031 ShapedRunGlyphIterator beginning(runs);
1032
1033 /** The position of the candidate line break. */
1034 ShapedRunGlyphIterator candidateLineBreak(runs);
1035 SkScalar candidateLineBreakWidth = 0;
1036
1037 /** The position of the candidate grapheme break. */
1038 ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1039 SkScalar candidateGraphemeBreakWidth = 0;
1040
1041 /** The position of the current location. */
1042 ShapedRunGlyphIterator current(runs);
1043 SkScalar currentWidth = 0;
1044 while (ShapedGlyph* glyph = current.current()) {
1045 // 'Break' at graphemes until a line boundary, then only at line boundaries.
1046 // Only break at graphemes if no line boundary is valid.
1047 if (current != beginning) {
1048 if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1049 // TODO: preserve line breaks <= grapheme breaks
1050 // and prevent line breaks inside graphemes
1051 candidateGraphemeBreak = current;
1052 candidateGraphemeBreakWidth = currentWidth;
1053 if (glyph->fMayLineBreakBefore) {
1054 candidateLineBreak = current;
1055 candidateLineBreakWidth = currentWidth;
1056 }
1057 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001058 }
1059
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001060 SkScalar glyphWidth = glyph->fAdvance.fX;
1061 // Break when overwidth, the glyph has a visual representation, and some space is used.
1062 if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1063 if (candidateLineBreak != beginning) {
1064 beginning = candidateLineBreak;
1065 currentWidth -= candidateLineBreakWidth;
1066 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1067 candidateLineBreakWidth = 0;
1068 } else if (candidateGraphemeBreak != beginning) {
1069 beginning = candidateGraphemeBreak;
1070 candidateLineBreak = beginning;
1071 currentWidth -= candidateGraphemeBreakWidth;
1072 candidateGraphemeBreakWidth = 0;
1073 candidateLineBreakWidth = 0;
1074 } else {
1075 SK_ABORT("");
1076 }
1077
1078 if (width < currentWidth) {
1079 if (width < candidateGraphemeBreakWidth) {
1080 candidateGraphemeBreak = candidateLineBreak;
1081 candidateGraphemeBreakWidth = candidateLineBreakWidth;
1082 }
1083 current = candidateGraphemeBreak;
1084 currentWidth = candidateGraphemeBreakWidth;
1085 }
1086
1087 glyph = beginning.current();
1088 if (glyph) {
1089 glyph->fMustLineBreakBefore = true;
1090 }
1091
1092 } else {
1093 current.next();
1094 currentWidth += glyphWidth;
Ben Wagner8d45a382017-11-16 10:08:28 -05001095 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001096 }
1097}
1098
1099// Reorder the runs and glyphs per line and write them out.
1100{
1101 ShapedRunGlyphIterator previousBreak(runs);
1102 ShapedRunGlyphIterator glyphIterator(runs);
Ben Wagner8d45a382017-11-16 10:08:28 -05001103 int previousRunIndex = -1;
1104 while (glyphIterator.current()) {
1105 int runIndex = glyphIterator.fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -04001106 size_t glyphIndex = glyphIterator.fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -05001107 ShapedGlyph* nextGlyph = glyphIterator.next();
1108
1109 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -05001110 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -05001111 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -05001112 previousRunIndex = runIndex;
1113 }
1114
1115 // Nothing can be written until the baseline is known.
1116 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1117 continue;
1118 }
1119
Ben Wagner8d45a382017-11-16 10:08:28 -05001120 int numRuns = runIndex - previousBreak.fRunIndex + 1;
1121 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1122 for (int i = 0; i < numRuns; ++i) {
1123 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1124 }
1125 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1126 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1127
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001128 // step through the runs in reverse visual order and the glyphs in reverse logical order
1129 // until a visible glyph is found and force them to the end of the visual line.
1130
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001131 handler->beginLine();
Ben Wagner8d45a382017-11-16 10:08:28 -05001132 for (int i = 0; i < numRuns; ++i) {
1133 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001134 const auto& run = runs[logicalIndex];
1135 const RunHandler::RunInfo info = {
1136 run.fFont,
1137 run.fLevel,
1138 run.fAdvance,
1139 run.fNumGlyphs,
1140 run.fUtf8Range
1141 };
1142 handler->runInfo(info);
1143 }
1144 handler->commitRunInfo();
1145 for (int i = 0; i < numRuns; ++i) {
1146 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1147 const auto& run = runs[logicalIndex];
1148 const RunHandler::RunInfo info = {
1149 run.fFont,
1150 run.fLevel,
1151 run.fAdvance,
1152 run.fNumGlyphs,
1153 run.fUtf8Range
1154 };
Ben Wagner8d45a382017-11-16 10:08:28 -05001155
Ben Wagner7415a422019-03-25 15:38:22 -04001156 size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1157 ? previousBreak.fGlyphIndex
1158 : 0;
1159 size_t endGlyphIndex = (logicalIndex == runIndex)
1160 ? glyphIndex + 1
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001161 : run.fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -05001162
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001163 append(handler, info, run, startGlyphIndex, endGlyphIndex);
Ben Wagner8d45a382017-11-16 10:08:28 -05001164 }
1165
Florin Malita500133b2019-02-07 10:56:55 -05001166 handler->commitLine();
1167
Ben Wagner8d45a382017-11-16 10:08:28 -05001168 previousRunIndex = -1;
1169 previousBreak = glyphIterator;
1170 }
1171}
Ben Wagnera25fbef2017-08-30 13:56:19 -04001172}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001173
Ben Wagner6bb79bb2019-05-15 10:50:20 -04001174void ShapeDontWrapOrReorder::wrap(char const * const utf8, size_t utf8Bytes,
1175 const BiDiRunIterator& bidi,
1176 const LanguageRunIterator& language,
1177 const ScriptRunIterator& script,
1178 const FontRunIterator& font,
1179 RunIteratorQueue& runSegmenter,
1180 SkScalar width,
1181 RunHandler* handler) const
1182{
1183 sk_ignore_unused_variable(width);
1184 SkTArray<ShapedRun> runs;
1185
1186 const char* utf8Start = nullptr;
1187 const char* utf8End = utf8;
1188 while (runSegmenter.advanceRuns()) {
1189 utf8Start = utf8End;
1190 utf8End = utf8 + runSegmenter.endOfCurrentRun();
1191
1192 runs.emplace_back(shape(utf8, utf8Bytes,
1193 utf8Start, utf8End,
1194 bidi, language, script, font));
1195 }
1196
1197 handler->beginLine();
1198 for (const auto& run : runs) {
1199 const RunHandler::RunInfo info = {
1200 run.fFont,
1201 run.fLevel,
1202 run.fAdvance,
1203 run.fNumGlyphs,
1204 run.fUtf8Range
1205 };
1206 handler->runInfo(info);
1207 }
1208 handler->commitRunInfo();
1209 for (const auto& run : runs) {
1210 const RunHandler::RunInfo info = {
1211 run.fFont,
1212 run.fLevel,
1213 run.fAdvance,
1214 run.fNumGlyphs,
1215 run.fUtf8Range
1216 };
1217 append(handler, info, run, 0, run.fNumGlyphs);
1218 }
1219 handler->commitLine();
1220}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001221
Ben Wagner51874e32019-04-04 15:21:20 -04001222ShapedRun ShaperHarfBuzz::shape(char const * const utf8,
Ben Wagner7415a422019-03-25 15:38:22 -04001223 size_t const utf8Bytes,
1224 char const * const utf8Start,
1225 char const * const utf8End,
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001226 const BiDiRunIterator& bidi,
1227 const LanguageRunIterator& language,
1228 const ScriptRunIterator& script,
1229 const FontRunIterator& font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001230{
Ben Wagner7415a422019-03-25 15:38:22 -04001231 size_t utf8runLength = utf8End - utf8Start;
1232 ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001233 font.currentFont(), bidi.currentLevel(), nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001234
1235 hb_buffer_t* buffer = fBuffer.get();
1236 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1237 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1238 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1239
Ben Wagner2fc14742019-02-06 16:37:44 -05001240 // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1241 hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1242
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001243 // Add precontext.
1244 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1245
1246 // Populate the hb_buffer directly with utf8 cluster indexes.
1247 const char* utf8Current = utf8Start;
1248 while (utf8Current < utf8End) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001249 unsigned int cluster = utf8Current - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001250 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1251 hb_buffer_add(buffer, u, cluster);
1252 }
1253
1254 // Add postcontext.
1255 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1256
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001257 hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001258 hb_buffer_set_direction(buffer, direction);
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001259 hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1260 hb_buffer_set_language(buffer, hb_language_from_string(language.currentLanguage(), -1));
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001261 hb_buffer_guess_segment_properties(buffer);
1262 // TODO: features
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001263
1264 // TODO: how to cache hbface (typeface) / hbfont (font)
1265 HBFont hbFont(create_hb_font(font.currentFont()));
1266 if (!hbFont) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001267 return run;
1268 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001269 hb_shape(hbFont.get(), buffer, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001270 unsigned len = hb_buffer_get_length(buffer);
1271 if (len == 0) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001272 return run;
1273 }
1274
1275 if (direction == HB_DIRECTION_RTL) {
1276 // Put the clusters back in logical order.
1277 // Note that the advances remain ltr.
1278 hb_buffer_reverse(buffer);
1279 }
1280 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1281 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1282
Ben Wagner7415a422019-03-25 15:38:22 -04001283 run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001284 font.currentFont(), bidi.currentLevel(),
Ben Wagner454e5fb2019-02-08 17:46:38 -05001285 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001286 int scaleX, scaleY;
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001287 hb_font_get_scale(hbFont.get(), &scaleX, &scaleY);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001288 double textSizeY = run.fFont.getSize() / scaleY;
1289 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1290 SkVector runAdvance = { 0, 0 };
1291 for (unsigned i = 0; i < len; i++) {
1292 ShapedGlyph& glyph = run.fGlyphs[i];
1293 glyph.fID = info[i].codepoint;
1294 glyph.fCluster = info[i].cluster;
1295 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1296 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1297 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1298 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1299
1300 SkRect bounds;
1301 SkScalar advance;
1302 SkPaint p;
1303 run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1304 glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
Kevin Lubick867da4b2019-02-22 15:55:39 -05001305#if SK_HB_VERSION_CHECK(1, 5, 0)
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001306 glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
Kevin Lubick867da4b2019-02-22 15:55:39 -05001307#else
1308 glyph.fUnsafeToBreak = false;
1309#endif
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001310 glyph.fMustLineBreakBefore = false;
1311
1312 runAdvance += glyph.fAdvance;
1313 }
1314 run.fAdvance = runAdvance;
1315
1316 return run;
1317}
Ben Wagner51874e32019-04-04 15:21:20 -04001318
1319} // namespace
1320
1321std::unique_ptr<SkShaper::BiDiRunIterator>
1322SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1323 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
1324 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
1325 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
1326 SkDEBUGF("Bidi error: text too long");
1327 return nullptr;
1328 }
1329
1330 UErrorCode status = U_ZERO_ERROR;
1331
1332 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
1333 int32_t utf16Units;
1334 u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
1335 status = U_ZERO_ERROR;
1336 std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
1337 u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
1338 if (U_FAILURE(status)) {
1339 SkDEBUGF("Invalid utf8 input: %s", u_errorName(status));
1340 return nullptr;
1341 }
1342
1343 ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
1344 if (U_FAILURE(status)) {
1345 SkDEBUGF("Bidi error: %s", u_errorName(status));
1346 return nullptr;
1347 }
1348 SkASSERT(bidi);
1349
1350 // The required lifetime of utf16 isn't well documented.
1351 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
1352 ubidi_setPara(bidi.get(), utf16.get(), utf16Units, bidiLevel, nullptr, &status);
1353 if (U_FAILURE(status)) {
1354 SkDEBUGF("Bidi error: %s", u_errorName(status));
1355 return nullptr;
1356 }
1357
1358 return skstd::make_unique<IcuBiDiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
1359}
1360
1361std::unique_ptr<SkShaper::ScriptRunIterator>
1362SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1363 return skstd::make_unique<HbIcuScriptRunIterator>(utf8, utf8Bytes);
1364}
1365
Florin Malita42684332019-07-26 14:54:40 -04001366std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(sk_sp<SkFontMgr> fontmgr) {
1367 return MakeHarfBuzz(std::move(fontmgr), true);
Ben Wagner51874e32019-04-04 15:21:20 -04001368}
Florin Malita42684332019-07-26 14:54:40 -04001369std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(sk_sp<SkFontMgr> fontmgr) {
1370 return MakeHarfBuzz(std::move(fontmgr), false);
Ben Wagner51874e32019-04-04 15:21:20 -04001371}
Florin Malita42684332019-07-26 14:54:40 -04001372std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(sk_sp<SkFontMgr> fontmgr) {
Ben Wagner6bb79bb2019-05-15 10:50:20 -04001373 #if defined(SK_USING_THIRD_PARTY_ICU)
1374 if (!SkLoadICU()) {
1375 SkDEBUGF("SkLoadICU() failed!\n");
1376 return nullptr;
1377 }
1378 #endif
1379 HBBuffer buffer(hb_buffer_create());
1380 if (!buffer) {
1381 SkDEBUGF("Could not create hb_buffer");
1382 return nullptr;
1383 }
1384
Florin Malita42684332019-07-26 14:54:40 -04001385 return skstd::make_unique<ShapeDontWrapOrReorder>(std::move(buffer), nullptr, nullptr,
1386 std::move(fontmgr));
Ben Wagner6bb79bb2019-05-15 10:50:20 -04001387}