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 #ifndef PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_TIMER_MODULE_H 17 #define PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_TIMER_MODULE_H 18 19 #include <uv.h> 20 #include <node_api.h> 21 #include <unordered_map> 22 #include <sys/types.h> 23 #include "libpandabase/macros.h" 24 #include "plugins/ets/runtime/napi/ets_napi.h" 25 26 class TimerModule { 27 public: 28 static bool Init(EtsEnv *env, napi_env jsEnv); 29 static ets_int StartTimer(EtsEnv *env, ets_class klass, ets_object funcObject, ets_int delayMs, 30 ets_boolean oneShotTimer); 31 static void StopTimer(EtsEnv *env, ets_class klass, ets_int timerId); 32 33 private: 34 class TimerInfo { 35 public: 36 TimerInfo(uint32_t id, ets_object funcObject, bool oneShotTimer); 37 ~TimerInfo() = default; 38 GetId()39 uint32_t GetId() const 40 { 41 return id_; 42 } 43 GetFuncObject()44 ets_object GetFuncObject() const 45 { 46 return funcObject_; 47 } 48 IsOneShotTimer()49 bool IsOneShotTimer() const 50 { 51 return oneShotTimer_; 52 } 53 54 private: 55 uint32_t id_; 56 ets_object funcObject_; 57 bool oneShotTimer_; 58 59 NO_COPY_SEMANTIC(TimerInfo); 60 NO_MOVE_SEMANTIC(TimerInfo); 61 }; 62 63 static void TimerCallback(uv_timer_t *timer); 64 static void DisarmTimer(uv_timer_t *timer); 65 static void FreeTimer(uv_handle_t *timer); 66 static uv_loop_t *GetMainEventLoop(); 67 static uint32_t GetTimerId(); 68 static bool CheckMainThread(EtsEnv *env); 69 70 static pid_t mainTid_; 71 static EtsEnv *mainEtsEnv_; 72 static napi_env jsEnv_; 73 static std::unordered_map<uint32_t, uv_timer_t *> timers_; 74 static uint32_t nextTimerId_; 75 }; 76 77 #endif // PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_TIMER_MODULE_H 78