WidgetTextInput.cpp 30 KB

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