WidgetTextInput.cpp 41 KB

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