BsEvent.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsPrerequisitesUtil.h"
  5. /** @addtogroup General
  6. * @{
  7. */
  8. namespace BansheeEngine
  9. {
  10. /** Data common to all event connections. */
  11. class BaseConnectionData
  12. {
  13. public:
  14. BaseConnectionData()
  15. :prev(nullptr), next(nullptr), isActive(true),
  16. handleLinks(0)
  17. {
  18. }
  19. virtual ~BaseConnectionData()
  20. {
  21. assert(!handleLinks && !isActive);
  22. }
  23. virtual void deactivate()
  24. {
  25. isActive = false;
  26. }
  27. BaseConnectionData* prev;
  28. BaseConnectionData* next;
  29. bool isActive;
  30. UINT32 handleLinks;
  31. };
  32. /** Internal data for an Event, storing all connections. */
  33. struct EventInternalData
  34. {
  35. EventInternalData()
  36. :mConnections(nullptr), mFreeConnections(nullptr)
  37. { }
  38. ~EventInternalData()
  39. {
  40. BaseConnectionData* conn = mConnections;
  41. while (conn != nullptr)
  42. {
  43. BaseConnectionData* next = conn->next;
  44. bs_free(conn);
  45. conn = next;
  46. }
  47. conn = mFreeConnections;
  48. while (conn != nullptr)
  49. {
  50. BaseConnectionData* next = conn->next;
  51. bs_free(conn);
  52. conn = next;
  53. }
  54. }
  55. /**
  56. * Disconnects the connection with the specified data, ensuring the event doesn't call its callback again.
  57. *
  58. * @note Only call this once.
  59. */
  60. void disconnect(BaseConnectionData* conn)
  61. {
  62. BS_LOCK_RECURSIVE_MUTEX(mMutex);
  63. conn->deactivate();
  64. conn->handleLinks--;
  65. if (conn->handleLinks == 0)
  66. free(conn);
  67. }
  68. /** Disconnects all connections in the event. */
  69. void clear()
  70. {
  71. BS_LOCK_RECURSIVE_MUTEX(mMutex);
  72. BaseConnectionData* conn = mConnections;
  73. while (conn != nullptr)
  74. {
  75. BaseConnectionData* next = conn->next;
  76. conn->deactivate();
  77. if (conn->handleLinks == 0)
  78. free(conn);
  79. conn = next;
  80. }
  81. }
  82. /**
  83. * Called when the event handle no longer keeps a reference to the connection data. This means we might be able to
  84. * free (and reuse) its memory if the event is done with it too.
  85. */
  86. void freeHandle(BaseConnectionData* conn)
  87. {
  88. BS_LOCK_RECURSIVE_MUTEX(mMutex);
  89. conn->handleLinks--;
  90. if (conn->handleLinks == 0 && !conn->isActive)
  91. free(conn);
  92. }
  93. /** Releases connection data and makes it available for re-use when next connection is formed. */
  94. void free(BaseConnectionData* conn)
  95. {
  96. if (conn->prev != nullptr)
  97. conn->prev->next = conn->next;
  98. else
  99. mConnections = conn->next;
  100. if (conn->next != nullptr)
  101. conn->next->prev = conn->prev;
  102. conn->prev = nullptr;
  103. conn->next = nullptr;
  104. if (mFreeConnections != nullptr)
  105. {
  106. conn->next = mFreeConnections;
  107. mFreeConnections->prev = conn;
  108. }
  109. mFreeConnections = conn;
  110. mFreeConnections->~BaseConnectionData();
  111. }
  112. BaseConnectionData* mConnections;
  113. BaseConnectionData* mFreeConnections;
  114. BS_RECURSIVE_MUTEX(mMutex);
  115. };
  116. /** Event handle. Allows you to track to which events you subscribed to and disconnect from them when needed. */
  117. class HEvent
  118. {
  119. public:
  120. HEvent()
  121. :mConnection(nullptr)
  122. { }
  123. explicit HEvent(const SPtr<EventInternalData>& eventData, BaseConnectionData* connection)
  124. :mConnection(connection), mEventData(eventData)
  125. {
  126. connection->handleLinks++;
  127. }
  128. ~HEvent()
  129. {
  130. if (mConnection != nullptr)
  131. mEventData->freeHandle(mConnection);
  132. }
  133. /** Disconnect from the event you are subscribed to. */
  134. void disconnect()
  135. {
  136. if (mConnection != nullptr)
  137. {
  138. mEventData->disconnect(mConnection);
  139. mConnection = nullptr;
  140. mEventData = nullptr;
  141. }
  142. }
  143. struct Bool_struct
  144. {
  145. int _Member;
  146. };
  147. /**
  148. * Allows direct conversion of a handle to bool.
  149. *
  150. * @note
  151. * Additional struct is needed because we can't directly convert to bool since then we can assign pointer to bool
  152. * and that's wrong.
  153. */
  154. operator int Bool_struct::*() const
  155. {
  156. return (mConnection != nullptr ? &Bool_struct::_Member : 0);
  157. }
  158. HEvent& operator=(const HEvent& rhs)
  159. {
  160. mConnection = rhs.mConnection;
  161. mEventData = rhs.mEventData;
  162. if (mConnection != nullptr)
  163. mConnection->handleLinks++;
  164. return *this;
  165. }
  166. private:
  167. BaseConnectionData* mConnection;
  168. SPtr<EventInternalData> mEventData;
  169. };
  170. /**
  171. * Events allows you to register method callbacks that get notified when the event is triggered.
  172. *
  173. * @note Callback method return value is ignored.
  174. */
  175. // Note: I could create a policy template argument that allows creation of
  176. // lockable and non-lockable events in the case mutex is causing too much overhead.
  177. template <class RetType, class... Args>
  178. class TEvent
  179. {
  180. struct ConnectionData : BaseConnectionData
  181. {
  182. public:
  183. void deactivate() override
  184. {
  185. func = nullptr;
  186. BaseConnectionData::deactivate();
  187. }
  188. std::function<RetType(Args...)> func;
  189. };
  190. public:
  191. TEvent()
  192. :mInternalData(bs_shared_ptr_new<EventInternalData>())
  193. { }
  194. ~TEvent()
  195. {
  196. clear();
  197. }
  198. /** Register a new callback that will get notified once the event is triggered. */
  199. HEvent connect(std::function<RetType(Args...)> func)
  200. {
  201. BS_LOCK_RECURSIVE_MUTEX(mInternalData->mMutex);
  202. ConnectionData* connData = nullptr;
  203. if (mInternalData->mFreeConnections != nullptr)
  204. {
  205. connData = static_cast<ConnectionData*>(mInternalData->mFreeConnections);
  206. mInternalData->mFreeConnections = connData->next;
  207. new (connData)ConnectionData();
  208. if (connData->next != nullptr)
  209. connData->next->prev = nullptr;
  210. connData->isActive = true;
  211. }
  212. if (connData == nullptr)
  213. connData = bs_new<ConnectionData>();
  214. connData->next = mInternalData->mConnections;
  215. if (mInternalData->mConnections != nullptr)
  216. mInternalData->mConnections->prev = connData;
  217. mInternalData->mConnections = connData;
  218. connData->func = func;
  219. return HEvent(mInternalData, connData);
  220. }
  221. /** Trigger the event, notifying all register callback methods. */
  222. void operator() (Args... args)
  223. {
  224. // Increase ref count to ensure this event data isn't destroyed if one of the callbacks
  225. // deletes the event itself.
  226. std::shared_ptr<EventInternalData> internalData = mInternalData;
  227. BS_LOCK_RECURSIVE_MUTEX(internalData->mMutex);
  228. // Hidden dependency: If any new connections are made during these callbacks they must be
  229. // inserted at the start of the linked list so that we don't trigger them here.
  230. ConnectionData* conn = static_cast<ConnectionData*>(internalData->mConnections);
  231. while (conn != nullptr)
  232. {
  233. // Save next here in case the callback itself disconnects this connection
  234. ConnectionData* next = static_cast<ConnectionData*>(conn->next);
  235. if (conn->func != nullptr)
  236. conn->func(std::forward<Args>(args)...);
  237. conn = next;
  238. }
  239. }
  240. /** Clear all callbacks from the event. */
  241. void clear()
  242. {
  243. mInternalData->clear();
  244. }
  245. /**
  246. * Check if event has any callbacks registered.
  247. *
  248. * @note It is safe to trigger an event even if no callbacks are registered.
  249. */
  250. bool empty() const
  251. {
  252. BS_LOCK_RECURSIVE_MUTEX(mInternalData->mMutex);
  253. return mInternalData->mConnections == nullptr;
  254. }
  255. private:
  256. SPtr<EventInternalData> mInternalData;
  257. };
  258. /************************************************************************/
  259. /* SPECIALIZATIONS */
  260. /* SO YOU MAY USE FUNCTION LIKE SYNTAX FOR DECLARING EVENT SIGNATURE */
  261. /************************************************************************/
  262. /** @copydoc TEvent */
  263. template <typename Signature>
  264. class Event;
  265. /** @copydoc TEvent */
  266. template <class RetType, class... Args>
  267. class Event<RetType(Args...) > : public TEvent <RetType, Args...>
  268. { };
  269. }
  270. /** @} */