CGuiHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #include "StdInc.h"
  2. #include "CGuiHandler.h"
  3. #include "GL2D.h"
  4. #include "SDL_Extensions.h"
  5. #include "CIntObject.h"
  6. #include "../CGameInfo.h"
  7. #include "../CPlayerInterface.h"
  8. #include "CCursorHandler.h"
  9. #include "../../lib/CThreadHelper.h"
  10. #include "../../lib/CConfigHandler.h"
  11. extern SDL_Surface * screenBuf, * screen2, * screen;
  12. extern std::queue<SDL_Event> events;
  13. extern boost::mutex eventsM;
  14. boost::thread_specific_ptr<bool> inGuiThread;
  15. SObjectConstruction::SObjectConstruction( CIntObject *obj )
  16. :myObj(obj)
  17. {
  18. GH.createdObj.push_front(obj);
  19. GH.captureChildren = true;
  20. }
  21. SObjectConstruction::~SObjectConstruction()
  22. {
  23. assert(GH.createdObj.size());
  24. assert(GH.createdObj.front() == myObj);
  25. GH.createdObj.pop_front();
  26. GH.captureChildren = GH.createdObj.size();
  27. }
  28. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  29. {
  30. previousCapture = GH.captureChildren;
  31. GH.captureChildren = false;
  32. prevActions = GH.defActionsDef;
  33. GH.defActionsDef = actions;
  34. }
  35. SSetCaptureState::~SSetCaptureState()
  36. {
  37. GH.captureChildren = previousCapture;
  38. GH.defActionsDef = prevActions;
  39. }
  40. static inline void
  41. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  42. {
  43. if (mask & flag)
  44. cb(lst);
  45. }
  46. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  47. {
  48. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  49. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  50. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  51. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  52. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  53. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  54. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  55. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  56. }
  57. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  58. {
  59. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  60. lst->push_front(elem);
  61. });
  62. elem->active_m |= activityFlag;
  63. }
  64. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  65. {
  66. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  67. std::list<CIntObject*>::iterator hlp = std::find(lst->begin(),lst->end(),elem);
  68. assert(hlp != lst->end());
  69. lst->erase(hlp);
  70. });
  71. elem->active_m &= ~activityFlag;
  72. }
  73. void CGuiHandler::popInt( IShowActivatable *top )
  74. {
  75. assert(listInt.front() == top);
  76. top->deactivate();
  77. listInt.pop_front();
  78. objsToBlit -= top;
  79. if(listInt.size())
  80. listInt.front()->activate();
  81. totalRedraw();
  82. }
  83. void CGuiHandler::popIntTotally( IShowActivatable *top )
  84. {
  85. assert(listInt.front() == top);
  86. popInt(top);
  87. delete top;
  88. fakeMouseMove();
  89. }
  90. void CGuiHandler::pushInt( IShowActivatable *newInt )
  91. {
  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.size())
  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.size())
  113. {
  114. listInt.front()->activate();
  115. totalRedraw();
  116. }
  117. fakeMouseMove();
  118. }
  119. IShowActivatable * CGuiHandler::topInt()
  120. {
  121. if(!listInt.size())
  122. return NULL;
  123. else
  124. return listInt.front();
  125. }
  126. void CGuiHandler::totalRedraw()
  127. {
  128. for (size_t i=0; i<objsToBlit.size(); ++i)
  129. objsToBlit[i]->showAll();
  130. if (settings["general"]["showfps"].Bool()) drawFPSCounter();
  131. // draw the mouse cursor and update the screen
  132. CCS->curh->drawWithScreenRestore();
  133. CCS->curh->drawRestored();
  134. SDL_GL_SwapBuffers();
  135. }
  136. void CGuiHandler::updateTime()
  137. {
  138. int ms = mainFPSmng->getElapsedMilliseconds();
  139. std::list<CIntObject*> hlp = timeinterested;
  140. for (std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end();i++)
  141. {
  142. if(!vstd::contains(timeinterested,*i)) continue;
  143. (*i)->onTimer(ms);
  144. }
  145. }
  146. void CGuiHandler::handleEvents()
  147. {
  148. while(true)
  149. {
  150. SDL_Event ev;
  151. boost::unique_lock<boost::mutex> lock(eventsM);
  152. if(!events.size())
  153. {
  154. return;
  155. }
  156. else
  157. {
  158. ev = events.front();
  159. events.pop();
  160. }
  161. handleEvent(&ev);
  162. }
  163. }
  164. void CGuiHandler::handleEvent(SDL_Event *sEvent)
  165. {
  166. current = sEvent;
  167. bool prev;
  168. if (sEvent->type==SDL_KEYDOWN || sEvent->type==SDL_KEYUP)
  169. {
  170. SDL_KeyboardEvent key = sEvent->key;
  171. //translate numpad keys
  172. if(key.keysym.sym == SDLK_KP_ENTER)
  173. {
  174. key.keysym.sym = (SDLKey)SDLK_RETURN;
  175. }
  176. bool keysCaptured = false;
  177. for(std::list<CIntObject*>::iterator i=keyinterested.begin(); i != keyinterested.end() && current; i++)
  178. {
  179. if((*i)->captureThisEvent(key))
  180. {
  181. keysCaptured = true;
  182. break;
  183. }
  184. }
  185. std::list<CIntObject*> miCopy = keyinterested;
  186. for(std::list<CIntObject*>::iterator i=miCopy.begin(); i != miCopy.end() && current; i++)
  187. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  188. (**i).keyPressed(key);
  189. }
  190. else if(sEvent->type==SDL_MOUSEMOTION)
  191. {
  192. CCS->curh->cursorMove(sEvent->motion.x, sEvent->motion.y);
  193. handleMouseMotion(sEvent);
  194. }
  195. else if (sEvent->type==SDL_MOUSEBUTTONDOWN)
  196. {
  197. if(sEvent->button.button == SDL_BUTTON_LEFT)
  198. {
  199. if(lastClick == sEvent->motion && (SDL_GetTicks() - lastClickTime) < 300)
  200. {
  201. std::list<CIntObject*> hlp = doubleClickInterested;
  202. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  203. {
  204. if(!vstd::contains(doubleClickInterested,*i)) continue;
  205. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  206. {
  207. (*i)->onDoubleClick();
  208. }
  209. }
  210. }
  211. lastClick = sEvent->motion;
  212. lastClickTime = SDL_GetTicks();
  213. std::list<CIntObject*> hlp = lclickable;
  214. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  215. {
  216. if(!vstd::contains(lclickable,*i)) continue;
  217. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  218. {
  219. prev = (*i)->pressedL;
  220. (*i)->pressedL = true;
  221. (*i)->clickLeft(true, prev);
  222. }
  223. }
  224. }
  225. else if (sEvent->button.button == SDL_BUTTON_RIGHT)
  226. {
  227. std::list<CIntObject*> hlp = rclickable;
  228. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  229. {
  230. if(!vstd::contains(rclickable,*i)) continue;
  231. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  232. {
  233. prev = (*i)->pressedR;
  234. (*i)->pressedR = true;
  235. (*i)->clickRight(true, prev);
  236. }
  237. }
  238. }
  239. else if(sEvent->button.button == SDL_BUTTON_WHEELDOWN || sEvent->button.button == SDL_BUTTON_WHEELUP)
  240. {
  241. std::list<CIntObject*> hlp = wheelInterested;
  242. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  243. {
  244. if(!vstd::contains(wheelInterested,*i)) continue;
  245. (*i)->wheelScrolled(sEvent->button.button == SDL_BUTTON_WHEELDOWN, isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y));
  246. }
  247. }
  248. }
  249. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_LEFT))
  250. {
  251. std::list<CIntObject*> hlp = lclickable;
  252. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  253. {
  254. if(!vstd::contains(lclickable,*i)) continue;
  255. prev = (*i)->pressedL;
  256. (*i)->pressedL = false;
  257. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  258. {
  259. (*i)->clickLeft(false, prev);
  260. }
  261. else
  262. (*i)->clickLeft(boost::logic::indeterminate, prev);
  263. }
  264. }
  265. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_RIGHT))
  266. {
  267. std::list<CIntObject*> hlp = rclickable;
  268. for(std::list<CIntObject*>::iterator i=hlp.begin(); i != hlp.end() && current; i++)
  269. {
  270. if(!vstd::contains(rclickable,*i)) continue;
  271. prev = (*i)->pressedR;
  272. (*i)->pressedR = false;
  273. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  274. {
  275. (*i)->clickRight(false, prev);
  276. }
  277. else
  278. (*i)->clickRight(boost::logic::indeterminate, prev);
  279. }
  280. }
  281. current = NULL;
  282. } //event end
  283. void CGuiHandler::handleMouseMotion(SDL_Event *sEvent)
  284. {
  285. //sending active, hovered hoverable objects hover() call
  286. std::vector<CIntObject*> hlp;
  287. for(std::list<CIntObject*>::iterator i=hoverable.begin(); i != hoverable.end();i++)
  288. {
  289. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  290. {
  291. if (!(*i)->hovered)
  292. hlp.push_back((*i));
  293. }
  294. else if ((*i)->hovered)
  295. {
  296. (*i)->hover(false);
  297. (*i)->hovered = false;
  298. }
  299. }
  300. for(int i=0; i<hlp.size();i++)
  301. {
  302. hlp[i]->hover(true);
  303. hlp[i]->hovered = true;
  304. }
  305. handleMoveInterested(sEvent->motion);
  306. }
  307. void CGuiHandler::simpleRedraw()
  308. {
  309. //update only top interface and draw background
  310. //* if(objsToBlit.size() > 1)
  311. //* blitAt(screen2,0,0,screen); //blit background
  312. objsToBlit.back()->show(); //blit active interface/window
  313. }
  314. void CGuiHandler::handleMoveInterested( const SDL_MouseMotionEvent & motion )
  315. {
  316. //sending active, MotionInterested objects mouseMoved() call
  317. std::list<CIntObject*> miCopy = motioninterested;
  318. for(std::list<CIntObject*>::iterator i=miCopy.begin(); i != miCopy.end();i++)
  319. {
  320. if ((*i)->strongInterest || isItIn(&(*i)->pos, motion.x, motion.y))
  321. {
  322. (*i)->mouseMoved(motion);
  323. }
  324. }
  325. }
  326. void CGuiHandler::fakeMouseMove()
  327. {
  328. SDL_Event evnt;
  329. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0};
  330. int x, y;
  331. sme.state = SDL_GetMouseState(&x, &y);
  332. sme.x = x;
  333. sme.y = y;
  334. evnt.motion = sme;
  335. current = &evnt;
  336. handleMouseMotion(&evnt);
  337. }
  338. void CGuiHandler::run()
  339. {
  340. setThreadName("CGuiHandler::run");
  341. inGuiThread.reset(new bool(true));
  342. try
  343. {
  344. GL2D::attachToCurrentThread();
  345. if (settings["video"]["fullscreen"].Bool())
  346. CCS->curh->centerCursor();
  347. mainFPSmng->init(); // resets internal clock, needed for FPS manager
  348. while(!terminate)
  349. {
  350. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  351. if (curInt) curInt->update();
  352. // Handles mouse and key input
  353. updateTime();
  354. handleEvents();
  355. totalRedraw();
  356. mainFPSmng->framerateDelay(); // holds a constant FPS
  357. }
  358. }
  359. catch(const std::exception & e)
  360. {
  361. tlog1 << "Error: " << e.what() << std::endl;
  362. exit(EXIT_FAILURE);
  363. }
  364. }
  365. CGuiHandler::CGuiHandler()
  366. :lastClick(-500, -500)
  367. {
  368. curInt = NULL;
  369. current = NULL;
  370. terminate = false;
  371. statusbar = NULL;
  372. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  373. mainFPSmng = new CFramerateManager(48);
  374. mainFPSmng->init(); // resets internal clock, needed for FPS manager
  375. }
  376. CGuiHandler::~CGuiHandler()
  377. {
  378. delete mainFPSmng;
  379. }
  380. void CGuiHandler::breakEventHandling()
  381. {
  382. current = NULL;
  383. }
  384. void CGuiHandler::drawFPSCounter()
  385. {
  386. const static SDL_Color yellow = {255, 255, 0, 0};
  387. static SDL_Rect overlay = { 0, 0, 64, 32};
  388. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  389. SDL_FillRect(screen, &overlay, black);
  390. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  391. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  392. }
  393. SDLKey CGuiHandler::arrowToNum( SDLKey key )
  394. {
  395. switch(key)
  396. {
  397. case SDLK_DOWN:
  398. return SDLK_KP2;
  399. case SDLK_UP:
  400. return SDLK_KP8;
  401. case SDLK_LEFT:
  402. return SDLK_KP4;
  403. case SDLK_RIGHT:
  404. return SDLK_KP6;
  405. default:
  406. assert(0);
  407. }
  408. throw std::runtime_error("Wrong key!");
  409. }
  410. SDLKey CGuiHandler::numToDigit( SDLKey key )
  411. {
  412. if(key >= SDLK_KP0 && key <= SDLK_KP9)
  413. return SDLKey(key - SDLK_KP0 + SDLK_0);
  414. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  415. switch(key)
  416. {
  417. REMOVE_KP(PERIOD)
  418. REMOVE_KP(MINUS)
  419. REMOVE_KP(PLUS)
  420. REMOVE_KP(EQUALS)
  421. case SDLK_KP_MULTIPLY:
  422. return SDLK_ASTERISK;
  423. case SDLK_KP_DIVIDE:
  424. return SDLK_SLASH;
  425. case SDLK_KP_ENTER:
  426. return SDLK_RETURN;
  427. default:
  428. //tlog3 << "Illegal numkey conversion!" << std::endl;
  429. return SDLK_UNKNOWN;
  430. }
  431. #undef REMOVE_KP
  432. }
  433. bool CGuiHandler::isNumKey( SDLKey key, bool number )
  434. {
  435. if(number)
  436. return key >= SDLK_KP0 && key <= SDLK_KP9;
  437. else
  438. return key >= SDLK_KP0 && key <= SDLK_KP_EQUALS;
  439. }
  440. bool CGuiHandler::isArrowKey( SDLKey key )
  441. {
  442. return key >= SDLK_UP && key <= SDLK_LEFT;
  443. }
  444. bool CGuiHandler::amIGuiThread()
  445. {
  446. return inGuiThread.get() && *inGuiThread;
  447. }
  448. void CGuiHandler::pushSDLEvent(int type, int usercode)
  449. {
  450. SDL_Event event;
  451. event.type = type;
  452. event.user.code = usercode; // not necessarily used
  453. SDL_PushEvent(&event);
  454. }
  455. CFramerateManager::CFramerateManager(int rate)
  456. {
  457. this->rate = rate;
  458. this->rateticks = (ui32)ceil(1000.0 / rate);
  459. this->fps = 0;
  460. }
  461. void CFramerateManager::init()
  462. {
  463. this->lastticks = SDL_GetTicks();
  464. }
  465. void CFramerateManager::framerateDelay()
  466. {
  467. ui32 currentTicks = SDL_GetTicks();
  468. timeElapsed = currentTicks - lastticks;
  469. // FPS is higher than it should be, then wait some time
  470. if (timeElapsed < rateticks)
  471. {
  472. SDL_Delay(rateticks - timeElapsed);
  473. }
  474. currentTicks = SDL_GetTicks();
  475. fps = ceil(1000.0 / timeElapsed);
  476. //recalculate timeElapsed for external calls via getElapsed()
  477. timeElapsed = currentTicks - lastticks;
  478. lastticks = SDL_GetTicks();
  479. }