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