1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4  ************************************************************************************
5  * Copyright (C) 2006-2016, International Business Machines Corporation
6  * and others. All Rights Reserved.
7  ************************************************************************************
8  */
9 
10 #include "unicode/utypes.h"
11 
12 #if !UCONFIG_NO_BREAK_ITERATION
13 
14 #include "unicode/uchar.h"
15 #include "unicode/uniset.h"
16 #include "unicode/chariter.h"
17 #include "unicode/ures.h"
18 #include "unicode/udata.h"
19 #include "unicode/putil.h"
20 #include "unicode/ustring.h"
21 #include "unicode/uscript.h"
22 #include "unicode/ucharstrie.h"
23 #include "unicode/bytestrie.h"
24 
25 #include "brkeng.h"
26 #include "cmemory.h"
27 #include "dictbe.h"
28 #include "lstmbe.h"
29 #include "charstr.h"
30 #include "dictionarydata.h"
31 #include "mutex.h"
32 #include "uvector.h"
33 #include "umutex.h"
34 #include "uresimp.h"
35 #include "ubrkimpl.h"
36 
37 U_NAMESPACE_BEGIN
38 
39 /*
40  ******************************************************************
41  */
42 
LanguageBreakEngine()43 LanguageBreakEngine::LanguageBreakEngine() {
44 }
45 
~LanguageBreakEngine()46 LanguageBreakEngine::~LanguageBreakEngine() {
47 }
48 
49 /*
50  ******************************************************************
51  */
52 
LanguageBreakFactory()53 LanguageBreakFactory::LanguageBreakFactory() {
54 }
55 
~LanguageBreakFactory()56 LanguageBreakFactory::~LanguageBreakFactory() {
57 }
58 
59 /*
60  ******************************************************************
61  */
62 
UnhandledEngine(UErrorCode & status)63 UnhandledEngine::UnhandledEngine(UErrorCode &status) : fHandled(nullptr) {
64     (void)status;
65 }
66 
~UnhandledEngine()67 UnhandledEngine::~UnhandledEngine() {
68     delete fHandled;
69     fHandled = nullptr;
70 }
71 
72 UBool
handles(UChar32 c) const73 UnhandledEngine::handles(UChar32 c) const {
74     return fHandled && fHandled->contains(c);
75 }
76 
77 int32_t
findBreaks(UText * text,int32_t,int32_t endPos,UVector32 &,UErrorCode & status) const78 UnhandledEngine::findBreaks( UText *text,
79                              int32_t /* startPos */,
80                              int32_t endPos,
81                              UVector32 &/*foundBreaks*/,
82                              UErrorCode &status) const {
83     if (U_FAILURE(status)) return 0;
84     UChar32 c = utext_current32(text);
85     while((int32_t)utext_getNativeIndex(text) < endPos && fHandled->contains(c)) {
86         utext_next32(text);            // TODO:  recast loop to work with post-increment operations.
87         c = utext_current32(text);
88     }
89     return 0;
90 }
91 
92 void
handleCharacter(UChar32 c)93 UnhandledEngine::handleCharacter(UChar32 c) {
94     if (fHandled == nullptr) {
95         fHandled = new UnicodeSet();
96         if (fHandled == nullptr) {
97             return;
98         }
99     }
100     if (!fHandled->contains(c)) {
101         UErrorCode status = U_ZERO_ERROR;
102         // Apply the entire script of the character.
103         int32_t script = u_getIntPropertyValue(c, UCHAR_SCRIPT);
104         fHandled->applyIntPropertyValue(UCHAR_SCRIPT, script, status);
105     }
106 }
107 
108 /*
109  ******************************************************************
110  */
111 
ICULanguageBreakFactory(UErrorCode &)112 ICULanguageBreakFactory::ICULanguageBreakFactory(UErrorCode &/*status*/) {
113     fEngines = 0;
114 }
115 
~ICULanguageBreakFactory()116 ICULanguageBreakFactory::~ICULanguageBreakFactory() {
117     if (fEngines != 0) {
118         delete fEngines;
119     }
120 }
121 
122 U_NAMESPACE_END
123 U_CDECL_BEGIN
_deleteEngine(void * obj)124 static void U_CALLCONV _deleteEngine(void *obj) {
125     delete (const icu::LanguageBreakEngine *) obj;
126 }
127 U_CDECL_END
128 U_NAMESPACE_BEGIN
129 
130 const LanguageBreakEngine *
getEngineFor(UChar32 c)131 ICULanguageBreakFactory::getEngineFor(UChar32 c) {
132     const LanguageBreakEngine *lbe = NULL;
133     UErrorCode  status = U_ZERO_ERROR;
134 
135     static UMutex gBreakEngineMutex;
136     Mutex m(&gBreakEngineMutex);
137 
138     if (fEngines == nullptr) {
139         LocalPointer<UStack>  engines(new UStack(_deleteEngine, nullptr, status), status);
140         if (U_FAILURE(status) ) {
141             // Note: no way to return error code to caller.
142             return nullptr;
143         }
144         fEngines = engines.orphan();
145     } else {
146         int32_t i = fEngines->size();
147         while (--i >= 0) {
148             lbe = (const LanguageBreakEngine *)(fEngines->elementAt(i));
149             if (lbe != NULL && lbe->handles(c)) {
150                 return lbe;
151             }
152         }
153     }
154 
155     // We didn't find an engine. Create one.
156     lbe = loadEngineFor(c);
157     if (lbe != nullptr) {
158         fEngines->push((void *)lbe, status);
159     }
160     return U_SUCCESS(status) ? lbe : nullptr;
161 }
162 
163 const LanguageBreakEngine *
loadEngineFor(UChar32 c)164 ICULanguageBreakFactory::loadEngineFor(UChar32 c) {
165     UErrorCode status = U_ZERO_ERROR;
166     UScriptCode code = uscript_getScript(c, &status);
167     if (U_SUCCESS(status)) {
168         const LanguageBreakEngine *engine = nullptr;
169         // Try to use LSTM first
170         const LSTMData *data = CreateLSTMDataForScript(code, status);
171         if (U_SUCCESS(status)) {
172             if (data != nullptr) {
173                 engine = CreateLSTMBreakEngine(code, data, status);
174                 if (U_SUCCESS(status) && engine != nullptr) {
175                     return engine;
176                 }
177                 if (engine != nullptr) {
178                     delete engine;
179                     engine = nullptr;
180                 } else {
181                     DeleteLSTMData(data);
182                 }
183             }
184         }
185         status = U_ZERO_ERROR;  // fallback to dictionary based
186         DictionaryMatcher *m = loadDictionaryMatcherFor(code);
187         if (m != NULL) {
188             switch(code) {
189             case USCRIPT_THAI:
190                 engine = new ThaiBreakEngine(m, status);
191                 break;
192             case USCRIPT_LAO:
193                 engine = new LaoBreakEngine(m, status);
194                 break;
195             case USCRIPT_MYANMAR:
196                 engine = new BurmeseBreakEngine(m, status);
197                 break;
198             case USCRIPT_KHMER:
199                 engine = new KhmerBreakEngine(m, status);
200                 break;
201 
202 #if !UCONFIG_NO_NORMALIZATION
203                 // CJK not available w/o normalization
204             case USCRIPT_HANGUL:
205                 engine = new CjkBreakEngine(m, kKorean, status);
206                 break;
207 
208             // use same BreakEngine and dictionary for both Chinese and Japanese
209             case USCRIPT_HIRAGANA:
210             case USCRIPT_KATAKANA:
211             case USCRIPT_HAN:
212                 engine = new CjkBreakEngine(m, kChineseJapanese, status);
213                 break;
214 #if 0
215             // TODO: Have to get some characters with script=common handled
216             // by CjkBreakEngine (e.g. U+309B). Simply subjecting
217             // them to CjkBreakEngine does not work. The engine has to
218             // special-case them.
219             case USCRIPT_COMMON:
220             {
221                 UBlockCode block = ublock_getCode(code);
222                 if (block == UBLOCK_HIRAGANA || block == UBLOCK_KATAKANA)
223                    engine = new CjkBreakEngine(dict, kChineseJapanese, status);
224                 break;
225             }
226 #endif
227 #endif
228 
229             default:
230                 break;
231             }
232             if (engine == NULL) {
233                 delete m;
234             }
235             else if (U_FAILURE(status)) {
236                 delete engine;
237                 engine = NULL;
238             }
239             return engine;
240         }
241     }
242     return NULL;
243 }
244 
245 DictionaryMatcher *
loadDictionaryMatcherFor(UScriptCode script)246 ICULanguageBreakFactory::loadDictionaryMatcherFor(UScriptCode script) {
247     UErrorCode status = U_ZERO_ERROR;
248     // open root from brkitr tree.
249     UResourceBundle *b = ures_open(U_ICUDATA_BRKITR, "", &status);
250     b = ures_getByKeyWithFallback(b, "dictionaries", b, &status);
251     int32_t dictnlength = 0;
252     const UChar *dictfname =
253         ures_getStringByKeyWithFallback(b, uscript_getShortName(script), &dictnlength, &status);
254     if (U_FAILURE(status)) {
255         ures_close(b);
256         return NULL;
257     }
258     CharString dictnbuf;
259     CharString ext;
260     const UChar *extStart = u_memrchr(dictfname, 0x002e, dictnlength);  // last dot
261     if (extStart != NULL) {
262         int32_t len = (int32_t)(extStart - dictfname);
263         ext.appendInvariantChars(UnicodeString(FALSE, extStart + 1, dictnlength - len - 1), status);
264         dictnlength = len;
265     }
266     dictnbuf.appendInvariantChars(UnicodeString(FALSE, dictfname, dictnlength), status);
267     ures_close(b);
268 
269     UDataMemory *file = udata_open(U_ICUDATA_BRKITR, ext.data(), dictnbuf.data(), &status);
270     if (U_SUCCESS(status)) {
271         // build trie
272         const uint8_t *data = (const uint8_t *)udata_getMemory(file);
273         const int32_t *indexes = (const int32_t *)data;
274         const int32_t offset = indexes[DictionaryData::IX_STRING_TRIE_OFFSET];
275         const int32_t trieType = indexes[DictionaryData::IX_TRIE_TYPE] & DictionaryData::TRIE_TYPE_MASK;
276         DictionaryMatcher *m = NULL;
277         if (trieType == DictionaryData::TRIE_TYPE_BYTES) {
278             const int32_t transform = indexes[DictionaryData::IX_TRANSFORM];
279             const char *characters = (const char *)(data + offset);
280             m = new BytesDictionaryMatcher(characters, transform, file);
281         }
282         else if (trieType == DictionaryData::TRIE_TYPE_UCHARS) {
283             const UChar *characters = (const UChar *)(data + offset);
284             m = new UCharsDictionaryMatcher(characters, file);
285         }
286         if (m == NULL) {
287             // no matcher exists to take ownership - either we are an invalid
288             // type or memory allocation failed
289             udata_close(file);
290         }
291         return m;
292     } else if (dictfname != NULL) {
293         // we don't have a dictionary matcher.
294         // returning NULL here will cause us to fail to find a dictionary break engine, as expected
295         status = U_ZERO_ERROR;
296         return NULL;
297     }
298     return NULL;
299 }
300 
301 U_NAMESPACE_END
302 
303 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */
304