CGuiHandler.cpp 23 KB

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