WidgetTextInput.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #ifndef RMLUI_CORE_ELEMENTS_WIDGETTEXTINPUT_H
  29. #define RMLUI_CORE_ELEMENTS_WIDGETTEXTINPUT_H
  30. #include "../../../Include/RmlUi/Core/EventListener.h"
  31. #include "../../../Include/RmlUi/Core/Geometry.h"
  32. #include "../../../Include/RmlUi/Core/Vertex.h"
  33. #include <float.h>
  34. namespace Rml {
  35. class ElementText;
  36. class ElementFormControl;
  37. class TextInputHandler;
  38. class WidgetTextInputContext;
  39. /**
  40. An abstract widget for editing and navigating around a text field.
  41. @author Peter Curry
  42. */
  43. class WidgetTextInput : public EventListener {
  44. public:
  45. WidgetTextInput(ElementFormControl* parent);
  46. virtual ~WidgetTextInput();
  47. /// Sets the value of the text field.
  48. /// @param[in] value The new value to set on the text field.
  49. /// @note The value will be sanitized and synchronized with the element's value attribute.
  50. void SetValue(String value);
  51. /// Returns the underlying text from the element's value attribute.
  52. String GetAttributeValue() const;
  53. /// Sets the maximum length (in characters) of this text field.
  54. /// @param[in] max_length The new maximum length of the text field. A number lower than zero will mean infinite characters.
  55. void SetMaxLength(int max_length);
  56. /// Returns the maximum length (in characters) of this text field.
  57. /// @return The maximum number of characters allowed in this text field.
  58. int GetMaxLength() const;
  59. /// Returns the current length (in characters) of this text field.
  60. int GetLength() const;
  61. /// Selects all text.
  62. void Select();
  63. /// Selects the text in the given character range.
  64. /// @param[in] selection_start The first character to be selected.
  65. /// @param[in] selection_end The first character *after* the selection.
  66. void SetSelectionRange(int selection_start, int selection_end);
  67. /// Retrieves the selection range and text.
  68. /// @param[out] selection_start The first character selected.
  69. /// @param[out] selection_end The first character *after* the selection.
  70. /// @param[out] selected_text The selected text.
  71. void GetSelection(int* selection_start, int* selection_end, String* selected_text) const;
  72. /// Sets visual feedback used for the IME composition in the range.
  73. /// @param[in] range_start The first character to be selected.
  74. /// @param[in] range_end The first character *after* the selection.
  75. void SetCompositionRange(int range_start, int range_end);
  76. /// Obtains the IME composition byte range relative to the current value.
  77. void GetCompositionRange(int& range_start, int& range_end) const;
  78. /// Update the colours of the selected text.
  79. void UpdateSelectionColours();
  80. /// Generates the text cursor.
  81. void GenerateCursor();
  82. /// Force text formatting on the next layout update.
  83. void ForceFormattingOnNextLayout();
  84. /// Updates the cursor, if necessary.
  85. void OnUpdate();
  86. /// Renders the cursor, if it is visible.
  87. void OnRender();
  88. /// Formats the widget's internal content.
  89. void OnLayout();
  90. /// Called when the parent element's size changes.
  91. void OnResize();
  92. protected:
  93. enum class CursorMovement { Begin = -4, BeginLine = -3, PreviousWord = -2, Left = -1, Right = 1, NextWord = 2, EndLine = 3, End = 4 };
  94. /// Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and
  95. /// "blur" to set the state of the cursor.
  96. void ProcessEvent(Event& event) override;
  97. /// Adds new characters to the string at the cursor position.
  98. /// @param[in] string The characters to add.
  99. /// @return True if at least one character was successfully added, false otherwise.
  100. bool AddCharacters(String string);
  101. /// Deletes characters from the string.
  102. /// @param[in] direction Movement of cursor for deletion.
  103. /// @return True if a character was deleted, false otherwise.
  104. bool DeleteCharacters(CursorMovement direction);
  105. /// Removes any invalid characters from the string.
  106. virtual void SanitizeValue(String& value) = 0;
  107. /// Transforms the displayed value of the text box, typically used for password fields.
  108. /// @note Only use this for transforming characters, do not modify the length of the string.
  109. virtual void TransformValue(String& value);
  110. /// Called when the user pressed enter.
  111. virtual void LineBreak() = 0;
  112. /// Gets the parent element containing the widget.
  113. Element* GetElement() const;
  114. /// Obtains the text input handler of the parent element's context.
  115. TextInputHandler* GetTextInputHandler() const;
  116. /// Returns true if the text input element is currently focused.
  117. bool IsFocused() const;
  118. /// Dispatches a change event to the widget's element.
  119. void DispatchChangeEvent(bool linebreak = false);
  120. private:
  121. struct Line {
  122. // Offset into the text field's value.
  123. int value_offset;
  124. // The size of the contents of the line (including the trailing endline, if that terminated the line).
  125. int size;
  126. // The length of the editable characters on the line (excluding any trailing endline).
  127. int editable_length;
  128. };
  129. /// Returns the displayed value of the text field.
  130. /// @note For password fields this would only return the displayed asterisks '****', while the attribute value below contains the underlying text.
  131. const String& GetValue() const;
  132. /// Moves the cursor along the current line.
  133. /// @param[in] movement Cursor movement operation.
  134. /// @param[in] select True if the movement will also move the selection cursor, false if not.
  135. /// @param[out] out_of_bounds Set to true if the resulting line position is out of bounds, false if not.
  136. /// @return True if selection was changed.
  137. bool MoveCursorHorizontal(CursorMovement movement, bool select, bool& out_of_bounds);
  138. /// Moves the cursor up and down the text field.
  139. /// @param[in] x How far to move the cursor.
  140. /// @param[in] select True if the movement will also move the selection cursor, false if not.
  141. /// @param[out] out_of_bounds Set to true if the resulting line position is out of bounds, false if not.
  142. /// @return True if selection was changed.
  143. bool MoveCursorVertical(int distance, bool select, bool& out_of_bounds);
  144. // Move the cursor to utf-8 boundaries, in case it was moved into the middle of a multibyte character.
  145. /// @param[in] forward True to seek forward, else back.
  146. void MoveCursorToCharacterBoundaries(bool forward);
  147. // Expands the cursor, selecting the current word or nearby whitespace.
  148. void ExpandSelection();
  149. /// Returns the relative indices from the current absolute index.
  150. void GetRelativeCursorIndices(int& out_cursor_line_index, int& out_cursor_character_index) const;
  151. /// Sets the absolute cursor index from the given relative indices.
  152. void SetCursorFromRelativeIndices(int line_index, int character_index);
  153. /// Calculates the line index under a specific vertical position.
  154. /// @param[in] position The position to query.
  155. /// @return The index of the line under the mouse cursor.
  156. int CalculateLineIndex(float position) const;
  157. /// Calculates the character index along a line under a specific horizontal position.
  158. /// @param[in] line_index The line to query.
  159. /// @param[in] position The position to query.
  160. /// @return The index of the character under the mouse cursor.
  161. int CalculateCharacterIndex(int line_index, float position);
  162. /// Shows or hides the cursor.
  163. /// @param[in] show True to show the cursor, false to hide it.
  164. /// @param[in] move_to_cursor True to force the cursor to be visible, false to not scroll the widget.
  165. void ShowCursor(bool show, bool move_to_cursor = true);
  166. /// Formats the element, laying out the text and inserting scrollbars as appropriate.
  167. void FormatElement();
  168. /// Formats the input element's text field.
  169. /// @param[in] height_constraint Abort formatting when the formatted size grows larger than this height.
  170. /// @return The content area of the element.
  171. Vector2f FormatText(float height_constraint = FLT_MAX);
  172. /// Updates the position to render the cursor.
  173. /// @param[in] update_ideal_cursor_position Generally should be true on horizontal movement and false on vertical movement.
  174. void UpdateCursorPosition(bool update_ideal_cursor_position);
  175. /// Expand or shrink the text selection to the position of the cursor.
  176. /// @param[in] selecting True if the new position of the cursor should expand / contract the selection area, false if it should only set the
  177. /// anchor for future selections.
  178. /// @return True if selection was changed.
  179. bool UpdateSelection(bool selecting);
  180. /// Removes the selection of text.
  181. /// @return True if selection was changed.
  182. bool ClearSelection();
  183. /// Deletes all selected text and removes the selection.
  184. void DeleteSelection();
  185. /// Copies the selection (if any) to the clipboard.
  186. void CopySelection();
  187. /// Split one line of text into three parts, based on the current selection.
  188. /// @param[out] pre_selection The section of unselected text before any selected text on the line.
  189. /// @param[out] selection The section of selected text on the line.
  190. /// @param[out] post_selection The section of unselected text after any selected text on the line. If there is no selection on the line, then this
  191. /// will be empty.
  192. /// @param[in] line The text making up the line.
  193. /// @param[in] line_begin The absolute index at the beginning of the line.
  194. /// @lifetime The returned string views are tied to the lifetime of the line's data.
  195. void GetLineSelection(StringView& pre_selection, StringView& selection, StringView& post_selection, const String& line, int line_begin) const;
  196. /// Fetch the IME composition range on the line.
  197. /// @param[out] pre_composition The section of text before the IME composition string on the line.
  198. /// @param[out] ime_composition The IME composition string on the line.
  199. /// @param[in] line The text making up the line.
  200. /// @param[in] line_begin The absolute index at the beginning of the line.
  201. void GetLineIMEComposition(StringView& pre_composition, StringView& ime_composition, const String& line, int line_begin) const;
  202. /// Returns the offset that aligns the contents of the line according to the 'text-align' property.
  203. float GetAlignmentSpecificTextOffset(const Line& line) const;
  204. /// Returns the used line height.
  205. float GetLineHeight() const;
  206. /// Returns the width available for the text contents without overflowing, that is, the content area subtracted by any scrollbar.
  207. float GetAvailableWidth() const;
  208. /// Returns the height available for the text contents without overflowing, that is, the content area subtracted by any scrollbar.
  209. float GetAvailableHeight() const;
  210. ElementFormControl* parent;
  211. ElementText* text_element;
  212. ElementText* selected_text_element;
  213. Vector2f internal_dimensions;
  214. Vector2f scroll_offset;
  215. using LineList = Vector<Line>;
  216. LineList lines;
  217. // Length in number of characters.
  218. int max_length;
  219. // -- All indices are in bytes: Should always be moved along UTF-8 start bytes. --
  220. // Absolute cursor index. Byte index into the text field's value.
  221. int absolute_cursor_index;
  222. // When the cursor is located at the very end of a word-wrapped line there are two valid positions for the same absolute index: at the end of the
  223. // line and at the beginning of the next line. This state determines which of these lines the cursor is placed on visually.
  224. bool cursor_wrap_down;
  225. bool ideal_cursor_position_to_the_right_of_cursor;
  226. bool cancel_next_drag;
  227. bool force_formatting_on_next_layout;
  228. // Selection. The start and end indices of the selection are in absolute coordinates.
  229. Element* selection_element;
  230. int selection_anchor_index;
  231. int selection_begin_index;
  232. int selection_length;
  233. // The colour of the background of selected text.
  234. ColourbPremultiplied selection_colour;
  235. // The selection background.
  236. Geometry selection_composition_geometry;
  237. // IME composition range. The start and end indices are in absolute coordinates.
  238. int ime_composition_begin_index;
  239. int ime_composition_end_index;
  240. // The IME context for this widget.
  241. UniquePtr<WidgetTextInputContext> text_input_context;
  242. // Cursor visibility and timings.
  243. float cursor_timer;
  244. bool cursor_visible;
  245. bool keyboard_showed;
  246. /// Activate or deactivate keyboard (for touchscreen devices)
  247. /// @param[in] active True if need activate keyboard, false if need deactivate.
  248. void SetKeyboardActive(bool active);
  249. bool ink_overflow;
  250. double last_update_time;
  251. // The cursor geometry.
  252. float ideal_cursor_position;
  253. Vector2f cursor_position;
  254. Vector2f cursor_size;
  255. Geometry cursor_geometry;
  256. };
  257. } // namespace Rml
  258. #endif