CGuiHandler.cpp 21 KB

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