WidgetTextInput.cpp 51 KB

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