CGuiHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. /*
  2. * CGuiHandler.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 "CGuiHandler.h"
  12. #include "../lib/CondSh.h"
  13. #include "CIntObject.h"
  14. #include "CursorHandler.h"
  15. #include "ShortcutHandler.h"
  16. #include "FramerateManager.h"
  17. #include "WindowHandler.h"
  18. #include "../CGameInfo.h"
  19. #include "../render/Colors.h"
  20. #include "../renderSDL/SDL_Extensions.h"
  21. #include "../renderSDL/ScreenHandler.h"
  22. #include "../CMT.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../battle/BattleInterface.h"
  25. #include "../../lib/CThreadHelper.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include <SDL_render.h>
  28. #include <SDL_timer.h>
  29. #include <SDL_events.h>
  30. #include <SDL_keycode.h>
  31. #ifdef VCMI_APPLE
  32. #include <dispatch/dispatch.h>
  33. #endif
  34. #ifdef VCMI_IOS
  35. #include "ios/utils.h"
  36. #endif
  37. CGuiHandler GH;
  38. extern std::queue<SDL_Event> SDLEventsQueue;
  39. extern boost::mutex eventsM;
  40. boost::thread_specific_ptr<bool> inGuiThread;
  41. SObjectConstruction::SObjectConstruction(CIntObject *obj)
  42. :myObj(obj)
  43. {
  44. GH.createdObj.push_front(obj);
  45. GH.captureChildren = true;
  46. }
  47. SObjectConstruction::~SObjectConstruction()
  48. {
  49. assert(GH.createdObj.size());
  50. assert(GH.createdObj.front() == myObj);
  51. GH.createdObj.pop_front();
  52. GH.captureChildren = GH.createdObj.size();
  53. }
  54. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  55. {
  56. previousCapture = GH.captureChildren;
  57. GH.captureChildren = false;
  58. prevActions = GH.defActionsDef;
  59. GH.defActionsDef = actions;
  60. }
  61. SSetCaptureState::~SSetCaptureState()
  62. {
  63. GH.captureChildren = previousCapture;
  64. GH.defActionsDef = prevActions;
  65. }
  66. static inline void
  67. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  68. {
  69. if (mask & flag)
  70. cb(lst);
  71. }
  72. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  73. {
  74. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  75. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  76. processList(CIntObject::MCLICK,activityFlag,&mclickable,cb);
  77. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  78. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  79. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  80. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  81. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  82. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  83. processList(CIntObject::TEXTINPUT,activityFlag,&textInterested,cb);
  84. }
  85. void CGuiHandler::init()
  86. {
  87. windowHandlerInstance = std::make_unique<WindowHandler>();
  88. screenHandlerInstance = std::make_unique<ScreenHandler>();
  89. shortcutsHandlerInstance = std::make_unique<ShortcutHandler>();
  90. framerateManagerInstance = std::make_unique<FramerateManager>(settings["video"]["targetfps"].Integer());
  91. isPointerRelativeMode = settings["general"]["userRelativePointer"].Bool();
  92. pointerSpeedMultiplier = settings["general"]["relativePointerSpeedMultiplier"].Float();
  93. }
  94. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  95. {
  96. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  97. lst->push_front(elem);
  98. });
  99. elem->active_m |= activityFlag;
  100. }
  101. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  102. {
  103. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  104. auto hlp = std::find(lst->begin(),lst->end(),elem);
  105. assert(hlp != lst->end());
  106. lst->erase(hlp);
  107. });
  108. elem->active_m &= ~activityFlag;
  109. }
  110. void CGuiHandler::updateTime()
  111. {
  112. int ms = framerateManager().getElapsedMilliseconds();
  113. std::list<CIntObject*> hlp = timeinterested;
  114. for (auto & elem : hlp)
  115. {
  116. if(!vstd::contains(timeinterested,elem)) continue;
  117. (elem)->tick(ms);
  118. }
  119. }
  120. void CGuiHandler::handleEvents()
  121. {
  122. //player interface may want special event handling
  123. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  124. return;
  125. boost::unique_lock<boost::mutex> lock(eventsM);
  126. while(!SDLEventsQueue.empty())
  127. {
  128. continueEventHandling = true;
  129. SDL_Event currentEvent = SDLEventsQueue.front();
  130. if (currentEvent.type == SDL_MOUSEMOTION)
  131. {
  132. cursorPosition = Point(currentEvent.motion.x, currentEvent.motion.y);
  133. mouseButtonsMask = currentEvent.motion.state;
  134. }
  135. SDLEventsQueue.pop();
  136. // In a sequence of mouse motion events, skip all but the last one.
  137. // This prevents freezes when every motion event takes longer to handle than interval at which
  138. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  139. // so that the events would start piling up faster than they can be processed.
  140. if ((currentEvent.type == SDL_MOUSEMOTION) && !SDLEventsQueue.empty() && (SDLEventsQueue.front().type == SDL_MOUSEMOTION))
  141. continue;
  142. handleCurrentEvent(currentEvent);
  143. }
  144. }
  145. void CGuiHandler::convertTouchToMouse(SDL_Event * current)
  146. {
  147. int rLogicalWidth, rLogicalHeight;
  148. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  149. int adjustedMouseY = (int)(current->tfinger.y * rLogicalHeight);
  150. int adjustedMouseX = (int)(current->tfinger.x * rLogicalWidth);
  151. current->button.x = adjustedMouseX;
  152. current->motion.x = adjustedMouseX;
  153. current->button.y = adjustedMouseY;
  154. current->motion.y = adjustedMouseY;
  155. }
  156. void CGuiHandler::fakeMoveCursor(float dx, float dy)
  157. {
  158. int x, y, w, h;
  159. SDL_Event event;
  160. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  161. sme.state = SDL_GetMouseState(&x, &y);
  162. SDL_GetWindowSize(mainWindow, &w, &h);
  163. sme.x = CCS->curh->position().x + (int)(GH.pointerSpeedMultiplier * w * dx);
  164. sme.y = CCS->curh->position().y + (int)(GH.pointerSpeedMultiplier * h * dy);
  165. vstd::abetween(sme.x, 0, w);
  166. vstd::abetween(sme.y, 0, h);
  167. event.motion = sme;
  168. SDL_PushEvent(&event);
  169. }
  170. void CGuiHandler::fakeMouseMove()
  171. {
  172. fakeMoveCursor(0, 0);
  173. }
  174. void CGuiHandler::startTextInput(const Rect & whereInput)
  175. {
  176. #ifdef VCMI_APPLE
  177. dispatch_async(dispatch_get_main_queue(), ^{
  178. #endif
  179. // TODO ios: looks like SDL bug actually, try fixing there
  180. auto renderer = SDL_GetRenderer(mainWindow);
  181. float scaleX, scaleY;
  182. SDL_Rect viewport;
  183. SDL_RenderGetScale(renderer, &scaleX, &scaleY);
  184. SDL_RenderGetViewport(renderer, &viewport);
  185. #ifdef VCMI_IOS
  186. const auto nativeScale = iOS_utils::screenScale();
  187. scaleX /= nativeScale;
  188. scaleY /= nativeScale;
  189. #endif
  190. SDL_Rect rectInScreenCoordinates;
  191. rectInScreenCoordinates.x = (viewport.x + whereInput.x) * scaleX;
  192. rectInScreenCoordinates.y = (viewport.y + whereInput.y) * scaleY;
  193. rectInScreenCoordinates.w = whereInput.w * scaleX;
  194. rectInScreenCoordinates.h = whereInput.h * scaleY;
  195. SDL_SetTextInputRect(&rectInScreenCoordinates);
  196. if (SDL_IsTextInputActive() == SDL_FALSE)
  197. {
  198. SDL_StartTextInput();
  199. }
  200. #ifdef VCMI_APPLE
  201. });
  202. #endif
  203. }
  204. void CGuiHandler::stopTextInput()
  205. {
  206. #ifdef VCMI_APPLE
  207. dispatch_async(dispatch_get_main_queue(), ^{
  208. #endif
  209. if (SDL_IsTextInputActive() == SDL_TRUE)
  210. {
  211. SDL_StopTextInput();
  212. }
  213. #ifdef VCMI_APPLE
  214. });
  215. #endif
  216. }
  217. void CGuiHandler::fakeMouseButtonEventRelativeMode(bool down, bool right)
  218. {
  219. SDL_Event event;
  220. SDL_MouseButtonEvent sme = {SDL_MOUSEBUTTONDOWN, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  221. if(!down)
  222. {
  223. sme.type = SDL_MOUSEBUTTONUP;
  224. }
  225. sme.button = right ? SDL_BUTTON_RIGHT : SDL_BUTTON_LEFT;
  226. sme.x = CCS->curh->position().x;
  227. sme.y = CCS->curh->position().y;
  228. float xScale, yScale;
  229. int w, h, rLogicalWidth, rLogicalHeight;
  230. SDL_GetWindowSize(mainWindow, &w, &h);
  231. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  232. SDL_RenderGetScale(mainRenderer, &xScale, &yScale);
  233. SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  234. moveCursorToPosition( Point(
  235. (int)(sme.x * xScale) + (w - rLogicalWidth * xScale) / 2,
  236. (int)(sme.y * yScale + (h - rLogicalHeight * yScale) / 2)));
  237. SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
  238. event.button = sme;
  239. SDL_PushEvent(&event);
  240. }
  241. void CGuiHandler::handleCurrentEvent( SDL_Event & current )
  242. {
  243. switch (current.type)
  244. {
  245. case SDL_KEYDOWN:
  246. return handleEventKeyDown(current);
  247. case SDL_KEYUP:
  248. return handleEventKeyUp(current);
  249. case SDL_MOUSEMOTION:
  250. return handleEventMouseMotion(current);
  251. case SDL_MOUSEBUTTONDOWN:
  252. return handleEventMouseButtonDown(current);
  253. case SDL_MOUSEWHEEL:
  254. return handleEventMouseWheel(current);
  255. case SDL_TEXTINPUT:
  256. return handleEventTextInput(current);
  257. case SDL_TEXTEDITING:
  258. return handleEventTextEditing(current);
  259. case SDL_MOUSEBUTTONUP:
  260. return handleEventMouseButtonUp(current);
  261. case SDL_FINGERMOTION:
  262. return handleEventFingerMotion(current);
  263. case SDL_FINGERDOWN:
  264. return handleEventFingerDown(current);
  265. case SDL_FINGERUP:
  266. return handleEventFingerUp(current);
  267. }
  268. }
  269. void CGuiHandler::handleEventKeyDown(SDL_Event & current)
  270. {
  271. SDL_KeyboardEvent key = current.key;
  272. if(key.repeat != 0)
  273. return; // ignore periodic event resends
  274. assert(key.state == SDL_PRESSED);
  275. if(current.type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  276. {
  277. //TODO: we need some central place for all interface-independent hotkeys
  278. Settings s = settings.write["session"];
  279. switch(key.keysym.sym)
  280. {
  281. case SDLK_F5:
  282. if(settings["session"]["spectate-locked-pim"].Bool())
  283. LOCPLINT->pim->unlock();
  284. else
  285. LOCPLINT->pim->lock();
  286. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  287. break;
  288. case SDLK_F6:
  289. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  290. break;
  291. case SDLK_F7:
  292. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  293. break;
  294. case SDLK_F8:
  295. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  296. break;
  297. default:
  298. break;
  299. }
  300. return;
  301. }
  302. auto shortcutsVector = shortcutsHandler().translateKeycode(key.keysym.sym);
  303. bool keysCaptured = false;
  304. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  305. for(EShortcut shortcut : shortcutsVector)
  306. if((*i)->captureThisKey(shortcut))
  307. keysCaptured = true;
  308. std::list<CIntObject *> miCopy = keyinterested;
  309. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  310. for(EShortcut shortcut : shortcutsVector)
  311. if(vstd::contains(keyinterested, *i) && (!keysCaptured || (*i)->captureThisKey(shortcut)))
  312. (**i).keyPressed(shortcut);
  313. }
  314. void CGuiHandler::handleEventKeyUp(SDL_Event & current)
  315. {
  316. SDL_KeyboardEvent key = current.key;
  317. if(key.repeat != 0)
  318. return; // ignore periodic event resends
  319. assert(key.state == SDL_RELEASED);
  320. auto shortcutsVector = shortcutsHandler().translateKeycode(key.keysym.sym);
  321. bool keysCaptured = false;
  322. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  323. for(EShortcut shortcut : shortcutsVector)
  324. if((*i)->captureThisKey(shortcut))
  325. keysCaptured = true;
  326. std::list<CIntObject *> miCopy = keyinterested;
  327. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  328. for(EShortcut shortcut : shortcutsVector)
  329. if(vstd::contains(keyinterested, *i) && (!keysCaptured || (*i)->captureThisKey(shortcut)))
  330. (**i).keyReleased(shortcut);
  331. }
  332. void CGuiHandler::handleEventMouseMotion(SDL_Event & current)
  333. {
  334. handleMouseMotion(current);
  335. }
  336. void CGuiHandler::handleEventMouseButtonDown(SDL_Event & current)
  337. {
  338. switch(current.button.button)
  339. {
  340. case SDL_BUTTON_LEFT:
  341. {
  342. auto doubleClicked = false;
  343. if(lastClick == getCursorPosition() && (SDL_GetTicks() - lastClickTime) < 300)
  344. {
  345. std::list<CIntObject*> hlp = doubleClickInterested;
  346. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  347. {
  348. if(!vstd::contains(doubleClickInterested, *i)) continue;
  349. if((*i)->pos.isInside(current.motion.x, current.motion.y))
  350. {
  351. (*i)->onDoubleClick();
  352. doubleClicked = true;
  353. }
  354. }
  355. }
  356. lastClick = current.motion;
  357. lastClickTime = SDL_GetTicks();
  358. if(!doubleClicked)
  359. handleMouseButtonClick(lclickable, MouseButton::LEFT, true);
  360. break;
  361. }
  362. case SDL_BUTTON_RIGHT:
  363. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  364. break;
  365. case SDL_BUTTON_MIDDLE:
  366. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, true);
  367. break;
  368. default:
  369. break;
  370. }
  371. }
  372. void CGuiHandler::handleEventMouseWheel(SDL_Event & current)
  373. {
  374. std::list<CIntObject*> hlp = wheelInterested;
  375. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  376. {
  377. if(!vstd::contains(wheelInterested,*i)) continue;
  378. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  379. int x = 0, y = 0;
  380. SDL_GetMouseState(&x, &y);
  381. (*i)->wheelScrolled(current.wheel.y < 0, (*i)->pos.isInside(x, y));
  382. }
  383. }
  384. void CGuiHandler::handleEventTextInput(SDL_Event & current)
  385. {
  386. for(auto it : textInterested)
  387. {
  388. it->textInputed(current.text.text);
  389. }
  390. }
  391. void CGuiHandler::handleEventTextEditing(SDL_Event & current)
  392. {
  393. for(auto it : textInterested)
  394. {
  395. it->textEdited(current.edit.text);
  396. }
  397. }
  398. void CGuiHandler::handleEventMouseButtonUp(SDL_Event & current)
  399. {
  400. if(!multifinger)
  401. {
  402. switch(current.button.button)
  403. {
  404. case SDL_BUTTON_LEFT:
  405. handleMouseButtonClick(lclickable, MouseButton::LEFT, false);
  406. break;
  407. case SDL_BUTTON_RIGHT:
  408. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  409. break;
  410. case SDL_BUTTON_MIDDLE:
  411. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, false);
  412. break;
  413. }
  414. }
  415. }
  416. void CGuiHandler::handleEventFingerMotion(SDL_Event & current)
  417. {
  418. if(isPointerRelativeMode)
  419. {
  420. fakeMoveCursor(current.tfinger.dx, current.tfinger.dy);
  421. }
  422. }
  423. void CGuiHandler::handleEventFingerDown(SDL_Event & current)
  424. {
  425. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  426. multifinger = fingerCount > 1;
  427. if(isPointerRelativeMode)
  428. {
  429. if(current.tfinger.x > 0.5)
  430. {
  431. bool isRightClick = current.tfinger.y < 0.5;
  432. fakeMouseButtonEventRelativeMode(true, isRightClick);
  433. }
  434. }
  435. #ifndef VCMI_IOS
  436. else if(fingerCount == 2)
  437. {
  438. convertTouchToMouse(&current);
  439. handleMouseMotion(current);
  440. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  441. }
  442. #endif //VCMI_IOS
  443. }
  444. void CGuiHandler::handleEventFingerUp(SDL_Event & current)
  445. {
  446. #ifndef VCMI_IOS
  447. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  448. #endif //VCMI_IOS
  449. if(isPointerRelativeMode)
  450. {
  451. if(current.tfinger.x > 0.5)
  452. {
  453. bool isRightClick = current.tfinger.y < 0.5;
  454. fakeMouseButtonEventRelativeMode(false, isRightClick);
  455. }
  456. }
  457. #ifndef VCMI_IOS
  458. else if(multifinger)
  459. {
  460. convertTouchToMouse(&current);
  461. handleMouseMotion(current);
  462. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  463. multifinger = fingerCount != 0;
  464. }
  465. #endif //VCMI_IOS
  466. }
  467. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, MouseButton btn, bool isPressed)
  468. {
  469. auto hlp = interestedObjs;
  470. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  471. {
  472. if(!vstd::contains(interestedObjs, *i)) continue;
  473. auto prev = (*i)->mouseState(btn);
  474. if(!isPressed)
  475. (*i)->updateMouseState(btn, isPressed);
  476. if((*i)->pos.isInside(getCursorPosition()))
  477. {
  478. if(isPressed)
  479. (*i)->updateMouseState(btn, isPressed);
  480. (*i)->click(btn, isPressed, prev);
  481. }
  482. else if(!isPressed)
  483. (*i)->click(btn, boost::logic::indeterminate, prev);
  484. }
  485. }
  486. void CGuiHandler::handleMouseMotion(const SDL_Event & current)
  487. {
  488. //sending active, hovered hoverable objects hover() call
  489. std::vector<CIntObject*> hlp;
  490. auto hoverableCopy = hoverable;
  491. for(auto & elem : hoverableCopy)
  492. {
  493. if(elem->pos.isInside(getCursorPosition()))
  494. {
  495. if (!(elem)->hovered)
  496. hlp.push_back((elem));
  497. }
  498. else if ((elem)->hovered)
  499. {
  500. (elem)->hover(false);
  501. (elem)->hovered = false;
  502. }
  503. }
  504. for(auto & elem : hlp)
  505. {
  506. elem->hover(true);
  507. elem->hovered = true;
  508. }
  509. // do not send motion events for events outside our window
  510. //if (current.motion.windowID == 0)
  511. handleMoveInterested(current.motion);
  512. }
  513. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  514. {
  515. //sending active, MotionInterested objects mouseMoved() call
  516. std::list<CIntObject*> miCopy = motioninterested;
  517. for(auto & elem : miCopy)
  518. {
  519. if(elem->strongInterest || Rect::createAround(elem->pos, 1).isInside( motion.x, motion.y)) //checking bounds including border fixes bug #2476
  520. {
  521. (elem)->mouseMoved(Point(motion.x, motion.y));
  522. }
  523. }
  524. }
  525. void CGuiHandler::renderFrame()
  526. {
  527. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  528. // During game:
  529. // When ending the game, the pim mutex might be hold by other thread,
  530. // that will notify us about the ending game by setting terminate_cond flag.
  531. //in PreGame terminate_cond stay false
  532. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  533. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  534. boost::this_thread::sleep(boost::posix_time::milliseconds(1));
  535. if(acquiredTheLockOnPim)
  536. {
  537. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  538. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  539. if(nullptr != curInt)
  540. curInt->update();
  541. if(settings["video"]["showfps"].Bool())
  542. drawFPSCounter();
  543. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  544. SDL_RenderClear(mainRenderer);
  545. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  546. CCS->curh->render();
  547. SDL_RenderPresent(mainRenderer);
  548. windows().onFrameRendered();
  549. }
  550. framerateManager().framerateDelay(); // holds a constant FPS
  551. }
  552. CGuiHandler::CGuiHandler()
  553. : lastClick(-500, -500)
  554. , lastClickTime(0)
  555. , defActionsDef(0)
  556. , captureChildren(false)
  557. , multifinger(false)
  558. , mouseButtonsMask(0)
  559. , continueEventHandling(true)
  560. , curInt(nullptr)
  561. , fakeStatusBar(std::make_shared<EmptyStatusBar>())
  562. , terminate_cond (new CondSh<bool>(false))
  563. {
  564. }
  565. CGuiHandler::~CGuiHandler()
  566. {
  567. delete terminate_cond;
  568. }
  569. ShortcutHandler & CGuiHandler::shortcutsHandler()
  570. {
  571. assert(shortcutsHandlerInstance);
  572. return *shortcutsHandlerInstance;
  573. }
  574. FramerateManager & CGuiHandler::framerateManager()
  575. {
  576. assert(framerateManagerInstance);
  577. return *framerateManagerInstance;
  578. }
  579. void CGuiHandler::moveCursorToPosition(const Point & position)
  580. {
  581. SDL_WarpMouseInWindow(mainWindow, position.x, position.y);
  582. }
  583. bool CGuiHandler::isKeyboardCtrlDown() const
  584. {
  585. #ifdef VCMI_MAC
  586. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LGUI] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RGUI];
  587. #else
  588. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LCTRL] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RCTRL];
  589. #endif
  590. }
  591. bool CGuiHandler::isKeyboardAltDown() const
  592. {
  593. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LALT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RALT];
  594. }
  595. bool CGuiHandler::isKeyboardShiftDown() const
  596. {
  597. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LSHIFT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RSHIFT];
  598. }
  599. void CGuiHandler::breakEventHandling()
  600. {
  601. continueEventHandling = false;
  602. }
  603. const Point & CGuiHandler::getCursorPosition() const
  604. {
  605. return cursorPosition;
  606. }
  607. Point CGuiHandler::screenDimensions() const
  608. {
  609. return Point(screen->w, screen->h);
  610. }
  611. bool CGuiHandler::isMouseButtonPressed() const
  612. {
  613. return mouseButtonsMask > 0;
  614. }
  615. bool CGuiHandler::isMouseButtonPressed(MouseButton button) const
  616. {
  617. static_assert(static_cast<uint32_t>(MouseButton::LEFT) == SDL_BUTTON_LEFT, "mismatch between VCMI and SDL enum!");
  618. static_assert(static_cast<uint32_t>(MouseButton::MIDDLE) == SDL_BUTTON_MIDDLE, "mismatch between VCMI and SDL enum!");
  619. static_assert(static_cast<uint32_t>(MouseButton::RIGHT) == SDL_BUTTON_RIGHT, "mismatch between VCMI and SDL enum!");
  620. static_assert(static_cast<uint32_t>(MouseButton::EXTRA1) == SDL_BUTTON_X1, "mismatch between VCMI and SDL enum!");
  621. static_assert(static_cast<uint32_t>(MouseButton::EXTRA2) == SDL_BUTTON_X2, "mismatch between VCMI and SDL enum!");
  622. uint32_t index = static_cast<uint32_t>(button);
  623. return mouseButtonsMask & SDL_BUTTON(index);
  624. }
  625. void CGuiHandler::drawFPSCounter()
  626. {
  627. static SDL_Rect overlay = { 0, 0, 64, 32};
  628. uint32_t black = SDL_MapRGB(screen->format, 10, 10, 10);
  629. SDL_FillRect(screen, &overlay, black);
  630. std::string fps = std::to_string(framerateManager().getFramerate());
  631. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, Colors::YELLOW, Point(10, 10));
  632. }
  633. bool CGuiHandler::amIGuiThread()
  634. {
  635. return inGuiThread.get() && *inGuiThread;
  636. }
  637. void CGuiHandler::pushUserEvent(EUserEvent usercode)
  638. {
  639. pushUserEvent(usercode, nullptr);
  640. }
  641. void CGuiHandler::pushUserEvent(EUserEvent usercode, void * userdata)
  642. {
  643. SDL_Event event;
  644. event.type = SDL_USEREVENT;
  645. event.user.code = static_cast<int32_t>(usercode);
  646. event.user.data1 = userdata;
  647. SDL_PushEvent(&event);
  648. }
  649. IScreenHandler & CGuiHandler::screenHandler()
  650. {
  651. return *screenHandlerInstance;
  652. }
  653. WindowHandler & CGuiHandler::windows()
  654. {
  655. assert(windowHandlerInstance);
  656. return *windowHandlerInstance;
  657. }
  658. std::shared_ptr<IStatusBar> CGuiHandler::statusbar()
  659. {
  660. auto locked = currentStatusBar.lock();
  661. if (!locked)
  662. return fakeStatusBar;
  663. return locked;
  664. }
  665. void CGuiHandler::setStatusbar(std::shared_ptr<IStatusBar> newStatusBar)
  666. {
  667. currentStatusBar = newStatusBar;
  668. }
  669. void CGuiHandler::onScreenResize()
  670. {
  671. screenHandler().onScreenResize();
  672. windows().onScreenResize();
  673. }