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.

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