Add LanguageGroup/GeoID enumeration fns.
[wine] / dlls / kernel / locale.c
1 /*
2  * Locale support
3  *
4  * Copyright 1995 Martin von Loewis
5  * Copyright 1998 David Lee Lambert
6  * Copyright 2000 Julio César Gázquez
7  * Copyright 2002 Alexandre Julliard for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <string.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <stdlib.h>
32
33 #include "ntstatus.h"
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winuser.h"  /* for RT_STRINGW */
37 #include "winreg.h"
38 #include "winternl.h"
39 #include "wine/unicode.h"
40 #include "winnls.h"
41 #include "winerror.h"
42 #include "thread.h"
43 #include "wine/debug.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(nls);
46
47 #define LOCALE_LOCALEINFOFLAGSMASK (LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP|LOCALE_RETURN_NUMBER)
48
49 static const WCHAR kernel32W[] = { 'K','E','R','N','E','L','3','2','\0' };
50
51 extern void CODEPAGE_Init( UINT ansi_cp, UINT oem_cp, UINT mac_cp, UINT unix_cp, LCID lcid );
52
53 /* Charset to codepage map, sorted by name. */
54 static const struct charset_entry
55 {
56     const char *charset_name;
57     UINT        codepage;
58 } charset_names[] =
59 {
60     { "CP1250", 1250 },
61     { "CP1251", 1251 },
62     { "CP1252", 1252 },
63     { "CP1253", 1253 },
64     { "CP1254", 1254 },
65     { "CP1255", 1255 },
66     { "CP1256", 1256 },
67     { "CP1257", 1257 },
68     { "CP1258", 1258 },
69     { "IBM037", 37 },
70     { "IBM1026", 1026 },
71     { "IBM424", 424 },
72     { "IBM437", 437 },
73     { "IBM500", 500 },
74     { "IBM850", 850 },
75     { "IBM852", 852 },
76     { "IBM855", 855 },
77     { "IBM857", 857 },
78     { "IBM860", 860 },
79     { "IBM861", 861 },
80     { "IBM862", 862 },
81     { "IBM863", 863 },
82     { "IBM864", 864 },
83     { "IBM865", 865 },
84     { "IBM866", 866 },
85     { "IBM869", 869 },
86     { "IBM874", 874 },
87     { "IBM875", 875 },
88     { "ISO88591", 28591 },
89     { "ISO885910", 28600 },
90     { "ISO885913", 28603 },
91     { "ISO885914", 28604 },
92     { "ISO885915", 28605 },
93     { "ISO88592", 28592 },
94     { "ISO88593", 28593 },
95     { "ISO88594", 28594 },
96     { "ISO88595", 28595 },
97     { "ISO88596", 28596 },
98     { "ISO88597", 28597 },
99     { "ISO88598", 28598 },
100     { "ISO88599", 28599 },
101     { "KOI8R", 20866 },
102     { "KOI8U", 20866 },
103     { "UTF8", CP_UTF8 }
104 };
105
106 #define NLS_MAX_LANGUAGES 20
107 typedef struct {
108     char lang[128];
109     char country[128];
110     LANGID found_lang_id[NLS_MAX_LANGUAGES];
111     char found_language[NLS_MAX_LANGUAGES][3];
112     char found_country[NLS_MAX_LANGUAGES][3];
113     int n_found;
114 } LANG_FIND_DATA;
115
116
117 /***********************************************************************
118  *              get_lcid_codepage
119  *
120  * Retrieve the ANSI codepage for a given locale.
121  */
122 inline static UINT get_lcid_codepage( LCID lcid )
123 {
124     UINT ret;
125     if (!GetLocaleInfoW( lcid, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER, (WCHAR *)&ret,
126                          sizeof(ret)/sizeof(WCHAR) )) ret = 0;
127     return ret;
128 }
129
130
131 /***********************************************************************
132  *              create_registry_key
133  *
134  * Create the Control Panel\\International registry key.
135  */
136 inline static HKEY create_registry_key(void)
137 {
138     static const WCHAR intlW[] = {'C','o','n','t','r','o','l',' ','P','a','n','e','l','\\',
139                                   'I','n','t','e','r','n','a','t','i','o','n','a','l',0};
140     OBJECT_ATTRIBUTES attr;
141     UNICODE_STRING nameW;
142     HKEY hkey;
143
144     if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &hkey ) != STATUS_SUCCESS) return 0;
145
146     attr.Length = sizeof(attr);
147     attr.RootDirectory = hkey;
148     attr.ObjectName = &nameW;
149     attr.Attributes = 0;
150     attr.SecurityDescriptor = NULL;
151     attr.SecurityQualityOfService = NULL;
152     RtlInitUnicodeString( &nameW, intlW );
153
154     if (NtCreateKey( &hkey, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS) hkey = 0;
155     NtClose( attr.RootDirectory );
156     return hkey;
157 }
158
159
160 /***********************************************************************
161  *              update_registry
162  *
163  * Update registry contents on startup if the user locale has changed.
164  * This simulates the action of the Windows control panel.
165  */
166 inline static void update_registry( LCID lcid )
167 {
168     static const USHORT updateValues[] = {
169       LOCALE_SLANGUAGE,
170       LOCALE_SCOUNTRY, LOCALE_ICOUNTRY,
171       LOCALE_S1159, LOCALE_S2359,
172       LOCALE_STIME, LOCALE_ITIME,
173       LOCALE_ITLZERO,
174       LOCALE_SSHORTDATE,
175       LOCALE_IDATE,
176       LOCALE_SLONGDATE,
177       LOCALE_SDATE,
178       LOCALE_SCURRENCY, LOCALE_ICURRENCY,
179       LOCALE_INEGCURR,
180       LOCALE_ICURRDIGITS,
181       LOCALE_SDECIMAL,
182       LOCALE_SLIST,
183       LOCALE_STHOUSAND,
184       LOCALE_IDIGITS,
185       LOCALE_IDIGITSUBSTITUTION,
186       LOCALE_SNATIVEDIGITS,
187       LOCALE_ITIMEMARKPOSN,
188       LOCALE_ICALENDARTYPE,
189       LOCALE_ILZERO,
190       LOCALE_IMEASURE
191     };
192     static const WCHAR LocaleW[] = {'L','o','c','a','l','e',0};
193     UNICODE_STRING nameW;
194     char buffer[20];
195     WCHAR bufferW[80];
196     DWORD count, i;
197     HKEY hkey;
198
199     if (!(hkey = create_registry_key()))
200         return;  /* don't do anything if we can't create the registry key */
201
202     RtlInitUnicodeString( &nameW, LocaleW );
203     count = sizeof(bufferW);
204     if (!NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation, (LPBYTE)bufferW, count, &count))
205     {
206         const KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)bufferW;
207         LPCWSTR szValueText = (LPCWSTR)info->Data;
208
209         if (strtoulW( szValueText, NULL, 16 ) == lcid)  /* already set correctly */
210         {
211             NtClose( hkey );
212             return;
213         }
214         TRACE( "updating registry, locale changed %s -> %08lx\n", debugstr_w(szValueText), lcid );
215     }
216     else TRACE( "updating registry, locale changed none -> %08lx\n", lcid );
217
218     sprintf( buffer, "%08lx", lcid );
219     /* Note: '9' constant below is strlen(buffer) + 1 */
220     RtlMultiByteToUnicodeN( bufferW, sizeof(bufferW), NULL, buffer, 9 );
221     NtSetValueKey( hkey, &nameW, 0, REG_SZ, bufferW, 9 * sizeof(WCHAR) );
222     NtClose( hkey );
223
224     for (i = 0; i < sizeof(updateValues)/sizeof(updateValues[0]); i++)
225     {
226         GetLocaleInfoW( lcid, updateValues[i] | LOCALE_NOUSEROVERRIDE, bufferW,
227                         sizeof(bufferW)/sizeof(WCHAR) );
228         SetLocaleInfoW( lcid, updateValues[i], bufferW );
229     }
230 }
231
232
233 /***********************************************************************
234  *           find_language_id_proc
235  */
236 static BOOL CALLBACK find_language_id_proc( HMODULE hModule, LPCSTR type,
237                                             LPCSTR name, WORD LangID, LPARAM lParam )
238 {
239     LANG_FIND_DATA *l_data = (LANG_FIND_DATA *)lParam;
240     LCID lcid = MAKELCID(LangID, SORT_DEFAULT);
241     char buf_language[128];
242     char buf_country[128];
243     char buf_en_language[128];
244
245     TRACE("%04X\n", (UINT)LangID);
246     if(PRIMARYLANGID(LangID) == LANG_NEUTRAL)
247         return TRUE; /* continue search */
248
249     buf_language[0] = 0;
250     buf_country[0] = 0;
251
252     GetLocaleInfoA(lcid, LOCALE_SISO639LANGNAME|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
253                    buf_language, sizeof(buf_language));
254     TRACE("LOCALE_SISO639LANGNAME: %s\n", buf_language);
255
256     GetLocaleInfoA(lcid, LOCALE_SISO3166CTRYNAME|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
257                    buf_country, sizeof(buf_country));
258     TRACE("LOCALE_SISO3166CTRYNAME: %s\n", buf_country);
259
260     if(l_data->lang[0] && !strcasecmp(l_data->lang, buf_language))
261     {
262         if(l_data->country[0])
263         {
264             if(!strcasecmp(l_data->country, buf_country))
265             {
266                 l_data->found_lang_id[0] = LangID;
267                 l_data->n_found = 1;
268                 TRACE("Found lang_id %04X for %s_%s\n", LangID, l_data->lang, l_data->country);
269                 return FALSE; /* stop enumeration */
270             }
271         }
272         else /* l_data->country not specified */
273         {
274             if(l_data->n_found < NLS_MAX_LANGUAGES)
275             {
276                 l_data->found_lang_id[l_data->n_found] = LangID;
277                 strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
278                 strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
279                 l_data->n_found++;
280                 TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
281                 return TRUE; /* continue search */
282             }
283         }
284     }
285
286     /* Just in case, check LOCALE_SENGLANGUAGE too,
287      * in hope that possible alias name might have that value.
288      */
289     buf_en_language[0] = 0;
290     GetLocaleInfoA(lcid, LOCALE_SENGLANGUAGE|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
291                    buf_en_language, sizeof(buf_en_language));
292     TRACE("LOCALE_SENGLANGUAGE: %s\n", buf_en_language);
293
294     if(l_data->lang[0] && !strcasecmp(l_data->lang, buf_en_language))
295     {
296         l_data->found_lang_id[l_data->n_found] = LangID;
297         strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
298         strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
299         l_data->n_found++;
300         TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
301     }
302
303     return TRUE; /* continue search */
304 }
305
306
307 /***********************************************************************
308  *           get_language_id
309  *
310  * INPUT:
311  *      Lang: a string whose two first chars are the iso name of a language.
312  *      Country: a string whose two first chars are the iso name of country
313  *      Charset: a string defining the chosen charset encoding
314  *      Dialect: a string defining a variation of the locale
315  *
316  *      all those values are from the standardized format of locale
317  *      name in unix which is: Lang[_Country][.Charset][@Dialect]
318  *
319  * RETURNS:
320  *      the numeric code of the language used by Windows
321  *
322  * FIXME: Charset and Dialect are not handled
323  */
324 static LANGID get_language_id(LPCSTR Lang, LPCSTR Country, LPCSTR Charset, LPCSTR Dialect)
325 {
326     LANG_FIND_DATA l_data;
327     char lang_string[256];
328     HMODULE hKernel32;
329
330     if(!Lang)
331     {
332         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
333         goto END;
334     }
335
336     memset(&l_data, 0, sizeof(LANG_FIND_DATA));
337     strncpy(l_data.lang, Lang, sizeof(l_data.lang));
338
339     if(Country && Country[0])
340         strncpy(l_data.country, Country, sizeof(l_data.country));
341
342     hKernel32 = GetModuleHandleW(kernel32W);
343
344     EnumResourceLanguagesA(hKernel32, (LPSTR)RT_STRING,
345                            (LPCSTR)LOCALE_ILANGUAGE, find_language_id_proc, (LPARAM)&l_data);
346
347     strcpy(lang_string, l_data.lang);
348     if(l_data.country[0])
349     {
350         strcat(lang_string, "_");
351         strcat(lang_string, l_data.country);
352     }
353
354     if(!l_data.n_found)
355     {
356         if(l_data.country[0])
357         {
358             MESSAGE("Warning: Language '%s' was not found, retrying without country name...\n", lang_string);
359             l_data.country[0] = 0;
360             EnumResourceLanguagesA(hKernel32, (LPSTR)RT_STRING,
361                                    (LPCSTR)LOCALE_ILANGUAGE, find_language_id_proc, (LONG)&l_data);
362         }
363     }
364
365     /* Re-evaluate lang_string */
366     strcpy(lang_string, l_data.lang);
367     if(l_data.country[0])
368     {
369         strcat(lang_string, "_");
370         strcat(lang_string, l_data.country);
371     }
372
373     if(!l_data.n_found)
374     {
375         MESSAGE("Warning: Language '%s' was not recognized, defaulting to English\n", lang_string);
376         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
377     }
378     else
379     {
380         if(l_data.n_found == 1)
381             TRACE("For language '%s' lang_id %04X was found\n", lang_string, l_data.found_lang_id[0]);
382         else /* l_data->n_found > 1 */
383         {
384             int i;
385             MESSAGE("For language '%s' several language ids were found:\n", lang_string);
386             for(i = 0; i < l_data.n_found; i++)
387                 MESSAGE("%s_%s - %04X; ", l_data.found_language[i], l_data.found_country[i], l_data.found_lang_id[i]);
388
389             MESSAGE("\nInstead of using first in the list, suggest to define\n"
390                     "your LANG environment variable like this: LANG=%s_%s\n",
391                     l_data.found_language[0], l_data.found_country[0]);
392         }
393     }
394 END:
395     TRACE("Returning %04X\n", l_data.found_lang_id[0]);
396     return l_data.found_lang_id[0];
397 }
398
399
400 /***********************************************************************
401  *              charset_cmp (internal)
402  */
403 static int charset_cmp( const void *name, const void *entry )
404 {
405     const struct charset_entry *charset = (struct charset_entry *)entry;
406     return strcasecmp( (char *)name, charset->charset_name );
407 }
408
409 /***********************************************************************
410  *              init_default_lcid
411  */
412 static LCID init_default_lcid( UINT *unix_cp )
413 {
414     char buf[256];
415     char *lang,*country,*charset,*dialect,*next;
416     LCID ret = 0;
417
418     if (GetEnvironmentVariableA( "LC_ALL", buf, sizeof(buf) ) ||
419         GetEnvironmentVariableA( "LC_CTYPE", buf, sizeof(buf) ) ||
420         GetEnvironmentVariableA( "LANGUAGE", buf, sizeof(buf) ) ||
421         GetEnvironmentVariableA( "LC_MESSAGES", buf, sizeof(buf) ) ||
422         GetEnvironmentVariableA( "LANG", buf, sizeof(buf) ))
423     {
424         if (!strcmp(buf,"POSIX") || !strcmp(buf,"C")) goto done;
425
426         lang=buf;
427
428         do {
429             next=strchr(lang,':'); if (next) *next++='\0';
430             dialect=strchr(lang,'@'); if (dialect) *dialect++='\0';
431             charset=strchr(lang,'.'); if (charset) *charset++='\0';
432             country=strchr(lang,'_'); if (country) *country++='\0';
433
434             ret = get_language_id(lang, country, charset, dialect);
435             if (ret && charset)
436             {
437                 const struct charset_entry *entry;
438                 char charset_name[16];
439                 size_t i, j;
440
441                 /* remove punctuation characters from charset name */
442                 for (i = j = 0; charset[i] && j < sizeof(charset_name)-1; i++)
443                     if (isalnum(charset[i])) charset_name[j++] = charset[i];
444                 charset_name[j] = 0;
445
446                 entry = bsearch( charset_name, charset_names,
447                                  sizeof(charset_names)/sizeof(charset_names[0]),
448                                  sizeof(charset_names[0]), charset_cmp );
449                 if (entry)
450                 {
451                     *unix_cp = entry->codepage;
452                     TRACE("charset %s was mapped to cp %u\n", charset, *unix_cp);
453                 }
454                 else
455                     FIXME("charset %s was not recognized\n", charset);
456             }
457
458             lang=next;
459         } while (lang && !ret);
460
461         if (!ret) MESSAGE("Warning: language '%s' not recognized, defaulting to English\n", buf);
462     }
463
464  done:
465     if (!ret) ret = MAKELCID( MAKELANGID(LANG_ENGLISH,SUBLANG_DEFAULT), SORT_DEFAULT) ;
466     return ret;
467 }
468
469
470 /******************************************************************************
471  *              get_locale_value_name
472  *
473  * Gets the registry value name for a given lctype.
474  */
475 static const WCHAR *get_locale_value_name( DWORD lctype )
476 {
477     static const WCHAR iCalendarTypeW[] = {'i','C','a','l','e','n','d','a','r','T','y','p','e',0};
478     static const WCHAR iCountryW[] = {'i','C','o','u','n','t','r','y',0};
479     static const WCHAR iCurrDigitsW[] = {'i','C','u','r','r','D','i','g','i','t','s',0};
480     static const WCHAR iCurrencyW[] = {'i','C','u','r','r','e','n','c','y',0};
481     static const WCHAR iDateW[] = {'i','D','a','t','e',0};
482     static const WCHAR iDigitsW[] = {'i','D','i','g','i','t','s',0};
483     static const WCHAR iFirstDayOfWeekW[] = {'i','F','i','r','s','t','D','a','y','O','f','W','e','e','k',0};
484     static const WCHAR iFirstWeekOfYearW[] = {'i','F','i','r','s','t','W','e','e','k','O','f','Y','e','a','r',0};
485     static const WCHAR iLDateW[] = {'i','L','D','a','t','e',0};
486     static const WCHAR iLZeroW[] = {'i','L','Z','e','r','o',0};
487     static const WCHAR iMeasureW[] = {'i','M','e','a','s','u','r','e',0};
488     static const WCHAR iNegCurrW[] = {'i','N','e','g','C','u','r','r',0};
489     static const WCHAR iNegNumberW[] = {'i','N','e','g','N','u','m','b','e','r',0};
490     static const WCHAR iPaperSizeW[] = {'i','P','a','p','e','r','S','i','z','e',0};
491     static const WCHAR iTLZeroW[] = {'i','T','L','Z','e','r','o',0};
492     static const WCHAR iTimePrefixW[] = {'i','T','i','m','e','P','r','e','f','i','x',0};
493     static const WCHAR iTimeW[] = {'i','T','i','m','e',0};
494     static const WCHAR s1159W[] = {'s','1','1','5','9',0};
495     static const WCHAR s2359W[] = {'s','2','3','5','9',0};
496     static const WCHAR sCountryW[] = {'s','C','o','u','n','t','r','y',0};
497     static const WCHAR sCurrencyW[] = {'s','C','u','r','r','e','n','c','y',0};
498     static const WCHAR sDateW[] = {'s','D','a','t','e',0};
499     static const WCHAR sDecimalW[] = {'s','D','e','c','i','m','a','l',0};
500     static const WCHAR sGroupingW[] = {'s','G','r','o','u','p','i','n','g',0};
501     static const WCHAR sLanguageW[] = {'s','L','a','n','g','u','a','g','e',0};
502     static const WCHAR sListW[] = {'s','L','i','s','t',0};
503     static const WCHAR sLongDateW[] = {'s','L','o','n','g','D','a','t','e',0};
504     static const WCHAR sMonDecimalSepW[] = {'s','M','o','n','D','e','c','i','m','a','l','S','e','p',0};
505     static const WCHAR sMonGroupingW[] = {'s','M','o','n','G','r','o','u','p','i','n','g',0};
506     static const WCHAR sMonThousandSepW[] = {'s','M','o','n','T','h','o','u','s','a','n','d','S','e','p',0};
507     static const WCHAR sNativeDigitsW[] = {'s','N','a','t','i','v','e','D','i','g','i','t','s',0};
508     static const WCHAR sNegativeSignW[] = {'s','N','e','g','a','t','i','v','e','S','i','g','n',0};
509     static const WCHAR sPositiveSignW[] = {'s','P','o','s','i','t','i','v','e','S','i','g','n',0};
510     static const WCHAR sShortDateW[] = {'s','S','h','o','r','t','D','a','t','e',0};
511     static const WCHAR sThousandW[] = {'s','T','h','o','u','s','a','n','d',0};
512     static const WCHAR sTimeFormatW[] = {'s','T','i','m','e','F','o','r','m','a','t',0};
513     static const WCHAR sTimeW[] = {'s','T','i','m','e',0};
514     static const WCHAR sYearMonthW[] = {'s','Y','e','a','r','M','o','n','t','h',0};
515     static const WCHAR NumShapeW[] = {'N','u','m','s','h','a','p','e',0};
516
517     switch (lctype & ~LOCALE_LOCALEINFOFLAGSMASK)
518     {
519     /* These values are used by SetLocaleInfo and GetLocaleInfo, and
520      * the values are stored in the registry, confirmed under Windows.
521      */
522     case LOCALE_ICALENDARTYPE:    return iCalendarTypeW;
523     case LOCALE_ICURRDIGITS:      return iCurrDigitsW;
524     case LOCALE_ICURRENCY:        return iCurrencyW;
525     case LOCALE_IDIGITS:          return iDigitsW;
526     case LOCALE_IFIRSTDAYOFWEEK:  return iFirstDayOfWeekW;
527     case LOCALE_IFIRSTWEEKOFYEAR: return iFirstWeekOfYearW;
528     case LOCALE_ILZERO:           return iLZeroW;
529     case LOCALE_IMEASURE:         return iMeasureW;
530     case LOCALE_INEGCURR:         return iNegCurrW;
531     case LOCALE_INEGNUMBER:       return iNegNumberW;
532     case LOCALE_IPAPERSIZE:       return iPaperSizeW;
533     case LOCALE_ITIME:            return iTimeW;
534     case LOCALE_S1159:            return s1159W;
535     case LOCALE_S2359:            return s2359W;
536     case LOCALE_SCURRENCY:        return sCurrencyW;
537     case LOCALE_SDATE:            return sDateW;
538     case LOCALE_SDECIMAL:         return sDecimalW;
539     case LOCALE_SGROUPING:        return sGroupingW;
540     case LOCALE_SLIST:            return sListW;
541     case LOCALE_SLONGDATE:        return sLongDateW;
542     case LOCALE_SMONDECIMALSEP:   return sMonDecimalSepW;
543     case LOCALE_SMONGROUPING:     return sMonGroupingW;
544     case LOCALE_SMONTHOUSANDSEP:  return sMonThousandSepW;
545     case LOCALE_SNEGATIVESIGN:    return sNegativeSignW;
546     case LOCALE_SPOSITIVESIGN:    return sPositiveSignW;
547     case LOCALE_SSHORTDATE:       return sShortDateW;
548     case LOCALE_STHOUSAND:        return sThousandW;
549     case LOCALE_STIME:            return sTimeW;
550     case LOCALE_STIMEFORMAT:      return sTimeFormatW;
551     case LOCALE_SYEARMONTH:       return sYearMonthW;
552
553     /* The following are not listed under MSDN as supported,
554      * but seem to be used and also stored in the registry.
555      */
556     case LOCALE_ICOUNTRY:         return iCountryW;
557     case LOCALE_IDATE:            return iDateW;
558     case LOCALE_ILDATE:           return iLDateW;
559     case LOCALE_ITLZERO:          return iTLZeroW;
560     case LOCALE_SCOUNTRY:         return sCountryW;
561     case LOCALE_SLANGUAGE:        return sLanguageW;
562
563     /* The following are used in XP and later */
564     case LOCALE_IDIGITSUBSTITUTION: return NumShapeW;
565     case LOCALE_SNATIVEDIGITS:      return sNativeDigitsW;
566     case LOCALE_ITIMEMARKPOSN:      return iTimePrefixW;
567     }
568     return NULL;
569 }
570
571
572 /******************************************************************************
573  *              get_registry_locale_info
574  *
575  * Retrieve user-modified locale info from the registry.
576  * Return length, 0 on error, -1 if not found.
577  */
578 static INT get_registry_locale_info( LPCWSTR value, LPWSTR buffer, INT len )
579 {
580     DWORD size;
581     INT ret;
582     HKEY hkey;
583     NTSTATUS status;
584     UNICODE_STRING nameW;
585     KEY_VALUE_PARTIAL_INFORMATION *info;
586     static const int info_size = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data);
587
588     if (!(hkey = create_registry_key())) return -1;
589
590     RtlInitUnicodeString( &nameW, value );
591     size = info_size + len * sizeof(WCHAR);
592
593     if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
594     {
595         NtClose( hkey );
596         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
597         return 0;
598     }
599
600     status = NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, info, size, &size );
601     if (status == STATUS_BUFFER_OVERFLOW && !buffer) status = 0;
602
603     if (!status)
604     {
605         ret = (size - info_size) / sizeof(WCHAR);
606         /* append terminating null if needed */
607         if (!ret || ((WCHAR *)info->Data)[ret-1])
608         {
609             if (ret < len || !buffer) ret++;
610             else
611             {
612                 SetLastError( ERROR_INSUFFICIENT_BUFFER );
613                 ret = 0;
614             }
615         }
616         if (ret && buffer)
617         {
618             memcpy( buffer, info->Data, (ret-1) * sizeof(WCHAR) );
619             buffer[ret-1] = 0;
620         }
621     }
622     else
623     {
624         if (status == STATUS_OBJECT_NAME_NOT_FOUND) ret = -1;
625         else
626         {
627             SetLastError( RtlNtStatusToDosError(status) );
628             ret = 0;
629         }
630     }
631     NtClose( hkey );
632     HeapFree( GetProcessHeap(), 0, info );
633     return ret;
634 }
635
636
637 /******************************************************************************
638  *              GetLocaleInfoA (KERNEL32.@)
639  *
640  * Get information about an aspect of a locale.
641  *
642  * PARAMS
643  *  lcid   [I] LCID of the locale
644  *  lctype [I] LCTYPE_ flags from "winnls.h"
645  *  buffer [O] Destination for the information
646  *  len    [I] Length of buffer in characters
647  *
648  * RETURNS
649  *  Success: The size of the data requested. If buffer is non-NULL, it is filled
650  *           with the information.
651  *  Failure: 0. Use GetLastError() to determine the cause.
652  *
653  * NOTES
654  *  - LOCALE_NEUTRAL is equal to LOCALE_SYSTEM_DEFAULT
655  *  - The string returned is NUL terminated, except for LOCALE_FONTSIGNATURE,
656  *    which is a bit string.
657  */
658 INT WINAPI GetLocaleInfoA( LCID lcid, LCTYPE lctype, LPSTR buffer, INT len )
659 {
660     WCHAR *bufferW;
661     INT lenW, ret;
662
663     if (len < 0 || (len && !buffer))
664     {
665         SetLastError( ERROR_INVALID_PARAMETER );
666         return 0;
667     }
668     if (!len) buffer = NULL;
669
670     if (!(lenW = GetLocaleInfoW( lcid, lctype, NULL, 0 ))) return 0;
671
672     if (!(bufferW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
673     {
674         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
675         return 0;
676     }
677     if ((ret = GetLocaleInfoW( lcid, lctype, bufferW, lenW )))
678     {
679         if ((lctype & LOCALE_RETURN_NUMBER) ||
680             ((lctype & ~LOCALE_LOCALEINFOFLAGSMASK) == LOCALE_FONTSIGNATURE))
681         {
682             /* it's not an ASCII string, just bytes */
683             ret *= sizeof(WCHAR);
684             if (buffer)
685             {
686                 if (ret <= len) memcpy( buffer, bufferW, ret );
687                 else
688                 {
689                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
690                     ret = 0;
691                 }
692             }
693         }
694         else
695         {
696             UINT codepage = CP_ACP;
697             if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
698             ret = WideCharToMultiByte( codepage, 0, bufferW, ret, buffer, len, NULL, NULL );
699         }
700     }
701     HeapFree( GetProcessHeap(), 0, bufferW );
702     return ret;
703 }
704
705
706 /******************************************************************************
707  *              GetLocaleInfoW (KERNEL32.@)
708  *
709  * See GetLocaleInfoA.
710  */
711 INT WINAPI GetLocaleInfoW( LCID lcid, LCTYPE lctype, LPWSTR buffer, INT len )
712 {
713     LANGID lang_id;
714     HRSRC hrsrc;
715     HGLOBAL hmem;
716     HMODULE hModule;
717     INT ret;
718     UINT lcflags;
719     const WCHAR *p;
720     unsigned int i;
721
722     if (len < 0 || (len && !buffer))
723     {
724         SetLastError( ERROR_INVALID_PARAMETER );
725         return 0;
726     }
727     if (!len) buffer = NULL;
728
729     lcid = ConvertDefaultLocale(lcid);
730
731     lcflags = lctype & LOCALE_LOCALEINFOFLAGSMASK;
732     lctype &= ~LOCALE_LOCALEINFOFLAGSMASK;
733
734     /* first check for overrides in the registry */
735
736     if (!(lcflags & LOCALE_NOUSEROVERRIDE) && lcid == GetUserDefaultLCID())
737     {
738         const WCHAR *value = get_locale_value_name(lctype);
739
740         if (value && ((ret = get_registry_locale_info( value, buffer, len )) != -1)) return ret;
741     }
742
743     /* now load it from kernel resources */
744
745     lang_id = LANGIDFROMLCID( lcid );
746
747     /* replace SUBLANG_NEUTRAL by SUBLANG_DEFAULT */
748     if (SUBLANGID(lang_id) == SUBLANG_NEUTRAL)
749         lang_id = MAKELANGID(PRIMARYLANGID(lang_id), SUBLANG_DEFAULT);
750
751     hModule = GetModuleHandleW( kernel32W );
752     if (!(hrsrc = FindResourceExW( hModule, (LPWSTR)RT_STRING, (LPCWSTR)((lctype >> 4) + 1), lang_id )))
753     {
754         SetLastError( ERROR_INVALID_FLAGS );  /* no such lctype */
755         return 0;
756     }
757     if (!(hmem = LoadResource( hModule, hrsrc )))
758         return 0;
759
760     p = LockResource( hmem );
761     for (i = 0; i < (lctype & 0x0f); i++) p += *p + 1;
762
763     if (lcflags & LOCALE_RETURN_NUMBER) ret = sizeof(UINT)/sizeof(WCHAR);
764     else ret = (lctype == LOCALE_FONTSIGNATURE) ? *p : *p + 1;
765
766     if (!buffer) return ret;
767
768     if (ret > len)
769     {
770         SetLastError( ERROR_INSUFFICIENT_BUFFER );
771         return 0;
772     }
773
774     if (lcflags & LOCALE_RETURN_NUMBER)
775     {
776         UINT number;
777         WCHAR *end, *tmp = HeapAlloc( GetProcessHeap(), 0, (*p + 1) * sizeof(WCHAR) );
778         if (!tmp) return 0;
779         memcpy( tmp, p + 1, *p * sizeof(WCHAR) );
780         tmp[*p] = 0;
781         number = strtolW( tmp, &end, 10 );
782         if (!*end)
783             memcpy( buffer, &number, sizeof(number) );
784         else  /* invalid number */
785         {
786             SetLastError( ERROR_INVALID_FLAGS );
787             ret = 0;
788         }
789         HeapFree( GetProcessHeap(), 0, tmp );
790
791         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning number %d\n",
792                lcid, lctype, buffer, len, number );
793     }
794     else
795     {
796         memcpy( buffer, p + 1, *p * sizeof(WCHAR) );
797         if (lctype != LOCALE_FONTSIGNATURE) buffer[ret-1] = 0;
798
799         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning %d %s\n",
800                lcid, lctype, buffer, len, ret, debugstr_w(buffer) );
801     }
802     return ret;
803 }
804
805
806 /******************************************************************************
807  *              SetLocaleInfoA  [KERNEL32.@]
808  *
809  * Set information about an aspect of a locale.
810  *
811  * PARAMS
812  *  lcid   [I] LCID of the locale
813  *  lctype [I] LCTYPE_ flags from "winnls.h"
814  *  data   [I] Information to set
815  *
816  * RETURNS
817  *  Success: TRUE. The information given will be returned by GetLocaleInfoA()
818  *           whenever it is called without LOCALE_NOUSEROVERRIDE.
819  *  Failure: FALSE. Use GetLastError() to determine the cause.
820  *
821  * NOTES
822  *  - Values are only be set for the current user locale; the system locale
823  *  settings cannot be changed.
824  *  - Any settings changed by this call are lost when the locale is changed by
825  *  the control panel (in Wine, this happens every time you change LANG).
826  *  - The native implementation of this function does not check that lcid matches
827  *  the current user locale, and simply sets the new values. Wine warns you in
828  *  this case, but behaves the same.
829  */
830 BOOL WINAPI SetLocaleInfoA(LCID lcid, LCTYPE lctype, LPCSTR data)
831 {
832     UINT codepage = CP_ACP;
833     WCHAR *strW;
834     DWORD len;
835     BOOL ret;
836
837     lcid = ConvertDefaultLocale(lcid);
838
839     if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
840     len = MultiByteToWideChar( codepage, 0, data, -1, NULL, 0 );
841     if (!(strW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
842     {
843         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
844         return FALSE;
845     }
846     MultiByteToWideChar( codepage, 0, data, -1, strW, len );
847     ret = SetLocaleInfoW( lcid, lctype, strW );
848     HeapFree( GetProcessHeap(), 0, strW );
849     return ret;
850 }
851
852
853 /******************************************************************************
854  *              SetLocaleInfoW  (KERNEL32.@)
855  *
856  * See SetLocaleInfoA.
857  */
858 BOOL WINAPI SetLocaleInfoW( LCID lcid, LCTYPE lctype, LPCWSTR data )
859 {
860     const WCHAR *value;
861     const WCHAR intlW[] = {'i','n','t','l',0 };
862     UNICODE_STRING valueW;
863     NTSTATUS status;
864     HKEY hkey;
865
866     lcid = ConvertDefaultLocale(lcid);
867
868     lctype &= ~LOCALE_LOCALEINFOFLAGSMASK;
869     value = get_locale_value_name( lctype );
870
871     if (!data || !value)
872     {
873         SetLastError( ERROR_INVALID_PARAMETER );
874         return FALSE;
875     }
876
877     if (lctype == LOCALE_IDATE || lctype == LOCALE_ILDATE)
878     {
879         SetLastError( ERROR_INVALID_FLAGS );
880         return FALSE;
881     }
882
883     if (lcid != GetUserDefaultLCID())
884     {
885         /* Windows does not check that the lcid matches the current lcid */
886         WARN("locale 0x%08lx isn't the current locale (0x%08lx), setting anyway!\n",
887              lcid, GetUserDefaultLCID());
888     }
889
890     TRACE("setting %lx to %s\n", lctype, debugstr_w(data) );
891
892     /* FIXME: should check that data to set is sane */
893
894     /* FIXME: profile functions should map to registry */
895     WriteProfileStringW( intlW, value, data );
896
897     if (!(hkey = create_registry_key())) return FALSE;
898     RtlInitUnicodeString( &valueW, value );
899     status = NtSetValueKey( hkey, &valueW, 0, REG_SZ, data, (strlenW(data)+1)*sizeof(WCHAR) );
900
901     if (lctype == LOCALE_SDATE || lctype == LOCALE_SLONGDATE)
902     {
903       /* Set I-value from S value */
904       WCHAR *lpD, *lpM, *lpY;
905       WCHAR szBuff[2];
906
907       lpD = strchrW(data, 'd');
908       lpM = strchrW(data, 'M');
909       lpY = strchrW(data, 'y');
910
911       if (lpD <= lpM)
912       {
913         szBuff[0] = '1'; /* D-M-Y */
914       }
915       else
916       {
917         if (lpY <= lpM)
918           szBuff[0] = '2'; /* Y-M-D */
919         else
920           szBuff[0] = '0'; /* M-D-Y */
921       }
922
923       szBuff[1] = '\0';
924
925       if (lctype == LOCALE_SDATE)
926         lctype = LOCALE_IDATE;
927       else
928         lctype = LOCALE_ILDATE;
929
930       value = get_locale_value_name( lctype );
931
932       WriteProfileStringW( intlW, value, szBuff );
933
934       RtlInitUnicodeString( &valueW, value );
935       status = NtSetValueKey( hkey, &valueW, 0, REG_SZ, szBuff, sizeof(szBuff) );
936     }
937
938     NtClose( hkey );
939
940     if (status) SetLastError( RtlNtStatusToDosError(status) );
941     return !status;
942 }
943
944
945 /***********************************************************************
946  *           GetThreadLocale    (KERNEL32.@)
947  *
948  * Get the current threads locale.
949  *
950  * PARAMS
951  *  None.
952  *
953  * RETURNS
954  *  The LCID currently assocated with the calling thread.
955  */
956 LCID WINAPI GetThreadLocale(void)
957 {
958     LCID ret = NtCurrentTeb()->CurrentLocale;
959     if (!ret) NtCurrentTeb()->CurrentLocale = ret = GetUserDefaultLCID();
960     return ret;
961 }
962
963 /**********************************************************************
964  *           SetThreadLocale    (KERNEL32.@)
965  *
966  * Set the current threads locale.
967  *
968  * PARAMS
969  *  lcid [I] LCID of the locale to set
970  *
971  * RETURNS
972  *  Success: TRUE. The threads locale is set to lcid.
973  *  Failure: FALSE. Use GetLastError() to determine the cause.
974  */
975 BOOL WINAPI SetThreadLocale( LCID lcid )
976 {
977     TRACE("(0x%04lX)\n", lcid);
978
979     lcid = ConvertDefaultLocale(lcid);
980
981     if (lcid != GetThreadLocale())
982     {
983         if (!IsValidLocale(lcid, LCID_SUPPORTED))
984         {
985             SetLastError(ERROR_INVALID_PARAMETER);
986             return FALSE;
987         }
988
989         NtCurrentTeb()->CurrentLocale = lcid;
990         NtCurrentTeb()->code_page = get_lcid_codepage( lcid );
991     }
992     return TRUE;
993 }
994
995 /******************************************************************************
996  *              ConvertDefaultLocale (KERNEL32.@)
997  *
998  * Convert a default locale identifier into a real identifier.
999  *
1000  * PARAMS
1001  *  lcid [I] LCID identifier of the locale to convert
1002  *
1003  * RETURNS
1004  *  lcid unchanged, if not a default locale or is its sublanguage is
1005  *   not SUBLANG_NEUTRAL.
1006  *  GetSystemDefaultLCID(), if lcid == LOCALE_SYSTEM_DEFAULT.
1007  *  GetUserDefaultLCID(), if lcid == LOCALE_USER_DEFAULT or LOCALE_NEUTRAL.
1008  *  Otherwise, lcid with sublanguage cheanged to SUBLANG_DEFAULT.
1009  */
1010 LCID WINAPI ConvertDefaultLocale( LCID lcid )
1011 {
1012     LANGID langid;
1013
1014     switch (lcid)
1015     {
1016     case LOCALE_SYSTEM_DEFAULT:
1017         lcid = GetSystemDefaultLCID();
1018         break;
1019     case LOCALE_USER_DEFAULT:
1020     case LOCALE_NEUTRAL:
1021         lcid = GetUserDefaultLCID();
1022         break;
1023     default:
1024         /* Replace SUBLANG_NEUTRAL with SUBLANG_DEFAULT */
1025         langid = LANGIDFROMLCID(lcid);
1026         if (SUBLANGID(langid) == SUBLANG_NEUTRAL)
1027         {
1028           langid = MAKELANGID(PRIMARYLANGID(langid), SUBLANG_DEFAULT);
1029           lcid = MAKELCID(langid, SORTIDFROMLCID(lcid));
1030         }
1031     }
1032     return lcid;
1033 }
1034
1035
1036 /******************************************************************************
1037  *           IsValidLocale   (KERNEL32.@)
1038  *
1039  * Determine if a locale is valid.
1040  *
1041  * PARAMS
1042  *  lcid  [I] LCID of the locale to check
1043  *  flags [I] LCID_SUPPORTED = Valid, LCID_INSTALLED = Valid and installed on the system
1044  *
1045  * RETURN
1046  *  TRUE,  if lcid is valid,
1047  *  FALSE, otherwise.
1048  *
1049  * NOTES
1050  *  Wine does not currently make the distinction between supported and installed. All
1051  *  languages supported are installed by default.
1052  */
1053 BOOL WINAPI IsValidLocale( LCID lcid, DWORD flags )
1054 {
1055     /* check if language is registered in the kernel32 resources */
1056     return FindResourceExW( GetModuleHandleW(kernel32W), (LPWSTR)RT_STRING,
1057                             (LPCWSTR)LOCALE_ILANGUAGE, LANGIDFROMLCID(lcid)) != 0;
1058 }
1059
1060
1061 static BOOL CALLBACK enum_lang_proc_a( HMODULE hModule, LPCSTR type,
1062                                        LPCSTR name, WORD LangID, LONG lParam )
1063 {
1064     LOCALE_ENUMPROCA lpfnLocaleEnum = (LOCALE_ENUMPROCA)lParam;
1065     char buf[20];
1066
1067     sprintf(buf, "%08x", (UINT)LangID);
1068     return lpfnLocaleEnum( buf );
1069 }
1070
1071 static BOOL CALLBACK enum_lang_proc_w( HMODULE hModule, LPCWSTR type,
1072                                        LPCWSTR name, WORD LangID, LONG lParam )
1073 {
1074     static const WCHAR formatW[] = {'%','0','8','x',0};
1075     LOCALE_ENUMPROCW lpfnLocaleEnum = (LOCALE_ENUMPROCW)lParam;
1076     WCHAR buf[20];
1077     sprintfW( buf, formatW, (UINT)LangID );
1078     return lpfnLocaleEnum( buf );
1079 }
1080
1081 /******************************************************************************
1082  *           EnumSystemLocalesA  (KERNEL32.@)
1083  *
1084  * Call a users function for each locale available on the system.
1085  *
1086  * PARAMS
1087  *  lpfnLocaleEnum [I] Callback function to call for each locale
1088  *  dwFlags        [I] LOCALE_SUPPORTED=All supported, LOCALE_INSTALLED=Installed only
1089  *
1090  * RETURNS
1091  *  Success: TRUE.
1092  *  Failure: FALSE. Use GetLastError() to determine the cause.
1093  */
1094 BOOL WINAPI EnumSystemLocalesA( LOCALE_ENUMPROCA lpfnLocaleEnum, DWORD dwFlags )
1095 {
1096     TRACE("(%p,%08lx)\n", lpfnLocaleEnum, dwFlags);
1097     EnumResourceLanguagesA( GetModuleHandleW(kernel32W), (LPSTR)RT_STRING,
1098                             (LPCSTR)LOCALE_ILANGUAGE, enum_lang_proc_a,
1099                             (LONG)lpfnLocaleEnum);
1100     return TRUE;
1101 }
1102
1103
1104 /******************************************************************************
1105  *           EnumSystemLocalesW  (KERNEL32.@)
1106  *
1107  * See EnumSystemLocalesA.
1108  */
1109 BOOL WINAPI EnumSystemLocalesW( LOCALE_ENUMPROCW lpfnLocaleEnum, DWORD dwFlags )
1110 {
1111     TRACE("(%p,%08lx)\n", lpfnLocaleEnum, dwFlags);
1112     EnumResourceLanguagesW( GetModuleHandleW(kernel32W), (LPWSTR)RT_STRING,
1113                             (LPCWSTR)LOCALE_ILANGUAGE, enum_lang_proc_w,
1114                             (LONG)lpfnLocaleEnum);
1115     return TRUE;
1116 }
1117
1118
1119 /***********************************************************************
1120  *           VerLanguageNameA  (KERNEL32.@)
1121  *
1122  * Get the name of a language.
1123  *
1124  * PARAMS
1125  *  wLang  [I] LANGID of the language
1126  *  szLang [O] Destination for the language name
1127  *
1128  * RETURNS
1129  *  Success: The size of the language name. If szLang is non-NULL, it is filled
1130  *           with the name.
1131  *  Failure: 0. Use GetLastError() to determine the cause.
1132  *
1133  */
1134 DWORD WINAPI VerLanguageNameA( UINT wLang, LPSTR szLang, UINT nSize )
1135 {
1136     return GetLocaleInfoA( MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize );
1137 }
1138
1139
1140 /***********************************************************************
1141  *           VerLanguageNameW  (KERNEL32.@)
1142  *
1143  * See VerLanguageNameA.
1144  */
1145 DWORD WINAPI VerLanguageNameW( UINT wLang, LPWSTR szLang, UINT nSize )
1146 {
1147     return GetLocaleInfoW( MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize );
1148 }
1149
1150
1151 /******************************************************************************
1152  *           GetStringTypeW    (KERNEL32.@)
1153  */
1154 BOOL WINAPI GetStringTypeW( DWORD type, LPCWSTR src, INT count, LPWORD chartype )
1155 {
1156     if (count == -1) count = strlenW(src) + 1;
1157     switch(type)
1158     {
1159     case CT_CTYPE1:
1160         while (count--) *chartype++ = get_char_typeW( *src++ ) & 0xfff;
1161         break;
1162     case CT_CTYPE2:
1163         while (count--) *chartype++ = get_char_typeW( *src++ ) >> 12;
1164         break;
1165     case CT_CTYPE3:
1166     {
1167         WARN("CT_CTYPE3: semi-stub.\n");
1168         while (count--)
1169         {
1170             int c = *src;
1171             WORD type1, type3 = 0; /* C3_NOTAPPLICABLE */
1172
1173             type1 = get_char_typeW( *src++ ) & 0xfff;
1174             /* try to construct type3 from type1 */
1175             if(type1 & C1_SPACE) type3 |= C3_SYMBOL;
1176             if(type1 & C1_ALPHA) type3 |= C3_ALPHA;
1177             if ((c>=0x30A0)&&(c<=0x30FF)) type3 |= C3_KATAKANA;
1178             if ((c>=0x3040)&&(c<=0x309F)) type3 |= C3_HIRAGANA;
1179             if ((c>=0x4E00)&&(c<=0x9FAF)) type3 |= C3_IDEOGRAPH;
1180             if ((c>=0x0600)&&(c<=0x06FF)) type3 |= C3_KASHIDA;
1181             if ((c>=0x3000)&&(c<=0x303F)) type3 |= C3_SYMBOL;
1182
1183             if ((c>=0xFF00)&&(c<=0xFF60)) type3 |= C3_FULLWIDTH;
1184             if ((c>=0xFF00)&&(c<=0xFF20)) type3 |= C3_SYMBOL;
1185             if ((c>=0xFF3B)&&(c<=0xFF40)) type3 |= C3_SYMBOL;
1186             if ((c>=0xFF5B)&&(c<=0xFF60)) type3 |= C3_SYMBOL;
1187             if ((c>=0xFF21)&&(c<=0xFF3A)) type3 |= C3_ALPHA;
1188             if ((c>=0xFF41)&&(c<=0xFF5A)) type3 |= C3_ALPHA;
1189             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_FULLWIDTH;
1190             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_SYMBOL;
1191
1192             if ((c>=0xFF61)&&(c<=0xFFDC)) type3 |= C3_HALFWIDTH;
1193             if ((c>=0xFF61)&&(c<=0xFF64)) type3 |= C3_SYMBOL;
1194             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_KATAKANA;
1195             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_ALPHA;
1196             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_HALFWIDTH;
1197             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_SYMBOL;
1198             *chartype++ = type3;
1199         }
1200         break;
1201     }
1202     default:
1203         SetLastError( ERROR_INVALID_PARAMETER );
1204         return FALSE;
1205     }
1206     return TRUE;
1207 }
1208
1209
1210 /******************************************************************************
1211  *           GetStringTypeExW    (KERNEL32.@)
1212  */
1213 BOOL WINAPI GetStringTypeExW( LCID locale, DWORD type, LPCWSTR src, INT count, LPWORD chartype )
1214 {
1215     /* locale is ignored for Unicode */
1216     return GetStringTypeW( type, src, count, chartype );
1217 }
1218
1219
1220 /******************************************************************************
1221  *           GetStringTypeA    (KERNEL32.@)
1222  */
1223 BOOL WINAPI GetStringTypeA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
1224 {
1225     UINT cp;
1226     INT countW;
1227     LPWSTR srcW;
1228     BOOL ret = FALSE;
1229
1230     if(count == -1) count = strlen(src) + 1;
1231
1232     if (!(cp = get_lcid_codepage( locale )))
1233     {
1234         FIXME("For locale %04lx using current ANSI code page\n", locale);
1235         cp = GetACP();
1236     }
1237
1238     countW = MultiByteToWideChar(cp, 0, src, count, NULL, 0);
1239     if((srcW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
1240     {
1241         MultiByteToWideChar(cp, 0, src, count, srcW, countW);
1242     /*
1243      * NOTE: the target buffer has 1 word for each CHARACTER in the source
1244      * string, with multibyte characters there maybe be more bytes in count
1245      * than character space in the buffer!
1246      */
1247         ret = GetStringTypeW(type, srcW, countW, chartype);
1248         HeapFree(GetProcessHeap(), 0, srcW);
1249     }
1250     return ret;
1251 }
1252
1253 /******************************************************************************
1254  *           GetStringTypeExA    (KERNEL32.@)
1255  */
1256 BOOL WINAPI GetStringTypeExA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
1257 {
1258     return GetStringTypeA(locale, type, src, count, chartype);
1259 }
1260
1261
1262 /*************************************************************************
1263  *           LCMapStringW    (KERNEL32.@)
1264  */
1265 INT WINAPI LCMapStringW(LCID lcid, DWORD flags, LPCWSTR src, INT srclen,
1266                         LPWSTR dst, INT dstlen)
1267 {
1268     LPWSTR dst_ptr;
1269
1270     if (!src || !srclen || dstlen < 0)
1271     {
1272         SetLastError(ERROR_INVALID_PARAMETER);
1273         return 0;
1274     }
1275
1276     /* mutually exclusive flags */
1277     if ((flags & (LCMAP_LOWERCASE | LCMAP_UPPERCASE)) == (LCMAP_LOWERCASE | LCMAP_UPPERCASE) ||
1278         (flags & (LCMAP_HIRAGANA | LCMAP_KATAKANA)) == (LCMAP_HIRAGANA | LCMAP_KATAKANA) ||
1279         (flags & (LCMAP_HALFWIDTH | LCMAP_FULLWIDTH)) == (LCMAP_HALFWIDTH | LCMAP_FULLWIDTH) ||
1280         (flags & (LCMAP_TRADITIONAL_CHINESE | LCMAP_SIMPLIFIED_CHINESE)) == (LCMAP_TRADITIONAL_CHINESE | LCMAP_SIMPLIFIED_CHINESE))
1281     {
1282         SetLastError(ERROR_INVALID_FLAGS);
1283         return 0;
1284     }
1285
1286     if (!dstlen) dst = NULL;
1287
1288     lcid = ConvertDefaultLocale(lcid);
1289
1290     if (flags & LCMAP_SORTKEY)
1291     {
1292         if (src == dst)
1293         {
1294             SetLastError(ERROR_INVALID_FLAGS);
1295             return 0;
1296         }
1297
1298         if (srclen < 0) srclen = strlenW(src);
1299
1300         TRACE("(0x%04lx,0x%08lx,%s,%d,%p,%d)\n",
1301               lcid, flags, debugstr_wn(src, srclen), srclen, dst, dstlen);
1302
1303         return wine_get_sortkey(flags, src, srclen, (char *)dst, dstlen);
1304     }
1305
1306     /* SORT_STRINGSORT must be used exclusively with LCMAP_SORTKEY */
1307     if (flags & SORT_STRINGSORT)
1308     {
1309         SetLastError(ERROR_INVALID_FLAGS);
1310         return 0;
1311     }
1312
1313     if (srclen < 0) srclen = strlenW(src) + 1;
1314
1315     TRACE("(0x%04lx,0x%08lx,%s,%d,%p,%d)\n",
1316           lcid, flags, debugstr_wn(src, srclen), srclen, dst, dstlen);
1317
1318     if (!dst) /* return required string length */
1319     {
1320         INT len;
1321
1322         for (len = 0; srclen; src++, srclen--)
1323         {
1324             WCHAR wch = *src;
1325             /* tests show that win2k just ignores NORM_IGNORENONSPACE,
1326              * and skips white space and punctuation characters for
1327              * NORM_IGNORESYMBOLS.
1328              */
1329             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
1330                 continue;
1331             len++;
1332         }
1333         return len;
1334     }
1335
1336     if (flags & LCMAP_UPPERCASE)
1337     {
1338         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
1339         {
1340             WCHAR wch = *src;
1341             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
1342                 continue;
1343             *dst_ptr++ = toupperW(wch);
1344             dstlen--;
1345         }
1346     }
1347     else if (flags & LCMAP_LOWERCASE)
1348     {
1349         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
1350         {
1351             WCHAR wch = *src;
1352             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
1353                 continue;
1354             *dst_ptr++ = tolowerW(wch);
1355             dstlen--;
1356         }
1357     }
1358     else
1359     {
1360         if (src == dst)
1361         {
1362             SetLastError(ERROR_INVALID_FLAGS);
1363             return 0;
1364         }
1365         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
1366         {
1367             WCHAR wch = *src;
1368             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
1369                 continue;
1370             *dst_ptr++ = wch;
1371             dstlen--;
1372         }
1373     }
1374
1375     return dst_ptr - dst;
1376 }
1377
1378 /*************************************************************************
1379  *           LCMapStringA    (KERNEL32.@)
1380  */
1381 INT WINAPI LCMapStringA(LCID lcid, DWORD flags, LPCSTR src, INT srclen,
1382                         LPSTR dst, INT dstlen)
1383 {
1384     WCHAR bufW[128];
1385     LPWSTR srcW, dstW;
1386     INT ret = 0, srclenW, dstlenW;
1387     UINT locale_cp;
1388
1389     if (!src || !srclen || dstlen < 0)
1390     {
1391         SetLastError(ERROR_INVALID_PARAMETER);
1392         return 0;
1393     }
1394
1395     locale_cp = get_lcid_codepage(lcid);
1396
1397     srclenW = MultiByteToWideChar(locale_cp, 0, src, srclen, bufW, 128);
1398     if (srclenW)
1399         srcW = bufW;
1400     else
1401     {
1402         srclenW = MultiByteToWideChar(locale_cp, 0, src, srclen, NULL, 0);
1403         srcW = HeapAlloc(GetProcessHeap(), 0, srclenW * sizeof(WCHAR));
1404         if (!srcW)
1405         {
1406             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1407             return 0;
1408         }
1409         MultiByteToWideChar(locale_cp, 0, src, srclen, srcW, srclenW);
1410     }
1411
1412     if (flags & LCMAP_SORTKEY)
1413     {
1414         if (src == dst)
1415         {
1416             SetLastError(ERROR_INVALID_FLAGS);
1417             goto map_string_exit;
1418         }
1419         ret = wine_get_sortkey(flags, srcW, srclenW, dst, dstlen);
1420         goto map_string_exit;
1421     }
1422
1423     if (flags & SORT_STRINGSORT)
1424     {
1425         SetLastError(ERROR_INVALID_FLAGS);
1426         goto map_string_exit;
1427     }
1428
1429     dstlenW = LCMapStringW(lcid, flags, srcW, srclenW, NULL, 0);
1430     dstW = HeapAlloc(GetProcessHeap(), 0, dstlenW * sizeof(WCHAR));
1431     if (!dstW)
1432     {
1433         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1434         goto map_string_exit;
1435     }
1436
1437     LCMapStringW(lcid, flags, srcW, srclenW, dstW, dstlenW);
1438     ret = WideCharToMultiByte(locale_cp, 0, dstW, dstlenW, dst, dstlen, NULL, NULL);
1439     HeapFree(GetProcessHeap(), 0, dstW);
1440
1441 map_string_exit:
1442     if (srcW != bufW) HeapFree(GetProcessHeap(), 0, srcW);
1443     return ret;
1444 }
1445
1446 /******************************************************************************
1447  *           CompareStringW    (KERNEL32.@)
1448  */
1449 INT WINAPI CompareStringW(LCID lcid, DWORD style,
1450                           LPCWSTR str1, INT len1, LPCWSTR str2, INT len2)
1451 {
1452     INT ret, len;
1453
1454     if (!str1 || !str2)
1455     {
1456         SetLastError(ERROR_INVALID_PARAMETER);
1457         return 0;
1458     }
1459
1460     if (len1 < 0) len1 = lstrlenW(str1);
1461     if (len2 < 0) len2 = lstrlenW(str2);
1462
1463     len = (len1 < len2) ? len1 : len2;
1464     ret = (style & NORM_IGNORECASE) ? strncmpiW(str1, str2, len) :
1465                                       strncmpW(str1, str2, len);
1466
1467     if (ret) /* need to translate result */
1468         return (ret < 0) ? CSTR_LESS_THAN : CSTR_GREATER_THAN;
1469
1470     if (len1 == len2) return CSTR_EQUAL;
1471     /* the longer one is lexically greater */
1472     return (len1 < len2) ? CSTR_LESS_THAN : CSTR_GREATER_THAN;
1473 }
1474
1475 /******************************************************************************
1476  *           CompareStringA    (KERNEL32.@)
1477  */
1478 INT WINAPI CompareStringA(LCID lcid, DWORD style,
1479                           LPCSTR str1, INT len1, LPCSTR str2, INT len2)
1480 {
1481     WCHAR buf1W[128], buf2W[128];
1482     LPWSTR str1W, str2W;
1483     INT len1W, len2W, ret;
1484     UINT locale_cp;
1485
1486     if (!str1 || !str2)
1487     {
1488         SetLastError(ERROR_INVALID_PARAMETER);
1489         return 0;
1490     }
1491
1492     if (len1 < 0) len1 = strlen(str1);
1493     if (len2 < 0) len2 = strlen(str2);
1494
1495     locale_cp = get_lcid_codepage(lcid);
1496
1497     len1W = MultiByteToWideChar(locale_cp, 0, str1, len1, buf1W, 128);
1498     if (len1W)
1499         str1W = buf1W;
1500     else
1501     {
1502         len1W = MultiByteToWideChar(locale_cp, 0, str1, len1, NULL, 0);
1503         str1W = HeapAlloc(GetProcessHeap(), 0, len1W * sizeof(WCHAR));
1504         if (!str1W)
1505         {
1506             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1507             return 0;
1508         }
1509         MultiByteToWideChar(locale_cp, 0, str1, len1, str1W, len1W);
1510     }
1511     len2W = MultiByteToWideChar(locale_cp, 0, str2, len2, buf2W, 128);
1512     if (len2W)
1513         str2W = buf2W;
1514     else
1515     {
1516         len2W = MultiByteToWideChar(locale_cp, 0, str2, len2, NULL, 0);
1517         str2W = HeapAlloc(GetProcessHeap(), 0, len2W * sizeof(WCHAR));
1518         if (!str2W)
1519         {
1520             if (str1W != buf1W) HeapFree(GetProcessHeap(), 0, str1W);
1521             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1522             return 0;
1523         }
1524         MultiByteToWideChar(locale_cp, 0, str2, len2, str2W, len2W);
1525     }
1526
1527     ret = CompareStringW(lcid, style, str1W, len1W, str2W, len2W);
1528
1529     if (str1W != buf1W) HeapFree(GetProcessHeap(), 0, str1W);
1530     if (str2W != buf2W) HeapFree(GetProcessHeap(), 0, str2W);
1531     return ret;
1532 }
1533
1534 /*************************************************************************
1535  *           lstrcmp     (KERNEL32.@)
1536  *           lstrcmpA    (KERNEL32.@)
1537  */
1538 int WINAPI lstrcmpA(LPCSTR str1, LPCSTR str2)
1539 {
1540     int ret = CompareStringA(GetThreadLocale(), 0, str1, -1, str2, -1);
1541     if (ret) ret -= 2;
1542     return ret;
1543 }
1544
1545 /*************************************************************************
1546  *           lstrcmpi     (KERNEL32.@)
1547  *           lstrcmpiA    (KERNEL32.@)
1548  */
1549 int WINAPI lstrcmpiA(LPCSTR str1, LPCSTR str2)
1550 {
1551     int ret = CompareStringA(GetThreadLocale(), NORM_IGNORECASE, str1, -1, str2, -1);
1552     if (ret) ret -= 2;
1553     return ret;
1554 }
1555
1556 /*************************************************************************
1557  *           lstrcmpW    (KERNEL32.@)
1558  */
1559 int WINAPI lstrcmpW(LPCWSTR str1, LPCWSTR str2)
1560 {
1561     int ret = CompareStringW(GetThreadLocale(), 0, str1, -1, str2, -1);
1562     if (ret) ret -= 2;
1563     return ret;
1564 }
1565
1566 /*************************************************************************
1567  *           lstrcmpiW    (KERNEL32.@)
1568  */
1569 int WINAPI lstrcmpiW(LPCWSTR str1, LPCWSTR str2)
1570 {
1571     int ret = CompareStringW(GetThreadLocale(), NORM_IGNORECASE, str1, -1, str2, -1);
1572     if (ret) ret -= 2;
1573     return ret;
1574 }
1575
1576 /******************************************************************************
1577  *              LOCALE_Init
1578  */
1579 void LOCALE_Init(void)
1580 {
1581     UINT ansi_cp = 1252, oem_cp = 437, mac_cp = 10000, unix_cp = ~0U;
1582     LCID lcid = init_default_lcid( &unix_cp );
1583
1584     NtSetDefaultLocale( FALSE, lcid );
1585     NtSetDefaultLocale( TRUE, lcid );
1586
1587     ansi_cp = get_lcid_codepage(lcid);
1588     GetLocaleInfoW( lcid, LOCALE_IDEFAULTMACCODEPAGE | LOCALE_RETURN_NUMBER,
1589                     (LPWSTR)&mac_cp, sizeof(mac_cp)/sizeof(WCHAR) );
1590     GetLocaleInfoW( lcid, LOCALE_IDEFAULTCODEPAGE | LOCALE_RETURN_NUMBER,
1591                     (LPWSTR)&oem_cp, sizeof(oem_cp)/sizeof(WCHAR) );
1592     if (unix_cp == ~0U)
1593         GetLocaleInfoW( lcid, LOCALE_IDEFAULTUNIXCODEPAGE | LOCALE_RETURN_NUMBER,
1594                     (LPWSTR)&unix_cp, sizeof(unix_cp)/sizeof(WCHAR) );
1595
1596     CODEPAGE_Init( ansi_cp, oem_cp, mac_cp, unix_cp, lcid );
1597     update_registry( lcid );
1598 }
1599
1600 static HKEY NLS_RegOpenKey(HKEY hRootKey, LPCWSTR szKeyName)
1601 {
1602     UNICODE_STRING keyName;
1603     OBJECT_ATTRIBUTES attr;
1604     HKEY hkey;
1605
1606     RtlInitUnicodeString( &keyName, szKeyName );
1607     InitializeObjectAttributes(&attr, &keyName, 0, hRootKey, NULL);
1608
1609     if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) != STATUS_SUCCESS)
1610         hkey = 0;
1611
1612     return hkey;
1613 }
1614
1615 static HKEY NLS_RegOpenSubKey(HKEY hRootKey, LPCWSTR szKeyName)
1616 {
1617     HKEY hKey = NLS_RegOpenKey(hRootKey, szKeyName);
1618
1619     if (hRootKey)
1620         NtClose( hRootKey );
1621
1622     return hKey;
1623 }
1624
1625 static BOOL NLS_RegEnumSubKey(HKEY hKey, UINT ulIndex, LPWSTR szKeyName,
1626                               ULONG keyNameSize)
1627 {
1628     BYTE buffer[80];
1629     KEY_BASIC_INFORMATION *info = (KEY_BASIC_INFORMATION *)buffer;
1630     DWORD dwLen;
1631
1632     if (NtEnumerateKey( hKey, ulIndex, KeyBasicInformation, buffer,
1633                         sizeof(buffer), &dwLen) != STATUS_SUCCESS ||
1634         info->NameLength > keyNameSize)
1635     {
1636         return FALSE;
1637     }
1638
1639     TRACE("info->Name %s info->NameLength %ld\n", debugstr_w(info->Name), info->NameLength);
1640
1641     memcpy( szKeyName, info->Name, info->NameLength);
1642     szKeyName[info->NameLength / sizeof(WCHAR)] = '\0';
1643
1644     TRACE("returning %s\n", debugstr_w(szKeyName));
1645     return TRUE;
1646 }
1647
1648 static BOOL NLS_RegEnumValue(HKEY hKey, UINT ulIndex,
1649                              LPWSTR szValueName, ULONG valueNameSize,
1650                              LPWSTR szValueData, ULONG valueDataSize)
1651 {
1652     BYTE buffer[80];
1653     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1654     DWORD dwLen;
1655
1656     if (NtEnumerateValueKey( hKey, ulIndex, KeyValueFullInformation,
1657         buffer, sizeof(buffer), &dwLen ) != STATUS_SUCCESS ||
1658         info->NameLength > valueNameSize ||
1659         info->DataLength > valueDataSize)
1660     {
1661         return FALSE;
1662     }
1663
1664     TRACE("info->Name %s info->DataLength %ld\n", debugstr_w(info->Name), info->DataLength);
1665
1666     memcpy( szValueName, info->Name, info->NameLength);
1667     szValueName[info->NameLength / sizeof(WCHAR)] = '\0';
1668     memcpy( szValueData, buffer + info->DataOffset, info->DataLength );
1669     szValueData[info->DataLength / sizeof(WCHAR)] = '\0';
1670
1671     TRACE("returning %s %s\n", debugstr_w(szValueName), debugstr_w(szValueData));
1672     return TRUE;
1673 }
1674
1675 static BOOL NLS_RegGetDword(HKEY hKey, LPCWSTR szValueName, DWORD *lpVal)
1676 {
1677     BYTE buffer[128];
1678     const KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1679     DWORD dwSize = sizeof(buffer);
1680     UNICODE_STRING valueName;
1681
1682     RtlInitUnicodeString( &valueName, szValueName );
1683
1684     TRACE("%p, %s\n", hKey, debugstr_w(szValueName));
1685     if (NtQueryValueKey( hKey, &valueName, KeyValuePartialInformation,
1686                          buffer, dwSize, &dwSize ) == STATUS_SUCCESS &&
1687         info->DataLength == sizeof(DWORD))
1688     {
1689         memcpy(lpVal, info->Data, sizeof(DWORD));
1690         return TRUE;
1691     }
1692
1693     return FALSE;
1694 }
1695
1696 static BOOL NLS_GetLanguageGroupName(LGRPID lgrpid, LPWSTR szName, ULONG nameSize)
1697 {
1698     HMODULE hModule = GetModuleHandleW(kernel32W);
1699     LANGID  langId;
1700     LPCWSTR szResourceName = (LPCWSTR)(((lgrpid + 0x2000) >> 4) + 1);
1701     HRSRC   hResource;
1702     BOOL    bRet = FALSE;
1703
1704     /* FIXME: Is it correct to use the system default langid? */
1705     langId = GetSystemDefaultLangID();
1706
1707     if (SUBLANGID(langId) == SUBLANG_NEUTRAL)
1708         langId = MAKELANGID( PRIMARYLANGID(langId), SUBLANG_DEFAULT );
1709
1710     hResource = FindResourceExW( hModule, (LPWSTR)RT_STRING, szResourceName, langId );
1711
1712     if (hResource)
1713     {
1714         HGLOBAL hResDir = LoadResource( hModule, hResource );
1715
1716         if (hResDir)
1717         {
1718             ULONG   iResourceIndex = lgrpid & 0xf;
1719             LPCWSTR lpResEntry = LockResource( hResDir );
1720             ULONG   i;
1721
1722             for (i = 0; i < iResourceIndex; i++)
1723                 lpResEntry += *lpResEntry + 1;
1724
1725             if (*lpResEntry < nameSize)
1726             {
1727                 memcpy( szName, lpResEntry + 1, *lpResEntry * sizeof(WCHAR) );
1728                 szName[*lpResEntry] = '\0';
1729                 bRet = TRUE;
1730             }
1731
1732         }
1733         FreeResource( hResource );
1734     }
1735     return bRet;
1736 }
1737
1738 /* Registry keys for NLS related information */
1739 static const WCHAR szNlsKeyName[] = {
1740     'M','a','c','h','i','n','e','\\','S','y','s','t','e','m','\\',
1741     'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
1742     'C','o','n','t','r','o','l','\\','N','l','s','\0'
1743 };
1744
1745 static const WCHAR szLangGroupsKeyName[] = {
1746     'L','a','n','g','u','a','g','e',' ','G','r','o','u','p','s','\0'
1747 };
1748
1749 static const WCHAR szCountryListName[] = {
1750     'M','a','c','h','i','n','e','\\','S','o','f','t','w','a','r','e','\\',
1751     'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
1752     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
1753     'T','e','l','e','p','h','o','n','y','\\',
1754     'C','o','u','n','t','r','y',' ','L','i','s','t','\0'
1755 };
1756
1757
1758 /* Callback function ptrs for EnumSystemLanguageGroupsA/W */
1759 typedef struct
1760 {
1761   LANGUAGEGROUP_ENUMPROCA procA;
1762   LANGUAGEGROUP_ENUMPROCW procW;
1763   DWORD    dwFlags;
1764   LONG_PTR lParam;
1765 } ENUMLANGUAGEGROUP_CALLBACKS;
1766
1767 /* Internal implementation of EnumSystemLanguageGroupsA/W */
1768 static BOOL NLS_EnumSystemLanguageGroups(ENUMLANGUAGEGROUP_CALLBACKS *lpProcs)
1769 {
1770     WCHAR szNumber[10], szValue[4];
1771     HKEY hKey;
1772     BOOL bContinue = TRUE;
1773     ULONG ulIndex = 0;
1774
1775     if (!lpProcs)
1776     {
1777         SetLastError(ERROR_INVALID_PARAMETER);
1778         return FALSE;
1779     }
1780
1781     switch (lpProcs->dwFlags)
1782     {
1783     case 0:
1784         /* Default to LGRPID_INSTALLED */
1785         lpProcs->dwFlags = LGRPID_INSTALLED;
1786         /* Fall through... */
1787     case LGRPID_INSTALLED:
1788     case LGRPID_SUPPORTED:
1789         break;
1790     default:
1791         SetLastError(ERROR_INVALID_FLAGS);
1792         return FALSE;
1793     }
1794
1795     hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLangGroupsKeyName );
1796
1797     if (!hKey)
1798       WARN("NLS registry key not found. Please apply the default registry file 'winedefault.reg'\n");
1799
1800     while (bContinue)
1801     {
1802         if (NLS_RegEnumValue( hKey, ulIndex, szNumber, sizeof(szNumber),
1803                               szValue, sizeof(szValue) ))
1804         {
1805             BOOL bInstalled = szValue[0] == '1' ? TRUE : FALSE;
1806             LGRPID lgrpid = strtoulW( szNumber, NULL, 16 );
1807
1808             TRACE("grpid %s (%sinstalled)\n", debugstr_w(szNumber),
1809                    bInstalled ? "" : "not ");
1810
1811             if (lpProcs->dwFlags == LGRPID_SUPPORTED || bInstalled)
1812             {
1813                 WCHAR szGrpName[48];
1814
1815                 if (!NLS_GetLanguageGroupName( lgrpid, szGrpName, sizeof(szGrpName) / sizeof(WCHAR) ))
1816                     szGrpName[0] = '\0';
1817
1818                 if (lpProcs->procW)
1819                     bContinue = lpProcs->procW( lgrpid, szNumber, szGrpName, lpProcs->dwFlags,
1820                                                 lpProcs->lParam );
1821                 else
1822                 {
1823                     char szNumberA[sizeof(szNumber)/sizeof(WCHAR)];
1824                     char szGrpNameA[48];
1825
1826                     /* FIXME: MSDN doesn't say which code page the W->A translation uses,
1827                      *        or whether the language names are ever localised. Assume CP_ACP.
1828                      */
1829
1830                     WideCharToMultiByte(CP_ACP, 0, szNumber, -1, szNumberA, sizeof(szNumberA), 0, 0);
1831                     WideCharToMultiByte(CP_ACP, 0, szGrpName, -1, szGrpNameA, sizeof(szGrpNameA), 0, 0);
1832
1833                     bContinue = lpProcs->procA( lgrpid, szNumberA, szGrpNameA, lpProcs->dwFlags,
1834                                                 lpProcs->lParam );
1835                 }
1836             }
1837
1838             ulIndex++;
1839         }
1840         else
1841             bContinue = FALSE;
1842
1843         if (!bContinue)
1844             break;
1845     }
1846
1847     if (hKey)
1848         NtClose( hKey );
1849
1850     return TRUE;
1851 }
1852
1853 /******************************************************************************
1854  *           EnumSystemLanguageGroupsA    (KERNEL32.@)
1855  *
1856  * Call a users function for each language group available on the system.
1857  *
1858  * PARAMS
1859  *  pLangGrpEnumProc [I] Callback function to call for each language group
1860  *  dwFlags          [I] LGRPID_SUPPORTED=All Supported, LGRPID_INSTALLED=Installed only
1861  *  lParam           [I] User parameter to pass to pLangGrpEnumProc
1862  *
1863  * RETURNS
1864  *  Success: TRUE.
1865  *  Failure: FALSE. Use GetLastError() to determine the cause.
1866  */
1867 BOOL WINAPI EnumSystemLanguageGroupsA(LANGUAGEGROUP_ENUMPROCA pLangGrpEnumProc,
1868                                       DWORD dwFlags, LONG_PTR lParam)
1869 {
1870     ENUMLANGUAGEGROUP_CALLBACKS procs;
1871
1872     TRACE("(%p,0x%08lX,0x%08lX)\n", pLangGrpEnumProc, dwFlags, lParam);
1873
1874     procs.procA = pLangGrpEnumProc;
1875     procs.procW = NULL;
1876     procs.dwFlags = dwFlags;
1877     procs.lParam = lParam;
1878
1879     return NLS_EnumSystemLanguageGroups( pLangGrpEnumProc ? &procs : NULL);
1880 }
1881
1882 /******************************************************************************
1883  *           EnumSystemLanguageGroupsW    (KERNEL32.@)
1884  *
1885  * See EnumSystemLanguageGroupsA.
1886  */
1887 BOOL WINAPI EnumSystemLanguageGroupsW(LANGUAGEGROUP_ENUMPROCW pLangGrpEnumProc,
1888                                       DWORD dwFlags, LONG_PTR lParam)
1889 {
1890     ENUMLANGUAGEGROUP_CALLBACKS procs;
1891
1892     TRACE("(%p,0x%08lX,0x%08lX)\n", pLangGrpEnumProc, dwFlags, lParam);
1893
1894     procs.procA = NULL;
1895     procs.procW = pLangGrpEnumProc;
1896     procs.dwFlags = dwFlags;
1897     procs.lParam = lParam;
1898
1899     return NLS_EnumSystemLanguageGroups( pLangGrpEnumProc ? &procs : NULL);
1900 }
1901
1902 /******************************************************************************
1903  *           IsValidLanguageGroup    (KERNEL32.@)
1904  *
1905  * Determine if a language group is supported and/or installed.
1906  *
1907  * PARAMS
1908  *  lgrpid  [I] Language Group Id (LGRPID_ values from "winnls.h")
1909  *  dwFlags [I] LGRPID_SUPPORTED=Supported, LGRPID_INSTALLED=Installed
1910  *
1911  * RETURNS
1912  *  TRUE, if lgrpid is supported and/or installed, according to dwFlags.
1913  *  FALSE otherwise.
1914  */
1915 BOOL WINAPI IsValidLanguageGroup(LGRPID lgrpid, DWORD dwFlags)
1916 {
1917     static const WCHAR szFormat[] = { '%','x','\0' };
1918     WCHAR szValueName[16], szValue[2];
1919     BOOL bSupported = FALSE, bInstalled = FALSE;
1920     HKEY hKey;
1921
1922
1923     switch (dwFlags)
1924     {
1925     case LGRPID_INSTALLED:
1926     case LGRPID_SUPPORTED:
1927
1928         hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLangGroupsKeyName );
1929
1930         sprintfW( szValueName, szFormat, lgrpid );
1931
1932         if (NLS_RegGetDword( hKey, szValueName, (LPDWORD)&szValue ))
1933         {
1934             bSupported = TRUE;
1935
1936             if (szValue[0] == '1')
1937                 bInstalled = TRUE;
1938         }
1939
1940         if (hKey)
1941             NtClose( hKey );
1942
1943         break;
1944     }
1945
1946     if ((dwFlags == LGRPID_SUPPORTED && bSupported) ||
1947         (dwFlags == LGRPID_INSTALLED && bInstalled))
1948         return TRUE;
1949
1950     return FALSE;
1951 }
1952
1953 /* Callback function ptrs for EnumLanguageGrouplocalesA/W */
1954 typedef struct
1955 {
1956   LANGGROUPLOCALE_ENUMPROCA procA;
1957   LANGGROUPLOCALE_ENUMPROCW procW;
1958   DWORD    dwFlags;
1959   LGRPID   lgrpid;
1960   LONG_PTR lParam;
1961 } ENUMLANGUAGEGROUPLOCALE_CALLBACKS;
1962
1963 /* Internal implementation of EnumLanguageGrouplocalesA/W */
1964 static BOOL NLS_EnumLanguageGroupLocales(ENUMLANGUAGEGROUPLOCALE_CALLBACKS *lpProcs)
1965 {
1966     static const WCHAR szLocaleKeyName[] = {
1967       'L','o','c','a','l','e','\0'
1968     };
1969     static const WCHAR szAlternateSortsKeyName[] = {
1970       'A','l','t','e','r','n','a','t','e',' ','S','o','r','t','s','\0'
1971     };
1972     WCHAR szNumber[10], szValue[4];
1973     HKEY hKey;
1974     BOOL bContinue = TRUE, bAlternate = FALSE;
1975     LGRPID lgrpid;
1976     ULONG ulIndex = 1;  /* Ignore default entry of 1st key */
1977
1978     if (!lpProcs || !lpProcs->lgrpid || lpProcs->lgrpid > LGRPID_ARMENIAN)
1979     {
1980         SetLastError(ERROR_INVALID_PARAMETER);
1981         return FALSE;
1982     }
1983
1984     if (lpProcs->dwFlags)
1985     {
1986         SetLastError(ERROR_INVALID_FLAGS);
1987         return FALSE;
1988     }
1989
1990     hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLocaleKeyName );
1991
1992     if (!hKey)
1993       WARN("NLS registry key not found. Please apply the default registry file 'winedefault.reg'\n");
1994
1995     while (bContinue)
1996     {
1997         if (NLS_RegEnumValue( hKey, ulIndex, szNumber, sizeof(szNumber),
1998                               szValue, sizeof(szValue) ))
1999         {
2000             lgrpid = strtoulW( szValue, NULL, 16 );
2001
2002             TRACE("lcid %s, grpid %ld (%smatched)\n", debugstr_w(szNumber),
2003                    lgrpid, lgrpid == lpProcs->lgrpid ? "" : "not ");
2004
2005             if (lgrpid == lpProcs->lgrpid)
2006             {
2007                 LCID lcid;
2008
2009                 lcid = strtoulW( szNumber, NULL, 16 );
2010
2011                 /* FIXME: native returns extra text for a few (17/150) locales, e.g:
2012                  * '00000437          ;Georgian'
2013                  * At present we only pass the LCID string.
2014                  */
2015
2016                 if (lpProcs->procW)
2017                     bContinue = lpProcs->procW( lgrpid, lcid, szNumber, lpProcs->lParam );
2018                 else
2019                 {
2020                     char szNumberA[sizeof(szNumber)/sizeof(WCHAR)];
2021
2022                     WideCharToMultiByte(CP_ACP, 0, szNumber, -1, szNumberA, sizeof(szNumberA), 0, 0);
2023
2024                     bContinue = lpProcs->procA( lgrpid, lcid, szNumberA, lpProcs->lParam );
2025                 }
2026             }
2027
2028             ulIndex++;
2029         }
2030         else
2031         {
2032             /* Finished enumerating this key */
2033             if (!bAlternate)
2034             {
2035                 /* Enumerate alternate sorts also */
2036                 hKey = NLS_RegOpenKey( hKey, szAlternateSortsKeyName );
2037                 bAlternate = TRUE;
2038                 ulIndex = 0;
2039             }
2040             else
2041                 bContinue = FALSE; /* Finished both keys */
2042         }
2043
2044         if (!bContinue)
2045             break;
2046     }
2047
2048     if (hKey)
2049         NtClose( hKey );
2050
2051     return TRUE;
2052 }
2053
2054 /******************************************************************************
2055  *           EnumLanguageGroupLocalesA    (KERNEL32.@)
2056  *
2057  * Call a users function for every locale in a language group available on the system.
2058  *
2059  * PARAMS
2060  *  pLangGrpLcEnumProc [I] Callback function to call for each locale
2061  *  lgrpid             [I] Language group (LGRPID_ values from "winnls.h")
2062  *  dwFlags            [I] Reserved, set to 0
2063  *  lParam             [I] User parameter to pass to pLangGrpLcEnumProc
2064  *
2065  * RETURNS
2066  *  Success: TRUE.
2067  *  Failure: FALSE. Use GetLastError() to determine the cause.
2068  */
2069 BOOL WINAPI EnumLanguageGroupLocalesA(LANGGROUPLOCALE_ENUMPROCA pLangGrpLcEnumProc,
2070                                       LGRPID lgrpid, DWORD dwFlags, LONG_PTR lParam)
2071 {
2072     ENUMLANGUAGEGROUPLOCALE_CALLBACKS callbacks;
2073
2074     TRACE("(%p,0x%08lX,0x%08lX,0x%08lX)\n", pLangGrpLcEnumProc, lgrpid, dwFlags, lParam);
2075
2076     callbacks.procA   = pLangGrpLcEnumProc;
2077     callbacks.procW   = NULL;
2078     callbacks.dwFlags = dwFlags;
2079     callbacks.lgrpid  = lgrpid;
2080     callbacks.lParam  = lParam;
2081
2082     return NLS_EnumLanguageGroupLocales( pLangGrpLcEnumProc ? &callbacks : NULL );
2083 }
2084
2085 /******************************************************************************
2086  *           EnumLanguageGroupLocalesW    (KERNEL32.@)
2087  *
2088  * See EnumLanguageGroupLocalesA.
2089  */
2090 BOOL WINAPI EnumLanguageGroupLocalesW(LANGGROUPLOCALE_ENUMPROCW pLangGrpLcEnumProc,
2091                                       LGRPID lgrpid, DWORD dwFlags, LONG_PTR lParam)
2092 {
2093     ENUMLANGUAGEGROUPLOCALE_CALLBACKS callbacks;
2094
2095     TRACE("(%p,0x%08lX,0x%08lX,0x%08lX)\n", pLangGrpLcEnumProc, lgrpid, dwFlags, lParam);
2096
2097     callbacks.procA   = NULL;
2098     callbacks.procW   = pLangGrpLcEnumProc;
2099     callbacks.dwFlags = dwFlags;
2100     callbacks.lgrpid  = lgrpid;
2101     callbacks.lParam  = lParam;
2102
2103     return NLS_EnumLanguageGroupLocales( pLangGrpLcEnumProc ? &callbacks : NULL );
2104 }
2105
2106 /******************************************************************************
2107  *           EnumSystemGeoID    (KERNEL32.@)
2108  *
2109  * Call a users function for every location available on the system.
2110  *
2111  * PARAMS
2112  *  geoclass     [I] Type of information desired (SYSGEOTYPE enum from "winnls.h")
2113  *  reserved     [I] Reserved, set to 0
2114  *  pGeoEnumProc [I] Callback function to call for each location
2115  *
2116  * RETURNS
2117  *  Success: TRUE.
2118  *  Failure: FALSE. Use GetLastError() to determine the cause.
2119  */
2120 BOOL WINAPI EnumSystemGeoID(GEOCLASS geoclass, GEOID reserved, GEO_ENUMPROC pGeoEnumProc)
2121 {
2122     static const WCHAR szCountryCodeValueName[] = {
2123       'C','o','u','n','t','r','y','C','o','d','e','\0'
2124     };
2125     WCHAR szNumber[10];
2126     HKEY hKey;
2127     ULONG ulIndex = 0;
2128
2129     TRACE("(0x%08lX,0x%08lX,%p)\n", geoclass, reserved, pGeoEnumProc);
2130
2131     if (geoclass != GEOCLASS_NATION || reserved || !pGeoEnumProc)
2132     {
2133         SetLastError(ERROR_INVALID_PARAMETER);
2134         return FALSE;
2135     }
2136
2137     hKey = NLS_RegOpenKey( 0, szCountryListName );
2138
2139     while (NLS_RegEnumSubKey( hKey, ulIndex, szNumber, sizeof(szNumber) ))
2140     {
2141         BOOL bContinue = TRUE;
2142         DWORD dwGeoId;
2143         HKEY hSubKey = NLS_RegOpenKey( hKey, szNumber );
2144
2145         if (hSubKey)
2146         {
2147             if (NLS_RegGetDword( hSubKey, szCountryCodeValueName, &dwGeoId ))
2148             {
2149                 TRACE("Got geoid %ld\n", dwGeoId);
2150
2151                 if (!pGeoEnumProc( dwGeoId ))
2152                     bContinue = FALSE;
2153             }
2154
2155             NtClose( hSubKey );
2156         }
2157
2158         if (!bContinue)
2159             break;
2160
2161         ulIndex++;
2162     }
2163
2164     if (hKey)
2165         NtClose( hKey );
2166
2167     return TRUE;
2168 }
2169
2170 /******************************************************************************
2171  *           InvalidateNLSCache           (KERNEL32.@)
2172  *
2173  * Invalidate the cache of NLS values.
2174  *
2175  * PARAMS
2176  *  None.
2177  *
2178  * RETURNS
2179  *  Success: TRUE.
2180  *  Failure: FALSE.
2181  */
2182 BOOL WINAPI InvalidateNLSCache(void)
2183 {
2184   FIXME("() stub\n");
2185   return FALSE;
2186 }