WidgetTextInput.cpp 53 KB

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