InputHandler.cpp 11 KB

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