WidgetTextInput.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "WidgetTextInput.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/Core.h"
  31. #include "../../../Include/RmlUi/Core/ElementScroll.h"
  32. #include "../../../Include/RmlUi/Core/ElementText.h"
  33. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  34. #include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h"
  35. #include "../../../Include/RmlUi/Core/Factory.h"
  36. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  37. #include "../../../Include/RmlUi/Core/Input.h"
  38. #include "../../../Include/RmlUi/Core/Math.h"
  39. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  40. #include "../../../Include/RmlUi/Core/SystemInterface.h"
  41. #include "../Clock.h"
  42. #include "ElementTextSelection.h"
  43. #include <algorithm>
  44. #include <limits.h>
  45. namespace Rml {
  46. static constexpr float CURSOR_BLINK_TIME = 0.7f;
  47. enum class CharacterClass { Word, Punctuation, Newline, Whitespace, Undefined };
  48. static CharacterClass GetCharacterClass(char c)
  49. {
  50. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || ((unsigned char)c >= 128))
  51. return CharacterClass::Word;
  52. if ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~'))
  53. return CharacterClass::Punctuation;
  54. if (c == '\n')
  55. return CharacterClass::Newline;
  56. return CharacterClass::Whitespace;
  57. }
  58. static int ConvertCharacterOffsetToByteOffset(const String& value, int character_offset)
  59. {
  60. if (character_offset >= (int)value.size())
  61. return (int)value.size();
  62. int character_count = 0;
  63. for (auto it = StringIteratorU8(value); it; ++it)
  64. {
  65. character_count += 1;
  66. if (character_count > character_offset)
  67. return (int)it.offset();
  68. }
  69. return (int)value.size();
  70. }
  71. static int ConvertByteOffsetToCharacterOffset(const String& value, int byte_offset)
  72. {
  73. int character_count = 0;
  74. for (auto it = StringIteratorU8(value); it; ++it)
  75. {
  76. if (it.offset() >= byte_offset)
  77. break;
  78. character_count += 1;
  79. }
  80. return character_count;
  81. }
  82. // Clamps the value to the given maximum number of unicode code points. Returns true if the value was changed.
  83. static bool ClampValue(String& value, int max_length)
  84. {
  85. if (max_length >= 0)
  86. {
  87. int max_byte_length = ConvertCharacterOffsetToByteOffset(value, max_length);
  88. if (max_byte_length < (int)value.size())
  89. {
  90. value.erase((size_t)max_byte_length);
  91. return true;
  92. }
  93. }
  94. return false;
  95. }
  96. 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)
  97. {
  98. keyboard_showed = false;
  99. parent = _parent;
  100. parent->SetProperty(PropertyId::WhiteSpace, Property(Style::WhiteSpace::Pre));
  101. parent->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Hidden));
  102. parent->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Hidden));
  103. parent->SetProperty(PropertyId::Drag, Property(Style::Drag::Drag));
  104. parent->SetProperty(PropertyId::WordBreak, Property(Style::WordBreak::BreakWord));
  105. parent->SetProperty(PropertyId::TextTransform, Property(Style::TextTransform::None));
  106. parent->SetClientArea(Box::CONTENT);
  107. parent->AddEventListener(EventId::Keydown, this, true);
  108. parent->AddEventListener(EventId::Textinput, this, true);
  109. parent->AddEventListener(EventId::Focus, this, true);
  110. parent->AddEventListener(EventId::Blur, this, true);
  111. parent->AddEventListener(EventId::Mousedown, this, true);
  112. parent->AddEventListener(EventId::Dblclick, this, true);
  113. parent->AddEventListener(EventId::Drag, this, true);
  114. ElementPtr unique_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  115. text_element = rmlui_dynamic_cast< ElementText* >(unique_text.get());
  116. ElementPtr unique_selected_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  117. selected_text_element = rmlui_dynamic_cast< ElementText* >(unique_selected_text.get());
  118. if (text_element)
  119. {
  120. text_element->SuppressAutoLayout();
  121. parent->AppendChild(std::move(unique_text), false);
  122. selected_text_element->SuppressAutoLayout();
  123. parent->AppendChild(std::move(unique_selected_text), false);
  124. }
  125. // Create the dummy selection element.
  126. ElementPtr unique_selection = Factory::InstanceElement(parent, "#selection", "selection", XMLAttributes());
  127. if (ElementTextSelection* text_selection_element = rmlui_dynamic_cast<ElementTextSelection*>(unique_selection.get()))
  128. {
  129. selection_element = text_selection_element;
  130. text_selection_element->SetWidget(this);
  131. parent->AppendChild(std::move(unique_selection), false);
  132. }
  133. absolute_cursor_index = 0;
  134. cursor_wrap_down = false;
  135. ideal_cursor_position_to_the_right_of_cursor = true;
  136. cancel_next_drag = false;
  137. force_formatting_on_next_layout = false;
  138. ideal_cursor_position = 0;
  139. max_length = -1;
  140. selection_anchor_index = 0;
  141. selection_begin_index = 0;
  142. selection_length = 0;
  143. last_update_time = 0;
  144. ShowCursor(false);
  145. }
  146. WidgetTextInput::~WidgetTextInput()
  147. {
  148. parent->RemoveEventListener(EventId::Keydown, this, true);
  149. parent->RemoveEventListener(EventId::Textinput, this, true);
  150. parent->RemoveEventListener(EventId::Focus, this, true);
  151. parent->RemoveEventListener(EventId::Blur, this, true);
  152. parent->RemoveEventListener(EventId::Mousedown, this, true);
  153. parent->RemoveEventListener(EventId::Dblclick, this, true);
  154. parent->RemoveEventListener(EventId::Drag, this, true);
  155. // Remove all the children added by the text widget.
  156. parent->RemoveChild(text_element);
  157. parent->RemoveChild(selected_text_element);
  158. parent->RemoveChild(selection_element);
  159. }
  160. void WidgetTextInput::SetValue(String value)
  161. {
  162. const size_t initial_size = value.size();
  163. SanitizeValue(value);
  164. if (initial_size != value.size())
  165. {
  166. parent->SetAttribute("value", value);
  167. DispatchChangeEvent();
  168. }
  169. else
  170. {
  171. TransformValue(value);
  172. RMLUI_ASSERTMSG(value.size() == initial_size, "TransformValue must not change the text length.");
  173. text_element->SetText(value);
  174. FormatElement();
  175. UpdateCursorPosition(true);
  176. }
  177. }
  178. void WidgetTextInput::TransformValue(String& /*value*/) {}
  179. // Sets the maximum length (in characters) of this text field.
  180. void WidgetTextInput::SetMaxLength(int _max_length)
  181. {
  182. if (max_length != _max_length)
  183. {
  184. max_length = _max_length;
  185. String value = GetValue();
  186. if (ClampValue(value, max_length))
  187. GetElement()->SetAttribute("value", value);
  188. }
  189. }
  190. // Returns the maximum length (in characters) of this text field.
  191. int WidgetTextInput::GetMaxLength() const
  192. {
  193. return max_length;
  194. }
  195. int WidgetTextInput::GetLength() const
  196. {
  197. size_t result = StringUtilities::LengthUTF8(GetValue());
  198. return (int)result;
  199. }
  200. void WidgetTextInput::Select()
  201. {
  202. SetSelectionRange(0, INT_MAX);
  203. }
  204. void WidgetTextInput::SetSelectionRange(int selection_start, int selection_end)
  205. {
  206. const String& value = GetValue();
  207. const int byte_start = ConvertCharacterOffsetToByteOffset(value, selection_start);
  208. const int byte_end = ConvertCharacterOffsetToByteOffset(value, selection_end);
  209. const bool is_selecting = (byte_start != byte_end);
  210. cursor_wrap_down = true;
  211. absolute_cursor_index = byte_end;
  212. bool selection_changed = false;
  213. if (is_selecting)
  214. {
  215. selection_anchor_index = byte_start;
  216. selection_changed = UpdateSelection(true);
  217. }
  218. else
  219. {
  220. selection_changed = UpdateSelection(false);
  221. }
  222. UpdateCursorPosition(true);
  223. if (selection_changed)
  224. FormatText();
  225. }
  226. void WidgetTextInput::GetSelection(int* selection_start, int* selection_end, String* selected_text) const
  227. {
  228. const String& value = GetValue();
  229. if (selection_start)
  230. *selection_start = ConvertByteOffsetToCharacterOffset(value, selection_begin_index);
  231. if (selection_end)
  232. *selection_end = ConvertByteOffsetToCharacterOffset(value, selection_begin_index + selection_length);
  233. if (selected_text)
  234. *selected_text = value.substr(Math::Min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length);
  235. }
  236. // Update the colours of the selected text.
  237. void WidgetTextInput::UpdateSelectionColours()
  238. {
  239. // Determine what the colour of the selected text is. If our 'selection' element has the 'color'
  240. // attribute set, then use that. Otherwise, use the inverse of our own text colour.
  241. Colourb colour;
  242. const Property* colour_property = selection_element->GetLocalProperty("color");
  243. if (colour_property != nullptr)
  244. colour = colour_property->Get< Colourb >();
  245. else
  246. {
  247. colour = parent->GetComputedValues().color();
  248. colour.red = 255 - colour.red;
  249. colour.green = 255 - colour.green;
  250. colour.blue = 255 - colour.blue;
  251. }
  252. // Set the computed text colour on the element holding the selected text.
  253. selected_text_element->SetProperty(PropertyId::Color, Property(colour, Property::COLOUR));
  254. // If the 'background-color' property has been set on the 'selection' element, use that as the
  255. // background colour for the selected text. Otherwise, use the inverse of the selected text
  256. // colour.
  257. colour_property = selection_element->GetLocalProperty("background-color");
  258. if (colour_property != nullptr)
  259. selection_colour = colour_property->Get< Colourb >();
  260. else
  261. selection_colour = Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha);
  262. // Color may have changed, so we update the cursor geometry.
  263. GenerateCursor();
  264. }
  265. // Updates the cursor, if necessary.
  266. void WidgetTextInput::OnUpdate()
  267. {
  268. if (cursor_timer > 0)
  269. {
  270. double current_time = Clock::GetElapsedTime();
  271. cursor_timer -= float(current_time - last_update_time);
  272. last_update_time = current_time;
  273. while (cursor_timer <= 0)
  274. {
  275. cursor_timer += CURSOR_BLINK_TIME;
  276. cursor_visible = !cursor_visible;
  277. }
  278. }
  279. }
  280. void WidgetTextInput::OnResize()
  281. {
  282. GenerateCursor();
  283. Vector2f text_position = parent->GetBox().GetPosition(Box::CONTENT);
  284. text_element->SetOffset(text_position, parent);
  285. selected_text_element->SetOffset(text_position, parent);
  286. ForceFormattingOnNextLayout();
  287. }
  288. // Renders the cursor, if it is visible.
  289. void WidgetTextInput::OnRender()
  290. {
  291. ElementUtilities::SetClippingRegion(text_element);
  292. Vector2f text_translation = parent->GetAbsoluteOffset() - Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
  293. selection_geometry.Render(text_translation);
  294. if (cursor_visible &&
  295. !parent->IsDisabled())
  296. {
  297. cursor_geometry.Render(text_translation + cursor_position);
  298. }
  299. }
  300. // Formats the widget's internal content.
  301. void WidgetTextInput::OnLayout()
  302. {
  303. if (force_formatting_on_next_layout)
  304. {
  305. internal_dimensions = parent->GetBox().GetSize(Box::CONTENT);
  306. FormatElement();
  307. UpdateCursorPosition(true);
  308. force_formatting_on_next_layout = false;
  309. }
  310. parent->SetScrollLeft(scroll_offset.x);
  311. parent->SetScrollTop(scroll_offset.y);
  312. }
  313. // Gets the parent element containing the widget.
  314. Element* WidgetTextInput::GetElement() const
  315. {
  316. return parent;
  317. }
  318. // Dispatches a change event to the widget's element.
  319. void WidgetTextInput::DispatchChangeEvent(bool linebreak)
  320. {
  321. Dictionary parameters;
  322. parameters["value"] = GetAttributeValue();
  323. parameters["linebreak"] = Variant(linebreak);
  324. GetElement()->DispatchEvent(EventId::Change, parameters);
  325. }
  326. // Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set
  327. // the state of the cursor.
  328. void WidgetTextInput::ProcessEvent(Event& event)
  329. {
  330. if (parent->IsDisabled())
  331. return;
  332. switch (event.GetId())
  333. {
  334. case EventId::Keydown:
  335. {
  336. Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
  337. bool numlock = event.GetParameter< int >("num_lock_key", 0) > 0;
  338. bool shift = event.GetParameter< int >("shift_key", 0) > 0;
  339. bool ctrl = event.GetParameter< int >("ctrl_key", 0) > 0;
  340. bool selection_changed = false;
  341. switch (key_identifier)
  342. {
  343. // clang-format off
  344. case Input::KI_NUMPAD4: if (numlock) break; //-fallthrough
  345. case Input::KI_LEFT: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::PreviousWord : CursorMovement::Left, shift); break;
  346. case Input::KI_NUMPAD6: if (numlock) break; //-fallthrough
  347. case Input::KI_RIGHT: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::NextWord : CursorMovement::Right, shift); break;
  348. case Input::KI_NUMPAD8: if (numlock) break; //-fallthrough
  349. case Input::KI_UP: selection_changed = MoveCursorVertical(-1, shift); break;
  350. case Input::KI_NUMPAD2: if (numlock) break; //-fallthrough
  351. case Input::KI_DOWN: selection_changed = MoveCursorVertical(1, shift); break;
  352. case Input::KI_NUMPAD7: if (numlock) break; //-fallthrough
  353. case Input::KI_HOME: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::Begin : CursorMovement::BeginLine, shift); break;
  354. case Input::KI_NUMPAD1: if (numlock) break; //-fallthrough
  355. case Input::KI_END: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::End : CursorMovement::EndLine, shift); break;
  356. case Input::KI_NUMPAD9: if (numlock) break; //-fallthrough
  357. case Input::KI_PRIOR: selection_changed = MoveCursorVertical(-int(internal_dimensions.y / parent->GetLineHeight()) + 1, shift); break;
  358. case Input::KI_NUMPAD3: if (numlock) break; //-fallthrough
  359. case Input::KI_NEXT: selection_changed = MoveCursorVertical(int(internal_dimensions.y / parent->GetLineHeight()) - 1, shift); break;
  360. case Input::KI_BACK:
  361. {
  362. CursorMovement direction = (ctrl ? CursorMovement::PreviousWord : CursorMovement::Left);
  363. DeleteCharacters(direction);
  364. ShowCursor(true);
  365. }
  366. break;
  367. case Input::KI_DECIMAL: if (numlock) break; //-fallthrough
  368. case Input::KI_DELETE:
  369. {
  370. CursorMovement direction = (ctrl ? CursorMovement::NextWord : CursorMovement::Right);
  371. DeleteCharacters(direction);
  372. ShowCursor(true);
  373. }
  374. break;
  375. // clang-format on
  376. case Input::KI_NUMPADENTER:
  377. case Input::KI_RETURN:
  378. {
  379. LineBreak();
  380. }
  381. break;
  382. case Input::KI_A:
  383. {
  384. if (ctrl)
  385. Select();
  386. }
  387. break;
  388. case Input::KI_C:
  389. {
  390. if (ctrl && selection_length > 0)
  391. CopySelection();
  392. }
  393. break;
  394. case Input::KI_X:
  395. {
  396. if (ctrl && selection_length > 0)
  397. {
  398. CopySelection();
  399. DeleteSelection();
  400. DispatchChangeEvent();
  401. ShowCursor(true);
  402. }
  403. }
  404. break;
  405. case Input::KI_V:
  406. {
  407. if (ctrl)
  408. {
  409. String clipboard_text;
  410. GetSystemInterface()->GetClipboardText(clipboard_text);
  411. AddCharacters(clipboard_text);
  412. ShowCursor(true);
  413. }
  414. }
  415. break;
  416. // Ignore tabs so input fields can be navigated through with keys.
  417. case Input::KI_TAB:
  418. return;
  419. default:
  420. break;
  421. }
  422. event.StopPropagation();
  423. if (selection_changed)
  424. FormatText();
  425. }
  426. break;
  427. case EventId::Textinput:
  428. {
  429. // Only process the text if no modifier keys are pressed.
  430. if (event.GetParameter< int >("ctrl_key", 0) == 0 &&
  431. event.GetParameter< int >("alt_key", 0) == 0 &&
  432. event.GetParameter< int >("meta_key", 0) == 0)
  433. {
  434. String text = event.GetParameter("text", String{});
  435. AddCharacters(text);
  436. }
  437. ShowCursor(true);
  438. event.StopPropagation();
  439. }
  440. break;
  441. case EventId::Focus:
  442. {
  443. if (event.GetTargetElement() == parent)
  444. {
  445. if (UpdateSelection(false))
  446. FormatElement();
  447. ShowCursor(true, false);
  448. }
  449. }
  450. break;
  451. case EventId::Blur:
  452. {
  453. if (event.GetTargetElement() == parent)
  454. {
  455. if (ClearSelection())
  456. FormatElement();
  457. ShowCursor(false, false);
  458. }
  459. }
  460. break;
  461. case EventId::Drag:
  462. if (cancel_next_drag)
  463. {
  464. // We currently ignore drag events right after a double click. They would need to be handled
  465. // specially by selecting whole words at a time, which is not yet implemented.
  466. break;
  467. }
  468. //-fallthrough
  469. case EventId::Mousedown:
  470. {
  471. if (event.GetTargetElement() == parent)
  472. {
  473. Vector2f mouse_position = Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0));
  474. mouse_position -= text_element->GetAbsoluteOffset();
  475. const int cursor_line_index = CalculateLineIndex(mouse_position.y);
  476. const int cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
  477. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  478. MoveCursorToCharacterBoundaries(false);
  479. UpdateCursorPosition(true);
  480. if (UpdateSelection(event == EventId::Drag || event.GetParameter<int>("shift_key", 0) > 0))
  481. FormatText();
  482. const bool move_to_cursor = (event == EventId::Drag);
  483. ShowCursor(true, move_to_cursor);
  484. cancel_next_drag = false;
  485. }
  486. }
  487. break;
  488. case EventId::Dblclick:
  489. {
  490. if (event.GetTargetElement() == parent)
  491. {
  492. ExpandSelection();
  493. cancel_next_drag = true;
  494. }
  495. }
  496. break;
  497. default:
  498. break;
  499. }
  500. }
  501. // Adds a new character to the string at the cursor position.
  502. bool WidgetTextInput::AddCharacters(String string)
  503. {
  504. SanitizeValue(string);
  505. if (selection_length > 0)
  506. DeleteSelection();
  507. if (max_length >= 0)
  508. ClampValue(string, Math::Max(max_length - GetLength(), 0));
  509. if (string.empty())
  510. return false;
  511. String value = GetAttributeValue();
  512. value.insert(std::min<size_t>((size_t)absolute_cursor_index, value.size()), string);
  513. absolute_cursor_index += (int)string.size();
  514. parent->SetAttribute("value", value);
  515. if (UpdateSelection(false))
  516. FormatText();
  517. DispatchChangeEvent();
  518. return true;
  519. }
  520. // Deletes a character from the string.
  521. bool WidgetTextInput::DeleteCharacters(CursorMovement direction)
  522. {
  523. // We set a selection of characters according to direction, and then delete it.
  524. // If we already have a selection, we delete that first.
  525. if (selection_length <= 0)
  526. MoveCursorHorizontal(direction, true);
  527. if (selection_length > 0)
  528. {
  529. DeleteSelection();
  530. DispatchChangeEvent();
  531. return true;
  532. }
  533. return false;
  534. }
  535. // Copies the selection (if any) to the clipboard.
  536. void WidgetTextInput::CopySelection()
  537. {
  538. const String& value = GetValue();
  539. const String snippet = value.substr(Math::Min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length);
  540. GetSystemInterface()->SetClipboardText(snippet);
  541. }
  542. // Moves the cursor along the current line.
  543. bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select)
  544. {
  545. const String& value = GetValue();
  546. int cursor_line_index = 0, cursor_character_index = 0;
  547. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  548. // By default the cursor wraps down when located on softbreaks. This may be overridden by setting the cursor using relative indices.
  549. cursor_wrap_down = true;
  550. // Whether to seek forward or back to align to utf8 boundaries later.
  551. bool seek_forward = false;
  552. switch (movement)
  553. {
  554. case CursorMovement::Begin:
  555. absolute_cursor_index = 0;
  556. break;
  557. case CursorMovement::BeginLine:
  558. SetCursorFromRelativeIndices(cursor_line_index, 0);
  559. break;
  560. case CursorMovement::PreviousWord:
  561. {
  562. // First skip whitespace, then skip all characters of the same class as the first non-whitespace character.
  563. CharacterClass skip_character_class = CharacterClass::Whitespace;
  564. const char* p_rend = value.data();
  565. const char* p_rbegin = p_rend + absolute_cursor_index;
  566. const char* p = p_rbegin - 1;
  567. for (; p > p_rend; --p)
  568. {
  569. const CharacterClass character_class = GetCharacterClass(*p);
  570. if (character_class != skip_character_class)
  571. {
  572. if (skip_character_class == CharacterClass::Whitespace)
  573. skip_character_class = character_class;
  574. else
  575. break;
  576. }
  577. }
  578. if (p != p_rend)
  579. ++p;
  580. absolute_cursor_index += int(p - p_rbegin);
  581. }
  582. break;
  583. case CursorMovement::Left:
  584. if (!select && selection_length > 0)
  585. absolute_cursor_index = selection_begin_index;
  586. else
  587. absolute_cursor_index -= 1;
  588. break;
  589. case CursorMovement::Right:
  590. seek_forward = true;
  591. if (!select && selection_length > 0)
  592. absolute_cursor_index = selection_begin_index + selection_length;
  593. else
  594. absolute_cursor_index += 1;
  595. break;
  596. case CursorMovement::NextWord:
  597. {
  598. // First skip all characters of the same class as the first character, then skip any whitespace.
  599. CharacterClass skip_character_class = CharacterClass::Undefined;
  600. const char* p_begin = value.data() + absolute_cursor_index;
  601. const char* p_end = value.data() + value.size();
  602. const char* p = p_begin;
  603. for (; p < p_end; ++p)
  604. {
  605. const CharacterClass character_class = GetCharacterClass(*p);
  606. if (skip_character_class == CharacterClass::Undefined)
  607. skip_character_class = character_class;
  608. if (character_class != skip_character_class)
  609. {
  610. if (character_class == CharacterClass::Whitespace)
  611. skip_character_class = CharacterClass::Whitespace;
  612. else
  613. break;
  614. }
  615. }
  616. absolute_cursor_index += int(p - p_begin);
  617. }
  618. break;
  619. case CursorMovement::EndLine:
  620. SetCursorFromRelativeIndices(cursor_line_index, lines[cursor_line_index].editable_length);
  621. break;
  622. case CursorMovement::End:
  623. absolute_cursor_index = INT_MAX;
  624. break;
  625. }
  626. absolute_cursor_index = Math::Clamp(absolute_cursor_index, 0, (int)GetValue().size());
  627. MoveCursorToCharacterBoundaries(seek_forward);
  628. UpdateCursorPosition(true);
  629. bool selection_changed = UpdateSelection(select);
  630. ShowCursor(true);
  631. return selection_changed;
  632. }
  633. // Moves the cursor up and down the text field.
  634. bool WidgetTextInput::MoveCursorVertical(int distance, bool select)
  635. {
  636. int cursor_line_index = 0, cursor_character_index = 0;
  637. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  638. cursor_line_index += distance;
  639. if (cursor_line_index < 0)
  640. {
  641. cursor_line_index = 0;
  642. cursor_character_index = 0;
  643. }
  644. else if (cursor_line_index >= (int)lines.size())
  645. {
  646. cursor_line_index = (int)lines.size() - 1;
  647. cursor_character_index = (int)lines[cursor_line_index].editable_length;
  648. }
  649. else
  650. cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
  651. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  652. MoveCursorToCharacterBoundaries(false);
  653. UpdateCursorPosition(false);
  654. bool selection_changed = UpdateSelection(select);
  655. ShowCursor(true);
  656. return selection_changed;
  657. }
  658. void WidgetTextInput::MoveCursorToCharacterBoundaries(bool forward)
  659. {
  660. const String& value = GetValue();
  661. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)value.size());
  662. const char* p_begin = value.data();
  663. const char* p_end = p_begin + value.size();
  664. const char* p_cursor = p_begin + absolute_cursor_index;
  665. const char* p = p_cursor;
  666. if (forward)
  667. p = StringUtilities::SeekForwardUTF8(p_cursor, p_end);
  668. else
  669. p = StringUtilities::SeekBackwardUTF8(p_cursor, p_begin);
  670. if (p != p_cursor)
  671. absolute_cursor_index += int(p - p_cursor);
  672. }
  673. void WidgetTextInput::ExpandSelection()
  674. {
  675. const String& value = GetValue();
  676. const char* const p_begin = value.data();
  677. const char* const p_end = p_begin + value.size();
  678. const char* const p_index = p_begin + absolute_cursor_index;
  679. // The first character encountered defines the character class to expand.
  680. CharacterClass expanding_character_class = CharacterClass::Undefined;
  681. auto character_is_wrong_type = [&expanding_character_class](const char* p) -> bool {
  682. const CharacterClass character_class = GetCharacterClass(*p);
  683. if (expanding_character_class == CharacterClass::Undefined)
  684. expanding_character_class = character_class;
  685. else if (character_class != expanding_character_class)
  686. return true;
  687. return false;
  688. };
  689. auto search_left = [&]() -> const char* {
  690. const char* p = p_index;
  691. for (; p > p_begin; p--)
  692. if (character_is_wrong_type(p - 1))
  693. break;
  694. return p;
  695. };
  696. auto search_right = [&]() -> const char* {
  697. const char* p = p_index;
  698. for (; p < p_end; p++)
  699. if (character_is_wrong_type(p))
  700. break;
  701. return p;
  702. };
  703. const char* p_left = p_index;
  704. const char* p_right = p_index;
  705. if (ideal_cursor_position_to_the_right_of_cursor)
  706. {
  707. p_right = search_right();
  708. p_left = search_left();
  709. }
  710. else
  711. {
  712. p_left = search_left();
  713. p_right = search_right();
  714. }
  715. cursor_wrap_down = true;
  716. absolute_cursor_index -= int(p_index - p_left);
  717. MoveCursorToCharacterBoundaries(false);
  718. bool selection_changed = UpdateSelection(false);
  719. absolute_cursor_index += int(p_right - p_left);
  720. MoveCursorToCharacterBoundaries(true);
  721. selection_changed |= UpdateSelection(true);
  722. if (selection_changed)
  723. FormatText();
  724. UpdateCursorPosition(true);
  725. }
  726. const String& WidgetTextInput::GetValue() const
  727. {
  728. return text_element->GetText();
  729. }
  730. String WidgetTextInput::GetAttributeValue() const
  731. {
  732. return parent->GetAttribute("value", String());
  733. }
  734. void WidgetTextInput::GetRelativeCursorIndices(int& out_cursor_line_index, int& out_cursor_character_index) const
  735. {
  736. int line_begin = 0;
  737. for (size_t i = 0; i < lines.size(); i++)
  738. {
  739. const int cursor_relative_line_end = absolute_cursor_index - (line_begin + lines[i].editable_length);
  740. // Test if the absolute index is located on the editable part of this line, otherwise we wrap down to the next line. We may have additional
  741. // characters after the editable length, such as the newline character '\n'. We also wrap down if the cursor is located to the right of any
  742. // such characters.
  743. if (cursor_relative_line_end <= 0)
  744. {
  745. const bool soft_wrapped_line = (lines[i].editable_length == lines[i].size);
  746. // If we are located exactly on a soft break (due to word wrapping) then the cursor wrap state determines whether or not we wrap down.
  747. if (cursor_relative_line_end == 0 && soft_wrapped_line && cursor_wrap_down && (int)i + 1 < (int)lines.size())
  748. {
  749. out_cursor_line_index = (int)i + 1;
  750. out_cursor_character_index = 0;
  751. }
  752. else
  753. {
  754. out_cursor_line_index = (int)i;
  755. out_cursor_character_index = Math::Max(absolute_cursor_index - line_begin, 0);
  756. }
  757. return;
  758. }
  759. line_begin += lines[i].size;
  760. }
  761. // We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
  762. // just set the relative cursors to the very end of the text field.
  763. out_cursor_line_index = (int)lines.size() - 1;
  764. out_cursor_character_index = lines[out_cursor_line_index].editable_length;
  765. }
  766. void WidgetTextInput::SetCursorFromRelativeIndices(int cursor_line_index, int cursor_character_index)
  767. {
  768. RMLUI_ASSERT(cursor_line_index < (int)lines.size())
  769. absolute_cursor_index = cursor_character_index;
  770. for (int i = 0; i < cursor_line_index; i++)
  771. absolute_cursor_index += lines[i].size;
  772. // Don't wrap down if we're located at the end of the line.
  773. cursor_wrap_down = !(cursor_character_index >= lines[cursor_line_index].editable_length);
  774. }
  775. // Calculates the line index under a specific vertical position.
  776. int WidgetTextInput::CalculateLineIndex(float position) const
  777. {
  778. float line_height = parent->GetLineHeight();
  779. int line_index = Math::RealToInteger(position / line_height);
  780. return Math::Clamp(line_index, 0, (int) (lines.size() - 1));
  781. }
  782. // Calculates the character index along a line under a specific horizontal position.
  783. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
  784. {
  785. int prev_offset = 0;
  786. float prev_line_width = 0;
  787. ideal_cursor_position_to_the_right_of_cursor = true;
  788. const char* p_begin = GetValue().data() + lines[line_index].value_offset;
  789. for (auto it = StringIteratorU8(p_begin, p_begin, p_begin + lines[line_index].editable_length); it;)
  790. {
  791. ++it;
  792. const int offset = (int)it.offset();
  793. const float line_width = (float)ElementUtilities::GetStringWidth(text_element, String(p_begin, (size_t)offset));
  794. if (line_width > position)
  795. {
  796. if (position - prev_line_width < line_width - position)
  797. {
  798. return prev_offset;
  799. }
  800. else
  801. {
  802. ideal_cursor_position_to_the_right_of_cursor = false;
  803. return offset;
  804. }
  805. }
  806. prev_line_width = line_width;
  807. prev_offset = offset;
  808. }
  809. return prev_offset;
  810. }
  811. // Shows or hides the cursor.
  812. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
  813. {
  814. if (show)
  815. {
  816. cursor_visible = true;
  817. cursor_timer = CURSOR_BLINK_TIME;
  818. last_update_time = GetSystemInterface()->GetElapsedTime();
  819. // Shift the cursor into view.
  820. if (move_to_cursor)
  821. {
  822. float minimum_scroll_top = (cursor_position.y + cursor_size.y) - parent->GetClientHeight();
  823. if (parent->GetScrollTop() < minimum_scroll_top)
  824. parent->SetScrollTop(minimum_scroll_top);
  825. else if (parent->GetScrollTop() > cursor_position.y)
  826. parent->SetScrollTop(cursor_position.y);
  827. float minimum_scroll_left = (cursor_position.x + cursor_size.x) - parent->GetClientWidth();
  828. if (parent->GetScrollLeft() < minimum_scroll_left)
  829. parent->SetScrollLeft(minimum_scroll_left);
  830. else if (parent->GetScrollLeft() > cursor_position.x)
  831. parent->SetScrollLeft(cursor_position.x);
  832. scroll_offset.x = parent->GetScrollLeft();
  833. scroll_offset.y = parent->GetScrollTop();
  834. }
  835. SetKeyboardActive(true);
  836. keyboard_showed = true;
  837. }
  838. else
  839. {
  840. cursor_visible = false;
  841. cursor_timer = -1;
  842. last_update_time = 0;
  843. if (keyboard_showed)
  844. {
  845. SetKeyboardActive(false);
  846. keyboard_showed = false;
  847. }
  848. }
  849. }
  850. // Formats the element, laying out the text and inserting scrollbars as appropriate.
  851. void WidgetTextInput::FormatElement()
  852. {
  853. using namespace Style;
  854. ElementScroll* scroll = parent->GetElementScroll();
  855. const float width = parent->GetBox().GetSize(Box::PADDING).x;
  856. const Overflow x_overflow_property = parent->GetComputedValues().overflow_x();
  857. const Overflow y_overflow_property = parent->GetComputedValues().overflow_y();
  858. const bool word_wrap = (parent->GetComputedValues().white_space() == WhiteSpace::Prewrap);
  859. if (x_overflow_property == Overflow::Scroll)
  860. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  861. else
  862. scroll->DisableScrollbar(ElementScroll::HORIZONTAL);
  863. if (y_overflow_property == Overflow::Scroll)
  864. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  865. else
  866. scroll->DisableScrollbar(ElementScroll::VERTICAL);
  867. // If the formatting produces scrollbars we need to format again later, this constraint enables early exit for the first formatting round.
  868. const float formatting_height_constraint = (y_overflow_property == Overflow::Auto ? parent->GetClientHeight() : FLT_MAX);
  869. // Format the text and determine its total area.
  870. Vector2f content_area = FormatText(formatting_height_constraint);
  871. // If we're set to automatically generate horizontal scrollbars, check for that now.
  872. if (!word_wrap && x_overflow_property == Overflow::Auto && content_area.x > parent->GetClientWidth())
  873. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  874. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  875. if (y_overflow_property == Overflow::Auto && content_area.y > parent->GetClientHeight())
  876. {
  877. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  878. content_area = FormatText();
  879. if (!word_wrap && x_overflow_property == Overflow::Auto && content_area.x > parent->GetClientWidth())
  880. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  881. }
  882. parent->SetContentBox(Vector2f(0, 0), content_area);
  883. scroll->FormatScrollbars();
  884. }
  885. Vector2f WidgetTextInput::FormatText(float height_constraint)
  886. {
  887. Vector2f content_area(0, 0);
  888. // Clear the old lines, and all the lines in the text elements.
  889. lines.clear();
  890. text_element->ClearLines();
  891. selected_text_element->ClearLines();
  892. // Clear the selection background geometry, and get the vertices and indices so the new geo can
  893. // be generated.
  894. selection_geometry.Release(true);
  895. Vector< Vertex >& selection_vertices = selection_geometry.GetVertices();
  896. Vector< int >& selection_indices = selection_geometry.GetIndices();
  897. // Determine the line-height of the text element.
  898. const float line_height = parent->GetLineHeight();
  899. // When the selection contains endlines we expand the selection area by this width.
  900. const int endline_selection_width = int(0.4f * parent->GetComputedValues().font_size());
  901. const float client_width = parent->GetClientWidth();
  902. int line_begin = 0;
  903. Vector2f line_position(0, 0);
  904. bool last_line = false;
  905. // Keep generating lines until all the text content is placed.
  906. do
  907. {
  908. if (client_width <= 0.f)
  909. {
  910. lines.push_back(Line{});
  911. break;
  912. }
  913. Line line = {};
  914. line.value_offset = line_begin;
  915. float line_width;
  916. String line_content;
  917. // Generate the next line.
  918. last_line = text_element->GenerateLine(line_content, line.size, line_width, line_begin, client_width - cursor_size.x, 0, false, false);
  919. // If this line terminates in a soft-return (word wrap), then the line may be leaving a space or two behind as an orphan. If so, we must
  920. // append the orphan onto the line even though it will push the line outside of the input field's bounds.
  921. if (!last_line && (line_content.empty() || line_content.back() != '\n'))
  922. {
  923. const String& text = GetValue();
  924. String orphan;
  925. for (int i = 1; i >= 0; --i)
  926. {
  927. int index = line_begin + line.size + i;
  928. if (index >= (int)text.size())
  929. continue;
  930. if (text[index] != ' ')
  931. {
  932. orphan.clear();
  933. continue;
  934. }
  935. int next_index = index + 1;
  936. if (!orphan.empty() || next_index >= (int)text.size() || text[next_index] != ' ')
  937. orphan += ' ';
  938. }
  939. if (!orphan.empty())
  940. {
  941. line_content += orphan;
  942. line.size += (int)orphan.size();
  943. line_width += ElementUtilities::GetStringWidth(text_element, orphan);
  944. }
  945. }
  946. // Now that we have the string of characters appearing on the new line, we split it into
  947. // three parts; the unselected text appearing before any selected text on the line, the
  948. // selected text on the line, and any unselected text after the selection.
  949. String pre_selection, selection, post_selection;
  950. GetLineSelection(pre_selection, selection, post_selection, line_content, line_begin);
  951. // The pre-selected text is placed, if there is any (if the selection starts on or before
  952. // the beginning of this line, then this will be empty).
  953. if (!pre_selection.empty())
  954. {
  955. text_element->AddLine(line_position, pre_selection);
  956. line_position.x += ElementUtilities::GetStringWidth(text_element, pre_selection);
  957. }
  958. // Return the extra kerning that would result in joining two strings.
  959. auto GetKerningBetween = [this](const String& left, const String& right) -> float {
  960. if (left.empty() || right.empty())
  961. return 0.0f;
  962. // We could join the whole string, and compare the result of the joined width to the individual widths of each string. Instead, we take
  963. // the two neighboring characters from each string and compare the string width with and without kerning, which should be much faster.
  964. const Character left_back = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&left.back(), &left.front()));
  965. const String right_front_u8 =
  966. right.substr(0, size_t(StringUtilities::SeekForwardUTF8(right.c_str() + 1, right.c_str() + right.size()) - right.c_str()));
  967. const int width_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, left_back);
  968. const int width_no_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, Character::Null);
  969. return float(width_kerning - width_no_kerning);
  970. };
  971. // Check if the editable length needs to be truncated to dodge a trailing endline.
  972. line.editable_length = (int)line_content.size();
  973. if (!line_content.empty() && line_content.back() == '\n')
  974. line.editable_length -= 1;
  975. // If there is any selected text on this line, place it in the selected text element and
  976. // generate the geometry for its background.
  977. if (!selection.empty())
  978. {
  979. line_position.x += GetKerningBetween(pre_selection, selection);
  980. selected_text_element->AddLine(line_position, selection);
  981. const int selection_width = ElementUtilities::GetStringWidth(selected_text_element, selection);
  982. const bool selection_contains_endline = (selection_begin_index + selection_length > line_begin + line.editable_length);
  983. const Vector2f selection_size(float(selection_width + (selection_contains_endline ? endline_selection_width : 0)), line_height);
  984. selection_vertices.resize(selection_vertices.size() + 4);
  985. selection_indices.resize(selection_indices.size() + 6);
  986. GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6],
  987. line_position, selection_size, selection_colour, (int)selection_vertices.size() - 4);
  988. line_position.x += selection_width;
  989. }
  990. // If there is any unselected text after the selection on this line, place it in the
  991. // standard text element after the selected text.
  992. if (!post_selection.empty())
  993. {
  994. line_position.x += GetKerningBetween(selection, post_selection);
  995. text_element->AddLine(line_position, post_selection);
  996. }
  997. // Update variables for the next line.
  998. line_begin += line.size;
  999. line_position.x = 0;
  1000. line_position.y += line_height;
  1001. // Grow the content area width-wise if this line is the longest so far, and push the height out.
  1002. content_area.x = Math::Max(content_area.x, line_width + cursor_size.x);
  1003. content_area.y = line_position.y;
  1004. // Finally, push the new line into our array of lines.
  1005. lines.push_back(std::move(line));
  1006. } while (!last_line && content_area.y <= height_constraint);
  1007. // Clamp the cursor to a valid range.
  1008. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)GetValue().size());
  1009. return content_area;
  1010. }
  1011. // Generates the text cursor.
  1012. void WidgetTextInput::GenerateCursor()
  1013. {
  1014. // Generates the cursor.
  1015. cursor_geometry.Release();
  1016. Vector< Vertex >& vertices = cursor_geometry.GetVertices();
  1017. vertices.resize(4);
  1018. Vector< int >& indices = cursor_geometry.GetIndices();
  1019. indices.resize(6);
  1020. cursor_size.x = Math::RoundFloat( ElementUtilities::GetDensityIndependentPixelRatio(text_element) );
  1021. cursor_size.y = text_element->GetLineHeight() + 2.0f;
  1022. Colourb color = parent->GetComputedValues().color();
  1023. if (const Property* property = parent->GetProperty(PropertyId::CaretColor))
  1024. {
  1025. if (property->unit == Property::COLOUR)
  1026. color = property->Get<Colourb>();
  1027. }
  1028. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), cursor_size, color);
  1029. }
  1030. void WidgetTextInput::ForceFormattingOnNextLayout()
  1031. {
  1032. force_formatting_on_next_layout = true;
  1033. }
  1034. void WidgetTextInput::UpdateCursorPosition(bool update_ideal_cursor_position)
  1035. {
  1036. if (text_element->GetFontFaceHandle() == 0 || lines.empty())
  1037. return;
  1038. int cursor_line_index = 0, cursor_character_index = 0;
  1039. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  1040. cursor_position.x = (float)ElementUtilities::GetStringWidth(text_element, GetValue().substr(lines[cursor_line_index].value_offset, cursor_character_index));
  1041. cursor_position.y = -1.f + (float)cursor_line_index * text_element->GetLineHeight();
  1042. if (update_ideal_cursor_position)
  1043. ideal_cursor_position = cursor_position.x;
  1044. }
  1045. bool WidgetTextInput::UpdateSelection(bool selecting)
  1046. {
  1047. bool selection_changed = false;
  1048. if (!selecting)
  1049. {
  1050. selection_anchor_index = absolute_cursor_index;
  1051. selection_changed = ClearSelection();
  1052. }
  1053. else
  1054. {
  1055. int new_begin_index;
  1056. int new_end_index;
  1057. if (absolute_cursor_index > selection_anchor_index)
  1058. {
  1059. new_begin_index = selection_anchor_index;
  1060. new_end_index = absolute_cursor_index;
  1061. }
  1062. else
  1063. {
  1064. new_begin_index = absolute_cursor_index;
  1065. new_end_index = selection_anchor_index;
  1066. }
  1067. if (new_begin_index != selection_begin_index ||
  1068. new_end_index - new_begin_index != selection_length)
  1069. {
  1070. selection_begin_index = new_begin_index;
  1071. selection_length = new_end_index - new_begin_index;
  1072. selection_changed = true;
  1073. }
  1074. }
  1075. return selection_changed;
  1076. }
  1077. // Removes the selection of text.
  1078. bool WidgetTextInput::ClearSelection()
  1079. {
  1080. if (selection_length > 0)
  1081. {
  1082. selection_length = 0;
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. // Deletes all selected text and removes the selection.
  1088. void WidgetTextInput::DeleteSelection()
  1089. {
  1090. if (selection_length > 0)
  1091. {
  1092. String new_value = GetAttributeValue();
  1093. const size_t selection_begin = std::min((size_t)selection_begin_index, (size_t)new_value.size());
  1094. new_value.erase(selection_begin, (size_t)selection_length);
  1095. // Move the cursor to the beginning of the old selection.
  1096. absolute_cursor_index = selection_begin_index;
  1097. GetElement()->SetAttribute("value", new_value);
  1098. // Erase our record of the selection.
  1099. if (UpdateSelection(false))
  1100. FormatText();
  1101. }
  1102. }
  1103. // Split one line of text into three parts, based on the current selection.
  1104. void WidgetTextInput::GetLineSelection(String& pre_selection, String& selection, String& post_selection, const String& line, int line_begin) const
  1105. {
  1106. const int selection_end = selection_begin_index + selection_length;
  1107. // Check if we have any selection at all, and if so if the selection is on this line.
  1108. if (selection_length <= 0 || selection_end < line_begin || selection_begin_index > line_begin + (int)line.size())
  1109. {
  1110. pre_selection = line;
  1111. return;
  1112. }
  1113. const int line_length = (int)line.size();
  1114. using namespace Math;
  1115. // Split the line up into its three parts, depending on the size and placement of the selection.
  1116. pre_selection = line.substr(0, Max(0, selection_begin_index - line_begin));
  1117. selection = line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin)));
  1118. post_selection = line.substr(Clamp(selection_end - line_begin, 0, line_length));
  1119. }
  1120. void WidgetTextInput::SetKeyboardActive(bool active)
  1121. {
  1122. if (SystemInterface* system = GetSystemInterface())
  1123. {
  1124. if (active)
  1125. {
  1126. // Activate the keyboard and submit the cursor position and line height to enable clients to adjust the input method editor (IME). Note
  1127. // that the cursor is extended by one pixel along the top and bottom, we reverse this extension here.
  1128. const Vector2f element_offset = parent->GetAbsoluteOffset() - scroll_offset;
  1129. const Vector2f absolute_cursor_position = element_offset + cursor_position + Vector2f(0, 1);
  1130. const float line_height = cursor_size.y - 2.f;
  1131. system->ActivateKeyboard(absolute_cursor_position, line_height);
  1132. }
  1133. else
  1134. {
  1135. system->DeactivateKeyboard();
  1136. }
  1137. }
  1138. }
  1139. } // namespace Rml