Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2494 lines
72KB

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