TextBox.cs 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  1. using Avalonia.Input.Platform;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Avalonia.Reactive;
  6. using Avalonia.Controls.Presenters;
  7. using Avalonia.Controls.Primitives;
  8. using Avalonia.Controls.Utils;
  9. using Avalonia.Input;
  10. using Avalonia.Interactivity;
  11. using Avalonia.Media;
  12. using Avalonia.Metadata;
  13. using Avalonia.Data;
  14. using Avalonia.Layout;
  15. using Avalonia.Utilities;
  16. using Avalonia.Controls.Metadata;
  17. using Avalonia.Media.TextFormatting;
  18. using Avalonia.Automation.Peers;
  19. using Avalonia.Threading;
  20. namespace Avalonia.Controls
  21. {
  22. /// <summary>
  23. /// Represents a control that can be used to display or edit unformatted text.
  24. /// </summary>
  25. [TemplatePart("PART_TextPresenter", typeof(TextPresenter))]
  26. [TemplatePart("PART_ScrollViewer", typeof(ScrollViewer))]
  27. [PseudoClasses(":empty")]
  28. public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
  29. {
  30. /// <summary>
  31. /// Gets a platform-specific <see cref="KeyGesture"/> for the Cut action
  32. /// </summary>
  33. public static KeyGesture? CutGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Cut.FirstOrDefault();
  34. /// <summary>
  35. /// Gets a platform-specific <see cref="KeyGesture"/> for the Copy action
  36. /// </summary>
  37. public static KeyGesture? CopyGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Copy.FirstOrDefault();
  38. /// <summary>
  39. /// Gets a platform-specific <see cref="KeyGesture"/> for the Paste action
  40. /// </summary>
  41. public static KeyGesture? PasteGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Paste.FirstOrDefault();
  42. /// <summary>
  43. /// Defines the <see cref="AcceptsReturn"/> property
  44. /// </summary>
  45. public static readonly StyledProperty<bool> AcceptsReturnProperty =
  46. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
  47. /// <summary>
  48. /// Defines the <see cref="AcceptsTab"/> property
  49. /// </summary>
  50. public static readonly StyledProperty<bool> AcceptsTabProperty =
  51. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
  52. /// <summary>
  53. /// Defines the <see cref="CaretIndex"/> property
  54. /// </summary>
  55. public static readonly StyledProperty<int> CaretIndexProperty =
  56. AvaloniaProperty.Register<TextBox, int>(nameof(CaretIndex),
  57. coerce: CoerceCaretIndex);
  58. /// <summary>
  59. /// Defines the <see cref="IsReadOnly"/> property
  60. /// </summary>
  61. public static readonly StyledProperty<bool> IsReadOnlyProperty =
  62. AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
  63. /// <summary>
  64. /// Defines the <see cref="PasswordChar"/> property
  65. /// </summary>
  66. public static readonly StyledProperty<char> PasswordCharProperty =
  67. AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
  68. /// <summary>
  69. /// Defines the <see cref="SelectionBrush"/> property
  70. /// </summary>
  71. public static readonly StyledProperty<IBrush?> SelectionBrushProperty =
  72. AvaloniaProperty.Register<TextBox, IBrush?>(nameof(SelectionBrush));
  73. /// <summary>
  74. /// Defines the <see cref="SelectionForegroundBrush"/> property
  75. /// </summary>
  76. public static readonly StyledProperty<IBrush?> SelectionForegroundBrushProperty =
  77. AvaloniaProperty.Register<TextBox, IBrush?>(nameof(SelectionForegroundBrush));
  78. /// <summary>
  79. /// Defines the <see cref="CaretBrush"/> property
  80. /// </summary>
  81. public static readonly StyledProperty<IBrush?> CaretBrushProperty =
  82. AvaloniaProperty.Register<TextBox, IBrush?>(nameof(CaretBrush));
  83. /// <summary>
  84. /// Defines the <see cref="CaretBlinkInterval"/> property
  85. /// </summary>
  86. public static readonly StyledProperty<TimeSpan> CaretBlinkIntervalProperty =
  87. AvaloniaProperty.Register<TextBox, TimeSpan>(nameof(CaretBlinkInterval), defaultValue: TimeSpan.FromMilliseconds(500));
  88. /// <summary>
  89. /// Defines the <see cref="SelectionStart"/> property
  90. /// </summary>
  91. public static readonly StyledProperty<int> SelectionStartProperty =
  92. AvaloniaProperty.Register<TextBox, int>(nameof(SelectionStart),
  93. coerce: CoerceCaretIndex);
  94. /// <summary>
  95. /// Defines the <see cref="SelectionEnd"/> property
  96. /// </summary>
  97. public static readonly StyledProperty<int> SelectionEndProperty =
  98. AvaloniaProperty.Register<TextBox, int>(nameof(SelectionEnd),
  99. coerce: CoerceCaretIndex);
  100. /// <summary>
  101. /// Defines the <see cref="MaxLength"/> property
  102. /// </summary>
  103. public static readonly StyledProperty<int> MaxLengthProperty =
  104. AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength));
  105. /// <summary>
  106. /// Defines the <see cref="MaxLines"/> property
  107. /// </summary>
  108. public static readonly StyledProperty<int> MaxLinesProperty =
  109. AvaloniaProperty.Register<TextBox, int>(nameof(MaxLines));
  110. /// <summary>
  111. /// Defines the <see cref="MinLines"/> property
  112. /// </summary>
  113. public static readonly StyledProperty<int> MinLinesProperty =
  114. AvaloniaProperty.Register<TextBox, int>(nameof(MinLines));
  115. /// <summary>
  116. /// Defines the <see cref="Text"/> property
  117. /// </summary>
  118. public static readonly StyledProperty<string?> TextProperty =
  119. TextBlock.TextProperty.AddOwner<TextBox>(new(
  120. coerce: CoerceText,
  121. defaultBindingMode: BindingMode.TwoWay,
  122. enableDataValidation: true));
  123. /// <summary>
  124. /// Defines the <see cref="TextAlignment"/> property
  125. /// </summary>
  126. public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
  127. TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
  128. /// <summary>
  129. /// Defines the <see cref="HorizontalAlignment"/> property.
  130. /// </summary>
  131. public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
  132. ContentControl.HorizontalContentAlignmentProperty.AddOwner<TextBox>();
  133. /// <summary>
  134. /// Defines the <see cref="VerticalAlignment"/> property.
  135. /// </summary>
  136. public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
  137. ContentControl.VerticalContentAlignmentProperty.AddOwner<TextBox>();
  138. public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
  139. TextBlock.TextWrappingProperty.AddOwner<TextBox>();
  140. /// <summary>
  141. /// Defines see <see cref="TextPresenter.LineHeight"/> property.
  142. /// </summary>
  143. public static readonly StyledProperty<double> LineHeightProperty =
  144. TextBlock.LineHeightProperty.AddOwner<TextBox>(new(defaultValue: double.NaN));
  145. /// <summary>
  146. /// Defines see <see cref="TextBlock.LetterSpacing"/> property.
  147. /// </summary>
  148. public static readonly StyledProperty<double> LetterSpacingProperty =
  149. TextBlock.LetterSpacingProperty.AddOwner<TextBox>();
  150. /// <summary>
  151. /// Defines the <see cref="Watermark"/> property
  152. /// </summary>
  153. public static readonly StyledProperty<string?> WatermarkProperty =
  154. AvaloniaProperty.Register<TextBox, string?>(nameof(Watermark));
  155. /// <summary>
  156. /// Defines the <see cref="UseFloatingWatermark"/> property
  157. /// </summary>
  158. public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
  159. AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
  160. /// <summary>
  161. /// Defines the <see cref="NewLine"/> property
  162. /// </summary>
  163. public static readonly StyledProperty<string> NewLineProperty =
  164. AvaloniaProperty.Register<TextBox, string>(nameof(NewLine), Environment.NewLine);
  165. /// <summary>
  166. /// Defines the <see cref="InnerLeftContent"/> property
  167. /// </summary>
  168. public static readonly StyledProperty<object> InnerLeftContentProperty =
  169. AvaloniaProperty.Register<TextBox, object>(nameof(InnerLeftContent));
  170. /// <summary>
  171. /// Defines the <see cref="InnerRightContent"/> property
  172. /// </summary>
  173. public static readonly StyledProperty<object> InnerRightContentProperty =
  174. AvaloniaProperty.Register<TextBox, object>(nameof(InnerRightContent));
  175. /// <summary>
  176. /// Defines the <see cref="RevealPassword"/> property
  177. /// </summary>
  178. public static readonly StyledProperty<bool> RevealPasswordProperty =
  179. AvaloniaProperty.Register<TextBox, bool>(nameof(RevealPassword));
  180. /// <summary>
  181. /// Defines the <see cref="CanCut"/> property
  182. /// </summary>
  183. public static readonly DirectProperty<TextBox, bool> CanCutProperty =
  184. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  185. nameof(CanCut),
  186. o => o.CanCut);
  187. /// <summary>
  188. /// Defines the <see cref="CanCopy"/> property
  189. /// </summary>
  190. public static readonly DirectProperty<TextBox, bool> CanCopyProperty =
  191. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  192. nameof(CanCopy),
  193. o => o.CanCopy);
  194. /// <summary>
  195. /// Defines the <see cref="CanPaste"/> property
  196. /// </summary>
  197. public static readonly DirectProperty<TextBox, bool> CanPasteProperty =
  198. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  199. nameof(CanPaste),
  200. o => o.CanPaste);
  201. /// <summary>
  202. /// Defines the <see cref="IsUndoEnabled"/> property
  203. /// </summary>
  204. public static readonly StyledProperty<bool> IsUndoEnabledProperty =
  205. AvaloniaProperty.Register<TextBox, bool>(
  206. nameof(IsUndoEnabled),
  207. defaultValue: true);
  208. /// <summary>
  209. /// Defines the <see cref="UndoLimit"/> property
  210. /// </summary>
  211. public static readonly StyledProperty<int> UndoLimitProperty =
  212. AvaloniaProperty.Register<TextBox, int>(nameof(UndoLimit), UndoRedoHelper<UndoRedoState>.DefaultUndoLimit);
  213. /// <summary>
  214. /// Defines the <see cref="CanUndo"/> property
  215. /// </summary>
  216. public static readonly DirectProperty<TextBox, bool> CanUndoProperty =
  217. AvaloniaProperty.RegisterDirect<TextBox, bool>(nameof(CanUndo), x => x.CanUndo);
  218. /// <summary>
  219. /// Defines the <see cref="CanRedo"/> property
  220. /// </summary>
  221. public static readonly DirectProperty<TextBox, bool> CanRedoProperty =
  222. AvaloniaProperty.RegisterDirect<TextBox, bool>(nameof(CanRedo), x => x.CanRedo);
  223. /// <summary>
  224. /// Defines the <see cref="CopyingToClipboard"/> event.
  225. /// </summary>
  226. public static readonly RoutedEvent<RoutedEventArgs> CopyingToClipboardEvent =
  227. RoutedEvent.Register<TextBox, RoutedEventArgs>(
  228. nameof(CopyingToClipboard), RoutingStrategies.Bubble);
  229. /// <summary>
  230. /// Defines the <see cref="CuttingToClipboard"/> event.
  231. /// </summary>
  232. public static readonly RoutedEvent<RoutedEventArgs> CuttingToClipboardEvent =
  233. RoutedEvent.Register<TextBox, RoutedEventArgs>(
  234. nameof(CuttingToClipboard), RoutingStrategies.Bubble);
  235. /// <summary>
  236. /// Defines the <see cref="PastingFromClipboard"/> event.
  237. /// </summary>
  238. public static readonly RoutedEvent<RoutedEventArgs> PastingFromClipboardEvent =
  239. RoutedEvent.Register<TextBox, RoutedEventArgs>(
  240. nameof(PastingFromClipboard), RoutingStrategies.Bubble);
  241. /// <summary>
  242. /// Defines the <see cref="TextChanged"/> event.
  243. /// </summary>
  244. public static readonly RoutedEvent<TextChangedEventArgs> TextChangedEvent =
  245. RoutedEvent.Register<TextBox, TextChangedEventArgs>(
  246. nameof(TextChanged), RoutingStrategies.Bubble);
  247. /// <summary>
  248. /// Defines the <see cref="TextChanging"/> event.
  249. /// </summary>
  250. public static readonly RoutedEvent<TextChangingEventArgs> TextChangingEvent =
  251. RoutedEvent.Register<TextBox, TextChangingEventArgs>(
  252. nameof(TextChanging), RoutingStrategies.Bubble);
  253. /// <summary>
  254. /// Stores the state information for available actions in the UndoRedoHelper
  255. /// </summary>
  256. readonly struct UndoRedoState : IEquatable<UndoRedoState>
  257. {
  258. public string? Text { get; }
  259. public int CaretPosition { get; }
  260. public UndoRedoState(string? text, int caretPosition)
  261. {
  262. Text = text;
  263. CaretPosition = caretPosition;
  264. }
  265. public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
  266. public override bool Equals(object? obj) => obj is UndoRedoState other && Equals(other);
  267. public override int GetHashCode() => Text?.GetHashCode() ?? 0;
  268. }
  269. private TextPresenter? _presenter;
  270. private ScrollViewer? _scrollViewer;
  271. private readonly TextBoxTextInputMethodClient _imClient = new();
  272. private readonly UndoRedoHelper<UndoRedoState> _undoRedoHelper;
  273. private bool _isUndoingRedoing;
  274. private bool _canCut;
  275. private bool _canCopy;
  276. private bool _canPaste;
  277. private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
  278. private bool _canUndo;
  279. private bool _canRedo;
  280. private int _wordSelectionStart = -1;
  281. private int _selectedTextChangesMadeSinceLastUndoSnapshot;
  282. private bool _hasDoneSnapshotOnce;
  283. private static bool _isHolding;
  284. private int _currentClickCount;
  285. private bool _isDoubleTapped;
  286. private const int _maxCharsBeforeUndoSnapshot = 7;
  287. static TextBox()
  288. {
  289. FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
  290. TextInputMethodClientRequestedEvent.AddClassHandler<TextBox>((tb, e) =>
  291. {
  292. if (!tb.IsReadOnly)
  293. {
  294. e.Client = tb._imClient;
  295. }
  296. });
  297. }
  298. public TextBox()
  299. {
  300. var horizontalScrollBarVisibility = Observable.CombineLatest(
  301. this.GetObservable(AcceptsReturnProperty),
  302. this.GetObservable(TextWrappingProperty),
  303. (acceptsReturn, wrapping) =>
  304. {
  305. if (wrapping != TextWrapping.NoWrap)
  306. {
  307. return ScrollBarVisibility.Disabled;
  308. }
  309. return acceptsReturn ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden;
  310. });
  311. this.Bind(
  312. ScrollViewer.HorizontalScrollBarVisibilityProperty,
  313. horizontalScrollBarVisibility,
  314. BindingPriority.Style);
  315. _undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
  316. _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
  317. _hasDoneSnapshotOnce = false;
  318. UpdatePseudoclasses();
  319. }
  320. /// <summary>
  321. /// Gets or sets a value that determines whether the TextBox allows and displays newline or return characters
  322. /// </summary>
  323. public bool AcceptsReturn
  324. {
  325. get => GetValue(AcceptsReturnProperty);
  326. set => SetValue(AcceptsReturnProperty, value);
  327. }
  328. /// <summary>
  329. /// Gets or sets a value that determins whether the TextBox allows and displays tabs
  330. /// </summary>
  331. public bool AcceptsTab
  332. {
  333. get => GetValue(AcceptsTabProperty);
  334. set => SetValue(AcceptsTabProperty, value);
  335. }
  336. /// <summary>
  337. /// Gets or sets the index of the text caret
  338. /// </summary>
  339. public int CaretIndex
  340. {
  341. get => GetValue(CaretIndexProperty);
  342. set => SetValue(CaretIndexProperty, value);
  343. }
  344. private void OnCaretIndexChanged(AvaloniaPropertyChangedEventArgs e)
  345. {
  346. UndoRedoState state;
  347. if (IsUndoEnabled && _undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
  348. _undoRedoHelper.UpdateLastState();
  349. var newValue = e.GetNewValue<int>();
  350. SetCurrentValue(SelectionStartProperty, newValue);
  351. SetCurrentValue(SelectionEndProperty, newValue);
  352. }
  353. /// <summary>
  354. /// Gets or sets a value whether this TextBox is read-only
  355. /// </summary>
  356. public bool IsReadOnly
  357. {
  358. get => GetValue(IsReadOnlyProperty);
  359. set => SetValue(IsReadOnlyProperty, value);
  360. }
  361. /// <summary>
  362. /// Gets or sets the <see cref="char"/> that should be used for password masking
  363. /// </summary>
  364. public char PasswordChar
  365. {
  366. get => GetValue(PasswordCharProperty);
  367. set => SetValue(PasswordCharProperty, value);
  368. }
  369. /// <summary>
  370. /// Gets or sets a brush that is used to highlight selected text
  371. /// </summary>
  372. public IBrush? SelectionBrush
  373. {
  374. get => GetValue(SelectionBrushProperty);
  375. set => SetValue(SelectionBrushProperty, value);
  376. }
  377. /// <summary>
  378. /// Gets or sets a brush that is used for the foreground of selected text
  379. /// </summary>
  380. public IBrush? SelectionForegroundBrush
  381. {
  382. get => GetValue(SelectionForegroundBrushProperty);
  383. set => SetValue(SelectionForegroundBrushProperty, value);
  384. }
  385. /// <summary>
  386. /// Gets or sets a brush that is used for the text caret
  387. /// </summary>
  388. public IBrush? CaretBrush
  389. {
  390. get => GetValue(CaretBrushProperty);
  391. set => SetValue(CaretBrushProperty, value);
  392. }
  393. /// <inheritdoc cref="TextPresenter.CaretBlinkInterval"/>
  394. public TimeSpan CaretBlinkInterval
  395. {
  396. get => GetValue(CaretBlinkIntervalProperty);
  397. set => SetValue(CaretBlinkIntervalProperty, value);
  398. }
  399. /// <summary>
  400. /// Gets or sets the starting position of the text selected in the TextBox
  401. /// </summary>
  402. public int SelectionStart
  403. {
  404. get => GetValue(SelectionStartProperty);
  405. set => SetValue(SelectionStartProperty, value);
  406. }
  407. private void OnSelectionStartChanged(AvaloniaPropertyChangedEventArgs e)
  408. {
  409. UpdateCommandStates();
  410. var value = e.GetNewValue<int>();
  411. if (SelectionEnd == value && CaretIndex != value)
  412. {
  413. SetCurrentValue(CaretIndexProperty, value);
  414. }
  415. }
  416. /// <summary>
  417. /// Gets or sets the end position of the text selected in the TextBox
  418. /// </summary>
  419. /// <remarks>
  420. /// When the SelectionEnd is equal to <see cref="SelectionStart"/>, there is no
  421. /// selected text and it marks the caret position
  422. /// </remarks>
  423. public int SelectionEnd
  424. {
  425. get => GetValue(SelectionEndProperty);
  426. set => SetValue(SelectionEndProperty, value);
  427. }
  428. private void OnSelectionEndChanged(AvaloniaPropertyChangedEventArgs e)
  429. {
  430. UpdateCommandStates();
  431. var value = e.GetNewValue<int>();
  432. if (SelectionStart == value && CaretIndex != value)
  433. {
  434. SetCurrentValue(CaretIndexProperty, value);
  435. }
  436. }
  437. /// <summary>
  438. /// Gets or sets the maximum number of characters that the <see cref="TextBox"/> can accept.
  439. /// This constraint only applies for manually entered (user-inputted) text.
  440. /// </summary>
  441. public int MaxLength
  442. {
  443. get => GetValue(MaxLengthProperty);
  444. set => SetValue(MaxLengthProperty, value);
  445. }
  446. /// <summary>
  447. /// Gets or sets the maximum number of visible lines to size to.
  448. /// </summary>
  449. public int MaxLines
  450. {
  451. get => GetValue(MaxLinesProperty);
  452. set => SetValue(MaxLinesProperty, value);
  453. }
  454. /// <summary>
  455. /// Gets or sets the minimum number of visible lines to size to.
  456. /// </summary>
  457. public int MinLines
  458. {
  459. get => GetValue(MinLinesProperty);
  460. set => SetValue(MinLinesProperty, value);
  461. }
  462. /// <summary>
  463. /// Gets or sets the spacing between characters
  464. /// </summary>
  465. public double LetterSpacing
  466. {
  467. get => GetValue(LetterSpacingProperty);
  468. set => SetValue(LetterSpacingProperty, value);
  469. }
  470. /// <summary>
  471. /// Gets or sets the line height.
  472. /// </summary>
  473. public double LineHeight
  474. {
  475. get => GetValue(LineHeightProperty);
  476. set => SetValue(LineHeightProperty, value);
  477. }
  478. /// <summary>
  479. /// Gets or sets the Text content of the TextBox
  480. /// </summary>
  481. [Content]
  482. public string? Text
  483. {
  484. get => GetValue(TextProperty);
  485. set => SetValue(TextProperty, value);
  486. }
  487. private static string? CoerceText(AvaloniaObject sender, string? value)
  488. {
  489. var textBox = (TextBox)sender;
  490. // Before #9490, snapshot here was done AFTER text change - this doesn't make sense
  491. // since intial state would never be no text and you'd always have to make a text
  492. // change before undo would be available
  493. // The undo/redo stacks were also cleared at this point, which also doesn't make sense
  494. // as it is still valid to want to undo a programmatic text set
  495. // So we snapshot text now BEFORE the change so we can always revert
  496. // Also don't need to check IsUndoEnabled here, that's done in SnapshotUndoRedo
  497. if (!textBox._isUndoingRedoing)
  498. {
  499. textBox.SnapshotUndoRedo();
  500. }
  501. return value;
  502. }
  503. /// <summary>
  504. /// Gets or sets the text selected in the TextBox
  505. /// </summary>
  506. public string SelectedText
  507. {
  508. get => GetSelection();
  509. set
  510. {
  511. if (string.IsNullOrEmpty(value))
  512. {
  513. _selectedTextChangesMadeSinceLastUndoSnapshot++;
  514. SnapshotUndoRedo(ignoreChangeCount: false);
  515. DeleteSelection();
  516. }
  517. else
  518. {
  519. HandleTextInput(value);
  520. }
  521. }
  522. }
  523. /// <summary>
  524. /// Gets or sets the horizontal alignment of the content within the control.
  525. /// </summary>
  526. public HorizontalAlignment HorizontalContentAlignment
  527. {
  528. get => GetValue(HorizontalContentAlignmentProperty);
  529. set => SetValue(HorizontalContentAlignmentProperty, value);
  530. }
  531. /// <summary>
  532. /// Gets or sets the vertical alignment of the content within the control.
  533. /// </summary>
  534. public VerticalAlignment VerticalContentAlignment
  535. {
  536. get => GetValue(VerticalContentAlignmentProperty);
  537. set => SetValue(VerticalContentAlignmentProperty, value);
  538. }
  539. /// <summary>
  540. /// Gets or sets the <see cref="Media.TextAlignment"/> of the TextBox
  541. /// </summary>
  542. public TextAlignment TextAlignment
  543. {
  544. get => GetValue(TextAlignmentProperty);
  545. set => SetValue(TextAlignmentProperty, value);
  546. }
  547. /// <summary>
  548. /// Gets or sets the placeholder or descriptive text that is displayed even if the <see cref="Text"/>
  549. /// property is not yet set.
  550. /// </summary>
  551. public string? Watermark
  552. {
  553. get => GetValue(WatermarkProperty);
  554. set => SetValue(WatermarkProperty, value);
  555. }
  556. /// <summary>
  557. /// Gets or sets a value indicating whether the <see cref="Watermark"/> will still be shown above the
  558. /// <see cref="Text"/> even after a text value is set.
  559. /// </summary>
  560. public bool UseFloatingWatermark
  561. {
  562. get => GetValue(UseFloatingWatermarkProperty);
  563. set => SetValue(UseFloatingWatermarkProperty, value);
  564. }
  565. /// <summary>
  566. /// Gets or sets custom content that is positioned on the left side of the text layout box
  567. /// </summary>
  568. public object InnerLeftContent
  569. {
  570. get => GetValue(InnerLeftContentProperty);
  571. set => SetValue(InnerLeftContentProperty, value);
  572. }
  573. /// <summary>
  574. /// Gets or sets custom content that is positioned on the right side of the text layout box
  575. /// </summary>
  576. public object InnerRightContent
  577. {
  578. get => GetValue(InnerRightContentProperty);
  579. set => SetValue(InnerRightContentProperty, value);
  580. }
  581. /// <summary>
  582. /// Gets or sets whether text masked by <see cref="PasswordChar"/> should be revealed
  583. /// </summary>
  584. public bool RevealPassword
  585. {
  586. get => GetValue(RevealPasswordProperty);
  587. set => SetValue(RevealPasswordProperty, value);
  588. }
  589. /// <summary>
  590. /// Gets or sets the <see cref="Media.TextWrapping"/> of the TextBox
  591. /// </summary>
  592. public TextWrapping TextWrapping
  593. {
  594. get => GetValue(TextWrappingProperty);
  595. set => SetValue(TextWrappingProperty, value);
  596. }
  597. /// <summary>
  598. /// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
  599. /// </summary>
  600. public string NewLine
  601. {
  602. get => GetValue(NewLineProperty);
  603. set => SetValue(NewLineProperty, value);
  604. }
  605. /// <summary>
  606. /// Clears the current selection, maintaining the <see cref="CaretIndex"/>
  607. /// </summary>
  608. public void ClearSelection()
  609. {
  610. SetCurrentValue(CaretIndexProperty, SelectionStart);
  611. SetCurrentValue(SelectionEndProperty, SelectionStart);
  612. }
  613. /// <summary>
  614. /// Property for determining if the Cut command can be executed.
  615. /// </summary>
  616. public bool CanCut
  617. {
  618. get => _canCut;
  619. private set => SetAndRaise(CanCutProperty, ref _canCut, value);
  620. }
  621. /// <summary>
  622. /// Property for determining if the Copy command can be executed.
  623. /// </summary>
  624. public bool CanCopy
  625. {
  626. get => _canCopy;
  627. private set => SetAndRaise(CanCopyProperty, ref _canCopy, value);
  628. }
  629. /// <summary>
  630. /// Property for determining if the Paste command can be executed.
  631. /// </summary>
  632. public bool CanPaste
  633. {
  634. get => _canPaste;
  635. private set => SetAndRaise(CanPasteProperty, ref _canPaste, value);
  636. }
  637. /// <summary>
  638. /// Property for determining whether undo/redo is enabled
  639. /// </summary>
  640. public bool IsUndoEnabled
  641. {
  642. get => GetValue(IsUndoEnabledProperty);
  643. set => SetValue(IsUndoEnabledProperty, value);
  644. }
  645. /// <summary>
  646. /// Gets or sets the maximum number of items that can reside in the Undo stack
  647. /// </summary>
  648. public int UndoLimit
  649. {
  650. get => GetValue(UndoLimitProperty);
  651. set => SetValue(UndoLimitProperty, value);
  652. }
  653. private void OnUndoLimitChanged(int newValue)
  654. {
  655. _undoRedoHelper.Limit = newValue;
  656. // from docs at
  657. // https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
  658. // "Setting UndoLimit clears the undo queue."
  659. _undoRedoHelper.Clear();
  660. _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
  661. _hasDoneSnapshotOnce = false;
  662. }
  663. /// <summary>
  664. /// Gets a value that indicates whether the undo stack has an action that can be undone
  665. /// </summary>
  666. public bool CanUndo
  667. {
  668. get => _canUndo;
  669. private set => SetAndRaise(CanUndoProperty, ref _canUndo, value);
  670. }
  671. /// <summary>
  672. /// Gets a value that indicates whether the redo stack has an action that can be redone
  673. /// </summary>
  674. public bool CanRedo
  675. {
  676. get => _canRedo;
  677. private set => SetAndRaise(CanRedoProperty, ref _canRedo, value);
  678. }
  679. /// <summary>
  680. /// Raised when content is being copied to the clipboard
  681. /// </summary>
  682. public event EventHandler<RoutedEventArgs>? CopyingToClipboard
  683. {
  684. add => AddHandler(CopyingToClipboardEvent, value);
  685. remove => RemoveHandler(CopyingToClipboardEvent, value);
  686. }
  687. /// <summary>
  688. /// Raised when content is being cut to the clipboard
  689. /// </summary>
  690. public event EventHandler<RoutedEventArgs>? CuttingToClipboard
  691. {
  692. add => AddHandler(CuttingToClipboardEvent, value);
  693. remove => RemoveHandler(CuttingToClipboardEvent, value);
  694. }
  695. /// <summary>
  696. /// Raised when content is being pasted from the clipboard
  697. /// </summary>
  698. public event EventHandler<RoutedEventArgs>? PastingFromClipboard
  699. {
  700. add => AddHandler(PastingFromClipboardEvent, value);
  701. remove => RemoveHandler(PastingFromClipboardEvent, value);
  702. }
  703. /// <summary>
  704. /// Occurs asynchronously after text changes and the new text is rendered.
  705. /// </summary>
  706. public event EventHandler<TextChangedEventArgs>? TextChanged
  707. {
  708. add => AddHandler(TextChangedEvent, value);
  709. remove => RemoveHandler(TextChangedEvent, value);
  710. }
  711. /// <summary>
  712. /// Occurs synchronously when text starts to change but before it is rendered.
  713. /// </summary>
  714. /// <remarks>
  715. /// This event occurs just after the <see cref="Text"/> property value has been updated.
  716. /// </remarks>
  717. public event EventHandler<TextChangingEventArgs>? TextChanging
  718. {
  719. add => AddHandler(TextChangingEvent, value);
  720. remove => RemoveHandler(TextChangingEvent, value);
  721. }
  722. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  723. {
  724. _presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
  725. if (_scrollViewer != null)
  726. {
  727. _scrollViewer.ScrollChanged -= ScrollViewer_ScrollChanged;
  728. }
  729. _scrollViewer = e.NameScope.Find<ScrollViewer>("PART_ScrollViewer");
  730. if(_scrollViewer != null)
  731. {
  732. _scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
  733. }
  734. _imClient.SetPresenter(_presenter, this);
  735. if (IsFocused)
  736. {
  737. _presenter?.ShowCaret();
  738. }
  739. }
  740. private void ScrollViewer_ScrollChanged(object? sender, ScrollChangedEventArgs e)
  741. {
  742. _presenter?.TextSelectionHandleCanvas?.MoveHandlesToSelection();
  743. }
  744. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  745. {
  746. base.OnAttachedToVisualTree(e);
  747. if (_presenter != null)
  748. {
  749. if (IsFocused)
  750. {
  751. _presenter.ShowCaret();
  752. }
  753. _presenter.PropertyChanged += PresenterPropertyChanged;
  754. }
  755. }
  756. protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
  757. {
  758. base.OnDetachedFromVisualTree(e);
  759. if (_presenter != null)
  760. {
  761. _presenter.HideCaret();
  762. _presenter.PropertyChanged -= PresenterPropertyChanged;
  763. }
  764. _imClient.SetPresenter(null, null);
  765. }
  766. private void PresenterPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
  767. {
  768. if(e.Property == TextPresenter.PreeditTextProperty)
  769. {
  770. if(string.IsNullOrEmpty(e.OldValue as string) && !string.IsNullOrEmpty(e.NewValue as string))
  771. {
  772. PseudoClasses.Set(":empty", false);
  773. DeleteSelection();
  774. }
  775. }
  776. }
  777. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  778. {
  779. base.OnPropertyChanged(change);
  780. if (change.Property == TextProperty)
  781. {
  782. CoerceValue(CaretIndexProperty);
  783. CoerceValue(SelectionStartProperty);
  784. CoerceValue(SelectionEndProperty);
  785. RaiseTextChangeEvents();
  786. UpdatePseudoclasses();
  787. UpdateCommandStates();
  788. }
  789. else if (change.Property == CaretIndexProperty)
  790. {
  791. OnCaretIndexChanged(change);
  792. }
  793. else if (change.Property == SelectionStartProperty)
  794. {
  795. OnSelectionStartChanged(change);
  796. }
  797. else if (change.Property == SelectionEndProperty)
  798. {
  799. OnSelectionEndChanged(change);
  800. }
  801. else if (change.Property == MaxLinesProperty)
  802. {
  803. InvalidateMeasure();
  804. }
  805. else if (change.Property == MinLinesProperty)
  806. {
  807. InvalidateMeasure();
  808. }
  809. else if (change.Property == UndoLimitProperty)
  810. {
  811. OnUndoLimitChanged(change.GetNewValue<int>());
  812. }
  813. else if (change.Property == IsUndoEnabledProperty && change.GetNewValue<bool>() == false)
  814. {
  815. // from docs at
  816. // https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
  817. // "Setting this property to false clears the undo stack.
  818. // Therefore, if you disable undo and then re-enable it, undo commands still do not work
  819. // because the undo stack was emptied when you disabled undo."
  820. _undoRedoHelper.Clear();
  821. _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
  822. _hasDoneSnapshotOnce = false;
  823. }
  824. }
  825. private void UpdateCommandStates()
  826. {
  827. var text = GetSelection();
  828. var isSelectionNullOrEmpty = string.IsNullOrEmpty(text);
  829. CanCopy = !IsPasswordBox && !isSelectionNullOrEmpty;
  830. CanCut = !IsPasswordBox && !isSelectionNullOrEmpty && !IsReadOnly;
  831. CanPaste = !IsReadOnly;
  832. }
  833. protected override void OnGotFocus(GotFocusEventArgs e)
  834. {
  835. base.OnGotFocus(e);
  836. // when navigating to a textbox via the tab key, select all text if
  837. // 1) this textbox is *not* a multiline textbox
  838. // 2) this textbox has any text to select
  839. if (e.NavigationMethod == NavigationMethod.Tab &&
  840. !AcceptsReturn &&
  841. Text?.Length > 0)
  842. {
  843. SelectAll();
  844. }
  845. UpdateCommandStates();
  846. _imClient.SetPresenter(_presenter, this);
  847. _presenter?.ShowCaret();
  848. }
  849. protected override void OnLostFocus(RoutedEventArgs e)
  850. {
  851. base.OnLostFocus(e);
  852. if ((ContextFlyout == null || !ContextFlyout.IsOpen) &&
  853. (ContextMenu == null || !ContextMenu.IsOpen))
  854. {
  855. ClearSelection();
  856. SetCurrentValue(RevealPasswordProperty, false);
  857. }
  858. UpdateCommandStates();
  859. _presenter?.HideCaret();
  860. _imClient.SetPresenter(null, null);
  861. }
  862. protected override void OnTextInput(TextInputEventArgs e)
  863. {
  864. if (!e.Handled)
  865. {
  866. HandleTextInput(e.Text);
  867. e.Handled = true;
  868. }
  869. }
  870. private void HandleTextInput(string? input)
  871. {
  872. if (IsReadOnly)
  873. {
  874. return;
  875. }
  876. input = RemoveInvalidCharacters(input);
  877. if (string.IsNullOrEmpty(input))
  878. {
  879. return;
  880. }
  881. _selectedTextChangesMadeSinceLastUndoSnapshot++;
  882. SnapshotUndoRedo(ignoreChangeCount: false);
  883. var currentText = Text ?? string.Empty;
  884. var selectionLength = Math.Abs(SelectionStart - SelectionEnd);
  885. var newLength = input.Length + currentText.Length - selectionLength;
  886. if (MaxLength > 0 && newLength > MaxLength)
  887. {
  888. input = input.Remove(Math.Max(0, input.Length - (newLength - MaxLength)));
  889. newLength = MaxLength;
  890. }
  891. if (!string.IsNullOrEmpty(input))
  892. {
  893. var textBuilder = StringBuilderCache.Acquire(Math.Max(currentText.Length, newLength));
  894. textBuilder.Append(currentText);
  895. var caretIndex = CaretIndex;
  896. if (selectionLength != 0)
  897. {
  898. var (start, _) = GetSelectionRange();
  899. textBuilder.Remove(start, selectionLength);
  900. caretIndex = start;
  901. }
  902. textBuilder.Insert(caretIndex, input);
  903. var text = StringBuilderCache.GetStringAndRelease(textBuilder);
  904. SetCurrentValue(TextProperty, text);
  905. ClearSelection();
  906. if (IsUndoEnabled)
  907. {
  908. _undoRedoHelper.DiscardRedo();
  909. }
  910. SetCurrentValue(CaretIndexProperty, caretIndex + input.Length);
  911. }
  912. }
  913. private string? RemoveInvalidCharacters(string? text)
  914. {
  915. if (text is null)
  916. return null;
  917. for (var i = 0; i < invalidCharacters.Length; i++)
  918. {
  919. text = text.Replace(invalidCharacters[i], string.Empty);
  920. }
  921. return text;
  922. }
  923. /// <summary>
  924. /// Cuts the current text onto the clipboard
  925. /// </summary>
  926. public async void Cut()
  927. {
  928. var text = GetSelection();
  929. if (string.IsNullOrEmpty(text))
  930. {
  931. return;
  932. }
  933. var eventArgs = new RoutedEventArgs(CuttingToClipboardEvent);
  934. RaiseEvent(eventArgs);
  935. if (!eventArgs.Handled)
  936. {
  937. SnapshotUndoRedo();
  938. var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
  939. if (clipboard == null)
  940. return;
  941. await clipboard.SetTextAsync(text);
  942. DeleteSelection();
  943. }
  944. }
  945. /// <summary>
  946. /// Copies the current text onto the clipboard
  947. /// </summary>
  948. public async void Copy()
  949. {
  950. var text = GetSelection();
  951. if (string.IsNullOrEmpty(text))
  952. {
  953. return;
  954. }
  955. var eventArgs = new RoutedEventArgs(CopyingToClipboardEvent);
  956. RaiseEvent(eventArgs);
  957. if (!eventArgs.Handled)
  958. {
  959. var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
  960. if (clipboard != null)
  961. await clipboard.SetTextAsync(text);
  962. }
  963. }
  964. /// <summary>
  965. /// Pastes the current clipboard text content into the TextBox
  966. /// </summary>
  967. public async void Paste()
  968. {
  969. var eventArgs = new RoutedEventArgs(PastingFromClipboardEvent);
  970. RaiseEvent(eventArgs);
  971. if (eventArgs.Handled)
  972. {
  973. return;
  974. }
  975. string? text = null;
  976. var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
  977. if (clipboard != null)
  978. {
  979. try
  980. {
  981. text = await clipboard.GetTextAsync();
  982. }
  983. catch (TimeoutException)
  984. {
  985. // Silently ignore.
  986. }
  987. }
  988. if (string.IsNullOrEmpty(text))
  989. {
  990. return;
  991. }
  992. SnapshotUndoRedo();
  993. HandleTextInput(text);
  994. }
  995. protected override void OnKeyDown(KeyEventArgs e)
  996. {
  997. if (_presenter == null)
  998. {
  999. return;
  1000. }
  1001. if (!string.IsNullOrEmpty(_presenter.PreeditText))
  1002. {
  1003. return;
  1004. }
  1005. var text = Text ?? string.Empty;
  1006. var caretIndex = CaretIndex;
  1007. var movement = false;
  1008. var selection = false;
  1009. var handled = false;
  1010. var modifiers = e.KeyModifiers;
  1011. var keymap = Application.Current!.PlatformSettings!.HotkeyConfiguration;
  1012. bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
  1013. bool DetectSelection() => e.KeyModifiers.HasAllFlags(keymap.SelectionModifiers);
  1014. if (Match(keymap.SelectAll))
  1015. {
  1016. SelectAll();
  1017. handled = true;
  1018. }
  1019. else if (Match(keymap.Copy))
  1020. {
  1021. if (!IsPasswordBox)
  1022. {
  1023. Copy();
  1024. }
  1025. handled = true;
  1026. }
  1027. else if (Match(keymap.Cut))
  1028. {
  1029. if (!IsPasswordBox)
  1030. {
  1031. Cut();
  1032. }
  1033. handled = true;
  1034. }
  1035. else if (Match(keymap.Paste))
  1036. {
  1037. Paste();
  1038. handled = true;
  1039. }
  1040. else if (Match(keymap.Undo) && IsUndoEnabled)
  1041. {
  1042. Undo();
  1043. handled = true;
  1044. }
  1045. else if (Match(keymap.Redo) && IsUndoEnabled)
  1046. {
  1047. Redo();
  1048. handled = true;
  1049. }
  1050. else if (Match(keymap.MoveCursorToTheStartOfDocument))
  1051. {
  1052. MoveHome(true);
  1053. movement = true;
  1054. selection = false;
  1055. handled = true;
  1056. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1057. }
  1058. else if (Match(keymap.MoveCursorToTheEndOfDocument))
  1059. {
  1060. MoveEnd(true);
  1061. movement = true;
  1062. selection = false;
  1063. handled = true;
  1064. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1065. }
  1066. else if (Match(keymap.MoveCursorToTheStartOfLine))
  1067. {
  1068. MoveHome(false);
  1069. movement = true;
  1070. selection = false;
  1071. handled = true;
  1072. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1073. }
  1074. else if (Match(keymap.MoveCursorToTheEndOfLine))
  1075. {
  1076. MoveEnd(false);
  1077. movement = true;
  1078. selection = false;
  1079. handled = true;
  1080. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1081. }
  1082. else if (Match(keymap.MoveCursorToTheStartOfDocumentWithSelection))
  1083. {
  1084. SetCurrentValue(SelectionStartProperty, caretIndex);
  1085. MoveHome(true);
  1086. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1087. movement = true;
  1088. selection = true;
  1089. handled = true;
  1090. }
  1091. else if (Match(keymap.MoveCursorToTheEndOfDocumentWithSelection))
  1092. {
  1093. SetCurrentValue(SelectionStartProperty, caretIndex);
  1094. MoveEnd(true);
  1095. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1096. movement = true;
  1097. selection = true;
  1098. handled = true;
  1099. }
  1100. else if (Match(keymap.MoveCursorToTheStartOfLineWithSelection))
  1101. {
  1102. SetCurrentValue(SelectionStartProperty, caretIndex);
  1103. MoveHome(false);
  1104. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1105. movement = true;
  1106. selection = true;
  1107. handled = true;
  1108. }
  1109. else if (Match(keymap.MoveCursorToTheEndOfLineWithSelection))
  1110. {
  1111. SetCurrentValue(SelectionStartProperty, caretIndex);
  1112. MoveEnd(false);
  1113. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1114. movement = true;
  1115. selection = true;
  1116. handled = true;
  1117. }
  1118. else if (Match(keymap.PageLeft))
  1119. {
  1120. MovePageLeft();
  1121. movement = true;
  1122. selection = false;
  1123. handled = true;
  1124. }
  1125. else if (Match(keymap.PageRight))
  1126. {
  1127. MovePageRight();
  1128. movement = true;
  1129. selection = false;
  1130. handled = true;
  1131. }
  1132. else if (Match(keymap.PageUp))
  1133. {
  1134. MovePageUp();
  1135. movement = true;
  1136. selection = false;
  1137. handled = true;
  1138. }
  1139. else if (Match(keymap.PageDown))
  1140. {
  1141. MovePageDown();
  1142. movement = true;
  1143. selection = false;
  1144. handled = true;
  1145. }
  1146. else
  1147. {
  1148. bool hasWholeWordModifiers = modifiers.HasAllFlags(keymap.WholeWordTextActionModifiers);
  1149. switch (e.Key)
  1150. {
  1151. case Key.Left:
  1152. selection = DetectSelection();
  1153. MoveHorizontal(-1, hasWholeWordModifiers, selection, true);
  1154. if (caretIndex != _presenter.CaretIndex)
  1155. {
  1156. movement = true;
  1157. }
  1158. break;
  1159. case Key.Right:
  1160. selection = DetectSelection();
  1161. MoveHorizontal(1, hasWholeWordModifiers, selection, true);
  1162. if (caretIndex != _presenter.CaretIndex)
  1163. {
  1164. movement = true;
  1165. }
  1166. break;
  1167. case Key.Up:
  1168. {
  1169. selection = DetectSelection();
  1170. _presenter.MoveCaretVertical(LogicalDirection.Backward);
  1171. if (caretIndex != _presenter.CaretIndex)
  1172. {
  1173. movement = true;
  1174. }
  1175. if (selection)
  1176. {
  1177. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1178. }
  1179. else
  1180. {
  1181. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1182. }
  1183. break;
  1184. }
  1185. case Key.Down:
  1186. {
  1187. selection = DetectSelection();
  1188. _presenter.MoveCaretVertical();
  1189. if (caretIndex != _presenter.CaretIndex)
  1190. {
  1191. movement = true;
  1192. }
  1193. if (selection)
  1194. {
  1195. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1196. }
  1197. else
  1198. {
  1199. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1200. }
  1201. break;
  1202. }
  1203. case Key.Back:
  1204. {
  1205. SnapshotUndoRedo();
  1206. if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
  1207. {
  1208. SetSelectionForControlBackspace();
  1209. }
  1210. if (!DeleteSelection())
  1211. {
  1212. var characterHit = _presenter.GetNextCharacterHit(LogicalDirection.Backward);
  1213. var backspacePosition = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
  1214. if (caretIndex != backspacePosition)
  1215. {
  1216. var start = Math.Min(backspacePosition, caretIndex);
  1217. var end = Math.Max(backspacePosition, caretIndex);
  1218. var length = end - start;
  1219. var sb = StringBuilderCache.Acquire(text.Length);
  1220. sb.Append(text);
  1221. sb.Remove(start, end - start);
  1222. SetCurrentValue(TextProperty, StringBuilderCache.GetStringAndRelease(sb));
  1223. SetCurrentValue(CaretIndexProperty, start);
  1224. }
  1225. }
  1226. SnapshotUndoRedo();
  1227. handled = true;
  1228. break;
  1229. }
  1230. case Key.Delete:
  1231. SnapshotUndoRedo();
  1232. if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
  1233. {
  1234. SetSelectionForControlDelete();
  1235. }
  1236. if (!DeleteSelection())
  1237. {
  1238. var characterHit = _presenter.GetNextCharacterHit();
  1239. var nextPosition = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
  1240. if (nextPosition != caretIndex)
  1241. {
  1242. var start = Math.Min(nextPosition, caretIndex);
  1243. var end = Math.Max(nextPosition, caretIndex);
  1244. var sb = StringBuilderCache.Acquire(text.Length);
  1245. sb.Append(text);
  1246. sb.Remove(start, end - start);
  1247. SetCurrentValue(TextProperty, StringBuilderCache.GetStringAndRelease(sb));
  1248. }
  1249. }
  1250. SnapshotUndoRedo();
  1251. handled = true;
  1252. break;
  1253. case Key.Enter:
  1254. if (AcceptsReturn)
  1255. {
  1256. SnapshotUndoRedo();
  1257. HandleTextInput(NewLine);
  1258. handled = true;
  1259. }
  1260. break;
  1261. case Key.Tab:
  1262. if (AcceptsTab)
  1263. {
  1264. SnapshotUndoRedo();
  1265. HandleTextInput("\t");
  1266. handled = true;
  1267. }
  1268. else
  1269. {
  1270. base.OnKeyDown(e);
  1271. }
  1272. break;
  1273. case Key.Space:
  1274. SnapshotUndoRedo(); // always snapshot in between words
  1275. break;
  1276. default:
  1277. handled = false;
  1278. break;
  1279. }
  1280. }
  1281. if (movement && !selection)
  1282. {
  1283. ClearSelection();
  1284. }
  1285. if (handled || movement)
  1286. {
  1287. e.Handled = true;
  1288. }
  1289. }
  1290. protected override void OnPointerPressed(PointerPressedEventArgs e)
  1291. {
  1292. if (_presenter == null)
  1293. {
  1294. return;
  1295. }
  1296. var text = Text;
  1297. var clickInfo = e.GetCurrentPoint(this);
  1298. if (text != null && (e.Pointer.Type == PointerType.Mouse || e.ClickCount >= 2) && clickInfo.Properties.IsLeftButtonPressed &&
  1299. !(clickInfo.Pointer?.Captured is Border))
  1300. {
  1301. _currentClickCount = e.ClickCount;
  1302. var point = e.GetPosition(_presenter);
  1303. _presenter.MoveCaretToPoint(point);
  1304. var caretIndex = _presenter.CaretIndex;
  1305. var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift);
  1306. var selectionStart = SelectionStart;
  1307. var selectionEnd = SelectionEnd;
  1308. switch (e.ClickCount)
  1309. {
  1310. case 1:
  1311. if (clickToSelect)
  1312. {
  1313. if (_wordSelectionStart >= 0)
  1314. {
  1315. UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
  1316. SetCurrentValue(SelectionStartProperty, selectionStart);
  1317. SetCurrentValue(SelectionEndProperty, selectionEnd);
  1318. }
  1319. else
  1320. {
  1321. SetCurrentValue(SelectionEndProperty, caretIndex);
  1322. }
  1323. }
  1324. else
  1325. {
  1326. SetCurrentValue(SelectionStartProperty, caretIndex);
  1327. SetCurrentValue(SelectionEndProperty, caretIndex);
  1328. _wordSelectionStart = -1;
  1329. }
  1330. break;
  1331. case 2:
  1332. if (!StringUtils.IsStartOfWord(text, caretIndex))
  1333. {
  1334. selectionStart = StringUtils.PreviousWord(text, caretIndex);
  1335. }
  1336. if (!StringUtils.IsEndOfWord(text, caretIndex))
  1337. {
  1338. selectionEnd = StringUtils.NextWord(text, caretIndex);
  1339. }
  1340. if (selectionStart != selectionEnd)
  1341. {
  1342. _wordSelectionStart = selectionStart;
  1343. }
  1344. SetCurrentValue(SelectionStartProperty, selectionStart);
  1345. SetCurrentValue(SelectionEndProperty, selectionEnd);
  1346. break;
  1347. case 3:
  1348. _wordSelectionStart = -1;
  1349. SelectAll();
  1350. break;
  1351. }
  1352. }
  1353. _isDoubleTapped = e.ClickCount == 2;
  1354. e.Pointer.Capture(_presenter);
  1355. e.Handled = true;
  1356. }
  1357. protected override void OnPointerMoved(PointerEventArgs e)
  1358. {
  1359. if (_presenter == null || _isHolding)
  1360. {
  1361. return;
  1362. }
  1363. // selection should not change during pointer move if the user right clicks
  1364. if (e.Pointer.Captured == _presenter && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
  1365. {
  1366. var point = e.GetPosition(_presenter);
  1367. point = new Point(
  1368. MathUtilities.Clamp(point.X, 0, Math.Max(_presenter.Bounds.Width - 1, 0)),
  1369. MathUtilities.Clamp(point.Y, 0, Math.Max(_presenter.Bounds.Height - 1, 0)));
  1370. var previousIndex = _presenter.CaretIndex;
  1371. _presenter.MoveCaretToPoint(point);
  1372. var caretIndex = _presenter.CaretIndex;
  1373. if (Math.Abs(caretIndex - previousIndex) == 1)
  1374. e.PreventGestureRecognition();
  1375. if (e.Pointer.Type == PointerType.Mouse)
  1376. {
  1377. var selectionStart = SelectionStart;
  1378. var selectionEnd = SelectionEnd;
  1379. if (_wordSelectionStart >= 0)
  1380. {
  1381. UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
  1382. SetCurrentValue(SelectionStartProperty, selectionStart);
  1383. SetCurrentValue(SelectionEndProperty, selectionEnd);
  1384. }
  1385. else
  1386. {
  1387. SetCurrentValue(SelectionEndProperty, caretIndex);
  1388. }
  1389. }
  1390. else
  1391. {
  1392. SetCurrentValue(SelectionStartProperty, caretIndex);
  1393. SetCurrentValue(SelectionEndProperty, caretIndex);
  1394. }
  1395. }
  1396. }
  1397. private void UpdateWordSelectionRange(int caretIndex, ref int selectionStart, ref int selectionEnd)
  1398. {
  1399. var text = Text;
  1400. if (string.IsNullOrEmpty(text))
  1401. {
  1402. return;
  1403. }
  1404. if (caretIndex > _wordSelectionStart)
  1405. {
  1406. var nextWord = StringUtils.NextWord(text, caretIndex);
  1407. selectionEnd = nextWord;
  1408. selectionStart = _wordSelectionStart;
  1409. }
  1410. else
  1411. {
  1412. var previousWord = StringUtils.PreviousWord(text, caretIndex);
  1413. selectionStart = previousWord;
  1414. selectionEnd = StringUtils.NextWord(text, _wordSelectionStart);
  1415. }
  1416. }
  1417. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  1418. {
  1419. if (_presenter == null)
  1420. {
  1421. return;
  1422. }
  1423. if (e.Pointer.Captured != _presenter)
  1424. {
  1425. return;
  1426. }
  1427. if (e.Pointer.Type != PointerType.Mouse && !_isDoubleTapped)
  1428. {
  1429. var text = Text;
  1430. var clickInfo = e.GetCurrentPoint(this);
  1431. if (text != null && !(clickInfo.Pointer?.Captured is Border))
  1432. {
  1433. var point = e.GetPosition(_presenter);
  1434. _presenter.MoveCaretToPoint(point);
  1435. var caretIndex = _presenter.CaretIndex;
  1436. var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift);
  1437. var selectionStart = SelectionStart;
  1438. var selectionEnd = SelectionEnd;
  1439. if (clickToSelect)
  1440. {
  1441. if (_wordSelectionStart >= 0)
  1442. {
  1443. UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
  1444. SetCurrentValue(SelectionStartProperty, selectionStart);
  1445. SetCurrentValue(SelectionEndProperty, selectionEnd);
  1446. }
  1447. else
  1448. {
  1449. SetCurrentValue(SelectionEndProperty, caretIndex);
  1450. }
  1451. }
  1452. else
  1453. {
  1454. SetCurrentValue(SelectionStartProperty, caretIndex);
  1455. SetCurrentValue(SelectionEndProperty, caretIndex);
  1456. _wordSelectionStart = -1;
  1457. }
  1458. _presenter.TextSelectionHandleCanvas?.MoveHandlesToSelection();
  1459. }
  1460. }
  1461. // Don't update selection if the pointer was held
  1462. if (_isHolding)
  1463. {
  1464. _isHolding = false;
  1465. }
  1466. else if (e.InitialPressMouseButton == MouseButton.Right)
  1467. {
  1468. var point = e.GetPosition(_presenter);
  1469. _presenter.MoveCaretToPoint(point);
  1470. var caretIndex = _presenter.CaretIndex;
  1471. // see if mouse clicked inside current selection
  1472. // if it did not, we change the selection to where the user clicked
  1473. var firstSelection = Math.Min(SelectionStart, SelectionEnd);
  1474. var lastSelection = Math.Max(SelectionStart, SelectionEnd);
  1475. var didClickInSelection = SelectionStart != SelectionEnd &&
  1476. caretIndex >= firstSelection && caretIndex <= lastSelection;
  1477. if (!didClickInSelection)
  1478. {
  1479. SetCurrentValue(CaretIndexProperty, caretIndex);
  1480. SetCurrentValue(SelectionEndProperty, caretIndex);
  1481. SetCurrentValue(SelectionStartProperty, caretIndex);
  1482. }
  1483. }
  1484. else if (e.Pointer.Type == PointerType.Touch)
  1485. {
  1486. if (_currentClickCount == 1)
  1487. {
  1488. var point = e.GetPosition(_presenter);
  1489. _presenter.MoveCaretToPoint(point);
  1490. var caretIndex = _presenter.CaretIndex;
  1491. SetCurrentValue(SelectionStartProperty, caretIndex);
  1492. SetCurrentValue(SelectionEndProperty, caretIndex);
  1493. }
  1494. if(SelectionStart != SelectionEnd)
  1495. {
  1496. _presenter.TextSelectionHandleCanvas?.ShowContextMenu();
  1497. }
  1498. }
  1499. e.Pointer.Capture(null);
  1500. }
  1501. protected override AutomationPeer OnCreateAutomationPeer()
  1502. {
  1503. return new TextBoxAutomationPeer(this);
  1504. }
  1505. protected override void UpdateDataValidation(
  1506. AvaloniaProperty property,
  1507. BindingValueType state,
  1508. Exception? error)
  1509. {
  1510. if (property == TextProperty)
  1511. {
  1512. DataValidationErrors.SetError(this, error);
  1513. }
  1514. }
  1515. internal static int CoerceCaretIndex(AvaloniaObject sender, int value)
  1516. {
  1517. var text = sender.GetValue(TextProperty); // method also used by TextPresenter and SelectableTextBlock
  1518. if (text == null)
  1519. {
  1520. return 0;
  1521. }
  1522. var length = text.Length;
  1523. if (value < 0)
  1524. {
  1525. return 0;
  1526. }
  1527. else if (value > length)
  1528. {
  1529. return length;
  1530. }
  1531. else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
  1532. {
  1533. return value + 1;
  1534. }
  1535. else
  1536. {
  1537. return value;
  1538. }
  1539. }
  1540. /// <summary>
  1541. /// Clears the text in the TextBox
  1542. /// </summary>
  1543. public void Clear() => SetCurrentValue(TextProperty, string.Empty);
  1544. private void MoveHorizontal(int direction, bool wholeWord, bool isSelecting, bool moveCaretPosition)
  1545. {
  1546. if (_presenter == null)
  1547. {
  1548. return;
  1549. }
  1550. var text = Text ?? string.Empty;
  1551. var selectionStart = SelectionStart;
  1552. var selectionEnd = SelectionEnd;
  1553. if (!wholeWord)
  1554. {
  1555. if (isSelecting)
  1556. {
  1557. _presenter.MoveCaretToTextPosition(selectionEnd);
  1558. _presenter.MoveCaretHorizontal(direction > 0 ?
  1559. LogicalDirection.Forward :
  1560. LogicalDirection.Backward);
  1561. SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
  1562. }
  1563. else
  1564. {
  1565. if (selectionStart != selectionEnd)
  1566. {
  1567. _presenter.MoveCaretToTextPosition(direction > 0 ?
  1568. Math.Max(selectionStart, selectionEnd) :
  1569. Math.Min(selectionStart, selectionEnd));
  1570. }
  1571. else
  1572. {
  1573. _presenter.MoveCaretHorizontal(direction > 0 ?
  1574. LogicalDirection.Forward :
  1575. LogicalDirection.Backward);
  1576. }
  1577. SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
  1578. }
  1579. }
  1580. else
  1581. {
  1582. int offset;
  1583. if (direction > 0)
  1584. {
  1585. offset = StringUtils.NextWord(text, selectionEnd) - selectionEnd;
  1586. }
  1587. else
  1588. {
  1589. offset = StringUtils.PreviousWord(text, selectionEnd) - selectionEnd;
  1590. }
  1591. SetCurrentValue(SelectionEndProperty, SelectionEnd + offset);
  1592. if (moveCaretPosition)
  1593. {
  1594. _presenter.MoveCaretToTextPosition(SelectionEnd);
  1595. }
  1596. if (!isSelecting && moveCaretPosition)
  1597. {
  1598. SetCurrentValue(CaretIndexProperty, SelectionEnd);
  1599. }
  1600. else
  1601. {
  1602. SetCurrentValue(SelectionStartProperty, selectionStart);
  1603. }
  1604. }
  1605. }
  1606. private void MoveHome(bool document)
  1607. {
  1608. if (_presenter is null)
  1609. {
  1610. return;
  1611. }
  1612. var caretIndex = CaretIndex;
  1613. if (document)
  1614. {
  1615. _presenter.MoveCaretToTextPosition(0);
  1616. }
  1617. else
  1618. {
  1619. var textLines = _presenter.TextLayout.TextLines;
  1620. var lineIndex = _presenter.TextLayout.GetLineIndexFromCharacterIndex(caretIndex, false);
  1621. var textLine = textLines[lineIndex];
  1622. _presenter.MoveCaretToTextPosition(textLine.FirstTextSourceIndex);
  1623. }
  1624. }
  1625. private void MoveEnd(bool document)
  1626. {
  1627. if (_presenter is null)
  1628. {
  1629. return;
  1630. }
  1631. var text = Text ?? string.Empty;
  1632. var caretIndex = CaretIndex;
  1633. if (document)
  1634. {
  1635. _presenter.MoveCaretToTextPosition(text.Length, true);
  1636. }
  1637. else
  1638. {
  1639. var textLines = _presenter.TextLayout.TextLines;
  1640. var lineIndex = _presenter.TextLayout.GetLineIndexFromCharacterIndex(caretIndex, false);
  1641. var textLine = textLines[lineIndex];
  1642. var textPosition = textLine.FirstTextSourceIndex + textLine.Length - textLine.NewLineLength;
  1643. _presenter.MoveCaretToTextPosition(textPosition, true);
  1644. }
  1645. }
  1646. private void MovePageRight()
  1647. {
  1648. _scrollViewer?.PageRight();
  1649. }
  1650. private void MovePageLeft()
  1651. {
  1652. _scrollViewer?.PageLeft();
  1653. }
  1654. private void MovePageUp()
  1655. {
  1656. _scrollViewer?.PageUp();
  1657. }
  1658. private void MovePageDown()
  1659. {
  1660. _scrollViewer?.PageDown();
  1661. }
  1662. /// <summary>
  1663. /// Scroll the <see cref="TextBox"/> to the specified line index.
  1664. /// </summary>
  1665. /// <param name="lineIndex">The line index to scroll to.</param>
  1666. /// <exception cref="ArgumentOutOfRangeException"><paramref name="lineIndex"/> is less than zero. -or - <paramref name="lineIndex"/> is larger than or equal to the line count.</exception>
  1667. public void ScrollToLine(int lineIndex)
  1668. {
  1669. if (_presenter is null)
  1670. {
  1671. return;
  1672. }
  1673. if (lineIndex < 0 || lineIndex >= _presenter.TextLayout.TextLines.Count)
  1674. {
  1675. throw new ArgumentOutOfRangeException(nameof(lineIndex));
  1676. }
  1677. var textLine = _presenter.TextLayout.TextLines[lineIndex];
  1678. _presenter.MoveCaretToTextPosition(textLine.FirstTextSourceIndex);
  1679. }
  1680. /// <summary>
  1681. /// Select all text in the TextBox
  1682. /// </summary>
  1683. public void SelectAll()
  1684. {
  1685. SetCurrentValue(SelectionStartProperty, 0);
  1686. SetCurrentValue(SelectionEndProperty, Text?.Length ?? 0);
  1687. }
  1688. private (int start, int end) GetSelectionRange()
  1689. {
  1690. var selectionStart = SelectionStart;
  1691. var selectionEnd = SelectionEnd;
  1692. return (Math.Min(selectionStart, selectionEnd), Math.Max(selectionStart, selectionEnd));
  1693. }
  1694. internal bool DeleteSelection()
  1695. {
  1696. if (IsReadOnly)
  1697. return true;
  1698. var (start, end) = GetSelectionRange();
  1699. if (start != end)
  1700. {
  1701. var text = Text!;
  1702. var textBuilder = StringBuilderCache.Acquire(text.Length);
  1703. textBuilder.Append(text);
  1704. textBuilder.Remove(start, end - start);
  1705. SetCurrentValue(TextProperty, textBuilder.ToString());
  1706. _presenter?.MoveCaretToTextPosition(start);
  1707. SetCurrentValue(SelectionStartProperty, start);
  1708. ClearSelection();
  1709. return true;
  1710. }
  1711. SetCurrentValue(CaretIndexProperty, SelectionStart);
  1712. return false;
  1713. }
  1714. private string GetSelection()
  1715. {
  1716. var text = Text;
  1717. if (string.IsNullOrEmpty(text))
  1718. {
  1719. return "";
  1720. }
  1721. var selectionStart = SelectionStart;
  1722. var selectionEnd = SelectionEnd;
  1723. var start = Math.Min(selectionStart, selectionEnd);
  1724. var end = Math.Max(selectionStart, selectionEnd);
  1725. if (start == end || (Text?.Length ?? 0) < end)
  1726. {
  1727. return "";
  1728. }
  1729. return text.Substring(start, end - start);
  1730. }
  1731. /// <summary>
  1732. /// Returns the sum of any vertical whitespace added between the <see cref="ScrollViewer"/> and <see cref="TextPresenter"/> in the control template.
  1733. /// </summary>
  1734. /// <returns>The total vertical whitespace.</returns>
  1735. private double GetVerticalSpaceBetweenScrollViewerAndPresenter()
  1736. {
  1737. var verticalSpace = 0.0;
  1738. if (_presenter != null)
  1739. {
  1740. Visual? visual = _presenter;
  1741. while ((visual != null) && (visual != this))
  1742. {
  1743. if (visual == _scrollViewer)
  1744. {
  1745. // ScrollViewer is a stopping point and should only include the Padding
  1746. verticalSpace += _scrollViewer.Padding.Top + _scrollViewer.Padding.Bottom;
  1747. break;
  1748. }
  1749. var margin = visual.GetValue<Thickness>(Layoutable.MarginProperty);
  1750. var padding = visual.GetValue<Thickness>(Decorator.PaddingProperty);
  1751. verticalSpace += margin.Top + padding.Top + padding.Bottom + margin.Bottom;
  1752. visual = visual.VisualParent;
  1753. }
  1754. }
  1755. return verticalSpace;
  1756. }
  1757. /// <summary>
  1758. /// Raises both the <see cref="TextChanging"/> and <see cref="TextChanged"/> events.
  1759. /// </summary>
  1760. /// <remarks>
  1761. /// This must be called after the <see cref="Text"/> property is set.
  1762. /// </remarks>
  1763. private void RaiseTextChangeEvents()
  1764. {
  1765. // Note the following sequence of these events (following WinUI)
  1766. // 1. TextChanging occurs synchronously when text starts to change but before it is rendered.
  1767. // This occurs after the Text property is set.
  1768. // 2. TextChanged occurs asynchronously after text changes and the new text is rendered.
  1769. var textChangingEventArgs = new TextChangingEventArgs(TextChangingEvent);
  1770. RaiseEvent(textChangingEventArgs);
  1771. Dispatcher.UIThread.Post(() =>
  1772. {
  1773. var textChangedEventArgs = new TextChangedEventArgs(TextChangedEvent);
  1774. RaiseEvent(textChangedEventArgs);
  1775. }, DispatcherPriority.Normal);
  1776. }
  1777. private void SetSelectionForControlBackspace()
  1778. {
  1779. var text = Text ?? string.Empty;
  1780. var selectionStart = CaretIndex;
  1781. MoveHorizontal(-1, true, false, false);
  1782. if (SelectionEnd > 0 &&
  1783. selectionStart < text.Length && text[selectionStart] == ' ')
  1784. {
  1785. SetCurrentValue(SelectionEndProperty, SelectionEnd - 1);
  1786. }
  1787. SetCurrentValue(SelectionStartProperty, selectionStart);
  1788. }
  1789. private void SetSelectionForControlDelete()
  1790. {
  1791. var textLength = Text?.Length ?? 0;
  1792. if (_presenter == null || textLength == 0)
  1793. {
  1794. return;
  1795. }
  1796. SetCurrentValue(SelectionStartProperty, CaretIndex);
  1797. MoveHorizontal(1, true, true, false);
  1798. if (SelectionEnd < textLength && Text![SelectionEnd] == ' ')
  1799. {
  1800. SetCurrentValue(SelectionEndProperty, SelectionEnd + 1);
  1801. }
  1802. }
  1803. private void UpdatePseudoclasses()
  1804. {
  1805. PseudoClasses.Set(":empty", string.IsNullOrEmpty(Text));
  1806. }
  1807. private bool IsPasswordBox => PasswordChar != default(char);
  1808. UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
  1809. {
  1810. get => new UndoRedoState(Text, CaretIndex);
  1811. set
  1812. {
  1813. SetCurrentValue(TextProperty, value.Text);
  1814. SetCurrentValue(CaretIndexProperty, value.CaretPosition);
  1815. ClearSelection();
  1816. }
  1817. }
  1818. private void SnapshotUndoRedo(bool ignoreChangeCount = true)
  1819. {
  1820. if (IsUndoEnabled)
  1821. {
  1822. if (ignoreChangeCount ||
  1823. !_hasDoneSnapshotOnce ||
  1824. (!ignoreChangeCount &&
  1825. _selectedTextChangesMadeSinceLastUndoSnapshot >= _maxCharsBeforeUndoSnapshot))
  1826. {
  1827. _undoRedoHelper.Snapshot();
  1828. _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
  1829. _hasDoneSnapshotOnce = true;
  1830. }
  1831. }
  1832. }
  1833. /// <summary>
  1834. /// Undoes the first action in the undo stack
  1835. /// </summary>
  1836. public void Undo()
  1837. {
  1838. if (IsUndoEnabled && CanUndo)
  1839. {
  1840. try
  1841. {
  1842. // Snapshot the current Text state - this will get popped on to the redo stack
  1843. // when we call undo below
  1844. SnapshotUndoRedo();
  1845. _isUndoingRedoing = true;
  1846. _undoRedoHelper.Undo();
  1847. }
  1848. finally
  1849. {
  1850. _isUndoingRedoing = false;
  1851. }
  1852. }
  1853. }
  1854. /// <summary>
  1855. /// Reapplies the first item on the redo stack
  1856. /// </summary>
  1857. public void Redo()
  1858. {
  1859. if (IsUndoEnabled && CanRedo)
  1860. {
  1861. try
  1862. {
  1863. _isUndoingRedoing = true;
  1864. _undoRedoHelper.Redo();
  1865. }
  1866. finally
  1867. {
  1868. _isUndoingRedoing = false;
  1869. }
  1870. }
  1871. }
  1872. /// <summary>
  1873. /// Called from the UndoRedoHelper when the undo stack is modified
  1874. /// </summary>
  1875. void UndoRedoHelper<UndoRedoState>.IUndoRedoHost.OnUndoStackChanged()
  1876. {
  1877. CanUndo = _undoRedoHelper.CanUndo;
  1878. }
  1879. /// <summary>
  1880. /// Called from the UndoRedoHelper when the redo stack is modified
  1881. /// </summary>
  1882. void UndoRedoHelper<UndoRedoState>.IUndoRedoHost.OnRedoStackChanged()
  1883. {
  1884. CanRedo = _undoRedoHelper.CanRedo;
  1885. }
  1886. protected override Size MeasureOverride(Size availableSize)
  1887. {
  1888. if(_scrollViewer != null)
  1889. {
  1890. var maxHeight = double.PositiveInfinity;
  1891. if (MaxLines > 0 && double.IsNaN(Height))
  1892. {
  1893. var fontSize = FontSize;
  1894. var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
  1895. var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
  1896. var textLayout = new TextLayout(new LineTextSource(MaxLines), paragraphProperties);
  1897. var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();
  1898. maxHeight = Math.Ceiling(textLayout.Height + verticalSpace);
  1899. }
  1900. _scrollViewer.SetCurrentValue(MaxHeightProperty, maxHeight);
  1901. var minHeight = 0.0;
  1902. if (MinLines > 0 && double.IsNaN(Height))
  1903. {
  1904. var fontSize = FontSize;
  1905. var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
  1906. var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
  1907. var textLayout = new TextLayout(new LineTextSource(MinLines), paragraphProperties);
  1908. var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();
  1909. minHeight = Math.Ceiling(textLayout.Height + verticalSpace);
  1910. }
  1911. _scrollViewer.SetCurrentValue(MinHeightProperty, minHeight);
  1912. }
  1913. return base.MeasureOverride(availableSize);
  1914. }
  1915. private class LineTextSource : ITextSource
  1916. {
  1917. private readonly int _lines;
  1918. public LineTextSource(int lines)
  1919. {
  1920. _lines = lines;
  1921. }
  1922. public TextRun? GetTextRun(int textSourceIndex)
  1923. {
  1924. if (textSourceIndex >= _lines)
  1925. {
  1926. return null;
  1927. }
  1928. return new TextEndOfLine(1);
  1929. }
  1930. }
  1931. }
  1932. }