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.

juce_TextLayout.cpp 19KB

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