CGuiHandler.cpp 24 KB

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