WidgetTextInput.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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 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. #include "WidgetTextInput.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/Core.h"
  31. #include "../../../Include/RmlUi/Core/ElementScroll.h"
  32. #include "../../../Include/RmlUi/Core/ElementText.h"
  33. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  34. #include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h"
  35. #include "../../../Include/RmlUi/Core/Factory.h"
  36. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  37. #include "../../../Include/RmlUi/Core/Input.h"
  38. #include "../../../Include/RmlUi/Core/Math.h"
  39. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  40. #include "../../../Include/RmlUi/Core/SystemInterface.h"
  41. #include "../Clock.h"
  42. #include "ElementTextSelection.h"
  43. #include <algorithm>
  44. #include <limits.h>
  45. namespace Rml {
  46. static constexpr float CURSOR_BLINK_TIME = 0.7f;
  47. enum class CharacterClass { Word, Punctuation, Newline, Whitespace, Undefined };
  48. static CharacterClass GetCharacterClass(char c)
  49. {
  50. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || ((unsigned char)c >= 128))
  51. return CharacterClass::Word;
  52. if ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~'))
  53. return CharacterClass::Punctuation;
  54. if (c == '\n')
  55. return CharacterClass::Newline;
  56. return CharacterClass::Whitespace;
  57. }
  58. WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : internal_dimensions(0, 0), scroll_offset(0, 0), selection_geometry(_parent), cursor_position(0, 0), cursor_size(0, 0), cursor_geometry(_parent)
  59. {
  60. keyboard_showed = false;
  61. parent = _parent;
  62. parent->SetProperty(PropertyId::WhiteSpace, Property(Style::WhiteSpace::Pre));
  63. parent->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Hidden));
  64. parent->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Hidden));
  65. parent->SetProperty(PropertyId::Drag, Property(Style::Drag::Drag));
  66. parent->SetProperty(PropertyId::WordBreak, Property(Style::WordBreak::BreakWord));
  67. parent->SetClientArea(Box::CONTENT);
  68. parent->AddEventListener(EventId::Keydown, this, true);
  69. parent->AddEventListener(EventId::Textinput, this, true);
  70. parent->AddEventListener(EventId::Focus, this, true);
  71. parent->AddEventListener(EventId::Blur, this, true);
  72. parent->AddEventListener(EventId::Mousedown, this, true);
  73. parent->AddEventListener(EventId::Dblclick, this, true);
  74. parent->AddEventListener(EventId::Drag, this, true);
  75. ElementPtr unique_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  76. text_element = rmlui_dynamic_cast< ElementText* >(unique_text.get());
  77. ElementPtr unique_selected_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  78. selected_text_element = rmlui_dynamic_cast< ElementText* >(unique_selected_text.get());
  79. if (text_element)
  80. {
  81. text_element->SuppressAutoLayout();
  82. parent->AppendChild(std::move(unique_text), false);
  83. selected_text_element->SuppressAutoLayout();
  84. parent->AppendChild(std::move(unique_selected_text), false);
  85. }
  86. // Create the dummy selection element.
  87. ElementPtr unique_selection = Factory::InstanceElement(parent, "#selection", "selection", XMLAttributes());
  88. if (ElementTextSelection* text_selection_element = rmlui_dynamic_cast<ElementTextSelection*>(unique_selection.get()))
  89. {
  90. selection_element = text_selection_element;
  91. text_selection_element->SetWidget(this);
  92. parent->AppendChild(std::move(unique_selection), false);
  93. }
  94. absolute_cursor_index = 0;
  95. cursor_wrap_down = false;
  96. ideal_cursor_position_to_the_right_of_cursor = true;
  97. cancel_next_drag = false;
  98. ideal_cursor_position = 0;
  99. max_length = -1;
  100. selection_anchor_index = 0;
  101. selection_begin_index = 0;
  102. selection_length = 0;
  103. last_update_time = 0;
  104. ShowCursor(false);
  105. }
  106. WidgetTextInput::~WidgetTextInput()
  107. {
  108. parent->RemoveEventListener(EventId::Keydown, this, true);
  109. parent->RemoveEventListener(EventId::Textinput, this, true);
  110. parent->RemoveEventListener(EventId::Focus, this, true);
  111. parent->RemoveEventListener(EventId::Blur, this, true);
  112. parent->RemoveEventListener(EventId::Mousedown, this, true);
  113. parent->RemoveEventListener(EventId::Dblclick, this, true);
  114. parent->RemoveEventListener(EventId::Drag, this, true);
  115. // Remove all the children added by the text widget.
  116. parent->RemoveChild(text_element);
  117. parent->RemoveChild(selected_text_element);
  118. parent->RemoveChild(selection_element);
  119. }
  120. void WidgetTextInput::SetValue(String value)
  121. {
  122. const size_t initial_size = value.size();
  123. SanitizeValue(value);
  124. if (initial_size != value.size())
  125. {
  126. parent->SetAttribute("value", value);
  127. DispatchChangeEvent();
  128. }
  129. else
  130. {
  131. TransformValue(value);
  132. RMLUI_ASSERTMSG(value.size() == initial_size, "TransformValue must not change the text length.");
  133. text_element->SetText(value);
  134. FormatElement();
  135. }
  136. }
  137. void WidgetTextInput::TransformValue(String& /*value*/) {}
  138. // Sets the maximum length (in characters) of this text field.
  139. void WidgetTextInput::SetMaxLength(int _max_length)
  140. {
  141. if (max_length != _max_length)
  142. {
  143. max_length = _max_length;
  144. if (max_length >= 0)
  145. {
  146. String value = GetValue();
  147. int num_characters = 0;
  148. size_t i_erase = value.size();
  149. for (auto it = StringIteratorU8(value); it; ++it)
  150. {
  151. num_characters += 1;
  152. if (num_characters > max_length)
  153. {
  154. i_erase = size_t(it.offset());
  155. break;
  156. }
  157. }
  158. if(i_erase < value.size())
  159. {
  160. value.erase(i_erase);
  161. GetElement()->SetAttribute("value", value);
  162. }
  163. }
  164. }
  165. }
  166. // Returns the maximum length (in characters) of this text field.
  167. int WidgetTextInput::GetMaxLength() const
  168. {
  169. return max_length;
  170. }
  171. int WidgetTextInput::GetLength() const
  172. {
  173. size_t result = StringUtilities::LengthUTF8(GetValue());
  174. return (int)result;
  175. }
  176. // Update the colours of the selected text.
  177. void WidgetTextInput::UpdateSelectionColours()
  178. {
  179. // Determine what the colour of the selected text is. If our 'selection' element has the 'color'
  180. // attribute set, then use that. Otherwise, use the inverse of our own text colour.
  181. Colourb colour;
  182. const Property* colour_property = selection_element->GetLocalProperty("color");
  183. if (colour_property != nullptr)
  184. colour = colour_property->Get< Colourb >();
  185. else
  186. {
  187. colour = parent->GetComputedValues().color();
  188. colour.red = 255 - colour.red;
  189. colour.green = 255 - colour.green;
  190. colour.blue = 255 - colour.blue;
  191. }
  192. // Set the computed text colour on the element holding the selected text.
  193. selected_text_element->SetProperty(PropertyId::Color, Property(colour, Property::COLOUR));
  194. // If the 'background-color' property has been set on the 'selection' element, use that as the
  195. // background colour for the selected text. Otherwise, use the inverse of the selected text
  196. // colour.
  197. colour_property = selection_element->GetLocalProperty("background-color");
  198. if (colour_property != nullptr)
  199. selection_colour = colour_property->Get< Colourb >();
  200. else
  201. selection_colour = Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha);
  202. // Color may have changed, so we update the cursor geometry.
  203. GenerateCursor();
  204. }
  205. // Updates the cursor, if necessary.
  206. void WidgetTextInput::OnUpdate()
  207. {
  208. if (cursor_timer > 0)
  209. {
  210. double current_time = Clock::GetElapsedTime();
  211. cursor_timer -= float(current_time - last_update_time);
  212. last_update_time = current_time;
  213. while (cursor_timer <= 0)
  214. {
  215. cursor_timer += CURSOR_BLINK_TIME;
  216. cursor_visible = !cursor_visible;
  217. }
  218. }
  219. }
  220. void WidgetTextInput::OnResize()
  221. {
  222. GenerateCursor();
  223. Vector2f text_position = parent->GetBox().GetPosition(Box::CONTENT);
  224. text_element->SetOffset(text_position, parent);
  225. selected_text_element->SetOffset(text_position, parent);
  226. }
  227. // Renders the cursor, if it is visible.
  228. void WidgetTextInput::OnRender()
  229. {
  230. ElementUtilities::SetClippingRegion(text_element);
  231. Vector2f text_translation = parent->GetAbsoluteOffset() - Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
  232. selection_geometry.Render(text_translation);
  233. if (cursor_visible &&
  234. !parent->IsDisabled())
  235. {
  236. cursor_geometry.Render(text_translation + cursor_position);
  237. }
  238. }
  239. // Formats the widget's internal content.
  240. void WidgetTextInput::OnLayout()
  241. {
  242. FormatElement();
  243. Vector2f new_internal_dimensions = parent->GetBox().GetSize(Box::CONTENT);
  244. if (new_internal_dimensions != internal_dimensions)
  245. {
  246. internal_dimensions = new_internal_dimensions;
  247. UpdateCursorPosition(true);
  248. }
  249. parent->SetScrollLeft(scroll_offset.x);
  250. parent->SetScrollTop(scroll_offset.y);
  251. }
  252. // Returns the input element's underlying text element.
  253. ElementText* WidgetTextInput::GetTextElement()
  254. {
  255. return text_element;
  256. }
  257. // Returns the input element's maximum allowed text dimensions.
  258. Vector2f WidgetTextInput::GetTextDimensions() const
  259. {
  260. return internal_dimensions;
  261. }
  262. // Gets the parent element containing the widget.
  263. Element* WidgetTextInput::GetElement() const
  264. {
  265. return parent;
  266. }
  267. // Dispatches a change event to the widget's element.
  268. void WidgetTextInput::DispatchChangeEvent(bool linebreak)
  269. {
  270. Dictionary parameters;
  271. parameters["value"] = GetAttributeValue();
  272. parameters["linebreak"] = Variant(linebreak);
  273. GetElement()->DispatchEvent(EventId::Change, parameters);
  274. }
  275. // Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set
  276. // the state of the cursor.
  277. void WidgetTextInput::ProcessEvent(Event& event)
  278. {
  279. if (parent->IsDisabled())
  280. return;
  281. switch (event.GetId())
  282. {
  283. case EventId::Keydown:
  284. {
  285. Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
  286. bool numlock = event.GetParameter< int >("num_lock_key", 0) > 0;
  287. bool shift = event.GetParameter< int >("shift_key", 0) > 0;
  288. bool ctrl = event.GetParameter< int >("ctrl_key", 0) > 0;
  289. switch (key_identifier)
  290. {
  291. case Input::KI_NUMPAD4: if (numlock) break; //-fallthrough
  292. case Input::KI_LEFT: MoveCursorHorizontal(ctrl ? CursorMovement::PreviousWord : CursorMovement::Left, shift); break;
  293. case Input::KI_NUMPAD6: if (numlock) break; //-fallthrough
  294. case Input::KI_RIGHT: MoveCursorHorizontal(ctrl ? CursorMovement::NextWord : CursorMovement::Right, shift); break;
  295. case Input::KI_NUMPAD8: if (numlock) break; //-fallthrough
  296. case Input::KI_UP: MoveCursorVertical(-1, shift); break;
  297. case Input::KI_NUMPAD2: if (numlock) break; //-fallthrough
  298. case Input::KI_DOWN: MoveCursorVertical(1, shift); break;
  299. case Input::KI_NUMPAD7: if (numlock) break; //-fallthrough
  300. case Input::KI_HOME: MoveCursorHorizontal(ctrl ? CursorMovement::Begin : CursorMovement::BeginLine, shift); break;
  301. case Input::KI_NUMPAD1: if (numlock) break; //-fallthrough
  302. case Input::KI_END: MoveCursorHorizontal(ctrl ? CursorMovement::End : CursorMovement::EndLine, shift); break;
  303. case Input::KI_NUMPAD9: if (numlock) break; //-fallthrough
  304. case Input::KI_PRIOR: MoveCursorVertical(-int(internal_dimensions.y / parent->GetLineHeight()) + 1, shift); break;
  305. case Input::KI_NUMPAD3: if (numlock) break; //-fallthrough
  306. case Input::KI_NEXT: MoveCursorVertical(int(internal_dimensions.y / parent->GetLineHeight()) - 1, shift); break;
  307. case Input::KI_BACK:
  308. {
  309. CursorMovement direction = (ctrl ? CursorMovement::PreviousWord : CursorMovement::Left);
  310. if (DeleteCharacters(direction))
  311. FormatElement();
  312. ShowCursor(true);
  313. }
  314. break;
  315. case Input::KI_DECIMAL: if (numlock) break; //-fallthrough
  316. case Input::KI_DELETE:
  317. {
  318. CursorMovement direction = (ctrl ? CursorMovement::NextWord : CursorMovement::Right);
  319. if (DeleteCharacters(direction))
  320. FormatElement();
  321. ShowCursor(true);
  322. }
  323. break;
  324. case Input::KI_NUMPADENTER:
  325. case Input::KI_RETURN:
  326. {
  327. LineBreak();
  328. }
  329. break;
  330. case Input::KI_A:
  331. {
  332. if (ctrl)
  333. {
  334. MoveCursorHorizontal(CursorMovement::Begin, false);
  335. MoveCursorHorizontal(CursorMovement::End, true);
  336. }
  337. }
  338. break;
  339. case Input::KI_C:
  340. {
  341. if (ctrl && selection_length > 0)
  342. CopySelection();
  343. }
  344. break;
  345. case Input::KI_X:
  346. {
  347. if (ctrl && selection_length > 0)
  348. {
  349. CopySelection();
  350. DeleteSelection();
  351. DispatchChangeEvent();
  352. ShowCursor(true);
  353. }
  354. }
  355. break;
  356. case Input::KI_V:
  357. {
  358. if (ctrl)
  359. {
  360. String clipboard_text;
  361. GetSystemInterface()->GetClipboardText(clipboard_text);
  362. AddCharacters(clipboard_text);
  363. ShowCursor(true);
  364. }
  365. }
  366. break;
  367. // Ignore tabs so input fields can be navigated through with keys.
  368. case Input::KI_TAB:
  369. return;
  370. default:
  371. break;
  372. }
  373. event.StopPropagation();
  374. }
  375. break;
  376. case EventId::Textinput:
  377. {
  378. // Only process the text if no modifier keys are pressed.
  379. if (event.GetParameter< int >("ctrl_key", 0) == 0 &&
  380. event.GetParameter< int >("alt_key", 0) == 0 &&
  381. event.GetParameter< int >("meta_key", 0) == 0)
  382. {
  383. String text = event.GetParameter("text", String{});
  384. AddCharacters(text);
  385. }
  386. ShowCursor(true);
  387. event.StopPropagation();
  388. }
  389. break;
  390. case EventId::Focus:
  391. {
  392. if (event.GetTargetElement() == parent)
  393. {
  394. UpdateSelection(false);
  395. ShowCursor(true, false);
  396. }
  397. }
  398. break;
  399. case EventId::Blur:
  400. {
  401. if (event.GetTargetElement() == parent)
  402. {
  403. ClearSelection();
  404. ShowCursor(false, false);
  405. }
  406. }
  407. break;
  408. case EventId::Drag:
  409. if (cancel_next_drag)
  410. {
  411. // We currently ignore drag events right after a double click. They would need to be handled
  412. // specially by selecting whole words at a time, which is not yet implemented.
  413. break;
  414. }
  415. //-fallthrough
  416. case EventId::Mousedown:
  417. {
  418. if (event.GetTargetElement() == parent)
  419. {
  420. Vector2f mouse_position = Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0));
  421. mouse_position -= text_element->GetAbsoluteOffset();
  422. const int cursor_line_index = CalculateLineIndex(mouse_position.y);
  423. const int cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
  424. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  425. MoveCursorToCharacterBoundaries(false);
  426. UpdateCursorPosition(true);
  427. UpdateSelection(event == EventId::Drag || event.GetParameter< int >("shift_key", 0) > 0);
  428. ShowCursor(true);
  429. cancel_next_drag = false;
  430. }
  431. }
  432. break;
  433. case EventId::Dblclick:
  434. {
  435. if (event.GetTargetElement() == parent)
  436. {
  437. ExpandSelection();
  438. cancel_next_drag = true;
  439. }
  440. }
  441. break;
  442. default:
  443. break;
  444. }
  445. }
  446. // Adds a new character to the string at the cursor position.
  447. bool WidgetTextInput::AddCharacters(String string)
  448. {
  449. SanitizeValue(string);
  450. if (string.empty())
  451. return false;
  452. if (selection_length > 0)
  453. DeleteSelection();
  454. if (max_length >= 0 && GetLength() >= max_length)
  455. return false;
  456. String value = GetAttributeValue();
  457. value.insert(std::min<size_t>((size_t)absolute_cursor_index, value.size()), string);
  458. parent->SetAttribute("value", value);
  459. absolute_cursor_index += (int)string.size();
  460. DispatchChangeEvent();
  461. UpdateCursorPosition(true);
  462. UpdateSelection(false);
  463. return true;
  464. }
  465. // Deletes a character from the string.
  466. bool WidgetTextInput::DeleteCharacters(CursorMovement direction)
  467. {
  468. // We set a selection of characters according to direction, and then delete it.
  469. // If we already have a selection, we delete that first.
  470. if (selection_length <= 0)
  471. MoveCursorHorizontal(direction, true);
  472. if (selection_length > 0)
  473. {
  474. DeleteSelection();
  475. DispatchChangeEvent();
  476. return true;
  477. }
  478. return false;
  479. }
  480. // Copies the selection (if any) to the clipboard.
  481. void WidgetTextInput::CopySelection()
  482. {
  483. const String& value = GetValue();
  484. const String snippet = value.substr(std::min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length);
  485. GetSystemInterface()->SetClipboardText(snippet);
  486. }
  487. // Moves the cursor along the current line.
  488. void WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select)
  489. {
  490. const String& value = GetValue();
  491. int cursor_line_index = 0, cursor_character_index = 0;
  492. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  493. // By default the cursor wraps down when located on softbreaks. This may be overridden by setting the cursor using relative indices.
  494. cursor_wrap_down = true;
  495. // Whether to seek forward or back to align to utf8 boundaries later.
  496. bool seek_forward = false;
  497. switch (movement)
  498. {
  499. case CursorMovement::Begin:
  500. absolute_cursor_index = 0;
  501. break;
  502. case CursorMovement::BeginLine:
  503. SetCursorFromRelativeIndices(cursor_line_index, 0);
  504. break;
  505. case CursorMovement::PreviousWord:
  506. {
  507. // First skip whitespace, then skip all characters of the same class as the first non-whitespace character.
  508. CharacterClass skip_character_class = CharacterClass::Whitespace;
  509. const char* p_rend = value.data();
  510. const char* p_rbegin = p_rend + absolute_cursor_index;
  511. const char* p = p_rbegin - 1;
  512. for (; p > p_rend; --p)
  513. {
  514. const CharacterClass character_class = GetCharacterClass(*p);
  515. if (character_class != skip_character_class)
  516. {
  517. if (skip_character_class == CharacterClass::Whitespace)
  518. skip_character_class = character_class;
  519. else
  520. break;
  521. }
  522. }
  523. if (p != p_rend)
  524. ++p;
  525. absolute_cursor_index += int(p - p_rbegin);
  526. }
  527. break;
  528. case CursorMovement::Left:
  529. if (!select && selection_length > 0)
  530. absolute_cursor_index = selection_begin_index;
  531. else
  532. absolute_cursor_index -= 1;
  533. break;
  534. case CursorMovement::Right:
  535. seek_forward = true;
  536. if (!select && selection_length > 0)
  537. absolute_cursor_index = selection_begin_index + selection_length;
  538. else
  539. absolute_cursor_index += 1;
  540. break;
  541. case CursorMovement::NextWord:
  542. {
  543. // First skip all characters of the same class as the first character, then skip any whitespace.
  544. CharacterClass skip_character_class = CharacterClass::Undefined;
  545. const char* p_begin = value.data() + absolute_cursor_index;
  546. const char* p_end = value.data() + value.size();
  547. const char* p = p_begin;
  548. for (; p < p_end; ++p)
  549. {
  550. const CharacterClass character_class = GetCharacterClass(*p);
  551. if (skip_character_class == CharacterClass::Undefined)
  552. skip_character_class = character_class;
  553. if (character_class != skip_character_class)
  554. {
  555. if (character_class == CharacterClass::Whitespace)
  556. skip_character_class = CharacterClass::Whitespace;
  557. else
  558. break;
  559. }
  560. }
  561. absolute_cursor_index += int(p - p_begin);
  562. }
  563. break;
  564. case CursorMovement::EndLine:
  565. SetCursorFromRelativeIndices(cursor_line_index, lines[cursor_line_index].editable_length);
  566. break;
  567. case CursorMovement::End:
  568. absolute_cursor_index = INT_MAX;
  569. break;
  570. default:
  571. break;
  572. }
  573. absolute_cursor_index = Math::Clamp(absolute_cursor_index, 0, (int)GetValue().size());
  574. MoveCursorToCharacterBoundaries(seek_forward);
  575. UpdateCursorPosition(true);
  576. UpdateSelection(select);
  577. ShowCursor(true);
  578. }
  579. // Moves the cursor up and down the text field.
  580. void WidgetTextInput::MoveCursorVertical(int distance, bool select)
  581. {
  582. int cursor_line_index = 0, cursor_character_index = 0;
  583. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  584. cursor_line_index += distance;
  585. if (cursor_line_index < 0)
  586. {
  587. cursor_line_index = 0;
  588. cursor_character_index = 0;
  589. }
  590. else if (cursor_line_index >= (int)lines.size())
  591. {
  592. cursor_line_index = (int)lines.size() - 1;
  593. cursor_character_index = (int)lines[cursor_line_index].editable_length;
  594. }
  595. else
  596. cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
  597. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  598. MoveCursorToCharacterBoundaries(false);
  599. UpdateCursorPosition(false);
  600. UpdateSelection(select);
  601. ShowCursor(true);
  602. }
  603. void WidgetTextInput::MoveCursorToCharacterBoundaries(bool forward)
  604. {
  605. const String& value = GetValue();
  606. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)value.size());
  607. const char* p_begin = value.data();
  608. const char* p_end = p_begin + value.size();
  609. const char* p_cursor = p_begin + absolute_cursor_index;
  610. const char* p = p_cursor;
  611. if (forward)
  612. p = StringUtilities::SeekForwardUTF8(p_cursor, p_end);
  613. else
  614. p = StringUtilities::SeekBackwardUTF8(p_cursor, p_begin);
  615. if (p != p_cursor)
  616. absolute_cursor_index += int(p - p_cursor);
  617. }
  618. void WidgetTextInput::ExpandSelection()
  619. {
  620. const String& value = GetValue();
  621. const char* const p_begin = value.data();
  622. const char* const p_end = p_begin + value.size();
  623. const char* const p_index = p_begin + absolute_cursor_index;
  624. // The first character encountered defines the character class to expand.
  625. CharacterClass expanding_character_class = CharacterClass::Undefined;
  626. auto character_is_wrong_type = [&expanding_character_class](const char* p) -> bool {
  627. const CharacterClass character_class = GetCharacterClass(*p);
  628. if (expanding_character_class == CharacterClass::Undefined)
  629. expanding_character_class = character_class;
  630. else if (character_class != expanding_character_class)
  631. return true;
  632. return false;
  633. };
  634. auto search_left = [&]() -> const char* {
  635. const char* p = p_index;
  636. for (; p > p_begin; p--)
  637. if (character_is_wrong_type(p - 1))
  638. break;
  639. return p;
  640. };
  641. auto search_right = [&]() -> const char* {
  642. const char* p = p_index;
  643. for (; p < p_end; p++)
  644. if (character_is_wrong_type(p))
  645. break;
  646. return p;
  647. };
  648. const char* p_left = p_index;
  649. const char* p_right = p_index;
  650. if (ideal_cursor_position_to_the_right_of_cursor)
  651. {
  652. p_right = search_right();
  653. p_left = search_left();
  654. }
  655. else
  656. {
  657. p_left = search_left();
  658. p_right = search_right();
  659. }
  660. cursor_wrap_down = true;
  661. absolute_cursor_index -= int(p_index - p_left);
  662. MoveCursorToCharacterBoundaries(false);
  663. UpdateSelection(false);
  664. absolute_cursor_index += int(p_right - p_left);
  665. MoveCursorToCharacterBoundaries(true);
  666. UpdateSelection(true);
  667. UpdateCursorPosition(true);
  668. }
  669. const String& WidgetTextInput::GetValue() const
  670. {
  671. return text_element->GetText();
  672. }
  673. String WidgetTextInput::GetAttributeValue() const
  674. {
  675. return parent->GetAttribute("value", String());
  676. }
  677. void WidgetTextInput::GetRelativeCursorIndices(int& out_cursor_line_index, int& out_cursor_character_index) const
  678. {
  679. int line_begin = 0;
  680. for (size_t i = 0; i < lines.size(); i++)
  681. {
  682. const int cursor_relative_line_end = absolute_cursor_index - (line_begin + lines[i].editable_length);
  683. // Test if the absolute index is located on the editable part of this line, otherwise we wrap down to the next line. We may have additional
  684. // characters after the editable length, such as the newline character '\n'. We also wrap down if the cursor is located to the right of any
  685. // such characters.
  686. if (cursor_relative_line_end <= 0)
  687. {
  688. const bool soft_wrapped_line = (lines[i].editable_length == lines[i].size);
  689. // If we are located exactly on a soft break (due to word wrapping) then the cursor wrap state determines whether or not we wrap down.
  690. if (cursor_relative_line_end == 0 && soft_wrapped_line && cursor_wrap_down && (int)i + 1 < (int)lines.size())
  691. {
  692. out_cursor_line_index = (int)i + 1;
  693. out_cursor_character_index = 0;
  694. }
  695. else
  696. {
  697. out_cursor_line_index = (int)i;
  698. out_cursor_character_index = Math::Max(absolute_cursor_index - line_begin, 0);
  699. }
  700. return;
  701. }
  702. line_begin += lines[i].size;
  703. }
  704. // We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
  705. // just set the relative cursors to the very end of the text field.
  706. out_cursor_line_index = (int)lines.size() - 1;
  707. out_cursor_character_index = lines[out_cursor_line_index].editable_length;
  708. }
  709. void WidgetTextInput::SetCursorFromRelativeIndices(int cursor_line_index, int cursor_character_index)
  710. {
  711. RMLUI_ASSERT(cursor_line_index < (int)lines.size())
  712. absolute_cursor_index = cursor_character_index;
  713. for (int i = 0; i < cursor_line_index; i++)
  714. absolute_cursor_index += lines[i].size;
  715. // Don't wrap down if we're located at the end of the line.
  716. cursor_wrap_down = !(cursor_character_index >= lines[cursor_line_index].editable_length);
  717. }
  718. // Calculates the line index under a specific vertical position.
  719. int WidgetTextInput::CalculateLineIndex(float position) const
  720. {
  721. float line_height = parent->GetLineHeight();
  722. int line_index = Math::RealToInteger(position / line_height);
  723. return Math::Clamp(line_index, 0, (int) (lines.size() - 1));
  724. }
  725. // Calculates the character index along a line under a specific horizontal position.
  726. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
  727. {
  728. int prev_offset = 0;
  729. float prev_line_width = 0;
  730. ideal_cursor_position_to_the_right_of_cursor = true;
  731. const char* p_begin = GetValue().data() + lines[line_index].value_offset;
  732. for (auto it = StringIteratorU8(p_begin, p_begin, p_begin + lines[line_index].editable_length); it;)
  733. {
  734. ++it;
  735. const int offset = (int)it.offset();
  736. const float line_width = (float)ElementUtilities::GetStringWidth(text_element, String(p_begin, (size_t)offset));
  737. if (line_width > position)
  738. {
  739. if (position - prev_line_width < line_width - position)
  740. {
  741. return prev_offset;
  742. }
  743. else
  744. {
  745. ideal_cursor_position_to_the_right_of_cursor = false;
  746. return offset;
  747. }
  748. }
  749. prev_line_width = line_width;
  750. prev_offset = offset;
  751. }
  752. return prev_offset;
  753. }
  754. // Shows or hides the cursor.
  755. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
  756. {
  757. if (show)
  758. {
  759. cursor_visible = true;
  760. cursor_timer = CURSOR_BLINK_TIME;
  761. last_update_time = GetSystemInterface()->GetElapsedTime();
  762. // Shift the cursor into view.
  763. if (move_to_cursor)
  764. {
  765. float minimum_scroll_top = (cursor_position.y + cursor_size.y) - parent->GetClientHeight();
  766. if (parent->GetScrollTop() < minimum_scroll_top)
  767. parent->SetScrollTop(minimum_scroll_top);
  768. else if (parent->GetScrollTop() > cursor_position.y)
  769. parent->SetScrollTop(cursor_position.y);
  770. float minimum_scroll_left = (cursor_position.x + cursor_size.x) - parent->GetClientWidth();
  771. if (parent->GetScrollLeft() < minimum_scroll_left)
  772. parent->SetScrollLeft(minimum_scroll_left);
  773. else if (parent->GetScrollLeft() > cursor_position.x)
  774. parent->SetScrollLeft(cursor_position.x);
  775. scroll_offset.x = parent->GetScrollLeft();
  776. scroll_offset.y = parent->GetScrollTop();
  777. }
  778. SetKeyboardActive(true);
  779. keyboard_showed = true;
  780. }
  781. else
  782. {
  783. cursor_visible = false;
  784. cursor_timer = -1;
  785. last_update_time = 0;
  786. if (keyboard_showed)
  787. {
  788. SetKeyboardActive(false);
  789. keyboard_showed = false;
  790. }
  791. }
  792. }
  793. // Formats the element, laying out the text and inserting scrollbars as appropriate.
  794. void WidgetTextInput::FormatElement()
  795. {
  796. using namespace Style;
  797. ElementScroll* scroll = parent->GetElementScroll();
  798. float width = parent->GetBox().GetSize(Box::PADDING).x;
  799. Overflow x_overflow_property = parent->GetComputedValues().overflow_x();
  800. Overflow y_overflow_property = parent->GetComputedValues().overflow_y();
  801. if (x_overflow_property == Overflow::Scroll)
  802. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  803. else
  804. scroll->DisableScrollbar(ElementScroll::HORIZONTAL);
  805. if (y_overflow_property == Overflow::Scroll)
  806. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  807. else
  808. scroll->DisableScrollbar(ElementScroll::VERTICAL);
  809. // Format the text and determine its total area.
  810. Vector2f content_area = FormatText();
  811. // If we're set to automatically generate horizontal scrollbars, check for that now.
  812. if (x_overflow_property == Overflow::Auto)
  813. {
  814. if (parent->GetClientWidth() < content_area.x)
  815. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  816. }
  817. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  818. if (y_overflow_property == Overflow::Auto)
  819. {
  820. if (parent->GetClientHeight() < content_area.y)
  821. {
  822. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  823. content_area = FormatText();
  824. if (x_overflow_property == Overflow::Auto &&
  825. parent->GetClientWidth() < content_area.x)
  826. {
  827. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  828. }
  829. }
  830. }
  831. parent->SetContentBox(Vector2f(0, 0), content_area);
  832. scroll->FormatScrollbars();
  833. }
  834. // Formats the input element's text field.
  835. Vector2f WidgetTextInput::FormatText()
  836. {
  837. Vector2f content_area(0, 0);
  838. // Clear the old lines, and all the lines in the text elements.
  839. lines.clear();
  840. text_element->ClearLines();
  841. selected_text_element->ClearLines();
  842. // Clear the selection background geometry, and get the vertices and indices so the new geo can
  843. // be generated.
  844. selection_geometry.Release(true);
  845. Vector< Vertex >& selection_vertices = selection_geometry.GetVertices();
  846. Vector< int >& selection_indices = selection_geometry.GetIndices();
  847. // Determine the line-height of the text element.
  848. const float line_height = parent->GetLineHeight();
  849. // When the selection contains endlines we expand the selection area by this width.
  850. const int endline_selection_width = int(0.4f * parent->GetComputedValues().font_size());
  851. int line_begin = 0;
  852. Vector2f line_position(0, 0);
  853. bool last_line = false;
  854. // Keep generating lines until all the text content is placed.
  855. do
  856. {
  857. Line line = {};
  858. line.value_offset = line_begin;
  859. float line_width;
  860. String line_content;
  861. // Generate the next line.
  862. last_line = text_element->GenerateLine(line_content, line.size, line_width, line_begin, parent->GetClientWidth() - cursor_size.x, 0, false, false);
  863. // If this line terminates in a soft-return (word wrap), then the line may be leaving a space or two behind as an orphan. If so, we must
  864. // append the orphan onto the line even though it will push the line outside of the input field's bounds.
  865. if (!last_line && (line_content.empty() || line_content.back() != '\n'))
  866. {
  867. const String& text = GetValue();
  868. String orphan;
  869. for (int i = 1; i >= 0; --i)
  870. {
  871. int index = line_begin + line.size + i;
  872. if (index >= (int) text.size())
  873. continue;
  874. if (text[index] != ' ')
  875. {
  876. orphan.clear();
  877. continue;
  878. }
  879. int next_index = index + 1;
  880. if (!orphan.empty() ||
  881. next_index >= (int) text.size() ||
  882. text[next_index] != ' ')
  883. orphan += ' ';
  884. }
  885. if (!orphan.empty())
  886. {
  887. line_content += orphan;
  888. line.size += (int)orphan.size();
  889. line_width += ElementUtilities::GetStringWidth(text_element, orphan);
  890. }
  891. }
  892. // Now that we have the string of characters appearing on the new line, we split it into
  893. // three parts; the unselected text appearing before any selected text on the line, the
  894. // selected text on the line, and any unselected text after the selection.
  895. String pre_selection, selection, post_selection;
  896. GetLineSelection(pre_selection, selection, post_selection, line_content, line_begin);
  897. // The pre-selected text is placed, if there is any (if the selection starts on or before
  898. // the beginning of this line, then this will be empty).
  899. if (!pre_selection.empty())
  900. {
  901. text_element->AddLine(line_position, pre_selection);
  902. line_position.x += ElementUtilities::GetStringWidth(text_element, pre_selection);
  903. }
  904. // Return the extra kerning that would result in joining two strings.
  905. auto GetKerningBetween = [this](const String& left, const String& right) -> float {
  906. if (left.empty() || right.empty())
  907. return 0.0f;
  908. // We could join the whole string, and compare the result of the joined width to the individual widths of each string. Instead, we just take the
  909. // two neighboring characters from each string and compare the string width with and without kerning, which should be much faster.
  910. const Character left_back = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&left.back(), &left.front()));
  911. const String right_front_u8 = right.substr(0, size_t(StringUtilities::SeekForwardUTF8(right.c_str() + 1, right.c_str() + right.size()) - right.c_str()));
  912. const int width_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, left_back);
  913. const int width_no_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, Character::Null);
  914. return float(width_kerning - width_no_kerning);
  915. };
  916. // Check if the editable length needs to be truncated to dodge a trailing endline.
  917. line.editable_length = (int)line_content.size();
  918. if (!line_content.empty() && line_content.back() == '\n')
  919. line.editable_length -= 1;
  920. // If there is any selected text on this line, place it in the selected text element and
  921. // generate the geometry for its background.
  922. if (!selection.empty())
  923. {
  924. line_position.x += GetKerningBetween(pre_selection, selection);
  925. selected_text_element->AddLine(line_position, selection);
  926. const int selection_width = ElementUtilities::GetStringWidth(selected_text_element, selection);
  927. const bool selection_contains_endline = (selection_begin_index + selection_length > line_begin + line.editable_length);
  928. const Vector2f selection_size(float(selection_width + (selection_contains_endline ? endline_selection_width : 0)), line_height);
  929. selection_vertices.resize(selection_vertices.size() + 4);
  930. selection_indices.resize(selection_indices.size() + 6);
  931. GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6],
  932. line_position, selection_size, selection_colour, (int)selection_vertices.size() - 4);
  933. line_position.x += selection_width;
  934. }
  935. // If there is any unselected text after the selection on this line, place it in the
  936. // standard text element after the selected text.
  937. if (!post_selection.empty())
  938. {
  939. line_position.x += GetKerningBetween(selection, post_selection);
  940. text_element->AddLine(line_position, post_selection);
  941. }
  942. // Update variables for the next line.
  943. line_begin += line.size;
  944. line_position.x = 0;
  945. line_position.y += line_height;
  946. // Grow the content area width-wise if this line is the longest so far, and push the height out.
  947. content_area.x = Math::Max(content_area.x, line_width + cursor_size.x);
  948. content_area.y = line_position.y;
  949. // Finally, push the new line into our array of lines.
  950. lines.push_back(std::move(line));
  951. }
  952. while (!last_line);
  953. // Clamp the cursor to a valid range.
  954. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)GetValue().size());
  955. return content_area;
  956. }
  957. // Generates the text cursor.
  958. void WidgetTextInput::GenerateCursor()
  959. {
  960. // Generates the cursor.
  961. cursor_geometry.Release();
  962. Vector< Vertex >& vertices = cursor_geometry.GetVertices();
  963. vertices.resize(4);
  964. Vector< int >& indices = cursor_geometry.GetIndices();
  965. indices.resize(6);
  966. cursor_size.x = Math::RoundFloat( ElementUtilities::GetDensityIndependentPixelRatio(text_element) );
  967. cursor_size.y = text_element->GetLineHeight() + 2.0f;
  968. Colourb color = parent->GetComputedValues().color();
  969. if (const Property* property = parent->GetProperty(PropertyId::CaretColor))
  970. {
  971. if (property->unit == Property::COLOUR)
  972. color = property->Get<Colourb>();
  973. }
  974. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), cursor_size, color);
  975. }
  976. void WidgetTextInput::UpdateCursorPosition(bool update_ideal_cursor_position)
  977. {
  978. if (text_element->GetFontFaceHandle() == 0)
  979. return;
  980. int cursor_line_index = 0, cursor_character_index = 0;
  981. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  982. cursor_position.x = (float)ElementUtilities::GetStringWidth(text_element, GetValue().substr(lines[cursor_line_index].value_offset, cursor_character_index));
  983. cursor_position.y = -1.f + (float)cursor_line_index * text_element->GetLineHeight();
  984. if (update_ideal_cursor_position)
  985. ideal_cursor_position = cursor_position.x;
  986. }
  987. // Expand the text selection to the position of the cursor.
  988. void WidgetTextInput::UpdateSelection(bool selecting)
  989. {
  990. if (!selecting)
  991. {
  992. selection_anchor_index = absolute_cursor_index;
  993. ClearSelection();
  994. }
  995. else
  996. {
  997. int new_begin_index;
  998. int new_end_index;
  999. if (absolute_cursor_index > selection_anchor_index)
  1000. {
  1001. new_begin_index = selection_anchor_index;
  1002. new_end_index = absolute_cursor_index;
  1003. }
  1004. else
  1005. {
  1006. new_begin_index = absolute_cursor_index;
  1007. new_end_index = selection_anchor_index;
  1008. }
  1009. if (new_begin_index != selection_begin_index ||
  1010. new_end_index - new_begin_index != selection_length)
  1011. {
  1012. selection_begin_index = new_begin_index;
  1013. selection_length = new_end_index - new_begin_index;
  1014. FormatText();
  1015. }
  1016. }
  1017. }
  1018. // Removes the selection of text.
  1019. void WidgetTextInput::ClearSelection()
  1020. {
  1021. if (selection_length > 0)
  1022. {
  1023. selection_length = 0;
  1024. FormatElement();
  1025. }
  1026. }
  1027. // Deletes all selected text and removes the selection.
  1028. void WidgetTextInput::DeleteSelection()
  1029. {
  1030. if (selection_length > 0)
  1031. {
  1032. String new_value = GetAttributeValue();
  1033. const size_t selection_begin = std::min((size_t)selection_begin_index, (size_t)new_value.size());
  1034. new_value.erase(selection_begin, (size_t)selection_length);
  1035. GetElement()->SetAttribute("value", new_value);
  1036. // Move the cursor to the beginning of the old selection.
  1037. absolute_cursor_index = selection_begin_index;
  1038. UpdateCursorPosition(true);
  1039. // Erase our record of the selection.
  1040. UpdateSelection(false);
  1041. }
  1042. }
  1043. // Split one line of text into three parts, based on the current selection.
  1044. void WidgetTextInput::GetLineSelection(String& pre_selection, String& selection, String& post_selection, const String& line, int line_begin) const
  1045. {
  1046. const int selection_end = selection_begin_index + selection_length;
  1047. // Check if we have any selection at all, and if so if the selection is on this line.
  1048. if (selection_length <= 0 || selection_end < line_begin || selection_begin_index > line_begin + (int)line.size())
  1049. {
  1050. pre_selection = line;
  1051. return;
  1052. }
  1053. const int line_length = (int)line.size();
  1054. using namespace Math;
  1055. // Split the line up into its three parts, depending on the size and placement of the selection.
  1056. pre_selection = line.substr(0, Max(0, selection_begin_index - line_begin));
  1057. selection = line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin)));
  1058. post_selection = line.substr(Clamp(selection_end - line_begin, 0, line_length));
  1059. }
  1060. void WidgetTextInput::SetKeyboardActive(bool active)
  1061. {
  1062. if (SystemInterface* system = GetSystemInterface())
  1063. {
  1064. if (active)
  1065. {
  1066. // Activate the keyboard and submit the cursor position and line height to enable clients to adjust the input method editor (IME). Note
  1067. // that the cursor is extended by one pixel along the top and bottom, we reverse this extension here.
  1068. const Vector2f element_offset = parent->GetAbsoluteOffset() - scroll_offset;
  1069. const Vector2f absolute_cursor_position = element_offset + cursor_position + Vector2f(0, 1);
  1070. const float line_height = cursor_size.y - 2.f;
  1071. system->ActivateKeyboard(absolute_cursor_position, line_height);
  1072. }
  1073. else
  1074. {
  1075. system->DeactivateKeyboard();
  1076. }
  1077. }
  1078. }
  1079. } // namespace Rml