Text.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 "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. static const float MIN_ROW_SPACING = 0.5f;
  33. static const std::string horizontalAlignments[] =
  34. {
  35. "left",
  36. "center",
  37. "right"
  38. };
  39. Text::Text(const std::string& name, const std::string& text) :
  40. UIElement(name),
  41. mFontSize(DEFAULT_FONT_SIZE),
  42. mText(text),
  43. mTextAlignment(HA_LEFT),
  44. mRowSpacing(1.0f),
  45. mWordwrap(false),
  46. mSelectionStart(0),
  47. mSelectionLength(0),
  48. mSelectionColor(Color(0.0f, 0.0f, 0.0f, 0.0f)),
  49. mHoverColor(Color(0.0f, 0.0f, 0.0f, 0.0f)),
  50. mRowHeight(0)
  51. {
  52. }
  53. Text::~Text()
  54. {
  55. }
  56. void Text::setStyle(const XMLElement& element, ResourceCache* cache)
  57. {
  58. UIElement::setStyle(element, cache);
  59. // Recalculating the text is expensive, so do it only once at the end if something changed
  60. bool changed = false;
  61. if (element.hasChildElement("font"))
  62. {
  63. XMLElement fontElem = element.getChildElement("font");
  64. Font* font = cache->getResource<Font>(fontElem.getString("name"));
  65. if (!font)
  66. LOGERROR("Null font for Text");
  67. else
  68. {
  69. mFont = font;
  70. mFontSize = max(fontElem.getInt("size"), 1);
  71. changed = true;
  72. }
  73. }
  74. if (element.hasChildElement("text"))
  75. {
  76. std::string text = element.getChildElement("text").getString("value");
  77. replaceInPlace(text, "\\n", "\n");
  78. mText = text;
  79. changed = true;
  80. }
  81. if (element.hasChildElement("textalignment"))
  82. {
  83. std::string horiz = element.getChildElement("textalignment").getStringLower("value");
  84. if (!horiz.empty())
  85. {
  86. mTextAlignment = (HorizontalAlignment)getIndexFromStringList(horiz, horizontalAlignments, 3, 0);
  87. changed = true;
  88. }
  89. }
  90. if (element.hasChildElement("rowspacing"))
  91. {
  92. mRowSpacing = max(element.getChildElement("rowspacing").getFloat("value"), MIN_ROW_SPACING);
  93. changed = true;
  94. }
  95. if (element.hasChildElement("wordwrap"))
  96. {
  97. mWordwrap = element.getChildElement("wordwrap").getBool("enable");
  98. changed = true;
  99. }
  100. if (element.hasChildElement("selection"))
  101. {
  102. XMLElement selectionElem = element.getChildElement("selection");
  103. mSelectionStart = selectionElem.getInt("start");
  104. mSelectionLength = selectionElem.getInt("length");
  105. changed = true;
  106. }
  107. if (element.hasChildElement("selectioncolor"))
  108. setSelectionColor(element.getChildElement("selectioncolor").getColor("value"));
  109. if (element.hasChildElement("hovercolor"))
  110. setHoverColor(element.getChildElement("hovercolor").getColor("value"));
  111. if (changed)
  112. {
  113. validateSelection();
  114. updateText();
  115. }
  116. }
  117. void Text::getBatches(std::vector<UIBatch>& batches, std::vector<UIQuad>& quads, const IntRect& currentScissor)
  118. {
  119. // Hovering or whole selection batch
  120. if ((mHovering && (mHoverColor.mA > 0.0f)) || (mSelected && (mSelectionColor.mA > 0.0f)))
  121. {
  122. UIBatch batch;
  123. batch.begin(&quads);
  124. batch.mBlendMode = BLEND_ALPHA;
  125. batch.mScissor = currentScissor;
  126. batch.mTexture = 0;
  127. batch.addQuad(*this, 0, 0, getWidth(), getHeight(), 0, 0, 0, 0, (mSelected && (mSelectionColor.mA > 0.0f)) ? mSelectionColor :
  128. mHoverColor);
  129. UIBatch::addOrMerge(batch, batches);
  130. }
  131. // Partial selection batch
  132. if ((!mSelected) && (mSelectionLength) && (mCharSizes.size() >= mSelectionStart + mSelectionLength) && (mSelectionColor.mA > 0.0f))
  133. {
  134. UIBatch batch;
  135. batch.begin(&quads);
  136. batch.mBlendMode = BLEND_ALPHA;
  137. batch.mScissor = currentScissor;
  138. batch.mTexture = 0;
  139. IntVector2 currentStart = mCharPositions[mSelectionStart];
  140. IntVector2 currentEnd = currentStart;
  141. for (unsigned i = mSelectionStart; i < mSelectionStart + mSelectionLength; ++i)
  142. {
  143. // Check if row changes, and start a new quad in that case
  144. if ((mCharSizes[i].mX) && (mCharSizes[i].mY))
  145. {
  146. if (mCharPositions[i].mY != currentStart.mY)
  147. {
  148. batch.addQuad(*this, currentStart.mX, currentStart.mY, currentEnd.mX - currentStart.mX, currentEnd.mY - currentStart.mY,
  149. 0, 0, 0, 0, mSelectionColor);
  150. currentStart = mCharPositions[i];
  151. currentEnd = currentStart + mCharSizes[i];
  152. }
  153. else
  154. {
  155. currentEnd.mX += mCharSizes[i].mX;
  156. currentEnd.mY = max(currentStart.mY + mCharSizes[i].mY, currentEnd.mY);
  157. }
  158. }
  159. }
  160. if (currentEnd != currentStart)
  161. {
  162. batch.addQuad(*this, currentStart.mX, currentStart.mY, currentEnd.mX - currentStart.mX, currentEnd.mY - currentStart.mY,
  163. 0, 0, 0, 0, mSelectionColor);
  164. }
  165. UIBatch::addOrMerge(batch, batches);
  166. }
  167. // Text batch
  168. if (mFont)
  169. {
  170. const FontFace* face = mFont->getFace(mFontSize);
  171. UIBatch batch;
  172. batch.begin(&quads);
  173. batch.mBlendMode = BLEND_ALPHA;
  174. batch.mScissor = currentScissor;
  175. batch.mTexture = face->mTexture;
  176. unsigned rowIndex = 0;
  177. int x = getRowStartPosition(rowIndex);
  178. int y = 0;
  179. for (unsigned i = 0; i < mPrintText.length(); ++i)
  180. {
  181. unsigned char c = (unsigned char)mPrintText[i];
  182. if (c != '\n')
  183. {
  184. const FontGlyph& glyph = face->mGlyphs[face->mGlyphIndex[c]];
  185. if (c != ' ')
  186. batch.addQuad(*this, x + glyph.mOffsetX, y + glyph.mOffsetY, glyph.mWidth, glyph.mHeight, glyph.mX, glyph.mY);
  187. x += glyph.mAdvanceX;
  188. }
  189. else
  190. {
  191. rowIndex++;
  192. x = getRowStartPosition(rowIndex);
  193. y += mRowHeight;
  194. }
  195. }
  196. UIBatch::addOrMerge(batch, batches);
  197. }
  198. // Reset hovering for next frame
  199. mHovering = false;
  200. }
  201. void Text::onResize()
  202. {
  203. if (mWordwrap)
  204. updateText();
  205. }
  206. bool Text::setFont(Font* font, int size)
  207. {
  208. if (!font)
  209. {
  210. LOGERROR("Null font for Text");
  211. return false;
  212. }
  213. if ((font != mFont) || (size != mFontSize))
  214. {
  215. mFont = font;
  216. mFontSize = max(size, 1);
  217. updateText();
  218. }
  219. return true;
  220. }
  221. void Text::setText(const std::string& text)
  222. {
  223. mText = text;
  224. validateSelection();
  225. updateText();
  226. }
  227. void Text::setTextAlignment(HorizontalAlignment align)
  228. {
  229. if (align != mTextAlignment)
  230. {
  231. mTextAlignment = align;
  232. updateText();
  233. }
  234. }
  235. void Text::setRowSpacing(float spacing)
  236. {
  237. if (spacing != mRowSpacing)
  238. {
  239. mRowSpacing = max(spacing, MIN_ROW_SPACING);
  240. updateText();
  241. }
  242. }
  243. void Text::setWordwrap(bool enable)
  244. {
  245. if (enable != mWordwrap)
  246. {
  247. mWordwrap = enable;
  248. updateText();
  249. }
  250. }
  251. void Text::setSelection(unsigned start, unsigned length)
  252. {
  253. mSelectionStart = start;
  254. mSelectionLength = length;
  255. validateSelection();
  256. }
  257. void Text::clearSelection()
  258. {
  259. mSelectionStart = 0;
  260. mSelectionLength = 0;
  261. }
  262. void Text::setSelectionColor(const Color& color)
  263. {
  264. mSelectionColor = color;
  265. }
  266. void Text::setHoverColor(const Color& color)
  267. {
  268. mHoverColor = color;
  269. }
  270. void Text::updateText(bool inResize)
  271. {
  272. int width = 0;
  273. int height = 0;
  274. mRowWidths.clear();
  275. mPrintText.clear();
  276. static std::vector<unsigned> printToText;
  277. printToText.clear();
  278. if (mFont)
  279. {
  280. const FontFace* face = mFont->getFace(mFontSize);
  281. mRowHeight = face->mRowHeight;
  282. int rowWidth = 0;
  283. int rowHeight = (int)(mRowSpacing * mRowHeight);
  284. // First see if the text must be split up
  285. if (!mWordwrap)
  286. {
  287. mPrintText = mText;
  288. printToText.resize(mText.length());
  289. for (unsigned i = 0; i < mText.length(); ++i)
  290. printToText[i] = i;
  291. }
  292. else
  293. {
  294. int maxWidth = getWidth();
  295. unsigned nextBreak = 0;
  296. unsigned lineStart = 0;
  297. for (unsigned i = 0; i < mText.length(); ++i)
  298. {
  299. unsigned j;
  300. if (mText[i] != '\n')
  301. {
  302. bool ok = true;
  303. if (nextBreak <= i)
  304. {
  305. int futureRowWidth = rowWidth;
  306. for (j = i; j < mText.length(); ++j)
  307. {
  308. if ((mText[j] == ' ') || (mText[j] == '\n'))
  309. {
  310. nextBreak = j;
  311. break;
  312. }
  313. futureRowWidth += face->mGlyphs[face->mGlyphIndex[mText[j]]].mAdvanceX;
  314. if ((mText[j] == '-') && (futureRowWidth <= maxWidth))
  315. {
  316. nextBreak = j + 1;
  317. break;
  318. }
  319. if (futureRowWidth > maxWidth)
  320. {
  321. ok = false;
  322. break;
  323. }
  324. }
  325. }
  326. if (!ok)
  327. {
  328. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  329. if (nextBreak == lineStart)
  330. {
  331. int copyLength = max(j - i, 1);
  332. mPrintText.append(mText.substr(i, copyLength));
  333. for (int k = 0; k < copyLength; ++k)
  334. {
  335. printToText.push_back(i);
  336. ++i;
  337. }
  338. }
  339. mPrintText += '\n';
  340. printToText.push_back(min((int)i, (int)mText.length() - 1));
  341. rowWidth = 0;
  342. nextBreak = lineStart = i;
  343. }
  344. if (i < mText.length())
  345. {
  346. // When copying a space, we may be over row width
  347. rowWidth += face->mGlyphs[face->mGlyphIndex[mText[i]]].mAdvanceX;
  348. if (rowWidth <= maxWidth)
  349. {
  350. mPrintText += mText[i];
  351. printToText.push_back(i);
  352. }
  353. }
  354. }
  355. else
  356. {
  357. mPrintText += '\n';
  358. printToText.push_back(min((int)i, (int)mText.length() - 1));
  359. rowWidth = 0;
  360. nextBreak = lineStart = i;
  361. }
  362. }
  363. }
  364. rowWidth = 0;
  365. for (unsigned i = 0; i < mPrintText.length(); ++i)
  366. {
  367. unsigned char c = (unsigned char)mPrintText[i];
  368. if (c != '\n')
  369. {
  370. const FontGlyph& glyph = face->mGlyphs[face->mGlyphIndex[c]];
  371. rowWidth += glyph.mAdvanceX;
  372. }
  373. else
  374. {
  375. width = max(width, rowWidth);
  376. height += rowHeight;
  377. mRowWidths.push_back(rowWidth);
  378. rowWidth = 0;
  379. }
  380. }
  381. if (rowWidth)
  382. {
  383. width = max(width, rowWidth);
  384. height += rowHeight;
  385. mRowWidths.push_back(rowWidth);
  386. }
  387. // Set row height even if text is empty
  388. if (!height)
  389. height = rowHeight;
  390. // Store position & size of each character
  391. mCharPositions.resize(mText.length() + 1);
  392. mCharSizes.resize(mText.length());
  393. unsigned rowIndex = 0;
  394. int x = getRowStartPosition(rowIndex);
  395. int y = 0;
  396. for (unsigned i = 0; i < mPrintText.length(); ++i)
  397. {
  398. mCharPositions[printToText[i]] = IntVector2(x, y);
  399. unsigned char c = (unsigned char)mPrintText[i];
  400. if (c != '\n')
  401. {
  402. const FontGlyph& glyph = face->mGlyphs[face->mGlyphIndex[c]];
  403. mCharSizes[printToText[i]] = IntVector2(glyph.mAdvanceX, mRowHeight);
  404. x += glyph.mAdvanceX;
  405. }
  406. else
  407. {
  408. mCharSizes[printToText[i]] = IntVector2::sZero;
  409. rowIndex++;
  410. x = getRowStartPosition(rowIndex);
  411. y += rowHeight;
  412. }
  413. }
  414. // Store the ending position
  415. mCharPositions[mText.length()] = IntVector2(x, y);
  416. }
  417. // Set minimum size according to the text size
  418. setMinWidth(width);
  419. setFixedHeight(height);
  420. }
  421. void Text::validateSelection()
  422. {
  423. unsigned textLength = mText.length();
  424. if (textLength)
  425. {
  426. if (mSelectionStart >= textLength)
  427. mSelectionStart = textLength - 1;
  428. if (mSelectionStart + mSelectionLength > textLength)
  429. mSelectionLength = textLength - mSelectionStart;
  430. }
  431. else
  432. {
  433. mSelectionStart = 0;
  434. mSelectionLength = 0;
  435. }
  436. }
  437. int Text::getRowStartPosition(unsigned rowIndex) const
  438. {
  439. int rowWidth = 0;
  440. if (rowIndex < mRowWidths.size())
  441. rowWidth = mRowWidths[rowIndex];
  442. switch (mTextAlignment)
  443. {
  444. default:
  445. return 0;
  446. case HA_CENTER:
  447. return (getSize().mX - rowWidth) / 2;
  448. case HA_RIGHT:
  449. return getSize().mX - rowWidth;
  450. }
  451. }