CGuiHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. boost::thread_specific_ptr<bool> inGuiThread;
  25. SObjectConstruction::SObjectConstruction(CIntObject *obj)
  26. :myObj(obj)
  27. {
  28. GH.createdObj.push_front(obj);
  29. GH.captureChildren = true;
  30. }
  31. SObjectConstruction::~SObjectConstruction()
  32. {
  33. assert(GH.createdObj.size());
  34. assert(GH.createdObj.front() == myObj);
  35. GH.createdObj.pop_front();
  36. GH.captureChildren = GH.createdObj.size();
  37. }
  38. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  39. {
  40. previousCapture = GH.captureChildren;
  41. GH.captureChildren = false;
  42. prevActions = GH.defActionsDef;
  43. GH.defActionsDef = actions;
  44. }
  45. SSetCaptureState::~SSetCaptureState()
  46. {
  47. GH.captureChildren = previousCapture;
  48. GH.defActionsDef = prevActions;
  49. }
  50. static inline void
  51. 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. lst->push_front(elem);
  73. });
  74. elem->active_m |= activityFlag;
  75. }
  76. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  77. {
  78. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  79. auto hlp = std::find(lst->begin(),lst->end(),elem);
  80. assert(hlp != lst->end());
  81. lst->erase(hlp);
  82. });
  83. elem->active_m &= ~activityFlag;
  84. }
  85. void CGuiHandler::popInt(IShowActivatable *top)
  86. {
  87. assert(listInt.front() == top);
  88. top->deactivate();
  89. listInt.pop_front();
  90. objsToBlit -= top;
  91. if(!listInt.empty())
  92. listInt.front()->activate();
  93. totalRedraw();
  94. pushSDLEvent(SDL_USEREVENT, INTERFACE_CHANGED);
  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. pushSDLEvent(SDL_USEREVENT, INTERFACE_CHANGED);
  116. }
  117. void CGuiHandler::popInts(int howMany)
  118. {
  119. if(!howMany) return; //senseless but who knows...
  120. assert(listInt.size() >= howMany);
  121. listInt.front()->deactivate();
  122. for(int i=0; i < howMany; i++)
  123. {
  124. objsToBlit -= listInt.front();
  125. delete listInt.front();
  126. listInt.pop_front();
  127. }
  128. if(!listInt.empty())
  129. {
  130. listInt.front()->activate();
  131. totalRedraw();
  132. }
  133. fakeMouseMove();
  134. pushSDLEvent(SDL_USEREVENT, INTERFACE_CHANGED);
  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)) continue;
  156. (elem)->onTimer(ms);
  157. }
  158. }
  159. void CGuiHandler::handleEvents()
  160. {
  161. //player interface may want special event handling
  162. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  163. return;
  164. boost::unique_lock<boost::mutex> lock(eventsM);
  165. while(!events.empty())
  166. {
  167. continueEventHandling = true;
  168. current = &events.front();
  169. events.pop();
  170. handleCurrentEvent();
  171. }
  172. }
  173. void CGuiHandler::handleCurrentEvent()
  174. {
  175. if(current->type == SDL_KEYDOWN || current->type == SDL_KEYUP)
  176. {
  177. SDL_KeyboardEvent key = current->key;
  178. if(current->type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  179. {
  180. //TODO: we need some central place for all interface-independent hotkeys
  181. Settings s = settings.write["session"];
  182. switch(key.keysym.sym)
  183. {
  184. case SDLK_F5:
  185. if(settings["session"]["spectate-locked-pim"].Bool())
  186. LOCPLINT->pim->unlock();
  187. else
  188. LOCPLINT->pim->lock();
  189. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  190. break;
  191. case SDLK_F6:
  192. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  193. break;
  194. case SDLK_F7:
  195. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  196. break;
  197. case SDLK_F8:
  198. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  199. break;
  200. case SDLK_F9:
  201. //not working yet since CClient::run remain locked after CBattleInterface removal
  202. if(LOCPLINT->battleInt)
  203. {
  204. GH.popIntTotally(GH.topInt());
  205. vstd::clear_pointer(LOCPLINT->battleInt);
  206. }
  207. break;
  208. default:
  209. break;
  210. }
  211. return;
  212. }
  213. //translate numpad keys
  214. if(key.keysym.sym == SDLK_KP_ENTER)
  215. {
  216. key.keysym.sym = SDLK_RETURN;
  217. key.keysym.scancode = SDL_SCANCODE_RETURN;
  218. }
  219. bool keysCaptured = false;
  220. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  221. {
  222. if((*i)->captureThisEvent(key))
  223. {
  224. keysCaptured = true;
  225. break;
  226. }
  227. }
  228. std::list<CIntObject*> miCopy = keyinterested;
  229. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  230. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  231. (**i).keyPressed(key);
  232. }
  233. else if(current->type == SDL_MOUSEMOTION)
  234. {
  235. CCS->curh->cursorMove(current->motion.x, current->motion.y);
  236. handleMouseMotion();
  237. }
  238. else if(current->type == SDL_MOUSEBUTTONDOWN)
  239. {
  240. switch(current->button.button)
  241. {
  242. case SDL_BUTTON_LEFT:
  243. if(lastClick == current->motion && (SDL_GetTicks() - lastClickTime) < 300)
  244. {
  245. std::list<CIntObject*> hlp = doubleClickInterested;
  246. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  247. {
  248. if(!vstd::contains(doubleClickInterested, *i)) continue;
  249. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  250. {
  251. (*i)->onDoubleClick();
  252. }
  253. }
  254. }
  255. lastClick = current->motion;
  256. lastClickTime = SDL_GetTicks();
  257. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, true);
  258. break;
  259. case SDL_BUTTON_RIGHT:
  260. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  261. break;
  262. case SDL_BUTTON_MIDDLE:
  263. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, true);
  264. break;
  265. default:
  266. break;
  267. }
  268. }
  269. else if(current->type == SDL_MOUSEWHEEL)
  270. {
  271. std::list<CIntObject*> hlp = wheelInterested;
  272. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  273. {
  274. if(!vstd::contains(wheelInterested,*i)) continue;
  275. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  276. int x = 0, y = 0;
  277. SDL_GetMouseState(&x, &y);
  278. (*i)->wheelScrolled(current->wheel.y < 0, isItIn(&(*i)->pos, x, y));
  279. }
  280. }
  281. else if(current->type == SDL_TEXTINPUT)
  282. {
  283. for(auto it : textInterested)
  284. {
  285. it->textInputed(current->text);
  286. }
  287. }
  288. else if(current->type == SDL_TEXTEDITING)
  289. {
  290. for(auto it : textInterested)
  291. {
  292. it->textEdited(current->edit);
  293. }
  294. }
  295. //todo: muiltitouch
  296. else if(current->type == SDL_MOUSEBUTTONUP)
  297. {
  298. switch(current->button.button)
  299. {
  300. case SDL_BUTTON_LEFT:
  301. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, false);
  302. break;
  303. case SDL_BUTTON_RIGHT:
  304. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  305. break;
  306. case SDL_BUTTON_MIDDLE:
  307. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, false);
  308. break;
  309. }
  310. }
  311. current = nullptr;
  312. } //event end
  313. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed)
  314. {
  315. auto hlp = interestedObjs;
  316. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  317. {
  318. if(!vstd::contains(interestedObjs, *i)) continue;
  319. auto prev = (*i)->mouseState(btn);
  320. if(!isPressed)
  321. (*i)->updateMouseState(btn, isPressed);
  322. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  323. {
  324. if(isPressed)
  325. (*i)->updateMouseState(btn, isPressed);
  326. (*i)->click(btn, isPressed, prev);
  327. }
  328. else if(!isPressed)
  329. (*i)->click(btn, boost::logic::indeterminate, prev);
  330. }
  331. }
  332. void CGuiHandler::handleMouseMotion()
  333. {
  334. //sending active, hovered hoverable objects hover() call
  335. std::vector<CIntObject*> hlp;
  336. for(auto & elem : hoverable)
  337. {
  338. if(isItIn(&(elem)->pos, current->motion.x, current->motion.y))
  339. {
  340. if (!(elem)->hovered)
  341. hlp.push_back((elem));
  342. }
  343. else if ((elem)->hovered)
  344. {
  345. (elem)->hover(false);
  346. (elem)->hovered = false;
  347. }
  348. }
  349. for(auto & elem : hlp)
  350. {
  351. elem->hover(true);
  352. elem->hovered = true;
  353. }
  354. handleMoveInterested(current->motion);
  355. }
  356. void CGuiHandler::simpleRedraw()
  357. {
  358. //update only top interface and draw background
  359. if(objsToBlit.size() > 1)
  360. blitAt(screen2,0,0,screen); //blit background
  361. if(!objsToBlit.empty())
  362. objsToBlit.back()->show(screen); //blit active interface/window
  363. }
  364. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  365. {
  366. //sending active, MotionInterested objects mouseMoved() call
  367. std::list<CIntObject*> miCopy = motioninterested;
  368. for(auto & elem : miCopy)
  369. {
  370. if(elem->strongInterest || isItInOrLowerBounds(&elem->pos, motion.x, motion.y)) //checking lower bounds fixes bug #2476
  371. {
  372. (elem)->mouseMoved(motion);
  373. }
  374. }
  375. }
  376. void CGuiHandler::fakeMouseMove()
  377. {
  378. SDL_Event event;
  379. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  380. int x, y;
  381. sme.state = SDL_GetMouseState(&x, &y);
  382. sme.x = x;
  383. sme.y = y;
  384. event.motion = sme;
  385. SDL_PushEvent(&event);
  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. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  408. SDL_RenderPresent(mainRenderer);
  409. }
  410. mainFPSmng->framerateDelay(); // holds a constant FPS
  411. }
  412. CGuiHandler::CGuiHandler()
  413. : lastClick(-500, -500),lastClickTime(0), defActionsDef(0), captureChildren(false)
  414. {
  415. continueEventHandling = true;
  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 = new CondSh<bool>(false);
  423. }
  424. CGuiHandler::~CGuiHandler()
  425. {
  426. delete mainFPSmng;
  427. delete terminate_cond;
  428. }
  429. void CGuiHandler::breakEventHandling()
  430. {
  431. continueEventHandling = false;
  432. }
  433. void CGuiHandler::drawFPSCounter()
  434. {
  435. const static SDL_Color yellow = {255, 255, 0, 0};
  436. static SDL_Rect overlay = { 0, 0, 64, 32};
  437. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  438. SDL_FillRect(screen, &overlay, black);
  439. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  440. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  441. }
  442. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  443. {
  444. switch(key)
  445. {
  446. case SDLK_DOWN:
  447. return SDLK_KP_2;
  448. case SDLK_UP:
  449. return SDLK_KP_8;
  450. case SDLK_LEFT:
  451. return SDLK_KP_4;
  452. case SDLK_RIGHT:
  453. return SDLK_KP_6;
  454. default:
  455. throw std::runtime_error("Wrong key!");
  456. }
  457. }
  458. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  459. {
  460. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  461. switch(key)
  462. {
  463. REMOVE_KP(0)
  464. REMOVE_KP(1)
  465. REMOVE_KP(2)
  466. REMOVE_KP(3)
  467. REMOVE_KP(4)
  468. REMOVE_KP(5)
  469. REMOVE_KP(6)
  470. REMOVE_KP(7)
  471. REMOVE_KP(8)
  472. REMOVE_KP(9)
  473. REMOVE_KP(PERIOD)
  474. REMOVE_KP(MINUS)
  475. REMOVE_KP(PLUS)
  476. REMOVE_KP(EQUALS)
  477. case SDLK_KP_MULTIPLY:
  478. return SDLK_ASTERISK;
  479. case SDLK_KP_DIVIDE:
  480. return SDLK_SLASH;
  481. case SDLK_KP_ENTER:
  482. return SDLK_RETURN;
  483. default:
  484. return SDLK_UNKNOWN;
  485. }
  486. #undef REMOVE_KP
  487. }
  488. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  489. {
  490. if(number)
  491. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  492. else
  493. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  494. }
  495. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  496. {
  497. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  498. }
  499. bool CGuiHandler::amIGuiThread()
  500. {
  501. return inGuiThread.get() && *inGuiThread;
  502. }
  503. void CGuiHandler::pushSDLEvent(int type, int usercode)
  504. {
  505. SDL_Event event;
  506. event.type = type;
  507. event.user.code = usercode; // not necessarily used
  508. SDL_PushEvent(&event);
  509. }
  510. CFramerateManager::CFramerateManager(int rate)
  511. {
  512. this->rate = rate;
  513. this->rateticks = (1000.0 / rate);
  514. this->fps = 0;
  515. this->accumulatedFrames = 0;
  516. this->accumulatedTime = 0;
  517. this->lastticks = 0;
  518. this->timeElapsed = 0;
  519. }
  520. void CFramerateManager::init()
  521. {
  522. this->lastticks = SDL_GetTicks();
  523. }
  524. void CFramerateManager::framerateDelay()
  525. {
  526. ui32 currentTicks = SDL_GetTicks();
  527. timeElapsed = currentTicks - lastticks;
  528. // FPS is higher than it should be, then wait some time
  529. if (timeElapsed < rateticks)
  530. {
  531. SDL_Delay(ceil(this->rateticks) - timeElapsed);
  532. }
  533. accumulatedTime += timeElapsed;
  534. accumulatedFrames++;
  535. if(accumulatedFrames >= 100)
  536. {
  537. //about 2 second should be passed
  538. fps = ceil(1000.0 / (accumulatedTime/accumulatedFrames));
  539. accumulatedTime = 0;
  540. accumulatedFrames = 0;
  541. }
  542. currentTicks = SDL_GetTicks();
  543. // recalculate timeElapsed for external calls via getElapsed()
  544. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  545. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  546. lastticks = SDL_GetTicks();
  547. }