WidgetTextInput.cpp 29 KB

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