WidgetTextInput.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 <Rocket/Core.h>
  30. #include <Rocket/Controls/ElementFormControl.h>
  31. #include <Rocket/Controls/Clipboard.h>
  32. #include <Rocket/Core/SystemInterface.h>
  33. namespace Rocket {
  34. namespace Controls {
  35. const float CURSOR_BLINK_TIME = 0.7f;
  36. WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : internal_dimensions(0, 0), scroll_offset(0, 0), cursor_position(0, 0), cursor_size(0, 0), cursor_geometry(_parent), selection_geometry(_parent)
  37. {
  38. keyboard_showed = false;
  39. parent = _parent;
  40. parent->SetProperty("white-space", "pre");
  41. parent->SetProperty("overflow", "hidden");
  42. parent->SetProperty("drag", "drag");
  43. parent->SetClientArea(Rocket::Core::Box::CONTENT);
  44. parent->AddEventListener("resize", this, true);
  45. parent->AddEventListener("keydown", this, true);
  46. parent->AddEventListener("textinput", this, true);
  47. parent->AddEventListener("focus", this, true);
  48. parent->AddEventListener("blur", this, true);
  49. parent->AddEventListener("mousedown", this, true);
  50. parent->AddEventListener("drag", this, true);
  51. text_element = dynamic_cast< Core::ElementText* >(Core::Factory::InstanceElement(parent, "#text", "#text", Rocket::Core::XMLAttributes()));
  52. selected_text_element = dynamic_cast< Core::ElementText* >(Core::Factory::InstanceElement(parent, "#text", "#text", Rocket::Core::XMLAttributes()));
  53. if (text_element != NULL)
  54. {
  55. text_element->SuppressAutoLayout();
  56. parent->AppendChild(text_element, false);
  57. text_element->RemoveReference();
  58. selected_text_element->SuppressAutoLayout();
  59. parent->AppendChild(selected_text_element, false);
  60. selected_text_element->RemoveReference();
  61. }
  62. // Create the dummy selection element.
  63. selection_element = Core::Factory::InstanceElement(parent, "#selection", "selection", Rocket::Core::XMLAttributes());
  64. ElementTextSelection* text_selection_element = dynamic_cast< ElementTextSelection* >(selection_element);
  65. if (text_selection_element != NULL)
  66. {
  67. text_selection_element->SetWidget(this);
  68. parent->AppendChild(text_selection_element, false);
  69. text_selection_element->RemoveReference();
  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. ShowCursor(false);
  81. }
  82. WidgetTextInput::~WidgetTextInput()
  83. {
  84. parent->RemoveEventListener("resize", this, true);
  85. parent->RemoveEventListener("keydown", this, true);
  86. parent->RemoveEventListener("textinput", this, true);
  87. parent->RemoveEventListener("focus", this, true);
  88. parent->RemoveEventListener("blur", this, true);
  89. parent->RemoveEventListener("mousedown", this, true);
  90. parent->RemoveEventListener("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(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. const Core::WString& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
  112. if ((int) value.Length() > max_length)
  113. {
  114. Rocket::Core::String new_value;
  115. Core::WString(value.CString(), value.CString() + max_length).ToUTF8(new_value);
  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. Rocket::Core::Colourb colour;
  132. const Rocket::Core::Property* colour_property = selection_element->GetLocalProperty("color");
  133. if (colour_property != NULL)
  134. colour = colour_property->Get< Rocket::Core::Colourb >();
  135. else
  136. {
  137. colour = parent->GetProperty< Rocket::Core::Colourb >("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("color", Rocket::Core::Property(colour, Rocket::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 != NULL)
  149. selection_colour = colour_property->Get< Rocket::Core::Colourb >();
  150. else
  151. selection_colour = Rocket::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. float current_time = Core::GetSystemInterface()->GetElapsedTime();
  159. cursor_timer -= (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. // Renders the cursor, if it is visible.
  169. void WidgetTextInput::OnRender()
  170. {
  171. Core::ElementUtilities::SetClippingRegion(text_element);
  172. Rocket::Core::Vector2f text_translation = parent->GetAbsoluteOffset() - Rocket::Core::Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
  173. selection_geometry.Render(text_translation);
  174. if (cursor_visible &&
  175. !parent->IsDisabled())
  176. {
  177. cursor_geometry.Render(text_translation + cursor_position);
  178. }
  179. }
  180. // Formats the widget's internal content.
  181. void WidgetTextInput::OnLayout()
  182. {
  183. FormatElement();
  184. parent->SetScrollLeft(scroll_offset.x);
  185. parent->SetScrollTop(scroll_offset.y);
  186. }
  187. // Returns the input element's underlying text element.
  188. Core::ElementText* WidgetTextInput::GetTextElement()
  189. {
  190. return text_element;
  191. }
  192. // Returns the input element's maximum allowed text dimensions.
  193. const Rocket::Core::Vector2f& WidgetTextInput::GetTextDimensions() const
  194. {
  195. return internal_dimensions;
  196. }
  197. // Gets the parent element containing the widget.
  198. Core::Element* WidgetTextInput::GetElement()
  199. {
  200. return parent;
  201. }
  202. // Dispatches a change event to the widget's element.
  203. void WidgetTextInput::DispatchChangeEvent(bool linebreak)
  204. {
  205. Rocket::Core::Dictionary parameters;
  206. parameters.Set("value", GetElement()->GetAttribute< Rocket::Core::String >("value", ""));
  207. parameters.Set("linebreak", linebreak);
  208. GetElement()->DispatchEvent("change", parameters);
  209. }
  210. // Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set
  211. // the state of the cursor.
  212. void WidgetTextInput::ProcessEvent(Core::Event& event)
  213. {
  214. if (event == "resize")
  215. {
  216. GenerateCursor();
  217. Rocket::Core::Vector2f text_position = parent->GetBox().GetPosition(Core::Box::CONTENT);
  218. text_element->SetOffset(text_position, parent);
  219. selected_text_element->SetOffset(text_position, parent);
  220. Rocket::Core::Vector2f new_internal_dimensions = parent->GetBox().GetSize(Core::Box::CONTENT);
  221. if (new_internal_dimensions != internal_dimensions)
  222. {
  223. internal_dimensions = new_internal_dimensions;
  224. FormatElement();
  225. UpdateCursorPosition();
  226. }
  227. }
  228. else if (parent->IsDisabled())
  229. {
  230. return;
  231. }
  232. else if (event == "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. const Core::WString clipboard_content = Clipboard::Get();
  299. for (size_t i = 0; i < clipboard_content.Length(); ++i)
  300. {
  301. if (max_length > 0 &&
  302. (int) Core::WString(GetElement()->GetAttribute< Rocket::Core::String >("value", "")).Length() < max_length)
  303. break;
  304. AddCharacter(clipboard_content[i]);
  305. }
  306. }
  307. }
  308. break;
  309. // Ignore tabs so input fields can be navigated through with keys.
  310. case Core::Input::KI_TAB:
  311. return;
  312. default:
  313. {
  314. }
  315. break;
  316. }
  317. event.StopPropagation();
  318. }
  319. else if (event == "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", "")).Length() < max_length)
  328. AddCharacter(character);
  329. }
  330. ShowCursor(true);
  331. event.StopPropagation();
  332. }
  333. else if (event == "focus" &&
  334. event.GetTargetElement() == parent)
  335. {
  336. UpdateSelection(false);
  337. ShowCursor(true, false);
  338. }
  339. else if (event == "blur" &&
  340. event.GetTargetElement() == parent)
  341. {
  342. ClearSelection();
  343. ShowCursor(false, false);
  344. }
  345. else if ((event == "mousedown" ||
  346. event == "drag") &&
  347. event.GetTargetElement() == parent)
  348. {
  349. Rocket::Core::Vector2f mouse_position = Rocket::Core::Vector2f((float) event.GetParameter< int >("mouse_x", 0),
  350. (float) event.GetParameter< int >("mouse_y", 0));
  351. mouse_position -= text_element->GetAbsoluteOffset();
  352. cursor_line_index = CalculateLineIndex(mouse_position.y);
  353. cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
  354. UpdateAbsoluteCursor();
  355. UpdateCursorPosition();
  356. ideal_cursor_position = cursor_position.x;
  357. UpdateSelection(event == "drag" || event.GetParameter< int >("shift_key", 0) > 0);
  358. ShowCursor(true);
  359. }
  360. }
  361. // Adds a new character to the string at the cursor position.
  362. bool WidgetTextInput::AddCharacter(Rocket::Core::word character)
  363. {
  364. if (!IsCharacterValid(character))
  365. return false;
  366. if (selection_length > 0)
  367. DeleteSelection();
  368. Core::WString value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
  369. value.Insert(GetCursorIndex(), Core::WString(1, character), 1);
  370. edit_index += 1;
  371. Rocket::Core::String utf8_value;
  372. value.ToUTF8(utf8_value);
  373. GetElement()->SetAttribute("value", utf8_value);
  374. DispatchChangeEvent();
  375. UpdateSelection(false);
  376. return true;
  377. }
  378. // Deletes a character from the string.
  379. bool WidgetTextInput::DeleteCharacter(bool back)
  380. {
  381. // First, check if we have anything selected; if so, delete that first before we start delete
  382. // individual characters.
  383. if (selection_length > 0)
  384. {
  385. DeleteSelection();
  386. DispatchChangeEvent();
  387. UpdateSelection(false);
  388. return true;
  389. }
  390. Core::WString value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
  391. if (back)
  392. {
  393. if (GetCursorIndex() == 0)
  394. return false;
  395. value.Erase(GetCursorIndex() - 1, 1);
  396. edit_index -= 1;
  397. }
  398. else
  399. {
  400. if (GetCursorIndex() == (int) value.Length())
  401. return false;
  402. value.Erase(GetCursorIndex(), 1);
  403. }
  404. Rocket::Core::String utf8_value;
  405. value.ToUTF8(utf8_value);
  406. GetElement()->SetAttribute("value", utf8_value);
  407. DispatchChangeEvent();
  408. UpdateSelection(false);
  409. return true;
  410. }
  411. // Copies the selection (if any) to the clipboard.
  412. void WidgetTextInput::CopySelection()
  413. {
  414. const Core::String& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
  415. Clipboard::Set(Core::String(value.Substring(selection_begin_index, selection_length)));
  416. }
  417. // Returns the absolute index of the cursor.
  418. int WidgetTextInput::GetCursorIndex() const
  419. {
  420. return edit_index;
  421. }
  422. // Moves the cursor along the current line.
  423. void WidgetTextInput::MoveCursorHorizontal(int distance, bool select)
  424. {
  425. absolute_cursor_index += distance;
  426. absolute_cursor_index = Rocket::Core::Math::Max(0, absolute_cursor_index);
  427. UpdateRelativeCursor();
  428. ideal_cursor_position = cursor_position.x;
  429. UpdateSelection(select);
  430. ShowCursor(true);
  431. }
  432. // Moves the cursor up and down the text field.
  433. void WidgetTextInput::MoveCursorVertical(int distance, bool select)
  434. {
  435. bool update_ideal_cursor_position = false;
  436. cursor_line_index += distance;
  437. if (cursor_line_index < 0)
  438. {
  439. cursor_line_index = 0;
  440. cursor_character_index = 0;
  441. update_ideal_cursor_position = true;
  442. }
  443. else if (cursor_line_index >= (int) lines.size())
  444. {
  445. cursor_line_index = (int) lines.size() - 1;
  446. cursor_character_index = (int) lines[cursor_line_index].content_length;
  447. update_ideal_cursor_position = true;
  448. }
  449. else
  450. cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
  451. UpdateAbsoluteCursor();
  452. UpdateCursorPosition();
  453. if (update_ideal_cursor_position)
  454. ideal_cursor_position = cursor_position.x;
  455. UpdateSelection(select);
  456. ShowCursor(true);
  457. }
  458. // Updates the absolute cursor index from the relative cursor indices.
  459. void WidgetTextInput::UpdateAbsoluteCursor()
  460. {
  461. ROCKET_ASSERT(cursor_line_index < (int) lines.size())
  462. absolute_cursor_index = cursor_character_index;
  463. edit_index = cursor_character_index;
  464. for (int i = 0; i < cursor_line_index; i++)
  465. {
  466. absolute_cursor_index += lines[i].content.Length();
  467. edit_index += lines[i].content.Length() + lines[i].extra_characters;
  468. }
  469. }
  470. // Updates the relative cursor indices from the absolute cursor index.
  471. void WidgetTextInput::UpdateRelativeCursor()
  472. {
  473. int num_characters = 0;
  474. edit_index = absolute_cursor_index;
  475. for (size_t i = 0; i < lines.size(); i++)
  476. {
  477. if (num_characters + lines[i].content_length >= absolute_cursor_index)
  478. {
  479. cursor_line_index = (int) i;
  480. cursor_character_index = absolute_cursor_index - num_characters;
  481. UpdateCursorPosition();
  482. return;
  483. }
  484. num_characters += (int) lines[i].content.Length();
  485. edit_index += lines[i].extra_characters;
  486. }
  487. // We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
  488. // just set the relative cursors to the very end of the text field, and update the absolute cursor to point here.
  489. cursor_line_index = (int) lines.size() - 1;
  490. cursor_character_index = lines[cursor_line_index].content_length;
  491. absolute_cursor_index = num_characters;
  492. edit_index = num_characters;
  493. UpdateCursorPosition();
  494. }
  495. // Calculates the line index under a specific vertical position.
  496. int WidgetTextInput::CalculateLineIndex(float position)
  497. {
  498. float line_height = (float) Core::ElementUtilities::GetLineHeight(parent);
  499. int line_index = Rocket::Core::Math::RealToInteger(position / line_height);
  500. return Rocket::Core::Math::Clamp(line_index, 0, (int) (lines.size() - 1));
  501. }
  502. // Calculates the character index along a line under a specific horizontal position.
  503. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
  504. {
  505. int character_index = 0;
  506. float line_width = 0;
  507. while (character_index < lines[line_index].content_length)
  508. {
  509. float next_line_width = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[line_index].content.Substring(0, character_index));
  510. if (next_line_width > position)
  511. {
  512. if (position - line_width < next_line_width - position)
  513. return Rocket::Core::Math::Max(0, character_index - 1);
  514. else
  515. return character_index;
  516. }
  517. line_width = next_line_width;
  518. character_index++;
  519. }
  520. return character_index;
  521. }
  522. // Shows or hides the cursor.
  523. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
  524. {
  525. if (show)
  526. {
  527. cursor_visible = true;
  528. SetKeyboardActive(true);
  529. keyboard_showed = true;
  530. cursor_timer = CURSOR_BLINK_TIME;
  531. last_update_time = Core::GetSystemInterface()->GetElapsedTime();
  532. // Shift the cursor into view.
  533. if (move_to_cursor)
  534. {
  535. float minimum_scroll_top = (cursor_position.y + cursor_size.y) - parent->GetClientHeight();
  536. if (parent->GetScrollTop() < minimum_scroll_top)
  537. parent->SetScrollTop(minimum_scroll_top);
  538. else if (parent->GetScrollTop() > cursor_position.y)
  539. parent->SetScrollTop(cursor_position.y);
  540. float minimum_scroll_left = (cursor_position.x + cursor_size.x) - parent->GetClientWidth();
  541. if (parent->GetScrollLeft() < minimum_scroll_left)
  542. parent->SetScrollLeft(minimum_scroll_left);
  543. else if (parent->GetScrollLeft() > cursor_position.x)
  544. parent->SetScrollLeft(cursor_position.x);
  545. scroll_offset.x = parent->GetScrollLeft();
  546. scroll_offset.y = parent->GetScrollTop();
  547. }
  548. }
  549. else
  550. {
  551. cursor_visible = false;
  552. cursor_timer = -1;
  553. last_update_time = 0;
  554. if (keyboard_showed)
  555. {
  556. SetKeyboardActive(false);
  557. keyboard_showed = false;
  558. }
  559. }
  560. }
  561. // Formats the element, laying out the text and inserting scrollbars as appropriate.
  562. void WidgetTextInput::FormatElement()
  563. {
  564. Core::ElementScroll* scroll = parent->GetElementScroll();
  565. float width = parent->GetBox().GetSize(Core::Box::PADDING).x;
  566. int x_overflow_property = parent->GetProperty< int >("overflow-x");
  567. int y_overflow_property = parent->GetProperty< int >("overflow-y");
  568. if (x_overflow_property == Core::OVERFLOW_SCROLL)
  569. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  570. else
  571. scroll->DisableScrollbar(Core::ElementScroll::HORIZONTAL);
  572. if (y_overflow_property == Core::OVERFLOW_SCROLL)
  573. scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
  574. else
  575. scroll->DisableScrollbar(Core::ElementScroll::VERTICAL);
  576. // Format the text and determine its total area.
  577. Rocket::Core::Vector2f content_area = FormatText();
  578. // If we're set to automatically generate horizontal scrollbars, check for that now.
  579. if (x_overflow_property == Core::OVERFLOW_AUTO)
  580. {
  581. if (parent->GetClientWidth() < content_area.x)
  582. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  583. }
  584. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  585. if (y_overflow_property == Core::OVERFLOW_AUTO)
  586. {
  587. if (parent->GetClientHeight() < content_area.y)
  588. {
  589. scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
  590. content_area = FormatText();
  591. if (x_overflow_property == Core::OVERFLOW_AUTO &&
  592. parent->GetClientWidth() < content_area.y)
  593. {
  594. scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
  595. }
  596. }
  597. }
  598. parent->SetContentBox(Rocket::Core::Vector2f(0, 0), content_area);
  599. scroll->FormatScrollbars();
  600. }
  601. // Formats the input element's text field.
  602. Rocket::Core::Vector2f WidgetTextInput::FormatText()
  603. {
  604. absolute_cursor_index = edit_index;
  605. Rocket::Core::Vector2f content_area(0, 0);
  606. // Clear the old lines, and all the lines in the text elements.
  607. lines.clear();
  608. text_element->ClearLines();
  609. selected_text_element->ClearLines();
  610. // Clear the selection background geometry, and get the vertices and indices so the new geo can
  611. // be generated.
  612. selection_geometry.Release(true);
  613. std::vector< Core::Vertex >& selection_vertices = selection_geometry.GetVertices();
  614. std::vector< int >& selection_indices = selection_geometry.GetIndices();
  615. // Determine the line-height of the text element.
  616. int line_height = Rocket::Core::ElementUtilities::GetLineHeight(parent);
  617. int line_begin = 0;
  618. Rocket::Core::Vector2f line_position(0, 0);
  619. bool last_line = false;
  620. // Keep generating lines until all the text content is placed.
  621. do
  622. {
  623. Line line;
  624. line.extra_characters = 0;
  625. float line_width;
  626. // Generate the next line.
  627. last_line = text_element->GenerateLine(line.content, line.content_length, line_width, line_begin, parent->GetClientWidth() - cursor_size.x, 0, false);
  628. // If this line terminates in a soft-return, then the line may be leaving a space or two behind as an orphan.
  629. // If so, we must append the orphan onto the line even though it will push the line outside of the input
  630. // field's bounds.
  631. bool soft_return = false;
  632. if (!last_line &&
  633. (line.content.Empty() ||
  634. line.content[line.content.Length() - 1] != '\n'))
  635. {
  636. soft_return = true;
  637. const Core::WString& text = text_element->GetText();
  638. Core::WString orphan;
  639. for (int i = 1; i >= 0; --i)
  640. {
  641. int index = line_begin + line.content_length + i;
  642. if (index >= (int) text.Length())
  643. continue;
  644. if (text[index] != ' ')
  645. {
  646. orphan = "";
  647. continue;
  648. }
  649. int next_index = index + 1;
  650. if (!orphan.Empty() ||
  651. next_index >= (int) text.Length() ||
  652. text[next_index] != ' ')
  653. orphan += ' ';
  654. }
  655. if (!orphan.Empty())
  656. {
  657. line.content += orphan;
  658. line.content_length += (int) orphan.Length();
  659. line_width += Core::ElementUtilities::GetStringWidth(text_element, orphan);
  660. }
  661. }
  662. // Now that we have the string of characters appearing on the new line, we split it into
  663. // three parts; the unselected text appearing before any selected text on the line, the
  664. // selected text on the line, and any unselected text after the selection.
  665. Core::WString pre_selection, selection, post_selection;
  666. GetLineSelection(pre_selection, selection, post_selection, line.content, line_begin);
  667. // The pre-selected text is placed, if there is any (if the selection starts on or before
  668. // the beginning of this line, then this will be empty).
  669. if (!pre_selection.Empty())
  670. {
  671. text_element->AddLine(line_position, pre_selection);
  672. line_position.x += Core::ElementUtilities::GetStringWidth(text_element, pre_selection);
  673. }
  674. // If there is any selected text on this line, place it in the selected text element and
  675. // generate the geometry for its background.
  676. if (!selection.Empty())
  677. {
  678. selected_text_element->AddLine(line_position, selection);
  679. int selection_width = Core::ElementUtilities::GetStringWidth(selected_text_element, selection);
  680. selection_vertices.resize(selection_vertices.size() + 4);
  681. selection_indices.resize(selection_indices.size() + 6);
  682. Core::GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6], line_position, Rocket::Core::Vector2f((float) selection_width, (float) line_height), selection_colour, selection_vertices.size() - 4);
  683. line_position.x += selection_width;
  684. }
  685. // If there is any unselected text after the selection on this line, place it in the
  686. // standard text element after the selected text.
  687. if (!post_selection.Empty())
  688. text_element->AddLine(line_position, post_selection);
  689. // Update variables for the next line.
  690. line_begin += line.content_length;
  691. line_position.x = 0;
  692. line_position.y += line_height;
  693. // Grow the content area width-wise if this line is the longest so far, and push the
  694. // height out.
  695. content_area.x = Rocket::Core::Math::Max(content_area.x, line_width + cursor_size.x);
  696. content_area.y = line_position.y;
  697. // Push a trailing '\r' token onto the back to indicate a soft return if necessary.
  698. if (soft_return)
  699. {
  700. line.content += '\r';
  701. line.extra_characters -= 1;
  702. if (edit_index >= line_begin)
  703. absolute_cursor_index += 1;
  704. }
  705. // Push the new line into our array of lines, but first check if its content length needs to be truncated to
  706. // dodge a trailing endline.
  707. if (!line.content.Empty() &&
  708. line.content[line.content.Length() - 1] == '\n')
  709. line.content_length -= 1;
  710. lines.push_back(line);
  711. }
  712. while (!last_line);
  713. return content_area;
  714. }
  715. // Generates the text cursor.
  716. void WidgetTextInput::GenerateCursor()
  717. {
  718. // Generates the cursor.
  719. cursor_geometry.Release();
  720. std::vector< Core::Vertex >& vertices = cursor_geometry.GetVertices();
  721. vertices.resize(4);
  722. std::vector< int >& indices = cursor_geometry.GetIndices();
  723. indices.resize(6);
  724. cursor_size.x = 1;
  725. cursor_size.y = (float) Core::ElementUtilities::GetLineHeight(text_element) + 2;
  726. Core::GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Rocket::Core::Vector2f(0, 0), cursor_size, parent->GetProperty< Rocket::Core::Colourb >("color"));
  727. }
  728. void WidgetTextInput::UpdateCursorPosition()
  729. {
  730. if (text_element->GetFontFaceHandle() == NULL)
  731. return;
  732. cursor_position.x = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[cursor_line_index].content.Substring(0, cursor_character_index));
  733. cursor_position.y = -1 + cursor_line_index * (float) Core::ElementUtilities::GetLineHeight(text_element);
  734. }
  735. // Expand the text selection to the position of the cursor.
  736. void WidgetTextInput::UpdateSelection(bool selecting)
  737. {
  738. if (!selecting)
  739. {
  740. selection_anchor_index = edit_index;
  741. ClearSelection();
  742. }
  743. else
  744. {
  745. int new_begin_index;
  746. int new_end_index;
  747. if (edit_index > selection_anchor_index)
  748. {
  749. new_begin_index = selection_anchor_index;
  750. new_end_index = edit_index;
  751. }
  752. else
  753. {
  754. new_begin_index = edit_index;
  755. new_end_index = selection_anchor_index;
  756. }
  757. if (new_begin_index != selection_begin_index ||
  758. new_end_index - new_begin_index != selection_length)
  759. {
  760. selection_begin_index = new_begin_index;
  761. selection_length = new_end_index - new_begin_index;
  762. FormatText();
  763. }
  764. }
  765. }
  766. // Removes the selection of text.
  767. void WidgetTextInput::ClearSelection()
  768. {
  769. if (selection_length > 0)
  770. {
  771. selection_length = 0;
  772. FormatElement();
  773. }
  774. }
  775. // Deletes all selected text and removes the selection.
  776. void WidgetTextInput::DeleteSelection()
  777. {
  778. if (selection_length > 0)
  779. {
  780. const Core::WString& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
  781. Rocket::Core::String new_value;
  782. Core::WString(value.Substring(0, selection_begin_index) + value.Substring(selection_begin_index + selection_length)).ToUTF8(new_value);
  783. GetElement()->SetAttribute("value", new_value);
  784. // Move the cursor to the beginning of the old selection.
  785. absolute_cursor_index = selection_begin_index;
  786. UpdateRelativeCursor();
  787. // Erase our record of the selection.
  788. ClearSelection();
  789. }
  790. }
  791. // Split one line of text into three parts, based on the current selection.
  792. void WidgetTextInput::GetLineSelection(Core::WString& pre_selection, Core::WString& selection, Core::WString& post_selection, const Core::WString& line, int line_begin)
  793. {
  794. // Check if we have any selection at all, and if so if the selection is on this line.
  795. if (selection_length <= 0 ||
  796. selection_begin_index + selection_length < line_begin ||
  797. selection_begin_index > line_begin + (int) line.Length())
  798. {
  799. pre_selection = line;
  800. return;
  801. }
  802. // Split the line up into its three parts, depending on the size and placement of the selection.
  803. pre_selection = line.Substring(0, Rocket::Core::Math::Max(0, selection_begin_index - line_begin));
  804. selection = line.Substring(Rocket::Core::Math::Max(0, selection_begin_index - line_begin), Rocket::Core::Math::Max(0, selection_length + Rocket::Core::Math::Min(0, selection_begin_index - line_begin)));
  805. post_selection = line.Substring(selection_begin_index + selection_length - line_begin);
  806. }
  807. void WidgetTextInput::SetKeyboardActive(bool active)
  808. {
  809. Core::SystemInterface* system = Core::GetSystemInterface();
  810. if (system) {
  811. if (active)
  812. {
  813. system->ActivateKeyboard();
  814. } else
  815. {
  816. system->DeactivateKeyboard();
  817. }
  818. }
  819. }
  820. }
  821. }