CGuiHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. #include "StdInc.h"
  2. #include "CGuiHandler.h"
  3. #include "CIntObject.h"
  4. #include "../CGameInfo.h"
  5. #include "CCursorHandler.h"
  6. #include "../../lib/CThreadHelper.h"
  7. #include "../../lib/CConfigHandler.h"
  8. #include "../CMT.h"
  9. extern std::queue<SDL_Event> events;
  10. extern boost::mutex eventsM;
  11. boost::thread_specific_ptr<bool> inGuiThread;
  12. SObjectConstruction::SObjectConstruction( CIntObject *obj )
  13. :myObj(obj)
  14. {
  15. GH.createdObj.push_front(obj);
  16. GH.captureChildren = true;
  17. }
  18. SObjectConstruction::~SObjectConstruction()
  19. {
  20. assert(GH.createdObj.size());
  21. assert(GH.createdObj.front() == myObj);
  22. GH.createdObj.pop_front();
  23. GH.captureChildren = GH.createdObj.size();
  24. }
  25. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  26. {
  27. previousCapture = GH.captureChildren;
  28. GH.captureChildren = false;
  29. prevActions = GH.defActionsDef;
  30. GH.defActionsDef = actions;
  31. }
  32. SSetCaptureState::~SSetCaptureState()
  33. {
  34. GH.captureChildren = previousCapture;
  35. GH.defActionsDef = prevActions;
  36. }
  37. static inline void
  38. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  39. {
  40. if (mask & flag)
  41. cb(lst);
  42. }
  43. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  44. {
  45. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  46. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  47. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  48. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  49. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  50. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  51. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  52. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  53. #ifndef VCMI_SDL1
  54. processList(CIntObject::TEXTINPUT,activityFlag,&textInterested,cb);
  55. #endif // VCMI_SDL1
  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. auto 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.empty())
  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. assert(newInt);
  93. assert(boost::range::find(listInt, newInt) == listInt.end()); // do not add same object twice
  94. //a new interface will be present, we'll need to use buffer surface (unless it's advmapint that will alter screenBuf on activate anyway)
  95. screenBuf = screen2;
  96. if(!listInt.empty())
  97. listInt.front()->deactivate();
  98. listInt.push_front(newInt);
  99. newInt->activate();
  100. objsToBlit.push_back(newInt);
  101. totalRedraw();
  102. }
  103. void CGuiHandler::popInts( int howMany )
  104. {
  105. if(!howMany) return; //senseless but who knows...
  106. assert(listInt.size() >= howMany);
  107. listInt.front()->deactivate();
  108. for(int i=0; i < howMany; i++)
  109. {
  110. objsToBlit -= listInt.front();
  111. delete listInt.front();
  112. listInt.pop_front();
  113. }
  114. if(!listInt.empty())
  115. {
  116. listInt.front()->activate();
  117. totalRedraw();
  118. }
  119. fakeMouseMove();
  120. }
  121. IShowActivatable * CGuiHandler::topInt()
  122. {
  123. if(listInt.empty())
  124. return nullptr;
  125. else
  126. return listInt.front();
  127. }
  128. void CGuiHandler::totalRedraw()
  129. {
  130. for(auto & elem : objsToBlit)
  131. elem->showAll(screen2);
  132. blitAt(screen2,0,0,screen);
  133. }
  134. void CGuiHandler::updateTime()
  135. {
  136. int ms = mainFPSmng->getElapsedMilliseconds();
  137. std::list<CIntObject*> hlp = timeinterested;
  138. for (auto & elem : hlp)
  139. {
  140. if(!vstd::contains(timeinterested,elem)) continue;
  141. (elem)->onTimer(ms);
  142. }
  143. }
  144. void CGuiHandler::handleEvents()
  145. {
  146. while(true)
  147. {
  148. SDL_Event ev;
  149. boost::unique_lock<boost::mutex> lock(eventsM);
  150. if(events.empty())
  151. {
  152. return;
  153. }
  154. else
  155. {
  156. ev = events.front();
  157. events.pop();
  158. }
  159. handleEvent(&ev);
  160. }
  161. }
  162. void CGuiHandler::handleEvent(SDL_Event *sEvent)
  163. {
  164. current = sEvent;
  165. bool prev;
  166. if (sEvent->type==SDL_KEYDOWN || sEvent->type==SDL_KEYUP)
  167. {
  168. SDL_KeyboardEvent key = sEvent->key;
  169. //translate numpad keys
  170. if(key.keysym.sym == SDLK_KP_ENTER)
  171. {
  172. key.keysym.sym = (SDLKey)SDLK_RETURN;
  173. }
  174. bool keysCaptured = false;
  175. for(auto i=keyinterested.begin(); i != keyinterested.end() && current; i++)
  176. {
  177. if((*i)->captureThisEvent(key))
  178. {
  179. keysCaptured = true;
  180. break;
  181. }
  182. }
  183. std::list<CIntObject*> miCopy = keyinterested;
  184. for(auto i=miCopy.begin(); i != miCopy.end() && current; i++)
  185. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  186. (**i).keyPressed(key);
  187. }
  188. else if(sEvent->type==SDL_MOUSEMOTION)
  189. {
  190. CCS->curh->cursorMove(sEvent->motion.x, sEvent->motion.y);
  191. handleMouseMotion(sEvent);
  192. }
  193. else if (sEvent->type==SDL_MOUSEBUTTONDOWN)
  194. {
  195. if(sEvent->button.button == SDL_BUTTON_LEFT)
  196. {
  197. if(lastClick == sEvent->motion && (SDL_GetTicks() - lastClickTime) < 300)
  198. {
  199. std::list<CIntObject*> hlp = doubleClickInterested;
  200. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  201. {
  202. if(!vstd::contains(doubleClickInterested,*i)) continue;
  203. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  204. {
  205. (*i)->onDoubleClick();
  206. }
  207. }
  208. }
  209. lastClick = sEvent->motion;
  210. lastClickTime = SDL_GetTicks();
  211. std::list<CIntObject*> hlp = lclickable;
  212. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  213. {
  214. if(!vstd::contains(lclickable,*i)) continue;
  215. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  216. {
  217. prev = (*i)->pressedL;
  218. (*i)->pressedL = true;
  219. (*i)->clickLeft(true, prev);
  220. }
  221. }
  222. }
  223. else if (sEvent->button.button == SDL_BUTTON_RIGHT)
  224. {
  225. std::list<CIntObject*> hlp = rclickable;
  226. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  227. {
  228. if(!vstd::contains(rclickable,*i)) continue;
  229. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  230. {
  231. prev = (*i)->pressedR;
  232. (*i)->pressedR = true;
  233. (*i)->clickRight(true, prev);
  234. }
  235. }
  236. }
  237. #ifdef VCMI_SDL1 //SDL1x only events
  238. else if(sEvent->button.button == SDL_BUTTON_WHEELDOWN || sEvent->button.button == SDL_BUTTON_WHEELUP)
  239. {
  240. std::list<CIntObject*> hlp = wheelInterested;
  241. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  242. {
  243. if(!vstd::contains(wheelInterested,*i)) continue;
  244. (*i)->wheelScrolled(sEvent->button.button == SDL_BUTTON_WHEELDOWN, isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y));
  245. }
  246. }
  247. #endif
  248. }
  249. #ifndef VCMI_SDL1 //SDL2x only events
  250. else if ((sEvent->type == SDL_MOUSEWHEEL))
  251. {
  252. std::list<CIntObject*> hlp = wheelInterested;
  253. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  254. {
  255. if(!vstd::contains(wheelInterested,*i)) continue;
  256. (*i)->wheelScrolled(sEvent->wheel.y < 0, isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y));
  257. }
  258. }
  259. else if(sEvent->type == SDL_TEXTINPUT)
  260. {
  261. for(auto it : textInterested)
  262. {
  263. it->textInputed(sEvent->text);
  264. }
  265. }
  266. else if(sEvent->type == SDL_TEXTEDITING)
  267. {
  268. for(auto it : textInterested)
  269. {
  270. it->textEdited(sEvent->edit);
  271. }
  272. }
  273. #endif // VCMI_SDL1
  274. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_LEFT))
  275. {
  276. std::list<CIntObject*> hlp = lclickable;
  277. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  278. {
  279. if(!vstd::contains(lclickable,*i)) continue;
  280. prev = (*i)->pressedL;
  281. (*i)->pressedL = false;
  282. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  283. {
  284. (*i)->clickLeft(false, prev);
  285. }
  286. else
  287. (*i)->clickLeft(boost::logic::indeterminate, prev);
  288. }
  289. }
  290. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_RIGHT))
  291. {
  292. std::list<CIntObject*> hlp = rclickable;
  293. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  294. {
  295. if(!vstd::contains(rclickable,*i)) continue;
  296. prev = (*i)->pressedR;
  297. (*i)->pressedR = false;
  298. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  299. {
  300. (*i)->clickRight(false, prev);
  301. }
  302. else
  303. (*i)->clickRight(boost::logic::indeterminate, prev);
  304. }
  305. }
  306. current = nullptr;
  307. } //event end
  308. void CGuiHandler::handleMouseMotion(SDL_Event *sEvent)
  309. {
  310. //sending active, hovered hoverable objects hover() call
  311. std::vector<CIntObject*> hlp;
  312. for(auto & elem : hoverable)
  313. {
  314. if (isItIn(&(elem)->pos,sEvent->motion.x,sEvent->motion.y))
  315. {
  316. if (!(elem)->hovered)
  317. hlp.push_back((elem));
  318. }
  319. else if ((elem)->hovered)
  320. {
  321. (elem)->hover(false);
  322. (elem)->hovered = false;
  323. }
  324. }
  325. for(auto & elem : hlp)
  326. {
  327. elem->hover(true);
  328. elem->hovered = true;
  329. }
  330. handleMoveInterested(sEvent->motion);
  331. }
  332. void CGuiHandler::simpleRedraw()
  333. {
  334. //update only top interface and draw background
  335. if(objsToBlit.size() > 1)
  336. blitAt(screen2,0,0,screen); //blit background
  337. objsToBlit.back()->show(screen); //blit active interface/window
  338. }
  339. void CGuiHandler::handleMoveInterested( const SDL_MouseMotionEvent & motion )
  340. {
  341. //sending active, MotionInterested objects mouseMoved() call
  342. std::list<CIntObject*> miCopy = motioninterested;
  343. for(auto & elem : miCopy)
  344. {
  345. if ((elem)->strongInterest || isItIn(&(elem)->pos, motion.x, motion.y))
  346. {
  347. (elem)->mouseMoved(motion);
  348. }
  349. }
  350. }
  351. void CGuiHandler::fakeMouseMove()
  352. {
  353. SDL_Event evnt;
  354. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0};
  355. int x, y;
  356. sme.state = SDL_GetMouseState(&x, &y);
  357. sme.x = x;
  358. sme.y = y;
  359. evnt.motion = sme;
  360. current = &evnt;
  361. handleMouseMotion(&evnt);
  362. }
  363. void CGuiHandler::run()
  364. {
  365. setThreadName("CGuiHandler::run");
  366. inGuiThread.reset(new bool(true));
  367. try
  368. {
  369. if(settings["video"]["fullscreen"].Bool())
  370. CCS->curh->centerCursor();
  371. mainFPSmng->init(); // resets internal clock, needed for FPS manager
  372. while(!terminate)
  373. {
  374. if(curInt)
  375. curInt->update(); // calls a update and drawing process of the loaded game interface object at the moment
  376. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  377. SDL_RenderClear(mainRenderer);
  378. SDL_RenderCopy(mainRenderer, screenTexture, NULL, NULL);
  379. SDL_RenderPresent(mainRenderer);
  380. mainFPSmng->framerateDelay(); // holds a constant FPS
  381. }
  382. }
  383. catch(const std::exception & e)
  384. {
  385. logGlobal->errorStream() << "Error: " << e.what();
  386. exit(EXIT_FAILURE);
  387. }
  388. }
  389. CGuiHandler::CGuiHandler()
  390. :lastClick(-500, -500)
  391. {
  392. curInt = nullptr;
  393. current = nullptr;
  394. terminate = false;
  395. statusbar = nullptr;
  396. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  397. mainFPSmng = new CFramerateManager(48);
  398. //do not init CFramerateManager here --AVS
  399. }
  400. CGuiHandler::~CGuiHandler()
  401. {
  402. delete mainFPSmng;
  403. }
  404. void CGuiHandler::breakEventHandling()
  405. {
  406. current = nullptr;
  407. }
  408. void CGuiHandler::drawFPSCounter()
  409. {
  410. const static SDL_Color yellow = {255, 255, 0, 0};
  411. static SDL_Rect overlay = { 0, 0, 64, 32};
  412. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  413. SDL_FillRect(screen, &overlay, black);
  414. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  415. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  416. }
  417. SDLKey CGuiHandler::arrowToNum( SDLKey key )
  418. {
  419. #ifdef VCMI_SDL1
  420. switch(key)
  421. {
  422. case SDLK_DOWN:
  423. return SDLK_KP2;
  424. case SDLK_UP:
  425. return SDLK_KP8;
  426. case SDLK_LEFT:
  427. return SDLK_KP4;
  428. case SDLK_RIGHT:
  429. return SDLK_KP6;
  430. default:
  431. assert(0);
  432. }
  433. #else
  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. assert(0);
  446. }
  447. #endif // 0
  448. throw std::runtime_error("Wrong key!");
  449. }
  450. SDLKey CGuiHandler::numToDigit( SDLKey key )
  451. {
  452. #ifdef VCMI_SDL1
  453. if(key >= SDLK_KP0 && key <= SDLK_KP9)
  454. return SDLKey(key - SDLK_KP0 + SDLK_0);
  455. #else
  456. if(key >= SDLK_KP_0 && key <= SDLK_KP_9)
  457. return SDLKey(key - SDLK_KP_0 + SDLK_0);
  458. #endif // 0
  459. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  460. switch(key)
  461. {
  462. REMOVE_KP(PERIOD)
  463. REMOVE_KP(MINUS)
  464. REMOVE_KP(PLUS)
  465. REMOVE_KP(EQUALS)
  466. case SDLK_KP_MULTIPLY:
  467. return SDLK_ASTERISK;
  468. case SDLK_KP_DIVIDE:
  469. return SDLK_SLASH;
  470. case SDLK_KP_ENTER:
  471. return SDLK_RETURN;
  472. default:
  473. return SDLK_UNKNOWN;
  474. }
  475. #undef REMOVE_KP
  476. }
  477. bool CGuiHandler::isNumKey( SDLKey key, bool number )
  478. {
  479. #ifdef VCMI_SDL1
  480. if(number)
  481. return key >= SDLK_KP0 && key <= SDLK_KP9;
  482. else
  483. return key >= SDLK_KP0 && key <= SDLK_KP_EQUALS;
  484. #else
  485. if(number)
  486. return key >= SDLK_KP_0 && key <= SDLK_KP_9;
  487. else
  488. return key >= SDLK_KP_0 && key <= SDLK_KP_EQUALS;
  489. #endif // 0
  490. }
  491. bool CGuiHandler::isArrowKey( SDLKey key )
  492. {
  493. return key >= SDLK_UP && key <= SDLK_LEFT;
  494. }
  495. bool CGuiHandler::amIGuiThread()
  496. {
  497. return inGuiThread.get() && *inGuiThread;
  498. }
  499. void CGuiHandler::pushSDLEvent(int type, int usercode)
  500. {
  501. SDL_Event event;
  502. event.type = type;
  503. event.user.code = usercode; // not necessarily used
  504. SDL_PushEvent(&event);
  505. }
  506. CFramerateManager::CFramerateManager(int rate)
  507. {
  508. this->rate = rate;
  509. this->rateticks = (1000.0 / rate);
  510. this->fps = 0;
  511. }
  512. void CFramerateManager::init()
  513. {
  514. this->lastticks = SDL_GetTicks();
  515. }
  516. void CFramerateManager::framerateDelay()
  517. {
  518. ui32 currentTicks = SDL_GetTicks();
  519. timeElapsed = currentTicks - lastticks;
  520. // FPS is higher than it should be, then wait some time
  521. if (timeElapsed < rateticks)
  522. {
  523. SDL_Delay(ceil(this->rateticks) - timeElapsed);
  524. }
  525. currentTicks = SDL_GetTicks();
  526. fps = ceil(1000.0 / timeElapsed);
  527. // recalculate timeElapsed for external calls via getElapsed()
  528. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  529. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  530. lastticks = SDL_GetTicks();
  531. }