Audio plugin host https://kx.studio/carla
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.

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