TextBox.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using Avalonia.Input.Platform;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reactive.Linq;
  8. using Avalonia.Controls.Presenters;
  9. using Avalonia.Controls.Primitives;
  10. using Avalonia.Controls.Utils;
  11. using Avalonia.Input;
  12. using Avalonia.Interactivity;
  13. using Avalonia.Media;
  14. using Avalonia.Metadata;
  15. using Avalonia.Data;
  16. namespace Avalonia.Controls
  17. {
  18. public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
  19. {
  20. public static readonly StyledProperty<bool> AcceptsReturnProperty =
  21. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
  22. public static readonly StyledProperty<bool> AcceptsTabProperty =
  23. AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
  24. public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
  25. AvaloniaProperty.RegisterDirect<TextBox, int>(
  26. nameof(CaretIndex),
  27. o => o.CaretIndex,
  28. (o, v) => o.CaretIndex = v);
  29. public static readonly StyledProperty<bool> IsReadOnlyProperty =
  30. AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
  31. public static readonly StyledProperty<char> PasswordCharProperty =
  32. AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
  33. public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
  34. AvaloniaProperty.RegisterDirect<TextBox, int>(
  35. nameof(SelectionStart),
  36. o => o.SelectionStart,
  37. (o, v) => o.SelectionStart = v);
  38. public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
  39. AvaloniaProperty.RegisterDirect<TextBox, int>(
  40. nameof(SelectionEnd),
  41. o => o.SelectionEnd,
  42. (o, v) => o.SelectionEnd = v);
  43. public static readonly DirectProperty<TextBox, string> TextProperty =
  44. TextBlock.TextProperty.AddOwner<TextBox>(
  45. o => o.Text,
  46. (o, v) => o.Text = v,
  47. defaultBindingMode: BindingMode.TwoWay,
  48. enableDataValidation: true);
  49. public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
  50. TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
  51. public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
  52. TextBlock.TextWrappingProperty.AddOwner<TextBox>();
  53. public static readonly StyledProperty<string> WatermarkProperty =
  54. AvaloniaProperty.Register<TextBox, string>(nameof(Watermark));
  55. public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
  56. AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
  57. public static readonly DirectProperty<TextBox, string> NewLineProperty =
  58. AvaloniaProperty.RegisterDirect<TextBox, string>(nameof(NewLine),
  59. textbox => textbox.NewLine, (textbox, newline) => textbox.NewLine = newline);
  60. struct UndoRedoState : IEquatable<UndoRedoState>
  61. {
  62. public string Text { get; }
  63. public int CaretPosition { get; }
  64. public UndoRedoState(string text, int caretPosition)
  65. {
  66. Text = text;
  67. CaretPosition = caretPosition;
  68. }
  69. public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
  70. }
  71. private string _text;
  72. private int _caretIndex;
  73. private int _selectionStart;
  74. private int _selectionEnd;
  75. private TextPresenter _presenter;
  76. private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
  77. private bool _isUndoingRedoing;
  78. private bool _ignoreTextChanges;
  79. private string _newLine = Environment.NewLine;
  80. private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
  81. static TextBox()
  82. {
  83. FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
  84. }
  85. public TextBox()
  86. {
  87. var horizontalScrollBarVisibility = Observable.CombineLatest(
  88. this.GetObservable(AcceptsReturnProperty),
  89. this.GetObservable(TextWrappingProperty),
  90. (acceptsReturn, wrapping) =>
  91. {
  92. if (acceptsReturn)
  93. {
  94. return wrapping == TextWrapping.NoWrap ?
  95. ScrollBarVisibility.Auto :
  96. ScrollBarVisibility.Disabled;
  97. }
  98. else
  99. {
  100. return ScrollBarVisibility.Hidden;
  101. }
  102. });
  103. Bind(
  104. ScrollViewer.HorizontalScrollBarVisibilityProperty,
  105. horizontalScrollBarVisibility,
  106. BindingPriority.Style);
  107. _undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
  108. }
  109. public bool AcceptsReturn
  110. {
  111. get { return GetValue(AcceptsReturnProperty); }
  112. set { SetValue(AcceptsReturnProperty, value); }
  113. }
  114. public bool AcceptsTab
  115. {
  116. get { return GetValue(AcceptsTabProperty); }
  117. set { SetValue(AcceptsTabProperty, value); }
  118. }
  119. public int CaretIndex
  120. {
  121. get
  122. {
  123. return _caretIndex;
  124. }
  125. set
  126. {
  127. value = CoerceCaretIndex(value);
  128. SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
  129. UndoRedoState state;
  130. if (_undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
  131. _undoRedoHelper.UpdateLastState();
  132. }
  133. }
  134. public bool IsReadOnly
  135. {
  136. get { return GetValue(IsReadOnlyProperty); }
  137. set { SetValue(IsReadOnlyProperty, value); }
  138. }
  139. public char PasswordChar
  140. {
  141. get => GetValue(PasswordCharProperty);
  142. set => SetValue(PasswordCharProperty, value);
  143. }
  144. public int SelectionStart
  145. {
  146. get
  147. {
  148. return _selectionStart;
  149. }
  150. set
  151. {
  152. value = CoerceCaretIndex(value);
  153. SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
  154. if (SelectionStart == SelectionEnd)
  155. {
  156. CaretIndex = SelectionStart;
  157. }
  158. }
  159. }
  160. public int SelectionEnd
  161. {
  162. get
  163. {
  164. return _selectionEnd;
  165. }
  166. set
  167. {
  168. value = CoerceCaretIndex(value);
  169. SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
  170. if (SelectionStart == SelectionEnd)
  171. {
  172. CaretIndex = SelectionEnd;
  173. }
  174. }
  175. }
  176. [Content]
  177. public string Text
  178. {
  179. get { return _text; }
  180. set
  181. {
  182. if (!_ignoreTextChanges)
  183. {
  184. CaretIndex = CoerceCaretIndex(CaretIndex, value?.Length ?? 0);
  185. if (SetAndRaise(TextProperty, ref _text, value) && !_isUndoingRedoing)
  186. {
  187. _undoRedoHelper.Clear();
  188. }
  189. }
  190. }
  191. }
  192. public TextAlignment TextAlignment
  193. {
  194. get { return GetValue(TextAlignmentProperty); }
  195. set { SetValue(TextAlignmentProperty, value); }
  196. }
  197. public string Watermark
  198. {
  199. get { return GetValue(WatermarkProperty); }
  200. set { SetValue(WatermarkProperty, value); }
  201. }
  202. public bool UseFloatingWatermark
  203. {
  204. get { return GetValue(UseFloatingWatermarkProperty); }
  205. set { SetValue(UseFloatingWatermarkProperty, value); }
  206. }
  207. public TextWrapping TextWrapping
  208. {
  209. get { return GetValue(TextWrappingProperty); }
  210. set { SetValue(TextWrappingProperty, value); }
  211. }
  212. /// <summary>
  213. /// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
  214. /// </summary>
  215. public string NewLine
  216. {
  217. get { return _newLine; }
  218. set { SetAndRaise(NewLineProperty, ref _newLine, value); }
  219. }
  220. protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
  221. {
  222. _presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
  223. _presenter.Cursor = new Cursor(StandardCursorType.Ibeam);
  224. if (IsFocused)
  225. {
  226. DecideCaretVisibility();
  227. }
  228. }
  229. protected override void OnGotFocus(GotFocusEventArgs e)
  230. {
  231. base.OnGotFocus(e);
  232. // when navigating to a textbox via the tab key, select all text if
  233. // 1) this textbox is *not* a multiline textbox
  234. // 2) this textbox has any text to select
  235. if (e.NavigationMethod == NavigationMethod.Tab &&
  236. !AcceptsReturn &&
  237. Text?.Length > 0)
  238. {
  239. SelectionStart = 0;
  240. SelectionEnd = Text.Length;
  241. }
  242. else
  243. {
  244. DecideCaretVisibility();
  245. }
  246. e.Handled = true;
  247. }
  248. private void DecideCaretVisibility()
  249. {
  250. if (!IsReadOnly || IsReadOnlyCaretVisible)
  251. _presenter?.ShowCaret();
  252. else
  253. _presenter?.HideCaret();
  254. }
  255. protected override void OnLostFocus(RoutedEventArgs e)
  256. {
  257. base.OnLostFocus(e);
  258. SelectionStart = 0;
  259. SelectionEnd = 0;
  260. _presenter?.HideCaret();
  261. }
  262. protected override void OnTextInput(TextInputEventArgs e)
  263. {
  264. if (!e.Handled)
  265. {
  266. HandleTextInput(e.Text);
  267. e.Handled = true;
  268. }
  269. }
  270. private void HandleTextInput(string input)
  271. {
  272. if (!IsReadOnly)
  273. {
  274. input = RemoveInvalidCharacters(input);
  275. string text = Text ?? string.Empty;
  276. int caretIndex = CaretIndex;
  277. if (!string.IsNullOrEmpty(input))
  278. {
  279. DeleteSelection();
  280. caretIndex = CaretIndex;
  281. text = Text ?? string.Empty;
  282. SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex));
  283. CaretIndex += input.Length;
  284. SelectionStart = SelectionEnd = CaretIndex;
  285. _undoRedoHelper.DiscardRedo();
  286. }
  287. }
  288. }
  289. public string RemoveInvalidCharacters(string text)
  290. {
  291. for (var i = 0; i < invalidCharacters.Length; i++)
  292. {
  293. text = text.Replace(invalidCharacters[i], string.Empty);
  294. }
  295. return text;
  296. }
  297. private async void Copy()
  298. {
  299. await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
  300. .SetTextAsync(GetSelection());
  301. }
  302. private async void Paste()
  303. {
  304. var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
  305. if (text == null)
  306. {
  307. return;
  308. }
  309. _undoRedoHelper.Snapshot();
  310. HandleTextInput(text);
  311. }
  312. protected override void OnKeyDown(KeyEventArgs e)
  313. {
  314. string text = Text ?? string.Empty;
  315. int caretIndex = CaretIndex;
  316. bool movement = false;
  317. bool handled = false;
  318. var modifiers = e.Modifiers;
  319. switch (e.Key)
  320. {
  321. case Key.A:
  322. if (modifiers == InputModifiers.Control)
  323. {
  324. SelectAll();
  325. handled = true;
  326. }
  327. break;
  328. case Key.C:
  329. if (modifiers == InputModifiers.Control)
  330. {
  331. if (!IsPasswordBox)
  332. {
  333. Copy();
  334. }
  335. handled = true;
  336. }
  337. break;
  338. case Key.X:
  339. if (modifiers == InputModifiers.Control)
  340. {
  341. if (!IsPasswordBox)
  342. {
  343. Copy();
  344. DeleteSelection();
  345. }
  346. handled = true;
  347. }
  348. break;
  349. case Key.V:
  350. if (modifiers == InputModifiers.Control)
  351. {
  352. Paste();
  353. handled = true;
  354. }
  355. break;
  356. case Key.Z:
  357. if (modifiers == InputModifiers.Control)
  358. {
  359. try
  360. {
  361. _isUndoingRedoing = true;
  362. _undoRedoHelper.Undo();
  363. }
  364. finally
  365. {
  366. _isUndoingRedoing = false;
  367. }
  368. handled = true;
  369. }
  370. break;
  371. case Key.Y:
  372. if (modifiers == InputModifiers.Control)
  373. {
  374. try
  375. {
  376. _isUndoingRedoing = true;
  377. _undoRedoHelper.Redo();
  378. }
  379. finally
  380. {
  381. _isUndoingRedoing = false;
  382. }
  383. handled = true;
  384. }
  385. break;
  386. case Key.Left:
  387. MoveHorizontal(-1, modifiers);
  388. movement = true;
  389. break;
  390. case Key.Right:
  391. MoveHorizontal(1, modifiers);
  392. movement = true;
  393. break;
  394. case Key.Up:
  395. movement = MoveVertical(-1, modifiers);
  396. break;
  397. case Key.Down:
  398. movement = MoveVertical(1, modifiers);
  399. break;
  400. case Key.Home:
  401. MoveHome(modifiers);
  402. movement = true;
  403. break;
  404. case Key.End:
  405. MoveEnd(modifiers);
  406. movement = true;
  407. break;
  408. case Key.Back:
  409. if (modifiers == InputModifiers.Control && SelectionStart == SelectionEnd)
  410. {
  411. SetSelectionForControlBackspace(modifiers);
  412. }
  413. if (!DeleteSelection() && CaretIndex > 0)
  414. {
  415. var removedCharacters = 1;
  416. // handle deleting /r/n
  417. // you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
  418. // a /r should also be deleted.
  419. if (CaretIndex > 1 &&
  420. text[CaretIndex - 1] == '\n' &&
  421. text[CaretIndex - 2] == '\r')
  422. {
  423. removedCharacters = 2;
  424. }
  425. SetTextInternal(text.Substring(0, caretIndex - removedCharacters) + text.Substring(caretIndex));
  426. CaretIndex -= removedCharacters;
  427. SelectionStart = SelectionEnd = CaretIndex;
  428. }
  429. handled = true;
  430. break;
  431. case Key.Delete:
  432. if (modifiers == InputModifiers.Control && SelectionStart == SelectionEnd)
  433. {
  434. SetSelectionForControlDelete(modifiers);
  435. }
  436. if (!DeleteSelection() && caretIndex < text.Length)
  437. {
  438. var removedCharacters = 1;
  439. // handle deleting /r/n
  440. // you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
  441. // a /r should also be deleted.
  442. if (CaretIndex < text.Length - 1 &&
  443. text[caretIndex + 1] == '\n' &&
  444. text[caretIndex] == '\r')
  445. {
  446. removedCharacters = 2;
  447. }
  448. SetTextInternal(text.Substring(0, caretIndex) + text.Substring(caretIndex + removedCharacters));
  449. }
  450. handled = true;
  451. break;
  452. case Key.Enter:
  453. if (AcceptsReturn)
  454. {
  455. HandleTextInput(NewLine);
  456. handled = true;
  457. }
  458. break;
  459. case Key.Tab:
  460. if (AcceptsTab)
  461. {
  462. HandleTextInput("\t");
  463. handled = true;
  464. }
  465. else
  466. {
  467. base.OnKeyDown(e);
  468. }
  469. break;
  470. default:
  471. handled = false;
  472. break;
  473. }
  474. if (movement && ((modifiers & InputModifiers.Shift) != 0))
  475. {
  476. SelectionEnd = CaretIndex;
  477. }
  478. else if (movement)
  479. {
  480. SelectionStart = SelectionEnd = CaretIndex;
  481. }
  482. if (handled || movement)
  483. {
  484. e.Handled = true;
  485. }
  486. }
  487. protected override void OnPointerPressed(PointerPressedEventArgs e)
  488. {
  489. var point = e.GetPosition(_presenter);
  490. var index = CaretIndex = _presenter.GetCaretIndex(point);
  491. var text = Text;
  492. if (text != null)
  493. {
  494. switch (e.ClickCount)
  495. {
  496. case 1:
  497. SelectionStart = SelectionEnd = index;
  498. break;
  499. case 2:
  500. if (!StringUtils.IsStartOfWord(text, index))
  501. {
  502. SelectionStart = StringUtils.PreviousWord(text, index);
  503. }
  504. SelectionEnd = StringUtils.NextWord(text, index);
  505. break;
  506. case 3:
  507. SelectionStart = 0;
  508. SelectionEnd = text.Length;
  509. break;
  510. }
  511. }
  512. e.Device.Capture(_presenter);
  513. e.Handled = true;
  514. }
  515. protected override void OnPointerMoved(PointerEventArgs e)
  516. {
  517. if (_presenter != null && e.Device.Captured == _presenter)
  518. {
  519. var point = e.GetPosition(_presenter);
  520. CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
  521. }
  522. }
  523. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  524. {
  525. if (_presenter != null && e.Device.Captured == _presenter)
  526. {
  527. e.Device.Capture(null);
  528. }
  529. }
  530. protected override void UpdateDataValidation(AvaloniaProperty property, BindingNotification status)
  531. {
  532. if (property == TextProperty)
  533. {
  534. DataValidationErrors.SetError(this, status.Error);
  535. }
  536. }
  537. private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text?.Length ?? 0);
  538. private int CoerceCaretIndex(int value, int length)
  539. {
  540. var text = Text;
  541. if (value < 0)
  542. {
  543. return 0;
  544. }
  545. else if (value > length)
  546. {
  547. return length;
  548. }
  549. else if (value > 0 && text[value - 1] == '\r' && text[value] == '\n')
  550. {
  551. return value + 1;
  552. }
  553. else
  554. {
  555. return value;
  556. }
  557. }
  558. private int DeleteCharacter(int index)
  559. {
  560. var start = index + 1;
  561. var text = Text;
  562. var c = text[index];
  563. var result = 1;
  564. if (c == '\n' && index > 0 && text[index - 1] == '\r')
  565. {
  566. --index;
  567. ++result;
  568. }
  569. else if (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n')
  570. {
  571. ++start;
  572. ++result;
  573. }
  574. Text = text.Substring(0, index) + text.Substring(start);
  575. return result;
  576. }
  577. private void MoveHorizontal(int direction, InputModifiers modifiers)
  578. {
  579. var text = Text ?? string.Empty;
  580. var caretIndex = CaretIndex;
  581. if ((modifiers & InputModifiers.Control) == 0)
  582. {
  583. var index = caretIndex + direction;
  584. if (index < 0 || index > text.Length)
  585. {
  586. return;
  587. }
  588. else if (index == text.Length)
  589. {
  590. CaretIndex = index;
  591. return;
  592. }
  593. var c = text[index];
  594. if (direction > 0)
  595. {
  596. CaretIndex += (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n') ? 2 : 1;
  597. }
  598. else
  599. {
  600. CaretIndex -= (c == '\n' && index > 0 && text[index - 1] == '\r') ? 2 : 1;
  601. }
  602. }
  603. else
  604. {
  605. if (direction > 0)
  606. {
  607. CaretIndex += StringUtils.NextWord(text, caretIndex) - caretIndex;
  608. }
  609. else
  610. {
  611. CaretIndex += StringUtils.PreviousWord(text, caretIndex) - caretIndex;
  612. }
  613. }
  614. }
  615. private bool MoveVertical(int count, InputModifiers modifiers)
  616. {
  617. var formattedText = _presenter.FormattedText;
  618. var lines = formattedText.GetLines().ToList();
  619. var caretIndex = CaretIndex;
  620. var lineIndex = GetLine(caretIndex, lines) + count;
  621. if (lineIndex >= 0 && lineIndex < lines.Count)
  622. {
  623. var line = lines[lineIndex];
  624. var rect = formattedText.HitTestTextPosition(caretIndex);
  625. var y = count < 0 ? rect.Y : rect.Bottom;
  626. var point = new Point(rect.X, y + (count * (line.Height / 2)));
  627. var hit = formattedText.HitTestPoint(point);
  628. CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
  629. return true;
  630. }
  631. else
  632. {
  633. return false;
  634. }
  635. }
  636. private void MoveHome(InputModifiers modifiers)
  637. {
  638. var text = Text ?? string.Empty;
  639. var caretIndex = CaretIndex;
  640. if ((modifiers & InputModifiers.Control) != 0)
  641. {
  642. caretIndex = 0;
  643. }
  644. else
  645. {
  646. var lines = _presenter.FormattedText.GetLines();
  647. var pos = 0;
  648. foreach (var line in lines)
  649. {
  650. if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
  651. {
  652. break;
  653. }
  654. pos += line.Length;
  655. }
  656. caretIndex = pos;
  657. }
  658. CaretIndex = caretIndex;
  659. }
  660. private void MoveEnd(InputModifiers modifiers)
  661. {
  662. var text = Text ?? string.Empty;
  663. var caretIndex = CaretIndex;
  664. if ((modifiers & InputModifiers.Control) != 0)
  665. {
  666. caretIndex = text.Length;
  667. }
  668. else
  669. {
  670. var lines = _presenter.FormattedText.GetLines();
  671. var pos = 0;
  672. foreach (var line in lines)
  673. {
  674. pos += line.Length;
  675. if (pos > caretIndex)
  676. {
  677. if (pos < text.Length)
  678. {
  679. --pos;
  680. if (pos > 0 && text[pos - 1] == '\r' && text[pos] == '\n')
  681. {
  682. --pos;
  683. }
  684. }
  685. break;
  686. }
  687. }
  688. caretIndex = pos;
  689. }
  690. CaretIndex = caretIndex;
  691. }
  692. private void SelectAll()
  693. {
  694. SelectionStart = 0;
  695. SelectionEnd = Text?.Length ?? 0;
  696. }
  697. private bool DeleteSelection()
  698. {
  699. if (!IsReadOnly)
  700. {
  701. var selectionStart = SelectionStart;
  702. var selectionEnd = SelectionEnd;
  703. if (selectionStart != selectionEnd)
  704. {
  705. var start = Math.Min(selectionStart, selectionEnd);
  706. var end = Math.Max(selectionStart, selectionEnd);
  707. var text = Text;
  708. SetTextInternal(text.Substring(0, start) + text.Substring(end));
  709. SelectionStart = SelectionEnd = CaretIndex = start;
  710. return true;
  711. }
  712. else
  713. {
  714. return false;
  715. }
  716. }
  717. else
  718. {
  719. return true;
  720. }
  721. }
  722. private string GetSelection()
  723. {
  724. var text = Text;
  725. if (string.IsNullOrEmpty(text))
  726. return "";
  727. var selectionStart = SelectionStart;
  728. var selectionEnd = SelectionEnd;
  729. var start = Math.Min(selectionStart, selectionEnd);
  730. var end = Math.Max(selectionStart, selectionEnd);
  731. if (start == end || (Text?.Length ?? 0) < end)
  732. {
  733. return "";
  734. }
  735. return text.Substring(start, end - start);
  736. }
  737. private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
  738. {
  739. int pos = 0;
  740. int i;
  741. for (i = 0; i < lines.Count - 1; ++i)
  742. {
  743. var line = lines[i];
  744. pos += line.Length;
  745. if (pos > caretIndex)
  746. {
  747. break;
  748. }
  749. }
  750. return i;
  751. }
  752. private void SetTextInternal(string value)
  753. {
  754. try
  755. {
  756. _ignoreTextChanges = true;
  757. SetAndRaise(TextProperty, ref _text, value);
  758. }
  759. finally
  760. {
  761. _ignoreTextChanges = false;
  762. }
  763. }
  764. private void SetSelectionForControlBackspace(InputModifiers modifiers)
  765. {
  766. SelectionStart = CaretIndex;
  767. MoveHorizontal(-1, modifiers);
  768. SelectionEnd = CaretIndex;
  769. }
  770. private void SetSelectionForControlDelete(InputModifiers modifiers)
  771. {
  772. SelectionStart = CaretIndex;
  773. MoveHorizontal(1, modifiers);
  774. SelectionEnd = CaretIndex;
  775. }
  776. private bool IsPasswordBox => PasswordChar != default(char);
  777. UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
  778. {
  779. get { return new UndoRedoState(Text, CaretIndex); }
  780. set
  781. {
  782. Text = value.Text;
  783. SelectionStart = SelectionEnd = CaretIndex = value.CaretPosition;
  784. }
  785. }
  786. }
  787. }