WidgetTextInput.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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.h"
  31. #include "../../Include/RmlUi/Controls/ElementFormControl.h"
  32. #include "../../Include/RmlUi/Core/SystemInterface.h"
  33. #include "../Core/Clock.h"
  34. namespace Rml {
  35. namespace Controls {
  36. static const float CURSOR_BLINK_TIME = 0.7f;
  37. 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)
  38. {
  39. // TODO: Check all usage of .size(), they are not the same as characters anymore
  40. keyboard_showed = false;
  41. parent = _parent;
  42. parent->SetProperty(Core::PropertyId::WhiteSpace, Core::Property(Core::Style::WhiteSpace::Pre));
  43. parent->SetProperty(Core::PropertyId::OverflowX, Core::Property(Core::Style::Overflow::Hidden));
  44. parent->SetProperty(Core::PropertyId::OverflowY, Core::Property(Core::Style::Overflow::Hidden));
  45. parent->SetProperty(Core::PropertyId::Drag, Core::Property(Core::Style::Drag::Drag));
  46. parent->SetClientArea(Rml::Core::Box::CONTENT);
  47. parent->AddEventListener(Core::EventId::Keydown, this, true);
  48. parent->AddEventListener(Core::EventId::Textinput, this, true);
  49. parent->AddEventListener(Core::EventId::Focus, this, true);
  50. parent->AddEventListener(Core::EventId::Blur, this, true);
  51. parent->AddEventListener(Core::EventId::Mousedown, this, true);
  52. parent->AddEventListener(Core::EventId::Drag, this, true);
  53. Core::ElementPtr unique_text = Core::Factory::InstanceElement(parent, "#text", "#text", Rml::Core::XMLAttributes());
  54. text_element = dynamic_cast< Core::ElementText* >(unique_text.get());
  55. Core::ElementPtr unique_selected_text = Core::Factory::InstanceElement(parent, "#text", "#text", Rml::Core::XMLAttributes());
  56. selected_text_element = dynamic_cast< Core::ElementText* >(unique_selected_text.get());
  57. if (text_element)
  58. {
  59. text_element->SuppressAutoLayout();
  60. parent->AppendChild(std::move(unique_text), false);
  61. selected_text_element->SuppressAutoLayout();
  62. parent->AppendChild(std::move(unique_selected_text), false);
  63. }
  64. // Create the dummy selection element.
  65. Core::ElementPtr unique_selection = Core::Factory::InstanceElement(parent, "#selection", "selection", Rml::Core::XMLAttributes());
  66. if (ElementTextSelection* text_selection_element = dynamic_cast<ElementTextSelection*>(unique_selection.get()))
  67. {
  68. selection_element = text_selection_element;
  69. text_selection_element->SetWidget(this);
  70. parent->AppendChild(std::move(unique_selection), false);
  71. }
  72. edit_index = 0;
  73. absolute_cursor_index = 0;
  74. cursor_line_index = 0;
  75. cursor_character_index = 0;
  76. ideal_cursor_position = 0;
  77. max_length = -1;
  78. selection_anchor_index = 0;
  79. selection_begin_index = 0;
  80. selection_length = 0;
  81. last_update_time = 0;
  82. ShowCursor(false);
  83. }
  84. WidgetTextInput::~WidgetTextInput()
  85. {
  86. parent->RemoveEventListener(Core::EventId::Keydown, this, true);
  87. parent->RemoveEventListener(Core::EventId::Textinput, this, true);
  88. parent->RemoveEventListener(Core::EventId::Focus, this, true);
  89. parent->RemoveEventListener(Core::EventId::Blur, this, true);
  90. parent->RemoveEventListener(Core::EventId::Mousedown, this, true);
  91. parent->RemoveEventListener(Core::EventId::Drag, this, true);
  92. // Remove all the children added by the text widget.
  93. parent->RemoveChild(text_element);
  94. parent->RemoveChild(selected_text_element);
  95. parent->RemoveChild(selection_element);
  96. }
  97. // Sets the value of the text field.
  98. void WidgetTextInput::SetValue(const Core::String& value)
  99. {
  100. text_element->SetText(value);
  101. FormatElement();
  102. UpdateRelativeCursor();
  103. }
  104. // Sets the maximum length (in characters) of this text field.
  105. void WidgetTextInput::SetMaxLength(int _max_length)
  106. {
  107. if (max_length != _max_length)
  108. {
  109. max_length = _max_length;
  110. if (max_length >= 0)
  111. {
  112. Core::String value = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  113. int num_characters = 0;
  114. size_t i_erase = value.size();
  115. for (auto it = Core::StringIteratorU8(value); it; ++it)
  116. {
  117. num_characters += 1;
  118. if (num_characters > max_length)
  119. {
  120. i_erase = size_t(it.Get() - value.data());
  121. break;
  122. }
  123. }
  124. if(i_erase < value.size())
  125. {
  126. value.erase(i_erase);
  127. GetElement()->SetAttribute("value", value);
  128. }
  129. }
  130. }
  131. }
  132. // Returns the maximum length (in characters) of this text field.
  133. int WidgetTextInput::GetMaxLength() const
  134. {
  135. return max_length;
  136. }
  137. int WidgetTextInput::GetLength() const
  138. {
  139. Core::String value = GetElement()->GetAttribute< Core::String >("value", "");
  140. size_t result = Core::StringUtilities::LengthU8(value);
  141. return (int)result;
  142. }
  143. // Update the colours of the selected text.
  144. void WidgetTextInput::UpdateSelectionColours()
  145. {
  146. // Determine what the colour of the selected text is. If our 'selection' element has the 'color'
  147. // attribute set, then use that. Otherwise, use the inverse of our own text colour.
  148. Rml::Core::Colourb colour;
  149. const Rml::Core::Property* colour_property = selection_element->GetLocalProperty("color");
  150. if (colour_property != nullptr)
  151. colour = colour_property->Get< Rml::Core::Colourb >();
  152. else
  153. {
  154. colour = parent->GetComputedValues().color;
  155. colour.red = 255 - colour.red;
  156. colour.green = 255 - colour.green;
  157. colour.blue = 255 - colour.blue;
  158. }
  159. // Set the computed text colour on the element holding the selected text.
  160. selected_text_element->SetProperty(Core::PropertyId::Color, Rml::Core::Property(colour, Rml::Core::Property::COLOUR));
  161. // If the 'background-color' property has been set on the 'selection' element, use that as the
  162. // background colour for the selected text. Otherwise, use the inverse of the selected text
  163. // colour.
  164. colour_property = selection_element->GetLocalProperty("background-color");
  165. if (colour_property != nullptr)
  166. selection_colour = colour_property->Get< Rml::Core::Colourb >();
  167. else
  168. selection_colour = Rml::Core::Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha);
  169. }
  170. // Updates the cursor, if necessary.
  171. void WidgetTextInput::OnUpdate()
  172. {
  173. if (cursor_timer > 0)
  174. {
  175. double current_time = Core::Clock::GetElapsedTime();
  176. cursor_timer -= float(current_time - last_update_time);
  177. last_update_time = current_time;
  178. while (cursor_timer <= 0)
  179. {
  180. cursor_timer += CURSOR_BLINK_TIME;
  181. cursor_visible = !cursor_visible;
  182. }
  183. }
  184. }
  185. void WidgetTextInput::OnResize()
  186. {
  187. GenerateCursor();
  188. Rml::Core::Vector2f text_position = parent->GetBox().GetPosition(Core::Box::CONTENT);
  189. text_element->SetOffset(text_position, parent);
  190. selected_text_element->SetOffset(text_position, parent);
  191. Rml::Core::Vector2f new_internal_dimensions = parent->GetBox().GetSize(Core::Box::CONTENT);
  192. if (new_internal_dimensions != internal_dimensions)
  193. {
  194. internal_dimensions = new_internal_dimensions;
  195. FormatElement();
  196. UpdateCursorPosition();
  197. }
  198. }
  199. // Renders the cursor, if it is visible.
  200. void WidgetTextInput::OnRender()
  201. {
  202. Core::ElementUtilities::SetClippingRegion(text_element);
  203. Rml::Core::Vector2f text_translation = parent->GetAbsoluteOffset() - Rml::Core::Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
  204. selection_geometry.Render(text_translation);
  205. if (cursor_visible &&
  206. !parent->IsDisabled())
  207. {
  208. cursor_geometry.Render(text_translation + cursor_position);
  209. }
  210. }
  211. // Formats the widget's internal content.
  212. void WidgetTextInput::OnLayout()
  213. {
  214. FormatElement();
  215. parent->SetScrollLeft(scroll_offset.x);
  216. parent->SetScrollTop(scroll_offset.y);
  217. }
  218. // Returns the input element's underlying text element.
  219. Core::ElementText* WidgetTextInput::GetTextElement()
  220. {
  221. return text_element;
  222. }
  223. // Returns the input element's maximum allowed text dimensions.
  224. const Rml::Core::Vector2f& WidgetTextInput::GetTextDimensions() const
  225. {
  226. return internal_dimensions;
  227. }
  228. // Gets the parent element containing the widget.
  229. Core::Element* WidgetTextInput::GetElement() const
  230. {
  231. return parent;
  232. }
  233. // Dispatches a change event to the widget's element.
  234. void WidgetTextInput::DispatchChangeEvent(bool linebreak)
  235. {
  236. Rml::Core::Dictionary parameters;
  237. parameters["value"] = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  238. parameters["linebreak"] = Core::Variant(linebreak);
  239. GetElement()->DispatchEvent(Core::EventId::Change, parameters);
  240. }
  241. // Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set
  242. // the state of the cursor.
  243. void WidgetTextInput::ProcessEvent(Core::Event& event)
  244. {
  245. if (parent->IsDisabled())
  246. return;
  247. using Rml::Core::EventId;
  248. switch (event.GetId())
  249. {
  250. case EventId::Keydown:
  251. {
  252. Core::Input::KeyIdentifier key_identifier = (Core::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
  253. bool numlock = event.GetParameter< int >("num_lock_key", 0) > 0;
  254. bool shift = event.GetParameter< int >("shift_key", 0) > 0;
  255. bool ctrl = event.GetParameter< int >("ctrl_key", 0) > 0;
  256. switch (key_identifier)
  257. {
  258. case Core::Input::KI_NUMPAD4: if (numlock) break;
  259. case Core::Input::KI_LEFT: MoveCursorHorizontal(-1, shift); break;
  260. case Core::Input::KI_NUMPAD6: if (numlock) break;
  261. case Core::Input::KI_RIGHT: MoveCursorHorizontal(1, shift); break;
  262. case Core::Input::KI_NUMPAD8: if (numlock) break;
  263. case Core::Input::KI_UP: MoveCursorVertical(-1, shift); break;
  264. case Core::Input::KI_NUMPAD2: if (numlock) break;
  265. case Core::Input::KI_DOWN: MoveCursorVertical(1, shift); break;
  266. case Core::Input::KI_NUMPAD7: if (numlock) break;
  267. case Core::Input::KI_HOME: MoveCursorHorizontal(-cursor_character_index, shift); break;
  268. case Core::Input::KI_NUMPAD1: if (numlock) break;
  269. case Core::Input::KI_END: MoveCursorHorizontal(lines[cursor_line_index].content_length - cursor_character_index, shift); break;
  270. case Core::Input::KI_BACK:
  271. {
  272. if (DeleteCharacter(true))
  273. {
  274. FormatElement();
  275. UpdateRelativeCursor();
  276. }
  277. ShowCursor(true);
  278. }
  279. break;
  280. case Core::Input::KI_DECIMAL: if (numlock) break;
  281. case Core::Input::KI_DELETE:
  282. {
  283. if (DeleteCharacter(false))
  284. {
  285. FormatElement();
  286. UpdateRelativeCursor();
  287. }
  288. ShowCursor(true);
  289. }
  290. break;
  291. case Core::Input::KI_NUMPADENTER:
  292. case Core::Input::KI_RETURN:
  293. {
  294. LineBreak();
  295. }
  296. break;
  297. case Core::Input::KI_C:
  298. {
  299. if (ctrl)
  300. CopySelection();
  301. }
  302. break;
  303. case Core::Input::KI_X:
  304. {
  305. if (ctrl)
  306. {
  307. CopySelection();
  308. DeleteSelection();
  309. }
  310. }
  311. break;
  312. case Core::Input::KI_V:
  313. {
  314. if (ctrl)
  315. {
  316. Core::String clipboard_text;
  317. Core::GetSystemInterface()->GetClipboardText(clipboard_text);
  318. // @performance: Can be made heaps faster.
  319. for (auto it = Core::StringIteratorU8(clipboard_text); it; ++it)
  320. {
  321. Core::CodePoint code = *it;
  322. AddCharacter(code);
  323. }
  324. }
  325. }
  326. break;
  327. // Ignore tabs so input fields can be navigated through with keys.
  328. case Core::Input::KI_TAB:
  329. return;
  330. default:
  331. break;
  332. }
  333. event.StopPropagation();
  334. }
  335. break;
  336. case EventId::Textinput:
  337. {
  338. // Only process the text if no modifier keys are pressed.
  339. if (event.GetParameter< int >("ctrl_key", 0) == 0 &&
  340. event.GetParameter< int >("alt_key", 0) == 0 &&
  341. event.GetParameter< int >("meta_key", 0) == 0)
  342. {
  343. Rml::Core::CodePoint character = event.GetParameter("data", Rml::Core::CodePoint::Null);
  344. AddCharacter(character);
  345. }
  346. ShowCursor(true);
  347. event.StopPropagation();
  348. }
  349. break;
  350. case EventId::Focus:
  351. {
  352. if (event.GetTargetElement() == parent)
  353. {
  354. UpdateSelection(false);
  355. ShowCursor(true, false);
  356. }
  357. }
  358. break;
  359. case EventId::Blur:
  360. {
  361. if (event.GetTargetElement() == parent)
  362. {
  363. ClearSelection();
  364. ShowCursor(false, false);
  365. }
  366. }
  367. break;
  368. case EventId::Mousedown:
  369. case EventId::Drag:
  370. {
  371. if (event.GetTargetElement() == parent)
  372. {
  373. Core::Vector2f mouse_position = Core::Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0));
  374. mouse_position -= text_element->GetAbsoluteOffset();
  375. cursor_line_index = CalculateLineIndex(mouse_position.y);
  376. cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
  377. UpdateAbsoluteCursor();
  378. UpdateCursorPosition();
  379. ideal_cursor_position = cursor_position.x;
  380. UpdateSelection(event == Core::EventId::Drag || event.GetParameter< int >("shift_key", 0) > 0);
  381. ShowCursor(true);
  382. }
  383. }
  384. break;
  385. default:
  386. break;
  387. }
  388. }
  389. // Adds a new character to the string at the cursor position.
  390. bool WidgetTextInput::AddCharacter(Rml::Core::CodePoint character)
  391. {
  392. if (!IsCharacterValid(static_cast<char>(character)))
  393. return false;
  394. if (selection_length > 0)
  395. DeleteSelection();
  396. if (max_length >= 0 && GetLength() >= max_length)
  397. return false;
  398. Core::String value = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  399. Core::String insert = Core::StringUtilities::ToUTF8(character);
  400. value.insert(GetCursorIndex(), insert);
  401. edit_index += insert.size();
  402. GetElement()->SetAttribute("value", value);
  403. DispatchChangeEvent();
  404. UpdateSelection(false);
  405. return true;
  406. }
  407. // Deletes a character from the string.
  408. bool WidgetTextInput::DeleteCharacter(bool back)
  409. {
  410. // First, check if we have anything selected; if so, delete that first before we start delete
  411. // individual characters.
  412. if (selection_length > 0)
  413. {
  414. DeleteSelection();
  415. DispatchChangeEvent();
  416. UpdateSelection(false);
  417. return true;
  418. }
  419. Core::String value = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  420. if (back)
  421. {
  422. if (GetCursorIndex() == 0)
  423. return false;
  424. value.erase(GetCursorIndex() - 1, 1);
  425. edit_index -= 1;
  426. }
  427. else
  428. {
  429. if (GetCursorIndex() == (int) value.size())
  430. return false;
  431. value.erase(GetCursorIndex(), 1);
  432. }
  433. GetElement()->SetAttribute("value", value);
  434. DispatchChangeEvent();
  435. UpdateSelection(false);
  436. return true;
  437. }
  438. // Copies the selection (if any) to the clipboard.
  439. void WidgetTextInput::CopySelection()
  440. {
  441. const Core::String& value = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  442. const Core::String snippet = value.substr(selection_begin_index, selection_length);
  443. Core::GetSystemInterface()->SetClipboardText(snippet);
  444. }
  445. // Returns the absolute index of the cursor.
  446. int WidgetTextInput::GetCursorIndex() const
  447. {
  448. // TODO: Sanitize cursor index ?
  449. return edit_index;
  450. }
  451. // Moves the cursor along the current line.
  452. void WidgetTextInput::MoveCursorHorizontal(int distance, bool select)
  453. {
  454. // Todo, move properly across multibyte characters
  455. absolute_cursor_index += distance;
  456. absolute_cursor_index = Rml::Core::Math::Max(0, absolute_cursor_index);
  457. UpdateRelativeCursor();
  458. ideal_cursor_position = cursor_position.x;
  459. UpdateSelection(select);
  460. ShowCursor(true);
  461. }
  462. // Moves the cursor up and down the text field.
  463. void WidgetTextInput::MoveCursorVertical(int distance, bool select)
  464. {
  465. bool update_ideal_cursor_position = false;
  466. cursor_line_index += distance;
  467. if (cursor_line_index < 0)
  468. {
  469. cursor_line_index = 0;
  470. cursor_character_index = 0;
  471. update_ideal_cursor_position = true;
  472. }
  473. else if (cursor_line_index >= (int) lines.size())
  474. {
  475. cursor_line_index = (int) lines.size() - 1;
  476. cursor_character_index = (int) lines[cursor_line_index].content_length;
  477. update_ideal_cursor_position = true;
  478. }
  479. else
  480. cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
  481. UpdateAbsoluteCursor();
  482. UpdateCursorPosition();
  483. if (update_ideal_cursor_position)
  484. ideal_cursor_position = cursor_position.x;
  485. UpdateSelection(select);
  486. ShowCursor(true);
  487. }
  488. // Updates the absolute cursor index from the relative cursor indices.
  489. void WidgetTextInput::UpdateAbsoluteCursor()
  490. {
  491. RMLUI_ASSERT(cursor_line_index < (int) lines.size())
  492. absolute_cursor_index = cursor_character_index;
  493. edit_index = cursor_character_index;
  494. for (int i = 0; i < cursor_line_index; i++)
  495. {
  496. absolute_cursor_index += (int)lines[i].content.size();
  497. edit_index += (int)lines[i].content.size() + lines[i].extra_characters;
  498. }
  499. }
  500. // Updates the relative cursor indices from the absolute cursor index.
  501. void WidgetTextInput::UpdateRelativeCursor()
  502. {
  503. int num_characters = 0;
  504. edit_index = absolute_cursor_index;
  505. for (size_t i = 0; i < lines.size(); i++)
  506. {
  507. if (num_characters + lines[i].content_length >= absolute_cursor_index)
  508. {
  509. cursor_line_index = (int) i;
  510. cursor_character_index = absolute_cursor_index - num_characters;
  511. UpdateCursorPosition();
  512. return;
  513. }
  514. num_characters += (int) lines[i].content.size();
  515. edit_index += lines[i].extra_characters;
  516. }
  517. // We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
  518. // just set the relative cursors to the very end of the text field, and update the absolute cursor to point here.
  519. cursor_line_index = (int) lines.size() - 1;
  520. cursor_character_index = lines[cursor_line_index].content_length;
  521. absolute_cursor_index = num_characters;
  522. edit_index = num_characters;
  523. UpdateCursorPosition();
  524. }
  525. // Calculates the line index under a specific vertical position.
  526. int WidgetTextInput::CalculateLineIndex(float position)
  527. {
  528. float line_height = parent->GetLineHeight();
  529. int line_index = Rml::Core::Math::RealToInteger(position / line_height);
  530. return Rml::Core::Math::Clamp(line_index, 0, (int) (lines.size() - 1));
  531. }
  532. // Calculates the character index along a line under a specific horizontal position.
  533. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
  534. {
  535. // Todo, move properly across multibyte characters
  536. int character_index = 0;
  537. float line_width = 0;
  538. while (character_index < lines[line_index].content_length)
  539. {
  540. float next_line_width = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[line_index].content.substr(0, character_index));
  541. if (next_line_width > position)
  542. {
  543. if (position - line_width < next_line_width - position)
  544. return Rml::Core::Math::Max(0, character_index - 1);
  545. else
  546. return character_index;
  547. }
  548. line_width = next_line_width;
  549. character_index++;
  550. }
  551. return character_index;
  552. }
  553. // Shows or hides the cursor.
  554. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
  555. {
  556. if (show)
  557. {
  558. cursor_visible = true;
  559. SetKeyboardActive(true);
  560. keyboard_showed = true;
  561. cursor_timer = CURSOR_BLINK_TIME;
  562. last_update_time = Core::GetSystemInterface()->GetElapsedTime();
  563. // Shift the cursor into view.
  564. if (move_to_cursor)
  565. {
  566. float minimum_scroll_top = (cursor_position.y + cursor_size.y) - parent->GetClientHeight();
  567. if (parent->GetScrollTop() < minimum_scroll_top)
  568. parent->SetScrollTop(minimum_scroll_top);
  569. else if (parent->GetScrollTop() > cursor_position.y)
  570. parent->SetScrollTop(cursor_position.y);
  571. float minimum_scroll_left = (cursor_position.x + cursor_size.x) - parent->GetClientWidth();
  572. if (parent->GetScrollLeft() < minimum_scroll_left)
  573. parent->SetScrollLeft(minimum_scroll_left);
  574. else if (parent->GetScrollLeft() > cursor_position.x)
  575. parent->SetScrollLeft(cursor_position.x);
  576. scroll_offset.x = parent->GetScrollLeft();
  577. scroll_offset.y = parent->GetScrollTop();
  578. }
  579. }
  580. else
  581. {
  582. cursor_visible = false;
  583. cursor_timer = -1;
  584. last_update_time = 0;
  585. if (keyboard_showed)
  586. {
  587. SetKeyboardActive(false);
  588. keyboard_showed = false;
  589. }
  590. }
  591. }
  592. // Formats the element, laying out the text and inserting scrollbars as appropriate.
  593. void WidgetTextInput::FormatElement()
  594. {
  595. using namespace Core::Style;
  596. Core::ElementScroll* scroll = parent->GetElementScroll();
  597. float width = parent->GetBox().GetSize(Core::Box::PADDING).x;
  598. Overflow x_overflow_property = parent->GetComputedValues().overflow_x;
  599. Overflow y_overflow_property = parent->GetComputedValues().overflow_y;
  600. if (x_overflow_property == Overflow::Scroll)
  601. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  602. else
  603. scroll->DisableScrollbar(Core::ElementScroll::HORIZONTAL);
  604. if (y_overflow_property == Overflow::Scroll)
  605. scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
  606. else
  607. scroll->DisableScrollbar(Core::ElementScroll::VERTICAL);
  608. // Format the text and determine its total area.
  609. Rml::Core::Vector2f content_area = FormatText();
  610. // If we're set to automatically generate horizontal scrollbars, check for that now.
  611. if (x_overflow_property == Overflow::Auto)
  612. {
  613. if (parent->GetClientWidth() < content_area.x)
  614. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  615. }
  616. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  617. if (y_overflow_property == Overflow::Auto)
  618. {
  619. if (parent->GetClientHeight() < content_area.y)
  620. {
  621. scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
  622. content_area = FormatText();
  623. if (x_overflow_property == Overflow::Auto &&
  624. parent->GetClientWidth() < content_area.y)
  625. {
  626. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  627. }
  628. }
  629. }
  630. parent->SetContentBox(Rml::Core::Vector2f(0, 0), content_area);
  631. scroll->FormatScrollbars();
  632. }
  633. // Formats the input element's text field.
  634. Rml::Core::Vector2f WidgetTextInput::FormatText()
  635. {
  636. absolute_cursor_index = edit_index;
  637. Rml::Core::Vector2f content_area(0, 0);
  638. // Clear the old lines, and all the lines in the text elements.
  639. lines.clear();
  640. text_element->ClearLines();
  641. selected_text_element->ClearLines();
  642. // Clear the selection background geometry, and get the vertices and indices so the new geo can
  643. // be generated.
  644. selection_geometry.Release(true);
  645. std::vector< Core::Vertex >& selection_vertices = selection_geometry.GetVertices();
  646. std::vector< int >& selection_indices = selection_geometry.GetIndices();
  647. // Determine the line-height of the text element.
  648. float line_height = parent->GetLineHeight();
  649. int line_begin = 0;
  650. Rml::Core::Vector2f line_position(0, 0);
  651. bool last_line = false;
  652. // Keep generating lines until all the text content is placed.
  653. do
  654. {
  655. Line line;
  656. line.extra_characters = 0;
  657. float line_width;
  658. // Generate the next line.
  659. last_line = text_element->GenerateLine(line.content, line.content_length, line_width, line_begin, parent->GetClientWidth() - cursor_size.x, 0, false);
  660. // If this line terminates in a soft-return, then the line may be leaving a space or two behind as an orphan.
  661. // If so, we must append the orphan onto the line even though it will push the line outside of the input
  662. // field's bounds.
  663. bool soft_return = false;
  664. if (!last_line &&
  665. (line.content.empty() ||
  666. line.content[line.content.size() - 1] != '\n'))
  667. {
  668. soft_return = true;
  669. const Core::String& text = text_element->GetText();
  670. Core::String orphan;
  671. for (int i = 1; i >= 0; --i)
  672. {
  673. int index = line_begin + line.content_length + i;
  674. if (index >= (int) text.size())
  675. continue;
  676. if (text[index] != ' ')
  677. {
  678. orphan.clear();
  679. continue;
  680. }
  681. int next_index = index + 1;
  682. if (!orphan.empty() ||
  683. next_index >= (int) text.size() ||
  684. text[next_index] != ' ')
  685. orphan += ' ';
  686. }
  687. if (!orphan.empty())
  688. {
  689. line.content += orphan;
  690. line.content_length += (int) orphan.size();
  691. line_width += Core::ElementUtilities::GetStringWidth(text_element, orphan);
  692. }
  693. }
  694. // Now that we have the string of characters appearing on the new line, we split it into
  695. // three parts; the unselected text appearing before any selected text on the line, the
  696. // selected text on the line, and any unselected text after the selection.
  697. Core::String pre_selection, selection, post_selection;
  698. GetLineSelection(pre_selection, selection, post_selection, line.content, line_begin);
  699. // The pre-selected text is placed, if there is any (if the selection starts on or before
  700. // the beginning of this line, then this will be empty).
  701. if (!pre_selection.empty())
  702. {
  703. text_element->AddLine(line_position, pre_selection);
  704. line_position.x += Core::ElementUtilities::GetStringWidth(text_element, pre_selection);
  705. }
  706. // If there is any selected text on this line, place it in the selected text element and
  707. // generate the geometry for its background.
  708. if (!selection.empty())
  709. {
  710. selected_text_element->AddLine(line_position, selection);
  711. int selection_width = Core::ElementUtilities::GetStringWidth(selected_text_element, selection);
  712. selection_vertices.resize(selection_vertices.size() + 4);
  713. selection_indices.resize(selection_indices.size() + 6);
  714. Core::GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6], line_position, Rml::Core::Vector2f((float)selection_width, line_height), selection_colour, (int)selection_vertices.size() - 4);
  715. line_position.x += selection_width;
  716. }
  717. // If there is any unselected text after the selection on this line, place it in the
  718. // standard text element after the selected text.
  719. if (!post_selection.empty())
  720. text_element->AddLine(line_position, post_selection);
  721. // Update variables for the next line.
  722. line_begin += line.content_length;
  723. line_position.x = 0;
  724. line_position.y += line_height;
  725. // Grow the content area width-wise if this line is the longest so far, and push the
  726. // height out.
  727. content_area.x = Rml::Core::Math::Max(content_area.x, line_width + cursor_size.x);
  728. content_area.y = line_position.y;
  729. // Push a trailing '\r' token onto the back to indicate a soft return if necessary.
  730. if (soft_return)
  731. {
  732. line.content += '\r';
  733. line.extra_characters -= 1;
  734. if (edit_index >= line_begin)
  735. absolute_cursor_index += 1;
  736. }
  737. // Push the new line into our array of lines, but first check if its content length needs to be truncated to
  738. // dodge a trailing endline.
  739. if (!line.content.empty() &&
  740. line.content[line.content.size() - 1] == '\n')
  741. line.content_length -= 1;
  742. lines.push_back(line);
  743. }
  744. while (!last_line);
  745. return content_area;
  746. }
  747. // Generates the text cursor.
  748. void WidgetTextInput::GenerateCursor()
  749. {
  750. // Generates the cursor.
  751. cursor_geometry.Release();
  752. std::vector< Core::Vertex >& vertices = cursor_geometry.GetVertices();
  753. vertices.resize(4);
  754. std::vector< int >& indices = cursor_geometry.GetIndices();
  755. indices.resize(6);
  756. cursor_size.x = Core::ElementUtilities::GetDensityIndependentPixelRatio(text_element);
  757. cursor_size.y = text_element->GetLineHeight() + 2.0f;
  758. Core::GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Rml::Core::Vector2f(0, 0), cursor_size, parent->GetProperty< Rml::Core::Colourb >("color"));
  759. }
  760. void WidgetTextInput::UpdateCursorPosition()
  761. {
  762. if (text_element->GetFontFaceHandle() == nullptr)
  763. return;
  764. cursor_position.x = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[cursor_line_index].content.substr(0, cursor_character_index));
  765. cursor_position.y = -1.f + (float)cursor_line_index * text_element->GetLineHeight();
  766. }
  767. // Expand the text selection to the position of the cursor.
  768. void WidgetTextInput::UpdateSelection(bool selecting)
  769. {
  770. if (!selecting)
  771. {
  772. selection_anchor_index = edit_index;
  773. ClearSelection();
  774. }
  775. else
  776. {
  777. int new_begin_index;
  778. int new_end_index;
  779. if (edit_index > selection_anchor_index)
  780. {
  781. new_begin_index = selection_anchor_index;
  782. new_end_index = edit_index;
  783. }
  784. else
  785. {
  786. new_begin_index = edit_index;
  787. new_end_index = selection_anchor_index;
  788. }
  789. if (new_begin_index != selection_begin_index ||
  790. new_end_index - new_begin_index != selection_length)
  791. {
  792. selection_begin_index = new_begin_index;
  793. selection_length = new_end_index - new_begin_index;
  794. FormatText();
  795. }
  796. }
  797. }
  798. // Removes the selection of text.
  799. void WidgetTextInput::ClearSelection()
  800. {
  801. if (selection_length > 0)
  802. {
  803. selection_length = 0;
  804. FormatElement();
  805. }
  806. }
  807. // Deletes all selected text and removes the selection.
  808. void WidgetTextInput::DeleteSelection()
  809. {
  810. if (selection_length > 0)
  811. {
  812. const Core::String& value = GetElement()->GetAttribute< Rml::Core::String >("value", "");
  813. Rml::Core::String new_value = value.substr(0, selection_begin_index) + value.substr(selection_begin_index + selection_length);
  814. GetElement()->SetAttribute("value", new_value);
  815. // Move the cursor to the beginning of the old selection.
  816. absolute_cursor_index = selection_begin_index;
  817. UpdateRelativeCursor();
  818. // Erase our record of the selection.
  819. ClearSelection();
  820. }
  821. }
  822. // Split one line of text into three parts, based on the current selection.
  823. void WidgetTextInput::GetLineSelection(Core::String& pre_selection, Core::String& selection, Core::String& post_selection, const Core::String& line, int line_begin)
  824. {
  825. // Check if we have any selection at all, and if so if the selection is on this line.
  826. if (selection_length <= 0 ||
  827. selection_begin_index + selection_length < line_begin ||
  828. selection_begin_index > line_begin + (int) line.size())
  829. {
  830. pre_selection = line;
  831. return;
  832. }
  833. int line_length = (int)line.size();
  834. using namespace Rml::Core::Math;
  835. // Split the line up into its three parts, depending on the size and placement of the selection.
  836. pre_selection = line.substr(0, Max(0, selection_begin_index - line_begin));
  837. selection = line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin)));
  838. post_selection = line.substr(Clamp(selection_begin_index + selection_length - line_begin, 0, line_length));
  839. }
  840. void WidgetTextInput::SetKeyboardActive(bool active)
  841. {
  842. Core::SystemInterface* system = Core::GetSystemInterface();
  843. if (system) {
  844. if (active)
  845. {
  846. system->ActivateKeyboard();
  847. } else
  848. {
  849. system->DeactivateKeyboard();
  850. }
  851. }
  852. }
  853. }
  854. }