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.

689 lines
27KB

  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. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  19. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  20. #include "../components/juce_Component.h"
  21. #include "../layout/juce_Viewport.h"
  22. #include "../menus/juce_PopupMenu.h"
  23. #include "../keyboard/juce_TextInputTarget.h"
  24. #include "../keyboard/juce_CaretComponent.h"
  25. //==============================================================================
  26. /**
  27. An editable text box.
  28. A TextEditor can either be in single- or multi-line mode, and supports mixed
  29. fonts and colours.
  30. @see TextEditor::Listener, Label
  31. */
  32. class JUCE_API TextEditor : public Component,
  33. public TextInputTarget,
  34. public SettableTooltipClient
  35. {
  36. public:
  37. //==============================================================================
  38. /** Creates a new, empty text editor.
  39. @param componentName the name to pass to the component for it to use as its name
  40. @param passwordCharacter if this is not zero, this character will be used as a replacement
  41. for all characters that are drawn on screen - e.g. to create
  42. a password-style textbox containing circular blobs instead of text,
  43. you could set this value to 0x25cf, which is the unicode character
  44. for a black splodge (not all fonts include this, though), or 0x2022,
  45. which is a bullet (probably the best choice for linux).
  46. */
  47. explicit TextEditor (const String& componentName = String::empty,
  48. juce_wchar passwordCharacter = 0);
  49. /** Destructor. */
  50. ~TextEditor();
  51. //==============================================================================
  52. /** Puts the editor into either multi- or single-line mode.
  53. By default, the editor will be in single-line mode, so use this if you need a multi-line
  54. editor.
  55. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  56. on if you want a multi-line editor with line-breaks.
  57. @see isMultiLine, setReturnKeyStartsNewLine
  58. */
  59. void setMultiLine (bool shouldBeMultiLine,
  60. bool shouldWordWrap = true);
  61. /** Returns true if the editor is in multi-line mode. */
  62. bool isMultiLine() const;
  63. //==============================================================================
  64. /** Changes the behaviour of the return key.
  65. If set to true, the return key will insert a new-line into the text; if false
  66. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  67. method. By default this is set to false, and when true it will only insert
  68. new-lines when in multi-line mode (see setMultiLine()).
  69. */
  70. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  71. /** Returns the value set by setReturnKeyStartsNewLine().
  72. See setReturnKeyStartsNewLine() for more info.
  73. */
  74. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  75. /** Indicates whether the tab key should be accepted and used to input a tab character,
  76. or whether it gets ignored.
  77. By default the tab key is ignored, so that it can be used to switch keyboard focus
  78. between components.
  79. */
  80. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  81. /** Returns true if the tab key is being used for input.
  82. @see setTabKeyUsedAsCharacter
  83. */
  84. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  85. //==============================================================================
  86. /** Changes the editor to read-only mode.
  87. By default, the text editor is not read-only. If you're making it read-only, you
  88. might also want to call setCaretVisible (false) to get rid of the caret.
  89. The text can still be highlighted and copied when in read-only mode.
  90. @see isReadOnly, setCaretVisible
  91. */
  92. void setReadOnly (bool shouldBeReadOnly);
  93. /** Returns true if the editor is in read-only mode. */
  94. bool isReadOnly() const;
  95. //==============================================================================
  96. /** Makes the caret visible or invisible.
  97. By default the caret is visible.
  98. @see setCaretColour, setCaretPosition
  99. */
  100. void setCaretVisible (bool shouldBeVisible);
  101. /** Returns true if the caret is enabled.
  102. @see setCaretVisible
  103. */
  104. bool isCaretVisible() const noexcept { return caret != nullptr; }
  105. //==============================================================================
  106. /** Enables/disables a vertical scrollbar.
  107. (This only applies when in multi-line mode). When the text gets too long to fit
  108. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  109. this is enabled, the scrollbar will be hidden unless it's needed.
  110. By default the scrollbar is enabled.
  111. */
  112. void setScrollbarsShown (bool shouldBeEnabled);
  113. /** Returns true if scrollbars are enabled.
  114. @see setScrollbarsShown
  115. */
  116. bool areScrollbarsShown() const noexcept { return scrollbarVisible; }
  117. /** Changes the password character used to disguise the text.
  118. @param passwordCharacter if this is not zero, this character will be used as a replacement
  119. for all characters that are drawn on screen - e.g. to create
  120. a password-style textbox containing circular blobs instead of text,
  121. you could set this value to 0x25cf, which is the unicode character
  122. for a black splodge (not all fonts include this, though), or 0x2022,
  123. which is a bullet (probably the best choice for linux).
  124. */
  125. void setPasswordCharacter (juce_wchar passwordCharacter);
  126. /** Returns the current password character.
  127. @see setPasswordCharacter
  128. */
  129. juce_wchar getPasswordCharacter() const noexcept { return passwordCharacter; }
  130. //==============================================================================
  131. /** Allows a right-click menu to appear for the editor.
  132. (This defaults to being enabled).
  133. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  134. of options such as cut/copy/paste, undo/redo, etc.
  135. */
  136. void setPopupMenuEnabled (bool menuEnabled);
  137. /** Returns true if the right-click menu is enabled.
  138. @see setPopupMenuEnabled
  139. */
  140. bool isPopupMenuEnabled() const noexcept { return popupMenuEnabled; }
  141. /** Returns true if a popup-menu is currently being displayed. */
  142. bool isPopupMenuCurrentlyActive() const noexcept { return menuActive; }
  143. //==============================================================================
  144. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  145. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  146. methods.
  147. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  148. */
  149. enum ColourIds
  150. {
  151. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  152. transparent if necessary. */
  153. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  154. that because the editor can contain multiple colours, calling this
  155. method won't change the colour of existing text - to do that, call
  156. applyFontToAllText() after calling this method.*/
  157. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  158. the text - this can be transparent if you don't want to show any
  159. highlighting.*/
  160. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  161. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  162. the edge of the component. */
  163. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  164. the edge of the component when it has focus. */
  165. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  166. around the edge of the editor. */
  167. };
  168. //==============================================================================
  169. /** Sets the font to use for newly added text.
  170. This will change the font that will be used next time any text is added or entered
  171. into the editor. It won't change the font of any existing text - to do that, use
  172. applyFontToAllText() instead.
  173. @see applyFontToAllText
  174. */
  175. void setFont (const Font& newFont);
  176. /** Applies a font to all the text in the editor.
  177. This will also set the current font to use for any new text that's added.
  178. @see setFont
  179. */
  180. void applyFontToAllText (const Font& newFont);
  181. /** Returns the font that's currently being used for new text.
  182. @see setFont
  183. */
  184. const Font& getFont() const noexcept { return currentFont; }
  185. //==============================================================================
  186. /** If set to true, focusing on the editor will highlight all its text.
  187. (Set to false by default).
  188. This is useful for boxes where you expect the user to re-enter all the
  189. text when they focus on the component, rather than editing what's already there.
  190. */
  191. void setSelectAllWhenFocused (bool shouldSelectAll);
  192. /** Sets limits on the characters that can be entered.
  193. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  194. limit is set
  195. @param allowedCharacters if this is non-empty, then only characters that occur in
  196. this string are allowed to be entered into the editor.
  197. */
  198. void setInputRestrictions (int maxTextLength,
  199. const String& allowedCharacters = String::empty);
  200. /** When the text editor is empty, it can be set to display a message.
  201. This is handy for things like telling the user what to type in the box - the
  202. string is only displayed, it's not taken to actually be the contents of
  203. the editor.
  204. */
  205. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  206. //==============================================================================
  207. /** Changes the size of the scrollbars that are used.
  208. Handy if you need smaller scrollbars for a small text box.
  209. */
  210. void setScrollBarThickness (int newThicknessPixels);
  211. //==============================================================================
  212. /**
  213. Receives callbacks from a TextEditor component when it changes.
  214. @see TextEditor::addListener
  215. */
  216. class JUCE_API Listener
  217. {
  218. public:
  219. /** Destructor. */
  220. virtual ~Listener() {}
  221. /** Called when the user changes the text in some way. */
  222. virtual void textEditorTextChanged (TextEditor& editor);
  223. /** Called when the user presses the return key. */
  224. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  225. /** Called when the user presses the escape key. */
  226. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  227. /** Called when the text editor loses focus. */
  228. virtual void textEditorFocusLost (TextEditor& editor);
  229. };
  230. /** Registers a listener to be told when things happen to the text.
  231. @see removeListener
  232. */
  233. void addListener (Listener* newListener);
  234. /** Deregisters a listener.
  235. @see addListener
  236. */
  237. void removeListener (Listener* listenerToRemove);
  238. //==============================================================================
  239. /** Returns the entire contents of the editor. */
  240. String getText() const;
  241. /** Returns a section of the contents of the editor. */
  242. String getTextInRange (const Range<int>& textRange) const;
  243. /** Returns true if there are no characters in the editor.
  244. This is far more efficient than calling getText().isEmpty().
  245. */
  246. bool isEmpty() const;
  247. /** Sets the entire content of the editor.
  248. This will clear the editor and insert the given text (using the current text colour
  249. and font). You can set the current text colour using
  250. @code setColour (TextEditor::textColourId, ...);
  251. @endcode
  252. @param newText the text to add
  253. @param sendTextChangeMessage if true, this will cause a change message to
  254. be sent to all the listeners.
  255. @see insertText
  256. */
  257. void setText (const String& newText,
  258. bool sendTextChangeMessage = true);
  259. /** Returns a Value object that can be used to get or set the text.
  260. Bear in mind that this operate quite slowly if your text box contains large
  261. amounts of text, as it needs to dynamically build the string that's involved.
  262. It's best used for small text boxes.
  263. */
  264. Value& getTextValue();
  265. /** Inserts some text at the current caret position.
  266. If a section of the text is highlighted, it will be replaced by
  267. this string, otherwise it will be inserted.
  268. To delete a section of text, you can use setHighlightedRegion() to
  269. highlight it, and call insertTextAtCursor (String::empty).
  270. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  271. */
  272. void insertTextAtCaret (const String& textToInsert);
  273. /** Deletes all the text from the editor. */
  274. void clear();
  275. /** Deletes the currently selected region.
  276. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  277. @see copy, paste, SystemClipboard
  278. */
  279. void cut();
  280. /** Copies the currently selected region to the clipboard.
  281. @see cut, paste, SystemClipboard
  282. */
  283. void copy();
  284. /** Pastes the contents of the clipboard into the editor at the caret position.
  285. @see cut, copy, SystemClipboard
  286. */
  287. void paste();
  288. //==============================================================================
  289. /** Returns the current index of the caret.
  290. @see setCaretPosition
  291. */
  292. int getCaretPosition() const;
  293. /** Moves the caret to be in front of a given character.
  294. @see getCaretPosition, moveCaretToEnd
  295. */
  296. void setCaretPosition (int newIndex);
  297. /** Moves the caret to be the end of all the text.
  298. @see setCaretPosition
  299. */
  300. void moveCaretToEnd();
  301. /** Attempts to scroll the text editor so that the caret ends up at
  302. a specified position.
  303. This won't affect the caret's position within the text, it tries to scroll
  304. the entire editor vertically and horizontally so that the caret is sitting
  305. at the given position (relative to the top-left of this component).
  306. Depending on the amount of text available, it might not be possible to
  307. scroll far enough for the caret to reach this exact position, but it
  308. will go as far as it can in that direction.
  309. */
  310. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  311. /** Get the graphical position of the caret.
  312. The rectangle returned is relative to the component's top-left corner.
  313. @see scrollEditorToPositionCaret
  314. */
  315. Rectangle<int> getCaretRectangle();
  316. /** Selects a section of the text. */
  317. void setHighlightedRegion (const Range<int>& newSelection);
  318. /** Returns the range of characters that are selected.
  319. If nothing is selected, this will return an empty range.
  320. @see setHighlightedRegion
  321. */
  322. Range<int> getHighlightedRegion() const { return selection; }
  323. /** Returns the section of text that is currently selected. */
  324. String getHighlightedText() const;
  325. /** Finds the index of the character at a given position.
  326. The co-ordinates are relative to the component's top-left.
  327. */
  328. int getTextIndexAt (int x, int y);
  329. /** Counts the number of characters in the text.
  330. This is quicker than getting the text as a string if you just need to know
  331. the length.
  332. */
  333. int getTotalNumChars() const;
  334. /** Returns the total width of the text, as it is currently laid-out.
  335. This may be larger than the size of the TextEditor, and can change when
  336. the TextEditor is resized or the text changes.
  337. */
  338. int getTextWidth() const;
  339. /** Returns the maximum height of the text, as it is currently laid-out.
  340. This may be larger than the size of the TextEditor, and can change when
  341. the TextEditor is resized or the text changes.
  342. */
  343. int getTextHeight() const;
  344. /** Changes the size of the gap at the top and left-edge of the editor.
  345. By default there's a gap of 4 pixels.
  346. */
  347. void setIndents (int newLeftIndent, int newTopIndent);
  348. /** Changes the size of border left around the edge of the component.
  349. @see getBorder
  350. */
  351. void setBorder (const BorderSize<int>& border);
  352. /** Returns the size of border around the edge of the component.
  353. @see setBorder
  354. */
  355. BorderSize<int> getBorder() const;
  356. /** Used to disable the auto-scrolling which keeps the caret visible.
  357. If true (the default), the editor will scroll when the caret moves offscreen. If
  358. set to false, it won't.
  359. */
  360. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  361. //==============================================================================
  362. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  363. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  364. bool moveCaretUp (bool selecting);
  365. bool moveCaretDown (bool selecting);
  366. bool pageUp (bool selecting);
  367. bool pageDown (bool selecting);
  368. bool scrollDown();
  369. bool scrollUp();
  370. bool moveCaretToTop (bool selecting);
  371. bool moveCaretToStartOfLine (bool selecting);
  372. bool moveCaretToEnd (bool selecting);
  373. bool moveCaretToEndOfLine (bool selecting);
  374. bool deleteBackwards (bool moveInWholeWordSteps);
  375. bool deleteForwards (bool moveInWholeWordSteps);
  376. bool copyToClipboard();
  377. bool cutToClipboard();
  378. bool pasteFromClipboard();
  379. bool selectAll();
  380. bool undo();
  381. bool redo();
  382. //==============================================================================
  383. /** This adds the items to the popup menu.
  384. By default it adds the cut/copy/paste items, but you can override this if
  385. you need to replace these with your own items.
  386. If you want to add your own items to the existing ones, you can override this,
  387. call the base class's addPopupMenuItems() method, then append your own items.
  388. When the menu has been shown, performPopupMenuAction() will be called to
  389. perform the item that the user has chosen.
  390. The default menu items will be added using item IDs from the
  391. StandardApplicationCommandIDs namespace.
  392. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  393. a pointer to the info about it, or may be null if the menu is being triggered
  394. by some other means.
  395. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  396. */
  397. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  398. const MouseEvent* mouseClickEvent);
  399. /** This is called to perform one of the items that was shown on the popup menu.
  400. If you've overridden addPopupMenuItems(), you should also override this
  401. to perform the actions that you've added.
  402. If you've overridden addPopupMenuItems() but have still left the default items
  403. on the menu, remember to call the superclass's performPopupMenuAction()
  404. so that it can perform the default actions if that's what the user clicked on.
  405. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  406. */
  407. virtual void performPopupMenuAction (int menuItemID);
  408. //==============================================================================
  409. /** @internal */
  410. void paint (Graphics& g);
  411. /** @internal */
  412. void paintOverChildren (Graphics& g);
  413. /** @internal */
  414. void mouseDown (const MouseEvent& e);
  415. /** @internal */
  416. void mouseUp (const MouseEvent& e);
  417. /** @internal */
  418. void mouseDrag (const MouseEvent& e);
  419. /** @internal */
  420. void mouseDoubleClick (const MouseEvent& e);
  421. /** @internal */
  422. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&);
  423. /** @internal */
  424. bool keyPressed (const KeyPress& key);
  425. /** @internal */
  426. bool keyStateChanged (bool isKeyDown);
  427. /** @internal */
  428. void focusGained (FocusChangeType);
  429. /** @internal */
  430. void focusLost (FocusChangeType);
  431. /** @internal */
  432. void resized();
  433. /** @internal */
  434. void enablementChanged();
  435. /** @internal */
  436. void colourChanged();
  437. /** @internal */
  438. void lookAndFeelChanged();
  439. /** @internal */
  440. bool isTextInputActive() const;
  441. /** @internal */
  442. void setTemporaryUnderlining (const Array <Range<int> >&);
  443. protected:
  444. //==============================================================================
  445. /** Scrolls the minimum distance needed to get the caret into view. */
  446. void scrollToMakeSureCursorIsVisible();
  447. /** @internal */
  448. void moveCaret (int newCaretPos);
  449. /** @internal */
  450. void moveCaretTo (int newPosition, bool isSelecting);
  451. /** Used internally to dispatch a text-change message. */
  452. void textChanged();
  453. /** Begins a new transaction in the UndoManager. */
  454. void newTransaction();
  455. /** Used internally to trigger an undo or redo. */
  456. void doUndoRedo (bool isRedo);
  457. /** Can be overridden to intercept return key presses directly */
  458. virtual void returnPressed();
  459. /** Can be overridden to intercept escape key presses directly */
  460. virtual void escapePressed();
  461. /** @internal */
  462. void handleCommandMessage (int commandId);
  463. private:
  464. //==============================================================================
  465. class Iterator;
  466. class UniformTextSection;
  467. class TextHolderComponent;
  468. class InsertAction;
  469. class RemoveAction;
  470. friend class InsertAction;
  471. friend class RemoveAction;
  472. ScopedPointer <Viewport> viewport;
  473. TextHolderComponent* textHolder;
  474. BorderSize<int> borderSize;
  475. bool readOnly : 1;
  476. bool multiline : 1;
  477. bool wordWrap : 1;
  478. bool returnKeyStartsNewLine : 1;
  479. bool popupMenuEnabled : 1;
  480. bool selectAllTextWhenFocused : 1;
  481. bool scrollbarVisible : 1;
  482. bool wasFocused : 1;
  483. bool keepCaretOnScreen : 1;
  484. bool tabKeyUsed : 1;
  485. bool menuActive : 1;
  486. bool valueTextNeedsUpdating : 1;
  487. UndoManager undoManager;
  488. ScopedPointer<CaretComponent> caret;
  489. int maxTextLength;
  490. Range<int> selection;
  491. int leftIndent, topIndent;
  492. unsigned int lastTransactionTime;
  493. Font currentFont;
  494. mutable int totalNumChars;
  495. int caretPosition;
  496. Array <UniformTextSection*> sections;
  497. String textToShowWhenEmpty;
  498. Colour colourForTextWhenEmpty;
  499. juce_wchar passwordCharacter;
  500. Value textValue;
  501. enum
  502. {
  503. notDragging,
  504. draggingSelectionStart,
  505. draggingSelectionEnd
  506. } dragType;
  507. String allowedCharacters;
  508. ListenerList <Listener> listeners;
  509. Array <Range<int> > underlinedSections;
  510. void coalesceSimilarSections();
  511. void splitSection (int sectionIndex, int charToSplitAt);
  512. void clearInternal (UndoManager* um);
  513. void insert (const String& text, int insertIndex, const Font& font,
  514. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  515. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  516. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  517. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  518. void updateCaretPosition();
  519. void updateValueFromText();
  520. void textWasChangedByValue();
  521. int indexAtPosition (float x, float y);
  522. int findWordBreakAfter (int position) const;
  523. int findWordBreakBefore (int position) const;
  524. bool moveCaretWithTransation (int newPos, bool selecting);
  525. friend class TextHolderComponent;
  526. friend class TextEditorViewport;
  527. void drawContent (Graphics& g);
  528. void updateTextHolderSize();
  529. float getWordWrapWidth() const;
  530. void timerCallbackInt();
  531. void repaintText (const Range<int>& range);
  532. void scrollByLines (int deltaLines);
  533. bool undoOrRedo (bool shouldUndo);
  534. UndoManager* getUndoManager() noexcept;
  535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  536. };
  537. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  538. typedef TextEditor::Listener TextEditorListener;
  539. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__