TGUI  1.6.1
Loading...
Searching...
No Matches
EditBox.hpp
1
2//
3// TGUI - Texus' Graphical User Interface
4// Copyright (C) 2012-2024 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#if !TGUI_EXPERIMENTAL_USE_STD_MODULE
34 #include <regex>
35#endif
36
38
39TGUI_MODULE_EXPORT namespace tgui
40{
47 class TGUI_API EditBox : public ClickableWidget
48 {
49 public:
50
51 using Ptr = std::shared_ptr<EditBox>;
52 using ConstPtr = std::shared_ptr<const EditBox>;
53
54 static constexpr const char StaticWidgetType[] = "EditBox";
55
59 using Alignment TGUI_DEPRECATED("Use tgui::HorizontalAlignment instead") = HorizontalAlignment;
60
64 struct Validator
65 {
66 static TGUI_API const char32_t* All;
67 static TGUI_API const char32_t* Int;
68 static TGUI_API const char32_t* UInt;
69 static TGUI_API const char32_t* Float;
70 };
71
79 EditBox(const char* typeName = StaticWidgetType, bool initRenderer = true);
80
86 TGUI_NODISCARD static EditBox::Ptr create();
87
95 TGUI_NODISCARD static EditBox::Ptr copy(const EditBox::ConstPtr& editBox);
96
101 TGUI_NODISCARD EditBoxRenderer* getSharedRenderer() override;
102 TGUI_NODISCARD const EditBoxRenderer* getSharedRenderer() const override;
103
109 TGUI_NODISCARD EditBoxRenderer* getRenderer() override;
110
116 void setSize(const Layout2d& size) override;
117 using Widget::setSize;
118
126 void setEnabled(bool enabled) override;
127
140 void setText(const String& text);
141
147 TGUI_NODISCARD const String& getText() const;
148
156 void setDefaultText(const String& text);
157
165 TGUI_NODISCARD const String& getDefaultText() const;
166
175 void selectText(std::size_t start = 0, std::size_t length = String::npos);
176
182 TGUI_NODISCARD String getSelectedText() const;
183
195 void setPasswordCharacter(char32_t passwordChar);
196
203 TGUI_NODISCARD char32_t getPasswordCharacter() const;
204
212 void setMaximumCharacters(unsigned int maxChars);
213
222 TGUI_NODISCARD unsigned int getMaximumCharacters() const;
223
230
236 TGUI_NODISCARD HorizontalAlignment getAlignment() const;
237
238#ifndef TGUI_REMOVE_DEPRECATED_CODE
247 TGUI_DEPRECATED("Use setTextWidthLimited instead") void limitTextWidth(bool limitWidth = true);
248#endif
249
260 void setTextWidthLimited(bool limitWidth);
261
267 TGUI_NODISCARD bool isTextWidthLimited() const;
268
277 void setReadOnly(bool readOnly = true);
278
287 TGUI_NODISCARD bool isReadOnly() const;
288
294 void setCaretPosition(std::size_t charactersBeforeCaret);
295
301 TGUI_NODISCARD std::size_t getCaretPosition() const;
302
319 bool setInputValidator(const String& regex = U".*");
320
326 TGUI_NODISCARD const String& getInputValidator() const;
327
335 void setSuffix(const String& suffix);
336
342 TGUI_NODISCARD const String& getSuffix() const;
343
352 void setFocused(bool focused) override;
353
358 TGUI_NODISCARD bool isMouseOnWidget(Vector2f pos) const override;
359
363 bool leftMousePressed(Vector2f pos) override;
364
368 void mouseMoved(Vector2f pos) override;
369
373 void keyPressed(const Event::KeyEvent& event) override;
374
384 bool canHandleKeyPress(const Event::KeyEvent& event) override;
385
389 void textEntered(char32_t key) override;
390
397 void draw(BackendRenderTarget& target, RenderStates states) const override;
398
400 protected:
401
411 TGUI_NODISCARD Signal& getSignal(String signalName) override;
412
418 void rendererChanged(const String& property) override;
419
423 TGUI_NODISCARD std::unique_ptr<DataIO::Node> save(SavingRenderersMap& renderers) const override;
424
428 void load(const std::unique_ptr<DataIO::Node>& node, const LoadingRenderersMap& renderers) override;
429
433 void updateTextSize() override;
434
436 // Returns the total width that the text is going to take
438 TGUI_NODISCARD float getFullTextWidth() const;
439
441 // Returns the size without the borders
443 TGUI_NODISCARD Vector2f getInnerSize() const;
444
446 // Returns the width of the edit box minus the padding.
448 TGUI_NODISCARD float getVisibleEditBoxWidth() const;
449
451 // This function will search after which character the caret should be placed. It will not change the caret position.
453 TGUI_NODISCARD std::size_t findCaretPosition(float posX);
454
456 // Removes the selected characters. This function is called when pressing backspace, delete or a letter while there were
457 // some characters selected.
459 void deleteSelectedCharacters();
460
462 // Recalculates the position of the texts.
464 void recalculateTextPositions();
465
467 // Updates the internal texts after SelStart or SelEnd changed.
469 void updateSelection();
470
472 // Update the color of the Text objects
474 void updateTextColor();
475
477 // This function is called every frame with the time passed since the last frame.
479 bool updateTime(Duration elapsedTime) override;
480
482 // Makes a copy of the widget
484 TGUI_NODISCARD Widget::Ptr clone() const override;
485
487 // Updates m_selEnd with a new value and emits the onCaretPositionChange signal
488 // @param newValue the value to assign to m_selEnd.
490 void updateSelEnd(const std::size_t newValue);
491
497 void emitReturnOrUnfocus(const String& text);
498
500 private:
501
503 // Handles "Backspace" key press
505 void backspaceKeyPressed();
506
508 // Handles "Delete" key press
510 void deleteKeyPressed();
511
513 // Handles "Ctrl+C" key press (or equivalent on macOS)
515 void copySelectedTextToClipboard();
516
518 // Handles "Ctrl+X" key press (or equivalent on macOS)
520 void cutSelectedTextToClipboard();
521
523 // Handles "Ctrl+V" key press (or equivalent on macOS)
525 void pasteTextFromClipboard();
526
528 // Handles "ArrowLeft" key press
530 void moveCaretLeft(bool shiftPressed);
531
533 // Handles "ArrowRight" key press
535 void moveCaretRight(bool shiftPressed);
536
538 // Handles "Ctrl+ArrowLeft" key press (or equivalent on macOS)
540 void moveCaretWordBegin();
541
543 // Handles "Ctrl+ArrowRight" key press (or equivalent on macOS)
545 void moveCaretWordEnd();
546
548 public:
549
550 SignalString onTextChange = {"TextChanged"};
551 SignalString onReturnKeyPress = {"ReturnKeyPressed"};
552 SignalString onReturnOrUnfocus = {"ReturnOrUnfocused"};
553 SignalTyped<std::size_t> onCaretPositionChange = {"CaretPositionChanged"};
554
556 protected:
557
558 // Is the caret visible or not?
559 bool m_caretVisible = true;
560
561 // When this boolean is true then you can no longer add text when the EditBox is full.
562 // Changing it to false will allow you to scroll the text (default).
563 // You can change the boolean with the setTextWidthLimited(bool) function.
564 bool m_limitTextWidth = false;
565
566 bool m_readOnly = false;
567
568 // The text inside the edit box
569 String m_text;
570 String m_displayedText; // Same as m_text unless a password char is set
571
572 String m_regexString = U".*";
573 std::wregex m_regex;
574
575 // The text alignment
576 HorizontalAlignment m_textAlignment = HorizontalAlignment::Left;
577
578 // The selection
579 std::size_t m_selChars = 0;
580 std::size_t m_selStart = 0;
581 std::size_t m_selEnd = 0;
582
583 // The password character
584 char32_t m_passwordChar = '\0';
585
586 // The maximum allowed characters.
587 // Zero by default, meaning no limit.
588 unsigned int m_maxChars = 0;
589
590 // When the text width is not limited, you can scroll the edit box and only a part will be visible.
591 unsigned int m_textCropPosition = 0;
592
593 // The rectangle behind the selected text
594 FloatRect m_selectedTextBackground;
595
596 // The blinking caret
597 FloatRect m_caret = {0, 0, 1, 0};
598
599 // Is there a possibility that the user is going to double click?
600 bool m_possibleDoubleClick = false;
601
602 // We need three texts for drawing + one for the default text + one more for calculations.
603 Text m_textBeforeSelection;
604 Text m_textSelection;
605 Text m_textAfterSelection;
606 Text m_defaultText;
607 Text m_textFull;
608 Text m_textSuffix;
609
610 Sprite m_sprite;
611 Sprite m_spriteHover;
612 Sprite m_spriteDisabled;
613 Sprite m_spriteFocused;
614
615 // Cached renderer properties
616 Borders m_bordersCached;
617 Padding m_paddingCached;
618 Color m_borderColorCached;
619 Color m_borderColorHoverCached;
620 Color m_borderColorDisabledCached;
621 Color m_borderColorFocusedCached;
622 Color m_backgroundColorCached;
623 Color m_backgroundColorHoverCached;
624 Color m_backgroundColorDisabledCached;
625 Color m_backgroundColorFocusedCached;
626 Color m_caretColorCached;
627 Color m_caretColorHoverCached;
628 Color m_caretColorFocusedCached;
629 Color m_selectedTextBackgroundColorCached;
630
632 private:
633
634 // Used to prevent emitting onReturnOrUnfocus twice when unfocusing the edit box inside the callback function.
635 bool m_onReturnOrUnfocusEmitted = false;
636
638 };
639
641}
642
644
645#endif // TGUI_EDIT_BOX_HPP
Base class for render targets.
Definition BackendRenderTarget.hpp:46
Clickable widget.
Definition ClickableWidget.hpp:38
Wrapper for durations.
Definition Duration.hpp:55
Definition EditBoxRenderer.hpp:35
Edit box widget.
Definition EditBox.hpp:48
void setFocused(bool focused) override
Focus or unfocus the widget.
static EditBox::Ptr create()
Creates a new edit box widget.
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.
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.
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.
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.
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:52
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:51
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:323
Signal to which the user can subscribe to get callbacks from.
Definition Signal.hpp:61
Wrapper class to store strings.
Definition String.hpp:96
std::shared_ptr< Widget > Ptr
Shared widget pointer.
Definition Widget.hpp:86
Namespace that contains all TGUI functions and classes.
Definition AbsoluteOrRelativeValue.hpp:38
HorizontalAlignment
The horizontal alignment.
Definition Layout.hpp:62
Predefined input validators.
Definition EditBox.hpp:65
static TGUI_API const char32_t * Int
Accept negative and positive integers.
Definition EditBox.hpp:67
static TGUI_API const char32_t * Float
Accept decimal numbers.
Definition EditBox.hpp:69
static TGUI_API const char32_t * UInt
Accept only positive integers.
Definition EditBox.hpp:68
static TGUI_API const char32_t * All
Accept any input.
Definition EditBox.hpp:66
KeyPressed event parameters.
Definition Event.hpp:168
States used for drawing.
Definition RenderStates.hpp:38