Text.cpp 18 KB

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