WidgetTextInput.cpp 36 KB

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