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.HasChild("font"))
  68. {
  69. XMLElement fontElem = element.GetChild("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.HasChild("fallbackfont"))
  83. {
  84. fontElem = element.GetChild("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.HasChild("text"))
  96. {
  97. text_ = element.GetChild("text").GetString("value").Replaced("\\n", "\n");
  98. changed = true;
  99. }
  100. if (element.HasChild("textalignment"))
  101. {
  102. String horiz = element.GetChild("textalignment").GetStringLower("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_.Length(); ++i)
  201. {
  202. unsigned char c = (unsigned char)printText_[i];
  203. if (c != '\n')
  204. {
  205. const FontGlyph& glyph = face->glyphs_[face->glyphIndex_[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. }
  210. else
  211. {
  212. rowIndex++;
  213. x = GetRowStartPosition(rowIndex);
  214. y += rowHeight_;
  215. }
  216. }
  217. UIBatch::AddOrMerge(batch, batches);
  218. }
  219. // Reset hovering for next frame
  220. hovering_ = false;
  221. }
  222. void Text::OnResize()
  223. {
  224. if (wordWrap_)
  225. UpdateText();
  226. }
  227. bool Text::SetFont(const String& fontName, int size)
  228. {
  229. ResourceCache* cache = GetSubsystem<ResourceCache>();
  230. return SetFont(cache->GetResource<Font>(fontName), size);
  231. }
  232. bool Text::SetFont(Font* font, int size)
  233. {
  234. if (!font)
  235. {
  236. LOGERROR("Null font for Text");
  237. return false;
  238. }
  239. if (font != font_ || size != fontSize_)
  240. {
  241. font_ = font;
  242. fontSize_ = Max(size, 1);
  243. UpdateText();
  244. }
  245. return true;
  246. }
  247. void Text::SetText(const String& text)
  248. {
  249. text_ = text;
  250. ValidateSelection();
  251. UpdateText();
  252. }
  253. void Text::SetTextAlignment(HorizontalAlignment align)
  254. {
  255. if (align != textAlignment_)
  256. {
  257. textAlignment_ = align;
  258. UpdateText();
  259. }
  260. }
  261. void Text::SetRowSpacing(float spacing)
  262. {
  263. if (spacing != rowSpacing_)
  264. {
  265. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  266. UpdateText();
  267. }
  268. }
  269. void Text::SetWordwrap(bool enable)
  270. {
  271. if (enable != wordWrap_)
  272. {
  273. wordWrap_ = enable;
  274. UpdateText();
  275. }
  276. }
  277. void Text::SetSelection(unsigned start, unsigned length)
  278. {
  279. selectionStart_ = start;
  280. selectionLength_ = length;
  281. ValidateSelection();
  282. }
  283. void Text::ClearSelection()
  284. {
  285. selectionStart_ = 0;
  286. selectionLength_ = 0;
  287. }
  288. void Text::SetSelectionColor(const Color& color)
  289. {
  290. selectionColor_ = color;
  291. }
  292. void Text::SetHoverColor(const Color& color)
  293. {
  294. hoverColor_ = color;
  295. }
  296. void Text::UpdateText(bool inResize)
  297. {
  298. int width = 0;
  299. int height = 0;
  300. rowWidths_.Clear();
  301. printText_.Clear();
  302. PODVector<unsigned> printToText;
  303. if (font_)
  304. {
  305. const FontFace* face = font_->GetFace(fontSize_);
  306. if (!face)
  307. return;
  308. rowHeight_ = face->rowHeight_;
  309. int rowWidth = 0;
  310. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  311. // First see if the text must be split up
  312. if (!wordWrap_)
  313. {
  314. printText_ = text_;
  315. printToText.Resize(text_.Length());
  316. for (unsigned i = 0; i < text_.Length(); ++i)
  317. printToText[i] = i;
  318. }
  319. else
  320. {
  321. int maxWidth = GetWidth();
  322. unsigned nextBreak = 0;
  323. unsigned lineStart = 0;
  324. for (unsigned i = 0; i < text_.Length(); ++i)
  325. {
  326. unsigned j;
  327. if (text_[i] != '\n')
  328. {
  329. bool ok = true;
  330. if (nextBreak <= i)
  331. {
  332. int futureRowWidth = rowWidth;
  333. for (j = i; j < text_.Length(); ++j)
  334. {
  335. if (text_[j] == ' ' || text_[j] == '\n')
  336. {
  337. nextBreak = j;
  338. break;
  339. }
  340. futureRowWidth += face->glyphs_[face->glyphIndex_[text_[j]]].advanceX_;
  341. if (text_[j] == '-' && futureRowWidth <= maxWidth)
  342. {
  343. nextBreak = j + 1;
  344. break;
  345. }
  346. if (futureRowWidth > maxWidth)
  347. {
  348. ok = false;
  349. break;
  350. }
  351. }
  352. }
  353. if (!ok)
  354. {
  355. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  356. if (nextBreak == lineStart)
  357. {
  358. int copyLength = Max(j - i, 1);
  359. printText_ += text_.Substring(i, copyLength);
  360. for (int k = 0; k < copyLength; ++k)
  361. {
  362. printToText.Push(i);
  363. ++i;
  364. }
  365. }
  366. printText_ += '\n';
  367. printToText.Push(Min((int)i, (int)text_.Length() - 1));
  368. rowWidth = 0;
  369. nextBreak = lineStart = i;
  370. }
  371. if (i < text_.Length())
  372. {
  373. // When copying a space, position is allowed to be over row width
  374. rowWidth += face->glyphs_[face->glyphIndex_[text_[i]]].advanceX_;
  375. if (rowWidth <= maxWidth)
  376. {
  377. printText_ += text_[i];
  378. printToText.Push(i);
  379. }
  380. }
  381. }
  382. else
  383. {
  384. printText_ += '\n';
  385. printToText.Push(Min((int)i, (int)text_.Length() - 1));
  386. rowWidth = 0;
  387. nextBreak = lineStart = i;
  388. }
  389. }
  390. }
  391. rowWidth = 0;
  392. for (unsigned i = 0; i < printText_.Length(); ++i)
  393. {
  394. unsigned char c = (unsigned char)printText_[i];
  395. if (c != '\n')
  396. {
  397. const FontGlyph& glyph = face->glyphs_[face->glyphIndex_[c]];
  398. rowWidth += glyph.advanceX_;
  399. }
  400. else
  401. {
  402. width = Max(width, rowWidth);
  403. height += rowHeight;
  404. rowWidths_.Push(rowWidth);
  405. rowWidth = 0;
  406. }
  407. }
  408. if (rowWidth)
  409. {
  410. width = Max(width, rowWidth);
  411. height += rowHeight;
  412. rowWidths_.Push(rowWidth);
  413. }
  414. // Set row height even if text is empty
  415. if (!height)
  416. height = rowHeight;
  417. // Store position & size of each character
  418. charPositions_.Resize(text_.Length() + 1);
  419. charSizes_.Resize(text_.Length());
  420. unsigned rowIndex = 0;
  421. int x = GetRowStartPosition(rowIndex);
  422. int y = 0;
  423. for (unsigned i = 0; i < printText_.Length(); ++i)
  424. {
  425. charPositions_[printToText[i]] = IntVector2(x, y);
  426. unsigned char c = (unsigned char)printText_[i];
  427. if (c != '\n')
  428. {
  429. const FontGlyph& glyph = face->glyphs_[face->glyphIndex_[c]];
  430. charSizes_[printToText[i]] = IntVector2(glyph.advanceX_, rowHeight_);
  431. x += glyph.advanceX_;
  432. }
  433. else
  434. {
  435. charSizes_[printToText[i]] = IntVector2::ZERO;
  436. rowIndex++;
  437. x = GetRowStartPosition(rowIndex);
  438. y += rowHeight;
  439. }
  440. }
  441. // Store the ending position
  442. charPositions_[text_.Length()] = IntVector2(x, y);
  443. }
  444. // Set minimum and current size according to the text size, but respect fixed width if set
  445. if (GetMinWidth() != GetMaxWidth())
  446. {
  447. SetMinWidth(width);
  448. SetWidth(width);
  449. }
  450. SetFixedHeight(height);
  451. }
  452. void Text::ValidateSelection()
  453. {
  454. unsigned textLength = text_.Length();
  455. if (textLength)
  456. {
  457. if (selectionStart_ >= textLength)
  458. selectionStart_ = textLength - 1;
  459. if (selectionStart_ + selectionLength_ > textLength)
  460. selectionLength_ = textLength - selectionStart_;
  461. }
  462. else
  463. {
  464. selectionStart_ = 0;
  465. selectionLength_ = 0;
  466. }
  467. }
  468. int Text::GetRowStartPosition(unsigned rowIndex) const
  469. {
  470. int rowWidth = 0;
  471. if (rowIndex < rowWidths_.Size())
  472. rowWidth = rowWidths_[rowIndex];
  473. switch (textAlignment_)
  474. {
  475. default:
  476. return 0;
  477. case HA_CENTER:
  478. return (GetSize().x_ - rowWidth) / 2;
  479. case HA_RIGHT:
  480. return GetSize().x_ - rowWidth;
  481. }
  482. }