2
0

CIntObjectClasses.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  1. #include "StdInc.h"
  2. #include "CIntObjectClasses.h"
  3. #include "CAnimation.h"
  4. #include "MiscWidgets.h"
  5. #include "../gui/SDL_Pixels.h"
  6. #include "../gui/SDL_Extensions.h"
  7. #include "../gui/CGuiHandler.h"
  8. #include "../gui/CCursorHandler.h"
  9. #include "../battle/CBattleInterface.h"
  10. #include "../battle/CBattleInterfaceClasses.h"
  11. #include "../CBitmapHandler.h"
  12. #include "../Graphics.h"
  13. #include "../CGameInfo.h"
  14. #include "../CPlayerInterface.h"
  15. #include "../CMessage.h"
  16. #include "../CMusicHandler.h"
  17. #include "../windows/CAdvmapInterface.h"
  18. #include "../../CCallback.h"
  19. #include "../../lib/CConfigHandler.h"
  20. #include "../../lib/CGeneralTextHandler.h" //for Unicode related stuff
  21. CPicture::CPicture( SDL_Surface *BG, int x, int y, bool Free )
  22. {
  23. init();
  24. bg = BG;
  25. freeSurf = Free;
  26. pos.x += x;
  27. pos.y += y;
  28. pos.w = BG->w;
  29. pos.h = BG->h;
  30. }
  31. CPicture::CPicture( const std::string &bmpname, int x, int y )
  32. {
  33. init();
  34. bg = BitmapHandler::loadBitmap(bmpname);
  35. freeSurf = true;;
  36. pos.x += x;
  37. pos.y += y;
  38. if(bg)
  39. {
  40. pos.w = bg->w;
  41. pos.h = bg->h;
  42. }
  43. else
  44. {
  45. pos.w = pos.h = 0;
  46. }
  47. }
  48. CPicture::CPicture(const Rect &r, const SDL_Color &color, bool screenFormat /*= false*/)
  49. {
  50. init();
  51. createSimpleRect(r, screenFormat, SDL_MapRGB(bg->format, color.r, color.g,color.b));
  52. }
  53. CPicture::CPicture(const Rect &r, ui32 color, bool screenFormat /*= false*/)
  54. {
  55. init();
  56. createSimpleRect(r, screenFormat, color);
  57. }
  58. CPicture::CPicture(SDL_Surface *BG, const Rect &SrcRect, int x /*= 0*/, int y /*= 0*/, bool free /*= false*/)
  59. {
  60. needRefresh = false;
  61. srcRect = new Rect(SrcRect);
  62. pos.x += x;
  63. pos.y += y;
  64. pos.w = srcRect->w;
  65. pos.h = srcRect->h;
  66. bg = BG;
  67. freeSurf = free;
  68. }
  69. void CPicture::setSurface(SDL_Surface *to)
  70. {
  71. bg = to;
  72. if (srcRect)
  73. {
  74. pos.w = srcRect->w;
  75. pos.h = srcRect->h;
  76. }
  77. else
  78. {
  79. pos.w = bg->w;
  80. pos.h = bg->h;
  81. }
  82. }
  83. CPicture::~CPicture()
  84. {
  85. if(freeSurf)
  86. SDL_FreeSurface(bg);
  87. delete srcRect;
  88. }
  89. void CPicture::init()
  90. {
  91. needRefresh = false;
  92. srcRect = nullptr;
  93. }
  94. void CPicture::show(SDL_Surface * to)
  95. {
  96. if (needRefresh)
  97. showAll(to);
  98. }
  99. void CPicture::showAll(SDL_Surface * to)
  100. {
  101. if(bg)
  102. {
  103. if(srcRect)
  104. {
  105. SDL_Rect srcRectCpy = *srcRect;
  106. SDL_Rect dstRect = srcRectCpy;
  107. dstRect.x = pos.x;
  108. dstRect.y = pos.y;
  109. CSDL_Ext::blitSurface(bg, &srcRectCpy, to, &dstRect);
  110. }
  111. else
  112. blitAt(bg, pos, to);
  113. }
  114. }
  115. void CPicture::convertToScreenBPP()
  116. {
  117. SDL_Surface *hlp = bg;
  118. bg = SDL_ConvertSurface(hlp,screen->format,0);
  119. CSDL_Ext::setDefaultColorKey(bg);
  120. SDL_FreeSurface(hlp);
  121. }
  122. void CPicture::setAlpha(int value)
  123. {
  124. #ifdef VCMI_SDL1
  125. SDL_SetAlpha(bg, SDL_SRCALPHA, value);
  126. #else
  127. SDL_SetSurfaceAlphaMod(bg,value);
  128. #endif // 0
  129. }
  130. void CPicture::scaleTo(Point size)
  131. {
  132. SDL_Surface * scaled = CSDL_Ext::scaleSurface(bg, size.x, size.y);
  133. if(freeSurf)
  134. SDL_FreeSurface(bg);
  135. setSurface(scaled);
  136. freeSurf = false;
  137. }
  138. void CPicture::createSimpleRect(const Rect &r, bool screenFormat, ui32 color)
  139. {
  140. pos += r;
  141. pos.w = r.w;
  142. pos.h = r.h;
  143. if(screenFormat)
  144. bg = CSDL_Ext::newSurface(r.w, r.h);
  145. else
  146. bg = SDL_CreateRGBSurface(SDL_SWSURFACE, r.w, r.h, 8, 0, 0, 0, 0);
  147. SDL_FillRect(bg, nullptr, color);
  148. freeSurf = true;
  149. }
  150. void CPicture::colorizeAndConvert(PlayerColor player)
  151. {
  152. assert(bg);
  153. colorize(player);
  154. convertToScreenBPP();
  155. }
  156. void CPicture::colorize(PlayerColor player)
  157. {
  158. assert(bg);
  159. graphics->blueToPlayersAdv(bg, player);
  160. }
  161. CFilledTexture::CFilledTexture(std::string imageName, Rect position):
  162. CIntObject(0, position.topLeft()),
  163. texture(BitmapHandler::loadBitmap(imageName))
  164. {
  165. pos.w = position.w;
  166. pos.h = position.h;
  167. }
  168. CFilledTexture::~CFilledTexture()
  169. {
  170. SDL_FreeSurface(texture);
  171. }
  172. void CFilledTexture::showAll(SDL_Surface *to)
  173. {
  174. CSDL_Ext::CClipRectGuard guard(to, pos);
  175. CSDL_Ext::fillTexture(to, texture);
  176. }
  177. CButtonBase::CButtonBase()
  178. {
  179. swappedImages = keepFrame = false;
  180. bitmapOffset = 0;
  181. state=NORMAL;
  182. image = nullptr;
  183. overlay = nullptr;
  184. }
  185. CButtonBase::~CButtonBase()
  186. {
  187. }
  188. void CButtonBase::update()
  189. {
  190. if (overlay)
  191. {
  192. if (state == PRESSED)
  193. overlay->moveTo(overlay->pos.centerIn(pos).topLeft() + Point(1,1));
  194. else
  195. overlay->moveTo(overlay->pos.centerIn(pos).topLeft());
  196. }
  197. int newPos = (int)state + bitmapOffset;
  198. if (newPos < 0)
  199. newPos = 0;
  200. if (state == HIGHLIGHTED && image->size() < 4)
  201. newPos = image->size()-1;
  202. if (swappedImages)
  203. {
  204. if (newPos == 0) newPos = 1;
  205. else if (newPos == 1) newPos = 0;
  206. }
  207. if (!keepFrame)
  208. image->setFrame(newPos);
  209. if (active)
  210. redraw();
  211. }
  212. void CButtonBase::addTextOverlay( const std::string &Text, EFonts font, SDL_Color color)
  213. {
  214. OBJ_CONSTRUCTION_CAPTURING_ALL;
  215. addOverlay(new CLabel(pos.w/2, pos.h/2, font, CENTER, color, Text));
  216. update();
  217. }
  218. void CButtonBase::addOverlay(CIntObject *newOverlay)
  219. {
  220. delete overlay;
  221. overlay = newOverlay;
  222. addChild(newOverlay);
  223. overlay->moveTo(overlay->pos.centerIn(pos).topLeft());
  224. update();
  225. }
  226. void CButtonBase::setOffset(int newOffset)
  227. {
  228. if (bitmapOffset == newOffset)
  229. return;
  230. bitmapOffset = newOffset;
  231. update();
  232. }
  233. void CButtonBase::setState(ButtonState newState)
  234. {
  235. if (state == newState)
  236. return;
  237. state = newState;
  238. update();
  239. }
  240. CButtonBase::ButtonState CButtonBase::getState()
  241. {
  242. return state;
  243. }
  244. bool CButtonBase::isBlocked()
  245. {
  246. return state == BLOCKED;
  247. }
  248. bool CButtonBase::isHighlighted()
  249. {
  250. return state == HIGHLIGHTED;
  251. }
  252. void CButtonBase::block(bool on)
  253. {
  254. setState(on?BLOCKED:NORMAL);
  255. }
  256. CAdventureMapButton::CAdventureMapButton ()
  257. {
  258. hoverable = actOnDown = borderEnabled = soundDisabled = false;
  259. CSDL_Ext::colorSetAlpha(borderColor,1);// represents a transparent color, used for HighlightableButton
  260. addUsedEvents(LCLICK | RCLICK | HOVER | KEYBOARD);
  261. }
  262. 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 )
  263. {
  264. std::map<int,std::string> pom;
  265. pom[0] = Name;
  266. init(Callback, pom, HelpBox, playerColoredButton, defName, add, x, y, key);
  267. }
  268. CAdventureMapButton::CAdventureMapButton( const std::string &Name, const std::string &HelpBox, const CFunctionList<void()> &Callback, config::ButtonInfo *info, int key/*=0*/ )
  269. {
  270. std::map<int,std::string> pom;
  271. pom[0] = Name;
  272. init(Callback, pom, HelpBox, info->playerColoured, info->defName, &info->additionalDefs, info->x, info->y, key);
  273. }
  274. 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 */ )
  275. {
  276. std::map<int,std::string> pom;
  277. pom[0] = help.first;
  278. init(Callback, pom, help.second, playerColoredButton, defName, add, x, y, key);
  279. }
  280. void CAdventureMapButton::onButtonClicked()
  281. {
  282. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  283. logAnim->traceStream() << "Button clicked at " << pos.x << "x" << pos.y;
  284. CIntObject * parent = this->parent;
  285. std::string prefix = "Parent is";
  286. while (parent)
  287. {
  288. logAnim->traceStream() << prefix << typeid(*parent).name() << " at " << parent->pos.x << "x" << parent->pos.y;
  289. parent = parent->parent;
  290. prefix = '\t' + prefix;
  291. }
  292. callback();
  293. }
  294. void CAdventureMapButton::clickLeft(tribool down, bool previousState)
  295. {
  296. if(isBlocked())
  297. return;
  298. if (down)
  299. {
  300. if (!soundDisabled)
  301. CCS->soundh->playSound(soundBase::button);
  302. setState(PRESSED);
  303. }
  304. else if(hoverable && hovered)
  305. setState(HIGHLIGHTED);
  306. else
  307. setState(NORMAL);
  308. if (actOnDown && down)
  309. {
  310. onButtonClicked();
  311. }
  312. else if (!actOnDown && previousState && (down==false))
  313. {
  314. onButtonClicked();
  315. }
  316. }
  317. void CAdventureMapButton::clickRight(tribool down, bool previousState)
  318. {
  319. if(down && helpBox.size()) //there is no point to show window with nothing inside...
  320. CRClickPopup::createAndPush(helpBox);
  321. }
  322. void CAdventureMapButton::hover (bool on)
  323. {
  324. if(hoverable)
  325. {
  326. if(on)
  327. setState(HIGHLIGHTED);
  328. else
  329. setState(NORMAL);
  330. }
  331. if(pressedL && on)
  332. setState(PRESSED);
  333. std::string *name = (vstd::contains(hoverTexts,getState()))
  334. ? (&hoverTexts[getState()])
  335. : (vstd::contains(hoverTexts,0) ? (&hoverTexts[0]) : nullptr);
  336. if(name && name->size() && !isBlocked()) //if there is no name, there is nohing to display also
  337. {
  338. if (LOCPLINT && LOCPLINT->battleInt) //for battle buttons
  339. {
  340. if(on && LOCPLINT->battleInt->console->alterTxt == "")
  341. {
  342. LOCPLINT->battleInt->console->alterTxt = *name;
  343. LOCPLINT->battleInt->console->whoSetAlter = 1;
  344. }
  345. else if (LOCPLINT->battleInt->console->alterTxt == *name)
  346. {
  347. LOCPLINT->battleInt->console->alterTxt = "";
  348. LOCPLINT->battleInt->console->whoSetAlter = 0;
  349. }
  350. }
  351. else if(GH.statusbar) //for other buttons
  352. {
  353. if (on)
  354. GH.statusbar->setText(*name);
  355. else if ( GH.statusbar->getText()==(*name) )
  356. GH.statusbar->clear();
  357. }
  358. }
  359. }
  360. 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)
  361. {
  362. currentImage = -1;
  363. addUsedEvents(LCLICK | RCLICK | HOVER | KEYBOARD);
  364. callback = Callback;
  365. hoverable = actOnDown = borderEnabled = soundDisabled = false;
  366. CSDL_Ext::colorSetAlpha(borderColor,1);// represents a transparent color, used for HighlightableButton
  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. #ifdef VCMI_SDL1
  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::fillRectBlack(to, &pos);
  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 && !text.empty())
  1012. {
  1013. LOCPLINT->showInfoDialog(text);
  1014. }
  1015. }
  1016. void LRClickableAreaWText::clickRight(tribool down, bool previousState)
  1017. {
  1018. if (!text.empty())
  1019. adventureInt->handleRightClick(text, down);
  1020. }
  1021. LRClickableAreaWText::LRClickableAreaWText()
  1022. {
  1023. init();
  1024. }
  1025. LRClickableAreaWText::LRClickableAreaWText(const Rect &Pos, const std::string &HoverText /*= ""*/, const std::string &ClickText /*= ""*/)
  1026. {
  1027. init();
  1028. pos = Pos + pos;
  1029. hoverText = HoverText;
  1030. text = ClickText;
  1031. }
  1032. LRClickableAreaWText::~LRClickableAreaWText()
  1033. {
  1034. }
  1035. void LRClickableAreaWText::init()
  1036. {
  1037. addUsedEvents(LCLICK | RCLICK | HOVER);
  1038. }
  1039. std::string CLabel::visibleText()
  1040. {
  1041. return text;
  1042. }
  1043. void CLabel::showAll(SDL_Surface * to)
  1044. {
  1045. CIntObject::showAll(to);
  1046. if(!visibleText().empty())
  1047. blitLine(to, pos, visibleText());
  1048. }
  1049. CLabel::CLabel(int x, int y, EFonts Font /*= FONT_SMALL*/, EAlignment Align, const SDL_Color &Color /*= Colors::WHITE*/, const std::string &Text /*= ""*/)
  1050. :CTextContainer(Align, Font, Color), text(Text)
  1051. {
  1052. type |= REDRAW_PARENT;
  1053. autoRedraw = true;
  1054. pos.x += x;
  1055. pos.y += y;
  1056. pos.w = pos.h = 0;
  1057. bg = nullptr;
  1058. if (alignment == TOPLEFT) // causes issues for MIDDLE
  1059. {
  1060. pos.w = graphics->fonts[font]->getStringWidth(visibleText().c_str());
  1061. pos.h = graphics->fonts[font]->getLineHeight();
  1062. }
  1063. }
  1064. Point CLabel::getBorderSize()
  1065. {
  1066. return Point(0, 0);
  1067. }
  1068. std::string CLabel::getText()
  1069. {
  1070. return text;
  1071. }
  1072. void CLabel::setText(const std::string &Txt)
  1073. {
  1074. text = Txt;
  1075. if(autoRedraw)
  1076. {
  1077. if(bg || !parent)
  1078. redraw();
  1079. else
  1080. parent->redraw();
  1081. }
  1082. }
  1083. CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, EAlignment Align, const SDL_Color &Color, const std::string &Text):
  1084. CLabel(position.x, position.y, Font, Align, Color, Text),
  1085. visibleSize(0, 0, position.w, position.h)
  1086. {
  1087. pos.w = position.w;
  1088. pos.h = position.h;
  1089. splitText(Text);
  1090. }
  1091. void CMultiLineLabel::setVisibleSize(Rect visibleSize)
  1092. {
  1093. this->visibleSize = visibleSize;
  1094. redraw();
  1095. }
  1096. void CMultiLineLabel::scrollTextBy(int distance)
  1097. {
  1098. scrollTextTo(visibleSize.y + distance);
  1099. }
  1100. void CMultiLineLabel::scrollTextTo(int distance)
  1101. {
  1102. Rect size = visibleSize;
  1103. size.y = distance;
  1104. setVisibleSize(size);
  1105. }
  1106. void CMultiLineLabel::setText(const std::string &Txt)
  1107. {
  1108. splitText(Txt);
  1109. CLabel::setText(Txt);
  1110. }
  1111. void CTextContainer::blitLine(SDL_Surface *to, Rect destRect, std::string what)
  1112. {
  1113. const IFont * f = graphics->fonts[font];
  1114. Point where = destRect.topLeft();
  1115. // input is rect in which given text should be placed
  1116. // calculate proper position for top-left corner of the text
  1117. if (alignment == TOPLEFT)
  1118. {
  1119. where.x += getBorderSize().x;
  1120. where.y += getBorderSize().y;
  1121. }
  1122. if (alignment == CENTER)
  1123. {
  1124. where.x += (int(destRect.w) - int(f->getStringWidth(what))) / 2;
  1125. where.y += (int(destRect.h) - int(f->getLineHeight())) / 2;
  1126. }
  1127. if (alignment == BOTTOMRIGHT)
  1128. {
  1129. where.x += getBorderSize().x + destRect.w - f->getStringWidth(what);
  1130. where.y += getBorderSize().y + destRect.h - f->getLineHeight();
  1131. }
  1132. size_t begin = 0;
  1133. std::string delimeters = "{}";
  1134. size_t currDelimeter = 0;
  1135. do
  1136. {
  1137. size_t end = what.find_first_of(delimeters[currDelimeter % 2], begin);
  1138. if (begin != end)
  1139. {
  1140. std::string toPrint = what.substr(begin, end - begin);
  1141. if (currDelimeter % 2) // Enclosed in {} text - set to yellow
  1142. f->renderTextLeft(to, toPrint, Colors::YELLOW, where);
  1143. else // Non-enclosed text, use default color
  1144. f->renderTextLeft(to, toPrint, color, where);
  1145. begin = end;
  1146. where.x += f->getStringWidth(toPrint);
  1147. }
  1148. currDelimeter++;
  1149. }
  1150. while (begin++ != std::string::npos);
  1151. }
  1152. CTextContainer::CTextContainer(EAlignment alignment, EFonts font, SDL_Color color):
  1153. alignment(alignment),
  1154. font(font),
  1155. color(color)
  1156. {}
  1157. void CMultiLineLabel::showAll(SDL_Surface * to)
  1158. {
  1159. CIntObject::showAll(to);
  1160. const IFont * f = graphics->fonts[font];
  1161. // calculate which lines should be visible
  1162. int totalLines = lines.size();
  1163. int beginLine = visibleSize.y;
  1164. int endLine = getTextLocation().h + visibleSize.y;
  1165. if (beginLine < 0)
  1166. beginLine = 0;
  1167. else
  1168. beginLine /= f->getLineHeight();
  1169. if (endLine < 0)
  1170. endLine = 0;
  1171. else
  1172. endLine /= f->getLineHeight();
  1173. endLine++;
  1174. // and where they should be displayed
  1175. Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * f->getLineHeight());
  1176. Point lineSize = Point(getTextLocation().w, f->getLineHeight());
  1177. CSDL_Ext::CClipRectGuard guard(to, getTextLocation()); // to properly trim text that is too big to fit
  1178. for (int i = beginLine; i < std::min(totalLines, endLine); i++)
  1179. {
  1180. if (!lines[i].empty()) //non-empty line
  1181. blitLine(to, Rect(lineStart, lineSize), lines[i]);
  1182. lineStart.y += f->getLineHeight();
  1183. }
  1184. }
  1185. void CMultiLineLabel::splitText(const std::string &Txt)
  1186. {
  1187. lines.clear();
  1188. const IFont * f = graphics->fonts[font];
  1189. int lineHeight = f->getLineHeight();
  1190. lines = CMessage::breakText(Txt, pos.w, font);
  1191. textSize.y = lineHeight * lines.size();
  1192. textSize.x = 0;
  1193. for(const std::string &line : lines)
  1194. vstd::amax( textSize.x, f->getStringWidth(line.c_str()));
  1195. redraw();
  1196. }
  1197. Rect CMultiLineLabel::getTextLocation()
  1198. {
  1199. // this method is needed for vertical alignment alignment of text
  1200. // when height of available text is smaller than height of widget
  1201. // in this case - we should add proper offset to display text at required position
  1202. if (pos.h <= textSize.y)
  1203. return pos;
  1204. Point textSize(pos.w, graphics->fonts[font]->getLineHeight() * lines.size());
  1205. Point textOffset(pos.w - textSize.x, pos.h - textSize.y);
  1206. switch(alignment)
  1207. {
  1208. case TOPLEFT: return Rect(pos.topLeft(), textSize);
  1209. case CENTER: return Rect(pos.topLeft() + textOffset / 2, textSize);
  1210. case BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
  1211. }
  1212. assert(0);
  1213. return Rect();
  1214. }
  1215. CLabelGroup::CLabelGroup(EFonts Font, EAlignment Align, const SDL_Color &Color):
  1216. font(Font), align(Align), color(Color)
  1217. {}
  1218. void CLabelGroup::add(int x, int y, const std::string &text)
  1219. {
  1220. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1221. new CLabel(x, y, font, align, color, text);
  1222. }
  1223. CTextBox::CTextBox(std::string Text, const Rect &rect, int SliderStyle, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= TOPLEFT*/, const SDL_Color &Color /*= Colors::WHITE*/):
  1224. sliderStyle(SliderStyle),
  1225. slider(nullptr)
  1226. {
  1227. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1228. label = new CMultiLineLabel(rect, Font, Align, Color);
  1229. type |= REDRAW_PARENT;
  1230. pos.x += rect.x;
  1231. pos.y += rect.y;
  1232. pos.h = rect.h;
  1233. pos.w = rect.w;
  1234. assert(pos.w >= 40); //we need some space
  1235. setText(Text);
  1236. }
  1237. void CTextBox::sliderMoved(int to)
  1238. {
  1239. label->scrollTextTo(to);
  1240. }
  1241. void CTextBox::resize(Point newSize)
  1242. {
  1243. pos.w = newSize.x;
  1244. pos.h = newSize.y;
  1245. label->pos.w = pos.w;
  1246. label->pos.h = pos.h;
  1247. if (slider)
  1248. vstd::clear_pointer(slider); // will be recreated if needed later
  1249. setText(label->getText()); // force refresh
  1250. }
  1251. void CTextBox::setText(const std::string &text)
  1252. {
  1253. label->setText(text);
  1254. if (label->textSize.y <= label->pos.h && slider)
  1255. {
  1256. // slider is no longer needed
  1257. vstd::clear_pointer(slider);
  1258. label->pos.w = pos.w;
  1259. label->setText(text);
  1260. }
  1261. else if (label->textSize.y > label->pos.h && !slider)
  1262. {
  1263. // create slider and update widget
  1264. label->pos.w = pos.w - 32;
  1265. label->setText(text);
  1266. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1267. slider = new CSlider(pos.w - 32, 0, pos.h, boost::bind(&CTextBox::sliderMoved, this, _1),
  1268. label->pos.h, label->textSize.y, 0, false, sliderStyle);
  1269. slider->scrollStep = graphics->fonts[label->font]->getLineHeight();
  1270. }
  1271. }
  1272. void CGStatusBar::setText(const std::string & Text)
  1273. {
  1274. if(!textLock)
  1275. CLabel::setText(Text);
  1276. }
  1277. void CGStatusBar::clear()
  1278. {
  1279. setText("");
  1280. }
  1281. CGStatusBar::CGStatusBar(CPicture *BG, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= CENTER*/, const SDL_Color &Color /*= Colors::WHITE*/)
  1282. : CLabel(BG->pos.x, BG->pos.y, Font, Align, Color, "")
  1283. {
  1284. init();
  1285. bg = BG;
  1286. addChild(bg);
  1287. pos = bg->pos;
  1288. getBorderSize();
  1289. textLock = false;
  1290. }
  1291. CGStatusBar::CGStatusBar(int x, int y, std::string name/*="ADROLLVR.bmp"*/, int maxw/*=-1*/)
  1292. : CLabel(x, y, FONT_SMALL, CENTER)
  1293. {
  1294. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1295. init();
  1296. bg = new CPicture(name);
  1297. pos = bg->pos;
  1298. if((unsigned int)maxw < pos.w)
  1299. {
  1300. vstd::amin(pos.w, maxw);
  1301. bg->srcRect = new Rect(0, 0, maxw, pos.h);
  1302. }
  1303. textLock = false;
  1304. }
  1305. CGStatusBar::~CGStatusBar()
  1306. {
  1307. GH.statusbar = oldStatusBar;
  1308. }
  1309. void CGStatusBar::show(SDL_Surface * to)
  1310. {
  1311. showAll(to);
  1312. }
  1313. void CGStatusBar::init()
  1314. {
  1315. oldStatusBar = GH.statusbar;
  1316. GH.statusbar = this;
  1317. }
  1318. Point CGStatusBar::getBorderSize()
  1319. {
  1320. //Width of borders where text should not be printed
  1321. static const Point borderSize(5,1);
  1322. switch(alignment)
  1323. {
  1324. case TOPLEFT: return Point(borderSize.x, borderSize.y);
  1325. case CENTER: return Point(pos.w/2, pos.h/2);
  1326. case BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
  1327. }
  1328. assert(0);
  1329. return Point();
  1330. }
  1331. void CGStatusBar::lock(bool shouldLock)
  1332. {
  1333. textLock = shouldLock;
  1334. }
  1335. CTextInput::CTextInput(const Rect &Pos, EFonts font, const CFunctionList<void(const std::string &)> &CB):
  1336. CLabel(Pos.x, Pos.y, font, CENTER),
  1337. cb(CB)
  1338. {
  1339. type |= REDRAW_PARENT;
  1340. focus = false;
  1341. pos.h = Pos.h;
  1342. pos.w = Pos.w;
  1343. captureAllKeys = true;
  1344. bg = nullptr;
  1345. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1346. giveFocus();
  1347. }
  1348. CTextInput::CTextInput( const Rect &Pos, const Point &bgOffset, const std::string &bgName, const CFunctionList<void(const std::string &)> &CB )
  1349. :cb(CB)
  1350. {
  1351. focus = false;
  1352. pos += Pos;
  1353. captureAllKeys = true;
  1354. OBJ_CONSTRUCTION;
  1355. bg = new CPicture(bgName, bgOffset.x, bgOffset.y);
  1356. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1357. giveFocus();
  1358. }
  1359. CTextInput::CTextInput(const Rect &Pos, SDL_Surface *srf)
  1360. {
  1361. focus = false;
  1362. pos += Pos;
  1363. captureAllKeys = true;
  1364. OBJ_CONSTRUCTION;
  1365. bg = new CPicture(Pos, 0, true);
  1366. Rect hlp = Pos;
  1367. if(srf)
  1368. CSDL_Ext::blitSurface(srf, &hlp, *bg, nullptr);
  1369. else
  1370. SDL_FillRect(*bg, nullptr, 0);
  1371. pos.w = bg->pos.w;
  1372. pos.h = bg->pos.h;
  1373. bg->pos = pos;
  1374. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1375. giveFocus();
  1376. }
  1377. void CTextInput::focusGot()
  1378. {
  1379. CSDL_Ext::startTextInput(&pos);
  1380. }
  1381. void CTextInput::focusLost()
  1382. {
  1383. CSDL_Ext::stopTextInput();
  1384. }
  1385. std::string CTextInput::visibleText()
  1386. {
  1387. return focus ? text + newText + "_" : text;
  1388. }
  1389. void CTextInput::clickLeft( tribool down, bool previousState )
  1390. {
  1391. if(down && !focus)
  1392. giveFocus();
  1393. }
  1394. void CTextInput::keyPressed( const SDL_KeyboardEvent & key )
  1395. {
  1396. if(!focus || key.state != SDL_PRESSED)
  1397. return;
  1398. if(key.keysym.sym == SDLK_TAB)
  1399. {
  1400. moveFocus();
  1401. GH.breakEventHandling();
  1402. return;
  1403. }
  1404. bool redrawNeeded = false;
  1405. #ifdef VCMI_SDL1
  1406. std::string oldText = text;
  1407. #endif // 0
  1408. switch(key.keysym.sym)
  1409. {
  1410. case SDLK_DELETE: // have index > ' ' so it won't be filtered out by default section
  1411. return;
  1412. case SDLK_BACKSPACE:
  1413. if(!newText.empty())
  1414. {
  1415. Unicode::trimRight(newText);
  1416. redrawNeeded = true;
  1417. }
  1418. else if(!text.empty())
  1419. {
  1420. Unicode::trimRight(text);
  1421. redrawNeeded = true;
  1422. }
  1423. break;
  1424. default:
  1425. #ifdef VCMI_SDL1
  1426. if (key.keysym.unicode < ' ')
  1427. return;
  1428. else
  1429. {
  1430. text += key.keysym.unicode; //TODO 16-/>8
  1431. redrawNeeded = true;
  1432. }
  1433. #endif // 0
  1434. break;
  1435. }
  1436. #ifdef VCMI_SDL1
  1437. filters(text, oldText);
  1438. #endif // 0
  1439. if (redrawNeeded)
  1440. {
  1441. redraw();
  1442. cb(text);
  1443. }
  1444. }
  1445. void CTextInput::setText( const std::string &nText, bool callCb )
  1446. {
  1447. CLabel::setText(nText);
  1448. if(callCb)
  1449. cb(text);
  1450. }
  1451. bool CTextInput::captureThisEvent(const SDL_KeyboardEvent & key)
  1452. {
  1453. if(key.keysym.sym == SDLK_RETURN || key.keysym.sym == SDLK_KP_ENTER)
  1454. return false;
  1455. #ifdef VCMI_SDL1
  1456. //this should allow all non-printable keys to go through (for example arrows)
  1457. if (key.keysym.unicode < ' ')
  1458. return false;
  1459. return true;
  1460. #else
  1461. return false;
  1462. #endif
  1463. }
  1464. #ifndef VCMI_SDL1
  1465. void CTextInput::textInputed(const SDL_TextInputEvent & event)
  1466. {
  1467. if(!focus)
  1468. return;
  1469. std::string oldText = text;
  1470. text += event.text;
  1471. filters(text,oldText);
  1472. if (text != oldText)
  1473. {
  1474. redraw();
  1475. cb(text);
  1476. }
  1477. newText = "";
  1478. }
  1479. void CTextInput::textEdited(const SDL_TextEditingEvent & event)
  1480. {
  1481. if(!focus)
  1482. return;
  1483. newText = event.text;
  1484. redraw();
  1485. cb(text+newText);
  1486. }
  1487. #endif
  1488. void CTextInput::filenameFilter(std::string & text, const std::string &)
  1489. {
  1490. static const std::string forbiddenChars = "<>:\"/\\|?*\r\n"; //if we are entering a filename, some special characters won't be allowed
  1491. size_t pos;
  1492. while ((pos = text.find_first_of(forbiddenChars)) != std::string::npos)
  1493. text.erase(pos, 1);
  1494. }
  1495. void CTextInput::numberFilter(std::string & text, const std::string & oldText, int minValue, int maxValue)
  1496. {
  1497. assert(minValue < maxValue);
  1498. if (text.empty())
  1499. text = "0";
  1500. size_t pos = 0;
  1501. if (text[0] == '-') //allow '-' sign as first symbol only
  1502. pos++;
  1503. while (pos < text.size())
  1504. {
  1505. if (text[pos] < '0' || text[pos] > '9')
  1506. {
  1507. text = oldText;
  1508. return; //new text is not number.
  1509. }
  1510. pos++;
  1511. }
  1512. try
  1513. {
  1514. int value = boost::lexical_cast<int>(text);
  1515. if (value < minValue)
  1516. text = boost::lexical_cast<std::string>(minValue);
  1517. else if (value > maxValue)
  1518. text = boost::lexical_cast<std::string>(maxValue);
  1519. }
  1520. catch(boost::bad_lexical_cast &)
  1521. {
  1522. //Should never happen. Unless I missed some cases
  1523. logGlobal->warnStream() << "Warning: failed to convert "<< text << " to number!";
  1524. text = oldText;
  1525. }
  1526. }
  1527. CFocusable::CFocusable()
  1528. {
  1529. focusables.push_back(this);
  1530. }
  1531. CFocusable::~CFocusable()
  1532. {
  1533. if(inputWithFocus == this)
  1534. {
  1535. focusLost();
  1536. inputWithFocus = nullptr;
  1537. }
  1538. focusables -= this;
  1539. }
  1540. void CFocusable::giveFocus()
  1541. {
  1542. if(inputWithFocus)
  1543. {
  1544. inputWithFocus->focus = false;
  1545. inputWithFocus->focusLost();
  1546. inputWithFocus->redraw();
  1547. }
  1548. focus = true;
  1549. inputWithFocus = this;
  1550. focusGot();
  1551. redraw();
  1552. }
  1553. void CFocusable::moveFocus()
  1554. {
  1555. auto i = vstd::find(focusables, this),
  1556. ourIt = i;
  1557. for(i++; i != ourIt; i++)
  1558. {
  1559. if(i == focusables.end())
  1560. i = focusables.begin();
  1561. if((*i)->active)
  1562. {
  1563. (*i)->giveFocus();
  1564. break;;
  1565. }
  1566. }
  1567. }
  1568. CWindowObject::CWindowObject(int options_, std::string imageName, Point centerAt):
  1569. CIntObject(getUsedEvents(options_), Point()),
  1570. shadow(nullptr),
  1571. options(options_),
  1572. background(createBg(imageName, options & PLAYER_COLORED))
  1573. {
  1574. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1575. if (options & RCLICK_POPUP)
  1576. CCS->curh->hide();
  1577. if (background)
  1578. pos = background->center(centerAt);
  1579. else
  1580. center(centerAt);
  1581. if (!(options & SHADOW_DISABLED))
  1582. setShadow(true);
  1583. }
  1584. CWindowObject::CWindowObject(int options_, std::string imageName):
  1585. CIntObject(getUsedEvents(options_), Point()),
  1586. shadow(nullptr),
  1587. options(options_),
  1588. background(createBg(imageName, options & PLAYER_COLORED))
  1589. {
  1590. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1591. if (options & RCLICK_POPUP)
  1592. CCS->curh->hide();
  1593. if (background)
  1594. pos = background->center();
  1595. else
  1596. center(Point(screen->w/2, screen->h/2));
  1597. if (!(options & SHADOW_DISABLED))
  1598. setShadow(true);
  1599. }
  1600. CWindowObject::~CWindowObject()
  1601. {
  1602. setShadow(false);
  1603. }
  1604. CPicture * CWindowObject::createBg(std::string imageName, bool playerColored)
  1605. {
  1606. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1607. if (imageName.empty())
  1608. return nullptr;
  1609. auto image = new CPicture(imageName);
  1610. if (playerColored)
  1611. image->colorize(LOCPLINT->playerID);
  1612. return image;
  1613. }
  1614. void CWindowObject::setBackground(std::string filename)
  1615. {
  1616. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1617. delete background;
  1618. background = createBg(filename, options & PLAYER_COLORED);
  1619. if (background)
  1620. pos = background->center(Point(pos.w/2 + pos.x, pos.h/2 + pos.y));
  1621. updateShadow();
  1622. }
  1623. int CWindowObject::getUsedEvents(int options)
  1624. {
  1625. if (options & RCLICK_POPUP)
  1626. return RCLICK;
  1627. return 0;
  1628. }
  1629. void CWindowObject::updateShadow()
  1630. {
  1631. setShadow(false);
  1632. if (!(options & SHADOW_DISABLED))
  1633. setShadow(true);
  1634. }
  1635. void CWindowObject::setShadow(bool on)
  1636. {
  1637. //size of shadow
  1638. static const int size = 8;
  1639. if (on == bool(shadow))
  1640. return;
  1641. vstd::clear_pointer(shadow);
  1642. //object too small to cast shadow
  1643. if (pos.h <= size || pos.w <= size)
  1644. return;
  1645. if (on)
  1646. {
  1647. //helper to set last row
  1648. auto blitAlphaRow = [](SDL_Surface *surf, size_t row)
  1649. {
  1650. Uint8 * ptr = (Uint8*)surf->pixels + surf->pitch * (row);
  1651. for (size_t i=0; i< surf->w; i++)
  1652. {
  1653. Channels::px<4>::a.set(ptr, 128);
  1654. ptr+=4;
  1655. }
  1656. };
  1657. // helper to set last column
  1658. auto blitAlphaCol = [](SDL_Surface *surf, size_t col)
  1659. {
  1660. Uint8 * ptr = (Uint8*)surf->pixels + 4 * (col);
  1661. for (size_t i=0; i< surf->h; i++)
  1662. {
  1663. Channels::px<4>::a.set(ptr, 128);
  1664. ptr+= surf->pitch;
  1665. }
  1666. };
  1667. static SDL_Surface * shadowCornerTempl = nullptr;
  1668. static SDL_Surface * shadowBottomTempl = nullptr;
  1669. static SDL_Surface * shadowRightTempl = nullptr;
  1670. //one-time initialization
  1671. if (!shadowCornerTempl)
  1672. {
  1673. //create "template" surfaces
  1674. shadowCornerTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, size);
  1675. shadowBottomTempl = CSDL_Ext::createSurfaceWithBpp<4>(1, size);
  1676. shadowRightTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, 1);
  1677. Uint32 shadowColor = SDL_MapRGBA(shadowCornerTempl->format, 0, 0, 0, 192);
  1678. //fill with shadow body color
  1679. SDL_FillRect(shadowCornerTempl, nullptr, shadowColor);
  1680. SDL_FillRect(shadowBottomTempl, nullptr, shadowColor);
  1681. SDL_FillRect(shadowRightTempl, nullptr, shadowColor);
  1682. //fill last row and column with more transparent color
  1683. blitAlphaCol(shadowRightTempl , size-1);
  1684. blitAlphaCol(shadowCornerTempl, size-1);
  1685. blitAlphaRow(shadowBottomTempl, size-1);
  1686. blitAlphaRow(shadowCornerTempl, size-1);
  1687. }
  1688. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1689. //FIXME: do something with this points
  1690. Point shadowStart;
  1691. if (options & BORDERED)
  1692. shadowStart = Point(size - 14, size - 14);
  1693. else
  1694. shadowStart = Point(size, size);
  1695. Point shadowPos;
  1696. if (options & BORDERED)
  1697. shadowPos = Point(pos.w + 14, pos.h + 14);
  1698. else
  1699. shadowPos = Point(pos.w, pos.h);
  1700. Point fullsize;
  1701. if (options & BORDERED)
  1702. fullsize = Point(pos.w + 28, pos.h + 29);
  1703. else
  1704. fullsize = Point(pos.w, pos.h);
  1705. //create base 8x8 piece of shadow
  1706. SDL_Surface * shadowCorner = CSDL_Ext::copySurface(shadowCornerTempl);
  1707. SDL_Surface * shadowBottom = CSDL_Ext::scaleSurfaceFast(shadowBottomTempl, fullsize.x - size, size);
  1708. SDL_Surface * shadowRight = CSDL_Ext::scaleSurfaceFast(shadowRightTempl, size, fullsize.y - size);
  1709. blitAlphaCol(shadowBottom, 0);
  1710. blitAlphaRow(shadowRight, 0);
  1711. //generate "shadow" object with these 3 pieces in it
  1712. shadow = new CIntObject;
  1713. shadow->addChild(new CPicture(shadowCorner, shadowPos.x, shadowPos.y));
  1714. shadow->addChild(new CPicture(shadowRight, shadowPos.x, shadowStart.y));
  1715. shadow->addChild(new CPicture(shadowBottom, shadowStart.x, shadowPos.y));
  1716. }
  1717. }
  1718. void CWindowObject::showAll(SDL_Surface *to)
  1719. {
  1720. CIntObject::showAll(to);
  1721. if ((options & BORDERED) && (pos.h != to->h || pos.w != to->w))
  1722. CMessage::drawBorder(LOCPLINT ? LOCPLINT->playerID : PlayerColor(1), to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  1723. }
  1724. void CWindowObject::close()
  1725. {
  1726. GH.popIntTotally(this);
  1727. }
  1728. void CWindowObject::clickRight(tribool down, bool previousState)
  1729. {
  1730. close();
  1731. CCS->curh->show();
  1732. }