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.

2535 lines
73KB

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