TGUI 1.13
Loading...
Searching...
No Matches
TextArea.hpp
1
2//
3// TGUI - Texus' Graphical User Interface
4// Copyright (C) 2012-2026 Bruno Van de Velde (vdv_b@tgui.eu)
5//
6// This software is provided 'as-is', without any express or implied warranty.
7// In no event will the authors be held liable for any damages arising from the use of this software.
8//
9// Permission is granted to anyone to use this software for any purpose,
10// including commercial applications, and to alter it and redistribute it freely,
11// subject to the following restrictions:
12//
13// 1. The origin of this software must not be misrepresented;
14// you must not claim that you wrote the original software.
15// If you use this software in a product, an acknowledgment
16// in the product documentation would be appreciated but is not required.
17//
18// 2. Altered source versions must be plainly marked as such,
19// and must not be misrepresented as being the original software.
20//
21// 3. This notice may not be removed or altered from any source distribution.
22//
24
25#ifndef TGUI_TEXT_AREA_HPP
26#define TGUI_TEXT_AREA_HPP
27
28#include <TGUI/Renderers/TextAreaRenderer.hpp>
29#include <TGUI/Text.hpp>
30#include <TGUI/Widgets/Scrollbar.hpp>
31
33
34namespace tgui
35{
42 class TGUI_API TextArea : public Widget, public DualScrollbarChildInterface
43 {
44 public:
45 using Ptr = std::shared_ptr<TextArea>;
46 using ConstPtr = std::shared_ptr<const TextArea>;
47
48 static constexpr char StaticWidgetType[] = "TextArea";
49
57 explicit TextArea(const char* typeName = StaticWidgetType, bool initRenderer = true);
58
64 [[nodiscard]] static TextArea::Ptr create();
65
73 [[nodiscard]] static TextArea::Ptr copy(const TextArea::ConstPtr& textArea);
74
79 [[nodiscard]] TextAreaRenderer* getSharedRenderer() override;
80 [[nodiscard]] const TextAreaRenderer* getSharedRenderer() const override;
81
87 [[nodiscard]] TextAreaRenderer* getRenderer() override;
88
96 void setSize(const Layout2d& size) override;
97 using Widget::setSize;
98
104 void setText(String text);
105
111 void addText(String text);
112
118 [[nodiscard]] String getText() const;
119
125 void setDefaultText(const String& text);
126
132 [[nodiscard]] const String& getDefaultText() const;
133
140 void setSelectedText(std::size_t selectionStartIndex, std::size_t selectionEndIndex);
141
147 [[nodiscard]] String getSelectedText() const;
148
159 [[nodiscard]] std::size_t getSelectionStart() const;
160
171 [[nodiscard]] std::size_t getSelectionEnd() const;
172
181 void setMaximumCharacters(std::size_t maxChars = 0);
182
191 [[nodiscard]] std::size_t getMaximumCharacters() const;
192
204 void setTabString(String tabText);
205
213 [[nodiscard]] String getTabString() const;
214
222 void setCaretPosition(std::size_t charactersBeforeCaret);
223
231 [[nodiscard]] std::size_t getCaretPosition() const;
232
244 [[nodiscard]] std::size_t getCaretLine() const;
245
257 [[nodiscard]] std::size_t getCaretColumn() const;
258
267 void setReadOnly(bool readOnly = true);
268
277 [[nodiscard]] bool isReadOnly() const;
278
285 TGUI_DEPRECATED("Use getVerticalScrollbar->setPolicy(policy) instead")
287
294 TGUI_DEPRECATED("Use getVerticalScrollbar->getPolicy() instead")
295 [[nodiscard]] Scrollbar::Policy getVerticalScrollbarPolicy() const;
296
303 TGUI_DEPRECATED("Use getHorizontalScrollbar->setPolicy(policy) instead")
305
312 TGUI_DEPRECATED("Use getHorizontalScrollbar->getPolicy() instead")
313 [[nodiscard]] Scrollbar::Policy getHorizontalScrollbarPolicy() const;
314
322 [[nodiscard]] std::size_t getLinesCount() const;
323
332 void setFocused(bool focused) override;
333
345 void enableMonospacedFontOptimization(bool enable = true);
346
352 TGUI_DEPRECATED("Use getVerticalScrollbar->setValue(value) instead") void setVerticalScrollbarValue(unsigned int value);
353
359 TGUI_DEPRECATED("Use getVerticalScrollbar->getValue() instead")
360 [[nodiscard]] unsigned int getVerticalScrollbarValue() const;
361
369 TGUI_DEPRECATED("Use getVerticalScrollbar->getMaxValue() instead")
370 [[nodiscard]] unsigned int getVerticalScrollbarMaxValue() const;
371
377 TGUI_DEPRECATED("Use getHorizontalScrollbar->setValue(value) instead")
378 void setHorizontalScrollbarValue(unsigned int value);
379
385 TGUI_DEPRECATED("Use getHorizontalScrollbar->getValue() instead")
386 [[nodiscard]] unsigned int getHorizontalScrollbarValue() const;
387
395 TGUI_DEPRECATED("Use getHorizontalScrollbar->getMaxValue() instead")
396 [[nodiscard]] unsigned int getHorizontalScrollbarMaxValue() const;
397
403 [[nodiscard]] bool isMouseOnWidget(Vector2f pos) const override;
404
408 bool leftMousePressed(Vector2f pos) override;
409
413 void leftMouseReleased(Vector2f pos) override;
414
418 void mouseMoved(Vector2f pos) override;
419
423 void keyPressed(const Event::KeyEvent& event) override;
424
434 bool canHandleKeyPress(const Event::KeyEvent& event) override;
435
439 void textEntered(char32_t key) override;
440
444 bool scrolled(float delta, Vector2f pos, bool touch) override;
445
449 void mouseNoLongerOnWidget() override;
450
454 void leftMouseButtonNoLongerDown() override;
455
457
458 protected:
460 // This function will search after which character the caret should be placed. It will not change the caret position.
462 [[nodiscard]] Vector2<std::size_t> findCaretPosition(Vector2f position) const;
463
465 // Gets the index of either m_selStart or m_selEnd
467 [[nodiscard]] std::size_t getIndexOfSelectionPos(Vector2<std::size_t> selectionPos) const;
468
470 // Removes the selected characters. This function is called when pressing backspace, delete or a letter while there were
471 // some characters selected.
473 void deleteSelectedCharacters();
474
476 // Inserts text at the current caret position.
477 // If the given string exceeds the maximum character limit,
478 // excess characters from the right side of the string will not be inserted.
480 void insertTextAtCaretPosition(String text);
481
483 // Rearrange the text inside the text area (by using word wrap).
485 void rearrangeText(bool keepSelection, bool emitCaretChangedPosition = true);
486
488 // Updates the physical size of the scrollbars, as well as the viewport size.
490 void updateScrollbars();
491
493 // This function will split the text into five pieces so that the text can be easily drawn.
495 void updateSelectionTexts();
496
498 // Handles "Ctrl+Backspace" key press (or equivalent on macOS)
500 void deleteWordLeft();
501
503 // Handles "Ctrl+Delete" key press (or equivalent on macOS)
505 void deleteWordRight();
506
508 // Handles "Backspace" key press (when Ctrl isn't being pressed, otherwise deleteWordLeft is called)
510 void backspaceKeyPressed();
511
513 // Handles "Delete" key press (when Ctrl isn't being pressed, otherwise deleteWordRight is called)
515 void deleteKeyPressed();
516
518 // Handles "Ctrl+C" key press (or equivalent on macOS)
520 void copySelectedTextToClipboard();
521
523 // Handles "Ctrl+X" key press (or equivalent on macOS)
525 void cutSelectedTextToClipboard();
526
528 // Handles "Ctrl+V" key press (or equivalent on macOS)
530 void pasteTextFromClipboard();
531
533 // Handles "Ctrl+A" key press (or equivalent on macOS)
535 void selectAllText();
536
538 // Handles "PageUp" key press
540 void moveCaretPageUp();
541
543 // Handles "PageDown" key press
545 void moveCaretPageDown();
546
548 // Handles "ArrowLeft" key press
550 void moveCaretLeft(bool shiftPressed);
551
553 // Handles "ArrowRight" key press
555 void moveCaretRight(bool shiftPressed);
556
558 // Handles "Ctrl+ArrowLeft" key press (or equivalent on macOS)
560 void moveCaretWordBegin();
561
563 // Handles "Ctrl+ArrowRight" key press (or equivalent on macOS)
565 void moveCaretWordEnd();
566
573 void draw(BackendRenderTarget& target, RenderStates states) const override;
574
576
577 private:
579 // Implementation of setCaretPosition() that either updates or retains the m_selEnd value.
581 void setCaretPositionImpl(std::size_t charactersBeforeCaret, bool selEndNeedUpdate, bool emitCaretChangedPosition);
582
584
585 protected:
587 // Returns the size without the borders
589 [[nodiscard]] Vector2f getInnerSize() const;
590
592 // This function is called every frame with the time passed since the last frame.
594 bool updateTime(Duration elapsedTime) override;
595
597 // Recalculates the positions of the contents of the text area.
599 void recalculatePositions();
600
602 // Recalculates which lines are currently visible.
604 void recalculateVisibleLines();
605
615 [[nodiscard]] Signal& getSignal(String signalName) override;
616
622 void rendererChanged(const String& property) override;
623
627 [[nodiscard]] std::unique_ptr<DataIO::Node> save(SavingRenderersMap& renderers) const override;
628
632 void load(const std::unique_ptr<DataIO::Node>& node, const LoadingRenderersMap& renderers) override;
633
637 void updateTextSize() override;
638
645 void scrollbarPolicyChanged(Orientation orientation) override;
646
648 // Makes a copy of the widget
650 [[nodiscard]] Widget::Ptr clone() const override;
651
653 // Updates m_selEnd with a new value and emits the onCaretPositionChange signal
654 // @param newValue the value to assign to m_selEnd.
656 void updateSelEnd(const Vector2<std::size_t>& newValue);
657
659
660 public:
661 SignalString onTextChange = {"TextChanged"};
662 Signal onSelectionChange = {"SelectionChanged"};
663 Signal onCaretPositionChange = {"CaretPositionChanged"};
664
666
667 protected:
668 String m_text;
669 float m_lineHeight = 24;
670
671 // The width of the largest line
672 float m_maxLineWidth = 0;
673
674 std::vector<String> m_lines;
675
676 // The maximum characters (0 by default, which means no limit)
677 std::size_t m_maxChars = 0;
678
679 // What is known about the visible lines?
680 std::size_t m_topLine = 1;
681 std::size_t m_visibleLines = 1;
682
683 // Information about the selection
684 Vector2<std::size_t> m_selStart;
685 Vector2<std::size_t> m_selEnd;
686 std::pair<Vector2<std::size_t>, Vector2<std::size_t>> m_lastSelection;
687
688 // Information about the caret
689 Vector2f m_caretPosition;
690 bool m_caretVisible = true;
691
692 // The text to insert when Tab is pressed
693 String m_tabText = U"\t";
694
695 Text m_textBeforeSelection;
696 Text m_textSelection1;
697 Text m_textSelection2;
698 Text m_textAfterSelection1;
699 Text m_textAfterSelection2;
700 Text m_defaultText;
701
702 std::vector<FloatRect> m_selectionRects;
703
704 // Is there a possibility that the user is going to double click?
705 bool m_possibleDoubleClick = false;
706
707 bool m_readOnly = false;
708
709 bool m_monospacedFontOptimizationEnabled = false;
710
711 Sprite m_spriteBackground;
712
713 // Cached renderer properties
714 Borders m_bordersCached;
715 Padding m_paddingCached;
716 Color m_borderColorCached;
717 Color m_backgroundColorCached;
718 Color m_caretColorCached;
719 Color m_selectedTextBackgroundColorCached;
720 float m_caretWidthCached = 1;
721 float m_roundedBorderRadiusCached = 0;
722 };
723} // namespace tgui
724
725#endif // TGUI_TEXT_AREA_HPP
Base class for render targets.
Definition BackendRenderTarget.hpp:46
Wrapper for colors.
Definition Color.hpp:63
DualScrollbarChildInterface()
Default constructor.
Wrapper for durations.
Definition Duration.hpp:52
Class to store the position or size of a widget.
Definition Layout.hpp:320
Scrollbar widget.
Definition Scrollbar.hpp:42
Signal to which the user can subscribe to get callbacks from.
Definition Signal.hpp:59
Definition Sprite.hpp:45
Wrapper class to store strings.
Definition String.hpp:94
Definition TextAreaRenderer.hpp:35
void setTabString(String tabText)
Changes the string that is inserted when the Tab key is pressed.
Signal onCaretPositionChange
Caret position changed.
Definition TextArea.hpp:663
void setReadOnly(bool readOnly=true)
Makes the text area read-only or make it writable again.
Signal & getSignal(String signalName) override
Retrieves a signal based on its name.
void enableMonospacedFontOptimization(bool enable=true)
Changes whether an optimization is made that only works when using a monospaced font.
bool leftMousePressed(Vector2f pos) override
Called by the parent when the left mouse button goes down on top of the widget.
String getText() const
Returns the text of the text area.
void load(const std::unique_ptr< DataIO::Node > &node, const LoadingRenderersMap &renderers) override
Loads the widget from a tree of nodes.
void setFocused(bool focused) override
Focus or unfocus the widget.
const String & getDefaultText() const
Returns the default text of the text area. This is the text drawn when the text area is empty.
std::shared_ptr< const TextArea > ConstPtr
Shared constant widget pointer.
Definition TextArea.hpp:46
void setHorizontalScrollbarValue(unsigned int value)
Changes the thumb position of the horizontal scrollbar.
TextAreaRenderer * getSharedRenderer() override
Returns the renderer, which gives access to functions that determine how the widget is displayed.
bool isMouseOnWidget(Vector2f pos) const override
Returns whether the mouse position (which is relative to the parent widget) lies on top of the widget...
SignalString onTextChange
The text was changed. Optional parameter: new text.
Definition TextArea.hpp:661
void scrollbarPolicyChanged(Orientation orientation) override
Called when the policy of one of the scrollbars has been changed calling either getVerticalScrollbar(...
Scrollbar::Policy getHorizontalScrollbarPolicy() const
Returns when the horizontal scrollbar should be displayed.
std::size_t getCaretPosition() const
Returns after which character the blinking cursor is currently located.
void addText(String text)
Appends some text to the text that was already in the text area.
std::shared_ptr< TextArea > Ptr
Shared widget pointer.
Definition TextArea.hpp:45
std::size_t getSelectionEnd() const
Returns the index where the selection ends.
static TextArea::Ptr copy(const TextArea::ConstPtr &textArea)
Makes a copy of another text area.
void setText(String text)
Changes the text of the text area.
bool isReadOnly() const
Checks if the text area read-only or writable.
std::size_t getLinesCount() const
Returns the amount of lines that the text occupies in the TextArea.
unsigned int getHorizontalScrollbarValue() const
Returns the thumb position of the horizontal scrollbar.
void setMaximumCharacters(std::size_t maxChars=0)
Changes the maximum character limit.
void setCaretPosition(std::size_t charactersBeforeCaret)
Sets the blinking caret to after a specific character.
String getSelectedText() const
Returns the text that you currently have selected.
void setSelectedText(std::size_t selectionStartIndex, std::size_t selectionEndIndex)
Changes which part of the text is selected.
unsigned int getVerticalScrollbarMaxValue() const
Returns the maximum thumb position of the vertical scrollbar.
void setHorizontalScrollbarPolicy(Scrollbar::Policy policy)
Changes when the horizontal scrollbar should be displayed.
TextAreaRenderer * getRenderer() override
Returns the renderer, which gives access to functions that determine how the widget is displayed.
void setVerticalScrollbarValue(unsigned int value)
Changes the thumb position of the vertical scrollbar.
bool canHandleKeyPress(const Event::KeyEvent &event) override
Called by the parent of the widget to check if keyPressed would process the event.
Widget::Ptr clone() const override
Makes a copy of the widget if you don't know its exact type.
unsigned int getVerticalScrollbarValue() const
Returns the thumb position of the vertical scrollbar.
std::size_t getSelectionStart() const
Returns the index where the selection starts.
void rendererChanged(const String &property) override
Function called when one of the properties of the renderer is changed.
static constexpr char StaticWidgetType[]
Type name of the widget.
Definition TextArea.hpp:48
static TextArea::Ptr create()
Creates a new text area widget.
std::size_t getCaretLine() const
Returns which line the blinking cursor is currently located on.
bool scrolled(float delta, Vector2f pos, bool touch) override
Called by the parent on scroll event (either from mouse wheel of from two finger scrolling on a touch...
void draw(BackendRenderTarget &target, RenderStates states) const override
Draw the widget to a render target.
std::size_t getMaximumCharacters() const
Returns the maximum character limit.
void setDefaultText(const String &text)
Changes the default text of the text area. This is the text drawn when the text area is empty.
std::unique_ptr< DataIO::Node > save(SavingRenderersMap &renderers) const override
Saves the widget as a tree node in order to save it to a file.
unsigned int getHorizontalScrollbarMaxValue() const
Returns the maximum thumb position of the horizontal scrollbar.
void setSize(const Layout2d &size) override
Changes the size of the text area.
Scrollbar::Policy getVerticalScrollbarPolicy() const
Returns when the vertical scrollbar should be displayed.
void setVerticalScrollbarPolicy(Scrollbar::Policy policy)
Changes when the vertical scrollbar should be displayed.
String getTabString() const
Returns the string that is inserted when the Tab key is pressed.
std::size_t getCaretColumn() const
Returns which column the blinking cursor is currently located on.
void updateTextSize() override
Called when the text size is changed (either by setTextSize or via the renderer).
Signal onSelectionChange
Selected text changed.
Definition TextArea.hpp:662
Backend-independent wrapper around the backend-specific text class.
Definition Text.hpp:53
Definition Vector2.hpp:42
virtual void setSize(const Layout2d &size)
Changes the size of the widget.
Namespace that contains all TGUI functions and classes.
Definition AbsoluteOrRelativeValue.hpp:37
Orientation
Orientation of the object.
Definition Layout.hpp:50
SignalTyped< const String & > SignalString
Signal with one "String" as optional unbound parameter.
Definition Signal.hpp:413
Definition Event.hpp:36
States used for drawing.
Definition RenderStates.hpp:38