CGuiHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #include "StdInc.h"
  2. #include "CGuiHandler.h"
  3. #include "SDL_Extensions.h"
  4. #include "CIntObject.h"
  5. #include "../CGameInfo.h"
  6. #include "CCursorHandler.h"
  7. #include "../../lib/CThreadHelper.h"
  8. #include "../../lib/CConfigHandler.h"
  9. #include "../CMT.h"
  10. extern std::queue<SDL_Event> events;
  11. extern boost::mutex eventsM;
  12. boost::thread_specific_ptr<bool> inGuiThread;
  13. SObjectConstruction::SObjectConstruction( CIntObject *obj )
  14. :myObj(obj)
  15. {
  16. GH.createdObj.push_front(obj);
  17. GH.captureChildren = true;
  18. }
  19. SObjectConstruction::~SObjectConstruction()
  20. {
  21. assert(GH.createdObj.size());
  22. assert(GH.createdObj.front() == myObj);
  23. GH.createdObj.pop_front();
  24. GH.captureChildren = GH.createdObj.size();
  25. }
  26. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  27. {
  28. previousCapture = GH.captureChildren;
  29. GH.captureChildren = false;
  30. prevActions = GH.defActionsDef;
  31. GH.defActionsDef = actions;
  32. }
  33. SSetCaptureState::~SSetCaptureState()
  34. {
  35. GH.captureChildren = previousCapture;
  36. GH.defActionsDef = prevActions;
  37. }
  38. static inline void
  39. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  40. {
  41. if (mask & flag)
  42. cb(lst);
  43. }
  44. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  45. {
  46. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  47. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  48. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  49. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  50. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  51. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  52. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  53. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  54. }
  55. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  56. {
  57. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  58. lst->push_front(elem);
  59. });
  60. elem->active_m |= activityFlag;
  61. }
  62. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  63. {
  64. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  65. auto hlp = std::find(lst->begin(),lst->end(),elem);
  66. assert(hlp != lst->end());
  67. lst->erase(hlp);
  68. });
  69. elem->active_m &= ~activityFlag;
  70. }
  71. void CGuiHandler::popInt( IShowActivatable *top )
  72. {
  73. assert(listInt.front() == top);
  74. top->deactivate();
  75. listInt.pop_front();
  76. objsToBlit -= top;
  77. if(!listInt.empty())
  78. listInt.front()->activate();
  79. totalRedraw();
  80. }
  81. void CGuiHandler::popIntTotally( IShowActivatable *top )
  82. {
  83. assert(listInt.front() == top);
  84. popInt(top);
  85. delete top;
  86. fakeMouseMove();
  87. }
  88. void CGuiHandler::pushInt( IShowActivatable *newInt )
  89. {
  90. assert(newInt);
  91. assert(boost::range::find(listInt, newInt) == listInt.end()); // do not add same object twice
  92. //a new interface will be present, we'll need to use buffer surface (unless it's advmapint that will alter screenBuf on activate anyway)
  93. screenBuf = screen2;
  94. if(!listInt.empty())
  95. listInt.front()->deactivate();
  96. listInt.push_front(newInt);
  97. newInt->activate();
  98. objsToBlit.push_back(newInt);
  99. totalRedraw();
  100. }
  101. void CGuiHandler::popInts( int howMany )
  102. {
  103. if(!howMany) return; //senseless but who knows...
  104. assert(listInt.size() >= howMany);
  105. listInt.front()->deactivate();
  106. for(int i=0; i < howMany; i++)
  107. {
  108. objsToBlit -= listInt.front();
  109. delete listInt.front();
  110. listInt.pop_front();
  111. }
  112. if(!listInt.empty())
  113. {
  114. listInt.front()->activate();
  115. totalRedraw();
  116. }
  117. fakeMouseMove();
  118. }
  119. IShowActivatable * CGuiHandler::topInt()
  120. {
  121. if(listInt.empty())
  122. return nullptr;
  123. else
  124. return listInt.front();
  125. }
  126. void CGuiHandler::totalRedraw()
  127. {
  128. for(auto & elem : objsToBlit)
  129. elem->showAll(screen2);
  130. blitAt(screen2,0,0,screen);
  131. }
  132. void CGuiHandler::updateTime()
  133. {
  134. int ms = mainFPSmng->getElapsedMilliseconds();
  135. std::list<CIntObject*> hlp = timeinterested;
  136. for (auto & elem : hlp)
  137. {
  138. if(!vstd::contains(timeinterested,elem)) continue;
  139. (elem)->onTimer(ms);
  140. }
  141. }
  142. void CGuiHandler::handleEvents()
  143. {
  144. while(true)
  145. {
  146. SDL_Event ev;
  147. boost::unique_lock<boost::mutex> lock(eventsM);
  148. if(!events.size())
  149. {
  150. return;
  151. }
  152. else
  153. {
  154. ev = events.front();
  155. events.pop();
  156. }
  157. 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. //translate numpad keys
  168. if(key.keysym.sym == SDLK_KP_ENTER)
  169. {
  170. key.keysym.sym = (SDLKey)SDLK_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. else if(sEvent->button.button == SDL_BUTTON_WHEELDOWN || sEvent->button.button == SDL_BUTTON_WHEELUP)
  236. {
  237. std::list<CIntObject*> hlp = wheelInterested;
  238. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  239. {
  240. if(!vstd::contains(wheelInterested,*i)) continue;
  241. (*i)->wheelScrolled(sEvent->button.button == SDL_BUTTON_WHEELDOWN, isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y));
  242. }
  243. }
  244. }
  245. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_LEFT))
  246. {
  247. std::list<CIntObject*> hlp = lclickable;
  248. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  249. {
  250. if(!vstd::contains(lclickable,*i)) continue;
  251. prev = (*i)->pressedL;
  252. (*i)->pressedL = false;
  253. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  254. {
  255. (*i)->clickLeft(false, prev);
  256. }
  257. else
  258. (*i)->clickLeft(boost::logic::indeterminate, prev);
  259. }
  260. }
  261. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_RIGHT))
  262. {
  263. std::list<CIntObject*> hlp = rclickable;
  264. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  265. {
  266. if(!vstd::contains(rclickable,*i)) continue;
  267. prev = (*i)->pressedR;
  268. (*i)->pressedR = false;
  269. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  270. {
  271. (*i)->clickRight(false, prev);
  272. }
  273. else
  274. (*i)->clickRight(boost::logic::indeterminate, prev);
  275. }
  276. }
  277. current = nullptr;
  278. } //event end
  279. void CGuiHandler::handleMouseMotion(SDL_Event *sEvent)
  280. {
  281. //sending active, hovered hoverable objects hover() call
  282. std::vector<CIntObject*> hlp;
  283. for(auto & elem : hoverable)
  284. {
  285. if (isItIn(&(elem)->pos,sEvent->motion.x,sEvent->motion.y))
  286. {
  287. if (!(elem)->hovered)
  288. hlp.push_back((elem));
  289. }
  290. else if ((elem)->hovered)
  291. {
  292. (elem)->hover(false);
  293. (elem)->hovered = false;
  294. }
  295. }
  296. for(auto & elem : hlp)
  297. {
  298. elem->hover(true);
  299. elem->hovered = true;
  300. }
  301. handleMoveInterested(sEvent->motion);
  302. }
  303. void CGuiHandler::simpleRedraw()
  304. {
  305. //update only top interface and draw background
  306. if(objsToBlit.size() > 1)
  307. blitAt(screen2,0,0,screen); //blit background
  308. objsToBlit.back()->show(screen); //blit active interface/window
  309. }
  310. void CGuiHandler::handleMoveInterested( const SDL_MouseMotionEvent & motion )
  311. {
  312. //sending active, MotionInterested objects mouseMoved() call
  313. std::list<CIntObject*> miCopy = motioninterested;
  314. for(auto & elem : miCopy)
  315. {
  316. if ((elem)->strongInterest || isItIn(&(elem)->pos, motion.x, motion.y))
  317. {
  318. (elem)->mouseMoved(motion);
  319. }
  320. }
  321. }
  322. void CGuiHandler::fakeMouseMove()
  323. {
  324. SDL_Event evnt;
  325. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0};
  326. int x, y;
  327. sme.state = SDL_GetMouseState(&x, &y);
  328. sme.x = x;
  329. sme.y = y;
  330. evnt.motion = sme;
  331. current = &evnt;
  332. handleMouseMotion(&evnt);
  333. }
  334. void CGuiHandler::run()
  335. {
  336. setThreadName("CGuiHandler::run");
  337. inGuiThread.reset(new bool(true));
  338. try
  339. {
  340. if(settings["video"]["fullscreen"].Bool())
  341. CCS->curh->centerCursor();
  342. mainFPSmng->init(); // resets internal clock, needed for FPS manager
  343. while(!terminate)
  344. {
  345. if(curInt)
  346. curInt->update(); // calls a update and drawing process of the loaded game interface object at the moment
  347. mainFPSmng->framerateDelay(); // holds a constant FPS
  348. }
  349. }
  350. catch(const std::exception & e)
  351. {
  352. logGlobal->errorStream() << "Error: " << e.what();
  353. exit(EXIT_FAILURE);
  354. }
  355. }
  356. CGuiHandler::CGuiHandler()
  357. :lastClick(-500, -500)
  358. {
  359. curInt = nullptr;
  360. current = nullptr;
  361. terminate = false;
  362. statusbar = nullptr;
  363. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  364. mainFPSmng = new CFramerateManager(48);
  365. mainFPSmng->init(); // resets internal clock, needed for FPS manager
  366. }
  367. CGuiHandler::~CGuiHandler()
  368. {
  369. delete mainFPSmng;
  370. }
  371. void CGuiHandler::breakEventHandling()
  372. {
  373. current = nullptr;
  374. }
  375. void CGuiHandler::drawFPSCounter()
  376. {
  377. const static SDL_Color yellow = {255, 255, 0, 0};
  378. static SDL_Rect overlay = { 0, 0, 64, 32};
  379. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  380. SDL_FillRect(screen, &overlay, black);
  381. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  382. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  383. }
  384. SDLKey CGuiHandler::arrowToNum( SDLKey key )
  385. {
  386. switch(key)
  387. {
  388. case SDLK_DOWN:
  389. return SDLK_KP2;
  390. case SDLK_UP:
  391. return SDLK_KP8;
  392. case SDLK_LEFT:
  393. return SDLK_KP4;
  394. case SDLK_RIGHT:
  395. return SDLK_KP6;
  396. default:
  397. assert(0);
  398. }
  399. throw std::runtime_error("Wrong key!");
  400. }
  401. SDLKey CGuiHandler::numToDigit( SDLKey key )
  402. {
  403. if(key >= SDLK_KP0 && key <= SDLK_KP9)
  404. return SDLKey(key - SDLK_KP0 + SDLK_0);
  405. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  406. switch(key)
  407. {
  408. REMOVE_KP(PERIOD)
  409. REMOVE_KP(MINUS)
  410. REMOVE_KP(PLUS)
  411. REMOVE_KP(EQUALS)
  412. case SDLK_KP_MULTIPLY:
  413. return SDLK_ASTERISK;
  414. case SDLK_KP_DIVIDE:
  415. return SDLK_SLASH;
  416. case SDLK_KP_ENTER:
  417. return SDLK_RETURN;
  418. default:
  419. return SDLK_UNKNOWN;
  420. }
  421. #undef REMOVE_KP
  422. }
  423. bool CGuiHandler::isNumKey( SDLKey key, bool number )
  424. {
  425. if(number)
  426. return key >= SDLK_KP0 && key <= SDLK_KP9;
  427. else
  428. return key >= SDLK_KP0 && key <= SDLK_KP_EQUALS;
  429. }
  430. bool CGuiHandler::isArrowKey( SDLKey key )
  431. {
  432. return key >= SDLK_UP && key <= SDLK_LEFT;
  433. }
  434. bool CGuiHandler::amIGuiThread()
  435. {
  436. return inGuiThread.get() && *inGuiThread;
  437. }
  438. void CGuiHandler::pushSDLEvent(int type, int usercode)
  439. {
  440. SDL_Event event;
  441. event.type = type;
  442. event.user.code = usercode; // not necessarily used
  443. SDL_PushEvent(&event);
  444. }
  445. CFramerateManager::CFramerateManager(int rate)
  446. {
  447. this->rate = rate;
  448. this->rateticks = (1000.0 / rate);
  449. this->fps = 0;
  450. }
  451. void CFramerateManager::init()
  452. {
  453. this->lastticks = SDL_GetTicks();
  454. }
  455. void CFramerateManager::framerateDelay()
  456. {
  457. ui32 currentTicks = SDL_GetTicks();
  458. timeElapsed = currentTicks - lastticks;
  459. // FPS is higher than it should be, then wait some time
  460. if (timeElapsed < rateticks)
  461. {
  462. SDL_Delay(ceil(this->rateticks) - timeElapsed);
  463. }
  464. currentTicks = SDL_GetTicks();
  465. fps = ceil(1000.0 / timeElapsed);
  466. // recalculate timeElapsed for external calls via getElapsed()
  467. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  468. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  469. lastticks = SDL_GetTicks();
  470. }