DateField.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 NStack;
  12. namespace Terminal.Gui {
  13. /// <summary>
  14. /// Date edit widget
  15. /// </summary>
  16. /// <remarks>
  17. /// This widget provides date editing functionality, and mouse support.
  18. /// </remarks>
  19. public class DateField : TextField {
  20. bool isShort;
  21. int longFieldLen = 10;
  22. int shortFieldLen = 8;
  23. int FieldLen { get { return isShort ? shortFieldLen : longFieldLen; } }
  24. string sepChar;
  25. string longFormat;
  26. string shortFormat;
  27. string Format { get { return isShort ? shortFormat : longFormat; } }
  28. /// <summary>
  29. /// Public constructor that creates a date edit field at an absolute position and fixed size.
  30. /// </summary>
  31. /// <param name="x">The x coordinate.</param>
  32. /// <param name="y">The y coordinate.</param>
  33. /// <param name="date">Initial date contents.</param>
  34. /// <param name="isShort">If true, shows only two digits for the year.</param>
  35. public DateField(int x, int y, DateTime date, bool isShort = false) : base(x, y, isShort ? 10 : 12, "")
  36. {
  37. CultureInfo cultureInfo = CultureInfo.CurrentCulture;
  38. sepChar = cultureInfo.DateTimeFormat.DateSeparator;
  39. longFormat = GetLongFormat (cultureInfo.DateTimeFormat.ShortDatePattern);
  40. shortFormat = GetShortFormat(longFormat);
  41. this.isShort = isShort;
  42. CursorPosition = 1;
  43. Date = date;
  44. Changed += DateField_Changed;
  45. }
  46. void DateField_Changed(object sender, ustring e)
  47. {
  48. if (!DateTime.TryParseExact(Text.ToString(), Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result))
  49. Text = e;
  50. }
  51. string GetLongFormat (string lf)
  52. {
  53. ustring [] frm = ustring.Make (lf).Split (ustring.Make (sepChar));
  54. for (int i = 0; i < frm.Length; i++) {
  55. if (frm [i].Contains ("M") && frm [i].Length < 2)
  56. lf = lf.Replace ("M", "MM");
  57. if (frm [i].Contains ("d") && frm [i].Length < 2)
  58. lf = lf.Replace ("d", "dd");
  59. if (frm [i].Contains ("y") && frm [i].Length < 4)
  60. lf = lf.Replace ("yy", "yyyy");
  61. }
  62. return $" {lf}";
  63. }
  64. string GetShortFormat (string lf)
  65. {
  66. return lf.Replace("yyyy", "yy");
  67. }
  68. /// <summary>
  69. /// Gets or sets the date in the widget.
  70. /// </summary>
  71. /// <remarks>
  72. /// </remarks>
  73. public DateTime Date {
  74. get {
  75. if (!DateTime.TryParseExact(Text.ToString(), Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result)) return new DateTime();
  76. return result;
  77. }
  78. set {
  79. this.Text = value.ToString(Format);
  80. }
  81. }
  82. bool SetText(Rune key)
  83. {
  84. var text = TextModel.ToRunes(Text);
  85. var newText = text.GetRange(0, CursorPosition);
  86. newText.Add(key);
  87. if (CursorPosition < FieldLen)
  88. newText = newText.Concat(text.GetRange(CursorPosition + 1, text.Count - (CursorPosition + 1))).ToList();
  89. return SetText(ustring.Make(newText));
  90. }
  91. bool SetText(ustring text)
  92. {
  93. ustring[] vals = text.Split(ustring.Make(sepChar));
  94. ustring[] frm = ustring.Make(Format).Split(ustring.Make(sepChar));
  95. bool isValidDate = true;
  96. int idx = GetFormatIndex(frm, "y");
  97. int year = Int32.Parse(vals[idx].ToString());
  98. int month;
  99. int day;
  100. idx = GetFormatIndex(frm, "M");
  101. if (Int32.Parse(vals[idx].ToString()) < 1) {
  102. isValidDate = false;
  103. month = 1;
  104. vals[idx] = "1";
  105. } else if (Int32.Parse(vals[idx].ToString()) > 12) {
  106. isValidDate = false;
  107. month = 12;
  108. vals[idx] = "12";
  109. } else
  110. month = Int32.Parse(vals[idx].ToString());
  111. idx = GetFormatIndex(frm, "d");
  112. if (Int32.Parse(vals[idx].ToString()) < 1) {
  113. isValidDate = false;
  114. day = 1;
  115. vals[idx] = "1";
  116. } else if (Int32.Parse(vals[idx].ToString()) > 31) {
  117. isValidDate = false;
  118. day = DateTime.DaysInMonth(year, month);
  119. vals[idx] = day.ToString();
  120. } else
  121. day = Int32.Parse(vals[idx].ToString());
  122. string date = GetData(month, day, year, frm);
  123. Text = date;
  124. if (!DateTime.TryParseExact(date, Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result) ||
  125. !isValidDate)
  126. return false;
  127. return true;
  128. }
  129. string GetData(int month, int day, int year, ustring[] fm)
  130. {
  131. string data = " ";
  132. for (int i = 0; i < fm.Length; i++) {
  133. if (fm[i].Contains("M"))
  134. data += $"{month,2:00}";
  135. else if (fm[i].Contains("d"))
  136. data += $"{day,2:00}";
  137. else
  138. data += isShort ? $"{year,2:00}" : $"{year,4:0000}";
  139. if (i < 2)
  140. data += $"{sepChar}";
  141. }
  142. return data;
  143. }
  144. int GetFormatIndex(ustring[] fm, string t)
  145. {
  146. int idx = -1;
  147. for (int i = 0; i < fm.Length; i++) {
  148. if (fm[i].Contains(t)) {
  149. idx = i;
  150. break;
  151. }
  152. }
  153. return idx;
  154. }
  155. void IncCursorPosition()
  156. {
  157. if (CursorPosition == FieldLen)
  158. return;
  159. if (Text[++CursorPosition] == sepChar.ToCharArray()[0])
  160. CursorPosition++;
  161. }
  162. void DecCursorPosition()
  163. {
  164. if (CursorPosition == 1)
  165. return;
  166. if (Text[--CursorPosition] == sepChar.ToCharArray()[0])
  167. CursorPosition--;
  168. }
  169. void AdjCursorPosition()
  170. {
  171. if (Text[CursorPosition] == sepChar.ToCharArray()[0])
  172. CursorPosition++;
  173. }
  174. public override bool ProcessKey(KeyEvent kb)
  175. {
  176. switch (kb.Key) {
  177. case Key.DeleteChar:
  178. case Key.ControlD:
  179. SetText('0');
  180. break;
  181. case Key.Delete:
  182. case Key.Backspace:
  183. SetText('0');
  184. DecCursorPosition();
  185. break;
  186. // Home, C-A
  187. case Key.Home:
  188. case Key.ControlA:
  189. CursorPosition = 1;
  190. break;
  191. case Key.CursorLeft:
  192. case Key.ControlB:
  193. DecCursorPosition();
  194. break;
  195. case Key.End:
  196. case Key.ControlE: // End
  197. CursorPosition = FieldLen;
  198. break;
  199. case Key.CursorRight:
  200. case Key.ControlF:
  201. IncCursorPosition();
  202. break;
  203. default:
  204. // Ignore non-numeric characters.
  205. if (kb.Key < (Key)((int)'0') || kb.Key > (Key)((int)'9'))
  206. return false;
  207. if (SetText(TextModel.ToRunes(ustring.Make((uint)kb.Key)).First()))
  208. IncCursorPosition();
  209. return true;
  210. }
  211. return true;
  212. }
  213. public override bool MouseEvent(MouseEvent ev)
  214. {
  215. if (!ev.Flags.HasFlag(MouseFlags.Button1Clicked))
  216. return false;
  217. if (!HasFocus)
  218. SuperView.SetFocus(this);
  219. var point = ev.X;
  220. if (point > FieldLen)
  221. point = FieldLen;
  222. if (point < 1)
  223. point = 1;
  224. CursorPosition = point;
  225. AdjCursorPosition();
  226. return true;
  227. }
  228. }
  229. }