1 /*
2 * Copyright (c) 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 #define LOG_TAG "WallpaperJSUtil"
16 #include "wallpaper_js_util.h"
17 #include "hilog_wrapper.h"
18
19 namespace OHOS::WallpaperNAPI {
20 const static int32_t ARRAY_LENGTH = 4;
21 const static int32_t ZERO = 0;
22 const static int32_t ONE = 1;
23 const static int32_t TWO = 2;
24 const static int32_t THREE = 3;
25
Convert2String(napi_env env,napi_value jsString)26 std::string WallpaperJSUtil::Convert2String(napi_env env, napi_value jsString)
27 {
28 size_t maxLen = WallpaperJSUtil::MAX_LEN;
29 napi_status status = napi_get_value_string_utf8(env, jsString, NULL, 0, &maxLen);
30 if (status != napi_ok) {
31 GET_AND_THROW_LAST_ERROR((env));
32 maxLen = WallpaperJSUtil::MAX_LEN;
33 }
34 if (maxLen <= 0) {
35 return std::string();
36 }
37 char *buf = new char[maxLen + 1];
38 if (buf == nullptr) {
39 return std::string();
40 }
41 size_t len = 0;
42 status = napi_get_value_string_utf8(env, jsString, buf, maxLen + 1, &len);
43 if (status != napi_ok) {
44 GET_AND_THROW_LAST_ERROR((env));
45 }
46 buf[len] = 0;
47 std::string value(buf);
48 delete[] buf;
49 return value;
50 }
51
Convert2JSRgbaArray(napi_env env,const std::vector<RgbaColor> & color)52 napi_value WallpaperJSUtil::Convert2JSRgbaArray(napi_env env, const std::vector<RgbaColor> &color)
53 {
54 napi_value result = nullptr;
55 napi_create_array_with_length(env, color.size(), &result);
56 int index = 0;
57 for (const auto it : color) {
58 napi_value element = nullptr;
59 napi_create_array_with_length(env, ARRAY_LENGTH, &element);
60 napi_value jsRgba = nullptr;
61 napi_create_int32(env, it.red, &jsRgba);
62 napi_set_element(env, element, ZERO, jsRgba);
63 jsRgba = nullptr;
64 napi_create_int32(env, it.green, &jsRgba);
65 napi_set_element(env, element, ONE, jsRgba);
66 jsRgba = nullptr;
67 napi_create_int32(env, it.blue, &jsRgba);
68 napi_set_element(env, element, TWO, jsRgba);
69 jsRgba = nullptr;
70 napi_create_int32(env, it.alpha, &jsRgba);
71 napi_set_element(env, element, THREE, jsRgba);
72 napi_set_element(env, result, index++, element);
73 }
74 return result;
75 }
76 }