WidgetTextInput.cpp 40 KB

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