WidgetTextInput.cpp 33 KB

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