CIntObjectClasses.cpp 45 KB

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