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.

2521 lines
74KB

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