TextControls.cpp 15 KB

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