Text.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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->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_.Length() - 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. 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->GetGlyph(text_[j]).advanceX_;
  343. if (j < text_.Length() - 1)
  344. futureRowWidth += face->GetKerning(text_[j], text_[j + 1]);
  345. if (text_[j] == '-' && futureRowWidth <= maxWidth)
  346. {
  347. nextBreak = j + 1;
  348. break;
  349. }
  350. if (futureRowWidth > maxWidth)
  351. {
  352. ok = false;
  353. break;
  354. }
  355. }
  356. }
  357. if (!ok)
  358. {
  359. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  360. if (nextBreak == lineStart)
  361. {
  362. int copyLength = Max(j - i, 1);
  363. printText_ += text_.Substring(i, copyLength);
  364. for (int k = 0; k < copyLength; ++k)
  365. {
  366. printToText.Push(i);
  367. ++i;
  368. }
  369. }
  370. printText_ += '\n';
  371. printToText.Push(Min((int)i, (int)text_.Length() - 1));
  372. rowWidth = 0;
  373. nextBreak = lineStart = i;
  374. }
  375. if (i < text_.Length())
  376. {
  377. // When copying a space, position is allowed to be over row width
  378. rowWidth += face->GetGlyph(text_[i]).advanceX_;
  379. if (i < text_.Length() - 1)
  380. rowWidth += face->GetKerning(text_[i], text_[i + 1]);
  381. if (rowWidth <= maxWidth)
  382. {
  383. printText_ += text_[i];
  384. printToText.Push(i);
  385. }
  386. }
  387. }
  388. else
  389. {
  390. printText_ += '\n';
  391. printToText.Push(Min((int)i, (int)text_.Length() - 1));
  392. rowWidth = 0;
  393. nextBreak = lineStart = i;
  394. }
  395. }
  396. }
  397. rowWidth = 0;
  398. for (unsigned i = 0; i < printText_.Length(); ++i)
  399. {
  400. unsigned char c = (unsigned char)printText_[i];
  401. if (c != '\n')
  402. {
  403. const FontGlyph& glyph = face->GetGlyph(c);
  404. rowWidth += glyph.advanceX_;
  405. if (i < printText_.Length() - 1)
  406. rowWidth += face->GetKerning(c, printText_[i + 1]);
  407. }
  408. else
  409. {
  410. width = Max(width, rowWidth);
  411. height += rowHeight;
  412. rowWidths_.Push(rowWidth);
  413. rowWidth = 0;
  414. }
  415. }
  416. if (rowWidth)
  417. {
  418. width = Max(width, rowWidth);
  419. height += rowHeight;
  420. rowWidths_.Push(rowWidth);
  421. }
  422. // Set row height even if text is empty
  423. if (!height)
  424. height = rowHeight;
  425. // Store position & size of each character
  426. charPositions_.Resize(text_.Length() + 1);
  427. charSizes_.Resize(text_.Length());
  428. unsigned rowIndex = 0;
  429. int x = GetRowStartPosition(rowIndex);
  430. int y = 0;
  431. for (unsigned i = 0; i < printText_.Length(); ++i)
  432. {
  433. charPositions_[printToText[i]] = IntVector2(x, y);
  434. unsigned char c = (unsigned char)printText_[i];
  435. if (c != '\n')
  436. {
  437. const FontGlyph& glyph = face->GetGlyph(c);
  438. charSizes_[printToText[i]] = IntVector2(glyph.advanceX_, rowHeight_);
  439. x += glyph.advanceX_;
  440. if (i < printText_.Length() - 1)
  441. x += face->GetKerning(c, printText_[i + 1]);
  442. }
  443. else
  444. {
  445. charSizes_[printToText[i]] = IntVector2::ZERO;
  446. rowIndex++;
  447. x = GetRowStartPosition(rowIndex);
  448. y += rowHeight;
  449. }
  450. }
  451. // Store the ending position
  452. charPositions_[text_.Length()] = IntVector2(x, y);
  453. }
  454. // Set minimum and current size according to the text size, but respect fixed width if set
  455. if (GetMinWidth() != GetMaxWidth())
  456. {
  457. SetMinWidth(width);
  458. SetWidth(width);
  459. }
  460. SetFixedHeight(height);
  461. }
  462. void Text::ValidateSelection()
  463. {
  464. unsigned textLength = text_.Length();
  465. if (textLength)
  466. {
  467. if (selectionStart_ >= textLength)
  468. selectionStart_ = textLength - 1;
  469. if (selectionStart_ + selectionLength_ > textLength)
  470. selectionLength_ = textLength - selectionStart_;
  471. }
  472. else
  473. {
  474. selectionStart_ = 0;
  475. selectionLength_ = 0;
  476. }
  477. }
  478. int Text::GetRowStartPosition(unsigned rowIndex) const
  479. {
  480. int rowWidth = 0;
  481. if (rowIndex < rowWidths_.Size())
  482. rowWidth = rowWidths_[rowIndex];
  483. switch (textAlignment_)
  484. {
  485. default:
  486. return 0;
  487. case HA_CENTER:
  488. return (GetSize().x_ - rowWidth) / 2;
  489. case HA_RIGHT:
  490. return GetSize().x_ - rowWidth;
  491. }
  492. }