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.

621 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. bool needToSetLineOrigin = true;
  248. for (int i = 0; i < tokens.size(); ++i)
  249. {
  250. const Token* const t = tokens.getUnchecked (i);
  251. const Point<float> tokenPos (t->area.getPosition().toFloat());
  252. Array <int> newGlyphs;
  253. Array <float> xOffsets;
  254. t->font.getGlyphPositions (t->text.trimEnd(), newGlyphs, xOffsets);
  255. glyphRun->glyphs.ensureStorageAllocated (glyphRun->glyphs.size() + newGlyphs.size());
  256. for (int j = 0; j < newGlyphs.size(); ++j)
  257. {
  258. if (needToSetLineOrigin)
  259. {
  260. needToSetLineOrigin = false;
  261. glyphLine->lineOrigin = tokenPos.translated (0, t->font.getAscent());
  262. }
  263. const float x = xOffsets.getUnchecked (j);
  264. glyphRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
  265. Point<float> (tokenPos.getX() + x, 0),
  266. xOffsets.getUnchecked (j + 1) - x));
  267. ++charPosition;
  268. }
  269. if (t->isWhitespace || t->isNewLine)
  270. ++charPosition;
  271. const Token* const nextToken = tokens [i + 1];
  272. if (nextToken == nullptr) // this is the last token
  273. {
  274. addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
  275. glyphLine->stringRange = Range<int> (lineStartPosition, charPosition);
  276. layout.addLine (glyphLine);
  277. }
  278. else
  279. {
  280. if (t->font != nextToken->font || t->colour != nextToken->colour)
  281. {
  282. addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
  283. runStartPosition = charPosition;
  284. glyphRun = new TextLayout::Run();
  285. }
  286. if (t->line != nextToken->line)
  287. {
  288. addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
  289. glyphLine->stringRange = Range<int> (lineStartPosition, charPosition);
  290. layout.addLine (glyphLine);
  291. runStartPosition = charPosition;
  292. lineStartPosition = charPosition;
  293. glyphLine = new TextLayout::Line();
  294. glyphRun = new TextLayout::Run();
  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. for (int i = 0; i < layout.getNumLines(); ++i)
  303. {
  304. const int lineW = getLineWidth (i);
  305. float dx = 0;
  306. if ((text.getJustification().getFlags() & Justification::right) != 0)
  307. dx = (float) (totalW - lineW);
  308. else
  309. dx = (totalW - lineW) / 2.0f;
  310. TextLayout::Line& glyphLine = layout.getLine (i);
  311. glyphLine.lineOrigin.x += dx;
  312. }
  313. }
  314. }
  315. private:
  316. static void addRun (TextLayout::Line* glyphLine, TextLayout::Run* glyphRun,
  317. const Token* const t, const int start, const int end)
  318. {
  319. glyphRun->stringRange = Range<int> (start, end);
  320. glyphRun->font = t->font;
  321. glyphRun->colour = t->colour;
  322. glyphLine->ascent = jmax (glyphLine->ascent, t->font.getAscent());
  323. glyphLine->descent = jmax (glyphLine->descent, t->font.getDescent());
  324. glyphLine->runs.add (glyphRun);
  325. }
  326. static int getCharacterType (const juce_wchar c) noexcept
  327. {
  328. if (c == '\r' || c == '\n')
  329. return 0;
  330. return CharacterFunctions::isWhitespace (c) ? 2 : 1;
  331. }
  332. void appendText (const AttributedString& text, const Range<int>& stringRange,
  333. const Font& font, const Colour& colour)
  334. {
  335. const String stringText (text.getText().substring (stringRange.getStart(), stringRange.getEnd()));
  336. String::CharPointerType t (stringText.getCharPointer());
  337. String currentString;
  338. int lastCharType = 0;
  339. for (;;)
  340. {
  341. const juce_wchar c = t.getAndAdvance();
  342. if (c == 0)
  343. break;
  344. const int charType = getCharacterType (c);
  345. if (charType == 0 || charType != lastCharType)
  346. {
  347. if (currentString.isNotEmpty())
  348. tokens.add (new Token (currentString, font, colour,
  349. lastCharType == 2 || lastCharType == 0));
  350. currentString = String::charToString (c);
  351. if (c == '\r' && *t == '\n')
  352. currentString += t.getAndAdvance();
  353. }
  354. else
  355. {
  356. currentString += c;
  357. }
  358. lastCharType = charType;
  359. }
  360. if (currentString.isNotEmpty())
  361. tokens.add (new Token (currentString, font, colour, lastCharType == 2));
  362. }
  363. void layoutRuns (const int maxWidth)
  364. {
  365. int x = 0, y = 0, h = 0;
  366. int i;
  367. for (i = 0; i < tokens.size(); ++i)
  368. {
  369. Token* const t = tokens.getUnchecked(i);
  370. t->area.setPosition (x, y);
  371. t->line = totalLines;
  372. x += t->area.getWidth();
  373. h = jmax (h, t->area.getHeight());
  374. const Token* const nextTok = tokens[i + 1];
  375. if (nextTok == nullptr)
  376. break;
  377. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->area.getWidth() > maxWidth))
  378. {
  379. setLastLineHeight (i + 1, h);
  380. x = 0;
  381. y += h;
  382. h = 0;
  383. ++totalLines;
  384. }
  385. }
  386. setLastLineHeight (jmin (i + 1, tokens.size()), h);
  387. ++totalLines;
  388. }
  389. void setLastLineHeight (int i, const int height) noexcept
  390. {
  391. while (--i >= 0)
  392. {
  393. Token* const tok = tokens.getUnchecked (i);
  394. if (tok->line == totalLines)
  395. tok->lineHeight = height;
  396. else
  397. break;
  398. }
  399. }
  400. int getLineWidth (const int lineNumber) const noexcept
  401. {
  402. int maxW = 0;
  403. for (int i = tokens.size(); --i >= 0;)
  404. {
  405. const Token* const t = tokens.getUnchecked (i);
  406. if (t->line == lineNumber && ! t->isWhitespace)
  407. maxW = jmax (maxW, t->area.getRight());
  408. }
  409. return maxW;
  410. }
  411. void addTextRuns (const AttributedString& text)
  412. {
  413. Font defaultFont;
  414. Array<RunAttribute> runAttributes;
  415. {
  416. const int stringLength = text.getText().length();
  417. int rangeStart = 0;
  418. FontAndColour lastFontAndColour (nullptr);
  419. // Iterate through every character in the string
  420. for (int i = 0; i < stringLength; ++i)
  421. {
  422. FontAndColour newFontAndColour (&defaultFont);
  423. const int numCharacterAttributes = text.getNumAttributes();
  424. for (int j = 0; j < numCharacterAttributes; ++j)
  425. {
  426. const AttributedString::Attribute* const attr = text.getAttribute (j);
  427. // Check if the current character falls within the range of a font attribute
  428. if (attr->getFont() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
  429. newFontAndColour.font = attr->getFont();
  430. // Check if the current character falls within the range of a foreground colour attribute
  431. if (attr->getColour() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
  432. newFontAndColour.colour = *attr->getColour();
  433. }
  434. if (i > 0 && (newFontAndColour != lastFontAndColour || i == stringLength - 1))
  435. {
  436. runAttributes.add (RunAttribute (lastFontAndColour,
  437. Range<int> (rangeStart, (i < stringLength - 1) ? i : (i + 1))));
  438. rangeStart = i;
  439. }
  440. lastFontAndColour = newFontAndColour;
  441. }
  442. }
  443. for (int i = 0; i < runAttributes.size(); ++i)
  444. {
  445. const RunAttribute& r = runAttributes.getReference(i);
  446. appendText (text, r.range, *(r.fontAndColour.font), r.fontAndColour.colour);
  447. }
  448. }
  449. OwnedArray<Token> tokens;
  450. int totalLines;
  451. JUCE_DECLARE_NON_COPYABLE (TokenList);
  452. };
  453. }
  454. //==============================================================================
  455. void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
  456. {
  457. const float minimumWidth = maxWidth / 2.0f;
  458. float bestWidth = maxWidth;
  459. float bestLineProportion = 0.0f;
  460. while (maxWidth > minimumWidth)
  461. {
  462. createLayout (text, maxWidth);
  463. if (getNumLines() < 2)
  464. return;
  465. const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
  466. const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
  467. const float prop = jmax (line1, line2) / jmin (line1, line2);
  468. if (prop > 0.9f)
  469. return;
  470. if (prop > bestLineProportion)
  471. {
  472. bestLineProportion = prop;
  473. bestWidth = maxWidth;
  474. }
  475. maxWidth -= 10.0f;
  476. }
  477. if (bestWidth != maxWidth)
  478. createLayout (text, bestWidth);
  479. }
  480. //==============================================================================
  481. void TextLayout::createStandardLayout (const AttributedString& text)
  482. {
  483. TextLayoutHelpers::TokenList l;
  484. l.createLayout (text, *this);
  485. }
  486. void TextLayout::recalculateWidth()
  487. {
  488. if (lines.size() > 0)
  489. {
  490. Range<float> range (lines.getFirst()->getLineBoundsX());
  491. int i;
  492. for (i = lines.size(); --i > 0;)
  493. range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
  494. for (i = lines.size(); --i >= 0;)
  495. lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
  496. width = range.getLength();
  497. }
  498. }
  499. END_JUCE_NAMESPACE