blob: 7eb0f86eea75e14141845df79ff6230441991ac4 [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 Lavrovab6b7fff2020-09-11 13:59:49 +000014#include <unicode/ustring.h>
Julia Lavrova90787fe2020-07-20 17:32:03 +000015#include <unicode/utext.h>
16#include <unicode/utypes.h>
17#include <vector>
18#include <functional>
19
Julia Lavrovab6b7fff2020-09-11 13:59:49 +000020#if defined(SK_USING_THIRD_PARTY_ICU)
21#include "SkLoadICU.h"
22#endif
23
Julia Lavrova1798f4f2020-08-26 14:22:48 +000024using SkUnicodeBidi = std::unique_ptr<UBiDi, SkFunctionWrapper<decltype(ubidi_close), ubidi_close>>;
Julia Lavrova90787fe2020-07-20 17:32:03 +000025using ICUUText = std::unique_ptr<UText, SkFunctionWrapper<decltype(utext_close), utext_close>>;
26using ICUBreakIterator = std::unique_ptr<UBreakIterator, SkFunctionWrapper<decltype(ubrk_close), ubrk_close>>;
27
28/** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
29static inline SkUnichar utf8_next(const char** ptr, const char* end) {
30 SkUnichar val = SkUTF::NextUTF8(ptr, end);
31 return val < 0 ? 0xFFFD : val;
32}
33
Julia Lavrova1798f4f2020-08-26 14:22:48 +000034class SkBidiIterator_icu : public SkBidiIterator {
35 SkUnicodeBidi fBidi;
36public:
37 explicit SkBidiIterator_icu(SkUnicodeBidi bidi) : fBidi(std::move(bidi)) {}
38 Position getLength() override { return ubidi_getLength(fBidi.get()); }
39 Level getLevelAt(Position pos) override { return ubidi_getLevelAt(fBidi.get(), pos); }
40
41 static std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t utf16[], int utf16Units, Direction dir) {
42 UErrorCode status = U_ZERO_ERROR;
43 SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
44 if (U_FAILURE(status)) {
45 SkDEBUGF("Bidi error: %s", u_errorName(status));
46 return nullptr;
47 }
48 SkASSERT(bidi);
49 uint8_t bidiLevel = (dir == SkBidiIterator::kLTR) ? UBIDI_LTR : UBIDI_RTL;
50 // The required lifetime of utf16 isn't well documented.
51 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
52 ubidi_setPara(bidi.get(), (const UChar*)utf16, utf16Units, bidiLevel, nullptr, &status);
53 if (U_FAILURE(status)) {
54 SkDEBUGF("Bidi error: %s", u_errorName(status));
55 return nullptr;
56 }
57 return std::unique_ptr<SkBidiIterator>(new SkBidiIterator_icu(std::move(bidi)));
58 }
59
60 // ICU bidi iterator works with utf16 but clients (Flutter for instance) may work with utf8
61 // This method allows the clients not to think about all these details
62 static std::unique_ptr<SkBidiIterator> makeBidiIterator(const char utf8[], int utf8Units, Direction dir) {
63 // Convert utf8 into utf16 since ubidi only accepts utf16
64 if (!SkTFitsIn<int32_t>(utf8Units)) {
65 SkDEBUGF("Bidi error: text too long");
66 return nullptr;
67 }
68
69 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
70 int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
71 if (utf16Units < 0) {
72 SkDEBUGF("Bidi error: Invalid utf8 input");
73 return nullptr;
74 }
75 std::unique_ptr<uint16_t[]> utf16(new uint16_t[utf16Units]);
76 SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16.get(), utf16Units, utf8, utf8Units);
77 SkASSERT(dstLen == utf16Units);
78
79 return makeBidiIterator(utf16.get(), utf16Units, dir);
80 }
81
82 // This method returns the final results only: a list of bidi regions
83 // (this is all SkParagraph really needs; SkShaper however uses the iterator itself)
84 static std::vector<Region> getBidiRegions(const char utf8[], int utf8Units, Direction dir) {
85
86 auto bidiIterator = makeBidiIterator(utf8, utf8Units, dir);
87 std::vector<Region> bidiRegions;
88 const char* start8 = utf8;
89 const char* end8 = utf8 + utf8Units;
90 SkBidiIterator::Level currentLevel = 0;
91
92 Position pos8 = 0;
93 Position pos16 = 0;
94 Position end16 = bidiIterator->getLength();
95 while (pos16 < end16) {
96 auto level = bidiIterator->getLevelAt(pos16);
97 if (pos16 == 0) {
98 currentLevel = level;
99 } else if (level != currentLevel) {
100 auto end = start8 - utf8;
101 bidiRegions.emplace_back(pos8, end, currentLevel);
102 currentLevel = level;
103 pos8 = end;
104 }
105 SkUnichar u = utf8_next(&start8, end8);
106 pos16 += SkUTF::ToUTF16(u);
107 }
108 auto end = start8 - utf8;
109 if (end != pos8) {
110 bidiRegions.emplace_back(pos8, end, currentLevel);
111 }
112 return bidiRegions;
113 }
114};
115
116void SkBidiIterator::ReorderVisual(const Level runLevels[], int levelsCount,
117 int32_t logicalFromVisual[]) {
118 ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
119}
Julia Lavrova90787fe2020-07-20 17:32:03 +0000120
Julia Lavrova6e51d922020-08-25 11:42:51 -0400121class SkBreakIterator_icu : public SkBreakIterator {
122 ICUBreakIterator fBreakIterator;
123 Position fLastResult;
124 public:
125 explicit SkBreakIterator_icu(ICUBreakIterator iter)
126 : fBreakIterator(std::move(iter)), fLastResult(0) {}
127 Position first() override
128 { return fLastResult = ubrk_first(fBreakIterator.get()); }
129 Position current() override
130 { return fLastResult = ubrk_current(fBreakIterator.get()); }
131 Position next() override
132 { return fLastResult = ubrk_next(fBreakIterator.get()); }
133 Position preceding(Position offset) override
134 { return fLastResult = ubrk_preceding(fBreakIterator.get(), offset); }
135 Position following(Position offset) override
136 { return fLastResult = ubrk_following(fBreakIterator.get(), offset);}
137 Status status() override { return ubrk_getRuleStatus(fBreakIterator.get()); }
138 bool isDone() override { return fLastResult == UBRK_DONE; }
139
140 bool setText(const char utftext8[], int utf8Units) override {
141 UErrorCode status = U_ZERO_ERROR;
142
143 UText sUtf8UText = UTEXT_INITIALIZER;
144 ICUUText text(utext_openUTF8(&sUtf8UText, &utftext8[0], utf8Units, &status));
145
146 if (U_FAILURE(status)) {
147 SkDEBUGF("Break error: %s", u_errorName(status));
148 return false;
149 }
150 SkASSERT(text);
151 ubrk_setUText(fBreakIterator.get(), text.get(), &status);
152 if (U_FAILURE(status)) {
153 SkDEBUGF("Break error: %s", u_errorName(status));
154 return false;
155 }
156 fLastResult = 0;
157 return true;
158 }
159
160 static UBreakIteratorType convertType(SkUnicode::BreakType type) {
161 switch (type) {
162 case SkUnicode::BreakType::kLines: return UBRK_LINE;
163 case SkUnicode::BreakType::kGraphemes: return UBRK_CHARACTER;
164 case SkUnicode::BreakType::kWords: return UBRK_WORD;
165 default:
166 return UBRK_CHARACTER;
167 }
168 }
169
170 static std::unique_ptr<SkBreakIterator> makeUtf8BreakIterator
171 (const char locale[], SkUnicode::BreakType type) {
172 UErrorCode status = U_ZERO_ERROR;
173 ICUBreakIterator iterator(ubrk_open(convertType(type), locale, nullptr, 0, &status));
174 if (U_FAILURE(status)) {
175 SkDEBUGF("Break error: %s", u_errorName(status));
176 return nullptr;
177 }
178 return std::unique_ptr<SkBreakIterator>(new SkBreakIterator_icu(std::move(iterator)));
179 }
180};
181
Julia Lavrova90787fe2020-07-20 17:32:03 +0000182class SkUnicode_icu : public SkUnicode {
183
Julia Lavrova6e51d922020-08-25 11:42:51 -0400184 static UBreakIteratorType convertType(BreakType type) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000185 switch (type) {
Julia Lavrova6e51d922020-08-25 11:42:51 -0400186 case BreakType::kLines: return UBRK_LINE;
187 case BreakType::kGraphemes: return UBRK_CHARACTER;
188 case BreakType::kWords: return UBRK_WORD;
Julia Lavrova90787fe2020-07-20 17:32:03 +0000189 default:
190 SkDEBUGF("Convert error: wrong break type");
191 return UBRK_CHARACTER;
192 }
193 }
194
Julia Lavrova6e51d922020-08-25 11:42:51 -0400195 static bool extractBidi(const char utf8[],
196 int utf8Units,
197 TextDirection dir,
198 std::vector<BidiRegion>* bidiRegions) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000199
200 // Convert to UTF16 since for now bidi iterator only operates on utf16
201 std::unique_ptr<uint16_t[]> utf16;
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000202 auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000203 if (utf16Units < 0) {
204 return false;
205 }
206
207 // Create bidi iterator
208 UErrorCode status = U_ZERO_ERROR;
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000209 SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
Julia Lavrova90787fe2020-07-20 17:32:03 +0000210 if (U_FAILURE(status)) {
211 SkDEBUGF("Bidi error: %s", u_errorName(status));
212 return false;
213 }
214 SkASSERT(bidi);
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000215 uint8_t bidiLevel = (dir == TextDirection::kLTR) ? UBIDI_LTR : UBIDI_RTL;
Julia Lavrova90787fe2020-07-20 17:32:03 +0000216 // The required lifetime of utf16 isn't well documented.
217 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
218 ubidi_setPara(bidi.get(), (const UChar*)utf16.get(), utf16Units, bidiLevel, nullptr, &status);
219 if (U_FAILURE(status)) {
220 SkDEBUGF("Bidi error: %s", u_errorName(status));
221 return false;
222 }
223
224 // Iterate through bidi regions and the result positions into utf8
225 const char* start8 = utf8;
226 const char* end8 = utf8 + utf8Units;
227 BidiLevel currentLevel = 0;
228
229 Position pos8 = 0;
230 Position pos16 = 0;
231 Position end16 = ubidi_getLength(bidi.get());
232 while (pos16 < end16) {
233 auto level = ubidi_getLevelAt(bidi.get(), pos16);
234 if (pos16 == 0) {
235 currentLevel = level;
236 } else if (level != currentLevel) {
237 Position end = start8 - utf8;
238 bidiRegions->emplace_back(pos8, end, currentLevel);
239 currentLevel = level;
240 pos8 = end;
241 }
242 SkUnichar u = utf8_next(&start8, end8);
243 pos16 += SkUTF::ToUTF16(u);
244 }
245 Position end = start8 - utf8;
246 if (end != pos8) {
247 bidiRegions->emplace_back(pos8, end, currentLevel);
248 }
249 return true;
250 }
251
252 static bool extractWords(uint16_t utf16[], int utf16Units, std::vector<Position>* words) {
253
254 UErrorCode status = U_ZERO_ERROR;
255
Julia Lavrova6e51d922020-08-25 11:42:51 -0400256 UBreakIteratorType breakType = convertType(BreakType::kWords);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000257 ICUBreakIterator iterator(ubrk_open(breakType, uloc_getDefault(), nullptr, 0, &status));
258 if (U_FAILURE(status)) {
259 SkDEBUGF("Break error: %s", u_errorName(status));
260 return false;
261 }
262 SkASSERT(iterator);
263
264 UText sUtf16UText = UTEXT_INITIALIZER;
265 ICUUText utf16UText(utext_openUChars(&sUtf16UText, (UChar*)utf16, utf16Units, &status));
266 if (U_FAILURE(status)) {
267 SkDEBUGF("Break error: %s", u_errorName(status));
268 return false;
269 }
270
271 ubrk_setUText(iterator.get(), utf16UText.get(), &status);
272 if (U_FAILURE(status)) {
273 SkDEBUGF("Break error: %s", u_errorName(status));
274 return false;
275 }
276
277 // Get the words
278 int32_t pos = ubrk_first(iterator.get());
279 while (pos != UBRK_DONE) {
280 words->emplace_back(pos);
281 pos = ubrk_next(iterator.get());
282 }
283
284 return true;
285 }
286
Julia Lavrova6e51d922020-08-25 11:42:51 -0400287 static bool extractPositions
288 (const char utf8[], int utf8Units, BreakType type, std::function<void(int, int)> add) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000289
290 UErrorCode status = U_ZERO_ERROR;
291 UText sUtf8UText = UTEXT_INITIALIZER;
292 ICUUText text(utext_openUTF8(&sUtf8UText, &utf8[0], utf8Units, &status));
293
294 if (U_FAILURE(status)) {
295 SkDEBUGF("Break error: %s", u_errorName(status));
296 return false;
297 }
298 SkASSERT(text);
299
300 ICUBreakIterator iterator(ubrk_open(convertType(type), uloc_getDefault(), nullptr, 0, &status));
301 if (U_FAILURE(status)) {
302 SkDEBUGF("Break error: %s", u_errorName(status));
303 }
304
305 ubrk_setUText(iterator.get(), text.get(), &status);
306 if (U_FAILURE(status)) {
307 SkDEBUGF("Break error: %s", u_errorName(status));
308 return false;
309 }
310
311 auto iter = iterator.get();
312 int32_t pos = ubrk_first(iter);
313 while (pos != UBRK_DONE) {
314 add(pos, ubrk_getRuleStatus(iter));
315 pos = ubrk_next(iter);
316 }
317 return true;
318 }
319
Julia Lavrova6e51d922020-08-25 11:42:51 -0400320 static bool extractWhitespaces(const char utf8[],
321 int utf8Units,
322 std::vector<Position>* whitespaces) {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000323
324 const char* start = utf8;
325 const char* end = utf8 + utf8Units;
326 const char* ch = start;
327 while (ch < end) {
328 auto index = ch - start;
329 auto unichar = utf8_next(&ch, end);
330 if (u_isWhitespace(unichar)) {
331 auto ending = ch - start;
332 for (auto k = index; k < ending; ++k) {
333 whitespaces->emplace_back(k);
334 }
335 }
336 }
337 return true;
338 }
339
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000340 static int utf8ToUtf16(const char* utf8, size_t utf8Units, std::unique_ptr<uint16_t[]>* utf16) {
341 int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
342 if (utf16Units < 0) {
343 SkDEBUGF("Convert error: Invalid utf8 input");
344 return utf16Units;
345 }
346 *utf16 = std::unique_ptr<uint16_t[]>(new uint16_t[utf16Units]);
347 SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16->get(), utf16Units, utf8, utf8Units);
348 SkASSERT(dstLen == utf16Units);
349 return utf16Units;
350 }
351
352 static int utf16ToUtf8(const uint16_t* utf16, size_t utf16Units, std::unique_ptr<char[]>* utf8) {
353 int utf8Units = SkUTF::UTF16ToUTF8(nullptr, 0, utf16, utf16Units);
354 if (utf8Units < 0) {
355 SkDEBUGF("Convert error: Invalid utf16 input");
356 return utf8Units;
357 }
358 *utf8 = std::unique_ptr<char[]>(new char[utf8Units]);
359 SkDEBUGCODE(int dstLen =) SkUTF::UTF16ToUTF8(utf8->get(), utf8Units, utf16, utf16Units);
360 SkASSERT(dstLen == utf8Units);
361 return utf8Units;
362 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400363
Julia Lavrova90787fe2020-07-20 17:32:03 +0000364public:
365 ~SkUnicode_icu() override { }
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000366 std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t text[], int count,
367 SkBidiIterator::Direction dir) override {
368 return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
369 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400370 std::unique_ptr<SkBidiIterator> makeBidiIterator(const char text[],
371 int count,
Julia Lavrova1798f4f2020-08-26 14:22:48 +0000372 SkBidiIterator::Direction dir) override {
373 return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
374 }
Julia Lavrova6e51d922020-08-25 11:42:51 -0400375 std::unique_ptr<SkBreakIterator> makeBreakIterator(const char locale[],
376 BreakType breakType) override {
377 return SkBreakIterator_icu::makeUtf8BreakIterator(locale, breakType);
378 }
Julia Lavrova90787fe2020-07-20 17:32:03 +0000379
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000380 // TODO: Use ICU data file to detect controls and whitespaces
381 bool isControl(SkUnichar utf8) override {
382 return u_iscntrl(utf8);
383 }
384
385 bool isWhitespace(SkUnichar utf8) override {
386 return u_isWhitespace(utf8);
387 }
388
389 SkString convertUtf16ToUtf8(const std::u16string& utf16) override {
390 std::unique_ptr<char[]> utf8;
391 auto utf8Units = SkUnicode_icu::utf16ToUtf8((uint16_t*)utf16.data(), utf16.size(), &utf8);
392 if (utf8Units >= 0) {
393 return SkString(utf8.get(), utf8Units);
394 } else {
395 return SkString();
396 }
397 }
398
Julia Lavrova6e51d922020-08-25 11:42:51 -0400399 bool getBidiRegions(const char utf8[],
400 int utf8Units,
401 TextDirection dir,
402 std::vector<BidiRegion>* results) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000403 return extractBidi(utf8, utf8Units, dir, results);
404 }
405
Julia Lavrova6e51d922020-08-25 11:42:51 -0400406 bool getLineBreaks(const char utf8[],
407 int utf8Units,
408 std::vector<LineBreakBefore>* results) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000409
Julia Lavrova6e51d922020-08-25 11:42:51 -0400410 return extractPositions(utf8, utf8Units, BreakType::kLines,
Julia Lavrova90787fe2020-07-20 17:32:03 +0000411 [results](int pos, int status) {
412 results->emplace_back(pos,status == UBRK_LINE_HARD
413 ? LineBreakType::kHardLineBreak
414 : LineBreakType::kSoftLineBreak);
415 });
416 }
417
418 bool getWords(const char utf8[], int utf8Units, std::vector<Position>* results) override {
419
420 // Convert to UTF16 since we want the results in utf16
421 std::unique_ptr<uint16_t[]> utf16;
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000422 auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
Julia Lavrova90787fe2020-07-20 17:32:03 +0000423 if (utf16Units < 0) {
424 return false;
425 }
426
427 return extractWords(utf16.get(), utf16Units, results);
428 }
429
430 bool getGraphemes(const char utf8[], int utf8Units, std::vector<Position>* results) override {
431
Julia Lavrova6e51d922020-08-25 11:42:51 -0400432 return extractPositions(utf8, utf8Units, BreakType::kGraphemes,
Julia Lavrova90787fe2020-07-20 17:32:03 +0000433 [results](int pos, int status) { results->emplace_back(pos);
434 });
435 }
436
437 bool getWhitespaces(const char utf8[], int utf8Units, std::vector<Position>* results) override {
438
439 return extractWhitespaces(utf8, utf8Units, results);
440 }
441
Julia Lavrova6e51d922020-08-25 11:42:51 -0400442 void reorderVisual(const BidiLevel runLevels[],
443 int levelsCount,
444 int32_t logicalFromVisual[]) override {
Julia Lavrova90787fe2020-07-20 17:32:03 +0000445 ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
446 }
447};
448
Julia Lavrovab6b7fff2020-09-11 13:59:49 +0000449std::unique_ptr<SkUnicode> SkUnicode::Make() {
450 #if defined(SK_USING_THIRD_PARTY_ICU)
451 if (!SkLoadICU()) {
452 SkDEBUGF("SkLoadICU() failed!\n");
453 return nullptr;
454 }
455 #endif
456 return std::make_unique<SkUnicode_icu>();
457}