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.

586 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. TextLayout::Glyph::Glyph (const int glyph, Point<float> anch, float w) noexcept
  20. : glyphCode (glyph), anchor (anch), width (w)
  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 (Range<int> range, 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 (Range<int> range, Point<float> o, float asc, float desc,
  59. float lead, int numRunsToPreallocate)
  60. : stringRange (range), lineOrigin (o),
  61. ascent (asc), descent (desc), leading (lead)
  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 (auto* run : runs)
  79. {
  80. for (auto& glyph : run->glyphs)
  81. {
  82. Range<float> runRange (glyph.anchor.x, glyph.anchor.x + glyph.width);
  83. if (isFirst)
  84. {
  85. isFirst = false;
  86. range = runRange;
  87. }
  88. else
  89. {
  90. range = range.getUnionWith (runRange);
  91. }
  92. }
  93. }
  94. return range + lineOrigin.x;
  95. }
  96. Range<float> TextLayout::Line::getLineBoundsY() const noexcept
  97. {
  98. return Range<float> (lineOrigin.y - ascent,
  99. lineOrigin.y + descent);
  100. }
  101. Rectangle<float> TextLayout::Line::getLineBounds() const noexcept
  102. {
  103. auto x = getLineBoundsX();
  104. auto y = getLineBoundsY();
  105. return { x.getStart(), y.getStart(), x.getLength(), y.getLength() };
  106. }
  107. //==============================================================================
  108. TextLayout::TextLayout()
  109. : width (0), height (0), justification (Justification::topLeft)
  110. {
  111. }
  112. TextLayout::TextLayout (const TextLayout& other)
  113. : width (other.width), height (other.height),
  114. justification (other.justification)
  115. {
  116. lines.addCopiesOf (other.lines);
  117. }
  118. TextLayout::TextLayout (TextLayout&& other) noexcept
  119. : lines (static_cast<OwnedArray<Line>&&> (other.lines)),
  120. width (other.width), height (other.height),
  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. height = other.height;
  129. justification = other.justification;
  130. return *this;
  131. }
  132. TextLayout& TextLayout::operator= (const TextLayout& other)
  133. {
  134. width = other.width;
  135. height = other.height;
  136. justification = other.justification;
  137. lines.clear();
  138. lines.addCopiesOf (other.lines);
  139. return *this;
  140. }
  141. TextLayout::~TextLayout()
  142. {
  143. }
  144. TextLayout::Line& TextLayout::getLine (const int index) const
  145. {
  146. return *lines.getUnchecked (index);
  147. }
  148. void TextLayout::ensureStorageAllocated (int numLinesNeeded)
  149. {
  150. lines.ensureStorageAllocated (numLinesNeeded);
  151. }
  152. void TextLayout::addLine (Line* line)
  153. {
  154. lines.add (line);
  155. }
  156. void TextLayout::draw (Graphics& g, Rectangle<float> area) const
  157. {
  158. auto origin = justification.appliedToRectangle (Rectangle<float> (width, getHeight()), area).getPosition();
  159. auto& context = g.getInternalContext();
  160. for (auto* line : lines)
  161. {
  162. auto lineOrigin = origin + line->lineOrigin;
  163. for (auto* run : line->runs)
  164. {
  165. context.setFont (run->font);
  166. context.setFill (run->colour);
  167. for (auto& glyph : run->glyphs)
  168. context.drawGlyph (glyph.glyphCode, AffineTransform::translation (lineOrigin.x + glyph.anchor.x,
  169. lineOrigin.y + glyph.anchor.y));
  170. if (run->font.isUnderlined())
  171. {
  172. Range<float> runExtent;
  173. for (auto& glyph : run->glyphs)
  174. {
  175. Range<float> glyphRange (glyph.anchor.x, glyph.anchor.x + glyph.width);
  176. runExtent = runExtent.isEmpty() ? glyphRange
  177. : runExtent.getUnionWith (glyphRange);
  178. }
  179. const float lineThickness = run->font.getDescent() * 0.3f;
  180. context.fillRect ({ runExtent.getStart() + lineOrigin.x, lineOrigin.y + lineThickness * 2.0f,
  181. runExtent.getLength(), lineThickness });
  182. }
  183. }
  184. }
  185. }
  186. void TextLayout::createLayout (const AttributedString& text, float maxWidth)
  187. {
  188. createLayout (text, maxWidth, 1.0e7f);
  189. }
  190. void TextLayout::createLayout (const AttributedString& text, float maxWidth, float maxHeight)
  191. {
  192. lines.clear();
  193. width = maxWidth;
  194. height = maxHeight;
  195. justification = text.getJustification();
  196. if (! createNativeLayout (text))
  197. createStandardLayout (text);
  198. recalculateSize();
  199. }
  200. void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
  201. {
  202. createLayoutWithBalancedLineLengths (text, maxWidth, 1.0e7f);
  203. }
  204. void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth, float maxHeight)
  205. {
  206. const float minimumWidth = maxWidth / 2.0f;
  207. float bestWidth = maxWidth;
  208. float bestLineProportion = 0.0f;
  209. while (maxWidth > minimumWidth)
  210. {
  211. createLayout (text, maxWidth, maxHeight);
  212. if (getNumLines() < 2)
  213. return;
  214. const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
  215. const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
  216. const float shortestLine = jmin (line1, line2);
  217. const float prop = (shortestLine > 0) ? jmax (line1, line2) / shortestLine : 1.0f;
  218. if (prop > 0.9f)
  219. return;
  220. if (prop > bestLineProportion)
  221. {
  222. bestLineProportion = prop;
  223. bestWidth = maxWidth;
  224. }
  225. maxWidth -= 10.0f;
  226. }
  227. if (bestWidth != maxWidth)
  228. createLayout (text, bestWidth, maxHeight);
  229. }
  230. //==============================================================================
  231. namespace TextLayoutHelpers
  232. {
  233. struct Token
  234. {
  235. Token (const String& t, const Font& f, Colour c, bool whitespace)
  236. : text (t), font (f), colour (c),
  237. area (font.getStringWidthFloat (t), f.getHeight()),
  238. isWhitespace (whitespace),
  239. isNewLine (t.containsChar ('\n') || t.containsChar ('\r'))
  240. {}
  241. const String text;
  242. const Font font;
  243. const Colour colour;
  244. Rectangle<float> area;
  245. int line;
  246. float lineHeight;
  247. const bool isWhitespace, isNewLine;
  248. private:
  249. Token& operator= (const Token&);
  250. };
  251. struct TokenList
  252. {
  253. TokenList() noexcept {}
  254. void createLayout (const AttributedString& text, TextLayout& layout)
  255. {
  256. layout.ensureStorageAllocated (totalLines);
  257. addTextRuns (text);
  258. layoutRuns (layout.getWidth(), text.getLineSpacing(), text.getWordWrap());
  259. int charPosition = 0;
  260. int lineStartPosition = 0;
  261. int runStartPosition = 0;
  262. ScopedPointer<TextLayout::Line> currentLine;
  263. ScopedPointer<TextLayout::Run> currentRun;
  264. bool needToSetLineOrigin = true;
  265. for (int i = 0; i < tokens.size(); ++i)
  266. {
  267. auto& t = *tokens.getUnchecked (i);
  268. Array<int> newGlyphs;
  269. Array<float> xOffsets;
  270. t.font.getGlyphPositions (getTrimmedEndIfNotAllWhitespace (t.text), newGlyphs, xOffsets);
  271. if (currentRun == nullptr) currentRun = new TextLayout::Run();
  272. if (currentLine == nullptr) currentLine = new TextLayout::Line();
  273. if (newGlyphs.size() > 0)
  274. {
  275. currentRun->glyphs.ensureStorageAllocated (currentRun->glyphs.size() + newGlyphs.size());
  276. const Point<float> tokenOrigin (t.area.getPosition().translated (0, t.font.getAscent()));
  277. if (needToSetLineOrigin)
  278. {
  279. needToSetLineOrigin = false;
  280. currentLine->lineOrigin = tokenOrigin;
  281. }
  282. const Point<float> glyphOffset (tokenOrigin - currentLine->lineOrigin);
  283. for (int j = 0; j < newGlyphs.size(); ++j)
  284. {
  285. const float x = xOffsets.getUnchecked (j);
  286. currentRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
  287. glyphOffset.translated (x, 0),
  288. xOffsets.getUnchecked (j + 1) - x));
  289. }
  290. charPosition += newGlyphs.size();
  291. }
  292. if (t.isWhitespace || t.isNewLine)
  293. ++charPosition;
  294. if (auto* nextToken = tokens [i + 1])
  295. {
  296. if (t.font != nextToken->font || t.colour != nextToken->colour)
  297. {
  298. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  299. runStartPosition = charPosition;
  300. }
  301. if (t.line != nextToken->line)
  302. {
  303. if (currentRun == nullptr)
  304. currentRun = new TextLayout::Run();
  305. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  306. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  307. if (! needToSetLineOrigin)
  308. layout.addLine (currentLine.release());
  309. runStartPosition = charPosition;
  310. lineStartPosition = charPosition;
  311. needToSetLineOrigin = true;
  312. }
  313. }
  314. else
  315. {
  316. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  317. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  318. if (! needToSetLineOrigin)
  319. layout.addLine (currentLine.release());
  320. needToSetLineOrigin = true;
  321. }
  322. }
  323. if ((text.getJustification().getFlags() & (Justification::right | Justification::horizontallyCentred)) != 0)
  324. {
  325. const float totalW = layout.getWidth();
  326. const bool isCentred = (text.getJustification().getFlags() & Justification::horizontallyCentred) != 0;
  327. for (int i = 0; i < layout.getNumLines(); ++i)
  328. {
  329. float dx = totalW - layout.getLine(i).getLineBoundsX().getLength();
  330. if (isCentred)
  331. dx /= 2.0f;
  332. layout.getLine(i).lineOrigin.x += dx;
  333. }
  334. }
  335. }
  336. private:
  337. static void addRun (TextLayout::Line& glyphLine, TextLayout::Run* glyphRun,
  338. const Token& t, const int start, const int end)
  339. {
  340. glyphRun->stringRange = { start, end };
  341. glyphRun->font = t.font;
  342. glyphRun->colour = t.colour;
  343. glyphLine.ascent = jmax (glyphLine.ascent, t.font.getAscent());
  344. glyphLine.descent = jmax (glyphLine.descent, t.font.getDescent());
  345. glyphLine.runs.add (glyphRun);
  346. }
  347. static int getCharacterType (const juce_wchar c) noexcept
  348. {
  349. if (c == '\r' || c == '\n')
  350. return 0;
  351. return CharacterFunctions::isWhitespace (c) ? 2 : 1;
  352. }
  353. void appendText (const String& stringText, const Font& font, Colour colour)
  354. {
  355. auto t = stringText.getCharPointer();
  356. String currentString;
  357. int lastCharType = 0;
  358. for (;;)
  359. {
  360. const juce_wchar c = t.getAndAdvance();
  361. if (c == 0)
  362. break;
  363. const int charType = getCharacterType (c);
  364. if (charType == 0 || charType != lastCharType)
  365. {
  366. if (currentString.isNotEmpty())
  367. tokens.add (new Token (currentString, font, colour,
  368. lastCharType == 2 || lastCharType == 0));
  369. currentString = String::charToString (c);
  370. if (c == '\r' && *t == '\n')
  371. currentString += t.getAndAdvance();
  372. }
  373. else
  374. {
  375. currentString += c;
  376. }
  377. lastCharType = charType;
  378. }
  379. if (currentString.isNotEmpty())
  380. tokens.add (new Token (currentString, font, colour, lastCharType == 2));
  381. }
  382. void layoutRuns (const float maxWidth, const float extraLineSpacing, const AttributedString::WordWrap wordWrap)
  383. {
  384. float x = 0, y = 0, h = 0;
  385. int i;
  386. for (i = 0; i < tokens.size(); ++i)
  387. {
  388. auto& t = *tokens.getUnchecked(i);
  389. t.area.setPosition (x, y);
  390. t.line = totalLines;
  391. x += t.area.getWidth();
  392. h = jmax (h, t.area.getHeight() + extraLineSpacing);
  393. auto* nextTok = tokens[i + 1];
  394. if (nextTok == nullptr)
  395. break;
  396. const bool tokenTooLarge = (x + nextTok->area.getWidth() > maxWidth);
  397. if (t.isNewLine || ((! nextTok->isWhitespace) && (tokenTooLarge && wordWrap != AttributedString::none)))
  398. {
  399. setLastLineHeight (i + 1, h);
  400. x = 0;
  401. y += h;
  402. h = 0;
  403. ++totalLines;
  404. }
  405. }
  406. setLastLineHeight (jmin (i + 1, tokens.size()), h);
  407. ++totalLines;
  408. }
  409. void setLastLineHeight (int i, const float height) noexcept
  410. {
  411. while (--i >= 0)
  412. {
  413. auto& tok = *tokens.getUnchecked (i);
  414. if (tok.line == totalLines)
  415. tok.lineHeight = height;
  416. else
  417. break;
  418. }
  419. }
  420. void addTextRuns (const AttributedString& text)
  421. {
  422. const int numAttributes = text.getNumAttributes();
  423. tokens.ensureStorageAllocated (jmax (64, numAttributes));
  424. for (int i = 0; i < numAttributes; ++i)
  425. {
  426. auto& attr = text.getAttribute (i);
  427. appendText (text.getText().substring (attr.range.getStart(), attr.range.getEnd()),
  428. attr.font, attr.colour);
  429. }
  430. }
  431. static String getTrimmedEndIfNotAllWhitespace (const String& s)
  432. {
  433. auto trimmed = s.trimEnd();
  434. if (trimmed.isEmpty() && s.isNotEmpty())
  435. trimmed = s.replaceCharacters ("\r\n\t", " ");
  436. return trimmed;
  437. }
  438. OwnedArray<Token> tokens;
  439. int totalLines = 0;
  440. JUCE_DECLARE_NON_COPYABLE (TokenList)
  441. };
  442. }
  443. //==============================================================================
  444. void TextLayout::createStandardLayout (const AttributedString& text)
  445. {
  446. TextLayoutHelpers::TokenList l;
  447. l.createLayout (text, *this);
  448. }
  449. void TextLayout::recalculateSize()
  450. {
  451. if (! lines.isEmpty())
  452. {
  453. auto bounds = lines.getFirst()->getLineBounds();
  454. for (auto* line : lines)
  455. bounds = bounds.getUnion (line->getLineBounds());
  456. for (auto* line : lines)
  457. line->lineOrigin.x -= bounds.getX();
  458. width = bounds.getWidth();
  459. height = bounds.getHeight();
  460. }
  461. else
  462. {
  463. width = 0;
  464. height = 0;
  465. }
  466. }