Text.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 thickness = Clamp(strokeThickness_, 0, fontSize_);
  185. int samples = thickness * thickness + (thickness % 2 == 0 ? 4 : 3);
  186. float angle = 360.f / samples;
  187. float floatThickness = (float)thickness;
  188. for (int i = 0; i < samples; ++i)
  189. {
  190. float x = Cos(angle * i) * floatThickness;
  191. float y = Sin(angle * i) * floatThickness;
  192. ConstructBatch(pageBatch, pageGlyphLocation, (int)x, (int)y, &effectColor_, effectDepthBias_);
  193. }
  194. }
  195. else
  196. {
  197. int thickness = Clamp(strokeThickness_, 0, fontSize_);
  198. int x, y;
  199. for (x = -thickness; x <= thickness; ++x)
  200. {
  201. for (y = -thickness; y <= thickness; ++y)
  202. {
  203. // Don't draw glyphs that aren't on the edges
  204. if (x > -thickness && x < thickness &&
  205. y > -thickness && y < thickness)
  206. continue;
  207. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  208. }
  209. }
  210. }
  211. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  212. break;
  213. }
  214. UIBatch::AddOrMerge(pageBatch, batches);
  215. }
  216. // Reset hovering for next frame
  217. hovering_ = false;
  218. }
  219. void Text::OnResize()
  220. {
  221. if (wordWrap_)
  222. UpdateText(true);
  223. else
  224. charLocationsDirty_ = true;
  225. }
  226. void Text::OnIndentSet()
  227. {
  228. charLocationsDirty_ = true;
  229. }
  230. bool Text::SetFont(const String& fontName, int size)
  231. {
  232. ResourceCache* cache = GetSubsystem<ResourceCache>();
  233. return SetFont(cache->GetResource<Font>(fontName), size);
  234. }
  235. bool Text::SetFont(Font* font, int size)
  236. {
  237. if (!font)
  238. {
  239. URHO3D_LOGERROR("Null font for Text");
  240. return false;
  241. }
  242. if (font != font_ || size != fontSize_)
  243. {
  244. font_ = font;
  245. fontSize_ = Max(size, 1);
  246. UpdateText();
  247. }
  248. return true;
  249. }
  250. void Text::DecodeToUnicode()
  251. {
  252. unicodeText_.Clear();
  253. for (unsigned i = 0; i < text_.Length();)
  254. unicodeText_.Push(text_.NextUTF8Char(i));
  255. }
  256. void Text::SetText(const String& text)
  257. {
  258. if (autoLocalizable_)
  259. {
  260. stringId_ = text;
  261. Localization* l10n = GetSubsystem<Localization>();
  262. text_ = l10n->Get(stringId_);
  263. }
  264. else
  265. {
  266. text_ = text;
  267. }
  268. DecodeToUnicode();
  269. ValidateSelection();
  270. UpdateText();
  271. }
  272. void Text::SetTextAlignment(HorizontalAlignment align)
  273. {
  274. if (align != textAlignment_)
  275. {
  276. textAlignment_ = align;
  277. charLocationsDirty_ = true;
  278. }
  279. }
  280. void Text::SetRowSpacing(float spacing)
  281. {
  282. if (spacing != rowSpacing_)
  283. {
  284. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  285. UpdateText();
  286. }
  287. }
  288. void Text::SetWordwrap(bool enable)
  289. {
  290. if (enable != wordWrap_)
  291. {
  292. wordWrap_ = enable;
  293. UpdateText();
  294. }
  295. }
  296. void Text::SetAutoLocalizable(bool enable)
  297. {
  298. if (enable != autoLocalizable_)
  299. {
  300. autoLocalizable_ = enable;
  301. if (enable)
  302. {
  303. stringId_ = text_;
  304. Localization* l10n = GetSubsystem<Localization>();
  305. text_ = l10n->Get(stringId_);
  306. SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Text, HandleChangeLanguage));
  307. }
  308. else
  309. {
  310. text_ = stringId_;
  311. stringId_ = "";
  312. UnsubscribeFromEvent(E_CHANGELANGUAGE);
  313. }
  314. DecodeToUnicode();
  315. ValidateSelection();
  316. UpdateText();
  317. }
  318. }
  319. void Text::HandleChangeLanguage(StringHash eventType, VariantMap& eventData)
  320. {
  321. Localization* l10n = GetSubsystem<Localization>();
  322. text_ = l10n->Get(stringId_);
  323. DecodeToUnicode();
  324. ValidateSelection();
  325. UpdateText();
  326. }
  327. void Text::SetSelection(unsigned start, unsigned length)
  328. {
  329. selectionStart_ = start;
  330. selectionLength_ = length;
  331. ValidateSelection();
  332. }
  333. void Text::ClearSelection()
  334. {
  335. selectionStart_ = 0;
  336. selectionLength_ = 0;
  337. }
  338. void Text::SetSelectionColor(const Color& color)
  339. {
  340. selectionColor_ = color;
  341. }
  342. void Text::SetHoverColor(const Color& color)
  343. {
  344. hoverColor_ = color;
  345. }
  346. void Text::SetTextEffect(TextEffect textEffect)
  347. {
  348. textEffect_ = textEffect;
  349. }
  350. void Text::SetEffectShadowOffset(const IntVector2& offset)
  351. {
  352. shadowOffset_ = offset;
  353. }
  354. void Text::SetEffectStrokeThickness(int thickness)
  355. {
  356. strokeThickness_ = thickness;
  357. }
  358. void Text::SetEffectRoundStroke(bool roundStroke)
  359. {
  360. roundStroke_ = roundStroke;
  361. }
  362. void Text::SetEffectColor(const Color& effectColor)
  363. {
  364. effectColor_ = effectColor;
  365. }
  366. void Text::SetEffectDepthBias(float bias)
  367. {
  368. effectDepthBias_ = bias;
  369. }
  370. int Text::GetRowWidth(unsigned index) const
  371. {
  372. return index < rowWidths_.Size() ? rowWidths_[index] : 0;
  373. }
  374. IntVector2 Text::GetCharPosition(unsigned index)
  375. {
  376. if (charLocationsDirty_)
  377. UpdateCharLocations();
  378. if (charLocations_.Empty())
  379. return IntVector2::ZERO;
  380. // For convenience, return the position of the text ending if index exceeded
  381. if (index > charLocations_.Size() - 1)
  382. index = charLocations_.Size() - 1;
  383. return charLocations_[index].position_;
  384. }
  385. IntVector2 Text::GetCharSize(unsigned index)
  386. {
  387. if (charLocationsDirty_)
  388. UpdateCharLocations();
  389. if (charLocations_.Size() < 2)
  390. return IntVector2::ZERO;
  391. // For convenience, return the size of the last char if index exceeded (last size entry is zero)
  392. if (index > charLocations_.Size() - 2)
  393. index = charLocations_.Size() - 2;
  394. return charLocations_[index].size_;
  395. }
  396. void Text::SetFontAttr(const ResourceRef& value)
  397. {
  398. ResourceCache* cache = GetSubsystem<ResourceCache>();
  399. font_ = cache->GetResource<Font>(value.name_);
  400. }
  401. ResourceRef Text::GetFontAttr() const
  402. {
  403. return GetResourceRef(font_, Font::GetTypeStatic());
  404. }
  405. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  406. {
  407. if (!UIElement::FilterImplicitAttributes(dest))
  408. return false;
  409. if (!IsFixedWidth())
  410. {
  411. if (!RemoveChildXML(dest, "Size"))
  412. return false;
  413. if (!RemoveChildXML(dest, "Min Size"))
  414. return false;
  415. if (!RemoveChildXML(dest, "Max Size"))
  416. return false;
  417. }
  418. return true;
  419. }
  420. void Text::UpdateText(bool onResize)
  421. {
  422. rowWidths_.Clear();
  423. printText_.Clear();
  424. if (font_)
  425. {
  426. FontFace* face = font_->GetFace(fontSize_);
  427. if (!face)
  428. return;
  429. rowHeight_ = face->GetRowHeight();
  430. int width = 0;
  431. int height = 0;
  432. int rowWidth = 0;
  433. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  434. // First see if the text must be split up
  435. if (!wordWrap_)
  436. {
  437. printText_ = unicodeText_;
  438. printToText_.Resize(printText_.Size());
  439. for (unsigned i = 0; i < printText_.Size(); ++i)
  440. printToText_[i] = i;
  441. }
  442. else
  443. {
  444. int maxWidth = GetWidth();
  445. unsigned nextBreak = 0;
  446. unsigned lineStart = 0;
  447. printToText_.Clear();
  448. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  449. {
  450. unsigned j;
  451. unsigned c = unicodeText_[i];
  452. if (c != '\n')
  453. {
  454. bool ok = true;
  455. if (nextBreak <= i)
  456. {
  457. int futureRowWidth = rowWidth;
  458. for (j = i; j < unicodeText_.Size(); ++j)
  459. {
  460. unsigned d = unicodeText_[j];
  461. if (d == ' ' || d == '\n')
  462. {
  463. nextBreak = j;
  464. break;
  465. }
  466. const FontGlyph* glyph = face->GetGlyph(d);
  467. if (glyph)
  468. {
  469. futureRowWidth += glyph->advanceX_;
  470. if (j < unicodeText_.Size() - 1)
  471. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  472. }
  473. if (d == '-' && futureRowWidth <= maxWidth)
  474. {
  475. nextBreak = j + 1;
  476. break;
  477. }
  478. if (futureRowWidth > maxWidth)
  479. {
  480. ok = false;
  481. break;
  482. }
  483. }
  484. }
  485. if (!ok)
  486. {
  487. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  488. if (nextBreak == lineStart)
  489. {
  490. while (i < j)
  491. {
  492. printText_.Push(unicodeText_[i]);
  493. printToText_.Push(i);
  494. ++i;
  495. }
  496. }
  497. // Eliminate spaces that have been copied before the forced break
  498. while (printText_.Size() && printText_.Back() == ' ')
  499. {
  500. printText_.Pop();
  501. printToText_.Pop();
  502. }
  503. printText_.Push('\n');
  504. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  505. rowWidth = 0;
  506. nextBreak = lineStart = i;
  507. }
  508. if (i < unicodeText_.Size())
  509. {
  510. // When copying a space, position is allowed to be over row width
  511. c = unicodeText_[i];
  512. const FontGlyph* glyph = face->GetGlyph(c);
  513. if (glyph)
  514. {
  515. rowWidth += glyph->advanceX_;
  516. if (i < unicodeText_.Size() - 1)
  517. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  518. }
  519. if (rowWidth <= maxWidth)
  520. {
  521. printText_.Push(c);
  522. printToText_.Push(i);
  523. }
  524. }
  525. }
  526. else
  527. {
  528. printText_.Push('\n');
  529. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  530. rowWidth = 0;
  531. nextBreak = lineStart = i;
  532. }
  533. }
  534. }
  535. rowWidth = 0;
  536. for (unsigned i = 0; i < printText_.Size(); ++i)
  537. {
  538. unsigned c = printText_[i];
  539. if (c != '\n')
  540. {
  541. const FontGlyph* glyph = face->GetGlyph(c);
  542. if (glyph)
  543. {
  544. rowWidth += glyph->advanceX_;
  545. if (i < printText_.Size() - 1)
  546. rowWidth += face->GetKerning(c, printText_[i + 1]);
  547. }
  548. }
  549. else
  550. {
  551. width = Max(width, rowWidth);
  552. height += rowHeight;
  553. rowWidths_.Push(rowWidth);
  554. rowWidth = 0;
  555. }
  556. }
  557. if (rowWidth)
  558. {
  559. width = Max(width, rowWidth);
  560. height += rowHeight;
  561. rowWidths_.Push(rowWidth);
  562. }
  563. // Set at least one row height even if text is empty
  564. if (!height)
  565. height = rowHeight;
  566. // Set minimum and current size according to the text size, but respect fixed width if set
  567. if (!IsFixedWidth())
  568. {
  569. SetMinWidth(wordWrap_ ? 0 : width);
  570. SetWidth(width);
  571. }
  572. SetFixedHeight(height);
  573. charLocationsDirty_ = true;
  574. }
  575. else
  576. {
  577. // No font, nothing to render
  578. pageGlyphLocations_.Clear();
  579. }
  580. // If wordwrap is on, parent may need layout update to correct for overshoot in size. However, do not do this when the
  581. // update is a response to resize, as that could cause infinite recursion
  582. if (wordWrap_ && !onResize)
  583. {
  584. UIElement* parent = GetParent();
  585. if (parent && parent->GetLayoutMode() != LM_FREE)
  586. parent->UpdateLayout();
  587. }
  588. }
  589. void Text::UpdateCharLocations()
  590. {
  591. // Remember the font face to see if it's still valid when it's time to render
  592. FontFace* face = font_ ? font_->GetFace(fontSize_) : (FontFace*)0;
  593. if (!face)
  594. return;
  595. fontFace_ = face;
  596. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  597. // Store position & size of each character, and locations per texture page
  598. unsigned numChars = unicodeText_.Size();
  599. charLocations_.Resize(numChars + 1);
  600. pageGlyphLocations_.Resize(face->GetTextures().Size());
  601. for (unsigned i = 0; i < pageGlyphLocations_.Size(); ++i)
  602. pageGlyphLocations_[i].Clear();
  603. IntVector2 offset = font_->GetTotalGlyphOffset(fontSize_);
  604. unsigned rowIndex = 0;
  605. unsigned lastFilled = 0;
  606. int x = GetRowStartPosition(rowIndex) + offset.x_;
  607. int y = offset.y_;
  608. for (unsigned i = 0; i < printText_.Size(); ++i)
  609. {
  610. CharLocation loc;
  611. loc.position_ = IntVector2(x, y);
  612. unsigned c = printText_[i];
  613. if (c != '\n')
  614. {
  615. const FontGlyph* glyph = face->GetGlyph(c);
  616. loc.size_ = IntVector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  617. if (glyph)
  618. {
  619. // Store glyph's location for rendering. Verify that glyph page is valid
  620. if (glyph->page_ < pageGlyphLocations_.Size())
  621. pageGlyphLocations_[glyph->page_].Push(GlyphLocation(x, y, glyph));
  622. x += glyph->advanceX_;
  623. if (i < printText_.Size() - 1)
  624. x += face->GetKerning(c, printText_[i + 1]);
  625. }
  626. }
  627. else
  628. {
  629. loc.size_ = IntVector2::ZERO;
  630. x = GetRowStartPosition(++rowIndex);
  631. y += rowHeight;
  632. }
  633. // Fill gaps in case characters were skipped from printing
  634. for (unsigned j = lastFilled; j <= printToText_[i]; ++j)
  635. charLocations_[j] = loc;
  636. lastFilled = printToText_[i] + 1;
  637. }
  638. // Store the ending position
  639. charLocations_[numChars].position_ = IntVector2(x, y);
  640. charLocations_[numChars].size_ = IntVector2::ZERO;
  641. charLocationsDirty_ = false;
  642. }
  643. void Text::ValidateSelection()
  644. {
  645. unsigned textLength = unicodeText_.Size();
  646. if (textLength)
  647. {
  648. if (selectionStart_ >= textLength)
  649. selectionStart_ = textLength - 1;
  650. if (selectionStart_ + selectionLength_ > textLength)
  651. selectionLength_ = textLength - selectionStart_;
  652. }
  653. else
  654. {
  655. selectionStart_ = 0;
  656. selectionLength_ = 0;
  657. }
  658. }
  659. int Text::GetRowStartPosition(unsigned rowIndex) const
  660. {
  661. int rowWidth = 0;
  662. if (rowIndex < rowWidths_.Size())
  663. rowWidth = rowWidths_[rowIndex];
  664. int ret = GetIndentWidth();
  665. switch (textAlignment_)
  666. {
  667. case HA_LEFT:
  668. break;
  669. case HA_CENTER:
  670. ret += (GetSize().x_ - rowWidth) / 2;
  671. break;
  672. case HA_RIGHT:
  673. ret += GetSize().x_ - rowWidth;
  674. break;
  675. }
  676. return ret;
  677. }
  678. void Text::ConstructBatch(UIBatch& pageBatch, const PODVector<GlyphLocation>& pageGlyphLocation, int dx, int dy, Color* color,
  679. float depthBias)
  680. {
  681. unsigned startDataSize = pageBatch.vertexData_->Size();
  682. if (!color)
  683. pageBatch.SetDefaultColor();
  684. else
  685. pageBatch.SetColor(*color);
  686. for (unsigned i = 0; i < pageGlyphLocation.Size(); ++i)
  687. {
  688. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  689. const FontGlyph& glyph = *glyphLocation.glyph_;
  690. pageBatch.AddQuad(dx + glyphLocation.x_ + glyph.offsetX_, dy + glyphLocation.y_ + glyph.offsetY_, glyph.width_,
  691. glyph.height_, glyph.x_, glyph.y_);
  692. }
  693. if (depthBias != 0.0f)
  694. {
  695. unsigned dataSize = pageBatch.vertexData_->Size();
  696. for (unsigned i = startDataSize; i < dataSize; i += UI_VERTEX_SIZE)
  697. pageBatch.vertexData_->At(i + 2) += depthBias;
  698. }
  699. }
  700. }