Audio plugin host https://kx.studio/carla
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.

juce_TextEditor.h 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. //==============================================================================
  21. /**
  22. An editable text box.
  23. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24. fonts and colours.
  25. @see TextEditor::Listener, Label
  26. @tags{GUI}
  27. */
  28. class JUCE_API TextEditor : public Component,
  29. public TextInputTarget,
  30. public SettableTooltipClient
  31. {
  32. public:
  33. //==============================================================================
  34. /** Creates a new, empty text editor.
  35. @param componentName the name to pass to the component for it to use as its name
  36. @param passwordCharacter if this is not zero, this character will be used as a replacement
  37. for all characters that are drawn on screen - e.g. to create
  38. a password-style textbox containing circular blobs instead of text,
  39. you could set this value to 0x25cf, which is the unicode character
  40. for a black splodge (not all fonts include this, though), or 0x2022,
  41. which is a bullet (probably the best choice for linux).
  42. */
  43. explicit TextEditor (const String& componentName = String(),
  44. juce_wchar passwordCharacter = 0);
  45. /** Destructor. */
  46. ~TextEditor() override;
  47. //==============================================================================
  48. /** Puts the editor into either multi- or single-line mode.
  49. By default, the editor will be in single-line mode, so use this if you need a multi-line
  50. editor.
  51. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  52. on if you want a multi-line editor with line-breaks.
  53. @param shouldBeMultiLine whether the editor should be multi- or single-line.
  54. @param shouldWordWrap sets whether long lines should be broken up in multi-line editors.
  55. If this is false and scrollbars are enabled a horizontal scrollbar
  56. will be shown.
  57. @see isMultiLine, setReturnKeyStartsNewLine, setScrollbarsShown
  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. /** This can be used to change whether escape and return keypress events are
  86. propagated up to the parent component.
  87. The default here is true, meaning that these events are not allowed to reach the
  88. parent, but you may want to allow them through so that they can trigger other
  89. actions, e.g. closing a dialog box, etc.
  90. */
  91. void setEscapeAndReturnKeysConsumed (bool shouldBeConsumed) noexcept;
  92. //==============================================================================
  93. /** Changes the editor to read-only mode.
  94. By default, the text editor is not read-only. If you're making it read-only, you
  95. might also want to call setCaretVisible (false) to get rid of the caret.
  96. The text can still be highlighted and copied when in read-only mode.
  97. @see isReadOnly, setCaretVisible
  98. */
  99. void setReadOnly (bool shouldBeReadOnly);
  100. /** Returns true if the editor is in read-only mode. */
  101. bool isReadOnly() const noexcept;
  102. //==============================================================================
  103. /** Makes the caret visible or invisible.
  104. By default the caret is visible.
  105. @see setCaretColour, setCaretPosition
  106. */
  107. void setCaretVisible (bool shouldBeVisible);
  108. /** Returns true if the caret is enabled.
  109. @see setCaretVisible
  110. */
  111. bool isCaretVisible() const noexcept { return caretVisible && ! isReadOnly(); }
  112. //==============================================================================
  113. /** Enables or disables scrollbars (this only applies when in multi-line mode).
  114. When the text gets too long to fit in the component, a scrollbar can appear to
  115. allow it to be scrolled. Even when this is enabled, the scrollbar will be hidden
  116. unless it's needed.
  117. By default scrollbars are enabled.
  118. */
  119. void setScrollbarsShown (bool shouldBeEnabled);
  120. /** Returns true if scrollbars are enabled.
  121. @see setScrollbarsShown
  122. */
  123. bool areScrollbarsShown() const noexcept { return scrollbarVisible; }
  124. /** Changes the password character used to disguise the text.
  125. @param passwordCharacter if this is not zero, this character will be used as a replacement
  126. for all characters that are drawn on screen - e.g. to create
  127. a password-style textbox containing circular blobs instead of text,
  128. you could set this value to 0x25cf, which is the unicode character
  129. for a black splodge (not all fonts include this, though), or 0x2022,
  130. which is a bullet (probably the best choice for linux).
  131. */
  132. void setPasswordCharacter (juce_wchar passwordCharacter);
  133. /** Returns the current password character.
  134. @see setPasswordCharacter
  135. */
  136. juce_wchar getPasswordCharacter() const noexcept { return passwordCharacter; }
  137. //==============================================================================
  138. /** Allows a right-click menu to appear for the editor.
  139. (This defaults to being enabled).
  140. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  141. of options such as cut/copy/paste, undo/redo, etc.
  142. */
  143. void setPopupMenuEnabled (bool menuEnabled);
  144. /** Returns true if the right-click menu is enabled.
  145. @see setPopupMenuEnabled
  146. */
  147. bool isPopupMenuEnabled() const noexcept { return popupMenuEnabled; }
  148. /** Returns true if a popup-menu is currently being displayed. */
  149. bool isPopupMenuCurrentlyActive() const noexcept { return menuActive; }
  150. //==============================================================================
  151. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  152. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  153. methods.
  154. NB: You can also set the caret colour using CaretComponent::caretColourId
  155. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  156. */
  157. enum ColourIds
  158. {
  159. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  160. transparent if necessary. */
  161. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  162. that because the editor can contain multiple colours, calling this
  163. method won't change the colour of existing text - to do that, use
  164. the applyColourToAllText() method */
  165. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  166. the text - this can be transparent if you don't want to show any
  167. highlighting.*/
  168. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  169. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  170. the edge of the component. */
  171. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  172. the edge of the component when it has focus. */
  173. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  174. around the edge of the editor. */
  175. };
  176. //==============================================================================
  177. /** Sets the font to use for newly added text.
  178. This will change the font that will be used next time any text is added or entered
  179. into the editor. It won't change the font of any existing text - to do that, use
  180. applyFontToAllText() instead.
  181. @see applyFontToAllText
  182. */
  183. void setFont (const Font& newFont);
  184. /** Applies a font to all the text in the editor.
  185. If the changeCurrentFont argument is true then this will also set the
  186. new font as the font to be used for any new text that's added.
  187. @see setFont
  188. */
  189. void applyFontToAllText (const Font& newFont, bool changeCurrentFont = true);
  190. /** Returns the font that's currently being used for new text.
  191. @see setFont
  192. */
  193. const Font& getFont() const noexcept { return currentFont; }
  194. /** Applies a colour to all the text in the editor.
  195. If the changeCurrentTextColour argument is true then this will also set the
  196. new colour as the colour to be used for any new text that's added.
  197. */
  198. void applyColourToAllText (const Colour& newColour, bool changeCurrentTextColour = true);
  199. /** Sets whether whitespace should be underlined when the editor font is underlined.
  200. @see isWhitespaceUnderlined
  201. */
  202. void setWhitespaceUnderlined (bool shouldUnderlineWhitespace) noexcept { underlineWhitespace = shouldUnderlineWhitespace; }
  203. /** Returns true if whitespace is underlined for underlined fonts.
  204. @see setWhitespaceIsUnderlined
  205. */
  206. bool isWhitespaceUnderlined() const noexcept { return underlineWhitespace; }
  207. //==============================================================================
  208. /** If set to true, focusing on the editor will highlight all its text.
  209. (Set to false by default).
  210. This is useful for boxes where you expect the user to re-enter all the
  211. text when they focus on the component, rather than editing what's already there.
  212. */
  213. void setSelectAllWhenFocused (bool shouldSelectAll);
  214. /** When the text editor is empty, it can be set to display a message.
  215. This is handy for things like telling the user what to type in the box - the
  216. string is only displayed, it's not taken to actually be the contents of
  217. the editor.
  218. */
  219. void setTextToShowWhenEmpty (const String& text, Colour colourToUse);
  220. /** Returns the text that will be shown when the text editor is empty.
  221. @see setTextToShowWhenEmpty
  222. */
  223. String getTextToShowWhenEmpty() const noexcept { return textToShowWhenEmpty; }
  224. //==============================================================================
  225. /** Changes the size of the scrollbars that are used.
  226. Handy if you need smaller scrollbars for a small text box.
  227. */
  228. void setScrollBarThickness (int newThicknessPixels);
  229. //==============================================================================
  230. /**
  231. Receives callbacks from a TextEditor component when it changes.
  232. @see TextEditor::addListener
  233. */
  234. class JUCE_API Listener
  235. {
  236. public:
  237. /** Destructor. */
  238. virtual ~Listener() = default;
  239. /** Called when the user changes the text in some way. */
  240. virtual void textEditorTextChanged (TextEditor&) {}
  241. /** Called when the user presses the return key. */
  242. virtual void textEditorReturnKeyPressed (TextEditor&) {}
  243. /** Called when the user presses the escape key. */
  244. virtual void textEditorEscapeKeyPressed (TextEditor&) {}
  245. /** Called when the text editor loses focus. */
  246. virtual void textEditorFocusLost (TextEditor&) {}
  247. };
  248. /** Registers a listener to be told when things happen to the text.
  249. @see removeListener
  250. */
  251. void addListener (Listener* newListener);
  252. /** Deregisters a listener.
  253. @see addListener
  254. */
  255. void removeListener (Listener* listenerToRemove);
  256. //==============================================================================
  257. /** You can assign a lambda to this callback object to have it called when the text is changed. */
  258. std::function<void()> onTextChange;
  259. /** You can assign a lambda to this callback object to have it called when the return key is pressed. */
  260. std::function<void()> onReturnKey;
  261. /** You can assign a lambda to this callback object to have it called when the escape key is pressed. */
  262. std::function<void()> onEscapeKey;
  263. /** You can assign a lambda to this callback object to have it called when the editor loses key focus. */
  264. std::function<void()> onFocusLost;
  265. //==============================================================================
  266. /** Returns the entire contents of the editor. */
  267. String getText() const;
  268. /** Returns a section of the contents of the editor. */
  269. String getTextInRange (const Range<int>& textRange) const override;
  270. /** Returns true if there are no characters in the editor.
  271. This is far more efficient than calling getText().isEmpty().
  272. */
  273. bool isEmpty() const;
  274. /** Sets the entire content of the editor.
  275. This will clear the editor and insert the given text (using the current text colour
  276. and font). You can set the current text colour using
  277. @code setColour (TextEditor::textColourId, ...);
  278. @endcode
  279. @param newText the text to add
  280. @param sendTextChangeMessage if true, this will cause a change message to
  281. be sent to all the listeners.
  282. @see insertTextAtCaret
  283. */
  284. void setText (const String& newText,
  285. bool sendTextChangeMessage = true);
  286. /** Returns a Value object that can be used to get or set the text.
  287. Bear in mind that this operate quite slowly if your text box contains large
  288. amounts of text, as it needs to dynamically build the string that's involved.
  289. It's best used for small text boxes.
  290. */
  291. Value& getTextValue();
  292. /** Inserts some text at the current caret position.
  293. If a section of the text is highlighted, it will be replaced by
  294. this string, otherwise it will be inserted.
  295. To delete a section of text, you can use setHighlightedRegion() to
  296. highlight it, and call insertTextAtCaret (String()).
  297. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  298. */
  299. void insertTextAtCaret (const String& textToInsert) override;
  300. /** Deletes all the text from the editor. */
  301. void clear();
  302. /** Deletes the currently selected region.
  303. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  304. @see copy, paste, SystemClipboard
  305. */
  306. void cut();
  307. /** Copies the currently selected region to the clipboard.
  308. @see cut, paste, SystemClipboard
  309. */
  310. void copy();
  311. /** Pastes the contents of the clipboard into the editor at the caret position.
  312. @see cut, copy, SystemClipboard
  313. */
  314. void paste();
  315. //==============================================================================
  316. /** Returns the current index of the caret.
  317. @see setCaretPosition
  318. */
  319. int getCaretPosition() const;
  320. /** Moves the caret to be in front of a given character.
  321. @see getCaretPosition, moveCaretToEnd
  322. */
  323. void setCaretPosition (int newIndex);
  324. /** Attempts to scroll the text editor so that the caret ends up at
  325. a specified position.
  326. This won't affect the caret's position within the text, it tries to scroll
  327. the entire editor vertically and horizontally so that the caret is sitting
  328. at the given position (relative to the top-left of this component).
  329. Depending on the amount of text available, it might not be possible to
  330. scroll far enough for the caret to reach this exact position, but it
  331. will go as far as it can in that direction.
  332. */
  333. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  334. /** Get the graphical position of the caret.
  335. The rectangle returned is relative to the component's top-left corner.
  336. @see scrollEditorToPositionCaret
  337. */
  338. Rectangle<int> getCaretRectangle() override;
  339. /** Selects a section of the text. */
  340. void setHighlightedRegion (const Range<int>& newSelection) override;
  341. /** Returns the range of characters that are selected.
  342. If nothing is selected, this will return an empty range.
  343. @see setHighlightedRegion
  344. */
  345. Range<int> getHighlightedRegion() const override { return selection; }
  346. /** Returns the section of text that is currently selected. */
  347. String getHighlightedText() const;
  348. /** Finds the index of the character at a given position.
  349. The coordinates are relative to the component's top-left.
  350. */
  351. int getTextIndexAt (int x, int y) const;
  352. /** Counts the number of characters in the text.
  353. This is quicker than getting the text as a string if you just need to know
  354. the length.
  355. */
  356. int getTotalNumChars() const;
  357. /** Returns the total width of the text, as it is currently laid-out.
  358. This may be larger than the size of the TextEditor, and can change when
  359. the TextEditor is resized or the text changes.
  360. */
  361. int getTextWidth() const;
  362. /** Returns the maximum height of the text, as it is currently laid-out.
  363. This may be larger than the size of the TextEditor, and can change when
  364. the TextEditor is resized or the text changes.
  365. */
  366. int getTextHeight() const;
  367. /** Changes the size of the gap at the top and left-edge of the editor.
  368. By default there's a gap of 4 pixels.
  369. */
  370. void setIndents (int newLeftIndent, int newTopIndent);
  371. /** Returns the gap at the top edge of the editor.
  372. @see setIndents
  373. */
  374. int getTopIndent() const noexcept { return topIndent; }
  375. /** Returns the gap at the left edge of the editor.
  376. @see setIndents
  377. */
  378. int getLeftIndent() const noexcept { return leftIndent; }
  379. /** Changes the size of border left around the edge of the component.
  380. @see getBorder
  381. */
  382. void setBorder (BorderSize<int> border);
  383. /** Returns the size of border around the edge of the component.
  384. @see setBorder
  385. */
  386. BorderSize<int> getBorder() const;
  387. /** Used to disable the auto-scrolling which keeps the caret visible.
  388. If true (the default), the editor will scroll when the caret moves offscreen. If
  389. set to false, it won't.
  390. */
  391. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  392. /** Modifies the justification of the text within the editor window. */
  393. void setJustification (Justification newJustification);
  394. /** Returns the type of justification, as set in setJustification(). */
  395. Justification getJustificationType() const noexcept { return justification; }
  396. /** Sets the line spacing of the TextEditor.
  397. The default (and minimum) value is 1.0 and values > 1.0 will increase the line spacing as a
  398. multiple of the line height e.g. for double-spacing call this method with an argument of 2.0.
  399. */
  400. void setLineSpacing (float newLineSpacing) noexcept { lineSpacing = jmax (1.0f, newLineSpacing); }
  401. /** Returns the current line spacing of the TextEditor. */
  402. float getLineSpacing() const noexcept { return lineSpacing; }
  403. /** Returns the bounding box for a range of text in the editor. As the range may span
  404. multiple lines, this method returns a RectangleList.
  405. The bounds are relative to the component's top-left and may extend beyond the bounds
  406. of the component if the text is long and word wrapping is disabled.
  407. */
  408. RectangleList<int> getTextBounds (Range<int> textRange);
  409. //==============================================================================
  410. void moveCaretToEnd();
  411. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  412. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  413. bool moveCaretUp (bool selecting);
  414. bool moveCaretDown (bool selecting);
  415. bool pageUp (bool selecting);
  416. bool pageDown (bool selecting);
  417. bool scrollDown();
  418. bool scrollUp();
  419. bool moveCaretToTop (bool selecting);
  420. bool moveCaretToStartOfLine (bool selecting);
  421. bool moveCaretToEnd (bool selecting);
  422. bool moveCaretToEndOfLine (bool selecting);
  423. bool deleteBackwards (bool moveInWholeWordSteps);
  424. bool deleteForwards (bool moveInWholeWordSteps);
  425. bool copyToClipboard();
  426. bool cutToClipboard();
  427. bool pasteFromClipboard();
  428. bool selectAll();
  429. bool undo();
  430. bool redo();
  431. //==============================================================================
  432. /** This adds the items to the popup menu.
  433. By default it adds the cut/copy/paste items, but you can override this if
  434. you need to replace these with your own items.
  435. If you want to add your own items to the existing ones, you can override this,
  436. call the base class's addPopupMenuItems() method, then append your own items.
  437. When the menu has been shown, performPopupMenuAction() will be called to
  438. perform the item that the user has chosen.
  439. The default menu items will be added using item IDs from the
  440. StandardApplicationCommandIDs namespace.
  441. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  442. a pointer to the info about it, or may be null if the menu is being triggered
  443. by some other means.
  444. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  445. */
  446. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  447. const MouseEvent* mouseClickEvent);
  448. /** This is called to perform one of the items that was shown on the popup menu.
  449. If you've overridden addPopupMenuItems(), you should also override this
  450. to perform the actions that you've added.
  451. If you've overridden addPopupMenuItems() but have still left the default items
  452. on the menu, remember to call the superclass's performPopupMenuAction()
  453. so that it can perform the default actions if that's what the user clicked on.
  454. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  455. */
  456. virtual void performPopupMenuAction (int menuItemID);
  457. //==============================================================================
  458. /** Base class for input filters that can be applied to a TextEditor to restrict
  459. the text that can be entered.
  460. */
  461. class JUCE_API InputFilter
  462. {
  463. public:
  464. InputFilter() = default;
  465. virtual ~InputFilter() = default;
  466. /** This method is called whenever text is entered into the editor.
  467. An implementation of this class should should check the input string,
  468. and return an edited version of it that should be used.
  469. */
  470. virtual String filterNewText (TextEditor&, const String& newInput) = 0;
  471. };
  472. /** An input filter for a TextEditor that limits the length of text and/or the
  473. characters that it may contain.
  474. */
  475. class JUCE_API LengthAndCharacterRestriction : public InputFilter
  476. {
  477. public:
  478. /** Creates a filter that limits the length of text, and/or the characters that it can contain.
  479. @param maxNumChars if this is > 0, it sets a maximum length limit; if <= 0, no
  480. limit is set
  481. @param allowedCharacters if this is non-empty, then only characters that occur in
  482. this string are allowed to be entered into the editor.
  483. */
  484. LengthAndCharacterRestriction (int maxNumChars, const String& allowedCharacters);
  485. String filterNewText (TextEditor&, const String&) override;
  486. private:
  487. String allowedCharacters;
  488. int maxLength;
  489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LengthAndCharacterRestriction)
  490. };
  491. /** Sets an input filter that should be applied to this editor.
  492. The filter can be nullptr, to remove any existing filters.
  493. If takeOwnership is true, then the filter will be owned and deleted by the editor
  494. when no longer needed.
  495. */
  496. void setInputFilter (InputFilter* newFilter, bool takeOwnership);
  497. /** Returns the current InputFilter, as set by setInputFilter(). */
  498. InputFilter* getInputFilter() const noexcept { return inputFilter; }
  499. /** Sets limits on the characters that can be entered.
  500. This is just a shortcut that passes an instance of the LengthAndCharacterRestriction
  501. class to setInputFilter().
  502. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  503. limit is set
  504. @param allowedCharacters if this is non-empty, then only characters that occur in
  505. this string are allowed to be entered into the editor.
  506. */
  507. void setInputRestrictions (int maxTextLength,
  508. const String& allowedCharacters = String());
  509. void setKeyboardType (VirtualKeyboardType type) noexcept { keyboardType = type; }
  510. //==============================================================================
  511. /** This abstract base class is implemented by LookAndFeel classes to provide
  512. TextEditor drawing functionality.
  513. */
  514. struct JUCE_API LookAndFeelMethods
  515. {
  516. virtual ~LookAndFeelMethods() = default;
  517. virtual void fillTextEditorBackground (Graphics&, int width, int height, TextEditor&) = 0;
  518. virtual void drawTextEditorOutline (Graphics&, int width, int height, TextEditor&) = 0;
  519. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner) = 0;
  520. };
  521. //==============================================================================
  522. /** @internal */
  523. void paint (Graphics&) override;
  524. /** @internal */
  525. void paintOverChildren (Graphics&) override;
  526. /** @internal */
  527. void mouseDown (const MouseEvent&) override;
  528. /** @internal */
  529. void mouseUp (const MouseEvent&) override;
  530. /** @internal */
  531. void mouseDrag (const MouseEvent&) override;
  532. /** @internal */
  533. void mouseDoubleClick (const MouseEvent&) override;
  534. /** @internal */
  535. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
  536. /** @internal */
  537. bool keyPressed (const KeyPress&) override;
  538. /** @internal */
  539. bool keyStateChanged (bool) override;
  540. /** @internal */
  541. void focusGained (FocusChangeType) override;
  542. /** @internal */
  543. void focusLost (FocusChangeType) override;
  544. /** @internal */
  545. void resized() override;
  546. /** @internal */
  547. void enablementChanged() override;
  548. /** @internal */
  549. void lookAndFeelChanged() override;
  550. /** @internal */
  551. void parentHierarchyChanged() override;
  552. /** @internal */
  553. bool isTextInputActive() const override;
  554. /** @internal */
  555. void setTemporaryUnderlining (const Array<Range<int>>&) override;
  556. /** @internal */
  557. VirtualKeyboardType getKeyboardType() override { return keyboardType; }
  558. protected:
  559. //==============================================================================
  560. /** Scrolls the minimum distance needed to get the caret into view. */
  561. void scrollToMakeSureCursorIsVisible();
  562. /** Used internally to dispatch a text-change message. */
  563. void textChanged();
  564. /** Begins a new transaction in the UndoManager. */
  565. void newTransaction();
  566. /** Can be overridden to intercept return key presses directly */
  567. virtual void returnPressed();
  568. /** Can be overridden to intercept escape key presses directly */
  569. virtual void escapePressed();
  570. private:
  571. //==============================================================================
  572. JUCE_PUBLIC_IN_DLL_BUILD (class UniformTextSection)
  573. struct Iterator;
  574. struct TextHolderComponent;
  575. struct TextEditorViewport;
  576. struct InsertAction;
  577. struct RemoveAction;
  578. std::unique_ptr<Viewport> viewport;
  579. TextHolderComponent* textHolder;
  580. BorderSize<int> borderSize { 1, 1, 1, 3 };
  581. Justification justification { Justification::topLeft };
  582. bool readOnly = false;
  583. bool caretVisible = true;
  584. bool multiline = false;
  585. bool wordWrap = false;
  586. bool returnKeyStartsNewLine = false;
  587. bool popupMenuEnabled = true;
  588. bool selectAllTextWhenFocused = false;
  589. bool scrollbarVisible = true;
  590. bool wasFocused = false;
  591. bool keepCaretOnScreen = true;
  592. bool tabKeyUsed = false;
  593. bool menuActive = false;
  594. bool valueTextNeedsUpdating = false;
  595. bool consumeEscAndReturnKeys = true;
  596. bool underlineWhitespace = true;
  597. UndoManager undoManager;
  598. std::unique_ptr<CaretComponent> caret;
  599. Range<int> selection;
  600. int leftIndent = 4, topIndent = 4;
  601. unsigned int lastTransactionTime = 0;
  602. Font currentFont { 14.0f };
  603. mutable int totalNumChars = 0;
  604. int caretPosition = 0;
  605. OwnedArray<UniformTextSection> sections;
  606. String textToShowWhenEmpty;
  607. Colour colourForTextWhenEmpty;
  608. juce_wchar passwordCharacter;
  609. OptionalScopedPointer<InputFilter> inputFilter;
  610. Value textValue;
  611. VirtualKeyboardType keyboardType = TextInputTarget::textKeyboard;
  612. float lineSpacing = 1.0f;
  613. enum DragType
  614. {
  615. notDragging,
  616. draggingSelectionStart,
  617. draggingSelectionEnd
  618. };
  619. DragType dragType = notDragging;
  620. ListenerList<Listener> listeners;
  621. Array<Range<int>> underlinedSections;
  622. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override;
  623. void moveCaret (int newCaretPos);
  624. void moveCaretTo (int newPosition, bool isSelecting);
  625. void recreateCaret();
  626. void handleCommandMessage (int) override;
  627. void coalesceSimilarSections();
  628. void splitSection (int sectionIndex, int charToSplitAt);
  629. void clearInternal (UndoManager*);
  630. void insert (const String&, int insertIndex, const Font&, Colour, UndoManager*, int newCaretPos);
  631. void reinsert (int insertIndex, const OwnedArray<UniformTextSection>&);
  632. void remove (Range<int>, UndoManager*, int caretPositionToMoveTo);
  633. void getCharPosition (int index, Point<float>&, float& lineHeight) const;
  634. Rectangle<float> getCaretRectangleFloat() const;
  635. void updateCaretPosition();
  636. void updateValueFromText();
  637. void textWasChangedByValue();
  638. int indexAtPosition (float x, float y) const;
  639. int findWordBreakAfter (int position) const;
  640. int findWordBreakBefore (int position) const;
  641. bool moveCaretWithTransaction (int newPos, bool selecting);
  642. void drawContent (Graphics&);
  643. void checkLayout();
  644. int getWordWrapWidth() const;
  645. int getMaximumTextWidth() const;
  646. int getMaximumTextHeight() const;
  647. void timerCallbackInt();
  648. void checkFocus();
  649. void repaintText (Range<int>);
  650. void scrollByLines (int deltaLines);
  651. bool undoOrRedo (bool shouldUndo);
  652. UndoManager* getUndoManager() noexcept;
  653. void setSelection (Range<int>) noexcept;
  654. Point<int> getTextOffset() const noexcept;
  655. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor)
  656. };
  657. } // namespace juce