Text.cpp 17 KB

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