TGUI 1.13
Loading...
Searching...
No Matches
EditBox.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_EDIT_BOX_HPP
26#define TGUI_EDIT_BOX_HPP
27
28#include <TGUI/Rect.hpp>
29#include <TGUI/Renderers/EditBoxRenderer.hpp>
30#include <TGUI/Text.hpp>
31#include <TGUI/Widgets/ClickableWidget.hpp>
32
33#include <regex>
34
36
37namespace tgui
38{
45 class TGUI_API EditBox : public ClickableWidget
46 {
47 public:
48 using Ptr = std::shared_ptr<EditBox>;
49 using ConstPtr = std::shared_ptr<const EditBox>;
50
51 static constexpr char StaticWidgetType[] = "EditBox";
52
56 using Alignment TGUI_DEPRECATED("Use tgui::HorizontalAlignment instead") = HorizontalAlignment;
57
61 struct Validator
62 {
63 static TGUI_API const char32_t* All;
64 static TGUI_API const char32_t* Int;
65 static TGUI_API const char32_t* UInt;
66 static TGUI_API const char32_t* Float;
67 };
68
76 explicit EditBox(const char* typeName = StaticWidgetType, bool initRenderer = true);
77
83 [[nodiscard]] static EditBox::Ptr create();
84
92 [[nodiscard]] static EditBox::Ptr copy(const EditBox::ConstPtr& editBox);
93
98 [[nodiscard]] EditBoxRenderer* getSharedRenderer() override;
99 [[nodiscard]] const EditBoxRenderer* getSharedRenderer() const override;
100
106 [[nodiscard]] EditBoxRenderer* getRenderer() override;
107
113 void setSize(const Layout2d& size) override;
114 using Widget::setSize;
115
123 void setEnabled(bool enabled) override;
124
137 void setText(const String& text);
138
144 [[nodiscard]] const String& getText() const;
145
153 void setDefaultText(const String& text);
154
162 [[nodiscard]] const String& getDefaultText() const;
163
172 void selectText(std::size_t start = 0, std::size_t length = String::npos);
173
179 [[nodiscard]] String getSelectedText() const;
180
192 void setPasswordCharacter(char32_t passwordChar);
193
200 [[nodiscard]] char32_t getPasswordCharacter() const;
201
209 void setMaximumCharacters(unsigned int maxChars);
210
219 [[nodiscard]] unsigned int getMaximumCharacters() const;
220
227
233 [[nodiscard]] HorizontalAlignment getAlignment() const;
234
235#ifndef TGUI_REMOVE_DEPRECATED_CODE
244 TGUI_DEPRECATED("Use setTextWidthLimited instead") void limitTextWidth(bool limitWidth = true);
245#endif
246
257 void setTextWidthLimited(bool limitWidth);
258
264 [[nodiscard]] bool isTextWidthLimited() const;
265
274 void setReadOnly(bool readOnly = true);
275
284 [[nodiscard]] bool isReadOnly() const;
285
291 void setCaretPosition(std::size_t charactersBeforeCaret);
292
298 [[nodiscard]] std::size_t getCaretPosition() const;
299
316 bool setInputValidator(const String& regex = U".*");
317
323 [[nodiscard]] const String& getInputValidator() const;
324
332 void setSuffix(const String& suffix);
333
339 [[nodiscard]] const String& getSuffix() const;
340
349 void setFocused(bool focused) override;
350
355 [[nodiscard]] bool isMouseOnWidget(Vector2f pos) const override;
356
360 bool leftMousePressed(Vector2f pos) override;
361
365 void mouseMoved(Vector2f pos) override;
366
370 void keyPressed(const Event::KeyEvent& event) override;
371
381 bool canHandleKeyPress(const Event::KeyEvent& event) override;
382
386 void textEntered(char32_t key) override;
387
394 void draw(BackendRenderTarget& target, RenderStates states) const override;
395
397
398 protected:
408 [[nodiscard]] Signal& getSignal(String signalName) override;
409
415 void rendererChanged(const String& property) override;
416
420 [[nodiscard]] std::unique_ptr<DataIO::Node> save(SavingRenderersMap& renderers) const override;
421
425 void load(const std::unique_ptr<DataIO::Node>& node, const LoadingRenderersMap& renderers) override;
426
430 void updateTextSize() override;
431
433 // Returns the total width that the text is going to take
435 [[nodiscard]] float getFullTextWidth() const;
436
438 // Returns the size without the borders
440 [[nodiscard]] Vector2f getInnerSize() const;
441
443 // Returns the width of the edit box minus the padding.
445 [[nodiscard]] float getVisibleEditBoxWidth() const;
446
448 // This function will search after which character the caret should be placed. It will not change the caret position.
450 [[nodiscard]] std::size_t findCaretPosition(float posX);
451
453 // Removes the selected characters. This function is called when pressing backspace, delete or a letter while there were
454 // some characters selected.
456 void deleteSelectedCharacters();
457
459 // Recalculates the position of the texts.
461 void recalculateTextPositions();
462
464 // Updates the internal texts after SelStart or SelEnd changed.
466 void updateSelection();
467
469 // Update the color of the Text objects
471 void updateTextColor();
472
474 // This function is called every frame with the time passed since the last frame.
476 bool updateTime(Duration elapsedTime) override;
477
479 // Makes a copy of the widget
481 [[nodiscard]] Widget::Ptr clone() const override;
482
484 // Updates m_selEnd with a new value and emits the onCaretPositionChange signal
485 // @param newValue the value to assign to m_selEnd.
487 void updateSelEnd(std::size_t newValue);
488
494 void emitReturnOrUnfocus(const String& text);
495
497
498 private:
500 // Handles "Ctrl+Backspace" key press (or equivalent on macOS)
502 void deleteWordLeft();
503
505 // Handles "Ctrl+Delete" key press (or equivalent on macOS)
507 void deleteWordRight();
508
510 // Handles "Backspace" key press (when Ctrl isn't being pressed, otherwise deleteWordLeft is called)
512 void backspaceKeyPressed();
513
515 // Handles "Delete" key press (when Ctrl isn't being pressed, otherwise deleteWordRight is called)
517 void deleteKeyPressed();
518
520 // Handles "Ctrl+C" key press (or equivalent on macOS)
522 void copySelectedTextToClipboard();
523
525 // Handles "Ctrl+X" key press (or equivalent on macOS)
527 void cutSelectedTextToClipboard();
528
530 // Handles "Ctrl+V" key press (or equivalent on macOS)
532 void pasteTextFromClipboard();
533
535 // Handles "ArrowLeft" key press
537 void moveCaretLeft(bool shiftPressed);
538
540 // Handles "ArrowRight" key press
542 void moveCaretRight(bool shiftPressed);
543
545 // Handles "Ctrl+ArrowLeft" key press (or equivalent on macOS)
547 void moveCaretWordBegin();
548
550 // Handles "Ctrl+ArrowRight" key press (or equivalent on macOS)
552 void moveCaretWordEnd();
553
555
556 public:
557 SignalString onTextChange = {"TextChanged"};
558 SignalString onReturnKeyPress = {"ReturnKeyPressed"};
560 "ReturnOrUnfocused"};
562 "CaretPositionChanged"};
563
565
566 protected:
567 // Is the caret visible or not?
568 bool m_caretVisible = true;
569
570 // When this boolean is true then you can no longer add text when the EditBox is full.
571 // Changing it to false will allow you to scroll the text (default).
572 // You can change the boolean with the setTextWidthLimited(bool) function.
573 bool m_limitTextWidth = false;
574
575 bool m_readOnly = false;
576
577 // The text inside the edit box
578 String m_text;
579 String m_displayedText; // Same as m_text unless a password char is set
580
581 String m_regexString = U".*";
582 std::wregex m_regex;
583
584 // The text alignment
586
587 // The selection
588 std::size_t m_selChars = 0;
589 std::size_t m_selStart = 0;
590 std::size_t m_selEnd = 0;
591
592 // The password character
593 char32_t m_passwordChar = '\0';
594
595 // The maximum allowed characters.
596 // Zero by default, meaning no limit.
597 unsigned int m_maxChars = 0;
598
599 // When the text width is not limited, you can scroll the edit box and only a part will be visible.
600 unsigned int m_textCropPosition = 0;
601
602 // The rectangle behind the selected text
603 FloatRect m_selectedTextBackground;
604
605 // The blinking caret
606 FloatRect m_caret = {0, 0, 1, 0};
607
608 // Is there a possibility that the user is going to double click?
609 bool m_possibleDoubleClick = false;
610
611 // We need three texts for drawing + one for the default text + one more for calculations.
612 Text m_textBeforeSelection;
613 Text m_textSelection;
614 Text m_textAfterSelection;
615 Text m_defaultText;
616 Text m_textFull;
617 Text m_textSuffix;
618
619 Sprite m_sprite;
620 Sprite m_spriteHover;
621 Sprite m_spriteDisabled;
622 Sprite m_spriteFocused;
623
624 // Cached renderer properties
625 Borders m_bordersCached;
626 Padding m_paddingCached;
627 Color m_borderColorCached;
628 Color m_borderColorHoverCached;
629 Color m_borderColorDisabledCached;
630 Color m_borderColorFocusedCached;
631 Color m_backgroundColorCached;
632 Color m_backgroundColorHoverCached;
633 Color m_backgroundColorDisabledCached;
634 Color m_backgroundColorFocusedCached;
635 Color m_caretColorCached;
636 Color m_caretColorHoverCached;
637 Color m_caretColorFocusedCached;
638 Color m_selectedTextBackgroundColorCached;
639 float m_roundedBorderRadiusCached = 0;
640
642
643 private:
644 // Used to prevent emitting onReturnOrUnfocus twice when unfocusing the edit box inside the callback function.
645 bool m_onReturnOrUnfocusEmitted = false;
646 };
647} // namespace tgui
648
649#endif // TGUI_EDIT_BOX_HPP
Base class for render targets.
Definition BackendRenderTarget.hpp:46
Wrapper for durations.
Definition Duration.hpp:52
Definition EditBoxRenderer.hpp:35
void setFocused(bool focused) override
Focus or unfocus the widget.
static EditBox::Ptr create()
Creates a new edit box widget.
SignalString onReturnOrUnfocus
The return key was pressed or the edit box was unfocused. Optional parameter: text in the edit box.
Definition EditBox.hpp:559
void emitReturnOrUnfocus(const String &text)
Emits the onReturnOrUnfocus signal.
void setReadOnly(bool readOnly=true)
Makes the edit box read-only or make it writable again.
SignalTyped< std::size_t > onCaretPositionChange
The caret's position was changed. Optional parameter: new caret position.
Definition EditBox.hpp:561
const String & getText() const
Returns the text inside the edit box. This text is not affected by the password character.
void selectText(std::size_t start=0, std::size_t length=String::npos)
Selects text in the edit box.
void setCaretPosition(std::size_t charactersBeforeCaret)
Sets the blinking caret to after a specific character.
bool isMouseOnWidget(Vector2f pos) const override
Returns whether the mouse position (which is relative to the parent widget) lies on top of the widget...
Widget::Ptr clone() const override
Makes a copy of the widget if you don't know its exact type.
void rendererChanged(const String &property) override
Function called when one of the properties of the renderer is changed.
SignalString onReturnKeyPress
The return key was pressed. Optional parameter: text in the edit box.
Definition EditBox.hpp:558
bool isTextWidthLimited() const
Checks if the text width is limited to the size of the edit box.
void setMaximumCharacters(unsigned int maxChars)
Changes the character limit.
void updateTextSize() override
Called when the text size is changed (either by setTextSize or via the renderer).
void setAlignment(HorizontalAlignment alignment)
Changes the text alignment.
char32_t getPasswordCharacter() const
Returns the password character.
void setText(const String &text)
Changes the text of the editbox.
const String & getInputValidator() const
Returns the regex to which the text is matched.
SignalString onTextChange
The text was changed. Optional parameter: new text.
Definition EditBox.hpp:557
void limitTextWidth(bool limitWidth=true)
Should the text width be limited or should you be able to type even if the edit box is full?
std::size_t getCaretPosition() const
Returns after which character the blinking cursor is currently located.
void draw(BackendRenderTarget &target, RenderStates states) const override
Draw the widget to a render target.
bool setInputValidator(const String &regex=U".*")
Defines how the text input should look like.
HorizontalAlignment Alignment
The text alignment.
Definition EditBox.hpp:56
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.
std::shared_ptr< const EditBox > ConstPtr
Shared constant widget pointer.
Definition EditBox.hpp:49
EditBoxRenderer * getSharedRenderer() override
Returns the renderer, which gives access to functions that determine how the widget is displayed.
unsigned int getMaximumCharacters() const
Returns the character limit.
void setSuffix(const String &suffix)
Places a suffix at the right side of the edit box.
String getSelectedText() const
Returns the text that you currently have selected. This text is not affected by the password characte...
static constexpr char StaticWidgetType[]
Type name of the widget.
Definition EditBox.hpp:51
std::shared_ptr< EditBox > Ptr
Shared widget pointer.
Definition EditBox.hpp:48
HorizontalAlignment getAlignment() const
Gets the current text alignment.
const String & getSuffix() const
Returns the suffix currently displayed on the right side of the edit box.
void setTextWidthLimited(bool limitWidth)
Should the text width be limited or should you be able to type even if the edit box is full?
void setEnabled(bool enabled) override
Enables or disables the widget.
void setSize(const Layout2d &size) override
Changes the size of the edit box.
const String & getDefaultText() const
Returns the default text of the edit box. This is the text drawn when the edit box is empty.
bool canHandleKeyPress(const Event::KeyEvent &event) override
Called by the parent of the widget to check if keyPressed would process the event.
Signal & getSignal(String signalName) override
Retrieves a signal based on its name.
static EditBox::Ptr copy(const EditBox::ConstPtr &editBox)
Makes a copy of another edit box.
void setPasswordCharacter(char32_t passwordChar)
Sets a password character.
bool isReadOnly() const
Checks if the edit box read-only or writable.
void load(const std::unique_ptr< DataIO::Node > &node, const LoadingRenderersMap &renderers) override
Loads the widget from a tree of nodes.
bool leftMousePressed(Vector2f pos) override
Called by the parent when the left mouse button goes down on top of the widget.
EditBoxRenderer * getRenderer() override
Returns the renderer, which gives access to functions that determine how the widget is displayed.
void setDefaultText(const String &text)
Changes the default text of the editbox. This is the text drawn when the edit box is empty.
Class to store the position or size of a widget.
Definition Layout.hpp:320
Signal to which the user can subscribe to get callbacks from.
Definition Signal.hpp:250
Signal to which the user can subscribe to get callbacks from.
Definition Signal.hpp:59
Wrapper class to store strings.
Definition String.hpp:94
std::shared_ptr< Widget > Ptr
Shared widget pointer.
Definition Widget.hpp:85
virtual void setSize(const Layout2d &size)
Changes the size of the widget.
Namespace that contains all TGUI functions and classes.
Definition AbsoluteOrRelativeValue.hpp:37
HorizontalAlignment
The horizontal alignment.
Definition Layout.hpp:60
@ Left
Align to the left side.
Definition Layout.hpp:61
SignalTyped< const String & > SignalString
Signal with one "String" as optional unbound parameter.
Definition Signal.hpp:413
Predefined input validators.
Definition EditBox.hpp:62
static TGUI_API const char32_t * Int
Accept negative and positive integers.
Definition EditBox.hpp:64
static TGUI_API const char32_t * Float
Accept decimal numbers.
Definition EditBox.hpp:66
static TGUI_API const char32_t * UInt
Accept only positive integers.
Definition EditBox.hpp:65
static TGUI_API const char32_t * All
Accept any input.
Definition EditBox.hpp:63
KeyPressed event parameters.
Definition Event.hpp:166
States used for drawing.
Definition RenderStates.hpp:38