Text.cpp 16 KB

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