WidgetTextInput.cpp 51 KB

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