Text.cpp 16 KB

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