DateField.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 override bool OnMouseEvent (MouseEventArgs ev)
  99. {
  100. if (base.OnMouseEvent (ev) || ev.Handled)
  101. {
  102. return true;
  103. }
  104. if (SelectedLength == 0 && ev.Flags.HasFlag (MouseFlags.Button1Pressed))
  105. {
  106. AdjCursorPosition (ev.Position.X);
  107. }
  108. return ev.Handled;
  109. }
  110. /// <summary>Event firing method for the <see cref="DateChanged"/> event.</summary>
  111. /// <param name="args">Event arguments</param>
  112. public virtual void OnDateChanged (DateTimeEventArgs<DateTime> args) { DateChanged?.Invoke (this, args); }
  113. /// <inheritdoc/>
  114. protected override bool OnKeyDownNotHandled (Key a)
  115. {
  116. // Ignore non-numeric characters.
  117. if (a >= Key.D0 && a <= Key.D9)
  118. {
  119. if (!ReadOnly)
  120. {
  121. if (SetText ((Rune)a))
  122. {
  123. IncCursorPosition ();
  124. }
  125. }
  126. return true;
  127. }
  128. return false;
  129. }
  130. private void AdjCursorPosition (int point, bool increment = true)
  131. {
  132. int newPoint = point;
  133. if (point > FormatLength)
  134. {
  135. newPoint = FormatLength;
  136. }
  137. if (point < 1)
  138. {
  139. newPoint = 1;
  140. }
  141. if (newPoint != point)
  142. {
  143. CursorPosition = newPoint;
  144. }
  145. while (CursorPosition < Text.GetColumns () - 1 && Text [CursorPosition].ToString () == _separator)
  146. {
  147. if (increment)
  148. {
  149. CursorPosition++;
  150. }
  151. else
  152. {
  153. CursorPosition--;
  154. }
  155. }
  156. }
  157. private void DateField_Changing (object sender, CancelEventArgs<string> e)
  158. {
  159. try
  160. {
  161. var spaces = 0;
  162. for (var i = 0; i < e.NewValue.Length; i++)
  163. {
  164. if (e.NewValue [i] == ' ')
  165. {
  166. spaces++;
  167. }
  168. else
  169. {
  170. break;
  171. }
  172. }
  173. spaces += FormatLength;
  174. string trimmedText = e.NewValue [..spaces];
  175. spaces -= FormatLength;
  176. trimmedText = trimmedText.Replace (new string (' ', spaces), " ");
  177. var date = Convert.ToDateTime (trimmedText).ToString (_format.Trim ());
  178. if ($" {date}" != e.NewValue)
  179. {
  180. e.NewValue = $" {date}".Replace (RightToLeftMark, "");
  181. }
  182. AdjCursorPosition (CursorPosition);
  183. }
  184. catch (Exception)
  185. {
  186. e.Cancel = true;
  187. }
  188. }
  189. private void DecCursorPosition ()
  190. {
  191. if (CursorPosition <= 1)
  192. {
  193. CursorPosition = 1;
  194. return;
  195. }
  196. CursorPosition--;
  197. AdjCursorPosition (CursorPosition, false);
  198. }
  199. private string GetDataSeparator (string separator)
  200. {
  201. string sepChar = separator.Trim ();
  202. if (sepChar.Length > 1 && sepChar.Contains (RightToLeftMark))
  203. {
  204. sepChar = sepChar.Replace (RightToLeftMark, "");
  205. }
  206. return sepChar;
  207. }
  208. private string GetDate (int month, int day, int year, string [] fm)
  209. {
  210. var date = " ";
  211. for (var i = 0; i < fm.Length; i++)
  212. {
  213. if (fm [i].Contains ('M'))
  214. {
  215. date += $"{month,2:00}";
  216. }
  217. else if (fm [i].Contains ('d'))
  218. {
  219. date += $"{day,2:00}";
  220. }
  221. else
  222. {
  223. date += $"{year,4:0000}";
  224. }
  225. if (i < 2)
  226. {
  227. date += $"{_separator}";
  228. }
  229. }
  230. return date;
  231. }
  232. private static int GetFormatIndex (string [] fm, string t)
  233. {
  234. int idx = -1;
  235. for (var i = 0; i < fm.Length; i++)
  236. {
  237. if (fm [i].Contains (t))
  238. {
  239. idx = i;
  240. break;
  241. }
  242. }
  243. return idx;
  244. }
  245. private void IncCursorPosition ()
  246. {
  247. if (CursorPosition >= FormatLength)
  248. {
  249. CursorPosition = FormatLength;
  250. return;
  251. }
  252. CursorPosition++;
  253. AdjCursorPosition (CursorPosition);
  254. }
  255. private new bool MoveEnd ()
  256. {
  257. ClearAllSelection ();
  258. CursorPosition = FormatLength;
  259. return true;
  260. }
  261. private bool MoveHome ()
  262. {
  263. // Home, C-A
  264. ClearAllSelection ();
  265. CursorPosition = 1;
  266. return true;
  267. }
  268. private bool MoveLeft ()
  269. {
  270. ClearAllSelection ();
  271. DecCursorPosition ();
  272. return true;
  273. }
  274. private bool MoveRight ()
  275. {
  276. ClearAllSelection ();
  277. IncCursorPosition ();
  278. return true;
  279. }
  280. private string NormalizeFormat (string text, string fmt = null, string sepChar = null)
  281. {
  282. if (string.IsNullOrEmpty (fmt))
  283. {
  284. fmt = _format;
  285. }
  286. if (string.IsNullOrEmpty (sepChar))
  287. {
  288. sepChar = _separator;
  289. }
  290. if (fmt.Length != text.Length)
  291. {
  292. return text;
  293. }
  294. char [] fmtText = text.ToCharArray ();
  295. for (var i = 0; i < text.Length; i++)
  296. {
  297. char c = fmt [i];
  298. if (c.ToString () == sepChar && text [i].ToString () != sepChar)
  299. {
  300. fmtText [i] = c;
  301. }
  302. }
  303. return new string (fmtText);
  304. }
  305. private void SetInitialProperties (DateTime date)
  306. {
  307. _format = $" {StandardizeDateFormat (Culture.DateTimeFormat.ShortDatePattern)}";
  308. _separator = GetDataSeparator (Culture.DateTimeFormat.DateSeparator);
  309. Date = date;
  310. CursorPosition = 1;
  311. TextChanging += DateField_Changing;
  312. // Things this view knows how to do
  313. AddCommand (
  314. Command.DeleteCharRight,
  315. () =>
  316. {
  317. DeleteCharRight ();
  318. return true;
  319. }
  320. );
  321. AddCommand (
  322. Command.DeleteCharLeft,
  323. () =>
  324. {
  325. DeleteCharLeft (false);
  326. return true;
  327. }
  328. );
  329. AddCommand (Command.LeftStart, () => MoveHome ());
  330. AddCommand (Command.Left, () => MoveLeft ());
  331. AddCommand (Command.RightEnd, () => MoveEnd ());
  332. AddCommand (Command.Right, () => MoveRight ());
  333. // Replace the commands defined in TextField
  334. KeyBindings.ReplaceCommands (Key.Delete, Command.DeleteCharRight);
  335. KeyBindings.ReplaceCommands (Key.D.WithCtrl, Command.DeleteCharRight);
  336. KeyBindings.ReplaceCommands (Key.Backspace, Command.DeleteCharLeft);
  337. KeyBindings.ReplaceCommands (Key.Home, Command.LeftStart);
  338. KeyBindings.ReplaceCommands (Key.Home.WithCtrl, Command.LeftStart);
  339. KeyBindings.ReplaceCommands (Key.CursorLeft, Command.Left);
  340. KeyBindings.ReplaceCommands (Key.B.WithCtrl, Command.Left);
  341. KeyBindings.ReplaceCommands (Key.End, Command.RightEnd);
  342. KeyBindings.ReplaceCommands (Key.E.WithCtrl, Command.RightEnd);
  343. KeyBindings.ReplaceCommands (Key.CursorRight, Command.Right);
  344. KeyBindings.ReplaceCommands (Key.F.WithCtrl, Command.Right);
  345. #if UNIX_KEY_BINDINGS
  346. KeyBindings.ReplaceCommands (Key.D.WithAlt, Command.DeleteCharLeft);
  347. #endif
  348. }
  349. private bool SetText (Rune key)
  350. {
  351. if (CursorPosition > FormatLength)
  352. {
  353. CursorPosition = FormatLength;
  354. return false;
  355. }
  356. if (CursorPosition < 1)
  357. {
  358. CursorPosition = 1;
  359. return false;
  360. }
  361. List<Rune> text = Text.EnumerateRunes ().ToList ();
  362. List<Rune> newText = text.GetRange (0, CursorPosition);
  363. newText.Add (key);
  364. if (CursorPosition < FormatLength)
  365. {
  366. newText =
  367. [
  368. .. newText,
  369. .. text.GetRange (CursorPosition + 1, text.Count - (CursorPosition + 1))
  370. ];
  371. }
  372. return SetText (StringExtensions.ToString (newText));
  373. }
  374. private bool SetText (string text)
  375. {
  376. if (string.IsNullOrEmpty (text))
  377. {
  378. return false;
  379. }
  380. text = NormalizeFormat (text);
  381. string [] vals = text.Split (_separator);
  382. for (var i = 0; i < vals.Length; i++)
  383. {
  384. if (vals [i].Contains (RightToLeftMark))
  385. {
  386. vals [i] = vals [i].Replace (RightToLeftMark, "");
  387. }
  388. }
  389. string [] frm = _format.Split (_separator);
  390. int year;
  391. int month;
  392. int day;
  393. int idx = GetFormatIndex (frm, "y");
  394. if (int.Parse (vals [idx]) < 1)
  395. {
  396. year = 1;
  397. vals [idx] = "1";
  398. }
  399. else
  400. {
  401. year = int.Parse (vals [idx]);
  402. }
  403. idx = GetFormatIndex (frm, "M");
  404. if (int.Parse (vals [idx]) < 1)
  405. {
  406. month = 1;
  407. vals [idx] = "1";
  408. }
  409. else if (int.Parse (vals [idx]) > 12)
  410. {
  411. month = 12;
  412. vals [idx] = "12";
  413. }
  414. else
  415. {
  416. month = int.Parse (vals [idx]);
  417. }
  418. idx = GetFormatIndex (frm, "d");
  419. if (int.Parse (vals [idx]) < 1)
  420. {
  421. day = 1;
  422. vals [idx] = "1";
  423. }
  424. else if (int.Parse (vals [idx]) > 31)
  425. {
  426. day = DateTime.DaysInMonth (year, month);
  427. vals [idx] = day.ToString ();
  428. }
  429. else
  430. {
  431. day = int.Parse (vals [idx]);
  432. }
  433. string d = GetDate (month, day, year, frm);
  434. DateTime date;
  435. try
  436. {
  437. date = Convert.ToDateTime (d);
  438. }
  439. catch (Exception)
  440. {
  441. return false;
  442. }
  443. Date = date;
  444. return true;
  445. }
  446. // Converts various date formats to a uniform 10-character format.
  447. // This aids in simplifying the handling of single-digit months and days,
  448. // and reduces the number of distinct date formats to maintain.
  449. private static string StandardizeDateFormat (string format)
  450. {
  451. return format switch
  452. {
  453. "MM/dd/yyyy" => "MM/dd/yyyy",
  454. "yyyy-MM-dd" => "yyyy-MM-dd",
  455. "yyyy/MM/dd" => "yyyy/MM/dd",
  456. "dd/MM/yyyy" => "dd/MM/yyyy",
  457. "d?/M?/yyyy" => "dd/MM/yyyy",
  458. "dd.MM.yyyy" => "dd.MM.yyyy",
  459. "dd-MM-yyyy" => "dd-MM-yyyy",
  460. "dd/MM yyyy" => "dd/MM/yyyy",
  461. "d. M. yyyy" => "dd.MM.yyyy",
  462. "yyyy.MM.dd" => "yyyy.MM.dd",
  463. "g yyyy/M/d" => "yyyy/MM/dd",
  464. "d/M/yyyy" => "dd/MM/yyyy",
  465. "d?/M?/yyyy g" => "dd/MM/yyyy",
  466. "d-M-yyyy" => "dd-MM-yyyy",
  467. "d.MM.yyyy" => "dd.MM.yyyy",
  468. "d.MM.yyyy '?'." => "dd.MM.yyyy",
  469. "M/d/yyyy" => "MM/dd/yyyy",
  470. "d. M. yyyy." => "dd.MM.yyyy",
  471. "d.M.yyyy." => "dd.MM.yyyy",
  472. "g yyyy-MM-dd" => "yyyy-MM-dd",
  473. "d.M.yyyy" => "dd.MM.yyyy",
  474. "d/MM/yyyy" => "dd/MM/yyyy",
  475. "yyyy/M/d" => "yyyy/MM/dd",
  476. "dd. MM. yyyy." => "dd.MM.yyyy",
  477. "yyyy. MM. dd." => "yyyy.MM.dd",
  478. "yyyy. M. d." => "yyyy.MM.dd",
  479. "d. MM. yyyy" => "dd.MM.yyyy",
  480. _ => "dd/MM/yyyy"
  481. };
  482. }
  483. }