WidgetTextInput.cpp 39 KB

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