BsEvent.h 7.5 KB

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