CIntObjectClasses.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  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. 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::fillRectBlack(to, &pos);
  744. CIntObject::showAll(to);
  745. }
  746. void CSlider::wheelScrolled(bool down, bool in)
  747. {
  748. moveTo(value + 3 * (down ? +scrollStep : -scrollStep));
  749. }
  750. void CSlider::keyPressed(const SDL_KeyboardEvent & key)
  751. {
  752. if(key.state != SDL_PRESSED) return;
  753. int moveDest = 0;
  754. switch(key.keysym.sym)
  755. {
  756. case SDLK_UP:
  757. case SDLK_LEFT:
  758. moveDest = value - scrollStep;
  759. break;
  760. case SDLK_DOWN:
  761. case SDLK_RIGHT:
  762. moveDest = value + scrollStep;
  763. break;
  764. case SDLK_PAGEUP:
  765. moveDest = value - capacity + scrollStep;
  766. break;
  767. case SDLK_PAGEDOWN:
  768. moveDest = value + capacity - scrollStep;
  769. break;
  770. case SDLK_HOME:
  771. moveDest = 0;
  772. break;
  773. case SDLK_END:
  774. moveDest = amount - capacity;
  775. break;
  776. default:
  777. return;
  778. }
  779. moveTo(moveDest);
  780. }
  781. void CSlider::moveToMax()
  782. {
  783. moveTo(amount);
  784. }
  785. static void intDeleter(CIntObject* object)
  786. {
  787. delete object;
  788. }
  789. CObjectList::CObjectList(CreateFunc create, DestroyFunc destroy):
  790. createObject(create),
  791. destroyObject(destroy)
  792. {
  793. if (!destroyObject)
  794. destroyObject = intDeleter;
  795. }
  796. void CObjectList::deleteItem(CIntObject* item)
  797. {
  798. if (!item)
  799. return;
  800. removeChild(item);
  801. destroyObject(item);
  802. }
  803. CIntObject* CObjectList::createItem(size_t index)
  804. {
  805. OBJ_CONSTRUCTION_CAPTURING_ALL;
  806. CIntObject * item = createObject(index);
  807. if (item == nullptr)
  808. item = new CIntObject();
  809. item->recActions = defActions;
  810. addChild(item);
  811. return item;
  812. }
  813. CTabbedInt::CTabbedInt(CreateFunc create, DestroyFunc destroy, Point position, size_t ActiveID):
  814. CObjectList(create, destroy),
  815. activeTab(nullptr),
  816. activeID(ActiveID)
  817. {
  818. pos += position;
  819. reset();
  820. }
  821. void CTabbedInt::setActive(size_t which)
  822. {
  823. if (which != activeID)
  824. {
  825. activeID = which;
  826. reset();
  827. }
  828. }
  829. void CTabbedInt::reset()
  830. {
  831. deleteItem(activeTab);
  832. activeTab = createItem(activeID);
  833. activeTab->moveTo(pos.topLeft());
  834. if (active)
  835. redraw();
  836. }
  837. CIntObject * CTabbedInt::getItem()
  838. {
  839. return activeTab;
  840. }
  841. CListBox::CListBox(CreateFunc create, DestroyFunc destroy, Point Pos, Point ItemOffset, size_t VisibleSize,
  842. size_t TotalSize, size_t InitialPos, int Slider, Rect SliderPos):
  843. CObjectList(create, destroy),
  844. first(InitialPos),
  845. totalSize(TotalSize),
  846. itemOffset(ItemOffset),
  847. slider(nullptr)
  848. {
  849. pos += Pos;
  850. items.resize(VisibleSize, nullptr);
  851. if (Slider & 1)
  852. {
  853. OBJ_CONSTRUCTION_CAPTURING_ALL;
  854. slider = new CSlider(SliderPos.x, SliderPos.y, SliderPos.w, boost::bind(&CListBox::moveToPos, this, _1),
  855. VisibleSize, TotalSize, InitialPos, Slider & 2, Slider & 4);
  856. }
  857. reset();
  858. }
  859. // Used to move active items after changing list position
  860. void CListBox::updatePositions()
  861. {
  862. Point itemPos = pos.topLeft();
  863. for (auto & elem : items)
  864. {
  865. (elem)->moveTo(itemPos);
  866. itemPos += itemOffset;
  867. }
  868. if (active)
  869. {
  870. redraw();
  871. if (slider)
  872. slider->moveTo(first);
  873. }
  874. }
  875. void CListBox::reset()
  876. {
  877. size_t current = first;
  878. for (auto & elem : items)
  879. {
  880. deleteItem(elem);
  881. elem = createItem(current++);
  882. }
  883. updatePositions();
  884. }
  885. void CListBox::resize(size_t newSize)
  886. {
  887. totalSize = newSize;
  888. if (slider)
  889. slider->setAmount(totalSize);
  890. reset();
  891. }
  892. size_t CListBox::size()
  893. {
  894. return totalSize;
  895. }
  896. CIntObject * CListBox::getItem(size_t which)
  897. {
  898. if (which < first || which > first + items.size() || which > totalSize)
  899. return nullptr;
  900. size_t i=first;
  901. for (auto iter = items.begin(); iter != items.end(); iter++, i++)
  902. if( i == which)
  903. return *iter;
  904. return nullptr;
  905. }
  906. size_t CListBox::getIndexOf(CIntObject *item)
  907. {
  908. size_t i=first;
  909. for (auto iter = items.begin(); iter != items.end(); iter++, i++)
  910. if(*iter == item)
  911. return i;
  912. return size_t(-1);
  913. }
  914. void CListBox::scrollTo(size_t which)
  915. {
  916. //scroll up
  917. if (first > which)
  918. moveToPos(which);
  919. //scroll down
  920. else if (first + items.size() <= which && which < totalSize)
  921. moveToPos(which - items.size() + 1);
  922. }
  923. void CListBox::moveToPos(size_t which)
  924. {
  925. //Calculate new position
  926. size_t maxPossible;
  927. if (totalSize > items.size())
  928. maxPossible = totalSize - items.size();
  929. else
  930. maxPossible = 0;
  931. size_t newPos = std::min(which, maxPossible);
  932. //If move distance is 1 (most of calls from Slider) - use faster shifts instead of resetting all items
  933. if (first - newPos == 1)
  934. moveToPrev();
  935. else if (newPos - first == 1)
  936. moveToNext();
  937. else if (newPos != first)
  938. {
  939. first = newPos;
  940. reset();
  941. }
  942. }
  943. void CListBox::moveToNext()
  944. {
  945. //Remove front item and insert new one to end
  946. if (first + items.size() < totalSize)
  947. {
  948. first++;
  949. deleteItem(items.front());
  950. items.pop_front();
  951. items.push_back(createItem(first+items.size()));
  952. updatePositions();
  953. }
  954. }
  955. void CListBox::moveToPrev()
  956. {
  957. //Remove last item and insert new one at start
  958. if (first)
  959. {
  960. first--;
  961. deleteItem(items.back());
  962. items.pop_back();
  963. items.push_front(createItem(first));
  964. updatePositions();
  965. }
  966. }
  967. size_t CListBox::getPos()
  968. {
  969. return first;
  970. }
  971. const std::list<CIntObject *> &CListBox::getItems()
  972. {
  973. return items;
  974. }
  975. void CSimpleWindow::show(SDL_Surface * to)
  976. {
  977. if(bitmap)
  978. blitAt(bitmap,pos.x,pos.y,to);
  979. }
  980. CSimpleWindow::~CSimpleWindow()
  981. {
  982. if (bitmap)
  983. {
  984. SDL_FreeSurface(bitmap);
  985. bitmap=nullptr;
  986. }
  987. }
  988. void CHoverableArea::hover (bool on)
  989. {
  990. if (on)
  991. GH.statusbar->setText(hoverText);
  992. else if (GH.statusbar->getText()==hoverText)
  993. GH.statusbar->clear();
  994. }
  995. CHoverableArea::CHoverableArea()
  996. {
  997. addUsedEvents(HOVER);
  998. }
  999. CHoverableArea::~CHoverableArea()
  1000. {
  1001. }
  1002. void LRClickableAreaWText::clickLeft(tribool down, bool previousState)
  1003. {
  1004. if(!down && previousState)
  1005. {
  1006. LOCPLINT->showInfoDialog(text);
  1007. }
  1008. }
  1009. void LRClickableAreaWText::clickRight(tribool down, bool previousState)
  1010. {
  1011. adventureInt->handleRightClick(text, down);
  1012. }
  1013. LRClickableAreaWText::LRClickableAreaWText()
  1014. {
  1015. init();
  1016. }
  1017. LRClickableAreaWText::LRClickableAreaWText(const Rect &Pos, const std::string &HoverText /*= ""*/, const std::string &ClickText /*= ""*/)
  1018. {
  1019. init();
  1020. pos = Pos + pos;
  1021. hoverText = HoverText;
  1022. text = ClickText;
  1023. }
  1024. LRClickableAreaWText::~LRClickableAreaWText()
  1025. {
  1026. }
  1027. void LRClickableAreaWText::init()
  1028. {
  1029. addUsedEvents(LCLICK | RCLICK | HOVER);
  1030. }
  1031. std::string CLabel::visibleText()
  1032. {
  1033. return text;
  1034. }
  1035. void CLabel::showAll(SDL_Surface * to)
  1036. {
  1037. CIntObject::showAll(to);
  1038. if(!visibleText().empty())
  1039. blitLine(to, pos, visibleText());
  1040. }
  1041. CLabel::CLabel(int x, int y, EFonts Font /*= FONT_SMALL*/, EAlignment Align, const SDL_Color &Color /*= Colors::WHITE*/, const std::string &Text /*= ""*/)
  1042. :CTextContainer(Align, Font, Color), text(Text)
  1043. {
  1044. type |= REDRAW_PARENT;
  1045. autoRedraw = true;
  1046. pos.x += x;
  1047. pos.y += y;
  1048. pos.w = pos.h = 0;
  1049. bg = nullptr;
  1050. if (alignment == TOPLEFT) // causes issues for MIDDLE
  1051. {
  1052. pos.w = graphics->fonts[font]->getStringWidth(visibleText().c_str());
  1053. pos.h = graphics->fonts[font]->getLineHeight();
  1054. }
  1055. }
  1056. Point CLabel::getBorderSize()
  1057. {
  1058. return Point(0, 0);
  1059. }
  1060. std::string CLabel::getText()
  1061. {
  1062. return text;
  1063. }
  1064. void CLabel::setText(const std::string &Txt)
  1065. {
  1066. text = Txt;
  1067. if(autoRedraw)
  1068. {
  1069. if(bg || !parent)
  1070. redraw();
  1071. else
  1072. parent->redraw();
  1073. }
  1074. }
  1075. CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, EAlignment Align, const SDL_Color &Color, const std::string &Text):
  1076. CLabel(position.x, position.y, Font, Align, Color, Text),
  1077. visibleSize(0, 0, position.w, position.h)
  1078. {
  1079. pos.w = position.w;
  1080. pos.h = position.h;
  1081. splitText(Text);
  1082. }
  1083. void CMultiLineLabel::setVisibleSize(Rect visibleSize)
  1084. {
  1085. this->visibleSize = visibleSize;
  1086. redraw();
  1087. }
  1088. void CMultiLineLabel::scrollTextBy(int distance)
  1089. {
  1090. scrollTextTo(visibleSize.y + distance);
  1091. }
  1092. void CMultiLineLabel::scrollTextTo(int distance)
  1093. {
  1094. Rect size = visibleSize;
  1095. size.y = distance;
  1096. setVisibleSize(size);
  1097. }
  1098. void CMultiLineLabel::setText(const std::string &Txt)
  1099. {
  1100. splitText(Txt);
  1101. CLabel::setText(Txt);
  1102. }
  1103. void CTextContainer::blitLine(SDL_Surface *to, Rect destRect, std::string what)
  1104. {
  1105. const IFont * f = graphics->fonts[font];
  1106. Point where = destRect.topLeft();
  1107. // input is rect in which given text should be placed
  1108. // calculate proper position for top-left corner of the text
  1109. if (alignment == TOPLEFT)
  1110. {
  1111. where.x += getBorderSize().x;
  1112. where.y += getBorderSize().y;
  1113. }
  1114. if (alignment == CENTER)
  1115. {
  1116. where.x += (int(destRect.w) - int(f->getStringWidth(what))) / 2;
  1117. where.y += (int(destRect.h) - int(f->getLineHeight())) / 2;
  1118. }
  1119. if (alignment == BOTTOMRIGHT)
  1120. {
  1121. where.x += getBorderSize().x + destRect.w - f->getStringWidth(what);
  1122. where.y += getBorderSize().y + destRect.h - f->getLineHeight();
  1123. }
  1124. size_t begin = 0;
  1125. std::string delimeters = "{}";
  1126. size_t currDelimeter = 0;
  1127. do
  1128. {
  1129. size_t end = what.find_first_of(delimeters[currDelimeter % 2], begin);
  1130. if (begin != end)
  1131. {
  1132. std::string toPrint = what.substr(begin, end - begin);
  1133. if (currDelimeter % 2) // Enclosed in {} text - set to yellow
  1134. f->renderTextLeft(to, toPrint, Colors::YELLOW, where);
  1135. else // Non-enclosed text, use default color
  1136. f->renderTextLeft(to, toPrint, color, where);
  1137. begin = end;
  1138. where.x += f->getStringWidth(toPrint);
  1139. }
  1140. currDelimeter++;
  1141. }
  1142. while (begin++ != std::string::npos);
  1143. }
  1144. CTextContainer::CTextContainer(EAlignment alignment, EFonts font, SDL_Color color):
  1145. alignment(alignment),
  1146. font(font),
  1147. color(color)
  1148. {}
  1149. void CMultiLineLabel::showAll(SDL_Surface * to)
  1150. {
  1151. CIntObject::showAll(to);
  1152. const IFont * f = graphics->fonts[font];
  1153. // calculate which lines should be visible
  1154. int totalLines = lines.size();
  1155. int beginLine = visibleSize.y;
  1156. int endLine = getTextLocation().h + visibleSize.y;
  1157. if (beginLine < 0)
  1158. beginLine = 0;
  1159. else
  1160. beginLine /= f->getLineHeight();
  1161. if (endLine < 0)
  1162. endLine = 0;
  1163. else
  1164. endLine /= f->getLineHeight();
  1165. endLine++;
  1166. // and where they should be displayed
  1167. Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * f->getLineHeight());
  1168. Point lineSize = Point(getTextLocation().w, f->getLineHeight());
  1169. CSDL_Ext::CClipRectGuard guard(to, getTextLocation()); // to properly trim text that is too big to fit
  1170. for (int i = beginLine; i < std::min(totalLines, endLine); i++)
  1171. {
  1172. if (!lines[i].empty()) //non-empty line
  1173. blitLine(to, Rect(lineStart, lineSize), lines[i]);
  1174. lineStart.y += f->getLineHeight();
  1175. }
  1176. }
  1177. void CMultiLineLabel::splitText(const std::string &Txt)
  1178. {
  1179. lines.clear();
  1180. const IFont * f = graphics->fonts[font];
  1181. int lineHeight = f->getLineHeight();
  1182. lines = CMessage::breakText(Txt, pos.w, font);
  1183. textSize.y = lineHeight * lines.size();
  1184. textSize.x = 0;
  1185. for(const std::string &line : lines)
  1186. vstd::amax( textSize.x, f->getStringWidth(line.c_str()));
  1187. redraw();
  1188. }
  1189. Rect CMultiLineLabel::getTextLocation()
  1190. {
  1191. // this method is needed for vertical alignment alignment of text
  1192. // when height of available text is smaller than height of widget
  1193. // in this case - we should add proper offset to display text at required position
  1194. if (pos.h <= textSize.y)
  1195. return pos;
  1196. Point textSize(pos.w, graphics->fonts[font]->getLineHeight() * lines.size());
  1197. Point textOffset(pos.w - textSize.x, pos.h - textSize.y);
  1198. switch(alignment)
  1199. {
  1200. case TOPLEFT: return Rect(pos.topLeft(), textSize);
  1201. case CENTER: return Rect(pos.topLeft() + textOffset / 2, textSize);
  1202. case BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
  1203. }
  1204. assert(0);
  1205. return Rect();
  1206. }
  1207. CLabelGroup::CLabelGroup(EFonts Font, EAlignment Align, const SDL_Color &Color):
  1208. font(Font), align(Align), color(Color)
  1209. {}
  1210. void CLabelGroup::add(int x, int y, const std::string &text)
  1211. {
  1212. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1213. new CLabel(x, y, font, align, color, text);
  1214. }
  1215. CTextBox::CTextBox(std::string Text, const Rect &rect, int SliderStyle, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= TOPLEFT*/, const SDL_Color &Color /*= Colors::WHITE*/):
  1216. sliderStyle(SliderStyle),
  1217. slider(nullptr)
  1218. {
  1219. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1220. label = new CMultiLineLabel(rect, Font, Align, Color);
  1221. type |= REDRAW_PARENT;
  1222. pos.x += rect.x;
  1223. pos.y += rect.y;
  1224. pos.h = rect.h;
  1225. pos.w = rect.w;
  1226. assert(pos.w >= 40); //we need some space
  1227. setText(Text);
  1228. }
  1229. void CTextBox::sliderMoved(int to)
  1230. {
  1231. label->scrollTextTo(to);
  1232. }
  1233. void CTextBox::resize(Point newSize)
  1234. {
  1235. pos.w = newSize.x;
  1236. pos.h = newSize.y;
  1237. label->pos.w = pos.w;
  1238. label->pos.h = pos.h;
  1239. if (slider)
  1240. vstd::clear_pointer(slider); // will be recreated if needed later
  1241. setText(label->getText()); // force refresh
  1242. }
  1243. void CTextBox::setText(const std::string &text)
  1244. {
  1245. label->setText(text);
  1246. if (label->textSize.y <= label->pos.h && slider)
  1247. {
  1248. // slider is no longer needed
  1249. vstd::clear_pointer(slider);
  1250. label->pos.w = pos.w;
  1251. label->setText(text);
  1252. }
  1253. else if (label->textSize.y > label->pos.h && !slider)
  1254. {
  1255. // create slider and update widget
  1256. label->pos.w = pos.w - 32;
  1257. label->setText(text);
  1258. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1259. slider = new CSlider(pos.w - 32, 0, pos.h, boost::bind(&CTextBox::sliderMoved, this, _1),
  1260. label->pos.h, label->textSize.y, 0, false, sliderStyle);
  1261. slider->scrollStep = graphics->fonts[label->font]->getLineHeight();
  1262. }
  1263. }
  1264. void CGStatusBar::setText(const std::string & Text)
  1265. {
  1266. if(!textLock)
  1267. CLabel::setText(Text);
  1268. }
  1269. void CGStatusBar::clear()
  1270. {
  1271. setText("");
  1272. }
  1273. CGStatusBar::CGStatusBar(CPicture *BG, EFonts Font /*= FONT_SMALL*/, EAlignment Align /*= CENTER*/, const SDL_Color &Color /*= Colors::WHITE*/)
  1274. : CLabel(BG->pos.x, BG->pos.y, Font, Align, Color, "")
  1275. {
  1276. init();
  1277. bg = BG;
  1278. addChild(bg);
  1279. pos = bg->pos;
  1280. getBorderSize();
  1281. textLock = false;
  1282. }
  1283. CGStatusBar::CGStatusBar(int x, int y, std::string name/*="ADROLLVR.bmp"*/, int maxw/*=-1*/)
  1284. : CLabel(x, y, FONT_SMALL, CENTER)
  1285. {
  1286. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1287. init();
  1288. bg = new CPicture(name);
  1289. pos = bg->pos;
  1290. if((unsigned int)maxw < pos.w)
  1291. {
  1292. vstd::amin(pos.w, maxw);
  1293. bg->srcRect = new Rect(0, 0, maxw, pos.h);
  1294. }
  1295. textLock = false;
  1296. }
  1297. CGStatusBar::~CGStatusBar()
  1298. {
  1299. GH.statusbar = oldStatusBar;
  1300. }
  1301. void CGStatusBar::show(SDL_Surface * to)
  1302. {
  1303. showAll(to);
  1304. }
  1305. void CGStatusBar::init()
  1306. {
  1307. oldStatusBar = GH.statusbar;
  1308. GH.statusbar = this;
  1309. }
  1310. Point CGStatusBar::getBorderSize()
  1311. {
  1312. //Width of borders where text should not be printed
  1313. static const Point borderSize(5,1);
  1314. switch(alignment)
  1315. {
  1316. case TOPLEFT: return Point(borderSize.x, borderSize.y);
  1317. case CENTER: return Point(pos.w/2, pos.h/2);
  1318. case BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
  1319. }
  1320. assert(0);
  1321. return Point();
  1322. }
  1323. void CGStatusBar::lock(bool shouldLock)
  1324. {
  1325. textLock = shouldLock;
  1326. }
  1327. CTextInput::CTextInput(const Rect &Pos, EFonts font, const CFunctionList<void(const std::string &)> &CB):
  1328. CLabel(Pos.x, Pos.y, font, CENTER),
  1329. cb(CB)
  1330. {
  1331. type |= REDRAW_PARENT;
  1332. focus = false;
  1333. pos.h = Pos.h;
  1334. pos.w = Pos.w;
  1335. captureAllKeys = true;
  1336. bg = nullptr;
  1337. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1338. giveFocus();
  1339. }
  1340. CTextInput::CTextInput( const Rect &Pos, const Point &bgOffset, const std::string &bgName, const CFunctionList<void(const std::string &)> &CB )
  1341. :cb(CB)
  1342. {
  1343. focus = false;
  1344. pos += Pos;
  1345. captureAllKeys = true;
  1346. OBJ_CONSTRUCTION;
  1347. bg = new CPicture(bgName, bgOffset.x, bgOffset.y);
  1348. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1349. giveFocus();
  1350. }
  1351. CTextInput::CTextInput(const Rect &Pos, SDL_Surface *srf)
  1352. {
  1353. focus = false;
  1354. pos += Pos;
  1355. captureAllKeys = true;
  1356. OBJ_CONSTRUCTION;
  1357. bg = new CPicture(Pos, 0, true);
  1358. Rect hlp = Pos;
  1359. if(srf)
  1360. CSDL_Ext::blitSurface(srf, &hlp, *bg, nullptr);
  1361. else
  1362. SDL_FillRect(*bg, nullptr, 0);
  1363. pos.w = bg->pos.w;
  1364. pos.h = bg->pos.h;
  1365. bg->pos = pos;
  1366. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  1367. giveFocus();
  1368. }
  1369. void CTextInput::focusGot()
  1370. {
  1371. CSDL_Ext::startTextInput(&pos);
  1372. }
  1373. void CTextInput::focusLost()
  1374. {
  1375. CSDL_Ext::stopTextInput();
  1376. }
  1377. std::string CTextInput::visibleText()
  1378. {
  1379. return focus ? text + newText + "_" : text;
  1380. }
  1381. void CTextInput::clickLeft( tribool down, bool previousState )
  1382. {
  1383. if(down && !focus)
  1384. giveFocus();
  1385. }
  1386. void CTextInput::keyPressed( const SDL_KeyboardEvent & key )
  1387. {
  1388. if(!focus || key.state != SDL_PRESSED)
  1389. return;
  1390. if(key.keysym.sym == SDLK_TAB)
  1391. {
  1392. moveFocus();
  1393. GH.breakEventHandling();
  1394. return;
  1395. }
  1396. bool redrawNeeded = false;
  1397. #ifdef VCMI_SDL1
  1398. std::string oldText = text;
  1399. #endif // 0
  1400. switch(key.keysym.sym)
  1401. {
  1402. case SDLK_DELETE: // have index > ' ' so it won't be filtered out by default section
  1403. return;
  1404. case SDLK_BACKSPACE:
  1405. if(!newText.empty())
  1406. {
  1407. Unicode::trimRight(newText);
  1408. redrawNeeded = true;
  1409. }
  1410. else if(!text.empty())
  1411. {
  1412. Unicode::trimRight(text);
  1413. redrawNeeded = true;
  1414. }
  1415. break;
  1416. default:
  1417. #ifdef VCMI_SDL1
  1418. if (key.keysym.unicode < ' ')
  1419. return;
  1420. else
  1421. {
  1422. text += key.keysym.unicode; //TODO 16-/>8
  1423. redrawNeeded = true;
  1424. }
  1425. #endif // 0
  1426. break;
  1427. }
  1428. #ifdef VCMI_SDL1
  1429. filters(text, oldText);
  1430. #endif // 0
  1431. if (redrawNeeded)
  1432. {
  1433. redraw();
  1434. cb(text);
  1435. }
  1436. }
  1437. void CTextInput::setText( const std::string &nText, bool callCb )
  1438. {
  1439. CLabel::setText(nText);
  1440. if(callCb)
  1441. cb(text);
  1442. }
  1443. bool CTextInput::captureThisEvent(const SDL_KeyboardEvent & key)
  1444. {
  1445. if(key.keysym.sym == SDLK_RETURN || key.keysym.sym == SDLK_KP_ENTER)
  1446. return false;
  1447. #ifdef VCMI_SDL1
  1448. //this should allow all non-printable keys to go through (for example arrows)
  1449. if (key.keysym.unicode < ' ')
  1450. return false;
  1451. return true;
  1452. #else
  1453. return false;
  1454. #endif
  1455. }
  1456. #ifndef VCMI_SDL1
  1457. void CTextInput::textInputed(const SDL_TextInputEvent & event)
  1458. {
  1459. if(!focus)
  1460. return;
  1461. std::string oldText = text;
  1462. text += event.text;
  1463. filters(text,oldText);
  1464. if (text != oldText)
  1465. {
  1466. redraw();
  1467. cb(text);
  1468. }
  1469. newText = "";
  1470. }
  1471. void CTextInput::textEdited(const SDL_TextEditingEvent & event)
  1472. {
  1473. if(!focus)
  1474. return;
  1475. newText = event.text;
  1476. redraw();
  1477. cb(text+newText);
  1478. }
  1479. #endif
  1480. void CTextInput::filenameFilter(std::string & text, const std::string &)
  1481. {
  1482. static const std::string forbiddenChars = "<>:\"/\\|?*\r\n"; //if we are entering a filename, some special characters won't be allowed
  1483. size_t pos;
  1484. while ((pos = text.find_first_of(forbiddenChars)) != std::string::npos)
  1485. text.erase(pos, 1);
  1486. }
  1487. void CTextInput::numberFilter(std::string & text, const std::string & oldText, int minValue, int maxValue)
  1488. {
  1489. assert(minValue < maxValue);
  1490. if (text.empty())
  1491. text = "0";
  1492. size_t pos = 0;
  1493. if (text[0] == '-') //allow '-' sign as first symbol only
  1494. pos++;
  1495. while (pos < text.size())
  1496. {
  1497. if (text[pos] < '0' || text[pos] > '9')
  1498. {
  1499. text = oldText;
  1500. return; //new text is not number.
  1501. }
  1502. pos++;
  1503. }
  1504. try
  1505. {
  1506. int value = boost::lexical_cast<int>(text);
  1507. if (value < minValue)
  1508. text = boost::lexical_cast<std::string>(minValue);
  1509. else if (value > maxValue)
  1510. text = boost::lexical_cast<std::string>(maxValue);
  1511. }
  1512. catch(boost::bad_lexical_cast &)
  1513. {
  1514. //Should never happen. Unless I missed some cases
  1515. logGlobal->warnStream() << "Warning: failed to convert "<< text << " to number!";
  1516. text = oldText;
  1517. }
  1518. }
  1519. CFocusable::CFocusable()
  1520. {
  1521. focusables.push_back(this);
  1522. }
  1523. CFocusable::~CFocusable()
  1524. {
  1525. if(inputWithFocus == this)
  1526. {
  1527. focusLost();
  1528. inputWithFocus = nullptr;
  1529. }
  1530. focusables -= this;
  1531. }
  1532. void CFocusable::giveFocus()
  1533. {
  1534. if(inputWithFocus)
  1535. {
  1536. inputWithFocus->focus = false;
  1537. inputWithFocus->focusLost();
  1538. inputWithFocus->redraw();
  1539. }
  1540. focus = true;
  1541. inputWithFocus = this;
  1542. focusGot();
  1543. redraw();
  1544. }
  1545. void CFocusable::moveFocus()
  1546. {
  1547. auto i = vstd::find(focusables, this),
  1548. ourIt = i;
  1549. for(i++; i != ourIt; i++)
  1550. {
  1551. if(i == focusables.end())
  1552. i = focusables.begin();
  1553. if((*i)->active)
  1554. {
  1555. (*i)->giveFocus();
  1556. break;;
  1557. }
  1558. }
  1559. }
  1560. CWindowObject::CWindowObject(int options_, std::string imageName, Point centerAt):
  1561. CIntObject(getUsedEvents(options_), Point()),
  1562. shadow(nullptr),
  1563. options(options_),
  1564. background(createBg(imageName, options & PLAYER_COLORED))
  1565. {
  1566. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1567. if (options & RCLICK_POPUP)
  1568. CCS->curh->hide();
  1569. if (background)
  1570. pos = background->center(centerAt);
  1571. else
  1572. center(centerAt);
  1573. if (!(options & SHADOW_DISABLED))
  1574. setShadow(true);
  1575. }
  1576. CWindowObject::CWindowObject(int options_, std::string imageName):
  1577. CIntObject(getUsedEvents(options_), Point()),
  1578. shadow(nullptr),
  1579. options(options_),
  1580. background(createBg(imageName, options & PLAYER_COLORED))
  1581. {
  1582. assert(parent == nullptr); //Safe to remove, but windows should not have parent
  1583. if (options & RCLICK_POPUP)
  1584. CCS->curh->hide();
  1585. if (background)
  1586. pos = background->center();
  1587. else
  1588. center(Point(screen->w/2, screen->h/2));
  1589. if (!(options & SHADOW_DISABLED))
  1590. setShadow(true);
  1591. }
  1592. CWindowObject::~CWindowObject()
  1593. {
  1594. setShadow(false);
  1595. }
  1596. CPicture * CWindowObject::createBg(std::string imageName, bool playerColored)
  1597. {
  1598. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1599. if (imageName.empty())
  1600. return nullptr;
  1601. auto image = new CPicture(imageName);
  1602. if (playerColored)
  1603. image->colorize(LOCPLINT->playerID);
  1604. return image;
  1605. }
  1606. void CWindowObject::setBackground(std::string filename)
  1607. {
  1608. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1609. delete background;
  1610. background = createBg(filename, options & PLAYER_COLORED);
  1611. if (background)
  1612. pos = background->center(Point(pos.w/2 + pos.x, pos.h/2 + pos.y));
  1613. updateShadow();
  1614. }
  1615. int CWindowObject::getUsedEvents(int options)
  1616. {
  1617. if (options & RCLICK_POPUP)
  1618. return RCLICK;
  1619. return 0;
  1620. }
  1621. void CWindowObject::updateShadow()
  1622. {
  1623. setShadow(false);
  1624. if (!(options & SHADOW_DISABLED))
  1625. setShadow(true);
  1626. }
  1627. void CWindowObject::setShadow(bool on)
  1628. {
  1629. //size of shadow
  1630. static const int size = 8;
  1631. if (on == bool(shadow))
  1632. return;
  1633. vstd::clear_pointer(shadow);
  1634. //object too small to cast shadow
  1635. if (pos.h <= size || pos.w <= size)
  1636. return;
  1637. if (on)
  1638. {
  1639. //helper to set last row
  1640. auto blitAlphaRow = [](SDL_Surface *surf, size_t row)
  1641. {
  1642. Uint8 * ptr = (Uint8*)surf->pixels + surf->pitch * (row);
  1643. for (size_t i=0; i< surf->w; i++)
  1644. {
  1645. Channels::px<4>::a.set(ptr, 128);
  1646. ptr+=4;
  1647. }
  1648. };
  1649. // helper to set last column
  1650. auto blitAlphaCol = [](SDL_Surface *surf, size_t col)
  1651. {
  1652. Uint8 * ptr = (Uint8*)surf->pixels + 4 * (col);
  1653. for (size_t i=0; i< surf->h; i++)
  1654. {
  1655. Channels::px<4>::a.set(ptr, 128);
  1656. ptr+= surf->pitch;
  1657. }
  1658. };
  1659. static SDL_Surface * shadowCornerTempl = nullptr;
  1660. static SDL_Surface * shadowBottomTempl = nullptr;
  1661. static SDL_Surface * shadowRightTempl = nullptr;
  1662. //one-time initialization
  1663. if (!shadowCornerTempl)
  1664. {
  1665. //create "template" surfaces
  1666. shadowCornerTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, size);
  1667. shadowBottomTempl = CSDL_Ext::createSurfaceWithBpp<4>(1, size);
  1668. shadowRightTempl = CSDL_Ext::createSurfaceWithBpp<4>(size, 1);
  1669. Uint32 shadowColor = SDL_MapRGBA(shadowCornerTempl->format, 0, 0, 0, 192);
  1670. //fill with shadow body color
  1671. SDL_FillRect(shadowCornerTempl, nullptr, shadowColor);
  1672. SDL_FillRect(shadowBottomTempl, nullptr, shadowColor);
  1673. SDL_FillRect(shadowRightTempl, nullptr, shadowColor);
  1674. //fill last row and column with more transparent color
  1675. blitAlphaCol(shadowRightTempl , size-1);
  1676. blitAlphaCol(shadowCornerTempl, size-1);
  1677. blitAlphaRow(shadowBottomTempl, size-1);
  1678. blitAlphaRow(shadowCornerTempl, size-1);
  1679. }
  1680. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1681. //FIXME: do something with this points
  1682. Point shadowStart;
  1683. if (options & BORDERED)
  1684. shadowStart = Point(size - 14, size - 14);
  1685. else
  1686. shadowStart = Point(size, size);
  1687. Point shadowPos;
  1688. if (options & BORDERED)
  1689. shadowPos = Point(pos.w + 14, pos.h + 14);
  1690. else
  1691. shadowPos = Point(pos.w, pos.h);
  1692. Point fullsize;
  1693. if (options & BORDERED)
  1694. fullsize = Point(pos.w + 28, pos.h + 29);
  1695. else
  1696. fullsize = Point(pos.w, pos.h);
  1697. //create base 8x8 piece of shadow
  1698. SDL_Surface * shadowCorner = CSDL_Ext::copySurface(shadowCornerTempl);
  1699. SDL_Surface * shadowBottom = CSDL_Ext::scaleSurfaceFast(shadowBottomTempl, fullsize.x - size, size);
  1700. SDL_Surface * shadowRight = CSDL_Ext::scaleSurfaceFast(shadowRightTempl, size, fullsize.y - size);
  1701. blitAlphaCol(shadowBottom, 0);
  1702. blitAlphaRow(shadowRight, 0);
  1703. //generate "shadow" object with these 3 pieces in it
  1704. shadow = new CIntObject;
  1705. shadow->addChild(new CPicture(shadowCorner, shadowPos.x, shadowPos.y));
  1706. shadow->addChild(new CPicture(shadowRight, shadowPos.x, shadowStart.y));
  1707. shadow->addChild(new CPicture(shadowBottom, shadowStart.x, shadowPos.y));
  1708. }
  1709. }
  1710. void CWindowObject::showAll(SDL_Surface *to)
  1711. {
  1712. CIntObject::showAll(to);
  1713. if ((options & BORDERED) && (pos.h != to->h || pos.w != to->w))
  1714. CMessage::drawBorder(LOCPLINT ? LOCPLINT->playerID : PlayerColor(1), to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  1715. }
  1716. void CWindowObject::close()
  1717. {
  1718. GH.popIntTotally(this);
  1719. }
  1720. void CWindowObject::clickRight(tribool down, bool previousState)
  1721. {
  1722. close();
  1723. CCS->curh->show();
  1724. }