Text.cpp 19 KB

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