WidgetTextInput.cpp 32 KB

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