DateField.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. //
  2. // DateField.cs: text entry for date
  3. //
  4. // Author: Barry Nolte
  5. //
  6. // Licensed under the MIT license
  7. //
  8. using System.Globalization;
  9. namespace Terminal.Gui;
  10. /// <summary>Simple Date editing <see cref="View"/></summary>
  11. /// <remarks>The <see cref="DateField"/> <see cref="View"/> provides date editing functionality with mouse support.</remarks>
  12. public class DateField : TextField
  13. {
  14. private const string RightToLeftMark = "\u200f";
  15. private readonly int _dateFieldLength = 12;
  16. private DateTime _date;
  17. private string _format;
  18. private string _separator;
  19. /// <summary>Initializes a new instance of <see cref="DateField"/>.</summary>
  20. public DateField () : this (DateTime.MinValue) { }
  21. /// <summary>Initializes a new instance of <see cref="DateField"/>.</summary>
  22. /// <param name="date"></param>
  23. public DateField (DateTime date)
  24. {
  25. Width = _dateFieldLength;
  26. SetInitialProperties (date);
  27. }
  28. /// <summary>CultureInfo for date. The default is CultureInfo.CurrentCulture.</summary>
  29. public CultureInfo Culture
  30. {
  31. get => CultureInfo.CurrentCulture;
  32. set
  33. {
  34. if (value is { })
  35. {
  36. CultureInfo.CurrentCulture = value;
  37. _separator = GetDataSeparator (value.DateTimeFormat.DateSeparator);
  38. _format = " " + StandardizeDateFormat (value.DateTimeFormat.ShortDatePattern);
  39. Text = Date.ToString (_format).Replace (RightToLeftMark, "");
  40. }
  41. }
  42. }
  43. /// <inheritdoc/>
  44. public override int CursorPosition
  45. {
  46. get => base.CursorPosition;
  47. set => base.CursorPosition = Math.Max (Math.Min (value, FormatLength), 1);
  48. }
  49. /// <summary>Gets or sets the date of the <see cref="DateField"/>.</summary>
  50. /// <remarks></remarks>
  51. public DateTime Date
  52. {
  53. get => _date;
  54. set
  55. {
  56. if (ReadOnly)
  57. {
  58. return;
  59. }
  60. DateTime oldData = _date;
  61. _date = value;
  62. Text = value.ToString (" " + StandardizeDateFormat (_format.Trim ()))
  63. .Replace (RightToLeftMark, "");
  64. DateTimeEventArgs<DateTime> args = new (oldData, value, _format);
  65. if (oldData != value)
  66. {
  67. OnDateChanged (args);
  68. }
  69. }
  70. }
  71. private int FormatLength => StandardizeDateFormat (_format).Trim ().Length;
  72. /// <summary>DateChanged event, raised when the <see cref="Date"/> property has changed.</summary>
  73. /// <remarks>This event is raised when the <see cref="Date"/> property changes.</remarks>
  74. /// <remarks>The passed event arguments containing the old value, new value, and format string.</remarks>
  75. public event EventHandler<DateTimeEventArgs<DateTime>> DateChanged;
  76. /// <inheritdoc/>
  77. public override void DeleteCharLeft (bool useOldCursorPos = true)
  78. {
  79. if (ReadOnly)
  80. {
  81. return;
  82. }
  83. ClearAllSelection ();
  84. SetText ((Rune)'0');
  85. DecCursorPosition ();
  86. }
  87. /// <inheritdoc/>
  88. public override void DeleteCharRight ()
  89. {
  90. if (ReadOnly)
  91. {
  92. return;
  93. }
  94. ClearAllSelection ();
  95. SetText ((Rune)'0');
  96. }
  97. /// <inheritdoc/>
  98. protected internal override bool OnMouseEvent (MouseEvent ev)
  99. {
  100. bool result = base.OnMouseEvent (ev);
  101. if (result && SelectedLength == 0 && ev.Flags.HasFlag (MouseFlags.Button1Pressed))
  102. {
  103. AdjCursorPosition (ev.Position.X);
  104. }
  105. return result;
  106. }
  107. /// <summary>Event firing method for the <see cref="DateChanged"/> event.</summary>
  108. /// <param name="args">Event arguments</param>
  109. public virtual void OnDateChanged (DateTimeEventArgs<DateTime> args) { DateChanged?.Invoke (this, args); }
  110. /// <inheritdoc/>
  111. public override bool OnProcessKeyDown (Key a)
  112. {
  113. // Ignore non-numeric characters.
  114. if (a >= Key.D0 && a <= Key.D9)
  115. {
  116. if (!ReadOnly)
  117. {
  118. if (SetText ((Rune)a))
  119. {
  120. IncCursorPosition ();
  121. }
  122. }
  123. return true;
  124. }
  125. return false;
  126. }
  127. private void AdjCursorPosition (int point, bool increment = true)
  128. {
  129. int newPoint = point;
  130. if (point > FormatLength)
  131. {
  132. newPoint = FormatLength;
  133. }
  134. if (point < 1)
  135. {
  136. newPoint = 1;
  137. }
  138. if (newPoint != point)
  139. {
  140. CursorPosition = newPoint;
  141. }
  142. while (Text [CursorPosition].ToString () == _separator)
  143. {
  144. if (increment)
  145. {
  146. CursorPosition++;
  147. }
  148. else
  149. {
  150. CursorPosition--;
  151. }
  152. }
  153. }
  154. private void DateField_Changing (object sender, CancelEventArgs<string> e)
  155. {
  156. try
  157. {
  158. var spaces = 0;
  159. for (var i = 0; i < e.NewValue.Length; i++)
  160. {
  161. if (e.NewValue [i] == ' ')
  162. {
  163. spaces++;
  164. }
  165. else
  166. {
  167. break;
  168. }
  169. }
  170. spaces += FormatLength;
  171. string trimmedText = e.NewValue [..spaces];
  172. spaces -= FormatLength;
  173. trimmedText = trimmedText.Replace (new string (' ', spaces), " ");
  174. var date = Convert.ToDateTime (trimmedText).ToString (_format.Trim ());
  175. if ($" {date}" != e.NewValue)
  176. {
  177. e.NewValue = $" {date}".Replace (RightToLeftMark, "");
  178. }
  179. AdjCursorPosition (CursorPosition);
  180. }
  181. catch (Exception)
  182. {
  183. e.Cancel = true;
  184. }
  185. }
  186. private void DecCursorPosition ()
  187. {
  188. if (CursorPosition <= 1)
  189. {
  190. CursorPosition = 1;
  191. return;
  192. }
  193. CursorPosition--;
  194. AdjCursorPosition (CursorPosition, false);
  195. }
  196. private string GetDataSeparator (string separator)
  197. {
  198. string sepChar = separator.Trim ();
  199. if (sepChar.Length > 1 && sepChar.Contains (RightToLeftMark))
  200. {
  201. sepChar = sepChar.Replace (RightToLeftMark, "");
  202. }
  203. return sepChar;
  204. }
  205. private string GetDate (int month, int day, int year, string [] fm)
  206. {
  207. var date = " ";
  208. for (var i = 0; i < fm.Length; i++)
  209. {
  210. if (fm [i].Contains ('M'))
  211. {
  212. date += $"{month,2:00}";
  213. }
  214. else if (fm [i].Contains ('d'))
  215. {
  216. date += $"{day,2:00}";
  217. }
  218. else
  219. {
  220. date += $"{year,4:0000}";
  221. }
  222. if (i < 2)
  223. {
  224. date += $"{_separator}";
  225. }
  226. }
  227. return date;
  228. }
  229. private static int GetFormatIndex (string [] fm, string t)
  230. {
  231. int idx = -1;
  232. for (var i = 0; i < fm.Length; i++)
  233. {
  234. if (fm [i].Contains (t))
  235. {
  236. idx = i;
  237. break;
  238. }
  239. }
  240. return idx;
  241. }
  242. private void IncCursorPosition ()
  243. {
  244. if (CursorPosition >= FormatLength)
  245. {
  246. CursorPosition = FormatLength;
  247. return;
  248. }
  249. CursorPosition++;
  250. AdjCursorPosition (CursorPosition);
  251. }
  252. private new bool MoveEnd ()
  253. {
  254. ClearAllSelection ();
  255. CursorPosition = FormatLength;
  256. return true;
  257. }
  258. private bool MoveHome ()
  259. {
  260. // Home, C-A
  261. ClearAllSelection ();
  262. CursorPosition = 1;
  263. return true;
  264. }
  265. private bool MoveLeft ()
  266. {
  267. ClearAllSelection ();
  268. DecCursorPosition ();
  269. return true;
  270. }
  271. private bool MoveRight ()
  272. {
  273. ClearAllSelection ();
  274. IncCursorPosition ();
  275. return true;
  276. }
  277. private string NormalizeFormat (string text, string fmt = null, string sepChar = null)
  278. {
  279. if (string.IsNullOrEmpty (fmt))
  280. {
  281. fmt = _format;
  282. }
  283. if (string.IsNullOrEmpty (sepChar))
  284. {
  285. sepChar = _separator;
  286. }
  287. if (fmt.Length != text.Length)
  288. {
  289. return text;
  290. }
  291. char [] fmtText = text.ToCharArray ();
  292. for (var i = 0; i < text.Length; i++)
  293. {
  294. char c = fmt [i];
  295. if (c.ToString () == sepChar && text [i].ToString () != sepChar)
  296. {
  297. fmtText [i] = c;
  298. }
  299. }
  300. return new string (fmtText);
  301. }
  302. private void SetInitialProperties (DateTime date)
  303. {
  304. _format = $" {StandardizeDateFormat (Culture.DateTimeFormat.ShortDatePattern)}";
  305. _separator = GetDataSeparator (Culture.DateTimeFormat.DateSeparator);
  306. Date = date;
  307. CursorPosition = 1;
  308. TextChanging += DateField_Changing;
  309. // Things this view knows how to do
  310. AddCommand (
  311. Command.DeleteCharRight,
  312. () =>
  313. {
  314. DeleteCharRight ();
  315. return true;
  316. }
  317. );
  318. AddCommand (
  319. Command.DeleteCharLeft,
  320. () =>
  321. {
  322. DeleteCharLeft (false);
  323. return true;
  324. }
  325. );
  326. AddCommand (Command.LeftHome, () => MoveHome ());
  327. AddCommand (Command.Left, () => MoveLeft ());
  328. AddCommand (Command.RightEnd, () => MoveEnd ());
  329. AddCommand (Command.Right, () => MoveRight ());
  330. // Replace the commands defined in TextField
  331. KeyBindings.ReplaceCommands (Key.Delete, Command.DeleteCharRight);
  332. KeyBindings.ReplaceCommands (Key.D.WithCtrl, Command.DeleteCharRight);
  333. KeyBindings.ReplaceCommands (Key.Backspace, Command.DeleteCharLeft);
  334. KeyBindings.ReplaceCommands (Key.Home, Command.LeftHome);
  335. KeyBindings.ReplaceCommands (Key.A.WithCtrl, Command.LeftHome);
  336. KeyBindings.ReplaceCommands (Key.CursorLeft, Command.Left);
  337. KeyBindings.ReplaceCommands (Key.B.WithCtrl, Command.Left);
  338. KeyBindings.ReplaceCommands (Key.End, Command.RightEnd);
  339. KeyBindings.ReplaceCommands (Key.E.WithCtrl, Command.RightEnd);
  340. KeyBindings.ReplaceCommands (Key.CursorRight, Command.Right);
  341. KeyBindings.ReplaceCommands (Key.F.WithCtrl, Command.Right);
  342. #if UNIX_KEY_BINDINGS
  343. KeyBindings.ReplaceCommands (Key.D.WithAlt, Command.DeleteCharLeft);
  344. #endif
  345. }
  346. private bool SetText (Rune key)
  347. {
  348. if (CursorPosition > FormatLength)
  349. {
  350. CursorPosition = FormatLength;
  351. return false;
  352. }
  353. if (CursorPosition < 1)
  354. {
  355. CursorPosition = 1;
  356. return false;
  357. }
  358. List<Rune> text = Text.EnumerateRunes ().ToList ();
  359. List<Rune> newText = text.GetRange (0, CursorPosition);
  360. newText.Add (key);
  361. if (CursorPosition < FormatLength)
  362. {
  363. newText =
  364. [
  365. .. newText,
  366. .. text.GetRange (CursorPosition + 1, text.Count - (CursorPosition + 1))
  367. ];
  368. }
  369. return SetText (StringExtensions.ToString (newText));
  370. }
  371. private bool SetText (string text)
  372. {
  373. if (string.IsNullOrEmpty (text))
  374. {
  375. return false;
  376. }
  377. text = NormalizeFormat (text);
  378. string [] vals = text.Split (_separator);
  379. for (var i = 0; i < vals.Length; i++)
  380. {
  381. if (vals [i].Contains (RightToLeftMark))
  382. {
  383. vals [i] = vals [i].Replace (RightToLeftMark, "");
  384. }
  385. }
  386. string [] frm = _format.Split (_separator);
  387. int year;
  388. int month;
  389. int day;
  390. int idx = GetFormatIndex (frm, "y");
  391. if (int.Parse (vals [idx]) < 1)
  392. {
  393. year = 1;
  394. vals [idx] = "1";
  395. }
  396. else
  397. {
  398. year = int.Parse (vals [idx]);
  399. }
  400. idx = GetFormatIndex (frm, "M");
  401. if (int.Parse (vals [idx]) < 1)
  402. {
  403. month = 1;
  404. vals [idx] = "1";
  405. }
  406. else if (int.Parse (vals [idx]) > 12)
  407. {
  408. month = 12;
  409. vals [idx] = "12";
  410. }
  411. else
  412. {
  413. month = int.Parse (vals [idx]);
  414. }
  415. idx = GetFormatIndex (frm, "d");
  416. if (int.Parse (vals [idx]) < 1)
  417. {
  418. day = 1;
  419. vals [idx] = "1";
  420. }
  421. else if (int.Parse (vals [idx]) > 31)
  422. {
  423. day = DateTime.DaysInMonth (year, month);
  424. vals [idx] = day.ToString ();
  425. }
  426. else
  427. {
  428. day = int.Parse (vals [idx]);
  429. }
  430. string d = GetDate (month, day, year, frm);
  431. DateTime date;
  432. try
  433. {
  434. date = Convert.ToDateTime (d);
  435. }
  436. catch (Exception)
  437. {
  438. return false;
  439. }
  440. Date = date;
  441. return true;
  442. }
  443. // Converts various date formats to a uniform 10-character format.
  444. // This aids in simplifying the handling of single-digit months and days,
  445. // and reduces the number of distinct date formats to maintain.
  446. private static string StandardizeDateFormat (string format)
  447. {
  448. return format switch
  449. {
  450. "MM/dd/yyyy" => "MM/dd/yyyy",
  451. "yyyy-MM-dd" => "yyyy-MM-dd",
  452. "yyyy/MM/dd" => "yyyy/MM/dd",
  453. "dd/MM/yyyy" => "dd/MM/yyyy",
  454. "d?/M?/yyyy" => "dd/MM/yyyy",
  455. "dd.MM.yyyy" => "dd.MM.yyyy",
  456. "dd-MM-yyyy" => "dd-MM-yyyy",
  457. "dd/MM yyyy" => "dd/MM/yyyy",
  458. "d. M. yyyy" => "dd.MM.yyyy",
  459. "yyyy.MM.dd" => "yyyy.MM.dd",
  460. "g yyyy/M/d" => "yyyy/MM/dd",
  461. "d/M/yyyy" => "dd/MM/yyyy",
  462. "d?/M?/yyyy g" => "dd/MM/yyyy",
  463. "d-M-yyyy" => "dd-MM-yyyy",
  464. "d.MM.yyyy" => "dd.MM.yyyy",
  465. "d.MM.yyyy '?'." => "dd.MM.yyyy",
  466. "M/d/yyyy" => "MM/dd/yyyy",
  467. "d. M. yyyy." => "dd.MM.yyyy",
  468. "d.M.yyyy." => "dd.MM.yyyy",
  469. "g yyyy-MM-dd" => "yyyy-MM-dd",
  470. "d.M.yyyy" => "dd.MM.yyyy",
  471. "d/MM/yyyy" => "dd/MM/yyyy",
  472. "yyyy/M/d" => "yyyy/MM/dd",
  473. "dd. MM. yyyy." => "dd.MM.yyyy",
  474. "yyyy. MM. dd." => "yyyy.MM.dd",
  475. "yyyy. M. d." => "yyyy.MM.dd",
  476. "d. MM. yyyy" => "dd.MM.yyyy",
  477. _ => "dd/MM/yyyy"
  478. };
  479. }
  480. }