2
0

WidgetTextInput.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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/Input.h"
  39. #include "../../../Include/RmlUi/Core/Math.h"
  40. #include "../../../Include/RmlUi/Core/MeshUtilities.h"
  41. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  42. #include "../../../Include/RmlUi/Core/SystemInterface.h"
  43. #include "../../../Include/RmlUi/Core/TextInputContext.h"
  44. #include "../../../Include/RmlUi/Core/TextInputHandler.h"
  45. #include "../Clock.h"
  46. #include "ElementTextSelection.h"
  47. #include <algorithm>
  48. #include <limits.h>
  49. namespace Rml {
  50. static constexpr float CURSOR_BLINK_TIME = 0.7f; // [s]
  51. static constexpr float OVERFLOW_TOLERANCE = 0.5f; // [px]
  52. static constexpr float COMPOSITION_UNDERLINE_WIDTH = 2.f; // [px]
  53. enum class CharacterClass { Word, Punctuation, Newline, Whitespace, Undefined };
  54. static CharacterClass GetCharacterClass(char c)
  55. {
  56. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || ((unsigned char)c >= 128))
  57. return CharacterClass::Word;
  58. if ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~'))
  59. return CharacterClass::Punctuation;
  60. if (c == '\n')
  61. return CharacterClass::Newline;
  62. return CharacterClass::Whitespace;
  63. }
  64. // Clamps the value to the given maximum number of unicode code points. Returns true if the value was changed.
  65. static bool ClampValue(String& value, int max_length)
  66. {
  67. if (max_length >= 0)
  68. {
  69. int max_byte_length = StringUtilities::ConvertCharacterOffsetToByteOffset(value, max_length);
  70. if (max_byte_length < (int)value.size())
  71. {
  72. value.erase((size_t)max_byte_length);
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. class WidgetTextInputContext final : public TextInputContext {
  79. public:
  80. WidgetTextInputContext(TextInputHandler* handler, WidgetTextInput* _owner, ElementFormControl* _element);
  81. ~WidgetTextInputContext();
  82. bool GetBoundingBox(Rectanglef& out_rectangle) const override;
  83. void GetSelectionRange(int& start, int& end) const override;
  84. void SetSelectionRange(int start, int end) override;
  85. void SetCursorPosition(int position) override;
  86. void SetText(StringView text, int start, int end) override;
  87. void SetCompositionRange(int start, int end) override;
  88. void CommitComposition(StringView composition) override;
  89. private:
  90. TextInputHandler* handler;
  91. WidgetTextInput* owner;
  92. ElementFormControl* element;
  93. };
  94. WidgetTextInputContext::WidgetTextInputContext(TextInputHandler* handler, WidgetTextInput* owner, ElementFormControl* element) :
  95. handler(handler), owner(owner), element(element)
  96. {}
  97. WidgetTextInputContext::~WidgetTextInputContext()
  98. {
  99. handler->OnDestroy(this);
  100. }
  101. bool WidgetTextInputContext::GetBoundingBox(Rectanglef& out_rectangle) const
  102. {
  103. return ElementUtilities::GetBoundingBox(out_rectangle, element, BoxArea::Border);
  104. }
  105. void WidgetTextInputContext::GetSelectionRange(int& start, int& end) const
  106. {
  107. owner->GetSelection(&start, &end, nullptr);
  108. }
  109. void WidgetTextInputContext::SetSelectionRange(int start, int end)
  110. {
  111. owner->SetSelectionRange(start, end);
  112. }
  113. void WidgetTextInputContext::SetCursorPosition(int position)
  114. {
  115. SetSelectionRange(position, position);
  116. }
  117. void WidgetTextInputContext::SetText(StringView text, int start, int end)
  118. {
  119. String value = owner->GetAttributeValue();
  120. start = StringUtilities::ConvertCharacterOffsetToByteOffset(value, start);
  121. end = StringUtilities::ConvertCharacterOffsetToByteOffset(value, end);
  122. RMLUI_ASSERTMSG(end >= start, "Invalid end character offset.");
  123. value.replace(start, end - start, text.begin(), text.size());
  124. element->SetValue(value);
  125. }
  126. void WidgetTextInputContext::SetCompositionRange(int start, int end)
  127. {
  128. owner->SetCompositionRange(start, end);
  129. }
  130. void WidgetTextInputContext::CommitComposition(StringView composition)
  131. {
  132. int start_byte, end_byte;
  133. owner->GetCompositionRange(start_byte, end_byte);
  134. // No composition to commit.
  135. if (start_byte == 0 && end_byte == 0)
  136. return;
  137. String value = owner->GetAttributeValue();
  138. // If the text input has a length restriction, we have to shorten the composition string.
  139. if (owner->GetMaxLength() >= 0)
  140. {
  141. int start = StringUtilities::ConvertByteOffsetToCharacterOffset(value, start_byte);
  142. int end = StringUtilities::ConvertByteOffsetToCharacterOffset(value, end_byte);
  143. int value_length = (int)StringUtilities::LengthUTF8(value);
  144. int composition_length = (int)StringUtilities::LengthUTF8(composition);
  145. // The requested text value would exceed the length restriction after replacing the original value.
  146. if (value_length + composition_length - (start - end) > owner->GetMaxLength())
  147. {
  148. int new_length = owner->GetMaxLength() - (value_length - composition_length);
  149. int new_length_byte = StringUtilities::ConvertCharacterOffsetToByteOffset(composition, new_length);
  150. composition = StringView(composition.begin(), composition.begin() + new_length_byte);
  151. }
  152. }
  153. RMLUI_ASSERTMSG(end_byte >= start_byte, "Invalid end character offset.");
  154. value.replace(start_byte, end_byte - start_byte, composition.begin(), composition.size());
  155. element->SetValue(value);
  156. }
  157. WidgetTextInput::WidgetTextInput(ElementFormControl* _parent)
  158. {
  159. keyboard_showed = false;
  160. parent = _parent;
  161. parent->SetProperty(PropertyId::WhiteSpace, Property(Style::WhiteSpace::Pre));
  162. parent->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Hidden));
  163. parent->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Hidden));
  164. parent->SetProperty(PropertyId::Drag, Property(Style::Drag::Drag));
  165. parent->SetProperty(PropertyId::WordBreak, Property(Style::WordBreak::BreakWord));
  166. parent->SetProperty(PropertyId::TextTransform, Property(Style::TextTransform::None));
  167. parent->SetProperty(PropertyId::Clip, Property(Style::Clip::Type::Auto));
  168. parent->AddEventListener(EventId::Keydown, this, true);
  169. parent->AddEventListener(EventId::Textinput, this, true);
  170. parent->AddEventListener(EventId::Focus, this, true);
  171. parent->AddEventListener(EventId::Blur, this, true);
  172. parent->AddEventListener(EventId::Mousedown, this, true);
  173. parent->AddEventListener(EventId::Dblclick, this, true);
  174. parent->AddEventListener(EventId::Drag, this, true);
  175. ElementPtr unique_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  176. text_element = rmlui_dynamic_cast<ElementText*>(unique_text.get());
  177. ElementPtr unique_selected_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes());
  178. selected_text_element = rmlui_dynamic_cast<ElementText*>(unique_selected_text.get());
  179. if (text_element)
  180. {
  181. text_element->SuppressAutoLayout();
  182. parent->AppendChild(std::move(unique_text), false);
  183. selected_text_element->SuppressAutoLayout();
  184. parent->AppendChild(std::move(unique_selected_text), false);
  185. }
  186. // Create the dummy selection element.
  187. ElementPtr unique_selection = Factory::InstanceElement(parent, "#selection", "selection", XMLAttributes());
  188. if (ElementTextSelection* text_selection_element = rmlui_dynamic_cast<ElementTextSelection*>(unique_selection.get()))
  189. {
  190. selection_element = text_selection_element;
  191. text_selection_element->SetWidget(this);
  192. parent->AppendChild(std::move(unique_selection), false);
  193. }
  194. absolute_cursor_index = 0;
  195. cursor_wrap_down = false;
  196. ideal_cursor_position_to_the_right_of_cursor = true;
  197. cancel_next_drag = false;
  198. force_formatting_on_next_layout = false;
  199. ideal_cursor_position = 0;
  200. max_length = -1;
  201. selection_anchor_index = 0;
  202. selection_begin_index = 0;
  203. selection_length = 0;
  204. ime_composition_begin_index = 0;
  205. ime_composition_end_index = 0;
  206. last_update_time = 0;
  207. ink_overflow = false;
  208. ShowCursor(false);
  209. }
  210. WidgetTextInput::~WidgetTextInput()
  211. {
  212. parent->RemoveEventListener(EventId::Keydown, this, true);
  213. parent->RemoveEventListener(EventId::Textinput, this, true);
  214. parent->RemoveEventListener(EventId::Focus, this, true);
  215. parent->RemoveEventListener(EventId::Blur, this, true);
  216. parent->RemoveEventListener(EventId::Mousedown, this, true);
  217. parent->RemoveEventListener(EventId::Dblclick, this, true);
  218. parent->RemoveEventListener(EventId::Drag, this, true);
  219. // This widget might be parented by an input element, which may now be constructing a completely different type.
  220. // Thus, remove all properties set by this widget so they don't affect the new type.
  221. parent->RemoveProperty(PropertyId::WhiteSpace);
  222. parent->RemoveProperty(PropertyId::OverflowX);
  223. parent->RemoveProperty(PropertyId::OverflowY);
  224. parent->RemoveProperty(PropertyId::Drag);
  225. parent->RemoveProperty(PropertyId::WordBreak);
  226. parent->RemoveProperty(PropertyId::TextTransform);
  227. // Remove all the children added by the text widget.
  228. parent->RemoveChild(text_element);
  229. parent->RemoveChild(selected_text_element);
  230. parent->RemoveChild(selection_element);
  231. }
  232. void WidgetTextInput::SetValue(String value)
  233. {
  234. const size_t initial_size = value.size();
  235. SanitizeValue(value);
  236. if (initial_size != value.size())
  237. {
  238. parent->SetAttribute("value", value);
  239. DispatchChangeEvent();
  240. }
  241. else
  242. {
  243. TransformValue(value);
  244. text_element->SetText(value);
  245. // Reset the IME composition range when the value changes.
  246. ime_composition_begin_index = 0;
  247. ime_composition_end_index = 0;
  248. FormatElement();
  249. UpdateCursorPosition(true);
  250. }
  251. }
  252. void WidgetTextInput::TransformValue(String& /*value*/) {}
  253. int WidgetTextInput::DisplayIndexToAttributeIndex(int display_index, const String& /*attribute_value*/)
  254. {
  255. return display_index;
  256. }
  257. int WidgetTextInput::AttributeIndexToDisplayIndex(int attribute_index, const String& /*attribute_value*/)
  258. {
  259. return attribute_index;
  260. }
  261. void WidgetTextInput::SetMaxLength(int _max_length)
  262. {
  263. if (max_length != _max_length)
  264. {
  265. max_length = _max_length;
  266. String value = GetValue();
  267. if (ClampValue(value, max_length))
  268. GetElement()->SetAttribute("value", value);
  269. }
  270. }
  271. int WidgetTextInput::GetMaxLength() const
  272. {
  273. return max_length;
  274. }
  275. int WidgetTextInput::GetLength() const
  276. {
  277. size_t result = StringUtilities::LengthUTF8(GetValue());
  278. return (int)result;
  279. }
  280. void WidgetTextInput::Select()
  281. {
  282. SetSelectionRange(0, INT_MAX);
  283. }
  284. void WidgetTextInput::SetSelectionRange(int selection_start, int selection_end)
  285. {
  286. if (!IsFocused())
  287. return;
  288. const String& value = GetValue();
  289. const int byte_start = StringUtilities::ConvertCharacterOffsetToByteOffset(value, selection_start);
  290. const int byte_end = StringUtilities::ConvertCharacterOffsetToByteOffset(value, selection_end);
  291. const bool is_selecting = (byte_start != byte_end);
  292. cursor_wrap_down = true;
  293. absolute_cursor_index = byte_end;
  294. bool selection_changed = false;
  295. if (is_selecting)
  296. {
  297. selection_anchor_index = byte_start;
  298. selection_changed = UpdateSelection(true);
  299. }
  300. else
  301. {
  302. selection_changed = UpdateSelection(false);
  303. }
  304. UpdateCursorPosition(true);
  305. ShowCursor(true, true);
  306. if (selection_changed)
  307. FormatText();
  308. }
  309. void WidgetTextInput::GetSelection(int* selection_start, int* selection_end, String* selected_text) const
  310. {
  311. const String& value = GetValue();
  312. if (selection_start)
  313. *selection_start = StringUtilities::ConvertByteOffsetToCharacterOffset(value, selection_begin_index);
  314. if (selection_end)
  315. *selection_end = StringUtilities::ConvertByteOffsetToCharacterOffset(value, selection_begin_index + selection_length);
  316. if (selected_text)
  317. *selected_text = value.substr(Math::Min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length);
  318. }
  319. void WidgetTextInput::SetCompositionRange(int range_start, int range_end)
  320. {
  321. const String& value = GetValue();
  322. const int byte_start = StringUtilities::ConvertCharacterOffsetToByteOffset(value, range_start);
  323. const int byte_end = StringUtilities::ConvertCharacterOffsetToByteOffset(value, range_end);
  324. if (byte_end > byte_start)
  325. {
  326. ime_composition_begin_index = byte_start;
  327. ime_composition_end_index = byte_end;
  328. }
  329. else
  330. {
  331. ime_composition_begin_index = 0;
  332. ime_composition_end_index = 0;
  333. }
  334. FormatText();
  335. }
  336. void WidgetTextInput::GetCompositionRange(int& range_start, int& range_end) const
  337. {
  338. range_start = ime_composition_begin_index;
  339. range_end = ime_composition_end_index;
  340. }
  341. void WidgetTextInput::UpdateSelectionColours()
  342. {
  343. // Determine what the colour of the selected text is. If our 'selection' element has the 'color'
  344. // attribute set, then use that. Otherwise, use the inverse of our own text colour.
  345. Colourb colour;
  346. const Property* colour_property = selection_element->GetLocalProperty(PropertyId::Color);
  347. if (colour_property)
  348. colour = colour_property->Get<Colourb>();
  349. else
  350. {
  351. colour = parent->GetComputedValues().color();
  352. colour.red = 255 - colour.red;
  353. colour.green = 255 - colour.green;
  354. colour.blue = 255 - colour.blue;
  355. }
  356. // Set the computed text colour on the element holding the selected text.
  357. selected_text_element->SetProperty(PropertyId::Color, Property(colour, Unit::COLOUR));
  358. // If the 'background-color' property has been set on the 'selection' element, use that as the
  359. // background colour for the selected text. Otherwise, use the inverse of the selected text
  360. // colour.
  361. colour_property = selection_element->GetLocalProperty(PropertyId::BackgroundColor);
  362. if (colour_property)
  363. colour = colour_property->Get<Colourb>();
  364. else
  365. colour = Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha);
  366. selection_colour = colour.ToPremultiplied();
  367. // Color may have changed, so we update the cursor geometry.
  368. GenerateCursor();
  369. }
  370. void WidgetTextInput::OnUpdate()
  371. {
  372. if (cursor_timer > 0)
  373. {
  374. double current_time = Clock::GetElapsedTime();
  375. cursor_timer -= float(current_time - last_update_time);
  376. last_update_time = current_time;
  377. while (cursor_timer <= 0)
  378. {
  379. cursor_timer += CURSOR_BLINK_TIME;
  380. cursor_visible = !cursor_visible;
  381. }
  382. if (parent->IsVisible(true))
  383. {
  384. if (Context* ctx = parent->GetContext())
  385. ctx->RequestNextUpdate(cursor_timer);
  386. }
  387. }
  388. }
  389. void WidgetTextInput::OnResize()
  390. {
  391. GenerateCursor();
  392. Vector2f text_position = parent->GetBox().GetPosition(BoxArea::Content);
  393. text_element->SetOffset(text_position, parent);
  394. selected_text_element->SetOffset(text_position, parent);
  395. ForceFormattingOnNextLayout();
  396. }
  397. void WidgetTextInput::OnRender()
  398. {
  399. ElementUtilities::SetClippingRegion(text_element);
  400. Vector2f text_translation = parent->GetAbsoluteOffset() - Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
  401. selection_composition_geometry.Render(text_translation);
  402. if (cursor_visible && selection_length <= 0 && !parent->IsDisabled())
  403. {
  404. cursor_geometry.Render(text_translation + cursor_position);
  405. }
  406. }
  407. void WidgetTextInput::OnLayout()
  408. {
  409. if (force_formatting_on_next_layout)
  410. {
  411. internal_dimensions = parent->GetBox().GetSize(BoxArea::Content);
  412. FormatElement();
  413. UpdateCursorPosition(true);
  414. force_formatting_on_next_layout = false;
  415. }
  416. }
  417. Element* WidgetTextInput::GetElement() const
  418. {
  419. return parent;
  420. }
  421. TextInputHandler* WidgetTextInput::GetTextInputHandler() const
  422. {
  423. if (Context* context = parent->GetContext())
  424. return context->GetTextInputHandler();
  425. return nullptr;
  426. }
  427. bool WidgetTextInput::IsFocused() const
  428. {
  429. return cursor_timer > 0;
  430. }
  431. void WidgetTextInput::DispatchChangeEvent(bool linebreak)
  432. {
  433. Dictionary parameters;
  434. parameters["value"] = GetAttributeValue();
  435. parameters["linebreak"] = Variant(linebreak);
  436. GetElement()->DispatchEvent(EventId::Change, parameters);
  437. }
  438. void WidgetTextInput::ProcessEvent(Event& event)
  439. {
  440. if (parent->IsDisabled())
  441. return;
  442. switch (event.GetId())
  443. {
  444. case EventId::Keydown:
  445. {
  446. Input::KeyIdentifier key_identifier = (Input::KeyIdentifier)event.GetParameter<int>("key_identifier", 0);
  447. bool numlock = event.GetParameter<int>("num_lock_key", 0) > 0;
  448. bool shift = event.GetParameter<int>("shift_key", 0) > 0;
  449. bool ctrl = event.GetParameter<int>("ctrl_key", 0) > 0;
  450. bool alt = event.GetParameter<int>("alt_key", 0) > 0;
  451. bool selection_changed = false;
  452. bool out_of_bounds = false;
  453. switch (key_identifier)
  454. {
  455. // clang-format off
  456. case Input::KI_NUMPAD4: if (numlock) break; //-fallthrough
  457. case Input::KI_LEFT: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::PreviousWord : CursorMovement::Left, shift, out_of_bounds); break;
  458. case Input::KI_NUMPAD6: if (numlock) break; //-fallthrough
  459. case Input::KI_RIGHT: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::NextWord : CursorMovement::Right, shift, out_of_bounds); break;
  460. case Input::KI_NUMPAD8: if (numlock) break; //-fallthrough
  461. case Input::KI_UP: selection_changed = MoveCursorVertical(-1, shift, out_of_bounds); break;
  462. case Input::KI_NUMPAD2: if (numlock) break; //-fallthrough
  463. case Input::KI_DOWN: selection_changed = MoveCursorVertical(1, shift, out_of_bounds); break;
  464. case Input::KI_NUMPAD7: if (numlock) break; //-fallthrough
  465. case Input::KI_HOME: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::Begin : CursorMovement::BeginLine, shift, out_of_bounds); break;
  466. case Input::KI_NUMPAD1: if (numlock) break; //-fallthrough
  467. case Input::KI_END: selection_changed = MoveCursorHorizontal(ctrl ? CursorMovement::End : CursorMovement::EndLine, shift, out_of_bounds); break;
  468. case Input::KI_NUMPAD9: if (numlock) break; //-fallthrough
  469. case Input::KI_PRIOR: selection_changed = MoveCursorVertical(-int(internal_dimensions.y / GetLineHeight()) + 1, shift, out_of_bounds); break;
  470. case Input::KI_NUMPAD3: if (numlock) break; //-fallthrough
  471. case Input::KI_NEXT: selection_changed = MoveCursorVertical(int(internal_dimensions.y / GetLineHeight()) - 1, shift, out_of_bounds); break;
  472. case Input::KI_BACK:
  473. {
  474. CursorMovement direction = (ctrl ? CursorMovement::PreviousWord : CursorMovement::Left);
  475. DeleteCharacters(direction);
  476. ShowCursor(true);
  477. }
  478. break;
  479. case Input::KI_DECIMAL: if (numlock) break; //-fallthrough
  480. case Input::KI_DELETE:
  481. {
  482. CursorMovement direction = (ctrl ? CursorMovement::NextWord : CursorMovement::Right);
  483. DeleteCharacters(direction);
  484. ShowCursor(true);
  485. }
  486. break;
  487. // clang-format on
  488. case Input::KI_NUMPADENTER:
  489. case Input::KI_RETURN:
  490. {
  491. LineBreak();
  492. }
  493. break;
  494. case Input::KI_A:
  495. {
  496. if (ctrl && !alt)
  497. Select();
  498. }
  499. break;
  500. case Input::KI_C:
  501. {
  502. if (ctrl && selection_length > 0)
  503. CopySelection();
  504. }
  505. break;
  506. case Input::KI_X:
  507. {
  508. if (ctrl && selection_length > 0)
  509. {
  510. CopySelection();
  511. DeleteSelection();
  512. DispatchChangeEvent();
  513. ShowCursor(true);
  514. }
  515. }
  516. break;
  517. case Input::KI_V:
  518. {
  519. if (ctrl && !alt)
  520. {
  521. String clipboard_text;
  522. GetSystemInterface()->GetClipboardText(clipboard_text);
  523. AddCharacters(clipboard_text);
  524. ShowCursor(true);
  525. }
  526. }
  527. break;
  528. // Ignore tabs so input fields can be navigated through with keys.
  529. case Input::KI_TAB: return;
  530. default: break;
  531. }
  532. if (shift || ctrl || !out_of_bounds || selection_changed)
  533. event.StopPropagation();
  534. if (selection_changed)
  535. FormatText();
  536. }
  537. break;
  538. case EventId::Textinput:
  539. {
  540. // Only process the text if no modifier keys are pressed.
  541. if (event.GetParameter<int>("ctrl_key", 0) == 0 && event.GetParameter<int>("alt_key", 0) == 0 && event.GetParameter<int>("meta_key", 0) == 0)
  542. {
  543. String text = event.GetParameter("text", String{});
  544. AddCharacters(text);
  545. }
  546. ShowCursor(true);
  547. event.StopPropagation();
  548. }
  549. break;
  550. case EventId::Focus:
  551. {
  552. if (event.GetTargetElement() == parent)
  553. {
  554. parent->SetPseudoClass("focus-visible", true);
  555. if (UpdateSelection(false))
  556. FormatText();
  557. ShowCursor(true, false);
  558. if (TextInputHandler* handler = GetTextInputHandler())
  559. {
  560. // Lazily instance the text input context for this widget.
  561. if (!text_input_context)
  562. text_input_context = MakeUnique<WidgetTextInputContext>(handler, this, parent);
  563. handler->OnActivate(text_input_context.get());
  564. }
  565. }
  566. }
  567. break;
  568. case EventId::Blur:
  569. {
  570. if (event.GetTargetElement() == parent)
  571. {
  572. if (TextInputHandler* handler = GetTextInputHandler())
  573. handler->OnDeactivate(text_input_context.get());
  574. if (ClearSelection())
  575. FormatText();
  576. ShowCursor(false, false);
  577. }
  578. }
  579. break;
  580. case EventId::Drag:
  581. if (cancel_next_drag)
  582. {
  583. // We currently ignore drag events right after a double click. They would need to be handled
  584. // specially by selecting whole words at a time, which is not yet implemented.
  585. break;
  586. }
  587. //-fallthrough
  588. case EventId::Mousedown:
  589. {
  590. if (event.GetTargetElement() == parent)
  591. {
  592. Vector2f mouse_position = Vector2f(event.GetParameter<float>("mouse_x", 0), event.GetParameter<float>("mouse_y", 0));
  593. mouse_position -= text_element->GetAbsoluteOffset();
  594. const int cursor_line_index = CalculateLineIndex(mouse_position.y);
  595. const int cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
  596. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  597. MoveCursorToCharacterBoundaries(false);
  598. UpdateCursorPosition(true);
  599. if (UpdateSelection(event == EventId::Drag || event.GetParameter<int>("shift_key", 0) > 0))
  600. FormatText();
  601. const bool move_to_cursor = (event == EventId::Drag);
  602. ShowCursor(true, move_to_cursor);
  603. cancel_next_drag = false;
  604. }
  605. }
  606. break;
  607. case EventId::Dblclick:
  608. {
  609. if (event.GetTargetElement() == parent)
  610. {
  611. ExpandSelection();
  612. cancel_next_drag = true;
  613. }
  614. }
  615. break;
  616. default: break;
  617. }
  618. }
  619. bool WidgetTextInput::AddCharacters(String string)
  620. {
  621. SanitizeValue(string);
  622. if (selection_length > 0)
  623. DeleteSelection();
  624. if (max_length >= 0)
  625. ClampValue(string, Math::Max(max_length - GetLength(), 0));
  626. if (string.empty())
  627. return false;
  628. String value = GetAttributeValue();
  629. const int attribute_insert_index = DisplayIndexToAttributeIndex(absolute_cursor_index, value);
  630. value.insert(std::min<size_t>((size_t)attribute_insert_index, value.size()), string);
  631. const int new_cursor_attribute_index = AttributeIndexToDisplayIndex(attribute_insert_index + (int)string.size(), value);
  632. absolute_cursor_index = new_cursor_attribute_index;
  633. parent->SetAttribute("value", value);
  634. if (UpdateSelection(false))
  635. FormatText();
  636. DispatchChangeEvent();
  637. return true;
  638. }
  639. bool WidgetTextInput::DeleteCharacters(CursorMovement direction)
  640. {
  641. bool out_of_bounds;
  642. // We set a selection of characters according to direction, and then delete it.
  643. // If we already have a selection, we delete that first.
  644. if (selection_length <= 0)
  645. MoveCursorHorizontal(direction, true, out_of_bounds);
  646. if (selection_length > 0)
  647. {
  648. DeleteSelection();
  649. DispatchChangeEvent();
  650. return true;
  651. }
  652. return false;
  653. }
  654. void WidgetTextInput::CopySelection()
  655. {
  656. const String& value = GetValue();
  657. const String snippet = value.substr(Math::Min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length);
  658. GetSystemInterface()->SetClipboardText(snippet);
  659. }
  660. bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select, bool& out_of_bounds)
  661. {
  662. out_of_bounds = false;
  663. const String& value = GetValue();
  664. int cursor_line_index = 0, cursor_character_index = 0;
  665. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  666. // By default the cursor wraps down when located on softbreaks. This may be overridden by setting the cursor using relative indices.
  667. cursor_wrap_down = true;
  668. // Whether to seek forward or back to align to utf8 boundaries later.
  669. bool seek_forward = false;
  670. switch (movement)
  671. {
  672. case CursorMovement::Begin: absolute_cursor_index = 0; break;
  673. case CursorMovement::BeginLine: SetCursorFromRelativeIndices(cursor_line_index, 0); break;
  674. case CursorMovement::PreviousWord:
  675. {
  676. // First skip whitespace, then skip all characters of the same class as the first non-whitespace character.
  677. CharacterClass skip_character_class = CharacterClass::Whitespace;
  678. const char* p_rend = value.data();
  679. const char* p_rbegin = p_rend + absolute_cursor_index;
  680. const char* p = p_rbegin - 1;
  681. for (; p > p_rend; --p)
  682. {
  683. const CharacterClass character_class = GetCharacterClass(*p);
  684. if (character_class != skip_character_class)
  685. {
  686. if (skip_character_class == CharacterClass::Whitespace)
  687. skip_character_class = character_class;
  688. else
  689. break;
  690. }
  691. }
  692. if (p != p_rend)
  693. ++p;
  694. absolute_cursor_index += int(p - p_rbegin);
  695. }
  696. break;
  697. case CursorMovement::Left:
  698. if (!select && selection_length > 0)
  699. absolute_cursor_index = selection_begin_index;
  700. else
  701. absolute_cursor_index -= 1;
  702. break;
  703. case CursorMovement::Right:
  704. seek_forward = true;
  705. if (!select && selection_length > 0)
  706. absolute_cursor_index = selection_begin_index + selection_length;
  707. else
  708. absolute_cursor_index += 1;
  709. break;
  710. case CursorMovement::NextWord:
  711. {
  712. // First skip all characters of the same class as the first character, then skip any whitespace.
  713. CharacterClass skip_character_class = CharacterClass::Undefined;
  714. const char* p_begin = value.data() + absolute_cursor_index;
  715. const char* p_end = value.data() + value.size();
  716. const char* p = p_begin;
  717. for (; p < p_end; ++p)
  718. {
  719. const CharacterClass character_class = GetCharacterClass(*p);
  720. if (skip_character_class == CharacterClass::Undefined)
  721. skip_character_class = character_class;
  722. if (character_class != skip_character_class)
  723. {
  724. if (character_class == CharacterClass::Whitespace)
  725. skip_character_class = CharacterClass::Whitespace;
  726. else
  727. break;
  728. }
  729. }
  730. absolute_cursor_index += int(p - p_begin);
  731. }
  732. break;
  733. case CursorMovement::EndLine: SetCursorFromRelativeIndices(cursor_line_index, lines[cursor_line_index].editable_length); break;
  734. case CursorMovement::End: absolute_cursor_index = (int)GetValue().size(); break;
  735. }
  736. const int unclamped_absolute_cursor_index = absolute_cursor_index;
  737. absolute_cursor_index = Math::Clamp(absolute_cursor_index, 0, (int)GetValue().size());
  738. out_of_bounds = (unclamped_absolute_cursor_index != absolute_cursor_index);
  739. MoveCursorToCharacterBoundaries(seek_forward);
  740. UpdateCursorPosition(true);
  741. bool selection_changed = UpdateSelection(select);
  742. ShowCursor(true);
  743. return selection_changed;
  744. }
  745. bool WidgetTextInput::MoveCursorVertical(int distance, bool select, bool& out_of_bounds)
  746. {
  747. int cursor_line_index = 0, cursor_character_index = 0;
  748. out_of_bounds = false;
  749. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  750. cursor_line_index += distance;
  751. if (cursor_line_index < 0)
  752. {
  753. out_of_bounds = true;
  754. cursor_line_index = 0;
  755. cursor_character_index = 0;
  756. }
  757. else if (cursor_line_index >= (int)lines.size())
  758. {
  759. out_of_bounds = true;
  760. cursor_line_index = (int)lines.size() - 1;
  761. cursor_character_index = (int)lines[cursor_line_index].editable_length;
  762. }
  763. else
  764. cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
  765. SetCursorFromRelativeIndices(cursor_line_index, cursor_character_index);
  766. MoveCursorToCharacterBoundaries(false);
  767. UpdateCursorPosition(false);
  768. bool selection_changed = UpdateSelection(select);
  769. ShowCursor(true);
  770. return selection_changed;
  771. }
  772. void WidgetTextInput::MoveCursorToCharacterBoundaries(bool forward)
  773. {
  774. const String& value = GetValue();
  775. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)value.size());
  776. const char* p_begin = value.data();
  777. const char* p_end = p_begin + value.size();
  778. const char* p_cursor = p_begin + absolute_cursor_index;
  779. const char* p = p_cursor;
  780. if (forward)
  781. p = StringUtilities::SeekForwardUTF8(p_cursor, p_end);
  782. else
  783. p = StringUtilities::SeekBackwardUTF8(p_cursor, p_begin);
  784. if (p != p_cursor)
  785. absolute_cursor_index += int(p - p_cursor);
  786. }
  787. void WidgetTextInput::ExpandSelection()
  788. {
  789. const String& value = GetValue();
  790. const char* const p_begin = value.data();
  791. const char* const p_end = p_begin + value.size();
  792. const char* const p_index = p_begin + absolute_cursor_index;
  793. // The first character encountered defines the character class to expand.
  794. CharacterClass expanding_character_class = CharacterClass::Undefined;
  795. auto character_is_wrong_type = [&expanding_character_class](const char* p) -> bool {
  796. const CharacterClass character_class = GetCharacterClass(*p);
  797. if (expanding_character_class == CharacterClass::Undefined)
  798. expanding_character_class = character_class;
  799. else if (character_class != expanding_character_class)
  800. return true;
  801. return false;
  802. };
  803. auto search_left = [&]() -> const char* {
  804. const char* p = p_index;
  805. for (; p > p_begin; p--)
  806. if (character_is_wrong_type(p - 1))
  807. break;
  808. return p;
  809. };
  810. auto search_right = [&]() -> const char* {
  811. const char* p = p_index;
  812. for (; p < p_end; p++)
  813. if (character_is_wrong_type(p))
  814. break;
  815. return p;
  816. };
  817. const char* p_left = p_index;
  818. const char* p_right = p_index;
  819. if (ideal_cursor_position_to_the_right_of_cursor)
  820. {
  821. p_right = search_right();
  822. p_left = search_left();
  823. }
  824. else
  825. {
  826. p_left = search_left();
  827. p_right = search_right();
  828. }
  829. cursor_wrap_down = true;
  830. absolute_cursor_index -= int(p_index - p_left);
  831. MoveCursorToCharacterBoundaries(false);
  832. bool selection_changed = UpdateSelection(false);
  833. absolute_cursor_index += int(p_right - p_left);
  834. MoveCursorToCharacterBoundaries(true);
  835. selection_changed |= UpdateSelection(true);
  836. if (selection_changed)
  837. FormatText();
  838. UpdateCursorPosition(true);
  839. }
  840. const String& WidgetTextInput::GetValue() const
  841. {
  842. return text_element->GetText();
  843. }
  844. String WidgetTextInput::GetAttributeValue() const
  845. {
  846. return parent->GetAttribute("value", String());
  847. }
  848. void WidgetTextInput::GetRelativeCursorIndices(int& out_cursor_line_index, int& out_cursor_character_index) const
  849. {
  850. int line_begin = 0;
  851. for (size_t i = 0; i < lines.size(); i++)
  852. {
  853. const int cursor_relative_line_end = absolute_cursor_index - (line_begin + lines[i].editable_length);
  854. // 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
  855. // 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
  856. // such characters.
  857. if (cursor_relative_line_end <= 0)
  858. {
  859. const bool soft_wrapped_line = (lines[i].editable_length == lines[i].size);
  860. // 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.
  861. if (cursor_relative_line_end == 0 && soft_wrapped_line && cursor_wrap_down && (int)i + 1 < (int)lines.size())
  862. {
  863. out_cursor_line_index = (int)i + 1;
  864. out_cursor_character_index = 0;
  865. }
  866. else
  867. {
  868. out_cursor_line_index = (int)i;
  869. out_cursor_character_index = Math::Max(absolute_cursor_index - line_begin, 0);
  870. }
  871. return;
  872. }
  873. line_begin += lines[i].size;
  874. }
  875. // We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
  876. // just set the relative cursors to the very end of the text field.
  877. out_cursor_line_index = (int)lines.size() - 1;
  878. out_cursor_character_index = lines[out_cursor_line_index].editable_length;
  879. }
  880. void WidgetTextInput::SetCursorFromRelativeIndices(int cursor_line_index, int cursor_character_index)
  881. {
  882. RMLUI_ASSERT(cursor_line_index < (int)lines.size())
  883. absolute_cursor_index = cursor_character_index;
  884. for (int i = 0; i < cursor_line_index; i++)
  885. absolute_cursor_index += lines[i].size;
  886. // Only wrap down if we're not located at the end of the line.
  887. cursor_wrap_down = (cursor_character_index < lines[cursor_line_index].editable_length);
  888. }
  889. int WidgetTextInput::CalculateLineIndex(float position) const
  890. {
  891. int line_index = int(position / GetLineHeight());
  892. return Math::Clamp(line_index, 0, (int)(lines.size() - 1));
  893. }
  894. float WidgetTextInput::GetAlignmentSpecificTextOffset(const Line& line) const
  895. {
  896. // Callback to avoid expensive calculation in the cases where it is not needed.
  897. auto RemainingWidth = [this](StringView editable_line_string) {
  898. const float total_width = (float)ElementUtilities::GetStringWidth(text_element, editable_line_string);
  899. return GetAvailableWidth() - total_width;
  900. };
  901. const String& value = GetValue();
  902. StringView editable_line_string(value, line.value_offset, line.editable_length);
  903. switch (parent->GetComputedValues().text_align())
  904. {
  905. case Style::TextAlign::Left: return 0;
  906. case Style::TextAlign::Right:
  907. {
  908. // For right alignment with soft-wrapped newlines, remove up to a single space to align the last word to the right edge.
  909. const bool is_last_line = (line.value_offset + line.size == (int)value.size());
  910. const bool is_soft_wrapped = (!is_last_line && line.editable_length == line.size);
  911. if (is_soft_wrapped && !editable_line_string.empty() && *(editable_line_string.end() - 1) == ' ')
  912. {
  913. editable_line_string = StringView(editable_line_string.begin(), editable_line_string.end() - 1);
  914. }
  915. return Math::Max(0.0f, RemainingWidth(editable_line_string));
  916. }
  917. case Style::TextAlign::Center: return Math::Max(0.0f, 0.5f * RemainingWidth(editable_line_string));
  918. case Style::TextAlign::Justify: return 0;
  919. }
  920. return 0;
  921. }
  922. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
  923. {
  924. int prev_offset = 0;
  925. float prev_line_width = 0;
  926. ideal_cursor_position_to_the_right_of_cursor = true;
  927. const Line& line = lines[line_index];
  928. const char* p_begin = GetValue().data() + line.value_offset;
  929. const char* p_end = p_begin + line.editable_length;
  930. position -= GetAlignmentSpecificTextOffset(line);
  931. for (auto it = StringIteratorU8(p_begin, p_begin, p_end); it;)
  932. {
  933. ++it;
  934. const int offset = (int)it.offset();
  935. const float line_width = (float)ElementUtilities::GetStringWidth(text_element, StringView(p_begin, p_begin + offset));
  936. if (line_width > position)
  937. {
  938. if (position - prev_line_width < line_width - position)
  939. {
  940. return prev_offset;
  941. }
  942. else
  943. {
  944. ideal_cursor_position_to_the_right_of_cursor = false;
  945. return offset;
  946. }
  947. }
  948. prev_line_width = line_width;
  949. prev_offset = offset;
  950. }
  951. return prev_offset;
  952. }
  953. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
  954. {
  955. if (show)
  956. {
  957. cursor_visible = true;
  958. cursor_timer = CURSOR_BLINK_TIME;
  959. last_update_time = GetSystemInterface()->GetElapsedTime();
  960. // Shift the cursor into view.
  961. if (move_to_cursor)
  962. {
  963. float minimum_scroll_top = Math::Min((cursor_position.y + cursor_size.y) - GetAvailableHeight(), cursor_position.y);
  964. if (parent->GetScrollTop() < minimum_scroll_top)
  965. parent->SetScrollTop(minimum_scroll_top);
  966. else if (parent->GetScrollTop() > cursor_position.y)
  967. parent->SetScrollTop(cursor_position.y);
  968. const bool word_wrap = parent->GetComputedValues().white_space() == Style::WhiteSpace::Prewrap;
  969. float minimum_scroll_left = Math::Min((cursor_position.x + cursor_size.x) - GetAvailableWidth(), cursor_position.x);
  970. if (word_wrap)
  971. parent->SetScrollLeft(0.f);
  972. else if (parent->GetScrollLeft() < minimum_scroll_left)
  973. parent->SetScrollLeft(minimum_scroll_left);
  974. else if (parent->GetScrollLeft() > cursor_position.x)
  975. parent->SetScrollLeft(cursor_position.x);
  976. }
  977. SetKeyboardActive(true);
  978. keyboard_showed = true;
  979. }
  980. else
  981. {
  982. cursor_visible = false;
  983. cursor_timer = -1;
  984. last_update_time = 0;
  985. if (keyboard_showed)
  986. {
  987. SetKeyboardActive(false);
  988. keyboard_showed = false;
  989. }
  990. }
  991. }
  992. void WidgetTextInput::FormatElement()
  993. {
  994. using namespace Style;
  995. ElementScroll* scroll = parent->GetElementScroll();
  996. float width = parent->GetBox().GetSize(BoxArea::Padding).x;
  997. const Overflow x_overflow_property = parent->GetComputedValues().overflow_x();
  998. const Overflow y_overflow_property = parent->GetComputedValues().overflow_y();
  999. const bool word_wrap = (parent->GetComputedValues().white_space() == WhiteSpace::Prewrap);
  1000. if (x_overflow_property == Overflow::Scroll)
  1001. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  1002. else
  1003. scroll->DisableScrollbar(ElementScroll::HORIZONTAL);
  1004. if (y_overflow_property == Overflow::Scroll)
  1005. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  1006. else
  1007. scroll->DisableScrollbar(ElementScroll::VERTICAL);
  1008. // If the formatting produces scrollbars we need to format again later, this constraint enables early exit for the first formatting round.
  1009. const float formatting_height_constraint = (y_overflow_property == Overflow::Auto ? GetAvailableHeight() : FLT_MAX);
  1010. // Format the text and determine its total area.
  1011. Vector2f content_area = FormatText(formatting_height_constraint);
  1012. // If we're set to automatically generate horizontal scrollbars, check for that now.
  1013. if (!word_wrap && x_overflow_property == Overflow::Auto && content_area.x > GetAvailableWidth() + OVERFLOW_TOLERANCE)
  1014. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  1015. // Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
  1016. if (y_overflow_property == Overflow::Auto && content_area.y > GetAvailableHeight() + OVERFLOW_TOLERANCE)
  1017. {
  1018. scroll->EnableScrollbar(ElementScroll::VERTICAL, width);
  1019. content_area = FormatText();
  1020. if (!word_wrap && x_overflow_property == Overflow::Auto && content_area.x > GetAvailableWidth() + OVERFLOW_TOLERANCE)
  1021. scroll->EnableScrollbar(ElementScroll::HORIZONTAL, width);
  1022. }
  1023. // For text elements, make the content and padding on all sides reachable by scrolling.
  1024. const Vector2f padding_size = parent->GetBox().GetFrameSize(BoxArea::Padding);
  1025. parent->SetScrollableOverflowRectangle(content_area + padding_size, true);
  1026. scroll->FormatScrollbars();
  1027. }
  1028. Vector2f WidgetTextInput::FormatText(float height_constraint)
  1029. {
  1030. Vector2f content_area(0, 0);
  1031. const FontFaceHandle font_handle = parent->GetFontFaceHandle();
  1032. if (!font_handle)
  1033. return content_area;
  1034. const FontMetrics& font_metrics = GetFontEngineInterface()->GetFontMetrics(font_handle);
  1035. // Clear the old lines, and all the lines in the text elements.
  1036. lines.clear();
  1037. text_element->ClearLines();
  1038. selected_text_element->ClearLines();
  1039. // Determine the line-height of the text element.
  1040. const float line_height = GetLineHeight();
  1041. const float half_leading = 0.5f * (line_height - (font_metrics.ascent + font_metrics.descent));
  1042. const float top_to_baseline = font_metrics.ascent + half_leading;
  1043. // When the selection contains endlines, we expand the selection area by this width.
  1044. const int endline_font_width = int(0.4f * parent->GetComputedValues().font_size());
  1045. const float available_width = GetAvailableWidth();
  1046. int line_begin = 0;
  1047. Vector2f line_position = {0, top_to_baseline};
  1048. bool last_line = false;
  1049. float max_selection_right_edge = 0;
  1050. // Clear the selection background and IME composition geometry, and get the vertices and indices so the new geometry can be generated.
  1051. Mesh selection_composition_mesh = selection_composition_geometry.Release(Geometry::ReleaseMode::ClearMesh);
  1052. // Keep generating lines until all the text content is placed.
  1053. do
  1054. {
  1055. const float maximum_line_width = available_width - cursor_size.x;
  1056. if (maximum_line_width <= 0.f)
  1057. {
  1058. lines.push_back(Line{});
  1059. break;
  1060. }
  1061. Line line = {};
  1062. line.value_offset = line_begin;
  1063. float line_width;
  1064. String line_content;
  1065. // Generate the next line.
  1066. last_line = text_element->GenerateLine(line_content, line.size, line_width, line_begin, maximum_line_width, 0, false, false, false);
  1067. // Check if the editable length needs to be truncated to dodge a trailing endline.
  1068. line.editable_length = (int)line_content.size();
  1069. if (!line_content.empty() && line_content.back() == '\n')
  1070. line.editable_length -= 1;
  1071. // Include all spaces at the end of this line, if they were not included due to soft-wrapping in `GenerateLine`.
  1072. // This helps prevent sudden shifts when whitespace wraps down to the next line.
  1073. {
  1074. const String& text = GetValue();
  1075. size_t i_space_begin = size_t(line_begin + line.editable_length);
  1076. size_t i_space_end = Math::Min(text.find_first_not_of(' ', i_space_begin), text.size());
  1077. size_t count = i_space_end - i_space_begin;
  1078. if (count > 0)
  1079. {
  1080. line_content.append(count, ' ');
  1081. line_width += ElementUtilities::GetStringWidth(text_element, " ") * (int)count;
  1082. line.editable_length += (int)count;
  1083. line.size += (int)count;
  1084. // Consume the hard wrap if we have one on this line, so that it doesn't make its own, empty line.
  1085. if (text[i_space_end] == '\n')
  1086. line.size += 1;
  1087. // If the spaces extend all the way to the end, we have consumed all the lines.
  1088. if (i_space_end == text.size())
  1089. last_line = true;
  1090. }
  1091. }
  1092. // Now that we have the string of characters appearing on the new line, we split it into
  1093. // three parts; the unselected text appearing before any selected text on the line, the
  1094. // selected text on the line, and any unselected text after the selection.
  1095. StringView pre_selection, selection, post_selection;
  1096. GetLineSelection(pre_selection, selection, post_selection, line_content, line_begin);
  1097. // The pre-selected text is placed, if there is any (if the selection starts on or before
  1098. // the beginning of this line, then this will be empty).
  1099. if (!pre_selection.empty())
  1100. {
  1101. const int width = ElementUtilities::GetStringWidth(text_element, pre_selection);
  1102. text_element->AddLine(line_position + Vector2f{GetAlignmentSpecificTextOffset(line), 0}, String(pre_selection));
  1103. line_position.x += width;
  1104. }
  1105. // Return the extra kerning that would result in joining two strings.
  1106. auto GetKerningBetween = [this](StringView left, StringView right) -> float {
  1107. if (left.empty() || right.empty())
  1108. return 0.0f;
  1109. // We could join the whole string, and compare the result of the joined width to the individual widths of each string. Instead, we take
  1110. // the two neighboring characters from each string and compare the string width with and without kerning, which should be much faster.
  1111. const Character left_back = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(left.end() - 1, left.begin()), left.end());
  1112. const StringView right_front_u8 = StringView(right.begin(), StringUtilities::SeekForwardUTF8(right.begin() + 1, right.end()));
  1113. const int width_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, left_back);
  1114. const int width_no_kerning = ElementUtilities::GetStringWidth(text_element, right_front_u8, Character::Null);
  1115. return float(width_kerning - width_no_kerning);
  1116. };
  1117. // If there is any selected text on this line, place it in the selected text element and
  1118. // generate the geometry for its background.
  1119. if (!selection.empty())
  1120. {
  1121. line_position.x += GetKerningBetween(pre_selection, selection);
  1122. const int selection_width = ElementUtilities::GetStringWidth(selected_text_element, selection);
  1123. const bool selection_contains_endline = (selection_begin_index + selection_length > line_begin + line.editable_length);
  1124. const Vector2f selection_size = {float(selection_width + (selection_contains_endline ? endline_font_width : 0)), line_height};
  1125. const Vector2f aligned_position = line_position + Vector2f{GetAlignmentSpecificTextOffset(line), 0};
  1126. MeshUtilities::GenerateQuad(selection_composition_mesh, aligned_position - Vector2f(0, top_to_baseline), selection_size,
  1127. selection_colour);
  1128. selected_text_element->AddLine(aligned_position, String(selection));
  1129. max_selection_right_edge = Math::Max(max_selection_right_edge, aligned_position.x + selection_size.x);
  1130. line_position.x += selection_width;
  1131. }
  1132. // If there is any unselected text after the selection on this line, place it in the
  1133. // standard text element after the selected text.
  1134. if (!post_selection.empty())
  1135. {
  1136. line_position.x += GetKerningBetween(selection, post_selection);
  1137. text_element->AddLine(line_position + Vector2f{GetAlignmentSpecificTextOffset(line), 0}, String(post_selection));
  1138. }
  1139. // We fetch the IME composition on the new line to highlight it.
  1140. StringView ime_pre_composition, ime_composition;
  1141. GetLineIMEComposition(ime_pre_composition, ime_composition, line_content, line_begin);
  1142. // If there is any IME composition string on the line, create a segment for its underline.
  1143. if (!ime_composition.empty())
  1144. {
  1145. const bool composition_contains_endline = (ime_composition_end_index > line_begin + line.editable_length);
  1146. const int composition_width = ElementUtilities::GetStringWidth(text_element, ime_composition);
  1147. const Vector2f composition_position = {
  1148. float(ElementUtilities::GetStringWidth(text_element, ime_pre_composition)) + GetAlignmentSpecificTextOffset(line),
  1149. line_position.y - top_to_baseline + line_height - COMPOSITION_UNDERLINE_WIDTH,
  1150. };
  1151. Vector2f line_size = {float(composition_width + (composition_contains_endline ? endline_font_width : 0)), COMPOSITION_UNDERLINE_WIDTH};
  1152. MeshUtilities::GenerateLine(selection_composition_mesh, composition_position, line_size,
  1153. parent->GetComputedValues().color().ToPremultiplied());
  1154. }
  1155. // Update variables for the next line.
  1156. line_begin += line.size;
  1157. line_position.x = 0;
  1158. line_position.y += line_height;
  1159. // Grow the content area width-wise if this line is the longest so far, and push the height out.
  1160. content_area.x = Math::Max(content_area.x, line_width + cursor_size.x);
  1161. content_area.y = line_position.y - top_to_baseline;
  1162. // Finally, push the new line into our array of lines.
  1163. lines.push_back(std::move(line));
  1164. } while (!last_line && content_area.y <= height_constraint + OVERFLOW_TOLERANCE);
  1165. // Clamp the cursor to a valid range.
  1166. absolute_cursor_index = Math::Min(absolute_cursor_index, (int)GetValue().size());
  1167. selection_composition_geometry = parent->GetRenderManager()->MakeGeometry(std::move(selection_composition_mesh));
  1168. // Overflow is automatically caught by any text overflowing the content area. However, sometimes it is possible that
  1169. // the selection box extends beyond the text and outside the content area. This can even overflow the element
  1170. // itself. In particular, when the selection includes newlines near the right edge. We don't want the selection box
  1171. // to take part in the scrollable region of the element, which would be one way to ensure that it is always clipped.
  1172. // Instead, we here detect such possible overflow manually and force the element to clip. This will clip any parts
  1173. // of the selection box that is overflowing. Maybe in the future we'll have a better way to specify ink overflow and
  1174. // have that automatically clipped.
  1175. const bool new_ink_overflow = (max_selection_right_edge > available_width + parent->GetBox().GetEdge(BoxArea::Padding, BoxEdge::Right));
  1176. if (new_ink_overflow != ink_overflow)
  1177. {
  1178. ink_overflow = new_ink_overflow;
  1179. parent->SetProperty(PropertyId::Clip, Property(ink_overflow ? Style::Clip::Type::Always : Style::Clip::Type::Auto));
  1180. }
  1181. return content_area;
  1182. }
  1183. void WidgetTextInput::GenerateCursor()
  1184. {
  1185. cursor_size.x = Math::Round(ElementUtilities::GetDensityIndependentPixelRatio(text_element));
  1186. cursor_size.y = GetLineHeight();
  1187. Colourb color = parent->GetComputedValues().color();
  1188. if (const Property* property = parent->GetProperty(PropertyId::CaretColor))
  1189. {
  1190. if (property->unit == Unit::COLOUR)
  1191. color = property->Get<Colourb>();
  1192. }
  1193. Mesh mesh = cursor_geometry.Release(Geometry::ReleaseMode::ClearMesh);
  1194. MeshUtilities::GenerateQuad(mesh, Vector2f(0, 0), cursor_size, color.ToPremultiplied());
  1195. cursor_geometry = parent->GetRenderManager()->MakeGeometry(std::move(mesh));
  1196. }
  1197. void WidgetTextInput::ForceFormattingOnNextLayout()
  1198. {
  1199. force_formatting_on_next_layout = true;
  1200. }
  1201. void WidgetTextInput::UpdateCursorPosition(bool update_ideal_cursor_position)
  1202. {
  1203. if (text_element->GetFontFaceHandle() == 0 || lines.empty())
  1204. return;
  1205. int cursor_line_index = 0, cursor_character_index = 0;
  1206. GetRelativeCursorIndices(cursor_line_index, cursor_character_index);
  1207. const auto& line = lines[cursor_line_index];
  1208. const int string_width_pre_cursor =
  1209. ElementUtilities::GetStringWidth(text_element, StringView(GetValue(), line.value_offset, cursor_character_index));
  1210. const float alignment_offset = GetAlignmentSpecificTextOffset(line);
  1211. cursor_position = {
  1212. (float)string_width_pre_cursor + alignment_offset,
  1213. (float)cursor_line_index * GetLineHeight(),
  1214. };
  1215. const bool word_wrap = parent->GetComputedValues().white_space() == Style::WhiteSpace::Prewrap;
  1216. if (word_wrap)
  1217. cursor_position.x = Math::Min(cursor_position.x, GetAvailableWidth() - cursor_size.x);
  1218. if (update_ideal_cursor_position)
  1219. ideal_cursor_position = cursor_position.x;
  1220. }
  1221. bool WidgetTextInput::UpdateSelection(bool selecting)
  1222. {
  1223. bool selection_changed = false;
  1224. if (!selecting)
  1225. {
  1226. selection_anchor_index = selection_begin_index = absolute_cursor_index;
  1227. selection_changed = ClearSelection();
  1228. }
  1229. else
  1230. {
  1231. int new_begin_index;
  1232. int new_end_index;
  1233. if (absolute_cursor_index > selection_anchor_index)
  1234. {
  1235. new_begin_index = selection_anchor_index;
  1236. new_end_index = absolute_cursor_index;
  1237. }
  1238. else
  1239. {
  1240. new_begin_index = absolute_cursor_index;
  1241. new_end_index = selection_anchor_index;
  1242. }
  1243. if (new_begin_index != selection_begin_index || new_end_index - new_begin_index != selection_length)
  1244. {
  1245. selection_begin_index = new_begin_index;
  1246. selection_length = new_end_index - new_begin_index;
  1247. selection_changed = true;
  1248. }
  1249. }
  1250. return selection_changed;
  1251. }
  1252. bool WidgetTextInput::ClearSelection()
  1253. {
  1254. if (selection_length > 0)
  1255. {
  1256. selection_length = 0;
  1257. return true;
  1258. }
  1259. return false;
  1260. }
  1261. void WidgetTextInput::DeleteSelection()
  1262. {
  1263. if (selection_length > 0)
  1264. {
  1265. String new_value = GetAttributeValue();
  1266. const int selection_begin_index_attribute = DisplayIndexToAttributeIndex(selection_begin_index, new_value);
  1267. const int selection_end_index_attribute = DisplayIndexToAttributeIndex(selection_begin_index + selection_length, new_value);
  1268. RMLUI_ASSERT(selection_end_index_attribute >= selection_begin_index_attribute);
  1269. const size_t selection_begin = std::min((size_t)selection_begin_index_attribute, (size_t)new_value.size());
  1270. const size_t attribute_selection_length = size_t(selection_end_index_attribute - selection_begin_index_attribute);
  1271. new_value.erase(selection_begin, (size_t)attribute_selection_length);
  1272. // Move the cursor to the beginning of the old selection.
  1273. absolute_cursor_index = selection_begin_index;
  1274. GetElement()->SetAttribute("value", new_value);
  1275. // Erase our record of the selection.
  1276. if (UpdateSelection(false))
  1277. FormatText();
  1278. }
  1279. }
  1280. void WidgetTextInput::GetLineSelection(StringView& pre_selection, StringView& selection, StringView& post_selection, const String& line,
  1281. int line_begin) const
  1282. {
  1283. const int selection_end = selection_begin_index + selection_length;
  1284. if (selection_length <= 0 || selection_end < line_begin || selection_begin_index > line_begin + (int)line.size())
  1285. {
  1286. pre_selection = line;
  1287. return;
  1288. }
  1289. const int line_length = (int)line.size();
  1290. using namespace Math;
  1291. // Split the line up into its three parts, depending on the size and placement of the selection.
  1292. pre_selection = StringView(line, 0, Max(0, selection_begin_index - line_begin));
  1293. selection = StringView(line, Clamp(selection_begin_index - line_begin, 0, line_length),
  1294. Max(0, selection_length + Min(0, selection_begin_index - line_begin)));
  1295. post_selection = StringView(line, Clamp(selection_end - line_begin, 0, line_length));
  1296. }
  1297. void WidgetTextInput::GetLineIMEComposition(StringView& pre_composition, StringView& ime_composition, const String& line, int line_begin) const
  1298. {
  1299. const int composition_length = ime_composition_end_index - ime_composition_begin_index;
  1300. // Check if the line has any text in the IME composition range at all.
  1301. if (composition_length <= 0 || ime_composition_end_index < line_begin || ime_composition_begin_index > line_begin + (int)line.size())
  1302. {
  1303. pre_composition = line;
  1304. return;
  1305. }
  1306. const int line_length = (int)line.size();
  1307. pre_composition = StringView(line, 0, Math::Max(0, ime_composition_begin_index - line_begin));
  1308. ime_composition = StringView(line, Math::Clamp(ime_composition_begin_index - line_begin, 0, line_length),
  1309. Math::Max(0, composition_length + Math::Min(0, ime_composition_begin_index - line_begin)));
  1310. }
  1311. void WidgetTextInput::SetKeyboardActive(bool active)
  1312. {
  1313. if (SystemInterface* system = GetSystemInterface())
  1314. {
  1315. if (active)
  1316. {
  1317. // Activate the keyboard and submit the cursor position and line height to enable clients to adjust the input method editor (IME).
  1318. const Vector2f element_offset = parent->GetAbsoluteOffset() - Vector2f{parent->GetScrollLeft(), parent->GetScrollTop()};
  1319. const Vector2f absolute_cursor_position = element_offset + cursor_position;
  1320. system->ActivateKeyboard(absolute_cursor_position, cursor_size.y);
  1321. }
  1322. else
  1323. {
  1324. system->DeactivateKeyboard();
  1325. }
  1326. }
  1327. }
  1328. float WidgetTextInput::GetLineHeight() const
  1329. {
  1330. return Math::Round(parent->GetLineHeight());
  1331. }
  1332. float WidgetTextInput::GetAvailableWidth() const
  1333. {
  1334. return parent->GetClientWidth() - parent->GetBox().GetFrameSize(BoxArea::Padding).x;
  1335. }
  1336. float WidgetTextInput::GetAvailableHeight() const
  1337. {
  1338. return parent->GetClientHeight() - parent->GetBox().GetFrameSize(BoxArea::Padding).y;
  1339. }
  1340. } // namespace Rml