The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

618 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. TextLayout::Glyph::Glyph (const int glyphCode_, const Point<float>& anchor_, float width_) noexcept
  19. : glyphCode (glyphCode_), anchor (anchor_), width (width_)
  20. {
  21. }
  22. TextLayout::Glyph::Glyph (const Glyph& other) noexcept
  23. : glyphCode (other.glyphCode), anchor (other.anchor), width (other.width)
  24. {
  25. }
  26. TextLayout::Glyph& TextLayout::Glyph::operator= (const Glyph& other) noexcept
  27. {
  28. glyphCode = other.glyphCode;
  29. anchor = other.anchor;
  30. width = other.width;
  31. return *this;
  32. }
  33. TextLayout::Glyph::~Glyph() noexcept {}
  34. //==============================================================================
  35. TextLayout::Run::Run() noexcept
  36. : colour (0xff000000)
  37. {
  38. }
  39. TextLayout::Run::Run (const Range<int>& range, const int numGlyphsToPreallocate)
  40. : colour (0xff000000), stringRange (range)
  41. {
  42. glyphs.ensureStorageAllocated (numGlyphsToPreallocate);
  43. }
  44. TextLayout::Run::Run (const Run& other)
  45. : font (other.font),
  46. colour (other.colour),
  47. glyphs (other.glyphs),
  48. stringRange (other.stringRange)
  49. {
  50. }
  51. TextLayout::Run::~Run() noexcept {}
  52. //==============================================================================
  53. TextLayout::Line::Line() noexcept
  54. : ascent (0.0f), descent (0.0f), leading (0.0f)
  55. {
  56. }
  57. TextLayout::Line::Line (const Range<int>& stringRange_, const Point<float>& lineOrigin_,
  58. const float ascent_, const float descent_, const float leading_,
  59. const int numRunsToPreallocate)
  60. : stringRange (stringRange_), lineOrigin (lineOrigin_),
  61. ascent (ascent_), descent (descent_), leading (leading_)
  62. {
  63. runs.ensureStorageAllocated (numRunsToPreallocate);
  64. }
  65. TextLayout::Line::Line (const Line& other)
  66. : stringRange (other.stringRange), lineOrigin (other.lineOrigin),
  67. ascent (other.ascent), descent (other.descent), leading (other.leading)
  68. {
  69. runs.addCopiesOf (other.runs);
  70. }
  71. TextLayout::Line::~Line() noexcept
  72. {
  73. }
  74. Range<float> TextLayout::Line::getLineBoundsX() const noexcept
  75. {
  76. Range<float> range;
  77. bool isFirst = true;
  78. for (int i = runs.size(); --i >= 0;)
  79. {
  80. const Run* run = runs.getUnchecked(i);
  81. jassert (run != nullptr);
  82. if (run->glyphs.size() > 0)
  83. {
  84. float minX = run->glyphs.getReference(0).anchor.x;
  85. float maxX = minX;
  86. for (int j = run->glyphs.size(); --j > 0;)
  87. {
  88. const Glyph& glyph = run->glyphs.getReference (j);
  89. const float x = glyph.anchor.x;
  90. minX = jmin (minX, x);
  91. maxX = jmax (maxX, x + glyph.width);
  92. }
  93. if (isFirst)
  94. {
  95. isFirst = false;
  96. range = Range<float> (minX, maxX);
  97. }
  98. else
  99. {
  100. range = range.getUnionWith (Range<float> (minX, maxX));
  101. }
  102. }
  103. }
  104. return range + lineOrigin.x;
  105. }
  106. //==============================================================================
  107. TextLayout::TextLayout()
  108. : width (0), justification (Justification::topLeft)
  109. {
  110. }
  111. TextLayout::TextLayout (const TextLayout& other)
  112. : width (other.width),
  113. justification (other.justification)
  114. {
  115. lines.addCopiesOf (other.lines);
  116. }
  117. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  118. TextLayout::TextLayout (TextLayout&& other) noexcept
  119. : lines (static_cast <OwnedArray<Line>&&> (other.lines)),
  120. width (other.width),
  121. justification (other.justification)
  122. {
  123. }
  124. TextLayout& TextLayout::operator= (TextLayout&& other) noexcept
  125. {
  126. lines = static_cast <OwnedArray<Line>&&> (other.lines);
  127. width = other.width;
  128. justification = other.justification;
  129. return *this;
  130. }
  131. #endif
  132. TextLayout& TextLayout::operator= (const TextLayout& other)
  133. {
  134. width = other.width;
  135. justification = other.justification;
  136. lines.clear();
  137. lines.addCopiesOf (other.lines);
  138. return *this;
  139. }
  140. TextLayout::~TextLayout()
  141. {
  142. }
  143. float TextLayout::getHeight() const noexcept
  144. {
  145. const Line* const lastLine = lines.getLast();
  146. return lastLine != nullptr ? lastLine->lineOrigin.y + lastLine->descent
  147. : 0;
  148. }
  149. TextLayout::Line& TextLayout::getLine (const int index) const
  150. {
  151. return *lines[index];
  152. }
  153. void TextLayout::ensureStorageAllocated (int numLinesNeeded)
  154. {
  155. lines.ensureStorageAllocated (numLinesNeeded);
  156. }
  157. void TextLayout::addLine (Line* line)
  158. {
  159. lines.add (line);
  160. }
  161. void TextLayout::draw (Graphics& g, const Rectangle<float>& area) const
  162. {
  163. const Point<float> origin (justification.appliedToRectangle (Rectangle<float> (0, 0, width, getHeight()), area).getPosition());
  164. LowLevelGraphicsContext& context = *g.getInternalContext();
  165. for (int i = 0; i < getNumLines(); ++i)
  166. {
  167. const Line& line = getLine (i);
  168. const Point<float> lineOrigin (origin + line.lineOrigin);
  169. for (int j = 0; j < line.runs.size(); ++j)
  170. {
  171. const Run* const run = line.runs.getUnchecked (j);
  172. jassert (run != nullptr);
  173. context.setFont (run->font);
  174. context.setFill (run->colour);
  175. for (int k = 0; k < run->glyphs.size(); ++k)
  176. {
  177. const Glyph& glyph = run->glyphs.getReference (k);
  178. context.drawGlyph (glyph.glyphCode, AffineTransform::translation (lineOrigin.x + glyph.anchor.x,
  179. lineOrigin.y + glyph.anchor.y));
  180. }
  181. }
  182. }
  183. }
  184. void TextLayout::createLayout (const AttributedString& text, float maxWidth)
  185. {
  186. lines.clear();
  187. width = maxWidth;
  188. justification = text.getJustification();
  189. if (! createNativeLayout (text))
  190. createStandardLayout (text);
  191. recalculateWidth (text);
  192. }
  193. //==============================================================================
  194. namespace TextLayoutHelpers
  195. {
  196. struct FontAndColour
  197. {
  198. FontAndColour (const Font* font_) noexcept : font (font_), colour (0xff000000) {}
  199. const Font* font;
  200. Colour colour;
  201. bool operator!= (const FontAndColour& other) const noexcept
  202. {
  203. return (font != other.font && *font != *other.font) || colour != other.colour;
  204. }
  205. };
  206. struct RunAttribute
  207. {
  208. RunAttribute (const FontAndColour& fontAndColour_, const Range<int>& range_) noexcept
  209. : fontAndColour (fontAndColour_), range (range_)
  210. {}
  211. FontAndColour fontAndColour;
  212. Range<int> range;
  213. };
  214. struct Token
  215. {
  216. Token (const String& t, const Font& f, const Colour& c, const bool isWhitespace_)
  217. : text (t), font (f), colour (c),
  218. area (font.getStringWidth (t), roundToInt (f.getHeight())),
  219. isWhitespace (isWhitespace_),
  220. isNewLine (t.containsChar ('\n') || t.containsChar ('\r'))
  221. {}
  222. const String text;
  223. const Font font;
  224. const Colour colour;
  225. Rectangle<int> area;
  226. int line, lineHeight;
  227. const bool isWhitespace, isNewLine;
  228. private:
  229. Token& operator= (const Token&);
  230. };
  231. class TokenList
  232. {
  233. public:
  234. TokenList() noexcept : totalLines (0) {}
  235. void createLayout (const AttributedString& text, TextLayout& layout)
  236. {
  237. tokens.ensureStorageAllocated (64);
  238. layout.ensureStorageAllocated (totalLines);
  239. addTextRuns (text);
  240. layoutRuns ((int) layout.getWidth());
  241. int charPosition = 0;
  242. int lineStartPosition = 0;
  243. int runStartPosition = 0;
  244. ScopedPointer<TextLayout::Line> currentLine;
  245. ScopedPointer<TextLayout::Run> currentRun;
  246. bool needToSetLineOrigin = true;
  247. for (int i = 0; i < tokens.size(); ++i)
  248. {
  249. const Token* const t = tokens.getUnchecked (i);
  250. const Point<float> tokenPos (t->area.getPosition().toFloat());
  251. Array <int> newGlyphs;
  252. Array <float> xOffsets;
  253. t->font.getGlyphPositions (t->text.trimEnd(), newGlyphs, xOffsets);
  254. if (currentRun == nullptr) currentRun = new TextLayout::Run();
  255. if (currentLine == nullptr) currentLine = new TextLayout::Line();
  256. currentRun->glyphs.ensureStorageAllocated (currentRun->glyphs.size() + newGlyphs.size());
  257. for (int j = 0; j < newGlyphs.size(); ++j)
  258. {
  259. if (needToSetLineOrigin)
  260. {
  261. needToSetLineOrigin = false;
  262. currentLine->lineOrigin = tokenPos.translated (0, t->font.getAscent());
  263. }
  264. const float x = xOffsets.getUnchecked (j);
  265. currentRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
  266. Point<float> (tokenPos.getX() + x, 0),
  267. xOffsets.getUnchecked (j + 1) - x));
  268. ++charPosition;
  269. }
  270. if (t->isWhitespace || t->isNewLine)
  271. ++charPosition;
  272. const Token* const nextToken = tokens [i + 1];
  273. if (nextToken == nullptr) // this is the last token
  274. {
  275. addRun (currentLine, currentRun.release(), t, runStartPosition, charPosition);
  276. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  277. layout.addLine (currentLine.release());
  278. }
  279. else
  280. {
  281. if (t->font != nextToken->font || t->colour != nextToken->colour)
  282. {
  283. addRun (currentLine, currentRun.release(), t, runStartPosition, charPosition);
  284. runStartPosition = charPosition;
  285. }
  286. if (t->line != nextToken->line)
  287. {
  288. if (currentRun == nullptr)
  289. currentRun = new TextLayout::Run();
  290. addRun (currentLine, currentRun.release(), t, runStartPosition, charPosition);
  291. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  292. layout.addLine (currentLine.release());
  293. runStartPosition = charPosition;
  294. lineStartPosition = charPosition;
  295. needToSetLineOrigin = true;
  296. }
  297. }
  298. }
  299. if ((text.getJustification().getFlags() & (Justification::right | Justification::horizontallyCentred)) != 0)
  300. {
  301. const int totalW = (int) layout.getWidth();
  302. const bool isCentred = (text.getJustification().getFlags() & Justification::horizontallyCentred) != 0;
  303. for (int i = 0; i < layout.getNumLines(); ++i)
  304. {
  305. float dx = (float) (totalW - getLineWidth (i));
  306. if (isCentred)
  307. dx /= 2.0f;
  308. layout.getLine(i).lineOrigin.x += dx;
  309. }
  310. }
  311. }
  312. private:
  313. static void addRun (TextLayout::Line* glyphLine, TextLayout::Run* glyphRun,
  314. const Token* const t, const int start, const int end)
  315. {
  316. glyphRun->stringRange = Range<int> (start, end);
  317. glyphRun->font = t->font;
  318. glyphRun->colour = t->colour;
  319. glyphLine->ascent = jmax (glyphLine->ascent, t->font.getAscent());
  320. glyphLine->descent = jmax (glyphLine->descent, t->font.getDescent());
  321. glyphLine->runs.add (glyphRun);
  322. }
  323. static int getCharacterType (const juce_wchar c) noexcept
  324. {
  325. if (c == '\r' || c == '\n')
  326. return 0;
  327. return CharacterFunctions::isWhitespace (c) ? 2 : 1;
  328. }
  329. void appendText (const AttributedString& text, const Range<int>& stringRange,
  330. const Font& font, const Colour& colour)
  331. {
  332. const String stringText (text.getText().substring (stringRange.getStart(), stringRange.getEnd()));
  333. String::CharPointerType t (stringText.getCharPointer());
  334. String currentString;
  335. int lastCharType = 0;
  336. for (;;)
  337. {
  338. const juce_wchar c = t.getAndAdvance();
  339. if (c == 0)
  340. break;
  341. const int charType = getCharacterType (c);
  342. if (charType == 0 || charType != lastCharType)
  343. {
  344. if (currentString.isNotEmpty())
  345. tokens.add (new Token (currentString, font, colour,
  346. lastCharType == 2 || lastCharType == 0));
  347. currentString = String::charToString (c);
  348. if (c == '\r' && *t == '\n')
  349. currentString += t.getAndAdvance();
  350. }
  351. else
  352. {
  353. currentString += c;
  354. }
  355. lastCharType = charType;
  356. }
  357. if (currentString.isNotEmpty())
  358. tokens.add (new Token (currentString, font, colour, lastCharType == 2));
  359. }
  360. void layoutRuns (const int maxWidth)
  361. {
  362. int x = 0, y = 0, h = 0;
  363. int i;
  364. for (i = 0; i < tokens.size(); ++i)
  365. {
  366. Token* const t = tokens.getUnchecked(i);
  367. t->area.setPosition (x, y);
  368. t->line = totalLines;
  369. x += t->area.getWidth();
  370. h = jmax (h, t->area.getHeight());
  371. const Token* const nextTok = tokens[i + 1];
  372. if (nextTok == nullptr)
  373. break;
  374. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->area.getWidth() > maxWidth))
  375. {
  376. setLastLineHeight (i + 1, h);
  377. x = 0;
  378. y += h;
  379. h = 0;
  380. ++totalLines;
  381. }
  382. }
  383. setLastLineHeight (jmin (i + 1, tokens.size()), h);
  384. ++totalLines;
  385. }
  386. void setLastLineHeight (int i, const int height) noexcept
  387. {
  388. while (--i >= 0)
  389. {
  390. Token* const tok = tokens.getUnchecked (i);
  391. if (tok->line == totalLines)
  392. tok->lineHeight = height;
  393. else
  394. break;
  395. }
  396. }
  397. int getLineWidth (const int lineNumber) const noexcept
  398. {
  399. int maxW = 0;
  400. for (int i = tokens.size(); --i >= 0;)
  401. {
  402. const Token* const t = tokens.getUnchecked (i);
  403. if (t->line == lineNumber && ! t->isWhitespace)
  404. maxW = jmax (maxW, t->area.getRight());
  405. }
  406. return maxW;
  407. }
  408. void addTextRuns (const AttributedString& text)
  409. {
  410. Font defaultFont;
  411. Array<RunAttribute> runAttributes;
  412. {
  413. const int stringLength = text.getText().length();
  414. int rangeStart = 0;
  415. FontAndColour lastFontAndColour (nullptr);
  416. // Iterate through every character in the string
  417. for (int i = 0; i < stringLength; ++i)
  418. {
  419. FontAndColour newFontAndColour (&defaultFont);
  420. const int numCharacterAttributes = text.getNumAttributes();
  421. for (int j = 0; j < numCharacterAttributes; ++j)
  422. {
  423. const AttributedString::Attribute* const attr = text.getAttribute (j);
  424. // Check if the current character falls within the range of a font attribute
  425. if (attr->getFont() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
  426. newFontAndColour.font = attr->getFont();
  427. // Check if the current character falls within the range of a foreground colour attribute
  428. if (attr->getColour() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
  429. newFontAndColour.colour = *attr->getColour();
  430. }
  431. if (i > 0 && (newFontAndColour != lastFontAndColour || i == stringLength - 1))
  432. {
  433. runAttributes.add (RunAttribute (lastFontAndColour,
  434. Range<int> (rangeStart, (i < stringLength - 1) ? i : (i + 1))));
  435. rangeStart = i;
  436. }
  437. lastFontAndColour = newFontAndColour;
  438. }
  439. }
  440. for (int i = 0; i < runAttributes.size(); ++i)
  441. {
  442. const RunAttribute& r = runAttributes.getReference(i);
  443. appendText (text, r.range, *(r.fontAndColour.font), r.fontAndColour.colour);
  444. }
  445. }
  446. OwnedArray<Token> tokens;
  447. int totalLines;
  448. JUCE_DECLARE_NON_COPYABLE (TokenList);
  449. };
  450. }
  451. //==============================================================================
  452. void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
  453. {
  454. const float minimumWidth = maxWidth / 2.0f;
  455. float bestWidth = maxWidth;
  456. float bestLineProportion = 0.0f;
  457. while (maxWidth > minimumWidth)
  458. {
  459. createLayout (text, maxWidth);
  460. if (getNumLines() < 2)
  461. return;
  462. const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
  463. const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
  464. const float shortestLine = jmin (line1, line2);
  465. const float prop = (shortestLine > 0) ? jmax (line1, line2) / shortestLine : 1.0f;
  466. if (prop > 0.9f)
  467. return;
  468. if (prop > bestLineProportion)
  469. {
  470. bestLineProportion = prop;
  471. bestWidth = maxWidth;
  472. }
  473. maxWidth -= 10.0f;
  474. }
  475. if (bestWidth != maxWidth)
  476. createLayout (text, bestWidth);
  477. }
  478. //==============================================================================
  479. void TextLayout::createStandardLayout (const AttributedString& text)
  480. {
  481. TextLayoutHelpers::TokenList l;
  482. l.createLayout (text, *this);
  483. }
  484. void TextLayout::recalculateWidth (const AttributedString& text)
  485. {
  486. if (lines.size() > 0 && text.getReadingDirection() != AttributedString::rightToLeft)
  487. {
  488. Range<float> range (lines.getFirst()->getLineBoundsX());
  489. for (int i = lines.size(); --i > 0;)
  490. range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
  491. for (int i = lines.size(); --i >= 0;)
  492. lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
  493. width = range.getLength();
  494. }
  495. }