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.

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