1 /*
2 * Copyright (c) 2024 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 "ark_interop_internal.h"
17 #include "ark_interop_napi.h"
18 #include "ark_interop_log.h"
19
20 #include <unordered_map>
21 #include <mutex>
22
23 using namespace panda::ecmascript;
24
25 #ifdef __OHOS__
26 using namespace OHOS::AppExecFwk;
27
28 namespace {
29 std::unordered_map<ARKTS_Env, ARKTS_Loop> g_eventHandlers_;
30 std::mutex g_eventHandlerMutex_;
31 }
32 #endif
33
ARKTS_GetOrCreateEventHandler(ARKTS_Env env)34 ARKTS_Loop ARKTS_GetOrCreateEventHandler(ARKTS_Env env)
35 {
36 if (!env) {
37 return nullptr;
38 }
39 #ifdef __OHOS__
40 std::lock_guard lock(g_eventHandlerMutex_);
41 auto searchRet = g_eventHandlers_.find(env);
42 if (searchRet != g_eventHandlers_.end()) {
43 return searchRet->second;
44 }
45 auto handler = std::make_shared<EventHandler>(EventRunner::Current());
46 g_eventHandlers_[env] = handler;
47 return handler;
48 #else
49 return nullptr;
50 #endif
51 }
52
53 #ifdef __OHOS__
ARKTS_GetEventHandler(ARKTS_Env env)54 static ARKTS_Loop ARKTS_GetEventHandler(ARKTS_Env env)
55 {
56 if (!env) {
57 return nullptr;
58 }
59 std::lock_guard lock(g_eventHandlerMutex_);
60 auto searchRet = g_eventHandlers_.find(env);
61 if (searchRet != g_eventHandlers_.end()) {
62 return searchRet->second;
63 }
64 return nullptr;
65 }
66 #endif
67
ARKTS_InitEventHandle(ARKTS_Env env)68 void ARKTS_InitEventHandle(ARKTS_Env env)
69 {
70 ARKTS_ASSERT_V(env, "env is null");
71 void (ARKTS_GetOrCreateEventHandler(env));
72 }
73
ARKTS_DisposeEventHandler(ARKTS_Env env)74 void ARKTS_DisposeEventHandler(ARKTS_Env env)
75 {
76 if (!env) {
77 return;
78 }
79 #ifdef __OHOS__
80 std::lock_guard lock(g_eventHandlerMutex_);
81 g_eventHandlers_.erase(env);
82 #endif
83 }
84
ARKTSInner_CreateAsyncTask(ARKTS_Env env,ARKTS_AsyncCallback callback,void * data)85 void ARKTSInner_CreateAsyncTask(ARKTS_Env env, ARKTS_AsyncCallback callback, void* data)
86 {
87 #ifdef __OHOS__
88 auto handler = ARKTS_GetEventHandler(env);
89 if (!handler) {
90 LOGE("event handler not initialized");
91 return;
92 }
93 handler->PostTask([env, callback, data] {
94 callback(env, data);
95 });
96 #endif
97 }
98
ARKTS_CreateAsyncTask(ARKTS_Env env,int64_t callbackId)99 void ARKTS_CreateAsyncTask(ARKTS_Env env, int64_t callbackId)
100 {
101 ARKTSInner_CreateAsyncTask(env, ARKTSInner_CJAsyncCallback, reinterpret_cast<void*>(callbackId));
102 }
103