Text.cpp 17 KB

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