Text.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Texture2D.h"
  26. #include "../IO/Log.h"
  27. #include "../Resource/ResourceCache.h"
  28. #include "../UI/Font.h"
  29. #include "../UI/FontFace.h"
  30. #include "../UI/Text.h"
  31. #include "../Resource/Localization.h"
  32. #include "../Resource/ResourceEvents.h"
  33. #include "../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. const char* textEffects[] =
  37. {
  38. "None",
  39. "Shadow",
  40. "Stroke",
  41. nullptr
  42. };
  43. static const float MIN_ROW_SPACING = 0.5f;
  44. extern const char* horizontalAlignments[];
  45. extern const char* UI_CATEGORY;
  46. Text::Text(Context* context) :
  47. UISelectable(context),
  48. fontSize_(DEFAULT_FONT_SIZE),
  49. textAlignment_(HA_LEFT),
  50. rowSpacing_(1.0f),
  51. wordWrap_(false),
  52. autoLocalizable_(false),
  53. charLocationsDirty_(true),
  54. selectionStart_(0),
  55. selectionLength_(0),
  56. textEffect_(TE_NONE),
  57. shadowOffset_(IntVector2(1, 1)),
  58. strokeThickness_(1),
  59. roundStroke_(false),
  60. effectColor_(Color::BLACK),
  61. effectDepthBias_(0.0f),
  62. rowHeight_(0)
  63. {
  64. // By default Text does not derive opacity from parent elements
  65. useDerivedOpacity_ = false;
  66. }
  67. Text::~Text() = default;
  68. void Text::RegisterObject(Context* context)
  69. {
  70. context->RegisterFactory<Text>(UI_CATEGORY);
  71. URHO3D_COPY_BASE_ATTRIBUTES(UISelectable);
  72. URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Use Derived Opacity", false);
  73. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  74. URHO3D_ATTRIBUTE("Font Size", float, fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  75. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Text", GetTextAttr, SetTextAttr, String, String::EMPTY, AM_FILE);
  76. URHO3D_ENUM_ATTRIBUTE("Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  77. URHO3D_ATTRIBUTE("Row Spacing", float, rowSpacing_, 1.0f, AM_FILE);
  78. URHO3D_ATTRIBUTE("Word Wrap", bool, wordWrap_, false, AM_FILE);
  79. URHO3D_ACCESSOR_ATTRIBUTE("Auto Localizable", GetAutoLocalizable, SetAutoLocalizable, bool, false, AM_FILE);
  80. URHO3D_ENUM_ATTRIBUTE("Text Effect", textEffect_, textEffects, TE_NONE, AM_FILE);
  81. URHO3D_ATTRIBUTE("Shadow Offset", IntVector2, shadowOffset_, IntVector2(1, 1), AM_FILE);
  82. URHO3D_ATTRIBUTE("Stroke Thickness", int, strokeThickness_, 1, AM_FILE);
  83. URHO3D_ATTRIBUTE("Round Stroke", bool, roundStroke_, false, AM_FILE);
  84. URHO3D_ACCESSOR_ATTRIBUTE("Effect Color", GetEffectColor, SetEffectColor, Color, Color::BLACK, AM_FILE);
  85. // Change the default value for UseDerivedOpacity
  86. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  87. }
  88. void Text::ApplyAttributes()
  89. {
  90. UISelectable::ApplyAttributes();
  91. // Localize now if attributes were loaded out-of-order
  92. if (autoLocalizable_ && stringId_.Length())
  93. {
  94. auto* l10n = GetSubsystem<Localization>();
  95. text_ = l10n->Get(stringId_);
  96. }
  97. DecodeToUnicode();
  98. fontSize_ = Max(fontSize_, 1);
  99. strokeThickness_ = Abs(strokeThickness_);
  100. ValidateSelection();
  101. UpdateText();
  102. }
  103. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  104. {
  105. FontFace* face = font_ ? font_->GetFace(fontSize_) : nullptr;
  106. if (!face)
  107. {
  108. hovering_ = false;
  109. return;
  110. }
  111. // If face has changed or char locations are not valid anymore, update before rendering
  112. if (charLocationsDirty_ || !fontFace_ || face != fontFace_)
  113. UpdateCharLocations();
  114. // If face uses mutable glyphs mechanism, reacquire glyphs before rendering to make sure they are in the texture
  115. else if (face->HasMutableGlyphs())
  116. {
  117. for (unsigned i = 0; i < printText_.Size(); ++i)
  118. face->GetGlyph(printText_[i]);
  119. }
  120. // Hovering and/or whole selection batch
  121. UISelectable::GetBatches(batches, vertexData, currentScissor);
  122. // Partial selection batch
  123. if (!selected_ && selectionLength_ && charLocations_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  124. {
  125. UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
  126. batch.SetColor(selectionColor_);
  127. Vector2 currentStart = charLocations_[selectionStart_].position_;
  128. Vector2 currentEnd = currentStart;
  129. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  130. {
  131. // Check if row changes, and start a new quad in that case
  132. if (charLocations_[i].size_ != Vector2::ZERO)
  133. {
  134. if (charLocations_[i].position_.y_ != currentStart.y_)
  135. {
  136. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_,
  137. currentEnd.y_ - currentStart.y_, 0, 0);
  138. currentStart = charLocations_[i].position_;
  139. currentEnd = currentStart + charLocations_[i].size_;
  140. }
  141. else
  142. {
  143. currentEnd.x_ += charLocations_[i].size_.x_;
  144. currentEnd.y_ = Max(currentStart.y_ + charLocations_[i].size_.y_, currentEnd.y_);
  145. }
  146. }
  147. }
  148. if (currentEnd != currentStart)
  149. {
  150. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_, 0, 0);
  151. }
  152. UIBatch::AddOrMerge(batch, batches);
  153. }
  154. // Text batch
  155. TextEffect textEffect = font_->IsSDFFont() ? TE_NONE : textEffect_;
  156. const Vector<SharedPtr<Texture2D> >& textures = face->GetTextures();
  157. for (unsigned n = 0; n < textures.Size() && n < pageGlyphLocations_.Size(); ++n)
  158. {
  159. // One batch per texture/page
  160. UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, textures[n], &vertexData);
  161. const PODVector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations_[n];
  162. switch (textEffect)
  163. {
  164. case TE_NONE:
  165. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  166. break;
  167. case TE_SHADOW:
  168. ConstructBatch(pageBatch, pageGlyphLocation, shadowOffset_.x_, shadowOffset_.y_, &effectColor_, effectDepthBias_);
  169. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  170. break;
  171. case TE_STROKE:
  172. if (roundStroke_)
  173. {
  174. // Samples should be even or glyph may be redrawn in wrong x y pos making stroke corners rough
  175. // Adding to thickness helps with thickness of 1 not having enought samples for this formula
  176. // or certain fonts with reflex corners requiring more glyph samples for a smooth stroke when large
  177. int thickness = Min(strokeThickness_, fontSize_);
  178. int samples = thickness * thickness + (thickness % 2 == 0 ? 4 : 3);
  179. float angle = 360.f / samples;
  180. auto floatThickness = (float)thickness;
  181. for (int i = 0; i < samples; ++i)
  182. {
  183. float x = Cos(angle * i) * floatThickness;
  184. float y = Sin(angle * i) * floatThickness;
  185. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  186. }
  187. }
  188. else
  189. {
  190. int thickness = Min(strokeThickness_, fontSize_);
  191. int x, y;
  192. for (x = -thickness; x <= thickness; ++x)
  193. {
  194. for (y = -thickness; y <= thickness; ++y)
  195. {
  196. // Don't draw glyphs that aren't on the edges
  197. if (x > -thickness && x < thickness &&
  198. y > -thickness && y < thickness)
  199. continue;
  200. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  201. }
  202. }
  203. }
  204. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  205. break;
  206. }
  207. UIBatch::AddOrMerge(pageBatch, batches);
  208. }
  209. }
  210. void Text::OnResize(const IntVector2& newSize, const IntVector2& delta)
  211. {
  212. if (wordWrap_)
  213. UpdateText(true);
  214. else
  215. charLocationsDirty_ = true;
  216. }
  217. void Text::OnIndentSet()
  218. {
  219. charLocationsDirty_ = true;
  220. }
  221. bool Text::SetFont(const String& fontName, float size)
  222. {
  223. auto* cache = GetSubsystem<ResourceCache>();
  224. return SetFont(cache->GetResource<Font>(fontName), size);
  225. }
  226. bool Text::SetFont(Font* font, float size)
  227. {
  228. if (!font)
  229. {
  230. URHO3D_LOGERROR("Null font for Text");
  231. return false;
  232. }
  233. if (font != font_ || size != fontSize_)
  234. {
  235. font_ = font;
  236. fontSize_ = Max(size, 1);
  237. UpdateText();
  238. }
  239. return true;
  240. }
  241. bool Text::SetFontSize(float size)
  242. {
  243. // Initial font must be set
  244. if (!font_)
  245. return false;
  246. else
  247. return SetFont(font_, size);
  248. }
  249. void Text::DecodeToUnicode()
  250. {
  251. unicodeText_.Clear();
  252. for (unsigned i = 0; i < text_.Length();)
  253. unicodeText_.Push(text_.NextUTF8Char(i));
  254. }
  255. void Text::SetText(const String& text)
  256. {
  257. if (autoLocalizable_)
  258. {
  259. stringId_ = text;
  260. auto* l10n = GetSubsystem<Localization>();
  261. text_ = l10n->Get(stringId_);
  262. }
  263. else
  264. {
  265. text_ = text;
  266. }
  267. DecodeToUnicode();
  268. ValidateSelection();
  269. UpdateText();
  270. }
  271. void Text::SetTextAlignment(HorizontalAlignment align)
  272. {
  273. if (align != textAlignment_)
  274. {
  275. textAlignment_ = align;
  276. charLocationsDirty_ = true;
  277. }
  278. }
  279. void Text::SetRowSpacing(float spacing)
  280. {
  281. if (spacing != rowSpacing_)
  282. {
  283. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  284. UpdateText();
  285. }
  286. }
  287. void Text::SetWordwrap(bool enable)
  288. {
  289. if (enable != wordWrap_)
  290. {
  291. wordWrap_ = enable;
  292. UpdateText();
  293. }
  294. }
  295. void Text::SetAutoLocalizable(bool enable)
  296. {
  297. if (enable != autoLocalizable_)
  298. {
  299. autoLocalizable_ = enable;
  300. if (enable)
  301. {
  302. stringId_ = text_;
  303. auto* l10n = GetSubsystem<Localization>();
  304. text_ = l10n->Get(stringId_);
  305. SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Text, HandleChangeLanguage));
  306. }
  307. else
  308. {
  309. text_ = stringId_;
  310. stringId_ = "";
  311. UnsubscribeFromEvent(E_CHANGELANGUAGE);
  312. }
  313. DecodeToUnicode();
  314. ValidateSelection();
  315. UpdateText();
  316. }
  317. }
  318. void Text::HandleChangeLanguage(StringHash eventType, VariantMap& eventData)
  319. {
  320. auto* l10n = GetSubsystem<Localization>();
  321. text_ = l10n->Get(stringId_);
  322. DecodeToUnicode();
  323. ValidateSelection();
  324. UpdateText();
  325. }
  326. void Text::SetSelection(unsigned start, unsigned length)
  327. {
  328. selectionStart_ = start;
  329. selectionLength_ = length;
  330. ValidateSelection();
  331. }
  332. void Text::ClearSelection()
  333. {
  334. selectionStart_ = 0;
  335. selectionLength_ = 0;
  336. }
  337. void Text::SetTextEffect(TextEffect textEffect)
  338. {
  339. textEffect_ = textEffect;
  340. }
  341. void Text::SetEffectShadowOffset(const IntVector2& offset)
  342. {
  343. shadowOffset_ = offset;
  344. }
  345. void Text::SetEffectStrokeThickness(int thickness)
  346. {
  347. strokeThickness_ = Abs(thickness);
  348. }
  349. void Text::SetEffectRoundStroke(bool roundStroke)
  350. {
  351. roundStroke_ = roundStroke;
  352. }
  353. void Text::SetEffectColor(const Color& effectColor)
  354. {
  355. effectColor_ = effectColor;
  356. }
  357. void Text::SetEffectDepthBias(float bias)
  358. {
  359. effectDepthBias_ = bias;
  360. }
  361. float Text::GetRowWidth(unsigned index) const
  362. {
  363. return index < rowWidths_.Size() ? rowWidths_[index] : 0;
  364. }
  365. Vector2 Text::GetCharPosition(unsigned index)
  366. {
  367. if (charLocationsDirty_)
  368. UpdateCharLocations();
  369. if (charLocations_.Empty())
  370. return Vector2::ZERO;
  371. // For convenience, return the position of the text ending if index exceeded
  372. if (index > charLocations_.Size() - 1)
  373. index = charLocations_.Size() - 1;
  374. return charLocations_[index].position_;
  375. }
  376. Vector2 Text::GetCharSize(unsigned index)
  377. {
  378. if (charLocationsDirty_)
  379. UpdateCharLocations();
  380. if (charLocations_.Size() < 2)
  381. return Vector2::ZERO;
  382. // For convenience, return the size of the last char if index exceeded (last size entry is zero)
  383. if (index > charLocations_.Size() - 2)
  384. index = charLocations_.Size() - 2;
  385. return charLocations_[index].size_;
  386. }
  387. void Text::SetFontAttr(const ResourceRef& value)
  388. {
  389. auto* cache = GetSubsystem<ResourceCache>();
  390. font_ = cache->GetResource<Font>(value.name_);
  391. }
  392. ResourceRef Text::GetFontAttr() const
  393. {
  394. return GetResourceRef(font_, Font::GetTypeStatic());
  395. }
  396. void Text::SetTextAttr(const String& value)
  397. {
  398. text_ = value;
  399. if (autoLocalizable_)
  400. stringId_ = value;
  401. }
  402. String Text::GetTextAttr() const
  403. {
  404. if (autoLocalizable_ && stringId_.Length())
  405. return stringId_;
  406. else
  407. return text_;
  408. }
  409. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  410. {
  411. if (!UISelectable::FilterImplicitAttributes(dest))
  412. return false;
  413. if (!IsFixedWidth())
  414. {
  415. if (!RemoveChildXML(dest, "Size"))
  416. return false;
  417. if (!RemoveChildXML(dest, "Min Size"))
  418. return false;
  419. if (!RemoveChildXML(dest, "Max Size"))
  420. return false;
  421. }
  422. return true;
  423. }
  424. void Text::UpdateText(bool onResize)
  425. {
  426. rowWidths_.Clear();
  427. printText_.Clear();
  428. if (font_)
  429. {
  430. FontFace* face = font_->GetFace(fontSize_);
  431. if (!face)
  432. return;
  433. rowHeight_ = face->GetRowHeight();
  434. int width = 0;
  435. int height = 0;
  436. int rowWidth = 0;
  437. auto rowHeight = RoundToInt(rowSpacing_ * rowHeight_);
  438. // First see if the text must be split up
  439. if (!wordWrap_)
  440. {
  441. printText_ = unicodeText_;
  442. printToText_.Resize(printText_.Size());
  443. for (unsigned i = 0; i < printText_.Size(); ++i)
  444. printToText_[i] = i;
  445. }
  446. else
  447. {
  448. int maxWidth = GetWidth();
  449. unsigned nextBreak = 0;
  450. unsigned lineStart = 0;
  451. printToText_.Clear();
  452. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  453. {
  454. unsigned j;
  455. unsigned c = unicodeText_[i];
  456. if (c != '\n')
  457. {
  458. bool ok = true;
  459. if (nextBreak <= i)
  460. {
  461. int futureRowWidth = rowWidth;
  462. for (j = i; j < unicodeText_.Size(); ++j)
  463. {
  464. unsigned d = unicodeText_[j];
  465. if (d == ' ' || d == '\n')
  466. {
  467. nextBreak = j;
  468. break;
  469. }
  470. const FontGlyph* glyph = face->GetGlyph(d);
  471. if (glyph)
  472. {
  473. futureRowWidth += glyph->advanceX_;
  474. if (j < unicodeText_.Size() - 1)
  475. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  476. }
  477. if (d == '-' && futureRowWidth <= maxWidth)
  478. {
  479. nextBreak = j + 1;
  480. break;
  481. }
  482. if (futureRowWidth > maxWidth)
  483. {
  484. ok = false;
  485. break;
  486. }
  487. }
  488. }
  489. if (!ok)
  490. {
  491. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  492. if (nextBreak == lineStart)
  493. {
  494. while (i < j)
  495. {
  496. printText_.Push(unicodeText_[i]);
  497. printToText_.Push(i);
  498. ++i;
  499. }
  500. }
  501. // Eliminate spaces that have been copied before the forced break
  502. while (printText_.Size() && printText_.Back() == ' ')
  503. {
  504. printText_.Pop();
  505. printToText_.Pop();
  506. }
  507. printText_.Push('\n');
  508. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  509. rowWidth = 0;
  510. nextBreak = lineStart = i;
  511. }
  512. if (i < unicodeText_.Size())
  513. {
  514. // When copying a space, position is allowed to be over row width
  515. c = unicodeText_[i];
  516. const FontGlyph* glyph = face->GetGlyph(c);
  517. if (glyph)
  518. {
  519. rowWidth += glyph->advanceX_;
  520. if (i < unicodeText_.Size() - 1)
  521. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  522. }
  523. if (rowWidth <= maxWidth)
  524. {
  525. printText_.Push(c);
  526. printToText_.Push(i);
  527. }
  528. }
  529. }
  530. else
  531. {
  532. printText_.Push('\n');
  533. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  534. rowWidth = 0;
  535. nextBreak = lineStart = i;
  536. }
  537. }
  538. }
  539. rowWidth = 0;
  540. for (unsigned i = 0; i < printText_.Size(); ++i)
  541. {
  542. unsigned c = printText_[i];
  543. if (c != '\n')
  544. {
  545. const FontGlyph* glyph = face->GetGlyph(c);
  546. if (glyph)
  547. {
  548. rowWidth += glyph->advanceX_;
  549. if (i < printText_.Size() - 1)
  550. rowWidth += face->GetKerning(c, printText_[i + 1]);
  551. }
  552. }
  553. else
  554. {
  555. width = Max(width, rowWidth);
  556. height += rowHeight;
  557. rowWidths_.Push(rowWidth);
  558. rowWidth = 0;
  559. }
  560. }
  561. if (rowWidth)
  562. {
  563. width = Max(width, rowWidth);
  564. height += rowHeight;
  565. rowWidths_.Push(rowWidth);
  566. }
  567. // Set at least one row height even if text is empty
  568. if (!height)
  569. height = rowHeight;
  570. // Set minimum and current size according to the text size, but respect fixed width if set
  571. if (!IsFixedWidth())
  572. {
  573. if (wordWrap_)
  574. SetMinWidth(0);
  575. else
  576. {
  577. SetMinWidth(width);
  578. SetWidth(width);
  579. }
  580. }
  581. SetFixedHeight(height);
  582. charLocationsDirty_ = true;
  583. }
  584. else
  585. {
  586. // No font, nothing to render
  587. pageGlyphLocations_.Clear();
  588. }
  589. // If wordwrap is on, parent may need layout update to correct for overshoot in size. However, do not do this when the
  590. // update is a response to resize, as that could cause infinite recursion
  591. if (wordWrap_ && !onResize)
  592. {
  593. UIElement* parent = GetParent();
  594. if (parent && parent->GetLayoutMode() != LM_FREE)
  595. parent->UpdateLayout();
  596. }
  597. }
  598. void Text::UpdateCharLocations()
  599. {
  600. // Remember the font face to see if it's still valid when it's time to render
  601. FontFace* face = font_ ? font_->GetFace(fontSize_) : nullptr;
  602. if (!face)
  603. return;
  604. fontFace_ = face;
  605. auto rowHeight = RoundToInt(rowSpacing_ * rowHeight_);
  606. // Store position & size of each character, and locations per texture page
  607. unsigned numChars = unicodeText_.Size();
  608. charLocations_.Resize(numChars + 1);
  609. pageGlyphLocations_.Resize(face->GetTextures().Size());
  610. for (unsigned i = 0; i < pageGlyphLocations_.Size(); ++i)
  611. pageGlyphLocations_[i].Clear();
  612. IntVector2 offset = font_->GetTotalGlyphOffset(fontSize_);
  613. unsigned rowIndex = 0;
  614. unsigned lastFilled = 0;
  615. float x = Round(GetRowStartPosition(rowIndex) + offset.x_);
  616. float y = Round(offset.y_);
  617. for (unsigned i = 0; i < printText_.Size(); ++i)
  618. {
  619. CharLocation loc;
  620. loc.position_ = Vector2(x, y);
  621. unsigned c = printText_[i];
  622. if (c != '\n')
  623. {
  624. const FontGlyph* glyph = face->GetGlyph(c);
  625. loc.size_ = Vector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  626. if (glyph)
  627. {
  628. // Store glyph's location for rendering. Verify that glyph page is valid
  629. if (glyph->page_ < pageGlyphLocations_.Size())
  630. pageGlyphLocations_[glyph->page_].Push(GlyphLocation(x, y, glyph));
  631. x += glyph->advanceX_;
  632. if (i < printText_.Size() - 1)
  633. x += face->GetKerning(c, printText_[i + 1]);
  634. }
  635. }
  636. else
  637. {
  638. loc.size_ = Vector2::ZERO;
  639. x = GetRowStartPosition(++rowIndex);
  640. y += rowHeight;
  641. }
  642. if (lastFilled > printToText_[i])
  643. lastFilled = printToText_[i];
  644. // Fill gaps in case characters were skipped from printing
  645. for (unsigned j = lastFilled; j <= printToText_[i]; ++j)
  646. charLocations_[j] = loc;
  647. lastFilled = printToText_[i] + 1;
  648. }
  649. // Store the ending position
  650. charLocations_[numChars].position_ = Vector2(x, y);
  651. charLocations_[numChars].size_ = Vector2::ZERO;
  652. charLocationsDirty_ = false;
  653. }
  654. void Text::ValidateSelection()
  655. {
  656. unsigned textLength = unicodeText_.Size();
  657. if (textLength)
  658. {
  659. if (selectionStart_ >= textLength)
  660. selectionStart_ = textLength - 1;
  661. if (selectionStart_ + selectionLength_ > textLength)
  662. selectionLength_ = textLength - selectionStart_;
  663. }
  664. else
  665. {
  666. selectionStart_ = 0;
  667. selectionLength_ = 0;
  668. }
  669. }
  670. int Text::GetRowStartPosition(unsigned rowIndex) const
  671. {
  672. float rowWidth = 0;
  673. if (rowIndex < rowWidths_.Size())
  674. rowWidth = rowWidths_[rowIndex];
  675. int ret = GetIndentWidth();
  676. switch (textAlignment_)
  677. {
  678. case HA_LEFT:
  679. break;
  680. case HA_CENTER:
  681. ret += (GetSize().x_ - rowWidth) / 2;
  682. break;
  683. case HA_RIGHT:
  684. ret += GetSize().x_ - rowWidth;
  685. break;
  686. case HA_CUSTOM:
  687. break;
  688. }
  689. return ret;
  690. }
  691. void Text::ConstructBatch(UIBatch& pageBatch, const PODVector<GlyphLocation>& pageGlyphLocation, float dx, float dy, Color* color,
  692. float depthBias)
  693. {
  694. unsigned startDataSize = pageBatch.vertexData_->Size();
  695. if (!color)
  696. pageBatch.SetDefaultColor();
  697. else
  698. pageBatch.SetColor(*color);
  699. for (unsigned i = 0; i < pageGlyphLocation.Size(); ++i)
  700. {
  701. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  702. const FontGlyph& glyph = *glyphLocation.glyph_;
  703. pageBatch.AddQuad(dx + glyphLocation.x_ + glyph.offsetX_, dy + glyphLocation.y_ + glyph.offsetY_, glyph.width_,
  704. glyph.height_, glyph.x_, glyph.y_, glyph.texWidth_, glyph.texHeight_);
  705. }
  706. if (depthBias != 0.0f)
  707. {
  708. unsigned dataSize = pageBatch.vertexData_->Size();
  709. for (unsigned i = startDataSize; i < dataSize; i += UI_VERTEX_SIZE)
  710. pageBatch.vertexData_->At(i + 2) += depthBias;
  711. }
  712. }
  713. }