TextValidateField.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. // Things this view knows how to do
  339. AddCommand (Command.LeftHome, () => { HomeKeyHandler (); return true; });
  340. AddCommand (Command.RightEnd, () => { EndKeyHandler (); return true; });
  341. AddCommand (Command.DeleteCharRight, () => { DeleteKeyHandler (); return true; });
  342. AddCommand (Command.DeleteCharLeft, () => { BackspaceKeyHandler (); return true; });
  343. AddCommand (Command.Left, () => { CursorLeft (); return true; });
  344. AddCommand (Command.Right, () => { CursorRight (); return true; });
  345. // Default keybindings for this view
  346. AddKeyBinding (Key.Home, Command.LeftHome);
  347. AddKeyBinding (Key.End, Command.RightEnd);
  348. AddKeyBinding (Key.Delete, Command.DeleteCharRight);
  349. AddKeyBinding (Key.DeleteChar, Command.DeleteCharRight);
  350. AddKeyBinding (Key.Backspace, Command.DeleteCharLeft);
  351. AddKeyBinding (Key.CursorLeft, Command.Left);
  352. AddKeyBinding (Key.CursorRight, Command.Right);
  353. }
  354. /// <summary>
  355. /// Provider
  356. /// </summary>
  357. public ITextValidateProvider Provider {
  358. get => provider;
  359. set {
  360. provider = value;
  361. if (provider.Fixed == true) {
  362. this.Width = provider.DisplayText == ustring.Empty ? 10 : Text.Length;
  363. }
  364. HomeKeyHandler ();
  365. SetNeedsDisplay ();
  366. }
  367. }
  368. ///<inheritdoc/>
  369. public override bool MouseEvent (MouseEvent mouseEvent)
  370. {
  371. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  372. var c = provider.Cursor (mouseEvent.X - GetMargins (Frame.Width).left);
  373. if (provider.Fixed == false && TextAlignment == TextAlignment.Right && Text.Length > 0) {
  374. c += 1;
  375. }
  376. cursorPosition = c;
  377. SetFocus ();
  378. SetNeedsDisplay ();
  379. return true;
  380. }
  381. return false;
  382. }
  383. /// <summary>
  384. /// Text
  385. /// </summary>
  386. public new ustring Text {
  387. get {
  388. if (provider == null) {
  389. return ustring.Empty;
  390. }
  391. return provider.Text;
  392. }
  393. set {
  394. if (provider == null) {
  395. return;
  396. }
  397. provider.Text = value;
  398. SetNeedsDisplay ();
  399. }
  400. }
  401. ///<inheritdoc/>
  402. public override void PositionCursor ()
  403. {
  404. var (left, _) = GetMargins (Frame.Width);
  405. // Fixed = true, is for inputs thar have fixed width, like masked ones.
  406. // Fixed = false, is for normal input.
  407. // When it's right-aligned and it's a normal input, the cursor behaves differently.
  408. if (provider?.Fixed == false && TextAlignment == TextAlignment.Right) {
  409. Move (cursorPosition + left - 1, 0);
  410. } else {
  411. Move (cursorPosition + left, 0);
  412. }
  413. }
  414. /// <summary>
  415. /// Margins for text alignment.
  416. /// </summary>
  417. /// <param name="width">Total width</param>
  418. /// <returns>Left and right margins</returns>
  419. (int left, int right) GetMargins (int width)
  420. {
  421. var count = Text.Length;
  422. var total = width - count;
  423. switch (TextAlignment) {
  424. case TextAlignment.Left:
  425. return (0, total);
  426. case TextAlignment.Centered:
  427. return (total / 2, (total / 2) + (total % 2));
  428. case TextAlignment.Right:
  429. return (total, 0);
  430. default:
  431. return (0, total);
  432. }
  433. }
  434. ///<inheritdoc/>
  435. public override void Redraw (Rect bounds)
  436. {
  437. if (provider == null) {
  438. Move (0, 0);
  439. Driver.AddStr ("Error: ITextValidateProvider not set!");
  440. return;
  441. }
  442. var bgcolor = !IsValid ? Color.BrightRed : ColorScheme.Focus.Background;
  443. var textColor = new Attribute (ColorScheme.Focus.Foreground, bgcolor);
  444. var (margin_left, margin_right) = GetMargins (bounds.Width);
  445. Move (0, 0);
  446. // Left Margin
  447. Driver.SetAttribute (textColor);
  448. for (int i = 0; i < margin_left; i++) {
  449. Driver.AddRune (' ');
  450. }
  451. // Content
  452. Driver.SetAttribute (textColor);
  453. // Content
  454. for (int i = 0; i < provider.DisplayText.Length; i++) {
  455. Driver.AddRune (provider.DisplayText [i]);
  456. }
  457. // Right Margin
  458. Driver.SetAttribute (textColor);
  459. for (int i = 0; i < margin_right; i++) {
  460. Driver.AddRune (' ');
  461. }
  462. }
  463. /// <summary>
  464. /// Try to move the cursor to the left.
  465. /// </summary>
  466. /// <returns>True if moved.</returns>
  467. bool CursorLeft ()
  468. {
  469. var current = cursorPosition;
  470. cursorPosition = provider.CursorLeft (cursorPosition);
  471. SetNeedsDisplay ();
  472. return current != cursorPosition;
  473. }
  474. /// <summary>
  475. /// Try to move the cursor to the right.
  476. /// </summary>
  477. /// <returns>True if moved.</returns>
  478. bool CursorRight ()
  479. {
  480. var current = cursorPosition;
  481. cursorPosition = provider.CursorRight (cursorPosition);
  482. SetNeedsDisplay ();
  483. return current != cursorPosition;
  484. }
  485. /// <summary>
  486. /// Delete char at cursor position - 1, moving the cursor.
  487. /// </summary>
  488. /// <returns></returns>
  489. bool BackspaceKeyHandler ()
  490. {
  491. if (provider.Fixed == false && TextAlignment == TextAlignment.Right && cursorPosition <= 1) {
  492. return false;
  493. }
  494. cursorPosition = provider.CursorLeft (cursorPosition);
  495. provider.Delete (cursorPosition);
  496. SetNeedsDisplay ();
  497. return true;
  498. }
  499. /// <summary>
  500. /// Deletes char at current position.
  501. /// </summary>
  502. /// <returns></returns>
  503. bool DeleteKeyHandler ()
  504. {
  505. if (provider.Fixed == false && TextAlignment == TextAlignment.Right) {
  506. cursorPosition = provider.CursorLeft (cursorPosition);
  507. }
  508. provider.Delete (cursorPosition);
  509. SetNeedsDisplay ();
  510. return true;
  511. }
  512. /// <summary>
  513. /// Moves the cursor to first char.
  514. /// </summary>
  515. /// <returns></returns>
  516. bool HomeKeyHandler ()
  517. {
  518. cursorPosition = provider.CursorStart ();
  519. SetNeedsDisplay ();
  520. return true;
  521. }
  522. /// <summary>
  523. /// Moves the cursor to the last char.
  524. /// </summary>
  525. /// <returns></returns>
  526. bool EndKeyHandler ()
  527. {
  528. cursorPosition = provider.CursorEnd ();
  529. SetNeedsDisplay ();
  530. return true;
  531. }
  532. ///<inheritdoc/>
  533. public override bool ProcessKey (KeyEvent kb)
  534. {
  535. if (provider == null) {
  536. return false;
  537. }
  538. var result = InvokeKeybindings (kb);
  539. if (result != null)
  540. return (bool)result;
  541. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  542. return false;
  543. var key = new Rune ((uint)kb.KeyValue);
  544. var inserted = provider.InsertAt ((char)key, cursorPosition);
  545. if (inserted) {
  546. CursorRight ();
  547. }
  548. return true;
  549. }
  550. /// <summary>
  551. /// This property returns true if the input is valid.
  552. /// </summary>
  553. public virtual bool IsValid {
  554. get {
  555. if (provider == null) {
  556. return false;
  557. }
  558. return provider.IsValid;
  559. }
  560. }
  561. }
  562. }