WidgetTextInput.cpp 44 KB

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