WidgetTextInput.cpp 53 KB

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