# core/textinput (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/textinput/

Text input queue. (held by InputManager)
- The original has no such layer. The original UIInputField attaches listeners directly to a DOM <input> and document keydown.
  In the Rust version the platform puts window events (desktop winit's KeyboardInput / Ime, the web hidden <input>'s input / composition / keydown)
  into this queue, and the input field with focus takes them out on tick. (ui/uiinputfield.rs)
- Components receive only &Engine. So the side the field uses (taking out, publishing state) is made to work from &self with RefCell.
  The platform holds &Engine, so the pushing side is &mut self.
- Frame flow:
  1. The platform pushes events between frames. (push_event)
  2. On scene tick, a field takes out its share. (take_events_for_field) Attached fields and the field with focus publish their state. (register_field_state)
  3. At the end of the frame the engine calls finish_frame. It drops the remaining events and moves the published states to the "last frame states".
  4. The platform reads the last frame states and applies them. (desktop: turning IME on and off and the candidate window position, web: hidden <input> position, value, focus)
- All character positions are in characters (char). The original (JavaScript strings) uses UTF-16 units. They are the same for Hangul and differ only for characters like emoji.
  The web platform converts DOM UTF-16 positions with the functions here before pushing.

Example: Convert between character positions, byte positions and UTF-16 positions

```rust
use vanilla::core::textinput::{convert_byte_index_to_character_index, convert_character_index_to_byte_index, convert_character_index_to_utf16_index, convert_utf16_index_to_character_index, count_characters};

let text = "a\u{D55C}\u{1F600}b";
assert_eq!(count_characters(text), 4);
assert_eq!(convert_character_index_to_byte_index(text, 2), 4);
assert_eq!(convert_byte_index_to_character_index(text, 4), 2);
assert_eq!(convert_character_index_to_utf16_index(text, 3), 4);
assert_eq!(convert_utf16_index_to_character_index(text, 4), 3);
```

## TextInputEvent (struct) (Clone, Debug, PartialEq)

Text input event. (receiving field + content)

Example: Send committed text to the field with focus

```rust
use vanilla::{TextInput, TextInputEvent, TextInputEventKind};

let mut text_input = TextInput::new();
text_input.push_event(TextInputEvent {
	target_field_id: 0,
	kind: TextInputEventKind::Commit(String::from("hello")),
});
assert_eq!(text_input.get_event_count(), 1);
```

- `pub target_field_id: u64` (field, since 0.3.2): Receiving field id. 0 means the field that currently has focus. (desktop keys and IME, web canvas mode keys)
  - returns u64
- `pub kind: TextInputEventKind` (field, since 0.3.2): Event content.
  - returns TextInputEventKind

## TextInputFieldState (struct) (Clone, Debug, PartialEq)

State a field publishes every frame. (read by the platform to sync the IME and the hidden <input>)
- Positions are logical coordinates inside the window (on the web, CSS pixels relative to the canvas).

Example: Publish field state and move it on at the end of the frame

```rust
use vanilla::{Rect, TextInput, TextInputFieldState};

let mut text_input = TextInput::new();
text_input.register_field_state(TextInputFieldState {
	field_id: 3,
	focus_serial: 1,
	is_focused: true,
	is_attached: true,
	use_dominput: true,
	use_touch_end_focus: false,
	use_direct_touch: false,
	is_visible: true,
	field_rect: Rect::create(10.0, 20.0, 200.0, 40.0),
	caret_rect: Rect::create(10.0, 20.0, 1.0, 40.0),
	value: String::from("abc"),
	selection_start: 0,
	cursor_index: 3,
	max_length: 0,
	value_revision: 0,
	is_multiline: false,
});
text_input.finish_frame();
assert_eq!(text_input.get_published_field_states().len(), 1);
assert_eq!(text_input.get_published_field_states()[0].value, "abc");
```

- `pub field_id: u64` (field, since 0.3.2): Field id. (numbered from 1 when UIInputField creates it)
  - returns u64
- `pub focus_serial: u64` (field, since 0.3.2): Order in which it got focus. (larger is later. 0 if no focus)
  - returns u64
- `pub is_focused: bool` (field, since 0.3.2): Whether it has focus.
  - returns bool
- `pub is_attached: bool` (field, since 0.3.2): Whether it chose to receive input with attach().
  - returns bool
- `pub use_dominput: bool` (field, since 0.3.2): Whether platform text input (IME, system keyboard, hidden web <input>) is used. (the original setUseDOMInput)
  - returns bool
- `pub use_touch_end_focus: bool` (field, since 0.3.2): Whether to give focus on release too. (web DOM input only)
  - returns bool
- `pub use_direct_touch: bool` (field, since 0.3.2): Whether to let the DOM input be pressed directly over the field. (web DOM input only)
  - returns bool
- `pub is_visible: bool` (field, since 0.3.2): Whether the node and all its ancestors are visible.
  - returns bool
- `pub field_rect: Rect` (field, since 0.3.2): Field rectangle.
  - returns Rect
- `pub caret_rect: Rect` (field, since 0.3.2): Cursor rectangle. (a vertical bar the height of the field)
  - returns Rect
- `pub value: String` (field, since 0.3.2): Current value.
  - returns String
- `pub selection_start: usize` (field, since 0.3.2): Selection start position. (in characters, the side fixed when extending the selection. No selection if equal to cursor_index)
  - returns usize
- `pub cursor_index: usize` (field, since 0.3.2): Cursor position. (in characters)
  - returns usize
- `pub max_length: usize` (field, since 0.3.2): Maximum length. (in UTF-16 units, no limit if 0)
  - returns usize
- `pub value_revision: u64` (field, since 0.3.2): Increases whenever the field side changes the value or cursor. (used by the web to see whether the hidden <input> needs rewriting)
  - returns u64
- `pub is_multiline: bool` (field, since 0.4.0): Whether it is a multiline field. (the web uses a hidden `<textarea>`)
  - returns bool

## TextInput (struct) (Default)

Text input queue.
- InputManager holds one. The platform pushes events, input fields take them out, and the engine calls finish_frame at the end of the frame.

Example: Push, let a field take out, and drop the rest at the end of the frame

```rust
use vanilla::{TextInput, TextInputEvent, TextInputEventKind};

let mut text_input = TextInput::new();
text_input.push_focused_field_event(TextInputEventKind::Commit(String::from("a")));
text_input.push_event(TextInputEvent {
	target_field_id: 7,
	kind: TextInputEventKind::FocusGained,
});
text_input.push_event(TextInputEvent {
	target_field_id: 9,
	kind: TextInputEventKind::FocusLost,
});
let taken_list = text_input.take_events_for_field(7, true);
assert_eq!(taken_list, vec![TextInputEventKind::Commit(String::from("a")), TextInputEventKind::FocusGained]);
assert_eq!(text_input.get_event_count(), 1);
text_input.finish_frame();
assert_eq!(text_input.get_event_count(), 0);
```

- `pub fn new() -> TextInput` (constructor, since 0.3.2): Constructor.
  - returns TextInput: An empty queue with no events and no field states.
- `pub fn push_event(&mut self, event: TextInputEvent)` (method, since 0.3.2): Pushes an event. (platform)
  - `event` TextInputEvent: Event to push. (for the field with focus if target_field_id is 0)
- `pub fn push_focused_field_event(&mut self, kind: TextInputEventKind)` (method, since 0.3.2): Pushes an event bound for the field with focus. (platform)
  - `kind` TextInputEventKind: Event content to push. (pushed with target_field_id 0)
- `pub fn get_event_count(&self) -> usize` (method, since 0.3.2): Number of queued events.
  - returns usize: Number of events nobody has taken out yet.
- `pub fn take_events_for_field(&self, field_id: u64, accepts_focused_field_events: bool) -> Vec<TextInputEventKind>` (method, since 0.3.2): Takes out the field's share of events. (those sent to its id, and those sent to 0 if it can receive focus events)
  - Taken events leave the queue. Even during a frame where two fields have focus, the same text does not go in twice.
  - `field_id` u64: Field id to take out for.
  - `accepts_focused_field_events` bool: If true, also takes out events whose target_field_id is 0 (the share for the field with focus).
  - returns Vec<TextInputEventKind>: List of taken event contents. (in the order pushed, an empty list if none)

  Example: Take out those sent to the id and the focus share

  ```rust
  use vanilla::{TextInput, TextInputEvent, TextInputEventKind};
  
  let mut text_input = TextInput::new();
  text_input.push_focused_field_event(TextInputEventKind::CompositionStart);
  text_input.push_event(TextInputEvent {
  	target_field_id: 5,
  	kind: TextInputEventKind::FocusGained,
  });
  assert!(text_input.take_events_for_field(3, false).is_empty());
  assert_eq!(text_input.take_events_for_field(5, false), vec![TextInputEventKind::FocusGained]);
  assert_eq!(text_input.take_events_for_field(3, true), vec![TextInputEventKind::CompositionStart]);
  ```

- `pub fn register_field_state(&self, field_state: TextInputFieldState)` (method, since 0.3.2): Publishes field state. (field tick, if the same field publishes twice, the later one)
  - `field_state` TextInputFieldState: State to publish. (visible via get_published_field_states after finish_frame)
- `pub fn get_published_field_states(&self) -> &[TextInputFieldState]` (method, since 0.3.2): List of field states published last frame. (published order = tree order)
  - returns &[TextInputFieldState]: List of last frame states. (empty before the first finish_frame)
- `pub fn get_latest_focus_serial(&self) -> u64` (method, since 0.3.2): Focus order of the field that got focus most recently last frame. (0 if none)
  - returns u64: The largest focus_serial among fields with focus. (0 if none)
- `pub fn get_active_field_state(&self) -> Option<&TextInputFieldState>` (method, since 0.3.2): State of the field receiving text input. (the latest among attached fields that had focus last frame)
  - returns Option<&TextInputFieldState>: That field state. None if no field has focus and is attached (is_attached).

  Example: The later of the attached fields with focus

  ```rust
  use vanilla::{Rect, TextInput, TextInputFieldState};
  
  fn create_field_state(field_id: u64, focus_serial: u64) -> TextInputFieldState {
  	TextInputFieldState {
  		field_id,
  		focus_serial,
  		is_focused: true,
  		is_attached: true,
  		use_dominput: true,
  		use_touch_end_focus: false,
  		use_direct_touch: false,
  		is_visible: true,
  		field_rect: Rect::zero(),
  		caret_rect: Rect::zero(),
  		value: String::new(),
  		selection_start: 0,
  		cursor_index: 0,
  		max_length: 0,
  		value_revision: 0,
  		is_multiline: false,
  	}
  }
  
  let mut text_input = TextInput::new();
  text_input.register_field_state(create_field_state(1, 4));
  text_input.register_field_state(create_field_state(2, 6));
  assert!(text_input.get_active_field_state().is_none());
  text_input.finish_frame();
  assert_eq!(text_input.get_active_field_state().map(|field_state| field_state.field_id), Some(2));
  assert_eq!(text_input.get_latest_focus_serial(), 6);
  ```

- `pub fn set_context_menu_request_position(&mut self, view_position: Option<Vector2>)` (method, since 0.3.2): Sets the context menu request position. (the desktop right button, a right click on a web field, view coordinates. It lasts only this frame)
  - `view_position` Option<Vector2>: Request position. (view coordinates, None means no request. finish_frame resets it to None)
- `pub fn get_context_menu_request_position(&self) -> Option<Vector2>` (method, since 0.3.2): Context menu request position.
  - returns Option<Vector2>: This frame's request position. (view coordinates, None if no request)
- `pub fn set_ime_commit_guard(&self, committed_text: &str)` (method, since 0.3.2): Records composition text the field committed by itself on losing focus. (field)
  - On desktop, turning off the IME can make the OS send the same composition text once more as Commit. This lets the platform drop it.
  - `committed_text` &str: Text the field committed. (the record disappears after two finish_frame calls)
- `pub fn consume_ime_commit_guard(&mut self, committed_text: &str) -> bool` (method, since 0.3.2): Returns true if the IME commit text is text the field already committed, and clears the record. (platform)
  - `committed_text` &str: Commit text sent by the IME.
  - returns bool: True if equal to the recorded text. (false if there is no record or it differs, and the record is kept)

  Example: Block the same commit text only once

  ```rust
  use vanilla::TextInput;
  
  let mut text_input = TextInput::new();
  text_input.set_ime_commit_guard("abc");
  assert!(!text_input.consume_ime_commit_guard("xyz"));
  assert!(text_input.consume_ime_commit_guard("abc"));
  assert!(!text_input.consume_ime_commit_guard("abc"));
  ```

- `pub fn set_pointer_click_count(&self, pointer_click_count: u32)` (method, since 0.4.0): Sets the mouse click count. (the web platform sets the mousedown detail, 1 if 0)
  - `pointer_click_count` u32: Click count. (the mousedown detail, 2 for a double click, 1 if 0)
- `pub fn get_pointer_click_count(&self) -> u32` (method, since 0.4.0): The last mouse click count. (1 if never set)
  - returns u32: The last click count. (1 or more, 1 if never set)
- `pub fn request_ime_reset(&self)` (method, since 0.3.2): Requests breaking the IME composition. (when the field committed the composition text by itself. The desktop platform turns the IME off and on)
- `pub fn take_ime_reset_request(&self) -> bool` (method, since 0.3.2): Takes out the IME composition break request. (platform, cleared when taken)
  - returns bool: True if request_ime_reset was called.
- `pub fn finish_frame(&mut self)` (method, since 0.3.2): Finishes the frame. (the engine calls it at the end of the frame)
  - Drops events nobody took out, and moves the states published this frame to the last frame states.

## Functions and constants

- `pub fn count_characters(text: &str) -> usize` (method, since 0.3.2): Character count.
  - `text` &str: Text to count.
  - returns usize: Number of chars. (not the byte count)
- `pub fn convert_character_index_to_byte_index(text: &str, character_index: usize) -> usize` (method, since 0.3.2): Character position → byte position. (the end if beyond)
  - `text` &str: Text.
  - `character_index` usize: Character position.
  - returns usize: Byte position where that character starts. (text.len() if at or beyond the character count of the text)
- `pub fn convert_byte_index_to_character_index(text: &str, byte_index: usize) -> usize` (method, since 0.3.2): Byte position → character position. (the cursor of winit Ime::Preedit is in bytes)
  - `text` &str: Text.
  - `byte_index` usize: Byte position.
  - returns usize: Number of characters starting before byte_index. (the position after that character if the byte is in the middle of a character)
- `pub fn convert_utf16_index_to_character_index(text: &str, utf16_index: usize) -> usize` (method, since 0.3.2): UTF-16 position → character position. (DOM selection_start / selection_end)
  - `text` &str: Text.
  - `utf16_index` usize: UTF-16 position.
  - returns usize: Character position. (the position after that character if in the middle of a surrogate pair, the character count if beyond)

  Example: Emoji take two UTF-16 units

  ```rust
  use vanilla::core::textinput::convert_utf16_index_to_character_index;
  
  let text = "a\u{1F600}b";
  assert_eq!(convert_utf16_index_to_character_index(text, 1), 1);
  assert_eq!(convert_utf16_index_to_character_index(text, 2), 2);
  assert_eq!(convert_utf16_index_to_character_index(text, 3), 2);
  assert_eq!(convert_utf16_index_to_character_index(text, 99), 3);
  ```

- `pub fn convert_character_index_to_utf16_index(text: &str, character_index: usize) -> usize` (method, since 0.3.2): Character position → UTF-16 position. (DOM setSelectionRange)
  - `text` &str: Text.
  - `character_index` usize: Character position. (treated as the end if beyond the character count)
  - returns usize: UTF-16 position.
- `pub fn find_previous_grapheme_boundary(text: &str, character_index: usize) -> usize` (method, since 0.4.0): Previous grapheme cluster boundary. (PositionMoveType::kGraphemeCluster of the Chrome left arrow, extended grapheme clusters UAX #29)
  - `text` &str: Text.
  - `character_index` usize: Character position.
  - returns usize: Character position of the nearest boundary before the position. (0 if 0, the start of the cluster if in the middle of one)
- `pub fn find_next_grapheme_boundary(text: &str, character_index: usize) -> usize` (method, since 0.4.0): Next grapheme cluster boundary. (PositionMoveType::kGraphemeCluster of the Chrome right arrow and Delete key)
  - `text` &str: Text.
  - `character_index` usize: Character position.
  - returns usize: Character position of the nearest boundary after the position. (the character count at the end of the text)
- `pub fn collect_grapheme_boundaries(text: &str) -> Vec<usize>` (method, since 0.4.0): List of grapheme cluster boundaries. (includes 0 and the character count, ascending)
  - `text` &str: Text to split.
  - returns Vec<usize>: List of character positions of grapheme cluster boundaries. (includes 0 and the character count, ascending)
- `pub fn find_backward_deletion_boundary(text: &str, character_index: usize) -> usize` (method, since 0.4.0): Start of the range Backspace deletes. (a port of Blink's BackspaceStateMachine)
  - Chrome deletes one code point at a time on Backspace, not a grapheme cluster. However, CR LF, an emoji variation selector (VS) and its base,
    a skin tone modifier and its base, emoji joined with ZWJ, flags (two regional indicators), keycaps and tag sequences are deleted whole.
  - Blink's pictographic characters (IsExtendedPictographicGb11) are Extended_Pictographic or Emoji.
  - Whether the canonical combining class of the character before a VS is 0 is judged, as in the original (the browser does not expose it), by whether it is not a combining mark (general category M).
  - `text` &str: Text.
  - `character_index` usize: Character position of the cursor.
  - returns usize: Character position of the start of the range to delete.
- `pub fn collect_word_boundaries(text: &str) -> Vec<usize>` (method, since 0.4.0): List of word boundaries. (the same as Chrome word breaking)
  - Adds the rules of Chromium ICU's wordbrk.patch to ICU word breaking (segment_words). Chrome joins periods (U+002E, U+FF0E) only between digits and does not join colons (U+003A, U+FE55, U+FF1A).
    (Chrome's Intl.Segmenter on the web already does this)
  - `text` &str: Text.
  - returns Vec<usize>: List of character positions of word boundaries. (includes 0 and the character count, ascending)

  Example: Addresses split at periods and decimals are one word

  ```rust
  use vanilla::core::textinput::collect_word_boundaries;
  
  assert_eq!(collect_word_boundaries("www.example.com 3.14"), vec![0, 3, 4, 11, 12, 15, 16, 20]);
  ```

- `pub fn find_next_word_position(text: &str, character_index: usize, is_skip_spaces: bool) -> usize` (method, since 0.4.0): Next word position. (Chrome's move word right and delete word forward, Blink NextWordPosition)
  - On macOS and Linux, the end of the current word ("abc| def|"); on Windows, the start of the next word after skipping the trailing space ("abc |def"). (ShouldSkipSpaceWhenMovingRight in editing_behavior.h)
  - At the end of a line, goes to the start of the next line. The character count at the end of the text.
  - `text` &str: Text.
  - `character_index` usize: Character position of the cursor.
  - `is_skip_spaces` bool: Whether to skip the trailing space. (true on Windows)
  - returns usize: Character position of the next word.

  Example: Moving a word right on macOS, Linux and Windows

  ```rust
  use vanilla::core::textinput::find_next_word_position;
  
  assert_eq!(find_next_word_position("abc def", 0, false), 3);
  assert_eq!(find_next_word_position("abc def", 0, true), 4);
  ```

- `pub fn find_previous_word_position(text: &str, character_index: usize) -> usize` (method, since 0.4.0): Previous word position. (Chrome's move word left and delete word backward, Blink PreviousWordPosition, the start of the word on all platforms "|abc |def")
  - Like Chrome's textarea, does not cross to the previous line from the start of a line with text. 0 at the start of the text.
  - `text` &str: Text.
  - `character_index` usize: Character position of the cursor.
  - returns usize: Character position of the previous word.

  Example: Moving a word left

  ```rust
  use vanilla::core::textinput::find_previous_word_position;
  
  assert_eq!(find_previous_word_position("abc def", 7), 4);
  assert_eq!(find_previous_word_position("ab\ncd", 3), 3);
  ```

## TextInputKey (enum) (Clone, Copy, Debug, PartialEq, Eq)

Editing key. (keys the original handleCanvasKeydown looks at)

- `Backspace`: Deletes the character before the cursor. (deletes the selection if there is one)
- `Delete`: Deletes the character after the cursor. (deletes the selection if there is one)
- `Left`: Moves the cursor one character left. (extends the selection if is_shift)
- `Right`: Moves the cursor one character right. (extends the selection if is_shift)
- `WordLeft`: Moves the cursor to the start of the previous word. (Ctrl + Left on Windows and Linux, Option + Left on macOS, extends the selection if is_shift. Blink MoveWordLeft)
- `WordRight`: Moves the cursor one word right. (Ctrl + Right on Windows and Linux, Option + Right on macOS, extends the selection if is_shift. Blink MoveWordRight)
- `DeleteWordBackward`: Deletes the word before the cursor. (Ctrl + Backspace on Windows and Linux, Option + Backspace on macOS, deletes the selection if there is one. Blink DeleteWordBackward)
- `DeleteWordForward`: Deletes the word after the cursor. (Ctrl + Delete on Windows and Linux, Option + Delete on macOS, deletes the selection if there is one. Blink DeleteWordForward)
- `Home`: Line start. (the start of the visible line in a multiline field, the start of the text in a single-line field. Cmd + Left too on Mac, extends the selection if is_shift)
- `End`: Line end. (the end of the visible line in a multiline field, the end of the text in a single-line field. Cmd + Right too on Mac, extends the selection if is_shift)
- `Up`: Line up. (multiline fields, the start of the text in a single-line DOM input box)
- `Down`: Line down. (multiline fields, the end of the text in a single-line DOM input box)
- `PageUp`: Up by one screen. (multiline fields, with Option on Mac)
- `PageDown`: Down by one screen. (multiline fields, with Option on Mac)
- `DocumentStart`: Text start. (Ctrl + Home, Cmd + Up on Mac)
- `DocumentEnd`: Text end. (Ctrl + End, Cmd + Down on Mac)
- `ScrollToDocumentStart`: Mac Home, End. (scrollToBeginningOfDocument, scrollToEndOfDocument of the Mac key bindings)
- Chrome on macOS leaves the cursor and scrolls a scrollable box to the start and end, and if there is nothing to scroll, moves to the line start and end per the Blink key table.
- With Shift (is_shift), selects to the start and end of the text like moveToBeginningOfDocumentAndModifySelection of the key bindings.
- `ScrollToDocumentEnd`: Mac End. (the end side of ScrollToDocumentStart, scrollToEndOfDocument of the Mac key bindings)
- `ScrollPageUp`: Mac PageUp, PageDown. (scrollPageUp, scrollPageDown of the Mac key bindings, Chrome on macOS leaves the cursor and scrolls by one screen)
- `ScrollPageDown`: Mac PageDown. (the downward side of ScrollPageUp, scrollPageDown of the Mac key bindings)
- `Enter`: Enter. (fires a submit event in a single-line field, inserts a line break in a multiline field)
- `Tab`: As in the original canvas mode, the field does not use it. (passed on for the game to check when moving to the next field)
- `SelectAll`: Ctrl (Cmd on Mac) + A
- `Copy`: Ctrl (Cmd on Mac) + C
- `Cut`: Ctrl (Cmd on Mac) + X
- `Paste`: Ctrl (Cmd on Mac) + V
- `Undo`: Undo. (Ctrl (Cmd on Mac) + Z, also Alt + Backspace on Windows. The browser undo of the original DOM input field)
- `Redo`: Redo. (Ctrl (Cmd on Mac) + Shift + Z, Ctrl + Y on Windows and Linux, also Alt + Shift + Backspace on Windows)

## TextInputEventKind (enum) (Clone, Debug, PartialEq)

Text input event content.

- `Commit` = `Commit(String)`: Committed text. (IME commit, characters typed with keys)
- `CompositionStart`: Composition start. (the original compositionstart)
- `Preedit` = `Preedit{ text: String, cursor_index: Option<usize>, }`: Text being composed. The cursor is a character position within the composition text. (the original compositionupdate, winit Ime::Preedit)
- `CompositionEnd`: Composition end. (the original compositionend)
- `Key` = `Key{ key: TextInputKey, is_shift: bool, }`: Editing key.
- `Paste` = `Paste(String)`: Text to paste. (after reading the clipboard asynchronously on the web)
- `ReplaceValue` = `ReplaceValue{ value: String, selection_start: usize, selection_end: usize, }`: The hidden <input>'s value changed. (web, the original handleDOMInputEvent)
- `Selection` = `Selection{ start: usize, end: usize, }`: The hidden <input>'s selection changed. (web, the original tick's selection polling)
- `FocusGained`: The hidden <input> got focus. (web, the original input focus event)
- `FocusLost`: The hidden <input> lost focus. (web, the original input blur event)
