WidgetTextInput.cpp 30 KB

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