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 "../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. }
  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. }
  126. void CGuiHandler::popInts(int howMany)
  127. {
  128. if(!howMany) return; //senseless but who knows...
  129. assert(listInt.size() >= howMany);
  130. listInt.front()->deactivate();
  131. for(int i=0; i < howMany; i++)
  132. {
  133. objsToBlit -= listInt.front();
  134. disposed.push_back(listInt.front());
  135. listInt.pop_front();
  136. }
  137. if(!listInt.empty())
  138. {
  139. listInt.front()->activate();
  140. totalRedraw();
  141. }
  142. fakeMouseMove();
  143. }
  144. std::shared_ptr<IShowActivatable> CGuiHandler::topInt()
  145. {
  146. if(listInt.empty())
  147. return std::shared_ptr<IShowActivatable>();
  148. else
  149. return listInt.front();
  150. }
  151. void CGuiHandler::totalRedraw()
  152. {
  153. #ifdef VCMI_ANDROID
  154. SDL_FillRect(screen2, NULL, SDL_MapRGB(screen2->format, 0, 0, 0));
  155. #endif
  156. for(auto & elem : objsToBlit)
  157. elem->showAll(screen2);
  158. CSDL_Ext::blitAt(screen2,0,0,screen);
  159. }
  160. void CGuiHandler::updateTime()
  161. {
  162. int ms = mainFPSmng->getElapsedMilliseconds();
  163. std::list<CIntObject*> hlp = timeinterested;
  164. for (auto & elem : hlp)
  165. {
  166. if(!vstd::contains(timeinterested,elem)) continue;
  167. (elem)->onTimer(ms);
  168. }
  169. }
  170. void CGuiHandler::handleEvents()
  171. {
  172. //player interface may want special event handling
  173. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  174. return;
  175. boost::unique_lock<boost::mutex> lock(eventsM);
  176. while(!SDLEventsQueue.empty())
  177. {
  178. continueEventHandling = true;
  179. SDL_Event currentEvent = SDLEventsQueue.front();
  180. if (currentEvent.type == SDL_MOUSEMOTION)
  181. {
  182. cursorPosition = Point(currentEvent.motion.x, currentEvent.motion.y);
  183. mouseButtonsMask = currentEvent.motion.state;
  184. }
  185. SDLEventsQueue.pop();
  186. // In a sequence of mouse motion events, skip all but the last one.
  187. // This prevents freezes when every motion event takes longer to handle than interval at which
  188. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  189. // so that the events would start piling up faster than they can be processed.
  190. if ((currentEvent.type == SDL_MOUSEMOTION) && !SDLEventsQueue.empty() && (SDLEventsQueue.front().type == SDL_MOUSEMOTION))
  191. continue;
  192. handleCurrentEvent(currentEvent);
  193. }
  194. }
  195. void CGuiHandler::convertTouchToMouse(SDL_Event * current)
  196. {
  197. int rLogicalWidth, rLogicalHeight;
  198. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  199. int adjustedMouseY = (int)(current->tfinger.y * rLogicalHeight);
  200. int adjustedMouseX = (int)(current->tfinger.x * rLogicalWidth);
  201. current->button.x = adjustedMouseX;
  202. current->motion.x = adjustedMouseX;
  203. current->button.y = adjustedMouseY;
  204. current->motion.y = adjustedMouseY;
  205. }
  206. void CGuiHandler::fakeMoveCursor(float dx, float dy)
  207. {
  208. int x, y, w, h;
  209. SDL_Event event;
  210. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  211. sme.state = SDL_GetMouseState(&x, &y);
  212. SDL_GetWindowSize(mainWindow, &w, &h);
  213. sme.x = CCS->curh->position().x + (int)(GH.pointerSpeedMultiplier * w * dx);
  214. sme.y = CCS->curh->position().y + (int)(GH.pointerSpeedMultiplier * h * dy);
  215. vstd::abetween(sme.x, 0, w);
  216. vstd::abetween(sme.y, 0, h);
  217. event.motion = sme;
  218. SDL_PushEvent(&event);
  219. }
  220. void CGuiHandler::fakeMouseMove()
  221. {
  222. fakeMoveCursor(0, 0);
  223. }
  224. void CGuiHandler::startTextInput(const Rect & whereInput)
  225. {
  226. #ifdef VCMI_APPLE
  227. dispatch_async(dispatch_get_main_queue(), ^{
  228. #endif
  229. // TODO ios: looks like SDL bug actually, try fixing there
  230. auto renderer = SDL_GetRenderer(mainWindow);
  231. float scaleX, scaleY;
  232. SDL_Rect viewport;
  233. SDL_RenderGetScale(renderer, &scaleX, &scaleY);
  234. SDL_RenderGetViewport(renderer, &viewport);
  235. #ifdef VCMI_IOS
  236. const auto nativeScale = iOS_utils::screenScale();
  237. scaleX /= nativeScale;
  238. scaleY /= nativeScale;
  239. #endif
  240. SDL_Rect rectInScreenCoordinates;
  241. rectInScreenCoordinates.x = (viewport.x + whereInput.x) * scaleX;
  242. rectInScreenCoordinates.y = (viewport.y + whereInput.y) * scaleY;
  243. rectInScreenCoordinates.w = whereInput.w * scaleX;
  244. rectInScreenCoordinates.h = whereInput.h * scaleY;
  245. SDL_SetTextInputRect(&rectInScreenCoordinates);
  246. if (SDL_IsTextInputActive() == SDL_FALSE)
  247. {
  248. SDL_StartTextInput();
  249. }
  250. #ifdef VCMI_APPLE
  251. });
  252. #endif
  253. }
  254. void CGuiHandler::stopTextInput()
  255. {
  256. #ifdef VCMI_APPLE
  257. dispatch_async(dispatch_get_main_queue(), ^{
  258. #endif
  259. if (SDL_IsTextInputActive() == SDL_TRUE)
  260. {
  261. SDL_StopTextInput();
  262. }
  263. #ifdef VCMI_APPLE
  264. });
  265. #endif
  266. }
  267. void CGuiHandler::fakeMouseButtonEventRelativeMode(bool down, bool right)
  268. {
  269. SDL_Event event;
  270. SDL_MouseButtonEvent sme = {SDL_MOUSEBUTTONDOWN, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  271. if(!down)
  272. {
  273. sme.type = SDL_MOUSEBUTTONUP;
  274. }
  275. sme.button = right ? SDL_BUTTON_RIGHT : SDL_BUTTON_LEFT;
  276. sme.x = CCS->curh->position().x;
  277. sme.y = CCS->curh->position().y;
  278. float xScale, yScale;
  279. int w, h, rLogicalWidth, rLogicalHeight;
  280. SDL_GetWindowSize(mainWindow, &w, &h);
  281. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  282. SDL_RenderGetScale(mainRenderer, &xScale, &yScale);
  283. SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  284. moveCursorToPosition( Point(
  285. (int)(sme.x * xScale) + (w - rLogicalWidth * xScale) / 2,
  286. (int)(sme.y * yScale + (h - rLogicalHeight * yScale) / 2)));
  287. SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
  288. event.button = sme;
  289. SDL_PushEvent(&event);
  290. }
  291. void CGuiHandler::handleCurrentEvent( SDL_Event & current )
  292. {
  293. if(current.type == SDL_KEYDOWN || current.type == SDL_KEYUP)
  294. {
  295. SDL_KeyboardEvent key = current.key;
  296. if(current.type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  297. {
  298. //TODO: we need some central place for all interface-independent hotkeys
  299. Settings s = settings.write["session"];
  300. switch(key.keysym.sym)
  301. {
  302. case SDLK_F5:
  303. if(settings["session"]["spectate-locked-pim"].Bool())
  304. LOCPLINT->pim->unlock();
  305. else
  306. LOCPLINT->pim->lock();
  307. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  308. break;
  309. case SDLK_F6:
  310. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  311. break;
  312. case SDLK_F7:
  313. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  314. break;
  315. case SDLK_F8:
  316. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  317. break;
  318. case SDLK_F9:
  319. //not working yet since CClient::run remain locked after BattleInterface removal
  320. // if(LOCPLINT->battleInt)
  321. // {
  322. // GH.popInts(1);
  323. // vstd::clear_pointer(LOCPLINT->battleInt);
  324. // }
  325. break;
  326. default:
  327. break;
  328. }
  329. return;
  330. }
  331. //translate numpad keys
  332. if(key.keysym.sym == SDLK_KP_ENTER)
  333. {
  334. key.keysym.sym = SDLK_RETURN;
  335. key.keysym.scancode = SDL_SCANCODE_RETURN;
  336. }
  337. bool keysCaptured = false;
  338. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  339. {
  340. if((*i)->captureThisKey(key.keysym.sym))
  341. {
  342. keysCaptured = true;
  343. break;
  344. }
  345. }
  346. std::list<CIntObject*> miCopy = keyinterested;
  347. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  348. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisKey(key.keysym.sym)))
  349. {
  350. if (key.state == SDL_PRESSED)
  351. (**i).keyPressed(key.keysym.sym);
  352. if (key.state == SDL_RELEASED)
  353. (**i).keyReleased(key.keysym.sym);
  354. }
  355. }
  356. else if(current.type == SDL_MOUSEMOTION)
  357. {
  358. handleMouseMotion(current);
  359. }
  360. else if(current.type == SDL_MOUSEBUTTONDOWN)
  361. {
  362. switch(current.button.button)
  363. {
  364. case SDL_BUTTON_LEFT:
  365. {
  366. auto doubleClicked = false;
  367. if(lastClick == getCursorPosition() && (SDL_GetTicks() - lastClickTime) < 300)
  368. {
  369. std::list<CIntObject*> hlp = doubleClickInterested;
  370. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  371. {
  372. if(!vstd::contains(doubleClickInterested, *i)) continue;
  373. if((*i)->pos.isInside(current.motion.x, current.motion.y))
  374. {
  375. (*i)->onDoubleClick();
  376. doubleClicked = true;
  377. }
  378. }
  379. }
  380. lastClick = current.motion;
  381. lastClickTime = SDL_GetTicks();
  382. if(!doubleClicked)
  383. handleMouseButtonClick(lclickable, MouseButton::LEFT, true);
  384. break;
  385. }
  386. case SDL_BUTTON_RIGHT:
  387. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  388. break;
  389. case SDL_BUTTON_MIDDLE:
  390. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, true);
  391. break;
  392. default:
  393. break;
  394. }
  395. }
  396. else if(current.type == SDL_MOUSEWHEEL)
  397. {
  398. std::list<CIntObject*> hlp = wheelInterested;
  399. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  400. {
  401. if(!vstd::contains(wheelInterested,*i)) continue;
  402. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  403. int x = 0, y = 0;
  404. SDL_GetMouseState(&x, &y);
  405. (*i)->wheelScrolled(current.wheel.y < 0, (*i)->pos.isInside(x, y));
  406. }
  407. }
  408. else if(current.type == SDL_TEXTINPUT)
  409. {
  410. for(auto it : textInterested)
  411. {
  412. it->textInputed(current.text.text);
  413. }
  414. }
  415. else if(current.type == SDL_TEXTEDITING)
  416. {
  417. for(auto it : textInterested)
  418. {
  419. it->textEdited(current.edit.text);
  420. }
  421. }
  422. else if(current.type == SDL_MOUSEBUTTONUP)
  423. {
  424. if(!multifinger)
  425. {
  426. switch(current.button.button)
  427. {
  428. case SDL_BUTTON_LEFT:
  429. handleMouseButtonClick(lclickable, MouseButton::LEFT, false);
  430. break;
  431. case SDL_BUTTON_RIGHT:
  432. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  433. break;
  434. case SDL_BUTTON_MIDDLE:
  435. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, false);
  436. break;
  437. }
  438. }
  439. }
  440. else if(current.type == SDL_FINGERMOTION)
  441. {
  442. if(isPointerRelativeMode)
  443. {
  444. fakeMoveCursor(current.tfinger.dx, current.tfinger.dy);
  445. }
  446. }
  447. else if(current.type == SDL_FINGERDOWN)
  448. {
  449. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  450. multifinger = fingerCount > 1;
  451. if(isPointerRelativeMode)
  452. {
  453. if(current.tfinger.x > 0.5)
  454. {
  455. bool isRightClick = current.tfinger.y < 0.5;
  456. fakeMouseButtonEventRelativeMode(true, isRightClick);
  457. }
  458. }
  459. #ifndef VCMI_IOS
  460. else if(fingerCount == 2)
  461. {
  462. convertTouchToMouse(&current);
  463. handleMouseMotion(current);
  464. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  465. }
  466. #endif //VCMI_IOS
  467. }
  468. else if(current.type == SDL_FINGERUP)
  469. {
  470. #ifndef VCMI_IOS
  471. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  472. #endif //VCMI_IOS
  473. if(isPointerRelativeMode)
  474. {
  475. if(current.tfinger.x > 0.5)
  476. {
  477. bool isRightClick = current.tfinger.y < 0.5;
  478. fakeMouseButtonEventRelativeMode(false, isRightClick);
  479. }
  480. }
  481. #ifndef VCMI_IOS
  482. else if(multifinger)
  483. {
  484. convertTouchToMouse(&current);
  485. handleMouseMotion(current);
  486. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  487. multifinger = fingerCount != 0;
  488. }
  489. #endif //VCMI_IOS
  490. }
  491. } //event end
  492. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, MouseButton btn, bool isPressed)
  493. {
  494. auto hlp = interestedObjs;
  495. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  496. {
  497. if(!vstd::contains(interestedObjs, *i)) continue;
  498. auto prev = (*i)->mouseState(btn);
  499. if(!isPressed)
  500. (*i)->updateMouseState(btn, isPressed);
  501. if((*i)->pos.isInside(getCursorPosition()))
  502. {
  503. if(isPressed)
  504. (*i)->updateMouseState(btn, isPressed);
  505. (*i)->click(btn, isPressed, prev);
  506. }
  507. else if(!isPressed)
  508. (*i)->click(btn, boost::logic::indeterminate, prev);
  509. }
  510. }
  511. void CGuiHandler::handleMouseMotion(const SDL_Event & current)
  512. {
  513. //sending active, hovered hoverable objects hover() call
  514. std::vector<CIntObject*> hlp;
  515. for(auto & elem : hoverable)
  516. {
  517. if(elem->pos.isInside(getCursorPosition()))
  518. {
  519. if (!(elem)->hovered)
  520. hlp.push_back((elem));
  521. }
  522. else if ((elem)->hovered)
  523. {
  524. (elem)->hover(false);
  525. (elem)->hovered = false;
  526. }
  527. }
  528. for(auto & elem : hlp)
  529. {
  530. elem->hover(true);
  531. elem->hovered = true;
  532. }
  533. // do not send motion events for events outside our window
  534. //if (current.motion.windowID == 0)
  535. handleMoveInterested(current.motion);
  536. }
  537. void CGuiHandler::simpleRedraw()
  538. {
  539. //update only top interface and draw background
  540. if(objsToBlit.size() > 1)
  541. CSDL_Ext::blitAt(screen2,0,0,screen); //blit background
  542. if(!objsToBlit.empty())
  543. objsToBlit.back()->show(screen); //blit active interface/window
  544. }
  545. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  546. {
  547. //sending active, MotionInterested objects mouseMoved() call
  548. std::list<CIntObject*> miCopy = motioninterested;
  549. for(auto & elem : miCopy)
  550. {
  551. if(elem->strongInterest || Rect::createAround(elem->pos, 1).isInside( motion.x, motion.y)) //checking bounds including border fixes bug #2476
  552. {
  553. (elem)->mouseMoved(Point(motion.x, motion.y));
  554. }
  555. }
  556. }
  557. void CGuiHandler::renderFrame()
  558. {
  559. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  560. // During game:
  561. // When ending the game, the pim mutex might be hold by other thread,
  562. // that will notify us about the ending game by setting terminate_cond flag.
  563. //in PreGame terminate_cond stay false
  564. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  565. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  566. boost::this_thread::sleep(boost::posix_time::milliseconds(1));
  567. if(acquiredTheLockOnPim)
  568. {
  569. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  570. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  571. if(nullptr != curInt)
  572. curInt->update();
  573. if(settings["general"]["showfps"].Bool())
  574. drawFPSCounter();
  575. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  576. SDL_RenderClear(mainRenderer);
  577. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  578. CCS->curh->render();
  579. SDL_RenderPresent(mainRenderer);
  580. disposed.clear();
  581. }
  582. mainFPSmng->framerateDelay(); // holds a constant FPS
  583. }
  584. CGuiHandler::CGuiHandler()
  585. : lastClick(-500, -500)
  586. , lastClickTime(0)
  587. , defActionsDef(0)
  588. , captureChildren(false)
  589. , multifinger(false)
  590. , mouseButtonsMask(0)
  591. , continueEventHandling(true)
  592. , curInt(nullptr)
  593. , statusbar(nullptr)
  594. {
  595. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  596. mainFPSmng = new CFramerateManager(60);
  597. //do not init CFramerateManager here --AVS
  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->fps);
  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(int rate)
  729. {
  730. this->rate = rate;
  731. this->rateticks = (1000.0 / rate);
  732. this->fps = 0;
  733. this->accumulatedFrames = 0;
  734. this->accumulatedTime = 0;
  735. this->lastticks = 0;
  736. this->timeElapsed = 0;
  737. }
  738. void CFramerateManager::init()
  739. {
  740. this->lastticks = SDL_GetTicks();
  741. }
  742. void CFramerateManager::framerateDelay()
  743. {
  744. ui32 currentTicks = SDL_GetTicks();
  745. timeElapsed = currentTicks - lastticks;
  746. accumulatedFrames++;
  747. // FPS is higher than it should be, then wait some time
  748. if(timeElapsed < rateticks)
  749. {
  750. int timeToSleep = (uint32_t)ceil(this->rateticks) - timeElapsed;
  751. boost::this_thread::sleep(boost::posix_time::milliseconds(timeToSleep));
  752. }
  753. currentTicks = SDL_GetTicks();
  754. // recalculate timeElapsed for external calls via getElapsed()
  755. // limit it to 100 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  756. timeElapsed = std::min<ui32>(currentTicks - lastticks, 100);
  757. lastticks = SDL_GetTicks();
  758. accumulatedTime += timeElapsed;
  759. if(accumulatedFrames >= 100)
  760. {
  761. //about 2 second should be passed
  762. fps = static_cast<int>(ceil(1000.0 / (accumulatedTime / accumulatedFrames)));
  763. accumulatedTime = 0;
  764. accumulatedFrames = 0;
  765. }
  766. }