juce_TextLayout.cpp 19 KB

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