CGuiHandler.cpp 16 KB

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