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.

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