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 "webview_web_inited_callback.h"
17 
18 #include "nweb_log.h"
19 #include "uv.h"
20 
21 namespace OHOS::NWeb {
22 namespace {
UvWebInitedCallbackThreadWoker(uv_work_t * work,int status)23 void UvWebInitedCallbackThreadWoker(uv_work_t *work, int status)
24 {
25     if (work == nullptr) {
26         WVLOG_E("uv work is null");
27         return;
28     }
29     WebInitedCallbackParam *data = reinterpret_cast<WebInitedCallbackParam*>(work->data);
30     if (data == nullptr) {
31         delete work;
32         work = nullptr;
33         return;
34     }
35     napi_handle_scope scope = nullptr;
36     napi_open_handle_scope(data->env_, &scope);
37     if (scope == nullptr) {
38         delete data;
39         data = nullptr;
40         delete work;
41         work = nullptr;
42         return;
43     }
44     napi_value webInitedResult = nullptr;
45     napi_value jsWebInitedCallback = nullptr;
46     napi_get_reference_value(data->env_, data->webInitedCallback_, &jsWebInitedCallback);
47     napi_call_function(data->env_, nullptr, jsWebInitedCallback, 0, {}, &webInitedResult);
48 
49     napi_close_handle_scope(data->env_, scope);
50     delete data;
51     data = nullptr;
52     delete work;
53     work = nullptr;
54 }
55 } // namespace
56 
RunInitedCallback()57 void WebRunInitedCallbackImpl::RunInitedCallback()
58 {
59     uv_loop_s *loop = nullptr;
60     uv_work_t *work = nullptr;
61     napi_get_uv_event_loop(param_->env_, &loop);
62 
63     if (loop == nullptr) {
64         WVLOG_E("get uv event loop failed");
65         return;
66     }
67     work = new (std::nothrow) uv_work_t;
68     if (work == nullptr) {
69         WVLOG_E("new uv work failed");
70         return;
71     }
72     work->data = reinterpret_cast<void*>(param_);
73     int ret = uv_queue_work_with_qos(
74         loop, work, [](uv_work_t* work) {}, UvWebInitedCallbackThreadWoker, uv_qos_user_initiated);
75     if (ret != 0) {
76         if (param_ != nullptr) {
77             delete param_;
78             param_ = nullptr;
79         }
80         if (work != nullptr) {
81             delete work;
82             work = nullptr;
83         }
84     }
85 }
86 }