CultureData.Unix.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Runtime.InteropServices;
  8. using System.Security;
  9. using System.Text;
  10. namespace System.Globalization
  11. {
  12. internal partial class CultureData
  13. {
  14. // ICU constants
  15. const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
  16. const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
  17. const string ICU_COLLATION_KEYWORD = "@collation=";
  18. /// <summary>
  19. /// This method uses the sRealName field (which is initialized by the constructor before this is called) to
  20. /// initialize the rest of the state of CultureData based on the underlying OS globalization library.
  21. /// </summary>
  22. private unsafe bool InitCultureData()
  23. {
  24. Debug.Assert(_sRealName != null);
  25. Debug.Assert(!GlobalizationMode.Invariant);
  26. string realNameBuffer = _sRealName;
  27. // Basic validation
  28. if (realNameBuffer.Contains('@'))
  29. {
  30. return false; // don't allow ICU variants to come in directly
  31. }
  32. // Replace _ (alternate sort) with @collation= for ICU
  33. ReadOnlySpan<char> alternateSortName = default;
  34. int index = realNameBuffer.IndexOf('_');
  35. if (index > 0)
  36. {
  37. if (index >= (realNameBuffer.Length - 1) // must have characters after _
  38. || realNameBuffer.IndexOf('_', index + 1) >= 0) // only one _ allowed
  39. {
  40. return false; // fail
  41. }
  42. alternateSortName = realNameBuffer.AsSpan(index + 1);
  43. realNameBuffer = string.Concat(realNameBuffer.AsSpan(0, index), ICU_COLLATION_KEYWORD, alternateSortName);
  44. }
  45. // Get the locale name from ICU
  46. if (!GetLocaleName(realNameBuffer, out _sWindowsName))
  47. {
  48. return false; // fail
  49. }
  50. // Replace the ICU collation keyword with an _
  51. Debug.Assert(_sWindowsName != null);
  52. index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
  53. if (index >= 0)
  54. {
  55. _sName = string.Concat(_sWindowsName.AsSpan(0, index), "_", alternateSortName);
  56. }
  57. else
  58. {
  59. _sName = _sWindowsName;
  60. }
  61. _sRealName = _sName;
  62. _iLanguage = LCID;
  63. if (_iLanguage == 0)
  64. {
  65. _iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
  66. }
  67. _bNeutral = TwoLetterISOCountryName.Length == 0;
  68. _sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
  69. // Remove the sort from sName unless custom culture
  70. if (index > 0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
  71. {
  72. _sName = _sWindowsName.Substring(0, index);
  73. }
  74. return true;
  75. }
  76. internal static unsafe bool GetLocaleName(string localeName, out string? windowsName)
  77. {
  78. // Get the locale name from ICU
  79. char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
  80. if (!Interop.Globalization.GetLocaleName(localeName, buffer, ICU_ULOC_FULLNAME_CAPACITY))
  81. {
  82. windowsName = null;
  83. return false; // fail
  84. }
  85. // Success - use the locale name returned which may be different than realNameBuffer (casing)
  86. windowsName = new string(buffer); // the name passed to subsequent ICU calls
  87. return true;
  88. }
  89. internal static unsafe bool GetDefaultLocaleName(out string? windowsName)
  90. {
  91. // Get the default (system) locale name from ICU
  92. char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
  93. if (!Interop.Globalization.GetDefaultLocaleName(buffer, ICU_ULOC_FULLNAME_CAPACITY))
  94. {
  95. windowsName = null;
  96. return false; // fail
  97. }
  98. // Success - use the locale name returned which may be different than realNameBuffer (casing)
  99. windowsName = new string(buffer); // the name passed to subsequent ICU calls
  100. return true;
  101. }
  102. private string GetLocaleInfo(LocaleStringData type)
  103. {
  104. Debug.Assert(!GlobalizationMode.Invariant);
  105. Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
  106. return GetLocaleInfo(_sWindowsName, type);
  107. }
  108. // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
  109. // "windows" name, which can be specific for downlevel (< windows 7) os's.
  110. private unsafe string GetLocaleInfo(string localeName, LocaleStringData type)
  111. {
  112. Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
  113. switch (type)
  114. {
  115. case LocaleStringData.NegativeInfinitySymbol:
  116. // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
  117. return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
  118. GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
  119. }
  120. char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
  121. bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
  122. if (!result)
  123. {
  124. // Failed, just use empty string
  125. Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
  126. return string.Empty;
  127. }
  128. return new string(buffer);
  129. }
  130. private int GetLocaleInfo(LocaleNumberData type)
  131. {
  132. Debug.Assert(!GlobalizationMode.Invariant);
  133. Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
  134. switch (type)
  135. {
  136. case LocaleNumberData.CalendarType:
  137. // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
  138. return 0;
  139. }
  140. int value = 0;
  141. bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
  142. if (!result)
  143. {
  144. // Failed, just use 0
  145. Debug.Fail("[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
  146. }
  147. return value;
  148. }
  149. private int[] GetLocaleInfo(LocaleGroupingData type)
  150. {
  151. Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
  152. int primaryGroupingSize = 0;
  153. int secondaryGroupingSize = 0;
  154. bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
  155. if (!result)
  156. {
  157. Debug.Fail("[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
  158. }
  159. if (secondaryGroupingSize == 0)
  160. {
  161. return new int[] { primaryGroupingSize };
  162. }
  163. return new int[] { primaryGroupingSize, secondaryGroupingSize };
  164. }
  165. private string GetTimeFormatString() => GetTimeFormatString(shortFormat: false);
  166. private unsafe string GetTimeFormatString(bool shortFormat)
  167. {
  168. Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
  169. char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
  170. bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
  171. if (!result)
  172. {
  173. // Failed, just use empty string
  174. Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
  175. return string.Empty;
  176. }
  177. var span = new ReadOnlySpan<char>(buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
  178. return ConvertIcuTimeFormatString(span.Slice(0, span.IndexOf('\0')));
  179. }
  180. private int GetFirstDayOfWeek() => GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
  181. private string[] GetTimeFormats()
  182. {
  183. string format = GetTimeFormatString(false);
  184. return new string[] { format };
  185. }
  186. private string[] GetShortTimeFormats()
  187. {
  188. string format = GetTimeFormatString(true);
  189. return new string[] { format };
  190. }
  191. private static CultureData? GetCultureDataFromRegionName(string? regionName)
  192. {
  193. // no support to lookup by region name, other than the hard-coded list in CultureData
  194. return null;
  195. }
  196. private static string GetLanguageDisplayName(string cultureName)
  197. {
  198. return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
  199. }
  200. private static string? GetRegionDisplayName(string? isoCountryCode)
  201. {
  202. // use the fallback which is to return NativeName
  203. return null;
  204. }
  205. private static CultureInfo GetUserDefaultCulture()
  206. {
  207. return CultureInfo.GetUserDefaultCulture();
  208. }
  209. private static string ConvertIcuTimeFormatString(ReadOnlySpan<char> icuFormatString)
  210. {
  211. Debug.Assert(icuFormatString.Length < ICU_ULOC_FULLNAME_CAPACITY);
  212. Span<char> result = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
  213. bool amPmAdded = false;
  214. int resultPos = 0;
  215. for (int i = 0; i < icuFormatString.Length; i++)
  216. {
  217. switch (icuFormatString[i])
  218. {
  219. case '\'':
  220. result[resultPos++] = icuFormatString[i++];
  221. while (i < icuFormatString.Length)
  222. {
  223. char current = icuFormatString[i++];
  224. result[resultPos++] = current;
  225. if (current == '\'')
  226. {
  227. break;
  228. }
  229. }
  230. break;
  231. case ':':
  232. case '.':
  233. case 'H':
  234. case 'h':
  235. case 'm':
  236. case 's':
  237. result[resultPos++] = icuFormatString[i];
  238. break;
  239. case ' ':
  240. case '\u00A0':
  241. // Convert nonbreaking spaces into regular spaces
  242. result[resultPos++] = ' ';
  243. break;
  244. case 'a': // AM/PM
  245. if (!amPmAdded)
  246. {
  247. amPmAdded = true;
  248. result[resultPos++] = 't';
  249. result[resultPos++] = 't';
  250. }
  251. break;
  252. }
  253. }
  254. return result.Slice(0, resultPos).ToString();
  255. }
  256. private static string? LCIDToLocaleName(int culture)
  257. {
  258. Debug.Assert(!GlobalizationMode.Invariant);
  259. return LocaleData.LCIDToLocaleName(culture);
  260. }
  261. private static int LocaleNameToLCID(string cultureName)
  262. {
  263. Debug.Assert(!GlobalizationMode.Invariant);
  264. int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
  265. return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
  266. }
  267. private static int GetAnsiCodePage(string cultureName)
  268. {
  269. int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
  270. return ansiCodePage == -1 ? CultureData.Invariant.ANSICodePage : ansiCodePage;
  271. }
  272. private static int GetOemCodePage(string cultureName)
  273. {
  274. int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
  275. return oemCodePage == -1 ? CultureData.Invariant.OEMCodePage : oemCodePage;
  276. }
  277. private static int GetMacCodePage(string cultureName)
  278. {
  279. int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
  280. return macCodePage == -1 ? CultureData.Invariant.MacCodePage : macCodePage;
  281. }
  282. private static int GetEbcdicCodePage(string cultureName)
  283. {
  284. int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
  285. return ebcdicCodePage == -1 ? CultureData.Invariant.EBCDICCodePage : ebcdicCodePage;
  286. }
  287. private static int GetGeoId(string cultureName)
  288. {
  289. int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
  290. return geoId == -1 ? CultureData.Invariant.GeoId : geoId;
  291. }
  292. private static int GetDigitSubstitution(string cultureName)
  293. {
  294. int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution);
  295. return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution;
  296. }
  297. private static string GetThreeLetterWindowsLanguageName(string cultureName)
  298. {
  299. return LocaleData.GetThreeLetterWindowsLanguageName(cultureName) ?? "ZZZ" /* default lang name */;
  300. }
  301. private static CultureInfo[] EnumCultures(CultureTypes types)
  302. {
  303. Debug.Assert(!GlobalizationMode.Invariant);
  304. if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
  305. {
  306. return Array.Empty<CultureInfo>();
  307. }
  308. int bufferLength = Interop.Globalization.GetLocales(null, 0);
  309. if (bufferLength <= 0)
  310. {
  311. return Array.Empty<CultureInfo>();
  312. }
  313. char [] chars = new char[bufferLength];
  314. bufferLength = Interop.Globalization.GetLocales(chars, bufferLength);
  315. if (bufferLength <= 0)
  316. {
  317. return Array.Empty<CultureInfo>();
  318. }
  319. bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
  320. bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
  321. List<CultureInfo> list = new List<CultureInfo>();
  322. if (enumNeutrals)
  323. {
  324. list.Add(CultureInfo.InvariantCulture);
  325. }
  326. int index = 0;
  327. while (index < bufferLength)
  328. {
  329. int length = (int) chars[index++];
  330. if (index + length <= bufferLength)
  331. {
  332. CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length));
  333. if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
  334. {
  335. list.Add(ci);
  336. }
  337. }
  338. index += length;
  339. }
  340. return list.ToArray();
  341. }
  342. private static string GetConsoleFallbackName(string cultureName)
  343. {
  344. return LocaleData.GetConsoleUICulture(cultureName);
  345. }
  346. internal bool IsFramework => false;
  347. internal bool IsWin32Installed => false;
  348. internal bool IsReplacementCulture => false;
  349. }
  350. }