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.

856 lines
35KB

  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. /** Sets the type of virtual keyboard that should be displayed when this editor has
  510. focus.
  511. */
  512. void setKeyboardType (VirtualKeyboardType type) noexcept { keyboardType = type; }
  513. /** Sets the behaviour of mouse/touch interactions outside this component.
  514. If true, then presses outside of the TextEditor will dismiss the virtual keyboard.
  515. If false, then the virtual keyboard will remain onscreen for as long as the TextEditor has
  516. keyboard focus.
  517. */
  518. void setClicksOutsideDismissVirtualKeyboard (bool);
  519. /** Returns true if the editor is configured to hide the virtual keyboard when the mouse is
  520. pressed on another component.
  521. */
  522. bool getClicksOutsideDismissVirtualKeyboard() const { return clicksOutsideDismissVirtualKeyboard; }
  523. //==============================================================================
  524. /** This abstract base class is implemented by LookAndFeel classes to provide
  525. TextEditor drawing functionality.
  526. */
  527. struct JUCE_API LookAndFeelMethods
  528. {
  529. virtual ~LookAndFeelMethods() = default;
  530. virtual void fillTextEditorBackground (Graphics&, int width, int height, TextEditor&) = 0;
  531. virtual void drawTextEditorOutline (Graphics&, int width, int height, TextEditor&) = 0;
  532. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner) = 0;
  533. };
  534. //==============================================================================
  535. /** @internal */
  536. void paint (Graphics&) override;
  537. /** @internal */
  538. void paintOverChildren (Graphics&) override;
  539. /** @internal */
  540. void mouseDown (const MouseEvent&) override;
  541. /** @internal */
  542. void mouseUp (const MouseEvent&) override;
  543. /** @internal */
  544. void mouseDrag (const MouseEvent&) override;
  545. /** @internal */
  546. void mouseDoubleClick (const MouseEvent&) override;
  547. /** @internal */
  548. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
  549. /** @internal */
  550. bool keyPressed (const KeyPress&) override;
  551. /** @internal */
  552. bool keyStateChanged (bool) override;
  553. /** @internal */
  554. void focusGained (FocusChangeType) override;
  555. /** @internal */
  556. void focusLost (FocusChangeType) override;
  557. /** @internal */
  558. void resized() override;
  559. /** @internal */
  560. void enablementChanged() override;
  561. /** @internal */
  562. void lookAndFeelChanged() override;
  563. /** @internal */
  564. void parentHierarchyChanged() override;
  565. /** @internal */
  566. bool isTextInputActive() const override;
  567. /** @internal */
  568. void setTemporaryUnderlining (const Array<Range<int>>&) override;
  569. /** @internal */
  570. VirtualKeyboardType getKeyboardType() override { return keyboardType; }
  571. protected:
  572. //==============================================================================
  573. /** Scrolls the minimum distance needed to get the caret into view. */
  574. void scrollToMakeSureCursorIsVisible();
  575. /** Used internally to dispatch a text-change message. */
  576. void textChanged();
  577. /** Begins a new transaction in the UndoManager. */
  578. void newTransaction();
  579. /** Can be overridden to intercept return key presses directly */
  580. virtual void returnPressed();
  581. /** Can be overridden to intercept escape key presses directly */
  582. virtual void escapePressed();
  583. private:
  584. //==============================================================================
  585. JUCE_PUBLIC_IN_DLL_BUILD (class UniformTextSection)
  586. struct Iterator;
  587. struct TextHolderComponent;
  588. struct TextEditorViewport;
  589. struct InsertAction;
  590. struct RemoveAction;
  591. class EditorAccessibilityHandler;
  592. std::unique_ptr<Viewport> viewport;
  593. TextHolderComponent* textHolder;
  594. BorderSize<int> borderSize { 1, 1, 1, 3 };
  595. Justification justification { Justification::topLeft };
  596. bool readOnly = false;
  597. bool caretVisible = true;
  598. bool multiline = false;
  599. bool wordWrap = false;
  600. bool returnKeyStartsNewLine = false;
  601. bool popupMenuEnabled = true;
  602. bool selectAllTextWhenFocused = false;
  603. bool scrollbarVisible = true;
  604. bool wasFocused = false;
  605. bool keepCaretOnScreen = true;
  606. bool tabKeyUsed = false;
  607. bool menuActive = false;
  608. bool valueTextNeedsUpdating = false;
  609. bool consumeEscAndReturnKeys = true;
  610. bool underlineWhitespace = true;
  611. bool mouseDownInEditor = false;
  612. bool clicksOutsideDismissVirtualKeyboard = false;
  613. UndoManager undoManager;
  614. std::unique_ptr<CaretComponent> caret;
  615. Range<int> selection;
  616. int leftIndent = 4, topIndent = 4;
  617. unsigned int lastTransactionTime = 0;
  618. Font currentFont { 14.0f };
  619. mutable int totalNumChars = 0;
  620. int caretPosition = 0;
  621. OwnedArray<UniformTextSection> sections;
  622. String textToShowWhenEmpty;
  623. Colour colourForTextWhenEmpty;
  624. juce_wchar passwordCharacter;
  625. OptionalScopedPointer<InputFilter> inputFilter;
  626. Value textValue;
  627. VirtualKeyboardType keyboardType = TextInputTarget::textKeyboard;
  628. float lineSpacing = 1.0f;
  629. enum DragType
  630. {
  631. notDragging,
  632. draggingSelectionStart,
  633. draggingSelectionEnd
  634. };
  635. DragType dragType = notDragging;
  636. ListenerList<Listener> listeners;
  637. Array<Range<int>> underlinedSections;
  638. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override;
  639. void moveCaret (int newCaretPos);
  640. void moveCaretTo (int newPosition, bool isSelecting);
  641. void recreateCaret();
  642. void handleCommandMessage (int) override;
  643. void coalesceSimilarSections();
  644. void splitSection (int sectionIndex, int charToSplitAt);
  645. void clearInternal (UndoManager*);
  646. void insert (const String&, int insertIndex, const Font&, Colour, UndoManager*, int newCaretPos);
  647. void reinsert (int insertIndex, const OwnedArray<UniformTextSection>&);
  648. void remove (Range<int>, UndoManager*, int caretPositionToMoveTo);
  649. void getCharPosition (int index, Point<float>&, float& lineHeight) const;
  650. Rectangle<float> getCaretRectangleFloat() const;
  651. void updateCaretPosition();
  652. void updateValueFromText();
  653. void textWasChangedByValue();
  654. int indexAtPosition (float x, float y) const;
  655. int findWordBreakAfter (int position) const;
  656. int findWordBreakBefore (int position) const;
  657. bool moveCaretWithTransaction (int newPos, bool selecting);
  658. void drawContent (Graphics&);
  659. void checkLayout();
  660. int getWordWrapWidth() const;
  661. int getMaximumTextWidth() const;
  662. int getMaximumTextHeight() const;
  663. void timerCallbackInt();
  664. void checkFocus();
  665. void repaintText (Range<int>);
  666. void scrollByLines (int deltaLines);
  667. bool undoOrRedo (bool shouldUndo);
  668. UndoManager* getUndoManager() noexcept;
  669. void setSelection (Range<int>) noexcept;
  670. Point<int> getTextOffset() const noexcept;
  671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor)
  672. };
  673. } // namespace juce