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 <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 { 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() const45 bool IsListenerListEmpty() const 46 { 47 return listeners_.empty(); 48 } 49 GetListenerListNum() const50 size_t GetListenerListNum() const 51 { 52 return listeners_.size(); 53 } 54 bool IsValid() const; 55 void SetInvalid(); 56 57 napi_ref GetRef() const; 58 void SetRef(napi_ref ref); 59 60 private: 61 std::mutex mutexForListenersAndEmitByUv_; 62 std::mutex mutexForEmitAndEmitByUv_; 63 std::mutex mutex_; 64 std::list<EventListener> listeners_; 65 void *data_ = nullptr; 66 std::atomic_bool isValid_; 67 napi_ref ref_ = nullptr; 68 }; 69 70 struct UvWorkWrapper { 71 UvWorkWrapper() = delete; 72 explicit UvWorkWrapper(void *theData, napi_env theEnv, std::string eventType, EventManager *eventManager); 73 void *data; 74 napi_env env; 75 std::string type; 76 EventManager *manager; 77 }; 78 } // namespace NetManagerStandard 79 } // namespace OHOS 80 #endif // COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H 81