CGuiHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 <SDL.h>
  14. #include "CIntObject.h"
  15. #include "CCursorHandler.h"
  16. #include "../CGameInfo.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/CConfigHandler.h"
  19. #include "../CMT.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../battle/CBattleInterface.h"
  22. extern std::queue<SDL_Event> events;
  23. extern boost::mutex eventsM;
  24. CondSh<bool> CGuiHandler::terminate_cond(false);
  25. boost::thread_specific_ptr<bool> inGuiThread;
  26. SObjectConstruction::SObjectConstruction(CIntObject * obj)
  27. : myObj(obj)
  28. {
  29. GH.createdObj.push_front(obj);
  30. GH.captureChildren = true;
  31. }
  32. SObjectConstruction::~SObjectConstruction()
  33. {
  34. assert(GH.createdObj.size());
  35. assert(GH.createdObj.front() == myObj);
  36. GH.createdObj.pop_front();
  37. GH.captureChildren = GH.createdObj.size();
  38. }
  39. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  40. {
  41. previousCapture = GH.captureChildren;
  42. GH.captureChildren = false;
  43. prevActions = GH.defActionsDef;
  44. GH.defActionsDef = actions;
  45. }
  46. SSetCaptureState::~SSetCaptureState()
  47. {
  48. GH.captureChildren = previousCapture;
  49. GH.defActionsDef = prevActions;
  50. }
  51. static inline void processList(const ui16 mask, const ui16 flag, std::list<CIntObject *> * lst, std::function<void(std::list<CIntObject *> *)> cb)
  52. {
  53. if(mask & flag)
  54. cb(lst);
  55. }
  56. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void(std::list<CIntObject *> *)> cb)
  57. {
  58. processList(CIntObject::LCLICK, activityFlag, &lclickable, cb);
  59. processList(CIntObject::RCLICK, activityFlag, &rclickable, cb);
  60. processList(CIntObject::MCLICK, activityFlag, &mclickable, cb);
  61. processList(CIntObject::HOVER, activityFlag, &hoverable, cb);
  62. processList(CIntObject::MOVE, activityFlag, &motioninterested, cb);
  63. processList(CIntObject::KEYBOARD, activityFlag, &keyinterested, cb);
  64. processList(CIntObject::TIME, activityFlag, &timeinterested, cb);
  65. processList(CIntObject::WHEEL, activityFlag, &wheelInterested, cb);
  66. processList(CIntObject::DOUBLECLICK, activityFlag, &doubleClickInterested, cb);
  67. processList(CIntObject::TEXTINPUT, activityFlag, &textInterested, cb);
  68. }
  69. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  70. {
  71. processLists(activityFlag, [&](std::list<CIntObject *> * lst)
  72. {
  73. lst->push_front(elem);
  74. });
  75. elem->active_m |= activityFlag;
  76. }
  77. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  78. {
  79. processLists(activityFlag, [&](std::list<CIntObject *> * lst)
  80. {
  81. auto hlp = std::find(lst->begin(), lst->end(), elem);
  82. assert(hlp != lst->end());
  83. lst->erase(hlp);
  84. });
  85. elem->active_m &= ~activityFlag;
  86. }
  87. void CGuiHandler::popInt(IShowActivatable * top)
  88. {
  89. assert(listInt.front() == top);
  90. top->deactivate();
  91. listInt.pop_front();
  92. objsToBlit -= top;
  93. if(!listInt.empty())
  94. listInt.front()->activate();
  95. totalRedraw();
  96. }
  97. void CGuiHandler::popIntTotally(IShowActivatable * top)
  98. {
  99. assert(listInt.front() == top);
  100. popInt(top);
  101. delete top;
  102. fakeMouseMove();
  103. }
  104. void CGuiHandler::pushInt(IShowActivatable * newInt)
  105. {
  106. assert(newInt);
  107. assert(boost::range::find(listInt, newInt) == listInt.end()); // do not add same object twice
  108. //a new interface will be present, we'll need to use buffer surface (unless it's advmapint that will alter screenBuf on activate anyway)
  109. screenBuf = screen2;
  110. if(!listInt.empty())
  111. listInt.front()->deactivate();
  112. listInt.push_front(newInt);
  113. newInt->activate();
  114. objsToBlit.push_back(newInt);
  115. totalRedraw();
  116. }
  117. void CGuiHandler::popInts(int howMany)
  118. {
  119. if(!howMany)
  120. return; //senseless but who knows...
  121. assert(listInt.size() >= howMany);
  122. listInt.front()->deactivate();
  123. for(int i = 0; i < howMany; i++)
  124. {
  125. objsToBlit -= listInt.front();
  126. delete listInt.front();
  127. listInt.pop_front();
  128. }
  129. if(!listInt.empty())
  130. {
  131. listInt.front()->activate();
  132. totalRedraw();
  133. }
  134. fakeMouseMove();
  135. }
  136. IShowActivatable * CGuiHandler::topInt()
  137. {
  138. if(listInt.empty())
  139. return nullptr;
  140. else
  141. return listInt.front();
  142. }
  143. void CGuiHandler::totalRedraw()
  144. {
  145. for(auto & elem : objsToBlit)
  146. elem->showAll(screen2);
  147. blitAt(screen2, 0, 0, screen);
  148. }
  149. void CGuiHandler::updateTime()
  150. {
  151. int ms = mainFPSmng->getElapsedMilliseconds();
  152. std::list<CIntObject *> hlp = timeinterested;
  153. for(auto & elem : hlp)
  154. {
  155. if(!vstd::contains(timeinterested, elem))
  156. continue;
  157. (elem)->onTimer(ms);
  158. }
  159. }
  160. void CGuiHandler::handleEvents()
  161. {
  162. //player interface may want special event handling
  163. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  164. return;
  165. boost::unique_lock<boost::mutex> lock(eventsM);
  166. while(!events.empty())
  167. {
  168. SDL_Event ev = events.front();
  169. events.pop();
  170. this->handleEvent(&ev);
  171. }
  172. }
  173. void CGuiHandler::handleEvent(SDL_Event * sEvent)
  174. {
  175. current = sEvent;
  176. bool prev;
  177. if(sEvent->type == SDL_KEYDOWN || sEvent->type == SDL_KEYUP)
  178. {
  179. SDL_KeyboardEvent key = sEvent->key;
  180. if(sEvent->type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  181. {
  182. //TODO: we need some central place for all interface-independent hotkeys
  183. Settings s = settings.write["session"];
  184. switch(key.keysym.sym)
  185. {
  186. case SDLK_F5:
  187. if(settings["session"]["spectate-locked-pim"].Bool())
  188. LOCPLINT->pim->unlock();
  189. else
  190. LOCPLINT->pim->lock();
  191. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  192. break;
  193. case SDLK_F6:
  194. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  195. break;
  196. case SDLK_F7:
  197. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  198. break;
  199. case SDLK_F8:
  200. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  201. break;
  202. case SDLK_F9:
  203. //not working yet since CClient::run remain locked after CBattleInterface removal
  204. if(LOCPLINT->battleInt)
  205. {
  206. GH.popIntTotally(GH.topInt());
  207. vstd::clear_pointer(LOCPLINT->battleInt);
  208. }
  209. break;
  210. default:
  211. break;
  212. }
  213. return;
  214. }
  215. //translate numpad keys
  216. if(key.keysym.sym == SDLK_KP_ENTER)
  217. {
  218. key.keysym.sym = SDLK_RETURN;
  219. key.keysym.scancode = SDL_SCANCODE_RETURN;
  220. }
  221. bool keysCaptured = false;
  222. for(auto i = keyinterested.begin(); i != keyinterested.end() && current; i++)
  223. {
  224. if((*i)->captureThisEvent(key))
  225. {
  226. keysCaptured = true;
  227. break;
  228. }
  229. }
  230. std::list<CIntObject *> miCopy = keyinterested;
  231. for(auto i = miCopy.begin(); i != miCopy.end() && current; i++)
  232. if(vstd::contains(keyinterested, *i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  233. (**i).keyPressed(key);
  234. }
  235. else if(sEvent->type == SDL_MOUSEMOTION)
  236. {
  237. CCS->curh->cursorMove(sEvent->motion.x, sEvent->motion.y);
  238. handleMouseMotion(sEvent);
  239. }
  240. else if(sEvent->type == SDL_MOUSEBUTTONDOWN)
  241. {
  242. switch(sEvent->button.button)
  243. {
  244. case SDL_BUTTON_LEFT:
  245. if(lastClick == sEvent->motion && (SDL_GetTicks() - lastClickTime) < 300)
  246. {
  247. std::list<CIntObject *> hlp = doubleClickInterested;
  248. for(auto i = hlp.begin(); i != hlp.end() && current; i++)
  249. {
  250. if(!vstd::contains(doubleClickInterested, *i))
  251. continue;
  252. if(isItIn(&(*i)->pos, sEvent->motion.x, sEvent->motion.y))
  253. {
  254. (*i)->onDoubleClick();
  255. }
  256. }
  257. }
  258. lastClick = sEvent->motion;
  259. lastClickTime = SDL_GetTicks();
  260. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, true);
  261. break;
  262. case SDL_BUTTON_RIGHT:
  263. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  264. break;
  265. case SDL_BUTTON_MIDDLE:
  266. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, true);
  267. break;
  268. default:
  269. break;
  270. }
  271. }
  272. else if(sEvent->type == SDL_MOUSEWHEEL)
  273. {
  274. std::list<CIntObject *> hlp = wheelInterested;
  275. for(auto i = hlp.begin(); i != hlp.end() && current; i++)
  276. {
  277. if(!vstd::contains(wheelInterested, *i))
  278. continue;
  279. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  280. int x = 0, y = 0;
  281. SDL_GetMouseState(&x, &y);
  282. (*i)->wheelScrolled(sEvent->wheel.y < 0, isItIn(&(*i)->pos, x, y));
  283. }
  284. }
  285. else if(sEvent->type == SDL_TEXTINPUT)
  286. {
  287. for(auto it : textInterested)
  288. {
  289. it->textInputed(sEvent->text);
  290. }
  291. }
  292. else if(sEvent->type == SDL_TEXTEDITING)
  293. {
  294. for(auto it : textInterested)
  295. {
  296. it->textEdited(sEvent->edit);
  297. }
  298. }
  299. //todo: muiltitouch
  300. else if(sEvent->type == SDL_MOUSEBUTTONUP)
  301. {
  302. switch(sEvent->button.button)
  303. {
  304. case SDL_BUTTON_LEFT:
  305. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, false);
  306. break;
  307. case SDL_BUTTON_RIGHT:
  308. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  309. break;
  310. case SDL_BUTTON_MIDDLE:
  311. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, false);
  312. break;
  313. }
  314. }
  315. current = nullptr;
  316. } //event end
  317. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed)
  318. {
  319. auto hlp = interestedObjs;
  320. for(auto i = hlp.begin(); i != hlp.end() && current; i++)
  321. {
  322. if(!vstd::contains(interestedObjs, *i))
  323. continue;
  324. auto prev = (*i)->mouseState(btn);
  325. if(!isPressed)
  326. (*i)->updateMouseState(btn, isPressed);
  327. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  328. {
  329. if(isPressed)
  330. (*i)->updateMouseState(btn, isPressed);
  331. (*i)->click(btn, isPressed, prev);
  332. }
  333. else if(!isPressed)
  334. (*i)->click(btn, boost::logic::indeterminate, prev);
  335. }
  336. }
  337. void CGuiHandler::handleMouseMotion(SDL_Event * sEvent)
  338. {
  339. //sending active, hovered hoverable objects hover() call
  340. std::vector<CIntObject *> hlp;
  341. for(auto & elem : hoverable)
  342. {
  343. if(isItIn(&(elem)->pos, sEvent->motion.x, sEvent->motion.y))
  344. {
  345. if(!(elem)->hovered)
  346. hlp.push_back((elem));
  347. }
  348. else if((elem)->hovered)
  349. {
  350. (elem)->hover(false);
  351. (elem)->hovered = false;
  352. }
  353. }
  354. for(auto & elem : hlp)
  355. {
  356. elem->hover(true);
  357. elem->hovered = true;
  358. }
  359. handleMoveInterested(sEvent->motion);
  360. }
  361. void CGuiHandler::simpleRedraw()
  362. {
  363. //update only top interface and draw background
  364. if(objsToBlit.size() > 1)
  365. blitAt(screen2, 0, 0, screen); //blit background
  366. if(!objsToBlit.empty())
  367. objsToBlit.back()->show(screen); //blit active interface/window
  368. }
  369. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  370. {
  371. //sending active, MotionInterested objects mouseMoved() call
  372. std::list<CIntObject *> miCopy = motioninterested;
  373. for(auto & elem : miCopy)
  374. {
  375. if(elem->strongInterest || isItInOrLowerBounds(&elem->pos, motion.x, motion.y)) //checking lower bounds fixes bug #2476
  376. {
  377. (elem)->mouseMoved(motion);
  378. }
  379. }
  380. }
  381. void CGuiHandler::fakeMouseMove()
  382. {
  383. SDL_Event evnt;
  384. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  385. int x, y;
  386. sme.state = SDL_GetMouseState(&x, &y);
  387. sme.x = x;
  388. sme.y = y;
  389. evnt.motion = sme;
  390. current = &evnt;
  391. handleMouseMotion(&evnt);
  392. }
  393. void CGuiHandler::renderFrame()
  394. {
  395. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  396. // During game:
  397. // When ending the game, the pim mutex might be hold by other thread,
  398. // that will notify us about the ending game by setting terminate_cond flag.
  399. //in PreGame terminate_cond stay false
  400. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  401. while(!terminate_cond.get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  402. boost::this_thread::sleep(boost::posix_time::milliseconds(15));
  403. if(acquiredTheLockOnPim)
  404. {
  405. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  406. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  407. if(nullptr != curInt)
  408. curInt->update();
  409. if(settings["general"]["showfps"].Bool())
  410. drawFPSCounter();
  411. // draw the mouse cursor and update the screen
  412. CCS->curh->render();
  413. if(0 != SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr))
  414. logGlobal->errorStream() << __FUNCTION__ << " SDL_RenderCopy " << SDL_GetError();
  415. SDL_RenderPresent(mainRenderer);
  416. }
  417. mainFPSmng->framerateDelay(); // holds a constant FPS
  418. }
  419. CGuiHandler::CGuiHandler()
  420. : lastClick(-500, -500), lastClickTime(0), defActionsDef(0), captureChildren(false)
  421. {
  422. curInt = nullptr;
  423. current = nullptr;
  424. statusbar = nullptr;
  425. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  426. mainFPSmng = new CFramerateManager(48);
  427. //do not init CFramerateManager here --AVS
  428. terminate_cond.set(false);
  429. }
  430. CGuiHandler::~CGuiHandler()
  431. {
  432. delete mainFPSmng;
  433. }
  434. void CGuiHandler::breakEventHandling()
  435. {
  436. current = nullptr;
  437. }
  438. void CGuiHandler::drawFPSCounter()
  439. {
  440. const static SDL_Color yellow = {255, 255, 0, 0};
  441. static SDL_Rect overlay = { 0, 0, 64, 32};
  442. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  443. SDL_FillRect(screen, &overlay, black);
  444. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  445. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  446. }
  447. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  448. {
  449. switch(key)
  450. {
  451. case SDLK_DOWN:
  452. return SDLK_KP_2;
  453. case SDLK_UP:
  454. return SDLK_KP_8;
  455. case SDLK_LEFT:
  456. return SDLK_KP_4;
  457. case SDLK_RIGHT:
  458. return SDLK_KP_6;
  459. default:
  460. throw std::runtime_error("Wrong key!");
  461. }
  462. }
  463. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  464. {
  465. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName: \
  466. return SDLK_ ## keyName;
  467. switch(key)
  468. {
  469. REMOVE_KP(0)
  470. REMOVE_KP(1)
  471. REMOVE_KP(2)
  472. REMOVE_KP(3)
  473. REMOVE_KP(4)
  474. REMOVE_KP(5)
  475. REMOVE_KP(6)
  476. REMOVE_KP(7)
  477. REMOVE_KP(8)
  478. REMOVE_KP(9)
  479. REMOVE_KP(PERIOD)
  480. REMOVE_KP(MINUS)
  481. REMOVE_KP(PLUS)
  482. REMOVE_KP(EQUALS)
  483. case SDLK_KP_MULTIPLY:
  484. return SDLK_ASTERISK;
  485. case SDLK_KP_DIVIDE:
  486. return SDLK_SLASH;
  487. case SDLK_KP_ENTER:
  488. return SDLK_RETURN;
  489. default:
  490. return SDLK_UNKNOWN;
  491. }
  492. #undef REMOVE_KP
  493. }
  494. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  495. {
  496. if(number)
  497. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  498. else
  499. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  500. }
  501. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  502. {
  503. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  504. }
  505. bool CGuiHandler::amIGuiThread()
  506. {
  507. return inGuiThread.get() && *inGuiThread;
  508. }
  509. void CGuiHandler::pushSDLEvent(int type, int usercode)
  510. {
  511. SDL_Event event;
  512. event.type = type;
  513. event.user.code = usercode; // not necessarily used
  514. SDL_PushEvent(&event);
  515. }
  516. CFramerateManager::CFramerateManager(int rate)
  517. {
  518. this->rate = rate;
  519. this->rateticks = (1000.0 / rate);
  520. this->fps = 0;
  521. this->accumulatedFrames = 0;
  522. this->accumulatedTime = 0;
  523. this->lastticks = 0;
  524. this->timeElapsed = 0;
  525. }
  526. void CFramerateManager::init()
  527. {
  528. this->lastticks = SDL_GetTicks();
  529. }
  530. void CFramerateManager::framerateDelay()
  531. {
  532. ui32 currentTicks = SDL_GetTicks();
  533. timeElapsed = currentTicks - lastticks;
  534. // FPS is higher than it should be, then wait some time
  535. if(timeElapsed < rateticks)
  536. {
  537. SDL_Delay(ceil(this->rateticks) - timeElapsed);
  538. }
  539. accumulatedTime += timeElapsed;
  540. accumulatedFrames++;
  541. if(accumulatedFrames >= 100)
  542. {
  543. //about 2 second should be passed
  544. fps = ceil(1000.0 / (accumulatedTime / accumulatedFrames));
  545. accumulatedTime = 0;
  546. accumulatedFrames = 0;
  547. }
  548. currentTicks = SDL_GetTicks();
  549. // recalculate timeElapsed for external calls via getElapsed()
  550. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  551. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  552. lastticks = SDL_GetTicks();
  553. }