TextValidateField.cs 16 KB

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