BsEvent.h 8.3 KB

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