WidgetTextInput.cpp 36 KB

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