Text.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "Font.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "ResourceCache.h"
  29. #include "StringUtils.h"
  30. #include "Text.h"
  31. #include "Texture2D.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. static const float MIN_ROW_SPACING = 0.5f;
  36. static const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. ""
  42. };
  43. OBJECTTYPESTATIC(Text);
  44. Text::Text(Context* context) :
  45. UIElement(context),
  46. fontSize_(DEFAULT_FONT_SIZE),
  47. textAlignment_(HA_LEFT),
  48. rowSpacing_(1.0f),
  49. wordWrap_(false),
  50. selectionStart_(0),
  51. selectionLength_(0),
  52. selectionColor_(Color(0.0f, 0.0f, 0.0f, 0.0f)),
  53. hoverColor_(Color(0.0f, 0.0f, 0.0f, 0.0f)),
  54. rowHeight_(0)
  55. {
  56. }
  57. Text::~Text()
  58. {
  59. }
  60. void Text::RegisterObject(Context* context)
  61. {
  62. context->RegisterFactory<Text>();
  63. COPY_BASE_ATTRIBUTES(Text, UIElement);
  64. ACCESSOR_ATTRIBUTE(Text, VAR_RESOURCEREF, "Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  65. ATTRIBUTE(Text, VAR_INT, "Font Size", fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  66. ATTRIBUTE(Text, VAR_STRING, "Text", text_, String(), AM_FILE);
  67. ENUM_ATTRIBUTE(Text, "Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  68. ATTRIBUTE(Text, VAR_FLOAT, "Row Spacing", rowSpacing_, 1.0f, AM_FILE);
  69. ATTRIBUTE(Text, VAR_BOOL, "Word Wrap", wordWrap_, false, AM_FILE);
  70. ATTRIBUTE(Text, VAR_INT, "Selection Start", selectionStart_, 0, AM_FILE);
  71. ATTRIBUTE(Text, VAR_INT, "Selection Length", selectionLength_, 0, AM_FILE);
  72. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::BLACK, AM_FILE);
  73. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Hover Color", GetHoverColor, SetHoverColor, Color, Color::BLACK, AM_FILE);
  74. }
  75. void Text::ApplyAttributes()
  76. {
  77. UIElement::ApplyAttributes();
  78. fontSize_ = Max(fontSize_, 1);
  79. ValidateSelection();
  80. UpdateText();
  81. }
  82. void Text::SetStyle(const XMLElement& element)
  83. {
  84. UIElement::SetStyle(element);
  85. // Recalculating the text is expensive, so do it only once at the end if something changed
  86. bool changed = false;
  87. if (element.HasChild("font"))
  88. {
  89. XMLElement fontElem = element.GetChild("font");
  90. String fontName = fontElem.GetAttribute("name");
  91. ResourceCache* cache = GetSubsystem<ResourceCache>();
  92. if (cache->Exists(fontName))
  93. {
  94. Font* font = cache->GetResource<Font>(fontName);
  95. if (font)
  96. {
  97. font_ = font;
  98. fontSize_ = Max(fontElem.GetInt("size"), 1);
  99. changed = true;
  100. }
  101. }
  102. else if (element.HasChild("fallbackfont"))
  103. {
  104. fontElem = element.GetChild("fallbackfont");
  105. String fontName = fontElem.GetAttribute("name");
  106. Font* font = cache->GetResource<Font>(fontName);
  107. if (font)
  108. {
  109. font_ = font;
  110. fontSize_ = Max(fontElem.GetInt("size"), 1);
  111. changed = true;
  112. }
  113. }
  114. }
  115. if (element.HasChild("text"))
  116. {
  117. // Do not call SetText() as that would possibly resize the element
  118. text_ = String(element.GetChild("text").GetAttribute("value")).Replaced("\\n", "\n");
  119. unicodeText_.Clear();
  120. for (unsigned i = 0; i < text_.Length();)
  121. unicodeText_.Push(text_.NextUTF8Char(i));
  122. changed = true;
  123. }
  124. if (element.HasChild("textalignment"))
  125. {
  126. String horiz = element.GetChild("textalignment").GetAttributeLower("value");
  127. if (!horiz.Empty())
  128. {
  129. textAlignment_ = (HorizontalAlignment)GetStringListIndex(horiz.CString(), horizontalAlignments, HA_LEFT);
  130. changed = true;
  131. }
  132. }
  133. if (element.HasChild("rowspacing"))
  134. {
  135. rowSpacing_ = Max(element.GetChild("rowspacing").GetFloat("value"), MIN_ROW_SPACING);
  136. changed = true;
  137. }
  138. if (element.HasChild("wordwrap"))
  139. {
  140. wordWrap_ = element.GetChild("wordwrap").GetBool("enable");
  141. changed = true;
  142. }
  143. if (element.HasChild("selection"))
  144. {
  145. XMLElement selectionElem = element.GetChild("selection");
  146. selectionStart_ = selectionElem.GetInt("start");
  147. selectionLength_ = selectionElem.GetInt("length");
  148. changed = true;
  149. }
  150. if (element.HasChild("selectioncolor"))
  151. SetSelectionColor(element.GetChild("selectioncolor").GetColor("value"));
  152. if (element.HasChild("hovercolor"))
  153. SetHoverColor(element.GetChild("hovercolor").GetColor("value"));
  154. if (changed)
  155. {
  156. ValidateSelection();
  157. UpdateText();
  158. }
  159. }
  160. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  161. {
  162. // Hovering or whole selection batch
  163. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  164. {
  165. UIBatch batch;
  166. batch.Begin(&quads);
  167. batch.blendMode_ = BLEND_ALPHA;
  168. batch.scissor_ = currentScissor;
  169. batch.texture_ = 0;
  170. batch.AddQuad(*this, 0, 0, GetWidth(), GetHeight(), 0, 0, 0, 0, selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ :
  171. hoverColor_);
  172. UIBatch::AddOrMerge(batch, batches);
  173. }
  174. // Partial selection batch
  175. if (!selected_ && selectionLength_ && charSizes_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  176. {
  177. UIBatch batch;
  178. batch.Begin(&quads);
  179. batch.blendMode_ = BLEND_ALPHA;
  180. batch.scissor_ = currentScissor;
  181. batch.texture_ = 0;
  182. IntVector2 currentStart = charPositions_[selectionStart_];
  183. IntVector2 currentEnd = currentStart;
  184. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  185. {
  186. // Check if row changes, and start a new quad in that case
  187. if (charSizes_[i].x_ && charSizes_[i].y_)
  188. {
  189. if (charPositions_[i].y_ != currentStart.y_)
  190. {
  191. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  192. 0, 0, 0, 0, selectionColor_);
  193. currentStart = charPositions_[i];
  194. currentEnd = currentStart + charSizes_[i];
  195. }
  196. else
  197. {
  198. currentEnd.x_ += charSizes_[i].x_;
  199. currentEnd.y_ = Max(currentStart.y_ + charSizes_[i].y_, currentEnd.y_);
  200. }
  201. }
  202. }
  203. if (currentEnd != currentStart)
  204. {
  205. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  206. 0, 0, 0, 0, selectionColor_);
  207. }
  208. UIBatch::AddOrMerge(batch, batches);
  209. }
  210. // Text batch
  211. if (font_)
  212. {
  213. const FontFace* face = font_->GetFace(fontSize_);
  214. if (!face)
  215. return;
  216. UIBatch batch;
  217. batch.Begin(&quads);
  218. batch.blendMode_ = BLEND_ALPHA;
  219. batch.scissor_ = currentScissor;
  220. batch.texture_ = face->texture_;
  221. unsigned rowIndex = 0;
  222. int x = GetRowStartPosition(rowIndex);
  223. int y = 0;
  224. for (unsigned i = 0; i < printText_.Size(); ++i)
  225. {
  226. unsigned c = printText_[i];
  227. if (c != '\n')
  228. {
  229. const FontGlyph& glyph = face->GetGlyph(c);
  230. if (c != ' ')
  231. batch.AddQuad(*this, x + glyph.offsetX_, y + glyph.offsetY_, glyph.width_, glyph.height_, glyph.x_, glyph.y_);
  232. x += glyph.advanceX_;
  233. if (i < printText_.Size() - 1)
  234. x += face->GetKerning(c, printText_[i + 1]);
  235. }
  236. else
  237. {
  238. rowIndex++;
  239. x = GetRowStartPosition(rowIndex);
  240. y += rowHeight_;
  241. }
  242. }
  243. UIBatch::AddOrMerge(batch, batches);
  244. }
  245. // Reset hovering for next frame
  246. hovering_ = false;
  247. }
  248. void Text::OnResize()
  249. {
  250. if (wordWrap_)
  251. UpdateText();
  252. }
  253. bool Text::SetFont(const String& fontName, int size)
  254. {
  255. ResourceCache* cache = GetSubsystem<ResourceCache>();
  256. return SetFont(cache->GetResource<Font>(fontName), size);
  257. }
  258. bool Text::SetFont(Font* font, int size)
  259. {
  260. if (!font)
  261. {
  262. LOGERROR("Null font for Text");
  263. return false;
  264. }
  265. if (font != font_ || size != fontSize_)
  266. {
  267. font_ = font;
  268. fontSize_ = Max(size, 1);
  269. UpdateText();
  270. }
  271. return true;
  272. }
  273. void Text::SetText(const String& text)
  274. {
  275. text_ = text;
  276. // Decode to Unicode now
  277. unicodeText_.Clear();
  278. for (unsigned i = 0; i < text_.Length();)
  279. unicodeText_.Push(text_.NextUTF8Char(i));
  280. ValidateSelection();
  281. UpdateText();
  282. }
  283. void Text::SetTextAlignment(HorizontalAlignment align)
  284. {
  285. if (align != textAlignment_)
  286. {
  287. textAlignment_ = align;
  288. UpdateText();
  289. }
  290. }
  291. void Text::SetRowSpacing(float spacing)
  292. {
  293. if (spacing != rowSpacing_)
  294. {
  295. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  296. UpdateText();
  297. }
  298. }
  299. void Text::SetWordwrap(bool enable)
  300. {
  301. if (enable != wordWrap_)
  302. {
  303. wordWrap_ = enable;
  304. UpdateText();
  305. }
  306. }
  307. void Text::SetSelection(unsigned start, unsigned length)
  308. {
  309. selectionStart_ = start;
  310. selectionLength_ = length;
  311. ValidateSelection();
  312. }
  313. void Text::ClearSelection()
  314. {
  315. selectionStart_ = 0;
  316. selectionLength_ = 0;
  317. }
  318. void Text::SetSelectionColor(const Color& color)
  319. {
  320. selectionColor_ = color;
  321. }
  322. void Text::SetHoverColor(const Color& color)
  323. {
  324. hoverColor_ = color;
  325. }
  326. void Text::SetFontAttr(ResourceRef value)
  327. {
  328. ResourceCache* cache = GetSubsystem<ResourceCache>();
  329. font_ = cache->GetResource<Font>(value.id_);
  330. }
  331. ResourceRef Text::GetFontAttr() const
  332. {
  333. return GetResourceRef(font_, Font::GetTypeStatic());
  334. }
  335. void Text::UpdateText(bool inResize)
  336. {
  337. int width = 0;
  338. int height = 0;
  339. rowWidths_.Clear();
  340. printText_.Clear();
  341. PODVector<unsigned> printToText;
  342. if (font_)
  343. {
  344. const FontFace* face = font_->GetFace(fontSize_);
  345. if (!face)
  346. return;
  347. rowHeight_ = face->rowHeight_;
  348. int rowWidth = 0;
  349. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  350. // First see if the text must be split up
  351. if (!wordWrap_)
  352. {
  353. printText_ = unicodeText_;
  354. printToText.Resize(printText_.Size());
  355. for (unsigned i = 0; i < printText_.Size(); ++i)
  356. printToText[i] = i;
  357. }
  358. else
  359. {
  360. int maxWidth = GetWidth();
  361. unsigned nextBreak = 0;
  362. unsigned lineStart = 0;
  363. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  364. {
  365. unsigned j;
  366. unsigned c = unicodeText_[i];
  367. if (c != '\n')
  368. {
  369. bool ok = true;
  370. if (nextBreak <= i)
  371. {
  372. int futureRowWidth = rowWidth;
  373. for (j = i; j < unicodeText_.Size(); ++j)
  374. {
  375. unsigned d = unicodeText_[j];
  376. if (d == ' ' || d == '\n')
  377. {
  378. nextBreak = j;
  379. break;
  380. }
  381. futureRowWidth += face->GetGlyph(d).advanceX_;
  382. if (j < unicodeText_.Size() - 1)
  383. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  384. if (d == '-' && futureRowWidth <= maxWidth)
  385. {
  386. nextBreak = j + 1;
  387. break;
  388. }
  389. if (futureRowWidth > maxWidth)
  390. {
  391. ok = false;
  392. break;
  393. }
  394. }
  395. }
  396. if (!ok)
  397. {
  398. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  399. if (nextBreak == lineStart)
  400. {
  401. while (i < j)
  402. {
  403. printText_.Push(unicodeText_[i]);
  404. printToText.Push(i);
  405. ++i;
  406. }
  407. }
  408. printText_.Push('\n');
  409. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  410. rowWidth = 0;
  411. nextBreak = lineStart = i;
  412. }
  413. if (i < unicodeText_.Size())
  414. {
  415. // When copying a space, position is allowed to be over row width
  416. c = unicodeText_[i];
  417. rowWidth += face->GetGlyph(c).advanceX_;
  418. if (i < text_.Length() - 1)
  419. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  420. if (rowWidth <= maxWidth)
  421. {
  422. printText_.Push(c);
  423. printToText.Push(i);
  424. }
  425. }
  426. }
  427. else
  428. {
  429. printText_.Push('\n');
  430. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  431. rowWidth = 0;
  432. nextBreak = lineStart = i;
  433. }
  434. }
  435. }
  436. rowWidth = 0;
  437. for (unsigned i = 0; i < printText_.Size(); ++i)
  438. {
  439. unsigned c = printText_[i];
  440. if (c != '\n')
  441. {
  442. const FontGlyph& glyph = face->GetGlyph(c);
  443. rowWidth += glyph.advanceX_;
  444. if (i < printText_.Size() - 1)
  445. rowWidth += face->GetKerning(c, printText_[i + 1]);
  446. }
  447. else
  448. {
  449. width = Max(width, rowWidth);
  450. height += rowHeight;
  451. rowWidths_.Push(rowWidth);
  452. rowWidth = 0;
  453. }
  454. }
  455. if (rowWidth)
  456. {
  457. width = Max(width, rowWidth);
  458. height += rowHeight;
  459. rowWidths_.Push(rowWidth);
  460. }
  461. // Set row height even if text is empty
  462. if (!height)
  463. height = rowHeight;
  464. // Store position & size of each character
  465. charPositions_.Resize(unicodeText_.Size() + 1);
  466. charSizes_.Resize(unicodeText_.Size());
  467. unsigned rowIndex = 0;
  468. int x = GetRowStartPosition(rowIndex);
  469. int y = 0;
  470. for (unsigned i = 0; i < printText_.Size(); ++i)
  471. {
  472. charPositions_[printToText[i]] = IntVector2(x, y);
  473. unsigned c = printText_[i];
  474. if (c != '\n')
  475. {
  476. const FontGlyph& glyph = face->GetGlyph(c);
  477. charSizes_[printToText[i]] = IntVector2(glyph.advanceX_, rowHeight_);
  478. x += glyph.advanceX_;
  479. if (i < printText_.Size() - 1)
  480. x += face->GetKerning(c, printText_[i + 1]);
  481. }
  482. else
  483. {
  484. charSizes_[printToText[i]] = IntVector2::ZERO;
  485. rowIndex++;
  486. x = GetRowStartPosition(rowIndex);
  487. y += rowHeight;
  488. }
  489. }
  490. // Store the ending position
  491. charPositions_[unicodeText_.Size()] = IntVector2(x, y);
  492. }
  493. // Set minimum and current size according to the text size, but respect fixed width if set
  494. if (GetMinWidth() != GetMaxWidth())
  495. {
  496. SetMinWidth(width);
  497. SetWidth(width);
  498. }
  499. SetFixedHeight(height);
  500. }
  501. void Text::ValidateSelection()
  502. {
  503. unsigned textLength = unicodeText_.Size();
  504. if (textLength)
  505. {
  506. if (selectionStart_ >= textLength)
  507. selectionStart_ = textLength - 1;
  508. if (selectionStart_ + selectionLength_ > textLength)
  509. selectionLength_ = textLength - selectionStart_;
  510. }
  511. else
  512. {
  513. selectionStart_ = 0;
  514. selectionLength_ = 0;
  515. }
  516. }
  517. int Text::GetRowStartPosition(unsigned rowIndex) const
  518. {
  519. int rowWidth = 0;
  520. if (rowIndex < rowWidths_.Size())
  521. rowWidth = rowWidths_[rowIndex];
  522. switch (textAlignment_)
  523. {
  524. default:
  525. return 0;
  526. case HA_CENTER:
  527. return (GetSize().x_ - rowWidth) / 2;
  528. case HA_RIGHT:
  529. return GetSize().x_ - rowWidth;
  530. }
  531. }
  532. }