• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 #include "color_parser.h"
17 #include <cstdlib>
18 
19 #include "window_manager_hilog.h"
20 
21 namespace OHOS {
22 namespace Rosen {
23 namespace {
24     constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "ColorParser"};
25 }
26 
Parse(const std::string & colorStr,uint32_t & colorValue)27 bool ColorParser::Parse(const std::string& colorStr, uint32_t& colorValue)
28 {
29     if (colorStr.empty()) {
30         WLOGFE("color string is empty");
31         return false;
32     }
33 
34     if (colorStr[0] == '#') { // start with '#'
35         std::string color = colorStr.substr(1);
36         if (!IsValidHexString(color)) {
37             return false;
38         }
39         char* ptr;
40         colorValue = std::strtoul(color.c_str(), &ptr, 16); // convert hex string to number
41         if (colorStr.size() == 7) { // #RRGGBB: RRGGBB -> AARRGGBB
42             colorValue |= 0xff000000;
43             return true;
44         } else if (colorStr.size() == 9) { // #AARRGGBB
45             return true;
46         } else {
47             // do nothing
48         }
49     }
50     return false;
51 }
52 
IsValidHexString(const std::string & colorStr)53 bool ColorParser::IsValidHexString(const std::string& colorStr)
54 {
55     if (colorStr.empty()) {
56         return false;
57     }
58     for (char ch : colorStr) {
59         if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
60             continue;
61         }
62         return false;
63     }
64     return true;
65 }
66 } // namespace Rosen
67 } // namespace OHOS