Text.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. // By default Text does not derive opacity from parent elements
  56. SetUseDerivedOpacity(false);
  57. }
  58. Text::~Text()
  59. {
  60. }
  61. void Text::RegisterObject(Context* context)
  62. {
  63. context->RegisterFactory<Text>();
  64. ACCESSOR_ATTRIBUTE(Text, VAR_RESOURCEREF, "Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  65. ATTRIBUTE(Text, VAR_INT, "Font Size", fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  66. ATTRIBUTE(Text, VAR_STRING, "Text", text_, String::EMPTY, AM_FILE);
  67. ENUM_ATTRIBUTE(Text, "Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  68. ATTRIBUTE(Text, VAR_FLOAT, "Row Spacing", rowSpacing_, 1.0f, AM_FILE);
  69. ATTRIBUTE(Text, VAR_BOOL, "Word Wrap", wordWrap_, false, AM_FILE);
  70. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::TRANSPARENT, AM_FILE);
  71. REF_ACCESSOR_ATTRIBUTE(Text, VAR_COLOR, "Hover Color", GetHoverColor, SetHoverColor, Color, Color::TRANSPARENT, AM_FILE);
  72. COPY_BASE_ATTRIBUTES(Text, UIElement);
  73. // Change the default value for UseDerivedOpacity
  74. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  75. }
  76. void Text::ApplyAttributes()
  77. {
  78. UIElement::ApplyAttributes();
  79. // Decode to Unicode now
  80. unicodeText_.Clear();
  81. for (unsigned i = 0; i < text_.Length();)
  82. unicodeText_.Push(text_.NextUTF8Char(i));
  83. fontSize_ = Max(fontSize_, 1);
  84. ValidateSelection();
  85. UpdateText();
  86. }
  87. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  88. {
  89. // Hovering or whole selection batch
  90. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  91. {
  92. UIBatch batch(BLEND_ALPHA, currentScissor, 0, &quads);
  93. batch.AddQuad(*this, 0, 0, GetWidth(), GetHeight(), 0, 0, 0, 0, selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ :
  94. hoverColor_);
  95. UIBatch::AddOrMerge(batch, batches);
  96. }
  97. // Partial selection batch
  98. if (!selected_ && selectionLength_ && charSizes_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  99. {
  100. UIBatch batch(BLEND_ALPHA, currentScissor, 0, &quads);
  101. IntVector2 currentStart = charPositions_[selectionStart_];
  102. IntVector2 currentEnd = currentStart;
  103. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  104. {
  105. // Check if row changes, and start a new quad in that case
  106. if (charSizes_[i].x_ && charSizes_[i].y_)
  107. {
  108. if (charPositions_[i].y_ != currentStart.y_)
  109. {
  110. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  111. 0, 0, 0, 0, selectionColor_);
  112. currentStart = charPositions_[i];
  113. currentEnd = currentStart + charSizes_[i];
  114. }
  115. else
  116. {
  117. currentEnd.x_ += charSizes_[i].x_;
  118. currentEnd.y_ = Max(currentStart.y_ + charSizes_[i].y_, currentEnd.y_);
  119. }
  120. }
  121. }
  122. if (currentEnd != currentStart)
  123. {
  124. batch.AddQuad(*this, currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_,
  125. 0, 0, 0, 0, selectionColor_);
  126. }
  127. UIBatch::AddOrMerge(batch, batches);
  128. }
  129. // Text batch
  130. if (font_)
  131. {
  132. const FontFace* face = font_->GetFace(fontSize_);
  133. if (!face)
  134. return;
  135. Vector<PODVector<UIQuad> > pageQuads(face->textures_.Size());
  136. unsigned rowIndex = 0;
  137. int x = GetRowStartPosition(rowIndex);
  138. int y = 0;
  139. for (unsigned i = 0; i < printText_.Size(); ++i)
  140. {
  141. unsigned c = printText_[i];
  142. if (c != '\n')
  143. {
  144. const FontGlyph* p = face->GetGlyph(c);
  145. if (!p)
  146. continue;
  147. const FontGlyph& glyph = *p;
  148. pageQuads[glyph.page_].Push(UIQuad(*this, x + glyph.offsetX_, y + glyph.offsetY_, glyph.width_, glyph.height_, glyph.x_, glyph.y_));
  149. x += glyph.advanceX_;
  150. if (i < printText_.Size() - 1)
  151. x += face->GetKerning(c, printText_[i + 1]);
  152. }
  153. else
  154. {
  155. x = GetRowStartPosition(++rowIndex);
  156. y += rowHeight_;
  157. }
  158. }
  159. for (unsigned page = 0; page < face->textures_.Size(); ++page)
  160. {
  161. UIBatch batch(BLEND_ALPHA, currentScissor, face->textures_[page], &quads);
  162. for (PODVector<UIQuad>::ConstIterator i = pageQuads[page].Begin(); i != pageQuads[page].End(); ++i)
  163. batch.AddQuad(*i);
  164. UIBatch::AddOrMerge(batch, batches);
  165. }
  166. }
  167. // Reset hovering for next frame
  168. hovering_ = false;
  169. }
  170. void Text::OnResize()
  171. {
  172. if (wordWrap_)
  173. UpdateText();
  174. }
  175. bool Text::SetFont(const String& fontName, int size)
  176. {
  177. ResourceCache* cache = GetSubsystem<ResourceCache>();
  178. return SetFont(cache->GetResource<Font>(fontName), size);
  179. }
  180. bool Text::SetFont(Font* font, int size)
  181. {
  182. if (!font)
  183. {
  184. LOGERROR("Null font for Text");
  185. return false;
  186. }
  187. if (font != font_ || size != fontSize_)
  188. {
  189. font_ = font;
  190. fontSize_ = Max(size, 1);
  191. UpdateText();
  192. }
  193. return true;
  194. }
  195. void Text::SetText(const String& text)
  196. {
  197. text_ = text;
  198. // Decode to Unicode now
  199. unicodeText_.Clear();
  200. for (unsigned i = 0; i < text_.Length();)
  201. unicodeText_.Push(text_.NextUTF8Char(i));
  202. ValidateSelection();
  203. UpdateText();
  204. }
  205. void Text::SetTextAlignment(HorizontalAlignment align)
  206. {
  207. if (align != textAlignment_)
  208. {
  209. textAlignment_ = align;
  210. UpdateText();
  211. }
  212. }
  213. void Text::SetRowSpacing(float spacing)
  214. {
  215. if (spacing != rowSpacing_)
  216. {
  217. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  218. UpdateText();
  219. }
  220. }
  221. void Text::SetWordwrap(bool enable)
  222. {
  223. if (enable != wordWrap_)
  224. {
  225. wordWrap_ = enable;
  226. UpdateText();
  227. }
  228. }
  229. void Text::SetSelection(unsigned start, unsigned length)
  230. {
  231. selectionStart_ = start;
  232. selectionLength_ = length;
  233. ValidateSelection();
  234. }
  235. void Text::ClearSelection()
  236. {
  237. selectionStart_ = 0;
  238. selectionLength_ = 0;
  239. }
  240. void Text::SetSelectionColor(const Color& color)
  241. {
  242. selectionColor_ = color;
  243. }
  244. void Text::SetHoverColor(const Color& color)
  245. {
  246. hoverColor_ = color;
  247. }
  248. void Text::SetFontAttr(ResourceRef value)
  249. {
  250. ResourceCache* cache = GetSubsystem<ResourceCache>();
  251. font_ = cache->GetResource<Font>(value.id_);
  252. }
  253. ResourceRef Text::GetFontAttr() const
  254. {
  255. return GetResourceRef(font_, Font::GetTypeStatic());
  256. }
  257. void Text::UpdateText(bool inResize)
  258. {
  259. int width = 0;
  260. int height = 0;
  261. rowWidths_.Clear();
  262. printText_.Clear();
  263. PODVector<unsigned> printToText;
  264. if (font_)
  265. {
  266. const FontFace* face = font_->GetFace(fontSize_);
  267. if (!face)
  268. return;
  269. rowHeight_ = face->rowHeight_;
  270. int rowWidth = 0;
  271. int rowHeight = (int)(rowSpacing_ * rowHeight_);
  272. // First see if the text must be split up
  273. if (!wordWrap_)
  274. {
  275. printText_ = unicodeText_;
  276. printToText.Resize(printText_.Size());
  277. for (unsigned i = 0; i < printText_.Size(); ++i)
  278. printToText[i] = i;
  279. }
  280. else
  281. {
  282. int maxWidth = GetWidth();
  283. unsigned nextBreak = 0;
  284. unsigned lineStart = 0;
  285. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  286. {
  287. unsigned j;
  288. unsigned c = unicodeText_[i];
  289. if (c != '\n')
  290. {
  291. bool ok = true;
  292. if (nextBreak <= i)
  293. {
  294. int futureRowWidth = rowWidth;
  295. for (j = i; j < unicodeText_.Size(); ++j)
  296. {
  297. unsigned d = unicodeText_[j];
  298. if (d == ' ' || d == '\n')
  299. {
  300. nextBreak = j;
  301. break;
  302. }
  303. const FontGlyph* glyph = face->GetGlyph(d);
  304. if (glyph)
  305. {
  306. futureRowWidth += glyph->advanceX_;
  307. if (j < unicodeText_.Size() - 1)
  308. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  309. }
  310. if (d == '-' && futureRowWidth <= maxWidth)
  311. {
  312. nextBreak = j + 1;
  313. break;
  314. }
  315. if (futureRowWidth > maxWidth)
  316. {
  317. ok = false;
  318. break;
  319. }
  320. }
  321. }
  322. if (!ok)
  323. {
  324. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  325. if (nextBreak == lineStart)
  326. {
  327. while (i < j)
  328. {
  329. printText_.Push(unicodeText_[i]);
  330. printToText.Push(i);
  331. ++i;
  332. }
  333. }
  334. printText_.Push('\n');
  335. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  336. rowWidth = 0;
  337. nextBreak = lineStart = i;
  338. }
  339. if (i < unicodeText_.Size())
  340. {
  341. // When copying a space, position is allowed to be over row width
  342. c = unicodeText_[i];
  343. const FontGlyph* glyph = face->GetGlyph(c);
  344. if (glyph)
  345. {
  346. rowWidth += glyph->advanceX_;
  347. if (i < text_.Length() - 1)
  348. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  349. }
  350. if (rowWidth <= maxWidth)
  351. {
  352. printText_.Push(c);
  353. printToText.Push(i);
  354. }
  355. }
  356. }
  357. else
  358. {
  359. printText_.Push('\n');
  360. printToText.Push(Min((int)i, (int)unicodeText_.Size() - 1));
  361. rowWidth = 0;
  362. nextBreak = lineStart = i;
  363. }
  364. }
  365. }
  366. rowWidth = 0;
  367. for (unsigned i = 0; i < printText_.Size(); ++i)
  368. {
  369. unsigned c = printText_[i];
  370. if (c != '\n')
  371. {
  372. const FontGlyph* glyph = face->GetGlyph(c);
  373. if (glyph)
  374. {
  375. rowWidth += glyph->advanceX_;
  376. if (i < printText_.Size() - 1)
  377. rowWidth += face->GetKerning(c, printText_[i + 1]);
  378. }
  379. }
  380. else
  381. {
  382. width = Max(width, rowWidth);
  383. height += rowHeight;
  384. rowWidths_.Push(rowWidth);
  385. rowWidth = 0;
  386. }
  387. }
  388. if (rowWidth)
  389. {
  390. width = Max(width, rowWidth);
  391. height += rowHeight;
  392. rowWidths_.Push(rowWidth);
  393. }
  394. // Set row height even if text is empty
  395. if (!height)
  396. height = rowHeight;
  397. // Store position & size of each character
  398. charPositions_.Resize(unicodeText_.Size() + 1);
  399. charSizes_.Resize(unicodeText_.Size());
  400. unsigned rowIndex = 0;
  401. int x = GetRowStartPosition(rowIndex);
  402. int y = 0;
  403. for (unsigned i = 0; i < printText_.Size(); ++i)
  404. {
  405. charPositions_[printToText[i]] = IntVector2(x, y);
  406. unsigned c = printText_[i];
  407. if (c != '\n')
  408. {
  409. const FontGlyph* glyph = face->GetGlyph(c);
  410. charSizes_[printToText[i]] = IntVector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  411. if (glyph)
  412. {
  413. x += glyph->advanceX_;
  414. if (i < printText_.Size() - 1)
  415. x += face->GetKerning(c, printText_[i + 1]);
  416. }
  417. }
  418. else
  419. {
  420. charSizes_[printToText[i]] = IntVector2::ZERO;
  421. x = GetRowStartPosition(++rowIndex);
  422. y += rowHeight;
  423. }
  424. }
  425. // Store the ending position
  426. charPositions_[unicodeText_.Size()] = IntVector2(x, y);
  427. }
  428. // Set minimum and current size according to the text size, but respect fixed width if set
  429. if (GetMinWidth() != GetMaxWidth())
  430. {
  431. SetMinWidth(width);
  432. SetWidth(width);
  433. }
  434. SetFixedHeight(height);
  435. }
  436. void Text::ValidateSelection()
  437. {
  438. unsigned textLength = unicodeText_.Size();
  439. if (textLength)
  440. {
  441. if (selectionStart_ >= textLength)
  442. selectionStart_ = textLength - 1;
  443. if (selectionStart_ + selectionLength_ > textLength)
  444. selectionLength_ = textLength - selectionStart_;
  445. }
  446. else
  447. {
  448. selectionStart_ = 0;
  449. selectionLength_ = 0;
  450. }
  451. }
  452. int Text::GetRowStartPosition(unsigned rowIndex) const
  453. {
  454. int rowWidth = 0;
  455. if (rowIndex < rowWidths_.Size())
  456. rowWidth = rowWidths_[rowIndex];
  457. switch (textAlignment_)
  458. {
  459. default:
  460. return 0;
  461. case HA_CENTER:
  462. return (GetSize().x_ - rowWidth) / 2;
  463. case HA_RIGHT:
  464. return GetSize().x_ - rowWidth;
  465. }
  466. }
  467. }