WidgetTextInput.cpp 52 KB

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