TextControls.cpp 14 KB

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