Text.cpp 19 KB

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