WidgetTextInput.cpp 42 KB

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