TextValidateField.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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 where T : ITextValidateProvider {
  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 () : this (ustring.Empty)
  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) : base ()
  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. return provider.Text;
  355. }
  356. set {
  357. provider.Text = value;
  358. SetNeedsDisplay ();
  359. }
  360. }
  361. /// <summary>
  362. /// Mask
  363. /// </summary>
  364. public ustring Mask {
  365. get {
  366. return provider.Mask;
  367. }
  368. set {
  369. provider.Mask = value;
  370. cursorPosition = provider.CursorStart ();
  371. SetNeedsDisplay ();
  372. }
  373. }
  374. ///inheritdoc/>
  375. public override void PositionCursor ()
  376. {
  377. var (left, _) = GetMargins (Frame.Width);
  378. // Fixed = true, is for inputs thar have fixed width, like masked ones.
  379. // Fixed = false, is for normal input.
  380. // When it's right-aligned and it's a normal input, the cursor behaves differently.
  381. if (provider.Fixed == false && TextAlignment == TextAlignment.Right) {
  382. Move (cursorPosition + left - 1, 0);
  383. } else {
  384. Move (cursorPosition + left, 0);
  385. }
  386. }
  387. /// <summary>
  388. /// Margins for text alignment.
  389. /// </summary>
  390. /// <param name="width">Total width</param>
  391. /// <returns>Left and right margins</returns>
  392. (int left, int right) GetMargins (int width)
  393. {
  394. var count = Text.Length;
  395. var total = width - count;
  396. switch (TextAlignment) {
  397. case TextAlignment.Left:
  398. return (0, total);
  399. case TextAlignment.Centered:
  400. return (total / 2, (total / 2) + (total % 2));
  401. case TextAlignment.Right:
  402. return (total, 0);
  403. default:
  404. return (0, total);
  405. }
  406. }
  407. ///<inheritdoc/>
  408. public override void Redraw (Rect bounds)
  409. {
  410. var bgcolor = !IsValid ? Color.BrightRed : ColorScheme.Focus.Background;
  411. var textColor = new Attribute (ColorScheme.Focus.Foreground, bgcolor);
  412. var (margin_left, margin_right) = GetMargins (bounds.Width);
  413. Move (0, 0);
  414. // Left Margin
  415. Driver.SetAttribute (textColor);
  416. for (int i = 0; i < margin_left; i++) {
  417. Driver.AddRune (' ');
  418. }
  419. // Content
  420. Driver.SetAttribute (textColor);
  421. // Content
  422. for (int i = 0; i < provider.Text.Length; i++) {
  423. Driver.AddRune (provider.Text [i]);
  424. }
  425. // Right Margin
  426. Driver.SetAttribute (textColor);
  427. for (int i = 0; i < margin_right; i++) {
  428. Driver.AddRune (' ');
  429. }
  430. }
  431. /// <summary>
  432. /// Try to move the cursor to the left.
  433. /// </summary>
  434. /// <returns>True if moved.</returns>
  435. bool CursorLeft ()
  436. {
  437. var current = cursorPosition;
  438. cursorPosition = provider.CursorLeft (cursorPosition);
  439. return current != cursorPosition;
  440. }
  441. /// <summary>
  442. /// Try to move the cursor to the right.
  443. /// </summary>
  444. /// <returns>True if moved.</returns>
  445. bool CursorRight ()
  446. {
  447. var current = cursorPosition;
  448. cursorPosition = provider.CursorRight (cursorPosition);
  449. return current != cursorPosition;
  450. }
  451. /// <summary>
  452. /// Delete char at cursor position - 1, moving the cursor.
  453. /// </summary>
  454. /// <returns></returns>
  455. bool BackspaceKeyHandler ()
  456. {
  457. if (provider.Fixed == false && TextAlignment == TextAlignment.Right && cursorPosition <= 1) {
  458. return false;
  459. }
  460. cursorPosition = provider.CursorLeft (cursorPosition);
  461. provider.Delete (cursorPosition);
  462. return true;
  463. }
  464. /// <summary>
  465. /// Deletes char at current position.
  466. /// </summary>
  467. /// <returns></returns>
  468. bool DeleteKeyHandler ()
  469. {
  470. if (provider.Fixed == false && TextAlignment == TextAlignment.Right) {
  471. cursorPosition = provider.CursorLeft (cursorPosition);
  472. }
  473. provider.Delete (cursorPosition);
  474. return true;
  475. }
  476. /// <summary>
  477. /// Moves the cursor to first char.
  478. /// </summary>
  479. /// <returns></returns>
  480. bool HomeKeyHandler ()
  481. {
  482. cursorPosition = provider.CursorStart ();
  483. return true;
  484. }
  485. /// <summary>
  486. /// Moves the cursor to the last char.
  487. /// </summary>
  488. /// <returns></returns>
  489. bool EndKeyHandler ()
  490. {
  491. cursorPosition = provider.CursorEnd ();
  492. return true;
  493. }
  494. ///<inheritdoc/>
  495. public override bool ProcessKey (KeyEvent kb)
  496. {
  497. switch (kb.Key) {
  498. case Key.Home: HomeKeyHandler (); break;
  499. case Key.End: EndKeyHandler (); break;
  500. case Key.Delete:
  501. case Key.DeleteChar: DeleteKeyHandler (); break;
  502. case Key.Backspace: BackspaceKeyHandler (); break;
  503. case Key.CursorLeft: CursorLeft (); break;
  504. case Key.CursorRight: CursorRight (); break;
  505. default:
  506. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  507. return false;
  508. var key = new Rune ((uint)kb.KeyValue);
  509. var inserted = provider.InsertAt ((char)key, cursorPosition);
  510. if (inserted) {
  511. CursorRight ();
  512. }
  513. break;
  514. }
  515. SetNeedsDisplay ();
  516. return true;
  517. }
  518. /// <summary>
  519. /// This property returns true if the input is valid.
  520. /// </summary>
  521. public virtual bool IsValid {
  522. get {
  523. return provider.IsValid;
  524. }
  525. }
  526. }
  527. }