CCEventDispatcher.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /****************************************************************************
  2. Copyright (c) 2013-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #ifndef __CC_EVENT_DISPATCHER_H__
  22. #define __CC_EVENT_DISPATCHER_H__
  23. #include <functional>
  24. #include <string>
  25. #include <unordered_map>
  26. #include <vector>
  27. #include <set>
  28. #include "platform/CCPlatformMacros.h"
  29. #include "base/CCEventListener.h"
  30. #include "base/CCEvent.h"
  31. #include "platform/CCStdC.h"
  32. /**
  33. * @addtogroup base
  34. * @{
  35. */
  36. NS_CC_BEGIN
  37. class Event;
  38. class EventTouch;
  39. class Node;
  40. class EventCustom;
  41. class EventListenerCustom;
  42. /** @class EventDispatcher
  43. * @brief This class manages event listener subscriptions
  44. and event dispatching.
  45. The EventListener list is managed in such a way that
  46. event listeners can be added and removed even
  47. from within an EventListener, while events are being
  48. dispatched.
  49. @js NA
  50. */
  51. class CC_DLL EventDispatcher : public Ref
  52. {
  53. public:
  54. // Adds event listener.
  55. /** Adds a event listener for a specified event with the priority of scene graph.
  56. * @param listener The listener of a specified event.
  57. * @param node The priority of the listener is based on the draw order of this node.
  58. * @note The priority of scene graph will be fixed value 0. So the order of listener item
  59. * in the vector will be ' <0, scene graph (0 priority), >0'.
  60. */
  61. void addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node);
  62. /** Adds a event listener for a specified event with the fixed priority.
  63. * @param listener The listener of a specified event.
  64. * @param fixedPriority The fixed priority of the listener.
  65. * @note A lower priority will be called before the ones that have a higher value.
  66. * 0 priority is forbidden for fixed priority since it's used for scene graph based priority.
  67. */
  68. void addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority);
  69. /** Adds a Custom event listener.
  70. It will use a fixed priority of 1.
  71. * @param eventName A given name of the event.
  72. * @param callback A given callback method that associated the event name.
  73. * @return the generated event. Needed in order to remove the event from the dispatcher
  74. */
  75. EventListenerCustom* addCustomEventListener(const std::string &eventName, const std::function<void(EventCustom*)>& callback);
  76. /////////////////////////////////////////////
  77. // Removes event listener
  78. /** Remove a listener.
  79. *
  80. * @param listener The specified event listener which needs to be removed.
  81. */
  82. void removeEventListener(EventListener* listener);
  83. /** Removes all listeners with the same event listener type.
  84. *
  85. * @param listenerType A given event listener type which needs to be removed.
  86. */
  87. void removeEventListenersForType(EventListener::Type listenerType);
  88. /** Removes all listeners which are associated with the specified target.
  89. *
  90. * @param target A given target node.
  91. * @param recursive True if remove recursively, the default value is false.
  92. */
  93. void removeEventListenersForTarget(Node* target, bool recursive = false);
  94. /** Removes all custom listeners with the same event name.
  95. *
  96. * @param customEventName A given event listener name which needs to be removed.
  97. */
  98. void removeCustomEventListeners(const std::string& customEventName);
  99. /** Removes all listeners.
  100. */
  101. void removeAllEventListeners();
  102. /////////////////////////////////////////////
  103. // Pauses / Resumes event listener
  104. /** Pauses all listeners which are associated the specified target.
  105. *
  106. * @param target A given target node.
  107. * @param recursive True if pause recursively, the default value is false.
  108. */
  109. void pauseEventListenersForTarget(Node* target, bool recursive = false);
  110. /** Resumes all listeners which are associated the specified target.
  111. *
  112. * @param target A given target node.
  113. * @param recursive True if resume recursively, the default value is false.
  114. */
  115. void resumeEventListenersForTarget(Node* target, bool recursive = false);
  116. /////////////////////////////////////////////
  117. /** Sets listener's priority with fixed value.
  118. *
  119. * @param listener A given listener.
  120. * @param fixedPriority The fixed priority value.
  121. */
  122. void setPriority(EventListener* listener, int fixedPriority);
  123. /** Whether to enable dispatching events.
  124. *
  125. * @param isEnabled True if enable dispatching events.
  126. */
  127. void setEnabled(bool isEnabled);
  128. /** Checks whether dispatching events is enabled.
  129. *
  130. * @return True if dispatching events is enabled.
  131. */
  132. bool isEnabled() const;
  133. /////////////////////////////////////////////
  134. /** Dispatches the event.
  135. * Also removes all EventListeners marked for deletion from the
  136. * event dispatcher list.
  137. *
  138. * @param event The event needs to be dispatched.
  139. */
  140. void dispatchEvent(Event* event);
  141. /** Dispatches a Custom Event with a event name an optional user data.
  142. *
  143. * @param eventName The name of the event which needs to be dispatched.
  144. * @param optionalUserData The optional user data, it's a void*, the default value is nullptr.
  145. */
  146. void dispatchCustomEvent(const std::string &eventName, void *optionalUserData = nullptr);
  147. /** Query whether the specified event listener id has been added.
  148. *
  149. * @param listenerID The listenerID of the event listener id.
  150. *
  151. * @return True if dispatching events is exist
  152. */
  153. bool hasEventListener(const EventListener::ListenerID& listenerID) const;
  154. /////////////////////////////////////////////
  155. /** Constructor of EventDispatcher.
  156. */
  157. EventDispatcher();
  158. /** Destructor of EventDispatcher.
  159. */
  160. ~EventDispatcher();
  161. #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS && COCOS2D_DEBUG > 0
  162. /**
  163. * To help track down event listener issues in debug builds.
  164. * Verifies that the node has no event listeners associated with it when destroyed.
  165. */
  166. void debugCheckNodeHasNoEventListenersOnDestruction(Node* node);
  167. #endif
  168. protected:
  169. friend class Node;
  170. /** Sets the dirty flag for a node. */
  171. void setDirtyForNode(Node* node);
  172. /**
  173. * The vector to store event listeners with scene graph based priority and fixed priority.
  174. */
  175. class EventListenerVector
  176. {
  177. public:
  178. EventListenerVector();
  179. ~EventListenerVector();
  180. size_t size() const;
  181. bool empty() const;
  182. void push_back(EventListener* item);
  183. void clearSceneGraphListeners();
  184. void clearFixedListeners();
  185. void clear();
  186. std::vector<EventListener*>* getFixedPriorityListeners() const { return _fixedListeners; }
  187. std::vector<EventListener*>* getSceneGraphPriorityListeners() const { return _sceneGraphListeners; }
  188. ssize_t getGt0Index() const { return _gt0Index; }
  189. void setGt0Index(ssize_t index) { _gt0Index = index; }
  190. private:
  191. std::vector<EventListener*>* _fixedListeners;
  192. std::vector<EventListener*>* _sceneGraphListeners;
  193. ssize_t _gt0Index;
  194. };
  195. /** Adds an event listener with item
  196. * @note if it is dispatching event, the added operation will be delayed to the end of current dispatch
  197. * @see forceAddEventListener
  198. */
  199. void addEventListener(EventListener* listener);
  200. /** Force adding an event listener
  201. * @note force add an event listener which will ignore whether it's in dispatching.
  202. * @see addEventListener
  203. */
  204. void forceAddEventListener(EventListener* listener);
  205. /** Gets event the listener list for the event listener type. */
  206. EventListenerVector* getListeners(const EventListener::ListenerID& listenerID) const;
  207. /** Update dirty flag */
  208. void updateDirtyFlagForSceneGraph();
  209. /** Removes all listeners with the same event listener ID */
  210. void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID);
  211. /** Sort event listener */
  212. void sortEventListeners(const EventListener::ListenerID& listenerID);
  213. /** Sorts the listeners of specified type by scene graph priority */
  214. void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, Node* rootNode);
  215. /** Sorts the listeners of specified type by fixed priority */
  216. void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID);
  217. /** Updates all listeners
  218. * 1) Removes all listener items that have been marked as 'removed' when dispatching event.
  219. * 2) Adds all listener items that have been marked as 'added' when dispatching event.
  220. */
  221. void updateListeners(Event* event);
  222. /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */
  223. void dispatchTouchEvent(EventTouch* event);
  224. /** Associates node with event listener */
  225. void associateNodeAndEventListener(Node* node, EventListener* listener);
  226. /** Dissociates node with event listener */
  227. void dissociateNodeAndEventListener(Node* node, EventListener* listener);
  228. /** Dispatches event to listeners with a specified listener type */
  229. void dispatchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent);
  230. /** Special version dispatchEventToListeners for touch/mouse event.
  231. *
  232. * Touch/mouse event process flow different with common event,
  233. * for scene graph node listeners, touch event process flow should
  234. * order by viewport/camera first, because the touch location convert
  235. * to 3D world space is different by different camera.
  236. * When listener process touch event, can get current camera by Camera::getVisitingCamera().
  237. */
  238. void dispatchTouchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent);
  239. void releaseListener(EventListener* listener);
  240. /// Priority dirty flag
  241. enum class DirtyFlag
  242. {
  243. NONE = 0,
  244. FIXED_PRIORITY = 1 << 0,
  245. SCENE_GRAPH_PRIORITY = 1 << 1,
  246. ALL = FIXED_PRIORITY | SCENE_GRAPH_PRIORITY
  247. };
  248. /** Sets the dirty flag for a specified listener ID */
  249. void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag);
  250. /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
  251. void visitTarget(Node* node, bool isRootNode);
  252. /** Remove all listeners in _toRemoveListeners list and cleanup */
  253. void cleanToRemovedListeners();
  254. /** Listeners map */
  255. std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listenerMap;
  256. /** The map of dirty flag */
  257. std::unordered_map<EventListener::ListenerID, DirtyFlag> _priorityDirtyFlagMap;
  258. /** The map of node and event listeners */
  259. std::unordered_map<Node*, std::vector<EventListener*>*> _nodeListenersMap;
  260. /** The map of node and its event priority */
  261. std::unordered_map<Node*, int> _nodePriorityMap;
  262. /** key: Global Z Order, value: Sorted Nodes */
  263. std::unordered_map<float, std::vector<Node*>> _globalZOrderNodeMap;
  264. /** The listeners to be added after dispatching event */
  265. std::vector<EventListener*> _toAddedListeners;
  266. /** The listeners to be removed after dispatching event */
  267. std::vector<EventListener*> _toRemovedListeners;
  268. /** The nodes were associated with scene graph based priority listeners */
  269. std::set<Node*> _dirtyNodes;
  270. /** Whether the dispatcher is dispatching event */
  271. int _inDispatch;
  272. /** Whether to enable dispatching event */
  273. bool _isEnabled;
  274. int _nodePriorityIndex;
  275. std::set<std::string> _internalCustomListenerIDs;
  276. };
  277. NS_CC_END
  278. // end of base group
  279. /// @}
  280. #endif // __CC_EVENT_DISPATCHER_H__