DateField.cs 15 KB

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