CIntObjectClasses.cpp 43 KB

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