TextBox.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. using Avalonia.Input.Platform;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reactive.Linq;
  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. namespace Avalonia.Controls
  18. {
  19. [PseudoClasses(":empty")]
  20. public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
  21. {
  22. public static KeyGesture CutGesture { get; } = AvaloniaLocator.Current
  23. .GetService<PlatformHotkeyConfiguration>()?.Cut.FirstOrDefault();
  24. public static KeyGesture CopyGesture { get; } = AvaloniaLocator.Current
  25. .GetService<PlatformHotkeyConfiguration>()?.Copy.FirstOrDefault();
  26. public static KeyGesture PasteGesture { get; } = AvaloniaLocator.Current
  27. .GetService<PlatformHotkeyConfiguration>()?.Paste.FirstOrDefault();
  28. public static readonly StyledProperty<bool> AcceptsReturnProperty =
  29. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
  30. public static readonly StyledProperty<bool> AcceptsTabProperty =
  31. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
  32. public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
  33. AvaloniaProperty.RegisterDirect<TextBox, int>(
  34. nameof(CaretIndex),
  35. o => o.CaretIndex,
  36. (o, v) => o.CaretIndex = v);
  37. public static readonly StyledProperty<bool> IsReadOnlyProperty =
  38. AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
  39. public static readonly StyledProperty<char> PasswordCharProperty =
  40. AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
  41. public static readonly StyledProperty<IBrush> SelectionBrushProperty =
  42. AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionBrushProperty));
  43. public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
  44. AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionForegroundBrushProperty));
  45. public static readonly StyledProperty<IBrush> CaretBrushProperty =
  46. AvaloniaProperty.Register<TextBox, IBrush>(nameof(CaretBrushProperty));
  47. public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
  48. AvaloniaProperty.RegisterDirect<TextBox, int>(
  49. nameof(SelectionStart),
  50. o => o.SelectionStart,
  51. (o, v) => o.SelectionStart = v);
  52. public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
  53. AvaloniaProperty.RegisterDirect<TextBox, int>(
  54. nameof(SelectionEnd),
  55. o => o.SelectionEnd,
  56. (o, v) => o.SelectionEnd = v);
  57. public static readonly StyledProperty<int> MaxLengthProperty =
  58. AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength), defaultValue: 0);
  59. public static readonly DirectProperty<TextBox, string> TextProperty =
  60. TextBlock.TextProperty.AddOwnerWithDataValidation<TextBox>(
  61. o => o.Text,
  62. (o, v) => o.Text = v,
  63. defaultBindingMode: BindingMode.TwoWay,
  64. enableDataValidation: true);
  65. public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
  66. TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
  67. /// <summary>
  68. /// Defines the <see cref="HorizontalAlignment"/> property.
  69. /// </summary>
  70. public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
  71. ContentControl.HorizontalContentAlignmentProperty.AddOwner<TextBox>();
  72. /// <summary>
  73. /// Defines the <see cref="VerticalAlignment"/> property.
  74. /// </summary>
  75. public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
  76. ContentControl.VerticalContentAlignmentProperty.AddOwner<TextBox>();
  77. public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
  78. TextBlock.TextWrappingProperty.AddOwner<TextBox>();
  79. public static readonly StyledProperty<string> WatermarkProperty =
  80. AvaloniaProperty.Register<TextBox, string>(nameof(Watermark));
  81. public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
  82. AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
  83. public static readonly DirectProperty<TextBox, string> NewLineProperty =
  84. AvaloniaProperty.RegisterDirect<TextBox, string>(nameof(NewLine),
  85. textbox => textbox.NewLine, (textbox, newline) => textbox.NewLine = newline);
  86. public static readonly StyledProperty<object> InnerLeftContentProperty =
  87. AvaloniaProperty.Register<TextBox, object>(nameof(InnerLeftContent));
  88. public static readonly StyledProperty<object> InnerRightContentProperty =
  89. AvaloniaProperty.Register<TextBox, object>(nameof(InnerRightContent));
  90. public static readonly StyledProperty<bool> RevealPasswordProperty =
  91. AvaloniaProperty.Register<TextBox, bool>(nameof(RevealPassword));
  92. public static readonly DirectProperty<TextBox, bool> CanCutProperty =
  93. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  94. nameof(CanCut),
  95. o => o.CanCut);
  96. public static readonly DirectProperty<TextBox, bool> CanCopyProperty =
  97. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  98. nameof(CanCopy),
  99. o => o.CanCopy);
  100. public static readonly DirectProperty<TextBox, bool> CanPasteProperty =
  101. AvaloniaProperty.RegisterDirect<TextBox, bool>(
  102. nameof(CanPaste),
  103. o => o.CanPaste);
  104. struct UndoRedoState : IEquatable<UndoRedoState>
  105. {
  106. public string Text { get; }
  107. public int CaretPosition { get; }
  108. public UndoRedoState(string text, int caretPosition)
  109. {
  110. Text = text;
  111. CaretPosition = caretPosition;
  112. }
  113. public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
  114. }
  115. private string _text;
  116. private int _caretIndex;
  117. private int _selectionStart;
  118. private int _selectionEnd;
  119. private TextPresenter _presenter;
  120. private TextBoxTextInputMethodClient _imClient = new TextBoxTextInputMethodClient();
  121. private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
  122. private bool _isUndoingRedoing;
  123. private bool _ignoreTextChanges;
  124. private bool _canCut;
  125. private bool _canCopy;
  126. private bool _canPaste;
  127. private string _newLine = Environment.NewLine;
  128. private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
  129. static TextBox()
  130. {
  131. FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
  132. TextInputMethodClientRequestedEvent.AddClassHandler<TextBox>((tb, e) =>
  133. {
  134. e.Client = tb._imClient;
  135. });
  136. }
  137. public TextBox()
  138. {
  139. var horizontalScrollBarVisibility = Observable.CombineLatest(
  140. this.GetObservable(AcceptsReturnProperty),
  141. this.GetObservable(TextWrappingProperty),
  142. (acceptsReturn, wrapping) =>
  143. {
  144. if (acceptsReturn)
  145. {
  146. return wrapping != TextWrapping.Wrap ?
  147. ScrollBarVisibility.Auto :
  148. ScrollBarVisibility.Disabled;
  149. }
  150. else
  151. {
  152. return ScrollBarVisibility.Hidden;
  153. }
  154. });
  155. this.Bind(
  156. ScrollViewer.HorizontalScrollBarVisibilityProperty,
  157. horizontalScrollBarVisibility,
  158. BindingPriority.Style);
  159. _undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
  160. UpdatePseudoclasses();
  161. }
  162. public bool AcceptsReturn
  163. {
  164. get { return GetValue(AcceptsReturnProperty); }
  165. set { SetValue(AcceptsReturnProperty, value); }
  166. }
  167. public bool AcceptsTab
  168. {
  169. get { return GetValue(AcceptsTabProperty); }
  170. set { SetValue(AcceptsTabProperty, value); }
  171. }
  172. public int CaretIndex
  173. {
  174. get
  175. {
  176. return _caretIndex;
  177. }
  178. set
  179. {
  180. value = CoerceCaretIndex(value);
  181. SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
  182. UndoRedoState state;
  183. if (_undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
  184. _undoRedoHelper.UpdateLastState();
  185. }
  186. }
  187. public bool IsReadOnly
  188. {
  189. get { return GetValue(IsReadOnlyProperty); }
  190. set { SetValue(IsReadOnlyProperty, value); }
  191. }
  192. public char PasswordChar
  193. {
  194. get => GetValue(PasswordCharProperty);
  195. set => SetValue(PasswordCharProperty, value);
  196. }
  197. public IBrush SelectionBrush
  198. {
  199. get => GetValue(SelectionBrushProperty);
  200. set => SetValue(SelectionBrushProperty, value);
  201. }
  202. public IBrush SelectionForegroundBrush
  203. {
  204. get => GetValue(SelectionForegroundBrushProperty);
  205. set => SetValue(SelectionForegroundBrushProperty, value);
  206. }
  207. public IBrush CaretBrush
  208. {
  209. get => GetValue(CaretBrushProperty);
  210. set => SetValue(CaretBrushProperty, value);
  211. }
  212. public int SelectionStart
  213. {
  214. get
  215. {
  216. return _selectionStart;
  217. }
  218. set
  219. {
  220. value = CoerceCaretIndex(value);
  221. SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
  222. if (SelectionStart == SelectionEnd)
  223. {
  224. CaretIndex = SelectionStart;
  225. }
  226. }
  227. }
  228. public int SelectionEnd
  229. {
  230. get
  231. {
  232. return _selectionEnd;
  233. }
  234. set
  235. {
  236. value = CoerceCaretIndex(value);
  237. SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
  238. if (SelectionStart == SelectionEnd)
  239. {
  240. CaretIndex = SelectionEnd;
  241. }
  242. }
  243. }
  244. public int MaxLength
  245. {
  246. get { return GetValue(MaxLengthProperty); }
  247. set { SetValue(MaxLengthProperty, value); }
  248. }
  249. [Content]
  250. public string Text
  251. {
  252. get { return _text; }
  253. set
  254. {
  255. if (!_ignoreTextChanges)
  256. {
  257. var caretIndex = CaretIndex;
  258. SelectionStart = CoerceCaretIndex(SelectionStart, value);
  259. SelectionEnd = CoerceCaretIndex(SelectionEnd, value);
  260. CaretIndex = CoerceCaretIndex(caretIndex, value);
  261. if (SetAndRaise(TextProperty, ref _text, value) && !_isUndoingRedoing)
  262. {
  263. _undoRedoHelper.Clear();
  264. }
  265. }
  266. }
  267. }
  268. public string SelectedText
  269. {
  270. get { return GetSelection(); }
  271. set
  272. {
  273. _undoRedoHelper.Snapshot();
  274. if (string.IsNullOrEmpty(value))
  275. {
  276. DeleteSelection();
  277. }
  278. else
  279. {
  280. HandleTextInput(value);
  281. }
  282. _undoRedoHelper.Snapshot();
  283. }
  284. }
  285. /// <summary>
  286. /// Gets or sets the horizontal alignment of the content within the control.
  287. /// </summary>
  288. public HorizontalAlignment HorizontalContentAlignment
  289. {
  290. get { return GetValue(HorizontalContentAlignmentProperty); }
  291. set { SetValue(HorizontalContentAlignmentProperty, value); }
  292. }
  293. /// <summary>
  294. /// Gets or sets the vertical alignment of the content within the control.
  295. /// </summary>
  296. public VerticalAlignment VerticalContentAlignment
  297. {
  298. get { return GetValue(VerticalContentAlignmentProperty); }
  299. set { SetValue(VerticalContentAlignmentProperty, value); }
  300. }
  301. public TextAlignment TextAlignment
  302. {
  303. get { return GetValue(TextAlignmentProperty); }
  304. set { SetValue(TextAlignmentProperty, value); }
  305. }
  306. public string Watermark
  307. {
  308. get { return GetValue(WatermarkProperty); }
  309. set { SetValue(WatermarkProperty, value); }
  310. }
  311. public bool UseFloatingWatermark
  312. {
  313. get { return GetValue(UseFloatingWatermarkProperty); }
  314. set { SetValue(UseFloatingWatermarkProperty, value); }
  315. }
  316. public object InnerLeftContent
  317. {
  318. get { return GetValue(InnerLeftContentProperty); }
  319. set { SetValue(InnerLeftContentProperty, value); }
  320. }
  321. public object InnerRightContent
  322. {
  323. get { return GetValue(InnerRightContentProperty); }
  324. set { SetValue(InnerRightContentProperty, value); }
  325. }
  326. public bool RevealPassword
  327. {
  328. get { return GetValue(RevealPasswordProperty); }
  329. set { SetValue(RevealPasswordProperty, value); }
  330. }
  331. public TextWrapping TextWrapping
  332. {
  333. get { return GetValue(TextWrappingProperty); }
  334. set { SetValue(TextWrappingProperty, value); }
  335. }
  336. /// <summary>
  337. /// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
  338. /// </summary>
  339. public string NewLine
  340. {
  341. get { return _newLine; }
  342. set { SetAndRaise(NewLineProperty, ref _newLine, value); }
  343. }
  344. /// <summary>
  345. /// Clears the current selection, maintaining the <see cref="CaretIndex"/>
  346. /// </summary>
  347. public void ClearSelection()
  348. {
  349. SelectionStart = SelectionEnd = CaretIndex;
  350. }
  351. /// <summary>
  352. /// Property for determining if the Cut command can be executed.
  353. /// </summary>
  354. public bool CanCut
  355. {
  356. get { return _canCut; }
  357. private set { SetAndRaise(CanCutProperty, ref _canCut, value); }
  358. }
  359. /// <summary>
  360. /// Property for determining if the Copy command can be executed.
  361. /// </summary>
  362. public bool CanCopy
  363. {
  364. get { return _canCopy; }
  365. private set { SetAndRaise(CanCopyProperty, ref _canCopy, value); }
  366. }
  367. /// <summary>
  368. /// Property for determining if the Paste command can be executed.
  369. /// </summary>
  370. public bool CanPaste
  371. {
  372. get { return _canPaste; }
  373. private set { SetAndRaise(CanPasteProperty, ref _canPaste, value); }
  374. }
  375. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  376. {
  377. _presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
  378. _imClient.SetPresenter(_presenter);
  379. if (IsFocused)
  380. {
  381. _presenter?.ShowCaret();
  382. }
  383. }
  384. protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
  385. {
  386. base.OnPropertyChanged(change);
  387. if (change.Property == TextProperty)
  388. {
  389. UpdatePseudoclasses();
  390. UpdateCommandStates();
  391. }
  392. }
  393. private void UpdateCommandStates()
  394. {
  395. var text = GetSelection();
  396. var isSelectionNullOrEmpty = string.IsNullOrEmpty(text);
  397. CanCopy = !IsPasswordBox && !isSelectionNullOrEmpty;
  398. CanCut = !IsPasswordBox && !isSelectionNullOrEmpty && !IsReadOnly;
  399. CanPaste = !IsReadOnly;
  400. }
  401. protected override void OnGotFocus(GotFocusEventArgs e)
  402. {
  403. base.OnGotFocus(e);
  404. // when navigating to a textbox via the tab key, select all text if
  405. // 1) this textbox is *not* a multiline textbox
  406. // 2) this textbox has any text to select
  407. if (e.NavigationMethod == NavigationMethod.Tab &&
  408. !AcceptsReturn &&
  409. Text?.Length > 0)
  410. {
  411. SelectAll();
  412. }
  413. UpdateCommandStates();
  414. _presenter?.ShowCaret();
  415. }
  416. protected override void OnLostFocus(RoutedEventArgs e)
  417. {
  418. base.OnLostFocus(e);
  419. if (ContextMenu == null || !ContextMenu.IsOpen)
  420. {
  421. ClearSelection();
  422. RevealPassword = false;
  423. }
  424. UpdateCommandStates();
  425. _presenter?.HideCaret();
  426. }
  427. protected override void OnTextInput(TextInputEventArgs e)
  428. {
  429. if (!e.Handled)
  430. {
  431. HandleTextInput(e.Text);
  432. e.Handled = true;
  433. }
  434. }
  435. private void HandleTextInput(string input)
  436. {
  437. if (!IsReadOnly)
  438. {
  439. input = RemoveInvalidCharacters(input);
  440. string text = Text ?? string.Empty;
  441. int caretIndex = CaretIndex;
  442. if (!string.IsNullOrEmpty(input) && (MaxLength == 0 || input.Length + text.Length - (Math.Abs(SelectionStart - SelectionEnd)) <= MaxLength))
  443. {
  444. DeleteSelection();
  445. caretIndex = CaretIndex;
  446. text = Text ?? string.Empty;
  447. SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex));
  448. CaretIndex += input.Length;
  449. ClearSelection();
  450. _undoRedoHelper.DiscardRedo();
  451. }
  452. }
  453. }
  454. public string RemoveInvalidCharacters(string text)
  455. {
  456. for (var i = 0; i < invalidCharacters.Length; i++)
  457. {
  458. text = text.Replace(invalidCharacters[i], string.Empty);
  459. }
  460. return text;
  461. }
  462. public async void Cut()
  463. {
  464. var text = GetSelection();
  465. if (text is null) return;
  466. _undoRedoHelper.Snapshot();
  467. Copy();
  468. DeleteSelection();
  469. _undoRedoHelper.Snapshot();
  470. }
  471. public async void Copy()
  472. {
  473. var text = GetSelection();
  474. if (text is null) return;
  475. await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
  476. .SetTextAsync(text);
  477. }
  478. public async void Paste()
  479. {
  480. var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
  481. if (text is null) return;
  482. _undoRedoHelper.Snapshot();
  483. HandleTextInput(text);
  484. _undoRedoHelper.Snapshot();
  485. }
  486. protected override void OnKeyDown(KeyEventArgs e)
  487. {
  488. string text = Text ?? string.Empty;
  489. int caretIndex = CaretIndex;
  490. bool movement = false;
  491. bool selection = false;
  492. bool handled = false;
  493. var modifiers = e.KeyModifiers;
  494. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
  495. bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
  496. bool DetectSelection() => e.KeyModifiers.HasFlagCustom(keymap.SelectionModifiers);
  497. if (Match(keymap.SelectAll))
  498. {
  499. SelectAll();
  500. handled = true;
  501. }
  502. else if (Match(keymap.Copy))
  503. {
  504. if (!IsPasswordBox)
  505. {
  506. Copy();
  507. }
  508. handled = true;
  509. }
  510. else if (Match(keymap.Cut))
  511. {
  512. if (!IsPasswordBox)
  513. {
  514. Cut();
  515. }
  516. handled = true;
  517. }
  518. else if (Match(keymap.Paste))
  519. {
  520. Paste();
  521. handled = true;
  522. }
  523. else if (Match(keymap.Undo))
  524. {
  525. try
  526. {
  527. _isUndoingRedoing = true;
  528. _undoRedoHelper.Undo();
  529. }
  530. finally
  531. {
  532. _isUndoingRedoing = false;
  533. }
  534. handled = true;
  535. }
  536. else if (Match(keymap.Redo))
  537. {
  538. try
  539. {
  540. _isUndoingRedoing = true;
  541. _undoRedoHelper.Redo();
  542. }
  543. finally
  544. {
  545. _isUndoingRedoing = false;
  546. }
  547. handled = true;
  548. }
  549. else if (Match(keymap.MoveCursorToTheStartOfDocument))
  550. {
  551. MoveHome(true);
  552. movement = true;
  553. selection = false;
  554. handled = true;
  555. }
  556. else if (Match(keymap.MoveCursorToTheEndOfDocument))
  557. {
  558. MoveEnd(true);
  559. movement = true;
  560. selection = false;
  561. handled = true;
  562. }
  563. else if (Match(keymap.MoveCursorToTheStartOfLine))
  564. {
  565. MoveHome(false);
  566. movement = true;
  567. selection = false;
  568. handled = true;
  569. }
  570. else if (Match(keymap.MoveCursorToTheEndOfLine))
  571. {
  572. MoveEnd(false);
  573. movement = true;
  574. selection = false;
  575. handled = true;
  576. }
  577. else if (Match(keymap.MoveCursorToTheStartOfDocumentWithSelection))
  578. {
  579. MoveHome(true);
  580. movement = true;
  581. selection = true;
  582. handled = true;
  583. }
  584. else if (Match(keymap.MoveCursorToTheEndOfDocumentWithSelection))
  585. {
  586. MoveEnd(true);
  587. movement = true;
  588. selection = true;
  589. handled = true;
  590. }
  591. else if (Match(keymap.MoveCursorToTheStartOfLineWithSelection))
  592. {
  593. MoveHome(false);
  594. movement = true;
  595. selection = true;
  596. handled = true;
  597. }
  598. else if (Match(keymap.MoveCursorToTheEndOfLineWithSelection))
  599. {
  600. MoveEnd(false);
  601. movement = true;
  602. selection = true;
  603. handled = true;
  604. }
  605. else
  606. {
  607. bool hasWholeWordModifiers = modifiers.HasFlagCustom(keymap.WholeWordTextActionModifiers);
  608. switch (e.Key)
  609. {
  610. case Key.Left:
  611. selection = DetectSelection();
  612. MoveHorizontal(-1, hasWholeWordModifiers, selection);
  613. movement = true;
  614. break;
  615. case Key.Right:
  616. selection = DetectSelection();
  617. MoveHorizontal(1, hasWholeWordModifiers, selection);
  618. movement = true;
  619. break;
  620. case Key.Up:
  621. movement = MoveVertical(-1);
  622. selection = DetectSelection();
  623. break;
  624. case Key.Down:
  625. movement = MoveVertical(1);
  626. selection = DetectSelection();
  627. break;
  628. case Key.Back:
  629. _undoRedoHelper.Snapshot();
  630. if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
  631. {
  632. SetSelectionForControlBackspace();
  633. }
  634. if (!DeleteSelection() && CaretIndex > 0)
  635. {
  636. var removedCharacters = 1;
  637. // handle deleting /r/n
  638. // you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
  639. // a /r should also be deleted.
  640. if (CaretIndex > 1 &&
  641. text[CaretIndex - 1] == '\n' &&
  642. text[CaretIndex - 2] == '\r')
  643. {
  644. removedCharacters = 2;
  645. }
  646. SetTextInternal(text.Substring(0, caretIndex - removedCharacters) +
  647. text.Substring(caretIndex));
  648. CaretIndex -= removedCharacters;
  649. ClearSelection();
  650. }
  651. _undoRedoHelper.Snapshot();
  652. handled = true;
  653. break;
  654. case Key.Delete:
  655. _undoRedoHelper.Snapshot();
  656. if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
  657. {
  658. SetSelectionForControlDelete();
  659. }
  660. if (!DeleteSelection() && caretIndex < text.Length)
  661. {
  662. var removedCharacters = 1;
  663. // handle deleting /r/n
  664. // you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
  665. // a /r should also be deleted.
  666. if (CaretIndex < text.Length - 1 &&
  667. text[caretIndex + 1] == '\n' &&
  668. text[caretIndex] == '\r')
  669. {
  670. removedCharacters = 2;
  671. }
  672. SetTextInternal(text.Substring(0, caretIndex) +
  673. text.Substring(caretIndex + removedCharacters));
  674. }
  675. _undoRedoHelper.Snapshot();
  676. handled = true;
  677. break;
  678. case Key.Enter:
  679. if (AcceptsReturn)
  680. {
  681. _undoRedoHelper.Snapshot();
  682. HandleTextInput(NewLine);
  683. _undoRedoHelper.Snapshot();
  684. handled = true;
  685. }
  686. break;
  687. case Key.Tab:
  688. if (AcceptsTab)
  689. {
  690. _undoRedoHelper.Snapshot();
  691. HandleTextInput("\t");
  692. _undoRedoHelper.Snapshot();
  693. handled = true;
  694. }
  695. else
  696. {
  697. base.OnKeyDown(e);
  698. }
  699. break;
  700. default:
  701. handled = false;
  702. break;
  703. }
  704. }
  705. if (movement && selection)
  706. {
  707. SelectionEnd = CaretIndex;
  708. }
  709. else if (movement)
  710. {
  711. ClearSelection();
  712. }
  713. if (handled || movement)
  714. {
  715. e.Handled = true;
  716. }
  717. }
  718. protected override void OnPointerPressed(PointerPressedEventArgs e)
  719. {
  720. var text = Text;
  721. var clickInfo = e.GetCurrentPoint(this);
  722. if (text != null && clickInfo.Properties.IsLeftButtonPressed && !(clickInfo.Pointer?.Captured is Border))
  723. {
  724. var point = e.GetPosition(_presenter);
  725. var index = CaretIndex = _presenter.GetCaretIndex(point);
  726. switch (e.ClickCount)
  727. {
  728. case 1:
  729. SelectionStart = SelectionEnd = index;
  730. break;
  731. case 2:
  732. if (!StringUtils.IsStartOfWord(text, index))
  733. {
  734. SelectionStart = StringUtils.PreviousWord(text, index);
  735. }
  736. SelectionEnd = StringUtils.NextWord(text, index);
  737. break;
  738. case 3:
  739. SelectAll();
  740. break;
  741. }
  742. }
  743. e.Pointer.Capture(_presenter);
  744. e.Handled = true;
  745. }
  746. protected override void OnPointerMoved(PointerEventArgs e)
  747. {
  748. // selection should not change during pointer move if the user right clicks
  749. if (_presenter != null && e.Pointer.Captured == _presenter && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
  750. {
  751. var point = e.GetPosition(_presenter);
  752. point = new Point(
  753. MathUtilities.Clamp(point.X, 0, Math.Max(_presenter.Bounds.Width - 1, 0)),
  754. MathUtilities.Clamp(point.Y, 0, Math.Max(_presenter.Bounds.Height - 1, 0)));
  755. CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
  756. }
  757. }
  758. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  759. {
  760. if (_presenter != null && e.Pointer.Captured == _presenter)
  761. {
  762. if (e.InitialPressMouseButton == MouseButton.Right)
  763. {
  764. var point = e.GetPosition(_presenter);
  765. var caretIndex = _presenter.GetCaretIndex(point);
  766. // see if mouse clicked inside current selection
  767. // if it did not, we change the selection to where the user clicked
  768. var firstSelection = Math.Min(SelectionStart, SelectionEnd);
  769. var lastSelection = Math.Max(SelectionStart, SelectionEnd);
  770. var didClickInSelection = SelectionStart != SelectionEnd &&
  771. caretIndex >= firstSelection && caretIndex <= lastSelection;
  772. if (!didClickInSelection)
  773. {
  774. CaretIndex = SelectionEnd = SelectionStart = caretIndex;
  775. }
  776. }
  777. e.Pointer.Capture(null);
  778. }
  779. }
  780. protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
  781. {
  782. if (property == TextProperty)
  783. {
  784. DataValidationErrors.SetError(this, value.Error);
  785. }
  786. }
  787. private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text);
  788. private int CoerceCaretIndex(int value, string text)
  789. {
  790. if (text == null)
  791. {
  792. return 0;
  793. }
  794. var length = text.Length;
  795. if (value < 0)
  796. {
  797. return 0;
  798. }
  799. else if (value > length)
  800. {
  801. return length;
  802. }
  803. else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
  804. {
  805. return value + 1;
  806. }
  807. else
  808. {
  809. return value;
  810. }
  811. }
  812. public void Clear()
  813. {
  814. Text = string.Empty;
  815. }
  816. private int DeleteCharacter(int index)
  817. {
  818. var start = index + 1;
  819. var text = Text;
  820. var c = text[index];
  821. var result = 1;
  822. if (c == '\n' && index > 0 && text[index - 1] == '\r')
  823. {
  824. --index;
  825. ++result;
  826. }
  827. else if (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n')
  828. {
  829. ++start;
  830. ++result;
  831. }
  832. Text = text.Substring(0, index) + text.Substring(start);
  833. return result;
  834. }
  835. private void MoveHorizontal(int direction, bool wholeWord, bool isSelecting)
  836. {
  837. var text = Text ?? string.Empty;
  838. var caretIndex = CaretIndex;
  839. if (!wholeWord)
  840. {
  841. if (SelectionStart != SelectionEnd && !isSelecting)
  842. {
  843. var start = Math.Min(SelectionStart, SelectionEnd);
  844. var end = Math.Max(SelectionStart, SelectionEnd);
  845. CaretIndex = direction < 0 ? start : end;
  846. return;
  847. }
  848. var index = caretIndex + direction;
  849. if (index < 0 || index > text.Length)
  850. {
  851. return;
  852. }
  853. else if (index == text.Length)
  854. {
  855. CaretIndex = index;
  856. return;
  857. }
  858. var c = text[index];
  859. if (direction > 0)
  860. {
  861. CaretIndex += (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n') ? 2 : 1;
  862. }
  863. else
  864. {
  865. CaretIndex -= (c == '\n' && index > 0 && text[index - 1] == '\r') ? 2 : 1;
  866. }
  867. }
  868. else
  869. {
  870. if (direction > 0)
  871. {
  872. CaretIndex += StringUtils.NextWord(text, caretIndex) - caretIndex;
  873. }
  874. else
  875. {
  876. CaretIndex += StringUtils.PreviousWord(text, caretIndex) - caretIndex;
  877. }
  878. }
  879. }
  880. private bool MoveVertical(int count)
  881. {
  882. var formattedText = _presenter.FormattedText;
  883. var lines = formattedText.GetLines().ToList();
  884. var caretIndex = CaretIndex;
  885. var lineIndex = GetLine(caretIndex, lines) + count;
  886. if (lineIndex >= 0 && lineIndex < lines.Count)
  887. {
  888. var line = lines[lineIndex];
  889. var rect = formattedText.HitTestTextPosition(caretIndex);
  890. var y = count < 0 ? rect.Y : rect.Bottom;
  891. var point = new Point(rect.X, y + (count * (line.Height / 2)));
  892. var hit = formattedText.HitTestPoint(point);
  893. CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
  894. return true;
  895. }
  896. else
  897. {
  898. return false;
  899. }
  900. }
  901. private void MoveHome(bool document)
  902. {
  903. var text = Text ?? string.Empty;
  904. var caretIndex = CaretIndex;
  905. if (document)
  906. {
  907. caretIndex = 0;
  908. }
  909. else
  910. {
  911. var lines = _presenter.FormattedText.GetLines();
  912. var pos = 0;
  913. foreach (var line in lines)
  914. {
  915. if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
  916. {
  917. break;
  918. }
  919. pos += line.Length;
  920. }
  921. caretIndex = pos;
  922. }
  923. CaretIndex = caretIndex;
  924. }
  925. private void MoveEnd(bool document)
  926. {
  927. var text = Text ?? string.Empty;
  928. var caretIndex = CaretIndex;
  929. if (document)
  930. {
  931. caretIndex = text.Length;
  932. }
  933. else
  934. {
  935. var lines = _presenter.FormattedText.GetLines();
  936. var pos = 0;
  937. foreach (var line in lines)
  938. {
  939. pos += line.Length;
  940. if (pos > caretIndex)
  941. {
  942. if (pos < text.Length)
  943. {
  944. --pos;
  945. if (pos > 0 && text[pos - 1] == '\r' && text[pos] == '\n')
  946. {
  947. --pos;
  948. }
  949. }
  950. break;
  951. }
  952. }
  953. caretIndex = pos;
  954. }
  955. CaretIndex = caretIndex;
  956. }
  957. /// <summary>
  958. /// Select all text in the TextBox
  959. /// </summary>
  960. public void SelectAll()
  961. {
  962. SelectionStart = 0;
  963. SelectionEnd = Text?.Length ?? 0;
  964. CaretIndex = SelectionEnd;
  965. }
  966. private bool DeleteSelection()
  967. {
  968. if (!IsReadOnly)
  969. {
  970. var selectionStart = SelectionStart;
  971. var selectionEnd = SelectionEnd;
  972. if (selectionStart != selectionEnd)
  973. {
  974. var start = Math.Min(selectionStart, selectionEnd);
  975. var end = Math.Max(selectionStart, selectionEnd);
  976. var text = Text;
  977. SetTextInternal(text.Substring(0, start) + text.Substring(end));
  978. CaretIndex = start;
  979. ClearSelection();
  980. return true;
  981. }
  982. else
  983. {
  984. return false;
  985. }
  986. }
  987. else
  988. {
  989. return true;
  990. }
  991. }
  992. private string GetSelection()
  993. {
  994. var text = Text;
  995. if (string.IsNullOrEmpty(text))
  996. return "";
  997. var selectionStart = SelectionStart;
  998. var selectionEnd = SelectionEnd;
  999. var start = Math.Min(selectionStart, selectionEnd);
  1000. var end = Math.Max(selectionStart, selectionEnd);
  1001. if (start == end || (Text?.Length ?? 0) < end)
  1002. {
  1003. return "";
  1004. }
  1005. return text.Substring(start, end - start);
  1006. }
  1007. private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
  1008. {
  1009. int pos = 0;
  1010. int i;
  1011. for (i = 0; i < lines.Count - 1; ++i)
  1012. {
  1013. var line = lines[i];
  1014. pos += line.Length;
  1015. if (pos > caretIndex)
  1016. {
  1017. break;
  1018. }
  1019. }
  1020. return i;
  1021. }
  1022. private void SetTextInternal(string value)
  1023. {
  1024. try
  1025. {
  1026. _ignoreTextChanges = true;
  1027. SetAndRaise(TextProperty, ref _text, value);
  1028. }
  1029. finally
  1030. {
  1031. _ignoreTextChanges = false;
  1032. }
  1033. }
  1034. private void SetSelectionForControlBackspace()
  1035. {
  1036. SelectionStart = CaretIndex;
  1037. MoveHorizontal(-1, true, false);
  1038. SelectionEnd = CaretIndex;
  1039. }
  1040. private void SetSelectionForControlDelete()
  1041. {
  1042. SelectionStart = CaretIndex;
  1043. MoveHorizontal(1, true, false);
  1044. SelectionEnd = CaretIndex;
  1045. }
  1046. private void UpdatePseudoclasses()
  1047. {
  1048. PseudoClasses.Set(":empty", string.IsNullOrWhiteSpace(Text));
  1049. }
  1050. private bool IsPasswordBox => PasswordChar != default(char);
  1051. UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
  1052. {
  1053. get { return new UndoRedoState(Text, CaretIndex); }
  1054. set
  1055. {
  1056. Text = value.Text;
  1057. CaretIndex = value.CaretPosition;
  1058. ClearSelection();
  1059. }
  1060. }
  1061. }
  1062. }