• 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 COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H
17 #define COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H
18 
19 #include <atomic>
20 #include <list>
21 #include <shared_mutex>
22 
23 #include <uv.h>
24 
25 #include "event_listener.h"
26 #include "napi_utils.h"
27 
28 namespace OHOS {
29 namespace NetManagerStandard {
30 class EventManager : public std::enable_shared_from_this<EventManager> {
31 public:
32     EventManager();
33 
34     void AddListener(napi_env env, const std::string &type, napi_value callback, bool once, bool asyncCallback);
35     void DeleteListener(const std::string &type, napi_value callback);
36     void Emit(const std::string &type, const std::pair<napi_value, napi_value> &argv);
37     void SetData(void *data);
38     void EmitByUv(const std::string &type, void *data, void(handler)(uv_work_t *, int status));
39     void EmitByUvWithModuleId(const std::string &type, const NapiUtils::UvHandler &handler, uint64_t moduleId);
40     bool HasEventListener(const std::string &type);
41     void DeleteListener(const std::string &type);
42     void DeleteAllListener();
43     [[nodiscard]] void *GetData();
44 
IsListenerListEmpty()45     bool IsListenerListEmpty() const
46     {
47         return listeners_.empty();
48     }
49 
GetListenerListNum()50     size_t GetListenerListNum() const
51     {
52         return listeners_.size();
53     }
54 
55     napi_ref GetRef() const;
56     void SetRef(napi_ref ref);
57 
58 private:
59     std::shared_mutex mutexForListenersAndEmitByUv_;
60     std::mutex mutexForEmitAndEmitByUv_;
61     std::list<EventListener> listeners_;
62     void *data_ = nullptr;
63     napi_ref ref_ = nullptr;
64 };
65 
66 struct UvWorkWrapper {
67     UvWorkWrapper() = delete;
68     explicit UvWorkWrapper(void *theData, napi_env theEnv, std::string eventType,
69         std::shared_ptr<EventManager> eventManager);
70     void *data;
71     napi_env env;
72     std::string type;
73     std::shared_ptr<EventManager> manager{ nullptr };
74 };
75 } // namespace NetManagerStandard
76 } // namespace OHOS
77 #endif // COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H
78