CGuiHandler.cpp 23 KB

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