TextValidateField.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. //
  2. // TextValidateField.cs: single-line text editor with validation through providers.
  3. //
  4. // Authors:
  5. // José Miguel Perricone ([email protected])
  6. //
  7. using System.Text;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Linq;
  11. using System.Text.RegularExpressions;
  12. using Terminal.Gui.TextValidateProviders;
  13. using System;
  14. namespace Terminal.Gui {
  15. namespace TextValidateProviders {
  16. /// <summary>
  17. /// TextValidateField Providers Interface.
  18. /// All TextValidateField are created with a ITextValidateProvider.
  19. /// </summary>
  20. public interface ITextValidateProvider {
  21. /// <summary>
  22. /// Set that this provider uses a fixed width.
  23. /// e.g. Masked ones are fixed.
  24. /// </summary>
  25. bool Fixed { get; }
  26. /// <summary>
  27. /// Set Cursor position to <paramref name="pos"/>.
  28. /// </summary>
  29. /// <param name="pos"></param>
  30. /// <returns>Return first valid position.</returns>
  31. int Cursor (int pos);
  32. /// <summary>
  33. /// First valid position before <paramref name="pos"/>.
  34. /// </summary>
  35. /// <param name="pos"></param>
  36. /// <returns>New cursor position if any, otherwise returns <paramref name="pos"/></returns>
  37. int CursorLeft (int pos);
  38. /// <summary>
  39. /// First valid position after <paramref name="pos"/>.
  40. /// </summary>
  41. /// <param name="pos">Current position.</param>
  42. /// <returns>New cursor position if any, otherwise returns <paramref name="pos"/></returns>
  43. int CursorRight (int pos);
  44. /// <summary>
  45. /// Find the first valid character position.
  46. /// </summary>
  47. /// <returns>New cursor position.</returns>
  48. int CursorStart ();
  49. /// <summary>
  50. /// Find the last valid character position.
  51. /// </summary>
  52. /// <returns>New cursor position.</returns>
  53. int CursorEnd ();
  54. /// <summary>
  55. /// Deletes the current character in <paramref name="pos"/>.
  56. /// </summary>
  57. /// <param name="pos"></param>
  58. /// <returns>true if the character was successfully removed, otherwise false.</returns>
  59. bool Delete (int pos);
  60. /// <summary>
  61. /// Insert character <paramref name="ch"/> in position <paramref name="pos"/>.
  62. /// </summary>
  63. /// <param name="ch"></param>
  64. /// <param name="pos"></param>
  65. /// <returns>true if the character was successfully inserted, otherwise false.</returns>
  66. bool InsertAt (char ch, int pos);
  67. /// <summary>
  68. /// True if the input is valid, otherwise false.
  69. /// </summary>
  70. bool IsValid { get; }
  71. /// <summary>
  72. /// Set the input text and get the current value.
  73. /// </summary>
  74. string Text { get; set; }
  75. /// <summary>
  76. /// Gets the formatted string for display.
  77. /// </summary>
  78. string DisplayText { get; }
  79. /// <summary>
  80. /// Method that invoke the <see cref="TextChanged"/> event if it's defined.
  81. /// </summary>
  82. /// <param name="oldValue">The previous text before replaced.</param>
  83. /// <returns>Returns the <see cref="TextChangedEventArgs"/></returns>
  84. void OnTextChanged (TextChangedEventArgs oldValue);
  85. /// <summary>
  86. /// Changed event, raised when the text has changed.
  87. /// <remarks>
  88. /// This event is raised when the <see cref="Text"/> changes.
  89. /// The passed <see cref="EventArgs"/> is a <see cref="string"/> containing the old value.
  90. /// </remarks>
  91. /// </summary>
  92. event EventHandler<TextChangedEventArgs> TextChanged;
  93. }
  94. //////////////////////////////////////////////////////////////////////////////
  95. // PROVIDERS
  96. //////////////////////////////////////////////////////////////////////////////
  97. #region NetMaskedTextProvider
  98. /// <summary>
  99. /// .Net MaskedTextProvider Provider for TextValidateField.
  100. /// <para></para>
  101. /// <para><a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.maskedtextprovider?view=net-5.0">Wrapper around MaskedTextProvider</a></para>
  102. /// <para><a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.maskedtextbox.mask?view=net-5.0">Masking elements</a></para>
  103. /// </summary>
  104. public class NetMaskedTextProvider : ITextValidateProvider {
  105. MaskedTextProvider _provider;
  106. /// <inheritdoc/>
  107. public event EventHandler<TextChangedEventArgs> TextChanged;
  108. /// <summary>
  109. /// Empty Constructor
  110. /// </summary>
  111. public NetMaskedTextProvider (string mask)
  112. {
  113. Mask = mask;
  114. }
  115. /// <summary>
  116. /// Mask property
  117. /// </summary>
  118. public string Mask {
  119. get {
  120. return _provider?.Mask;
  121. }
  122. set {
  123. var current = _provider != null ? _provider.ToString (false, false) : string.Empty;
  124. _provider = new MaskedTextProvider (value == string.Empty ? "&&&&&&" : value);
  125. if (!string.IsNullOrEmpty (current)) {
  126. _provider.Set (current);
  127. }
  128. }
  129. }
  130. ///<inheritdoc/>
  131. public string Text {
  132. get {
  133. return _provider.ToString ();
  134. }
  135. set {
  136. _provider.Set (value);
  137. }
  138. }
  139. ///<inheritdoc/>
  140. public bool IsValid => _provider.MaskCompleted;
  141. ///<inheritdoc/>
  142. public bool Fixed => true;
  143. ///<inheritdoc/>
  144. public string DisplayText => _provider.ToDisplayString ();
  145. ///<inheritdoc/>
  146. public int Cursor (int pos)
  147. {
  148. if (pos < 0) {
  149. return CursorStart ();
  150. } else if (pos > _provider.Length) {
  151. return CursorEnd ();
  152. } else {
  153. var p = _provider.FindEditPositionFrom (pos, false);
  154. if (p == -1) p = _provider.FindEditPositionFrom (pos, true);
  155. return p;
  156. }
  157. }
  158. ///<inheritdoc/>
  159. public int CursorStart ()
  160. {
  161. return
  162. _provider.IsEditPosition (0)
  163. ? 0
  164. : _provider.FindEditPositionFrom (0, true);
  165. }
  166. ///<inheritdoc/>
  167. public int CursorEnd ()
  168. {
  169. return
  170. _provider.IsEditPosition (_provider.Length - 1)
  171. ? _provider.Length - 1
  172. : _provider.FindEditPositionFrom (_provider.Length, false);
  173. }
  174. ///<inheritdoc/>
  175. public int CursorLeft (int pos)
  176. {
  177. var c = _provider.FindEditPositionFrom (pos - 1, false);
  178. return c == -1 ? pos : c;
  179. }
  180. ///<inheritdoc/>
  181. public int CursorRight (int pos)
  182. {
  183. var c = _provider.FindEditPositionFrom (pos + 1, true);
  184. return c == -1 ? pos : c;
  185. }
  186. ///<inheritdoc/>
  187. public bool Delete (int pos)
  188. {
  189. var oldValue = Text;
  190. var result = _provider.Replace (' ', pos);// .RemoveAt (pos);
  191. if (result) {
  192. OnTextChanged (new TextChangedEventArgs (oldValue));
  193. }
  194. return result;
  195. }
  196. ///<inheritdoc/>
  197. public bool InsertAt (char ch, int pos)
  198. {
  199. var oldValue = Text;
  200. var result = _provider.Replace (ch, pos);
  201. if (result) {
  202. OnTextChanged (new TextChangedEventArgs (oldValue));
  203. }
  204. return result;
  205. }
  206. /// <inheritdoc/>
  207. public void OnTextChanged (TextChangedEventArgs oldValue) => TextChanged?.Invoke (this, oldValue);
  208. }
  209. #endregion
  210. #region TextRegexProvider
  211. /// <summary>
  212. /// Regex Provider for TextValidateField.
  213. /// </summary>
  214. public class TextRegexProvider : ITextValidateProvider {
  215. Regex _regex;
  216. List<Rune> _text;
  217. List<Rune> _pattern;
  218. /// <inheritdoc/>
  219. public event EventHandler<TextChangedEventArgs> TextChanged;
  220. /// <summary>
  221. /// Empty Constructor.
  222. /// </summary>
  223. public TextRegexProvider (string pattern)
  224. {
  225. Pattern = pattern;
  226. }
  227. /// <summary>
  228. /// Regex pattern property.
  229. /// </summary>
  230. public string Pattern {
  231. get {
  232. return StringExtensions.ToString (_pattern);
  233. }
  234. set {
  235. _pattern = value.ToRuneList ();
  236. CompileMask ();
  237. SetupText ();
  238. }
  239. }
  240. ///<inheritdoc/>
  241. public string Text {
  242. get {
  243. return StringExtensions.ToString (_text);
  244. }
  245. set {
  246. _text = value != string.Empty ? value.ToRuneList () : null;
  247. SetupText ();
  248. }
  249. }
  250. ///<inheritdoc/>
  251. public string DisplayText => Text;
  252. ///<inheritdoc/>
  253. public bool IsValid {
  254. get {
  255. return Validate (_text);
  256. }
  257. }
  258. ///<inheritdoc/>
  259. public bool Fixed => false;
  260. /// <summary>
  261. /// When true, validates with the regex pattern on each input, preventing the input if it's not valid.
  262. /// </summary>
  263. public bool ValidateOnInput { get; set; } = true;
  264. bool Validate (List<Rune> text)
  265. {
  266. var match = _regex.Match (StringExtensions.ToString (text));
  267. return match.Success;
  268. }
  269. ///<inheritdoc/>
  270. public int Cursor (int pos)
  271. {
  272. if (pos < 0) {
  273. return CursorStart ();
  274. } else if (pos >= _text.Count) {
  275. return CursorEnd ();
  276. } else {
  277. return pos;
  278. }
  279. }
  280. ///<inheritdoc/>
  281. public int CursorStart ()
  282. {
  283. return 0;
  284. }
  285. ///<inheritdoc/>
  286. public int CursorEnd ()
  287. {
  288. return _text.Count;
  289. }
  290. ///<inheritdoc/>
  291. public int CursorLeft (int pos)
  292. {
  293. if (pos > 0) {
  294. return pos - 1;
  295. }
  296. return pos;
  297. }
  298. ///<inheritdoc/>
  299. public int CursorRight (int pos)
  300. {
  301. if (pos < _text.Count) {
  302. return pos + 1;
  303. }
  304. return pos;
  305. }
  306. ///<inheritdoc/>
  307. public bool Delete (int pos)
  308. {
  309. if (_text.Count > 0 && pos < _text.Count) {
  310. var oldValue = Text;
  311. _text.RemoveAt (pos);
  312. OnTextChanged (new TextChangedEventArgs (oldValue));
  313. }
  314. return true;
  315. }
  316. ///<inheritdoc/>
  317. public bool InsertAt (char ch, int pos)
  318. {
  319. var aux = _text.ToList ();
  320. aux.Insert (pos, (Rune)ch);
  321. if (Validate (aux) || ValidateOnInput == false) {
  322. var oldValue = Text;
  323. _text.Insert (pos, (Rune)ch);
  324. OnTextChanged (new TextChangedEventArgs (oldValue));
  325. return true;
  326. }
  327. return false;
  328. }
  329. void SetupText ()
  330. {
  331. if (_text != null && IsValid) {
  332. return;
  333. }
  334. _text = new List<Rune> ();
  335. }
  336. /// <summary>
  337. /// Compiles the regex pattern for validation./>
  338. /// </summary>
  339. private void CompileMask ()
  340. {
  341. _regex = new Regex (StringExtensions.ToString (_pattern), RegexOptions.Compiled);
  342. }
  343. /// <inheritdoc/>
  344. public void OnTextChanged (TextChangedEventArgs oldValue) => TextChanged?.Invoke (this, oldValue);
  345. }
  346. #endregion
  347. }
  348. /// <summary>
  349. /// Text field that validates input through a <see cref="ITextValidateProvider"/>
  350. /// </summary>
  351. public class TextValidateField : View {
  352. ITextValidateProvider _provider;
  353. int _cursorPosition;
  354. int _defaultLength = 10;
  355. /// <summary>
  356. /// Initializes a new instance of the <see cref="TextValidateField"/> class using <see cref="LayoutStyle.Computed"/> positioning.
  357. /// </summary>
  358. public TextValidateField () : this (null) { }
  359. /// <summary>
  360. /// Initializes a new instance of the <see cref="TextValidateField"/> class using <see cref="LayoutStyle.Computed"/> positioning.
  361. /// </summary>
  362. public TextValidateField (ITextValidateProvider provider)
  363. {
  364. if (provider != null) {
  365. Provider = provider;
  366. }
  367. SetInitialProperties ();
  368. }
  369. void SetInitialProperties ()
  370. {
  371. Height = 1;
  372. CanFocus = true;
  373. // Things this view knows how to do
  374. AddCommand (Command.LeftHome, () => { HomeKeyHandler (); return true; });
  375. AddCommand (Command.RightEnd, () => { EndKeyHandler (); return true; });
  376. AddCommand (Command.DeleteCharRight, () => { DeleteKeyHandler (); return true; });
  377. AddCommand (Command.DeleteCharLeft, () => { BackspaceKeyHandler (); return true; });
  378. AddCommand (Command.Left, () => { CursorLeft (); return true; });
  379. AddCommand (Command.Right, () => { CursorRight (); return true; });
  380. // Default keybindings for this view
  381. KeyBindings.Add (KeyCode.Home, Command.LeftHome);
  382. KeyBindings.Add (KeyCode.End, Command.RightEnd);
  383. KeyBindings.Add (KeyCode.Delete, Command.DeleteCharRight);
  384. KeyBindings.Add (KeyCode.Delete, Command.DeleteCharRight);
  385. KeyBindings.Add (KeyCode.Backspace, Command.DeleteCharLeft);
  386. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  387. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  388. }
  389. /// <summary>
  390. /// Provider
  391. /// </summary>
  392. public ITextValidateProvider Provider {
  393. get => _provider;
  394. set {
  395. _provider = value;
  396. if (_provider.Fixed) {
  397. this.Width = _provider.DisplayText == string.Empty ? _defaultLength : _provider.DisplayText.Length;
  398. }
  399. // HomeKeyHandler already call SetNeedsDisplay
  400. HomeKeyHandler ();
  401. }
  402. }
  403. ///<inheritdoc/>
  404. public override bool MouseEvent (MouseEvent mouseEvent)
  405. {
  406. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  407. var c = _provider.Cursor (mouseEvent.X - GetMargins (Bounds.Width).left);
  408. if (_provider.Fixed == false && TextAlignment == TextAlignment.Right && Text.Length > 0) {
  409. c++;
  410. }
  411. _cursorPosition = c;
  412. SetFocus ();
  413. SetNeedsDisplay ();
  414. return true;
  415. }
  416. return false;
  417. }
  418. /// <summary>
  419. /// Text
  420. /// </summary>
  421. public new string Text {
  422. get {
  423. if (_provider == null) {
  424. return string.Empty;
  425. }
  426. return _provider.Text;
  427. }
  428. set {
  429. if (_provider == null) {
  430. return;
  431. }
  432. _provider.Text = value;
  433. SetNeedsDisplay ();
  434. }
  435. }
  436. ///<inheritdoc/>
  437. public override void PositionCursor ()
  438. {
  439. var (left, _) = GetMargins (Bounds.Width);
  440. // Fixed = true, is for inputs that have fixed width, like masked ones.
  441. // Fixed = false, is for normal input.
  442. // When it's right-aligned and it's a normal input, the cursor behaves differently.
  443. int curPos;
  444. if (_provider?.Fixed == false && TextAlignment == TextAlignment.Right) {
  445. curPos = _cursorPosition + left - 1;
  446. Move (curPos, 0);
  447. } else {
  448. curPos = _cursorPosition + left;
  449. Move (curPos, 0);
  450. }
  451. if (curPos < 0 || curPos >= Bounds.Width) {
  452. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  453. } else {
  454. Application.Driver.SetCursorVisibility (CursorVisibility.Default);
  455. }
  456. }
  457. /// <summary>
  458. /// Margins for text alignment.
  459. /// </summary>
  460. /// <param name="width">Total width</param>
  461. /// <returns>Left and right margins</returns>
  462. (int left, int right) GetMargins (int width)
  463. {
  464. var count = Text.Length;
  465. var total = width - count;
  466. switch (TextAlignment) {
  467. case TextAlignment.Left:
  468. return (0, total);
  469. case TextAlignment.Centered:
  470. return (total / 2, (total / 2) + (total % 2));
  471. case TextAlignment.Right:
  472. return (total, 0);
  473. default:
  474. return (0, total);
  475. }
  476. }
  477. ///<inheritdoc/>
  478. public override void OnDrawContent (Rect contentArea)
  479. {
  480. if (_provider == null) {
  481. Move (0, 0);
  482. Driver.AddStr ("Error: ITextValidateProvider not set!");
  483. return;
  484. }
  485. var bgcolor = !IsValid ? new Color (Color.BrightRed) : ColorScheme.Focus.Background;
  486. var textColor = new Attribute (ColorScheme.Focus.Foreground, bgcolor);
  487. var (margin_left, margin_right) = GetMargins (Bounds.Width);
  488. Move (0, 0);
  489. // Left Margin
  490. Driver.SetAttribute (textColor);
  491. for (int i = 0; i < margin_left; i++) {
  492. Driver.AddRune ((Rune)' ');
  493. }
  494. // Content
  495. Driver.SetAttribute (textColor);
  496. // Content
  497. for (int i = 0; i < _provider.DisplayText.Length; i++) {
  498. Driver.AddRune ((Rune)_provider.DisplayText [i]);
  499. }
  500. // Right Margin
  501. Driver.SetAttribute (textColor);
  502. for (int i = 0; i < margin_right; i++) {
  503. Driver.AddRune ((Rune)' ');
  504. }
  505. }
  506. /// <summary>
  507. /// Try to move the cursor to the left.
  508. /// </summary>
  509. /// <returns>True if moved.</returns>
  510. bool CursorLeft ()
  511. {
  512. var current = _cursorPosition;
  513. _cursorPosition = _provider.CursorLeft (_cursorPosition);
  514. SetNeedsDisplay ();
  515. return current != _cursorPosition;
  516. }
  517. /// <summary>
  518. /// Try to move the cursor to the right.
  519. /// </summary>
  520. /// <returns>True if moved.</returns>
  521. bool CursorRight ()
  522. {
  523. var current = _cursorPosition;
  524. _cursorPosition = _provider.CursorRight (_cursorPosition);
  525. SetNeedsDisplay ();
  526. return current != _cursorPosition;
  527. }
  528. /// <summary>
  529. /// Delete char at cursor position - 1, moving the cursor.
  530. /// </summary>
  531. /// <returns></returns>
  532. bool BackspaceKeyHandler ()
  533. {
  534. if (_provider.Fixed == false && TextAlignment == TextAlignment.Right && _cursorPosition <= 1) {
  535. return false;
  536. }
  537. _cursorPosition = _provider.CursorLeft (_cursorPosition);
  538. _provider.Delete (_cursorPosition);
  539. SetNeedsDisplay ();
  540. return true;
  541. }
  542. /// <summary>
  543. /// Deletes char at current position.
  544. /// </summary>
  545. /// <returns></returns>
  546. bool DeleteKeyHandler ()
  547. {
  548. if (_provider.Fixed == false && TextAlignment == TextAlignment.Right) {
  549. _cursorPosition = _provider.CursorLeft (_cursorPosition);
  550. }
  551. _provider.Delete (_cursorPosition);
  552. SetNeedsDisplay ();
  553. return true;
  554. }
  555. /// <summary>
  556. /// Moves the cursor to first char.
  557. /// </summary>
  558. /// <returns></returns>
  559. bool HomeKeyHandler ()
  560. {
  561. _cursorPosition = _provider.CursorStart ();
  562. SetNeedsDisplay ();
  563. return true;
  564. }
  565. /// <summary>
  566. /// Moves the cursor to the last char.
  567. /// </summary>
  568. /// <returns></returns>
  569. bool EndKeyHandler ()
  570. {
  571. _cursorPosition = _provider.CursorEnd ();
  572. SetNeedsDisplay ();
  573. return true;
  574. }
  575. ///<inheritdoc/>
  576. public override bool OnProcessKeyDown (Key a)
  577. {
  578. if (_provider == null) {
  579. return false;
  580. }
  581. if (a.AsRune == default) {
  582. return false;
  583. }
  584. var key = a.AsRune;
  585. var inserted = _provider.InsertAt ((char)key.Value, _cursorPosition);
  586. if (inserted) {
  587. CursorRight ();
  588. }
  589. return false;
  590. }
  591. /// <summary>
  592. /// This property returns true if the input is valid.
  593. /// </summary>
  594. public virtual bool IsValid {
  595. get {
  596. if (_provider == null) {
  597. return false;
  598. }
  599. return _provider.IsValid;
  600. }
  601. }
  602. ///<inheritdoc/>
  603. public override bool OnEnter (View view)
  604. {
  605. Application.Driver.SetCursorVisibility (CursorVisibility.Default);
  606. return base.OnEnter (view);
  607. }
  608. ///<inheritdoc/>
  609. public override bool OnLeave (View view)
  610. {
  611. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  612. return base.OnLeave (view);
  613. }
  614. }
  615. }