WidgetTextInput.cpp 53 KB

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