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 
16 #include "js_display.h"
17 
18 #include <cinttypes>
19 #include <hitrace_meter.h>
20 #include <map>
21 #include <set>
22 
23 #include "cutout_info.h"
24 #include "display.h"
25 #include "display_info.h"
26 #include "window_manager_hilog.h"
27 #include "display_manager.h"
28 #include "singleton_container.h"
29 #include "js_display_listener.h"
30 
31 namespace OHOS {
32 namespace Rosen {
33 using namespace AbilityRuntime;
34 constexpr size_t ARGC_ONE = 1;
35 constexpr size_t ARGC_TWO = 2;
36 constexpr int32_t INDEX_ONE = 1;
37 namespace {
38 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_DISPLAY, "JsDisplay"};
39 const std::map<DisplayState,      DisplayStateMode> NATIVE_TO_JS_DISPLAY_STATE_MAP {
40     { DisplayState::UNKNOWN,      DisplayStateMode::STATE_UNKNOWN      },
41     { DisplayState::OFF,          DisplayStateMode::STATE_OFF          },
42     { DisplayState::ON,           DisplayStateMode::STATE_ON           },
43     { DisplayState::DOZE,         DisplayStateMode::STATE_DOZE         },
44     { DisplayState::DOZE_SUSPEND, DisplayStateMode::STATE_DOZE_SUSPEND },
45     { DisplayState::VR,           DisplayStateMode::STATE_VR           },
46     { DisplayState::ON_SUSPEND,   DisplayStateMode::STATE_ON_SUSPEND   },
47 };
48 
49 using GraphicCM_ColorSpaceType = enum {
50     GRAPHIC_CM_COLORSPACE_NONE,
51 
52     GRAPHIC_CM_BT601_EBU_FULL      = 2 | (1 << 8) | (2 << 16) | (1 << 21),  // COLORPRIMARIES_BT601_P | (TRANSFUNC_BT709 << 8) | (MATRIX_BT601_P << 16) | (RANGE_FULL << 21)
53     GRAPHIC_CM_BT601_SMPTE_C_FULL  = 3 | (1 << 8) | (3 << 16) | (1 << 21),  // COLORPRIMARIES_BT601_N | (TRANSFUNC_BT709 << 8) | (MATRIX_BT601_N << 16) | (RANGE_FULL << 21)
54     GRAPHIC_CM_BT709_FULL          = 1 | (1 << 8) | (1 << 16) | (1 << 21),  // COLORPRIMARIES_BT709   | (TRANSFUNC_BT709 << 8) | (MATRIX_BT709   << 16) | (RANGE_FULL << 21)
55     GRAPHIC_CM_BT2020_HLG_FULL     = 4 | (5 << 8) | (4 << 16) | (1 << 21),  // COLORPRIMARIES_BT2020  | (TRANSFUNC_HLG   << 8) | (MATRIX_BT2020  << 16) | (RANGE_FULL << 21)
56     GRAPHIC_CM_BT2020_PQ_FULL      = 4 | (4 << 8) | (4 << 16) | (1 << 21),  // COLORPRIMARIES_BT2020  | (TRANSFUNC_PQ    << 8) | (MATRIX_BT2020  << 16) | (RANGE_FULL << 21)
57 
58     GRAPHIC_CM_BT601_EBU_LIMIT     = 2 | (1 << 8) | (2 << 16) | (2 << 21),  // COLORPRIMARIES_BT601_P | (TRANSFUNC_BT709 << 8) | (MATRIX_BT601_P << 16) | (RANGE_LIMITED << 21)
59     GRAPHIC_CM_BT601_SMPTE_C_LIMIT = 3 | (1 << 8) | (3 << 16) | (2 << 21),  // COLORPRIMARIES_BT601_N | (TRANSFUNC_BT709 << 8) | (MATRIX_BT601_N << 16) | (RANGE_LIMITED << 21)
60     GRAPHIC_CM_BT709_LIMIT         = 1 | (1 << 8) | (1 << 16) | (2 << 21),  // COLORPRIMARIES_BT709   | (TRANSFUNC_BT709 << 8) | (MATRIX_BT709   << 16) | (RANGE_LIMITED << 21)
61     GRAPHIC_CM_BT2020_HLG_LIMIT    = 4 | (5 << 8) | (4 << 16) | (2 << 21),  // COLORPRIMARIES_BT2020  | (TRANSFUNC_HLG   << 8) | (MATRIX_BT2020  << 16) | (RANGE_LIMITED << 21)
62     GRAPHIC_CM_BT2020_PQ_LIMIT     = 4 | (4 << 8) | (4 << 16) | (2 << 21),  // COLORPRIMARIES_BT2020  | (TRANSFUNC_PQ    << 8) | (MATRIX_BT2020  << 16) | (RANGE_LIMITED << 21)
63 
64     GRAPHIC_CM_SRGB_FULL           = 1 | (2 << 8) | (3 << 16) | (1 << 21),  // COLORPRIMARIES_SRGB     | (TRANSFUNC_SRGB     << 8) | (MATRIX_BT601_N  << 16) | (RANGE_FULL << 21)
65     GRAPHIC_CM_P3_FULL             = 6 | (2 << 8) | (3 << 16) | (1 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_SRGB     << 8) | (MATRIX_P3       << 16) | (RANGE_FULL << 21)
66     GRAPHIC_CM_P3_HLG_FULL         = 6 | (5 << 8) | (3 << 16) | (1 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_HLG      << 8) | (MATRIX_P3       << 16) | (RANGE_FULL << 21)
67     GRAPHIC_CM_P3_PQ_FULL          = 6 | (4 << 8) | (3 << 16) | (1 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_PQ       << 8) | (MATRIX_P3       << 16) | (RANGE_FULL << 21)
68     GRAPHIC_CM_ADOBERGB_FULL       = 23 | (6 << 8) | (0 << 16) | (1 << 21), // COLORPRIMARIES_ADOBERGB | (TRANSFUNC_ADOBERGB << 8) | (MATRIX_ADOBERGB << 16) | (RANGE_FULL << 21)
69 
70     GRAPHIC_CM_SRGB_LIMIT          = 1 | (2 << 8) | (3 << 16) | (2 << 21),  // COLORPRIMARIES_SRGB     | (TRANSFUNC_SRGB     << 8) | (MATRIX_BT601_N  << 16) | (RANGE_LIMITED << 21)
71     GRAPHIC_CM_P3_LIMIT            = 6 | (2 << 8) | (3 << 16) | (2 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_SRGB     << 8) | (MATRIX_P3       << 16) | (RANGE_LIMITED << 21)
72     GRAPHIC_CM_P3_HLG_LIMIT        = 6 | (5 << 8) | (3 << 16) | (2 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_HLG      << 8) | (MATRIX_P3       << 16) | (RANGE_LIMITED << 21)
73     GRAPHIC_CM_P3_PQ_LIMIT         = 6 | (4 << 8) | (3 << 16) | (2 << 21),  // COLORPRIMARIES_P3_D65   | (TRANSFUNC_PQ       << 8) | (MATRIX_P3       << 16) | (RANGE_LIMITED << 21)
74     GRAPHIC_CM_ADOBERGB_LIMIT      = 23 | (6 << 8) | (0 << 16) | (2 << 21), // COLORPRIMARIES_ADOBERGB | (TRANSFUNC_ADOBERGB << 8) | (MATRIX_ADOBERGB << 16) | (RANGE_LIMITED << 21)
75 
76     GRAPHIC_CM_LINEAR_SRGB         = 1 | (3 << 8),                          // COLORPRIMARIES_SRGB   | (TRANSFUNC_LINEAR << 8)
77     GRAPHIC_CM_LINEAR_BT709        = 1 | (3 << 8),                          // equal to GRAPHIC_CM_LINEAR_SRGB
78     GRAPHIC_CM_LINEAR_P3           = 6 | (3 << 8),                          // COLORPRIMARIES_P3_D65 | (TRANSFUNC_LINEAR << 8)
79     GRAPHIC_CM_LINEAR_BT2020       = 4 | (3 << 8),                          // COLORPRIMARIES_BT2020 | (TRANSFUNC_LINEAR << 8)
80 
81     GRAPHIC_CM_DISPLAY_SRGB        = 1 | (2 << 8) | (3 << 16) | (1 << 21),  // equal to GRAPHIC_CM_SRGB_FULL
82     GRAPHIC_CM_DISPLAY_P3_SRGB     = 6 | (2 << 8) | (3 << 16) | (1 << 21),  // equal to GRAPHIC_CM_P3_FULL
83     GRAPHIC_CM_DISPLAY_P3_HLG      = 6 | (5 << 8) | (3 << 16) | (1 << 21),  // equal to GRAPHIC_CM_P3_HLG_FULL
84     GRAPHIC_CM_DISPLAY_P3_PQ       = 6 | (4 << 8) | (3 << 16) | (1 << 21),  // equal to GRAPHIC_CM_P3_PQ_FULL
85     GRAPHIC_CM_DISPLAY_BT2020_SRGB = 4 | (2 << 8) | (4 << 16) | (1 << 21),  // COLORPRIMARIES_BT2020   | (TRANSFUNC_SRGB << 8)     | (MATRIX_BT2020 << 16)   | (RANGE_FULL << 21)
86     GRAPHIC_CM_DISPLAY_BT2020_HLG  = 4 | (5 << 8) | (4 << 16) | (1 << 21),  // equal to GRAPHIC_CM_BT2020_HLG_FULL
87     GRAPHIC_CM_DISPLAY_BT2020_PQ   = 4 | (4 << 8) | (4 << 16) | (1 << 21)   // equal to GRAPHIC_CM_BT2020_PQ_FULL
88 };
89 
90 typedef enum : uint32_t {
91     NOT_SUPPORT_HDR = 0,
92     VIDEO_HLG,
93     VIDEO_HDR10,
94     VIDEO_HDR_VIVID,
95     IMAGE_HDR_VIVID_DUAL,
96     IMAGE_HDR_VIVID_SINGLE,
97     IMAGE_HDR_ISO_DUAL,
98     IMAGE_HDR_ISO_SINGLE,
99 } ScreenHDRFormat;
100 
101 const std::map<GraphicCM_ColorSpaceType, ColorSpace> NATIVE_TO_JS_COLOR_SPACE_TYPE_MAP {
102     { GraphicCM_ColorSpaceType::GRAPHIC_CM_COLORSPACE_NONE,        ColorSpace::UNKNOWN },
103     { GraphicCM_ColorSpaceType::GRAPHIC_CM_ADOBERGB_FULL,          ColorSpace::ADOBE_RGB },
104     { GraphicCM_ColorSpaceType::GRAPHIC_CM_ADOBERGB_LIMIT,         ColorSpace::ADOBE_RGB },
105     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT2020_HLG_FULL,        ColorSpace::BT2020_HLG },
106     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT2020_HLG_LIMIT,       ColorSpace::BT2020_HLG },
107     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_BT2020_HLG,     ColorSpace::BT2020_HLG },
108     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT2020_PQ_FULL,         ColorSpace::BT2020_PQ },
109     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT2020_PQ_LIMIT,        ColorSpace::BT2020_PQ },
110     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_BT2020_PQ,      ColorSpace::BT2020_PQ },
111     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT601_EBU_FULL,         ColorSpace::BT601_EBU },
112     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT601_EBU_LIMIT,        ColorSpace::BT601_EBU },
113     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT601_SMPTE_C_FULL,     ColorSpace::BT601_SMPTE_C },
114     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT601_SMPTE_C_LIMIT,    ColorSpace::BT601_SMPTE_C },
115     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT709_FULL,             ColorSpace::BT709 },
116     { GraphicCM_ColorSpaceType::GRAPHIC_CM_BT709_LIMIT,            ColorSpace::BT709 },
117     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_HLG_FULL,            ColorSpace::P3_HLG },
118     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_HLG_LIMIT,           ColorSpace::P3_HLG },
119     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_P3_HLG,         ColorSpace::P3_HLG },
120     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_PQ_FULL,             ColorSpace::P3_PQ },
121     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_PQ_LIMIT,            ColorSpace::P3_PQ },
122     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_P3_PQ,          ColorSpace::P3_PQ },
123     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_FULL,                ColorSpace::DISPLAY_P3 },
124     { GraphicCM_ColorSpaceType::GRAPHIC_CM_P3_LIMIT,               ColorSpace::DISPLAY_P3 },
125     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_P3_SRGB,        ColorSpace::DISPLAY_P3 },
126     { GraphicCM_ColorSpaceType::GRAPHIC_CM_SRGB_FULL,              ColorSpace::SRGB },
127     { GraphicCM_ColorSpaceType::GRAPHIC_CM_SRGB_LIMIT,             ColorSpace::SRGB },
128     { GraphicCM_ColorSpaceType::GRAPHIC_CM_DISPLAY_SRGB,           ColorSpace::SRGB },
129     { GraphicCM_ColorSpaceType::GRAPHIC_CM_LINEAR_SRGB,            ColorSpace::LINEAR_SRGB },
130     { GraphicCM_ColorSpaceType::GRAPHIC_CM_LINEAR_BT709,           ColorSpace::LINEAR_SRGB },
131     { GraphicCM_ColorSpaceType::GRAPHIC_CM_LINEAR_P3,              ColorSpace::LINEAR_P3 },
132     { GraphicCM_ColorSpaceType::GRAPHIC_CM_LINEAR_BT2020,          ColorSpace::LINEAR_BT2020 },
133 };
134 
135 const std::map<ScreenHDRFormat, HDRFormat> NATIVE_TO_JS_HDR_FORMAT_TYPE_MAP {
136     { ScreenHDRFormat::NOT_SUPPORT_HDR,             HDRFormat::NONE },
137     { ScreenHDRFormat::VIDEO_HLG,                   HDRFormat::VIDEO_HLG },
138     { ScreenHDRFormat::VIDEO_HDR10,                 HDRFormat::VIDEO_HDR10 },
139     { ScreenHDRFormat::VIDEO_HDR_VIVID,             HDRFormat::VIDEO_HDR_VIVID },
140     { ScreenHDRFormat::IMAGE_HDR_VIVID_DUAL,        HDRFormat::IMAGE_HDR_VIVID_DUAL },
141     { ScreenHDRFormat::IMAGE_HDR_VIVID_SINGLE,      HDRFormat::IMAGE_HDR_VIVID_SINGLE },
142     { ScreenHDRFormat::IMAGE_HDR_ISO_DUAL,          HDRFormat::IMAGE_HDR_ISO_DUAL },
143     { ScreenHDRFormat::IMAGE_HDR_ISO_SINGLE,        HDRFormat::IMAGE_HDR_ISO_SINGLE },
144 };
145 }
146 
147 static thread_local std::map<DisplayId, std::shared_ptr<NativeReference>> g_JsDisplayMap;
148 std::map<std::string, std::map<std::unique_ptr<NativeReference>, sptr<JsDisplayListener>>> jsCbMap_;
149 std::mutex mtx_;
150 std::recursive_mutex g_mutex;
151 
JsDisplay(const sptr<Display>& display)152 JsDisplay::JsDisplay(const sptr<Display>& display) : display_(display)
153 {
154 }
155 
~JsDisplay()156 JsDisplay::~JsDisplay()
157 {
158     WLOGI("JsDisplay::~JsDisplay is called");
159 }
160 
Finalizer(napi_env env, void* data, void* hint)161 void JsDisplay::Finalizer(napi_env env, void* data, void* hint)
162 {
163     WLOGI("JsDisplay::Finalizer is called");
164     auto jsDisplay = std::unique_ptr<JsDisplay>(static_cast<JsDisplay*>(data));
165     if (jsDisplay == nullptr) {
166         WLOGFE("JsDisplay::Finalizer jsDisplay is null");
167         return;
168     }
169     sptr<Display> display = jsDisplay->display_;
170     if (display == nullptr) {
171         WLOGFE("JsDisplay::Finalizer display is null");
172         return;
173     }
174     DisplayId displayId = display->GetId();
175     WLOGI("JsDisplay::Finalizer displayId : %{public}" PRIu64"", displayId);
176     std::lock_guard<std::recursive_mutex> lock(g_mutex);
177     if (g_JsDisplayMap.find(displayId) != g_JsDisplayMap.end()) {
178         WLOGI("JsDisplay::Finalizer Display is destroyed: %{public}" PRIu64"", displayId);
179         g_JsDisplayMap.erase(displayId);
180     }
181 }
182 
GetCutoutInfo(napi_env env, napi_callback_info info)183 napi_value JsDisplay::GetCutoutInfo(napi_env env, napi_callback_info info)
184 {
185     WLOGD("GetCutoutInfo is called");
186     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
187     return (me != nullptr) ? me->OnGetCutoutInfo(env, info) : nullptr;
188 }
189 
GetAvailableArea(napi_env env, napi_callback_info info)190 napi_value JsDisplay::GetAvailableArea(napi_env env, napi_callback_info info)
191 {
192     WLOGI("GetAvailableArea is called");
193     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
194     return (me != nullptr) ? me->OnGetAvailableArea(env, info) : nullptr;
195 }
196 
RegisterDisplayManagerCallback(napi_env env, napi_callback_info info)197 napi_value JsDisplay::RegisterDisplayManagerCallback(napi_env env, napi_callback_info info)
198 {
199     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
200     return (me != nullptr) ? me->OnRegisterDisplayManagerCallback(env, info) : nullptr;
201 }
202 
UnregisterDisplayManagerCallback(napi_env env, napi_callback_info info)203 napi_value JsDisplay::UnregisterDisplayManagerCallback(napi_env env, napi_callback_info info)
204 {
205     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
206     return (me != nullptr) ? me->OnUnregisterDisplayManagerCallback(env, info) : nullptr;
207 }
208 
NapiIsCallable(napi_env env, napi_value value)209 bool NapiIsCallable(napi_env env, napi_value value)
210 {
211     bool result = false;
212     napi_is_callable(env, value, &result);
213     return result;
214 }
215 
IfCallbackRegistered(napi_env env, const std::string& type, napi_value jsListenerObject)216 bool IfCallbackRegistered(napi_env env, const std::string& type, napi_value jsListenerObject)
217 {
218     if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) {
219         WLOGI("IfCallbackRegistered methodName %{public}s not registered!", type.c_str());
220         return false;
221     }
222 
223     for (auto& iter : jsCbMap_[type]) {
224         bool isEquals = false;
225         napi_strict_equals(env, jsListenerObject, iter.first->GetNapiValue(), &isEquals);
226         if (isEquals) {
227             WLOGFE("IfCallbackRegistered callback already registered!");
228             return true;
229         }
230     }
231     return false;
232 }
233 
OnRegisterDisplayManagerCallback(napi_env env, napi_callback_info info)234 napi_value JsDisplay::OnRegisterDisplayManagerCallback(napi_env env, napi_callback_info info)
235 {
236     WLOGD("OnRegisterDisplayManagerCallback is called");
237     size_t argc = 4;
238     napi_value argv[4] = {nullptr};
239     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
240     if (argc < ARGC_TWO) {
241         WLOGFE("JsDisplayManager Params not match: %{public}zu", argc);
242         std::string errMsg = "Invalid args count, need 2 args";
243         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
244         return NapiGetUndefined(env);
245     }
246     std::string cbType;
247     if (!ConvertFromJsValue(env, argv[0], cbType)) {
248         std::string errMsg = "Failed to convert parameter to callbackType";
249         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
250         WLOGFE("Failed to convert parameter to callbackType");
251         return NapiGetUndefined(env);
252     }
253     napi_value value = argv[INDEX_ONE];
254     if (value == nullptr) {
255         WLOGI("OnRegisterDisplayManagerCallback info->argv[1] is nullptr");
256         std::string errMsg = "OnRegisterDisplayManagerCallback is nullptr";
257         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
258         return NapiGetUndefined(env);
259     }
260     if (!NapiIsCallable(env, value)) {
261         WLOGI("OnRegisterDisplayManagerCallback info->argv[1] is not callable");
262         std::string errMsg = "OnRegisterDisplayManagerCallback is not callable";
263         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
264         return NapiGetUndefined(env);
265     }
266     std::lock_guard<std::mutex> lock(mtx_);
267     DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(RegisterDisplayListenerWithType(env, cbType, value));
268     if (ret != DmErrorCode::DM_OK) {
269         WLOGFE("Failed to register display listener with type");
270         std::string errMsg = "Failed to register display listener with type";
271         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
272         return NapiGetUndefined(env);
273     }
274     return NapiGetUndefined(env);
275 }
276 
RegisterDisplayListenerWithType(napi_env env, const std::string& type, napi_value value)277 DMError JsDisplay::RegisterDisplayListenerWithType(napi_env env, const std::string& type, napi_value value)
278 {
279     if (IfCallbackRegistered(env, type, value)) {
280         WLOGFI("RegisterDisplayListenerWithType callback already registered!");
281         return DMError::DM_OK;
282     }
283     std::unique_ptr<NativeReference> callbackRef;
284     napi_ref result = nullptr;
285     napi_create_reference(env, value, 1, &result);
286     callbackRef.reset(reinterpret_cast<NativeReference*>(result));
287     sptr<JsDisplayListener> displayListener = new(std::nothrow) JsDisplayListener(env);
288     DMError ret = DMError::DM_OK;
289     if (displayListener == nullptr) {
290         WLOGFE("displayListener is nullptr");
291         return DMError::DM_ERROR_INVALID_PARAM;
292     }
293     if (type == EVENT_AVAILABLE_AREA_CHANGED) {
294         ret = SingletonContainer::Get<DisplayManager>().RegisterAvailableAreaListener(displayListener);
295     } else {
296         WLOGFE("RegisterDisplayListenerWithType failed, %{public}s not support", type.c_str());
297         return DMError::DM_ERROR_INVALID_PARAM;
298     }
299     if (ret != DMError::DM_OK) {
300         WLOGFE("RegisterDisplayListenerWithType failed, ret: %{public}u", ret);
301         return ret;
302     }
303     displayListener->AddCallback(type, value);
304     jsCbMap_[type][std::move(callbackRef)] = displayListener;
305     return DMError::DM_OK;
306 }
307 
OnUnregisterDisplayManagerCallback(napi_env env, napi_callback_info info)308 napi_value JsDisplay::OnUnregisterDisplayManagerCallback(napi_env env, napi_callback_info info)
309 {
310     WLOGI("OnUnregisterDisplayCallback is called");
311     size_t argc = 4;
312     napi_value argv[4] = {nullptr};
313     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
314     if (argc < ARGC_ONE) {
315         WLOGFE("JsDisplayManager Params not match %{public}zu", argc);
316         std::string errMsg = "Invalid args count, need one arg at least!";
317         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
318         return NapiGetUndefined(env);
319     }
320     std::string cbType;
321     if (!ConvertFromJsValue(env, argv[0], cbType)) {
322         WLOGFE("Failed to convert parameter to callbackType");
323         std::string errMsg = "Failed to convert parameter to string";
324         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
325         return NapiGetUndefined(env);
326     }
327     std::lock_guard<std::mutex> lock(mtx_);
328     DmErrorCode ret;
329     if (argc == ARGC_ONE) {
330         ret = DM_JS_TO_ERROR_CODE_MAP.at(UnregisterAllDisplayListenerWithType(cbType));
331     } else {
332         napi_value value = argv[INDEX_ONE];
333         if ((value == nullptr) || (!NapiIsCallable(env, value))) {
334             ret = DM_JS_TO_ERROR_CODE_MAP.at(UnregisterAllDisplayListenerWithType(cbType));
335         } else {
336             ret = DM_JS_TO_ERROR_CODE_MAP.at(UnRegisterDisplayListenerWithType(env, cbType, value));
337         }
338     }
339     if (ret != DmErrorCode::DM_OK) {
340         WLOGFW("failed to unregister display listener with type");
341         std::string errMsg = "failed to unregister display listener with type";
342         napi_throw(env, CreateJsError(env, static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_PARAM), errMsg));
343         return NapiGetUndefined(env);
344     }
345     return NapiGetUndefined(env);
346 }
347 
UnregisterAllDisplayListenerWithType(const std::string& type)348 DMError JsDisplay::UnregisterAllDisplayListenerWithType(const std::string& type)
349 {
350     if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) {
351         WLOGI("UnregisterAllDisplayListenerWithType methodName %{public}s not registered!",
352             type.c_str());
353         return DMError::DM_OK;
354     }
355     DMError ret = DMError::DM_OK;
356     for (auto it = jsCbMap_[type].begin(); it != jsCbMap_[type].end();) {
357         it->second->RemoveAllCallback();
358         if (type == EVENT_AVAILABLE_AREA_CHANGED) {
359             sptr<DisplayManager::IAvailableAreaListener> thisListener(it->second);
360             ret = SingletonContainer::Get<DisplayManager>().UnregisterAvailableAreaListener(thisListener);
361         } else {
362             ret = DMError::DM_ERROR_INVALID_PARAM;
363         }
364         jsCbMap_[type].erase(it++);
365         WLOGFI("unregister display listener with type %{public}s  ret: %{public}u", type.c_str(), ret);
366     }
367     jsCbMap_.erase(type);
368     return ret;
369 }
370 
UnRegisterDisplayListenerWithType(napi_env env, const std::string& type, napi_value value)371 DMError JsDisplay::UnRegisterDisplayListenerWithType(napi_env env, const std::string& type, napi_value value)
372 {
373     if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) {
374         WLOGI("UnRegisterDisplayListenerWithType methodName %{public}s not registered!", type.c_str());
375         return DMError::DM_OK;
376     }
377     DMError ret = DMError::DM_OK;
378     for (auto it = jsCbMap_[type].begin(); it != jsCbMap_[type].end();) {
379         bool isEquals = false;
380         napi_strict_equals(env, value, it->first->GetNapiValue(), &isEquals);
381         if (isEquals) {
382             it->second->RemoveCallback(env, type, value);
383             if (type == EVENT_AVAILABLE_AREA_CHANGED) {
384                 sptr<DisplayManager::IAvailableAreaListener> thisListener(it->second);
385                 ret = SingletonContainer::Get<DisplayManager>().UnregisterAvailableAreaListener(thisListener);
386             } else {
387                 ret = DMError::DM_ERROR_INVALID_PARAM;
388             }
389             jsCbMap_[type].erase(it++);
390             WLOGFI("unregister display listener with type %{public}s  ret: %{public}u", type.c_str(), ret);
391             break;
392         } else {
393             it++;
394         }
395     }
396     if (jsCbMap_[type].empty()) {
397         jsCbMap_.erase(type);
398     }
399     return ret;
400 }
401 
HasImmersiveWindow(napi_env env, napi_callback_info info)402 napi_value JsDisplay::HasImmersiveWindow(napi_env env, napi_callback_info info)
403 {
404     WLOGI("HasImmersiveWindow is called");
405     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
406     return (me != nullptr) ? me->OnHasImmersiveWindow(env, info) : nullptr;
407 }
408 
GetType(napi_env env, napi_value value)409 napi_valuetype GetType(napi_env env, napi_value value)
410 {
411     napi_valuetype res = napi_undefined;
412     napi_typeof(env, value, &res);
413     return res;
414 }
415 
OnGetCutoutInfo(napi_env env, napi_callback_info info)416 napi_value JsDisplay::OnGetCutoutInfo(napi_env env, napi_callback_info info)
417 {
418     WLOGD("OnGetCutoutInfo is called");
419     napi_value result = nullptr;
420     size_t argc = 4;
421     napi_value argv[4] = {nullptr};
422     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
423     napi_value lastParam = nullptr;
424     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr && GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
425         lastParam = argv[ARGC_ONE - 1];
426     }
427     std::unique_ptr<NapiAsyncTask> napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result);
428     auto asyncTask = [this, env, task = napiAsyncTask.get()]() {
429         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "JsDisplay::OnGetCutoutInfo");
430         sptr<CutoutInfo> cutoutInfo = display_->GetCutoutInfo();
431         if (cutoutInfo != nullptr) {
432             task->Resolve(env, CreateJsCutoutInfoObject(env, cutoutInfo));
433             WLOGD("JsDisplay::OnGetCutoutInfo success");
434         } else {
435             task->Reject(env, CreateJsError(env,
436                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "JsDisplay::OnGetCutoutInfo failed."));
437         }
438         delete task;
439     };
440     if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) {
441         napiAsyncTask->Reject(env, CreateJsError(env,
442                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "Send event failed!"));
443     } else {
444         napiAsyncTask.release();
445     }
446     return result;
447 }
448 
CreateEmptyAsyncTask(napi_env env, napi_value lastParam, napi_value* result)449 std::unique_ptr<NapiAsyncTask> JsDisplay::CreateEmptyAsyncTask(napi_env env, napi_value lastParam, napi_value* result)
450 {
451     napi_valuetype type = napi_undefined;
452     napi_typeof(env, lastParam, &type);
453     if (lastParam == nullptr || type != napi_function) {
454         napi_deferred nativeDeferred = nullptr;
455         napi_create_promise(env, &nativeDeferred, result);
456         return std::make_unique<NapiAsyncTask>(nativeDeferred, std::unique_ptr<NapiAsyncTask::ExecuteCallback>(),
457             std::unique_ptr<NapiAsyncTask::CompleteCallback>());
458     } else {
459         napi_get_undefined(env, result);
460         napi_ref callbackRef = nullptr;
461         napi_create_reference(env, lastParam, 1, &callbackRef);
462         return std::make_unique<NapiAsyncTask>(callbackRef, std::unique_ptr<NapiAsyncTask::ExecuteCallback>(),
463             std::unique_ptr<NapiAsyncTask::CompleteCallback>());
464     }
465 }
466 
OnGetAvailableArea(napi_env env, napi_callback_info info)467 napi_value JsDisplay::OnGetAvailableArea(napi_env env, napi_callback_info info)
468 {
469     WLOGI("OnGetAvailableArea is called");
470     size_t argc = 4;
471     napi_value argv[4] = {nullptr};
472     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
473     napi_value lastParam = nullptr;
474     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
475         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
476         lastParam = argv[ARGC_ONE - 1];
477     }
478     napi_value result = nullptr;
479     std::unique_ptr<NapiAsyncTask> napiAsyncTask = JsDisplay::CreateEmptyAsyncTask(env, lastParam, &result);
480     auto asyncTask = [this, env, task = napiAsyncTask.get()]() {
481         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "JsDisplay::OnGetAvailableArea");
482         DMRect area;
483         DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetAvailableArea(area));
484         if (ret == DmErrorCode::DM_OK) {
485             task->Resolve(env, CreateJsRectObject(env, area));
486             WLOGI("JsDisplay::OnGetAvailableArea success");
487         } else {
488             task->Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
489                 "JsDisplay::OnGetAvailableArea failed."));
490         }
491         delete task;
492     };
493     if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) {
494         napiAsyncTask->Reject(env, CreateJsError(env,
495                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "Send event failed!"));
496     } else {
497         napiAsyncTask.release();
498     }
499     return result;
500 }
501 
OnHasImmersiveWindow(napi_env env, napi_callback_info info)502 napi_value JsDisplay::OnHasImmersiveWindow(napi_env env, napi_callback_info info)
503 {
504     WLOGI("OnHasImmersiveWindow is called");
505     size_t argc = 4;
506     napi_value argv[4] = {nullptr};
507     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
508     napi_value lastParam = nullptr;
509     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
510         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
511         lastParam = argv[ARGC_ONE - 1];
512     }
513     napi_value result = nullptr;
514     std::unique_ptr<NapiAsyncTask> napiAsyncTask = JsDisplay::CreateEmptyAsyncTask(env, lastParam, &result);
515     auto asyncTask = [this, env, task = napiAsyncTask.get()]() {
516         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "JsDisplay::OnHasImmersiveWindow");
517         bool immersive = false;
518         DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->HasImmersiveWindow(immersive));
519         if (ret == DmErrorCode::DM_OK) {
520             task->Resolve(env, CreateJsValue(env, immersive));
521             WLOGI("JsDisplay::OnHasImmersiveWindow success - immersive window exists: %{public}d", immersive);
522         } else {
523             task->Reject(env, CreateJsError(env,
524                 static_cast<int32_t>(ret), "JsDisplay::OnHasImmersiveWindow failed."));
525         }
526         delete task;
527     };
528     if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) {
529         napiAsyncTask->Reject(env, CreateJsError(env,
530                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "Send event failed!"));
531     } else {
532         napiAsyncTask.release();
533     }
534     return result;
535 }
536 
GetSupportedColorSpaces(napi_env env, napi_callback_info info)537 napi_value JsDisplay::GetSupportedColorSpaces(napi_env env, napi_callback_info info)
538 {
539     WLOGI("GetSupportedColorSpaces is called");
540     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
541     return (me != nullptr) ? me->OnGetSupportedColorSpaces(env, info) : nullptr;
542 }
543 
CreateJsColorSpaceArray(napi_env env, const std::vector<uint32_t>& colorSpaces)544 static napi_value CreateJsColorSpaceArray(napi_env env, const std::vector<uint32_t>& colorSpaces)
545 {
546     WLOGD("JsDisplay::CreateJsColorSpaceArray is called");
547     std::set<uint32_t> nativeColorSpaces;
548     for (const auto colorSpace : colorSpaces) {
549         GraphicCM_ColorSpaceType colorSpaceValue = static_cast<GraphicCM_ColorSpaceType>(colorSpace);
550         if (NATIVE_TO_JS_COLOR_SPACE_TYPE_MAP.count(colorSpaceValue) == 0) {
551             WLOGFE("Get color space name %{public}u, but not in api type", colorSpace);
552             napi_throw(env, CreateJsError(env, static_cast<int32_t>(DMError::DM_ERROR_DEVICE_NOT_SUPPORT)));
553             return NapiGetUndefined(env);
554         }
555         nativeColorSpaces.insert(static_cast<uint32_t>(NATIVE_TO_JS_COLOR_SPACE_TYPE_MAP.at(colorSpaceValue)));
556     }
557     napi_value arrayValue = nullptr;
558     napi_create_array_with_length(env, nativeColorSpaces.size(), &arrayValue);
559     if (arrayValue == nullptr) {
560         WLOGFE("Failed to create color space array");
561         return NapiGetUndefined(env);
562     }
563     uint32_t index = 0;
564     for (const auto nativeColorSpace : nativeColorSpaces) {
565         napi_set_element(env, arrayValue, index++, CreateJsValue(env, nativeColorSpace));
566     }
567     return arrayValue;
568 }
569 
OnGetSupportedColorSpaces(napi_env env, napi_callback_info info)570 napi_value JsDisplay::OnGetSupportedColorSpaces(napi_env env, napi_callback_info info)
571 {
572     WLOGI("OnGetSupportedColorSpaces is called");
573     size_t argc = 4;
574     napi_value argv[4] = {nullptr};
575     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
576     napi_value lastParam = nullptr;
577     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
578         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
579         lastParam = argv[ARGC_ONE - 1];
580     }
581     napi_value result = nullptr;
582     std::unique_ptr<NapiAsyncTask> napiAsyncTask = JsDisplay::CreateEmptyAsyncTask(env, lastParam, &result);
583     auto asyncTask = [this, env, task = napiAsyncTask.get()]() {
584         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "JsDisplay::OnGetSupportedColorSpaces");
585         std::vector<uint32_t> colorSpaces;
586         DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetSupportedColorSpaces(colorSpaces));
587         if (ret == DmErrorCode::DM_OK) {
588             task->Resolve(env, CreateJsColorSpaceArray(env, colorSpaces));
589             WLOGI("OnGetSupportedColorSpaces success");
590         } else {
591             task->Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
592                                             "JsDisplay::OnGetSupportedColorSpaces failed."));
593             WLOGFE("OnGetSupportedColorSpaces failed");
594         }
595         delete task;
596     };
597     if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) {
598         napiAsyncTask->Reject(env, CreateJsError(env,
599                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "Send event failed!"));
600     } else {
601         napiAsyncTask.release();
602     }
603     return result;
604 }
605 
GetSupportedHDRFormats(napi_env env, napi_callback_info info)606 napi_value JsDisplay::GetSupportedHDRFormats(napi_env env, napi_callback_info info)
607 {
608     WLOGI("GetSupportedHDRFormats is called");
609     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
610     return (me != nullptr) ? me->OnGetSupportedHDRFormats(env, info) : nullptr;
611 }
612 
CreateJsHDRFormatArray(napi_env env, const std::vector<uint32_t>& hdrFormats)613 static napi_value CreateJsHDRFormatArray(napi_env env, const std::vector<uint32_t>& hdrFormats)
614 {
615     WLOGD("JsDisplay::CreateJsHDRFormatArray is called");
616     std::set<uint32_t> nativeHDRFormats;
617     for (const auto hdrFormat : hdrFormats) {
618         ScreenHDRFormat hdrFormatValue = static_cast<ScreenHDRFormat>(hdrFormat);
619         if (NATIVE_TO_JS_HDR_FORMAT_TYPE_MAP.count(hdrFormatValue) == 0) {
620             WLOGFE("Get HDR format name %{public}u, but not in api type", hdrFormat);
621             napi_throw(env, CreateJsError(env, static_cast<int32_t>(DMError::DM_ERROR_DEVICE_NOT_SUPPORT)));
622             return NapiGetUndefined(env);
623         }
624         nativeHDRFormats.insert(static_cast<uint32_t>(NATIVE_TO_JS_HDR_FORMAT_TYPE_MAP.at(hdrFormatValue)));
625     }
626     napi_value arrayValue = nullptr;
627     napi_create_array_with_length(env, hdrFormats.size(), &arrayValue);
628     if (arrayValue == nullptr) {
629         WLOGFE("Failed to create HDR format array");
630         return NapiGetUndefined(env);
631     }
632     uint32_t index = 0;
633     for (const auto nativeHDRFormat : nativeHDRFormats) {
634         napi_set_element(env, arrayValue, index++, CreateJsValue(env, nativeHDRFormat));
635     }
636     return arrayValue;
637 }
638 
OnGetSupportedHDRFormats(napi_env env, napi_callback_info info)639 napi_value JsDisplay::OnGetSupportedHDRFormats(napi_env env, napi_callback_info info)
640 {
641     WLOGI("OnGetSupportedHDRFormats is called");
642     size_t argc = 4;
643     napi_value argv[4] = {nullptr};
644     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
645     napi_value lastParam = nullptr;
646     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
647         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
648         lastParam = argv[ARGC_ONE - 1];
649     }
650     napi_value result = nullptr;
651     std::unique_ptr<NapiAsyncTask> napiAsyncTask = JsDisplay::CreateEmptyAsyncTask(env, lastParam, &result);
652     auto asyncTask = [this, env, task = napiAsyncTask.get()]() {
653         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "JsDisplay::OnGetSupportedHDRFormats");
654         std::vector<uint32_t> hdrFormats;
655         DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetSupportedHDRFormats(hdrFormats));
656         if (ret == DmErrorCode::DM_OK) {
657             task->Resolve(env, CreateJsHDRFormatArray(env, hdrFormats));
658             WLOGI("OnGetSupportedHDRFormats success");
659         } else {
660             task->Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
661                                             "JsDisplay::OnGetSupportedHDRFormats failed."));
662             WLOGFE("OnGetSupportedHDRFormats failed");
663         }
664         delete task;
665     };
666     if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) {
667         napiAsyncTask->Reject(env, CreateJsError(env,
668                 static_cast<int32_t>(DmErrorCode::DM_ERROR_INVALID_SCREEN), "Send event failed!"));
669     } else {
670         napiAsyncTask.release();
671     }
672     return result;
673 }
674 
FindJsDisplayObject(DisplayId displayId)675 std::shared_ptr<NativeReference> FindJsDisplayObject(DisplayId displayId)
676 {
677     WLOGD("[NAPI]Try to find display %{public}" PRIu64" in g_JsDisplayMap", displayId);
678     std::lock_guard<std::recursive_mutex> lock(g_mutex);
679     if (g_JsDisplayMap.find(displayId) == g_JsDisplayMap.end()) {
680         WLOGD("[NAPI]Can not find display %{public}" PRIu64" in g_JsDisplayMap", displayId);
681         return nullptr;
682     }
683     return g_JsDisplayMap[displayId];
684 }
685 
NapiGetUndefined(napi_env env)686 napi_value NapiGetUndefined(napi_env env)
687 {
688     napi_value result = nullptr;
689     napi_get_undefined(env, &result);
690     return result;
691 }
692 
CreateJsCutoutInfoObject(napi_env env, sptr<CutoutInfo> cutoutInfo)693 napi_value CreateJsCutoutInfoObject(napi_env env, sptr<CutoutInfo> cutoutInfo)
694 {
695     WLOGD("JsDisplay::CreateJsCutoutInfoObject is called");
696     napi_value objValue = nullptr;
697     napi_create_object(env, &objValue);
698     if (objValue == nullptr) {
699         WLOGFE("Failed to convert prop to jsObject");
700         return NapiGetUndefined(env);
701     }
702     if (cutoutInfo == nullptr) {
703         WLOGFE("Get null cutout info");
704         return NapiGetUndefined(env);
705     }
706     std::vector<DMRect> boundingRects = cutoutInfo->GetBoundingRects();
707     WaterfallDisplayAreaRects waterfallDisplayAreaRects = cutoutInfo->GetWaterfallDisplayAreaRects();
708     napi_set_named_property(env, objValue, "boundingRects", CreateJsBoundingRectsArrayObject(env, boundingRects));
709     napi_set_named_property(env, objValue, "waterfallDisplayAreaRects",
710         CreateJsWaterfallDisplayAreaRectsObject(env, waterfallDisplayAreaRects));
711     return objValue;
712 }
713 
CreateJsDisplayPhysicalInfoObject(napi_env env, DisplayPhysicalResolution physicalInfo)714 napi_value CreateJsDisplayPhysicalInfoObject(napi_env env, DisplayPhysicalResolution physicalInfo)
715 {
716     napi_value objValue = nullptr;
717     napi_create_object(env, &objValue);
718     napi_set_named_property(env, objValue, "foldDisplayMode", CreateJsValue(env, physicalInfo.foldDisplayMode_));
719     napi_set_named_property(env, objValue, "physicalWidth", CreateJsValue(env, physicalInfo.physicalWidth_));
720     napi_set_named_property(env, objValue, "physicalHeight", CreateJsValue(env, physicalInfo.physicalHeight_));
721     return objValue;
722 }
723 
CreateJsRectObject(napi_env env, DMRect rect)724 napi_value CreateJsRectObject(napi_env env, DMRect rect)
725 {
726     napi_value objValue = nullptr;
727     napi_create_object(env, &objValue);
728     napi_set_named_property(env, objValue, "left", CreateJsValue(env, rect.posX_));
729     napi_set_named_property(env, objValue, "top", CreateJsValue(env, rect.posY_));
730     napi_set_named_property(env, objValue, "width", CreateJsValue(env, rect.width_));
731     napi_set_named_property(env, objValue, "height", CreateJsValue(env, rect.height_));
732     return objValue;
733 }
734 
CreateJsWaterfallDisplayAreaRectsObject(napi_env env, WaterfallDisplayAreaRects waterfallDisplayAreaRects)735 napi_value CreateJsWaterfallDisplayAreaRectsObject(napi_env env,
736     WaterfallDisplayAreaRects waterfallDisplayAreaRects)
737 {
738     napi_value objValue = nullptr;
739     napi_create_object(env, &objValue);
740     napi_set_named_property(env, objValue, "left", CreateJsRectObject(env, waterfallDisplayAreaRects.left));
741     napi_set_named_property(env, objValue, "top", CreateJsRectObject(env, waterfallDisplayAreaRects.top));
742     napi_set_named_property(env, objValue, "right", CreateJsRectObject(env, waterfallDisplayAreaRects.right));
743     napi_set_named_property(env, objValue, "bottom", CreateJsRectObject(env, waterfallDisplayAreaRects.bottom));
744     return objValue;
745 }
746 
CreateJsBoundingRectsArrayObject(napi_env env, std::vector<DMRect> boundingRects)747 napi_value CreateJsBoundingRectsArrayObject(napi_env env, std::vector<DMRect> boundingRects)
748 {
749     napi_value arrayValue = nullptr;
750     napi_create_array_with_length(env, boundingRects.size(), &arrayValue);
751     size_t i = 0;
752     for (const auto& rect : boundingRects) {
753         napi_set_element(env, arrayValue, i++, CreateJsRectObject(env, rect));
754     }
755     return arrayValue;
756 }
757 
NapiSetNamedProperty(napi_env env, napi_value objValue, sptr<DisplayInfo> info)758 void NapiSetNamedProperty(napi_env env, napi_value objValue, sptr<DisplayInfo> info)
759 {
760     napi_set_named_property(env, objValue, "id", CreateJsValue(env, static_cast<uint32_t>(info->GetDisplayId())));
761     napi_set_named_property(env, objValue, "name", CreateJsValue(env, info->GetName()));
762     napi_set_named_property(env, objValue, "alive", CreateJsValue(env, info->GetAliveStatus()));
763     if (NATIVE_TO_JS_DISPLAY_STATE_MAP.count(info->GetDisplayState()) != 0) {
764         napi_set_named_property(env, objValue, "state",
765             CreateJsValue(env, NATIVE_TO_JS_DISPLAY_STATE_MAP.at(info->GetDisplayState())));
766     } else {
767         napi_set_named_property(env, objValue, "state", CreateJsValue(env, DisplayStateMode::STATE_UNKNOWN));
768     }
769     napi_set_named_property(env, objValue, "refreshRate", CreateJsValue(env, info->GetRefreshRate()));
770     napi_set_named_property(env, objValue, "rotation", CreateJsValue(env, info->GetRotation()));
771     napi_set_named_property(env, objValue, "width", CreateJsValue(env, info->GetWidth()));
772     napi_set_named_property(env, objValue, "height", CreateJsValue(env, info->GetHeight()));
773     napi_set_named_property(env, objValue, "densityDPI",
774         CreateJsValue(env, info->GetVirtualPixelRatio() * DOT_PER_INCH));
775     napi_set_named_property(env, objValue, "orientation", CreateJsValue(env, info->GetDisplayOrientation()));
776     napi_set_named_property(env, objValue, "densityPixels", CreateJsValue(env, info->GetVirtualPixelRatio()));
777     napi_set_named_property(env, objValue, "scaledDensity", CreateJsValue(env, info->GetVirtualPixelRatio()));
778     napi_set_named_property(env, objValue, "xDPI", CreateJsValue(env, info->GetXDpi()));
779     napi_set_named_property(env, objValue, "yDPI", CreateJsValue(env, info->GetYDpi()));
780     napi_set_named_property(env, objValue, "colorSpaces", CreateJsColorSpaceArray(env, info->GetColorSpaces()));
781     napi_set_named_property(env, objValue, "hdrFormats", CreateJsHDRFormatArray(env, info->GetHdrFormats()));
782     napi_set_named_property(env, objValue, "availableWidth", CreateJsValue(env, info->GetAvailableWidth()));
783     napi_set_named_property(env, objValue, "availableHeight", CreateJsValue(env, info->GetAvailableHeight()));
784 }
785 
CreateJsDisplayObject(napi_env env, sptr<Display>& display)786 napi_value CreateJsDisplayObject(napi_env env, sptr<Display>& display)
787 {
788     WLOGD("CreateJsDisplay is called");
789     napi_value objValue = nullptr;
790     std::shared_ptr<NativeReference> jsDisplayObj = FindJsDisplayObject(display->GetId());
791     if (jsDisplayObj != nullptr && jsDisplayObj->GetNapiValue() != nullptr) {
792         WLOGD("[NAPI]FindJsDisplayObject %{public}" PRIu64"", display->GetId());
793         objValue = jsDisplayObj->GetNapiValue();
794     }
795     if (objValue == nullptr) {
796         napi_create_object(env, &objValue);
797     }
798     if (objValue == nullptr) {
799         WLOGFE("Failed to get jsObject");
800         return NapiGetUndefined(env);
801     }
802     auto info = display->GetDisplayInfoByJs();
803     if (info == nullptr) {
804         WLOGFE("Failed to GetDisplayInfo");
805         return NapiGetUndefined(env);
806     }
807 
808     NapiSetNamedProperty(env, objValue, info);
809 
810     if (jsDisplayObj == nullptr || jsDisplayObj->GetNapiValue() == nullptr) {
811         std::unique_ptr<JsDisplay> jsDisplay = std::make_unique<JsDisplay>(display);
812         napi_wrap(env, objValue, jsDisplay.release(), JsDisplay::Finalizer, nullptr, nullptr);
813         BindNativeFunction(env, objValue, "getCutoutInfo", "JsDisplay", JsDisplay::GetCutoutInfo);
814         BindNativeFunction(env, objValue, "hasImmersiveWindow", "JsDisplay", JsDisplay::HasImmersiveWindow);
815         BindNativeFunction(env, objValue, "getSupportedColorSpaces", "JsDisplay", JsDisplay::GetSupportedColorSpaces);
816         BindNativeFunction(env, objValue, "getSupportedHDRFormats", "JsDisplay", JsDisplay::GetSupportedHDRFormats);
817         BindNativeFunction(env, objValue, "getAvailableArea", "JsDisplay", JsDisplay::GetAvailableArea);
818         BindNativeFunction(env, objValue, "on", "JsDisplay", JsDisplay::RegisterDisplayManagerCallback);
819         BindNativeFunction(env, objValue, "off", "JsDisplay", JsDisplay::UnregisterDisplayManagerCallback);
820         std::shared_ptr<NativeReference> jsDisplayRef;
821         napi_ref result = nullptr;
822         napi_create_reference(env, objValue, 1, &result);
823         jsDisplayRef.reset(reinterpret_cast<NativeReference*>(result));
824         DisplayId displayId = display->GetId();
825         std::lock_guard<std::recursive_mutex> lock(g_mutex);
826         g_JsDisplayMap[displayId] = jsDisplayRef;
827     }
828     return objValue;
829 }
830 }  // namespace Rosen
831 }  // namespace OHOS
832