CGuiHandler.cpp 24 KB

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