WidgetTextInput.cpp 36 KB

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