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.

615 lines
19KB

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