Text.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Font.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "StringUtils.h"
  29. #include "Text.h"
  30. #include "Texture2D.h"
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. static const float MIN_ROW_SPACING = 0.5f;
  35. static const char* horizontalAlignments[] =
  36. {
  37. "Left",
  38. "Center",
  39. "Right",
  40. ""
  41. };
  42. OBJECTTYPESTATIC(Text);
  43. Text::Text(Context* context) :
  44. UIElement(context),
  45. fontSize_(DEFAULT_FONT_SIZE),
  46. textAlignment_(HA_LEFT),
  47. rowSpacing_(1.0f),
  48. wordWrap_(false),
  49. selectionStart_(0),
  50. selectionLength_(0),
  51. selectionColor_(Color::TRANSPARENT),
  52. hoverColor_(Color::TRANSPARENT),
  53. rowHeight_(0)
  54. {
  55. }
  56. Text::~Text()
  57. {
  58. }
  59. void Text::RegisterObject(Context* context)
  60. {
  61. context->RegisterFactory<Text>();
  62. ACCESSOR_ATTRIBUTE(Text, VAR_RESOURCEREF, "Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  63. ATTRIBUTE(Text, VAR_INT, "Font Size", fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  64. ATTRIBUTE(Text, VAR_STRING, "Text", text_, String::EMPTY, AM_FILE);
  65. ENUM_ATTRIBUTE(Text, "Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  66. ATTRIBUTE(Text, VAR_FLOAT, "Row Spacing", rowSpacing_, 1.0f, AM_FILE);
  67. ATTRIBUTE(Text, VAR_BOOL, "Word Wrap", wordWrap_, false, AM_FILE);
  68. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::TRANSPARENT, AM_FILE);
  69. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Hover Color", GetHoverColor, SetHoverColor, Color, Color::TRANSPARENT, AM_FILE);
  70. COPY_BASE_ATTRIBUTES(Text, UIElement);
  71. }
  72. void Text::ApplyAttributes()
  73. {
  74. UIElement::ApplyAttributes();
  75. // Decode to Unicode now
  76. unicodeText_.Clear();
  77. for (unsigned i = 0; i < text_.Length();)
  78. unicodeText_.Push(text_.NextUTF8Char(i));
  79. fontSize_ = Max(fontSize_, 1);
  80. ValidateSelection();
  81. UpdateText();
  82. }
  83. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  84. {
  85. // Hovering or whole selection batch
  86. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  87. {
  88. UIBatch batch(BLEND_ALPHA, currentScissor, 0, &quads);
  89. batch.AddQuad(*this, 0, 0, GetWidth(), GetHeight(), 0, 0, 0, 0, selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ :
  90. hoverColor_);
  91. UIBatch::AddOrMerge(batch, batches);
  92. }
  93. // Partial selection batch
  94. if (!selected_ && selectionLength_ && charSizes_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  95. {
  96. UIBatch batch(BLEND_ALPHA, currentScissor, 0, &quads);
  97. IntVector2 currentStart = charPositions_[selectionStart_];
  98. IntVector2 currentEnd = currentStart;
  99. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  100. {
  101. // Check if row changes, and start a new quad in that case
  102. if (charSizes_[i].x_ && charSizes_[i].y_)
  103. {
  104. if (charPositions_[i].y_ != currentStart.y_)
  105. {
  106. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  107. 0, 0, 0, 0, selectionColor_);
  108. currentStart = charPositions_[i];
  109. currentEnd = currentStart + charSizes_[i];
  110. }
  111. else
  112. {
  113. currentEnd.x_ += charSizes_[i].x_;
  114. currentEnd.y_ = Max(currentStart.y_ + charSizes_[i].y_, currentEnd.y_);
  115. }
  116. }
  117. }
  118. if (currentEnd != currentStart)
  119. {
  120. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  121. 0, 0, 0, 0, selectionColor_);
  122. }
  123. UIBatch::AddOrMerge(batch, batches);
  124. }
  125. // Text batch
  126. if (font_)
  127. {
  128. const FontFace* face = font_->GetFace(fontSize_);
  129. if (!face)
  130. return;
  131. UIBatch batch(BLEND_ALPHA, currentScissor, face->texture_, &quads);
  132. unsigned rowIndex = 0;
  133. int x = GetRowStartPosition(rowIndex);
  134. int y = 0;
  135. for (unsigned i = 0; i < printText_.Size(); ++i)
  136. {
  137. unsigned c = printText_[i];
  138. if (c != '\n')
  139. {
  140. const FontGlyph& glyph = face->GetGlyph(c);
  141. if (c != ' ')
  142. batch.AddQuad(*this, x + glyph.offsetX_, y + glyph.offsetY_, glyph.width_, glyph.height_, glyph.x_, glyph.y_);
  143. x += glyph.advanceX_;
  144. if (i < printText_.Size() - 1)
  145. x += face->GetKerning(c, printText_[i + 1]);
  146. }
  147. else
  148. {
  149. x = GetRowStartPosition(++rowIndex);
  150. y += rowHeight_;
  151. }
  152. }
  153. UIBatch::AddOrMerge(batch, batches);
  154. }
  155. // Reset hovering for next frame
  156. hovering_ = false;
  157. }
  158. void Text::OnResize()
  159. {
  160. if (wordWrap_)
  161. UpdateText();
  162. }
  163. float Text::GetDerivedOpacity() const
  164. {
  165. // Text should always use its own opacity.
  166. return GetOpacity();
  167. }
  168. bool Text::SetFont(const String& fontName, int size)
  169. {
  170. ResourceCache* cache = GetSubsystem<ResourceCache>();
  171. return SetFont(cache->GetResource<Font>(fontName), size);
  172. }
  173. bool Text::SetFont(Font* font, int size)
  174. {
  175. if (!font)
  176. {
  177. LOGERROR("Null font for Text");
  178. return false;
  179. }
  180. if (font != font_ || size != fontSize_)
  181. {
  182. font_ = font;
  183. fontSize_ = Max(size, 1);
  184. UpdateText();
  185. }
  186. return true;
  187. }
  188. void Text::SetText(const String& text)
  189. {
  190. text_ = text;
  191. // Decode to Unicode now
  192. unicodeText_.Clear();
  193. for (unsigned i = 0; i < text_.Length();)
  194. unicodeText_.Push(text_.NextUTF8Char(i));
  195. ValidateSelection();
  196. UpdateText();
  197. }
  198. void Text::SetTextAlignment(HorizontalAlignment align)
  199. {
  200. if (align != textAlignment_)
  201. {
  202. textAlignment_ = align;
  203. UpdateText();
  204. }
  205. }
  206. void Text::SetRowSpacing(float spacing)
  207. {
  208. if (spacing != rowSpacing_)
  209. {
  210. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  211. UpdateText();
  212. }
  213. }
  214. void Text::SetWordwrap(bool enable)
  215. {
  216. if (enable != wordWrap_)
  217. {
  218. wordWrap_ = enable;
  219. UpdateText();
  220. }
  221. }
  222. void Text::SetSelection(unsigned start, unsigned length)
  223. {
  224. selectionStart_ = start;
  225. selectionLength_ = length;
  226. ValidateSelection();
  227. }
  228. void Text::ClearSelection()
  229. {
  230. selectionStart_ = 0;
  231. selectionLength_ = 0;
  232. }
  233. void Text::SetSelectionColor(const Color& color)
  234. {
  235. selectionColor_ = color;
  236. }
  237. void Text::SetHoverColor(const Color& color)
  238. {
  239. hoverColor_ = color;
  240. }
  241. void Text::SetFontAttr(ResourceRef value)
  242. {
  243. ResourceCache* cache = GetSubsystem<ResourceCache>();
  244. font_ = cache->GetResource<Font>(value.id_);
  245. }
  246. ResourceRef Text::GetFontAttr() const
  247. {
  248. return GetResourceRef(font_, Font::GetTypeStatic());
  249. }
  250. void Text::UpdateText(bool inResize)
  251. {
  252. int width = 0;
  253. int height = 0;
  254. rowWidths_.Clear();
  255. printText_.Clear();
  256. PODVector<unsigned> printToText;
  257. if (font_)
  258. {
  259. const FontFace* face = font_->GetFace(fontSize_);
  260. if (!face)
  261. return;
  262. rowHeight_ = face->rowHeight_;
  263. int rowWidth = 0;
  264. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  265. // First see if the text must be split up
  266. if (!wordWrap_)
  267. {
  268. printText_ = unicodeText_;
  269. printToText.Resize(printText_.Size());
  270. for (unsigned i = 0; i < printText_.Size(); ++i)
  271. printToText[i] = i;
  272. }
  273. else
  274. {
  275. int maxWidth = GetWidth();
  276. unsigned nextBreak = 0;
  277. unsigned lineStart = 0;
  278. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  279. {
  280. unsigned j;
  281. unsigned c = unicodeText_[i];
  282. if (c != '\n')
  283. {
  284. bool ok = true;
  285. if (nextBreak <= i)
  286. {
  287. int futureRowWidth = rowWidth;
  288. for (j = i; j < unicodeText_.Size(); ++j)
  289. {
  290. unsigned d = unicodeText_[j];
  291. if (d == ' ' || d == '\n')
  292. {
  293. nextBreak = j;
  294. break;
  295. }
  296. futureRowWidth += face->GetGlyph(d).advanceX_;
  297. if (j < unicodeText_.Size() - 1)
  298. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  299. if (d == '-' && futureRowWidth <= maxWidth)
  300. {
  301. nextBreak = j + 1;
  302. break;
  303. }
  304. if (futureRowWidth > maxWidth)
  305. {
  306. ok = false;
  307. break;
  308. }
  309. }
  310. }
  311. if (!ok)
  312. {
  313. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  314. if (nextBreak == lineStart)
  315. {
  316. while (i < j)
  317. {
  318. printText_.Push(unicodeText_[i]);
  319. printToText.Push(i);
  320. ++i;
  321. }
  322. }
  323. printText_.Push('\n');
  324. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  325. rowWidth = 0;
  326. nextBreak = lineStart = i;
  327. }
  328. if (i < unicodeText_.Size())
  329. {
  330. // When copying a space, position is allowed to be over row width
  331. c = unicodeText_[i];
  332. rowWidth += face->GetGlyph(c).advanceX_;
  333. if (i < text_.Length() - 1)
  334. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  335. if (rowWidth <= maxWidth)
  336. {
  337. printText_.Push(c);
  338. printToText.Push(i);
  339. }
  340. }
  341. }
  342. else
  343. {
  344. printText_.Push('\n');
  345. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  346. rowWidth = 0;
  347. nextBreak = lineStart = i;
  348. }
  349. }
  350. }
  351. rowWidth = 0;
  352. for (unsigned i = 0; i < printText_.Size(); ++i)
  353. {
  354. unsigned c = printText_[i];
  355. if (c != '\n')
  356. {
  357. const FontGlyph& glyph = face->GetGlyph(c);
  358. rowWidth += glyph.advanceX_;
  359. if (i < printText_.Size() - 1)
  360. rowWidth += face->GetKerning(c, printText_[i + 1]);
  361. }
  362. else
  363. {
  364. width = Max(width, rowWidth);
  365. height += rowHeight;
  366. rowWidths_.Push(rowWidth);
  367. rowWidth = 0;
  368. }
  369. }
  370. if (rowWidth)
  371. {
  372. width = Max(width, rowWidth);
  373. height += rowHeight;
  374. rowWidths_.Push(rowWidth);
  375. }
  376. // Set row height even if text is empty
  377. if (!height)
  378. height = rowHeight;
  379. // Store position & size of each character
  380. charPositions_.Resize(unicodeText_.Size() + 1);
  381. charSizes_.Resize(unicodeText_.Size());
  382. unsigned rowIndex = 0;
  383. int x = GetRowStartPosition(rowIndex);
  384. int y = 0;
  385. for (unsigned i = 0; i < printText_.Size(); ++i)
  386. {
  387. charPositions_[printToText[i]] = IntVector2(x, y);
  388. unsigned c = printText_[i];
  389. if (c != '\n')
  390. {
  391. const FontGlyph& glyph = face->GetGlyph(c);
  392. charSizes_[printToText[i]] = IntVector2(glyph.advanceX_, rowHeight_);
  393. x += glyph.advanceX_;
  394. if (i < printText_.Size() - 1)
  395. x += face->GetKerning(c, printText_[i + 1]);
  396. }
  397. else
  398. {
  399. charSizes_[printToText[i]] = IntVector2::ZERO;
  400. x = GetRowStartPosition(++rowIndex);
  401. y += rowHeight;
  402. }
  403. }
  404. // Store the ending position
  405. charPositions_[unicodeText_.Size()] = IntVector2(x, y);
  406. }
  407. // Set minimum and current size according to the text size, but respect fixed width if set
  408. if (GetMinWidth() != GetMaxWidth())
  409. {
  410. SetMinWidth(width);
  411. SetWidth(width);
  412. }
  413. SetFixedHeight(height);
  414. }
  415. void Text::ValidateSelection()
  416. {
  417. unsigned textLength = unicodeText_.Size();
  418. if (textLength)
  419. {
  420. if (selectionStart_ >= textLength)
  421. selectionStart_ = textLength - 1;
  422. if (selectionStart_ + selectionLength_ > textLength)
  423. selectionLength_ = textLength - selectionStart_;
  424. }
  425. else
  426. {
  427. selectionStart_ = 0;
  428. selectionLength_ = 0;
  429. }
  430. }
  431. int Text::GetRowStartPosition(unsigned rowIndex) const
  432. {
  433. int rowWidth = 0;
  434. if (rowIndex < rowWidths_.Size())
  435. rowWidth = rowWidths_[rowIndex];
  436. switch (textAlignment_)
  437. {
  438. default:
  439. return 0;
  440. case HA_CENTER:
  441. return (GetSize().x_ - rowWidth) / 2;
  442. case HA_RIGHT:
  443. return GetSize().x_ - rowWidth;
  444. }
  445. }
  446. }