WidgetTextInput.cpp 37 KB

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