1 /*
2 * Copyright (c) 2021-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 BASE_EVENTHANDLER_FRAMEWORKS_NAPI_INCLUDE_JS_EMITTER_H
17 #define BASE_EVENTHANDLER_FRAMEWORKS_NAPI_INCLUDE_JS_EMITTER_H
18
19 #include <map>
20 #include <memory>
21 #include <string>
22 #include <vector>
23
24 #include "event_handler.h"
25 #include "event_runner.h"
26 #include "event_queue.h"
27 #include "inner_event.h"
28 #include "napi/native_api.h"
29 #include "napi/native_node_api.h"
30
31 namespace OHOS {
32 namespace AppExecFwk {
33 using Priority = EventQueue::Priority;
34 static const int32_t ARGC_NUM = 2;
35 static const int32_t NAPI_VALUE_STRING_LEN = 10240;
36 class EventHandlerInstance : public EventHandler {
37 public:
38 EventHandlerInstance(const std::shared_ptr<EventRunner>& runner);
39 static std::shared_ptr<EventHandlerInstance> GetInstance();
40 ~EventHandlerInstance();
41 void ProcessEvent(const InnerEvent::Pointer& event) override;
42 napi_env deleteEnv = nullptr;
43 };
44
45 enum class DataType: uint32_t {
46 BOOL = 0,
47 INT,
48 STRING,
49 };
50
51 struct Val {
52 DataType type;
53
54 union {
55 bool bValue;
56 int32_t nValue;
57 char cValue[NAPI_VALUE_STRING_LEN] = {0};
58 } value;
59 };
60
61 struct AsyncCallbackInfo {
62 std::atomic<napi_env> env;
63 std::atomic<bool> once = false;
64 std::atomic<bool> isDeleted = false;
65 napi_ref callback = 0;
66 napi_threadsafe_function tsfn = nullptr;
67 InnerEvent::EventId eventId;
68 ~AsyncCallbackInfo();
69 };
70
71 using EventData = std::shared_ptr<napi_value>;
72 struct EventDataWorker {
73 EventData data;
74 std::shared_ptr<AsyncCallbackInfo> callbackInfo;
75 };
76
77 napi_value EmitterInit(napi_env env, napi_value exports);
78 napi_value JS_On(napi_env env, napi_callback_info cbinfo);
79 napi_value JS_Off(napi_env env, napi_callback_info cbinfo);
80 napi_value JS_Once(napi_env env, napi_callback_info cbinfo);
81 napi_value JS_Emit(napi_env env, napi_callback_info cbinfo);
82
GetNapiType(napi_env env,napi_value param)83 static inline napi_valuetype GetNapiType(napi_env env, napi_value param)
84 {
85 napi_valuetype type;
86 napi_typeof(env, param, &type);
87 return type;
88 }
89 } // namespace AppExecFwk
90 } // namespace OHOS
91
92 #endif // BASE_EVENTHANDLER_FRAMEWORKS_NAPI_INCLUDE_JS_EMITTER_H
93