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.

2619 lines
75KB

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