2
0

CGuiHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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(false);
  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. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  243. int x = 0, y = 0;
  244. SDL_GetMouseState(&x, &y);
  245. (*i)->wheelScrolled(sEvent->wheel.y < 0, isItIn(&(*i)->pos, x, y));
  246. }
  247. }
  248. else if(sEvent->type == SDL_TEXTINPUT)
  249. {
  250. for(auto it : textInterested)
  251. {
  252. it->textInputed(sEvent->text);
  253. }
  254. }
  255. else if(sEvent->type == SDL_TEXTEDITING)
  256. {
  257. for(auto it : textInterested)
  258. {
  259. it->textEdited(sEvent->edit);
  260. }
  261. }
  262. //todo: muiltitouch
  263. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_LEFT))
  264. {
  265. std::list<CIntObject*> hlp = lclickable;
  266. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  267. {
  268. if(!vstd::contains(lclickable,*i)) continue;
  269. prev = (*i)->pressedL;
  270. (*i)->pressedL = false;
  271. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  272. {
  273. (*i)->clickLeft(false, prev);
  274. }
  275. else
  276. (*i)->clickLeft(boost::logic::indeterminate, prev);
  277. }
  278. }
  279. else if ((sEvent->type==SDL_MOUSEBUTTONUP) && (sEvent->button.button == SDL_BUTTON_RIGHT))
  280. {
  281. std::list<CIntObject*> hlp = rclickable;
  282. for(auto i=hlp.begin(); i != hlp.end() && current; i++)
  283. {
  284. if(!vstd::contains(rclickable,*i)) continue;
  285. prev = (*i)->pressedR;
  286. (*i)->pressedR = false;
  287. if (isItIn(&(*i)->pos,sEvent->motion.x,sEvent->motion.y))
  288. {
  289. (*i)->clickRight(false, prev);
  290. }
  291. else
  292. (*i)->clickRight(boost::logic::indeterminate, prev);
  293. }
  294. }
  295. current = nullptr;
  296. } //event end
  297. void CGuiHandler::handleMouseMotion(SDL_Event *sEvent)
  298. {
  299. //sending active, hovered hoverable objects hover() call
  300. std::vector<CIntObject*> hlp;
  301. for(auto & elem : hoverable)
  302. {
  303. if (isItIn(&(elem)->pos,sEvent->motion.x,sEvent->motion.y))
  304. {
  305. if (!(elem)->hovered)
  306. hlp.push_back((elem));
  307. }
  308. else if ((elem)->hovered)
  309. {
  310. (elem)->hover(false);
  311. (elem)->hovered = false;
  312. }
  313. }
  314. for(auto & elem : hlp)
  315. {
  316. elem->hover(true);
  317. elem->hovered = true;
  318. }
  319. handleMoveInterested(sEvent->motion);
  320. }
  321. void CGuiHandler::simpleRedraw()
  322. {
  323. //update only top interface and draw background
  324. if(objsToBlit.size() > 1)
  325. blitAt(screen2,0,0,screen); //blit background
  326. objsToBlit.back()->show(screen); //blit active interface/window
  327. }
  328. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  329. {
  330. //sending active, MotionInterested objects mouseMoved() call
  331. std::list<CIntObject*> miCopy = motioninterested;
  332. for(auto & elem : miCopy)
  333. {
  334. if ((elem)->strongInterest || isItIn(&(elem)->pos, motion.x, motion.y))
  335. {
  336. (elem)->mouseMoved(motion);
  337. }
  338. }
  339. }
  340. void CGuiHandler::fakeMouseMove()
  341. {
  342. SDL_Event evnt;
  343. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  344. int x, y;
  345. sme.state = SDL_GetMouseState(&x, &y);
  346. sme.x = x;
  347. sme.y = y;
  348. evnt.motion = sme;
  349. current = &evnt;
  350. handleMouseMotion(&evnt);
  351. }
  352. void CGuiHandler::renderFrame()
  353. {
  354. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  355. // During game:
  356. // When ending the game, the pim mutex might be hold by other thread,
  357. // that will notify us about the ending game by setting terminate_cond flag.
  358. //in PreGame terminate_cond stay false
  359. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  360. while(!terminate_cond.get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  361. boost::this_thread::sleep(boost::posix_time::milliseconds(15));
  362. if(acquiredTheLockOnPim)
  363. {
  364. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  365. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  366. if(nullptr != curInt)
  367. curInt->update();
  368. if (settings["general"]["showfps"].Bool())
  369. drawFPSCounter();
  370. // draw the mouse cursor and update the screen
  371. CCS->curh->render();
  372. if(0 != SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr))
  373. logGlobal->errorStream() << __FUNCTION__ << " SDL_RenderCopy " << SDL_GetError();
  374. SDL_RenderPresent(mainRenderer);
  375. }
  376. mainFPSmng->framerateDelay(); // holds a constant FPS
  377. }
  378. CGuiHandler::CGuiHandler()
  379. : lastClick(-500, -500),lastClickTime(0), defActionsDef(0), captureChildren(false)
  380. {
  381. curInt = nullptr;
  382. current = nullptr;
  383. statusbar = nullptr;
  384. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  385. mainFPSmng = new CFramerateManager(48);
  386. //do not init CFramerateManager here --AVS
  387. terminate_cond.set(false);
  388. }
  389. CGuiHandler::~CGuiHandler()
  390. {
  391. delete mainFPSmng;
  392. }
  393. void CGuiHandler::breakEventHandling()
  394. {
  395. current = nullptr;
  396. }
  397. void CGuiHandler::drawFPSCounter()
  398. {
  399. const static SDL_Color yellow = {255, 255, 0, 0};
  400. static SDL_Rect overlay = { 0, 0, 64, 32};
  401. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  402. SDL_FillRect(screen, &overlay, black);
  403. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  404. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  405. }
  406. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  407. {
  408. switch(key)
  409. {
  410. case SDLK_DOWN:
  411. return SDLK_KP_2;
  412. case SDLK_UP:
  413. return SDLK_KP_8;
  414. case SDLK_LEFT:
  415. return SDLK_KP_4;
  416. case SDLK_RIGHT:
  417. return SDLK_KP_6;
  418. default:
  419. throw std::runtime_error("Wrong key!");
  420. }
  421. }
  422. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  423. {
  424. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  425. switch(key)
  426. {
  427. REMOVE_KP(0)
  428. REMOVE_KP(1)
  429. REMOVE_KP(2)
  430. REMOVE_KP(3)
  431. REMOVE_KP(4)
  432. REMOVE_KP(5)
  433. REMOVE_KP(6)
  434. REMOVE_KP(7)
  435. REMOVE_KP(8)
  436. REMOVE_KP(9)
  437. REMOVE_KP(PERIOD)
  438. REMOVE_KP(MINUS)
  439. REMOVE_KP(PLUS)
  440. REMOVE_KP(EQUALS)
  441. case SDLK_KP_MULTIPLY:
  442. return SDLK_ASTERISK;
  443. case SDLK_KP_DIVIDE:
  444. return SDLK_SLASH;
  445. case SDLK_KP_ENTER:
  446. return SDLK_RETURN;
  447. default:
  448. return SDLK_UNKNOWN;
  449. }
  450. #undef REMOVE_KP
  451. }
  452. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  453. {
  454. if(number)
  455. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  456. else
  457. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  458. }
  459. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  460. {
  461. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  462. }
  463. bool CGuiHandler::amIGuiThread()
  464. {
  465. return inGuiThread.get() && *inGuiThread;
  466. }
  467. void CGuiHandler::pushSDLEvent(int type, int usercode)
  468. {
  469. SDL_Event event;
  470. event.type = type;
  471. event.user.code = usercode; // not necessarily used
  472. SDL_PushEvent(&event);
  473. }
  474. CFramerateManager::CFramerateManager(int rate)
  475. {
  476. this->rate = rate;
  477. this->rateticks = (1000.0 / rate);
  478. this->fps = 0;
  479. this->accumulatedFrames = 0;
  480. this->accumulatedTime = 0;
  481. this->lastticks = 0;
  482. this->timeElapsed = 0;
  483. }
  484. void CFramerateManager::init()
  485. {
  486. this->lastticks = SDL_GetTicks();
  487. }
  488. void CFramerateManager::framerateDelay()
  489. {
  490. ui32 currentTicks = SDL_GetTicks();
  491. timeElapsed = currentTicks - lastticks;
  492. // FPS is higher than it should be, then wait some time
  493. if (timeElapsed < rateticks)
  494. {
  495. SDL_Delay(ceil(this->rateticks) - timeElapsed);
  496. }
  497. accumulatedTime += timeElapsed;
  498. accumulatedFrames++;
  499. if(accumulatedFrames >= 100)
  500. {
  501. //about 2 second should be passed
  502. fps = ceil(1000.0 / (accumulatedTime/accumulatedFrames));
  503. accumulatedTime = 0;
  504. accumulatedFrames = 0;
  505. };
  506. currentTicks = SDL_GetTicks();
  507. // recalculate timeElapsed for external calls via getElapsed()
  508. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  509. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  510. lastticks = SDL_GetTicks();
  511. }