blob: 806900d2c3a46854d8182acc694be602e2a1e2ef [file] [log] [blame]
Julia Lavrova90787fe2020-07-20 17:32:03 +00001/*
2* Copyright 2020 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*/
Julia Lavrovab6b7fff2020-09-11 13:59:49 +00007#include "include/core/SkString.h"
Julia Lavrova90787fe2020-07-20 17:32:03 +00008#include "include/private/SkTFitsIn.h"
9#include "include/private/SkTemplates.h"
10#include "modules/skshaper/src/SkUnicode.h"
11#include "src/utils/SkUTF.h"
12#include <unicode/ubidi.h>
13#include <unicode/ubrk.h>
Julia Lavrova36700ef2020-08-25 11:42:51 -040014#include <unicode/uscript.h>
Julia Lavrovab6b7fff2020-09-11 13:59:49 +000015#include <unicode/ustring.h>
Julia Lavrova90787fe2020-07-20 17:32:03 +000016#include <unicode/utext.h>
17#include <unicode/utypes.h>
18#include <vector>
19#include <functional>
20
Julia Lavrovab6b7fff2020-09-11 13:59:49 +000021#if defined(SK_USING_THIRD_PARTY_ICU)
22#include "SkLoadICU.h"
23#endif
24
Julia Lavrova1798f4f2020-08-26 14:22:48 +000025using SkUnicodeBidi = std::unique_ptr<UBiDi, SkFunctionWrapper<decltype(ubidi_close), ubidi_close>>;
Julia Lavrova90787fe2020-07-20 17:32:03 +000026using ICUUText = std::unique_ptr<UText, SkFunctionWrapper<decltype(utext_close), utext_close>>;
27using ICUBreakIterator = std::unique_ptr<UBreakIterator, SkFunctionWrapper<decltype(ubrk_close), ubrk_close>>;
28
29/** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
30static inline SkUnichar utf8_next(const char** ptr, const char* end) {
31 SkUnichar val = SkUTF::NextUTF8(ptr, end);
32 return val < 0 ? 0xFFFD : val;
33}
34
Julia Lavrova1798f4f2020-08-26 14:22:48 +000035class SkBidiIterator_icu : public SkBidiIterator {
36 SkUnicodeBidi fBidi;
37public:
38 explicit SkBidiIterator_icu(SkUnicodeBidi bidi) : fBidi(std::move(bidi)) {}
39 Position getLength() override { return ubidi_getLength(fBidi.get()); }
40 Level getLevelAt(Position pos) override { return ubidi_getLevelAt(fBidi.get(), pos); }
41
42 static std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t utf16[], int utf16Units, Direction dir) {
43 UErrorCode status = U_ZERO_ERROR;
44 SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
45 if (U_FAILURE(status)) {
46 SkDEBUGF("Bidi error: %s", u_errorName(status));
47 return nullptr;
48 }
49 SkASSERT(bidi);
50 uint8_t bidiLevel = (dir == SkBidiIterator::kLTR) ? UBIDI_LTR : UBIDI_RTL;
51 // The required lifetime of utf16 isn't well documented.
52 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
53 ubidi_setPara(bidi.get(), (const UChar*)utf16, utf16Units, bidiLevel, nullptr, &status);
54 if (U_FAILURE(status)) {
55 SkDEBUGF("Bidi error: %s", u_errorName(status));
56 return nullptr;
57 }
58 return std::unique_ptr<SkBidiIterator>(new SkBidiIterator_icu(std::move(bidi)));
59 }
60
61 // ICU bidi iterator works with utf16 but clients (Flutter for instance) may work with utf8
62 // This method allows the clients not to think about all these details
63 static std::unique_ptr<SkBidiIterator> makeBidiIterator(const char utf8[], int utf8Units, Direction dir) {
64 // Convert utf8 into utf16 since ubidi only accepts utf16
65 if (!SkTFitsIn<int32_t>(utf8Units)) {
66 SkDEBUGF("Bidi error: text too long");
67 return nullptr;
68 }
69
70 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
71 int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
72 if (utf16Units < 0) {
73 SkDEBUGF("Bidi error: Invalid utf8 input");
74 return nullptr;
75 }
76 std::unique_ptr<uint16_t[]> utf16(new uint16_t[utf16Units]);
77 SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16.get(), utf16Units, utf8, utf8Units);
78 SkASSERT(dstLen == utf16Units);
79
80 return makeBidiIterator(utf16.get(), utf16Units, dir);
81 }
82
83 // This method returns the final results only: a list of bidi regions
84 // (this is all SkParagraph really needs; SkShaper however uses the iterator itself)
85 static std::vector<Region> getBidiRegions(const char utf8[], int utf8Units, Direction dir) {
86
87 auto bidiIterator = makeBidiIterator(utf8, utf8Units, dir);
88 std::vector<Region> bidiRegions;
89 const char* start8 = utf8;
90 const char* end8 = utf8 + utf8Units;
91 SkBidiIterator::Level currentLevel = 0;
92
93 Position pos8 = 0;
94 Position pos16 = 0;
95 Position end16 = bidiIterator->getLength();
96 while (pos16 < end16) {
97 auto level = bidiIterator->getLevelAt(pos16);
98 if (pos16 == 0) {
99 currentLevel = level;
100 } else if (level != currentLevel) {
101 auto end = start8 - utf8;
102 bidiRegions.emplace_back(pos8, end, currentLevel);
103 currentLevel = level;
104 pos8 = end;
105 }
106 SkUnichar u = utf8_next(&start8, end8);
107 pos16 += SkUTF::ToUTF16(u);
108 }
109 auto end = start8 - utf8;
110 if (end != pos8) {
111 bidiRegions.emplace_back(pos8, end, currentLevel);
112 }
113 return bidiRegions;
114 }
115};
116
117void SkBidiIterator::ReorderVisual(const Level runLevels[], int levelsCount,
118 int32_t logicalFromVisual[]) {
119 ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
120}
Julia Lavrova90787fe2020-07-20 17:32:03 +0000121
Julia Lavrova6e51d922020-08-25 11:42:51 -0400122class SkBreakIterator_icu : public SkBreakIterator {
123 ICUBreakIterator fBreakIterator;
124 Position fLastResult;
125 public:
126 explicit SkBreakIterator_icu(ICUBreakIterator iter)
127 : fBreakIterator(std::move(iter)), fLastResult(0) {}
128 Position first() override
129 { return fLastResult = ubrk_first(fBreakIterator.get()); }
130 Position current() override
131 { return fLastResult = ubrk_current(fBreakIterator.get()); }
132 Position next() override
133 { return fLastResult = ubrk_next(fBreakIterator.get()); }
134 Position preceding(Position offset) override
135 { return fLastResult = ubrk_preceding(fBreakIterator.get(), offset); }
136 Position following(Position offset) override
137 { return fLastResult = ubrk_following(fBreakIterator.get(), offset);}
138 Status status() override { return ubrk_getRuleStatus(fBreakIterator.get()); }
139 bool isDone() override { return fLastResult == UBRK_DONE; }
140
141 bool setText(const char utftext8[], int utf8Units) override {
142 UErrorCode status = U_ZERO_ERROR;
143
144 UText sUtf8UText = UTEXT_INITIALIZER;
145 ICUUText text(utext_openUTF8(&sUtf8UText, &utftext8[0], utf8Units, &status));
146
147 if (U_FAILURE(status)) {
148 SkDEBUGF("Break error: %s", u_errorName(status));
149 return false;
150 }
151 SkASSERT(text);
152 ubrk_setUText(fBreakIterator.get(), text.get(), &status);
153 if (U_FAILURE(status)) {
154 SkDEBUGF("Break error: %s", u_errorName(status));
155 return false;
156 }
157 fLastResult = 0;
158 return true;
159 }
160
161 static UBreakIteratorType convertType(SkUnicode::BreakType type) {
162 switch (type) {
163 case SkUnicode::BreakType::kLines: return UBRK_LINE;
164 case SkUnicode::BreakType::kGraphemes: return UBRK_CHARACTER;
165 case SkUnicode::BreakType::kWords: return UBRK_WORD;
166 default:
167 return UBRK_CHARACTER;
168 }
169 }
170
171 static std::unique_ptr<SkBreakIterator> makeUtf8BreakIterator
172 (const char locale[], SkUnicode::BreakType type) {
173 UErrorCode status = U_ZERO_ERROR;
174 ICUBreakIterator iterator(ubrk_open(convertType(type), locale, nullptr, 0, &status));
175 if (U_FAILURE(status)) {
176 SkDEBUGF("Break error: %s", u_errorName(status));
177 return nullptr;
178 }
179 return std::unique_ptr<SkBreakIterator>(new SkBreakIterator_icu(std::move(iterator)));
180 }
181};
182
Julia Lavrova36700ef2020-08-25 11:42:51 -0400183class SkScriptIterator_icu : public SkScriptIterator {
184 public:
185 bool getScript(SkUnichar u, ScriptID* script) override {
186 UErrorCode status = U_ZERO_ERROR;
187 UScriptCode scriptCode = uscript_getScript(u, &status);
188 if (U_FAILURE (status)) {
189 return false;
190 }
191 if (script) {
192 *script = (ScriptID)scriptCode;
193 }
194 return true;
195 }
196
197 static std::unique_ptr<SkScriptIterator> makeScriptIterator() {
198 return std::unique_ptr<SkScriptIterator>(new SkScriptIterator_icu());
199 }
200};
201
Julia Lavrova90787fe2020-07-20 17:32:03 +0000202class SkUnicode_icu : public SkUnicode {
203
Julia Lavrova6e51d922020-08-25 11:42:51 -0400204 static UBreakIteratorType convertType(BreakType type) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000205 switch (type) {
Julia Lavrova6e51d922020-08-25 11:42:51 -0400206 case BreakType::kLines: return UBRK_LINE;
207 case BreakType::kGraphemes: return UBRK_CHARACTER;
208 case BreakType::kWords: return UBRK_WORD;
Julia Lavrova90787fe2020-07-20 17:32:03 +0000209 default:
210 SkDEBUGF("Convert error: wrong break type");
211 return UBRK_CHARACTER;
212 }
213 }
214
Julia Lavrova6e51d922020-08-25 11:42:51 -0400215 static bool extractBidi(const char utf8[],
216 int utf8Units,
217 TextDirection dir,
218 std::vector<BidiRegion>* bidiRegions) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000219
220 // Convert to UTF16 since for now bidi iterator only operates on utf16
221 std::unique_ptr<uint16_t[]> utf16;
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000222 auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000223 if (utf16Units < 0) {
224 return false;
225 }
226
227 // Create bidi iterator
228 UErrorCode status = U_ZERO_ERROR;
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000229 SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
Julia Lavrova90787fe2020-07-20 17:32:03 +0000230 if (U_FAILURE(status)) {
231 SkDEBUGF("Bidi error: %s", u_errorName(status));
232 return false;
233 }
234 SkASSERT(bidi);
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000235 uint8_t bidiLevel = (dir == TextDirection::kLTR) ? UBIDI_LTR : UBIDI_RTL;
Julia Lavrova90787fe2020-07-20 17:32:03 +0000236 // The required lifetime of utf16 isn't well documented.
237 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
238 ubidi_setPara(bidi.get(), (const UChar*)utf16.get(), utf16Units, bidiLevel, nullptr, &status);
239 if (U_FAILURE(status)) {
240 SkDEBUGF("Bidi error: %s", u_errorName(status));
241 return false;
242 }
243
244 // Iterate through bidi regions and the result positions into utf8
245 const char* start8 = utf8;
246 const char* end8 = utf8 + utf8Units;
247 BidiLevel currentLevel = 0;
248
249 Position pos8 = 0;
250 Position pos16 = 0;
251 Position end16 = ubidi_getLength(bidi.get());
252 while (pos16 < end16) {
253 auto level = ubidi_getLevelAt(bidi.get(), pos16);
254 if (pos16 == 0) {
255 currentLevel = level;
256 } else if (level != currentLevel) {
257 Position end = start8 - utf8;
258 bidiRegions->emplace_back(pos8, end, currentLevel);
259 currentLevel = level;
260 pos8 = end;
261 }
262 SkUnichar u = utf8_next(&start8, end8);
263 pos16 += SkUTF::ToUTF16(u);
264 }
265 Position end = start8 - utf8;
266 if (end != pos8) {
267 bidiRegions->emplace_back(pos8, end, currentLevel);
268 }
269 return true;
270 }
271
272 static bool extractWords(uint16_t utf16[], int utf16Units, std::vector<Position>* words) {
273
274 UErrorCode status = U_ZERO_ERROR;
275
Julia Lavrova6e51d922020-08-25 11:42:51 -0400276 UBreakIteratorType breakType = convertType(BreakType::kWords);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000277 ICUBreakIterator iterator(ubrk_open(breakType, uloc_getDefault(), nullptr, 0, &status));
278 if (U_FAILURE(status)) {
279 SkDEBUGF("Break error: %s", u_errorName(status));
280 return false;
281 }
282 SkASSERT(iterator);
283
284 UText sUtf16UText = UTEXT_INITIALIZER;
285 ICUUText utf16UText(utext_openUChars(&sUtf16UText, (UChar*)utf16, utf16Units, &status));
286 if (U_FAILURE(status)) {
287 SkDEBUGF("Break error: %s", u_errorName(status));
288 return false;
289 }
290
291 ubrk_setUText(iterator.get(), utf16UText.get(), &status);
292 if (U_FAILURE(status)) {
293 SkDEBUGF("Break error: %s", u_errorName(status));
294 return false;
295 }
296
297 // Get the words
298 int32_t pos = ubrk_first(iterator.get());
299 while (pos != UBRK_DONE) {
300 words->emplace_back(pos);
301 pos = ubrk_next(iterator.get());
302 }
303
304 return true;
305 }
306
Julia Lavrova6e51d922020-08-25 11:42:51 -0400307 static bool extractPositions
308 (const char utf8[], int utf8Units, BreakType type, std::function<void(int, int)> add) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000309
310 UErrorCode status = U_ZERO_ERROR;
311 UText sUtf8UText = UTEXT_INITIALIZER;
312 ICUUText text(utext_openUTF8(&sUtf8UText, &utf8[0], utf8Units, &status));
313
314 if (U_FAILURE(status)) {
315 SkDEBUGF("Break error: %s", u_errorName(status));
316 return false;
317 }
318 SkASSERT(text);
319
320 ICUBreakIterator iterator(ubrk_open(convertType(type), uloc_getDefault(), nullptr, 0, &status));
321 if (U_FAILURE(status)) {
322 SkDEBUGF("Break error: %s", u_errorName(status));
323 }
324
325 ubrk_setUText(iterator.get(), text.get(), &status);
326 if (U_FAILURE(status)) {
327 SkDEBUGF("Break error: %s", u_errorName(status));
328 return false;
329 }
330
331 auto iter = iterator.get();
332 int32_t pos = ubrk_first(iter);
333 while (pos != UBRK_DONE) {
334 add(pos, ubrk_getRuleStatus(iter));
335 pos = ubrk_next(iter);
336 }
337 return true;
338 }
339
Julia Lavrova6e51d922020-08-25 11:42:51 -0400340 static bool extractWhitespaces(const char utf8[],
341 int utf8Units,
342 std::vector<Position>* whitespaces) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000343
344 const char* start = utf8;
345 const char* end = utf8 + utf8Units;
346 const char* ch = start;
347 while (ch < end) {
348 auto index = ch - start;
349 auto unichar = utf8_next(&ch, end);
350 if (u_isWhitespace(unichar)) {
351 auto ending = ch - start;
352 for (auto k = index; k < ending; ++k) {
353 whitespaces->emplace_back(k);
354 }
355 }
356 }
357 return true;
358 }
359
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000360 static int utf8ToUtf16(const char* utf8, size_t utf8Units, std::unique_ptr<uint16_t[]>* utf16) {
361 int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
362 if (utf16Units < 0) {
363 SkDEBUGF("Convert error: Invalid utf8 input");
364 return utf16Units;
365 }
366 *utf16 = std::unique_ptr<uint16_t[]>(new uint16_t[utf16Units]);
367 SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16->get(), utf16Units, utf8, utf8Units);
368 SkASSERT(dstLen == utf16Units);
369 return utf16Units;
370 }
371
372 static int utf16ToUtf8(const uint16_t* utf16, size_t utf16Units, std::unique_ptr<char[]>* utf8) {
373 int utf8Units = SkUTF::UTF16ToUTF8(nullptr, 0, utf16, utf16Units);
374 if (utf8Units < 0) {
375 SkDEBUGF("Convert error: Invalid utf16 input");
376 return utf8Units;
377 }
378 *utf8 = std::unique_ptr<char[]>(new char[utf8Units]);
379 SkDEBUGCODE(int dstLen =) SkUTF::UTF16ToUTF8(utf8->get(), utf8Units, utf16, utf16Units);
380 SkASSERT(dstLen == utf8Units);
381 return utf8Units;
382 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400383
Julia Lavrova90787fe2020-07-20 17:32:03 +0000384public:
385 ~SkUnicode_icu() override { }
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000386 std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t text[], int count,
387 SkBidiIterator::Direction dir) override {
388 return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
389 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400390 std::unique_ptr<SkBidiIterator> makeBidiIterator(const char text[],
391 int count,
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000392 SkBidiIterator::Direction dir) override {
393 return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
394 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400395 std::unique_ptr<SkBreakIterator> makeBreakIterator(const char locale[],
396 BreakType breakType) override {
397 return SkBreakIterator_icu::makeUtf8BreakIterator(locale, breakType);
398 }
Julia Lavrova36700ef2020-08-25 11:42:51 -0400399 std::unique_ptr<SkScriptIterator> makeScriptIterator() override {
400 return SkScriptIterator_icu::makeScriptIterator();
401 }
Julia Lavrova90787fe2020-07-20 17:32:03 +0000402
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000403 // TODO: Use ICU data file to detect controls and whitespaces
404 bool isControl(SkUnichar utf8) override {
405 return u_iscntrl(utf8);
406 }
407
408 bool isWhitespace(SkUnichar utf8) override {
409 return u_isWhitespace(utf8);
410 }
411
412 SkString convertUtf16ToUtf8(const std::u16string& utf16) override {
413 std::unique_ptr<char[]> utf8;
414 auto utf8Units = SkUnicode_icu::utf16ToUtf8((uint16_t*)utf16.data(), utf16.size(), &utf8);
415 if (utf8Units >= 0) {
416 return SkString(utf8.get(), utf8Units);
417 } else {
418 return SkString();
419 }
420 }
421
Julia Lavrova6e51d922020-08-25 11:42:51 -0400422 bool getBidiRegions(const char utf8[],
423 int utf8Units,
424 TextDirection dir,
425 std::vector<BidiRegion>* results) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000426 return extractBidi(utf8, utf8Units, dir, results);
427 }
428
Julia Lavrova6e51d922020-08-25 11:42:51 -0400429 bool getLineBreaks(const char utf8[],
430 int utf8Units,
431 std::vector<LineBreakBefore>* results) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000432
Julia Lavrova6e51d922020-08-25 11:42:51 -0400433 return extractPositions(utf8, utf8Units, BreakType::kLines,
Julia Lavrova90787fe2020-07-20 17:32:03 +0000434 [results](int pos, int status) {
435 results->emplace_back(pos,status == UBRK_LINE_HARD
436 ? LineBreakType::kHardLineBreak
437 : LineBreakType::kSoftLineBreak);
438 });
439 }
440
441 bool getWords(const char utf8[], int utf8Units, std::vector<Position>* results) override {
442
443 // Convert to UTF16 since we want the results in utf16
444 std::unique_ptr<uint16_t[]> utf16;
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000445 auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000446 if (utf16Units < 0) {
447 return false;
448 }
449
450 return extractWords(utf16.get(), utf16Units, results);
451 }
452
453 bool getGraphemes(const char utf8[], int utf8Units, std::vector<Position>* results) override {
454
Julia Lavrova6e51d922020-08-25 11:42:51 -0400455 return extractPositions(utf8, utf8Units, BreakType::kGraphemes,
Julia Lavrova90787fe2020-07-20 17:32:03 +0000456 [results](int pos, int status) { results->emplace_back(pos);
457 });
458 }
459
460 bool getWhitespaces(const char utf8[], int utf8Units, std::vector<Position>* results) override {
461
462 return extractWhitespaces(utf8, utf8Units, results);
463 }
464
Julia Lavrova6e51d922020-08-25 11:42:51 -0400465 void reorderVisual(const BidiLevel runLevels[],
466 int levelsCount,
467 int32_t logicalFromVisual[]) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000468 ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
469 }
470};
471
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000472std::unique_ptr<SkUnicode> SkUnicode::Make() {
473 #if defined(SK_USING_THIRD_PARTY_ICU)
474 if (!SkLoadICU()) {
475 SkDEBUGF("SkLoadICU() failed!\n");
476 return nullptr;
477 }
478 #endif
479 return std::make_unique<SkUnicode_icu>();
480}