InputHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. * InputHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "InputHandler.h"
  12. #include "NotificationHandler.h"
  13. #include "InputSourceMouse.h"
  14. #include "InputSourceKeyboard.h"
  15. #include "InputSourceTouch.h"
  16. #include "InputSourceText.h"
  17. #include "InputSourceGameController.h"
  18. #include "../GameEngine.h"
  19. #include "../GameEngineUser.h"
  20. #include "../gui/CursorHandler.h"
  21. #include "../gui/EventDispatcher.h"
  22. #include "../gui/MouseButton.h"
  23. #include "../media/IMusicPlayer.h"
  24. #include "../media/ISoundPlayer.h"
  25. #include "../CMT.h"
  26. #include "../CPlayerInterface.h"
  27. #include "../../lib/AsyncRunner.h"
  28. #include "../../lib/CConfigHandler.h"
  29. #include <SDL_events.h>
  30. #include <SDL_timer.h>
  31. #include <SDL_clipboard.h>
  32. #include <SDL_power.h>
  33. InputHandler::InputHandler()
  34. : enableMouse(settings["input"]["enableMouse"].Bool())
  35. , enableTouch(settings["input"]["enableTouch"].Bool())
  36. , enableController(settings["input"]["enableController"].Bool())
  37. , currentInputMode(InputMode::KEYBOARD_AND_MOUSE)
  38. , mouseHandler(std::make_unique<InputSourceMouse>())
  39. , keyboardHandler(std::make_unique<InputSourceKeyboard>())
  40. , fingerHandler(std::make_unique<InputSourceTouch>())
  41. , textHandler(std::make_unique<InputSourceText>())
  42. , gameControllerHandler(std::make_unique<InputSourceGameController>())
  43. , cachedPowerStateMode(static_cast<int>(PowerStateMode::UNKNOWN))
  44. , cachedPowerStateSeconds(-1)
  45. , cachedPowerStatePercent(-1)
  46. , powerStateFrameCounter(0)
  47. {
  48. }
  49. InputHandler::~InputHandler() = default;
  50. void InputHandler::handleCurrentEvent(const SDL_Event & current)
  51. {
  52. switch (current.type)
  53. {
  54. case SDL_KEYDOWN:
  55. setCurrentInputMode(InputMode::KEYBOARD_AND_MOUSE);
  56. keyboardHandler->handleEventKeyDown(current.key);
  57. return;
  58. case SDL_KEYUP:
  59. keyboardHandler->handleEventKeyUp(current.key);
  60. return;
  61. #ifndef VCMI_EMULATE_TOUCHSCREEN_WITH_MOUSE
  62. case SDL_MOUSEMOTION:
  63. if (enableMouse)
  64. {
  65. setCurrentInputMode(InputMode::KEYBOARD_AND_MOUSE);
  66. mouseHandler->handleEventMouseMotion(current.motion);
  67. }
  68. return;
  69. case SDL_MOUSEBUTTONDOWN:
  70. if (enableMouse)
  71. {
  72. setCurrentInputMode(InputMode::KEYBOARD_AND_MOUSE);
  73. mouseHandler->handleEventMouseButtonDown(current.button);
  74. }
  75. return;
  76. case SDL_MOUSEBUTTONUP:
  77. if (enableMouse)
  78. mouseHandler->handleEventMouseButtonUp(current.button);
  79. return;
  80. case SDL_MOUSEWHEEL:
  81. if (enableMouse)
  82. mouseHandler->handleEventMouseWheel(current.wheel);
  83. return;
  84. #endif
  85. case SDL_TEXTINPUT:
  86. textHandler->handleEventTextInput(current.text);
  87. return;
  88. case SDL_TEXTEDITING:
  89. textHandler->handleEventTextEditing(current.edit);
  90. return;
  91. case SDL_FINGERMOTION:
  92. if (enableTouch)
  93. {
  94. setCurrentInputMode(InputMode::TOUCH);
  95. fingerHandler->handleEventFingerMotion(current.tfinger);
  96. }
  97. return;
  98. case SDL_FINGERDOWN:
  99. if (enableTouch)
  100. {
  101. setCurrentInputMode(InputMode::TOUCH);
  102. fingerHandler->handleEventFingerDown(current.tfinger);
  103. }
  104. return;
  105. case SDL_FINGERUP:
  106. if (enableTouch)
  107. fingerHandler->handleEventFingerUp(current.tfinger);
  108. return;
  109. case SDL_CONTROLLERAXISMOTION:
  110. if (enableController)
  111. {
  112. setCurrentInputMode(InputMode::CONTROLLER);
  113. gameControllerHandler->handleEventAxisMotion(current.caxis);
  114. }
  115. return;
  116. case SDL_CONTROLLERBUTTONDOWN:
  117. if (enableController)
  118. {
  119. setCurrentInputMode(InputMode::CONTROLLER);
  120. gameControllerHandler->handleEventButtonDown(current.cbutton);
  121. }
  122. return;
  123. case SDL_CONTROLLERBUTTONUP:
  124. if (enableController)
  125. gameControllerHandler->handleEventButtonUp(current.cbutton);
  126. return;
  127. }
  128. }
  129. void InputHandler::setCurrentInputMode(InputMode modi)
  130. {
  131. if(currentInputMode != modi)
  132. {
  133. currentInputMode = modi;
  134. ENGINE->events().dispatchInputModeChanged(modi);
  135. }
  136. }
  137. InputMode InputHandler::getCurrentInputMode()
  138. {
  139. return currentInputMode;
  140. }
  141. void InputHandler::copyToClipBoard(const std::string & text)
  142. {
  143. SDL_SetClipboardText(text.c_str());
  144. }
  145. void InputHandler::updatePowerState()
  146. {
  147. int seconds;
  148. int percent;
  149. auto sdlPowerState = SDL_GetPowerInfo(&seconds, &percent);
  150. PowerStateMode powerState = PowerStateMode::UNKNOWN;
  151. if(sdlPowerState == SDL_POWERSTATE_ON_BATTERY)
  152. powerState = PowerStateMode::ON_BATTERY;
  153. else if(sdlPowerState == SDL_POWERSTATE_CHARGING || sdlPowerState == SDL_POWERSTATE_CHARGED)
  154. powerState = PowerStateMode::CHARGING;
  155. cachedPowerStateMode.store(static_cast<int>(powerState), std::memory_order_relaxed);
  156. cachedPowerStateSeconds.store(seconds, std::memory_order_relaxed);
  157. cachedPowerStatePercent.store(percent, std::memory_order_relaxed);
  158. }
  159. PowerState InputHandler::getPowerState()
  160. {
  161. return PowerState{
  162. static_cast<PowerStateMode>(cachedPowerStateMode.load(std::memory_order_relaxed)),
  163. cachedPowerStateSeconds.load(std::memory_order_relaxed),
  164. cachedPowerStatePercent.load(std::memory_order_relaxed)
  165. };
  166. }
  167. std::vector<SDL_Event> InputHandler::acquireEvents()
  168. {
  169. std::unique_lock<std::mutex> lock(eventsMutex);
  170. std::vector<SDL_Event> result;
  171. std::swap(result, eventsQueue);
  172. return result;
  173. }
  174. void InputHandler::processEvents()
  175. {
  176. // Update power state every ~300 frames (approx 5 seconds at 60 FPS)
  177. if (++powerStateFrameCounter >= 300)
  178. {
  179. const auto updateTask = [this]()
  180. {
  181. updatePowerState();
  182. };
  183. ENGINE->async().run(updateTask);
  184. powerStateFrameCounter = 0;
  185. }
  186. std::vector<SDL_Event> eventsToProcess = acquireEvents();
  187. for(const auto & currentEvent : eventsToProcess)
  188. handleCurrentEvent(currentEvent);
  189. gameControllerHandler->handleUpdate();
  190. fingerHandler->handleUpdate();
  191. }
  192. bool InputHandler::ignoreEventsUntilInput()
  193. {
  194. bool inputFound = false;
  195. std::unique_lock<std::mutex> lock(eventsMutex);
  196. for(const auto & event : eventsQueue)
  197. {
  198. switch(event.type)
  199. {
  200. case SDL_MOUSEBUTTONDOWN:
  201. case SDL_FINGERDOWN:
  202. case SDL_KEYDOWN:
  203. case SDL_CONTROLLERBUTTONDOWN:
  204. inputFound = true;
  205. }
  206. }
  207. eventsQueue.clear();
  208. return inputFound;
  209. }
  210. void InputHandler::preprocessEvent(const SDL_Event & ev)
  211. {
  212. if(ev.type == SDL_QUIT)
  213. {
  214. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  215. #ifdef VCMI_ANDROID
  216. ENGINE->user().onShutdownRequested(false);
  217. #else
  218. ENGINE->user().onShutdownRequested(true);
  219. #endif
  220. return;
  221. }
  222. else if(ev.type == SDL_APP_WILLENTERBACKGROUND)
  223. {
  224. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  225. ENGINE->user().onAppPaused();
  226. return;
  227. }
  228. else if(ev.type == SDL_KEYDOWN)
  229. {
  230. if(ev.key.keysym.sym == SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT))
  231. {
  232. // FIXME: dead code? Looks like intercepted by OS/SDL and delivered as SDL_Quit instead?
  233. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  234. ENGINE->user().onShutdownRequested(true);
  235. return;
  236. }
  237. if(ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK && !settings["input"]["handleBackRightMouseButton"].Bool())
  238. {
  239. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  240. ENGINE->user().onShutdownRequested(true);
  241. return;
  242. }
  243. }
  244. else if(ev.type == SDL_USEREVENT)
  245. {
  246. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  247. handleUserEvent(ev.user);
  248. return;
  249. }
  250. else if(ev.type == SDL_WINDOWEVENT)
  251. {
  252. switch (ev.window.event) {
  253. case SDL_WINDOWEVENT_RESTORED:
  254. #ifndef VCMI_IOS
  255. {
  256. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  257. ENGINE->onScreenResize(false, false);
  258. }
  259. #endif
  260. break;
  261. case SDL_WINDOWEVENT_SIZE_CHANGED:
  262. {
  263. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  264. #ifdef VCMI_MOBILE
  265. ENGINE->onScreenResize(true, false);
  266. #else
  267. ENGINE->onScreenResize(true, true);
  268. #endif
  269. }
  270. break;
  271. case SDL_WINDOWEVENT_FOCUS_GAINED:
  272. {
  273. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  274. if(settings["general"]["audioMuteFocus"].Bool()) {
  275. ENGINE->music().setVolume(settings["general"]["music"].Integer());
  276. ENGINE->sound().setVolume(settings["general"]["sound"].Integer());
  277. }
  278. }
  279. break;
  280. case SDL_WINDOWEVENT_FOCUS_LOST:
  281. {
  282. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  283. if(settings["general"]["audioMuteFocus"].Bool()) {
  284. ENGINE->music().setVolume(0);
  285. ENGINE->sound().setVolume(0);
  286. }
  287. }
  288. break;
  289. }
  290. return;
  291. }
  292. else if(ev.type == SDL_SYSWMEVENT)
  293. {
  294. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  295. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  296. {
  297. NotificationHandler::handleSdlEvent(ev);
  298. }
  299. }
  300. else if(ev.type == SDL_CONTROLLERDEVICEADDED)
  301. {
  302. gameControllerHandler->handleEventDeviceAdded(ev.cdevice);
  303. return;
  304. }
  305. else if(ev.type == SDL_CONTROLLERDEVICEREMOVED)
  306. {
  307. gameControllerHandler->handleEventDeviceRemoved(ev.cdevice);
  308. return;
  309. }
  310. else if(ev.type == SDL_CONTROLLERDEVICEREMAPPED)
  311. {
  312. gameControllerHandler->handleEventDeviceRemapped(ev.cdevice);
  313. return;
  314. }
  315. #ifndef VCMI_EMULATE_TOUCHSCREEN_WITH_MOUSE
  316. //preprocessing
  317. if(ev.type == SDL_MOUSEMOTION)
  318. {
  319. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  320. ENGINE->cursor().cursorMove(ev.motion.x, ev.motion.y);
  321. }
  322. #endif
  323. {
  324. std::unique_lock<std::mutex> lock(eventsMutex);
  325. // In a sequence of motion events, skip all but the last one.
  326. // This prevents freezes when every motion event takes longer to handle than interval at which
  327. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  328. // so that the events would start piling up faster than they can be processed.
  329. if (!eventsQueue.empty())
  330. {
  331. const SDL_Event & prev = eventsQueue.back();
  332. if(ev.type == SDL_MOUSEMOTION && prev.type == SDL_MOUSEMOTION)
  333. {
  334. SDL_Event accumulated = ev;
  335. accumulated.motion.xrel += prev.motion.xrel;
  336. accumulated.motion.yrel += prev.motion.yrel;
  337. eventsQueue.back() = accumulated;
  338. return;
  339. }
  340. if(ev.type == SDL_FINGERMOTION && prev.type == SDL_FINGERMOTION && ev.tfinger.fingerId == prev.tfinger.fingerId)
  341. {
  342. SDL_Event accumulated = ev;
  343. accumulated.tfinger.dx += prev.tfinger.dx;
  344. accumulated.tfinger.dy += prev.tfinger.dy;
  345. eventsQueue.back() = accumulated;
  346. return;
  347. }
  348. }
  349. eventsQueue.push_back(ev);
  350. }
  351. }
  352. void InputHandler::fetchEvents()
  353. {
  354. SDL_Event ev;
  355. while(1 == SDL_PollEvent(&ev))
  356. {
  357. preprocessEvent(ev);
  358. }
  359. }
  360. bool InputHandler::isKeyboardCmdDown() const
  361. {
  362. return keyboardHandler->isKeyboardCmdDown();
  363. }
  364. bool InputHandler::isKeyboardCtrlDown() const
  365. {
  366. return keyboardHandler->isKeyboardCtrlDown();
  367. }
  368. bool InputHandler::isKeyboardAltDown() const
  369. {
  370. return keyboardHandler->isKeyboardAltDown();
  371. }
  372. bool InputHandler::isKeyboardShiftDown() const
  373. {
  374. return keyboardHandler->isKeyboardShiftDown();
  375. }
  376. void InputHandler::moveCursorPosition(const Point & distance)
  377. {
  378. setCursorPosition(getCursorPosition() + distance);
  379. }
  380. void InputHandler::setCursorPosition(const Point & position)
  381. {
  382. cursorPosition = position;
  383. ENGINE->events().dispatchMouseMoved(Point(0, 0), position);
  384. }
  385. void InputHandler::startTextInput(const Rect & where)
  386. {
  387. textHandler->startTextInput(where);
  388. }
  389. void InputHandler::stopTextInput()
  390. {
  391. textHandler->stopTextInput();
  392. }
  393. void InputHandler::hapticFeedback()
  394. {
  395. if(currentInputMode == InputMode::TOUCH)
  396. fingerHandler->hapticFeedback();
  397. }
  398. uint32_t InputHandler::getTicks()
  399. {
  400. return SDL_GetTicks();
  401. }
  402. bool InputHandler::hasTouchInputDevice() const
  403. {
  404. return fingerHandler->hasTouchInputDevice();
  405. }
  406. int InputHandler::getNumTouchFingers() const
  407. {
  408. if(currentInputMode != InputMode::TOUCH)
  409. return 0;
  410. return fingerHandler->getNumTouchFingers();
  411. }
  412. void InputHandler::dispatchMainThread(const std::function<void()> & functor)
  413. {
  414. auto heapFunctor = std::make_unique<std::function<void()>>(functor);
  415. SDL_Event event;
  416. event.user.type = SDL_USEREVENT;
  417. event.user.code = 0;
  418. event.user.data1 = nullptr;
  419. event.user.data2 = nullptr;
  420. SDL_PushEvent(&event);
  421. // NOTE: approach with dispatchedTasks container is a bit excessive
  422. // used mostly to prevent false-positives leaks in analyzers
  423. dispatchedTasks.push(std::move(heapFunctor));
  424. }
  425. void InputHandler::handleUserEvent(const SDL_UserEvent & current)
  426. {
  427. std::unique_ptr<std::function<void()>> task;
  428. if (!dispatchedTasks.try_pop(task))
  429. {
  430. logGlobal->error("InputHandler::handleUserEvent received without active task!");
  431. return;
  432. }
  433. (*task)();
  434. }
  435. const Point & InputHandler::getCursorPosition() const
  436. {
  437. return cursorPosition;
  438. }