DateField.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 = $" {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 GetShortFormat(string lf)
  52. {
  53. return lf.Replace("yyyy", "yy");
  54. }
  55. /// <summary>
  56. /// Gets or sets the date in the widget.
  57. /// </summary>
  58. /// <remarks>
  59. /// </remarks>
  60. public DateTime Date {
  61. get {
  62. if (!DateTime.TryParseExact(Text.ToString(), Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result)) return new DateTime();
  63. return result;
  64. }
  65. set {
  66. this.Text = value.ToString(Format);
  67. }
  68. }
  69. bool SetText(Rune key)
  70. {
  71. var text = TextModel.ToRunes(Text);
  72. var newText = text.GetRange(0, CursorPosition);
  73. newText.Add(key);
  74. if (CursorPosition < FieldLen)
  75. newText = newText.Concat(text.GetRange(CursorPosition + 1, text.Count - (CursorPosition + 1))).ToList();
  76. return SetText(ustring.Make(newText));
  77. }
  78. bool SetText(ustring text)
  79. {
  80. ustring[] vals = text.Split(ustring.Make(sepChar));
  81. ustring[] frm = ustring.Make(Format).Split(ustring.Make(sepChar));
  82. bool isValidDate = true;
  83. int idx = GetFormatIndex(frm, "y");
  84. int year = Int32.Parse(vals[idx].ToString());
  85. int month;
  86. int day;
  87. idx = GetFormatIndex(frm, "M");
  88. if (Int32.Parse(vals[idx].ToString()) < 1) {
  89. isValidDate = false;
  90. month = 1;
  91. vals[idx] = "1";
  92. } else if (Int32.Parse(vals[idx].ToString()) > 12) {
  93. isValidDate = false;
  94. month = 12;
  95. vals[idx] = "12";
  96. } else
  97. month = Int32.Parse(vals[idx].ToString());
  98. idx = GetFormatIndex(frm, "d");
  99. if (Int32.Parse(vals[idx].ToString()) < 1) {
  100. isValidDate = false;
  101. day = 1;
  102. vals[idx] = "1";
  103. } else if (Int32.Parse(vals[idx].ToString()) > 31) {
  104. isValidDate = false;
  105. day = DateTime.DaysInMonth(year, month);
  106. vals[idx] = day.ToString();
  107. } else
  108. day = Int32.Parse(vals[idx].ToString());
  109. string date = GetData(month, day, year, frm);
  110. Text = date;
  111. if (!DateTime.TryParseExact(date, Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result) ||
  112. !isValidDate)
  113. return false;
  114. return true;
  115. }
  116. string GetData(int month, int day, int year, ustring[] fm)
  117. {
  118. string data = " ";
  119. for (int i = 0; i < fm.Length; i++) {
  120. if (fm[i].Contains("M"))
  121. data += $"{month,2:00}";
  122. else if (fm[i].Contains("d"))
  123. data += $"{day,2:00}";
  124. else
  125. data += isShort ? $"{year,2:00}" : $"{year,4:0000}";
  126. if (i < 2)
  127. data += $"{sepChar}";
  128. }
  129. return data;
  130. }
  131. int GetFormatIndex(ustring[] fm, string t)
  132. {
  133. int idx = -1;
  134. for (int i = 0; i < fm.Length; i++) {
  135. if (fm[i].Contains(t)) {
  136. idx = i;
  137. break;
  138. }
  139. }
  140. return idx;
  141. }
  142. void IncCursorPosition()
  143. {
  144. if (CursorPosition == FieldLen)
  145. return;
  146. if (Text[++CursorPosition] == sepChar.ToCharArray()[0])
  147. CursorPosition++;
  148. }
  149. void DecCursorPosition()
  150. {
  151. if (CursorPosition == 1)
  152. return;
  153. if (Text[--CursorPosition] == sepChar.ToCharArray()[0])
  154. CursorPosition--;
  155. }
  156. void AdjCursorPosition()
  157. {
  158. if (Text[CursorPosition] == sepChar.ToCharArray()[0])
  159. CursorPosition++;
  160. }
  161. public override bool ProcessKey(KeyEvent kb)
  162. {
  163. switch (kb.Key) {
  164. case Key.DeleteChar:
  165. case Key.ControlD:
  166. SetText('0');
  167. break;
  168. case Key.Delete:
  169. case Key.Backspace:
  170. SetText('0');
  171. DecCursorPosition();
  172. break;
  173. // Home, C-A
  174. case Key.Home:
  175. case Key.ControlA:
  176. CursorPosition = 1;
  177. break;
  178. case Key.CursorLeft:
  179. case Key.ControlB:
  180. DecCursorPosition();
  181. break;
  182. case Key.End:
  183. case Key.ControlE: // End
  184. CursorPosition = FieldLen;
  185. break;
  186. case Key.CursorRight:
  187. case Key.ControlF:
  188. IncCursorPosition();
  189. break;
  190. default:
  191. // Ignore non-numeric characters.
  192. if (kb.Key < (Key)((int)'0') || kb.Key > (Key)((int)'9'))
  193. return false;
  194. if (SetText(TextModel.ToRunes(ustring.Make((uint)kb.Key)).First()))
  195. IncCursorPosition();
  196. return true;
  197. }
  198. return true;
  199. }
  200. public override bool MouseEvent(MouseEvent ev)
  201. {
  202. if (!ev.Flags.HasFlag(MouseFlags.Button1Clicked))
  203. return false;
  204. if (!HasFocus)
  205. SuperView.SetFocus(this);
  206. var point = ev.X;
  207. if (point > FieldLen)
  208. point = FieldLen;
  209. if (point < 1)
  210. point = 1;
  211. CursorPosition = point;
  212. AdjCursorPosition();
  213. return true;
  214. }
  215. }
  216. }