WidgetTextInput.cpp 30 KB

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