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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. TextLayout::Glyph::Glyph (const int glyphCode_, Point<float> anchor_, float width_) noexcept
  18. : glyphCode (glyphCode_), anchor (anchor_), width (width_)
  19. {
  20. }
  21. TextLayout::Glyph::Glyph (const Glyph& other) noexcept
  22. : glyphCode (other.glyphCode), anchor (other.anchor), width (other.width)
  23. {
  24. }
  25. TextLayout::Glyph& TextLayout::Glyph::operator= (const Glyph& other) noexcept
  26. {
  27. glyphCode = other.glyphCode;
  28. anchor = other.anchor;
  29. width = other.width;
  30. return *this;
  31. }
  32. TextLayout::Glyph::~Glyph() noexcept {}
  33. //==============================================================================
  34. TextLayout::Run::Run() noexcept
  35. : colour (0xff000000)
  36. {
  37. }
  38. TextLayout::Run::Run (Range<int> range, const int numGlyphsToPreallocate)
  39. : colour (0xff000000), stringRange (range)
  40. {
  41. glyphs.ensureStorageAllocated (numGlyphsToPreallocate);
  42. }
  43. TextLayout::Run::Run (const Run& other)
  44. : font (other.font),
  45. colour (other.colour),
  46. glyphs (other.glyphs),
  47. stringRange (other.stringRange)
  48. {
  49. }
  50. TextLayout::Run::~Run() noexcept {}
  51. //==============================================================================
  52. TextLayout::Line::Line() noexcept
  53. : ascent (0.0f), descent (0.0f), leading (0.0f)
  54. {
  55. }
  56. TextLayout::Line::Line (Range<int> stringRange_, Point<float> lineOrigin_,
  57. const float ascent_, const float descent_, const float leading_,
  58. const int numRunsToPreallocate)
  59. : stringRange (stringRange_), lineOrigin (lineOrigin_),
  60. ascent (ascent_), descent (descent_), leading (leading_)
  61. {
  62. runs.ensureStorageAllocated (numRunsToPreallocate);
  63. }
  64. TextLayout::Line::Line (const Line& other)
  65. : stringRange (other.stringRange), lineOrigin (other.lineOrigin),
  66. ascent (other.ascent), descent (other.descent), leading (other.leading)
  67. {
  68. runs.addCopiesOf (other.runs);
  69. }
  70. TextLayout::Line::~Line() noexcept
  71. {
  72. }
  73. Range<float> TextLayout::Line::getLineBoundsX() const noexcept
  74. {
  75. Range<float> range;
  76. bool isFirst = true;
  77. for (int i = runs.size(); --i >= 0;)
  78. {
  79. const Run& run = *runs.getUnchecked(i);
  80. if (run.glyphs.size() > 0)
  81. {
  82. float minX = run.glyphs.getReference(0).anchor.x;
  83. float maxX = minX;
  84. for (int j = run.glyphs.size(); --j >= 0;)
  85. {
  86. const Glyph& glyph = run.glyphs.getReference (j);
  87. const float x = glyph.anchor.x;
  88. minX = jmin (minX, x);
  89. maxX = jmax (maxX, x + glyph.width);
  90. }
  91. if (isFirst)
  92. {
  93. isFirst = false;
  94. range = Range<float> (minX, maxX);
  95. }
  96. else
  97. {
  98. range = range.getUnionWith (Range<float> (minX, maxX));
  99. }
  100. }
  101. }
  102. return range + lineOrigin.x;
  103. }
  104. //==============================================================================
  105. TextLayout::TextLayout()
  106. : width (0), justification (Justification::topLeft)
  107. {
  108. }
  109. TextLayout::TextLayout (const TextLayout& other)
  110. : width (other.width),
  111. justification (other.justification)
  112. {
  113. lines.addCopiesOf (other.lines);
  114. }
  115. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  116. TextLayout::TextLayout (TextLayout&& other) noexcept
  117. : lines (static_cast <OwnedArray<Line>&&> (other.lines)),
  118. width (other.width),
  119. justification (other.justification)
  120. {
  121. }
  122. TextLayout& TextLayout::operator= (TextLayout&& other) noexcept
  123. {
  124. lines = static_cast <OwnedArray<Line>&&> (other.lines);
  125. width = other.width;
  126. justification = other.justification;
  127. return *this;
  128. }
  129. #endif
  130. TextLayout& TextLayout::operator= (const TextLayout& other)
  131. {
  132. width = other.width;
  133. justification = other.justification;
  134. lines.clear();
  135. lines.addCopiesOf (other.lines);
  136. return *this;
  137. }
  138. TextLayout::~TextLayout()
  139. {
  140. }
  141. float TextLayout::getHeight() const noexcept
  142. {
  143. if (const Line* const lastLine = lines.getLast())
  144. return lastLine->lineOrigin.y + lastLine->descent;
  145. return 0.0f;
  146. }
  147. TextLayout::Line& TextLayout::getLine (const int index) const
  148. {
  149. return *lines[index];
  150. }
  151. void TextLayout::ensureStorageAllocated (int numLinesNeeded)
  152. {
  153. lines.ensureStorageAllocated (numLinesNeeded);
  154. }
  155. void TextLayout::addLine (Line* line)
  156. {
  157. lines.add (line);
  158. }
  159. void TextLayout::draw (Graphics& g, const Rectangle<float>& area) const
  160. {
  161. const Point<float> origin (justification.appliedToRectangle (Rectangle<float> (width, getHeight()), area).getPosition());
  162. LowLevelGraphicsContext& context = g.getInternalContext();
  163. for (int i = 0; i < getNumLines(); ++i)
  164. {
  165. const Line& line = getLine (i);
  166. const Point<float> lineOrigin (origin + line.lineOrigin);
  167. for (int j = 0; j < line.runs.size(); ++j)
  168. {
  169. const Run& run = *line.runs.getUnchecked (j);
  170. context.setFont (run.font);
  171. context.setFill (run.colour);
  172. for (int k = 0; k < run.glyphs.size(); ++k)
  173. {
  174. const Glyph& glyph = run.glyphs.getReference (k);
  175. context.drawGlyph (glyph.glyphCode, AffineTransform::translation (lineOrigin.x + glyph.anchor.x,
  176. lineOrigin.y + glyph.anchor.y));
  177. }
  178. }
  179. }
  180. }
  181. void TextLayout::createLayout (const AttributedString& text, float maxWidth)
  182. {
  183. lines.clear();
  184. width = maxWidth;
  185. justification = text.getJustification();
  186. if (! createNativeLayout (text))
  187. createStandardLayout (text);
  188. recalculateWidth (text);
  189. }
  190. //==============================================================================
  191. namespace TextLayoutHelpers
  192. {
  193. struct FontAndColour
  194. {
  195. FontAndColour (const Font* f) noexcept : font (f), colour (0xff000000) {}
  196. const Font* font;
  197. Colour colour;
  198. bool operator!= (const FontAndColour& other) const noexcept
  199. {
  200. return (font != other.font && *font != *other.font) || colour != other.colour;
  201. }
  202. };
  203. struct RunAttribute
  204. {
  205. RunAttribute (const FontAndColour& fc, const Range<int> r) noexcept
  206. : fontAndColour (fc), range (r)
  207. {}
  208. FontAndColour fontAndColour;
  209. Range<int> range;
  210. };
  211. struct Token
  212. {
  213. Token (const String& t, const Font& f, Colour c, const bool whitespace)
  214. : text (t), font (f), colour (c),
  215. area (font.getStringWidthFloat (t), f.getHeight()),
  216. isWhitespace (whitespace),
  217. isNewLine (t.containsChar ('\n') || t.containsChar ('\r'))
  218. {}
  219. const String text;
  220. const Font font;
  221. const Colour colour;
  222. Rectangle<float> area;
  223. int line;
  224. float lineHeight;
  225. const bool isWhitespace, isNewLine;
  226. private:
  227. Token& operator= (const Token&);
  228. };
  229. class TokenList
  230. {
  231. public:
  232. TokenList() noexcept : totalLines (0) {}
  233. void createLayout (const AttributedString& text, TextLayout& layout)
  234. {
  235. tokens.ensureStorageAllocated (64);
  236. layout.ensureStorageAllocated (totalLines);
  237. addTextRuns (text);
  238. layoutRuns (layout.getWidth());
  239. int charPosition = 0;
  240. int lineStartPosition = 0;
  241. int runStartPosition = 0;
  242. ScopedPointer<TextLayout::Line> currentLine;
  243. ScopedPointer<TextLayout::Run> currentRun;
  244. bool needToSetLineOrigin = true;
  245. for (int i = 0; i < tokens.size(); ++i)
  246. {
  247. const Token& t = *tokens.getUnchecked (i);
  248. Array <int> newGlyphs;
  249. Array <float> xOffsets;
  250. t.font.getGlyphPositions (getTrimmedEndIfNotAllWhitespace (t.text), newGlyphs, xOffsets);
  251. if (currentRun == nullptr) currentRun = new TextLayout::Run();
  252. if (currentLine == nullptr) currentLine = new TextLayout::Line();
  253. if (newGlyphs.size() > 0)
  254. {
  255. currentRun->glyphs.ensureStorageAllocated (currentRun->glyphs.size() + newGlyphs.size());
  256. const Point<float> tokenOrigin (t.area.getPosition().translated (0, t.font.getAscent()));
  257. if (needToSetLineOrigin)
  258. {
  259. needToSetLineOrigin = false;
  260. currentLine->lineOrigin = tokenOrigin;
  261. }
  262. const Point<float> glyphOffset (tokenOrigin - currentLine->lineOrigin);
  263. for (int j = 0; j < newGlyphs.size(); ++j)
  264. {
  265. const float x = xOffsets.getUnchecked (j);
  266. currentRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
  267. glyphOffset.translated (x, 0),
  268. xOffsets.getUnchecked (j + 1) - x));
  269. }
  270. charPosition += newGlyphs.size();
  271. }
  272. if (t.isWhitespace || t.isNewLine)
  273. ++charPosition;
  274. const Token* const nextToken = tokens [i + 1];
  275. if (nextToken == nullptr) // this is the last token
  276. {
  277. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  278. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  279. if (! needToSetLineOrigin)
  280. layout.addLine (currentLine.release());
  281. needToSetLineOrigin = true;
  282. }
  283. else
  284. {
  285. if (t.font != nextToken->font || t.colour != nextToken->colour)
  286. {
  287. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  288. runStartPosition = charPosition;
  289. }
  290. if (t.line != nextToken->line)
  291. {
  292. if (currentRun == nullptr)
  293. currentRun = new TextLayout::Run();
  294. addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
  295. currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
  296. if (! needToSetLineOrigin)
  297. layout.addLine (currentLine.release());
  298. runStartPosition = charPosition;
  299. lineStartPosition = charPosition;
  300. needToSetLineOrigin = true;
  301. }
  302. }
  303. }
  304. if ((text.getJustification().getFlags() & (Justification::right | Justification::horizontallyCentred)) != 0)
  305. {
  306. const float totalW = layout.getWidth();
  307. const bool isCentred = (text.getJustification().getFlags() & Justification::horizontallyCentred) != 0;
  308. for (int i = 0; i < layout.getNumLines(); ++i)
  309. {
  310. float dx = totalW - layout.getLine(i).getLineBoundsX().getLength();
  311. if (isCentred)
  312. dx /= 2.0f;
  313. layout.getLine(i).lineOrigin.x += dx;
  314. }
  315. }
  316. }
  317. private:
  318. static void addRun (TextLayout::Line& glyphLine, TextLayout::Run* glyphRun,
  319. const Token& t, const int start, const int end)
  320. {
  321. glyphRun->stringRange = Range<int> (start, end);
  322. glyphRun->font = t.font;
  323. glyphRun->colour = t.colour;
  324. glyphLine.ascent = jmax (glyphLine.ascent, t.font.getAscent());
  325. glyphLine.descent = jmax (glyphLine.descent, t.font.getDescent());
  326. glyphLine.runs.add (glyphRun);
  327. }
  328. static int getCharacterType (const juce_wchar c) noexcept
  329. {
  330. if (c == '\r' || c == '\n')
  331. return 0;
  332. return CharacterFunctions::isWhitespace (c) ? 2 : 1;
  333. }
  334. void appendText (const AttributedString& text, const Range<int> stringRange,
  335. const Font& font, Colour colour)
  336. {
  337. const String stringText (text.getText().substring (stringRange.getStart(), stringRange.getEnd()));
  338. String::CharPointerType t (stringText.getCharPointer());
  339. String currentString;
  340. int lastCharType = 0;
  341. for (;;)
  342. {
  343. const juce_wchar c = t.getAndAdvance();
  344. if (c == 0)
  345. break;
  346. const int charType = getCharacterType (c);
  347. if (charType == 0 || charType != lastCharType)
  348. {
  349. if (currentString.isNotEmpty())
  350. tokens.add (new Token (currentString, font, colour,
  351. lastCharType == 2 || lastCharType == 0));
  352. currentString = String::charToString (c);
  353. if (c == '\r' && *t == '\n')
  354. currentString += t.getAndAdvance();
  355. }
  356. else
  357. {
  358. currentString += c;
  359. }
  360. lastCharType = charType;
  361. }
  362. if (currentString.isNotEmpty())
  363. tokens.add (new Token (currentString, font, colour, lastCharType == 2));
  364. }
  365. void layoutRuns (const float maxWidth)
  366. {
  367. float x = 0, y = 0, h = 0;
  368. int i;
  369. for (i = 0; i < tokens.size(); ++i)
  370. {
  371. Token& t = *tokens.getUnchecked(i);
  372. t.area.setPosition (x, y);
  373. t.line = totalLines;
  374. x += t.area.getWidth();
  375. h = jmax (h, t.area.getHeight());
  376. const Token* const nextTok = tokens[i + 1];
  377. if (nextTok == nullptr)
  378. break;
  379. if (t.isNewLine || ((! nextTok->isWhitespace) && x + nextTok->area.getWidth() > maxWidth))
  380. {
  381. setLastLineHeight (i + 1, h);
  382. x = 0;
  383. y += h;
  384. h = 0;
  385. ++totalLines;
  386. }
  387. }
  388. setLastLineHeight (jmin (i + 1, tokens.size()), h);
  389. ++totalLines;
  390. }
  391. void setLastLineHeight (int i, const float height) noexcept
  392. {
  393. while (--i >= 0)
  394. {
  395. Token& tok = *tokens.getUnchecked (i);
  396. if (tok.line == totalLines)
  397. tok.lineHeight = height;
  398. else
  399. break;
  400. }
  401. }
  402. void addTextRuns (const AttributedString& text)
  403. {
  404. Font defaultFont;
  405. Array<RunAttribute> runAttributes;
  406. {
  407. const int stringLength = text.getText().length();
  408. int rangeStart = 0;
  409. FontAndColour lastFontAndColour (&defaultFont);
  410. // Iterate through every character in the string
  411. for (int i = 0; i < stringLength; ++i)
  412. {
  413. FontAndColour newFontAndColour (&defaultFont);
  414. const int numCharacterAttributes = text.getNumAttributes();
  415. for (int j = 0; j < numCharacterAttributes; ++j)
  416. {
  417. const AttributedString::Attribute& attr = *text.getAttribute (j);
  418. if (attr.range.contains (i))
  419. {
  420. if (const Font* f = attr.getFont()) newFontAndColour.font = f;
  421. if (const Colour* c = attr.getColour()) newFontAndColour.colour = *c;
  422. }
  423. }
  424. if (i > 0 && newFontAndColour != lastFontAndColour)
  425. {
  426. runAttributes.add (RunAttribute (lastFontAndColour, Range<int> (rangeStart, i)));
  427. rangeStart = i;
  428. }
  429. lastFontAndColour = newFontAndColour;
  430. }
  431. if (rangeStart < stringLength)
  432. runAttributes.add (RunAttribute (lastFontAndColour, Range<int> (rangeStart, stringLength)));
  433. }
  434. for (int i = 0; i < runAttributes.size(); ++i)
  435. {
  436. const RunAttribute& r = runAttributes.getReference(i);
  437. appendText (text, r.range, *(r.fontAndColour.font), r.fontAndColour.colour);
  438. }
  439. }
  440. static String getTrimmedEndIfNotAllWhitespace (const String& s)
  441. {
  442. String trimmed (s.trimEnd());
  443. if (trimmed.isEmpty() && ! s.isEmpty())
  444. trimmed = s.replaceCharacters ("\r\n\t", " ");
  445. return trimmed;
  446. }
  447. OwnedArray<Token> tokens;
  448. int totalLines;
  449. JUCE_DECLARE_NON_COPYABLE (TokenList)
  450. };
  451. }
  452. //==============================================================================
  453. void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
  454. {
  455. const float minimumWidth = maxWidth / 2.0f;
  456. float bestWidth = maxWidth;
  457. float bestLineProportion = 0.0f;
  458. while (maxWidth > minimumWidth)
  459. {
  460. createLayout (text, maxWidth);
  461. if (getNumLines() < 2)
  462. return;
  463. const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
  464. const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
  465. const float shortestLine = jmin (line1, line2);
  466. const float prop = (shortestLine > 0) ? jmax (line1, line2) / shortestLine : 1.0f;
  467. if (prop > 0.9f)
  468. return;
  469. if (prop > bestLineProportion)
  470. {
  471. bestLineProportion = prop;
  472. bestWidth = maxWidth;
  473. }
  474. maxWidth -= 10.0f;
  475. }
  476. if (bestWidth != maxWidth)
  477. createLayout (text, bestWidth);
  478. }
  479. //==============================================================================
  480. void TextLayout::createStandardLayout (const AttributedString& text)
  481. {
  482. TextLayoutHelpers::TokenList l;
  483. l.createLayout (text, *this);
  484. }
  485. void TextLayout::recalculateWidth (const AttributedString& text)
  486. {
  487. if (lines.size() > 0 && text.getReadingDirection() != AttributedString::rightToLeft)
  488. {
  489. Range<float> range (lines.getFirst()->getLineBoundsX());
  490. for (int i = lines.size(); --i > 0;)
  491. range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
  492. for (int i = lines.size(); --i >= 0;)
  493. lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
  494. width = range.getLength();
  495. }
  496. }