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.

2785 lines
81KB

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