| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288 |
- using Avalonia.Input.Platform;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Avalonia.Reactive;
- using Avalonia.Controls.Presenters;
- using Avalonia.Controls.Primitives;
- using Avalonia.Controls.Utils;
- using Avalonia.Input;
- using Avalonia.Interactivity;
- using Avalonia.Media;
- using Avalonia.Metadata;
- using Avalonia.Data;
- using Avalonia.Layout;
- using Avalonia.Utilities;
- using Avalonia.Controls.Metadata;
- using Avalonia.Media.TextFormatting;
- using Avalonia.Automation.Peers;
- using Avalonia.Threading;
- namespace Avalonia.Controls
- {
- /// <summary>
- /// Represents a control that can be used to display or edit unformatted text.
- /// </summary>
- [TemplatePart("PART_TextPresenter", typeof(TextPresenter))]
- [TemplatePart("PART_ScrollViewer", typeof(ScrollViewer))]
- [PseudoClasses(":empty")]
- public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
- {
- /// <summary>
- /// Gets a platform-specific <see cref="KeyGesture"/> for the Cut action
- /// </summary>
- public static KeyGesture? CutGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Cut.FirstOrDefault();
- /// <summary>
- /// Gets a platform-specific <see cref="KeyGesture"/> for the Copy action
- /// </summary>
- public static KeyGesture? CopyGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Copy.FirstOrDefault();
- /// <summary>
- /// Gets a platform-specific <see cref="KeyGesture"/> for the Paste action
- /// </summary>
- public static KeyGesture? PasteGesture => Application.Current?.PlatformSettings?.HotkeyConfiguration.Paste.FirstOrDefault();
- /// <summary>
- /// Defines the <see cref="AcceptsReturn"/> property
- /// </summary>
- public static readonly StyledProperty<bool> AcceptsReturnProperty =
- AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
- /// <summary>
- /// Defines the <see cref="AcceptsTab"/> property
- /// </summary>
- public static readonly StyledProperty<bool> AcceptsTabProperty =
- AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
- /// <summary>
- /// Defines the <see cref="CaretIndex"/> property
- /// </summary>
- public static readonly StyledProperty<int> CaretIndexProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(CaretIndex),
- coerce: CoerceCaretIndex);
- /// <summary>
- /// Defines the <see cref="IsReadOnly"/> property
- /// </summary>
- public static readonly StyledProperty<bool> IsReadOnlyProperty =
- AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
- /// <summary>
- /// Defines the <see cref="PasswordChar"/> property
- /// </summary>
- public static readonly StyledProperty<char> PasswordCharProperty =
- AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
- /// <summary>
- /// Defines the <see cref="SelectionBrush"/> property
- /// </summary>
- public static readonly StyledProperty<IBrush?> SelectionBrushProperty =
- AvaloniaProperty.Register<TextBox, IBrush?>(nameof(SelectionBrush));
- /// <summary>
- /// Defines the <see cref="SelectionForegroundBrush"/> property
- /// </summary>
- public static readonly StyledProperty<IBrush?> SelectionForegroundBrushProperty =
- AvaloniaProperty.Register<TextBox, IBrush?>(nameof(SelectionForegroundBrush));
- /// <summary>
- /// Defines the <see cref="CaretBrush"/> property
- /// </summary>
- public static readonly StyledProperty<IBrush?> CaretBrushProperty =
- AvaloniaProperty.Register<TextBox, IBrush?>(nameof(CaretBrush));
- /// <summary>
- /// Defines the <see cref="CaretBlinkInterval"/> property
- /// </summary>
- public static readonly StyledProperty<TimeSpan> CaretBlinkIntervalProperty =
- AvaloniaProperty.Register<TextBox, TimeSpan>(nameof(CaretBlinkInterval), defaultValue: TimeSpan.FromMilliseconds(500));
- /// <summary>
- /// Defines the <see cref="SelectionStart"/> property
- /// </summary>
- public static readonly StyledProperty<int> SelectionStartProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(SelectionStart),
- coerce: CoerceCaretIndex);
- /// <summary>
- /// Defines the <see cref="SelectionEnd"/> property
- /// </summary>
- public static readonly StyledProperty<int> SelectionEndProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(SelectionEnd),
- coerce: CoerceCaretIndex);
- /// <summary>
- /// Defines the <see cref="MaxLength"/> property
- /// </summary>
- public static readonly StyledProperty<int> MaxLengthProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength));
- /// <summary>
- /// Defines the <see cref="MaxLines"/> property
- /// </summary>
- public static readonly StyledProperty<int> MaxLinesProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(MaxLines));
- /// <summary>
- /// Defines the <see cref="MinLines"/> property
- /// </summary>
- public static readonly StyledProperty<int> MinLinesProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(MinLines));
- /// <summary>
- /// Defines the <see cref="Text"/> property
- /// </summary>
- public static readonly StyledProperty<string?> TextProperty =
- TextBlock.TextProperty.AddOwner<TextBox>(new(
- coerce: CoerceText,
- defaultBindingMode: BindingMode.TwoWay,
- enableDataValidation: true));
- /// <summary>
- /// Defines the <see cref="TextAlignment"/> property
- /// </summary>
- public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
- TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
- /// <summary>
- /// Defines the <see cref="HorizontalAlignment"/> property.
- /// </summary>
- public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
- ContentControl.HorizontalContentAlignmentProperty.AddOwner<TextBox>();
- /// <summary>
- /// Defines the <see cref="VerticalAlignment"/> property.
- /// </summary>
- public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
- ContentControl.VerticalContentAlignmentProperty.AddOwner<TextBox>();
- public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
- TextBlock.TextWrappingProperty.AddOwner<TextBox>();
- /// <summary>
- /// Defines see <see cref="TextPresenter.LineHeight"/> property.
- /// </summary>
- public static readonly StyledProperty<double> LineHeightProperty =
- TextBlock.LineHeightProperty.AddOwner<TextBox>(new(defaultValue: double.NaN));
- /// <summary>
- /// Defines see <see cref="TextBlock.LetterSpacing"/> property.
- /// </summary>
- public static readonly StyledProperty<double> LetterSpacingProperty =
- TextBlock.LetterSpacingProperty.AddOwner<TextBox>();
- /// <summary>
- /// Defines the <see cref="Watermark"/> property
- /// </summary>
- public static readonly StyledProperty<string?> WatermarkProperty =
- AvaloniaProperty.Register<TextBox, string?>(nameof(Watermark));
- /// <summary>
- /// Defines the <see cref="UseFloatingWatermark"/> property
- /// </summary>
- public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
- AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
- /// <summary>
- /// Defines the <see cref="NewLine"/> property
- /// </summary>
- public static readonly StyledProperty<string> NewLineProperty =
- AvaloniaProperty.Register<TextBox, string>(nameof(NewLine), Environment.NewLine);
- /// <summary>
- /// Defines the <see cref="InnerLeftContent"/> property
- /// </summary>
- public static readonly StyledProperty<object> InnerLeftContentProperty =
- AvaloniaProperty.Register<TextBox, object>(nameof(InnerLeftContent));
- /// <summary>
- /// Defines the <see cref="InnerRightContent"/> property
- /// </summary>
- public static readonly StyledProperty<object> InnerRightContentProperty =
- AvaloniaProperty.Register<TextBox, object>(nameof(InnerRightContent));
- /// <summary>
- /// Defines the <see cref="RevealPassword"/> property
- /// </summary>
- public static readonly StyledProperty<bool> RevealPasswordProperty =
- AvaloniaProperty.Register<TextBox, bool>(nameof(RevealPassword));
- /// <summary>
- /// Defines the <see cref="CanCut"/> property
- /// </summary>
- public static readonly DirectProperty<TextBox, bool> CanCutProperty =
- AvaloniaProperty.RegisterDirect<TextBox, bool>(
- nameof(CanCut),
- o => o.CanCut);
- /// <summary>
- /// Defines the <see cref="CanCopy"/> property
- /// </summary>
- public static readonly DirectProperty<TextBox, bool> CanCopyProperty =
- AvaloniaProperty.RegisterDirect<TextBox, bool>(
- nameof(CanCopy),
- o => o.CanCopy);
- /// <summary>
- /// Defines the <see cref="CanPaste"/> property
- /// </summary>
- public static readonly DirectProperty<TextBox, bool> CanPasteProperty =
- AvaloniaProperty.RegisterDirect<TextBox, bool>(
- nameof(CanPaste),
- o => o.CanPaste);
- /// <summary>
- /// Defines the <see cref="IsUndoEnabled"/> property
- /// </summary>
- public static readonly StyledProperty<bool> IsUndoEnabledProperty =
- AvaloniaProperty.Register<TextBox, bool>(
- nameof(IsUndoEnabled),
- defaultValue: true);
- /// <summary>
- /// Defines the <see cref="UndoLimit"/> property
- /// </summary>
- public static readonly StyledProperty<int> UndoLimitProperty =
- AvaloniaProperty.Register<TextBox, int>(nameof(UndoLimit), UndoRedoHelper<UndoRedoState>.DefaultUndoLimit);
- /// <summary>
- /// Defines the <see cref="CanUndo"/> property
- /// </summary>
- public static readonly DirectProperty<TextBox, bool> CanUndoProperty =
- AvaloniaProperty.RegisterDirect<TextBox, bool>(nameof(CanUndo), x => x.CanUndo);
- /// <summary>
- /// Defines the <see cref="CanRedo"/> property
- /// </summary>
- public static readonly DirectProperty<TextBox, bool> CanRedoProperty =
- AvaloniaProperty.RegisterDirect<TextBox, bool>(nameof(CanRedo), x => x.CanRedo);
- /// <summary>
- /// Defines the <see cref="CopyingToClipboard"/> event.
- /// </summary>
- public static readonly RoutedEvent<RoutedEventArgs> CopyingToClipboardEvent =
- RoutedEvent.Register<TextBox, RoutedEventArgs>(
- nameof(CopyingToClipboard), RoutingStrategies.Bubble);
- /// <summary>
- /// Defines the <see cref="CuttingToClipboard"/> event.
- /// </summary>
- public static readonly RoutedEvent<RoutedEventArgs> CuttingToClipboardEvent =
- RoutedEvent.Register<TextBox, RoutedEventArgs>(
- nameof(CuttingToClipboard), RoutingStrategies.Bubble);
- /// <summary>
- /// Defines the <see cref="PastingFromClipboard"/> event.
- /// </summary>
- public static readonly RoutedEvent<RoutedEventArgs> PastingFromClipboardEvent =
- RoutedEvent.Register<TextBox, RoutedEventArgs>(
- nameof(PastingFromClipboard), RoutingStrategies.Bubble);
- /// <summary>
- /// Defines the <see cref="TextChanged"/> event.
- /// </summary>
- public static readonly RoutedEvent<TextChangedEventArgs> TextChangedEvent =
- RoutedEvent.Register<TextBox, TextChangedEventArgs>(
- nameof(TextChanged), RoutingStrategies.Bubble);
- /// <summary>
- /// Defines the <see cref="TextChanging"/> event.
- /// </summary>
- public static readonly RoutedEvent<TextChangingEventArgs> TextChangingEvent =
- RoutedEvent.Register<TextBox, TextChangingEventArgs>(
- nameof(TextChanging), RoutingStrategies.Bubble);
- /// <summary>
- /// Stores the state information for available actions in the UndoRedoHelper
- /// </summary>
- readonly struct UndoRedoState : IEquatable<UndoRedoState>
- {
- public string? Text { get; }
- public int CaretPosition { get; }
- public UndoRedoState(string? text, int caretPosition)
- {
- Text = text;
- CaretPosition = caretPosition;
- }
- public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
- public override bool Equals(object? obj) => obj is UndoRedoState other && Equals(other);
- public override int GetHashCode() => Text?.GetHashCode() ?? 0;
- }
- private TextPresenter? _presenter;
- private ScrollViewer? _scrollViewer;
- private readonly TextBoxTextInputMethodClient _imClient = new();
- private readonly UndoRedoHelper<UndoRedoState> _undoRedoHelper;
- private bool _isUndoingRedoing;
- private bool _canCut;
- private bool _canCopy;
- private bool _canPaste;
- private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
- private bool _canUndo;
- private bool _canRedo;
- private int _wordSelectionStart = -1;
- private int _selectedTextChangesMadeSinceLastUndoSnapshot;
- private bool _hasDoneSnapshotOnce;
- private static bool _isHolding;
- private int _currentClickCount;
- private bool _isDoubleTapped;
- private const int _maxCharsBeforeUndoSnapshot = 7;
- static TextBox()
- {
- FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
- TextInputMethodClientRequestedEvent.AddClassHandler<TextBox>((tb, e) =>
- {
- if (!tb.IsReadOnly)
- {
- e.Client = tb._imClient;
- }
- });
- }
- public TextBox()
- {
- var horizontalScrollBarVisibility = Observable.CombineLatest(
- this.GetObservable(AcceptsReturnProperty),
- this.GetObservable(TextWrappingProperty),
- (acceptsReturn, wrapping) =>
- {
- if (wrapping != TextWrapping.NoWrap)
- {
- return ScrollBarVisibility.Disabled;
- }
- return acceptsReturn ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden;
- });
- this.Bind(
- ScrollViewer.HorizontalScrollBarVisibilityProperty,
- horizontalScrollBarVisibility,
- BindingPriority.Style);
- _undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
- _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
- _hasDoneSnapshotOnce = false;
- UpdatePseudoclasses();
- }
- /// <summary>
- /// Gets or sets a value that determines whether the TextBox allows and displays newline or return characters
- /// </summary>
- public bool AcceptsReturn
- {
- get => GetValue(AcceptsReturnProperty);
- set => SetValue(AcceptsReturnProperty, value);
- }
- /// <summary>
- /// Gets or sets a value that determins whether the TextBox allows and displays tabs
- /// </summary>
- public bool AcceptsTab
- {
- get => GetValue(AcceptsTabProperty);
- set => SetValue(AcceptsTabProperty, value);
- }
- /// <summary>
- /// Gets or sets the index of the text caret
- /// </summary>
- public int CaretIndex
- {
- get => GetValue(CaretIndexProperty);
- set => SetValue(CaretIndexProperty, value);
- }
- private void OnCaretIndexChanged(AvaloniaPropertyChangedEventArgs e)
- {
- UndoRedoState state;
- if (IsUndoEnabled && _undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
- _undoRedoHelper.UpdateLastState();
- var newValue = e.GetNewValue<int>();
- SetCurrentValue(SelectionStartProperty, newValue);
- SetCurrentValue(SelectionEndProperty, newValue);
- }
- /// <summary>
- /// Gets or sets a value whether this TextBox is read-only
- /// </summary>
- public bool IsReadOnly
- {
- get => GetValue(IsReadOnlyProperty);
- set => SetValue(IsReadOnlyProperty, value);
- }
- /// <summary>
- /// Gets or sets the <see cref="char"/> that should be used for password masking
- /// </summary>
- public char PasswordChar
- {
- get => GetValue(PasswordCharProperty);
- set => SetValue(PasswordCharProperty, value);
- }
- /// <summary>
- /// Gets or sets a brush that is used to highlight selected text
- /// </summary>
- public IBrush? SelectionBrush
- {
- get => GetValue(SelectionBrushProperty);
- set => SetValue(SelectionBrushProperty, value);
- }
- /// <summary>
- /// Gets or sets a brush that is used for the foreground of selected text
- /// </summary>
- public IBrush? SelectionForegroundBrush
- {
- get => GetValue(SelectionForegroundBrushProperty);
- set => SetValue(SelectionForegroundBrushProperty, value);
- }
- /// <summary>
- /// Gets or sets a brush that is used for the text caret
- /// </summary>
- public IBrush? CaretBrush
- {
- get => GetValue(CaretBrushProperty);
- set => SetValue(CaretBrushProperty, value);
- }
- /// <inheritdoc cref="TextPresenter.CaretBlinkInterval"/>
- public TimeSpan CaretBlinkInterval
- {
- get => GetValue(CaretBlinkIntervalProperty);
- set => SetValue(CaretBlinkIntervalProperty, value);
- }
- /// <summary>
- /// Gets or sets the starting position of the text selected in the TextBox
- /// </summary>
- public int SelectionStart
- {
- get => GetValue(SelectionStartProperty);
- set => SetValue(SelectionStartProperty, value);
- }
- private void OnSelectionStartChanged(AvaloniaPropertyChangedEventArgs e)
- {
- UpdateCommandStates();
- var value = e.GetNewValue<int>();
- if (SelectionEnd == value && CaretIndex != value)
- {
- SetCurrentValue(CaretIndexProperty, value);
- }
- }
- /// <summary>
- /// Gets or sets the end position of the text selected in the TextBox
- /// </summary>
- /// <remarks>
- /// When the SelectionEnd is equal to <see cref="SelectionStart"/>, there is no
- /// selected text and it marks the caret position
- /// </remarks>
- public int SelectionEnd
- {
- get => GetValue(SelectionEndProperty);
- set => SetValue(SelectionEndProperty, value);
- }
- private void OnSelectionEndChanged(AvaloniaPropertyChangedEventArgs e)
- {
- UpdateCommandStates();
- var value = e.GetNewValue<int>();
- if (SelectionStart == value && CaretIndex != value)
- {
- SetCurrentValue(CaretIndexProperty, value);
- }
- }
- /// <summary>
- /// Gets or sets the maximum number of characters that the <see cref="TextBox"/> can accept.
- /// This constraint only applies for manually entered (user-inputted) text.
- /// </summary>
- public int MaxLength
- {
- get => GetValue(MaxLengthProperty);
- set => SetValue(MaxLengthProperty, value);
- }
- /// <summary>
- /// Gets or sets the maximum number of visible lines to size to.
- /// </summary>
- public int MaxLines
- {
- get => GetValue(MaxLinesProperty);
- set => SetValue(MaxLinesProperty, value);
- }
- /// <summary>
- /// Gets or sets the minimum number of visible lines to size to.
- /// </summary>
- public int MinLines
- {
- get => GetValue(MinLinesProperty);
- set => SetValue(MinLinesProperty, value);
- }
- /// <summary>
- /// Gets or sets the spacing between characters
- /// </summary>
- public double LetterSpacing
- {
- get => GetValue(LetterSpacingProperty);
- set => SetValue(LetterSpacingProperty, value);
- }
- /// <summary>
- /// Gets or sets the line height.
- /// </summary>
- public double LineHeight
- {
- get => GetValue(LineHeightProperty);
- set => SetValue(LineHeightProperty, value);
- }
- /// <summary>
- /// Gets or sets the Text content of the TextBox
- /// </summary>
- [Content]
- public string? Text
- {
- get => GetValue(TextProperty);
- set => SetValue(TextProperty, value);
- }
- private static string? CoerceText(AvaloniaObject sender, string? value)
- {
- var textBox = (TextBox)sender;
- // Before #9490, snapshot here was done AFTER text change - this doesn't make sense
- // since intial state would never be no text and you'd always have to make a text
- // change before undo would be available
- // The undo/redo stacks were also cleared at this point, which also doesn't make sense
- // as it is still valid to want to undo a programmatic text set
- // So we snapshot text now BEFORE the change so we can always revert
- // Also don't need to check IsUndoEnabled here, that's done in SnapshotUndoRedo
- if (!textBox._isUndoingRedoing)
- {
- textBox.SnapshotUndoRedo();
- }
- return value;
- }
- /// <summary>
- /// Gets or sets the text selected in the TextBox
- /// </summary>
- public string SelectedText
- {
- get => GetSelection();
- set
- {
- if (string.IsNullOrEmpty(value))
- {
- _selectedTextChangesMadeSinceLastUndoSnapshot++;
- SnapshotUndoRedo(ignoreChangeCount: false);
- DeleteSelection();
- }
- else
- {
- HandleTextInput(value);
- }
- }
- }
- /// <summary>
- /// Gets or sets the horizontal alignment of the content within the control.
- /// </summary>
- public HorizontalAlignment HorizontalContentAlignment
- {
- get => GetValue(HorizontalContentAlignmentProperty);
- set => SetValue(HorizontalContentAlignmentProperty, value);
- }
- /// <summary>
- /// Gets or sets the vertical alignment of the content within the control.
- /// </summary>
- public VerticalAlignment VerticalContentAlignment
- {
- get => GetValue(VerticalContentAlignmentProperty);
- set => SetValue(VerticalContentAlignmentProperty, value);
- }
- /// <summary>
- /// Gets or sets the <see cref="Media.TextAlignment"/> of the TextBox
- /// </summary>
- public TextAlignment TextAlignment
- {
- get => GetValue(TextAlignmentProperty);
- set => SetValue(TextAlignmentProperty, value);
- }
- /// <summary>
- /// Gets or sets the placeholder or descriptive text that is displayed even if the <see cref="Text"/>
- /// property is not yet set.
- /// </summary>
- public string? Watermark
- {
- get => GetValue(WatermarkProperty);
- set => SetValue(WatermarkProperty, value);
- }
- /// <summary>
- /// Gets or sets a value indicating whether the <see cref="Watermark"/> will still be shown above the
- /// <see cref="Text"/> even after a text value is set.
- /// </summary>
- public bool UseFloatingWatermark
- {
- get => GetValue(UseFloatingWatermarkProperty);
- set => SetValue(UseFloatingWatermarkProperty, value);
- }
- /// <summary>
- /// Gets or sets custom content that is positioned on the left side of the text layout box
- /// </summary>
- public object InnerLeftContent
- {
- get => GetValue(InnerLeftContentProperty);
- set => SetValue(InnerLeftContentProperty, value);
- }
- /// <summary>
- /// Gets or sets custom content that is positioned on the right side of the text layout box
- /// </summary>
- public object InnerRightContent
- {
- get => GetValue(InnerRightContentProperty);
- set => SetValue(InnerRightContentProperty, value);
- }
- /// <summary>
- /// Gets or sets whether text masked by <see cref="PasswordChar"/> should be revealed
- /// </summary>
- public bool RevealPassword
- {
- get => GetValue(RevealPasswordProperty);
- set => SetValue(RevealPasswordProperty, value);
- }
- /// <summary>
- /// Gets or sets the <see cref="Media.TextWrapping"/> of the TextBox
- /// </summary>
- public TextWrapping TextWrapping
- {
- get => GetValue(TextWrappingProperty);
- set => SetValue(TextWrappingProperty, value);
- }
- /// <summary>
- /// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
- /// </summary>
- public string NewLine
- {
- get => GetValue(NewLineProperty);
- set => SetValue(NewLineProperty, value);
- }
- /// <summary>
- /// Clears the current selection, maintaining the <see cref="CaretIndex"/>
- /// </summary>
- public void ClearSelection()
- {
- SetCurrentValue(CaretIndexProperty, SelectionStart);
- SetCurrentValue(SelectionEndProperty, SelectionStart);
- }
- /// <summary>
- /// Property for determining if the Cut command can be executed.
- /// </summary>
- public bool CanCut
- {
- get => _canCut;
- private set => SetAndRaise(CanCutProperty, ref _canCut, value);
- }
- /// <summary>
- /// Property for determining if the Copy command can be executed.
- /// </summary>
- public bool CanCopy
- {
- get => _canCopy;
- private set => SetAndRaise(CanCopyProperty, ref _canCopy, value);
- }
- /// <summary>
- /// Property for determining if the Paste command can be executed.
- /// </summary>
- public bool CanPaste
- {
- get => _canPaste;
- private set => SetAndRaise(CanPasteProperty, ref _canPaste, value);
- }
- /// <summary>
- /// Property for determining whether undo/redo is enabled
- /// </summary>
- public bool IsUndoEnabled
- {
- get => GetValue(IsUndoEnabledProperty);
- set => SetValue(IsUndoEnabledProperty, value);
- }
- /// <summary>
- /// Gets or sets the maximum number of items that can reside in the Undo stack
- /// </summary>
- public int UndoLimit
- {
- get => GetValue(UndoLimitProperty);
- set => SetValue(UndoLimitProperty, value);
- }
- private void OnUndoLimitChanged(int newValue)
- {
- _undoRedoHelper.Limit = newValue;
- // from docs at
- // https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
- // "Setting UndoLimit clears the undo queue."
- _undoRedoHelper.Clear();
- _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
- _hasDoneSnapshotOnce = false;
- }
- /// <summary>
- /// Gets a value that indicates whether the undo stack has an action that can be undone
- /// </summary>
- public bool CanUndo
- {
- get => _canUndo;
- private set => SetAndRaise(CanUndoProperty, ref _canUndo, value);
- }
- /// <summary>
- /// Gets a value that indicates whether the redo stack has an action that can be redone
- /// </summary>
- public bool CanRedo
- {
- get => _canRedo;
- private set => SetAndRaise(CanRedoProperty, ref _canRedo, value);
- }
- /// <summary>
- /// Raised when content is being copied to the clipboard
- /// </summary>
- public event EventHandler<RoutedEventArgs>? CopyingToClipboard
- {
- add => AddHandler(CopyingToClipboardEvent, value);
- remove => RemoveHandler(CopyingToClipboardEvent, value);
- }
- /// <summary>
- /// Raised when content is being cut to the clipboard
- /// </summary>
- public event EventHandler<RoutedEventArgs>? CuttingToClipboard
- {
- add => AddHandler(CuttingToClipboardEvent, value);
- remove => RemoveHandler(CuttingToClipboardEvent, value);
- }
- /// <summary>
- /// Raised when content is being pasted from the clipboard
- /// </summary>
- public event EventHandler<RoutedEventArgs>? PastingFromClipboard
- {
- add => AddHandler(PastingFromClipboardEvent, value);
- remove => RemoveHandler(PastingFromClipboardEvent, value);
- }
- /// <summary>
- /// Occurs asynchronously after text changes and the new text is rendered.
- /// </summary>
- public event EventHandler<TextChangedEventArgs>? TextChanged
- {
- add => AddHandler(TextChangedEvent, value);
- remove => RemoveHandler(TextChangedEvent, value);
- }
- /// <summary>
- /// Occurs synchronously when text starts to change but before it is rendered.
- /// </summary>
- /// <remarks>
- /// This event occurs just after the <see cref="Text"/> property value has been updated.
- /// </remarks>
- public event EventHandler<TextChangingEventArgs>? TextChanging
- {
- add => AddHandler(TextChangingEvent, value);
- remove => RemoveHandler(TextChangingEvent, value);
- }
- protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
- {
- _presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
- if (_scrollViewer != null)
- {
- _scrollViewer.ScrollChanged -= ScrollViewer_ScrollChanged;
- }
- _scrollViewer = e.NameScope.Find<ScrollViewer>("PART_ScrollViewer");
- if(_scrollViewer != null)
- {
- _scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
- }
- _imClient.SetPresenter(_presenter, this);
- if (IsFocused)
- {
- _presenter?.ShowCaret();
- }
- }
- private void ScrollViewer_ScrollChanged(object? sender, ScrollChangedEventArgs e)
- {
- _presenter?.TextSelectionHandleCanvas?.MoveHandlesToSelection();
- }
- protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
- {
- base.OnAttachedToVisualTree(e);
- if (_presenter != null)
- {
- if (IsFocused)
- {
- _presenter.ShowCaret();
- }
- _presenter.PropertyChanged += PresenterPropertyChanged;
- }
- }
- protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
- {
- base.OnDetachedFromVisualTree(e);
- if (_presenter != null)
- {
- _presenter.HideCaret();
- _presenter.PropertyChanged -= PresenterPropertyChanged;
- }
- _imClient.SetPresenter(null, null);
- }
- private void PresenterPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
- {
- if(e.Property == TextPresenter.PreeditTextProperty)
- {
- if(string.IsNullOrEmpty(e.OldValue as string) && !string.IsNullOrEmpty(e.NewValue as string))
- {
- PseudoClasses.Set(":empty", false);
- DeleteSelection();
- }
- }
- }
- protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
- {
- base.OnPropertyChanged(change);
- if (change.Property == TextProperty)
- {
- CoerceValue(CaretIndexProperty);
- CoerceValue(SelectionStartProperty);
- CoerceValue(SelectionEndProperty);
- RaiseTextChangeEvents();
- UpdatePseudoclasses();
- UpdateCommandStates();
- }
- else if (change.Property == CaretIndexProperty)
- {
- OnCaretIndexChanged(change);
- }
- else if (change.Property == SelectionStartProperty)
- {
- OnSelectionStartChanged(change);
- }
- else if (change.Property == SelectionEndProperty)
- {
- OnSelectionEndChanged(change);
- }
- else if (change.Property == MaxLinesProperty)
- {
- InvalidateMeasure();
- }
- else if (change.Property == MinLinesProperty)
- {
- InvalidateMeasure();
- }
- else if (change.Property == UndoLimitProperty)
- {
- OnUndoLimitChanged(change.GetNewValue<int>());
- }
- else if (change.Property == IsUndoEnabledProperty && change.GetNewValue<bool>() == false)
- {
- // from docs at
- // https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
- // "Setting this property to false clears the undo stack.
- // Therefore, if you disable undo and then re-enable it, undo commands still do not work
- // because the undo stack was emptied when you disabled undo."
- _undoRedoHelper.Clear();
- _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
- _hasDoneSnapshotOnce = false;
- }
- }
- private void UpdateCommandStates()
- {
- var text = GetSelection();
- var isSelectionNullOrEmpty = string.IsNullOrEmpty(text);
- CanCopy = !IsPasswordBox && !isSelectionNullOrEmpty;
- CanCut = !IsPasswordBox && !isSelectionNullOrEmpty && !IsReadOnly;
- CanPaste = !IsReadOnly;
- }
- protected override void OnGotFocus(GotFocusEventArgs e)
- {
- base.OnGotFocus(e);
- // when navigating to a textbox via the tab key, select all text if
- // 1) this textbox is *not* a multiline textbox
- // 2) this textbox has any text to select
- if (e.NavigationMethod == NavigationMethod.Tab &&
- !AcceptsReturn &&
- Text?.Length > 0)
- {
- SelectAll();
- }
- UpdateCommandStates();
- _imClient.SetPresenter(_presenter, this);
- _presenter?.ShowCaret();
- }
- protected override void OnLostFocus(RoutedEventArgs e)
- {
- base.OnLostFocus(e);
- if ((ContextFlyout == null || !ContextFlyout.IsOpen) &&
- (ContextMenu == null || !ContextMenu.IsOpen))
- {
- ClearSelection();
- SetCurrentValue(RevealPasswordProperty, false);
- }
- UpdateCommandStates();
- _presenter?.HideCaret();
- _imClient.SetPresenter(null, null);
- }
- protected override void OnTextInput(TextInputEventArgs e)
- {
- if (!e.Handled)
- {
- HandleTextInput(e.Text);
- e.Handled = true;
- }
- }
- private void HandleTextInput(string? input)
- {
- if (IsReadOnly)
- {
- return;
- }
- input = RemoveInvalidCharacters(input);
- if (string.IsNullOrEmpty(input))
- {
- return;
- }
- _selectedTextChangesMadeSinceLastUndoSnapshot++;
- SnapshotUndoRedo(ignoreChangeCount: false);
- var currentText = Text ?? string.Empty;
- var selectionLength = Math.Abs(SelectionStart - SelectionEnd);
- var newLength = input.Length + currentText.Length - selectionLength;
- if (MaxLength > 0 && newLength > MaxLength)
- {
- input = input.Remove(Math.Max(0, input.Length - (newLength - MaxLength)));
- newLength = MaxLength;
- }
- if (!string.IsNullOrEmpty(input))
- {
- var textBuilder = StringBuilderCache.Acquire(Math.Max(currentText.Length, newLength));
- textBuilder.Append(currentText);
- var caretIndex = CaretIndex;
- if (selectionLength != 0)
- {
- var (start, _) = GetSelectionRange();
- textBuilder.Remove(start, selectionLength);
- caretIndex = start;
- }
- textBuilder.Insert(caretIndex, input);
- var text = StringBuilderCache.GetStringAndRelease(textBuilder);
- SetCurrentValue(TextProperty, text);
- ClearSelection();
- if (IsUndoEnabled)
- {
- _undoRedoHelper.DiscardRedo();
- }
- SetCurrentValue(CaretIndexProperty, caretIndex + input.Length);
- }
- }
- private string? RemoveInvalidCharacters(string? text)
- {
- if (text is null)
- return null;
- for (var i = 0; i < invalidCharacters.Length; i++)
- {
- text = text.Replace(invalidCharacters[i], string.Empty);
- }
- return text;
- }
- /// <summary>
- /// Cuts the current text onto the clipboard
- /// </summary>
- public async void Cut()
- {
- var text = GetSelection();
- if (string.IsNullOrEmpty(text))
- {
- return;
- }
- var eventArgs = new RoutedEventArgs(CuttingToClipboardEvent);
- RaiseEvent(eventArgs);
- if (!eventArgs.Handled)
- {
- SnapshotUndoRedo();
- var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
- if (clipboard == null)
- return;
- await clipboard.SetTextAsync(text);
- DeleteSelection();
- }
- }
- /// <summary>
- /// Copies the current text onto the clipboard
- /// </summary>
- public async void Copy()
- {
- var text = GetSelection();
- if (string.IsNullOrEmpty(text))
- {
- return;
- }
- var eventArgs = new RoutedEventArgs(CopyingToClipboardEvent);
- RaiseEvent(eventArgs);
- if (!eventArgs.Handled)
- {
- var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
- if (clipboard != null)
- await clipboard.SetTextAsync(text);
- }
- }
- /// <summary>
- /// Pastes the current clipboard text content into the TextBox
- /// </summary>
- public async void Paste()
- {
- var eventArgs = new RoutedEventArgs(PastingFromClipboardEvent);
- RaiseEvent(eventArgs);
- if (eventArgs.Handled)
- {
- return;
- }
- string? text = null;
- var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
- if (clipboard != null)
- {
- try
- {
- text = await clipboard.GetTextAsync();
- }
- catch (TimeoutException)
- {
- // Silently ignore.
- }
- }
- if (string.IsNullOrEmpty(text))
- {
- return;
- }
- SnapshotUndoRedo();
- HandleTextInput(text);
- }
- protected override void OnKeyDown(KeyEventArgs e)
- {
- if (_presenter == null)
- {
- return;
- }
- if (!string.IsNullOrEmpty(_presenter.PreeditText))
- {
- return;
- }
- var text = Text ?? string.Empty;
- var caretIndex = CaretIndex;
- var movement = false;
- var selection = false;
- var handled = false;
- var modifiers = e.KeyModifiers;
- var keymap = Application.Current!.PlatformSettings!.HotkeyConfiguration;
- bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
- bool DetectSelection() => e.KeyModifiers.HasAllFlags(keymap.SelectionModifiers);
- if (Match(keymap.SelectAll))
- {
- SelectAll();
- handled = true;
- }
- else if (Match(keymap.Copy))
- {
- if (!IsPasswordBox)
- {
- Copy();
- }
- handled = true;
- }
- else if (Match(keymap.Cut))
- {
- if (!IsPasswordBox)
- {
- Cut();
- }
- handled = true;
- }
- else if (Match(keymap.Paste))
- {
- Paste();
- handled = true;
- }
- else if (Match(keymap.Undo) && IsUndoEnabled)
- {
- Undo();
- handled = true;
- }
- else if (Match(keymap.Redo) && IsUndoEnabled)
- {
- Redo();
- handled = true;
- }
- else if (Match(keymap.MoveCursorToTheStartOfDocument))
- {
- MoveHome(true);
- movement = true;
- selection = false;
- handled = true;
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- else if (Match(keymap.MoveCursorToTheEndOfDocument))
- {
- MoveEnd(true);
- movement = true;
- selection = false;
- handled = true;
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- else if (Match(keymap.MoveCursorToTheStartOfLine))
- {
- MoveHome(false);
- movement = true;
- selection = false;
- handled = true;
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- else if (Match(keymap.MoveCursorToTheEndOfLine))
- {
- MoveEnd(false);
- movement = true;
- selection = false;
- handled = true;
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- else if (Match(keymap.MoveCursorToTheStartOfDocumentWithSelection))
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- MoveHome(true);
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- movement = true;
- selection = true;
- handled = true;
- }
- else if (Match(keymap.MoveCursorToTheEndOfDocumentWithSelection))
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- MoveEnd(true);
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- movement = true;
- selection = true;
- handled = true;
- }
- else if (Match(keymap.MoveCursorToTheStartOfLineWithSelection))
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- MoveHome(false);
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- movement = true;
- selection = true;
- handled = true;
- }
- else if (Match(keymap.MoveCursorToTheEndOfLineWithSelection))
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- MoveEnd(false);
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- movement = true;
- selection = true;
- handled = true;
- }
- else if (Match(keymap.PageLeft))
- {
- MovePageLeft();
- movement = true;
- selection = false;
- handled = true;
- }
- else if (Match(keymap.PageRight))
- {
- MovePageRight();
- movement = true;
- selection = false;
- handled = true;
- }
- else if (Match(keymap.PageUp))
- {
- MovePageUp();
- movement = true;
- selection = false;
- handled = true;
- }
- else if (Match(keymap.PageDown))
- {
- MovePageDown();
- movement = true;
- selection = false;
- handled = true;
- }
- else
- {
- bool hasWholeWordModifiers = modifiers.HasAllFlags(keymap.WholeWordTextActionModifiers);
- switch (e.Key)
- {
- case Key.Left:
- selection = DetectSelection();
- MoveHorizontal(-1, hasWholeWordModifiers, selection, true);
- if (caretIndex != _presenter.CaretIndex)
- {
- movement = true;
- }
- break;
- case Key.Right:
- selection = DetectSelection();
- MoveHorizontal(1, hasWholeWordModifiers, selection, true);
- if (caretIndex != _presenter.CaretIndex)
- {
- movement = true;
- }
- break;
- case Key.Up:
- {
- selection = DetectSelection();
- _presenter.MoveCaretVertical(LogicalDirection.Backward);
- if (caretIndex != _presenter.CaretIndex)
- {
- movement = true;
- }
- if (selection)
- {
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- }
- else
- {
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- break;
- }
- case Key.Down:
- {
- selection = DetectSelection();
- _presenter.MoveCaretVertical();
- if (caretIndex != _presenter.CaretIndex)
- {
- movement = true;
- }
- if (selection)
- {
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- }
- else
- {
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- break;
- }
- case Key.Back:
- {
- SnapshotUndoRedo();
- if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
- {
- SetSelectionForControlBackspace();
- }
- if (!DeleteSelection())
- {
- var characterHit = _presenter.GetNextCharacterHit(LogicalDirection.Backward);
- var backspacePosition = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
- if (caretIndex != backspacePosition)
- {
- var start = Math.Min(backspacePosition, caretIndex);
- var end = Math.Max(backspacePosition, caretIndex);
- var length = end - start;
- var sb = StringBuilderCache.Acquire(text.Length);
- sb.Append(text);
- sb.Remove(start, end - start);
- SetCurrentValue(TextProperty, StringBuilderCache.GetStringAndRelease(sb));
- SetCurrentValue(CaretIndexProperty, start);
- }
- }
- SnapshotUndoRedo();
- handled = true;
- break;
- }
- case Key.Delete:
- SnapshotUndoRedo();
- if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
- {
- SetSelectionForControlDelete();
- }
- if (!DeleteSelection())
- {
- var characterHit = _presenter.GetNextCharacterHit();
- var nextPosition = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
- if (nextPosition != caretIndex)
- {
- var start = Math.Min(nextPosition, caretIndex);
- var end = Math.Max(nextPosition, caretIndex);
- var sb = StringBuilderCache.Acquire(text.Length);
- sb.Append(text);
- sb.Remove(start, end - start);
- SetCurrentValue(TextProperty, StringBuilderCache.GetStringAndRelease(sb));
- }
- }
- SnapshotUndoRedo();
- handled = true;
- break;
- case Key.Enter:
- if (AcceptsReturn)
- {
- SnapshotUndoRedo();
- HandleTextInput(NewLine);
- handled = true;
- }
- break;
- case Key.Tab:
- if (AcceptsTab)
- {
- SnapshotUndoRedo();
- HandleTextInput("\t");
- handled = true;
- }
- else
- {
- base.OnKeyDown(e);
- }
- break;
- case Key.Space:
- SnapshotUndoRedo(); // always snapshot in between words
- break;
- default:
- handled = false;
- break;
- }
- }
- if (movement && !selection)
- {
- ClearSelection();
- }
- if (handled || movement)
- {
- e.Handled = true;
- }
- }
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- {
- if (_presenter == null)
- {
- return;
- }
- var text = Text;
- var clickInfo = e.GetCurrentPoint(this);
- if (text != null && (e.Pointer.Type == PointerType.Mouse || e.ClickCount >= 2) && clickInfo.Properties.IsLeftButtonPressed &&
- !(clickInfo.Pointer?.Captured is Border))
- {
- _currentClickCount = e.ClickCount;
- var point = e.GetPosition(_presenter);
- _presenter.MoveCaretToPoint(point);
- var caretIndex = _presenter.CaretIndex;
- var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift);
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- switch (e.ClickCount)
- {
- case 1:
- if (clickToSelect)
- {
- if (_wordSelectionStart >= 0)
- {
- UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
- SetCurrentValue(SelectionStartProperty, selectionStart);
- SetCurrentValue(SelectionEndProperty, selectionEnd);
- }
- else
- {
- SetCurrentValue(SelectionEndProperty, caretIndex);
- }
- }
- else
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- SetCurrentValue(SelectionEndProperty, caretIndex);
- _wordSelectionStart = -1;
- }
- break;
- case 2:
- if (!StringUtils.IsStartOfWord(text, caretIndex))
- {
- selectionStart = StringUtils.PreviousWord(text, caretIndex);
- }
- if (!StringUtils.IsEndOfWord(text, caretIndex))
- {
- selectionEnd = StringUtils.NextWord(text, caretIndex);
- }
- if (selectionStart != selectionEnd)
- {
- _wordSelectionStart = selectionStart;
- }
- SetCurrentValue(SelectionStartProperty, selectionStart);
- SetCurrentValue(SelectionEndProperty, selectionEnd);
- break;
- case 3:
- _wordSelectionStart = -1;
- SelectAll();
- break;
- }
- }
- _isDoubleTapped = e.ClickCount == 2;
- e.Pointer.Capture(_presenter);
- e.Handled = true;
- }
- protected override void OnPointerMoved(PointerEventArgs e)
- {
- if (_presenter == null || _isHolding)
- {
- return;
- }
- // selection should not change during pointer move if the user right clicks
- if (e.Pointer.Captured == _presenter && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
- {
- var point = e.GetPosition(_presenter);
- point = new Point(
- MathUtilities.Clamp(point.X, 0, Math.Max(_presenter.Bounds.Width - 1, 0)),
- MathUtilities.Clamp(point.Y, 0, Math.Max(_presenter.Bounds.Height - 1, 0)));
- var previousIndex = _presenter.CaretIndex;
- _presenter.MoveCaretToPoint(point);
- var caretIndex = _presenter.CaretIndex;
- if (Math.Abs(caretIndex - previousIndex) == 1)
- e.PreventGestureRecognition();
- if (e.Pointer.Type == PointerType.Mouse)
- {
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- if (_wordSelectionStart >= 0)
- {
- UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
- SetCurrentValue(SelectionStartProperty, selectionStart);
- SetCurrentValue(SelectionEndProperty, selectionEnd);
- }
- else
- {
- SetCurrentValue(SelectionEndProperty, caretIndex);
- }
- }
- else
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- SetCurrentValue(SelectionEndProperty, caretIndex);
- }
- }
- }
- private void UpdateWordSelectionRange(int caretIndex, ref int selectionStart, ref int selectionEnd)
- {
- var text = Text;
- if (string.IsNullOrEmpty(text))
- {
- return;
- }
- if (caretIndex > _wordSelectionStart)
- {
- var nextWord = StringUtils.NextWord(text, caretIndex);
- selectionEnd = nextWord;
- selectionStart = _wordSelectionStart;
- }
- else
- {
- var previousWord = StringUtils.PreviousWord(text, caretIndex);
- selectionStart = previousWord;
- selectionEnd = StringUtils.NextWord(text, _wordSelectionStart);
- }
- }
- protected override void OnPointerReleased(PointerReleasedEventArgs e)
- {
- if (_presenter == null)
- {
- return;
- }
- if (e.Pointer.Captured != _presenter)
- {
- return;
- }
- if (e.Pointer.Type != PointerType.Mouse && !_isDoubleTapped)
- {
- var text = Text;
- var clickInfo = e.GetCurrentPoint(this);
- if (text != null && !(clickInfo.Pointer?.Captured is Border))
- {
- var point = e.GetPosition(_presenter);
- _presenter.MoveCaretToPoint(point);
- var caretIndex = _presenter.CaretIndex;
- var clickToSelect = e.KeyModifiers.HasFlag(KeyModifiers.Shift);
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- if (clickToSelect)
- {
- if (_wordSelectionStart >= 0)
- {
- UpdateWordSelectionRange(caretIndex, ref selectionStart, ref selectionEnd);
- SetCurrentValue(SelectionStartProperty, selectionStart);
- SetCurrentValue(SelectionEndProperty, selectionEnd);
- }
- else
- {
- SetCurrentValue(SelectionEndProperty, caretIndex);
- }
- }
- else
- {
- SetCurrentValue(SelectionStartProperty, caretIndex);
- SetCurrentValue(SelectionEndProperty, caretIndex);
- _wordSelectionStart = -1;
- }
- _presenter.TextSelectionHandleCanvas?.MoveHandlesToSelection();
- }
- }
- // Don't update selection if the pointer was held
- if (_isHolding)
- {
- _isHolding = false;
- }
- else if (e.InitialPressMouseButton == MouseButton.Right)
- {
- var point = e.GetPosition(_presenter);
- _presenter.MoveCaretToPoint(point);
- var caretIndex = _presenter.CaretIndex;
- // see if mouse clicked inside current selection
- // if it did not, we change the selection to where the user clicked
- var firstSelection = Math.Min(SelectionStart, SelectionEnd);
- var lastSelection = Math.Max(SelectionStart, SelectionEnd);
- var didClickInSelection = SelectionStart != SelectionEnd &&
- caretIndex >= firstSelection && caretIndex <= lastSelection;
- if (!didClickInSelection)
- {
- SetCurrentValue(CaretIndexProperty, caretIndex);
- SetCurrentValue(SelectionEndProperty, caretIndex);
- SetCurrentValue(SelectionStartProperty, caretIndex);
- }
- }
- else if (e.Pointer.Type == PointerType.Touch)
- {
- if (_currentClickCount == 1)
- {
- var point = e.GetPosition(_presenter);
- _presenter.MoveCaretToPoint(point);
- var caretIndex = _presenter.CaretIndex;
- SetCurrentValue(SelectionStartProperty, caretIndex);
- SetCurrentValue(SelectionEndProperty, caretIndex);
- }
- if(SelectionStart != SelectionEnd)
- {
- _presenter.TextSelectionHandleCanvas?.ShowContextMenu();
- }
- }
- e.Pointer.Capture(null);
- }
- protected override AutomationPeer OnCreateAutomationPeer()
- {
- return new TextBoxAutomationPeer(this);
- }
- protected override void UpdateDataValidation(
- AvaloniaProperty property,
- BindingValueType state,
- Exception? error)
- {
- if (property == TextProperty)
- {
- DataValidationErrors.SetError(this, error);
- }
- }
- internal static int CoerceCaretIndex(AvaloniaObject sender, int value)
- {
- var text = sender.GetValue(TextProperty); // method also used by TextPresenter and SelectableTextBlock
- if (text == null)
- {
- return 0;
- }
- var length = text.Length;
- if (value < 0)
- {
- return 0;
- }
- else if (value > length)
- {
- return length;
- }
- else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
- {
- return value + 1;
- }
- else
- {
- return value;
- }
- }
- /// <summary>
- /// Clears the text in the TextBox
- /// </summary>
- public void Clear() => SetCurrentValue(TextProperty, string.Empty);
- private void MoveHorizontal(int direction, bool wholeWord, bool isSelecting, bool moveCaretPosition)
- {
- if (_presenter == null)
- {
- return;
- }
- var text = Text ?? string.Empty;
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- if (!wholeWord)
- {
- if (isSelecting)
- {
- _presenter.MoveCaretToTextPosition(selectionEnd);
- _presenter.MoveCaretHorizontal(direction > 0 ?
- LogicalDirection.Forward :
- LogicalDirection.Backward);
- SetCurrentValue(SelectionEndProperty, _presenter.CaretIndex);
- }
- else
- {
- if (selectionStart != selectionEnd)
- {
- _presenter.MoveCaretToTextPosition(direction > 0 ?
- Math.Max(selectionStart, selectionEnd) :
- Math.Min(selectionStart, selectionEnd));
- }
- else
- {
- _presenter.MoveCaretHorizontal(direction > 0 ?
- LogicalDirection.Forward :
- LogicalDirection.Backward);
- }
- SetCurrentValue(CaretIndexProperty, _presenter.CaretIndex);
- }
- }
- else
- {
- int offset;
- if (direction > 0)
- {
- offset = StringUtils.NextWord(text, selectionEnd) - selectionEnd;
- }
- else
- {
- offset = StringUtils.PreviousWord(text, selectionEnd) - selectionEnd;
- }
- SetCurrentValue(SelectionEndProperty, SelectionEnd + offset);
- if (moveCaretPosition)
- {
- _presenter.MoveCaretToTextPosition(SelectionEnd);
- }
- if (!isSelecting && moveCaretPosition)
- {
- SetCurrentValue(CaretIndexProperty, SelectionEnd);
- }
- else
- {
- SetCurrentValue(SelectionStartProperty, selectionStart);
- }
- }
- }
- private void MoveHome(bool document)
- {
- if (_presenter is null)
- {
- return;
- }
- var caretIndex = CaretIndex;
- if (document)
- {
- _presenter.MoveCaretToTextPosition(0);
- }
- else
- {
- var textLines = _presenter.TextLayout.TextLines;
- var lineIndex = _presenter.TextLayout.GetLineIndexFromCharacterIndex(caretIndex, false);
- var textLine = textLines[lineIndex];
- _presenter.MoveCaretToTextPosition(textLine.FirstTextSourceIndex);
- }
- }
- private void MoveEnd(bool document)
- {
- if (_presenter is null)
- {
- return;
- }
- var text = Text ?? string.Empty;
- var caretIndex = CaretIndex;
- if (document)
- {
- _presenter.MoveCaretToTextPosition(text.Length, true);
- }
- else
- {
- var textLines = _presenter.TextLayout.TextLines;
- var lineIndex = _presenter.TextLayout.GetLineIndexFromCharacterIndex(caretIndex, false);
- var textLine = textLines[lineIndex];
- var textPosition = textLine.FirstTextSourceIndex + textLine.Length - textLine.NewLineLength;
- _presenter.MoveCaretToTextPosition(textPosition, true);
- }
- }
- private void MovePageRight()
- {
- _scrollViewer?.PageRight();
- }
- private void MovePageLeft()
- {
- _scrollViewer?.PageLeft();
- }
- private void MovePageUp()
- {
- _scrollViewer?.PageUp();
- }
- private void MovePageDown()
- {
- _scrollViewer?.PageDown();
- }
- /// <summary>
- /// Scroll the <see cref="TextBox"/> to the specified line index.
- /// </summary>
- /// <param name="lineIndex">The line index to scroll to.</param>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="lineIndex"/> is less than zero. -or - <paramref name="lineIndex"/> is larger than or equal to the line count.</exception>
- public void ScrollToLine(int lineIndex)
- {
- if (_presenter is null)
- {
- return;
- }
- if (lineIndex < 0 || lineIndex >= _presenter.TextLayout.TextLines.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(lineIndex));
- }
- var textLine = _presenter.TextLayout.TextLines[lineIndex];
- _presenter.MoveCaretToTextPosition(textLine.FirstTextSourceIndex);
- }
- /// <summary>
- /// Select all text in the TextBox
- /// </summary>
- public void SelectAll()
- {
- SetCurrentValue(SelectionStartProperty, 0);
- SetCurrentValue(SelectionEndProperty, Text?.Length ?? 0);
- }
- private (int start, int end) GetSelectionRange()
- {
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- return (Math.Min(selectionStart, selectionEnd), Math.Max(selectionStart, selectionEnd));
- }
- internal bool DeleteSelection()
- {
- if (IsReadOnly)
- return true;
- var (start, end) = GetSelectionRange();
- if (start != end)
- {
- var text = Text!;
- var textBuilder = StringBuilderCache.Acquire(text.Length);
- textBuilder.Append(text);
- textBuilder.Remove(start, end - start);
- SetCurrentValue(TextProperty, textBuilder.ToString());
- _presenter?.MoveCaretToTextPosition(start);
- SetCurrentValue(SelectionStartProperty, start);
- ClearSelection();
- return true;
- }
- SetCurrentValue(CaretIndexProperty, SelectionStart);
- return false;
- }
- private string GetSelection()
- {
- var text = Text;
- if (string.IsNullOrEmpty(text))
- {
- return "";
- }
- var selectionStart = SelectionStart;
- var selectionEnd = SelectionEnd;
- var start = Math.Min(selectionStart, selectionEnd);
- var end = Math.Max(selectionStart, selectionEnd);
- if (start == end || (Text?.Length ?? 0) < end)
- {
- return "";
- }
- return text.Substring(start, end - start);
- }
- /// <summary>
- /// Returns the sum of any vertical whitespace added between the <see cref="ScrollViewer"/> and <see cref="TextPresenter"/> in the control template.
- /// </summary>
- /// <returns>The total vertical whitespace.</returns>
- private double GetVerticalSpaceBetweenScrollViewerAndPresenter()
- {
- var verticalSpace = 0.0;
- if (_presenter != null)
- {
- Visual? visual = _presenter;
- while ((visual != null) && (visual != this))
- {
- if (visual == _scrollViewer)
- {
- // ScrollViewer is a stopping point and should only include the Padding
- verticalSpace += _scrollViewer.Padding.Top + _scrollViewer.Padding.Bottom;
- break;
- }
- var margin = visual.GetValue<Thickness>(Layoutable.MarginProperty);
- var padding = visual.GetValue<Thickness>(Decorator.PaddingProperty);
- verticalSpace += margin.Top + padding.Top + padding.Bottom + margin.Bottom;
- visual = visual.VisualParent;
- }
- }
- return verticalSpace;
- }
- /// <summary>
- /// Raises both the <see cref="TextChanging"/> and <see cref="TextChanged"/> events.
- /// </summary>
- /// <remarks>
- /// This must be called after the <see cref="Text"/> property is set.
- /// </remarks>
- private void RaiseTextChangeEvents()
- {
- // Note the following sequence of these events (following WinUI)
- // 1. TextChanging occurs synchronously when text starts to change but before it is rendered.
- // This occurs after the Text property is set.
- // 2. TextChanged occurs asynchronously after text changes and the new text is rendered.
- var textChangingEventArgs = new TextChangingEventArgs(TextChangingEvent);
- RaiseEvent(textChangingEventArgs);
- Dispatcher.UIThread.Post(() =>
- {
- var textChangedEventArgs = new TextChangedEventArgs(TextChangedEvent);
- RaiseEvent(textChangedEventArgs);
- }, DispatcherPriority.Normal);
- }
- private void SetSelectionForControlBackspace()
- {
- var text = Text ?? string.Empty;
- var selectionStart = CaretIndex;
- MoveHorizontal(-1, true, false, false);
- if (SelectionEnd > 0 &&
- selectionStart < text.Length && text[selectionStart] == ' ')
- {
- SetCurrentValue(SelectionEndProperty, SelectionEnd - 1);
- }
- SetCurrentValue(SelectionStartProperty, selectionStart);
- }
- private void SetSelectionForControlDelete()
- {
- var textLength = Text?.Length ?? 0;
- if (_presenter == null || textLength == 0)
- {
- return;
- }
- SetCurrentValue(SelectionStartProperty, CaretIndex);
- MoveHorizontal(1, true, true, false);
- if (SelectionEnd < textLength && Text![SelectionEnd] == ' ')
- {
- SetCurrentValue(SelectionEndProperty, SelectionEnd + 1);
- }
- }
- private void UpdatePseudoclasses()
- {
- PseudoClasses.Set(":empty", string.IsNullOrEmpty(Text));
- }
- private bool IsPasswordBox => PasswordChar != default(char);
- UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
- {
- get => new UndoRedoState(Text, CaretIndex);
- set
- {
- SetCurrentValue(TextProperty, value.Text);
- SetCurrentValue(CaretIndexProperty, value.CaretPosition);
- ClearSelection();
- }
- }
- private void SnapshotUndoRedo(bool ignoreChangeCount = true)
- {
- if (IsUndoEnabled)
- {
- if (ignoreChangeCount ||
- !_hasDoneSnapshotOnce ||
- (!ignoreChangeCount &&
- _selectedTextChangesMadeSinceLastUndoSnapshot >= _maxCharsBeforeUndoSnapshot))
- {
- _undoRedoHelper.Snapshot();
- _selectedTextChangesMadeSinceLastUndoSnapshot = 0;
- _hasDoneSnapshotOnce = true;
- }
- }
- }
- /// <summary>
- /// Undoes the first action in the undo stack
- /// </summary>
- public void Undo()
- {
- if (IsUndoEnabled && CanUndo)
- {
- try
- {
- // Snapshot the current Text state - this will get popped on to the redo stack
- // when we call undo below
- SnapshotUndoRedo();
- _isUndoingRedoing = true;
- _undoRedoHelper.Undo();
- }
- finally
- {
- _isUndoingRedoing = false;
- }
- }
- }
- /// <summary>
- /// Reapplies the first item on the redo stack
- /// </summary>
- public void Redo()
- {
- if (IsUndoEnabled && CanRedo)
- {
- try
- {
- _isUndoingRedoing = true;
- _undoRedoHelper.Redo();
- }
- finally
- {
- _isUndoingRedoing = false;
- }
- }
- }
- /// <summary>
- /// Called from the UndoRedoHelper when the undo stack is modified
- /// </summary>
- void UndoRedoHelper<UndoRedoState>.IUndoRedoHost.OnUndoStackChanged()
- {
- CanUndo = _undoRedoHelper.CanUndo;
- }
- /// <summary>
- /// Called from the UndoRedoHelper when the redo stack is modified
- /// </summary>
- void UndoRedoHelper<UndoRedoState>.IUndoRedoHost.OnRedoStackChanged()
- {
- CanRedo = _undoRedoHelper.CanRedo;
- }
- protected override Size MeasureOverride(Size availableSize)
- {
- if(_scrollViewer != null)
- {
- var maxHeight = double.PositiveInfinity;
- if (MaxLines > 0 && double.IsNaN(Height))
- {
- var fontSize = FontSize;
- var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
- var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
- var textLayout = new TextLayout(new LineTextSource(MaxLines), paragraphProperties);
- var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();
- maxHeight = Math.Ceiling(textLayout.Height + verticalSpace);
- }
- _scrollViewer.SetCurrentValue(MaxHeightProperty, maxHeight);
- var minHeight = 0.0;
- if (MinLines > 0 && double.IsNaN(Height))
- {
- var fontSize = FontSize;
- var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
- var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
- var textLayout = new TextLayout(new LineTextSource(MinLines), paragraphProperties);
- var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();
- minHeight = Math.Ceiling(textLayout.Height + verticalSpace);
- }
- _scrollViewer.SetCurrentValue(MinHeightProperty, minHeight);
- }
- return base.MeasureOverride(availableSize);
- }
- private class LineTextSource : ITextSource
- {
- private readonly int _lines;
- public LineTextSource(int lines)
- {
- _lines = lines;
- }
- public TextRun? GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex >= _lines)
- {
- return null;
- }
- return new TextEndOfLine(1);
- }
- }
- }
- }
|