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.

2510 lines
73KB

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