• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 */
7 #include "include/core/SkString.h"
8 #include "include/private/SkMutex.h"
9 #include "include/private/SkTFitsIn.h"
10 #include "include/private/SkTHash.h"
11 #include "include/private/SkTemplates.h"
12 #include "modules/skshaper/src/SkUnicode.h"
13 #include "src/utils/SkUTF.h"
14 #include <unicode/ubidi.h>
15 #include <unicode/ubrk.h>
16 #include <unicode/uscript.h>
17 #include <unicode/ustring.h>
18 #include <unicode/utext.h>
19 #include <unicode/utypes.h>
20 #include <vector>
21 #include <functional>
22 
23 #if defined(SK_USING_THIRD_PARTY_ICU)
24 #include "SkLoadICU.h"
25 #endif
26 
27 // ubrk_clone added as draft in ICU69 and Android API 31 (first ICU NDK).
28 // ubrk_safeClone deprecated in ICU69 and not exposed by Android.
29 template<typename...> using void_t = void;
30 template<typename T, typename = void>
31 struct SkUbrkClone {
operator ()SkUbrkClone32     UBreakIterator* operator()(T bi, UErrorCode* status) {
33         return ubrk_safeClone(bi, nullptr, nullptr, status);
34     }
35 };
36 template<typename T>
37 struct SkUbrkClone<T, void_t<decltype(ubrk_clone(std::declval<T>(), nullptr))>> {
operator ()SkUbrkClone38     UBreakIterator* operator()(T bi, UErrorCode* status) {
39         return ubrk_clone(bi, status);
40     }
41 };
42 
43 using SkUnicodeBidi = std::unique_ptr<UBiDi, SkFunctionWrapper<decltype(ubidi_close), ubidi_close>>;
44 using ICUUText = std::unique_ptr<UText, SkFunctionWrapper<decltype(utext_close), utext_close>>;
45 using ICUBreakIterator = std::unique_ptr<UBreakIterator, SkFunctionWrapper<decltype(ubrk_close), ubrk_close>>;
46 
47 /** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
utf8_next(const char ** ptr,const char * end)48 static inline SkUnichar utf8_next(const char** ptr, const char* end) {
49     SkUnichar val = SkUTF::NextUTF8(ptr, end);
50     return val < 0 ? 0xFFFD : val;
51 }
52 
convertType(SkUnicode::BreakType type)53 static UBreakIteratorType convertType(SkUnicode::BreakType type) {
54     switch (type) {
55         case SkUnicode::BreakType::kLines: return UBRK_LINE;
56         case SkUnicode::BreakType::kGraphemes: return UBRK_CHARACTER;
57         case SkUnicode::BreakType::kWords: return UBRK_WORD;
58         default:
59             return UBRK_CHARACTER;
60     }
61 }
62 
63 class SkBidiIterator_icu : public SkBidiIterator {
64     SkUnicodeBidi fBidi;
65 public:
SkBidiIterator_icu(SkUnicodeBidi bidi)66     explicit SkBidiIterator_icu(SkUnicodeBidi bidi) : fBidi(std::move(bidi)) {}
getLength()67     Position getLength() override { return ubidi_getLength(fBidi.get()); }
getLevelAt(Position pos)68     Level getLevelAt(Position pos) override { return ubidi_getLevelAt(fBidi.get(), pos); }
69 
makeBidiIterator(const uint16_t utf16[],int utf16Units,Direction dir)70     static std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t utf16[], int utf16Units, Direction dir) {
71         UErrorCode status = U_ZERO_ERROR;
72         SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
73         if (U_FAILURE(status)) {
74             SkDEBUGF("Bidi error: %s", u_errorName(status));
75             return nullptr;
76         }
77         SkASSERT(bidi);
78         uint8_t bidiLevel = (dir == SkBidiIterator::kLTR) ? UBIDI_LTR : UBIDI_RTL;
79         // The required lifetime of utf16 isn't well documented.
80         // It appears it isn't used after ubidi_setPara except through ubidi_getText.
81         ubidi_setPara(bidi.get(), (const UChar*)utf16, utf16Units, bidiLevel, nullptr, &status);
82         if (U_FAILURE(status)) {
83             SkDEBUGF("Bidi error: %s", u_errorName(status));
84             return nullptr;
85         }
86         return std::unique_ptr<SkBidiIterator>(new SkBidiIterator_icu(std::move(bidi)));
87     }
88 
89     // ICU bidi iterator works with utf16 but clients (Flutter for instance) may work with utf8
90     // This method allows the clients not to think about all these details
makeBidiIterator(const char utf8[],int utf8Units,Direction dir)91     static std::unique_ptr<SkBidiIterator> makeBidiIterator(const char utf8[], int utf8Units, Direction dir) {
92         // Convert utf8 into utf16 since ubidi only accepts utf16
93         if (!SkTFitsIn<int32_t>(utf8Units)) {
94             SkDEBUGF("Bidi error: text too long");
95             return nullptr;
96         }
97 
98         // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
99         int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
100         if (utf16Units < 0) {
101             SkDEBUGF("Bidi error: Invalid utf8 input");
102             return nullptr;
103         }
104         std::unique_ptr<uint16_t[]> utf16(new uint16_t[utf16Units]);
105         SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16.get(), utf16Units, utf8, utf8Units);
106         SkASSERT(dstLen == utf16Units);
107 
108         return makeBidiIterator(utf16.get(), utf16Units, dir);
109     }
110 
111     // This method returns the final results only: a list of bidi regions
112     // (this is all SkParagraph really needs; SkShaper however uses the iterator itself)
getBidiRegions(const char utf8[],int utf8Units,Direction dir)113     static std::vector<Region> getBidiRegions(const char utf8[], int utf8Units, Direction dir) {
114 
115         auto bidiIterator = makeBidiIterator(utf8, utf8Units, dir);
116         std::vector<Region> bidiRegions;
117         const char* start8 = utf8;
118         const char* end8 = utf8 + utf8Units;
119         SkBidiIterator::Level currentLevel = 0;
120 
121         Position pos8 = 0;
122         Position pos16 = 0;
123         Position end16 = bidiIterator->getLength();
124         while (pos16 < end16) {
125             auto level = bidiIterator->getLevelAt(pos16);
126             if (pos16 == 0) {
127                 currentLevel = level;
128             } else if (level != currentLevel) {
129                 auto end = start8 - utf8;
130                 bidiRegions.emplace_back(pos8, end, currentLevel);
131                 currentLevel = level;
132                 pos8 = end;
133             }
134             SkUnichar u = utf8_next(&start8, end8);
135             pos16 += SkUTF::ToUTF16(u);
136         }
137         auto end = start8 - utf8;
138         if (end != pos8) {
139             bidiRegions.emplace_back(pos8, end, currentLevel);
140         }
141         return bidiRegions;
142     }
143 };
144 
ReorderVisual(const Level runLevels[],int levelsCount,int32_t logicalFromVisual[])145 void SkBidiIterator::ReorderVisual(const Level runLevels[], int levelsCount,
146                                    int32_t logicalFromVisual[]) {
147     ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
148 }
149 
150 class SkBreakIterator_icu : public SkBreakIterator {
151     ICUBreakIterator fBreakIterator;
152     Position fLastResult;
153  public:
SkBreakIterator_icu(ICUBreakIterator iter)154     explicit SkBreakIterator_icu(ICUBreakIterator iter)
155         : fBreakIterator(std::move(iter)), fLastResult(0) {}
first()156     Position first() override
157       { return fLastResult = ubrk_first(fBreakIterator.get()); }
current()158     Position current() override
159       { return fLastResult = ubrk_current(fBreakIterator.get()); }
next()160     Position next() override
161       { return fLastResult = ubrk_next(fBreakIterator.get()); }
preceding(Position offset)162     Position preceding(Position offset) override
163         { return fLastResult = ubrk_preceding(fBreakIterator.get(), offset); }
following(Position offset)164     Position following(Position offset) override
165         { return fLastResult = ubrk_following(fBreakIterator.get(), offset);}
status()166     Status status() override { return ubrk_getRuleStatus(fBreakIterator.get()); }
isDone()167     bool isDone() override { return fLastResult == UBRK_DONE; }
168 
setText(const char utftext8[],int utf8Units)169     bool setText(const char utftext8[], int utf8Units) override {
170         UErrorCode status = U_ZERO_ERROR;
171         ICUUText text(utext_openUTF8(nullptr, &utftext8[0], utf8Units, &status));
172 
173         if (U_FAILURE(status)) {
174             SkDEBUGF("Break error: %s", u_errorName(status));
175             return false;
176         }
177         SkASSERT(text);
178         ubrk_setUText(fBreakIterator.get(), text.get(), &status);
179         if (U_FAILURE(status)) {
180             SkDEBUGF("Break error: %s", u_errorName(status));
181             return false;
182         }
183         fLastResult = 0;
184         return true;
185     }
186 };
187 
188 class SkIcuBreakIteratorCache {
189     SkTHashMap<SkUnicode::BreakType, ICUBreakIterator> fBreakCache;
190     SkMutex fBreakCacheMutex;
191 
192  public:
get()193     static SkIcuBreakIteratorCache& get() {
194         static SkIcuBreakIteratorCache instance;
195         return instance;
196     }
197 
makeBreakIterator(SkUnicode::BreakType type)198     ICUBreakIterator makeBreakIterator(SkUnicode::BreakType type) {
199         UErrorCode status = U_ZERO_ERROR;
200         ICUBreakIterator* cachedIterator;
201         {
202             SkAutoMutexExclusive lock(fBreakCacheMutex);
203             cachedIterator = fBreakCache.find(type);
204             if (!cachedIterator) {
205                 ICUBreakIterator newIterator(ubrk_open(convertType(type), uloc_getDefault(), nullptr, 0, &status));
206                 if (U_FAILURE(status)) {
207                     SkDEBUGF("Break error: %s", u_errorName(status));
208                 } else {
209                     cachedIterator = fBreakCache.set(type, std::move(newIterator));
210                 }
211             }
212         }
213         ICUBreakIterator iterator;
214         if (cachedIterator) {
215             iterator.reset(SkUbrkClone<const UBreakIterator*>()(cachedIterator->get(), &status));
216             if (U_FAILURE(status)) {
217                 SkDEBUGF("Break error: %s", u_errorName(status));
218             }
219         }
220         return iterator;
221     }
222 };
223 
224 class SkScriptIterator_icu : public SkScriptIterator {
225  public:
getScript(SkUnichar u,ScriptID * script)226    bool getScript(SkUnichar u, ScriptID* script) override {
227         UErrorCode status = U_ZERO_ERROR;
228         UScriptCode scriptCode = uscript_getScript(u, &status);
229         if (U_FAILURE (status)) {
230             return false;
231         }
232         if (script) {
233             *script = (ScriptID)scriptCode;
234         }
235         return true;
236    }
237 
makeScriptIterator()238    static std::unique_ptr<SkScriptIterator> makeScriptIterator() {
239         return std::unique_ptr<SkScriptIterator>(new SkScriptIterator_icu());
240    }
241 };
242 
243 class SkUnicode_icu : public SkUnicode {
extractBidi(const char utf8[],int utf8Units,TextDirection dir,std::vector<BidiRegion> * bidiRegions)244     static bool extractBidi(const char utf8[],
245                             int utf8Units,
246                             TextDirection dir,
247                             std::vector<BidiRegion>* bidiRegions) {
248 
249         // Convert to UTF16 since for now bidi iterator only operates on utf16
250         std::unique_ptr<uint16_t[]> utf16;
251         auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
252         if (utf16Units < 0) {
253             return false;
254         }
255 
256         // Create bidi iterator
257         UErrorCode status = U_ZERO_ERROR;
258         SkUnicodeBidi bidi(ubidi_openSized(utf16Units, 0, &status));
259         if (U_FAILURE(status)) {
260             SkDEBUGF("Bidi error: %s", u_errorName(status));
261             return false;
262         }
263         SkASSERT(bidi);
264         uint8_t bidiLevel = (dir == TextDirection::kLTR) ? UBIDI_LTR : UBIDI_RTL;
265         // The required lifetime of utf16 isn't well documented.
266         // It appears it isn't used after ubidi_setPara except through ubidi_getText.
267         ubidi_setPara(bidi.get(), (const UChar*)utf16.get(), utf16Units, bidiLevel, nullptr, &status);
268         if (U_FAILURE(status)) {
269             SkDEBUGF("Bidi error: %s", u_errorName(status));
270             return false;
271         }
272 
273         // Iterate through bidi regions and the result positions into utf8
274         const char* start8 = utf8;
275         const char* end8 = utf8 + utf8Units;
276         BidiLevel currentLevel = 0;
277 
278         Position pos8 = 0;
279         Position pos16 = 0;
280         Position end16 = ubidi_getLength(bidi.get());
281         while (pos16 < end16) {
282             auto level = ubidi_getLevelAt(bidi.get(), pos16);
283             if (pos16 == 0) {
284                 currentLevel = level;
285             } else if (level != currentLevel) {
286                 Position end = start8 - utf8;
287                 bidiRegions->emplace_back(pos8, end, currentLevel);
288                 currentLevel = level;
289                 pos8 = end;
290             }
291             SkUnichar u = utf8_next(&start8, end8);
292             pos16 += SkUTF::ToUTF16(u);
293         }
294         Position end = start8 - utf8;
295         if (end != pos8) {
296             bidiRegions->emplace_back(pos8, end, currentLevel);
297         }
298         return true;
299     }
300 
extractWords(uint16_t utf16[],int utf16Units,std::vector<Position> * words)301     static bool extractWords(uint16_t utf16[], int utf16Units, std::vector<Position>* words) {
302 
303         UErrorCode status = U_ZERO_ERROR;
304 
305         ICUBreakIterator iterator = SkIcuBreakIteratorCache::get().makeBreakIterator(BreakType::kWords);
306         if (!iterator) {
307             SkDEBUGF("Break error: %s", u_errorName(status));
308             return false;
309         }
310         SkASSERT(iterator);
311 
312         ICUUText utf16UText(utext_openUChars(nullptr, (UChar*)utf16, utf16Units, &status));
313         if (U_FAILURE(status)) {
314             SkDEBUGF("Break error: %s", u_errorName(status));
315             return false;
316         }
317 
318         ubrk_setUText(iterator.get(), utf16UText.get(), &status);
319         if (U_FAILURE(status)) {
320             SkDEBUGF("Break error: %s", u_errorName(status));
321             return false;
322         }
323 
324         // Get the words
325         int32_t pos = ubrk_first(iterator.get());
326         while (pos != UBRK_DONE) {
327             words->emplace_back(pos);
328             pos = ubrk_next(iterator.get());
329         }
330 
331         return true;
332     }
333 
extractPositions(const char utf8[],int utf8Units,BreakType type,std::function<void (int,int)> setBreak)334     static bool extractPositions
335         (const char utf8[], int utf8Units, BreakType type, std::function<void(int, int)> setBreak) {
336 
337         UErrorCode status = U_ZERO_ERROR;
338         ICUUText text(utext_openUTF8(nullptr, &utf8[0], utf8Units, &status));
339 
340         if (U_FAILURE(status)) {
341             SkDEBUGF("Break error: %s", u_errorName(status));
342             return false;
343         }
344         SkASSERT(text);
345 
346         ICUBreakIterator iterator = SkIcuBreakIteratorCache::get().makeBreakIterator(type);
347         if (!iterator) {
348             return false;
349         }
350 
351         ubrk_setUText(iterator.get(), text.get(), &status);
352         if (U_FAILURE(status)) {
353             SkDEBUGF("Break error: %s", u_errorName(status));
354             return false;
355         }
356 
357         auto iter = iterator.get();
358         int32_t pos = ubrk_first(iter);
359         while (pos != UBRK_DONE) {
360             auto status = type == SkUnicode::BreakType::kLines
361                               ? UBRK_LINE_SOFT
362                               : ubrk_getRuleStatus(iter);
363             setBreak(pos, status);
364             pos = ubrk_next(iter);
365         }
366 
367         if (type == SkUnicode::BreakType::kLines) {
368             // This is a workaround for https://bugs.chromium.org/p/skia/issues/detail?id=10715
369             // (ICU line break iterator does not work correctly on Thai text with new lines)
370             // So, we only use the iterator to collect soft line breaks and
371             // scan the text for all hard line breaks ourselves
372             const char* end = utf8 + utf8Units;
373             const char* ch = utf8;
374             while (ch < end) {
375                 auto unichar = utf8_next(&ch, end);
376                 if (isHardLineBreak(unichar)) {
377                     setBreak(ch - utf8, UBRK_LINE_HARD);
378                 }
379             }
380         }
381         return true;
382     }
383 
utf8ToUtf16(const char * utf8,size_t utf8Units,std::unique_ptr<uint16_t[]> * utf16)384     static int utf8ToUtf16(const char* utf8, size_t utf8Units, std::unique_ptr<uint16_t[]>* utf16) {
385         int utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Units);
386         if (utf16Units < 0) {
387             SkDEBUGF("Convert error: Invalid utf8 input");
388             return utf16Units;
389         }
390         *utf16 = std::unique_ptr<uint16_t[]>(new uint16_t[utf16Units]);
391         SkDEBUGCODE(int dstLen =) SkUTF::UTF8ToUTF16(utf16->get(), utf16Units, utf8, utf8Units);
392         SkASSERT(dstLen == utf16Units);
393         return utf16Units;
394    }
395 
utf16ToUtf8(const uint16_t * utf16,size_t utf16Units,std::unique_ptr<char[]> * utf8)396     static int utf16ToUtf8(const uint16_t* utf16, size_t utf16Units, std::unique_ptr<char[]>* utf8) {
397         int utf8Units = SkUTF::UTF16ToUTF8(nullptr, 0, utf16, utf16Units);
398         if (utf8Units < 0) {
399             SkDEBUGF("Convert error: Invalid utf16 input");
400             return utf8Units;
401         }
402         *utf8 = std::unique_ptr<char[]>(new char[utf8Units]);
403         SkDEBUGCODE(int dstLen =) SkUTF::UTF16ToUTF8(utf8->get(), utf8Units, utf16, utf16Units);
404         SkASSERT(dstLen == utf8Units);
405         return utf8Units;
406    }
407 
408 public:
~SkUnicode_icu()409     ~SkUnicode_icu() override { }
makeBidiIterator(const uint16_t text[],int count,SkBidiIterator::Direction dir)410     std::unique_ptr<SkBidiIterator> makeBidiIterator(const uint16_t text[], int count,
411                                                      SkBidiIterator::Direction dir) override {
412         return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
413     }
makeBidiIterator(const char text[],int count,SkBidiIterator::Direction dir)414     std::unique_ptr<SkBidiIterator> makeBidiIterator(const char text[],
415                                                      int count,
416                                                      SkBidiIterator::Direction dir) override {
417         return SkBidiIterator_icu::makeBidiIterator(text, count, dir);
418     }
makeBreakIterator(const char locale[],BreakType breakType)419     std::unique_ptr<SkBreakIterator> makeBreakIterator(const char locale[],
420                                                        BreakType breakType) override {
421         UErrorCode status = U_ZERO_ERROR;
422         ICUBreakIterator iterator(ubrk_open(convertType(breakType), locale, nullptr, 0, &status));
423         if (U_FAILURE(status)) {
424             SkDEBUGF("Break error: %s", u_errorName(status));
425             return nullptr;
426         }
427         return std::unique_ptr<SkBreakIterator>(new SkBreakIterator_icu(std::move(iterator)));
428     }
makeScriptIterator()429     std::unique_ptr<SkScriptIterator> makeScriptIterator() override {
430         return SkScriptIterator_icu::makeScriptIterator();
431     }
432 
433     // TODO: Use ICU data file to detect controls and whitespaces
isControl(SkUnichar utf8)434     bool isControl(SkUnichar utf8) override {
435         return u_iscntrl(utf8);
436     }
437 
isWhitespace(SkUnichar utf8)438     bool isWhitespace(SkUnichar utf8) override {
439         return u_isWhitespace(utf8);
440     }
441 
isSpace(SkUnichar utf8)442     bool isSpace(SkUnichar utf8) override {
443         return u_isspace(utf8);
444     }
445 
isHardLineBreak(SkUnichar utf8)446     static bool isHardLineBreak(SkUnichar utf8) {
447         auto property = u_getIntPropertyValue(utf8, UCHAR_LINE_BREAK);
448         return property == U_LB_LINE_FEED || property == U_LB_MANDATORY_BREAK;
449     }
450 
convertUtf16ToUtf8(const std::u16string & utf16)451     SkString convertUtf16ToUtf8(const std::u16string& utf16) override {
452         std::unique_ptr<char[]> utf8;
453         auto utf8Units = SkUnicode_icu::utf16ToUtf8((uint16_t*)utf16.data(), utf16.size(), &utf8);
454         if (utf8Units >= 0) {
455             return SkString(utf8.get(), utf8Units);
456         } else {
457             return SkString();
458         }
459     }
460 
getBidiRegions(const char utf8[],int utf8Units,TextDirection dir,std::vector<BidiRegion> * results)461     bool getBidiRegions(const char utf8[],
462                         int utf8Units,
463                         TextDirection dir,
464                         std::vector<BidiRegion>* results) override {
465         return extractBidi(utf8, utf8Units, dir, results);
466     }
467 
getLineBreaks(const char utf8[],int utf8Units,std::vector<LineBreakBefore> * results)468     bool getLineBreaks(const char utf8[],
469                        int utf8Units,
470                        std::vector<LineBreakBefore>* results) override {
471 
472         return extractPositions(utf8, utf8Units, BreakType::kLines,
473             [results](int pos, int status) {
474                     results->emplace_back(pos, status == UBRK_LINE_HARD
475                                                         ? LineBreakType::kHardLineBreak
476                                                         : LineBreakType::kSoftLineBreak);
477         });
478     }
479 
getWords(const char utf8[],int utf8Units,std::vector<Position> * results)480     bool getWords(const char utf8[], int utf8Units, std::vector<Position>* results) override {
481 
482         // Convert to UTF16 since we want the results in utf16
483         std::unique_ptr<uint16_t[]> utf16;
484         auto utf16Units = utf8ToUtf16(utf8, utf8Units, &utf16);
485         if (utf16Units < 0) {
486             return false;
487         }
488 
489         return extractWords(utf16.get(), utf16Units, results);
490     }
491 
getGraphemes(const char utf8[],int utf8Units,std::vector<Position> * results)492     bool getGraphemes(const char utf8[], int utf8Units, std::vector<Position>* results) override {
493 
494         return extractPositions(utf8, utf8Units, BreakType::kGraphemes,
495             [results](int pos, int status) { results->emplace_back(pos);
496         });
497     }
498 
reorderVisual(const BidiLevel runLevels[],int levelsCount,int32_t logicalFromVisual[])499     void reorderVisual(const BidiLevel runLevels[],
500                        int levelsCount,
501                        int32_t logicalFromVisual[]) override {
502         ubidi_reorderVisual(runLevels, levelsCount, logicalFromVisual);
503     }
504 };
505 
Make()506 std::unique_ptr<SkUnicode> SkUnicode::Make() {
507     #if defined(SK_USING_THIRD_PARTY_ICU)
508     if (!SkLoadICU()) {
509         SkDEBUGF("SkLoadICU() failed!\n");
510         return nullptr;
511     }
512     #endif
513     return std::make_unique<SkUnicode_icu>();
514 }
515