DateField.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. DateTime _date;
  21. int _fieldLen = 10;
  22. string _sepChar;
  23. string _format;
  24. /// <summary>
  25. /// DateChanged event, raised when the <see cref="Date"/> property has changed.
  26. /// </summary>
  27. /// <remarks>
  28. /// This event is raised when the <see cref="Date"/> property changes.
  29. /// </remarks>
  30. /// <remarks>
  31. /// The passed event arguments containing the old value, new value, and format string.
  32. /// </remarks>
  33. public event EventHandler<DateTimeEventArgs<DateTime>> DateChanged;
  34. /// <summary>
  35. /// Initializes a new instance of <see cref="DateField"/> using <see cref="LayoutStyle.Computed"/> layout.
  36. /// </summary>
  37. public DateField () : this (DateTime.MinValue) { }
  38. /// <summary>
  39. /// Initializes a new instance of <see cref="DateField"/> using <see cref="LayoutStyle.Computed"/> layout.
  40. /// </summary>
  41. /// <param name="date"></param>
  42. public DateField (DateTime date) : base ("")
  43. {
  44. Width = _fieldLen + 2;
  45. SetInitialProperties (date);
  46. }
  47. void SetInitialProperties (DateTime date)
  48. {
  49. var cultureInfo = CultureInfo.CurrentCulture;
  50. _sepChar = cultureInfo.DateTimeFormat.DateSeparator;
  51. _format = $" {cultureInfo.DateTimeFormat.ShortDatePattern}";
  52. Date = date;
  53. CursorPosition = 1;
  54. TextChanging += DateField_Changing;
  55. // Things this view knows how to do
  56. AddCommand (Command.DeleteCharRight, () => {
  57. DeleteCharRight ();
  58. return true;
  59. });
  60. AddCommand (Command.DeleteCharLeft, () => {
  61. DeleteCharLeft (false);
  62. return true;
  63. });
  64. AddCommand (Command.LeftHome, () => MoveHome ());
  65. AddCommand (Command.Left, () => MoveLeft ());
  66. AddCommand (Command.RightEnd, () => MoveEnd ());
  67. AddCommand (Command.Right, () => MoveRight ());
  68. // Default keybindings for this view
  69. KeyBindings.Add (KeyCode.Delete, Command.DeleteCharRight);
  70. KeyBindings.Add (Key.D.WithCtrl, Command.DeleteCharRight);
  71. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  72. KeyBindings.Add (Key.D.WithAlt, Command.DeleteCharLeft);
  73. KeyBindings.Add (Key.Home, Command.LeftHome);
  74. KeyBindings.Add (Key.A.WithCtrl, Command.LeftHome);
  75. KeyBindings.Add (Key.CursorLeft, Command.Left);
  76. KeyBindings.Add (Key.B.WithCtrl, Command.Left);
  77. KeyBindings.Add (Key.End, Command.RightEnd);
  78. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  79. KeyBindings.Add (Key.CursorRight, Command.Right);
  80. KeyBindings.Add (Key.F.WithCtrl, Command.Right);
  81. }
  82. /// <inheritdoc />
  83. public override bool OnProcessKeyDown (Key a)
  84. {
  85. // Ignore non-numeric characters.
  86. if (a >= Key.D0 && a <= Key.D9) {
  87. if (!ReadOnly) {
  88. if (SetText ((Rune)a)) {
  89. IncCursorPosition ();
  90. }
  91. }
  92. return true;
  93. }
  94. return false;
  95. }
  96. void DateField_Changing (object sender, TextChangingEventArgs e)
  97. {
  98. try {
  99. var cultureInfo = CultureInfo.CurrentCulture;
  100. DateTimeFormatInfo ccFmt = cultureInfo.DateTimeFormat;
  101. int spaces = 0;
  102. for (int i = 0; i < e.NewText.Length; i++) {
  103. if (e.NewText [i] == ' ') {
  104. spaces++;
  105. } else {
  106. break;
  107. }
  108. }
  109. spaces += _fieldLen;
  110. string trimedText = e.NewText [..spaces];
  111. spaces -= _fieldLen;
  112. trimedText = trimedText.Replace (new string (' ', spaces), " ");
  113. var date = Convert.ToDateTime (trimedText, ccFmt).ToString (ccFmt.ShortDatePattern);
  114. if ($" {date}" != e.NewText) {
  115. e.NewText = $" {date}";
  116. }
  117. AdjCursorPosition (CursorPosition, true);
  118. } catch (Exception) {
  119. e.Cancel = true;
  120. }
  121. }
  122. /// <summary>
  123. /// Gets or sets the date of the <see cref="DateField"/>.
  124. /// </summary>
  125. /// <remarks>
  126. /// </remarks>
  127. public DateTime Date {
  128. get => _date;
  129. set {
  130. if (ReadOnly) {
  131. return;
  132. }
  133. var oldData = _date;
  134. _date = value;
  135. Text = value.ToString (_format);
  136. var args = new DateTimeEventArgs<DateTime> (oldData, value, _format);
  137. if (oldData != value) {
  138. OnDateChanged (args);
  139. }
  140. }
  141. }
  142. /// <inheritdoc/>
  143. public override int CursorPosition {
  144. get => base.CursorPosition;
  145. set => base.CursorPosition = Math.Max (Math.Min (value, _fieldLen), 1);
  146. }
  147. bool SetText (Rune key)
  148. {
  149. if (CursorPosition > _fieldLen) {
  150. CursorPosition = _fieldLen;
  151. return false;
  152. } else if (CursorPosition < 1) {
  153. CursorPosition = 1;
  154. return false;
  155. }
  156. var text = Text.EnumerateRunes ().ToList ();
  157. var newText = text.GetRange (0, CursorPosition);
  158. newText.Add (key);
  159. if (CursorPosition < _fieldLen) {
  160. newText = [.. newText, .. text.GetRange (CursorPosition + 1, text.Count - (CursorPosition + 1))];
  161. }
  162. return SetText (StringExtensions.ToString (newText));
  163. }
  164. bool SetText (string text)
  165. {
  166. if (string.IsNullOrEmpty (text)) {
  167. return false;
  168. }
  169. text = NormalizeFormat (text);
  170. string [] vals = text.Split (_sepChar);
  171. string [] frm = _format.Split (_sepChar);
  172. int year;
  173. int month;
  174. int day;
  175. int idx = GetFormatIndex (frm, "y");
  176. if (Int32.Parse (vals [idx]) < 1) {
  177. year = 1;
  178. vals [idx] = "1";
  179. } else {
  180. year = Int32.Parse (vals [idx]);
  181. }
  182. idx = GetFormatIndex (frm, "M");
  183. if (Int32.Parse (vals [idx]) < 1) {
  184. month = 1;
  185. vals [idx] = "1";
  186. } else if (Int32.Parse (vals [idx]) > 12) {
  187. month = 12;
  188. vals [idx] = "12";
  189. } else {
  190. month = Int32.Parse (vals [idx]);
  191. }
  192. idx = GetFormatIndex (frm, "d");
  193. if (Int32.Parse (vals [idx]) < 1) {
  194. day = 1;
  195. vals [idx] = "1";
  196. } else if (Int32.Parse (vals [idx]) > 31) {
  197. day = DateTime.DaysInMonth (year, month);
  198. vals [idx] = day.ToString ();
  199. } else {
  200. day = Int32.Parse (vals [idx]);
  201. }
  202. string d = GetDate (month, day, year, frm);
  203. if (!DateTime.TryParseExact (d, _format, CultureInfo.CurrentCulture, DateTimeStyles.None, out var result)) {
  204. return false;
  205. }
  206. Date = result;
  207. return true;
  208. }
  209. string NormalizeFormat (string text, string fmt = null, string sepChar = null)
  210. {
  211. if (string.IsNullOrEmpty (fmt)) {
  212. fmt = _format;
  213. }
  214. if (string.IsNullOrEmpty (sepChar)) {
  215. sepChar = _sepChar;
  216. }
  217. if (fmt.Length != text.Length) {
  218. return text;
  219. }
  220. var fmtText = text.ToCharArray ();
  221. for (int i = 0; i < text.Length; i++) {
  222. var c = fmt [i];
  223. if (c.ToString () == sepChar && text [i].ToString () != sepChar) {
  224. fmtText [i] = c;
  225. }
  226. }
  227. return new string (fmtText);
  228. }
  229. string GetDate (int month, int day, int year, string [] fm)
  230. {
  231. string date = " ";
  232. for (int i = 0; i < fm.Length; i++) {
  233. if (fm [i].Contains ('M')) {
  234. date += $"{month,2:00}";
  235. } else if (fm [i].Contains ('d')) {
  236. date += $"{day,2:00}";
  237. } else {
  238. date += $"{year,4:0000}";
  239. }
  240. if (i < 2) {
  241. date += $"{_sepChar}";
  242. }
  243. }
  244. return date;
  245. }
  246. static int GetFormatIndex (string [] fm, string t)
  247. {
  248. int idx = -1;
  249. for (int i = 0; i < fm.Length; i++) {
  250. if (fm [i].Contains (t)) {
  251. idx = i;
  252. break;
  253. }
  254. }
  255. return idx;
  256. }
  257. void IncCursorPosition ()
  258. {
  259. if (CursorPosition >= _fieldLen) {
  260. CursorPosition = _fieldLen;
  261. return;
  262. }
  263. CursorPosition++;
  264. AdjCursorPosition (CursorPosition);
  265. }
  266. void DecCursorPosition ()
  267. {
  268. if (CursorPosition <= 1) {
  269. CursorPosition = 1;
  270. return;
  271. }
  272. CursorPosition--;
  273. AdjCursorPosition (CursorPosition, false);
  274. }
  275. void AdjCursorPosition (int point, bool increment = true)
  276. {
  277. var newPoint = point;
  278. if (point > _fieldLen) {
  279. newPoint = _fieldLen;
  280. }
  281. if (point < 1) {
  282. newPoint = 1;
  283. }
  284. if (newPoint != point) {
  285. CursorPosition = newPoint;
  286. }
  287. while (Text [CursorPosition] == _sepChar [0]) {
  288. if (increment) {
  289. CursorPosition++;
  290. } else {
  291. CursorPosition--;
  292. }
  293. }
  294. }
  295. bool MoveRight ()
  296. {
  297. ClearAllSelection ();
  298. IncCursorPosition ();
  299. return true;
  300. }
  301. new bool MoveEnd ()
  302. {
  303. ClearAllSelection ();
  304. CursorPosition = _fieldLen;
  305. return true;
  306. }
  307. bool MoveLeft ()
  308. {
  309. ClearAllSelection ();
  310. DecCursorPosition ();
  311. return true;
  312. }
  313. bool MoveHome ()
  314. {
  315. // Home, C-A
  316. ClearAllSelection ();
  317. CursorPosition = 1;
  318. return true;
  319. }
  320. /// <inheritdoc/>
  321. public override void DeleteCharLeft (bool useOldCursorPos = true)
  322. {
  323. if (ReadOnly) {
  324. return;
  325. }
  326. ClearAllSelection ();
  327. SetText ((Rune)'0');
  328. DecCursorPosition ();
  329. return;
  330. }
  331. /// <inheritdoc/>
  332. public override void DeleteCharRight ()
  333. {
  334. if (ReadOnly) {
  335. return;
  336. }
  337. ClearAllSelection ();
  338. SetText ((Rune)'0');
  339. return;
  340. }
  341. /// <inheritdoc/>
  342. public override bool MouseEvent (MouseEvent ev)
  343. {
  344. var result = base.MouseEvent (ev);
  345. if (result && SelectedLength == 0 && ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  346. int point = ev.X;
  347. AdjCursorPosition (point, true);
  348. }
  349. return result;
  350. }
  351. /// <summary>
  352. /// Event firing method for the <see cref="DateChanged"/> event.
  353. /// </summary>
  354. /// <param name="args">Event arguments</param>
  355. public virtual void OnDateChanged (DateTimeEventArgs<DateTime> args) => DateChanged?.Invoke (this, args);
  356. }