1 /* 2 * Copyright (c) 2024-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 LISTENER_BASE_H_ 17 #define LISTENER_BASE_H_ 18 19 #include <list> 20 #include <memory> 21 #include <mutex> 22 #include <unordered_map> 23 24 #include "camera_napi_auto_ref.h" 25 #include "camera_napi_utils.h" 26 namespace OHOS { 27 namespace CameraStandard { 28 class ListenerBase { 29 public: 30 explicit ListenerBase(napi_env env); 31 virtual ~ListenerBase(); 32 33 struct ExecuteCallbackNapiPara { 34 napi_value recv; 35 size_t argc; 36 const napi_value* argv; 37 napi_value* result; 38 }; 39 virtual void SaveCallbackReference(const std::string eventName, napi_value callback, bool isOnce) final; 40 virtual void ExecuteCallback(const std::string eventName, const ExecuteCallbackNapiPara& callbackPara) const final; 41 virtual void RemoveCallbackRef(const std::string eventName, napi_value callback) final; 42 virtual void RemoveAllCallbacks(const std::string eventName) final; 43 virtual bool IsEmpty(const std::string eventName) const final; 44 45 protected: 46 napi_env env_ = nullptr; 47 48 private: 49 struct CallbackList { 50 std::mutex listMutex; 51 std::list<AutoRef> refList; 52 }; 53 GetCallbackList(const std::string eventName)54 inline CallbackList& GetCallbackList(const std::string eventName) const 55 { 56 std::lock_guard<std::mutex> lock(namedCallbackMapMutex_); 57 auto it = namedCallbackMap_.find(eventName); 58 if (it == namedCallbackMap_.end()) { 59 auto callbackList = std::make_shared<CallbackList>(); 60 namedCallbackMap_.emplace(eventName, callbackList); 61 return *callbackList; 62 } 63 return *it->second; 64 } 65 66 mutable std::mutex namedCallbackMapMutex_; 67 mutable std::unordered_map<std::string, std::shared_ptr<CallbackList>> namedCallbackMap_; 68 }; 69 } // namespace CameraStandard 70 } // namespace OHOS 71 #endif /* LISTENER_BASE_H_ */ 72