1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "Minikin"
18
19 #include "ScriptUtils.h"
20
21 #include <unicode/ubidi.h>
22 #include <unicode/uscript.h>
23 #include <unicode/utf16.h>
24 #include <unicode/utypes.h>
25
26 #include <algorithm>
27
28 #include "MinikinInternal.h"
29 #include "minikin/Emoji.h"
30
31 namespace minikin {
32
decodeUtf16(U16StringPiece text,Range range,uint32_t pos)33 static hb_codepoint_t decodeUtf16(U16StringPiece text, Range range, uint32_t pos) {
34 uint32_t result;
35 U16_NEXT(text.data(), pos, range.getEnd(), result);
36 if (U_IS_SURROGATE(result)) { // isolated surrogate
37 result = CHAR_REPLACEMENT_CHARACTER;
38 }
39 return static_cast<hb_codepoint_t>(result);
40 }
41
getICUScript(uint32_t cp)42 static UScriptCode getICUScript(uint32_t cp) {
43 UErrorCode status = U_ZERO_ERROR;
44 UScriptCode scriptCode = uscript_getScript(cp, &status);
45 if (U_FAILURE(status)) [[unlikely]] {
46 return USCRIPT_INVALID_CODE;
47 }
48 return scriptCode;
49 }
50
getHbScript(uint32_t cp)51 static hb_script_t getHbScript(uint32_t cp) {
52 hb_unicode_funcs_t* unicode_func = hb_unicode_funcs_get_default();
53 return hb_unicode_script(unicode_func, cp);
54 }
55
56 // static
getScriptRun(U16StringPiece text,Range range,uint32_t pos)57 std::pair<uint32_t, hb_script_t> ScriptText::getScriptRun(U16StringPiece text, Range range,
58 uint32_t pos) {
59 if (!range.contains(pos)) {
60 return std::make_pair(range.getEnd(), HB_SCRIPT_UNKNOWN);
61 }
62
63 uint32_t cp = decodeUtf16(text, range, pos);
64 UScriptCode current_script = getICUScript(cp);
65 hb_script_t current_hb_script = getHbScript(cp);
66 uint32_t i;
67 for (i = pos + U16_LENGTH(cp); i < range.getEnd(); i += U16_LENGTH(cp)) {
68 cp = decodeUtf16(text, range, i);
69 UScriptCode next_script = getICUScript(cp);
70 if (current_script != next_script) {
71 if (current_script == USCRIPT_INHERITED || current_script == USCRIPT_COMMON) {
72 current_script = next_script;
73 current_hb_script = getHbScript(cp);
74 } else if (next_script == USCRIPT_INHERITED || next_script == USCRIPT_COMMON) {
75 continue;
76 } else {
77 break;
78 }
79 }
80 }
81 if (current_script == USCRIPT_INHERITED) {
82 return std::make_pair(i, HB_SCRIPT_COMMON);
83 } else {
84 return std::make_pair(i, current_hb_script);
85 }
86 }
87
88 } // namespace minikin
89