Text.cpp 17 KB

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