WidgetTextInput.cpp 37 KB

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