TextBox.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. // Copyright (c) The Perspex Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using Perspex.Input.Platform;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reactive.Linq;
  8. using Perspex.Controls.Presenters;
  9. using Perspex.Controls.Primitives;
  10. using Perspex.Controls.Templates;
  11. using Perspex.Controls.Utils;
  12. using Perspex.Input;
  13. using Perspex.Interactivity;
  14. using Perspex.Media;
  15. using Perspex.Metadata;
  16. namespace Perspex.Controls
  17. {
  18. public class TextBox : TemplatedControl
  19. {
  20. public static readonly PerspexProperty<bool> AcceptsReturnProperty =
  21. PerspexProperty.Register<TextBox, bool>("AcceptsReturn");
  22. public static readonly PerspexProperty<bool> AcceptsTabProperty =
  23. PerspexProperty.Register<TextBox, bool>("AcceptsTab");
  24. public static readonly PerspexProperty<int> CaretIndexProperty =
  25. PerspexProperty.Register<TextBox, int>("CaretIndex", validate: ValidateCaretIndex);
  26. public static readonly PerspexProperty<int> SelectionStartProperty =
  27. PerspexProperty.Register<TextBox, int>("SelectionStart", validate: ValidateCaretIndex);
  28. public static readonly PerspexProperty<int> SelectionEndProperty =
  29. PerspexProperty.Register<TextBox, int>("SelectionEnd", validate: ValidateCaretIndex);
  30. public static readonly PerspexProperty<string> TextProperty =
  31. TextBlock.TextProperty.AddOwner<TextBox>();
  32. public static readonly PerspexProperty<TextWrapping> TextWrappingProperty =
  33. TextBlock.TextWrappingProperty.AddOwner<TextBox>();
  34. public static readonly PerspexProperty<string> WatermarkProperty =
  35. PerspexProperty.Register<TextBox, string>("Watermark");
  36. public static readonly PerspexProperty<bool> UseFloatingWatermarkProperty =
  37. PerspexProperty.Register<TextBox, bool>("UseFloatingWatermark");
  38. private TextPresenter _presenter;
  39. static TextBox()
  40. {
  41. FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
  42. }
  43. public TextBox()
  44. {
  45. var canScrollHorizontally = GetObservable(AcceptsReturnProperty)
  46. .Select(x => !x);
  47. Bind(
  48. ScrollViewer.CanScrollHorizontallyProperty,
  49. canScrollHorizontally,
  50. BindingPriority.Style);
  51. var horizontalScrollBarVisibility = GetObservable(AcceptsReturnProperty)
  52. .Select(x => x ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden);
  53. Bind(
  54. ScrollViewer.HorizontalScrollBarVisibilityProperty,
  55. horizontalScrollBarVisibility,
  56. BindingPriority.Style);
  57. }
  58. public bool AcceptsReturn
  59. {
  60. get { return GetValue(AcceptsReturnProperty); }
  61. set { SetValue(AcceptsReturnProperty, value); }
  62. }
  63. public bool AcceptsTab
  64. {
  65. get { return GetValue(AcceptsTabProperty); }
  66. set { SetValue(AcceptsTabProperty, value); }
  67. }
  68. public int CaretIndex
  69. {
  70. get { return GetValue(CaretIndexProperty); }
  71. set { SetValue(CaretIndexProperty, value); }
  72. }
  73. public int SelectionStart
  74. {
  75. get { return GetValue(SelectionStartProperty); }
  76. set { SetValue(SelectionStartProperty, value); }
  77. }
  78. public int SelectionEnd
  79. {
  80. get { return GetValue(SelectionEndProperty); }
  81. set { SetValue(SelectionEndProperty, value); }
  82. }
  83. [Content]
  84. public string Text
  85. {
  86. get { return GetValue(TextProperty); }
  87. set { SetValue(TextProperty, value); }
  88. }
  89. public string Watermark
  90. {
  91. get { return GetValue(WatermarkProperty); }
  92. set { SetValue(WatermarkProperty, value); }
  93. }
  94. public bool UseFloatingWatermark
  95. {
  96. get { return GetValue(UseFloatingWatermarkProperty); }
  97. set { SetValue(UseFloatingWatermarkProperty, value); }
  98. }
  99. public TextWrapping TextWrapping
  100. {
  101. get { return GetValue(TextWrappingProperty); }
  102. set { SetValue(TextWrappingProperty, value); }
  103. }
  104. protected override void OnTemplateApplied()
  105. {
  106. _presenter = this.GetTemplateChild<TextPresenter>("PART_TextPresenter");
  107. _presenter.Cursor = new Cursor(StandardCursorType.Ibeam);
  108. }
  109. protected override void OnGotFocus(GotFocusEventArgs e)
  110. {
  111. base.OnGotFocus(e);
  112. _presenter.ShowCaret();
  113. }
  114. protected override void OnLostFocus(RoutedEventArgs e)
  115. {
  116. base.OnLostFocus(e);
  117. SelectionStart = 0;
  118. SelectionEnd = 0;
  119. _presenter.HideCaret();
  120. }
  121. protected override void OnTextInput(TextInputEventArgs e)
  122. {
  123. HandleTextInput(e.Text);
  124. }
  125. private void HandleTextInput(string input)
  126. {
  127. string text = Text ?? string.Empty;
  128. int caretIndex = CaretIndex;
  129. if (!string.IsNullOrEmpty(input))
  130. {
  131. DeleteSelection();
  132. caretIndex = CaretIndex;
  133. text = Text ?? string.Empty;
  134. Text = text.Substring(0, caretIndex) + input + text.Substring(caretIndex);
  135. CaretIndex += input.Length;
  136. SelectionStart = SelectionEnd = CaretIndex;
  137. }
  138. }
  139. private async void Copy()
  140. {
  141. await ((IClipboard)PerspexLocator.Current.GetService(typeof(IClipboard)))
  142. .SetTextAsync(GetSelection());
  143. }
  144. private async void Paste()
  145. {
  146. var text = await ((IClipboard)PerspexLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
  147. if (text == null)
  148. {
  149. return;
  150. }
  151. HandleTextInput(text);
  152. }
  153. protected override void OnKeyDown(KeyEventArgs e)
  154. {
  155. string text = Text ?? string.Empty;
  156. int caretIndex = CaretIndex;
  157. bool movement = false;
  158. bool handled = true;
  159. var modifiers = e.Modifiers;
  160. switch (e.Key)
  161. {
  162. case Key.A:
  163. if (modifiers == InputModifiers.Control)
  164. {
  165. SelectAll();
  166. }
  167. break;
  168. case Key.C:
  169. if (modifiers == InputModifiers.Control)
  170. {
  171. Copy();
  172. }
  173. break;
  174. case Key.V:
  175. if (modifiers == InputModifiers.Control)
  176. {
  177. Paste();
  178. }
  179. break;
  180. case Key.Left:
  181. MoveHorizontal(-1, modifiers);
  182. movement = true;
  183. break;
  184. case Key.Right:
  185. MoveHorizontal(1, modifiers);
  186. movement = true;
  187. break;
  188. case Key.Up:
  189. MoveVertical(-1, modifiers);
  190. movement = true;
  191. break;
  192. case Key.Down:
  193. MoveVertical(1, modifiers);
  194. movement = true;
  195. break;
  196. case Key.Home:
  197. MoveHome(modifiers);
  198. movement = true;
  199. break;
  200. case Key.End:
  201. MoveEnd(modifiers);
  202. movement = true;
  203. break;
  204. case Key.Back:
  205. if (!DeleteSelection() && CaretIndex > 0)
  206. {
  207. Text = text.Substring(0, caretIndex - 1) + text.Substring(caretIndex);
  208. --CaretIndex;
  209. }
  210. break;
  211. case Key.Delete:
  212. if (!DeleteSelection() && caretIndex < text.Length)
  213. {
  214. Text = text.Substring(0, caretIndex) + text.Substring(caretIndex + 1);
  215. }
  216. break;
  217. case Key.Enter:
  218. if (AcceptsReturn)
  219. {
  220. HandleTextInput("\r\n");
  221. }
  222. break;
  223. case Key.Tab:
  224. if (AcceptsTab)
  225. {
  226. HandleTextInput("\t");
  227. }
  228. else
  229. {
  230. base.OnKeyDown(e);
  231. handled = false;
  232. }
  233. break;
  234. }
  235. if (movement && ((modifiers & InputModifiers.Shift) != 0))
  236. {
  237. SelectionEnd = CaretIndex;
  238. }
  239. else if (movement)
  240. {
  241. SelectionStart = SelectionEnd = CaretIndex;
  242. }
  243. if (handled)
  244. {
  245. e.Handled = true;
  246. }
  247. }
  248. protected override void OnPointerPressed(PointerPressEventArgs e)
  249. {
  250. if (e.Source == _presenter)
  251. {
  252. var point = e.GetPosition(_presenter);
  253. var index = CaretIndex = _presenter.GetCaretIndex(point);
  254. var text = Text;
  255. switch (e.ClickCount)
  256. {
  257. case 1:
  258. SelectionStart = SelectionEnd = index;
  259. break;
  260. case 2:
  261. if (!StringUtils.IsStartOfWord(text, index))
  262. {
  263. SelectionStart = StringUtils.PreviousWord(text, index, false);
  264. }
  265. SelectionEnd = StringUtils.NextWord(text, index, false);
  266. break;
  267. case 3:
  268. SelectionStart = 0;
  269. SelectionEnd = text.Length;
  270. break;
  271. }
  272. e.Device.Capture(_presenter);
  273. e.Handled = true;
  274. }
  275. }
  276. protected override void OnPointerMoved(PointerEventArgs e)
  277. {
  278. if (_presenter != null && e.Device.Captured == _presenter)
  279. {
  280. var point = e.GetPosition(_presenter);
  281. CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
  282. }
  283. }
  284. protected override void OnPointerReleased(PointerEventArgs e)
  285. {
  286. if (_presenter != null && e.Device.Captured == _presenter)
  287. {
  288. e.Device.Capture(null);
  289. }
  290. }
  291. private static int ValidateCaretIndex(PerspexObject o, int value)
  292. {
  293. var text = o.GetValue(TextProperty);
  294. var length = (text != null) ? text.Length : 0;
  295. return Math.Max(0, Math.Min(length, value));
  296. }
  297. private void MoveHorizontal(int count, InputModifiers modifiers)
  298. {
  299. var text = Text ?? string.Empty;
  300. var caretIndex = CaretIndex;
  301. if ((modifiers & InputModifiers.Control) != 0)
  302. {
  303. if (count > 0)
  304. {
  305. count = StringUtils.NextWord(text, caretIndex, false) - caretIndex;
  306. }
  307. else
  308. {
  309. count = StringUtils.PreviousWord(text, caretIndex, false) - caretIndex;
  310. }
  311. }
  312. CaretIndex = caretIndex += count;
  313. }
  314. private void MoveVertical(int count, InputModifiers modifiers)
  315. {
  316. var formattedText = _presenter.FormattedText;
  317. var lines = formattedText.GetLines().ToList();
  318. var caretIndex = CaretIndex;
  319. var lineIndex = GetLine(caretIndex, lines) + count;
  320. if (lineIndex >= 0 && lineIndex < lines.Count)
  321. {
  322. var line = lines[lineIndex];
  323. var rect = formattedText.HitTestTextPosition(caretIndex);
  324. var y = count < 0 ? rect.Y : rect.Bottom;
  325. var point = new Point(rect.X, y + (count * (line.Height / 2)));
  326. var hit = formattedText.HitTestPoint(point);
  327. CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
  328. }
  329. }
  330. private void MoveHome(InputModifiers modifiers)
  331. {
  332. var text = Text ?? string.Empty;
  333. var caretIndex = CaretIndex;
  334. if ((modifiers & InputModifiers.Control) != 0)
  335. {
  336. caretIndex = 0;
  337. }
  338. else
  339. {
  340. var lines = _presenter.FormattedText.GetLines();
  341. var pos = 0;
  342. foreach (var line in lines)
  343. {
  344. if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
  345. {
  346. break;
  347. }
  348. pos += line.Length;
  349. }
  350. caretIndex = pos;
  351. }
  352. CaretIndex = caretIndex;
  353. }
  354. private void MoveEnd(InputModifiers modifiers)
  355. {
  356. var text = Text ?? string.Empty;
  357. var caretIndex = CaretIndex;
  358. if ((modifiers & InputModifiers.Control) != 0)
  359. {
  360. caretIndex = text.Length;
  361. }
  362. else
  363. {
  364. var lines = _presenter.FormattedText.GetLines();
  365. var pos = 0;
  366. foreach (var line in lines)
  367. {
  368. pos += line.Length;
  369. if (pos > caretIndex)
  370. {
  371. if (pos < text.Length)
  372. {
  373. --pos;
  374. }
  375. break;
  376. }
  377. }
  378. caretIndex = pos;
  379. }
  380. CaretIndex = caretIndex;
  381. }
  382. private void SelectAll()
  383. {
  384. SelectionStart = 0;
  385. SelectionEnd = Text.Length;
  386. }
  387. private bool DeleteSelection()
  388. {
  389. var selectionStart = SelectionStart;
  390. var selectionEnd = SelectionEnd;
  391. if (selectionStart != selectionEnd)
  392. {
  393. var start = Math.Min(selectionStart, selectionEnd);
  394. var end = Math.Max(selectionStart, selectionEnd);
  395. var text = Text;
  396. Text = text.Substring(0, start) + text.Substring(end);
  397. SelectionStart = SelectionEnd = CaretIndex = start;
  398. return true;
  399. }
  400. else
  401. {
  402. return false;
  403. }
  404. }
  405. private string GetSelection()
  406. {
  407. var selectionStart = SelectionStart;
  408. var selectionEnd = SelectionEnd;
  409. var start = Math.Min(selectionStart, selectionEnd);
  410. var end = Math.Max(selectionStart, selectionEnd);
  411. if (start == end || (Text?.Length ?? 0) < end)
  412. {
  413. return "";
  414. }
  415. return Text.Substring(start, end - start);
  416. }
  417. private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
  418. {
  419. int pos = 0;
  420. int i;
  421. for (i = 0; i < lines.Count; ++i)
  422. {
  423. var line = lines[i];
  424. pos += line.Length;
  425. if (pos > caretIndex)
  426. {
  427. break;
  428. }
  429. }
  430. return i;
  431. }
  432. }
  433. }