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 #ifndef OHOS_NAPI_UV_QUEUE_H
17 #define OHOS_NAPI_UV_QUEUE_H
18 
19 #include <chrono>
20 #include <functional>
21 #include <semaphore.h>
22 #include "avsession_log.h"
23 #include "napi/native_api.h"
24 #include "napi/native_common.h"
25 #include "napi/native_node_api.h"
26 #include "uv.h"
27 
28 namespace OHOS::AVSession {
29 class NapiAsyncCallback final {
30 public:
31     using NapiArgsGetter = std::function<void(napi_env env, int& argc, napi_value* argv)>;
32 
33     explicit NapiAsyncCallback(napi_env env);
34     ~NapiAsyncCallback();
35 
36     napi_env GetEnv() const;
37 
38     void Call(napi_ref& method, NapiArgsGetter getter = NapiArgsGetter());
39 
40     void CallWithFlag(napi_ref& method, std::shared_ptr<bool> isValid, NapiArgsGetter getter = NapiArgsGetter());
41 
42     void CallWithFunc(napi_ref& method, std::shared_ptr<bool> isValid,
43         const std::function<bool()>& checkCallbackValid,
44         NapiArgsGetter getter = NapiArgsGetter());
45 
46 private:
47     static void AfterWorkCallback(uv_work_t* work, int aStatus);
48 
49     static void AfterWorkCallbackWithFlag(uv_work_t* work, int aStatus);
50 
51     static void AfterWorkCallbackWithFunc(uv_work_t* work, int aStatus);
52 
53     struct DataContext {
54         napi_env env;
55         napi_ref& method;
56         NapiArgsGetter getter;
57     };
58     struct DataContextWithFlag {
59         napi_env env;
60         napi_ref& method;
61         std::shared_ptr<bool> isValid;
62         NapiArgsGetter getter;
63     };
64     struct DataContextWithFunc {
65         napi_env env;
66         napi_ref& method;
67         std::shared_ptr<bool> isValid;
68         NapiArgsGetter getter;
69         std::function<bool()> checkCallbackValid;
70     };
71 
72     napi_env env_ = nullptr;
73     uv_loop_s* loop_ = nullptr;
74     uv_loop_s* loopOrder_ = nullptr;
75     sem_t semaphore_ = {};
76 
77     static constexpr size_t ARGC_MAX = 6;
78 };
79 } // namespace OHOS::AVSession
80 #endif