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         WLOGFE("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     NapiAsyncTask::CompleteCallback complete =
471         [this](napi_env env, NapiAsyncTask& task, int32_t status) {
472             DMRect area;
473             DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetAvailableArea(area));
474             if (ret == DmErrorCode::DM_OK) {
475                 task.Resolve(env, CreateJsRectObject(env, area));
476                 WLOGI("JsDisplay::OnGetAvailableArea success");
477             } else {
478                 task.Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
479                     "JsDisplay::OnGetAvailableArea failed."));
480             }
481         };
482     size_t argc = 4;
483     napi_value argv[4] = {nullptr};
484     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
485     napi_value lastParam = nullptr;
486     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
487         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
488         lastParam = argv[ARGC_ONE - 1];
489     }
490     napi_value result = nullptr;
491     NapiAsyncTask::Schedule("JsDisplay::OnGetAvailableArea",
492         env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result));
493     return result;
494 }
495 
OnHasImmersiveWindow(napi_env env,napi_callback_info info)496 napi_value JsDisplay::OnHasImmersiveWindow(napi_env env, napi_callback_info info)
497 {
498     WLOGI("OnHasImmersiveWindow is called");
499     NapiAsyncTask::CompleteCallback complete =
500         [this](napi_env env, NapiAsyncTask& task, int32_t status) {
501             bool immersive = false;
502             DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->HasImmersiveWindow(immersive));
503             if (ret == DmErrorCode::DM_OK) {
504                 task.Resolve(env, CreateJsValue(env, immersive));
505                 WLOGI("JsDisplay::OnHasImmersiveWindow success - immersive window exists: %{public}d", immersive);
506             } else {
507                 task.Reject(env, CreateJsError(env,
508                     static_cast<int32_t>(ret), "JsDisplay::OnHasImmersiveWindow failed."));
509             }
510         };
511     size_t argc = 4;
512     napi_value argv[4] = {nullptr};
513     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
514     napi_value lastParam = nullptr;
515     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
516         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
517         lastParam = argv[ARGC_ONE - 1];
518     }
519     napi_value result = nullptr;
520     NapiAsyncTask::Schedule("JsDisplay::OnHasImmersiveWindow",
521         env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result));
522     return result;
523 }
524 
GetSupportedColorSpaces(napi_env env,napi_callback_info info)525 napi_value JsDisplay::GetSupportedColorSpaces(napi_env env, napi_callback_info info)
526 {
527     WLOGI("GetSupportedColorSpaces is called");
528     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
529     return (me != nullptr) ? me->OnGetSupportedColorSpaces(env, info) : nullptr;
530 }
531 
CreateJsColorSpaceArray(napi_env env,const std::vector<uint32_t> & colorSpaces)532 static napi_value CreateJsColorSpaceArray(napi_env env, const std::vector<uint32_t>& colorSpaces)
533 {
534     WLOGD("JsDisplay::CreateJsColorSpaceArray is called");
535     std::set<uint32_t> nativeColorSpaces;
536     for (const auto colorSpace : colorSpaces) {
537         GraphicCM_ColorSpaceType colorSpaceValue = static_cast<GraphicCM_ColorSpaceType>(colorSpace);
538         if (NATIVE_TO_JS_COLOR_SPACE_TYPE_MAP.count(colorSpaceValue) == 0) {
539             WLOGFE("Get color space name %{public}u, but not in api type", colorSpace);
540             napi_throw(env, CreateJsError(env, static_cast<int32_t>(DMError::DM_ERROR_DEVICE_NOT_SUPPORT)));
541             return NapiGetUndefined(env);
542         }
543         nativeColorSpaces.insert(static_cast<uint32_t>(NATIVE_TO_JS_COLOR_SPACE_TYPE_MAP.at(colorSpaceValue)));
544     }
545     napi_value arrayValue = nullptr;
546     napi_create_array_with_length(env, nativeColorSpaces.size(), &arrayValue);
547     if (arrayValue == nullptr) {
548         WLOGFE("Failed to create color space array");
549         return NapiGetUndefined(env);
550     }
551     uint32_t index = 0;
552     for (const auto nativeColorSpace : nativeColorSpaces) {
553         napi_set_element(env, arrayValue, index++, CreateJsValue(env, nativeColorSpace));
554     }
555     return arrayValue;
556 }
557 
OnGetSupportedColorSpaces(napi_env env,napi_callback_info info)558 napi_value JsDisplay::OnGetSupportedColorSpaces(napi_env env, napi_callback_info info)
559 {
560     WLOGI("OnGetSupportedColorSpaces is called");
561     NapiAsyncTask::CompleteCallback complete =
562         [=](napi_env env, NapiAsyncTask& task, int32_t status) {
563             std::vector<uint32_t> colorSpaces;
564             DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetSupportedColorSpaces(colorSpaces));
565             if (ret == DmErrorCode::DM_OK) {
566                 task.Resolve(env, CreateJsColorSpaceArray(env, colorSpaces));
567                 WLOGI("OnGetSupportedColorSpaces success");
568             } else {
569                 task.Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
570                                                "JsDisplay::OnGetSupportedColorSpaces failed."));
571                 WLOGFE("OnGetSupportedColorSpaces failed");
572             }
573         };
574     size_t argc = 4;
575     napi_value argv[4] = {nullptr};
576     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
577     napi_value lastParam = nullptr;
578     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
579         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
580         lastParam = argv[ARGC_ONE - 1];
581     }
582     napi_value result = nullptr;
583     NapiAsyncTask::Schedule("JsDisplay::OnGetSupportedColorSpaces",
584         env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result));
585     return result;
586 }
587 
GetSupportedHDRFormats(napi_env env,napi_callback_info info)588 napi_value JsDisplay::GetSupportedHDRFormats(napi_env env, napi_callback_info info)
589 {
590     WLOGI("GetSupportedHDRFormats is called");
591     JsDisplay* me = CheckParamsAndGetThis<JsDisplay>(env, info);
592     return (me != nullptr) ? me->OnGetSupportedHDRFormats(env, info) : nullptr;
593 }
594 
CreateJsHDRFormatArray(napi_env env,const std::vector<uint32_t> & hdrFormats)595 static napi_value CreateJsHDRFormatArray(napi_env env, const std::vector<uint32_t>& hdrFormats)
596 {
597     WLOGD("JsDisplay::CreateJsHDRFormatArray is called");
598     std::set<uint32_t> nativeHDRFormats;
599     for (const auto hdrFormat : hdrFormats) {
600         ScreenHDRFormat hdrFormatValue = static_cast<ScreenHDRFormat>(hdrFormat);
601         if (NATIVE_TO_JS_HDR_FORMAT_TYPE_MAP.count(hdrFormatValue) == 0) {
602             WLOGFE("Get HDR format name %{public}u, but not in api type", hdrFormat);
603             napi_throw(env, CreateJsError(env, static_cast<int32_t>(DMError::DM_ERROR_DEVICE_NOT_SUPPORT)));
604             return NapiGetUndefined(env);
605         }
606         nativeHDRFormats.insert(static_cast<uint32_t>(NATIVE_TO_JS_HDR_FORMAT_TYPE_MAP.at(hdrFormatValue)));
607     }
608     napi_value arrayValue = nullptr;
609     napi_create_array_with_length(env, hdrFormats.size(), &arrayValue);
610     if (arrayValue == nullptr) {
611         WLOGFE("Failed to create HDR format array");
612         return NapiGetUndefined(env);
613     }
614     uint32_t index = 0;
615     for (const auto nativeHDRFormat : nativeHDRFormats) {
616         napi_set_element(env, arrayValue, index++, CreateJsValue(env, nativeHDRFormat));
617     }
618     return arrayValue;
619 }
620 
OnGetSupportedHDRFormats(napi_env env,napi_callback_info info)621 napi_value JsDisplay::OnGetSupportedHDRFormats(napi_env env, napi_callback_info info)
622 {
623     WLOGI("OnGetSupportedHDRFormats is called");
624     NapiAsyncTask::CompleteCallback complete =
625         [=](napi_env env, NapiAsyncTask& task, int32_t status) {
626             std::vector<uint32_t> hdrFormats;
627             DmErrorCode ret = DM_JS_TO_ERROR_CODE_MAP.at(display_->GetSupportedHDRFormats(hdrFormats));
628             if (ret == DmErrorCode::DM_OK) {
629                 task.Resolve(env, CreateJsHDRFormatArray(env, hdrFormats));
630                 WLOGI("OnGetSupportedHDRFormats success");
631             } else {
632                 task.Reject(env, CreateJsError(env, static_cast<int32_t>(ret),
633                                                "JsDisplay::OnGetSupportedHDRFormats failed."));
634                 WLOGFE("OnGetSupportedHDRFormats failed");
635             }
636         };
637     size_t argc = 4;
638     napi_value argv[4] = {nullptr};
639     napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
640     napi_value lastParam = nullptr;
641     if (argc >= ARGC_ONE && argv[ARGC_ONE - 1] != nullptr &&
642         GetType(env, argv[ARGC_ONE - 1]) == napi_function) {
643         lastParam = argv[ARGC_ONE - 1];
644     }
645     napi_value result = nullptr;
646     NapiAsyncTask::Schedule("JsDisplay::OnGetSupportedHDRFormats",
647         env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result));
648     return result;
649 }
650 
FindJsDisplayObject(DisplayId displayId)651 std::shared_ptr<NativeReference> FindJsDisplayObject(DisplayId displayId)
652 {
653     WLOGD("[NAPI]Try to find display %{public}" PRIu64" in g_JsDisplayMap", displayId);
654     std::lock_guard<std::recursive_mutex> lock(g_mutex);
655     if (g_JsDisplayMap.find(displayId) == g_JsDisplayMap.end()) {
656         WLOGD("[NAPI]Can not find display %{public}" PRIu64" in g_JsDisplayMap", displayId);
657         return nullptr;
658     }
659     return g_JsDisplayMap[displayId];
660 }
661 
NapiGetUndefined(napi_env env)662 napi_value NapiGetUndefined(napi_env env)
663 {
664     napi_value result = nullptr;
665     napi_get_undefined(env, &result);
666     return result;
667 }
668 
CreateJsCutoutInfoObject(napi_env env,sptr<CutoutInfo> cutoutInfo)669 napi_value CreateJsCutoutInfoObject(napi_env env, sptr<CutoutInfo> cutoutInfo)
670 {
671     WLOGD("JsDisplay::CreateJsCutoutInfoObject is called");
672     napi_value objValue = nullptr;
673     napi_create_object(env, &objValue);
674     if (objValue == nullptr) {
675         WLOGFE("Failed to convert prop to jsObject");
676         return NapiGetUndefined(env);
677     }
678     if (cutoutInfo == nullptr) {
679         WLOGFE("Get null cutout info");
680         return NapiGetUndefined(env);
681     }
682     std::vector<DMRect> boundingRects = cutoutInfo->GetBoundingRects();
683     WaterfallDisplayAreaRects waterfallDisplayAreaRects = cutoutInfo->GetWaterfallDisplayAreaRects();
684     napi_set_named_property(env, objValue, "boundingRects", CreateJsBoundingRectsArrayObject(env, boundingRects));
685     napi_set_named_property(env, objValue, "waterfallDisplayAreaRects",
686         CreateJsWaterfallDisplayAreaRectsObject(env, waterfallDisplayAreaRects));
687     return objValue;
688 }
689 
CreateJsDisplayPhysicalInfoObject(napi_env env,DisplayPhysicalResolution physicalInfo)690 napi_value CreateJsDisplayPhysicalInfoObject(napi_env env, DisplayPhysicalResolution physicalInfo)
691 {
692     napi_value objValue = nullptr;
693     napi_create_object(env, &objValue);
694     napi_set_named_property(env, objValue, "foldDisplayMode", CreateJsValue(env, physicalInfo.foldDisplayMode_));
695     napi_set_named_property(env, objValue, "physicalWidth", CreateJsValue(env, physicalInfo.physicalWidth_));
696     napi_set_named_property(env, objValue, "physicalHeight", CreateJsValue(env, physicalInfo.physicalHeight_));
697     return objValue;
698 }
699 
CreateJsRectObject(napi_env env,DMRect rect)700 napi_value CreateJsRectObject(napi_env env, DMRect rect)
701 {
702     napi_value objValue = nullptr;
703     napi_create_object(env, &objValue);
704     napi_set_named_property(env, objValue, "left", CreateJsValue(env, rect.posX_));
705     napi_set_named_property(env, objValue, "top", CreateJsValue(env, rect.posY_));
706     napi_set_named_property(env, objValue, "width", CreateJsValue(env, rect.width_));
707     napi_set_named_property(env, objValue, "height", CreateJsValue(env, rect.height_));
708     return objValue;
709 }
710 
CreateJsWaterfallDisplayAreaRectsObject(napi_env env,WaterfallDisplayAreaRects waterfallDisplayAreaRects)711 napi_value CreateJsWaterfallDisplayAreaRectsObject(napi_env env,
712     WaterfallDisplayAreaRects waterfallDisplayAreaRects)
713 {
714     napi_value objValue = nullptr;
715     napi_create_object(env, &objValue);
716     napi_set_named_property(env, objValue, "left", CreateJsRectObject(env, waterfallDisplayAreaRects.left));
717     napi_set_named_property(env, objValue, "top", CreateJsRectObject(env, waterfallDisplayAreaRects.top));
718     napi_set_named_property(env, objValue, "right", CreateJsRectObject(env, waterfallDisplayAreaRects.right));
719     napi_set_named_property(env, objValue, "bottom", CreateJsRectObject(env, waterfallDisplayAreaRects.bottom));
720     return objValue;
721 }
722 
CreateJsBoundingRectsArrayObject(napi_env env,std::vector<DMRect> boundingRects)723 napi_value CreateJsBoundingRectsArrayObject(napi_env env, std::vector<DMRect> boundingRects)
724 {
725     napi_value arrayValue = nullptr;
726     napi_create_array_with_length(env, boundingRects.size(), &arrayValue);
727     size_t i = 0;
728     for (const auto& rect : boundingRects) {
729         napi_set_element(env, arrayValue, i++, CreateJsRectObject(env, rect));
730     }
731     return arrayValue;
732 }
733 
NapiSetNamedProperty(napi_env env,napi_value objValue,sptr<DisplayInfo> info)734 void NapiSetNamedProperty(napi_env env, napi_value objValue, sptr<DisplayInfo> info)
735 {
736     napi_set_named_property(env, objValue, "id", CreateJsValue(env, static_cast<uint32_t>(info->GetDisplayId())));
737     napi_set_named_property(env, objValue, "name", CreateJsValue(env, info->GetName()));
738     napi_set_named_property(env, objValue, "alive", CreateJsValue(env, info->GetAliveStatus()));
739     if (NATIVE_TO_JS_DISPLAY_STATE_MAP.count(info->GetDisplayState()) != 0) {
740         napi_set_named_property(env, objValue, "state",
741             CreateJsValue(env, NATIVE_TO_JS_DISPLAY_STATE_MAP.at(info->GetDisplayState())));
742     } else {
743         napi_set_named_property(env, objValue, "state", CreateJsValue(env, DisplayStateMode::STATE_UNKNOWN));
744     }
745     napi_set_named_property(env, objValue, "refreshRate", CreateJsValue(env, info->GetRefreshRate()));
746     napi_set_named_property(env, objValue, "rotation", CreateJsValue(env, info->GetRotation()));
747     napi_set_named_property(env, objValue, "width", CreateJsValue(env, info->GetWidth()));
748     napi_set_named_property(env, objValue, "height", CreateJsValue(env, info->GetHeight()));
749     napi_set_named_property(env, objValue, "densityDPI",
750         CreateJsValue(env, info->GetVirtualPixelRatio() * DOT_PER_INCH));
751     napi_set_named_property(env, objValue, "orientation", CreateJsValue(env, info->GetDisplayOrientation()));
752     napi_set_named_property(env, objValue, "densityPixels", CreateJsValue(env, info->GetVirtualPixelRatio()));
753     napi_set_named_property(env, objValue, "scaledDensity", CreateJsValue(env, info->GetVirtualPixelRatio()));
754     napi_set_named_property(env, objValue, "xDPI", CreateJsValue(env, info->GetXDpi()));
755     napi_set_named_property(env, objValue, "yDPI", CreateJsValue(env, info->GetYDpi()));
756     napi_set_named_property(env, objValue, "colorSpaces", CreateJsColorSpaceArray(env, info->GetColorSpaces()));
757     napi_set_named_property(env, objValue, "hdrFormats", CreateJsHDRFormatArray(env, info->GetHdrFormats()));
758     napi_set_named_property(env, objValue, "availableWidth", CreateJsValue(env, info->GetAvailableWidth()));
759     napi_set_named_property(env, objValue, "availableHeight", CreateJsValue(env, info->GetAvailableHeight()));
760 }
761 
CreateJsDisplayObject(napi_env env,sptr<Display> & display)762 napi_value CreateJsDisplayObject(napi_env env, sptr<Display>& display)
763 {
764     WLOGD("CreateJsDisplay is called");
765     napi_value objValue = nullptr;
766     std::shared_ptr<NativeReference> jsDisplayObj = FindJsDisplayObject(display->GetId());
767     if (jsDisplayObj != nullptr && jsDisplayObj->GetNapiValue() != nullptr) {
768         WLOGD("[NAPI]FindJsDisplayObject %{public}" PRIu64"", display->GetId());
769         objValue = jsDisplayObj->GetNapiValue();
770     }
771     if (objValue == nullptr) {
772         napi_create_object(env, &objValue);
773     }
774     if (objValue == nullptr) {
775         WLOGFE("Failed to get jsObject");
776         return NapiGetUndefined(env);
777     }
778     auto info = display->GetDisplayInfoByJs();
779     if (info == nullptr) {
780         WLOGFE("Failed to GetDisplayInfo");
781         return NapiGetUndefined(env);
782     }
783 
784     NapiSetNamedProperty(env, objValue, info);
785 
786     if (jsDisplayObj == nullptr || jsDisplayObj->GetNapiValue() == nullptr) {
787         std::unique_ptr<JsDisplay> jsDisplay = std::make_unique<JsDisplay>(display);
788         napi_wrap(env, objValue, jsDisplay.release(), JsDisplay::Finalizer, nullptr, nullptr);
789         BindNativeFunction(env, objValue, "getCutoutInfo", "JsDisplay", JsDisplay::GetCutoutInfo);
790         BindNativeFunction(env, objValue, "hasImmersiveWindow", "JsDisplay", JsDisplay::HasImmersiveWindow);
791         BindNativeFunction(env, objValue, "getAvailableArea", "JsDisplay", JsDisplay::GetAvailableArea);
792         BindNativeFunction(env, objValue, "getSupportedColorSpaces", "JsDisplay", JsDisplay::GetSupportedColorSpaces);
793         BindNativeFunction(env, objValue, "getSupportedHDRFormats", "JsDisplay", JsDisplay::GetSupportedHDRFormats);
794         BindNativeFunction(env, objValue, "on", "JsDisplay", JsDisplay::RegisterDisplayManagerCallback);
795         BindNativeFunction(env, objValue, "off", "JsDisplay", JsDisplay::UnregisterDisplayManagerCallback);
796         std::shared_ptr<NativeReference> jsDisplayRef;
797         napi_ref result = nullptr;
798         napi_create_reference(env, objValue, 1, &result);
799         jsDisplayRef.reset(reinterpret_cast<NativeReference*>(result));
800         DisplayId displayId = display->GetId();
801         std::lock_guard<std::recursive_mutex> lock(g_mutex);
802         g_JsDisplayMap[displayId] = jsDisplayRef;
803     }
804     return objValue;
805 }
806 }  // namespace Rosen
807 }  // namespace OHOS
808