WidgetTextInput.cpp 36 KB

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