• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H
17 #define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H
18 
19 #include <mutex>
20 #include <unordered_map>
21 
22 #include "adapter/ohos/entrance/pa_engine/backend_delegate.h"
23 #include "base/thread/cancelable_callback.h"
24 #include "native_engine/native_engine.h"
25 
26 namespace OHOS::Ace {
27 struct TimerCallbackNode {
28     std::shared_ptr<NativeReference> func;
29     std::vector<std::shared_ptr<NativeReference>> params;
30     NativeEngine* engine;
31 };
32 
33 class JsBackendTimerModule final {
34 public:
35     JsBackendTimerModule() = default;
36     ~JsBackendTimerModule() = default;
37 
38     static JsBackendTimerModule* GetInstance();
39     void InitTimerModule(NativeEngine* engine, const RefPtr<BackendDelegate>& delegate);
40 
41     uint32_t AddCallBack(const std::shared_ptr<NativeReference>& func,
42         const std::vector<std::shared_ptr<NativeReference>>& params, NativeEngine* engine);
43     bool GetCallBackById(uint32_t callbackId, std::shared_ptr<NativeReference>& func,
44         std::vector<std::shared_ptr<NativeReference>>& params, NativeEngine** engine);
45     void TimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval);
46     void PostTimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval, bool isFirst, NativeEngine* engine);
47     void RemoveTimerCallback(uint32_t callbackId);
48 
49 private:
50     void AddDelegate(NativeEngine* engine, const RefPtr<BackendDelegate>& delegate);
51     RefPtr<BackendDelegate> GetDelegateWithoutLock(NativeEngine* engine);
52 
53     std::mutex mutex_;
54     uint32_t callbackId_ = 0;
55     std::unordered_map<uint32_t, TimerCallbackNode> callbackNodeMap_;
56     std::unordered_map<uint32_t, CancelableCallback<void()>> timeoutTaskMap_;
57     std::unordered_map<NativeEngine*, RefPtr<BackendDelegate>> delegateMap_;
58 };
59 } // namespace OHOS::Ace
60 
61 #endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H
62