WidgetTextInput.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. // Format the text and determine its total area.
  802. Vector2f content_area = FormatText();
  803. // If we're set to automatically generate horizontal scrollbars, check for that now.
  804. if (x_overflow_property == Overflow::Auto)
  805. {
  806. if (parent->GetClientWidth() < content_area.x)
  807. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  808. }
  809. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  810. if (y_overflow_property == Overflow::Auto)
  811. {
  812. if (parent->GetClientHeight() < content_area.y)
  813. {
  814. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  815. content_area = FormatText();
  816. if (x_overflow_property == Overflow::Auto &&
  817. parent->GetClientWidth() < content_area.x)
  818. {
  819. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  820. }
  821. }
  822. }
  823. parent->SetContentBox(Vector2f(0, 0), content_area);
  824. scroll->FormatScrollbars();
  825. }
  826. // Formats the input element's text field.
  827. Vector2f WidgetTextInput::FormatText()
  828. {
  829. Vector2f content_area(0, 0);
  830. // Clear the old lines, and all the lines in the text elements.
  831. lines.clear();
  832. text_element->ClearLines();
  833. selected_text_element->ClearLines();
  834. // Clear the selection background geometry, and get the vertices and indices so the new geo can
  835. // be generated.
  836. selection_geometry.Release(true);
  837. Vector< Vertex >& selection_vertices = selection_geometry.GetVertices();
  838. Vector< int >& selection_indices = selection_geometry.GetIndices();
  839. // Determine the line-height of the text element.
  840. const float line_height = parent->GetLineHeight();
  841. // When the selection contains endlines we expand the selection area by this width.
  842. const int endline_selection_width = int(0.4f * parent->GetComputedValues().font_size());
  843. int line_begin = 0;
  844. Vector2f line_position(0, 0);
  845. bool last_line = false;
  846. // Keep generating lines until all the text content is placed.
  847. do
  848. {
  849. Line line = {};
  850. line.value_offset = line_begin;
  851. float line_width;
  852. String line_content;
  853. // Generate the next line.
  854. last_line = text_element->GenerateLine(line_content, line.size, line_width, line_begin, parent->GetClientWidth() - cursor_size.x, 0, false, false);
  855. // 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
  856. // append the orphan onto the line even though it will push the line outside of the input field's bounds.
  857. if (!last_line && (line_content.empty() || line_content.back() != '\n'))
  858. {
  859. const String& text = GetValue();
  860. String orphan;
  861. for (int i = 1; i >= 0; --i)
  862. {
  863. int index = line_begin + line.size + i;
  864. if (index >= (int) text.size())
  865. continue;
  866. if (text[index] != ' ')
  867. {
  868. orphan.clear();
  869. continue;
  870. }
  871. int next_index = index + 1;
  872. if (!orphan.empty() ||
  873. next_index >= (int) text.size() ||
  874. text[next_index] != ' ')
  875. orphan += ' ';
  876. }
  877. if (!orphan.empty())
  878. {
  879. line_content += orphan;
  880. line.size += (int)orphan.size();
  881. line_width += ElementUtilities::GetStringWidth(text_element, orphan);
  882. }
  883. }
  884. // Now that we have the string of characters appearing on the new line, we split it into
  885. // three parts; the unselected text appearing before any selected text on the line, the
  886. // selected text on the line, and any unselected text after the selection.
  887. String pre_selection, selection, post_selection;
  888. GetLineSelection(pre_selection, selection, post_selection, line_content, line_begin);
  889. // The pre-selected text is placed, if there is any (if the selection starts on or before
  890. // the beginning of this line, then this will be empty).
  891. if (!pre_selection.empty())
  892. {
  893. text_element->AddLine(line_position, pre_selection);
  894. line_position.x += ElementUtilities::GetStringWidth(text_element, pre_selection);
  895. }
  896. // Return the extra kerning that would result in joining two strings.
  897. auto GetKerningBetween = [this](const String& left, const String& right) -> float {
  898. if (left.empty() || right.empty())
  899. return 0.0f;
  900. // 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
  901. // two neighboring characters from each string and compare the string width with and without kerning, which should be much faster.
  902. const Character left_back = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&left.back(), &left.front()));
  903. const String right_front_u8 = right.substr(0, size_t(StringUtilities::SeekForwardUTF8(right.c_str() + 1, right.c_str() + right.size()) - right.c_str()));
  904. const int width_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, left_back);
  905. const int width_no_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, Character::Null);
  906. return float(width_kerning - width_no_kerning);
  907. };
  908. // Check if the editable length needs to be truncated to dodge a trailing endline.
  909. line.editable_length = (int)line_content.size();
  910. if (!line_content.empty() && line_content.back() == '\n')
  911. line.editable_length -= 1;
  912. // If there is any selected text on this line, place it in the selected text element and
  913. // generate the geometry for its background.
  914. if (!selection.empty())
  915. {
  916. line_position.x += GetKerningBetween(pre_selection, selection);
  917. selected_text_element->AddLine(line_position, selection);
  918. const int selection_width = ElementUtilities::GetStringWidth(selected_text_element, selection);
  919. const bool selection_contains_endline = (selection_begin_index + selection_length > line_begin + line.editable_length);
  920. const Vector2f selection_size(float(selection_width + (selection_contains_endline ? endline_selection_width : 0)), line_height);
  921. selection_vertices.resize(selection_vertices.size() + 4);
  922. selection_indices.resize(selection_indices.size() + 6);
  923. GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6],
  924. line_position, selection_size, selection_colour, (int)selection_vertices.size() - 4);
  925. line_position.x += selection_width;
  926. }
  927. // If there is any unselected text after the selection on this line, place it in the
  928. // standard text element after the selected text.
  929. if (!post_selection.empty())
  930. {
  931. line_position.x += GetKerningBetween(selection, post_selection);
  932. text_element->AddLine(line_position, post_selection);
  933. }
  934. // Update variables for the next line.
  935. line_begin += line.size;
  936. line_position.x = 0;
  937. line_position.y += line_height;
  938. // Grow the content area width-wise if this line is the longest so far, and push the height out.
  939. content_area.x = Math::Max(content_area.x, line_width + cursor_size.x);
  940. content_area.y = line_position.y;
  941. // Finally, push the new line into our array of lines.
  942. lines.push_back(std::move(line));
  943. }
  944. while (!last_line);
  945. // Clamp the cursor to a valid range.
  946. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)GetValue().size());
  947. return content_area;
  948. }
  949. // Generates the text cursor.
  950. void WidgetTextInput::GenerateCursor()
  951. {
  952. // Generates the cursor.
  953. cursor_geometry.Release();
  954. Vector< Vertex >& vertices = cursor_geometry.GetVertices();
  955. vertices.resize(4);
  956. Vector< int >& indices = cursor_geometry.GetIndices();
  957. indices.resize(6);
  958. cursor_size.x = Math::RoundFloat( ElementUtilities::GetDensityIndependentPixelRatio(text_element) );
  959. cursor_size.y = text_element->GetLineHeight() + 2.0f;
  960. Colourb color = parent->GetComputedValues().color();
  961. if (const Property* property = parent->GetProperty(PropertyId::CaretColor))
  962. {
  963. if (property->unit == Property::COLOUR)
  964. color = property->Get<Colourb>();
  965. }
  966. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), cursor_size, color);
  967. }
  968. void WidgetTextInput::ForceFormattingOnNextLayout()
  969. {
  970. force_formatting_on_next_layout = true;
  971. }
  972. void WidgetTextInput::UpdateCursorPosition(bool update_ideal_cursor_position)
  973. {
  974. if (text_element->GetFontFaceHandle() == 0)
  975. return;
  976. int cursor_line_index = 0, cursor_character_index = 0;
  977. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  978. cursor_position.x = (float)ElementUtilities::GetStringWidth(text_element, GetValue().substr(lines[cursor_line_index].value_offset, cursor_character_index));
  979. cursor_position.y = -1.f + (float)cursor_line_index * text_element->GetLineHeight();
  980. if (update_ideal_cursor_position)
  981. ideal_cursor_position = cursor_position.x;
  982. }
  983. // Expand the text selection to the position of the cursor.
  984. void WidgetTextInput::UpdateSelection(bool selecting)
  985. {
  986. if (!selecting)
  987. {
  988. selection_anchor_index = absolute_cursor_index;
  989. ClearSelection();
  990. }
  991. else
  992. {
  993. int new_begin_index;
  994. int new_end_index;
  995. if (absolute_cursor_index > selection_anchor_index)
  996. {
  997. new_begin_index = selection_anchor_index;
  998. new_end_index = absolute_cursor_index;
  999. }
  1000. else
  1001. {
  1002. new_begin_index = absolute_cursor_index;
  1003. new_end_index = selection_anchor_index;
  1004. }
  1005. if (new_begin_index != selection_begin_index ||
  1006. new_end_index - new_begin_index != selection_length)
  1007. {
  1008. selection_begin_index = new_begin_index;
  1009. selection_length = new_end_index - new_begin_index;
  1010. FormatText();
  1011. }
  1012. }
  1013. }
  1014. // Removes the selection of text.
  1015. void WidgetTextInput::ClearSelection()
  1016. {
  1017. if (selection_length > 0)
  1018. {
  1019. selection_length = 0;
  1020. FormatElement();
  1021. }
  1022. }
  1023. // Deletes all selected text and removes the selection.
  1024. void WidgetTextInput::DeleteSelection()
  1025. {
  1026. if (selection_length > 0)
  1027. {
  1028. String new_value = GetAttributeValue();
  1029. const size_t selection_begin = std::min((size_t)selection_begin_index, (size_t)new_value.size());
  1030. new_value.erase(selection_begin, (size_t)selection_length);
  1031. GetElement()->SetAttribute("value", new_value);
  1032. // Move the cursor to the beginning of the old selection.
  1033. absolute_cursor_index = selection_begin_index;
  1034. UpdateCursorPosition(true);
  1035. // Erase our record of the selection.
  1036. UpdateSelection(false);
  1037. }
  1038. }
  1039. // Split one line of text into three parts, based on the current selection.
  1040. void WidgetTextInput::GetLineSelection(String& pre_selection, String& selection, String& post_selection, const String& line, int line_begin) const
  1041. {
  1042. const int selection_end = selection_begin_index + selection_length;
  1043. // Check if we have any selection at all, and if so if the selection is on this line.
  1044. if (selection_length <= 0 || selection_end < line_begin || selection_begin_index > line_begin + (int)line.size())
  1045. {
  1046. pre_selection = line;
  1047. return;
  1048. }
  1049. const int line_length = (int)line.size();
  1050. using namespace Math;
  1051. // Split the line up into its three parts, depending on the size and placement of the selection.
  1052. pre_selection = line.substr(0, Max(0, selection_begin_index - line_begin));
  1053. selection = line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin)));
  1054. post_selection = line.substr(Clamp(selection_end - line_begin, 0, line_length));
  1055. }
  1056. void WidgetTextInput::SetKeyboardActive(bool active)
  1057. {
  1058. if (SystemInterface* system = GetSystemInterface())
  1059. {
  1060. if (active)
  1061. {
  1062. // Activate the keyboard and submit the cursor position and line height to enable clients to adjust the input method editor (IME). Note
  1063. // that the cursor is extended by one pixel along the top and bottom, we reverse this extension here.
  1064. const Vector2f element_offset = parent->GetAbsoluteOffset() - scroll_offset;
  1065. const Vector2f absolute_cursor_position = element_offset + cursor_position + Vector2f(0, 1);
  1066. const float line_height = cursor_size.y - 2.f;
  1067. system->ActivateKeyboard(absolute_cursor_position, line_height);
  1068. }
  1069. else
  1070. {
  1071. system->DeactivateKeyboard();
  1072. }
  1073. }
  1074. }
  1075. } // namespace Rml