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