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.

2614 lines
76KB

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