Text.cpp 16 KB

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