TextControls.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /*
  2. * TextControls.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "TextControls.h"
  12. #include "Buttons.h"
  13. #include "Images.h"
  14. #include "../CPlayerInterface.h"
  15. #include "../gui/CGuiHandler.h"
  16. #include "../windows/CMessage.h"
  17. #include "../adventureMap/CInGameConsole.h"
  18. #include "../../lib/CGeneralTextHandler.h"
  19. #ifdef VCMI_ANDROID
  20. #include "lib/CAndroidVMHelper.h"
  21. #endif
  22. std::list<CFocusable*> CFocusable::focusables;
  23. CFocusable * CFocusable::inputWithFocus;
  24. std::string CLabel::visibleText()
  25. {
  26. return text;
  27. }
  28. void CLabel::showAll(SDL_Surface * to)
  29. {
  30. CIntObject::showAll(to);
  31. if(!visibleText().empty())
  32. blitLine(to, pos, visibleText());
  33. }
  34. CLabel::CLabel(int x, int y, EFonts Font, ETextAlignment Align, const SDL_Color & Color, const std::string & Text)
  35. : CTextContainer(Align, Font, Color), text(Text)
  36. {
  37. type |= REDRAW_PARENT;
  38. autoRedraw = true;
  39. pos.x += x;
  40. pos.y += y;
  41. pos.w = pos.h = 0;
  42. if(alignment == ETextAlignment::TOPLEFT) // causes issues for MIDDLE
  43. {
  44. pos.w = (int)graphics->fonts[font]->getStringWidth(visibleText().c_str());
  45. pos.h = (int)graphics->fonts[font]->getLineHeight();
  46. }
  47. }
  48. Point CLabel::getBorderSize()
  49. {
  50. return Point(0, 0);
  51. }
  52. std::string CLabel::getText()
  53. {
  54. return text;
  55. }
  56. void CLabel::setAutoRedraw(bool value)
  57. {
  58. autoRedraw = value;
  59. }
  60. void CLabel::setText(const std::string & Txt)
  61. {
  62. text = Txt;
  63. if(autoRedraw)
  64. {
  65. if(background || !parent)
  66. redraw();
  67. else
  68. parent->redraw();
  69. }
  70. }
  71. void CLabel::setColor(const SDL_Color & Color)
  72. {
  73. color = Color;
  74. if(autoRedraw)
  75. {
  76. if(background || !parent)
  77. redraw();
  78. else
  79. parent->redraw();
  80. }
  81. }
  82. size_t CLabel::getWidth()
  83. {
  84. return graphics->fonts[font]->getStringWidth(visibleText());;
  85. }
  86. CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, ETextAlignment Align, const SDL_Color & Color, const std::string & Text) :
  87. CLabel(position.x, position.y, Font, Align, Color, Text),
  88. visibleSize(0, 0, position.w, position.h)
  89. {
  90. pos.w = position.w;
  91. pos.h = position.h;
  92. splitText(Text, true);
  93. }
  94. void CMultiLineLabel::setVisibleSize(Rect visibleSize, bool redrawElement)
  95. {
  96. this->visibleSize = visibleSize;
  97. if(redrawElement)
  98. redraw();
  99. }
  100. void CMultiLineLabel::scrollTextBy(int distance)
  101. {
  102. scrollTextTo(visibleSize.y + distance);
  103. }
  104. void CMultiLineLabel::scrollTextTo(int distance, bool redrawAfterScroll)
  105. {
  106. Rect size = visibleSize;
  107. size.y = distance;
  108. setVisibleSize(size, redrawAfterScroll);
  109. }
  110. void CMultiLineLabel::setText(const std::string & Txt)
  111. {
  112. splitText(Txt, false); //setText used below can handle redraw
  113. CLabel::setText(Txt);
  114. }
  115. void CTextContainer::blitLine(SDL_Surface * to, Rect destRect, std::string what)
  116. {
  117. const auto f = graphics->fonts[font];
  118. Point where = destRect.topLeft();
  119. // input is rect in which given text should be placed
  120. // calculate proper position for top-left corner of the text
  121. if(alignment == ETextAlignment::TOPLEFT)
  122. {
  123. where.x += getBorderSize().x;
  124. where.y += getBorderSize().y;
  125. }
  126. if(alignment == ETextAlignment::CENTER)
  127. {
  128. where.x += (int(destRect.w) - int(f->getStringWidth(what))) / 2;
  129. where.y += (int(destRect.h) - int(f->getLineHeight())) / 2;
  130. }
  131. if(alignment == ETextAlignment::BOTTOMRIGHT)
  132. {
  133. where.x += getBorderSize().x + destRect.w - (int)f->getStringWidth(what);
  134. where.y += getBorderSize().y + destRect.h - (int)f->getLineHeight();
  135. }
  136. size_t begin = 0;
  137. std::string delimeters = "{}";
  138. size_t currDelimeter = 0;
  139. do
  140. {
  141. size_t end = what.find_first_of(delimeters[currDelimeter % 2], begin);
  142. if(begin != end)
  143. {
  144. std::string toPrint = what.substr(begin, end - begin);
  145. if(currDelimeter % 2) // Enclosed in {} text - set to yellow
  146. f->renderTextLeft(to, toPrint, Colors::YELLOW, where);
  147. else // Non-enclosed text, use default color
  148. f->renderTextLeft(to, toPrint, color, where);
  149. begin = end;
  150. where.x += (int)f->getStringWidth(toPrint);
  151. }
  152. currDelimeter++;
  153. } while(begin++ != std::string::npos);
  154. }
  155. CTextContainer::CTextContainer(ETextAlignment alignment, EFonts font, SDL_Color color) :
  156. alignment(alignment),
  157. font(font),
  158. color(color)
  159. {
  160. }
  161. void CMultiLineLabel::showAll(SDL_Surface * to)
  162. {
  163. CIntObject::showAll(to);
  164. const auto f = graphics->fonts[font];
  165. // calculate which lines should be visible
  166. int totalLines = static_cast<int>(lines.size());
  167. int beginLine = visibleSize.y;
  168. int endLine = getTextLocation().h + visibleSize.y;
  169. if(beginLine < 0)
  170. beginLine = 0;
  171. else
  172. beginLine /= (int)f->getLineHeight();
  173. if(endLine < 0)
  174. endLine = 0;
  175. else
  176. endLine /= (int)f->getLineHeight();
  177. endLine++;
  178. // and where they should be displayed
  179. Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * (int)f->getLineHeight());
  180. Point lineSize = Point(getTextLocation().w, (int)f->getLineHeight());
  181. CSDL_Ext::CClipRectGuard guard(to, getTextLocation()); // to properly trim text that is too big to fit
  182. for(int i = beginLine; i < std::min(totalLines, endLine); i++)
  183. {
  184. if(!lines[i].empty()) //non-empty line
  185. blitLine(to, Rect(lineStart, lineSize), lines[i]);
  186. lineStart.y += (int)f->getLineHeight();
  187. }
  188. }
  189. void CMultiLineLabel::splitText(const std::string & Txt, bool redrawAfter)
  190. {
  191. lines.clear();
  192. const auto f = graphics->fonts[font];
  193. int lineHeight = static_cast<int>(f->getLineHeight());
  194. lines = CMessage::breakText(Txt, pos.w, font);
  195. textSize.y = lineHeight * (int)lines.size();
  196. textSize.x = 0;
  197. for(const std::string & line : lines)
  198. vstd::amax(textSize.x, f->getStringWidth(line.c_str()));
  199. if(redrawAfter)
  200. redraw();
  201. }
  202. Rect CMultiLineLabel::getTextLocation()
  203. {
  204. // this method is needed for vertical alignment alignment of text
  205. // when height of available text is smaller than height of widget
  206. // in this case - we should add proper offset to display text at required position
  207. if(pos.h <= textSize.y)
  208. return pos;
  209. Point textSize(pos.w, (int)graphics->fonts[font]->getLineHeight() * (int)lines.size());
  210. Point textOffset(pos.w - textSize.x, pos.h - textSize.y);
  211. switch(alignment)
  212. {
  213. case ETextAlignment::TOPLEFT: return Rect(pos.topLeft(), textSize);
  214. case ETextAlignment::CENTER: return Rect(pos.topLeft() + textOffset / 2, textSize);
  215. case ETextAlignment::BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
  216. }
  217. assert(0);
  218. return Rect();
  219. }
  220. CLabelGroup::CLabelGroup(EFonts Font, ETextAlignment Align, const SDL_Color & Color)
  221. : font(Font), align(Align), color(Color)
  222. {
  223. defActions = 255 - DISPOSE;
  224. }
  225. void CLabelGroup::add(int x, int y, const std::string & text)
  226. {
  227. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255 - DISPOSE);
  228. labels.push_back(std::make_shared<CLabel>(x, y, font, align, color, text));
  229. }
  230. size_t CLabelGroup::currentSize() const
  231. {
  232. return labels.size();
  233. }
  234. CTextBox::CTextBox(std::string Text, const Rect & rect, int SliderStyle, EFonts Font, ETextAlignment Align, const SDL_Color & Color) :
  235. sliderStyle(SliderStyle),
  236. slider(nullptr)
  237. {
  238. OBJECT_CONSTRUCTION_CAPTURING(255 - DISPOSE);
  239. label = std::make_shared<CMultiLineLabel>(rect, Font, Align, Color);
  240. type |= REDRAW_PARENT;
  241. pos.x += rect.x;
  242. pos.y += rect.y;
  243. pos.h = rect.h;
  244. pos.w = rect.w;
  245. assert(pos.w >= 40); //we need some space
  246. setText(Text);
  247. }
  248. void CTextBox::sliderMoved(int to)
  249. {
  250. label->scrollTextTo(to);
  251. }
  252. void CTextBox::resize(Point newSize)
  253. {
  254. pos.w = newSize.x;
  255. pos.h = newSize.y;
  256. label->pos.w = pos.w;
  257. label->pos.h = pos.h;
  258. slider.reset();
  259. setText(label->getText()); // force refresh
  260. }
  261. void CTextBox::setText(const std::string & text)
  262. {
  263. label->pos.w = pos.w; // reset to default before textSize.y check
  264. label->setText(text);
  265. if(label->textSize.y <= label->pos.h && slider)
  266. {
  267. // slider is no longer needed
  268. slider.reset();
  269. }
  270. else if(slider)
  271. {
  272. // decrease width again if slider still used
  273. label->pos.w = pos.w - 32;
  274. label->setText(text);
  275. slider->setAmount(label->textSize.y);
  276. }
  277. else if(label->textSize.y > label->pos.h)
  278. {
  279. // create slider and update widget
  280. label->pos.w = pos.w - 32;
  281. label->setText(text);
  282. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255 - DISPOSE);
  283. slider = std::make_shared<CSlider>(Point(pos.w - 32, 0), pos.h, std::bind(&CTextBox::sliderMoved, this, _1),
  284. label->pos.h, label->textSize.y, 0, false, CSlider::EStyle(sliderStyle));
  285. slider->setScrollStep((int)graphics->fonts[label->font]->getLineHeight());
  286. }
  287. }
  288. void CGStatusBar::setEnteringMode(bool on)
  289. {
  290. consoleText.clear();
  291. if (on)
  292. {
  293. assert(enteringText == false);
  294. alignment = ETextAlignment::TOPLEFT;
  295. GH.startTextInput(pos);
  296. setText(consoleText);
  297. }
  298. else
  299. {
  300. assert(enteringText == true);
  301. alignment = ETextAlignment::CENTER;
  302. GH.stopTextInput();
  303. setText(hoverText);
  304. }
  305. enteringText = on;
  306. }
  307. void CGStatusBar::setEnteredText(const std::string & text)
  308. {
  309. assert(enteringText == true);
  310. consoleText = text;
  311. setText(text);
  312. }
  313. void CGStatusBar::write(const std::string & Text)
  314. {
  315. hoverText = Text;
  316. if (enteringText == false)
  317. setText(hoverText);
  318. }
  319. void CGStatusBar::clearIfMatching(const std::string & Text)
  320. {
  321. if (hoverText == Text)
  322. clear();
  323. }
  324. void CGStatusBar::clear()
  325. {
  326. write({});
  327. }
  328. CGStatusBar::CGStatusBar(std::shared_ptr<CPicture> background_, EFonts Font, ETextAlignment Align, const SDL_Color & Color)
  329. : CLabel(background_->pos.x, background_->pos.y, Font, Align, Color, "")
  330. , enteringText(false)
  331. {
  332. addUsedEvents(LCLICK);
  333. background = background_;
  334. addChild(background.get());
  335. pos = background->pos;
  336. getBorderSize();
  337. autoRedraw = false;
  338. }
  339. CGStatusBar::CGStatusBar(int x, int y, std::string name, int maxw)
  340. : CLabel(x, y, FONT_SMALL, ETextAlignment::CENTER)
  341. , enteringText(false)
  342. {
  343. addUsedEvents(LCLICK);
  344. OBJECT_CONSTRUCTION_CAPTURING(255 - DISPOSE);
  345. background = std::make_shared<CPicture>(name);
  346. pos = background->pos;
  347. if((unsigned)maxw < (unsigned)pos.w) //(insigned)-1 > than any correct value of pos.w
  348. {
  349. //execution of this block when maxw is incorrect breaks text centralization (issue #3151)
  350. vstd::amin(pos.w, maxw);
  351. background->srcRect = Rect(0, 0, maxw, pos.h);
  352. }
  353. autoRedraw = false;
  354. }
  355. void CGStatusBar::show(SDL_Surface * to)
  356. {
  357. showAll(to);
  358. }
  359. void CGStatusBar::init()
  360. {
  361. GH.statusbar = shared_from_this();
  362. }
  363. void CGStatusBar::clickLeft(tribool down, bool previousState)
  364. {
  365. if(!down)
  366. {
  367. if(LOCPLINT && LOCPLINT->cingconsole->active)
  368. LOCPLINT->cingconsole->startEnteringText();
  369. }
  370. }
  371. void CGStatusBar::deactivate()
  372. {
  373. if (enteringText)
  374. LOCPLINT->cingconsole->endEnteringText(false);
  375. CIntObject::deactivate();
  376. }
  377. Point CGStatusBar::getBorderSize()
  378. {
  379. //Width of borders where text should not be printed
  380. static const Point borderSize(5, 1);
  381. switch(alignment)
  382. {
  383. case ETextAlignment::TOPLEFT: return Point(borderSize.x, borderSize.y);
  384. case ETextAlignment::CENTER: return Point(pos.w / 2, pos.h / 2);
  385. case ETextAlignment::BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
  386. }
  387. assert(0);
  388. return Point();
  389. }
  390. CTextInput::CTextInput(const Rect & Pos, EFonts font, const CFunctionList<void(const std::string &)> & CB)
  391. : CLabel(Pos.x, Pos.y, font, ETextAlignment::CENTER),
  392. cb(CB),
  393. CFocusable(std::make_shared<CKeyboardFocusListener>(this))
  394. {
  395. type |= REDRAW_PARENT;
  396. pos.h = Pos.h;
  397. pos.w = Pos.w;
  398. captureAllKeys = true;
  399. background.reset();
  400. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  401. #if !(defined(VCMI_ANDROID) || defined(VCMI_IOS))
  402. giveFocus();
  403. #endif
  404. }
  405. CTextInput::CTextInput(const Rect & Pos, const Point & bgOffset, const std::string & bgName, const CFunctionList<void(const std::string &)> & CB)
  406. :cb(CB), CFocusable(std::make_shared<CKeyboardFocusListener>(this))
  407. {
  408. pos += Pos.topLeft();
  409. pos.h = Pos.h;
  410. pos.w = Pos.w;
  411. captureAllKeys = true;
  412. OBJ_CONSTRUCTION;
  413. background = std::make_shared<CPicture>(bgName, bgOffset.x, bgOffset.y);
  414. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  415. #if !(defined(VCMI_ANDROID) || defined(VCMI_IOS))
  416. giveFocus();
  417. #endif
  418. }
  419. CTextInput::CTextInput(const Rect & Pos, std::shared_ptr<IImage> srf)
  420. :CFocusable(std::make_shared<CKeyboardFocusListener>(this))
  421. {
  422. pos += Pos.topLeft();
  423. captureAllKeys = true;
  424. OBJ_CONSTRUCTION;
  425. background = std::make_shared<CPicture>(srf, Pos);
  426. pos.w = background->pos.w;
  427. pos.h = background->pos.h;
  428. background->pos = pos;
  429. addUsedEvents(LCLICK | KEYBOARD | TEXTINPUT);
  430. #if !(defined(VCMI_ANDROID) || defined(VCMI_IOS))
  431. giveFocus();
  432. #endif
  433. }
  434. std::atomic<int> CKeyboardFocusListener::usageIndex(0);
  435. CKeyboardFocusListener::CKeyboardFocusListener(CTextInput * textInput)
  436. :textInput(textInput)
  437. {
  438. }
  439. void CKeyboardFocusListener::focusGot()
  440. {
  441. GH.startTextInput(textInput->pos);
  442. usageIndex++;
  443. }
  444. void CKeyboardFocusListener::focusLost()
  445. {
  446. if(0 == --usageIndex)
  447. {
  448. GH.stopTextInput();
  449. }
  450. }
  451. std::string CTextInput::visibleText()
  452. {
  453. return focus ? text + newText + "_" : text;
  454. }
  455. void CTextInput::clickLeft(tribool down, bool previousState)
  456. {
  457. if(down && !focus)
  458. giveFocus();
  459. }
  460. void CTextInput::keyPressed(const SDL_Keycode & key)
  461. {
  462. if(!focus)
  463. return;
  464. if(key == SDLK_TAB)
  465. {
  466. moveFocus();
  467. GH.breakEventHandling();
  468. return;
  469. }
  470. bool redrawNeeded = false;
  471. switch(key)
  472. {
  473. case SDLK_DELETE: // have index > ' ' so it won't be filtered out by default section
  474. return;
  475. case SDLK_BACKSPACE:
  476. if(!newText.empty())
  477. {
  478. Unicode::trimRight(newText);
  479. redrawNeeded = true;
  480. }
  481. else if(!text.empty())
  482. {
  483. Unicode::trimRight(text);
  484. redrawNeeded = true;
  485. }
  486. break;
  487. default:
  488. break;
  489. }
  490. if(redrawNeeded)
  491. {
  492. redraw();
  493. cb(text);
  494. }
  495. }
  496. void CTextInput::setText(const std::string & nText)
  497. {
  498. setText(nText, false);
  499. }
  500. void CTextInput::setText(const std::string & nText, bool callCb)
  501. {
  502. CLabel::setText(nText);
  503. if(callCb)
  504. cb(text);
  505. }
  506. bool CTextInput::captureThisKey(const SDL_Keycode & key)
  507. {
  508. if(key == SDLK_RETURN || key == SDLK_KP_ENTER || key == SDLK_ESCAPE)
  509. return false;
  510. return true;
  511. }
  512. void CTextInput::textInputed(const std::string & enteredText)
  513. {
  514. if(!focus)
  515. return;
  516. std::string oldText = text;
  517. text += enteredText;
  518. filters(text, oldText);
  519. if(text != oldText)
  520. {
  521. redraw();
  522. cb(text);
  523. }
  524. newText.clear();
  525. }
  526. void CTextInput::textEdited(const std::string & enteredText)
  527. {
  528. if(!focus)
  529. return;
  530. newText = enteredText;
  531. redraw();
  532. cb(text + newText);
  533. }
  534. void CTextInput::filenameFilter(std::string & text, const std::string &)
  535. {
  536. static const std::string forbiddenChars = "<>:\"/\\|?*\r\n"; //if we are entering a filename, some special characters won't be allowed
  537. size_t pos;
  538. while((pos = text.find_first_of(forbiddenChars)) != std::string::npos)
  539. text.erase(pos, 1);
  540. }
  541. void CTextInput::numberFilter(std::string & text, const std::string & oldText, int minValue, int maxValue)
  542. {
  543. assert(minValue < maxValue);
  544. if(text.empty())
  545. text = "0";
  546. size_t pos = 0;
  547. if(text[0] == '-') //allow '-' sign as first symbol only
  548. pos++;
  549. while(pos < text.size())
  550. {
  551. if(text[pos] < '0' || text[pos] > '9')
  552. {
  553. text = oldText;
  554. return; //new text is not number.
  555. }
  556. pos++;
  557. }
  558. try
  559. {
  560. int value = boost::lexical_cast<int>(text);
  561. if(value < minValue)
  562. text = boost::lexical_cast<std::string>(minValue);
  563. else if(value > maxValue)
  564. text = boost::lexical_cast<std::string>(maxValue);
  565. }
  566. catch(boost::bad_lexical_cast &)
  567. {
  568. //Should never happen. Unless I missed some cases
  569. logGlobal->warn("Warning: failed to convert %s to number!", text);
  570. text = oldText;
  571. }
  572. }
  573. CFocusable::CFocusable()
  574. :CFocusable(std::make_shared<IFocusListener>())
  575. {
  576. }
  577. CFocusable::CFocusable(std::shared_ptr<IFocusListener> focusListener)
  578. : focusListener(focusListener)
  579. {
  580. focus = false;
  581. focusables.push_back(this);
  582. }
  583. CFocusable::~CFocusable()
  584. {
  585. if(hasFocus())
  586. {
  587. inputWithFocus = nullptr;
  588. focusListener->focusLost();
  589. }
  590. focusables -= this;
  591. }
  592. bool CFocusable::hasFocus() const
  593. {
  594. return inputWithFocus == this;
  595. }
  596. void CFocusable::giveFocus()
  597. {
  598. focus = true;
  599. focusListener->focusGot();
  600. redraw();
  601. if(inputWithFocus)
  602. {
  603. inputWithFocus->focus = false;
  604. inputWithFocus->focusListener->focusLost();
  605. inputWithFocus->redraw();
  606. }
  607. inputWithFocus = this;
  608. }
  609. void CFocusable::moveFocus()
  610. {
  611. auto i = vstd::find(focusables, this),
  612. ourIt = i;
  613. for(i++; i != ourIt; i++)
  614. {
  615. if(i == focusables.end())
  616. i = focusables.begin();
  617. if((*i)->active)
  618. {
  619. (*i)->giveFocus();
  620. break;
  621. }
  622. }
  623. }