2
0

WidgetTextInput.cpp 37 KB

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