CGuiHandler.cpp 22 KB

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