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.

2536 lines
73KB

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