DateField.cs 11 KB

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