WidgetTextInput.cpp 37 KB

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