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.

622 lines
21KB

  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();
  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. 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 shortestLine = jmin (line1, line2);
  468. const float prop = (shortestLine > 0) ? jmax (line1, line2) / shortestLine : 1.0f;
  469. if (prop > 0.9f)
  470. return;
  471. if (prop > bestLineProportion)
  472. {
  473. bestLineProportion = prop;
  474. bestWidth = maxWidth;
  475. }
  476. maxWidth -= 10.0f;
  477. }
  478. if (bestWidth != maxWidth)
  479. createLayout (text, bestWidth);
  480. }
  481. //==============================================================================
  482. void TextLayout::createStandardLayout (const AttributedString& text)
  483. {
  484. TextLayoutHelpers::TokenList l;
  485. l.createLayout (text, *this);
  486. }
  487. void TextLayout::recalculateWidth()
  488. {
  489. if (lines.size() > 0)
  490. {
  491. Range<float> range (lines.getFirst()->getLineBoundsX());
  492. int i;
  493. for (i = lines.size(); --i > 0;)
  494. range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
  495. for (i = lines.size(); --i >= 0;)
  496. lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
  497. width = range.getLength();
  498. }
  499. }