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