CCEventDispatcher.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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. #include "base/CCEventDispatcher.h"
  22. #include <algorithm>
  23. #include "base/CCEventCustom.h"
  24. #include "base/CCEventListenerTouch.h"
  25. #include "base/CCEventListenerAcceleration.h"
  26. #include "base/CCEventListenerMouse.h"
  27. #include "base/CCEventListenerKeyboard.h"
  28. #include "base/CCEventListenerCustom.h"
  29. #include "base/CCEventListenerFocus.h"
  30. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  31. #include "base/CCEventListenerController.h"
  32. #endif
  33. #include "2d/CCScene.h"
  34. #include "base/CCDirector.h"
  35. #include "base/CCEventType.h"
  36. #include "2d/CCCamera.h"
  37. #define DUMP_LISTENER_ITEM_PRIORITY_INFO 0
  38. namespace
  39. {
  40. class DispatchGuard
  41. {
  42. public:
  43. DispatchGuard(int& count):
  44. _count(count)
  45. {
  46. ++_count;
  47. }
  48. ~DispatchGuard()
  49. {
  50. --_count;
  51. }
  52. private:
  53. int& _count;
  54. };
  55. }
  56. NS_CC_BEGIN
  57. static EventListener::ListenerID __getListenerID(Event* event)
  58. {
  59. EventListener::ListenerID ret;
  60. switch (event->getType())
  61. {
  62. case Event::Type::ACCELERATION:
  63. ret = EventListenerAcceleration::LISTENER_ID;
  64. break;
  65. case Event::Type::CUSTOM:
  66. {
  67. auto customEvent = static_cast<EventCustom*>(event);
  68. ret = customEvent->getEventName();
  69. }
  70. break;
  71. case Event::Type::KEYBOARD:
  72. ret = EventListenerKeyboard::LISTENER_ID;
  73. break;
  74. case Event::Type::MOUSE:
  75. ret = EventListenerMouse::LISTENER_ID;
  76. break;
  77. case Event::Type::FOCUS:
  78. ret = EventListenerFocus::LISTENER_ID;
  79. break;
  80. case Event::Type::TOUCH:
  81. // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce.
  82. // return UNKNOWN instead.
  83. CCASSERT(false, "Don't call this method if the event is for touch.");
  84. break;
  85. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  86. case Event::Type::GAME_CONTROLLER:
  87. ret = EventListenerController::LISTENER_ID;
  88. break;
  89. #endif
  90. default:
  91. CCASSERT(false, "Invalid type!");
  92. break;
  93. }
  94. return ret;
  95. }
  96. EventDispatcher::EventListenerVector::EventListenerVector() :
  97. _fixedListeners(nullptr),
  98. _sceneGraphListeners(nullptr),
  99. _gt0Index(0)
  100. {
  101. }
  102. EventDispatcher::EventListenerVector::~EventListenerVector()
  103. {
  104. CC_SAFE_DELETE(_sceneGraphListeners);
  105. CC_SAFE_DELETE(_fixedListeners);
  106. }
  107. size_t EventDispatcher::EventListenerVector::size() const
  108. {
  109. size_t ret = 0;
  110. if (_sceneGraphListeners)
  111. ret += _sceneGraphListeners->size();
  112. if (_fixedListeners)
  113. ret += _fixedListeners->size();
  114. return ret;
  115. }
  116. bool EventDispatcher::EventListenerVector::empty() const
  117. {
  118. return (_sceneGraphListeners == nullptr || _sceneGraphListeners->empty())
  119. && (_fixedListeners == nullptr || _fixedListeners->empty());
  120. }
  121. void EventDispatcher::EventListenerVector::push_back(EventListener* listener)
  122. {
  123. #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
  124. CCASSERT(_sceneGraphListeners == nullptr ||
  125. std::count(_sceneGraphListeners->begin(), _sceneGraphListeners->end(), listener) == 0,
  126. "Listener should not be added twice!");
  127. CCASSERT(_fixedListeners == nullptr ||
  128. std::count(_fixedListeners->begin(), _fixedListeners->end(), listener) == 0,
  129. "Listener should not be added twice!");
  130. #endif
  131. if (listener->getFixedPriority() == 0)
  132. {
  133. if (_sceneGraphListeners == nullptr)
  134. {
  135. _sceneGraphListeners = new (std::nothrow) std::vector<EventListener*>();
  136. _sceneGraphListeners->reserve(100);
  137. }
  138. _sceneGraphListeners->push_back(listener);
  139. }
  140. else
  141. {
  142. if (_fixedListeners == nullptr)
  143. {
  144. _fixedListeners = new std::vector<EventListener*>();
  145. _fixedListeners->reserve(100);
  146. }
  147. _fixedListeners->push_back(listener);
  148. }
  149. }
  150. void EventDispatcher::EventListenerVector::clearSceneGraphListeners()
  151. {
  152. if (_sceneGraphListeners)
  153. {
  154. _sceneGraphListeners->clear();
  155. delete _sceneGraphListeners;
  156. _sceneGraphListeners = nullptr;
  157. }
  158. }
  159. void EventDispatcher::EventListenerVector::clearFixedListeners()
  160. {
  161. if (_fixedListeners)
  162. {
  163. _fixedListeners->clear();
  164. delete _fixedListeners;
  165. _fixedListeners = nullptr;
  166. }
  167. }
  168. void EventDispatcher::EventListenerVector::clear()
  169. {
  170. clearSceneGraphListeners();
  171. clearFixedListeners();
  172. }
  173. EventDispatcher::EventDispatcher()
  174. : _inDispatch(0)
  175. , _isEnabled(false)
  176. , _nodePriorityIndex(0)
  177. {
  178. _toAddedListeners.reserve(50);
  179. _toRemovedListeners.reserve(50);
  180. // fixed #4129: Mark the following listener IDs for internal use.
  181. // Therefore, internal listeners would not be cleaned when removeAllEventListeners is invoked.
  182. _internalCustomListenerIDs.insert(EVENT_COME_TO_FOREGROUND);
  183. _internalCustomListenerIDs.insert(EVENT_COME_TO_BACKGROUND);
  184. _internalCustomListenerIDs.insert(EVENT_RENDERER_RECREATED);
  185. }
  186. EventDispatcher::~EventDispatcher()
  187. {
  188. // Clear internal custom listener IDs from set,
  189. // so removeAllEventListeners would clean internal custom listeners.
  190. _internalCustomListenerIDs.clear();
  191. removeAllEventListeners();
  192. }
  193. void EventDispatcher::visitTarget(Node* node, bool isRootNode)
  194. {
  195. node->sortAllChildren();
  196. int i = 0;
  197. auto& children = node->getChildren();
  198. auto childrenCount = children.size();
  199. if(childrenCount > 0)
  200. {
  201. Node* child = nullptr;
  202. // visit children zOrder < 0
  203. for( ; i < childrenCount; i++ )
  204. {
  205. child = children.at(i);
  206. if ( child && child->getLocalZOrder() < 0 )
  207. visitTarget(child, false);
  208. else
  209. break;
  210. }
  211. if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
  212. {
  213. _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node);
  214. }
  215. for( ; i < childrenCount; i++ )
  216. {
  217. child = children.at(i);
  218. if (child)
  219. visitTarget(child, false);
  220. }
  221. }
  222. else
  223. {
  224. if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
  225. {
  226. _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node);
  227. }
  228. }
  229. if (isRootNode)
  230. {
  231. std::vector<float> globalZOrders;
  232. globalZOrders.reserve(_globalZOrderNodeMap.size());
  233. for (const auto& e : _globalZOrderNodeMap)
  234. {
  235. globalZOrders.push_back(e.first);
  236. }
  237. std::stable_sort(globalZOrders.begin(), globalZOrders.end(), [](const float a, const float b){
  238. return a < b;
  239. });
  240. for (const auto& globalZ : globalZOrders)
  241. {
  242. for (const auto& n : _globalZOrderNodeMap[globalZ])
  243. {
  244. _nodePriorityMap[n] = ++_nodePriorityIndex;
  245. }
  246. }
  247. _globalZOrderNodeMap.clear();
  248. }
  249. }
  250. void EventDispatcher::pauseEventListenersForTarget(Node* target, bool recursive/* = false */)
  251. {
  252. auto listenerIter = _nodeListenersMap.find(target);
  253. if (listenerIter != _nodeListenersMap.end())
  254. {
  255. auto listeners = listenerIter->second;
  256. for (auto& l : *listeners)
  257. {
  258. l->setPaused(true);
  259. }
  260. }
  261. for (auto& listener : _toAddedListeners)
  262. {
  263. if (listener->getAssociatedNode() == target)
  264. {
  265. listener->setPaused(true);
  266. }
  267. }
  268. if (recursive)
  269. {
  270. const auto& children = target->getChildren();
  271. for (const auto& child : children)
  272. {
  273. pauseEventListenersForTarget(child, true);
  274. }
  275. }
  276. }
  277. void EventDispatcher::resumeEventListenersForTarget(Node* target, bool recursive/* = false */)
  278. {
  279. auto listenerIter = _nodeListenersMap.find(target);
  280. if (listenerIter != _nodeListenersMap.end())
  281. {
  282. auto listeners = listenerIter->second;
  283. for (auto& l : *listeners)
  284. {
  285. l->setPaused(false);
  286. }
  287. }
  288. for (auto& listener : _toAddedListeners)
  289. {
  290. if (listener->getAssociatedNode() == target)
  291. {
  292. listener->setPaused(false);
  293. }
  294. }
  295. setDirtyForNode(target);
  296. if (recursive)
  297. {
  298. const auto& children = target->getChildren();
  299. for (const auto& child : children)
  300. {
  301. resumeEventListenersForTarget(child, true);
  302. }
  303. }
  304. }
  305. void EventDispatcher::removeEventListenersForTarget(Node* target, bool recursive/* = false */)
  306. {
  307. // Ensure the node is removed from these immediately also.
  308. // Don't want any dangling pointers or the possibility of dealing with deleted objects..
  309. _nodePriorityMap.erase(target);
  310. _dirtyNodes.erase(target);
  311. auto listenerIter = _nodeListenersMap.find(target);
  312. if (listenerIter != _nodeListenersMap.end())
  313. {
  314. auto listeners = listenerIter->second;
  315. auto listenersCopy = *listeners;
  316. for (auto& l : listenersCopy)
  317. {
  318. removeEventListener(l);
  319. }
  320. }
  321. // Bug fix: ensure there are no references to the node in the list of listeners to be added.
  322. // If we find any listeners associated with the destroyed node in this list then remove them.
  323. // This is to catch the scenario where the node gets destroyed before it's listener
  324. // is added into the event dispatcher fully. This could happen if a node registers a listener
  325. // and gets destroyed while we are dispatching an event (touch etc.)
  326. for (auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end(); )
  327. {
  328. EventListener * listener = *iter;
  329. if (listener->getAssociatedNode() == target)
  330. {
  331. listener->setAssociatedNode(nullptr); // Ensure no dangling ptr to the target node.
  332. listener->setRegistered(false);
  333. releaseListener(listener);
  334. iter = _toAddedListeners.erase(iter);
  335. }
  336. else
  337. {
  338. ++iter;
  339. }
  340. }
  341. if (recursive)
  342. {
  343. const auto& children = target->getChildren();
  344. for (const auto& child : children)
  345. {
  346. removeEventListenersForTarget(child, true);
  347. }
  348. }
  349. }
  350. void EventDispatcher::associateNodeAndEventListener(Node* node, EventListener* listener)
  351. {
  352. std::vector<EventListener*>* listeners = nullptr;
  353. auto found = _nodeListenersMap.find(node);
  354. if (found != _nodeListenersMap.end())
  355. {
  356. listeners = found->second;
  357. }
  358. else
  359. {
  360. listeners = new (std::nothrow) std::vector<EventListener*>();
  361. _nodeListenersMap.emplace(node, listeners);
  362. }
  363. listeners->push_back(listener);
  364. }
  365. void EventDispatcher::dissociateNodeAndEventListener(Node* node, EventListener* listener)
  366. {
  367. std::vector<EventListener*>* listeners = nullptr;
  368. auto found = _nodeListenersMap.find(node);
  369. if (found != _nodeListenersMap.end())
  370. {
  371. listeners = found->second;
  372. auto iter = std::find(listeners->begin(), listeners->end(), listener);
  373. if (iter != listeners->end())
  374. {
  375. listeners->erase(iter);
  376. }
  377. if (listeners->empty())
  378. {
  379. _nodeListenersMap.erase(found);
  380. delete listeners;
  381. }
  382. }
  383. }
  384. void EventDispatcher::addEventListener(EventListener* listener)
  385. {
  386. if (_inDispatch == 0)
  387. {
  388. forceAddEventListener(listener);
  389. }
  390. else
  391. {
  392. _toAddedListeners.push_back(listener);
  393. }
  394. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  395. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  396. if (sEngine)
  397. {
  398. sEngine->retainScriptObject(this, listener);
  399. }
  400. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  401. listener->retain();
  402. }
  403. void EventDispatcher::forceAddEventListener(EventListener* listener)
  404. {
  405. EventListenerVector* listeners = nullptr;
  406. EventListener::ListenerID listenerID = listener->getListenerID();
  407. auto itr = _listenerMap.find(listenerID);
  408. if (itr == _listenerMap.end())
  409. {
  410. listeners = new (std::nothrow) EventListenerVector();
  411. _listenerMap.emplace(listenerID, listeners);
  412. }
  413. else
  414. {
  415. listeners = itr->second;
  416. }
  417. listeners->push_back(listener);
  418. if (listener->getFixedPriority() == 0)
  419. {
  420. setDirty(listenerID, DirtyFlag::SCENE_GRAPH_PRIORITY);
  421. auto node = listener->getAssociatedNode();
  422. CCASSERT(node != nullptr, "Invalid scene graph priority!");
  423. associateNodeAndEventListener(node, listener);
  424. if (!node->isRunning())
  425. {
  426. listener->setPaused(true);
  427. }
  428. }
  429. else
  430. {
  431. setDirty(listenerID, DirtyFlag::FIXED_PRIORITY);
  432. }
  433. }
  434. void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)
  435. {
  436. CCASSERT(listener && node, "Invalid parameters.");
  437. CCASSERT(!listener->isRegistered(), "The listener has been registered.");
  438. if (!listener->checkAvailable())
  439. return;
  440. listener->setAssociatedNode(node);
  441. listener->setFixedPriority(0);
  442. listener->setRegistered(true);
  443. addEventListener(listener);
  444. }
  445. #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS && COCOS2D_DEBUG > 0
  446. void EventDispatcher::debugCheckNodeHasNoEventListenersOnDestruction(Node* node)
  447. {
  448. // Check the listeners map
  449. for (const auto & keyValuePair : _listenerMap)
  450. {
  451. const EventListenerVector * eventListenerVector = keyValuePair.second;
  452. if (eventListenerVector)
  453. {
  454. if (eventListenerVector->getSceneGraphPriorityListeners())
  455. {
  456. for (EventListener * listener : *eventListenerVector->getSceneGraphPriorityListeners())
  457. {
  458. CCASSERT(!listener ||
  459. listener->getAssociatedNode() != node,
  460. "Node should have no event listeners registered for it upon destruction!");
  461. }
  462. }
  463. }
  464. }
  465. // Check the node listeners map
  466. for (const auto & keyValuePair : _nodeListenersMap)
  467. {
  468. CCASSERT(keyValuePair.first != node, "Node should have no event listeners registered for it upon destruction!");
  469. if (keyValuePair.second)
  470. {
  471. for (EventListener * listener : *keyValuePair.second)
  472. {
  473. CCASSERT(listener->getAssociatedNode() != node,
  474. "Node should have no event listeners registered for it upon destruction!");
  475. }
  476. }
  477. }
  478. // Check the node priority map
  479. for (const auto & keyValuePair : _nodePriorityMap)
  480. {
  481. CCASSERT(keyValuePair.first != node,
  482. "Node should have no event listeners registered for it upon destruction!");
  483. }
  484. // Check the to be added list
  485. for (EventListener * listener : _toAddedListeners)
  486. {
  487. CCASSERT(listener->getAssociatedNode() != node,
  488. "Node should have no event listeners registered for it upon destruction!");
  489. }
  490. // Check the dirty nodes set
  491. for (Node * dirtyNode : _dirtyNodes)
  492. {
  493. CCASSERT(dirtyNode != node,
  494. "Node should have no event listeners registered for it upon destruction!");
  495. }
  496. }
  497. #endif // #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS && COCOS2D_DEBUG > 0
  498. void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority)
  499. {
  500. CCASSERT(listener, "Invalid parameters.");
  501. CCASSERT(!listener->isRegistered(), "The listener has been registered.");
  502. CCASSERT(fixedPriority != 0, "0 priority is forbidden for fixed priority since it's used for scene graph based priority.");
  503. if (!listener->checkAvailable())
  504. return;
  505. listener->setAssociatedNode(nullptr);
  506. listener->setFixedPriority(fixedPriority);
  507. listener->setRegistered(true);
  508. listener->setPaused(false);
  509. addEventListener(listener);
  510. }
  511. EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, const std::function<void(EventCustom*)>& callback)
  512. {
  513. EventListenerCustom *listener = EventListenerCustom::create(eventName, callback);
  514. addEventListenerWithFixedPriority(listener, 1);
  515. return listener;
  516. }
  517. void EventDispatcher::removeEventListener(EventListener* listener)
  518. {
  519. if (listener == nullptr)
  520. return;
  521. // just return if listener is in _toRemovedListeners to avoid remove listeners more than once
  522. if (std::find(_toRemovedListeners.begin(), _toRemovedListeners.end(), listener) != _toRemovedListeners.end())
  523. return;
  524. bool isFound = false;
  525. auto removeListenerInVector = [&](std::vector<EventListener*>* listeners){
  526. if (listeners == nullptr)
  527. return;
  528. for (auto iter = listeners->begin(); iter != listeners->end(); ++iter)
  529. {
  530. auto l = *iter;
  531. if (l == listener)
  532. {
  533. CC_SAFE_RETAIN(l);
  534. l->setRegistered(false);
  535. if (l->getAssociatedNode() != nullptr)
  536. {
  537. dissociateNodeAndEventListener(l->getAssociatedNode(), l);
  538. l->setAssociatedNode(nullptr); // nullptr out the node pointer so we don't have any dangling pointers to destroyed nodes.
  539. }
  540. if (_inDispatch == 0)
  541. {
  542. iter = listeners->erase(iter);
  543. releaseListener(l);
  544. }
  545. else
  546. {
  547. _toRemovedListeners.push_back(l);
  548. }
  549. isFound = true;
  550. break;
  551. }
  552. }
  553. };
  554. for (auto iter = _listenerMap.begin(); iter != _listenerMap.end();)
  555. {
  556. auto listeners = iter->second;
  557. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  558. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  559. removeListenerInVector(sceneGraphPriorityListeners);
  560. if (isFound)
  561. {
  562. // fixed #4160: Dirty flag need to be updated after listeners were removed.
  563. setDirty(listener->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY);
  564. }
  565. else
  566. {
  567. removeListenerInVector(fixedPriorityListeners);
  568. if (isFound)
  569. {
  570. setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY);
  571. }
  572. }
  573. #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
  574. CCASSERT(_inDispatch != 0 ||
  575. !sceneGraphPriorityListeners ||
  576. std::count(sceneGraphPriorityListeners->begin(), sceneGraphPriorityListeners->end(), listener) == 0,
  577. "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
  578. CCASSERT(_inDispatch != 0 ||
  579. !fixedPriorityListeners ||
  580. std::count(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener) == 0,
  581. "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
  582. #endif
  583. if (iter->second->empty())
  584. {
  585. _priorityDirtyFlagMap.erase(listener->getListenerID());
  586. auto list = iter->second;
  587. iter = _listenerMap.erase(iter);
  588. CC_SAFE_DELETE(list);
  589. }
  590. else
  591. {
  592. ++iter;
  593. }
  594. if (isFound)
  595. break;
  596. }
  597. if (isFound)
  598. {
  599. releaseListener(listener);
  600. }
  601. else
  602. {
  603. for(auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end(); ++iter)
  604. {
  605. if (*iter == listener)
  606. {
  607. listener->setRegistered(false);
  608. releaseListener(listener);
  609. _toAddedListeners.erase(iter);
  610. break;
  611. }
  612. }
  613. }
  614. }
  615. void EventDispatcher::setPriority(EventListener* listener, int fixedPriority)
  616. {
  617. if (listener == nullptr)
  618. return;
  619. for (auto& iter : _listenerMap)
  620. {
  621. auto fixedPriorityListeners = iter.second->getFixedPriorityListeners();
  622. if (fixedPriorityListeners)
  623. {
  624. auto found = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener);
  625. if (found != fixedPriorityListeners->end())
  626. {
  627. CCASSERT(listener->getAssociatedNode() == nullptr, "Can't set fixed priority with scene graph based listener.");
  628. if (listener->getFixedPriority() != fixedPriority)
  629. {
  630. listener->setFixedPriority(fixedPriority);
  631. setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY);
  632. }
  633. return;
  634. }
  635. }
  636. }
  637. }
  638. void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent)
  639. {
  640. bool shouldStopPropagation = false;
  641. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  642. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  643. ssize_t i = 0;
  644. // priority < 0
  645. if (fixedPriorityListeners)
  646. {
  647. CCASSERT(listeners->getGt0Index() <= static_cast<ssize_t>(fixedPriorityListeners->size()), "Out of range exception!");
  648. if (!fixedPriorityListeners->empty())
  649. {
  650. for (; i < listeners->getGt0Index(); ++i)
  651. {
  652. auto l = fixedPriorityListeners->at(i);
  653. if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
  654. {
  655. shouldStopPropagation = true;
  656. break;
  657. }
  658. }
  659. }
  660. }
  661. if (sceneGraphPriorityListeners)
  662. {
  663. if (!shouldStopPropagation)
  664. {
  665. // priority == 0, scene graph priority
  666. for (auto& l : *sceneGraphPriorityListeners)
  667. {
  668. if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
  669. {
  670. shouldStopPropagation = true;
  671. break;
  672. }
  673. }
  674. }
  675. }
  676. if (fixedPriorityListeners)
  677. {
  678. if (!shouldStopPropagation)
  679. {
  680. // priority > 0
  681. ssize_t size = fixedPriorityListeners->size();
  682. for (; i < size; ++i)
  683. {
  684. auto l = fixedPriorityListeners->at(i);
  685. if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
  686. {
  687. shouldStopPropagation = true;
  688. break;
  689. }
  690. }
  691. }
  692. }
  693. }
  694. void EventDispatcher::dispatchTouchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent)
  695. {
  696. bool shouldStopPropagation = false;
  697. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  698. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  699. ssize_t i = 0;
  700. // priority < 0
  701. if (fixedPriorityListeners)
  702. {
  703. CCASSERT(listeners->getGt0Index() <= static_cast<ssize_t>(fixedPriorityListeners->size()), "Out of range exception!");
  704. if (!fixedPriorityListeners->empty())
  705. {
  706. for (; i < listeners->getGt0Index(); ++i)
  707. {
  708. auto l = fixedPriorityListeners->at(i);
  709. if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
  710. {
  711. shouldStopPropagation = true;
  712. break;
  713. }
  714. }
  715. }
  716. }
  717. auto scene = Director::getInstance()->getRunningScene();
  718. if (scene && sceneGraphPriorityListeners)
  719. {
  720. if (!shouldStopPropagation)
  721. {
  722. // priority == 0, scene graph priority
  723. // first, get all enabled, unPaused and registered listeners
  724. std::vector<EventListener*> sceneListeners;
  725. for (auto& l : *sceneGraphPriorityListeners)
  726. {
  727. if (l->isEnabled() && !l->isPaused() && l->isRegistered())
  728. {
  729. sceneListeners.push_back(l);
  730. }
  731. }
  732. // second, for all camera call all listeners
  733. // get a copy of cameras, prevent it's been modified in listener callback
  734. // if camera's depth is greater, process it earlier
  735. auto cameras = scene->getCameras();
  736. for (auto rit = cameras.rbegin(), ritRend = cameras.rend(); rit != ritRend; ++rit)
  737. {
  738. Camera* camera = *rit;
  739. if (camera->isVisible() == false)
  740. {
  741. continue;
  742. }
  743. Camera::_visitingCamera = camera;
  744. auto cameraFlag = (unsigned short)camera->getCameraFlag();
  745. for (auto& l : sceneListeners)
  746. {
  747. if (nullptr == l->getAssociatedNode() || 0 == (l->getAssociatedNode()->getCameraMask() & cameraFlag))
  748. {
  749. continue;
  750. }
  751. if (onEvent(l))
  752. {
  753. shouldStopPropagation = true;
  754. break;
  755. }
  756. }
  757. if (shouldStopPropagation)
  758. {
  759. break;
  760. }
  761. }
  762. Camera::_visitingCamera = nullptr;
  763. }
  764. }
  765. if (fixedPriorityListeners)
  766. {
  767. if (!shouldStopPropagation)
  768. {
  769. // priority > 0
  770. ssize_t size = fixedPriorityListeners->size();
  771. for (; i < size; ++i)
  772. {
  773. auto l = fixedPriorityListeners->at(i);
  774. if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
  775. {
  776. shouldStopPropagation = true;
  777. break;
  778. }
  779. }
  780. }
  781. }
  782. }
  783. void EventDispatcher::dispatchEvent(Event* event)
  784. {
  785. if (!_isEnabled)
  786. return;
  787. updateDirtyFlagForSceneGraph();
  788. DispatchGuard guard(_inDispatch);
  789. if (event->getType() == Event::Type::TOUCH)
  790. {
  791. dispatchTouchEvent(static_cast<EventTouch*>(event));
  792. return;
  793. }
  794. auto listenerID = __getListenerID(event);
  795. sortEventListeners(listenerID);
  796. auto pfnDispatchEventToListeners = &EventDispatcher::dispatchEventToListeners;
  797. if (event->getType() == Event::Type::MOUSE) {
  798. pfnDispatchEventToListeners = &EventDispatcher::dispatchTouchEventToListeners;
  799. }
  800. auto iter = _listenerMap.find(listenerID);
  801. if (iter != _listenerMap.end())
  802. {
  803. auto listeners = iter->second;
  804. auto onEvent = [&event](EventListener* listener) -> bool{
  805. event->setCurrentTarget(listener->getAssociatedNode());
  806. listener->_onEvent(event);
  807. return event->isStopped();
  808. };
  809. (this->*pfnDispatchEventToListeners)(listeners, onEvent);
  810. }
  811. updateListeners(event);
  812. }
  813. void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData)
  814. {
  815. EventCustom ev(eventName);
  816. ev.setUserData(optionalUserData);
  817. dispatchEvent(&ev);
  818. }
  819. bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listenerID) const
  820. {
  821. return getListeners(listenerID) != nullptr;
  822. }
  823. void EventDispatcher::dispatchTouchEvent(EventTouch* event)
  824. {
  825. sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID);
  826. sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
  827. auto oneByOneListeners = getListeners(EventListenerTouchOneByOne::LISTENER_ID);
  828. auto allAtOnceListeners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
  829. // If there aren't any touch listeners, return directly.
  830. if (nullptr == oneByOneListeners && nullptr == allAtOnceListeners)
  831. return;
  832. bool isNeedsMutableSet = (oneByOneListeners && allAtOnceListeners);
  833. const std::vector<Touch*>& originalTouches = event->getTouches();
  834. std::vector<Touch*> mutableTouches(originalTouches.size());
  835. std::copy(originalTouches.begin(), originalTouches.end(), mutableTouches.begin());
  836. //
  837. // process the target handlers 1st
  838. //
  839. if (oneByOneListeners)
  840. {
  841. auto mutableTouchesIter = mutableTouches.begin();
  842. for (auto& touches : originalTouches)
  843. {
  844. bool isSwallowed = false;
  845. auto onTouchEvent = [&](EventListener* l) -> bool { // Return true to break
  846. EventListenerTouchOneByOne* listener = static_cast<EventListenerTouchOneByOne*>(l);
  847. // Skip if the listener was removed.
  848. if (!listener->_isRegistered)
  849. return false;
  850. event->setCurrentTarget(listener->_node);
  851. bool isClaimed = false;
  852. std::vector<Touch*>::iterator removedIter;
  853. EventTouch::EventCode eventCode = event->getEventCode();
  854. if (eventCode == EventTouch::EventCode::BEGAN)
  855. {
  856. if (listener->onTouchBegan)
  857. {
  858. isClaimed = listener->onTouchBegan(touches, event);
  859. if (isClaimed && listener->_isRegistered)
  860. {
  861. listener->_claimedTouches.push_back(touches);
  862. }
  863. }
  864. }
  865. else if (listener->_claimedTouches.size() > 0
  866. && ((removedIter = std::find(listener->_claimedTouches.begin(), listener->_claimedTouches.end(), touches)) != listener->_claimedTouches.end()))
  867. {
  868. isClaimed = true;
  869. switch (eventCode)
  870. {
  871. case EventTouch::EventCode::MOVED:
  872. if (listener->onTouchMoved)
  873. {
  874. listener->onTouchMoved(touches, event);
  875. }
  876. break;
  877. case EventTouch::EventCode::ENDED:
  878. if (listener->onTouchEnded)
  879. {
  880. listener->onTouchEnded(touches, event);
  881. }
  882. if (listener->_isRegistered)
  883. {
  884. listener->_claimedTouches.erase(removedIter);
  885. }
  886. break;
  887. case EventTouch::EventCode::CANCELLED:
  888. if (listener->onTouchCancelled)
  889. {
  890. listener->onTouchCancelled(touches, event);
  891. }
  892. if (listener->_isRegistered)
  893. {
  894. listener->_claimedTouches.erase(removedIter);
  895. }
  896. break;
  897. default:
  898. CCASSERT(false, "The eventcode is invalid.");
  899. break;
  900. }
  901. }
  902. // If the event was stopped, return directly.
  903. if (event->isStopped())
  904. {
  905. updateListeners(event);
  906. return true;
  907. }
  908. CCASSERT(touches->getID() == (*mutableTouchesIter)->getID(),
  909. "touches ID should be equal to mutableTouchesIter's ID.");
  910. if (isClaimed && listener->_isRegistered && listener->_needSwallow)
  911. {
  912. if (isNeedsMutableSet)
  913. {
  914. mutableTouchesIter = mutableTouches.erase(mutableTouchesIter);
  915. isSwallowed = true;
  916. }
  917. return true;
  918. }
  919. return false;
  920. };
  921. //
  922. dispatchTouchEventToListeners(oneByOneListeners, onTouchEvent);
  923. if (event->isStopped())
  924. {
  925. return;
  926. }
  927. if (!isSwallowed)
  928. ++mutableTouchesIter;
  929. }
  930. }
  931. //
  932. // process standard handlers 2nd
  933. //
  934. if (allAtOnceListeners && mutableTouches.size() > 0)
  935. {
  936. auto onTouchesEvent = [&](EventListener* l) -> bool{
  937. EventListenerTouchAllAtOnce* listener = static_cast<EventListenerTouchAllAtOnce*>(l);
  938. // Skip if the listener was removed.
  939. if (!listener->_isRegistered)
  940. return false;
  941. event->setCurrentTarget(listener->_node);
  942. switch (event->getEventCode())
  943. {
  944. case EventTouch::EventCode::BEGAN:
  945. if (listener->onTouchesBegan)
  946. {
  947. listener->onTouchesBegan(mutableTouches, event);
  948. }
  949. break;
  950. case EventTouch::EventCode::MOVED:
  951. if (listener->onTouchesMoved)
  952. {
  953. listener->onTouchesMoved(mutableTouches, event);
  954. }
  955. break;
  956. case EventTouch::EventCode::ENDED:
  957. if (listener->onTouchesEnded)
  958. {
  959. listener->onTouchesEnded(mutableTouches, event);
  960. }
  961. break;
  962. case EventTouch::EventCode::CANCELLED:
  963. if (listener->onTouchesCancelled)
  964. {
  965. listener->onTouchesCancelled(mutableTouches, event);
  966. }
  967. break;
  968. default:
  969. CCASSERT(false, "The eventcode is invalid.");
  970. break;
  971. }
  972. // If the event was stopped, return directly.
  973. if (event->isStopped())
  974. {
  975. updateListeners(event);
  976. return true;
  977. }
  978. return false;
  979. };
  980. dispatchTouchEventToListeners(allAtOnceListeners, onTouchesEvent);
  981. if (event->isStopped())
  982. {
  983. return;
  984. }
  985. }
  986. updateListeners(event);
  987. }
  988. void EventDispatcher::updateListeners(Event* event)
  989. {
  990. CCASSERT(_inDispatch > 0, "If program goes here, there should be event in dispatch.");
  991. if (_inDispatch > 1)
  992. return;
  993. auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID)
  994. {
  995. auto listenersIter = _listenerMap.find(listenerID);
  996. if (listenersIter == _listenerMap.end())
  997. return;
  998. auto listeners = listenersIter->second;
  999. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  1000. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  1001. if (sceneGraphPriorityListeners)
  1002. {
  1003. for (auto iter = sceneGraphPriorityListeners->begin(); iter != sceneGraphPriorityListeners->end();)
  1004. {
  1005. auto l = *iter;
  1006. if (!l->isRegistered())
  1007. {
  1008. iter = sceneGraphPriorityListeners->erase(iter);
  1009. // if item in toRemove list, remove it from the list
  1010. auto matchIter = std::find(_toRemovedListeners.begin(), _toRemovedListeners.end(), l);
  1011. if (matchIter != _toRemovedListeners.end())
  1012. _toRemovedListeners.erase(matchIter);
  1013. releaseListener(l);
  1014. }
  1015. else
  1016. {
  1017. ++iter;
  1018. }
  1019. }
  1020. }
  1021. if (fixedPriorityListeners)
  1022. {
  1023. for (auto iter = fixedPriorityListeners->begin(); iter != fixedPriorityListeners->end();)
  1024. {
  1025. auto l = *iter;
  1026. if (!l->isRegistered())
  1027. {
  1028. iter = fixedPriorityListeners->erase(iter);
  1029. // if item in toRemove list, remove it from the list
  1030. auto matchIter = std::find(_toRemovedListeners.begin(), _toRemovedListeners.end(), l);
  1031. if (matchIter != _toRemovedListeners.end())
  1032. _toRemovedListeners.erase(matchIter);
  1033. releaseListener(l);
  1034. }
  1035. else
  1036. {
  1037. ++iter;
  1038. }
  1039. }
  1040. }
  1041. if (sceneGraphPriorityListeners && sceneGraphPriorityListeners->empty())
  1042. {
  1043. listeners->clearSceneGraphListeners();
  1044. }
  1045. if (fixedPriorityListeners && fixedPriorityListeners->empty())
  1046. {
  1047. listeners->clearFixedListeners();
  1048. }
  1049. };
  1050. if (event->getType() == Event::Type::TOUCH)
  1051. {
  1052. onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID);
  1053. onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
  1054. }
  1055. else
  1056. {
  1057. onUpdateListeners(__getListenerID(event));
  1058. }
  1059. CCASSERT(_inDispatch == 1, "_inDispatch should be 1 here.");
  1060. for (auto iter = _listenerMap.begin(); iter != _listenerMap.end();)
  1061. {
  1062. if (iter->second->empty())
  1063. {
  1064. _priorityDirtyFlagMap.erase(iter->first);
  1065. delete iter->second;
  1066. iter = _listenerMap.erase(iter);
  1067. }
  1068. else
  1069. {
  1070. ++iter;
  1071. }
  1072. }
  1073. if (!_toAddedListeners.empty())
  1074. {
  1075. for (auto& listener : _toAddedListeners)
  1076. {
  1077. forceAddEventListener(listener);
  1078. }
  1079. _toAddedListeners.clear();
  1080. }
  1081. if (!_toRemovedListeners.empty())
  1082. {
  1083. cleanToRemovedListeners();
  1084. }
  1085. }
  1086. void EventDispatcher::updateDirtyFlagForSceneGraph()
  1087. {
  1088. if (!_dirtyNodes.empty())
  1089. {
  1090. for (auto& node : _dirtyNodes)
  1091. {
  1092. auto iter = _nodeListenersMap.find(node);
  1093. if (iter != _nodeListenersMap.end())
  1094. {
  1095. for (auto& l : *iter->second)
  1096. {
  1097. setDirty(l->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY);
  1098. }
  1099. }
  1100. }
  1101. _dirtyNodes.clear();
  1102. }
  1103. }
  1104. void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID)
  1105. {
  1106. DirtyFlag dirtyFlag = DirtyFlag::NONE;
  1107. auto dirtyIter = _priorityDirtyFlagMap.find(listenerID);
  1108. if (dirtyIter != _priorityDirtyFlagMap.end())
  1109. {
  1110. dirtyFlag = dirtyIter->second;
  1111. }
  1112. if (dirtyFlag != DirtyFlag::NONE)
  1113. {
  1114. // Clear the dirty flag first, if `rootNode` is nullptr, then set its dirty flag of scene graph priority
  1115. dirtyIter->second = DirtyFlag::NONE;
  1116. if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRIORITY)
  1117. {
  1118. sortEventListenersOfFixedPriority(listenerID);
  1119. }
  1120. if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY)
  1121. {
  1122. auto rootNode = Director::getInstance()->getRunningScene();
  1123. if (rootNode)
  1124. {
  1125. sortEventListenersOfSceneGraphPriority(listenerID, rootNode);
  1126. }
  1127. else
  1128. {
  1129. dirtyIter->second = DirtyFlag::SCENE_GRAPH_PRIORITY;
  1130. }
  1131. }
  1132. }
  1133. }
  1134. void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, Node* rootNode)
  1135. {
  1136. auto listeners = getListeners(listenerID);
  1137. if (listeners == nullptr)
  1138. return;
  1139. auto sceneGraphListeners = listeners->getSceneGraphPriorityListeners();
  1140. if (sceneGraphListeners == nullptr)
  1141. return;
  1142. // Reset priority index
  1143. _nodePriorityIndex = 0;
  1144. _nodePriorityMap.clear();
  1145. visitTarget(rootNode, true);
  1146. // After sort: priority < 0, > 0
  1147. std::stable_sort(sceneGraphListeners->begin(), sceneGraphListeners->end(), [this](const EventListener* l1, const EventListener* l2) {
  1148. return _nodePriorityMap[l1->getAssociatedNode()] > _nodePriorityMap[l2->getAssociatedNode()];
  1149. });
  1150. #if DUMP_LISTENER_ITEM_PRIORITY_INFO
  1151. log("-----------------------------------");
  1152. for (auto& l : *sceneGraphListeners)
  1153. {
  1154. log("listener priority: node ([%s]%p), priority (%d)", typeid(*l->_node).name(), l->_node, _nodePriorityMap[l->_node]);
  1155. }
  1156. #endif
  1157. }
  1158. void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID)
  1159. {
  1160. auto listeners = getListeners(listenerID);
  1161. if (listeners == nullptr)
  1162. return;
  1163. auto fixedListeners = listeners->getFixedPriorityListeners();
  1164. if (fixedListeners == nullptr)
  1165. return;
  1166. // After sort: priority < 0, > 0
  1167. std::stable_sort(fixedListeners->begin(), fixedListeners->end(), [](const EventListener* l1, const EventListener* l2) {
  1168. return l1->getFixedPriority() < l2->getFixedPriority();
  1169. });
  1170. // FIXME: Should use binary search
  1171. int index = 0;
  1172. for (auto& listener : *fixedListeners)
  1173. {
  1174. if (listener->getFixedPriority() >= 0)
  1175. break;
  1176. ++index;
  1177. }
  1178. listeners->setGt0Index(index);
  1179. #if DUMP_LISTENER_ITEM_PRIORITY_INFO
  1180. log("-----------------------------------");
  1181. for (auto& l : *fixedListeners)
  1182. {
  1183. log("listener priority: node (%p), fixed (%d)", l->_node, l->_fixedPriority);
  1184. }
  1185. #endif
  1186. }
  1187. EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID) const
  1188. {
  1189. auto iter = _listenerMap.find(listenerID);
  1190. if (iter != _listenerMap.end())
  1191. {
  1192. return iter->second;
  1193. }
  1194. return nullptr;
  1195. }
  1196. void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID)
  1197. {
  1198. auto listenerItemIter = _listenerMap.find(listenerID);
  1199. if (listenerItemIter != _listenerMap.end())
  1200. {
  1201. auto listeners = listenerItemIter->second;
  1202. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  1203. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  1204. auto removeAllListenersInVector = [&](std::vector<EventListener*>* listenerVector){
  1205. if (listenerVector == nullptr)
  1206. return;
  1207. for (auto iter = listenerVector->begin(); iter != listenerVector->end();)
  1208. {
  1209. auto l = *iter;
  1210. l->setRegistered(false);
  1211. if (l->getAssociatedNode() != nullptr)
  1212. {
  1213. dissociateNodeAndEventListener(l->getAssociatedNode(), l);
  1214. l->setAssociatedNode(nullptr); // nullptr out the node pointer so we don't have any dangling pointers to destroyed nodes.
  1215. }
  1216. if (_inDispatch == 0)
  1217. {
  1218. iter = listenerVector->erase(iter);
  1219. releaseListener(l);
  1220. }
  1221. else
  1222. {
  1223. ++iter;
  1224. }
  1225. }
  1226. };
  1227. removeAllListenersInVector(sceneGraphPriorityListeners);
  1228. removeAllListenersInVector(fixedPriorityListeners);
  1229. // Remove the dirty flag according the 'listenerID'.
  1230. // No need to check whether the dispatcher is dispatching event.
  1231. _priorityDirtyFlagMap.erase(listenerID);
  1232. if (!_inDispatch)
  1233. {
  1234. listeners->clear();
  1235. delete listeners;
  1236. _listenerMap.erase(listenerItemIter);
  1237. }
  1238. }
  1239. for (auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end();)
  1240. {
  1241. if ((*iter)->getListenerID() == listenerID)
  1242. {
  1243. (*iter)->setRegistered(false);
  1244. releaseListener(*iter);
  1245. iter = _toAddedListeners.erase(iter);
  1246. }
  1247. else
  1248. {
  1249. ++iter;
  1250. }
  1251. }
  1252. }
  1253. void EventDispatcher::removeEventListenersForType(EventListener::Type listenerType)
  1254. {
  1255. if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE)
  1256. {
  1257. removeEventListenersForListenerID(EventListenerTouchOneByOne::LISTENER_ID);
  1258. }
  1259. else if (listenerType == EventListener::Type::TOUCH_ALL_AT_ONCE)
  1260. {
  1261. removeEventListenersForListenerID(EventListenerTouchAllAtOnce::LISTENER_ID);
  1262. }
  1263. else if (listenerType == EventListener::Type::MOUSE)
  1264. {
  1265. removeEventListenersForListenerID(EventListenerMouse::LISTENER_ID);
  1266. }
  1267. else if (listenerType == EventListener::Type::ACCELERATION)
  1268. {
  1269. removeEventListenersForListenerID(EventListenerAcceleration::LISTENER_ID);
  1270. }
  1271. else if (listenerType == EventListener::Type::KEYBOARD)
  1272. {
  1273. removeEventListenersForListenerID(EventListenerKeyboard::LISTENER_ID);
  1274. }
  1275. else
  1276. {
  1277. CCASSERT(false, "Invalid listener type!");
  1278. }
  1279. }
  1280. void EventDispatcher::removeCustomEventListeners(const std::string& customEventName)
  1281. {
  1282. removeEventListenersForListenerID(customEventName);
  1283. }
  1284. void EventDispatcher::removeAllEventListeners()
  1285. {
  1286. bool cleanMap = true;
  1287. std::vector<EventListener::ListenerID> types;
  1288. types.reserve(_listenerMap.size());
  1289. for (const auto& e : _listenerMap)
  1290. {
  1291. if (_internalCustomListenerIDs.find(e.first) != _internalCustomListenerIDs.end())
  1292. {
  1293. cleanMap = false;
  1294. }
  1295. else
  1296. {
  1297. types.push_back(e.first);
  1298. }
  1299. }
  1300. for (const auto& type : types)
  1301. {
  1302. removeEventListenersForListenerID(type);
  1303. }
  1304. if (!_inDispatch && cleanMap)
  1305. {
  1306. _listenerMap.clear();
  1307. }
  1308. }
  1309. void EventDispatcher::setEnabled(bool isEnabled)
  1310. {
  1311. _isEnabled = isEnabled;
  1312. }
  1313. bool EventDispatcher::isEnabled() const
  1314. {
  1315. return _isEnabled;
  1316. }
  1317. void EventDispatcher::setDirtyForNode(Node* node)
  1318. {
  1319. // Mark the node dirty only when there is an eventlistener associated with it.
  1320. if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
  1321. {
  1322. _dirtyNodes.insert(node);
  1323. }
  1324. // Also set the dirty flag for node's children
  1325. const auto& children = node->getChildren();
  1326. for (const auto& child : children)
  1327. {
  1328. setDirtyForNode(child);
  1329. }
  1330. }
  1331. void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag)
  1332. {
  1333. auto iter = _priorityDirtyFlagMap.find(listenerID);
  1334. if (iter == _priorityDirtyFlagMap.end())
  1335. {
  1336. _priorityDirtyFlagMap.emplace(listenerID, flag);
  1337. }
  1338. else
  1339. {
  1340. int ret = (int)flag | (int)iter->second;
  1341. iter->second = (DirtyFlag) ret;
  1342. }
  1343. }
  1344. void EventDispatcher::cleanToRemovedListeners()
  1345. {
  1346. for (auto& l : _toRemovedListeners)
  1347. {
  1348. auto listenersIter = _listenerMap.find(l->getListenerID());
  1349. if (listenersIter == _listenerMap.end())
  1350. {
  1351. releaseListener(l);
  1352. continue;
  1353. }
  1354. bool find = false;
  1355. auto listeners = listenersIter->second;
  1356. auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
  1357. auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
  1358. if (sceneGraphPriorityListeners)
  1359. {
  1360. auto machedIter = std::find(sceneGraphPriorityListeners->begin(), sceneGraphPriorityListeners->end(), l);
  1361. if (machedIter != sceneGraphPriorityListeners->end())
  1362. {
  1363. find = true;
  1364. releaseListener(l);
  1365. sceneGraphPriorityListeners->erase(machedIter);
  1366. }
  1367. }
  1368. if (fixedPriorityListeners)
  1369. {
  1370. auto machedIter = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), l);
  1371. if (machedIter != fixedPriorityListeners->end())
  1372. {
  1373. find = true;
  1374. releaseListener(l);
  1375. fixedPriorityListeners->erase(machedIter);
  1376. }
  1377. }
  1378. if (find)
  1379. {
  1380. if (sceneGraphPriorityListeners && sceneGraphPriorityListeners->empty())
  1381. {
  1382. listeners->clearSceneGraphListeners();
  1383. }
  1384. if (fixedPriorityListeners && fixedPriorityListeners->empty())
  1385. {
  1386. listeners->clearFixedListeners();
  1387. }
  1388. }
  1389. else
  1390. CC_SAFE_RELEASE(l);
  1391. }
  1392. _toRemovedListeners.clear();
  1393. }
  1394. void EventDispatcher::releaseListener(EventListener* listener)
  1395. {
  1396. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  1397. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  1398. if (listener && sEngine)
  1399. {
  1400. sEngine->releaseScriptObject(this, listener);
  1401. }
  1402. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  1403. CC_SAFE_RELEASE(listener);
  1404. }
  1405. NS_CC_END