CGuiHandler.cpp 16 KB

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