CultureData.Unix.cs 16 KB

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