1 /* 2 * Copyright (c) 2021-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 #ifndef MSG_HANDLER_H 16 #define MSG_HANDLER_H 17 18 #include <functional> 19 #include <map> 20 #include <string> 21 22 #include "proto.h" 23 24 namespace OHOS { 25 namespace MMI { 26 template<typename K, typename V> 27 class MsgHandler { 28 public: Clear()29 void Clear() 30 { 31 callbacks_.clear(); 32 } ChkKey(K id)33 bool ChkKey(K id) 34 { 35 return (GetMsgCallback(id) != nullptr); 36 } 37 GetDebugInfo()38 const std::string& GetDebugInfo() const 39 { 40 std::string str; 41 for (auto &it : callbacks_) { 42 str += std::to_string(it.first); 43 str += ','; 44 } 45 if (str.size() > 0) { 46 str.resize(str.size() - 1); 47 } 48 return std::move(str); 49 } 50 51 protected: 52 struct MsgCallback { 53 K id; 54 V fun; 55 }; 56 57 protected: 58 virtual ~MsgHandler() = default; GetMsgCallback(K id)59 V *GetMsgCallback(K id) 60 { 61 auto it = callbacks_.find(id); 62 if (it == callbacks_.end()) { 63 return nullptr; 64 } 65 return &it->second; 66 } RegistrationEvent(MsgCallback & msg)67 bool RegistrationEvent(MsgCallback& msg) 68 { 69 auto it = callbacks_.find(msg.id); 70 if (it != callbacks_.end()) { 71 return false; 72 } 73 callbacks_[msg.id] = msg.fun; 74 return true; 75 } 76 77 protected: 78 std::map<K, V> callbacks_; 79 }; 80 } // namespace MMI 81 } // namespace OHOS 82 #endif // MSG_HANDLER_H 83