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.

2642 lines
77KB

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