WidgetTextInput.cpp 42 KB

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