WidgetTextInput.cpp 38 KB

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