CGuiHandler.cpp 24 KB

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