TextValidateField.cs 14 KB

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