WidgetTextInput.cpp 36 KB

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