Text.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "Font.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "StringUtils.h"
  29. #include "Text.h"
  30. #include "Texture2D.h"
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. static const float MIN_ROW_SPACING = 0.5f;
  35. extern const char* horizontalAlignments[];
  36. extern const char* UI_CATEGORY;
  37. struct GlyphLocation
  38. {
  39. int x_;
  40. int y_;
  41. const FontGlyph* glyph_;
  42. GlyphLocation(int x, int y, const FontGlyph* glyph) :
  43. x_(x),
  44. y_(y),
  45. glyph_(glyph)
  46. {
  47. }
  48. };
  49. Text::Text(Context* context) :
  50. UIElement(context),
  51. fontSize_(DEFAULT_FONT_SIZE),
  52. textAlignment_(HA_LEFT),
  53. rowSpacing_(1.0f),
  54. wordWrap_(false),
  55. selectionStart_(0),
  56. selectionLength_(0),
  57. selectionColor_(Color::TRANSPARENT),
  58. hoverColor_(Color::TRANSPARENT),
  59. rowHeight_(0)
  60. {
  61. // By default Text does not derive opacity from parent elements
  62. useDerivedOpacity_ = false;
  63. }
  64. Text::~Text()
  65. {
  66. }
  67. void Text::RegisterObject(Context* context)
  68. {
  69. context->RegisterFactory<Text>(UI_CATEGORY);
  70. COPY_BASE_ATTRIBUTES(Text, UIElement);
  71. UPDATE_ATTRIBUTE_DEFAULT_VALUE(Text, "Use Derived Opacity", false);
  72. ACCESSOR_ATTRIBUTE(Text, VAR_RESOURCEREF, "Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  73. ATTRIBUTE(Text, VAR_INT, "Font Size", fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  74. ATTRIBUTE(Text, VAR_STRING, "Text", text_, String::EMPTY, AM_FILE);
  75. ENUM_ATTRIBUTE(Text, "Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  76. ATTRIBUTE(Text, VAR_FLOAT, "Row Spacing", rowSpacing_, 1.0f, AM_FILE);
  77. ATTRIBUTE(Text, VAR_BOOL, "Word Wrap", wordWrap_, false, AM_FILE);
  78. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::TRANSPARENT, AM_FILE);
  79. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Hover Color", GetHoverColor, SetHoverColor, Color, Color::TRANSPARENT, AM_FILE);
  80. // Change the default value for UseDerivedOpacity
  81. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  82. }
  83. void Text::ApplyAttributes()
  84. {
  85. UIElement::ApplyAttributes();
  86. // Decode to Unicode now
  87. unicodeText_.Clear();
  88. for (unsigned i = 0; i < text_.Length();)
  89. unicodeText_.Push(text_.NextUTF8Char(i));
  90. fontSize_ = Max(fontSize_, 1);
  91. ValidateSelection();
  92. UpdateText();
  93. }
  94. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  95. {
  96. // Hovering and/or whole selection batch
  97. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  98. {
  99. bool both = hovering_ && selected_ && hoverColor_.a_ > 0.0 && selectionColor_.a_ > 0.0f;
  100. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  101. batch.AddQuad(0, 0, GetWidth(), GetHeight(), 0, 0, 0, 0, both ? selectionColor_.Lerp(hoverColor_, 0.5f) :
  102. (selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ : hoverColor_));
  103. UIBatch::AddOrMerge(batch, batches);
  104. }
  105. // Partial selection batch
  106. if (!selected_ && selectionLength_ && charSizes_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  107. {
  108. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  109. IntVector2 currentStart = charPositions_[selectionStart_];
  110. IntVector2 currentEnd = currentStart;
  111. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  112. {
  113. // Check if row changes, and start a new quad in that case
  114. if (charSizes_[i].x_ && charSizes_[i].y_)
  115. {
  116. if (charPositions_[i].y_ != currentStart.y_)
  117. {
  118. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  119. 0, 0, 0, 0, selectionColor_);
  120. currentStart = charPositions_[i];
  121. currentEnd = currentStart + charSizes_[i];
  122. }
  123. else
  124. {
  125. currentEnd.x_ += charSizes_[i].x_;
  126. currentEnd.y_ = Max(currentStart.y_ + charSizes_[i].y_, currentEnd.y_);
  127. }
  128. }
  129. }
  130. if (currentEnd != currentStart)
  131. {
  132. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  133. 0, 0, 0, 0, selectionColor_);
  134. }
  135. UIBatch::AddOrMerge(batch, batches);
  136. }
  137. // Text batch
  138. if (font_)
  139. {
  140. const FontFace* face = font_->GetFace(fontSize_);
  141. if (!face)
  142. return;
  143. if (face->textures_.Size() > 1)
  144. {
  145. // Only traversing thru the printText once regardless of number of textures/pages in the font
  146. Vector<PODVector<GlyphLocation> > pageGlyphLocations(face->textures_.Size());
  147. unsigned rowIndex = 0;
  148. int x = GetRowStartPosition(rowIndex);
  149. int y = 0;
  150. for (unsigned i = 0; i < printText_.Size(); ++i)
  151. {
  152. unsigned c = printText_[i];
  153. if (c != '\n')
  154. {
  155. const FontGlyph* p = face->GetGlyph(c);
  156. if (!p)
  157. continue;
  158. pageGlyphLocations[p->page_].Push(GlyphLocation(x, y, p));
  159. x += p->advanceX_;
  160. if (i < printText_.Size() - 1)
  161. x += face->GetKerning(c, printText_[i + 1]);
  162. }
  163. else
  164. {
  165. x = GetRowStartPosition(++rowIndex);
  166. y += rowHeight_;
  167. }
  168. }
  169. for (unsigned n = 0; n < face->textures_.Size(); ++n)
  170. {
  171. // One batch per texture/page
  172. UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, face->textures_[n], &vertexData);
  173. const PODVector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations[n];
  174. for (unsigned i = 0; i < pageGlyphLocation.Size(); ++i)
  175. {
  176. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  177. const FontGlyph& glyph = *glyphLocation.glyph_;
  178. pageBatch.AddQuad(glyphLocation.x_ + glyph.offsetX_, glyphLocation.y_ + glyph.offsetY_, glyph.width_, glyph.height_, glyph.x_, glyph.y_);
  179. }
  180. batches.Push(pageBatch);
  181. }
  182. }
  183. else
  184. {
  185. // If only one texture page, construct the UI batch directly
  186. unsigned rowIndex = 0;
  187. int x = GetRowStartPosition(rowIndex);
  188. int y = 0;
  189. UIBatch batch(this, BLEND_ALPHA, currentScissor, face->textures_[0], &vertexData);
  190. for (unsigned i = 0; i < printText_.Size(); ++i)
  191. {
  192. unsigned c = printText_[i];
  193. if (c != '\n')
  194. {
  195. const FontGlyph* p = face->GetGlyph(c);
  196. if (!p)
  197. continue;
  198. batch.AddQuad(x + p->offsetX_, y + p->offsetY_, p->width_, p->height_, p->x_, p->y_);
  199. x += p->advanceX_;
  200. if (i < printText_.Size() - 1)
  201. x += face->GetKerning(c, printText_[i + 1]);
  202. }
  203. else
  204. {
  205. x = GetRowStartPosition(++rowIndex);
  206. y += rowHeight_;
  207. }
  208. }
  209. UIBatch::AddOrMerge(batch, batches);
  210. }
  211. }
  212. // Reset hovering for next frame
  213. hovering_ = false;
  214. }
  215. void Text::OnResize()
  216. {
  217. if (wordWrap_)
  218. UpdateText();
  219. }
  220. bool Text::SetFont(const String& fontName, int size)
  221. {
  222. ResourceCache* cache = GetSubsystem<ResourceCache>();
  223. return SetFont(cache->GetResource<Font>(fontName), size);
  224. }
  225. bool Text::SetFont(Font* font, int size)
  226. {
  227. if (!font)
  228. {
  229. LOGERROR("Null font for Text");
  230. return false;
  231. }
  232. if (font != font_ || size != fontSize_)
  233. {
  234. font_ = font;
  235. fontSize_ = Max(size, 1);
  236. UpdateText();
  237. }
  238. return true;
  239. }
  240. void Text::SetText(const String& text)
  241. {
  242. text_ = text;
  243. // Decode to Unicode now
  244. unicodeText_.Clear();
  245. for (unsigned i = 0; i < text_.Length();)
  246. unicodeText_.Push(text_.NextUTF8Char(i));
  247. ValidateSelection();
  248. UpdateText();
  249. }
  250. void Text::SetTextAlignment(HorizontalAlignment align)
  251. {
  252. if (align != textAlignment_)
  253. {
  254. textAlignment_ = align;
  255. UpdateText();
  256. }
  257. }
  258. void Text::SetRowSpacing(float spacing)
  259. {
  260. if (spacing != rowSpacing_)
  261. {
  262. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  263. UpdateText();
  264. }
  265. }
  266. void Text::SetWordwrap(bool enable)
  267. {
  268. if (enable != wordWrap_)
  269. {
  270. wordWrap_ = enable;
  271. UpdateText();
  272. }
  273. }
  274. void Text::SetSelection(unsigned start, unsigned length)
  275. {
  276. selectionStart_ = start;
  277. selectionLength_ = length;
  278. ValidateSelection();
  279. }
  280. void Text::ClearSelection()
  281. {
  282. selectionStart_ = 0;
  283. selectionLength_ = 0;
  284. }
  285. void Text::SetSelectionColor(const Color& color)
  286. {
  287. selectionColor_ = color;
  288. }
  289. void Text::SetHoverColor(const Color& color)
  290. {
  291. hoverColor_ = color;
  292. }
  293. void Text::SetFontAttr(ResourceRef value)
  294. {
  295. ResourceCache* cache = GetSubsystem<ResourceCache>();
  296. font_ = cache->GetResource<Font>(value.id_);
  297. }
  298. ResourceRef Text::GetFontAttr() const
  299. {
  300. return GetResourceRef(font_, Font::GetTypeStatic());
  301. }
  302. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  303. {
  304. if (!UIElement::FilterImplicitAttributes(dest))
  305. return false;
  306. if (!IsFixedWidth())
  307. {
  308. if (!RemoveChildXML(dest, "Size"))
  309. return false;
  310. if (!RemoveChildXML(dest, "Min Size"))
  311. return false;
  312. if (!RemoveChildXML(dest, "Max Size"))
  313. return false;
  314. }
  315. return true;
  316. }
  317. void Text::UpdateText()
  318. {
  319. int width = 0;
  320. int height = 0;
  321. rowWidths_.Clear();
  322. printText_.Clear();
  323. PODVector<unsigned> printToText;
  324. if (font_)
  325. {
  326. const FontFace* face = font_->GetFace(fontSize_);
  327. if (!face)
  328. return;
  329. rowHeight_ = face->rowHeight_;
  330. int rowWidth = 0;
  331. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  332. // First see if the text must be split up
  333. if (!wordWrap_)
  334. {
  335. printText_ = unicodeText_;
  336. printToText.Resize(printText_.Size());
  337. for (unsigned i = 0; i < printText_.Size(); ++i)
  338. printToText[i] = i;
  339. }
  340. else
  341. {
  342. int maxWidth = GetWidth();
  343. unsigned nextBreak = 0;
  344. unsigned lineStart = 0;
  345. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  346. {
  347. unsigned j;
  348. unsigned c = unicodeText_[i];
  349. if (c != '\n')
  350. {
  351. bool ok = true;
  352. if (nextBreak <= i)
  353. {
  354. int futureRowWidth = rowWidth;
  355. for (j = i; j < unicodeText_.Size(); ++j)
  356. {
  357. unsigned d = unicodeText_[j];
  358. if (d == ' ' || d == '\n')
  359. {
  360. nextBreak = j;
  361. break;
  362. }
  363. const FontGlyph* glyph = face->GetGlyph(d);
  364. if (glyph)
  365. {
  366. futureRowWidth += glyph->advanceX_;
  367. if (j < unicodeText_.Size() - 1)
  368. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  369. }
  370. if (d == '-' && futureRowWidth <= maxWidth)
  371. {
  372. nextBreak = j + 1;
  373. break;
  374. }
  375. if (futureRowWidth > maxWidth)
  376. {
  377. ok = false;
  378. break;
  379. }
  380. }
  381. }
  382. if (!ok)
  383. {
  384. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  385. if (nextBreak == lineStart)
  386. {
  387. while (i < j)
  388. {
  389. printText_.Push(unicodeText_[i]);
  390. printToText.Push(i);
  391. ++i;
  392. }
  393. }
  394. printText_.Push('\n');
  395. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  396. rowWidth = 0;
  397. nextBreak = lineStart = i;
  398. }
  399. if (i < unicodeText_.Size())
  400. {
  401. // When copying a space, position is allowed to be over row width
  402. c = unicodeText_[i];
  403. const FontGlyph* glyph = face->GetGlyph(c);
  404. if (glyph)
  405. {
  406. rowWidth += glyph->advanceX_;
  407. if (i < text_.Length() - 1)
  408. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  409. }
  410. if (rowWidth <= maxWidth)
  411. {
  412. printText_.Push(c);
  413. printToText.Push(i);
  414. }
  415. }
  416. }
  417. else
  418. {
  419. printText_.Push('\n');
  420. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  421. rowWidth = 0;
  422. nextBreak = lineStart = i;
  423. }
  424. }
  425. }
  426. rowWidth = 0;
  427. for (unsigned i = 0; i < printText_.Size(); ++i)
  428. {
  429. unsigned c = printText_[i];
  430. if (c != '\n')
  431. {
  432. const FontGlyph* glyph = face->GetGlyph(c);
  433. if (glyph)
  434. {
  435. rowWidth += glyph->advanceX_;
  436. if (i < printText_.Size() - 1)
  437. rowWidth += face->GetKerning(c, printText_[i + 1]);
  438. }
  439. }
  440. else
  441. {
  442. width = Max(width, rowWidth);
  443. height += rowHeight;
  444. rowWidths_.Push(rowWidth);
  445. rowWidth = 0;
  446. }
  447. }
  448. if (rowWidth)
  449. {
  450. width = Max(width, rowWidth);
  451. height += rowHeight;
  452. rowWidths_.Push(rowWidth);
  453. }
  454. // Set row height even if text is empty
  455. if (!height)
  456. height = rowHeight;
  457. // Store position & size of each character
  458. charPositions_.Resize(unicodeText_.Size() + 1);
  459. charSizes_.Resize(unicodeText_.Size());
  460. unsigned rowIndex = 0;
  461. int x = GetRowStartPosition(rowIndex);
  462. int y = 0;
  463. for (unsigned i = 0; i < printText_.Size(); ++i)
  464. {
  465. charPositions_[printToText[i]] = IntVector2(x, y);
  466. unsigned c = printText_[i];
  467. if (c != '\n')
  468. {
  469. const FontGlyph* glyph = face->GetGlyph(c);
  470. charSizes_[printToText[i]] = IntVector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  471. if (glyph)
  472. {
  473. x += glyph->advanceX_;
  474. if (i < printText_.Size() - 1)
  475. x += face->GetKerning(c, printText_[i + 1]);
  476. }
  477. }
  478. else
  479. {
  480. charSizes_[printToText[i]] = IntVector2::ZERO;
  481. x = GetRowStartPosition(++rowIndex);
  482. y += rowHeight;
  483. }
  484. }
  485. // Store the ending position
  486. charPositions_[unicodeText_.Size()] = IntVector2(x, y);
  487. }
  488. // Set minimum and current size according to the text size, but respect fixed width if set
  489. if (!IsFixedWidth())
  490. {
  491. SetMinWidth(wordWrap_ ? 0 : width);
  492. SetWidth(width);
  493. }
  494. SetFixedHeight(height);
  495. }
  496. void Text::ValidateSelection()
  497. {
  498. unsigned textLength = unicodeText_.Size();
  499. if (textLength)
  500. {
  501. if (selectionStart_ >= textLength)
  502. selectionStart_ = textLength - 1;
  503. if (selectionStart_ + selectionLength_ > textLength)
  504. selectionLength_ = textLength - selectionStart_;
  505. }
  506. else
  507. {
  508. selectionStart_ = 0;
  509. selectionLength_ = 0;
  510. }
  511. }
  512. int Text::GetRowStartPosition(unsigned rowIndex) const
  513. {
  514. int rowWidth = 0;
  515. if (rowIndex < rowWidths_.Size())
  516. rowWidth = rowWidths_[rowIndex];
  517. int ret = GetIndentWidth();
  518. switch (textAlignment_)
  519. {
  520. case HA_LEFT:
  521. break;
  522. case HA_CENTER:
  523. ret += (GetSize().x_ - rowWidth) / 2;
  524. break;
  525. case HA_RIGHT:
  526. ret += GetSize().x_ - rowWidth;
  527. break;
  528. }
  529. return ret;
  530. }
  531. }