The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2608 lines
75KB

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