CGuiHandler.cpp 14 KB

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