1//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
2//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
3#include "Utility/BsMessageHandler.h"
4
5namespace bs
6{
7 Map<String, UINT32> MessageId::UniqueMessageIds;
8 UINT32 MessageId::NextMessageId = 0;
9
10 MessageId::MessageId(const String& name)
11 {
12 auto findIter = UniqueMessageIds.find(name);
13
14 if (findIter != UniqueMessageIds.end())
15 mMsgIdentifier = findIter->second;
16 else
17 {
18 mMsgIdentifier = NextMessageId;
19 UniqueMessageIds[name] = NextMessageId++;
20 }
21 }
22
23 HMessage::HMessage(UINT32 id)
24 :mId(id)
25 { }
26
27 void HMessage::disconnect()
28 {
29 if (mId > 0)
30 MessageHandler::instance().unsubscribe(mId);
31 }
32
33 void MessageHandler::send(MessageId message)
34 {
35 auto iterFind = mMessageHandlers.find(message.mMsgIdentifier);
36 if (iterFind != mMessageHandlers.end())
37 {
38 for (auto& handlerData : iterFind->second)
39 {
40 handlerData.callback();
41 }
42 }
43 }
44
45 HMessage MessageHandler::listen(MessageId message, std::function<void()> callback)
46 {
47 UINT32 callbackId = mNextCallbackId++;
48
49 MessageHandlerData data;
50 data.id = callbackId;
51 data.callback = callback;
52
53 mMessageHandlers[message.mMsgIdentifier].push_back(data);
54 mHandlerIdToMessageMap[callbackId] = message.mMsgIdentifier;
55
56 return HMessage(callbackId);
57 }
58
59 void MessageHandler::unsubscribe(UINT32 handleId)
60 {
61 UINT32 msgId = mHandlerIdToMessageMap[handleId];
62
63 auto iterFind = mMessageHandlers.find(msgId);
64 if (iterFind != mMessageHandlers.end())
65 {
66 Vector<MessageHandlerData>& handlerData = iterFind->second;
67
68 handlerData.erase(
69 std::remove_if(handlerData.begin(), handlerData.end(),
70 [&](MessageHandlerData& x)
71 {
72 return x.id == handleId;
73 }),
74 handlerData.end());
75 }
76
77 mHandlerIdToMessageMap.erase(handleId);
78 }
79
80 void sendMessage(MessageId message)
81 {
82 MessageHandler::instance().send(message);
83 }
84}
85