EventDispatcher.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /****************************************************************************
  2. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  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. #include "EventDispatcher.h"
  21. #include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
  22. #include "cocos/scripting/js-bindings/manual/jsb_global.h"
  23. #include "cocos/scripting/js-bindings/event/CustomEventTypes.h"
  24. namespace {
  25. se::Value _tickVal;
  26. std::vector<se::Object*> _jsTouchObjPool;
  27. se::Object* _jsTouchObjArray = nullptr;
  28. se::Object* _jsMouseEventObj = nullptr;
  29. se::Object* _jsKeyboardEventObj = nullptr;
  30. se::Object* _jsResizeEventObj = nullptr;
  31. se::Object* _jsOrientationEventObj = nullptr;
  32. bool _inited = false;
  33. }
  34. namespace cocos2d
  35. {
  36. std::unordered_map<std::string, EventDispatcher::Node*> EventDispatcher::_listeners;
  37. void EventDispatcher::init()
  38. {
  39. _inited = true;
  40. se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){
  41. EventDispatcher::destroy();
  42. });
  43. }
  44. void EventDispatcher::destroy()
  45. {
  46. for (auto touchObj : _jsTouchObjPool)
  47. {
  48. touchObj->unroot();
  49. touchObj->decRef();
  50. }
  51. _jsTouchObjPool.clear();
  52. if (_jsTouchObjArray != nullptr)
  53. {
  54. _jsTouchObjArray->unroot();
  55. _jsTouchObjArray->decRef();
  56. _jsTouchObjArray = nullptr;
  57. }
  58. if (_jsMouseEventObj != nullptr)
  59. {
  60. _jsMouseEventObj->unroot();
  61. _jsMouseEventObj->decRef();
  62. _jsMouseEventObj = nullptr;
  63. }
  64. if (_jsKeyboardEventObj != nullptr)
  65. {
  66. _jsKeyboardEventObj->unroot();
  67. _jsKeyboardEventObj->decRef();
  68. _jsKeyboardEventObj = nullptr;
  69. }
  70. if (_jsResizeEventObj != nullptr)
  71. {
  72. _jsResizeEventObj->unroot();
  73. _jsResizeEventObj->decRef();
  74. _jsResizeEventObj = nullptr;
  75. }
  76. if (_jsOrientationEventObj != nullptr)
  77. {
  78. _jsOrientationEventObj->unroot();
  79. _jsOrientationEventObj->decRef();
  80. _jsOrientationEventObj = nullptr;
  81. }
  82. _inited = false;
  83. _tickVal.setUndefined();
  84. }
  85. void EventDispatcher::dispatchTouchEvent(const struct TouchEvent& touchEvent)
  86. {
  87. if (!se::ScriptEngine::getInstance()->isValid())
  88. return;
  89. se::AutoHandleScope scope;
  90. assert(_inited);
  91. if (_jsTouchObjArray == nullptr)
  92. {
  93. _jsTouchObjArray = se::Object::createArrayObject(0);
  94. _jsTouchObjArray->root();
  95. }
  96. _jsTouchObjArray->setProperty("length", se::Value(touchEvent.touches.size()));
  97. while (_jsTouchObjPool.size() < touchEvent.touches.size())
  98. {
  99. se::Object* touchObj = se::Object::createPlainObject();
  100. touchObj->root();
  101. _jsTouchObjPool.push_back(touchObj);
  102. }
  103. uint32_t touchIndex = 0;
  104. int poolIndex = 0;
  105. for (const auto& touch : touchEvent.touches)
  106. {
  107. se::Object* jsTouch = _jsTouchObjPool.at(poolIndex++);
  108. jsTouch->setProperty("identifier", se::Value(touch.index));
  109. jsTouch->setProperty("clientX", se::Value(touch.x));
  110. jsTouch->setProperty("clientY", se::Value(touch.y));
  111. jsTouch->setProperty("pageX", se::Value(touch.x));
  112. jsTouch->setProperty("pageY", se::Value(touch.y));
  113. _jsTouchObjArray->setArrayElement(touchIndex, se::Value(jsTouch));
  114. ++touchIndex;
  115. }
  116. const char* eventName = nullptr;
  117. switch (touchEvent.type) {
  118. case TouchEvent::Type::BEGAN:
  119. eventName = "onTouchStart";
  120. break;
  121. case TouchEvent::Type::MOVED:
  122. eventName = "onTouchMove";
  123. break;
  124. case TouchEvent::Type::ENDED:
  125. eventName = "onTouchEnd";
  126. break;
  127. case TouchEvent::Type::CANCELLED:
  128. eventName = "onTouchCancel";
  129. break;
  130. default:
  131. assert(false);
  132. break;
  133. }
  134. se::Value callbackVal;
  135. if (__jsbObj->getProperty(eventName, &callbackVal) && !callbackVal.isNullOrUndefined())
  136. {
  137. se::ValueArray args;
  138. args.push_back(se::Value(_jsTouchObjArray));
  139. callbackVal.toObject()->call(args, nullptr);
  140. }
  141. }
  142. void EventDispatcher::dispatchMouseEvent(const struct MouseEvent& mouseEvent)
  143. {
  144. if (!se::ScriptEngine::getInstance()->isValid())
  145. return;
  146. se::AutoHandleScope scope;
  147. assert(_inited);
  148. if (_jsMouseEventObj == nullptr)
  149. {
  150. _jsMouseEventObj = se::Object::createPlainObject();
  151. _jsMouseEventObj->root();
  152. }
  153. const auto& xVal = se::Value(mouseEvent.x);
  154. const auto& yVal = se::Value(mouseEvent.y);
  155. const MouseEvent::Type type = mouseEvent.type;
  156. if (type == MouseEvent::Type::WHEEL)
  157. {
  158. _jsMouseEventObj->setProperty("wheelDeltaX", xVal);
  159. _jsMouseEventObj->setProperty("wheelDeltaY", yVal);
  160. }
  161. else
  162. {
  163. if (type == MouseEvent::Type::DOWN || type == MouseEvent::Type::UP)
  164. {
  165. _jsMouseEventObj->setProperty("button", se::Value(mouseEvent.button));
  166. }
  167. _jsMouseEventObj->setProperty("x", xVal);
  168. _jsMouseEventObj->setProperty("y", yVal);
  169. }
  170. const char* eventName = nullptr;
  171. switch (type) {
  172. case MouseEvent::Type::DOWN:
  173. eventName = "onMouseDown";
  174. break;
  175. case MouseEvent::Type::MOVE:
  176. eventName = "onMouseMove";
  177. break;
  178. case MouseEvent::Type::UP:
  179. eventName = "onMouseUp";
  180. break;
  181. case MouseEvent::Type::WHEEL:
  182. eventName = "onMouseWheel";
  183. break;
  184. default:
  185. assert(false);
  186. break;
  187. }
  188. se::Value callbackVal;
  189. if (__jsbObj->getProperty(eventName, &callbackVal) && !callbackVal.isNullOrUndefined())
  190. {
  191. se::ValueArray args;
  192. args.push_back(se::Value(_jsMouseEventObj));
  193. callbackVal.toObject()->call(args, nullptr);
  194. }
  195. }
  196. void EventDispatcher::dispatchKeyboardEvent(const struct KeyboardEvent& keyboardEvent)
  197. {
  198. if (!se::ScriptEngine::getInstance()->isValid())
  199. return;
  200. se::AutoHandleScope scope;
  201. assert(_inited);
  202. if (_jsKeyboardEventObj == nullptr)
  203. {
  204. _jsKeyboardEventObj = se::Object::createPlainObject();
  205. _jsKeyboardEventObj->root();
  206. }
  207. const char* eventName = nullptr;
  208. switch (keyboardEvent.action) {
  209. case KeyboardEvent::Action::PRESS:
  210. case KeyboardEvent::Action::REPEAT:
  211. eventName = "onKeyDown";
  212. break;
  213. case KeyboardEvent::Action::RELEASE:
  214. eventName = "onKeyUp";
  215. break;
  216. default:
  217. assert(false);
  218. break;
  219. }
  220. se::Value callbackVal;
  221. if (__jsbObj->getProperty(eventName, &callbackVal) && !callbackVal.isNullOrUndefined())
  222. {
  223. _jsKeyboardEventObj->setProperty("altKey", se::Value(keyboardEvent.altKeyActive));
  224. _jsKeyboardEventObj->setProperty("ctrlKey", se::Value(keyboardEvent.ctrlKeyActive));
  225. _jsKeyboardEventObj->setProperty("metaKey", se::Value(keyboardEvent.metaKeyActive));
  226. _jsKeyboardEventObj->setProperty("shiftKey", se::Value(keyboardEvent.shiftKeyActive));
  227. _jsKeyboardEventObj->setProperty("repeat", se::Value(keyboardEvent.action == KeyboardEvent::Action::REPEAT));
  228. _jsKeyboardEventObj->setProperty("keyCode", se::Value(keyboardEvent.key));
  229. se::ValueArray args;
  230. args.push_back(se::Value(_jsKeyboardEventObj));
  231. callbackVal.toObject()->call(args, nullptr);
  232. }
  233. }
  234. void EventDispatcher::dispatchTickEvent(float dt)
  235. {
  236. if (!se::ScriptEngine::getInstance()->isValid())
  237. return;
  238. se::AutoHandleScope scope;
  239. if (_tickVal.isUndefined())
  240. {
  241. se::ScriptEngine::getInstance()->getGlobalObject()->getProperty("gameTick", &_tickVal);
  242. }
  243. static std::chrono::steady_clock::time_point prevTime;
  244. prevTime = std::chrono::steady_clock::now();
  245. se::ValueArray args;
  246. long long microSeconds = std::chrono::duration_cast<std::chrono::microseconds>(prevTime - se::ScriptEngine::getInstance()->getStartTime()).count();
  247. args.push_back(se::Value((double)(microSeconds * 0.001)));
  248. _tickVal.toObject()->call(args, nullptr);
  249. }
  250. void EventDispatcher::dispatchResizeEvent(int width, int height)
  251. {
  252. if (!se::ScriptEngine::getInstance()->isValid())
  253. return;
  254. se::AutoHandleScope scope;
  255. assert(_inited);
  256. if (_jsResizeEventObj == nullptr)
  257. {
  258. _jsResizeEventObj = se::Object::createPlainObject();
  259. _jsResizeEventObj->root();
  260. }
  261. se::Value func;
  262. __jsbObj->getProperty("onResize", &func);
  263. if (func.isObject() && func.toObject()->isFunction())
  264. {
  265. _jsResizeEventObj->setProperty("width", se::Value(width));
  266. _jsResizeEventObj->setProperty("height", se::Value(height));
  267. se::ValueArray args;
  268. args.push_back(se::Value(_jsResizeEventObj));
  269. func.toObject()->call(args, nullptr);
  270. }
  271. }
  272. void EventDispatcher::dispatchOrientationChangeEvent(int rotation)
  273. {
  274. if (!se::ScriptEngine::getInstance()->isValid())
  275. return;
  276. se::AutoHandleScope scope;
  277. assert(_inited);
  278. if (_jsOrientationEventObj == nullptr)
  279. {
  280. _jsOrientationEventObj = se::Object::createPlainObject();
  281. _jsOrientationEventObj->root();
  282. }
  283. se::Value func;
  284. __jsbObj->getProperty("onOrientationChanged", &func);
  285. if (func.isObject() && func.toObject()->isFunction())
  286. {
  287. _jsOrientationEventObj->setProperty("rotation", se::Value(rotation));
  288. se::ValueArray args;
  289. args.push_back(se::Value(_jsOrientationEventObj));
  290. func.toObject()->call(args, nullptr);
  291. }
  292. }
  293. static void dispatchEnterBackgroundOrForegroundEvent(const char* funcName)
  294. {
  295. if (!se::ScriptEngine::getInstance()->isValid())
  296. return;
  297. se::AutoHandleScope scope;
  298. assert(_inited);
  299. se::Value func;
  300. __jsbObj->getProperty(funcName, &func);
  301. if (func.isObject() && func.toObject()->isFunction())
  302. {
  303. func.toObject()->call(se::EmptyValueArray, nullptr);
  304. }
  305. }
  306. void EventDispatcher::dispatchOnPauseEvent()
  307. {
  308. // dispatch to Native
  309. CustomEvent event;
  310. event.name = EVENT_ON_PAUSE;
  311. EventDispatcher::dispatchCustomEvent(event);
  312. // dispatch to JavaScript
  313. dispatchEnterBackgroundOrForegroundEvent("onPause");
  314. }
  315. void EventDispatcher::dispatchOnResumeEvent()
  316. {
  317. // dispatch to Native
  318. CustomEvent event;
  319. event.name = EVENT_ON_RESUME;
  320. EventDispatcher::dispatchCustomEvent(event);
  321. // dispatch to JavaScript
  322. dispatchEnterBackgroundOrForegroundEvent("onResume");
  323. }
  324. uint32_t EventDispatcher::addCustomEventListener(const std::string& eventName, const CustomEventListener& listener)
  325. {
  326. static uint32_t __listenerIDCounter = 0;
  327. uint32_t listenerID = ++__listenerIDCounter;
  328. listenerID = listenerID == 0 ? 1 : listenerID;
  329. Node* newNode = new Node();
  330. newNode->listener = listener;
  331. newNode->listenerID = listenerID;
  332. newNode->next = nullptr;
  333. auto iter = _listeners.find(eventName);
  334. if (iter == _listeners.end())
  335. {
  336. _listeners.emplace(eventName, newNode);
  337. }
  338. else
  339. {
  340. Node* node = iter->second;
  341. assert(node != nullptr);
  342. Node* prev = nullptr;
  343. while (node != nullptr)
  344. {
  345. prev = node;
  346. node = node->next;
  347. }
  348. prev->next = newNode;
  349. }
  350. return listenerID;
  351. }
  352. void EventDispatcher::removeCustomEventListener(const std::string& eventName, uint32_t listenerID)
  353. {
  354. if (eventName.empty())
  355. return;
  356. if (listenerID == 0)
  357. return;
  358. auto iter = _listeners.find(eventName);
  359. if (iter != _listeners.end())
  360. {
  361. Node* prev = nullptr;
  362. Node* node = iter->second;
  363. while (node != nullptr)
  364. {
  365. if (node->listenerID == listenerID)
  366. {
  367. if (prev != nullptr)
  368. {
  369. prev->next = node->next;
  370. }
  371. else if (node->next)
  372. {
  373. _listeners[eventName] = node->next;
  374. }
  375. else
  376. {
  377. _listeners.erase(iter);
  378. }
  379. delete node;
  380. return;
  381. }
  382. prev = node;
  383. node = node->next;
  384. }
  385. }
  386. }
  387. void EventDispatcher::removeAllCustomEventListeners(const std::string& eventName)
  388. {
  389. auto iter = _listeners.find(eventName);
  390. if (iter != _listeners.end())
  391. {
  392. Node* node = iter->second;
  393. while (node != nullptr)
  394. {
  395. Node* next = node->next;
  396. delete node;
  397. node = next;
  398. }
  399. _listeners.erase(iter);
  400. }
  401. }
  402. void EventDispatcher::dispatchCustomEvent(const CustomEvent& event)
  403. {
  404. auto iter = _listeners.find(event.name);
  405. if (iter != _listeners.end())
  406. {
  407. Node* next = nullptr;
  408. Node* node = iter->second;
  409. while (node != nullptr)
  410. {
  411. next = node->next;
  412. node->listener(event);
  413. node = next;
  414. }
  415. }
  416. }
  417. } // end of namespace cocos2d