TGUI 1.11
Loading...
Searching...
No Matches
EditBox.hpp
1
2//
3// TGUI - Texus' Graphical User Interface
4// Copyright (C) 2012-2025 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/Widgets/ClickableWidget.hpp>
29#include <TGUI/Renderers/EditBoxRenderer.hpp>
30#include <TGUI/Rect.hpp>
31#include <TGUI/Text.hpp>
32
33#include <regex>
34
36
37namespace tgui
38{
45 class TGUI_API EditBox : public ClickableWidget
46 {
47 public:
48
49 using Ptr = std::shared_ptr<EditBox>;
50 using ConstPtr = std::shared_ptr<const EditBox>;
51
52 static constexpr const char StaticWidgetType[] = "EditBox";
53
57 using Alignment TGUI_DEPRECATED("Use tgui::HorizontalAlignment instead") = HorizontalAlignment;
58
62 struct Validator
63 {
64 static TGUI_API const char32_t* All;
65 static TGUI_API const char32_t* Int;
66 static TGUI_API const char32_t* UInt;
67 static TGUI_API const char32_t* Float;
68 };
69
77 EditBox(const char* typeName = StaticWidgetType, bool initRenderer = true);
78
84 TGUI_NODISCARD static EditBox::Ptr create();
85
93 TGUI_NODISCARD static EditBox::Ptr copy(const EditBox::ConstPtr& editBox);
94
99 TGUI_NODISCARD EditBoxRenderer* getSharedRenderer() override;
100 TGUI_NODISCARD const EditBoxRenderer* getSharedRenderer() const override;
101
107 TGUI_NODISCARD EditBoxRenderer* getRenderer() override;
108
114 void setSize(const Layout2d& size) override;
115 using Widget::setSize;
116
124 void setEnabled(bool enabled) override;
125
138 void setText(const String& text);
139
145 TGUI_NODISCARD const String& getText() const;
146
154 void setDefaultText(const String& text);
155
163 TGUI_NODISCARD const String& getDefaultText() const;
164
173 void selectText(std::size_t start = 0, std::size_t length = String::npos);
174
180 TGUI_NODISCARD String getSelectedText() const;
181
193 void setPasswordCharacter(char32_t passwordChar);
194
201 TGUI_NODISCARD char32_t getPasswordCharacter() const;
202
210 void setMaximumCharacters(unsigned int maxChars);
211
220 TGUI_NODISCARD unsigned int getMaximumCharacters() const;
221
228
234 TGUI_NODISCARD HorizontalAlignment getAlignment() const;
235
236#ifndef TGUI_REMOVE_DEPRECATED_CODE
245 TGUI_DEPRECATED("Use setTextWidthLimited instead") void limitTextWidth(bool limitWidth = true);
246#endif
247
258 void setTextWidthLimited(bool limitWidth);
259
265 TGUI_NODISCARD bool isTextWidthLimited() const;
266
275 void setReadOnly(bool readOnly = true);
276
285 TGUI_NODISCARD bool isReadOnly() const;
286
292 void setCaretPosition(std::size_t charactersBeforeCaret);
293
299 TGUI_NODISCARD std::size_t getCaretPosition() const;
300
317 bool setInputValidator(const String& regex = U".*");
318
324 TGUI_NODISCARD const String& getInputValidator() const;
325
333 void setSuffix(const String& suffix);
334
340 TGUI_NODISCARD const String& getSuffix() const;
341
350 void setFocused(bool focused) override;
351
356 TGUI_NODISCARD bool isMouseOnWidget(Vector2f pos) const override;
357
361 bool leftMousePressed(Vector2f pos) override;
362
366 void mouseMoved(Vector2f pos) override;
367
371 void keyPressed(const Event::KeyEvent& event) override;
372
382 bool canHandleKeyPress(const Event::KeyEvent& event) override;
383
387 void textEntered(char32_t key) override;
388
395 void draw(BackendRenderTarget& target, RenderStates states) const override;
396
398 protected:
399
409 TGUI_NODISCARD Signal& getSignal(String signalName) override;
410
416 void rendererChanged(const String& property) override;
417
421 TGUI_NODISCARD std::unique_ptr<DataIO::Node> save(SavingRenderersMap& renderers) const override;
422
426 void load(const std::unique_ptr<DataIO::Node>& node, const LoadingRenderersMap& renderers) override;
427
431 void updateTextSize() override;
432
434 // Returns the total width that the text is going to take
436 TGUI_NODISCARD float getFullTextWidth() const;
437
439 // Returns the size without the borders
441 TGUI_NODISCARD Vector2f getInnerSize() const;
442
444 // Returns the width of the edit box minus the padding.
446 TGUI_NODISCARD float getVisibleEditBoxWidth() const;
447
449 // This function will search after which character the caret should be placed. It will not change the caret position.
451 TGUI_NODISCARD std::size_t findCaretPosition(float posX);
452
454 // Removes the selected characters. This function is called when pressing backspace, delete or a letter while there were
455 // some characters selected.
457 void deleteSelectedCharacters();
458
460 // Recalculates the position of the texts.
462 void recalculateTextPositions();
463
465 // Updates the internal texts after SelStart or SelEnd changed.
467 void updateSelection();
468
470 // Update the color of the Text objects
472 void updateTextColor();
473
475 // This function is called every frame with the time passed since the last frame.
477 bool updateTime(Duration elapsedTime) override;
478
480 // Makes a copy of the widget
482 TGUI_NODISCARD Widget::Ptr clone() const override;
483
485 // Updates m_selEnd with a new value and emits the onCaretPositionChange signal
486 // @param newValue the value to assign to m_selEnd.
488 void updateSelEnd(const std::size_t newValue);
489
495 void emitReturnOrUnfocus(const String& text);
496
498 private:
499
501 // Handles "Ctrl+Backspace" key press (or equivalent on macOS)
503 void deleteWordLeft();
504
506 // Handles "Ctrl+Delete" key press (or equivalent on macOS)
508 void deleteWordRight();
509
511 // Handles "Backspace" key press (when Ctrl isn't being pressed, otherwise deleteWordLeft is called)
513 void backspaceKeyPressed();
514
516 // Handles "Delete" key press (when Ctrl isn't being pressed, otherwise deleteWordRight is called)
518 void deleteKeyPressed();
519
521 // Handles "Ctrl+C" key press (or equivalent on macOS)
523 void copySelectedTextToClipboard();
524
526 // Handles "Ctrl+X" key press (or equivalent on macOS)
528 void cutSelectedTextToClipboard();
529
531 // Handles "Ctrl+V" key press (or equivalent on macOS)
533 void pasteTextFromClipboard();
534
536 // Handles "ArrowLeft" key press
538 void moveCaretLeft(bool shiftPressed);
539
541 // Handles "ArrowRight" key press
543 void moveCaretRight(bool shiftPressed);
544
546 // Handles "Ctrl+ArrowLeft" key press (or equivalent on macOS)
548 void moveCaretWordBegin();
549
551 // Handles "Ctrl+ArrowRight" key press (or equivalent on macOS)
553 void moveCaretWordEnd();
554
556 public:
557
558 SignalString onTextChange = {"TextChanged"};
559 SignalString onReturnKeyPress = {"ReturnKeyPressed"};
560 SignalString onReturnOrUnfocus = {"ReturnOrUnfocused"};
562
564 protected:
565
566 // Is the caret visible or not?
567 bool m_caretVisible = true;
568
569 // When this boolean is true then you can no longer add text when the EditBox is full.
570 // Changing it to false will allow you to scroll the text (default).
571 // You can change the boolean with the setTextWidthLimited(bool) function.
572 bool m_limitTextWidth = false;
573
574 bool m_readOnly = false;
575
576 // The text inside the edit box
577 String m_text;
578 String m_displayedText; // Same as m_text unless a password char is set
579
580 String m_regexString = U".*";
581 std::wregex m_regex;
582
583 // The text alignment
585
586 // The selection
587 std::size_t m_selChars = 0;
588 std::size_t m_selStart = 0;
589 std::size_t m_selEnd = 0;
590
591 // The password character
592 char32_t m_passwordChar = '\0';
593
594 // The maximum allowed characters.
595 // Zero by default, meaning no limit.
596 unsigned int m_maxChars = 0;
597
598 // When the text width is not limited, you can scroll the edit box and only a part will be visible.
599 unsigned int m_textCropPosition = 0;
600
601 // The rectangle behind the selected text
602 FloatRect m_selectedTextBackground;
603
604 // The blinking caret
605 FloatRect m_caret = {0, 0, 1, 0};
606
607 // Is there a possibility that the user is going to double click?
608 bool m_possibleDoubleClick = false;
609
610 // We need three texts for drawing + one for the default text + one more for calculations.
611 Text m_textBeforeSelection;
612 Text m_textSelection;
613 Text m_textAfterSelection;
614 Text m_defaultText;
615 Text m_textFull;
616 Text m_textSuffix;
617
618 Sprite m_sprite;
619 Sprite m_spriteHover;
620 Sprite m_spriteDisabled;
621 Sprite m_spriteFocused;
622
623 // Cached renderer properties
624 Borders m_bordersCached;
625 Padding m_paddingCached;
626 Color m_borderColorCached;
627 Color m_borderColorHoverCached;
628 Color m_borderColorDisabledCached;
629 Color m_borderColorFocusedCached;
630 Color m_backgroundColorCached;
631 Color m_backgroundColorHoverCached;
632 Color m_backgroundColorDisabledCached;
633 Color m_backgroundColorFocusedCached;
634 Color m_caretColorCached;
635 Color m_caretColorHoverCached;
636 Color m_caretColorFocusedCached;
637 Color m_selectedTextBackgroundColorCached;
638 float m_roundedBorderRadiusCached = 0;
639
641 private:
642
643 // Used to prevent emitting onReturnOrUnfocus twice when unfocusing the edit box inside the callback function.
644 bool m_onReturnOrUnfocusEmitted = false;
645
647 };
648
650}
651
653
654#endif // TGUI_EDIT_BOX_HPP
Base class for render targets.
Definition BackendRenderTarget.hpp:46
Wrapper for durations.
Definition Duration.hpp:53
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:560
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:559
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:558
static constexpr const char StaticWidgetType[]
Type name of the widget.
Definition EditBox.hpp:52
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:57
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:50
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...
std::shared_ptr< EditBox > Ptr
Shared widget pointer.
Definition EditBox.hpp:49
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:321
Signal to which the user can subscribe to get callbacks from.
Definition Signal.hpp:269
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:87
virtual void setSize(const Layout2d &size)
Changes the size of the widget.
Namespace that contains all TGUI functions and classes.
Definition AbsoluteOrRelativeValue.hpp:36
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:426
Predefined input validators.
Definition EditBox.hpp:63
static TGUI_API const char32_t * Int
Accept negative and positive integers.
Definition EditBox.hpp:65
static TGUI_API const char32_t * Float
Accept decimal numbers.
Definition EditBox.hpp:67
static TGUI_API const char32_t * UInt
Accept only positive integers.
Definition EditBox.hpp:66
static TGUI_API const char32_t * All
Accept any input.
Definition EditBox.hpp:64
KeyPressed event parameters.
Definition Event.hpp:168
States used for drawing.
Definition RenderStates.hpp:38