Text.cpp 18 KB

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