CalendarData.Windows.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Collections.Generic;
  6. using Internal.Runtime.CompilerServices;
  7. namespace System.Globalization
  8. {
  9. internal partial class CalendarData
  10. {
  11. private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId)
  12. {
  13. Debug.Assert(!GlobalizationMode.Invariant);
  14. bool ret = true;
  15. uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE;
  16. //
  17. // Windows doesn't support some calendars right now, so remap those.
  18. //
  19. switch (calendarId)
  20. {
  21. case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese
  22. calendarId = CalendarId.JAPAN;
  23. break;
  24. case CalendarId.JULIAN: // Data looks like gregorian US
  25. case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent
  26. case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent
  27. case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent
  28. case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent
  29. case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent
  30. case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent
  31. case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent
  32. calendarId = CalendarId.GREGORIAN_US;
  33. break;
  34. }
  35. //
  36. // Special handling for some special calendar due to OS limitation.
  37. // This includes calendar like Taiwan calendar, UmAlQura calendar, etc.
  38. //
  39. CheckSpecialCalendar(ref calendarId, ref localeName);
  40. // Numbers
  41. ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax);
  42. // Strings
  43. ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName);
  44. ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay);
  45. // String Arrays
  46. // Formats
  47. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates!);
  48. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates!);
  49. // Get the YearMonth pattern.
  50. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths!);
  51. // Day & Month Names
  52. // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names
  53. // Day
  54. // Note that we're off-by-one since managed starts on sunday and windows starts on monday
  55. ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames);
  56. ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames);
  57. // Month names
  58. ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames);
  59. ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames);
  60. //
  61. // The following LCTYPE are not supported in some platforms. If the call fails,
  62. // don't return a failure.
  63. //
  64. GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames);
  65. // Gregorian may have genitive month names
  66. if (calendarId == CalendarId.GREGORIAN)
  67. {
  68. GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames);
  69. GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames);
  70. }
  71. // Calendar Parts Names
  72. // This doesn't get always get localized names for gregorian (not available in windows < 7)
  73. // so: eg: coreclr on win < 7 won't get these
  74. CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames!);
  75. CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames!);
  76. //
  77. // Calendar Era Info
  78. // Note that calendar era data (offsets, etc) is hard coded for each calendar since this
  79. // data is implementation specific and not dynamic (except perhaps Japanese)
  80. //
  81. // Clean up the escaping of the formats
  82. this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates)!;
  83. this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates)!;
  84. this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths)!;
  85. this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay)!;
  86. return ret;
  87. }
  88. // Get native two digit year max
  89. internal static int GetTwoDigitYearMax(CalendarId calendarId) =>
  90. GlobalizationMode.Invariant ? Invariant.iTwoDigitYearMax :
  91. CallGetCalendarInfoEx(null, calendarId, CAL_ITWODIGITYEARMAX, out int twoDigitYearMax) ? twoDigitYearMax :
  92. -1;
  93. // Call native side to figure out which calendars are allowed
  94. internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
  95. {
  96. Debug.Assert(!GlobalizationMode.Invariant);
  97. EnumCalendarsData data = default;
  98. data.userOverride = 0;
  99. data.calendars = new List<int>();
  100. // First call GetLocaleInfo if necessary
  101. if (useUserOverride)
  102. {
  103. // They want user overrides, see if the user calendar matches the input calendar
  104. int userCalendar = CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
  105. // If we got a default, then use it as the first calendar
  106. if (userCalendar != 0)
  107. {
  108. data.userOverride = userCalendar;
  109. data.calendars.Add(userCalendar);
  110. }
  111. }
  112. unsafe
  113. {
  114. Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, Unsafe.AsPointer(ref data));
  115. }
  116. // Copy to the output array
  117. for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++)
  118. calendars[i] = (CalendarId)data.calendars[i];
  119. // Now we have a list of data, return the count
  120. return data.calendars.Count;
  121. }
  122. private static bool SystemSupportsTaiwaneseCalendar()
  123. {
  124. Debug.Assert(!GlobalizationMode.Invariant);
  125. // Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI
  126. return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out string _);
  127. }
  128. // PAL Layer ends here
  129. private const uint CAL_RETURN_NUMBER = 0x20000000;
  130. private const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000;
  131. private const uint CAL_NOUSEROVERRIDE = 0x80000000;
  132. private const uint CAL_SCALNAME = 0x00000002;
  133. private const uint CAL_SMONTHDAY = 0x00000038;
  134. private const uint CAL_SSHORTDATE = 0x00000005;
  135. private const uint CAL_SLONGDATE = 0x00000006;
  136. private const uint CAL_SYEARMONTH = 0x0000002f;
  137. private const uint CAL_SDAYNAME7 = 0x0000000d;
  138. private const uint CAL_SABBREVDAYNAME7 = 0x00000014;
  139. private const uint CAL_SMONTHNAME1 = 0x00000015;
  140. private const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
  141. private const uint CAL_SSHORTESTDAYNAME7 = 0x00000037;
  142. private const uint CAL_SERASTRING = 0x00000004;
  143. private const uint CAL_SABBREVERASTRING = 0x00000039;
  144. private const uint CAL_ICALINTVALUE = 0x00000001;
  145. private const uint CAL_ITWODIGITYEARMAX = 0x00000030;
  146. private const uint ENUM_ALL_CALENDARS = 0xffffffff;
  147. private const uint LOCALE_SSHORTDATE = 0x0000001F;
  148. private const uint LOCALE_SLONGDATE = 0x00000020;
  149. private const uint LOCALE_SYEARMONTH = 0x00001006;
  150. private const uint LOCALE_ICALENDARTYPE = 0x00001009;
  151. ////////////////////////////////////////////////////////////////////////
  152. //
  153. // For calendars like Gregorain US/Taiwan/UmAlQura, they are not available
  154. // in all OS or all localized versions of OS.
  155. // If OS does not support these calendars, we will fallback by using the
  156. // appropriate fallback calendar and locale combination to retrieve data from OS.
  157. //
  158. // Parameters:
  159. // __deref_inout pCalendarInt:
  160. // Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed.
  161. // __in_out pLocaleNameStackBuffer
  162. // Pointer to the StackSString object which holds the locale name to be checked.
  163. // This will be updated to new fallback locale name if needed.
  164. //
  165. ////////////////////////////////////////////////////////////////////////
  166. private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName)
  167. {
  168. // Gregorian-US isn't always available in the OS, however it is the same for all locales
  169. switch (calendar)
  170. {
  171. case CalendarId.GREGORIAN_US:
  172. // See if this works
  173. if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out string _))
  174. {
  175. // Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS
  176. localeName = "fa-IR";
  177. }
  178. // See if that works
  179. if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out string _))
  180. {
  181. // Failed again, just use en-US with the gregorian calendar
  182. localeName = "en-US";
  183. calendar = CalendarId.GREGORIAN;
  184. }
  185. break;
  186. case CalendarId.TAIWAN:
  187. // Taiwan calendar data is not always in all language version of OS due to Geopolical reasons.
  188. // It is only available in zh-TW localized versions of Windows.
  189. // Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar.
  190. if (!SystemSupportsTaiwaneseCalendar())
  191. {
  192. calendar = CalendarId.GREGORIAN;
  193. }
  194. break;
  195. }
  196. }
  197. private static bool CallGetCalendarInfoEx(string? localeName, CalendarId calendar, uint calType, out int data)
  198. {
  199. return Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0;
  200. }
  201. private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data)
  202. {
  203. const int BUFFER_LENGTH = 80;
  204. // The maximum size for values returned from GetCalendarInfoEx is 80 characters.
  205. char* buffer = stackalloc char[BUFFER_LENGTH];
  206. int ret = Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero);
  207. if (ret > 0)
  208. {
  209. if (buffer[ret - 1] == '\0')
  210. {
  211. ret--; // don't include the null termination in the string
  212. }
  213. data = new string(buffer, 0, ret);
  214. return true;
  215. }
  216. data = "";
  217. return false;
  218. }
  219. // Context for EnumCalendarInfoExEx callback.
  220. private struct EnumData
  221. {
  222. public string? userOverride;
  223. public List<string>? strings;
  224. }
  225. // EnumCalendarInfoExEx callback itself.
  226. // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
  227. private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam)
  228. {
  229. ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam);
  230. try
  231. {
  232. string calendarInfo = new string(lpCalendarInfoString);
  233. // If we had a user override, check to make sure this differs
  234. if (context.userOverride != calendarInfo)
  235. {
  236. Debug.Assert(context.strings != null);
  237. context.strings.Add(calendarInfo);
  238. }
  239. return Interop.BOOL.TRUE;
  240. }
  241. catch (Exception)
  242. {
  243. return Interop.BOOL.FALSE;
  244. }
  245. }
  246. private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[]? data)
  247. {
  248. EnumData context = default;
  249. context.userOverride = null;
  250. context.strings = new List<string>();
  251. // First call GetLocaleInfo if necessary
  252. if ((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0) &&
  253. // Get user locale, see if it matches localeName.
  254. // Note that they should match exactly, including letter case
  255. GetUserDefaultLocaleName() == localeName)
  256. {
  257. // They want user overrides, see if the user calendar matches the input calendar
  258. CalendarId userCalendar = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
  259. // If the calendars were the same, see if the locales were the same
  260. if (userCalendar == calendar)
  261. {
  262. // They matched, get the user override since locale & calendar match
  263. string? res = CultureData.GetLocaleInfoEx(localeName, lcType);
  264. // if it succeeded remember the override for the later callers
  265. if (res != null)
  266. {
  267. // Remember this was the override (so we can look for duplicates later in the enum function)
  268. context.userOverride = res;
  269. // Add to the result strings.
  270. context.strings.Add(res);
  271. }
  272. }
  273. }
  274. // Now call the enumeration API. Work is done by our callback function
  275. Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context));
  276. // Now we have a list of data, fail if we didn't find anything.
  277. Debug.Assert(context.strings != null);
  278. if (context.strings.Count == 0)
  279. {
  280. data = null;
  281. return false;
  282. }
  283. string[] output = context.strings.ToArray();
  284. if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING)
  285. {
  286. // Eras are enumerated backwards. (oldest era name first, but
  287. // Japanese calendar has newest era first in array, and is only
  288. // calendar with multiple eras)
  289. Array.Reverse(output, 0, output.Length);
  290. }
  291. data = output;
  292. return true;
  293. }
  294. ////////////////////////////////////////////////////////////////////////
  295. //
  296. // Get the native day names
  297. //
  298. // NOTE: There's a disparity between .NET & windows day orders, the input day should
  299. // start with Sunday
  300. //
  301. // Parameters:
  302. // OUT pOutputStrings The output string[] value.
  303. //
  304. ////////////////////////////////////////////////////////////////////////
  305. private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
  306. {
  307. bool result = true;
  308. //
  309. // We'll need a new array of 7 items
  310. //
  311. string[] results = new string[7];
  312. // Get each one of them
  313. for (int i = 0; i < 7; i++, calType++)
  314. {
  315. result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]);
  316. // On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens
  317. // This is because the framework starts on sunday and windows starts on monday when counting days
  318. if (i == 0)
  319. calType -= 7;
  320. }
  321. outputStrings = results;
  322. return result;
  323. }
  324. ////////////////////////////////////////////////////////////////////////
  325. //
  326. // Get the native month names
  327. //
  328. // Parameters:
  329. // OUT pOutputStrings The output string[] value.
  330. //
  331. ////////////////////////////////////////////////////////////////////////
  332. private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
  333. {
  334. //
  335. // We'll need a new array of 13 items
  336. //
  337. string[] results = new string[13];
  338. // Get each one of them
  339. for (int i = 0; i < 13; i++, calType++)
  340. {
  341. if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]))
  342. results[i] = "";
  343. }
  344. outputStrings = results;
  345. return true;
  346. }
  347. //
  348. // struct to help our calendar data enumaration callback
  349. //
  350. private struct EnumCalendarsData
  351. {
  352. public int userOverride; // user override value (if found)
  353. public List<int> calendars; // list of calendars found so far
  354. }
  355. // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
  356. private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam)
  357. {
  358. ref EnumCalendarsData context = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)lParam);
  359. try
  360. {
  361. // If we had a user override, check to make sure this differs
  362. if (context.userOverride != calendar)
  363. context.calendars.Add((int)calendar);
  364. return Interop.BOOL.TRUE;
  365. }
  366. catch (Exception)
  367. {
  368. return Interop.BOOL.FALSE;
  369. }
  370. }
  371. private static unsafe string GetUserDefaultLocaleName()
  372. {
  373. Debug.Assert(!GlobalizationMode.Invariant);
  374. int result;
  375. char* localeName = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH];
  376. result = CultureData.GetLocaleInfoEx(Interop.Kernel32.LOCALE_NAME_USER_DEFAULT, Interop.Kernel32.LOCALE_SNAME, localeName, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH);
  377. return result <= 0 ? "" : new string(localeName, 0, result - 1); // exclude the null termination
  378. }
  379. }
  380. }