WidgetTextInput.cpp 44 KB

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