• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_UTILS_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_UTILS_H
18 
19 #include <algorithm>
20 #include <cctype>
21 #include <climits>
22 #include <cmath>
23 #include <cstring>
24 #include <iomanip>
25 #include <map>
26 #include <optional>
27 #include <sstream>
28 #include <string>
29 #include <unordered_map>
30 #include <unordered_set>
31 
32 #include "base/geometry/axis.h"
33 #include "base/json/json_util.h"
34 #include "base/log/log.h"
35 #include "base/resource/asset_manager.h"
36 #include "base/utils/linear_map.h"
37 #include "base/utils/string_utils.h"
38 #include "base/utils/utils.h"
39 #include "core/animation/animation_pub.h"
40 #include "core/animation/curve.h"
41 #include "core/animation/curves.h"
42 #include "core/animation/spring_curve.h"
43 #include "core/common/ime/text_input_action.h"
44 #include "core/common/ime/text_input_type.h"
45 #include "core/components/common/layout/constants.h"
46 #include "core/components/common/properties/clip_path.h"
47 #include "core/components/common/properties/decoration.h"
48 #include "core/components/common/properties/text_style.h"
49 #include "frameworks/bridge/common/dom/dom_type.h"
50 
51 namespace OHOS::Ace::Framework {
52 
53 constexpr int32_t OFFSET_VALUE_NUMBER = 2;
54 constexpr uint8_t UTF8_CHARATER_HEAD = 0xc0;
55 constexpr uint8_t UTF8_CHARATER_BODY = 0x80;
56 constexpr int32_t UNICODE_LENGTH = 4;
57 constexpr int32_t STRTOL_BASE = 10;
58 constexpr int32_t INVALID_PARAM = -1;
59 constexpr int32_t PLACE_HOLDER_LENGTH = 3;
60 
61 constexpr char INPUT_ACTION_NEXT[] = "next";
62 constexpr char INPUT_ACTION_GO[] = "go";
63 constexpr char INPUT_ACTION_DONE[] = "done";
64 constexpr char INPUT_ACTION_SEND[] = "send";
65 constexpr char INPUT_ACTION_SEARCH[] = "search";
66 constexpr char PLURAL_COUNT_POS[] = "{count}";
67 constexpr char DEFAULT_PLURAL_CHOICE[] = "other";
68 
69 const char DOUBLE_QUOTATION = '"';
70 const char BACKSLASH = '\\';
71 const char ESCAPE_CHARATER_START = '\x00';
72 const char ESCAPE_CHARATER_END = '\x1f';
73 const char UNICODE_BODY = '0';
74 const char UNICODE_HEAD[] = "\\u";
75 const char LEFT_CURLY_BRACES = '{';
76 const char RIGHT_CURLY_BRACES = '}';
77 
78 // Common error code
79 constexpr int32_t ERROR_CODE_NO_ERROR = 0;
80 constexpr int32_t ERROR_CODE_PERMISSION_DENIED = 201; // The application does not have permission to call the interface.
81 constexpr int32_t ERROR_CODE_PARAM_INVALID = 401;     // Invalid input parameter.
82 constexpr int32_t ERROR_CODE_SYSTEMCAP_ERROR = 801;   // The specified SystemCapability names was not found.
83 
84 // Notification error code
85 constexpr int32_t ERROR_CODE_INTERNAL_ERROR = 100001;      // Internal error.
86 constexpr int32_t ERROR_CODE_URI_ERROR = 100002;           // Uri error.
87 constexpr int32_t ERROR_CODE_PAGE_STACK_FULL = 100003;     // The pages are pushed too much.
88 constexpr int32_t ERROR_CODE_NAMED_ROUTE_ERROR = 100004;           // Named route error.
89 constexpr int32_t ERROR_CODE_URI_ERROR_LITE = 200002;      // Uri error for lite.
90 
91 // Drag event error code
92 constexpr int32_t ERROR_CODE_DRAG_DATA_NOT_FOUND = 190001;      // GetData failed, data not found.
93 constexpr int32_t ERROR_CODE_DRAG_DATA_ERROR = 190002;      // GetData failed, data error.
94 
95 template<class T>
GetAssetContentImpl(const RefPtr<AssetManager> & assetManager,const std::string & url,T & content)96 bool GetAssetContentImpl(const RefPtr<AssetManager>& assetManager, const std::string& url, T& content)
97 {
98     if (!assetManager) {
99         LOGE("AssetManager is null");
100         return false;
101     }
102     auto jsAsset = assetManager->GetAsset(url);
103     if (jsAsset == nullptr) {
104         LOGW("uri:%{public}s Asset is null", url.c_str());
105         return false;
106     }
107     auto bufLen = jsAsset->GetSize();
108     auto buffer = jsAsset->GetData();
109     if ((buffer == nullptr) || (bufLen <= 0)) {
110         LOGE("uri:%{private}s buffer is null", url.c_str());
111         return false;
112     }
113     content.assign(buffer, buffer + bufLen);
114     return true;
115 }
116 
117 template<class T>
GetAssetContentAllowEmpty(const RefPtr<AssetManager> & assetManager,const std::string & url,T & content)118 bool GetAssetContentAllowEmpty(const RefPtr<AssetManager>& assetManager, const std::string& url, T& content)
119 {
120     if (!assetManager) {
121         LOGE("AssetManager is null");
122         return false;
123     }
124     auto jsAsset = assetManager->GetAsset(url);
125     if (jsAsset == nullptr) {
126         LOGW("uri:%{public}s Asset is null", url.c_str());
127         return false;
128     }
129     auto bufLen = jsAsset->GetSize();
130     auto buffer = jsAsset->GetData();
131     content.assign(buffer, buffer + bufLen);
132     return true;
133 }
134 
GetAssetPathImpl(const RefPtr<AssetManager> & assetManager,const std::string & url)135 inline std::string GetAssetPathImpl(const RefPtr<AssetManager>& assetManager, const std::string& url)
136 {
137     if (!assetManager) {
138         LOGE("AssetManager is null");
139         return {};
140     }
141     return assetManager->GetAssetPath(url, true);
142 }
143 
ParseFileData(const std::string & data)144 inline std::unique_ptr<JsonValue> ParseFileData(const std::string& data)
145 {
146     const char* endMsg = nullptr;
147     auto fileData = JsonUtil::ParseJsonString(data, &endMsg);
148     if (!fileData) {
149         LOGE("parse i18n data failed, error: %{private}s", endMsg);
150         return nullptr;
151     }
152     return fileData;
153 }
154 
StringToDouble(const std::string & value)155 inline double StringToDouble(const std::string& value)
156 {
157     return StringUtils::StringToDouble(value);
158 }
159 
StringToDimension(const std::string & value)160 inline Dimension StringToDimension(const std::string& value)
161 {
162     return StringUtils::StringToDimension(value);
163 }
164 
165 inline Dimension StringToDimensionWithUnit(const std::string& value, DimensionUnit defaultUnit = DimensionUnit::PX)
166 {
167     return StringUtils::StringToDimensionWithUnit(value, defaultUnit);
168 }
169 
StringToInt(const std::string & value)170 inline int32_t StringToInt(const std::string& value)
171 {
172     return StringUtils::StringToInt(value);
173 }
174 
StringToBool(const std::string & value)175 inline bool StringToBool(const std::string& value)
176 {
177     return value == "true";
178 }
179 
ConvertStrToBorderStyle(const std::string & style)180 inline BorderStyle ConvertStrToBorderStyle(const std::string& style)
181 {
182     static const LinearMapNode<BorderStyle> borderStyleTable[] = {
183         { "dashed", BorderStyle::DASHED },
184         { "dotted", BorderStyle::DOTTED },
185         { "solid", BorderStyle::SOLID },
186     };
187 
188     auto index = BinarySearchFindIndex(borderStyleTable, ArraySize(borderStyleTable), style.c_str());
189     return index < 0 ? BorderStyle::NONE : borderStyleTable[index].value;
190 }
191 
ConvertStrToBorderImageRepeat(const std::string & repeat)192 inline BorderImageRepeat ConvertStrToBorderImageRepeat(const std::string& repeat)
193 {
194     static const LinearMapNode<BorderImageRepeat> borderImageRepeatTable[] = {
195         { "repeat", BorderImageRepeat::REPEAT },
196         { "round", BorderImageRepeat::ROUND },
197         { "space", BorderImageRepeat::SPACE },
198         { "stretch", BorderImageRepeat::STRETCH },
199     };
200 
201     auto index = BinarySearchFindIndex(borderImageRepeatTable, ArraySize(borderImageRepeatTable), repeat.c_str());
202     return index < 0 ? BorderImageRepeat::STRETCH : borderImageRepeatTable[index].value;
203 }
204 
ConvertStrToBadgePosition(const std::string & badgePosition)205 inline BadgePosition ConvertStrToBadgePosition(const std::string& badgePosition)
206 {
207     static const LinearMapNode<BadgePosition> badgePositionTable[] = {
208         { "left", BadgePosition::LEFT },
209         { "right", BadgePosition::RIGHT },
210         { "rightTop", BadgePosition::RIGHT_TOP },
211     };
212     auto index = BinarySearchFindIndex(badgePositionTable, ArraySize(badgePositionTable), badgePosition.c_str());
213     return index < 0 ? BadgePosition::RIGHT_TOP : badgePositionTable[index].value;
214 }
215 
ConvertStrToBoxSizing(const std::string & value)216 inline BoxSizing ConvertStrToBoxSizing(const std::string& value)
217 {
218     static const LinearMapNode<BoxSizing> boxSizingTable[] = {
219         { "border-box", BoxSizing::BORDER_BOX },
220         { "content-box", BoxSizing::CONTENT_BOX },
221     };
222     auto index = BinarySearchFindIndex(boxSizingTable, ArraySize(boxSizingTable), value.c_str());
223     return index < 0 ? BoxSizing::BORDER_BOX : boxSizingTable[index].value;
224 }
225 
ConvertStrToImageRepeat(const std::string & repeat)226 inline ImageRepeat ConvertStrToImageRepeat(const std::string& repeat)
227 {
228     static const LinearMapNode<ImageRepeat> imageRepeatTable[] = {
229         { "no-repeat", ImageRepeat::NO_REPEAT },
230         { "repeat", ImageRepeat::REPEAT },
231         { "repeat-x", ImageRepeat::REPEAT_X },
232         { "repeat-y", ImageRepeat::REPEAT_Y },
233     };
234 
235     auto index = BinarySearchFindIndex(imageRepeatTable, ArraySize(imageRepeatTable), repeat.c_str());
236     return index < 0 ? ImageRepeat::NO_REPEAT : imageRepeatTable[index].value;
237 }
238 
239 inline FontWeight ConvertStrToFontWeight(const std::string& weight, FontWeight defaultFontWeight = FontWeight::NORMAL)
240 {
241     return StringUtils::StringToFontWeight(weight, defaultFontWeight);
242 }
243 
ConvertStrToTextDecoration(const std::string & textDecoration)244 inline TextDecoration ConvertStrToTextDecoration(const std::string& textDecoration)
245 {
246     // this map should be sorted bu key.
247     static const LinearMapNode<TextDecoration> textDecorationTable[] = {
248         { DOM_TEXT_DECORATION_INHERIT, TextDecoration::INHERIT },
249         { DOM_TEXT_DECORATION_LINETHROUGH, TextDecoration::LINE_THROUGH },
250         { DOM_TEXT_DECORATION_NONE, TextDecoration::NONE },
251         { DOM_TEXT_DECORATION_OVERLINE, TextDecoration::OVERLINE },
252         { DOM_TEXT_DECORATION_UNDERLINE, TextDecoration::UNDERLINE },
253     };
254 
255     auto index = BinarySearchFindIndex(textDecorationTable, ArraySize(textDecorationTable), textDecoration.c_str());
256     return index < 0 ? TextDecoration::NONE : textDecorationTable[index].value;
257 }
258 
ConvertStrToWhiteSpace(const std::string & whiteSpace)259 inline WhiteSpace ConvertStrToWhiteSpace(const std::string& whiteSpace)
260 {
261     // this map should be sorted bu key.
262     static const LinearMapNode<WhiteSpace> whiteSpaceTable[] = {
263         { DOM_WHITE_SPACE_INHERIT, WhiteSpace::INHERIT },
264         { DOM_WHITE_SPACE_NORMAL, WhiteSpace::NORMAL },
265         { DOM_WHITE_SPACE_NOWRAP, WhiteSpace::NOWRAP },
266         { DOM_WHITE_SPACE_PRE, WhiteSpace::PRE },
267         { DOM_WHITE_SPACE_PRELINE, WhiteSpace::PRE_LINE },
268         { DOM_WHITE_SPACE_PREWRAP, WhiteSpace::PRE_WRAP },
269     };
270 
271     auto index = BinarySearchFindIndex(whiteSpaceTable, ArraySize(whiteSpaceTable), whiteSpace.c_str());
272     return index < 0 ? WhiteSpace::NORMAL : whiteSpaceTable[index].value;
273 }
274 
ConvertStrToTextVerticalAlign(const std::string & align)275 inline VerticalAlign ConvertStrToTextVerticalAlign(const std::string& align)
276 {
277     static const LinearMapNode<VerticalAlign> textVerticalAlignTable[] = {
278         {DOM_BOTTOM, VerticalAlign::BOTTOM},
279         {DOM_MIDDLE, VerticalAlign::CENTER},
280         {DOM_TOP, VerticalAlign::TOP},
281     };
282     auto index = BinarySearchFindIndex(textVerticalAlignTable, ArraySize(textVerticalAlignTable), align.c_str());
283     return index < 0 ? VerticalAlign::NONE : textVerticalAlignTable[index].value;
284 }
285 
ConvertStrToFontStyle(const std::string & fontStyle)286 inline FontStyle ConvertStrToFontStyle(const std::string& fontStyle)
287 {
288     return fontStyle == DOM_TEXT_FONT_STYLE_ITALIC ? FontStyle::ITALIC : FontStyle::NORMAL;
289 }
290 
ConvertStrToTextAlign(const std::string & align)291 inline TextAlign ConvertStrToTextAlign(const std::string& align)
292 {
293     static const LinearMapNode<TextAlign> textAlignTable[] = {
294         { DOM_CENTER, TextAlign::CENTER },
295         { DOM_END, TextAlign::END },
296         { DOM_LEFT, TextAlign::LEFT },
297         { DOM_RIGHT, TextAlign::RIGHT },
298         { DOM_START, TextAlign::START },
299     };
300 
301     auto index = BinarySearchFindIndex(textAlignTable, ArraySize(textAlignTable), align.c_str());
302     return index < 0 ? TextAlign::CENTER : textAlignTable[index].value;
303 }
304 
ConvertStrToTextOverflow(const std::string & overflow)305 inline TextOverflow ConvertStrToTextOverflow(const std::string& overflow)
306 {
307     return overflow == DOM_ELLIPSIS ? TextOverflow::ELLIPSIS : TextOverflow::CLIP;
308 }
309 
ConvertStrToOverflow(const std::string & val)310 inline Overflow ConvertStrToOverflow(const std::string& val)
311 {
312     const LinearMapNode<Overflow> overflowTable[] = {
313         { "auto", Overflow::SCROLL },
314         { "hidden", Overflow::FORCE_CLIP },
315         { "scroll", Overflow::SCROLL },
316         { "visible", Overflow::OBSERVABLE },
317     };
318     auto index = BinarySearchFindIndex(overflowTable, ArraySize(overflowTable), val.c_str());
319     return index < 0 ? Overflow::CLIP : overflowTable[index].value;
320 }
321 
ConvertStrToTextDirection(const std::string & val)322 inline TextDirection ConvertStrToTextDirection(const std::string& val)
323 {
324     const LinearMapNode<TextDirection> textDirectionTable[] = {
325         { "inherit", TextDirection::INHERIT },
326         { "ltr", TextDirection::LTR },
327         { "rtl", TextDirection::RTL },
328     };
329     auto index = BinarySearchFindIndex(textDirectionTable, ArraySize(textDirectionTable), val.c_str());
330     return index < 0 ? TextDirection::LTR : textDirectionTable[index].value;
331 }
ConvertStrToFontFamilies(const std::string & family)332 inline std::vector<std::string> ConvertStrToFontFamilies(const std::string& family)
333 {
334     std::vector<std::string> fontFamilies;
335     std::stringstream stream(family);
336     std::string fontFamily;
337     while (getline(stream, fontFamily, ',')) {
338         fontFamilies.emplace_back(fontFamily);
339     }
340     return fontFamilies;
341 }
342 
ConvertStrToFlexDirection(const std::string & flexKey)343 inline FlexDirection ConvertStrToFlexDirection(const std::string& flexKey)
344 {
345     return flexKey == DOM_FLEX_COLUMN ? FlexDirection::COLUMN : FlexDirection::ROW;
346 }
347 
ConvertStrToFlexAlign(const std::string & flexKey)348 inline FlexAlign ConvertStrToFlexAlign(const std::string& flexKey)
349 {
350     static const LinearMapNode<FlexAlign> flexMap[] = {
351         { DOM_ALIGN_ITEMS_BASELINE, FlexAlign::BASELINE },
352         { DOM_JUSTIFY_CONTENT_CENTER, FlexAlign::CENTER },
353         { DOM_JUSTIFY_CONTENT_END, FlexAlign::FLEX_END },
354         { DOM_JUSTIFY_CONTENT_START, FlexAlign::FLEX_START },
355         { DOM_JUSTIFY_CONTENT_AROUND, FlexAlign::SPACE_AROUND },
356         { DOM_JUSTIFY_CONTENT_BETWEEN, FlexAlign::SPACE_BETWEEN },
357         { DOM_JUSTIFY_CONTENT_EVENLY, FlexAlign::SPACE_EVENLY },
358         { DOM_ALIGN_ITEMS_STRETCH, FlexAlign::STRETCH },
359     };
360     auto index = BinarySearchFindIndex(flexMap, ArraySize(flexMap), flexKey.c_str());
361     return index < 0 ? FlexAlign::FLEX_START : flexMap[index].value;
362 }
363 
ConvertStrToOffset(const std::string & value)364 inline Offset ConvertStrToOffset(const std::string& value)
365 {
366     Offset offset;
367     std::vector<std::string> offsetValues;
368     std::stringstream stream(value);
369     std::string offsetValue;
370     while (getline(stream, offsetValue, ' ')) {
371         offsetValues.emplace_back(offsetValue);
372     }
373     // To avoid illegal input, such as "100px ".
374     offsetValues.resize(OFFSET_VALUE_NUMBER);
375     offset.SetX(StringToDouble(offsetValues[0]));
376     offset.SetY(StringToDouble(offsetValues[1]));
377     return offset;
378 }
379 
ConvertStrToQrcodeType(const std::string & value)380 inline QrcodeType ConvertStrToQrcodeType(const std::string& value)
381 {
382     return value == "circle" ? QrcodeType::CIRCLE : QrcodeType::RECT;
383 }
384 
ConvertStrToAnimationCurve(const std::string & value)385 inline AnimationCurve ConvertStrToAnimationCurve(const std::string& value)
386 {
387     return value == "standard" ? AnimationCurve::STANDARD : AnimationCurve::FRICTION;
388 }
389 
ConvertStrToTextInputAction(const std::string & action)390 inline TextInputAction ConvertStrToTextInputAction(const std::string& action)
391 {
392     TextInputAction inputAction;
393     if (action == INPUT_ACTION_NEXT) {
394         inputAction = TextInputAction::NEXT;
395     } else if (action == INPUT_ACTION_GO) {
396         inputAction = TextInputAction::GO;
397     } else if (action == INPUT_ACTION_DONE) {
398         inputAction = TextInputAction::DONE;
399     } else if (action == INPUT_ACTION_SEND) {
400         inputAction = TextInputAction::SEND;
401     } else if (action == INPUT_ACTION_SEARCH) {
402         inputAction = TextInputAction::SEARCH;
403     } else {
404         inputAction = TextInputAction::UNSPECIFIED;
405     }
406     return inputAction;
407 }
408 
ConvertStrToTextInputType(const std::string & type)409 inline TextInputType ConvertStrToTextInputType(const std::string& type)
410 {
411     TextInputType inputType;
412     if (type == DOM_INPUT_TYPE_NUMBER) {
413         inputType = TextInputType::NUMBER;
414     } else if (type == DOM_INPUT_TYPE_DATE || type == DOM_INPUT_TYPE_TIME) {
415         inputType = TextInputType::DATETIME;
416     } else if (type == DOM_INPUT_TYPE_EMAIL) {
417         inputType = TextInputType::EMAIL_ADDRESS;
418     } else if (type == DOM_INPUT_TYPE_PASSWORD) {
419         inputType = TextInputType::VISIBLE_PASSWORD;
420     } else {
421         inputType = TextInputType::TEXT;
422     }
423     return inputType;
424 }
425 
ConvertStrToTabBarMode(const std::string & value)426 inline TabBarMode ConvertStrToTabBarMode(const std::string& value)
427 {
428     std::string temp = value;
429     transform(temp.begin(), temp.end(), temp.begin(), tolower);
430     return temp == "fixed" ? TabBarMode::FIXED : TabBarMode::SCROLLABLE;
431 }
432 
433 ACE_FORCE_EXPORT RefPtr<Curve> CreateBuiltinCurve(const std::string& aniTimFunc);
434 
435 ACE_FORCE_EXPORT RefPtr<Curve> CreateCustomCurve(const std::string& aniTimFunc);
436 
437 ACE_FORCE_EXPORT RefPtr<Curve> CreateCurve(const std::function<float(float)>& jsFunc);
438 
439 ACE_FORCE_EXPORT RefPtr<Curve> CreateCurve(const std::string& aniTimFunc, bool useDefault = true);
440 
441 ACE_EXPORT TransitionType ParseTransitionType(const std::string& transitionType);
442 
443 ACE_EXPORT RefPtr<ClipPath> CreateClipPath(const std::string& value);
444 
StringToFillMode(const std::string & fillMode)445 inline FillMode StringToFillMode(const std::string& fillMode)
446 {
447     if (fillMode == DOM_ANIMATION_FILL_MODE_FORWARDS) {
448         return FillMode::FORWARDS;
449     } else if (fillMode == DOM_ANIMATION_FILL_MODE_BACKWARDS) {
450         return FillMode::BACKWARDS;
451     } else if (fillMode == DOM_ANIMATION_FILL_MODE_BOTH) {
452         return FillMode::BOTH;
453     } else {
454         return FillMode::NONE;
455     }
456 }
457 
StringToAnimationDirection(const std::string & direction)458 inline AnimationDirection StringToAnimationDirection(const std::string& direction)
459 {
460     if (direction == DOM_ANIMATION_DIRECTION_ALTERNATE) {
461         return AnimationDirection::ALTERNATE;
462     } else if (direction == DOM_ANIMATION_DIRECTION_REVERSE) {
463         return AnimationDirection::REVERSE;
464     } else if (direction == DOM_ANIMATION_DIRECTION_ALTERNATE_REVERSE) {
465         return AnimationDirection::ALTERNATE_REVERSE;
466     } else {
467         return AnimationDirection::NORMAL;
468     }
469 }
470 
StringToAnimationOperation(const std::string & direction)471 inline AnimationOperation StringToAnimationOperation(const std::string& direction)
472 {
473     if (direction == DOM_ANIMATION_PLAY_STATE_IDLE) {
474         return AnimationOperation::CANCEL;
475     } else if (direction == DOM_ANIMATION_PLAY_STATE_RUNNING) {
476         return AnimationOperation::RUNNING;
477     } else if (direction == DOM_ANIMATION_PLAY_STATE_PAUSED) {
478         return AnimationOperation::PAUSE;
479     } else if (direction == DOM_ANIMATION_PLAY_STATE_FINISHED) {
480         return AnimationOperation::FINISH;
481     } else {
482         return AnimationOperation::NONE;
483     }
484 }
485 
RemoveHeadTailSpace(std::string & value)486 inline void RemoveHeadTailSpace(std::string& value)
487 {
488     if (!value.empty()) {
489         auto start = value.find_first_not_of(' ');
490         if (start == std::string::npos) {
491             value.clear();
492         } else {
493             value = value.substr(start, value.find_last_not_of(' ') - start + 1);
494         }
495     }
496 }
497 
StrToGradientDirection(const std::string & direction)498 inline GradientDirection StrToGradientDirection(const std::string& direction)
499 {
500     static const LinearMapNode<GradientDirection> gradientDirectionTable[] = {
501         { DOM_GRADIENT_DIRECTION_LEFT, GradientDirection::LEFT },
502         { DOM_GRADIENT_DIRECTION_RIGHT, GradientDirection::RIGHT },
503         { DOM_GRADIENT_DIRECTION_TOP, GradientDirection::TOP },
504         { DOM_GRADIENT_DIRECTION_BOTTOM, GradientDirection::BOTTOM },
505     };
506 
507     auto index = BinarySearchFindIndex(gradientDirectionTable, ArraySize(gradientDirectionTable), direction.c_str());
508     return index < 0 ? GradientDirection::BOTTOM : gradientDirectionTable[index].value;
509 }
510 
511 bool ParseBackgroundImagePosition(const std::string& value, BackgroundImagePosition& backgroundImagePosition);
512 
513 bool ParseBackgroundImageSize(const std::string& value, BackgroundImageSize& backgroundImageSize);
514 
515 ImageObjectPosition ParseImageObjectPosition(const std::string& value);
516 
517 std::optional<RadialSizeType> ParseRadialGradientSize(const std::string& value);
518 
StartWith(const std::string & dst,const std::string & prefix)519 inline bool StartWith(const std::string& dst, const std::string& prefix)
520 {
521     return dst.compare(0, prefix.size(), prefix) == 0;
522 }
523 
EndWith(const std::string & dst,const std::string & suffix)524 inline bool EndWith(const std::string& dst, const std::string& suffix)
525 {
526     return dst.size() >= suffix.size() && dst.compare(dst.size() - suffix.size(), suffix.size(), suffix) == 0;
527 }
528 
ConvertTimeStr(const std::string & str)529 inline double ConvertTimeStr(const std::string& str)
530 {
531     std::string time(str);
532     StringUtils::TrimStr(time);
533     double result = 0.0;
534     if (EndWith(time, "ms")) {
535         result = StringToDouble(std::string(time.begin(), time.end() - 2.0));
536     } else if (EndWith(time, "s")) {
537         result = StringToDouble(std::string(time.begin(), time.end() - 1.0)) * 1000.0;
538     } else if (EndWith(time, "m")) {
539         result = StringToDouble(std::string(time.begin(), time.end() - 1.0)) * 60.0 * 1000.0;
540     } else {
541         result = StringToDouble(str);
542     }
543     return result;
544 }
545 
ConvertStrToWordBreak(const std::string & wordBreak)546 inline WordBreak ConvertStrToWordBreak(const std::string& wordBreak)
547 {
548     return StringUtils::StringToWordBreak(wordBreak);
549 }
550 
CheckTransformEnum(const std::string & str)551 inline bool CheckTransformEnum(const std::string& str)
552 {
553     const static std::unordered_set<std::string> offsetKeywords = { "left", "right", "center", "top", "bottom" };
554 
555     return offsetKeywords.find(str) != offsetKeywords.end();
556 }
557 
ConvertStrToTransformOrigin(const std::string & str,Axis axis)558 inline std::pair<bool, Dimension> ConvertStrToTransformOrigin(const std::string& str, Axis axis)
559 {
560     const static std::unordered_map<std::string, Dimension> xOffsetKeywords = {
561         { "left", 0.0_pct },
562         { "right", 1.0_pct },
563         { "center", 0.5_pct },
564     };
565     const static std::unordered_map<std::string, Dimension> yOffsetKeywords = {
566         { "top", 0.0_pct },
567         { "bottom", 1.0_pct },
568         { "center", 0.5_pct },
569     };
570 
571     if (axis == Axis::HORIZONTAL) {
572         auto pos = xOffsetKeywords.find(str);
573         if (pos != xOffsetKeywords.end()) {
574             return std::make_pair(true, pos->second);
575         }
576     } else if (axis == Axis::VERTICAL) {
577         auto pos = yOffsetKeywords.find(str);
578         if (pos != yOffsetKeywords.end()) {
579             return std::make_pair(true, pos->second);
580         }
581     }
582 
583     return std::make_pair(false, Dimension {});
584 }
585 
ParseUtf8TextLength(std::string & text)586 inline int32_t ParseUtf8TextLength(std::string& text)
587 {
588     int32_t trueLength = 0;
589     int32_t stringLength = 0;
590     while (stringLength < static_cast<int32_t>(text.length())) {
591         uint8_t stringChar = static_cast<uint8_t>(text[stringLength++]);
592         if ((stringChar & UTF8_CHARATER_HEAD) != UTF8_CHARATER_BODY) {
593             trueLength++;
594         }
595     }
596     return trueLength;
597 }
598 
ParseUtf8TextSubstrStartPos(std::string & text,int32_t targetPos)599 inline int32_t ParseUtf8TextSubstrStartPos(std::string& text, int32_t targetPos)
600 {
601     int32_t truePos = 0;
602     int32_t stringPos = 0;
603     while ((stringPos < static_cast<int32_t>(text.length())) && (truePos < targetPos)) {
604         uint8_t stringChar = static_cast<uint8_t>(text[stringPos++]);
605         if ((stringChar & UTF8_CHARATER_HEAD) != UTF8_CHARATER_BODY) {
606             truePos++;
607         }
608     }
609 
610     return stringPos;
611 }
612 
ParseUtf8TextSubstrEndPos(std::string & text,int32_t targetPos)613 inline int32_t ParseUtf8TextSubstrEndPos(std::string& text, int32_t targetPos)
614 {
615     auto stringPos = ParseUtf8TextSubstrStartPos(text, targetPos);
616     while (stringPos < static_cast<int32_t>(text.length())) {
617         uint8_t stringChar = static_cast<uint8_t>(text[stringPos]);
618         if ((stringChar & UTF8_CHARATER_HEAD) != UTF8_CHARATER_BODY) {
619             break;
620         }
621         stringPos++;
622     }
623 
624     return stringPos;
625 }
626 
HandleEscapeCharaterInUtf8TextForJson(std::string & text)627 inline void HandleEscapeCharaterInUtf8TextForJson(std::string& text)
628 {
629     for (size_t pos = 0; pos < text.size(); pos++) {
630         if ((text.at(pos) == DOUBLE_QUOTATION) || (text.at(pos) == BACKSLASH) ||
631             ((text.at(pos) >= ESCAPE_CHARATER_START) && (text.at(pos) <= ESCAPE_CHARATER_END))) {
632             std::ostringstream is;
633             is << UNICODE_HEAD << std::hex << std::setw(UNICODE_LENGTH) << std::setfill(UNICODE_BODY)
634                 << int(text.at(pos));
635             text.replace(pos, 1, is.str());
636         }
637     }
638 }
639 
ParseResourceInputNumberParam(const std::string & param)640 inline int32_t ParseResourceInputNumberParam(const std::string& param)
641 {
642     if (!StringUtils::IsNumber(param) || param.empty()) {
643         return INVALID_PARAM;
644     } else {
645         errno = 0;
646         char* pEnd = nullptr;
647         int64_t result = std::strtol(param.c_str(), &pEnd, STRTOL_BASE);
648         if ((result < INT_MIN || result > INT_MAX) || errno == ERANGE) {
649             return INT_MAX;
650         } else {
651             return static_cast<int32_t>(result);
652         }
653     }
654 }
655 
ReplacePlaceHolderArray(std::string & resultStr,const std::vector<std::string> & arrayResult)656 inline void ReplacePlaceHolderArray(std::string& resultStr, const std::vector<std::string>& arrayResult)
657 {
658     auto size = arrayResult.size();
659     size_t startPos = 0;
660     for (size_t i = 0; i < size; i++) {
661         std::string placeHolder;
662         placeHolder += LEFT_CURLY_BRACES;
663         placeHolder += (i + '0');
664         placeHolder += RIGHT_CURLY_BRACES;
665         if (startPos < resultStr.length()) {
666             auto pos = resultStr.find(placeHolder, startPos);
667             if (pos != std::string::npos) {
668                 resultStr.replace(pos, PLACE_HOLDER_LENGTH, arrayResult[i]);
669                 startPos = pos + arrayResult[i].length();
670             }
671         }
672     }
673 }
674 
ReplacePlaceHolder(std::string & resultStr,const std::unique_ptr<JsonValue> & argsPtr)675 inline void ReplacePlaceHolder(std::string& resultStr, const std::unique_ptr<JsonValue>& argsPtr)
676 {
677     auto placeHolderKey = argsPtr->GetChild()->GetKey();
678     std::string placeHolder;
679     placeHolder += LEFT_CURLY_BRACES;
680     placeHolder += placeHolderKey;
681     placeHolder += RIGHT_CURLY_BRACES;
682     auto pos = resultStr.find(placeHolder);
683     if (pos != std::string::npos) {
684         resultStr.replace(pos, placeHolder.length(), argsPtr->GetChild()->GetString());
685     }
686 }
687 
ParserPluralResource(const std::unique_ptr<JsonValue> & argsPtr,const std::string & choice,const std::string & count)688 inline std::string ParserPluralResource(const std::unique_ptr<JsonValue>& argsPtr, const std::string& choice,
689     const std::string& count)
690 {
691     std::string valueStr;
692     std::string defaultPluralStr(DEFAULT_PLURAL_CHOICE);
693     if (argsPtr->Contains(choice)) {
694         valueStr = argsPtr->GetValue(choice)->GetString();
695     } else if (argsPtr->Contains(defaultPluralStr)) {
696         valueStr = argsPtr->GetValue(defaultPluralStr)->GetString();
697     } else {
698         return std::string();
699     }
700 
701     std::string pluralStr(PLURAL_COUNT_POS);
702     auto pos = valueStr.find(pluralStr);
703     if (pos != std::string::npos) {
704         valueStr.replace(pos, pluralStr.length(), count);
705     }
706     return valueStr;
707 }
708 
709 } // namespace OHOS::Ace::Framework
710 
711 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_UTILS_H
712