CGuiHandler.cpp 16 KB

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