Text.cpp 16 KB

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