DateField.cs 15 KB

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