Text.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. //
  2. // Copyright (c) 2008-2016 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. 0
  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. UIElement(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. selectionColor_(Color::TRANSPARENT),
  57. hoverColor_(Color::TRANSPARENT),
  58. textEffect_(TE_NONE),
  59. shadowOffset_(IntVector2(1, 1)),
  60. strokeThickness_(1),
  61. roundStroke_(false),
  62. effectColor_(Color::BLACK),
  63. effectDepthBias_(0.0f),
  64. rowHeight_(0)
  65. {
  66. // By default Text does not derive opacity from parent elements
  67. useDerivedOpacity_ = false;
  68. }
  69. Text::~Text()
  70. {
  71. }
  72. void Text::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<Text>(UI_CATEGORY);
  75. URHO3D_COPY_BASE_ATTRIBUTES(UIElement);
  76. URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Use Derived Opacity", false);
  77. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  78. URHO3D_ATTRIBUTE("Font Size", int, fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  79. URHO3D_ATTRIBUTE("Text", String, text_, String::EMPTY, AM_FILE);
  80. URHO3D_ENUM_ATTRIBUTE("Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  81. URHO3D_ATTRIBUTE("Row Spacing", float, rowSpacing_, 1.0f, AM_FILE);
  82. URHO3D_ATTRIBUTE("Word Wrap", bool, wordWrap_, false, AM_FILE);
  83. URHO3D_ACCESSOR_ATTRIBUTE("Auto Localizable", GetAutoLocalizable, SetAutoLocalizable, bool, false, AM_FILE);
  84. URHO3D_ACCESSOR_ATTRIBUTE("Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::TRANSPARENT, AM_FILE);
  85. URHO3D_ACCESSOR_ATTRIBUTE("Hover Color", GetHoverColor, SetHoverColor, Color, Color::TRANSPARENT, AM_FILE);
  86. URHO3D_ENUM_ATTRIBUTE("Text Effect", textEffect_, textEffects, TE_NONE, AM_FILE);
  87. URHO3D_ATTRIBUTE("Shadow Offset", IntVector2, shadowOffset_, IntVector2(1, 1), AM_FILE);
  88. URHO3D_ATTRIBUTE("Stroke Thickness", int, strokeThickness_, 1, AM_FILE);
  89. URHO3D_ATTRIBUTE("Round Stroke", bool, roundStroke_, false, AM_FILE);
  90. URHO3D_ACCESSOR_ATTRIBUTE("Effect Color", GetEffectColor, SetEffectColor, Color, Color::BLACK, AM_FILE);
  91. // Change the default value for UseDerivedOpacity
  92. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  93. }
  94. void Text::ApplyAttributes()
  95. {
  96. UIElement::ApplyAttributes();
  97. DecodeToUnicode();
  98. fontSize_ = Max(fontSize_, 1);
  99. ValidateSelection();
  100. UpdateText();
  101. }
  102. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  103. {
  104. FontFace* face = font_ ? font_->GetFace(fontSize_) : (FontFace*)0;
  105. if (!face)
  106. {
  107. hovering_ = false;
  108. return;
  109. }
  110. // If face has changed or char locations are not valid anymore, update before rendering
  111. if (charLocationsDirty_ || !fontFace_ || face != fontFace_)
  112. UpdateCharLocations();
  113. // If face uses mutable glyphs mechanism, reacquire glyphs before rendering to make sure they are in the texture
  114. else if (face->HasMutableGlyphs())
  115. {
  116. for (unsigned i = 0; i < printText_.Size(); ++i)
  117. face->GetGlyph(printText_[i]);
  118. }
  119. // Hovering and/or whole selection batch
  120. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  121. {
  122. bool both = hovering_ && selected_ && hoverColor_.a_ > 0.0 && selectionColor_.a_ > 0.0f;
  123. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  124. batch.SetColor(both ? selectionColor_.Lerp(hoverColor_, 0.5f) :
  125. (selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ : hoverColor_));
  126. batch.AddQuad(0, 0, GetWidth(), GetHeight(), 0, 0);
  127. UIBatch::AddOrMerge(batch, batches);
  128. }
  129. // Partial selection batch
  130. if (!selected_ && selectionLength_ && charLocations_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  131. {
  132. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  133. batch.SetColor(selectionColor_);
  134. IntVector2 currentStart = charLocations_[selectionStart_].position_;
  135. IntVector2 currentEnd = currentStart;
  136. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  137. {
  138. // Check if row changes, and start a new quad in that case
  139. if (charLocations_[i].size_ != IntVector2::ZERO)
  140. {
  141. if (charLocations_[i].position_.y_ != currentStart.y_)
  142. {
  143. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_,
  144. currentEnd.y_ - currentStart.y_, 0, 0);
  145. currentStart = charLocations_[i].position_;
  146. currentEnd = currentStart + charLocations_[i].size_;
  147. }
  148. else
  149. {
  150. currentEnd.x_ += charLocations_[i].size_.x_;
  151. currentEnd.y_ = Max(currentStart.y_ + charLocations_[i].size_.y_, currentEnd.y_);
  152. }
  153. }
  154. }
  155. if (currentEnd != currentStart)
  156. {
  157. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_, 0, 0);
  158. }
  159. UIBatch::AddOrMerge(batch, batches);
  160. }
  161. // Text batch
  162. TextEffect textEffect = font_->IsSDFFont() ? TE_NONE : textEffect_;
  163. const Vector<SharedPtr<Texture2D> >& textures = face->GetTextures();
  164. for (unsigned n = 0; n < textures.Size() && n < pageGlyphLocations_.Size(); ++n)
  165. {
  166. // One batch per texture/page
  167. UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, textures[n], &vertexData);
  168. const PODVector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations_[n];
  169. switch (textEffect)
  170. {
  171. case TE_NONE:
  172. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  173. break;
  174. case TE_SHADOW:
  175. ConstructBatch(pageBatch, pageGlyphLocation, shadowOffset_.x_, shadowOffset_.y_, &effectColor_, effectDepthBias_);
  176. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  177. break;
  178. case TE_STROKE:
  179. if (roundStroke_)
  180. {
  181. // Samples should be even or glyph may be redrawn in wrong x y pos making stroke corners rough
  182. // Adding to thickness helps with thickness of 1 not having enought samples for this formula
  183. // or certain fonts with reflex corners requiring more glyph samples for a smooth stroke when large
  184. int samples = strokeThickness_ * strokeThickness_ + (strokeThickness_ % 2 == 0 ? 4 : 3);
  185. float angle = 360.f / samples;
  186. for (int i = 0; i < samples; ++i)
  187. {
  188. float x = cos(angle * i * M_PI / 180.f) * strokeThickness_;
  189. float y = sin(angle * i * M_PI / 180.f) * strokeThickness_;
  190. ConstructBatch(pageBatch, pageGlyphLocation, (int)x, (int)y, &effectColor_, effectDepthBias_);
  191. }
  192. }
  193. else
  194. {
  195. float offset = strokeThickness_ / 2.f;
  196. offset = floor(offset + .5f);
  197. int x, y;
  198. for (x = -(int)offset; x <= (int)offset; ++x)
  199. {
  200. for (y = -(int)offset; y <= (int)offset; ++y)
  201. {
  202. // Don't draw glyphs that aren't on the edges
  203. if (x > -(int)offset && x < (int)offset &&
  204. y > -(int)offset && y < (int)offset)
  205. continue;
  206. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  207. }
  208. }
  209. }
  210. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  211. break;
  212. }
  213. UIBatch::AddOrMerge(pageBatch, batches);
  214. }
  215. // Reset hovering for next frame
  216. hovering_ = false;
  217. }
  218. void Text::OnResize()
  219. {
  220. if (wordWrap_)
  221. UpdateText(true);
  222. else
  223. charLocationsDirty_ = true;
  224. }
  225. void Text::OnIndentSet()
  226. {
  227. charLocationsDirty_ = true;
  228. }
  229. bool Text::SetFont(const String& fontName, int size)
  230. {
  231. ResourceCache* cache = GetSubsystem<ResourceCache>();
  232. return SetFont(cache->GetResource<Font>(fontName), size);
  233. }
  234. bool Text::SetFont(Font* font, int size)
  235. {
  236. if (!font)
  237. {
  238. URHO3D_LOGERROR("Null font for Text");
  239. return false;
  240. }
  241. if (font != font_ || size != fontSize_)
  242. {
  243. font_ = font;
  244. fontSize_ = Max(size, 1);
  245. UpdateText();
  246. }
  247. return true;
  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. Localization* 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. Localization* 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. Localization* 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::SetSelectionColor(const Color& color)
  338. {
  339. selectionColor_ = color;
  340. }
  341. void Text::SetHoverColor(const Color& color)
  342. {
  343. hoverColor_ = color;
  344. }
  345. void Text::SetTextEffect(TextEffect textEffect)
  346. {
  347. textEffect_ = textEffect;
  348. }
  349. void Text::SetEffectShadowOffset(IntVector2 offset)
  350. {
  351. shadowOffset_ = offset;
  352. }
  353. void Text::SetEffectStrokeThickness(int thickness)
  354. {
  355. strokeThickness_ = thickness;
  356. }
  357. void Text::SetEffectRoundStroke(bool roundStroke)
  358. {
  359. roundStroke_ = roundStroke;
  360. }
  361. void Text::SetEffectColor(const Color& effectColor)
  362. {
  363. effectColor_ = effectColor;
  364. }
  365. void Text::SetEffectDepthBias(float bias)
  366. {
  367. effectDepthBias_ = bias;
  368. }
  369. int Text::GetRowWidth(unsigned index) const
  370. {
  371. return index < rowWidths_.Size() ? rowWidths_[index] : 0;
  372. }
  373. IntVector2 Text::GetCharPosition(unsigned index)
  374. {
  375. if (charLocationsDirty_)
  376. UpdateCharLocations();
  377. if (charLocations_.Empty())
  378. return IntVector2::ZERO;
  379. // For convenience, return the position of the text ending if index exceeded
  380. if (index > charLocations_.Size() - 1)
  381. index = charLocations_.Size() - 1;
  382. return charLocations_[index].position_;
  383. }
  384. IntVector2 Text::GetCharSize(unsigned index)
  385. {
  386. if (charLocationsDirty_)
  387. UpdateCharLocations();
  388. if (charLocations_.Size() < 2)
  389. return IntVector2::ZERO;
  390. // For convenience, return the size of the last char if index exceeded (last size entry is zero)
  391. if (index > charLocations_.Size() - 2)
  392. index = charLocations_.Size() - 2;
  393. return charLocations_[index].size_;
  394. }
  395. void Text::SetFontAttr(const ResourceRef& value)
  396. {
  397. ResourceCache* cache = GetSubsystem<ResourceCache>();
  398. font_ = cache->GetResource<Font>(value.name_);
  399. }
  400. ResourceRef Text::GetFontAttr() const
  401. {
  402. return GetResourceRef(font_, Font::GetTypeStatic());
  403. }
  404. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  405. {
  406. if (!UIElement::FilterImplicitAttributes(dest))
  407. return false;
  408. if (!IsFixedWidth())
  409. {
  410. if (!RemoveChildXML(dest, "Size"))
  411. return false;
  412. if (!RemoveChildXML(dest, "Min Size"))
  413. return false;
  414. if (!RemoveChildXML(dest, "Max Size"))
  415. return false;
  416. }
  417. return true;
  418. }
  419. void Text::UpdateText(bool onResize)
  420. {
  421. rowWidths_.Clear();
  422. printText_.Clear();
  423. if (font_)
  424. {
  425. FontFace* face = font_->GetFace(fontSize_);
  426. if (!face)
  427. return;
  428. rowHeight_ = face->GetRowHeight();
  429. int width = 0;
  430. int height = 0;
  431. int rowWidth = 0;
  432. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  433. // First see if the text must be split up
  434. if (!wordWrap_)
  435. {
  436. printText_ = unicodeText_;
  437. printToText_.Resize(printText_.Size());
  438. for (unsigned i = 0; i < printText_.Size(); ++i)
  439. printToText_[i] = i;
  440. }
  441. else
  442. {
  443. int maxWidth = GetWidth();
  444. unsigned nextBreak = 0;
  445. unsigned lineStart = 0;
  446. printToText_.Clear();
  447. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  448. {
  449. unsigned j;
  450. unsigned c = unicodeText_[i];
  451. if (c != '\n')
  452. {
  453. bool ok = true;
  454. if (nextBreak <= i)
  455. {
  456. int futureRowWidth = rowWidth;
  457. for (j = i; j < unicodeText_.Size(); ++j)
  458. {
  459. unsigned d = unicodeText_[j];
  460. if (d == ' ' || d == '\n')
  461. {
  462. nextBreak = j;
  463. break;
  464. }
  465. const FontGlyph* glyph = face->GetGlyph(d);
  466. if (glyph)
  467. {
  468. futureRowWidth += glyph->advanceX_;
  469. if (j < unicodeText_.Size() - 1)
  470. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  471. }
  472. if (d == '-' && futureRowWidth <= maxWidth)
  473. {
  474. nextBreak = j + 1;
  475. break;
  476. }
  477. if (futureRowWidth > maxWidth)
  478. {
  479. ok = false;
  480. break;
  481. }
  482. }
  483. }
  484. if (!ok)
  485. {
  486. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  487. if (nextBreak == lineStart)
  488. {
  489. while (i < j)
  490. {
  491. printText_.Push(unicodeText_[i]);
  492. printToText_.Push(i);
  493. ++i;
  494. }
  495. }
  496. // Eliminate spaces that have been copied before the forced break
  497. while (printText_.Size() && printText_.Back() == ' ')
  498. {
  499. printText_.Pop();
  500. printToText_.Pop();
  501. }
  502. printText_.Push('\n');
  503. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  504. rowWidth = 0;
  505. nextBreak = lineStart = i;
  506. }
  507. if (i < unicodeText_.Size())
  508. {
  509. // When copying a space, position is allowed to be over row width
  510. c = unicodeText_[i];
  511. const FontGlyph* glyph = face->GetGlyph(c);
  512. if (glyph)
  513. {
  514. rowWidth += glyph->advanceX_;
  515. if (i < unicodeText_.Size() - 1)
  516. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  517. }
  518. if (rowWidth <= maxWidth)
  519. {
  520. printText_.Push(c);
  521. printToText_.Push(i);
  522. }
  523. }
  524. }
  525. else
  526. {
  527. printText_.Push('\n');
  528. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  529. rowWidth = 0;
  530. nextBreak = lineStart = i;
  531. }
  532. }
  533. }
  534. rowWidth = 0;
  535. for (unsigned i = 0; i < printText_.Size(); ++i)
  536. {
  537. unsigned c = printText_[i];
  538. if (c != '\n')
  539. {
  540. const FontGlyph* glyph = face->GetGlyph(c);
  541. if (glyph)
  542. {
  543. rowWidth += glyph->advanceX_;
  544. if (i < printText_.Size() - 1)
  545. rowWidth += face->GetKerning(c, printText_[i + 1]);
  546. }
  547. }
  548. else
  549. {
  550. width = Max(width, rowWidth);
  551. height += rowHeight;
  552. rowWidths_.Push(rowWidth);
  553. rowWidth = 0;
  554. }
  555. }
  556. if (rowWidth)
  557. {
  558. width = Max(width, rowWidth);
  559. height += rowHeight;
  560. rowWidths_.Push(rowWidth);
  561. }
  562. // Set at least one row height even if text is empty
  563. if (!height)
  564. height = rowHeight;
  565. // Set minimum and current size according to the text size, but respect fixed width if set
  566. if (!IsFixedWidth())
  567. {
  568. SetMinWidth(wordWrap_ ? 0 : width);
  569. SetWidth(width);
  570. }
  571. SetFixedHeight(height);
  572. charLocationsDirty_ = true;
  573. }
  574. else
  575. {
  576. // No font, nothing to render
  577. pageGlyphLocations_.Clear();
  578. }
  579. // If wordwrap is on, parent may need layout update to correct for overshoot in size. However, do not do this when the
  580. // update is a response to resize, as that could cause infinite recursion
  581. if (wordWrap_ && !onResize)
  582. {
  583. UIElement* parent = GetParent();
  584. if (parent && parent->GetLayoutMode() != LM_FREE)
  585. parent->UpdateLayout();
  586. }
  587. }
  588. void Text::UpdateCharLocations()
  589. {
  590. // Remember the font face to see if it's still valid when it's time to render
  591. FontFace* face = font_ ? font_->GetFace(fontSize_) : (FontFace*)0;
  592. if (!face)
  593. return;
  594. fontFace_ = face;
  595. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  596. // Store position & size of each character, and locations per texture page
  597. unsigned numChars = unicodeText_.Size();
  598. charLocations_.Resize(numChars + 1);
  599. pageGlyphLocations_.Resize(face->GetTextures().Size());
  600. for (unsigned i = 0; i < pageGlyphLocations_.Size(); ++i)
  601. pageGlyphLocations_[i].Clear();
  602. IntVector2 offset = font_->GetTotalGlyphOffset(fontSize_);
  603. unsigned rowIndex = 0;
  604. unsigned lastFilled = 0;
  605. int x = GetRowStartPosition(rowIndex) + offset.x_;
  606. int y = offset.y_;
  607. for (unsigned i = 0; i < printText_.Size(); ++i)
  608. {
  609. CharLocation loc;
  610. loc.position_ = IntVector2(x, y);
  611. unsigned c = printText_[i];
  612. if (c != '\n')
  613. {
  614. const FontGlyph* glyph = face->GetGlyph(c);
  615. loc.size_ = IntVector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  616. if (glyph)
  617. {
  618. // Store glyph's location for rendering. Verify that glyph page is valid
  619. if (glyph->page_ < pageGlyphLocations_.Size())
  620. pageGlyphLocations_[glyph->page_].Push(GlyphLocation(x, y, glyph));
  621. x += glyph->advanceX_;
  622. if (i < printText_.Size() - 1)
  623. x += face->GetKerning(c, printText_[i + 1]);
  624. }
  625. }
  626. else
  627. {
  628. loc.size_ = IntVector2::ZERO;
  629. x = GetRowStartPosition(++rowIndex);
  630. y += rowHeight;
  631. }
  632. // Fill gaps in case characters were skipped from printing
  633. for (unsigned j = lastFilled; j <= printToText_[i]; ++j)
  634. charLocations_[j] = loc;
  635. lastFilled = printToText_[i] + 1;
  636. }
  637. // Store the ending position
  638. charLocations_[numChars].position_ = IntVector2(x, y);
  639. charLocations_[numChars].size_ = IntVector2::ZERO;
  640. charLocationsDirty_ = false;
  641. }
  642. void Text::ValidateSelection()
  643. {
  644. unsigned textLength = unicodeText_.Size();
  645. if (textLength)
  646. {
  647. if (selectionStart_ >= textLength)
  648. selectionStart_ = textLength - 1;
  649. if (selectionStart_ + selectionLength_ > textLength)
  650. selectionLength_ = textLength - selectionStart_;
  651. }
  652. else
  653. {
  654. selectionStart_ = 0;
  655. selectionLength_ = 0;
  656. }
  657. }
  658. int Text::GetRowStartPosition(unsigned rowIndex) const
  659. {
  660. int rowWidth = 0;
  661. if (rowIndex < rowWidths_.Size())
  662. rowWidth = rowWidths_[rowIndex];
  663. int ret = GetIndentWidth();
  664. switch (textAlignment_)
  665. {
  666. case HA_LEFT:
  667. break;
  668. case HA_CENTER:
  669. ret += (GetSize().x_ - rowWidth) / 2;
  670. break;
  671. case HA_RIGHT:
  672. ret += GetSize().x_ - rowWidth;
  673. break;
  674. }
  675. return ret;
  676. }
  677. void Text::ConstructBatch(UIBatch& pageBatch, const PODVector<GlyphLocation>& pageGlyphLocation, int dx, int dy, Color* color,
  678. float depthBias)
  679. {
  680. unsigned startDataSize = pageBatch.vertexData_->Size();
  681. if (!color)
  682. pageBatch.SetDefaultColor();
  683. else
  684. pageBatch.SetColor(*color);
  685. for (unsigned i = 0; i < pageGlyphLocation.Size(); ++i)
  686. {
  687. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  688. const FontGlyph& glyph = *glyphLocation.glyph_;
  689. pageBatch.AddQuad(dx + glyphLocation.x_ + glyph.offsetX_, dy + glyphLocation.y_ + glyph.offsetY_, glyph.width_,
  690. glyph.height_, glyph.x_, glyph.y_);
  691. }
  692. if (depthBias != 0.0f)
  693. {
  694. unsigned dataSize = pageBatch.vertexData_->Size();
  695. for (unsigned i = startDataSize; i < dataSize; i += UI_VERTEX_SIZE)
  696. pageBatch.vertexData_->At(i + 2) += depthBias;
  697. }
  698. }
  699. }