PageRenderTime 25ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/cocos2d/cocos/base/CCEventDispatcher.h

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