CIntObjectClasses.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958
  1. #include "StdInc.h"
  2. #include "CIntObjectClasses.h"
  3. #include "../CBitmapHandler.h"
  4. #include "SDL_Pixels.h"
  5. #include "SDL_Extensions.h"
  6. #include "../Graphics.h"
  7. #include "../CAnimation.h"
  8. #include "CCursorHandler.h"
  9. #include "../CGameInfo.h"
  10. #include "../../CCallback.h"
  11. #include "../../lib/CConfigHandler.h"
  12. #include "../battle/CBattleInterface.h"
  13. #include "../battle/CBattleInterfaceClasses.h"
  14. #include "../CPlayerInterface.h"
  15. #include "../CMessage.h"
  16. #include "../CMusicHandler.h"
  17. #include "../GUIClasses.h"
  18. #include "CGuiHandler.h"
  19. #include "../CAdvmapInterface.h"
  20. CPicture::CPicture( SDL_Surface *BG, int x, int y, bool Free )
  21. {
  22. init();
  23. bg = BG;
  24. freeSurf = Free;
  25. pos.x += x;
  26. pos.y += y;
  27. pos.w = BG->w;
  28. pos.h = BG->h;
  29. }
  30. CPicture::CPicture( const std::string &bmpname, int x, int y )
  31. {
  32. init();
  33. bg = BitmapHandler::loadBitmap(bmpname);
  34. freeSurf = true;;
  35. pos.x += x;
  36. pos.y += y;
  37. if(bg)
  38. {
  39. pos.w = bg->w;
  40. pos.h = bg->h;
  41. }
  42. else
  43. {
  44. pos.w = pos.h = 0;
  45. }
  46. }
  47. CPicture::CPicture(const Rect &r, const SDL_Color &color, bool screenFormat /*= false*/)
  48. {
  49. init();
  50. createSimpleRect(r, screenFormat, SDL_MapRGB(bg->format, color.r, color.g,color.b));
  51. }
  52. CPicture::CPicture(const Rect &r, ui32 color, bool screenFormat /*= false*/)
  53. {
  54. init();
  55. createSimpleRect(r, screenFormat, color);
  56. }
  57. CPicture::CPicture(SDL_Surface *BG, const Rect &SrcRect, int x /*= 0*/, int y /*= 0*/, bool free /*= false*/)
  58. {
  59. needRefresh = false;
  60. srcRect = new Rect(SrcRect);
  61. pos.x += x;
  62. pos.y += y;
  63. pos.w = srcRect->w;
  64. pos.h = srcRect->h;
  65. bg = BG;
  66. freeSurf = free;
  67. }
  68. void CPicture::setSurface(SDL_Surface *to)
  69. {
  70. bg = to;
  71. if (srcRect)
  72. {
  73. pos.w = srcRect->w;
  74. pos.h = srcRect->h;
  75. }
  76. else
  77. {
  78. pos.w = bg->w;
  79. pos.h = bg->h;
  80. }
  81. }
  82. CPicture::~CPicture()
  83. {
  84. if(freeSurf)
  85. SDL_FreeSurface(bg);
  86. delete srcRect;
  87. }
  88. void CPicture::init()
  89. {
  90. needRefresh = false;
  91. srcRect = nullptr;
  92. }
  93. void CPicture::show(SDL_Surface * to)
  94. {
  95. if (needRefresh)
  96. showAll(to);
  97. }
  98. void CPicture::showAll(SDL_Surface * to)
  99. {
  100. if(bg)
  101. {
  102. if(srcRect)
  103. {
  104. SDL_Rect srcRectCpy = *srcRect;
  105. SDL_Rect dstRect = srcRectCpy;
  106. dstRect.x = pos.x;
  107. dstRect.y = pos.y;
  108. CSDL_Ext::blitSurface(bg, &srcRectCpy, to, &dstRect);
  109. }
  110. else
  111. blitAt(bg, pos, to);
  112. }
  113. }
  114. void CPicture::convertToScreenBPP()
  115. {
  116. SDL_Surface *hlp = bg;
  117. bg = SDL_ConvertSurface(hlp,screen->format,0);
  118. SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
  119. SDL_FreeSurface(hlp);
  120. }
  121. void CPicture::setAlpha(int value)
  122. {
  123. #if 0
  124. SDL_SetAlpha(bg, SDL_SRCALPHA, value);
  125. #else
  126. SDL_SetSurfaceAlphaMod(bg,value);
  127. #endif // 0
  128. }
  129. void CPicture::scaleTo(Point size)
  130. {
  131. SDL_Surface * scaled = CSDL_Ext::scaleSurface(bg, size.x, size.y);
  132. if(freeSurf)
  133. SDL_FreeSurface(bg);
  134. setSurface(scaled);
  135. freeSurf = false;
  136. }
  137. void CPicture::createSimpleRect(const Rect &r, bool screenFormat, ui32 color)
  138. {
  139. pos += r;
  140. pos.w = r.w;
  141. pos.h = r.h;
  142. if(screenFormat)
  143. bg = CSDL_Ext::newSurface(r.w, r.h);
  144. else
  145. bg = SDL_CreateRGBSurface(SDL_SWSURFACE, r.w, r.h, 8, 0, 0, 0, 0);
  146. SDL_FillRect(bg, nullptr, color);
  147. freeSurf = true;
  148. }
  149. void CPicture::colorizeAndConvert(PlayerColor player)
  150. {
  151. assert(bg);
  152. colorize(player);
  153. convertToScreenBPP();
  154. }
  155. void CPicture::colorize(PlayerColor player)
  156. {
  157. assert(bg);
  158. graphics->blueToPlayersAdv(bg, player);
  159. }
  160. CFilledTexture::CFilledTexture(std::string imageName, Rect position):
  161. CIntObject(0, position.topLeft()),
  162. texture(BitmapHandler::loadBitmap(imageName))
  163. {
  164. pos.w = position.w;
  165. pos.h = position.h;
  166. }
  167. CFilledTexture::~CFilledTexture()
  168. {
  169. SDL_FreeSurface(texture);
  170. }
  171. void CFilledTexture::showAll(SDL_Surface *to)
  172. {
  173. CSDL_Ext::CClipRectGuard guard(to, pos);
  174. CSDL_Ext::fillTexture(to, texture);
  175. }
  176. CButtonBase::CButtonBase()
  177. {
  178. swappedImages = keepFrame = false;
  179. bitmapOffset = 0;
  180. state=NORMAL;
  181. image = nullptr;
  182. text = nullptr;
  183. }
  184. CButtonBase::~CButtonBase()
  185. {
  186. }
  187. void CButtonBase::update()
  188. {
  189. if (text)
  190. {
  191. if (state == PRESSED)
  192. text->moveTo(Point(pos.x+pos.w/2+1, pos.y+pos.h/2+1));
  193. else
  194. text->moveTo(Point(pos.x+pos.w/2, pos.y+pos.h/2));
  195. }
  196. int newPos = (int)state + bitmapOffset;
  197. if (newPos < 0)
  198. newPos = 0;
  199. if (state == HIGHLIGHTED && image->size() < 4)
  200. newPos = image->size()-1;
  201. if (swappedImages)
  202. {
  203. if (newPos == 0) newPos = 1;
  204. else if (newPos == 1) newPos = 0;
  205. }
  206. if (!keepFrame)
  207. image->setFrame(newPos);
  208. if (active)
  209. redraw();
  210. }
  211. void CButtonBase::addTextOverlay( const std::string &Text, EFonts font, SDL_Color color)
  212. {
  213. OBJ_CONSTRUCTION_CAPTURING_ALL;
  214. delete text;
  215. text = new CLabel(pos.w/2, pos.h/2, font, CENTER, color, Text);
  216. update();
  217. }
  218. void CButtonBase::setOffset(int newOffset)
  219. {
  220. if (bitmapOffset == newOffset)
  221. return;
  222. bitmapOffset = newOffset;
  223. update();
  224. }
  225. void CButtonBase::setState(ButtonState newState)
  226. {
  227. if (state == newState)
  228. return;
  229. state = newState;
  230. update();
  231. }
  232. CButtonBase::ButtonState CButtonBase::getState()
  233. {
  234. return state;
  235. }
  236. bool CButtonBase::isBlocked()
  237. {
  238. return state == BLOCKED;
  239. }
  240. bool CButtonBase::isHighlighted()
  241. {
  242. return state == HIGHLIGHTED;
  243. }
  244. void CButtonBase::block(bool on)
  245. {
  246. setState(on?BLOCKED:NORMAL);
  247. }
  248. CAdventureMapButton::CAdventureMapButton ()
  249. {
  250. hoverable = actOnDown = borderEnabled = soundDisabled = false;
  251. #if 0
  252. borderColor.unused = 1; // represents a transparent color, used for HighlightableButton
  253. #else
  254. borderColor.a = 1; // represents a transparent color, used for HighlightableButton
  255. #endif // 0
  256. addUsedEvents(LCLICK | RCLICK | HOVER | KEYBOARD);
  257. }
  258. CAdventureMapButton::CAdventureMapButton( const std::string &Name, const std::string &HelpBox, const CFunctionList<void()> &Callback, int x, int y, const std::string &defName,int key, std::vector<std::string> * add, bool playerColoredButton )
  259. {
  260. std::map<int,std::string> pom;
  261. pom[0] = Name;
  262. init(Callback, pom, HelpBox, playerColoredButton, defName, add, x, y, key);
  263. }
  264. CAdventureMapButton::CAdventureMapButton( const std::string &Name, const std::string &HelpBox, const CFunctionList<void()> &Callback, config::ButtonInfo *info, int key/*=0*/ )
  265. {
  266. std::map<int,std::string> pom;
  267. pom[0] = Name;
  268. init(Callback, pom, HelpBox, info->playerColoured, info->defName, &info->additionalDefs, info->x, info->y, key);
  269. }
  270. CAdventureMapButton::CAdventureMapButton( const std::pair<std::string, std::string> &help, const CFunctionList<void()> &Callback, int x, int y, const std::string &defName, int key/*=0*/, std::vector<std::string> * add /*= nullptr*/, bool playerColoredButton /*= false */ )
  271. {
  272. std::map<int,std::string> pom;
  273. pom[0] = help.first;
  274. init(Callback, pom, help.second, playerColoredButton, defName, add, x, y, key);
  275. }
  276. void CAdventureMapButton::onButtonClicked()
  277. {
  278. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  279. logAnim->traceStream() << "Button clicked at " << pos.x << "x" << pos.y;
  280. CIntObject * parent = this->parent;
  281. std::string prefix = "Parent is";
  282. while (parent)
  283. {
  284. logAnim->traceStream() << prefix << typeid(*parent).name() << " at " << parent->pos.x << "x" << parent->pos.y;
  285. parent = parent->parent;
  286. prefix = '\t' + prefix;
  287. }
  288. callback();
  289. }
  290. void CAdventureMapButton::clickLeft(tribool down, bool previousState)
  291. {
  292. if(isBlocked())
  293. return;
  294. if (down)
  295. {
  296. if (!soundDisabled)
  297. CCS->soundh->playSound(soundBase::button);
  298. setState(PRESSED);
  299. }
  300. else if(hoverable && hovered)
  301. setState(HIGHLIGHTED);
  302. else
  303. setState(NORMAL);
  304. if (actOnDown && down)
  305. {
  306. onButtonClicked();
  307. }
  308. else if (!actOnDown && previousState && (down==false))
  309. {
  310. onButtonClicked();
  311. }
  312. }
  313. void CAdventureMapButton::clickRight(tribool down, bool previousState)
  314. {
  315. if(down && helpBox.size()) //there is no point to show window with nothing inside...
  316. CRClickPopup::createAndPush(helpBox);
  317. }
  318. void CAdventureMapButton::hover (bool on)
  319. {
  320. if(hoverable)
  321. {
  322. if(on)
  323. setState(HIGHLIGHTED);
  324. else
  325. setState(NORMAL);
  326. }
  327. if(pressedL && on)
  328. setState(PRESSED);
  329. std::string *name = (vstd::contains(hoverTexts,getState()))
  330. ? (&hoverTexts[getState()])
  331. : (vstd::contains(hoverTexts,0) ? (&hoverTexts[0]) : nullptr);
  332. if(name && name->size() && !isBlocked()) //if there is no name, there is nohing to display also
  333. {
  334. if (LOCPLINT && LOCPLINT->battleInt) //for battle buttons
  335. {
  336. if(on && LOCPLINT->battleInt->console->alterTxt == "")
  337. {
  338. LOCPLINT->battleInt->console->alterTxt = *name;
  339. LOCPLINT->battleInt->console->whoSetAlter = 1;
  340. }
  341. else if (LOCPLINT->battleInt->console->alterTxt == *name)
  342. {
  343. LOCPLINT->battleInt->console->alterTxt = "";
  344. LOCPLINT->battleInt->console->whoSetAlter = 0;
  345. }
  346. }
  347. else if(GH.statusbar) //for other buttons
  348. {
  349. if (on)
  350. GH.statusbar->setText(*name);
  351. else if ( GH.statusbar->getText()==(*name) )
  352. GH.statusbar->clear();
  353. }
  354. }
  355. }
  356. void CAdventureMapButton::init(const CFunctionList<void()> &Callback, const std::map<int,std::string> &Name, const std::string &HelpBox, bool playerColoredButton, const std::string &defName, std::vector<std::string> * add, int x, int y, int key)
  357. {
  358. currentImage = -1;
  359. addUsedEvents(LCLICK | RCLICK | HOVER | KEYBOARD);
  360. callback = Callback;
  361. hoverable = actOnDown = borderEnabled = soundDisabled = false;
  362. #if 0
  363. borderColor.unused = 1; // represents a transparent color, used for HighlightableButton
  364. #else
  365. borderColor.a = 1; // represents a transparent color, used for HighlightableButton
  366. #endif // 0
  367. hoverTexts = Name;
  368. helpBox=HelpBox;
  369. if (key != SDLK_UNKNOWN)
  370. assignedKeys.insert(key);
  371. pos.x += x;
  372. pos.y += y;
  373. if (!defName.empty())
  374. imageNames.push_back(defName);
  375. if (add)
  376. for (auto & elem : *add)
  377. imageNames.push_back(elem);
  378. setIndex(0, playerColoredButton);
  379. }
  380. void CAdventureMapButton::setIndex(size_t index, bool playerColoredButton)
  381. {
  382. if (index == currentImage || index>=imageNames.size())
  383. return;
  384. currentImage = index;
  385. setImage(new CAnimation(imageNames[index]), playerColoredButton);
  386. }
  387. void CAdventureMapButton::setImage(CAnimation* anim, bool playerColoredButton, int animFlags)
  388. {
  389. OBJ_CONSTRUCTION_CAPTURING_ALL;
  390. delete image;
  391. image = new CAnimImage(anim, getState(), 0, 0, 0, animFlags);
  392. if (playerColoredButton)
  393. image->playerColored(LOCPLINT->playerID);
  394. pos.w = image->pos.w;
  395. pos.h = image->pos.h;
  396. }
  397. void CAdventureMapButton::setPlayerColor(PlayerColor player)
  398. {
  399. if (image)
  400. image->playerColored(player);
  401. }
  402. void CAdventureMapButton::showAll(SDL_Surface * to)
  403. {
  404. CIntObject::showAll(to);
  405. #if 0
  406. if (borderEnabled && borderColor.unused == 0)
  407. CSDL_Ext::drawBorder(to, pos.x-1, pos.y-1, pos.w+2, pos.h+2, int3(borderColor.r, borderColor.g, borderColor.b));
  408. #else
  409. if (borderEnabled && borderColor.a == 0)
  410. CSDL_Ext::drawBorder(to, pos.x-1, pos.y-1, pos.w+2, pos.h+2, int3(borderColor.r, borderColor.g, borderColor.b));
  411. #endif // 0
  412. }
  413. void CHighlightableButton::select(bool on)
  414. {
  415. selected = on;
  416. if (on)
  417. {
  418. borderEnabled = true;
  419. setState(HIGHLIGHTED);
  420. callback();
  421. }
  422. else
  423. {
  424. borderEnabled = false;
  425. setState(NORMAL);
  426. callback2();
  427. }
  428. if(hoverTexts.size()>1)
  429. {
  430. hover(false);
  431. hover(true);
  432. }
  433. }
  434. void CHighlightableButton::clickLeft(tribool down, bool previousState)
  435. {
  436. if(isBlocked())
  437. return;
  438. if (down && !(onlyOn && isHighlighted()))
  439. {
  440. CCS->soundh->playSound(soundBase::button);
  441. setState(PRESSED);
  442. }
  443. if(previousState)//mouse up
  444. {
  445. if(down == false && getState() == PRESSED)
  446. select(!selected);
  447. else
  448. setState(selected?HIGHLIGHTED:NORMAL);
  449. }
  450. }
  451. CHighlightableButton::CHighlightableButton( const CFunctionList<void()> &onSelect, const CFunctionList<void()> &onDeselect, const std::map<int,std::string> &Name, const std::string &HelpBox, bool playerColoredButton, const std::string &defName, std::vector<std::string> * add, int x, int y, int key)
  452. : onlyOn(false), selected(false), callback2(onDeselect)
  453. {
  454. init(onSelect,Name,HelpBox,playerColoredButton,defName,add,x,y,key);
  455. }
  456. CHighlightableButton::CHighlightableButton( const std::pair<std::string, std::string> &help, const CFunctionList<void()> &onSelect, int x, int y, const std::string &defName, int myid, int key/*=0*/, std::vector<std::string> * add /*= nullptr*/, bool playerColoredButton /*= false */ )
  457. : onlyOn(false), selected(false) // TODO: callback2(???)
  458. {
  459. ID = myid;
  460. std::map<int,std::string> pom;
  461. pom[0] = help.first;
  462. init(onSelect, pom, help.second, playerColoredButton, defName, add, x, y, key);
  463. }
  464. CHighlightableButton::CHighlightableButton( const std::string &Name, const std::string &HelpBox, const CFunctionList<void()> &onSelect, int x, int y, const std::string &defName, int myid, int key/*=0*/, std::vector<std::string> * add /*= nullptr*/, bool playerColoredButton /*= false */ )
  465. : onlyOn(false), selected(false) // TODO: callback2(???)
  466. {
  467. ID = myid;
  468. std::map<int,std::string> pom;
  469. pom[0] = Name;
  470. init(onSelect, pom,HelpBox, playerColoredButton, defName, add, x, y, key);
  471. }
  472. void CHighlightableButtonsGroup::addButton(CHighlightableButton* bt)
  473. {
  474. if (bt->parent)
  475. bt->parent->removeChild(bt);
  476. addChild(bt);
  477. bt->recActions = defActions;//FIXME: not needed?
  478. bt->callback += boost::bind(&CHighlightableButtonsGroup::selectionChanged,this,bt->ID);
  479. bt->onlyOn = true;
  480. buttons.push_back(bt);
  481. }
  482. void CHighlightableButtonsGroup::addButton(const std::map<int,std::string> &tooltip, const std::string &HelpBox, const std::string &defName, int x, int y, int uid, const CFunctionList<void()> &OnSelect, int key)
  483. {
  484. OBJ_CONSTRUCTION_CAPTURING_ALL;
  485. CHighlightableButton *bt = new CHighlightableButton(OnSelect, 0, tooltip, HelpBox, false, defName, nullptr, x, y, key);
  486. if(musicLike)
  487. {
  488. bt->setOffset(buttons.size()-3);
  489. }
  490. bt->ID = uid;
  491. bt->callback += boost::bind(&CHighlightableButtonsGroup::selectionChanged,this,bt->ID);
  492. bt->onlyOn = true;
  493. buttons.push_back(bt);
  494. }
  495. CHighlightableButtonsGroup::CHighlightableButtonsGroup(const CFunctionList<void(int)> &OnChange, bool musicLikeButtons)
  496. : onChange(OnChange), musicLike(musicLikeButtons)
  497. {}
  498. CHighlightableButtonsGroup::~CHighlightableButtonsGroup()
  499. {
  500. }
  501. void CHighlightableButtonsGroup::select(int id, bool mode)
  502. {
  503. assert(!buttons.empty());
  504. CHighlightableButton *bt = buttons.front();
  505. if(mode)
  506. {
  507. for(auto btn : buttons)
  508. if (btn->ID == id)
  509. bt = btn;
  510. }
  511. else
  512. {
  513. bt = buttons[id];
  514. }
  515. bt->select(true);
  516. selectionChanged(bt->ID);
  517. }
  518. void CHighlightableButtonsGroup::selectionChanged(int to)
  519. {
  520. for(auto & elem : buttons)
  521. if(elem->ID!=to && elem->isHighlighted())
  522. elem->select(false);
  523. onChange(to);
  524. if (parent)
  525. parent->redraw();
  526. }
  527. void CHighlightableButtonsGroup::show(SDL_Surface * to)
  528. {
  529. if (musicLike)
  530. {
  531. for(auto & elem : buttons)
  532. if(elem->isHighlighted())
  533. elem->show(to);
  534. }
  535. else
  536. CIntObject::show(to);
  537. }
  538. void CHighlightableButtonsGroup::showAll(SDL_Surface * to)
  539. {
  540. if (musicLike)
  541. {
  542. for(auto & elem : buttons)
  543. if(elem->isHighlighted())
  544. elem->showAll(to);
  545. }
  546. else
  547. CIntObject::showAll(to);
  548. }
  549. void CHighlightableButtonsGroup::block( ui8 on )
  550. {
  551. for(auto & elem : buttons)
  552. {
  553. elem->block(on);
  554. }
  555. }
  556. void CSlider::sliderClicked()
  557. {
  558. if(!(active & MOVE))
  559. addUsedEvents(MOVE);
  560. }
  561. void CSlider::mouseMoved (const SDL_MouseMotionEvent & sEvent)
  562. {
  563. double v = 0;
  564. if(horizontal)
  565. {
  566. if( std::abs(sEvent.y-(pos.y+pos.h/2)) > pos.h/2+40 || std::abs(sEvent.x-(pos.x+pos.w/2)) > pos.w/2 )
  567. return;
  568. v = sEvent.x - pos.x - 24;
  569. v *= positions;
  570. v /= (pos.w - 48);
  571. }
  572. else
  573. {
  574. if(std::abs(sEvent.x-(pos.x+pos.w/2)) > pos.w/2+40 || std::abs(sEvent.y-(pos.y+pos.h/2)) > pos.h/2 )
  575. return;
  576. v = sEvent.y - pos.y - 24;
  577. v *= positions;
  578. v /= (pos.h - 48);
  579. }
  580. v += 0.5;
  581. if(v!=value)
  582. {
  583. moveTo(v);
  584. redrawSlider();
  585. }
  586. }
  587. void CSlider::redrawSlider()
  588. {
  589. //slider->show(screenBuf);
  590. }
  591. void CSlider::moveLeft()
  592. {
  593. moveTo(value-1);
  594. }
  595. void CSlider::moveRight()
  596. {
  597. moveTo(value+1);
  598. }
  599. void CSlider::moveTo(int to)
  600. {
  601. vstd::amax(to, 0);
  602. vstd::amin(to, positions);
  603. //same, old position?
  604. if(value == to)
  605. return;
  606. value = to;
  607. if(horizontal)
  608. {
  609. if(positions)
  610. {
  611. double part = static_cast<double>(to) / positions;
  612. part*=(pos.w-48);
  613. int newPos = part + pos.x + 16 - slider->pos.x;
  614. slider->moveBy(Point(newPos, 0));
  615. }
  616. else
  617. slider->moveTo(Point(pos.x+16, pos.y));
  618. }
  619. else
  620. {
  621. if(positions)
  622. {
  623. double part = static_cast<double>(to) / positions;
  624. part*=(pos.h-48);
  625. int newPos = part + pos.y + 16 - slider->pos.y;
  626. slider->moveBy(Point(0, newPos));
  627. }
  628. else
  629. slider->moveTo(Point(pos.x, pos.y+16));
  630. }
  631. if(moved)
  632. moved(to);
  633. }
  634. void CSlider::clickLeft(tribool down, bool previousState)
  635. {
  636. if(down && !slider->isBlocked())
  637. {
  638. double pw = 0;
  639. double rw = 0;
  640. if(horizontal)
  641. {
  642. pw = GH.current->motion.x-pos.x-25;
  643. rw = pw / static_cast<double>(pos.w - 48);
  644. }
  645. else
  646. {
  647. pw = GH.current->motion.y-pos.y-24;
  648. rw = pw / (pos.h-48);
  649. }
  650. if(pw < -8 || pw > (horizontal ? pos.w : pos.h) - 40)
  651. return;
  652. // if (rw>1) return;
  653. // if (rw<0) return;
  654. slider->clickLeft(true, slider->pressedL);
  655. moveTo(rw * positions + 0.5);
  656. return;
  657. }
  658. if(active & MOVE)
  659. removeUsedEvents(MOVE);
  660. }
  661. CSlider::~CSlider()
  662. {
  663. }
  664. CSlider::CSlider(int x, int y, int totalw, std::function<void(int)> Moved, int Capacity, int Amount, int Value, bool Horizontal, int style):
  665. capacity(Capacity),
  666. amount(Amount),
  667. scrollStep(1),
  668. horizontal(Horizontal),
  669. moved(Moved)
  670. {
  671. OBJ_CONSTRUCTION_CAPTURING_ALL;
  672. setAmount(amount);
  673. addUsedEvents(LCLICK | KEYBOARD | WHEEL);
  674. strongInterest = true;
  675. left = new CAdventureMapButton();
  676. right = new CAdventureMapButton();
  677. slider = new CAdventureMapButton();
  678. pos.x += x;
  679. pos.y += y;
  680. if(horizontal)
  681. {
  682. left->pos.y = slider->pos.y = right->pos.y = pos.y;
  683. left->pos.x = pos.x;
  684. right->pos.x = pos.x + totalw - 16;
  685. }
  686. else
  687. {
  688. left->pos.x = slider->pos.x = right->pos.x = pos.x;
  689. left->pos.y = pos.y;
  690. right->pos.y = pos.y + totalw - 16;
  691. }
  692. left->callback = boost::bind(&CSlider::moveLeft,this);
  693. right->callback = boost::bind(&CSlider::moveRight,this);
  694. slider->callback = boost::bind(&CSlider::sliderClicked,this);
  695. left->pos.w = left->pos.h = right->pos.w = right->pos.h = slider->pos.w = slider->pos.h = 16;
  696. if(horizontal)
  697. {
  698. pos.h = 16;
  699. pos.w = totalw;
  700. }
  701. else
  702. {
  703. pos.w = 16;
  704. pos.h = totalw;
  705. }
  706. if(style == 0)
  707. {
  708. std::string name = horizontal?"IGPCRDIV.DEF":"OVBUTN2.DEF";
  709. //NOTE: this images do not have "blocked" frames. They should be implemented somehow (e.g. palette transform or something...)
  710. //use source def to create custom animations. Format "name.def:123" will load this frame from def file
  711. auto animLeft = new CAnimation();
  712. animLeft->setCustom(name + ":0", 0);
  713. animLeft->setCustom(name + ":1", 1);
  714. left->setImage(animLeft);
  715. auto animRight = new CAnimation();
  716. animRight->setCustom(name + ":2", 0);
  717. animRight->setCustom(name + ":3", 1);
  718. right->setImage(animRight);
  719. auto animSlider = new CAnimation();
  720. animSlider->setCustom(name + ":4", 0);
  721. slider->setImage(animSlider);
  722. }
  723. else
  724. {
  725. left->setImage(new CAnimation(horizontal ? "SCNRBLF.DEF" : "SCNRBUP.DEF"));
  726. right->setImage(new CAnimation(horizontal ? "SCNRBRT.DEF" : "SCNRBDN.DEF"));
  727. slider->setImage(new CAnimation("SCNRBSL.DEF"));
  728. }
  729. slider->actOnDown = true;
  730. slider->soundDisabled = true;
  731. left->soundDisabled = true;
  732. right->soundDisabled = true;
  733. value = -1;
  734. moveTo(Value);
  735. }
  736. void CSlider::block( bool on )
  737. {
  738. left->block(on);
  739. right->block(on);
  740. slider->block(on);
  741. }
  742. void CSlider::setAmount( int to )
  743. {
  744. amount = to;
  745. positions = to - capacity;
  746. vstd::amax(positions, 0);
  747. }
  748. void CSlider::showAll(SDL_Surface * to)
  749. {
  750. CSDL_Ext::fillRect(to, &pos, 0);
  751. CIntObject::showAll(to);
  752. }
  753. void CSlider::wheelScrolled(bool down, bool in)
  754. {
  755. moveTo(value + 3 * (down ? +scrollStep : -scrollStep));
  756. }
  757. void CSlider::keyPressed(const SDL_KeyboardEvent & key)
  758. {
  759. if(key.state != SDL_PRESSED) return;
  760. int moveDest = 0;
  761. switch(key.keysym.sym)
  762. {
  763. case SDLK_UP:
  764. case SDLK_LEFT:
  765. moveDest = value - scrollStep;
  766. break;
  767. case SDLK_DOWN:
  768. case SDLK_RIGHT:
  769. moveDest = value + scrollStep;
  770. break;
  771. case SDLK_PAGEUP:
  772. moveDest = value - capacity + scrollStep;
  773. break;
  774. case SDLK_PAGEDOWN:
  775. moveDest = value + capacity - scrollStep;
  776. break;
  777. case SDLK_HOME:
  778. moveDest = 0;
  779. break;
  780. case SDLK_END:
  781. moveDest = amount - capacity;
  782. break;
  783. default:
  784. return;
  785. }
  786. moveTo(moveDest);
  787. }
  788. void CSlider::moveToMax()
  789. {
  790. moveTo(amount);
  791. }
  792. static void intDeleter(CIntObject* object)
  793. {
  794. delete object;
  795. }
  796. CObjectList::CObjectList(CreateFunc create, DestroyFunc destroy):
  797. createObject(create),
  798. destroyObject(destroy)
  799. {
  800. if (!destroyObject)
  801. destroyObject = intDeleter;
  802. }
  803. void CObjectList::deleteItem(CIntObject* item)
  804. {
  805. if (!item)
  806. return;
  807. removeChild(item);
  808. destroyObject(item);
  809. }
  810. CIntObject* CObjectList::createItem(size_t index)
  811. {
  812. OBJ_CONSTRUCTION_CAPTURING_ALL;
  813. CIntObject * item = createObject(index);
  814. if (item == nullptr)
  815. item = new CIntObject();
  816. item->recActions = defActions;
  817. addChild(item);
  818. return item;
  819. }
  820. CTabbedInt::CTabbedInt(CreateFunc create, DestroyFunc destroy, Point position, size_t ActiveID):
  821. CObjectList(create, destroy),
  822. activeTab(nullptr),
  823. activeID(ActiveID)
  824. {
  825. pos += position;
  826. reset();
  827. }
  828. void CTabbedInt::setActive(size_t which)
  829. {
  830. if (which != activeID)
  831. {
  832. activeID = which;
  833. reset();
  834. }
  835. }
  836. void CTabbedInt::reset()
  837. {
  838. deleteItem(activeTab);
  839. activeTab = createItem(activeID);
  840. activeTab->moveTo(pos.topLeft());
  841. if (active)
  842. redraw();
  843. }
  844. CIntObject * CTabbedInt::getItem()
  845. {
  846. return activeTab;
  847. }
  848. CListBox::CListBox(CreateFunc create, DestroyFunc destroy, Point Pos, Point ItemOffset, size_t VisibleSize,
  849. size_t TotalSize, size_t InitialPos, int Slider, Rect SliderPos):
  850. CObjectList(create, destroy),
  851. first(InitialPos),
  852. totalSize(TotalSize),
  853. itemOffset(ItemOffset),
  854. slider(nullptr)
  855. {
  856. pos += Pos;
  857. items.resize(VisibleSize, nullptr);
  858. if (Slider & 1)
  859. {
  860. OBJ_CONSTRUCTION_CAPTURING_ALL;
  861. slider = new CSlider(SliderPos.x, SliderPos.y, SliderPos.w, boost::bind(&CListBox::moveToPos, this, _1),
  862. VisibleSize, TotalSize, InitialPos, Slider & 2, Slider & 4);
  863. }
  864. reset();
  865. }
  866. // Used to move active items after changing list position
  867. void CListBox::updatePositions()
  868. {
  869. Point itemPos = pos.topLeft();
  870. for (auto & elem : items)
  871. {
  872. (elem)->moveTo(itemPos);
  873. itemPos += itemOffset;
  874. }
  875. if (active)
  876. {
  877. redraw();
  878. if (slider)
  879. slider->moveTo(first);
  880. }
  881. }
  882. void CListBox::reset()
  883. {
  884. size_t current = first;
  885. for (auto & elem : items)
  886. {
  887. deleteItem(elem);
  888. elem = createItem(current++);
  889. }
  890. updatePositions();
  891. }
  892. void CListBox::resize(size_t newSize)
  893. {
  894. totalSize = newSize;
  895. if (slider)
  896. slider->setAmount(totalSize);
  897. reset();
  898. }
  899. size_t CListBox::size()
  900. {
  901. return totalSize;
  902. }
  903. CIntObject * CListBox::getItem(size_t which)
  904. {
  905. if (which < first || which > first + items.size() || which > totalSize)
  906. return nullptr;
  907. size_t i=first;
  908. for (auto iter = items.begin(); iter != items.end(); iter++, i++)
  909. if( i == which)
  910. return *iter;
  911. return nullptr;
  912. }
  913. size_t CListBox::getIndexOf(CIntObject *item)
  914. {
  915. size_t i=first;
  916. for (auto iter = items.begin(); iter != items.end(); iter++, i++)
  917. if(*iter == item)
  918. return i;
  919. return size_t(-1);
  920. }
  921. void CListBox::scrollTo(size_t which)
  922. {
  923. //scroll up
  924. if (first > which)
  925. moveToPos(which);
  926. //scroll down
  927. else if (first + items.size() <= which && which < totalSize)
  928. moveToPos(which - items.size() + 1);
  929. }
  930. void CListBox::moveToPos(size_t which)
  931. {
  932. //Calculate new position
  933. size_t maxPossible;
  934. if (totalSize > items.size())
  935. maxPossible = totalSize - items.size();
  936. else
  937. maxPossible = 0;
  938. size_t newPos = std::min(which, maxPossible);
  939. //If move distance is 1 (most of calls from Slider) - use faster shifts instead of resetting all items
  940. if (first - newPos == 1)
  941. moveToPrev();
  942. else if (newPos - first == 1)
  943. moveToNext();
  944. else if (newPos != first)
  945. {
  946. first = newPos;
  947. reset();
  948. }
  949. }
  950. void CListBox::moveToNext()
  951. {
  952. //Remove front item and insert new one to end
  953. if (first + items.size() < totalSize)
  954. {
  955. first++;
  956. deleteItem(items.front());
  957. items.pop_front();
  958. items.push_back(createItem(first+items.size()));
  959. updatePositions();
  960. }
  961. }
  962. void CListBox::moveToPrev()
  963. {
  964. //Remove last item and insert new one at start
  965. if (first)
  966. {
  967. first--;
  968. deleteItem(items.back());
  969. items.pop_back();
  970. items.push_front(createItem(first));
  971. updatePositions();
  972. }
  973. }
  974. size_t CListBox::getPos()
  975. {
  976. return first;
  977. }
  978. const std::list<CIntObject *> &CListBox::getItems()
  979. {
  980. return items;
  981. }
  982. void CSimpleWindow::show(SDL_Surface * to)
  983. {
  984. if(bitmap)
  985. blitAt(bitmap,pos.x,pos.y,to);
  986. }
  987. CSimpleWindow::~CSimpleWindow()
  988. {
  989. if (bitmap)
  990. {
  991. SDL_FreeSurface(bitmap);
  992. bitmap=nullptr;
  993. }
  994. }
  995. void CHoverableArea::hover (bool on)
  996. {
  997. if (on)
  998. GH.statusbar->setText(hoverText);
  999. else if (GH.statusbar->getText()==hoverText)
  1000. GH.statusbar->clear();
  1001. }
  1002. CHoverableArea::CHoverableArea()
  1003. {
  1004. addUsedEvents(HOVER);
  1005. }
  1006. CHoverableArea::~CHoverableArea()
  1007. {
  1008. }
  1009. void LRClickableAreaWText::clickLeft(tribool down, bool previousState)
  1010. {
  1011. if(!down && previousState)
  1012. {
  1013. LOCPLINT->showInfoDialog(text);
  1014. }
  1015. }
  1016. void LRClickableAreaWText::clickRight(tribool down, bool previousState)
  1017. {
  1018. adventureInt->handleRightClick(text, down);
  1019. }
  1020. LRClickableAreaWText::LRClickableAreaWText()
  1021. {
  1022. init();
  1023. }
  1024. LRClickableAreaWText::LRClickableAreaWText(const Rect &Pos, const std::string &HoverText /*= ""*/, const std::string &ClickText /*= ""*/)
  1025. {
  1026. init();
  1027. pos = Pos + pos;
  1028. hoverText = HoverText;
  1029. text = ClickText;
  1030. }
  1031. LRClickableAreaWText::~LRClickableAreaWText()
  1032. {
  1033. }
  1034. void LRClickableAreaWText::init()
  1035. {
  1036. addUsedEvents(LCLICK | RCLICK | HOVER);
  1037. }
  1038. std::string CLabel::visibleText()
  1039. {
  1040. return text;
  1041. }
  1042. void CLabel::showAll(SDL_Surface * to)
  1043. {
  1044. CIntObject::showAll(to);
  1045. if(!visibleText().empty())
  1046. blitLine(to, pos, visibleText());
  1047. }
  1048. CLabel::CLabel(int x, int y, EFonts Font /*= FONT_SMALL*/, EAlignment Align, const SDL_Color &Color /*= Colors::WHITE*/, const std::string &Text /*= ""*/)
  1049. :CTextContainer(Align, Font, Color), text(Text)
  1050. {
  1051. type |= REDRAW_PARENT;
  1052. autoRedraw = true;
  1053. pos.x += x;
  1054. pos.y += y;
  1055. pos.w = pos.h = 0;
  1056. bg = nullptr;
  1057. if (alignment == TOPLEFT) // causes issues for MIDDLE
  1058. {
  1059. pos.w = graphics->fonts[font]->getStringWidth(visibleText().c_str());
  1060. pos.h = graphics->fonts[font]->getLineHeight();
  1061. }
  1062. }
  1063. Point CLabel::getBorderSize()
  1064. {
  1065. return Point(0, 0);
  1066. }
  1067. std::string CLabel::getText()
  1068. {
  1069. return text;
  1070. }
  1071. void CLabel::setText(const std::string &Txt)
  1072. {
  1073. text = Txt;
  1074. if(autoRedraw)
  1075. {
  1076. if(bg || !parent)
  1077. redraw();
  1078. else
  1079. parent->redraw();
  1080. }
  1081. }
  1082. CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, EAlignment Align, const SDL_Color &Color, const std::string &Text):
  1083. CLabel(position.x, position.y, Font, Align, Color, Text),
  1084. visibleSize(0, 0, position.w, position.h)
  1085. {
  1086. pos.w = position.w;
  1087. pos.h = position.h;
  1088. splitText(Text);
  1089. }
  1090. void CMultiLineLabel::setVisibleSize(Rect visibleSize)
  1091. {
  1092. this->visibleSize = visibleSize;
  1093. redraw();
  1094. }
  1095. void CMultiLineLabel::scrollTextBy(int distance)
  1096. {
  1097. scrollTextTo(visibleSize.y + distance);
  1098. }
  1099. void CMultiLineLabel::scrollTextTo(int distance)
  1100. {
  1101. Rect size = visibleSize;
  1102. size.y = distance;
  1103. setVisibleSize(size);
  1104. }
  1105. void CMultiLineLabel::setText(const std::string &Txt)
  1106. {
  1107. splitText(Txt);
  1108. CLabel::setText(Txt);
  1109. }
  1110. void CTextContainer::blitLine(SDL_Surface *to, Rect destRect, std::string what)
  1111. {
  1112. const IFont * f = graphics->fonts[font];
  1113. Point where = destRect.topLeft();
  1114. // input is rect in which given text should be placed
  1115. // calculate proper position for top-left corner of the text
  1116. if (alignment == TOPLEFT)
  1117. {
  1118. where.x += getBorderSize().x;
  1119. where.y += getBorderSize().y;
  1120. }
  1121. if (alignment == CENTER)
  1122. {
  1123. where.x += (int(destRect.w) - int(f->getStringWidth(what))) / 2;
  1124. where.y += (int(destRect.h) - int(f->getLineHeight())) / 2;
  1125. }
  1126. if (alignment == BOTTOMRIGHT)
  1127. {
  1128. where.x += getBorderSize().x + destRect.w - f->getStringWidth(what);
  1129. where.y += getBorderSize().y + destRect.h - f->getLineHeight();
  1130. }
  1131. size_t begin = 0;
  1132. std::string delimeters = "{}";
  1133. size_t currDelimeter = 0;
  1134. do
  1135. {
  1136. size_t end = what.find_first_of(delimeters[currDelimeter % 2], begin);
  1137. if (begin != end)
  1138. {
  1139. std::string toPrint = what.substr(begin, end - begin);
  1140. if (currDelimeter % 2) // Enclosed in {} text - set to yellow
  1141. f->renderTextLeft(to, toPrint, Colors::YELLOW, where);
  1142. else // Non-enclosed text, use default color
  1143. f->renderTextLeft(to, toPrint, color, where);
  1144. begin = end;
  1145. where.x += f->getStringWidth(toPrint);
  1146. }
  1147. currDelimeter++;
  1148. }
  1149. while (begin++ != std::string::npos);
  1150. }
  1151. CTextContainer::CTextContainer(EAlignment alignment, EFonts font, SDL_Color color):
  1152. alignment(alignment),
  1153. font(font),
  1154. color(color)
  1155. {}
  1156. void CMultiLineLabel::showAll(SDL_Surface * to)
  1157. {
  1158. CIntObject::showAll(to);
  1159. const IFont * f = graphics->fonts[font];
  1160. // calculate which lines should be visible
  1161. int totalLines = lines.size();
  1162. int beginLine = visibleSize.y;
  1163. int endLine = getTextLocation().h + visibleSize.y;
  1164. if (beginLine < 0)
  1165. beginLine = 0;
  1166. else
  1167. beginLine /= f->getLineHeight();
  1168. if (endLine < 0)
  1169. endLine = 0;
  1170. else
  1171. endLine /= f->getLineHeight();
  1172. endLine++;
  1173. // and where they should be displayed
  1174. Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * f->getLineHeight());
  1175. Point lineSize = Point(getTextLocation().w, f->getLineHeight());
  1176. CSDL_Ext::CClipRectGuard guard(to, getTextLocation()); // to properly trim text that is too big to fit
  1177. for (int i = beginLine; i < std::min(totalLines, endLine); i++)
  1178. {
  1179. if (!lines[i].empty()) //non-empty line
  1180. blitLine(to, Rect(lineStart, lineSize), lines[i]);
  1181. lineStart.y += f->getLineHeight();
  1182. }
  1183. }
  1184. void CMultiLineLabel::splitText(const std::string &Txt)
  1185. {
  1186. lines.clear();
  1187. const IFont * f = graphics->fonts[font];
  1188. int lineHeight = f->getLineHeight();
  1189. lines = CMessage::breakText(Txt, pos.w, font);
  1190. textSize.y = lineHeight * lines.size();
  1191. textSize.x = 0;
  1192. for(const std::string &line : lines)
  1193. vstd::amax( textSize.x, f->getStringWidth(line.c_str()));
  1194. redraw();
  1195. }
  1196. Rect CMultiLineLabel::getTextLocation()
  1197. {
  1198. // this method is needed for vertical alignment alignment of text
  1199. // when height of available text is smaller than height of widget
  1200. // in this case - we should add proper offset to display text at required position
  1201. if (pos.h <= textSize.y)
  1202. return pos;
  1203. Point textSize(pos.w, graphics->fonts[font]->getLineHeight() * lines.size());
  1204. Point textOffset(pos.w - textSize.x, pos.h - textSize.y);
  1205. switch(alignment)
  1206. {
  1207. case TOPLEFT: return Rect(pos.topLeft(), textSize);
  1208. case CENTER: return Rect(pos.topLeft() + textOffset / 2, textSize);
  1209. case BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
  1210. }
  1211. assert(0);
  1212. return Rect();
  1213. }
  1214. CLabelGroup::CLabelGroup(EFonts Font, EAlignment Align, const SDL_Color &Color):
  1215. font(Font), align(Align), color(Color)
  1216. {}
  1217. void CLabelGroup::add(int x, int y, const std::string &text)
  1218. {
  1219. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1220. new CLabel(x, y, font, align, color, text);
  1221. }
  1222. CTextBox::CTextBox(std::string Text, const Rect &rect, int SliderStyle, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= TOPLEFT*/, const SDL_Color &Color /*= Colors::WHITE*/):
  1223. sliderStyle(SliderStyle),
  1224. slider(nullptr)
  1225. {
  1226. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1227. label = new CMultiLineLabel(rect, Font, Align, Color);
  1228. type |= REDRAW_PARENT;
  1229. pos.x += rect.x;
  1230. pos.y += rect.y;
  1231. pos.h = rect.h;
  1232. pos.w = rect.w;
  1233. assert(pos.w >= 40); //we need some space
  1234. setText(Text);
  1235. }
  1236. void CTextBox::sliderMoved(int to)
  1237. {
  1238. label->scrollTextTo(to);
  1239. }
  1240. void CTextBox::resize(Point newSize)
  1241. {
  1242. pos.w = newSize.x;
  1243. pos.h = newSize.y;
  1244. label->pos.w = pos.w;
  1245. label->pos.h = pos.h;
  1246. if (slider)
  1247. vstd::clear_pointer(slider); // will be recreated if needed later
  1248. setText(label->getText()); // force refresh
  1249. }
  1250. void CTextBox::setText(const std::string &text)
  1251. {
  1252. label->setText(text);
  1253. if (label->textSize.y <= label->pos.h && slider)
  1254. {
  1255. // slider is no longer needed
  1256. vstd::clear_pointer(slider);
  1257. label->pos.w = pos.w;
  1258. label->setText(text);
  1259. }
  1260. else if (label->textSize.y > label->pos.h && !slider)
  1261. {
  1262. // create slider and update widget
  1263. label->pos.w = pos.w - 32;
  1264. label->setText(text);
  1265. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1266. slider = new CSlider(pos.w - 32, 0, pos.h, boost::bind(&CTextBox::sliderMoved, this, _1),
  1267. label->pos.h, label->textSize.y, 0, false, sliderStyle);
  1268. slider->scrollStep = graphics->fonts[label->font]->getLineHeight();
  1269. }
  1270. }
  1271. void CGStatusBar::setText(const std::string & Text)
  1272. {
  1273. if(!textLock)
  1274. CLabel::setText(Text);
  1275. }
  1276. void CGStatusBar::clear()
  1277. {
  1278. setText("");
  1279. }
  1280. CGStatusBar::CGStatusBar(CPicture *BG, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= CENTER*/, const SDL_Color &Color /*= Colors::WHITE*/)
  1281. : CLabel(BG->pos.x, BG->pos.y, Font, Align, Color, "")
  1282. {
  1283. init();
  1284. bg = BG;
  1285. addChild(bg);
  1286. pos = bg->pos;
  1287. getBorderSize();
  1288. textLock = false;
  1289. }
  1290. CGStatusBar::CGStatusBar(int x, int y, std::string name/*="ADROLLVR.bmp"*/, int maxw/*=-1*/)
  1291. : CLabel(x, y, FONT_SMALL, CENTER)
  1292. {
  1293. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1294. init();
  1295. bg = new CPicture(name);
  1296. pos = bg->pos;
  1297. if((unsigned int)maxw < pos.w)
  1298. {
  1299. vstd::amin(pos.w, maxw);
  1300. bg->srcRect = new Rect(0, 0, maxw, pos.h);
  1301. }
  1302. textLock = false;
  1303. }
  1304. CGStatusBar::~CGStatusBar()
  1305. {
  1306. GH.statusbar = oldStatusBar;
  1307. }
  1308. void CGStatusBar::show(SDL_Surface * to)
  1309. {
  1310. showAll(to);
  1311. }
  1312. void CGStatusBar::init()
  1313. {
  1314. oldStatusBar = GH.statusbar;
  1315. GH.statusbar = this;
  1316. }
  1317. Point CGStatusBar::getBorderSize()
  1318. {
  1319. //Width of borders where text should not be printed
  1320. static const Point borderSize(5,1);
  1321. switch(alignment)
  1322. {
  1323. case TOPLEFT: return Point(borderSize.x, borderSize.y);
  1324. case CENTER: return Point(pos.w/2, pos.h/2);
  1325. case BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
  1326. }
  1327. assert(0);
  1328. return Point();
  1329. }
  1330. void CGStatusBar::lock(bool shouldLock)
  1331. {
  1332. textLock = shouldLock;
  1333. }
  1334. CTextInput::CTextInput(const Rect &Pos, EFonts font, const CFunctionList<void(const std::string &)> &CB):
  1335. CLabel(Pos.x, Pos.y, font, CENTER),
  1336. cb(CB)
  1337. {
  1338. type |= REDRAW_PARENT;
  1339. focus = false;
  1340. pos.h = Pos.h;
  1341. pos.w = Pos.w;
  1342. captureAllKeys = true;
  1343. bg = nullptr;
  1344. addUsedEvents(LCLICK | KEYBOARD);
  1345. giveFocus();
  1346. }
  1347. CTextInput::CTextInput( const Rect &Pos, const Point &bgOffset, const std::string &bgName, const CFunctionList<void(const std::string &)> &CB )
  1348. :cb(CB)
  1349. {
  1350. focus = false;
  1351. pos += Pos;
  1352. captureAllKeys = true;
  1353. OBJ_CONSTRUCTION;
  1354. bg = new CPicture(bgName, bgOffset.x, bgOffset.y);
  1355. addUsedEvents(LCLICK | KEYBOARD);
  1356. giveFocus();
  1357. }
  1358. CTextInput::CTextInput(const Rect &Pos, SDL_Surface *srf)
  1359. {
  1360. focus = false;
  1361. pos += Pos;
  1362. captureAllKeys = true;
  1363. OBJ_CONSTRUCTION;
  1364. bg = new CPicture(Pos, 0, true);
  1365. Rect hlp = Pos;
  1366. if(srf)
  1367. CSDL_Ext::blitSurface(srf, &hlp, *bg, nullptr);
  1368. else
  1369. SDL_FillRect(*bg, nullptr, 0);
  1370. pos.w = bg->pos.w;
  1371. pos.h = bg->pos.h;
  1372. bg->pos = pos;
  1373. addUsedEvents(LCLICK | KEYBOARD);
  1374. giveFocus();
  1375. }
  1376. std::string CTextInput::visibleText()
  1377. {
  1378. return focus ? text + "_" : text;
  1379. }
  1380. void CTextInput::clickLeft( tribool down, bool previousState )
  1381. {
  1382. if(down && !focus)
  1383. giveFocus();
  1384. }
  1385. void CTextInput::keyPressed( const SDL_KeyboardEvent & key )
  1386. {
  1387. if(!focus || key.state != SDL_PRESSED)
  1388. return;
  1389. if(key.keysym.sym == SDLK_TAB)
  1390. {
  1391. moveFocus();
  1392. GH.breakEventHandling();
  1393. return;
  1394. }
  1395. std::string oldText = text;
  1396. switch(key.keysym.sym)
  1397. {
  1398. case SDLK_DELETE: // have index > ' ' so it won't be filtered out by default section
  1399. return;
  1400. case SDLK_BACKSPACE:
  1401. if(!text.empty())
  1402. text.resize(text.size()-1);
  1403. break;
  1404. default:
  1405. #if 0
  1406. if (key.keysym.unicode < ' ')
  1407. return;
  1408. else
  1409. text += key.keysym.unicode; //TODO 16-/>8
  1410. #endif // 0
  1411. break;
  1412. }
  1413. #if 0
  1414. filters(text, oldText);
  1415. if (text != oldText)
  1416. {
  1417. redraw();
  1418. cb(text);
  1419. }
  1420. #endif // 0
  1421. //todo: handle text input for SDL2
  1422. }
  1423. void CTextInput::setText( const std::string &nText, bool callCb )
  1424. {
  1425. CLabel::setText(nText);
  1426. if(callCb)
  1427. cb(text);
  1428. }
  1429. bool CTextInput::captureThisEvent(const SDL_KeyboardEvent & key)
  1430. {
  1431. if(key.keysym.sym == SDLK_RETURN || key.keysym.sym == SDLK_KP_ENTER)
  1432. return false;
  1433. #if 0
  1434. //this should allow all non-printable keys to go through (for example arrows)
  1435. if (key.keysym.unicode < ' ')
  1436. return false;
  1437. return true;
  1438. #else
  1439. return false; //todo:CTextInput::captureThisEvent
  1440. #endif
  1441. }
  1442. void CTextInput::filenameFilter(std::string & text, const std::string &)
  1443. {
  1444. static const std::string forbiddenChars = "<>:\"/\\|?*\r\n"; //if we are entering a filename, some special characters won't be allowed
  1445. size_t pos;
  1446. while ((pos = text.find_first_of(forbiddenChars)) != std::string::npos)
  1447. text.erase(pos, 1);
  1448. }
  1449. void CTextInput::numberFilter(std::string & text, const std::string & oldText, int minValue, int maxValue)
  1450. {
  1451. assert(minValue < maxValue);
  1452. if (text.empty())
  1453. text = "0";
  1454. size_t pos = 0;
  1455. if (text[0] == '-') //allow '-' sign as first symbol only
  1456. pos++;
  1457. while (pos < text.size())
  1458. {
  1459. if (text[pos] < '0' || text[pos] > '9')
  1460. {
  1461. text = oldText;
  1462. return; //new text is not number.
  1463. }
  1464. pos++;
  1465. }
  1466. try
  1467. {
  1468. int value = boost::lexical_cast<int>(text);
  1469. if (value < minValue)
  1470. text = boost::lexical_cast<std::string>(minValue);
  1471. else if (value > maxValue)
  1472. text = boost::lexical_cast<std::string>(maxValue);
  1473. }
  1474. catch(boost::bad_lexical_cast &)
  1475. {
  1476. //Should never happen. Unless I missed some cases
  1477. logGlobal->warnStream() << "Warning: failed to convert "<< text << " to number!";
  1478. text = oldText;
  1479. }
  1480. }
  1481. CFocusable::CFocusable()
  1482. {
  1483. focusables.push_back(this);
  1484. }
  1485. CFocusable::~CFocusable()
  1486. {
  1487. if(inputWithFocus == this)
  1488. inputWithFocus = nullptr;
  1489. focusables -= this;
  1490. }
  1491. void CFocusable::giveFocus()
  1492. {
  1493. if(inputWithFocus)
  1494. {
  1495. inputWithFocus->focus = false;
  1496. inputWithFocus->redraw();
  1497. }
  1498. focus = true;
  1499. inputWithFocus = this;
  1500. redraw();
  1501. }
  1502. void CFocusable::moveFocus()
  1503. {
  1504. auto i = vstd::find(focusables, this),
  1505. ourIt = i;
  1506. for(i++; i != ourIt; i++)
  1507. {
  1508. if(i == focusables.end())
  1509. i = focusables.begin();
  1510. if((*i)->active)
  1511. {
  1512. (*i)->giveFocus();
  1513. break;;
  1514. }
  1515. }
  1516. }
  1517. CWindowObject::CWindowObject(int options_, std::string imageName, Point centerAt):
  1518. CIntObject(getUsedEvents(options_), Point()),
  1519. shadow(nullptr),
  1520. options(options_),
  1521. background(createBg(imageName, options & PLAYER_COLORED))
  1522. {
  1523. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1524. if (options & RCLICK_POPUP)
  1525. CCS->curh->hide();
  1526. if (background)
  1527. pos = background->center(centerAt);
  1528. else
  1529. center(centerAt);
  1530. if (!(options & SHADOW_DISABLED))
  1531. setShadow(true);
  1532. }
  1533. CWindowObject::CWindowObject(int options_, std::string imageName):
  1534. CIntObject(getUsedEvents(options_), Point()),
  1535. shadow(nullptr),
  1536. options(options_),
  1537. background(createBg(imageName, options & PLAYER_COLORED))
  1538. {
  1539. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1540. if (options & RCLICK_POPUP)
  1541. CCS->curh->hide();
  1542. if (background)
  1543. pos = background->center();
  1544. else
  1545. center(Point(screen->w/2, screen->h/2));
  1546. if (!(options & SHADOW_DISABLED))
  1547. setShadow(true);
  1548. }
  1549. CWindowObject::~CWindowObject()
  1550. {
  1551. setShadow(false);
  1552. }
  1553. CPicture * CWindowObject::createBg(std::string imageName, bool playerColored)
  1554. {
  1555. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1556. if (imageName.empty())
  1557. return nullptr;
  1558. auto image = new CPicture(imageName);
  1559. if (playerColored)
  1560. image->colorize(LOCPLINT->playerID);
  1561. return image;
  1562. }
  1563. void CWindowObject::setBackground(std::string filename)
  1564. {
  1565. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1566. delete background;
  1567. background = createBg(filename, options & PLAYER_COLORED);
  1568. if (background)
  1569. pos = background->center(Point(pos.w/2 + pos.x, pos.h/2 + pos.y));
  1570. updateShadow();
  1571. }
  1572. int CWindowObject::getUsedEvents(int options)
  1573. {
  1574. if (options & RCLICK_POPUP)
  1575. return RCLICK;
  1576. return 0;
  1577. }
  1578. void CWindowObject::updateShadow()
  1579. {
  1580. setShadow(false);
  1581. if (!(options & SHADOW_DISABLED))
  1582. setShadow(true);
  1583. }
  1584. void CWindowObject::setShadow(bool on)
  1585. {
  1586. //size of shadow
  1587. static const int size = 8;
  1588. if (on == bool(shadow))
  1589. return;
  1590. vstd::clear_pointer(shadow);
  1591. //object too small to cast shadow
  1592. if (pos.h <= size || pos.w <= size)
  1593. return;
  1594. if (on)
  1595. {
  1596. //helper to set last row
  1597. auto blitAlphaRow = [](SDL_Surface *surf, size_t row)
  1598. {
  1599. Uint8 * ptr = (Uint8*)surf->pixels + surf->pitch * (row);
  1600. for (size_t i=0; i< surf->w; i++)
  1601. {
  1602. Channels::px<4>::a.set(ptr, 128);
  1603. ptr+=4;
  1604. }
  1605. };
  1606. // helper to set last column
  1607. auto blitAlphaCol = [](SDL_Surface *surf, size_t col)
  1608. {
  1609. Uint8 * ptr = (Uint8*)surf->pixels + 4 * (col);
  1610. for (size_t i=0; i< surf->h; i++)
  1611. {
  1612. Channels::px<4>::a.set(ptr, 128);
  1613. ptr+= surf->pitch;
  1614. }
  1615. };
  1616. static SDL_Surface * shadowCornerTempl = nullptr;
  1617. static SDL_Surface * shadowBottomTempl = nullptr;
  1618. static SDL_Surface * shadowRightTempl = nullptr;
  1619. //one-time initialization
  1620. if (!shadowCornerTempl)
  1621. {
  1622. //create "template" surfaces
  1623. shadowCornerTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, size);
  1624. shadowBottomTempl = CSDL_Ext::createSurfaceWithBpp<4>(1, size);
  1625. shadowRightTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, 1);
  1626. Uint32 shadowColor = SDL_MapRGBA(shadowCornerTempl->format, 0, 0, 0, 192);
  1627. //fill with shadow body color
  1628. SDL_FillRect(shadowCornerTempl, nullptr, shadowColor);
  1629. SDL_FillRect(shadowBottomTempl, nullptr, shadowColor);
  1630. SDL_FillRect(shadowRightTempl, nullptr, shadowColor);
  1631. //fill last row and column with more transparent color
  1632. blitAlphaCol(shadowRightTempl , size-1);
  1633. blitAlphaCol(shadowCornerTempl, size-1);
  1634. blitAlphaRow(shadowBottomTempl, size-1);
  1635. blitAlphaRow(shadowCornerTempl, size-1);
  1636. }
  1637. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1638. //FIXME: do something with this points
  1639. Point shadowStart;
  1640. if (options & BORDERED)
  1641. shadowStart = Point(size - 14, size - 14);
  1642. else
  1643. shadowStart = Point(size, size);
  1644. Point shadowPos;
  1645. if (options & BORDERED)
  1646. shadowPos = Point(pos.w + 14, pos.h + 14);
  1647. else
  1648. shadowPos = Point(pos.w, pos.h);
  1649. Point fullsize;
  1650. if (options & BORDERED)
  1651. fullsize = Point(pos.w + 28, pos.h + 29);
  1652. else
  1653. fullsize = Point(pos.w, pos.h);
  1654. //create base 8x8 piece of shadow
  1655. SDL_Surface * shadowCorner = CSDL_Ext::copySurface(shadowCornerTempl);
  1656. SDL_Surface * shadowBottom = CSDL_Ext::scaleSurfaceFast(shadowBottomTempl, fullsize.x - size, size);
  1657. SDL_Surface * shadowRight = CSDL_Ext::scaleSurfaceFast(shadowRightTempl, size, fullsize.y - size);
  1658. blitAlphaCol(shadowBottom, 0);
  1659. blitAlphaRow(shadowRight, 0);
  1660. //generate "shadow" object with these 3 pieces in it
  1661. shadow = new CIntObject;
  1662. shadow->addChild(new CPicture(shadowCorner, shadowPos.x, shadowPos.y));
  1663. shadow->addChild(new CPicture(shadowRight, shadowPos.x, shadowStart.y));
  1664. shadow->addChild(new CPicture(shadowBottom, shadowStart.x, shadowPos.y));
  1665. }
  1666. }
  1667. void CWindowObject::showAll(SDL_Surface *to)
  1668. {
  1669. CIntObject::showAll(to);
  1670. if ((options & BORDERED) && (pos.h != to->h || pos.w != to->w))
  1671. CMessage::drawBorder(LOCPLINT ? LOCPLINT->playerID : PlayerColor(1), to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  1672. }
  1673. void CWindowObject::close()
  1674. {
  1675. GH.popIntTotally(this);
  1676. }
  1677. void CWindowObject::clickRight(tribool down, bool previousState)
  1678. {
  1679. close();
  1680. CCS->curh->show();
  1681. }