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.

2553 lines
75KB

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