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.

2495 lines
72KB

  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. // a word or space that can't be broken down any further
  22. struct TextAtom
  23. {
  24. //==============================================================================
  25. String atomText;
  26. float width;
  27. int numChars;
  28. //==============================================================================
  29. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (atomText[0]); }
  30. bool isNewLine() const noexcept { return atomText[0] == '\r' || atomText[0] == '\n'; }
  31. String getText (juce_wchar passwordCharacter) const
  32. {
  33. if (passwordCharacter == 0)
  34. return atomText;
  35. return String::repeatedString (String::charToString (passwordCharacter),
  36. atomText.length());
  37. }
  38. String getTrimmedText (const juce_wchar passwordCharacter) const
  39. {
  40. if (passwordCharacter == 0)
  41. return atomText.substring (0, numChars);
  42. if (isNewLine())
  43. return {};
  44. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  45. }
  46. JUCE_LEAK_DETECTOR (TextAtom)
  47. };
  48. //==============================================================================
  49. // a run of text with a single font and colour
  50. class TextEditor::UniformTextSection
  51. {
  52. public:
  53. UniformTextSection (const String& text, const Font& f, Colour col, juce_wchar passwordChar)
  54. : font (f), colour (col)
  55. {
  56. initialiseAtoms (text, passwordChar);
  57. }
  58. UniformTextSection (const UniformTextSection&) = default;
  59. UniformTextSection (UniformTextSection&&) = default;
  60. UniformTextSection& operator= (const UniformTextSection&) = delete;
  61. void append (UniformTextSection& other, const juce_wchar passwordChar)
  62. {
  63. if (! other.atoms.isEmpty())
  64. {
  65. int i = 0;
  66. if (! atoms.isEmpty())
  67. {
  68. auto& lastAtom = atoms.getReference (atoms.size() - 1);
  69. if (! CharacterFunctions::isWhitespace (lastAtom.atomText.getLastCharacter()))
  70. {
  71. auto& first = other.atoms.getReference(0);
  72. if (! CharacterFunctions::isWhitespace (first.atomText[0]))
  73. {
  74. lastAtom.atomText += first.atomText;
  75. lastAtom.numChars = (uint16) (lastAtom.numChars + first.numChars);
  76. lastAtom.width = font.getStringWidthFloat (lastAtom.getText (passwordChar));
  77. ++i;
  78. }
  79. }
  80. }
  81. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  82. while (i < other.atoms.size())
  83. {
  84. atoms.add (other.atoms.getReference(i));
  85. ++i;
  86. }
  87. }
  88. }
  89. UniformTextSection* split (int indexToBreakAt, juce_wchar passwordChar)
  90. {
  91. auto* section2 = new UniformTextSection (String(), font, colour, passwordChar);
  92. int index = 0;
  93. for (int i = 0; i < atoms.size(); ++i)
  94. {
  95. auto& atom = atoms.getReference(i);
  96. auto nextIndex = index + atom.numChars;
  97. if (index == indexToBreakAt)
  98. {
  99. for (int j = i; j < atoms.size(); ++j)
  100. section2->atoms.add (atoms.getUnchecked (j));
  101. atoms.removeRange (i, atoms.size());
  102. break;
  103. }
  104. if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  105. {
  106. TextAtom secondAtom;
  107. secondAtom.atomText = atom.atomText.substring (indexToBreakAt - index);
  108. secondAtom.width = font.getStringWidthFloat (secondAtom.getText (passwordChar));
  109. secondAtom.numChars = (uint16) secondAtom.atomText.length();
  110. section2->atoms.add (secondAtom);
  111. atom.atomText = atom.atomText.substring (0, indexToBreakAt - index);
  112. atom.width = font.getStringWidthFloat (atom.getText (passwordChar));
  113. atom.numChars = (uint16) (indexToBreakAt - index);
  114. for (int j = i + 1; j < atoms.size(); ++j)
  115. section2->atoms.add (atoms.getUnchecked (j));
  116. atoms.removeRange (i + 1, atoms.size());
  117. break;
  118. }
  119. index = nextIndex;
  120. }
  121. return section2;
  122. }
  123. void appendAllText (MemoryOutputStream& mo) const
  124. {
  125. for (auto& atom : atoms)
  126. mo << atom.atomText;
  127. }
  128. void appendSubstring (MemoryOutputStream& mo, Range<int> range) const
  129. {
  130. int index = 0;
  131. for (auto& atom : atoms)
  132. {
  133. auto nextIndex = index + atom.numChars;
  134. if (range.getStart() < nextIndex)
  135. {
  136. if (range.getEnd() <= index)
  137. break;
  138. auto r = (range - index).getIntersectionWith ({ 0, (int) atom.numChars });
  139. if (! r.isEmpty())
  140. mo << atom.atomText.substring (r.getStart(), r.getEnd());
  141. }
  142. index = nextIndex;
  143. }
  144. }
  145. int getTotalLength() const noexcept
  146. {
  147. int total = 0;
  148. for (auto& atom : atoms)
  149. total += atom.numChars;
  150. return total;
  151. }
  152. void setFont (const Font& newFont, const juce_wchar passwordChar)
  153. {
  154. if (font != newFont)
  155. {
  156. font = newFont;
  157. for (auto& atom : atoms)
  158. atom.width = newFont.getStringWidthFloat (atom.getText (passwordChar));
  159. }
  160. }
  161. //==============================================================================
  162. Font font;
  163. Colour colour;
  164. Array<TextAtom> atoms;
  165. private:
  166. void initialiseAtoms (const String& textToParse, const juce_wchar passwordChar)
  167. {
  168. auto text = textToParse.getCharPointer();
  169. while (! text.isEmpty())
  170. {
  171. size_t numChars = 0;
  172. auto start = text;
  173. // create a whitespace atom unless it starts with non-ws
  174. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  175. {
  176. do
  177. {
  178. ++text;
  179. ++numChars;
  180. }
  181. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  182. }
  183. else
  184. {
  185. if (*text == '\r')
  186. {
  187. ++text;
  188. ++numChars;
  189. if (*text == '\n')
  190. {
  191. ++start;
  192. ++text;
  193. }
  194. }
  195. else if (*text == '\n')
  196. {
  197. ++text;
  198. ++numChars;
  199. }
  200. else
  201. {
  202. while (! (text.isEmpty() || text.isWhitespace()))
  203. {
  204. ++text;
  205. ++numChars;
  206. }
  207. }
  208. }
  209. TextAtom atom;
  210. atom.atomText = String (start, numChars);
  211. atom.width = font.getStringWidthFloat (atom.getText (passwordChar));
  212. atom.numChars = (uint16) numChars;
  213. atoms.add (atom);
  214. }
  215. }
  216. JUCE_LEAK_DETECTOR (UniformTextSection)
  217. };
  218. //==============================================================================
  219. struct TextEditor::Iterator
  220. {
  221. Iterator (const TextEditor& ed)
  222. : sections (ed.sections),
  223. justification (ed.justification),
  224. justificationWidth (ed.getJustificationWidth()),
  225. wordWrapWidth (ed.getWordWrapWidth()),
  226. passwordCharacter (ed.passwordCharacter),
  227. lineSpacing (ed.lineSpacing)
  228. {
  229. jassert (wordWrapWidth > 0);
  230. if (! sections.isEmpty())
  231. {
  232. currentSection = sections.getUnchecked (sectionIndex);
  233. if (currentSection != nullptr)
  234. beginNewLine();
  235. }
  236. }
  237. Iterator (const Iterator&) = default;
  238. Iterator& operator= (const Iterator&) = delete;
  239. //==============================================================================
  240. bool next()
  241. {
  242. if (atom == &tempAtom)
  243. {
  244. auto numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  245. if (numRemaining > 0)
  246. {
  247. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  248. if (tempAtom.numChars > 0)
  249. lineY += lineHeight * lineSpacing;
  250. indexInText += tempAtom.numChars;
  251. GlyphArrangement g;
  252. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  253. int split;
  254. for (split = 0; split < g.getNumGlyphs(); ++split)
  255. if (shouldWrap (g.getGlyph (split).getRight()))
  256. break;
  257. if (split > 0 && split <= numRemaining)
  258. {
  259. tempAtom.numChars = (uint16) split;
  260. tempAtom.width = g.getGlyph (split - 1).getRight();
  261. atomX = getJustificationOffset (tempAtom.width);
  262. atomRight = atomX + tempAtom.width;
  263. return true;
  264. }
  265. }
  266. }
  267. if (sectionIndex >= sections.size())
  268. {
  269. moveToEndOfLastAtom();
  270. return false;
  271. }
  272. bool forceNewLine = false;
  273. if (atomIndex >= currentSection->atoms.size() - 1)
  274. {
  275. if (atomIndex >= currentSection->atoms.size())
  276. {
  277. if (++sectionIndex >= sections.size())
  278. {
  279. moveToEndOfLastAtom();
  280. return false;
  281. }
  282. atomIndex = 0;
  283. currentSection = sections.getUnchecked (sectionIndex);
  284. }
  285. else
  286. {
  287. auto& lastAtom = currentSection->atoms.getReference (atomIndex);
  288. if (! lastAtom.isWhitespace())
  289. {
  290. // handle the case where the last atom in a section is actually part of the same
  291. // word as the first atom of the next section...
  292. float right = atomRight + lastAtom.width;
  293. float lineHeight2 = lineHeight;
  294. float maxDescent2 = maxDescent;
  295. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  296. {
  297. auto* s = sections.getUnchecked (section);
  298. if (s->atoms.size() == 0)
  299. break;
  300. auto& nextAtom = s->atoms.getReference (0);
  301. if (nextAtom.isWhitespace())
  302. break;
  303. right += nextAtom.width;
  304. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  305. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  306. if (shouldWrap (right))
  307. {
  308. lineHeight = lineHeight2;
  309. maxDescent = maxDescent2;
  310. forceNewLine = true;
  311. break;
  312. }
  313. if (s->atoms.size() > 1)
  314. break;
  315. }
  316. }
  317. }
  318. }
  319. if (atom != nullptr)
  320. {
  321. atomX = atomRight;
  322. indexInText += atom->numChars;
  323. if (atom->isNewLine())
  324. beginNewLine();
  325. }
  326. atom = &(currentSection->atoms.getReference (atomIndex));
  327. atomRight = atomX + atom->width;
  328. ++atomIndex;
  329. if (shouldWrap (atomRight) || forceNewLine)
  330. {
  331. if (atom->isWhitespace())
  332. {
  333. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  334. atomRight = jmin (atomRight, wordWrapWidth);
  335. }
  336. else
  337. {
  338. if (shouldWrap (atom->width)) // atom too big to fit on a line, so break it up..
  339. {
  340. tempAtom = *atom;
  341. tempAtom.width = 0;
  342. tempAtom.numChars = 0;
  343. atom = &tempAtom;
  344. if (atomX > justificationOffset)
  345. beginNewLine();
  346. return next();
  347. }
  348. beginNewLine();
  349. atomX = justificationOffset;
  350. atomRight = atomX + atom->width;
  351. return true;
  352. }
  353. }
  354. return true;
  355. }
  356. void beginNewLine()
  357. {
  358. lineY += lineHeight * lineSpacing;
  359. float lineWidth = 0;
  360. auto tempSectionIndex = sectionIndex;
  361. auto tempAtomIndex = atomIndex;
  362. auto* section = sections.getUnchecked (tempSectionIndex);
  363. lineHeight = section->font.getHeight();
  364. maxDescent = section->font.getDescent();
  365. float nextLineWidth = (atom != nullptr) ? atom->width : 0.0f;
  366. while (! shouldWrap (nextLineWidth))
  367. {
  368. lineWidth = nextLineWidth;
  369. if (tempSectionIndex >= sections.size())
  370. break;
  371. bool checkSize = false;
  372. if (tempAtomIndex >= section->atoms.size())
  373. {
  374. if (++tempSectionIndex >= sections.size())
  375. break;
  376. tempAtomIndex = 0;
  377. section = sections.getUnchecked (tempSectionIndex);
  378. checkSize = true;
  379. }
  380. if (! isPositiveAndBelow (tempAtomIndex, section->atoms.size()))
  381. break;
  382. auto& nextAtom = section->atoms.getReference (tempAtomIndex);
  383. nextLineWidth += nextAtom.width;
  384. if (shouldWrap (nextLineWidth) || nextAtom.isNewLine())
  385. break;
  386. if (checkSize)
  387. {
  388. lineHeight = jmax (lineHeight, section->font.getHeight());
  389. maxDescent = jmax (maxDescent, section->font.getDescent());
  390. }
  391. ++tempAtomIndex;
  392. }
  393. justificationOffset = getJustificationOffset (lineWidth);
  394. atomX = justificationOffset;
  395. }
  396. float getJustificationOffset (float lineWidth) const
  397. {
  398. if (justification.getOnlyHorizontalFlags() == Justification::horizontallyCentred)
  399. return jmax (0.0f, (justificationWidth - lineWidth) * 0.5f);
  400. if (justification.getOnlyHorizontalFlags() == Justification::right)
  401. return jmax (0.0f, justificationWidth - lineWidth);
  402. return 0;
  403. }
  404. //==============================================================================
  405. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  406. {
  407. if (passwordCharacter != 0 || ! atom->isWhitespace())
  408. {
  409. if (lastSection != currentSection)
  410. {
  411. lastSection = currentSection;
  412. g.setColour (currentSection->colour);
  413. g.setFont (currentSection->font);
  414. }
  415. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  416. GlyphArrangement ga;
  417. ga.addLineOfText (currentSection->font,
  418. atom->getTrimmedText (passwordCharacter),
  419. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  420. ga.draw (g);
  421. }
  422. }
  423. void addSelection (RectangleList<float>& area, Range<int> selected) const
  424. {
  425. auto startX = indexToX (selected.getStart());
  426. auto endX = indexToX (selected.getEnd());
  427. area.add (startX, lineY, endX - startX, lineHeight * lineSpacing);
  428. }
  429. void drawUnderline (Graphics& g, Range<int> underline, Colour colour) const
  430. {
  431. auto startX = roundToInt (indexToX (underline.getStart()));
  432. auto endX = roundToInt (indexToX (underline.getEnd()));
  433. auto baselineY = roundToInt (lineY + currentSection->font.getAscent() + 0.5f);
  434. Graphics::ScopedSaveState state (g);
  435. g.reduceClipRegion ({ startX, baselineY, endX - startX, 1 });
  436. g.fillCheckerBoard ({ endX, baselineY + 1 }, 3, 1, colour, Colours::transparentBlack);
  437. }
  438. void drawSelectedText (Graphics& g, Range<int> selected, Colour selectedTextColour) const
  439. {
  440. if (passwordCharacter != 0 || ! atom->isWhitespace())
  441. {
  442. GlyphArrangement ga;
  443. ga.addLineOfText (currentSection->font,
  444. atom->getTrimmedText (passwordCharacter),
  445. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  446. if (selected.getEnd() < indexInText + atom->numChars)
  447. {
  448. GlyphArrangement ga2 (ga);
  449. ga2.removeRangeOfGlyphs (0, selected.getEnd() - indexInText);
  450. ga.removeRangeOfGlyphs (selected.getEnd() - indexInText, -1);
  451. g.setColour (currentSection->colour);
  452. ga2.draw (g);
  453. }
  454. if (selected.getStart() > indexInText)
  455. {
  456. GlyphArrangement ga2 (ga);
  457. ga2.removeRangeOfGlyphs (selected.getStart() - indexInText, -1);
  458. ga.removeRangeOfGlyphs (0, selected.getStart() - indexInText);
  459. g.setColour (currentSection->colour);
  460. ga2.draw (g);
  461. }
  462. g.setColour (selectedTextColour);
  463. ga.draw (g);
  464. }
  465. }
  466. //==============================================================================
  467. float indexToX (int indexToFind) const
  468. {
  469. if (indexToFind <= indexInText)
  470. return atomX;
  471. if (indexToFind >= indexInText + atom->numChars)
  472. return atomRight;
  473. GlyphArrangement g;
  474. g.addLineOfText (currentSection->font,
  475. atom->getText (passwordCharacter),
  476. atomX, 0.0f);
  477. if (indexToFind - indexInText >= g.getNumGlyphs())
  478. return atomRight;
  479. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  480. }
  481. int xToIndex (float xToFind) const
  482. {
  483. if (xToFind <= atomX || atom->isNewLine())
  484. return indexInText;
  485. if (xToFind >= atomRight)
  486. return indexInText + atom->numChars;
  487. GlyphArrangement g;
  488. g.addLineOfText (currentSection->font,
  489. atom->getText (passwordCharacter),
  490. atomX, 0.0f);
  491. auto numGlyphs = g.getNumGlyphs();
  492. int j;
  493. for (j = 0; j < numGlyphs; ++j)
  494. {
  495. auto& pg = g.getGlyph(j);
  496. if ((pg.getLeft() + pg.getRight()) / 2 > xToFind)
  497. break;
  498. }
  499. return indexInText + j;
  500. }
  501. //==============================================================================
  502. bool getCharPosition (int index, Point<float>& anchor, float& lineHeightFound)
  503. {
  504. while (next())
  505. {
  506. if (indexInText + atom->numChars > index)
  507. {
  508. anchor = { indexToX (index), lineY };
  509. lineHeightFound = lineHeight;
  510. return true;
  511. }
  512. }
  513. anchor = { atomX, lineY };
  514. lineHeightFound = lineHeight;
  515. return false;
  516. }
  517. //==============================================================================
  518. int indexInText = 0;
  519. float lineY = 0, justificationOffset = 0, lineHeight = 0, maxDescent = 0;
  520. float atomX = 0, atomRight = 0;
  521. const TextAtom* atom = nullptr;
  522. const UniformTextSection* currentSection = nullptr;
  523. private:
  524. const OwnedArray<UniformTextSection>& sections;
  525. int sectionIndex = 0, atomIndex = 0;
  526. Justification justification;
  527. const float justificationWidth, wordWrapWidth;
  528. const juce_wchar passwordCharacter;
  529. const float lineSpacing;
  530. TextAtom tempAtom;
  531. void moveToEndOfLastAtom()
  532. {
  533. if (atom != nullptr)
  534. {
  535. atomX = atomRight;
  536. if (atom->isNewLine())
  537. {
  538. atomX = 0.0f;
  539. lineY += lineHeight * lineSpacing;
  540. }
  541. }
  542. }
  543. bool shouldWrap (const float x) const noexcept
  544. {
  545. return (x - 0.0001f) >= wordWrapWidth;
  546. }
  547. JUCE_LEAK_DETECTOR (Iterator)
  548. };
  549. //==============================================================================
  550. struct TextEditor::InsertAction : public UndoableAction
  551. {
  552. InsertAction (TextEditor& ed, const String& newText, int insertPos,
  553. const Font& newFont, Colour newColour, int oldCaret, int newCaret)
  554. : owner (ed),
  555. text (newText),
  556. insertIndex (insertPos),
  557. oldCaretPos (oldCaret),
  558. newCaretPos (newCaret),
  559. font (newFont),
  560. colour (newColour)
  561. {
  562. }
  563. bool perform() override
  564. {
  565. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  566. return true;
  567. }
  568. bool undo() override
  569. {
  570. owner.remove ({ insertIndex, insertIndex + text.length() }, 0, oldCaretPos);
  571. return true;
  572. }
  573. int getSizeInUnits() override
  574. {
  575. return text.length() + 16;
  576. }
  577. private:
  578. TextEditor& owner;
  579. const String text;
  580. const int insertIndex, oldCaretPos, newCaretPos;
  581. const Font font;
  582. const Colour colour;
  583. JUCE_DECLARE_NON_COPYABLE (InsertAction)
  584. };
  585. //==============================================================================
  586. struct TextEditor::RemoveAction : public UndoableAction
  587. {
  588. RemoveAction (TextEditor& ed, Range<int> rangeToRemove, int oldCaret, int newCaret,
  589. const Array<UniformTextSection*>& oldSections)
  590. : owner (ed),
  591. range (rangeToRemove),
  592. oldCaretPos (oldCaret),
  593. newCaretPos (newCaret)
  594. {
  595. removedSections.addArray (oldSections);
  596. }
  597. bool perform() override
  598. {
  599. owner.remove (range, 0, newCaretPos);
  600. return true;
  601. }
  602. bool undo() override
  603. {
  604. owner.reinsert (range.getStart(), removedSections);
  605. owner.moveCaretTo (oldCaretPos, false);
  606. return true;
  607. }
  608. int getSizeInUnits() override
  609. {
  610. int n = 16;
  611. for (auto* s : removedSections)
  612. n += s->getTotalLength();
  613. return n;
  614. }
  615. private:
  616. TextEditor& owner;
  617. const Range<int> range;
  618. const int oldCaretPos, newCaretPos;
  619. OwnedArray<UniformTextSection> removedSections;
  620. JUCE_DECLARE_NON_COPYABLE (RemoveAction)
  621. };
  622. //==============================================================================
  623. struct TextEditor::TextHolderComponent : public Component,
  624. public Timer,
  625. public Value::Listener
  626. {
  627. TextHolderComponent (TextEditor& ed) : owner (ed)
  628. {
  629. setWantsKeyboardFocus (false);
  630. setInterceptsMouseClicks (false, true);
  631. setMouseCursor (MouseCursor::ParentCursor);
  632. owner.getTextValue().addListener (this);
  633. }
  634. ~TextHolderComponent()
  635. {
  636. owner.getTextValue().removeListener (this);
  637. }
  638. void paint (Graphics& g) override
  639. {
  640. owner.drawContent (g);
  641. }
  642. void restartTimer()
  643. {
  644. startTimer (350);
  645. }
  646. void timerCallback() override
  647. {
  648. owner.timerCallbackInt();
  649. }
  650. void valueChanged (Value&) override
  651. {
  652. owner.textWasChangedByValue();
  653. }
  654. TextEditor& owner;
  655. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent)
  656. };
  657. //==============================================================================
  658. struct TextEditor::TextEditorViewport : public Viewport
  659. {
  660. TextEditorViewport (TextEditor& ed) : owner (ed) {}
  661. void visibleAreaChanged (const Rectangle<int>&) override
  662. {
  663. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  664. // appear and disappear, causing the wrap width to change.
  665. {
  666. auto wordWrapWidth = owner.getWordWrapWidth();
  667. if (wordWrapWidth != lastWordWrapWidth)
  668. {
  669. lastWordWrapWidth = wordWrapWidth;
  670. rentrant = true;
  671. owner.updateTextHolderSize();
  672. rentrant = false;
  673. }
  674. }
  675. }
  676. private:
  677. TextEditor& owner;
  678. float lastWordWrapWidth = 0;
  679. bool rentrant = false;
  680. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport)
  681. };
  682. //==============================================================================
  683. namespace TextEditorDefs
  684. {
  685. const int textChangeMessageId = 0x10003001;
  686. const int returnKeyMessageId = 0x10003002;
  687. const int escapeKeyMessageId = 0x10003003;
  688. const int focusLossMessageId = 0x10003004;
  689. const int maxActionsPerTransaction = 100;
  690. static int getCharacterCategory (juce_wchar character) noexcept
  691. {
  692. return CharacterFunctions::isLetterOrDigit (character)
  693. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  694. }
  695. }
  696. //==============================================================================
  697. TextEditor::TextEditor (const String& name, juce_wchar passwordChar)
  698. : Component (name),
  699. passwordCharacter (passwordChar)
  700. {
  701. setMouseCursor (MouseCursor::IBeamCursor);
  702. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  703. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  704. viewport->setWantsKeyboardFocus (false);
  705. viewport->setScrollBarsShown (false, false);
  706. setWantsKeyboardFocus (true);
  707. recreateCaret();
  708. }
  709. TextEditor::~TextEditor()
  710. {
  711. if (wasFocused)
  712. if (auto* peer = getPeer())
  713. peer->dismissPendingTextInput();
  714. textValue.removeListener (textHolder);
  715. textValue.referTo (Value());
  716. viewport = nullptr;
  717. textHolder = nullptr;
  718. }
  719. //==============================================================================
  720. void TextEditor::newTransaction()
  721. {
  722. lastTransactionTime = Time::getApproximateMillisecondCounter();
  723. undoManager.beginNewTransaction();
  724. }
  725. bool TextEditor::undoOrRedo (const bool shouldUndo)
  726. {
  727. if (! isReadOnly())
  728. {
  729. newTransaction();
  730. if (shouldUndo ? undoManager.undo()
  731. : undoManager.redo())
  732. {
  733. scrollToMakeSureCursorIsVisible();
  734. repaint();
  735. textChanged();
  736. return true;
  737. }
  738. }
  739. return false;
  740. }
  741. bool TextEditor::undo() { return undoOrRedo (true); }
  742. bool TextEditor::redo() { return undoOrRedo (false); }
  743. //==============================================================================
  744. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  745. const bool shouldWordWrap)
  746. {
  747. if (multiline != shouldBeMultiLine
  748. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  749. {
  750. multiline = shouldBeMultiLine;
  751. wordWrap = shouldWordWrap && shouldBeMultiLine;
  752. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  753. scrollbarVisible && multiline);
  754. viewport->setViewPosition (0, 0);
  755. resized();
  756. scrollToMakeSureCursorIsVisible();
  757. }
  758. }
  759. bool TextEditor::isMultiLine() const
  760. {
  761. return multiline;
  762. }
  763. void TextEditor::setScrollbarsShown (bool shown)
  764. {
  765. if (scrollbarVisible != shown)
  766. {
  767. scrollbarVisible = shown;
  768. shown = shown && isMultiLine();
  769. viewport->setScrollBarsShown (shown, shown);
  770. }
  771. }
  772. void TextEditor::setReadOnly (bool shouldBeReadOnly)
  773. {
  774. if (readOnly != shouldBeReadOnly)
  775. {
  776. readOnly = shouldBeReadOnly;
  777. enablementChanged();
  778. }
  779. }
  780. bool TextEditor::isReadOnly() const noexcept
  781. {
  782. return readOnly || ! isEnabled();
  783. }
  784. bool TextEditor::isTextInputActive() const
  785. {
  786. return ! isReadOnly();
  787. }
  788. void TextEditor::setReturnKeyStartsNewLine (bool shouldStartNewLine)
  789. {
  790. returnKeyStartsNewLine = shouldStartNewLine;
  791. }
  792. void TextEditor::setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed)
  793. {
  794. tabKeyUsed = shouldTabKeyBeUsed;
  795. }
  796. void TextEditor::setPopupMenuEnabled (bool b)
  797. {
  798. popupMenuEnabled = b;
  799. }
  800. void TextEditor::setSelectAllWhenFocused (bool b)
  801. {
  802. selectAllTextWhenFocused = b;
  803. }
  804. void TextEditor::setJustification (Justification j)
  805. {
  806. if (justification != j)
  807. {
  808. justification = j;
  809. resized();
  810. }
  811. }
  812. //==============================================================================
  813. void TextEditor::setFont (const Font& newFont)
  814. {
  815. currentFont = newFont;
  816. scrollToMakeSureCursorIsVisible();
  817. }
  818. void TextEditor::applyFontToAllText (const Font& newFont, bool changeCurrentFont)
  819. {
  820. if (changeCurrentFont)
  821. currentFont = newFont;
  822. auto overallColour = findColour (textColourId);
  823. for (auto* uts : sections)
  824. {
  825. uts->setFont (newFont, passwordCharacter);
  826. uts->colour = overallColour;
  827. }
  828. coalesceSimilarSections();
  829. updateTextHolderSize();
  830. scrollToMakeSureCursorIsVisible();
  831. repaint();
  832. }
  833. void TextEditor::applyColourToAllText (const Colour& newColour, bool changeCurrentTextColour)
  834. {
  835. for (auto* uts : sections)
  836. uts->colour = newColour;
  837. if (changeCurrentTextColour)
  838. setColour (TextEditor::textColourId, newColour);
  839. else
  840. repaint();
  841. }
  842. void TextEditor::lookAndFeelChanged()
  843. {
  844. caret = nullptr;
  845. recreateCaret();
  846. repaint();
  847. }
  848. void TextEditor::parentHierarchyChanged()
  849. {
  850. lookAndFeelChanged();
  851. }
  852. void TextEditor::enablementChanged()
  853. {
  854. recreateCaret();
  855. repaint();
  856. }
  857. void TextEditor::setCaretVisible (bool shouldCaretBeVisible)
  858. {
  859. if (caretVisible != shouldCaretBeVisible)
  860. {
  861. caretVisible = shouldCaretBeVisible;
  862. recreateCaret();
  863. }
  864. }
  865. void TextEditor::recreateCaret()
  866. {
  867. if (isCaretVisible())
  868. {
  869. if (caret == nullptr)
  870. {
  871. textHolder->addChildComponent (caret = getLookAndFeel().createCaretComponent (this));
  872. updateCaretPosition();
  873. }
  874. }
  875. else
  876. {
  877. caret = nullptr;
  878. }
  879. }
  880. void TextEditor::updateCaretPosition()
  881. {
  882. if (caret != nullptr)
  883. caret->setCaretPosition (getCaretRectangle().translated (leftIndent, topIndent));
  884. }
  885. TextEditor::LengthAndCharacterRestriction::LengthAndCharacterRestriction (int maxLen, const String& chars)
  886. : allowedCharacters (chars), maxLength (maxLen)
  887. {
  888. }
  889. String TextEditor::LengthAndCharacterRestriction::filterNewText (TextEditor& ed, const String& newInput)
  890. {
  891. String t (newInput);
  892. if (allowedCharacters.isNotEmpty())
  893. t = t.retainCharacters (allowedCharacters);
  894. if (maxLength > 0)
  895. t = t.substring (0, maxLength - (ed.getTotalNumChars() - ed.getHighlightedRegion().getLength()));
  896. return t;
  897. }
  898. void TextEditor::setInputFilter (InputFilter* newFilter, bool takeOwnership)
  899. {
  900. inputFilter.set (newFilter, takeOwnership);
  901. }
  902. void TextEditor::setInputRestrictions (int maxLen, const String& chars)
  903. {
  904. setInputFilter (new LengthAndCharacterRestriction (maxLen, chars), true);
  905. }
  906. void TextEditor::setTextToShowWhenEmpty (const String& text, Colour colourToUse)
  907. {
  908. textToShowWhenEmpty = text;
  909. colourForTextWhenEmpty = colourToUse;
  910. }
  911. void TextEditor::setPasswordCharacter (juce_wchar newPasswordCharacter)
  912. {
  913. if (passwordCharacter != newPasswordCharacter)
  914. {
  915. passwordCharacter = newPasswordCharacter;
  916. applyFontToAllText (currentFont);
  917. }
  918. }
  919. void TextEditor::setScrollBarThickness (int newThicknessPixels)
  920. {
  921. viewport->setScrollBarThickness (newThicknessPixels);
  922. }
  923. //==============================================================================
  924. void TextEditor::clear()
  925. {
  926. clearInternal (nullptr);
  927. updateTextHolderSize();
  928. undoManager.clearUndoHistory();
  929. }
  930. void TextEditor::setText (const String& newText, bool sendTextChangeMessage)
  931. {
  932. auto newLength = newText.length();
  933. if (newLength != getTotalNumChars() || getText() != newText)
  934. {
  935. if (! sendTextChangeMessage)
  936. textValue.removeListener (textHolder);
  937. textValue = newText;
  938. auto oldCursorPos = caretPosition;
  939. bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  940. clearInternal (nullptr);
  941. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  942. // if you're adding text with line-feeds to a single-line text editor, it
  943. // ain't gonna look right!
  944. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  945. if (cursorWasAtEnd && ! isMultiLine())
  946. oldCursorPos = getTotalNumChars();
  947. moveCaretTo (oldCursorPos, false);
  948. if (sendTextChangeMessage)
  949. textChanged();
  950. else
  951. textValue.addListener (textHolder);
  952. updateTextHolderSize();
  953. scrollToMakeSureCursorIsVisible();
  954. undoManager.clearUndoHistory();
  955. repaint();
  956. }
  957. }
  958. //==============================================================================
  959. void TextEditor::updateValueFromText()
  960. {
  961. if (valueTextNeedsUpdating)
  962. {
  963. valueTextNeedsUpdating = false;
  964. textValue = getText();
  965. }
  966. }
  967. Value& TextEditor::getTextValue()
  968. {
  969. updateValueFromText();
  970. return textValue;
  971. }
  972. void TextEditor::textWasChangedByValue()
  973. {
  974. if (textValue.getValueSource().getReferenceCount() > 1)
  975. setText (textValue.getValue());
  976. }
  977. //==============================================================================
  978. void TextEditor::textChanged()
  979. {
  980. updateTextHolderSize();
  981. if (listeners.size() > 0)
  982. postCommandMessage (TextEditorDefs::textChangeMessageId);
  983. if (textValue.getValueSource().getReferenceCount() > 1)
  984. {
  985. valueTextNeedsUpdating = false;
  986. textValue = getText();
  987. }
  988. }
  989. void TextEditor::returnPressed() { postCommandMessage (TextEditorDefs::returnKeyMessageId); }
  990. void TextEditor::escapePressed() { postCommandMessage (TextEditorDefs::escapeKeyMessageId); }
  991. void TextEditor::addListener (Listener* l) { listeners.add (l); }
  992. void TextEditor::removeListener (Listener* l) { listeners.remove (l); }
  993. //==============================================================================
  994. void TextEditor::timerCallbackInt()
  995. {
  996. if (hasKeyboardFocus (false) && ! isCurrentlyBlockedByAnotherModalComponent())
  997. wasFocused = true;
  998. auto now = Time::getApproximateMillisecondCounter();
  999. if (now > lastTransactionTime + 200)
  1000. newTransaction();
  1001. }
  1002. void TextEditor::repaintText (Range<int> range)
  1003. {
  1004. if (! range.isEmpty())
  1005. {
  1006. auto lh = currentFont.getHeight();
  1007. auto wordWrapWidth = getWordWrapWidth();
  1008. if (wordWrapWidth > 0)
  1009. {
  1010. Point<float> anchor;
  1011. Iterator i (*this);
  1012. i.getCharPosition (range.getStart(), anchor, lh);
  1013. auto y1 = (int) anchor.y;
  1014. int y2;
  1015. if (range.getEnd() >= getTotalNumChars())
  1016. {
  1017. y2 = textHolder->getHeight();
  1018. }
  1019. else
  1020. {
  1021. i.getCharPosition (range.getEnd(), anchor, lh);
  1022. y2 = (int) (anchor.y + lh * 2.0f);
  1023. }
  1024. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  1025. }
  1026. }
  1027. }
  1028. //==============================================================================
  1029. void TextEditor::moveCaret (int newCaretPos)
  1030. {
  1031. if (newCaretPos < 0)
  1032. newCaretPos = 0;
  1033. else
  1034. newCaretPos = jmin (newCaretPos, getTotalNumChars());
  1035. if (newCaretPos != getCaretPosition())
  1036. {
  1037. caretPosition = newCaretPos;
  1038. textHolder->restartTimer();
  1039. scrollToMakeSureCursorIsVisible();
  1040. updateCaretPosition();
  1041. }
  1042. }
  1043. int TextEditor::getCaretPosition() const
  1044. {
  1045. return caretPosition;
  1046. }
  1047. void TextEditor::setCaretPosition (const int newIndex)
  1048. {
  1049. moveCaretTo (newIndex, false);
  1050. }
  1051. void TextEditor::moveCaretToEnd()
  1052. {
  1053. setCaretPosition (std::numeric_limits<int>::max());
  1054. }
  1055. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  1056. const int desiredCaretY)
  1057. {
  1058. updateCaretPosition();
  1059. auto caretPos = getCaretRectangle();
  1060. auto vx = caretPos.getX() - desiredCaretX;
  1061. auto vy = caretPos.getY() - desiredCaretY;
  1062. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  1063. vx += desiredCaretX - proportionOfWidth (0.2f);
  1064. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1065. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1066. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  1067. if (! isMultiLine())
  1068. {
  1069. vy = viewport->getViewPositionY();
  1070. }
  1071. else
  1072. {
  1073. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  1074. if (desiredCaretY < 0)
  1075. vy = jmax (0, desiredCaretY + vy);
  1076. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - caretPos.getHeight()))
  1077. vy += desiredCaretY + 2 + caretPos.getHeight() + topIndent - viewport->getMaximumVisibleHeight();
  1078. }
  1079. viewport->setViewPosition (vx, vy);
  1080. }
  1081. Rectangle<int> TextEditor::getCaretRectangle()
  1082. {
  1083. Point<float> anchor;
  1084. auto cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  1085. getCharPosition (caretPosition, anchor, cursorHeight);
  1086. return { roundToInt (anchor.x), roundToInt (anchor.y), 2, roundToInt (cursorHeight) };
  1087. }
  1088. //==============================================================================
  1089. enum { rightEdgeSpace = 2 };
  1090. float TextEditor::getWordWrapWidth() const
  1091. {
  1092. return wordWrap ? getJustificationWidth()
  1093. : std::numeric_limits<float>::max();
  1094. }
  1095. float TextEditor::getJustificationWidth() const
  1096. {
  1097. return (float) (viewport->getMaximumVisibleWidth() - (leftIndent + rightEdgeSpace + 1));
  1098. }
  1099. void TextEditor::updateTextHolderSize()
  1100. {
  1101. if (getWordWrapWidth() > 0)
  1102. {
  1103. float maxWidth = getJustificationWidth();
  1104. Iterator i (*this);
  1105. while (i.next())
  1106. maxWidth = jmax (maxWidth, i.atomRight);
  1107. auto w = leftIndent + roundToInt (maxWidth);
  1108. auto h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight, currentFont.getHeight()));
  1109. textHolder->setSize (w + rightEdgeSpace, h + 1); // (allows a bit of space for the cursor to be at the right-hand-edge)
  1110. }
  1111. }
  1112. int TextEditor::getTextWidth() const { return textHolder->getWidth(); }
  1113. int TextEditor::getTextHeight() const { return textHolder->getHeight(); }
  1114. void TextEditor::setIndents (int newLeftIndent, int newTopIndent)
  1115. {
  1116. leftIndent = newLeftIndent;
  1117. topIndent = newTopIndent;
  1118. }
  1119. void TextEditor::setBorder (const BorderSize<int>& border)
  1120. {
  1121. borderSize = border;
  1122. resized();
  1123. }
  1124. BorderSize<int> TextEditor::getBorder() const
  1125. {
  1126. return borderSize;
  1127. }
  1128. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  1129. {
  1130. keepCaretOnScreen = shouldScrollToShowCursor;
  1131. }
  1132. void TextEditor::scrollToMakeSureCursorIsVisible()
  1133. {
  1134. updateCaretPosition();
  1135. if (keepCaretOnScreen)
  1136. {
  1137. auto viewPos = viewport->getViewPosition();
  1138. auto caretRect = getCaretRectangle();
  1139. auto relativeCursor = caretRect.getPosition() - viewPos;
  1140. if (relativeCursor.x < jmax (1, proportionOfWidth (0.05f)))
  1141. {
  1142. viewPos.x += relativeCursor.x - proportionOfWidth (0.2f);
  1143. }
  1144. else if (relativeCursor.x > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1145. {
  1146. viewPos.x += relativeCursor.x + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1147. }
  1148. viewPos.x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), viewPos.x);
  1149. if (! isMultiLine())
  1150. {
  1151. viewPos.y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  1152. }
  1153. else if (relativeCursor.y < 0)
  1154. {
  1155. viewPos.y = jmax (0, relativeCursor.y + viewPos.y);
  1156. }
  1157. else if (relativeCursor.y > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - caretRect.getHeight()))
  1158. {
  1159. viewPos.y += relativeCursor.y + 2 + caretRect.getHeight() + topIndent - viewport->getMaximumVisibleHeight();
  1160. }
  1161. viewport->setViewPosition (viewPos);
  1162. }
  1163. }
  1164. void TextEditor::moveCaretTo (const int newPosition, const bool isSelecting)
  1165. {
  1166. if (isSelecting)
  1167. {
  1168. moveCaret (newPosition);
  1169. auto oldSelection = selection;
  1170. if (dragType == notDragging)
  1171. {
  1172. if (std::abs (getCaretPosition() - selection.getStart()) < std::abs (getCaretPosition() - selection.getEnd()))
  1173. dragType = draggingSelectionStart;
  1174. else
  1175. dragType = draggingSelectionEnd;
  1176. }
  1177. if (dragType == draggingSelectionStart)
  1178. {
  1179. if (getCaretPosition() >= selection.getEnd())
  1180. dragType = draggingSelectionEnd;
  1181. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  1182. }
  1183. else
  1184. {
  1185. if (getCaretPosition() < selection.getStart())
  1186. dragType = draggingSelectionStart;
  1187. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  1188. }
  1189. repaintText (selection.getUnionWith (oldSelection));
  1190. }
  1191. else
  1192. {
  1193. dragType = notDragging;
  1194. repaintText (selection);
  1195. moveCaret (newPosition);
  1196. selection = Range<int>::emptyRange (getCaretPosition());
  1197. }
  1198. }
  1199. int TextEditor::getTextIndexAt (const int x, const int y)
  1200. {
  1201. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent - borderSize.getLeft()),
  1202. (float) (y + viewport->getViewPositionY() - topIndent - borderSize.getTop()));
  1203. }
  1204. void TextEditor::insertTextAtCaret (const String& t)
  1205. {
  1206. String newText (inputFilter != nullptr ? inputFilter->filterNewText (*this, t) : t);
  1207. if (isMultiLine())
  1208. newText = newText.replace ("\r\n", "\n");
  1209. else
  1210. newText = newText.replaceCharacters ("\r\n", " ");
  1211. const int insertIndex = selection.getStart();
  1212. const int newCaretPos = insertIndex + newText.length();
  1213. remove (selection, getUndoManager(),
  1214. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  1215. insert (newText, insertIndex, currentFont, findColour (textColourId),
  1216. getUndoManager(), newCaretPos);
  1217. textChanged();
  1218. }
  1219. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  1220. {
  1221. moveCaretTo (newSelection.getStart(), false);
  1222. moveCaretTo (newSelection.getEnd(), true);
  1223. }
  1224. //==============================================================================
  1225. void TextEditor::copy()
  1226. {
  1227. if (passwordCharacter == 0)
  1228. {
  1229. auto selectedText = getHighlightedText();
  1230. if (selectedText.isNotEmpty())
  1231. SystemClipboard::copyTextToClipboard (selectedText);
  1232. }
  1233. }
  1234. void TextEditor::paste()
  1235. {
  1236. if (! isReadOnly())
  1237. {
  1238. auto clip = SystemClipboard::getTextFromClipboard();
  1239. if (clip.isNotEmpty())
  1240. insertTextAtCaret (clip);
  1241. }
  1242. }
  1243. void TextEditor::cut()
  1244. {
  1245. if (! isReadOnly())
  1246. {
  1247. moveCaret (selection.getEnd());
  1248. insertTextAtCaret (String());
  1249. }
  1250. }
  1251. //==============================================================================
  1252. void TextEditor::drawContent (Graphics& g)
  1253. {
  1254. if (getWordWrapWidth() > 0)
  1255. {
  1256. g.setOrigin (leftIndent, topIndent);
  1257. auto clip = g.getClipBounds();
  1258. Colour selectedTextColour;
  1259. Iterator i (*this);
  1260. if (! selection.isEmpty())
  1261. {
  1262. Iterator i2 (i);
  1263. RectangleList<float> selectionArea;
  1264. while (i2.next() && i2.lineY < clip.getBottom())
  1265. {
  1266. if (i2.lineY + i2.lineHeight >= clip.getY()
  1267. && selection.intersects ({ i2.indexInText, i2.indexInText + i2.atom->numChars }))
  1268. {
  1269. i2.addSelection (selectionArea, selection);
  1270. }
  1271. }
  1272. g.setColour (findColour (highlightColourId).withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  1273. g.fillRectList (selectionArea);
  1274. selectedTextColour = findColour (highlightedTextColourId);
  1275. }
  1276. const UniformTextSection* lastSection = nullptr;
  1277. while (i.next() && i.lineY < clip.getBottom())
  1278. {
  1279. if (i.lineY + i.lineHeight >= clip.getY())
  1280. {
  1281. if (selection.intersects ({ i.indexInText, i.indexInText + i.atom->numChars }))
  1282. {
  1283. i.drawSelectedText (g, selection, selectedTextColour);
  1284. lastSection = nullptr;
  1285. }
  1286. else
  1287. {
  1288. i.draw (g, lastSection);
  1289. }
  1290. }
  1291. }
  1292. for (auto& underlinedSection : underlinedSections)
  1293. {
  1294. Iterator i2 (*this);
  1295. while (i2.next() && i2.lineY < clip.getBottom())
  1296. {
  1297. if (i2.lineY + i2.lineHeight >= clip.getY()
  1298. && underlinedSection.intersects ({ i2.indexInText, i2.indexInText + i2.atom->numChars }))
  1299. {
  1300. i2.drawUnderline (g, underlinedSection, findColour (textColourId));
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. void TextEditor::paint (Graphics& g)
  1307. {
  1308. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  1309. }
  1310. void TextEditor::paintOverChildren (Graphics& g)
  1311. {
  1312. if (textToShowWhenEmpty.isNotEmpty()
  1313. && (! hasKeyboardFocus (false))
  1314. && getTotalNumChars() == 0)
  1315. {
  1316. g.setColour (colourForTextWhenEmpty);
  1317. g.setFont (getFont());
  1318. if (isMultiLine())
  1319. g.drawText (textToShowWhenEmpty, getLocalBounds(),
  1320. Justification::centred, true);
  1321. else
  1322. g.drawText (textToShowWhenEmpty,
  1323. leftIndent, 0, viewport->getWidth() - leftIndent, getHeight(),
  1324. Justification::centredLeft, true);
  1325. }
  1326. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  1327. }
  1328. //==============================================================================
  1329. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  1330. {
  1331. const bool writable = ! isReadOnly();
  1332. if (passwordCharacter == 0)
  1333. {
  1334. m.addItem (StandardApplicationCommandIDs::cut, TRANS("Cut"), writable);
  1335. m.addItem (StandardApplicationCommandIDs::copy, TRANS("Copy"), ! selection.isEmpty());
  1336. }
  1337. m.addItem (StandardApplicationCommandIDs::paste, TRANS("Paste"), writable);
  1338. m.addItem (StandardApplicationCommandIDs::del, TRANS("Delete"), writable);
  1339. m.addSeparator();
  1340. m.addItem (StandardApplicationCommandIDs::selectAll, TRANS("Select All"));
  1341. m.addSeparator();
  1342. if (getUndoManager() != nullptr)
  1343. {
  1344. m.addItem (StandardApplicationCommandIDs::undo, TRANS("Undo"), undoManager.canUndo());
  1345. m.addItem (StandardApplicationCommandIDs::redo, TRANS("Redo"), undoManager.canRedo());
  1346. }
  1347. }
  1348. void TextEditor::performPopupMenuAction (const int menuItemID)
  1349. {
  1350. switch (menuItemID)
  1351. {
  1352. case StandardApplicationCommandIDs::cut: cutToClipboard(); break;
  1353. case StandardApplicationCommandIDs::copy: copyToClipboard(); break;
  1354. case StandardApplicationCommandIDs::paste: pasteFromClipboard(); break;
  1355. case StandardApplicationCommandIDs::del: cut(); break;
  1356. case StandardApplicationCommandIDs::selectAll: selectAll(); break;
  1357. case StandardApplicationCommandIDs::undo: undo(); break;
  1358. case StandardApplicationCommandIDs::redo: redo(); break;
  1359. default: break;
  1360. }
  1361. }
  1362. static void textEditorMenuCallback (int menuResult, TextEditor* editor)
  1363. {
  1364. if (editor != nullptr && menuResult != 0)
  1365. editor->performPopupMenuAction (menuResult);
  1366. }
  1367. //==============================================================================
  1368. void TextEditor::mouseDown (const MouseEvent& e)
  1369. {
  1370. beginDragAutoRepeat (100);
  1371. newTransaction();
  1372. if (wasFocused || ! selectAllTextWhenFocused)
  1373. {
  1374. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1375. {
  1376. moveCaretTo (getTextIndexAt (e.x, e.y),
  1377. e.mods.isShiftDown());
  1378. }
  1379. else
  1380. {
  1381. PopupMenu m;
  1382. m.setLookAndFeel (&getLookAndFeel());
  1383. addPopupMenuItems (m, &e);
  1384. m.showMenuAsync (PopupMenu::Options(),
  1385. ModalCallbackFunction::forComponent (textEditorMenuCallback, this));
  1386. }
  1387. }
  1388. }
  1389. void TextEditor::mouseDrag (const MouseEvent& e)
  1390. {
  1391. if (wasFocused || ! selectAllTextWhenFocused)
  1392. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1393. moveCaretTo (getTextIndexAt (e.x, e.y), true);
  1394. }
  1395. void TextEditor::mouseUp (const MouseEvent& e)
  1396. {
  1397. newTransaction();
  1398. textHolder->restartTimer();
  1399. if (wasFocused || ! selectAllTextWhenFocused)
  1400. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  1401. moveCaret (getTextIndexAt (e.x, e.y));
  1402. wasFocused = true;
  1403. }
  1404. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  1405. {
  1406. int tokenEnd = getTextIndexAt (e.x, e.y);
  1407. int tokenStart = 0;
  1408. if (e.getNumberOfClicks() > 3)
  1409. {
  1410. tokenEnd = getTotalNumChars();
  1411. }
  1412. else
  1413. {
  1414. auto t = getText();
  1415. auto totalLength = getTotalNumChars();
  1416. while (tokenEnd < totalLength)
  1417. {
  1418. auto c = t[tokenEnd];
  1419. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1420. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1421. ++tokenEnd;
  1422. else
  1423. break;
  1424. }
  1425. tokenStart = tokenEnd;
  1426. while (tokenStart > 0)
  1427. {
  1428. auto c = t[tokenStart - 1];
  1429. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1430. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1431. --tokenStart;
  1432. else
  1433. break;
  1434. }
  1435. if (e.getNumberOfClicks() > 2)
  1436. {
  1437. while (tokenEnd < totalLength)
  1438. {
  1439. auto c = t[tokenEnd];
  1440. if (c != '\r' && c != '\n')
  1441. ++tokenEnd;
  1442. else
  1443. break;
  1444. }
  1445. while (tokenStart > 0)
  1446. {
  1447. auto c = t[tokenStart - 1];
  1448. if (c != '\r' && c != '\n')
  1449. --tokenStart;
  1450. else
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. moveCaretTo (tokenEnd, false);
  1456. moveCaretTo (tokenStart, true);
  1457. }
  1458. void TextEditor::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1459. {
  1460. if (! viewport->useMouseWheelMoveIfNeeded (e, wheel))
  1461. Component::mouseWheelMove (e, wheel);
  1462. }
  1463. //==============================================================================
  1464. bool TextEditor::moveCaretWithTransaction (const int newPos, const bool selecting)
  1465. {
  1466. newTransaction();
  1467. moveCaretTo (newPos, selecting);
  1468. return true;
  1469. }
  1470. bool TextEditor::moveCaretLeft (bool moveInWholeWordSteps, bool selecting)
  1471. {
  1472. auto pos = getCaretPosition();
  1473. if (moveInWholeWordSteps)
  1474. pos = findWordBreakBefore (pos);
  1475. else
  1476. --pos;
  1477. return moveCaretWithTransaction (pos, selecting);
  1478. }
  1479. bool TextEditor::moveCaretRight (bool moveInWholeWordSteps, bool selecting)
  1480. {
  1481. auto pos = getCaretPosition();
  1482. if (moveInWholeWordSteps)
  1483. pos = findWordBreakAfter (pos);
  1484. else
  1485. ++pos;
  1486. return moveCaretWithTransaction (pos, selecting);
  1487. }
  1488. bool TextEditor::moveCaretUp (bool selecting)
  1489. {
  1490. if (! isMultiLine())
  1491. return moveCaretToStartOfLine (selecting);
  1492. auto caretPos = getCaretRectangle().toFloat();
  1493. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - 1.0f), selecting);
  1494. }
  1495. bool TextEditor::moveCaretDown (bool selecting)
  1496. {
  1497. if (! isMultiLine())
  1498. return moveCaretToEndOfLine (selecting);
  1499. auto caretPos = getCaretRectangle().toFloat();
  1500. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + 1.0f), selecting);
  1501. }
  1502. bool TextEditor::pageUp (bool selecting)
  1503. {
  1504. if (! isMultiLine())
  1505. return moveCaretToStartOfLine (selecting);
  1506. auto caretPos = getCaretRectangle().toFloat();
  1507. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - viewport->getViewHeight()), selecting);
  1508. }
  1509. bool TextEditor::pageDown (bool selecting)
  1510. {
  1511. if (! isMultiLine())
  1512. return moveCaretToEndOfLine (selecting);
  1513. auto caretPos = getCaretRectangle().toFloat();
  1514. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + viewport->getViewHeight()), selecting);
  1515. }
  1516. void TextEditor::scrollByLines (int deltaLines)
  1517. {
  1518. viewport->getVerticalScrollBar().moveScrollbarInSteps (deltaLines);
  1519. }
  1520. bool TextEditor::scrollDown()
  1521. {
  1522. scrollByLines (-1);
  1523. return true;
  1524. }
  1525. bool TextEditor::scrollUp()
  1526. {
  1527. scrollByLines (1);
  1528. return true;
  1529. }
  1530. bool TextEditor::moveCaretToTop (bool selecting)
  1531. {
  1532. return moveCaretWithTransaction (0, selecting);
  1533. }
  1534. bool TextEditor::moveCaretToStartOfLine (bool selecting)
  1535. {
  1536. auto caretPos = getCaretRectangle().toFloat();
  1537. return moveCaretWithTransaction (indexAtPosition (0.0f, caretPos.getY()), selecting);
  1538. }
  1539. bool TextEditor::moveCaretToEnd (bool selecting)
  1540. {
  1541. return moveCaretWithTransaction (getTotalNumChars(), selecting);
  1542. }
  1543. bool TextEditor::moveCaretToEndOfLine (bool selecting)
  1544. {
  1545. auto caretPos = getCaretRectangle().toFloat();
  1546. return moveCaretWithTransaction (indexAtPosition ((float) textHolder->getWidth(), caretPos.getY()), selecting);
  1547. }
  1548. bool TextEditor::deleteBackwards (bool moveInWholeWordSteps)
  1549. {
  1550. if (moveInWholeWordSteps)
  1551. moveCaretTo (findWordBreakBefore (getCaretPosition()), true);
  1552. else if (selection.isEmpty() && selection.getStart() > 0)
  1553. selection = { selection.getEnd() - 1, selection.getEnd() };
  1554. cut();
  1555. return true;
  1556. }
  1557. bool TextEditor::deleteForwards (bool /*moveInWholeWordSteps*/)
  1558. {
  1559. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  1560. selection = { selection.getStart(), selection.getStart() + 1 };
  1561. cut();
  1562. return true;
  1563. }
  1564. bool TextEditor::copyToClipboard()
  1565. {
  1566. newTransaction();
  1567. copy();
  1568. return true;
  1569. }
  1570. bool TextEditor::cutToClipboard()
  1571. {
  1572. newTransaction();
  1573. copy();
  1574. cut();
  1575. return true;
  1576. }
  1577. bool TextEditor::pasteFromClipboard()
  1578. {
  1579. newTransaction();
  1580. paste();
  1581. return true;
  1582. }
  1583. bool TextEditor::selectAll()
  1584. {
  1585. newTransaction();
  1586. moveCaretTo (getTotalNumChars(), false);
  1587. moveCaretTo (0, true);
  1588. return true;
  1589. }
  1590. //==============================================================================
  1591. void TextEditor::setEscapeAndReturnKeysConsumed (bool shouldBeConsumed) noexcept
  1592. {
  1593. consumeEscAndReturnKeys = shouldBeConsumed;
  1594. }
  1595. bool TextEditor::keyPressed (const KeyPress& key)
  1596. {
  1597. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0)
  1598. && key != KeyPress ('a', ModifierKeys::commandModifier, 0))
  1599. return false;
  1600. if (! TextEditorKeyMapper<TextEditor>::invokeKeyFunction (*this, key))
  1601. {
  1602. if (key == KeyPress::returnKey)
  1603. {
  1604. newTransaction();
  1605. if (returnKeyStartsNewLine)
  1606. {
  1607. insertTextAtCaret ("\n");
  1608. }
  1609. else
  1610. {
  1611. returnPressed();
  1612. return consumeEscAndReturnKeys;
  1613. }
  1614. }
  1615. else if (key.isKeyCode (KeyPress::escapeKey))
  1616. {
  1617. newTransaction();
  1618. moveCaretTo (getCaretPosition(), false);
  1619. escapePressed();
  1620. return consumeEscAndReturnKeys;
  1621. }
  1622. else if (key.getTextCharacter() >= ' '
  1623. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  1624. {
  1625. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  1626. lastTransactionTime = Time::getApproximateMillisecondCounter();
  1627. }
  1628. else
  1629. {
  1630. return false;
  1631. }
  1632. }
  1633. return true;
  1634. }
  1635. bool TextEditor::keyStateChanged (const bool isKeyDown)
  1636. {
  1637. if (! isKeyDown)
  1638. return false;
  1639. #if JUCE_WINDOWS
  1640. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  1641. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  1642. #endif
  1643. if ((! consumeEscAndReturnKeys)
  1644. && (KeyPress (KeyPress::escapeKey).isCurrentlyDown()
  1645. || KeyPress (KeyPress::returnKey).isCurrentlyDown()))
  1646. return false;
  1647. // (overridden to avoid forwarding key events to the parent)
  1648. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  1649. }
  1650. //==============================================================================
  1651. void TextEditor::focusGained (FocusChangeType)
  1652. {
  1653. newTransaction();
  1654. if (selectAllTextWhenFocused)
  1655. {
  1656. moveCaretTo (0, false);
  1657. moveCaretTo (getTotalNumChars(), true);
  1658. }
  1659. repaint();
  1660. updateCaretPosition();
  1661. if (auto* peer = getPeer())
  1662. if (! isReadOnly())
  1663. peer->textInputRequired (peer->globalToLocal (getScreenPosition()), *this);
  1664. }
  1665. void TextEditor::focusLost (FocusChangeType)
  1666. {
  1667. newTransaction();
  1668. wasFocused = false;
  1669. textHolder->stopTimer();
  1670. underlinedSections.clear();
  1671. if (auto* peer = getPeer())
  1672. peer->dismissPendingTextInput();
  1673. updateCaretPosition();
  1674. postCommandMessage (TextEditorDefs::focusLossMessageId);
  1675. repaint();
  1676. }
  1677. //==============================================================================
  1678. void TextEditor::resized()
  1679. {
  1680. viewport->setBoundsInset (borderSize);
  1681. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  1682. updateTextHolderSize();
  1683. if (isMultiLine())
  1684. updateCaretPosition();
  1685. else
  1686. scrollToMakeSureCursorIsVisible();
  1687. }
  1688. void TextEditor::handleCommandMessage (const int commandId)
  1689. {
  1690. Component::BailOutChecker checker (this);
  1691. switch (commandId)
  1692. {
  1693. case TextEditorDefs::textChangeMessageId:
  1694. listeners.callChecked (checker, &Listener::textEditorTextChanged, (TextEditor&) *this);
  1695. break;
  1696. case TextEditorDefs::returnKeyMessageId:
  1697. listeners.callChecked (checker, &Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  1698. break;
  1699. case TextEditorDefs::escapeKeyMessageId:
  1700. listeners.callChecked (checker, &Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  1701. break;
  1702. case TextEditorDefs::focusLossMessageId:
  1703. updateValueFromText();
  1704. listeners.callChecked (checker, &Listener::textEditorFocusLost, (TextEditor&) *this);
  1705. break;
  1706. default:
  1707. jassertfalse;
  1708. break;
  1709. }
  1710. }
  1711. void TextEditor::setTemporaryUnderlining (const Array<Range<int>>& newUnderlinedSections)
  1712. {
  1713. underlinedSections = newUnderlinedSections;
  1714. repaint();
  1715. }
  1716. //==============================================================================
  1717. UndoManager* TextEditor::getUndoManager() noexcept
  1718. {
  1719. return readOnly ? nullptr : &undoManager;
  1720. }
  1721. void TextEditor::clearInternal (UndoManager* const um)
  1722. {
  1723. remove ({ 0, getTotalNumChars() }, um, caretPosition);
  1724. }
  1725. void TextEditor::insert (const String& text, int insertIndex, const Font& font,
  1726. Colour colour, UndoManager* um, int caretPositionToMoveTo)
  1727. {
  1728. if (text.isNotEmpty())
  1729. {
  1730. if (um != nullptr)
  1731. {
  1732. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1733. newTransaction();
  1734. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  1735. caretPosition, caretPositionToMoveTo));
  1736. }
  1737. else
  1738. {
  1739. repaintText ({ insertIndex, getTotalNumChars() }); // must do this before and after changing the data, in case
  1740. // a line gets moved due to word wrap
  1741. int index = 0;
  1742. int nextIndex = 0;
  1743. for (int i = 0; i < sections.size(); ++i)
  1744. {
  1745. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1746. if (insertIndex == index)
  1747. {
  1748. sections.insert (i, new UniformTextSection (text, font, colour, passwordCharacter));
  1749. break;
  1750. }
  1751. if (insertIndex > index && insertIndex < nextIndex)
  1752. {
  1753. splitSection (i, insertIndex - index);
  1754. sections.insert (i + 1, new UniformTextSection (text, font, colour, passwordCharacter));
  1755. break;
  1756. }
  1757. index = nextIndex;
  1758. }
  1759. if (nextIndex == insertIndex)
  1760. sections.add (new UniformTextSection (text, font, colour, passwordCharacter));
  1761. coalesceSimilarSections();
  1762. totalNumChars = -1;
  1763. valueTextNeedsUpdating = true;
  1764. updateTextHolderSize();
  1765. moveCaretTo (caretPositionToMoveTo, false);
  1766. repaintText ({ insertIndex, getTotalNumChars() });
  1767. }
  1768. }
  1769. }
  1770. void TextEditor::reinsert (int insertIndex, const OwnedArray<UniformTextSection>& sectionsToInsert)
  1771. {
  1772. int index = 0;
  1773. int nextIndex = 0;
  1774. for (int i = 0; i < sections.size(); ++i)
  1775. {
  1776. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1777. if (insertIndex == index)
  1778. {
  1779. for (int j = sectionsToInsert.size(); --j >= 0;)
  1780. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1781. break;
  1782. }
  1783. if (insertIndex > index && insertIndex < nextIndex)
  1784. {
  1785. splitSection (i, insertIndex - index);
  1786. for (int j = sectionsToInsert.size(); --j >= 0;)
  1787. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1788. break;
  1789. }
  1790. index = nextIndex;
  1791. }
  1792. if (nextIndex == insertIndex)
  1793. for (auto* s : sectionsToInsert)
  1794. sections.add (new UniformTextSection (*s));
  1795. coalesceSimilarSections();
  1796. totalNumChars = -1;
  1797. valueTextNeedsUpdating = true;
  1798. }
  1799. void TextEditor::remove (Range<int> range, UndoManager* const um, const int caretPositionToMoveTo)
  1800. {
  1801. if (! range.isEmpty())
  1802. {
  1803. int index = 0;
  1804. for (int i = 0; i < sections.size(); ++i)
  1805. {
  1806. auto nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  1807. if (range.getStart() > index && range.getStart() < nextIndex)
  1808. {
  1809. splitSection (i, range.getStart() - index);
  1810. --i;
  1811. }
  1812. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  1813. {
  1814. splitSection (i, range.getEnd() - index);
  1815. --i;
  1816. }
  1817. else
  1818. {
  1819. index = nextIndex;
  1820. if (index > range.getEnd())
  1821. break;
  1822. }
  1823. }
  1824. index = 0;
  1825. if (um != nullptr)
  1826. {
  1827. Array<UniformTextSection*> removedSections;
  1828. for (auto* section : sections)
  1829. {
  1830. if (range.getEnd() <= range.getStart())
  1831. break;
  1832. auto nextIndex = index + section->getTotalLength();
  1833. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  1834. removedSections.add (new UniformTextSection (*section));
  1835. index = nextIndex;
  1836. }
  1837. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1838. newTransaction();
  1839. um->perform (new RemoveAction (*this, range, caretPosition,
  1840. caretPositionToMoveTo, removedSections));
  1841. }
  1842. else
  1843. {
  1844. auto remainingRange = range;
  1845. for (int i = 0; i < sections.size(); ++i)
  1846. {
  1847. auto* section = sections.getUnchecked (i);
  1848. auto nextIndex = index + section->getTotalLength();
  1849. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  1850. {
  1851. sections.remove (i);
  1852. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  1853. if (remainingRange.isEmpty())
  1854. break;
  1855. --i;
  1856. }
  1857. else
  1858. {
  1859. index = nextIndex;
  1860. }
  1861. }
  1862. coalesceSimilarSections();
  1863. totalNumChars = -1;
  1864. valueTextNeedsUpdating = true;
  1865. moveCaretTo (caretPositionToMoveTo, false);
  1866. repaintText ({ range.getStart(), getTotalNumChars() });
  1867. }
  1868. }
  1869. }
  1870. //==============================================================================
  1871. String TextEditor::getText() const
  1872. {
  1873. MemoryOutputStream mo;
  1874. mo.preallocate ((size_t) getTotalNumChars());
  1875. for (auto* s : sections)
  1876. s->appendAllText (mo);
  1877. return mo.toUTF8();
  1878. }
  1879. String TextEditor::getTextInRange (const Range<int>& range) const
  1880. {
  1881. if (range.isEmpty())
  1882. return {};
  1883. MemoryOutputStream mo;
  1884. mo.preallocate ((size_t) jmin (getTotalNumChars(), range.getLength()));
  1885. int index = 0;
  1886. for (auto* s : sections)
  1887. {
  1888. auto nextIndex = index + s->getTotalLength();
  1889. if (range.getStart() < nextIndex)
  1890. {
  1891. if (range.getEnd() <= index)
  1892. break;
  1893. s->appendSubstring (mo, range - index);
  1894. }
  1895. index = nextIndex;
  1896. }
  1897. return mo.toUTF8();
  1898. }
  1899. String TextEditor::getHighlightedText() const
  1900. {
  1901. return getTextInRange (selection);
  1902. }
  1903. int TextEditor::getTotalNumChars() const
  1904. {
  1905. if (totalNumChars < 0)
  1906. {
  1907. totalNumChars = 0;
  1908. for (auto* s : sections)
  1909. totalNumChars += s->getTotalLength();
  1910. }
  1911. return totalNumChars;
  1912. }
  1913. bool TextEditor::isEmpty() const
  1914. {
  1915. return getTotalNumChars() == 0;
  1916. }
  1917. void TextEditor::getCharPosition (int index, Point<float>& anchor, float& lineHeight) const
  1918. {
  1919. if (getWordWrapWidth() <= 0)
  1920. {
  1921. anchor = {};
  1922. lineHeight = currentFont.getHeight();
  1923. }
  1924. else
  1925. {
  1926. Iterator i (*this);
  1927. if (sections.isEmpty())
  1928. {
  1929. anchor = { i.getJustificationOffset (0), 0 };
  1930. lineHeight = currentFont.getHeight();
  1931. }
  1932. else
  1933. {
  1934. i.getCharPosition (index, anchor, lineHeight);
  1935. }
  1936. }
  1937. }
  1938. int TextEditor::indexAtPosition (const float x, const float y)
  1939. {
  1940. if (getWordWrapWidth() > 0)
  1941. {
  1942. for (Iterator i (*this); i.next();)
  1943. {
  1944. if (y < i.lineY + i.lineHeight)
  1945. {
  1946. if (y < i.lineY)
  1947. return jmax (0, i.indexInText - 1);
  1948. if (x <= i.atomX || i.atom->isNewLine())
  1949. return i.indexInText;
  1950. if (x < i.atomRight)
  1951. return i.xToIndex (x);
  1952. }
  1953. }
  1954. }
  1955. return getTotalNumChars();
  1956. }
  1957. //==============================================================================
  1958. int TextEditor::findWordBreakAfter (const int position) const
  1959. {
  1960. auto t = getTextInRange ({ position, position + 512 });
  1961. auto totalLength = t.length();
  1962. int i = 0;
  1963. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  1964. ++i;
  1965. auto type = TextEditorDefs::getCharacterCategory (t[i]);
  1966. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  1967. ++i;
  1968. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  1969. ++i;
  1970. return position + i;
  1971. }
  1972. int TextEditor::findWordBreakBefore (const int position) const
  1973. {
  1974. if (position <= 0)
  1975. return 0;
  1976. auto startOfBuffer = jmax (0, position - 512);
  1977. auto t = getTextInRange ({ startOfBuffer, position });
  1978. int i = position - startOfBuffer;
  1979. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  1980. --i;
  1981. if (i > 0)
  1982. {
  1983. auto type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  1984. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  1985. --i;
  1986. }
  1987. jassert (startOfBuffer + i >= 0);
  1988. return startOfBuffer + i;
  1989. }
  1990. //==============================================================================
  1991. void TextEditor::splitSection (const int sectionIndex, const int charToSplitAt)
  1992. {
  1993. jassert (sections[sectionIndex] != nullptr);
  1994. sections.insert (sectionIndex + 1,
  1995. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  1996. }
  1997. void TextEditor::coalesceSimilarSections()
  1998. {
  1999. for (int i = 0; i < sections.size() - 1; ++i)
  2000. {
  2001. auto* s1 = sections.getUnchecked (i);
  2002. auto* s2 = sections.getUnchecked (i + 1);
  2003. if (s1->font == s2->font
  2004. && s1->colour == s2->colour)
  2005. {
  2006. s1->append (*s2, passwordCharacter);
  2007. sections.remove (i + 1);
  2008. --i;
  2009. }
  2010. }
  2011. }
  2012. } // namespace juce