BsEvent.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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_delete(conn);
  44. conn = next;
  45. }
  46. conn = mFreeConnections;
  47. while (conn != nullptr)
  48. {
  49. BaseConnectionData* next = conn->next;
  50. bs_delete(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. }
  119. BaseConnectionData* mConnections;
  120. BaseConnectionData* mFreeConnections;
  121. BS_RECURSIVE_MUTEX(mMutex);
  122. };
  123. /**
  124. * @brief Event handle. Allows you to track to which events you subscribed to and
  125. * disconnect from them when needed.
  126. */
  127. class HEvent
  128. {
  129. public:
  130. HEvent()
  131. :mConnection(nullptr)
  132. { }
  133. explicit HEvent(const SPtr<EventInternalData>& eventData, BaseConnectionData* connection)
  134. :mConnection(connection), mEventData(eventData)
  135. {
  136. connection->handleLinks++;
  137. }
  138. ~HEvent()
  139. {
  140. if (mConnection != nullptr)
  141. mEventData->freeHandle(mConnection);
  142. }
  143. /**
  144. * @brief Disconnect from the event you are subscribed to.
  145. */
  146. void disconnect()
  147. {
  148. if (mConnection != nullptr)
  149. {
  150. mEventData->disconnect(mConnection);
  151. mConnection = nullptr;
  152. mEventData = nullptr;
  153. }
  154. }
  155. struct Bool_struct
  156. {
  157. int _Member;
  158. };
  159. /**
  160. * @brief Allows direct conversion of a handle to bool.
  161. *
  162. * @note This is needed because we can't directly convert to bool
  163. * since then we can assign pointer to bool and that's wrong.
  164. */
  165. operator int Bool_struct::*() const
  166. {
  167. return (mConnection != nullptr ? &Bool_struct::_Member : 0);
  168. }
  169. HEvent& operator=(const HEvent& rhs)
  170. {
  171. mConnection = rhs.mConnection;
  172. mEventData = rhs.mEventData;
  173. if (mConnection != nullptr)
  174. mConnection->handleLinks++;
  175. return *this;
  176. }
  177. private:
  178. BaseConnectionData* mConnection;
  179. SPtr<EventInternalData> mEventData;
  180. };
  181. /**
  182. * @brief Events allows you to register method callbacks that get notified
  183. * when the event is triggered.
  184. *
  185. * @note Callback method return value is ignored.
  186. */
  187. // Note: I could create a policy template argument that allows creation of
  188. // lockable and non-lockable events in the case mutex is causing too much overhead.
  189. template <class RetType, class... Args>
  190. class TEvent
  191. {
  192. struct ConnectionData : BaseConnectionData
  193. {
  194. public:
  195. void deactivate() override
  196. {
  197. func = nullptr;
  198. BaseConnectionData::deactivate();
  199. }
  200. std::function<RetType(Args...)> func;
  201. };
  202. public:
  203. TEvent()
  204. :mInternalData(bs_shared_ptr_new<EventInternalData>())
  205. { }
  206. ~TEvent()
  207. {
  208. clear();
  209. }
  210. /**
  211. * @brief Register a new callback that will get notified once
  212. * the event is triggered.
  213. */
  214. HEvent connect(std::function<RetType(Args...)> func)
  215. {
  216. BS_LOCK_RECURSIVE_MUTEX(mInternalData->mMutex);
  217. ConnectionData* connData = nullptr;
  218. if (mInternalData->mFreeConnections != nullptr)
  219. {
  220. connData = static_cast<ConnectionData*>(mInternalData->mFreeConnections);
  221. mInternalData->mFreeConnections = connData->next;
  222. if (connData->next != nullptr)
  223. connData->next->prev = nullptr;
  224. connData->isActive = true;
  225. }
  226. if (connData == nullptr)
  227. connData = bs_new<ConnectionData>();
  228. connData->next = mInternalData->mConnections;
  229. if (mInternalData->mConnections != nullptr)
  230. mInternalData->mConnections->prev = connData;
  231. mInternalData->mConnections = connData;
  232. connData->func = func;
  233. return HEvent(mInternalData, connData);
  234. }
  235. /**
  236. * @brief Trigger the event, notifying all register callback methods.
  237. */
  238. void operator() (Args... args)
  239. {
  240. // Increase ref count to ensure this event data isn't destroyed if one of the callbacks
  241. // deletes the event itself.
  242. std::shared_ptr<EventInternalData> internalData = mInternalData;
  243. BS_LOCK_RECURSIVE_MUTEX(internalData->mMutex);
  244. // Hidden dependency: If any new connections are made during these callbacks they must be
  245. // inserted at the start of the linked list so that we don't trigger them here.
  246. ConnectionData* conn = static_cast<ConnectionData*>(internalData->mConnections);
  247. while (conn != nullptr)
  248. {
  249. // Save next here in case the callback itself disconnects this connection
  250. ConnectionData* next = static_cast<ConnectionData*>(conn->next);
  251. if (conn->func != nullptr)
  252. conn->func(std::forward<Args>(args)...);
  253. conn = next;
  254. }
  255. }
  256. /**
  257. * @brief Clear all callbacks from the event.
  258. */
  259. void clear()
  260. {
  261. mInternalData->clear();
  262. }
  263. /**
  264. * @brief Check if event has any callbacks registered.
  265. *
  266. * @note It is safe to trigger an event even if no callbacks are registered.
  267. */
  268. bool empty() const
  269. {
  270. BS_LOCK_RECURSIVE_MUTEX(mInternalData->mMutex);
  271. return mInternalData->mConnections == nullptr;
  272. }
  273. private:
  274. SPtr<EventInternalData> mInternalData;
  275. };
  276. /************************************************************************/
  277. /* SPECIALIZATIONS */
  278. /* SO YOU MAY USE FUNCTION LIKE SYNTAX FOR DECLARING EVENT SIGNATURE */
  279. /************************************************************************/
  280. /**
  281. * @copydoc TEvent
  282. */
  283. template <typename Signature>
  284. class Event;
  285. /**
  286. * @copydoc TEvent
  287. */
  288. template <class RetType, class... Args>
  289. class Event<RetType(Args...) > : public TEvent <RetType, Args...>
  290. { };
  291. }