TextControls.cpp 14 KB

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