WidgetTextInput.cpp 41 KB

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