Fix segmentation fault caused by incorrect referencing of client audio
[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 <assert.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <stdlib.h>
33
34 #include "ntstatus.h"
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winuser.h"  /* for RT_STRINGW */
38 #include "winreg.h"
39 #include "winternl.h"
40 #include "wine/unicode.h"
41 #include "winnls.h"
42 #include "winerror.h"
43 #include "winver.h"
44 #include "thread.h"
45 #include "kernel_private.h"
46 #include "wine/debug.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(nls);
49
50 #define LOCALE_LOCALEINFOFLAGSMASK (LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP|LOCALE_RETURN_NUMBER)
51
52 /* current code pages */
53 static const union cptable *ansi_cptable;
54 static const union cptable *oem_cptable;
55 static const union cptable *mac_cptable;
56 static const union cptable *unix_cptable;  /* NULL if UTF8 */
57
58 static HKEY NLS_RegOpenKey(HKEY hRootKey, LPCWSTR szKeyName);
59 static HKEY NLS_RegOpenSubKey(HKEY hRootKey, LPCWSTR szKeyName);
60
61 static const WCHAR szNlsKeyName[] = {
62     'M','a','c','h','i','n','e','\\','S','y','s','t','e','m','\\',
63     'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
64     'C','o','n','t','r','o','l','\\','N','l','s','\0'
65 };
66
67 /* Charset to codepage map, sorted by name. */
68 static const struct charset_entry
69 {
70     const char *charset_name;
71     UINT        codepage;
72 } charset_names[] =
73 {
74     { "BIG5", 950 },
75     { "CP1250", 1250 },
76     { "CP1251", 1251 },
77     { "CP1252", 1252 },
78     { "CP1253", 1253 },
79     { "CP1254", 1254 },
80     { "CP1255", 1255 },
81     { "CP1256", 1256 },
82     { "CP1257", 1257 },
83     { "CP1258", 1258 },
84     { "CP932", 932 },
85     { "CP936", 936 },
86     { "CP949", 949 },
87     { "CP950", 950 },
88     { "EUCJP", 20932 },
89     { "GB2312", 936 },
90     { "IBM037", 37 },
91     { "IBM1026", 1026 },
92     { "IBM424", 424 },
93     { "IBM437", 437 },
94     { "IBM500", 500 },
95     { "IBM850", 850 },
96     { "IBM852", 852 },
97     { "IBM855", 855 },
98     { "IBM857", 857 },
99     { "IBM860", 860 },
100     { "IBM861", 861 },
101     { "IBM862", 862 },
102     { "IBM863", 863 },
103     { "IBM864", 864 },
104     { "IBM865", 865 },
105     { "IBM866", 866 },
106     { "IBM869", 869 },
107     { "IBM874", 874 },
108     { "IBM875", 875 },
109     { "ISO88591", 28591 },
110     { "ISO885910", 28600 },
111     { "ISO885913", 28603 },
112     { "ISO885914", 28604 },
113     { "ISO885915", 28605 },
114     { "ISO885916", 28606 },
115     { "ISO88592", 28592 },
116     { "ISO88593", 28593 },
117     { "ISO88594", 28594 },
118     { "ISO88595", 28595 },
119     { "ISO88596", 28596 },
120     { "ISO88597", 28597 },
121     { "ISO88598", 28598 },
122     { "ISO88599", 28599 },
123     { "KOI8R", 20866 },
124     { "KOI8U", 21866 },
125     { "UTF8", CP_UTF8 }
126 };
127
128 #define NLS_MAX_LANGUAGES 20
129 typedef struct {
130     WCHAR lang[128];
131     WCHAR country[4];
132     LANGID found_lang_id[NLS_MAX_LANGUAGES];
133     int n_found;
134 } LANG_FIND_DATA;
135
136
137 /* copy Unicode string to Ascii without using codepages */
138 static inline void strcpyWtoA( char *dst, const WCHAR *src )
139 {
140     while ((*dst++ = *src++));
141 }
142
143 /* Copy Ascii string to Unicode without using codepages */
144 static inline void strcpynAtoW( WCHAR *dst, const char *src, size_t n )
145 {
146     while (n > 1 && *src)
147     {
148         *dst++ = (unsigned char)*src++;
149         n--;
150     }
151     if (n) *dst = 0;
152 }
153
154 /* return a printable string for a language id */
155 static const char *debugstr_lang( LANGID lang )
156 {
157     WCHAR langW[4], countryW[4];
158     char buffer[8];
159     LCID lcid = MAKELCID( lang, SORT_DEFAULT );
160
161     GetLocaleInfoW(lcid, LOCALE_SISO639LANGNAME|LOCALE_NOUSEROVERRIDE, langW, sizeof(langW)/sizeof(WCHAR));
162     GetLocaleInfoW(lcid, LOCALE_SISO3166CTRYNAME|LOCALE_NOUSEROVERRIDE, countryW, sizeof(countryW)/sizeof(WCHAR));
163     strcpyWtoA( buffer, langW );
164     strcat( buffer, "_" );
165     strcpyWtoA( buffer + strlen(buffer), countryW );
166     return wine_dbg_sprintf( "%s", buffer );
167 }
168
169 /***********************************************************************
170  *              get_lcid_codepage
171  *
172  * Retrieve the ANSI codepage for a given locale.
173  */
174 inline static UINT get_lcid_codepage( LCID lcid )
175 {
176     UINT ret;
177     if (!GetLocaleInfoW( lcid, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER, (WCHAR *)&ret,
178                          sizeof(ret)/sizeof(WCHAR) )) ret = 0;
179     return ret;
180 }
181
182
183 /***********************************************************************
184  *              get_codepage_table
185  *
186  * Find the table for a given codepage, handling CP_ACP etc. pseudo-codepages
187  */
188 static const union cptable *get_codepage_table( unsigned int codepage )
189 {
190     const union cptable *ret = NULL;
191
192     assert( ansi_cptable );  /* init must have been done already */
193
194     switch(codepage)
195     {
196     case CP_ACP:
197         return ansi_cptable;
198     case CP_OEMCP:
199         return oem_cptable;
200     case CP_MACCP:
201         return mac_cptable;
202     case CP_UTF7:
203     case CP_UTF8:
204         break;
205     case CP_THREAD_ACP:
206         if (!(codepage = NtCurrentTeb()->code_page)) return ansi_cptable;
207         /* fall through */
208     default:
209         if (codepage == ansi_cptable->info.codepage) return ansi_cptable;
210         if (codepage == oem_cptable->info.codepage) return oem_cptable;
211         if (codepage == mac_cptable->info.codepage) return mac_cptable;
212         ret = wine_cp_get_table( codepage );
213         break;
214     }
215     return ret;
216 }
217
218 /***********************************************************************
219  *              create_registry_key
220  *
221  * Create the Control Panel\\International registry key.
222  */
223 inline static HKEY create_registry_key(void)
224 {
225     static const WCHAR intlW[] = {'C','o','n','t','r','o','l',' ','P','a','n','e','l','\\',
226                                   'I','n','t','e','r','n','a','t','i','o','n','a','l',0};
227     OBJECT_ATTRIBUTES attr;
228     UNICODE_STRING nameW;
229     HKEY hkey;
230
231     if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &hkey ) != STATUS_SUCCESS) return 0;
232
233     attr.Length = sizeof(attr);
234     attr.RootDirectory = hkey;
235     attr.ObjectName = &nameW;
236     attr.Attributes = 0;
237     attr.SecurityDescriptor = NULL;
238     attr.SecurityQualityOfService = NULL;
239     RtlInitUnicodeString( &nameW, intlW );
240
241     if (NtCreateKey( &hkey, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS) hkey = 0;
242     NtClose( attr.RootDirectory );
243     return hkey;
244 }
245
246
247 /***********************************************************************
248  *              LOCALE_InitRegistry
249  *
250  * Update registry contents on startup if the user locale has changed.
251  * This simulates the action of the Windows control panel.
252  */
253 void LOCALE_InitRegistry(void)
254 {
255     static const WCHAR CodepageW[] = {'C','o','d','e','p','a','g','e',0};
256     static const WCHAR acpW[] = {'A','C','P',0};
257     static const WCHAR oemcpW[] = {'O','E','M','C','P',0};
258     static const WCHAR maccpW[] = {'M','A','C','C','P',0};
259     static const struct
260     {
261         LPCWSTR name;
262         USHORT value;
263     } update_cp_values[] = {
264         { acpW, LOCALE_IDEFAULTANSICODEPAGE },
265         { oemcpW, LOCALE_IDEFAULTCODEPAGE },
266         { maccpW, LOCALE_IDEFAULTMACCODEPAGE }
267     };
268     static const USHORT updateValues[] = {
269       LOCALE_SLANGUAGE,
270       LOCALE_SCOUNTRY, LOCALE_ICOUNTRY,
271       LOCALE_S1159, LOCALE_S2359,
272       LOCALE_STIME, LOCALE_ITIME,
273       LOCALE_ITLZERO,
274       LOCALE_SSHORTDATE,
275       LOCALE_SLONGDATE,
276       LOCALE_SDATE,
277       LOCALE_SCURRENCY, LOCALE_ICURRENCY,
278       LOCALE_INEGCURR,
279       LOCALE_ICURRDIGITS,
280       LOCALE_SDECIMAL,
281       LOCALE_SLIST,
282       LOCALE_STHOUSAND,
283       LOCALE_IDIGITS,
284       LOCALE_IDIGITSUBSTITUTION,
285       LOCALE_SNATIVEDIGITS,
286       LOCALE_ITIMEMARKPOSN,
287       LOCALE_ICALENDARTYPE,
288       LOCALE_ILZERO,
289       LOCALE_IMEASURE
290     };
291     static const WCHAR LocaleW[] = {'L','o','c','a','l','e',0};
292     UNICODE_STRING nameW;
293     char buffer[20];
294     WCHAR bufferW[80];
295     DWORD count, i;
296     HKEY hkey;
297     LCID lcid = GetUserDefaultLCID();
298
299     if (!(hkey = create_registry_key()))
300         return;  /* don't do anything if we can't create the registry key */
301
302     RtlInitUnicodeString( &nameW, LocaleW );
303     count = sizeof(bufferW);
304     if (!NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation, (LPBYTE)bufferW, count, &count))
305     {
306         const KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)bufferW;
307         LPCWSTR szValueText = (LPCWSTR)info->Data;
308
309         if (strtoulW( szValueText, NULL, 16 ) == lcid)  /* already set correctly */
310         {
311             NtClose( hkey );
312             return;
313         }
314         TRACE( "updating registry, locale changed %s -> %08lx\n", debugstr_w(szValueText), lcid );
315     }
316     else TRACE( "updating registry, locale changed none -> %08lx\n", lcid );
317
318     sprintf( buffer, "%08lx", lcid );
319     /* Note: '9' constant below is strlen(buffer) + 1 */
320     RtlMultiByteToUnicodeN( bufferW, sizeof(bufferW), NULL, buffer, 9 );
321     NtSetValueKey( hkey, &nameW, 0, REG_SZ, bufferW, 9 * sizeof(WCHAR) );
322     NtClose( hkey );
323
324     for (i = 0; i < sizeof(updateValues)/sizeof(updateValues[0]); i++)
325     {
326         GetLocaleInfoW( lcid, updateValues[i] | LOCALE_NOUSEROVERRIDE, bufferW,
327                         sizeof(bufferW)/sizeof(WCHAR) );
328         SetLocaleInfoW( lcid, updateValues[i], bufferW );
329     }
330
331     hkey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), CodepageW );
332
333     for (i = 0; i < sizeof(update_cp_values)/sizeof(update_cp_values[0]); i++)
334     {
335         count = GetLocaleInfoW( lcid, update_cp_values[i].value | LOCALE_NOUSEROVERRIDE,
336                                 bufferW, sizeof(bufferW)/sizeof(WCHAR) );
337         RtlInitUnicodeString( &nameW, update_cp_values[i].name );
338         NtSetValueKey( hkey, &nameW, 0, REG_SZ, bufferW, count * sizeof(WCHAR) );
339     }
340
341     NtClose( hkey );
342 }
343
344
345 /***********************************************************************
346  *           find_language_id_proc
347  */
348 static BOOL CALLBACK find_language_id_proc( HMODULE hModule, LPCWSTR type,
349                                             LPCWSTR name, WORD LangID, LPARAM lParam )
350 {
351     LANG_FIND_DATA *l_data = (LANG_FIND_DATA *)lParam;
352     LCID lcid = MAKELCID(LangID, SORT_DEFAULT);
353     WCHAR buf_language[128];
354     WCHAR buf_country[128];
355     WCHAR buf_en_language[128];
356
357     if(PRIMARYLANGID(LangID) == LANG_NEUTRAL)
358         return TRUE; /* continue search */
359
360     buf_language[0] = 0;
361     buf_country[0] = 0;
362
363     GetLocaleInfoW(lcid, LOCALE_SISO639LANGNAME|LOCALE_NOUSEROVERRIDE,
364                    buf_language, sizeof(buf_language)/sizeof(WCHAR));
365     GetLocaleInfoW(lcid, LOCALE_SISO3166CTRYNAME|LOCALE_NOUSEROVERRIDE,
366                    buf_country, sizeof(buf_country)/sizeof(WCHAR));
367
368     if(l_data->lang[0] && !strcmpiW(l_data->lang, buf_language))
369     {
370         if(l_data->country[0])
371         {
372             if(!strcmpiW(l_data->country, buf_country))
373             {
374                 l_data->found_lang_id[0] = LangID;
375                 l_data->n_found = 1;
376                 TRACE("Found id %04X for lang %s country %s\n",
377                       LangID, debugstr_w(l_data->lang), debugstr_w(l_data->country));
378                 return FALSE; /* stop enumeration */
379             }
380         }
381         else goto found; /* l_data->country not specified */
382     }
383
384     /* Just in case, check LOCALE_SENGLANGUAGE too,
385      * in hope that possible alias name might have that value.
386      */
387     buf_en_language[0] = 0;
388     GetLocaleInfoW(lcid, LOCALE_SENGLANGUAGE|LOCALE_NOUSEROVERRIDE,
389                    buf_en_language, sizeof(buf_en_language)/sizeof(WCHAR));
390
391     if(l_data->lang[0] && !strcmpiW(l_data->lang, buf_en_language)) goto found;
392     return TRUE;  /* not found, continue search */
393
394 found:
395     l_data->found_lang_id[l_data->n_found] = LangID;
396     l_data->n_found++;
397     TRACE("Found id %04X for lang %s\n", LangID, debugstr_w(l_data->lang));
398     return (l_data->n_found < NLS_MAX_LANGUAGES); /* continue search, unless we have enough */
399 }
400
401
402 /***********************************************************************
403  *           get_language_id
404  *
405  * INPUT:
406  *      Lang: a string whose two first chars are the iso name of a language.
407  *      Country: a string whose two first chars are the iso name of country
408  *      Charset: a string defining the chosen charset encoding
409  *      Dialect: a string defining a variation of the locale
410  *
411  *      all those values are from the standardized format of locale
412  *      name in unix which is: Lang[_Country][.Charset][@Dialect]
413  *
414  * RETURNS:
415  *      the numeric code of the language used by Windows
416  *
417  * FIXME: Charset and Dialect are not handled
418  */
419 static LANGID get_language_id(LPCSTR Lang, LPCSTR Country, LPCSTR Charset, LPCSTR Dialect)
420 {
421     LANG_FIND_DATA l_data;
422
423     if(!Lang)
424     {
425         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
426         goto END;
427     }
428
429     l_data.n_found = 0;
430     strcpynAtoW(l_data.lang, Lang, sizeof(l_data.lang));
431
432     if (Country) strcpynAtoW(l_data.country, Country, sizeof(l_data.country));
433     else l_data.country[0] = 0;
434
435     EnumResourceLanguagesW(kernel32_handle, (LPCWSTR)RT_STRING, (LPCWSTR)LOCALE_ILANGUAGE,
436                            find_language_id_proc, (LPARAM)&l_data);
437
438     if (l_data.n_found == 1) goto END;
439
440     if(!l_data.n_found)
441     {
442         if(l_data.country[0])
443         {
444             /* retry without country name */
445             l_data.country[0] = 0;
446             EnumResourceLanguagesW(kernel32_handle, (LPCWSTR)RT_STRING, (LPCWSTR)LOCALE_ILANGUAGE,
447                                    find_language_id_proc, (LONG)&l_data);
448             if (!l_data.n_found)
449             {
450                 MESSAGE("Warning: Language '%s_%s' was not recognized, defaulting to English.\n",
451                         Lang, Country);
452                 l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
453             }
454             else MESSAGE("Warning: Language '%s_%s' was not recognized, defaulting to '%s'.\n",
455                          Lang, Country, debugstr_lang(l_data.found_lang_id[0]) );
456         }
457         else
458         {
459             MESSAGE("Warning: Language '%s' was not recognized, defaulting to English.\n", Lang);
460             l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
461         }
462     }
463     else
464     {
465         int i;
466
467         if (Country && Country[0])
468             MESSAGE("For language '%s_%s' several language ids were found:\n", Lang, Country);
469         else
470             MESSAGE("For language '%s' several language ids were found:\n", Lang);
471
472         /* print a list of languages with their description */
473         for (i = 0; i < l_data.n_found; i++)
474         {
475             WCHAR buffW[128];
476             char buffA[128];
477             GetLocaleInfoW( MAKELCID( l_data.found_lang_id[i], SORT_DEFAULT ),
478                            LOCALE_SLANGUAGE|LOCALE_NOUSEROVERRIDE, buffW, sizeof(buffW)/sizeof(WCHAR));
479             strcpyWtoA( buffA, buffW );
480             MESSAGE( "   %s (%04X) - %s\n", debugstr_lang(l_data.found_lang_id[i]),
481                      l_data.found_lang_id[i], buffA );
482         }
483         MESSAGE("Defaulting to '%s'. You should specify the exact language you want\n"
484                 "by defining your LANG environment variable like this: LANG=%s\n",
485                 debugstr_lang(l_data.found_lang_id[0]), debugstr_lang(l_data.found_lang_id[0]) );
486     }
487 END:
488     TRACE("Returning %04X (%s)\n", l_data.found_lang_id[0], debugstr_lang(l_data.found_lang_id[0]));
489     return l_data.found_lang_id[0];
490 }
491
492
493 /***********************************************************************
494  *              charset_cmp (internal)
495  */
496 static int charset_cmp( const void *name, const void *entry )
497 {
498     const struct charset_entry *charset = (const struct charset_entry *)entry;
499     return strcasecmp( (const char *)name, charset->charset_name );
500 }
501
502 /***********************************************************************
503  *              get_env_lcid
504  */
505 static LCID get_env_lcid( UINT *unix_cp, const char *env_str )
506 {
507     char *buf, *lang,*country,*charset,*dialect,*next;
508     LCID ret = 0;
509
510     if ((lang = getenv( "LC_ALL" )) ||
511         (env_str && (lang = getenv( env_str ))) ||
512         (lang = getenv( "LANG" )))
513     {
514         if (!strcmp(lang,"POSIX") || !strcmp(lang,"C")) goto done;
515
516         buf = RtlAllocateHeap( GetProcessHeap(), 0, strlen(lang) + 1 );
517         strcpy( buf, lang );
518         lang=buf;
519
520         do {
521             next=strchr(lang,':'); if (next) *next++='\0';
522             dialect=strchr(lang,'@'); if (dialect) *dialect++='\0';
523             charset=strchr(lang,'.'); if (charset) *charset++='\0';
524             country=strchr(lang,'_'); if (country) *country++='\0';
525
526             ret = get_language_id(lang, country, charset, dialect);
527             if (ret && charset && unix_cp)
528             {
529                 const struct charset_entry *entry;
530                 char charset_name[16];
531                 size_t i, j;
532
533                 /* remove punctuation characters from charset name */
534                 for (i = j = 0; charset[i] && j < sizeof(charset_name)-1; i++)
535                     if (isalnum(charset[i])) charset_name[j++] = charset[i];
536                 charset_name[j] = 0;
537
538                 entry = bsearch( charset_name, charset_names,
539                                  sizeof(charset_names)/sizeof(charset_names[0]),
540                                  sizeof(charset_names[0]), charset_cmp );
541                 if (entry)
542                 {
543                     *unix_cp = entry->codepage;
544                     TRACE("charset %s was mapped to cp %u\n", charset, *unix_cp);
545                 }
546                 else
547                     FIXME("charset %s was not recognized\n", charset);
548             }
549
550             lang=next;
551         } while (lang && !ret);
552
553         if (!ret) MESSAGE("Warning: language '%s' not recognized, defaulting to English\n", buf);
554         RtlFreeHeap( GetProcessHeap(), 0, buf );
555     }
556
557  done:
558     if (!ret) ret = MAKELCID( MAKELANGID(LANG_ENGLISH,SUBLANG_DEFAULT), SORT_DEFAULT) ;
559     return ret;
560 }
561
562
563 /***********************************************************************
564  *              GetUserDefaultLangID (KERNEL32.@)
565  *
566  * Get the default language Id for the current user.
567  *
568  * PARAMS
569  *  None.
570  *
571  * RETURNS
572  *  The current LANGID of the default language for the current user.
573  */
574 LANGID WINAPI GetUserDefaultLangID(void)
575 {
576     return LANGIDFROMLCID(GetUserDefaultLCID());
577 }
578
579
580 /***********************************************************************
581  *              GetSystemDefaultLangID (KERNEL32.@)
582  *
583  * Get the default language Id for the system.
584  *
585  * PARAMS
586  *  None.
587  *
588  * RETURNS
589  *  The current LANGID of the default language for the system.
590  */
591 LANGID WINAPI GetSystemDefaultLangID(void)
592 {
593     return LANGIDFROMLCID(GetSystemDefaultLCID());
594 }
595
596
597 /***********************************************************************
598  *              GetUserDefaultLCID (KERNEL32.@)
599  *
600  * Get the default locale Id for the current user.
601  *
602  * PARAMS
603  *  None.
604  *
605  * RETURNS
606  *  The current LCID of the default locale for the current user.
607  */
608 LCID WINAPI GetUserDefaultLCID(void)
609 {
610     LCID lcid;
611     NtQueryDefaultLocale( TRUE, &lcid );
612     return lcid;
613 }
614
615
616 /***********************************************************************
617  *              GetSystemDefaultLCID (KERNEL32.@)
618  *
619  * Get the default locale Id for the system.
620  *
621  * PARAMS
622  *  None.
623  *
624  * RETURNS
625  *  The current LCID of the default locale for the system.
626  */
627 LCID WINAPI GetSystemDefaultLCID(void)
628 {
629     LCID lcid;
630     NtQueryDefaultLocale( FALSE, &lcid );
631     return lcid;
632 }
633
634
635 /***********************************************************************
636  *              GetUserDefaultUILanguage (KERNEL32.@)
637  *
638  * Get the default user interface language Id for the current user.
639  *
640  * PARAMS
641  *  None.
642  *
643  * RETURNS
644  *  The current LANGID of the default UI language for the current user.
645  */
646 LANGID WINAPI GetUserDefaultUILanguage(void)
647 {
648     LANGID lang;
649     NtQueryDefaultUILanguage( &lang );
650     return lang;
651 }
652
653
654 /***********************************************************************
655  *              GetSystemDefaultUILanguage (KERNEL32.@)
656  *
657  * Get the default user interface language Id for the system.
658  *
659  * PARAMS
660  *  None.
661  *
662  * RETURNS
663  *  The current LANGID of the default UI language for the system. This is
664  *  typically the same language used during the installation process.
665  */
666 LANGID WINAPI GetSystemDefaultUILanguage(void)
667 {
668     LANGID lang;
669     NtQueryInstallUILanguage( &lang );
670     return lang;
671 }
672
673
674 /******************************************************************************
675  *              get_locale_value_name
676  *
677  * Gets the registry value name for a given lctype.
678  */
679 static const WCHAR *get_locale_value_name( DWORD lctype )
680 {
681     static const WCHAR iCalendarTypeW[] = {'i','C','a','l','e','n','d','a','r','T','y','p','e',0};
682     static const WCHAR iCountryW[] = {'i','C','o','u','n','t','r','y',0};
683     static const WCHAR iCurrDigitsW[] = {'i','C','u','r','r','D','i','g','i','t','s',0};
684     static const WCHAR iCurrencyW[] = {'i','C','u','r','r','e','n','c','y',0};
685     static const WCHAR iDateW[] = {'i','D','a','t','e',0};
686     static const WCHAR iDigitsW[] = {'i','D','i','g','i','t','s',0};
687     static const WCHAR iFirstDayOfWeekW[] = {'i','F','i','r','s','t','D','a','y','O','f','W','e','e','k',0};
688     static const WCHAR iFirstWeekOfYearW[] = {'i','F','i','r','s','t','W','e','e','k','O','f','Y','e','a','r',0};
689     static const WCHAR iLDateW[] = {'i','L','D','a','t','e',0};
690     static const WCHAR iLZeroW[] = {'i','L','Z','e','r','o',0};
691     static const WCHAR iMeasureW[] = {'i','M','e','a','s','u','r','e',0};
692     static const WCHAR iNegCurrW[] = {'i','N','e','g','C','u','r','r',0};
693     static const WCHAR iNegNumberW[] = {'i','N','e','g','N','u','m','b','e','r',0};
694     static const WCHAR iPaperSizeW[] = {'i','P','a','p','e','r','S','i','z','e',0};
695     static const WCHAR iTLZeroW[] = {'i','T','L','Z','e','r','o',0};
696     static const WCHAR iTimePrefixW[] = {'i','T','i','m','e','P','r','e','f','i','x',0};
697     static const WCHAR iTimeW[] = {'i','T','i','m','e',0};
698     static const WCHAR s1159W[] = {'s','1','1','5','9',0};
699     static const WCHAR s2359W[] = {'s','2','3','5','9',0};
700     static const WCHAR sCountryW[] = {'s','C','o','u','n','t','r','y',0};
701     static const WCHAR sCurrencyW[] = {'s','C','u','r','r','e','n','c','y',0};
702     static const WCHAR sDateW[] = {'s','D','a','t','e',0};
703     static const WCHAR sDecimalW[] = {'s','D','e','c','i','m','a','l',0};
704     static const WCHAR sGroupingW[] = {'s','G','r','o','u','p','i','n','g',0};
705     static const WCHAR sLanguageW[] = {'s','L','a','n','g','u','a','g','e',0};
706     static const WCHAR sListW[] = {'s','L','i','s','t',0};
707     static const WCHAR sLongDateW[] = {'s','L','o','n','g','D','a','t','e',0};
708     static const WCHAR sMonDecimalSepW[] = {'s','M','o','n','D','e','c','i','m','a','l','S','e','p',0};
709     static const WCHAR sMonGroupingW[] = {'s','M','o','n','G','r','o','u','p','i','n','g',0};
710     static const WCHAR sMonThousandSepW[] = {'s','M','o','n','T','h','o','u','s','a','n','d','S','e','p',0};
711     static const WCHAR sNativeDigitsW[] = {'s','N','a','t','i','v','e','D','i','g','i','t','s',0};
712     static const WCHAR sNegativeSignW[] = {'s','N','e','g','a','t','i','v','e','S','i','g','n',0};
713     static const WCHAR sPositiveSignW[] = {'s','P','o','s','i','t','i','v','e','S','i','g','n',0};
714     static const WCHAR sShortDateW[] = {'s','S','h','o','r','t','D','a','t','e',0};
715     static const WCHAR sThousandW[] = {'s','T','h','o','u','s','a','n','d',0};
716     static const WCHAR sTimeFormatW[] = {'s','T','i','m','e','F','o','r','m','a','t',0};
717     static const WCHAR sTimeW[] = {'s','T','i','m','e',0};
718     static const WCHAR sYearMonthW[] = {'s','Y','e','a','r','M','o','n','t','h',0};
719     static const WCHAR NumShapeW[] = {'N','u','m','s','h','a','p','e',0};
720
721     switch (lctype)
722     {
723     /* These values are used by SetLocaleInfo and GetLocaleInfo, and
724      * the values are stored in the registry, confirmed under Windows.
725      */
726     case LOCALE_ICALENDARTYPE:    return iCalendarTypeW;
727     case LOCALE_ICURRDIGITS:      return iCurrDigitsW;
728     case LOCALE_ICURRENCY:        return iCurrencyW;
729     case LOCALE_IDIGITS:          return iDigitsW;
730     case LOCALE_IFIRSTDAYOFWEEK:  return iFirstDayOfWeekW;
731     case LOCALE_IFIRSTWEEKOFYEAR: return iFirstWeekOfYearW;
732     case LOCALE_ILZERO:           return iLZeroW;
733     case LOCALE_IMEASURE:         return iMeasureW;
734     case LOCALE_INEGCURR:         return iNegCurrW;
735     case LOCALE_INEGNUMBER:       return iNegNumberW;
736     case LOCALE_IPAPERSIZE:       return iPaperSizeW;
737     case LOCALE_ITIME:            return iTimeW;
738     case LOCALE_S1159:            return s1159W;
739     case LOCALE_S2359:            return s2359W;
740     case LOCALE_SCURRENCY:        return sCurrencyW;
741     case LOCALE_SDATE:            return sDateW;
742     case LOCALE_SDECIMAL:         return sDecimalW;
743     case LOCALE_SGROUPING:        return sGroupingW;
744     case LOCALE_SLIST:            return sListW;
745     case LOCALE_SLONGDATE:        return sLongDateW;
746     case LOCALE_SMONDECIMALSEP:   return sMonDecimalSepW;
747     case LOCALE_SMONGROUPING:     return sMonGroupingW;
748     case LOCALE_SMONTHOUSANDSEP:  return sMonThousandSepW;
749     case LOCALE_SNEGATIVESIGN:    return sNegativeSignW;
750     case LOCALE_SPOSITIVESIGN:    return sPositiveSignW;
751     case LOCALE_SSHORTDATE:       return sShortDateW;
752     case LOCALE_STHOUSAND:        return sThousandW;
753     case LOCALE_STIME:            return sTimeW;
754     case LOCALE_STIMEFORMAT:      return sTimeFormatW;
755     case LOCALE_SYEARMONTH:       return sYearMonthW;
756
757     /* The following are not listed under MSDN as supported,
758      * but seem to be used and also stored in the registry.
759      */
760     case LOCALE_ICOUNTRY:         return iCountryW;
761     case LOCALE_IDATE:            return iDateW;
762     case LOCALE_ILDATE:           return iLDateW;
763     case LOCALE_ITLZERO:          return iTLZeroW;
764     case LOCALE_SCOUNTRY:         return sCountryW;
765     case LOCALE_SLANGUAGE:        return sLanguageW;
766
767     /* The following are used in XP and later */
768     case LOCALE_IDIGITSUBSTITUTION: return NumShapeW;
769     case LOCALE_SNATIVEDIGITS:      return sNativeDigitsW;
770     case LOCALE_ITIMEMARKPOSN:      return iTimePrefixW;
771     }
772     return NULL;
773 }
774
775
776 /******************************************************************************
777  *              get_registry_locale_info
778  *
779  * Retrieve user-modified locale info from the registry.
780  * Return length, 0 on error, -1 if not found.
781  */
782 static INT get_registry_locale_info( LPCWSTR value, LPWSTR buffer, INT len )
783 {
784     DWORD size;
785     INT ret;
786     HKEY hkey;
787     NTSTATUS status;
788     UNICODE_STRING nameW;
789     KEY_VALUE_PARTIAL_INFORMATION *info;
790     static const int info_size = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data);
791
792     if (!(hkey = create_registry_key())) return -1;
793
794     RtlInitUnicodeString( &nameW, value );
795     size = info_size + len * sizeof(WCHAR);
796
797     if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
798     {
799         NtClose( hkey );
800         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
801         return 0;
802     }
803
804     status = NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, info, size, &size );
805     if (status == STATUS_BUFFER_OVERFLOW && !buffer) status = 0;
806
807     if (!status)
808     {
809         ret = (size - info_size) / sizeof(WCHAR);
810         /* append terminating null if needed */
811         if (!ret || ((WCHAR *)info->Data)[ret-1])
812         {
813             if (ret < len || !buffer) ret++;
814             else
815             {
816                 SetLastError( ERROR_INSUFFICIENT_BUFFER );
817                 ret = 0;
818             }
819         }
820         if (ret && buffer)
821         {
822             memcpy( buffer, info->Data, (ret-1) * sizeof(WCHAR) );
823             buffer[ret-1] = 0;
824         }
825     }
826     else
827     {
828         if (status == STATUS_OBJECT_NAME_NOT_FOUND) ret = -1;
829         else
830         {
831             SetLastError( RtlNtStatusToDosError(status) );
832             ret = 0;
833         }
834     }
835     NtClose( hkey );
836     HeapFree( GetProcessHeap(), 0, info );
837     return ret;
838 }
839
840
841 /******************************************************************************
842  *              GetLocaleInfoA (KERNEL32.@)
843  *
844  * Get information about an aspect of a locale.
845  *
846  * PARAMS
847  *  lcid   [I] LCID of the locale
848  *  lctype [I] LCTYPE_ flags from "winnls.h"
849  *  buffer [O] Destination for the information
850  *  len    [I] Length of buffer in characters
851  *
852  * RETURNS
853  *  Success: The size of the data requested. If buffer is non-NULL, it is filled
854  *           with the information.
855  *  Failure: 0. Use GetLastError() to determine the cause.
856  *
857  * NOTES
858  *  - LOCALE_NEUTRAL is equal to LOCALE_SYSTEM_DEFAULT
859  *  - The string returned is NUL terminated, except for LOCALE_FONTSIGNATURE,
860  *    which is a bit string.
861  */
862 INT WINAPI GetLocaleInfoA( LCID lcid, LCTYPE lctype, LPSTR buffer, INT len )
863 {
864     WCHAR *bufferW;
865     INT lenW, ret;
866
867     TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d)\n", lcid, lctype, buffer, len );
868
869     if (len < 0 || (len && !buffer))
870     {
871         SetLastError( ERROR_INVALID_PARAMETER );
872         return 0;
873     }
874     if (!len) buffer = NULL;
875
876     if (!(lenW = GetLocaleInfoW( lcid, lctype, NULL, 0 ))) return 0;
877
878     if (!(bufferW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
879     {
880         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
881         return 0;
882     }
883     if ((ret = GetLocaleInfoW( lcid, lctype, bufferW, lenW )))
884     {
885         if ((lctype & LOCALE_RETURN_NUMBER) ||
886             ((lctype & ~LOCALE_LOCALEINFOFLAGSMASK) == LOCALE_FONTSIGNATURE))
887         {
888             /* it's not an ASCII string, just bytes */
889             ret *= sizeof(WCHAR);
890             if (buffer)
891             {
892                 if (ret <= len) memcpy( buffer, bufferW, ret );
893                 else
894                 {
895                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
896                     ret = 0;
897                 }
898             }
899         }
900         else
901         {
902             UINT codepage = CP_ACP;
903             if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
904             ret = WideCharToMultiByte( codepage, 0, bufferW, ret, buffer, len, NULL, NULL );
905         }
906     }
907     HeapFree( GetProcessHeap(), 0, bufferW );
908     return ret;
909 }
910
911
912 /******************************************************************************
913  *              GetLocaleInfoW (KERNEL32.@)
914  *
915  * See GetLocaleInfoA.
916  */
917 INT WINAPI GetLocaleInfoW( LCID lcid, LCTYPE lctype, LPWSTR buffer, INT len )
918 {
919     LANGID lang_id;
920     HRSRC hrsrc;
921     HGLOBAL hmem;
922     INT ret;
923     UINT lcflags;
924     const WCHAR *p;
925     unsigned int i;
926
927     if (len < 0 || (len && !buffer))
928     {
929         SetLastError( ERROR_INVALID_PARAMETER );
930         return 0;
931     }
932     if (!len) buffer = NULL;
933
934     lcid = ConvertDefaultLocale(lcid);
935
936     lcflags = lctype & LOCALE_LOCALEINFOFLAGSMASK;
937     lctype &= 0xffff;
938
939     TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d)\n", lcid, lctype, buffer, len );
940
941     /* first check for overrides in the registry */
942
943     if (!(lcflags & LOCALE_NOUSEROVERRIDE) && lcid == GetUserDefaultLCID())
944     {
945         const WCHAR *value = get_locale_value_name(lctype);
946
947         if (value)
948         {
949             if (lcflags & LOCALE_RETURN_NUMBER)
950             {
951                 WCHAR tmp[16];
952                 ret = get_registry_locale_info( value, tmp, sizeof(tmp)/sizeof(WCHAR) );
953                 if (ret > 0)
954                 {
955                     WCHAR *end;
956                     UINT number = strtolW( tmp, &end, 10 );
957                     if (*end)  /* invalid number */
958                     {
959                         SetLastError( ERROR_INVALID_FLAGS );
960                         return 0;
961                     }
962                     ret = sizeof(UINT)/sizeof(WCHAR);
963                     if (!buffer) return ret;
964                     if (ret > len)
965                     {
966                         SetLastError( ERROR_INSUFFICIENT_BUFFER );
967                         return 0;
968                     }
969                     memcpy( buffer, &number, sizeof(number) );
970                 }
971             }
972             else ret = get_registry_locale_info( value, buffer, len );
973
974             if (ret != -1) return ret;
975         }
976     }
977
978     /* now load it from kernel resources */
979
980     lang_id = LANGIDFROMLCID( lcid );
981
982     /* replace SUBLANG_NEUTRAL by SUBLANG_DEFAULT */
983     if (SUBLANGID(lang_id) == SUBLANG_NEUTRAL)
984         lang_id = MAKELANGID(PRIMARYLANGID(lang_id), SUBLANG_DEFAULT);
985
986     if (!(hrsrc = FindResourceExW( kernel32_handle, (LPWSTR)RT_STRING,
987                                    (LPCWSTR)((lctype >> 4) + 1), lang_id )))
988     {
989         SetLastError( ERROR_INVALID_FLAGS );  /* no such lctype */
990         return 0;
991     }
992     if (!(hmem = LoadResource( kernel32_handle, hrsrc )))
993         return 0;
994
995     p = LockResource( hmem );
996     for (i = 0; i < (lctype & 0x0f); i++) p += *p + 1;
997
998     if (lcflags & LOCALE_RETURN_NUMBER) ret = sizeof(UINT)/sizeof(WCHAR);
999     else ret = (lctype == LOCALE_FONTSIGNATURE) ? *p : *p + 1;
1000
1001     if (!buffer) return ret;
1002
1003     if (ret > len)
1004     {
1005         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1006         return 0;
1007     }
1008
1009     if (lcflags & LOCALE_RETURN_NUMBER)
1010     {
1011         UINT number;
1012         WCHAR *end, *tmp = HeapAlloc( GetProcessHeap(), 0, (*p + 1) * sizeof(WCHAR) );
1013         if (!tmp) return 0;
1014         memcpy( tmp, p + 1, *p * sizeof(WCHAR) );
1015         tmp[*p] = 0;
1016         number = strtolW( tmp, &end, 10 );
1017         if (!*end)
1018             memcpy( buffer, &number, sizeof(number) );
1019         else  /* invalid number */
1020         {
1021             SetLastError( ERROR_INVALID_FLAGS );
1022             ret = 0;
1023         }
1024         HeapFree( GetProcessHeap(), 0, tmp );
1025
1026         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning number %d\n",
1027                lcid, lctype, buffer, len, number );
1028     }
1029     else
1030     {
1031         memcpy( buffer, p + 1, *p * sizeof(WCHAR) );
1032         if (lctype != LOCALE_FONTSIGNATURE) buffer[ret-1] = 0;
1033
1034         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning %d %s\n",
1035                lcid, lctype, buffer, len, ret, debugstr_w(buffer) );
1036     }
1037     return ret;
1038 }
1039
1040
1041 /******************************************************************************
1042  *              SetLocaleInfoA  [KERNEL32.@]
1043  *
1044  * Set information about an aspect of a locale.
1045  *
1046  * PARAMS
1047  *  lcid   [I] LCID of the locale
1048  *  lctype [I] LCTYPE_ flags from "winnls.h"
1049  *  data   [I] Information to set
1050  *
1051  * RETURNS
1052  *  Success: TRUE. The information given will be returned by GetLocaleInfoA()
1053  *           whenever it is called without LOCALE_NOUSEROVERRIDE.
1054  *  Failure: FALSE. Use GetLastError() to determine the cause.
1055  *
1056  * NOTES
1057  *  - Values are only be set for the current user locale; the system locale
1058  *  settings cannot be changed.
1059  *  - Any settings changed by this call are lost when the locale is changed by
1060  *  the control panel (in Wine, this happens every time you change LANG).
1061  *  - The native implementation of this function does not check that lcid matches
1062  *  the current user locale, and simply sets the new values. Wine warns you in
1063  *  this case, but behaves the same.
1064  */
1065 BOOL WINAPI SetLocaleInfoA(LCID lcid, LCTYPE lctype, LPCSTR data)
1066 {
1067     UINT codepage = CP_ACP;
1068     WCHAR *strW;
1069     DWORD len;
1070     BOOL ret;
1071
1072     lcid = ConvertDefaultLocale(lcid);
1073
1074     if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
1075
1076     if (!data)
1077     {
1078         SetLastError( ERROR_INVALID_PARAMETER );
1079         return FALSE;
1080     }
1081     len = MultiByteToWideChar( codepage, 0, data, -1, NULL, 0 );
1082     if (!(strW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1083     {
1084         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1085         return FALSE;
1086     }
1087     MultiByteToWideChar( codepage, 0, data, -1, strW, len );
1088     ret = SetLocaleInfoW( lcid, lctype, strW );
1089     HeapFree( GetProcessHeap(), 0, strW );
1090     return ret;
1091 }
1092
1093
1094 /******************************************************************************
1095  *              SetLocaleInfoW  (KERNEL32.@)
1096  *
1097  * See SetLocaleInfoA.
1098  */
1099 BOOL WINAPI SetLocaleInfoW( LCID lcid, LCTYPE lctype, LPCWSTR data )
1100 {
1101     const WCHAR *value;
1102     static const WCHAR intlW[] = {'i','n','t','l',0 };
1103     UNICODE_STRING valueW;
1104     NTSTATUS status;
1105     HKEY hkey;
1106
1107     lcid = ConvertDefaultLocale(lcid);
1108
1109     lctype &= 0xffff;
1110     value = get_locale_value_name( lctype );
1111
1112     if (!data || !value)
1113     {
1114         SetLastError( ERROR_INVALID_PARAMETER );
1115         return FALSE;
1116     }
1117
1118     if (lctype == LOCALE_IDATE || lctype == LOCALE_ILDATE)
1119     {
1120         SetLastError( ERROR_INVALID_FLAGS );
1121         return FALSE;
1122     }
1123
1124     if (lcid != GetUserDefaultLCID())
1125     {
1126         /* Windows does not check that the lcid matches the current lcid */
1127         WARN("locale 0x%08lx isn't the current locale (0x%08lx), setting anyway!\n",
1128              lcid, GetUserDefaultLCID());
1129     }
1130
1131     TRACE("setting %lx (%s) to %s\n", lctype, debugstr_w(value), debugstr_w(data) );
1132
1133     /* FIXME: should check that data to set is sane */
1134
1135     /* FIXME: profile functions should map to registry */
1136     WriteProfileStringW( intlW, value, data );
1137
1138     if (!(hkey = create_registry_key())) return FALSE;
1139     RtlInitUnicodeString( &valueW, value );
1140     status = NtSetValueKey( hkey, &valueW, 0, REG_SZ, data, (strlenW(data)+1)*sizeof(WCHAR) );
1141
1142     if (lctype == LOCALE_SSHORTDATE || lctype == LOCALE_SLONGDATE)
1143     {
1144       /* Set I-value from S value */
1145       WCHAR *lpD, *lpM, *lpY;
1146       WCHAR szBuff[2];
1147
1148       lpD = strrchrW(data, 'd');
1149       lpM = strrchrW(data, 'M');
1150       lpY = strrchrW(data, 'y');
1151
1152       if (lpD <= lpM)
1153       {
1154         szBuff[0] = '1'; /* D-M-Y */
1155       }
1156       else
1157       {
1158         if (lpY <= lpM)
1159           szBuff[0] = '2'; /* Y-M-D */
1160         else
1161           szBuff[0] = '0'; /* M-D-Y */
1162       }
1163
1164       szBuff[1] = '\0';
1165
1166       if (lctype == LOCALE_SSHORTDATE)
1167         lctype = LOCALE_IDATE;
1168       else
1169         lctype = LOCALE_ILDATE;
1170
1171       value = get_locale_value_name( lctype );
1172
1173       WriteProfileStringW( intlW, value, szBuff );
1174
1175       RtlInitUnicodeString( &valueW, value );
1176       status = NtSetValueKey( hkey, &valueW, 0, REG_SZ, szBuff, sizeof(szBuff) );
1177     }
1178
1179     NtClose( hkey );
1180
1181     if (status) SetLastError( RtlNtStatusToDosError(status) );
1182     return !status;
1183 }
1184
1185
1186 /******************************************************************************
1187  *              GetACP   (KERNEL32.@)
1188  *
1189  * Get the current Ansi code page Id for the system.
1190  *
1191  * PARAMS
1192  *  None.
1193  *
1194  * RETURNS
1195  *    The current Ansi code page identifier for the system.
1196  */
1197 UINT WINAPI GetACP(void)
1198 {
1199     assert( ansi_cptable );
1200     return ansi_cptable->info.codepage;
1201 }
1202
1203
1204 /******************************************************************************
1205  *              SetCPGlobal   (KERNEL32.@)
1206  *
1207  * Set the current Ansi code page Id for the system.
1208  *
1209  * PARAMS
1210  *    acp [I] code page ID to be the new ACP.
1211  *
1212  * RETURNS
1213  *    The previous ACP.
1214  */
1215 UINT WINAPI SetCPGlobal( UINT acp )
1216 {
1217     UINT ret = GetACP();
1218     const union cptable *new_cptable = wine_cp_get_table( acp );
1219
1220     if (new_cptable) ansi_cptable = new_cptable;
1221     return ret;
1222 }
1223
1224
1225 /***********************************************************************
1226  *              GetOEMCP   (KERNEL32.@)
1227  *
1228  * Get the current OEM code page Id for the system.
1229  *
1230  * PARAMS
1231  *  None.
1232  *
1233  * RETURNS
1234  *    The current OEM code page identifier for the system.
1235  */
1236 UINT WINAPI GetOEMCP(void)
1237 {
1238     assert( oem_cptable );
1239     return oem_cptable->info.codepage;
1240 }
1241
1242
1243 /***********************************************************************
1244  *           IsValidCodePage   (KERNEL32.@)
1245  *
1246  * Determine if a given code page identifier is valid.
1247  *
1248  * PARAMS
1249  *  codepage [I] Code page Id to verify.
1250  *
1251  * RETURNS
1252  *  TRUE, If codepage is valid and available on the system,
1253  *  FALSE otherwise.
1254  */
1255 BOOL WINAPI IsValidCodePage( UINT codepage )
1256 {
1257     switch(codepage) {
1258     case CP_UTF7:
1259     case CP_UTF8:
1260         return TRUE;
1261     default:
1262         return wine_cp_get_table( codepage ) != NULL;
1263     }
1264 }
1265
1266
1267 /***********************************************************************
1268  *           IsDBCSLeadByteEx   (KERNEL32.@)
1269  *
1270  * Determine if a character is a lead byte in a given code page.
1271  *
1272  * PARAMS
1273  *  codepage [I] Code page for the test.
1274  *  testchar [I] Character to test
1275  *
1276  * RETURNS
1277  *  TRUE, if testchar is a lead byte in codepage,
1278  *  FALSE otherwise.
1279  */
1280 BOOL WINAPI IsDBCSLeadByteEx( UINT codepage, BYTE testchar )
1281 {
1282     const union cptable *table = get_codepage_table( codepage );
1283     return table && is_dbcs_leadbyte( table, testchar );
1284 }
1285
1286
1287 /***********************************************************************
1288  *           IsDBCSLeadByte   (KERNEL32.@)
1289  *           IsDBCSLeadByte   (KERNEL.207)
1290  *
1291  * Determine if a character is a lead byte.
1292  *
1293  * PARAMS
1294  *  testchar [I] Character to test
1295  *
1296  * RETURNS
1297  *  TRUE, if testchar is a lead byte in the Ansii code page,
1298  *  FALSE otherwise.
1299  */
1300 BOOL WINAPI IsDBCSLeadByte( BYTE testchar )
1301 {
1302     if (!ansi_cptable) return FALSE;
1303     return is_dbcs_leadbyte( ansi_cptable, testchar );
1304 }
1305
1306
1307 /***********************************************************************
1308  *           GetCPInfo   (KERNEL32.@)
1309  *
1310  * Get information about a code page.
1311  *
1312  * PARAMS
1313  *  codepage [I] Code page number
1314  *  cpinfo   [O] Destination for code page information
1315  *
1316  * RETURNS
1317  *  Success: TRUE. cpinfo is updated with the information about codepage.
1318  *  Failure: FALSE, if codepage is invalid or cpinfo is NULL.
1319  */
1320 BOOL WINAPI GetCPInfo( UINT codepage, LPCPINFO cpinfo )
1321 {
1322     const union cptable *table;
1323
1324     if (!cpinfo)
1325     {
1326         SetLastError( ERROR_INVALID_PARAMETER );
1327         return FALSE;
1328     }
1329
1330     if (!(table = get_codepage_table( codepage )))
1331     {
1332         switch(codepage)
1333         {
1334             case CP_UTF7:
1335             case CP_UTF8:
1336                 cpinfo->DefaultChar[0] = 0x3f;
1337                 cpinfo->DefaultChar[1] = 0;
1338                 cpinfo->LeadByte[0] = cpinfo->LeadByte[1] = 0;
1339                 cpinfo->MaxCharSize = (codepage == CP_UTF7) ? 5 : 4;
1340                 return TRUE;
1341         }
1342
1343         SetLastError( ERROR_INVALID_PARAMETER );
1344         return FALSE;
1345     }
1346     if (table->info.def_char & 0xff00)
1347     {
1348         cpinfo->DefaultChar[0] = table->info.def_char & 0xff00;
1349         cpinfo->DefaultChar[1] = table->info.def_char & 0x00ff;
1350     }
1351     else
1352     {
1353         cpinfo->DefaultChar[0] = table->info.def_char & 0xff;
1354         cpinfo->DefaultChar[1] = 0;
1355     }
1356     if ((cpinfo->MaxCharSize = table->info.char_size) == 2)
1357         memcpy( cpinfo->LeadByte, table->dbcs.lead_bytes, sizeof(cpinfo->LeadByte) );
1358     else
1359         cpinfo->LeadByte[0] = cpinfo->LeadByte[1] = 0;
1360
1361     return TRUE;
1362 }
1363
1364 /***********************************************************************
1365  *           GetCPInfoExA   (KERNEL32.@)
1366  *
1367  * Get extended information about a code page.
1368  *
1369  * PARAMS
1370  *  codepage [I] Code page number
1371  *  dwFlags  [I] Reserved, must to 0.
1372  *  cpinfo   [O] Destination for code page information
1373  *
1374  * RETURNS
1375  *  Success: TRUE. cpinfo is updated with the information about codepage.
1376  *  Failure: FALSE, if codepage is invalid or cpinfo is NULL.
1377  */
1378 BOOL WINAPI GetCPInfoExA( UINT codepage, DWORD dwFlags, LPCPINFOEXA cpinfo )
1379 {
1380     CPINFOEXW cpinfoW;
1381
1382     if (!GetCPInfoExW( codepage, dwFlags, &cpinfoW ))
1383       return FALSE;
1384
1385     /* the layout is the same except for CodePageName */
1386     memcpy(cpinfo, &cpinfoW, sizeof(CPINFOEXA));
1387     WideCharToMultiByte(CP_ACP, 0, cpinfoW.CodePageName, -1, cpinfo->CodePageName, sizeof(cpinfo->CodePageName), NULL, NULL);
1388     return TRUE;
1389 }
1390
1391 /***********************************************************************
1392  *           GetCPInfoExW   (KERNEL32.@)
1393  *
1394  * Unicode version of GetCPInfoExA.
1395  */
1396 BOOL WINAPI GetCPInfoExW( UINT codepage, DWORD dwFlags, LPCPINFOEXW cpinfo )
1397 {
1398     if (!GetCPInfo( codepage, (LPCPINFO)cpinfo ))
1399       return FALSE;
1400
1401     switch(codepage)
1402     {
1403         case CP_UTF7:
1404         {
1405             static const WCHAR utf7[] = {'U','n','i','c','o','d','e',' ','(','U','T','F','-','7',')',0};
1406
1407             cpinfo->CodePage = CP_UTF7;
1408             cpinfo->UnicodeDefaultChar = 0x3f;
1409             strcpyW(cpinfo->CodePageName, utf7);
1410             break;
1411         }
1412
1413         case CP_UTF8:
1414         {
1415             static const WCHAR utf8[] = {'U','n','i','c','o','d','e',' ','(','U','T','F','-','8',')',0};
1416
1417             cpinfo->CodePage = CP_UTF8;
1418             cpinfo->UnicodeDefaultChar = 0x3f;
1419             strcpyW(cpinfo->CodePageName, utf8);
1420             break;
1421         }
1422
1423         default:
1424         {
1425             const union cptable *table = get_codepage_table( codepage );
1426
1427             cpinfo->CodePage = table->info.codepage;
1428             cpinfo->UnicodeDefaultChar = table->info.def_unicode_char;
1429             MultiByteToWideChar( CP_ACP, 0, table->info.name, -1, cpinfo->CodePageName,
1430                                  sizeof(cpinfo->CodePageName)/sizeof(WCHAR));
1431             break;
1432         }
1433     }
1434     return TRUE;
1435 }
1436
1437 /***********************************************************************
1438  *              EnumSystemCodePagesA   (KERNEL32.@)
1439  *
1440  * Call a user defined function for every code page installed on the system.
1441  *
1442  * PARAMS
1443  *   lpfnCodePageEnum [I] User CODEPAGE_ENUMPROC to call with each found code page
1444  *   flags            [I] Reserved, set to 0.
1445  *
1446  * RETURNS
1447  *  TRUE, If all code pages have been enumerated, or
1448  *  FALSE if lpfnCodePageEnum returned FALSE to stop the enumeration.
1449  */
1450 BOOL WINAPI EnumSystemCodePagesA( CODEPAGE_ENUMPROCA lpfnCodePageEnum, DWORD flags )
1451 {
1452     const union cptable *table;
1453     char buffer[10];
1454     int index = 0;
1455
1456     for (;;)
1457     {
1458         if (!(table = wine_cp_enum_table( index++ ))) break;
1459         sprintf( buffer, "%d", table->info.codepage );
1460         if (!lpfnCodePageEnum( buffer )) break;
1461     }
1462     return TRUE;
1463 }
1464
1465
1466 /***********************************************************************
1467  *              EnumSystemCodePagesW   (KERNEL32.@)
1468  *
1469  * See EnumSystemCodePagesA.
1470  */
1471 BOOL WINAPI EnumSystemCodePagesW( CODEPAGE_ENUMPROCW lpfnCodePageEnum, DWORD flags )
1472 {
1473     const union cptable *table;
1474     WCHAR buffer[10], *p;
1475     int page, index = 0;
1476
1477     for (;;)
1478     {
1479         if (!(table = wine_cp_enum_table( index++ ))) break;
1480         p = buffer + sizeof(buffer)/sizeof(WCHAR);
1481         *--p = 0;
1482         page = table->info.codepage;
1483         do
1484         {
1485             *--p = '0' + (page % 10);
1486             page /= 10;
1487         } while( page );
1488         if (!lpfnCodePageEnum( p )) break;
1489     }
1490     return TRUE;
1491 }
1492
1493
1494 /***********************************************************************
1495  *              MultiByteToWideChar   (KERNEL32.@)
1496  *
1497  * Convert a multibyte character string into a Unicode string.
1498  *
1499  * PARAMS
1500  *   page   [I] Codepage character set to convert from
1501  *   flags  [I] Character mapping flags
1502  *   src    [I] Source string buffer
1503  *   srclen [I] Length of src, or -1 if src is NUL terminated
1504  *   dst    [O] Destination buffer
1505  *   dstlen [I] Length of dst, or 0 to compute the required length
1506  *
1507  * RETURNS
1508  *   Success: If dstlen > 0, the number of characters written to dst.
1509  *            If dstlen == 0, the number of characters needed to perform the
1510  *            conversion. In both cases the count includes the terminating NUL.
1511  *   Failure: 0. Use GetLastError() to determine the cause. Possible errors are
1512  *            ERROR_INSUFFICIENT_BUFFER, if not enough space is available in dst
1513  *            and dstlen != 0; ERROR_INVALID_PARAMETER,  if an invalid parameter
1514  *            is passed, and ERROR_NO_UNICODE_TRANSLATION if no translation is
1515  *            possible for src.
1516  */
1517 INT WINAPI MultiByteToWideChar( UINT page, DWORD flags, LPCSTR src, INT srclen,
1518                                 LPWSTR dst, INT dstlen )
1519 {
1520     const union cptable *table;
1521     int ret;
1522
1523     if (!src || (!dst && dstlen))
1524     {
1525         SetLastError( ERROR_INVALID_PARAMETER );
1526         return 0;
1527     }
1528
1529     if (srclen < 0) srclen = strlen(src) + 1;
1530
1531     if (flags & MB_USEGLYPHCHARS) FIXME("MB_USEGLYPHCHARS not supported\n");
1532
1533     switch(page)
1534     {
1535     case CP_SYMBOL:
1536         if( flags)
1537         {
1538             SetLastError( ERROR_INVALID_PARAMETER );
1539             return 0;
1540         }
1541         ret = wine_cpsymbol_mbstowcs( src, srclen, dst, dstlen );
1542         break;
1543     case CP_UTF7:
1544         FIXME("UTF-7 not supported\n");
1545         SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1546         return 0;
1547     case CP_UNIXCP:
1548         if (unix_cptable)
1549         {
1550             ret = wine_cp_mbstowcs( unix_cptable, flags, src, srclen, dst, dstlen );
1551             break;
1552         }
1553         /* fall through */
1554     case CP_UTF8:
1555         ret = wine_utf8_mbstowcs( flags, src, srclen, dst, dstlen );
1556         break;
1557     default:
1558         if (!(table = get_codepage_table( page )))
1559         {
1560             SetLastError( ERROR_INVALID_PARAMETER );
1561             return 0;
1562         }
1563         ret = wine_cp_mbstowcs( table, flags, src, srclen, dst, dstlen );
1564         break;
1565     }
1566
1567     if (ret < 0)
1568     {
1569         switch(ret)
1570         {
1571         case -1: SetLastError( ERROR_INSUFFICIENT_BUFFER ); break;
1572         case -2: SetLastError( ERROR_NO_UNICODE_TRANSLATION ); break;
1573         }
1574         ret = 0;
1575     }
1576     return ret;
1577 }
1578
1579
1580 /***********************************************************************
1581  *              WideCharToMultiByte   (KERNEL32.@)
1582  *
1583  * Convert a Unicode character string into a multibyte string.
1584  *
1585  * PARAMS
1586  *   page    [I] Code page character set to convert to
1587  *   flags   [I] Mapping Flags (MB_ constants from "winnls.h").
1588  *   src     [I] Source string buffer
1589  *   srclen  [I] Length of src, or -1 if src is NUL terminated
1590  *   dst     [O] Destination buffer
1591  *   dstlen  [I] Length of dst, or 0 to compute the required length
1592  *   defchar [I] Default character to use for conversion if no exact
1593  *                  conversion can be made
1594  *   used    [O] Set if default character was used in the conversion
1595  *
1596  * RETURNS
1597  *   Success: If dstlen > 0, the number of characters written to dst.
1598  *            If dstlen == 0, number of characters needed to perform the
1599  *            conversion. In both cases the count includes the terminating NUL.
1600  *   Failure: 0. Use GetLastError() to determine the cause. Possible errors are
1601  *            ERROR_INSUFFICIENT_BUFFER, if not enough space is available in dst
1602  *            and dstlen != 0, and ERROR_INVALID_PARAMETER, if an invalid
1603  *            parameter was given.
1604  */
1605 INT WINAPI WideCharToMultiByte( UINT page, DWORD flags, LPCWSTR src, INT srclen,
1606                                 LPSTR dst, INT dstlen, LPCSTR defchar, BOOL *used )
1607 {
1608     const union cptable *table;
1609     int ret, used_tmp;
1610
1611     if (!src || (!dst && dstlen))
1612     {
1613         SetLastError( ERROR_INVALID_PARAMETER );
1614         return 0;
1615     }
1616
1617     if (srclen < 0) srclen = strlenW(src) + 1;
1618
1619     switch(page)
1620     {
1621     case CP_SYMBOL:
1622         if( flags || defchar || used)
1623         {
1624             SetLastError( ERROR_INVALID_PARAMETER );
1625             return 0;
1626         }
1627         ret = wine_cpsymbol_wcstombs( src, srclen, dst, dstlen );
1628         break;
1629     case CP_UTF7:
1630         FIXME("UTF-7 not supported\n");
1631         SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1632         return 0;
1633     case CP_UNIXCP:
1634         if (unix_cptable)
1635         {
1636             ret = wine_cp_wcstombs( unix_cptable, flags, src, srclen, dst, dstlen,
1637                                     defchar, used ? &used_tmp : NULL );
1638             break;
1639         }
1640         /* fall through */
1641     case CP_UTF8:
1642         if (used) *used = FALSE;  /* all chars are valid for UTF-8 */
1643         ret = wine_utf8_wcstombs( src, srclen, dst, dstlen );
1644         break;
1645     default:
1646         if (!(table = get_codepage_table( page )))
1647         {
1648             SetLastError( ERROR_INVALID_PARAMETER );
1649             return 0;
1650         }
1651         ret = wine_cp_wcstombs( table, flags, src, srclen, dst, dstlen,
1652                                 defchar, used ? &used_tmp : NULL );
1653         if (used) *used = used_tmp;
1654         break;
1655     }
1656
1657     if (ret < 0)
1658     {
1659         switch(ret)
1660         {
1661         case -1: SetLastError( ERROR_INSUFFICIENT_BUFFER ); break;
1662         case -2: SetLastError( ERROR_NO_UNICODE_TRANSLATION ); break;
1663         }
1664         ret = 0;
1665     }
1666     TRACE("cp %d %s -> %s\n", page, debugstr_w(src), debugstr_a(dst));
1667     return ret;
1668 }
1669
1670
1671 /***********************************************************************
1672  *           GetThreadLocale    (KERNEL32.@)
1673  *
1674  * Get the current threads locale.
1675  *
1676  * PARAMS
1677  *  None.
1678  *
1679  * RETURNS
1680  *  The LCID currently assocated with the calling thread.
1681  */
1682 LCID WINAPI GetThreadLocale(void)
1683 {
1684     LCID ret = NtCurrentTeb()->CurrentLocale;
1685     if (!ret) NtCurrentTeb()->CurrentLocale = ret = GetUserDefaultLCID();
1686     return ret;
1687 }
1688
1689 /**********************************************************************
1690  *           SetThreadLocale    (KERNEL32.@)
1691  *
1692  * Set the current threads locale.
1693  *
1694  * PARAMS
1695  *  lcid [I] LCID of the locale to set
1696  *
1697  * RETURNS
1698  *  Success: TRUE. The threads locale is set to lcid.
1699  *  Failure: FALSE. Use GetLastError() to determine the cause.
1700  */
1701 BOOL WINAPI SetThreadLocale( LCID lcid )
1702 {
1703     TRACE("(0x%04lX)\n", lcid);
1704
1705     lcid = ConvertDefaultLocale(lcid);
1706
1707     if (lcid != GetThreadLocale())
1708     {
1709         if (!IsValidLocale(lcid, LCID_SUPPORTED))
1710         {
1711             SetLastError(ERROR_INVALID_PARAMETER);
1712             return FALSE;
1713         }
1714
1715         NtCurrentTeb()->CurrentLocale = lcid;
1716         NtCurrentTeb()->code_page = get_lcid_codepage( lcid );
1717     }
1718     return TRUE;
1719 }
1720
1721 /******************************************************************************
1722  *              ConvertDefaultLocale (KERNEL32.@)
1723  *
1724  * Convert a default locale identifier into a real identifier.
1725  *
1726  * PARAMS
1727  *  lcid [I] LCID identifier of the locale to convert
1728  *
1729  * RETURNS
1730  *  lcid unchanged, if not a default locale or its sublanguage is
1731  *   not SUBLANG_NEUTRAL.
1732  *  GetSystemDefaultLCID(), if lcid == LOCALE_SYSTEM_DEFAULT.
1733  *  GetUserDefaultLCID(), if lcid == LOCALE_USER_DEFAULT or LOCALE_NEUTRAL.
1734  *  Otherwise, lcid with sublanguage changed to SUBLANG_DEFAULT.
1735  */
1736 LCID WINAPI ConvertDefaultLocale( LCID lcid )
1737 {
1738     LANGID langid;
1739
1740     switch (lcid)
1741     {
1742     case LOCALE_SYSTEM_DEFAULT:
1743         lcid = GetSystemDefaultLCID();
1744         break;
1745     case LOCALE_USER_DEFAULT:
1746     case LOCALE_NEUTRAL:
1747         lcid = GetUserDefaultLCID();
1748         break;
1749     default:
1750         /* Replace SUBLANG_NEUTRAL with SUBLANG_DEFAULT */
1751         langid = LANGIDFROMLCID(lcid);
1752         if (SUBLANGID(langid) == SUBLANG_NEUTRAL)
1753         {
1754           langid = MAKELANGID(PRIMARYLANGID(langid), SUBLANG_DEFAULT);
1755           lcid = MAKELCID(langid, SORTIDFROMLCID(lcid));
1756         }
1757     }
1758     return lcid;
1759 }
1760
1761
1762 /******************************************************************************
1763  *           IsValidLocale   (KERNEL32.@)
1764  *
1765  * Determine if a locale is valid.
1766  *
1767  * PARAMS
1768  *  lcid  [I] LCID of the locale to check
1769  *  flags [I] LCID_SUPPORTED = Valid, LCID_INSTALLED = Valid and installed on the system
1770  *
1771  * RETURN
1772  *  TRUE,  if lcid is valid,
1773  *  FALSE, otherwise.
1774  *
1775  * NOTES
1776  *  Wine does not currently make the distinction between supported and installed. All
1777  *  languages supported are installed by default.
1778  */
1779 BOOL WINAPI IsValidLocale( LCID lcid, DWORD flags )
1780 {
1781     /* check if language is registered in the kernel32 resources */
1782     return FindResourceExW( kernel32_handle, (LPWSTR)RT_STRING,
1783                             (LPCWSTR)LOCALE_ILANGUAGE, LANGIDFROMLCID(lcid)) != 0;
1784 }
1785
1786
1787 static BOOL CALLBACK enum_lang_proc_a( HMODULE hModule, LPCSTR type,
1788                                        LPCSTR name, WORD LangID, LONG lParam )
1789 {
1790     LOCALE_ENUMPROCA lpfnLocaleEnum = (LOCALE_ENUMPROCA)lParam;
1791     char buf[20];
1792
1793     sprintf(buf, "%08x", (UINT)LangID);
1794     return lpfnLocaleEnum( buf );
1795 }
1796
1797 static BOOL CALLBACK enum_lang_proc_w( HMODULE hModule, LPCWSTR type,
1798                                        LPCWSTR name, WORD LangID, LONG lParam )
1799 {
1800     static const WCHAR formatW[] = {'%','0','8','x',0};
1801     LOCALE_ENUMPROCW lpfnLocaleEnum = (LOCALE_ENUMPROCW)lParam;
1802     WCHAR buf[20];
1803     sprintfW( buf, formatW, (UINT)LangID );
1804     return lpfnLocaleEnum( buf );
1805 }
1806
1807 /******************************************************************************
1808  *           EnumSystemLocalesA  (KERNEL32.@)
1809  *
1810  * Call a users function for each locale available on the system.
1811  *
1812  * PARAMS
1813  *  lpfnLocaleEnum [I] Callback function to call for each locale
1814  *  dwFlags        [I] LOCALE_SUPPORTED=All supported, LOCALE_INSTALLED=Installed only
1815  *
1816  * RETURNS
1817  *  Success: TRUE.
1818  *  Failure: FALSE. Use GetLastError() to determine the cause.
1819  */
1820 BOOL WINAPI EnumSystemLocalesA( LOCALE_ENUMPROCA lpfnLocaleEnum, DWORD dwFlags )
1821 {
1822     TRACE("(%p,%08lx)\n", lpfnLocaleEnum, dwFlags);
1823     EnumResourceLanguagesA( kernel32_handle, (LPSTR)RT_STRING,
1824                             (LPCSTR)LOCALE_ILANGUAGE, enum_lang_proc_a,
1825                             (LONG)lpfnLocaleEnum);
1826     return TRUE;
1827 }
1828
1829
1830 /******************************************************************************
1831  *           EnumSystemLocalesW  (KERNEL32.@)
1832  *
1833  * See EnumSystemLocalesA.
1834  */
1835 BOOL WINAPI EnumSystemLocalesW( LOCALE_ENUMPROCW lpfnLocaleEnum, DWORD dwFlags )
1836 {
1837     TRACE("(%p,%08lx)\n", lpfnLocaleEnum, dwFlags);
1838     EnumResourceLanguagesW( kernel32_handle, (LPWSTR)RT_STRING,
1839                             (LPCWSTR)LOCALE_ILANGUAGE, enum_lang_proc_w,
1840                             (LONG)lpfnLocaleEnum);
1841     return TRUE;
1842 }
1843
1844
1845 /***********************************************************************
1846  *           VerLanguageNameA  (KERNEL32.@)
1847  *
1848  * Get the name of a language.
1849  *
1850  * PARAMS
1851  *  wLang  [I] LANGID of the language
1852  *  szLang [O] Destination for the language name
1853  *
1854  * RETURNS
1855  *  Success: The size of the language name. If szLang is non-NULL, it is filled
1856  *           with the name.
1857  *  Failure: 0. Use GetLastError() to determine the cause.
1858  *
1859  */
1860 DWORD WINAPI VerLanguageNameA( UINT wLang, LPSTR szLang, UINT nSize )
1861 {
1862     return GetLocaleInfoA( MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize );
1863 }
1864
1865
1866 /***********************************************************************
1867  *           VerLanguageNameW  (KERNEL32.@)
1868  *
1869  * See VerLanguageNameA.
1870  */
1871 DWORD WINAPI VerLanguageNameW( UINT wLang, LPWSTR szLang, UINT nSize )
1872 {
1873     return GetLocaleInfoW( MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize );
1874 }
1875
1876
1877 /******************************************************************************
1878  *           GetStringTypeW    (KERNEL32.@)
1879  *
1880  * See GetStringTypeA.
1881  */
1882 BOOL WINAPI GetStringTypeW( DWORD type, LPCWSTR src, INT count, LPWORD chartype )
1883 {
1884     if (count == -1) count = strlenW(src) + 1;
1885     switch(type)
1886     {
1887     case CT_CTYPE1:
1888         while (count--) *chartype++ = get_char_typeW( *src++ ) & 0xfff;
1889         break;
1890     case CT_CTYPE2:
1891         while (count--) *chartype++ = get_char_typeW( *src++ ) >> 12;
1892         break;
1893     case CT_CTYPE3:
1894     {
1895         WARN("CT_CTYPE3: semi-stub.\n");
1896         while (count--)
1897         {
1898             int c = *src;
1899             WORD type1, type3 = 0; /* C3_NOTAPPLICABLE */
1900
1901             type1 = get_char_typeW( *src++ ) & 0xfff;
1902             /* try to construct type3 from type1 */
1903             if(type1 & C1_SPACE) type3 |= C3_SYMBOL;
1904             if(type1 & C1_ALPHA) type3 |= C3_ALPHA;
1905             if ((c>=0x30A0)&&(c<=0x30FF)) type3 |= C3_KATAKANA;
1906             if ((c>=0x3040)&&(c<=0x309F)) type3 |= C3_HIRAGANA;
1907             if ((c>=0x4E00)&&(c<=0x9FAF)) type3 |= C3_IDEOGRAPH;
1908             if ((c>=0x0600)&&(c<=0x06FF)) type3 |= C3_KASHIDA;
1909             if ((c>=0x3000)&&(c<=0x303F)) type3 |= C3_SYMBOL;
1910
1911             if ((c>=0xFF00)&&(c<=0xFF60)) type3 |= C3_FULLWIDTH;
1912             if ((c>=0xFF00)&&(c<=0xFF20)) type3 |= C3_SYMBOL;
1913             if ((c>=0xFF3B)&&(c<=0xFF40)) type3 |= C3_SYMBOL;
1914             if ((c>=0xFF5B)&&(c<=0xFF60)) type3 |= C3_SYMBOL;
1915             if ((c>=0xFF21)&&(c<=0xFF3A)) type3 |= C3_ALPHA;
1916             if ((c>=0xFF41)&&(c<=0xFF5A)) type3 |= C3_ALPHA;
1917             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_FULLWIDTH;
1918             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_SYMBOL;
1919
1920             if ((c>=0xFF61)&&(c<=0xFFDC)) type3 |= C3_HALFWIDTH;
1921             if ((c>=0xFF61)&&(c<=0xFF64)) type3 |= C3_SYMBOL;
1922             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_KATAKANA;
1923             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_ALPHA;
1924             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_HALFWIDTH;
1925             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_SYMBOL;
1926             *chartype++ = type3;
1927         }
1928         break;
1929     }
1930     default:
1931         SetLastError( ERROR_INVALID_PARAMETER );
1932         return FALSE;
1933     }
1934     return TRUE;
1935 }
1936
1937
1938 /******************************************************************************
1939  *           GetStringTypeExW    (KERNEL32.@)
1940  *
1941  * See GetStringTypeExA.
1942  */
1943 BOOL WINAPI GetStringTypeExW( LCID locale, DWORD type, LPCWSTR src, INT count, LPWORD chartype )
1944 {
1945     /* locale is ignored for Unicode */
1946     return GetStringTypeW( type, src, count, chartype );
1947 }
1948
1949
1950 /******************************************************************************
1951  *           GetStringTypeA    (KERNEL32.@)
1952  *
1953  * Get characteristics of the characters making up a string.
1954  *
1955  * PARAMS
1956  *  locale   [I] Locale Id for the string
1957  *  type     [I] CT_CTYPE1 = classification, CT_CTYPE2 = directionality, CT_CTYPE3 = typographic info
1958  *  src      [I] String to analyse
1959  *  count    [I] Length of src in chars, or -1 if src is NUL terminated
1960  *  chartype [O] Destination for the calculated characteristics
1961  *
1962  * RETURNS
1963  *  Success: TRUE. chartype is filled with the requested characteristics of each char
1964  *           in src.
1965  *  Failure: FALSE. Use GetLastError() to determine the cause.
1966  */
1967 BOOL WINAPI GetStringTypeA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
1968 {
1969     UINT cp;
1970     INT countW;
1971     LPWSTR srcW;
1972     BOOL ret = FALSE;
1973
1974     if(count == -1) count = strlen(src) + 1;
1975
1976     if (!(cp = get_lcid_codepage( locale )))
1977     {
1978         FIXME("For locale %04lx using current ANSI code page\n", locale);
1979         cp = GetACP();
1980     }
1981
1982     countW = MultiByteToWideChar(cp, 0, src, count, NULL, 0);
1983     if((srcW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
1984     {
1985         MultiByteToWideChar(cp, 0, src, count, srcW, countW);
1986     /*
1987      * NOTE: the target buffer has 1 word for each CHARACTER in the source
1988      * string, with multibyte characters there maybe be more bytes in count
1989      * than character space in the buffer!
1990      */
1991         ret = GetStringTypeW(type, srcW, countW, chartype);
1992         HeapFree(GetProcessHeap(), 0, srcW);
1993     }
1994     return ret;
1995 }
1996
1997 /******************************************************************************
1998  *           GetStringTypeExA    (KERNEL32.@)
1999  *
2000  * Get characteristics of the characters making up a string.
2001  *
2002  * PARAMS
2003  *  locale   [I] Locale Id for the string
2004  *  type     [I] CT_CTYPE1 = classification, CT_CTYPE2 = directionality, CT_CTYPE3 = typographic info
2005  *  src      [I] String to analyse
2006  *  count    [I] Length of src in chars, or -1 if src is NUL terminated
2007  *  chartype [O] Destination for the calculated characteristics
2008  *
2009  * RETURNS
2010  *  Success: TRUE. chartype is filled with the requested characteristics of each char
2011  *           in src.
2012  *  Failure: FALSE. Use GetLastError() to determine the cause.
2013  */
2014 BOOL WINAPI GetStringTypeExA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
2015 {
2016     return GetStringTypeA(locale, type, src, count, chartype);
2017 }
2018
2019
2020 /*************************************************************************
2021  *           LCMapStringW    (KERNEL32.@)
2022  *
2023  * See LCMapStringA.
2024  */
2025 INT WINAPI LCMapStringW(LCID lcid, DWORD flags, LPCWSTR src, INT srclen,
2026                         LPWSTR dst, INT dstlen)
2027 {
2028     LPWSTR dst_ptr;
2029
2030     if (!src || !srclen || dstlen < 0)
2031     {
2032         SetLastError(ERROR_INVALID_PARAMETER);
2033         return 0;
2034     }
2035
2036     /* mutually exclusive flags */
2037     if ((flags & (LCMAP_LOWERCASE | LCMAP_UPPERCASE)) == (LCMAP_LOWERCASE | LCMAP_UPPERCASE) ||
2038         (flags & (LCMAP_HIRAGANA | LCMAP_KATAKANA)) == (LCMAP_HIRAGANA | LCMAP_KATAKANA) ||
2039         (flags & (LCMAP_HALFWIDTH | LCMAP_FULLWIDTH)) == (LCMAP_HALFWIDTH | LCMAP_FULLWIDTH) ||
2040         (flags & (LCMAP_TRADITIONAL_CHINESE | LCMAP_SIMPLIFIED_CHINESE)) == (LCMAP_TRADITIONAL_CHINESE | LCMAP_SIMPLIFIED_CHINESE))
2041     {
2042         SetLastError(ERROR_INVALID_FLAGS);
2043         return 0;
2044     }
2045
2046     if (!dstlen) dst = NULL;
2047
2048     lcid = ConvertDefaultLocale(lcid);
2049
2050     if (flags & LCMAP_SORTKEY)
2051     {
2052         if (src == dst)
2053         {
2054             SetLastError(ERROR_INVALID_FLAGS);
2055             return 0;
2056         }
2057
2058         if (srclen < 0) srclen = strlenW(src);
2059
2060         TRACE("(0x%04lx,0x%08lx,%s,%d,%p,%d)\n",
2061               lcid, flags, debugstr_wn(src, srclen), srclen, dst, dstlen);
2062
2063         return wine_get_sortkey(flags, src, srclen, (char *)dst, dstlen);
2064     }
2065
2066     /* SORT_STRINGSORT must be used exclusively with LCMAP_SORTKEY */
2067     if (flags & SORT_STRINGSORT)
2068     {
2069         SetLastError(ERROR_INVALID_FLAGS);
2070         return 0;
2071     }
2072
2073     if (srclen < 0) srclen = strlenW(src) + 1;
2074
2075     TRACE("(0x%04lx,0x%08lx,%s,%d,%p,%d)\n",
2076           lcid, flags, debugstr_wn(src, srclen), srclen, dst, dstlen);
2077
2078     if (!dst) /* return required string length */
2079     {
2080         INT len;
2081
2082         for (len = 0; srclen; src++, srclen--)
2083         {
2084             WCHAR wch = *src;
2085             /* tests show that win2k just ignores NORM_IGNORENONSPACE,
2086              * and skips white space and punctuation characters for
2087              * NORM_IGNORESYMBOLS.
2088              */
2089             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
2090                 continue;
2091             len++;
2092         }
2093         return len;
2094     }
2095
2096     if (flags & LCMAP_UPPERCASE)
2097     {
2098         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
2099         {
2100             WCHAR wch = *src;
2101             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
2102                 continue;
2103             *dst_ptr++ = toupperW(wch);
2104             dstlen--;
2105         }
2106     }
2107     else if (flags & LCMAP_LOWERCASE)
2108     {
2109         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
2110         {
2111             WCHAR wch = *src;
2112             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
2113                 continue;
2114             *dst_ptr++ = tolowerW(wch);
2115             dstlen--;
2116         }
2117     }
2118     else
2119     {
2120         if (src == dst)
2121         {
2122             SetLastError(ERROR_INVALID_FLAGS);
2123             return 0;
2124         }
2125         for (dst_ptr = dst; srclen && dstlen; src++, srclen--)
2126         {
2127             WCHAR wch = *src;
2128             if ((flags & NORM_IGNORESYMBOLS) && (get_char_typeW(wch) & (C1_PUNCT | C1_SPACE)))
2129                 continue;
2130             *dst_ptr++ = wch;
2131             dstlen--;
2132         }
2133     }
2134
2135     if (srclen)
2136     {
2137         SetLastError(ERROR_INSUFFICIENT_BUFFER);
2138         return 0;
2139     }
2140
2141     return dst_ptr - dst;
2142 }
2143
2144 /*************************************************************************
2145  *           LCMapStringA    (KERNEL32.@)
2146  *
2147  * Map characters in a locale sensitive string.
2148  *
2149  * PARAMS
2150  *  lcid   [I] LCID for the conversion.
2151  *  flags  [I] Flags controlling the mapping (LCMAP_ constants from "winnls.h").
2152  *  src    [I] String to map
2153  *  srclen [I] Length of src in chars, or -1 if src is NUL terminated
2154  *  dst    [O] Destination for mapped string
2155  *  dstlen [I] Length of dst in characters
2156  *
2157  * RETURNS
2158  *  Success: The length of the mapped string in dst, including the NUL terminator.
2159  *  Failure: 0. Use GetLastError() to determine the cause.
2160  */
2161 INT WINAPI LCMapStringA(LCID lcid, DWORD flags, LPCSTR src, INT srclen,
2162                         LPSTR dst, INT dstlen)
2163 {
2164     WCHAR *bufW = NtCurrentTeb()->StaticUnicodeBuffer;
2165     LPWSTR srcW, dstW;
2166     INT ret = 0, srclenW, dstlenW;
2167     UINT locale_cp = CP_ACP;
2168
2169     if (!src || !srclen || dstlen < 0)
2170     {
2171         SetLastError(ERROR_INVALID_PARAMETER);
2172         return 0;
2173     }
2174
2175     if (!(flags & LOCALE_USE_CP_ACP)) locale_cp = get_lcid_codepage( lcid );
2176
2177     srclenW = MultiByteToWideChar(locale_cp, 0, src, srclen, bufW, 260);
2178     if (srclenW)
2179         srcW = bufW;
2180     else
2181     {
2182         srclenW = MultiByteToWideChar(locale_cp, 0, src, srclen, NULL, 0);
2183         srcW = HeapAlloc(GetProcessHeap(), 0, srclenW * sizeof(WCHAR));
2184         if (!srcW)
2185         {
2186             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2187             return 0;
2188         }
2189         MultiByteToWideChar(locale_cp, 0, src, srclen, srcW, srclenW);
2190     }
2191
2192     if (flags & LCMAP_SORTKEY)
2193     {
2194         if (src == dst)
2195         {
2196             SetLastError(ERROR_INVALID_FLAGS);
2197             goto map_string_exit;
2198         }
2199         ret = wine_get_sortkey(flags, srcW, srclenW, dst, dstlen);
2200         goto map_string_exit;
2201     }
2202
2203     if (flags & SORT_STRINGSORT)
2204     {
2205         SetLastError(ERROR_INVALID_FLAGS);
2206         goto map_string_exit;
2207     }
2208
2209     dstlenW = LCMapStringW(lcid, flags, srcW, srclenW, NULL, 0);
2210     if (!dstlenW)
2211         goto map_string_exit;
2212
2213     dstW = HeapAlloc(GetProcessHeap(), 0, dstlenW * sizeof(WCHAR));
2214     if (!dstW)
2215     {
2216         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2217         goto map_string_exit;
2218     }
2219
2220     LCMapStringW(lcid, flags, srcW, srclenW, dstW, dstlenW);
2221     ret = WideCharToMultiByte(locale_cp, 0, dstW, dstlenW, dst, dstlen, NULL, NULL);
2222     HeapFree(GetProcessHeap(), 0, dstW);
2223
2224 map_string_exit:
2225     if (srcW != bufW) HeapFree(GetProcessHeap(), 0, srcW);
2226     return ret;
2227 }
2228
2229 /*************************************************************************
2230  *           FoldStringA    (KERNEL32.@)
2231  *
2232  * Map characters in a string.
2233  *
2234  * PARAMS
2235  *  dwFlags [I] Flags controlling chars to map (MAP_ constants from "winnls.h")
2236  *  src     [I] String to map
2237  *  srclen  [I] Length of src, or -1 if src is NUL terminated
2238  *  dst     [O] Destination for mapped string
2239  *  dstlen  [I] Length of dst, or 0 to find the required length for the mapped string
2240  *
2241  * RETURNS
2242  *  Success: The length of the string written to dst, including the terminating NUL. If
2243  *           dstlen is 0, the value returned is the same, but nothing is written to dst,
2244  *           and dst may be NULL.
2245  *  Failure: 0. Use GetLastError() to determine the cause.
2246  */
2247 INT WINAPI FoldStringA(DWORD dwFlags, LPCSTR src, INT srclen,
2248                        LPSTR dst, INT dstlen)
2249 {
2250     INT ret = 0, srclenW = 0;
2251     WCHAR *srcW = NULL, *dstW = NULL;
2252
2253     if (!src || !srclen || dstlen < 0 || (dstlen && !dst) || src == dst)
2254     {
2255         SetLastError(ERROR_INVALID_PARAMETER);
2256         return 0;
2257     }
2258
2259     srclenW = MultiByteToWideChar(CP_ACP, dwFlags & MAP_COMPOSITE ? MB_COMPOSITE : 0,
2260                                   src, srclen, NULL, 0);
2261     srcW = HeapAlloc(GetProcessHeap(), 0, srclenW * sizeof(WCHAR));
2262
2263     if (!srcW)
2264     {
2265         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2266         goto FoldStringA_exit;
2267     }
2268
2269     MultiByteToWideChar(CP_ACP, dwFlags & MAP_COMPOSITE ? MB_COMPOSITE : 0,
2270                         src, srclen, srcW, srclenW);
2271
2272     dwFlags = (dwFlags & ~MAP_PRECOMPOSED) | MAP_FOLDCZONE;
2273
2274     ret = FoldStringW(dwFlags, srcW, srclenW, NULL, 0);
2275     if (ret && dstlen)
2276     {
2277         dstW = HeapAlloc(GetProcessHeap(), 0, ret * sizeof(WCHAR));
2278
2279         if (!dstW)
2280         {
2281             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2282             goto FoldStringA_exit;
2283         }
2284
2285         ret = FoldStringW(dwFlags, srcW, srclenW, dstW, ret);
2286         if (!WideCharToMultiByte(CP_ACP, 0, dstW, ret, dst, dstlen, NULL, NULL))
2287         {
2288             ret = 0;
2289             SetLastError(ERROR_INSUFFICIENT_BUFFER);
2290         }
2291     }
2292
2293     HeapFree(GetProcessHeap(), 0, dstW);
2294
2295 FoldStringA_exit:
2296     HeapFree(GetProcessHeap(), 0, srcW);
2297     return ret;
2298 }
2299
2300 /*************************************************************************
2301  *           FoldStringW    (KERNEL32.@)
2302  *
2303  * See FoldStringA.
2304  */
2305 INT WINAPI FoldStringW(DWORD dwFlags, LPCWSTR src, INT srclen,
2306                        LPWSTR dst, INT dstlen)
2307 {
2308     int ret;
2309
2310     switch (dwFlags & (MAP_COMPOSITE|MAP_PRECOMPOSED|MAP_EXPAND_LIGATURES))
2311     {
2312     case 0:
2313         if (dwFlags)
2314           break;
2315         /* Fall through for dwFlags == 0 */
2316     case MAP_PRECOMPOSED|MAP_COMPOSITE:
2317     case MAP_PRECOMPOSED|MAP_EXPAND_LIGATURES:
2318     case MAP_COMPOSITE|MAP_EXPAND_LIGATURES:
2319         SetLastError(ERROR_INVALID_FLAGS);
2320         return 0;
2321     }
2322
2323     if (!src || !srclen || dstlen < 0 || (dstlen && !dst) || src == dst)
2324     {
2325         SetLastError(ERROR_INVALID_PARAMETER);
2326         return 0;
2327     }
2328
2329     ret = wine_fold_string(dwFlags, src, srclen, dst, dstlen);
2330     if (!ret)
2331         SetLastError(ERROR_INSUFFICIENT_BUFFER);
2332     return ret;
2333 }
2334
2335 /******************************************************************************
2336  *           CompareStringW    (KERNEL32.@)
2337  *
2338  * See CompareStringA.
2339  */
2340 INT WINAPI CompareStringW(LCID lcid, DWORD style,
2341                           LPCWSTR str1, INT len1, LPCWSTR str2, INT len2)
2342 {
2343     INT ret;
2344
2345     if (!str1 || !str2)
2346     {
2347         SetLastError(ERROR_INVALID_PARAMETER);
2348         return 0;
2349     }
2350
2351     if( style & ~(NORM_IGNORECASE|NORM_IGNORENONSPACE|NORM_IGNORESYMBOLS|
2352         SORT_STRINGSORT|NORM_IGNOREKANATYPE|NORM_IGNOREWIDTH|LOCALE_USE_CP_ACP|0x10000000) )
2353     {
2354         SetLastError(ERROR_INVALID_FLAGS);
2355         return 0;
2356     }
2357
2358     if (style & 0x10000000)
2359         FIXME("Ignoring unknown style 0x10000000\n");
2360
2361     if (len1 < 0) len1 = strlenW(str1);
2362     if (len2 < 0) len2 = strlenW(str2);
2363
2364     ret = wine_compare_string(style, str1, len1, str2, len2);
2365
2366     if (ret) /* need to translate result */
2367         return (ret < 0) ? CSTR_LESS_THAN : CSTR_GREATER_THAN;
2368     return CSTR_EQUAL;
2369 }
2370
2371 /******************************************************************************
2372  *           CompareStringA    (KERNEL32.@)
2373  *
2374  * Compare two locale sensitive strings.
2375  *
2376  * PARAMS
2377  *  lcid  [I] LCID for the comparison
2378  *  style [I] Flags for the comparison (NORM_ constants from "winnls.h").
2379  *  str1  [I] First string to compare
2380  *  len1  [I] Length of str1, or -1 if str1 is NUL terminated
2381  *  str2  [I] Second string to compare
2382  *  len2  [I] Length of str2, or -1 if str2 is NUL terminated
2383  *
2384  * RETURNS
2385  *  Success: CSTR_LESS_THAN, CSTR_EQUAL or CSTR_GREATER_THAN depending on whether
2386  *           str2 is less than, equal to or greater than str1 respectively.
2387  *  Failure: FALSE. Use GetLastError() to determine the cause.
2388  */
2389 INT WINAPI CompareStringA(LCID lcid, DWORD style,
2390                           LPCSTR str1, INT len1, LPCSTR str2, INT len2)
2391 {
2392     WCHAR *buf1W = NtCurrentTeb()->StaticUnicodeBuffer;
2393     WCHAR *buf2W = buf1W + 130;
2394     LPWSTR str1W, str2W;
2395     INT len1W, len2W, ret;
2396     UINT locale_cp = CP_ACP;
2397
2398     if (!str1 || !str2)
2399     {
2400         SetLastError(ERROR_INVALID_PARAMETER);
2401         return 0;
2402     }
2403     if (len1 < 0) len1 = strlen(str1);
2404     if (len2 < 0) len2 = strlen(str2);
2405
2406     if (!(style & LOCALE_USE_CP_ACP)) locale_cp = get_lcid_codepage( lcid );
2407
2408     len1W = MultiByteToWideChar(locale_cp, 0, str1, len1, buf1W, 130);
2409     if (len1W)
2410         str1W = buf1W;
2411     else
2412     {
2413         len1W = MultiByteToWideChar(locale_cp, 0, str1, len1, NULL, 0);
2414         str1W = HeapAlloc(GetProcessHeap(), 0, len1W * sizeof(WCHAR));
2415         if (!str1W)
2416         {
2417             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2418             return 0;
2419         }
2420         MultiByteToWideChar(locale_cp, 0, str1, len1, str1W, len1W);
2421     }
2422     len2W = MultiByteToWideChar(locale_cp, 0, str2, len2, buf2W, 130);
2423     if (len2W)
2424         str2W = buf2W;
2425     else
2426     {
2427         len2W = MultiByteToWideChar(locale_cp, 0, str2, len2, NULL, 0);
2428         str2W = HeapAlloc(GetProcessHeap(), 0, len2W * sizeof(WCHAR));
2429         if (!str2W)
2430         {
2431             if (str1W != buf1W) HeapFree(GetProcessHeap(), 0, str1W);
2432             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2433             return 0;
2434         }
2435         MultiByteToWideChar(locale_cp, 0, str2, len2, str2W, len2W);
2436     }
2437
2438     ret = CompareStringW(lcid, style, str1W, len1W, str2W, len2W);
2439
2440     if (str1W != buf1W) HeapFree(GetProcessHeap(), 0, str1W);
2441     if (str2W != buf2W) HeapFree(GetProcessHeap(), 0, str2W);
2442     return ret;
2443 }
2444
2445 /*************************************************************************
2446  *           lstrcmp     (KERNEL32.@)
2447  *           lstrcmpA    (KERNEL32.@)
2448  *
2449  * Compare two strings using the current thread locale.
2450  *
2451  * PARAMS
2452  *  str1  [I] First string to compare
2453  *  str2  [I] Second string to compare
2454  *
2455  * RETURNS
2456  *  Success: A number less than, equal to or greater than 0 depending on whether
2457  *           str2 is less than, equal to or greater than str1 respectively.
2458  *  Failure: FALSE. Use GetLastError() to determine the cause.
2459  */
2460 int WINAPI lstrcmpA(LPCSTR str1, LPCSTR str2)
2461 {
2462     int ret;
2463     
2464     if ((str1 == NULL) && (str2 == NULL)) return 0;
2465     if (str1 == NULL) return -1;
2466     if (str2 == NULL) return 1;
2467
2468     ret = CompareStringA(GetThreadLocale(), LOCALE_USE_CP_ACP, str1, -1, str2, -1);
2469     if (ret) ret -= 2;
2470     
2471     return ret;
2472 }
2473
2474 /*************************************************************************
2475  *           lstrcmpi     (KERNEL32.@)
2476  *           lstrcmpiA    (KERNEL32.@)
2477  *
2478  * Compare two strings using the current thread locale, ignoring case.
2479  *
2480  * PARAMS
2481  *  str1  [I] First string to compare
2482  *  str2  [I] Second string to compare
2483  *
2484  * RETURNS
2485  *  Success: A number less than, equal to or greater than 0 depending on whether
2486  *           str2 is less than, equal to or greater than str1 respectively.
2487  *  Failure: FALSE. Use GetLastError() to determine the cause.
2488  */
2489 int WINAPI lstrcmpiA(LPCSTR str1, LPCSTR str2)
2490 {
2491     int ret;
2492     
2493     if ((str1 == NULL) && (str2 == NULL)) return 0;
2494     if (str1 == NULL) return -1;
2495     if (str2 == NULL) return 1;
2496
2497     ret = CompareStringA(GetThreadLocale(), NORM_IGNORECASE|LOCALE_USE_CP_ACP, str1, -1, str2, -1);
2498     if (ret) ret -= 2;
2499     
2500     return ret;
2501 }
2502
2503 /*************************************************************************
2504  *           lstrcmpW    (KERNEL32.@)
2505  *
2506  * See lstrcmpA.
2507  */
2508 int WINAPI lstrcmpW(LPCWSTR str1, LPCWSTR str2)
2509 {
2510     int ret;
2511
2512     if ((str1 == NULL) && (str2 == NULL)) return 0;
2513     if (str1 == NULL) return -1;
2514     if (str2 == NULL) return 1;
2515
2516     ret = CompareStringW(GetThreadLocale(), 0, str1, -1, str2, -1);
2517     if (ret) ret -= 2;
2518     
2519     return ret;
2520 }
2521
2522 /*************************************************************************
2523  *           lstrcmpiW    (KERNEL32.@)
2524  *
2525  * See lstrcmpiA.
2526  */
2527 int WINAPI lstrcmpiW(LPCWSTR str1, LPCWSTR str2)
2528 {
2529     int ret;
2530     
2531     if ((str1 == NULL) && (str2 == NULL)) return 0;
2532     if (str1 == NULL) return -1;
2533     if (str2 == NULL) return 1;
2534
2535     ret = CompareStringW(GetThreadLocale(), NORM_IGNORECASE, str1, -1, str2, -1);
2536     if (ret) ret -= 2;
2537     
2538     return ret;
2539 }
2540
2541 /******************************************************************************
2542  *              LOCALE_Init
2543  */
2544 void LOCALE_Init(void)
2545 {
2546     extern void __wine_init_codepages( const union cptable *ansi_cp, const union cptable *oem_cp,
2547                                        const union cptable *unix_cp );
2548
2549     UINT ansi_cp = 1252, oem_cp = 437, mac_cp = 10000, unix_cp = ~0U;
2550     LCID lcid;
2551
2552     lcid = get_env_lcid( NULL, NULL );
2553     NtSetDefaultLocale( TRUE, lcid );
2554
2555     lcid = get_env_lcid( NULL, "LC_MESSAGES" );
2556     NtSetDefaultUILanguage( LANGIDFROMLCID(lcid) );
2557
2558     lcid = get_env_lcid( &unix_cp, "LC_CTYPE" );
2559     NtSetDefaultLocale( FALSE, lcid );
2560
2561     ansi_cp = get_lcid_codepage(lcid);
2562     GetLocaleInfoW( lcid, LOCALE_IDEFAULTMACCODEPAGE | LOCALE_RETURN_NUMBER,
2563                     (LPWSTR)&mac_cp, sizeof(mac_cp)/sizeof(WCHAR) );
2564     GetLocaleInfoW( lcid, LOCALE_IDEFAULTCODEPAGE | LOCALE_RETURN_NUMBER,
2565                     (LPWSTR)&oem_cp, sizeof(oem_cp)/sizeof(WCHAR) );
2566     if (unix_cp == ~0U)
2567         GetLocaleInfoW( lcid, LOCALE_IDEFAULTUNIXCODEPAGE | LOCALE_RETURN_NUMBER,
2568                     (LPWSTR)&unix_cp, sizeof(unix_cp)/sizeof(WCHAR) );
2569
2570     if (!(ansi_cptable = wine_cp_get_table( ansi_cp )))
2571         ansi_cptable = wine_cp_get_table( 1252 );
2572     if (!(oem_cptable = wine_cp_get_table( oem_cp )))
2573         oem_cptable  = wine_cp_get_table( 437 );
2574     if (!(mac_cptable = wine_cp_get_table( mac_cp )))
2575         mac_cptable  = wine_cp_get_table( 10000 );
2576     if (unix_cp != CP_UTF8)
2577     {
2578         if (!(unix_cptable = wine_cp_get_table( unix_cp )))
2579             unix_cptable  = wine_cp_get_table( 28591 );
2580     }
2581
2582     __wine_init_codepages( ansi_cptable, oem_cptable, unix_cptable );
2583
2584     TRACE( "ansi=%03d oem=%03d mac=%03d unix=%03d\n",
2585            ansi_cptable->info.codepage, oem_cptable->info.codepage,
2586            mac_cptable->info.codepage, unix_cp );
2587 }
2588
2589 static HKEY NLS_RegOpenKey(HKEY hRootKey, LPCWSTR szKeyName)
2590 {
2591     UNICODE_STRING keyName;
2592     OBJECT_ATTRIBUTES attr;
2593     HKEY hkey;
2594
2595     RtlInitUnicodeString( &keyName, szKeyName );
2596     InitializeObjectAttributes(&attr, &keyName, 0, hRootKey, NULL);
2597
2598     if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) != STATUS_SUCCESS)
2599         hkey = 0;
2600
2601     return hkey;
2602 }
2603
2604 static HKEY NLS_RegOpenSubKey(HKEY hRootKey, LPCWSTR szKeyName)
2605 {
2606     HKEY hKey = NLS_RegOpenKey(hRootKey, szKeyName);
2607
2608     if (hRootKey)
2609         NtClose( hRootKey );
2610
2611     return hKey;
2612 }
2613
2614 static BOOL NLS_RegEnumSubKey(HKEY hKey, UINT ulIndex, LPWSTR szKeyName,
2615                               ULONG keyNameSize)
2616 {
2617     BYTE buffer[80];
2618     KEY_BASIC_INFORMATION *info = (KEY_BASIC_INFORMATION *)buffer;
2619     DWORD dwLen;
2620
2621     if (NtEnumerateKey( hKey, ulIndex, KeyBasicInformation, buffer,
2622                         sizeof(buffer), &dwLen) != STATUS_SUCCESS ||
2623         info->NameLength > keyNameSize)
2624     {
2625         return FALSE;
2626     }
2627
2628     TRACE("info->Name %s info->NameLength %ld\n", debugstr_w(info->Name), info->NameLength);
2629
2630     memcpy( szKeyName, info->Name, info->NameLength);
2631     szKeyName[info->NameLength / sizeof(WCHAR)] = '\0';
2632
2633     TRACE("returning %s\n", debugstr_w(szKeyName));
2634     return TRUE;
2635 }
2636
2637 static BOOL NLS_RegEnumValue(HKEY hKey, UINT ulIndex,
2638                              LPWSTR szValueName, ULONG valueNameSize,
2639                              LPWSTR szValueData, ULONG valueDataSize)
2640 {
2641     BYTE buffer[80];
2642     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
2643     DWORD dwLen;
2644
2645     if (NtEnumerateValueKey( hKey, ulIndex, KeyValueFullInformation,
2646         buffer, sizeof(buffer), &dwLen ) != STATUS_SUCCESS ||
2647         info->NameLength > valueNameSize ||
2648         info->DataLength > valueDataSize)
2649     {
2650         return FALSE;
2651     }
2652
2653     TRACE("info->Name %s info->DataLength %ld\n", debugstr_w(info->Name), info->DataLength);
2654
2655     memcpy( szValueName, info->Name, info->NameLength);
2656     szValueName[info->NameLength / sizeof(WCHAR)] = '\0';
2657     memcpy( szValueData, buffer + info->DataOffset, info->DataLength );
2658     szValueData[info->DataLength / sizeof(WCHAR)] = '\0';
2659
2660     TRACE("returning %s %s\n", debugstr_w(szValueName), debugstr_w(szValueData));
2661     return TRUE;
2662 }
2663
2664 static BOOL NLS_RegGetDword(HKEY hKey, LPCWSTR szValueName, DWORD *lpVal)
2665 {
2666     BYTE buffer[128];
2667     const KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2668     DWORD dwSize = sizeof(buffer);
2669     UNICODE_STRING valueName;
2670
2671     RtlInitUnicodeString( &valueName, szValueName );
2672
2673     TRACE("%p, %s\n", hKey, debugstr_w(szValueName));
2674     if (NtQueryValueKey( hKey, &valueName, KeyValuePartialInformation,
2675                          buffer, dwSize, &dwSize ) == STATUS_SUCCESS &&
2676         info->DataLength == sizeof(DWORD))
2677     {
2678         memcpy(lpVal, info->Data, sizeof(DWORD));
2679         return TRUE;
2680     }
2681
2682     return FALSE;
2683 }
2684
2685 static BOOL NLS_GetLanguageGroupName(LGRPID lgrpid, LPWSTR szName, ULONG nameSize)
2686 {
2687     LANGID  langId;
2688     LPCWSTR szResourceName = (LPCWSTR)(((lgrpid + 0x2000) >> 4) + 1);
2689     HRSRC   hResource;
2690     BOOL    bRet = FALSE;
2691
2692     /* FIXME: Is it correct to use the system default langid? */
2693     langId = GetSystemDefaultLangID();
2694
2695     if (SUBLANGID(langId) == SUBLANG_NEUTRAL)
2696         langId = MAKELANGID( PRIMARYLANGID(langId), SUBLANG_DEFAULT );
2697
2698     hResource = FindResourceExW( kernel32_handle, (LPWSTR)RT_STRING, szResourceName, langId );
2699
2700     if (hResource)
2701     {
2702         HGLOBAL hResDir = LoadResource( kernel32_handle, hResource );
2703
2704         if (hResDir)
2705         {
2706             ULONG   iResourceIndex = lgrpid & 0xf;
2707             LPCWSTR lpResEntry = LockResource( hResDir );
2708             ULONG   i;
2709
2710             for (i = 0; i < iResourceIndex; i++)
2711                 lpResEntry += *lpResEntry + 1;
2712
2713             if (*lpResEntry < nameSize)
2714             {
2715                 memcpy( szName, lpResEntry + 1, *lpResEntry * sizeof(WCHAR) );
2716                 szName[*lpResEntry] = '\0';
2717                 bRet = TRUE;
2718             }
2719
2720         }
2721         FreeResource( hResource );
2722     }
2723     return bRet;
2724 }
2725
2726 /* Registry keys for NLS related information */
2727 static const WCHAR szLangGroupsKeyName[] = {
2728     'L','a','n','g','u','a','g','e',' ','G','r','o','u','p','s','\0'
2729 };
2730
2731 static const WCHAR szCountryListName[] = {
2732     'M','a','c','h','i','n','e','\\','S','o','f','t','w','a','r','e','\\',
2733     'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
2734     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2735     'T','e','l','e','p','h','o','n','y','\\',
2736     'C','o','u','n','t','r','y',' ','L','i','s','t','\0'
2737 };
2738
2739
2740 /* Callback function ptrs for EnumSystemLanguageGroupsA/W */
2741 typedef struct
2742 {
2743   LANGUAGEGROUP_ENUMPROCA procA;
2744   LANGUAGEGROUP_ENUMPROCW procW;
2745   DWORD    dwFlags;
2746   LONG_PTR lParam;
2747 } ENUMLANGUAGEGROUP_CALLBACKS;
2748
2749 /* Internal implementation of EnumSystemLanguageGroupsA/W */
2750 static BOOL NLS_EnumSystemLanguageGroups(ENUMLANGUAGEGROUP_CALLBACKS *lpProcs)
2751 {
2752     WCHAR szNumber[10], szValue[4];
2753     HKEY hKey;
2754     BOOL bContinue = TRUE;
2755     ULONG ulIndex = 0;
2756
2757     if (!lpProcs)
2758     {
2759         SetLastError(ERROR_INVALID_PARAMETER);
2760         return FALSE;
2761     }
2762
2763     switch (lpProcs->dwFlags)
2764     {
2765     case 0:
2766         /* Default to LGRPID_INSTALLED */
2767         lpProcs->dwFlags = LGRPID_INSTALLED;
2768         /* Fall through... */
2769     case LGRPID_INSTALLED:
2770     case LGRPID_SUPPORTED:
2771         break;
2772     default:
2773         SetLastError(ERROR_INVALID_FLAGS);
2774         return FALSE;
2775     }
2776
2777     hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLangGroupsKeyName );
2778
2779     if (!hKey)
2780         FIXME("NLS registry key not found. Please apply the default registry file 'wine.inf'\n");
2781
2782     while (bContinue)
2783     {
2784         if (NLS_RegEnumValue( hKey, ulIndex, szNumber, sizeof(szNumber),
2785                               szValue, sizeof(szValue) ))
2786         {
2787             BOOL bInstalled = szValue[0] == '1' ? TRUE : FALSE;
2788             LGRPID lgrpid = strtoulW( szNumber, NULL, 16 );
2789
2790             TRACE("grpid %s (%sinstalled)\n", debugstr_w(szNumber),
2791                    bInstalled ? "" : "not ");
2792
2793             if (lpProcs->dwFlags == LGRPID_SUPPORTED || bInstalled)
2794             {
2795                 WCHAR szGrpName[48];
2796
2797                 if (!NLS_GetLanguageGroupName( lgrpid, szGrpName, sizeof(szGrpName) / sizeof(WCHAR) ))
2798                     szGrpName[0] = '\0';
2799
2800                 if (lpProcs->procW)
2801                     bContinue = lpProcs->procW( lgrpid, szNumber, szGrpName, lpProcs->dwFlags,
2802                                                 lpProcs->lParam );
2803                 else
2804                 {
2805                     char szNumberA[sizeof(szNumber)/sizeof(WCHAR)];
2806                     char szGrpNameA[48];
2807
2808                     /* FIXME: MSDN doesn't say which code page the W->A translation uses,
2809                      *        or whether the language names are ever localised. Assume CP_ACP.
2810                      */
2811
2812                     WideCharToMultiByte(CP_ACP, 0, szNumber, -1, szNumberA, sizeof(szNumberA), 0, 0);
2813                     WideCharToMultiByte(CP_ACP, 0, szGrpName, -1, szGrpNameA, sizeof(szGrpNameA), 0, 0);
2814
2815                     bContinue = lpProcs->procA( lgrpid, szNumberA, szGrpNameA, lpProcs->dwFlags,
2816                                                 lpProcs->lParam );
2817                 }
2818             }
2819
2820             ulIndex++;
2821         }
2822         else
2823             bContinue = FALSE;
2824
2825         if (!bContinue)
2826             break;
2827     }
2828
2829     if (hKey)
2830         NtClose( hKey );
2831
2832     return TRUE;
2833 }
2834
2835 /******************************************************************************
2836  *           EnumSystemLanguageGroupsA    (KERNEL32.@)
2837  *
2838  * Call a users function for each language group available on the system.
2839  *
2840  * PARAMS
2841  *  pLangGrpEnumProc [I] Callback function to call for each language group
2842  *  dwFlags          [I] LGRPID_SUPPORTED=All Supported, LGRPID_INSTALLED=Installed only
2843  *  lParam           [I] User parameter to pass to pLangGrpEnumProc
2844  *
2845  * RETURNS
2846  *  Success: TRUE.
2847  *  Failure: FALSE. Use GetLastError() to determine the cause.
2848  */
2849 BOOL WINAPI EnumSystemLanguageGroupsA(LANGUAGEGROUP_ENUMPROCA pLangGrpEnumProc,
2850                                       DWORD dwFlags, LONG_PTR lParam)
2851 {
2852     ENUMLANGUAGEGROUP_CALLBACKS procs;
2853
2854     TRACE("(%p,0x%08lX,0x%08lX)\n", pLangGrpEnumProc, dwFlags, lParam);
2855
2856     procs.procA = pLangGrpEnumProc;
2857     procs.procW = NULL;
2858     procs.dwFlags = dwFlags;
2859     procs.lParam = lParam;
2860
2861     return NLS_EnumSystemLanguageGroups( pLangGrpEnumProc ? &procs : NULL);
2862 }
2863
2864 /******************************************************************************
2865  *           EnumSystemLanguageGroupsW    (KERNEL32.@)
2866  *
2867  * See EnumSystemLanguageGroupsA.
2868  */
2869 BOOL WINAPI EnumSystemLanguageGroupsW(LANGUAGEGROUP_ENUMPROCW pLangGrpEnumProc,
2870                                       DWORD dwFlags, LONG_PTR lParam)
2871 {
2872     ENUMLANGUAGEGROUP_CALLBACKS procs;
2873
2874     TRACE("(%p,0x%08lX,0x%08lX)\n", pLangGrpEnumProc, dwFlags, lParam);
2875
2876     procs.procA = NULL;
2877     procs.procW = pLangGrpEnumProc;
2878     procs.dwFlags = dwFlags;
2879     procs.lParam = lParam;
2880
2881     return NLS_EnumSystemLanguageGroups( pLangGrpEnumProc ? &procs : NULL);
2882 }
2883
2884 /******************************************************************************
2885  *           IsValidLanguageGroup    (KERNEL32.@)
2886  *
2887  * Determine if a language group is supported and/or installed.
2888  *
2889  * PARAMS
2890  *  lgrpid  [I] Language Group Id (LGRPID_ values from "winnls.h")
2891  *  dwFlags [I] LGRPID_SUPPORTED=Supported, LGRPID_INSTALLED=Installed
2892  *
2893  * RETURNS
2894  *  TRUE, if lgrpid is supported and/or installed, according to dwFlags.
2895  *  FALSE otherwise.
2896  */
2897 BOOL WINAPI IsValidLanguageGroup(LGRPID lgrpid, DWORD dwFlags)
2898 {
2899     static const WCHAR szFormat[] = { '%','x','\0' };
2900     WCHAR szValueName[16], szValue[2];
2901     BOOL bSupported = FALSE, bInstalled = FALSE;
2902     HKEY hKey;
2903
2904
2905     switch (dwFlags)
2906     {
2907     case LGRPID_INSTALLED:
2908     case LGRPID_SUPPORTED:
2909
2910         hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLangGroupsKeyName );
2911
2912         sprintfW( szValueName, szFormat, lgrpid );
2913
2914         if (NLS_RegGetDword( hKey, szValueName, (LPDWORD)&szValue ))
2915         {
2916             bSupported = TRUE;
2917
2918             if (szValue[0] == '1')
2919                 bInstalled = TRUE;
2920         }
2921
2922         if (hKey)
2923             NtClose( hKey );
2924
2925         break;
2926     }
2927
2928     if ((dwFlags == LGRPID_SUPPORTED && bSupported) ||
2929         (dwFlags == LGRPID_INSTALLED && bInstalled))
2930         return TRUE;
2931
2932     return FALSE;
2933 }
2934
2935 /* Callback function ptrs for EnumLanguageGrouplocalesA/W */
2936 typedef struct
2937 {
2938   LANGGROUPLOCALE_ENUMPROCA procA;
2939   LANGGROUPLOCALE_ENUMPROCW procW;
2940   DWORD    dwFlags;
2941   LGRPID   lgrpid;
2942   LONG_PTR lParam;
2943 } ENUMLANGUAGEGROUPLOCALE_CALLBACKS;
2944
2945 /* Internal implementation of EnumLanguageGrouplocalesA/W */
2946 static BOOL NLS_EnumLanguageGroupLocales(ENUMLANGUAGEGROUPLOCALE_CALLBACKS *lpProcs)
2947 {
2948     static const WCHAR szLocaleKeyName[] = {
2949       'L','o','c','a','l','e','\0'
2950     };
2951     static const WCHAR szAlternateSortsKeyName[] = {
2952       'A','l','t','e','r','n','a','t','e',' ','S','o','r','t','s','\0'
2953     };
2954     WCHAR szNumber[10], szValue[4];
2955     HKEY hKey;
2956     BOOL bContinue = TRUE, bAlternate = FALSE;
2957     LGRPID lgrpid;
2958     ULONG ulIndex = 1;  /* Ignore default entry of 1st key */
2959
2960     if (!lpProcs || !lpProcs->lgrpid || lpProcs->lgrpid > LGRPID_ARMENIAN)
2961     {
2962         SetLastError(ERROR_INVALID_PARAMETER);
2963         return FALSE;
2964     }
2965
2966     if (lpProcs->dwFlags)
2967     {
2968         SetLastError(ERROR_INVALID_FLAGS);
2969         return FALSE;
2970     }
2971
2972     hKey = NLS_RegOpenSubKey( NLS_RegOpenKey( 0, szNlsKeyName ), szLocaleKeyName );
2973
2974     if (!hKey)
2975         WARN("NLS registry key not found. Please apply the default registry file 'wine.inf'\n");
2976
2977     while (bContinue)
2978     {
2979         if (NLS_RegEnumValue( hKey, ulIndex, szNumber, sizeof(szNumber),
2980                               szValue, sizeof(szValue) ))
2981         {
2982             lgrpid = strtoulW( szValue, NULL, 16 );
2983
2984             TRACE("lcid %s, grpid %ld (%smatched)\n", debugstr_w(szNumber),
2985                    lgrpid, lgrpid == lpProcs->lgrpid ? "" : "not ");
2986
2987             if (lgrpid == lpProcs->lgrpid)
2988             {
2989                 LCID lcid;
2990
2991                 lcid = strtoulW( szNumber, NULL, 16 );
2992
2993                 /* FIXME: native returns extra text for a few (17/150) locales, e.g:
2994                  * '00000437          ;Georgian'
2995                  * At present we only pass the LCID string.
2996                  */
2997
2998                 if (lpProcs->procW)
2999                     bContinue = lpProcs->procW( lgrpid, lcid, szNumber, lpProcs->lParam );
3000                 else
3001                 {
3002                     char szNumberA[sizeof(szNumber)/sizeof(WCHAR)];
3003
3004                     WideCharToMultiByte(CP_ACP, 0, szNumber, -1, szNumberA, sizeof(szNumberA), 0, 0);
3005
3006                     bContinue = lpProcs->procA( lgrpid, lcid, szNumberA, lpProcs->lParam );
3007                 }
3008             }
3009
3010             ulIndex++;
3011         }
3012         else
3013         {
3014             /* Finished enumerating this key */
3015             if (!bAlternate)
3016             {
3017                 /* Enumerate alternate sorts also */
3018                 hKey = NLS_RegOpenKey( hKey, szAlternateSortsKeyName );
3019                 bAlternate = TRUE;
3020                 ulIndex = 0;
3021             }
3022             else
3023                 bContinue = FALSE; /* Finished both keys */
3024         }
3025
3026         if (!bContinue)
3027             break;
3028     }
3029
3030     if (hKey)
3031         NtClose( hKey );
3032
3033     return TRUE;
3034 }
3035
3036 /******************************************************************************
3037  *           EnumLanguageGroupLocalesA    (KERNEL32.@)
3038  *
3039  * Call a users function for every locale in a language group available on the system.
3040  *
3041  * PARAMS
3042  *  pLangGrpLcEnumProc [I] Callback function to call for each locale
3043  *  lgrpid             [I] Language group (LGRPID_ values from "winnls.h")
3044  *  dwFlags            [I] Reserved, set to 0
3045  *  lParam             [I] User parameter to pass to pLangGrpLcEnumProc
3046  *
3047  * RETURNS
3048  *  Success: TRUE.
3049  *  Failure: FALSE. Use GetLastError() to determine the cause.
3050  */
3051 BOOL WINAPI EnumLanguageGroupLocalesA(LANGGROUPLOCALE_ENUMPROCA pLangGrpLcEnumProc,
3052                                       LGRPID lgrpid, DWORD dwFlags, LONG_PTR lParam)
3053 {
3054     ENUMLANGUAGEGROUPLOCALE_CALLBACKS callbacks;
3055
3056     TRACE("(%p,0x%08lX,0x%08lX,0x%08lX)\n", pLangGrpLcEnumProc, lgrpid, dwFlags, lParam);
3057
3058     callbacks.procA   = pLangGrpLcEnumProc;
3059     callbacks.procW   = NULL;
3060     callbacks.dwFlags = dwFlags;
3061     callbacks.lgrpid  = lgrpid;
3062     callbacks.lParam  = lParam;
3063
3064     return NLS_EnumLanguageGroupLocales( pLangGrpLcEnumProc ? &callbacks : NULL );
3065 }
3066
3067 /******************************************************************************
3068  *           EnumLanguageGroupLocalesW    (KERNEL32.@)
3069  *
3070  * See EnumLanguageGroupLocalesA.
3071  */
3072 BOOL WINAPI EnumLanguageGroupLocalesW(LANGGROUPLOCALE_ENUMPROCW pLangGrpLcEnumProc,
3073                                       LGRPID lgrpid, DWORD dwFlags, LONG_PTR lParam)
3074 {
3075     ENUMLANGUAGEGROUPLOCALE_CALLBACKS callbacks;
3076
3077     TRACE("(%p,0x%08lX,0x%08lX,0x%08lX)\n", pLangGrpLcEnumProc, lgrpid, dwFlags, lParam);
3078
3079     callbacks.procA   = NULL;
3080     callbacks.procW   = pLangGrpLcEnumProc;
3081     callbacks.dwFlags = dwFlags;
3082     callbacks.lgrpid  = lgrpid;
3083     callbacks.lParam  = lParam;
3084
3085     return NLS_EnumLanguageGroupLocales( pLangGrpLcEnumProc ? &callbacks : NULL );
3086 }
3087
3088 /******************************************************************************
3089  *           EnumSystemGeoID    (KERNEL32.@)
3090  *
3091  * Call a users function for every location available on the system.
3092  *
3093  * PARAMS
3094  *  geoclass     [I] Type of information desired (SYSGEOTYPE enum from "winnls.h")
3095  *  reserved     [I] Reserved, set to 0
3096  *  pGeoEnumProc [I] Callback function to call for each location
3097  *
3098  * RETURNS
3099  *  Success: TRUE.
3100  *  Failure: FALSE. Use GetLastError() to determine the cause.
3101  */
3102 BOOL WINAPI EnumSystemGeoID(GEOCLASS geoclass, GEOID reserved, GEO_ENUMPROC pGeoEnumProc)
3103 {
3104     static const WCHAR szCountryCodeValueName[] = {
3105       'C','o','u','n','t','r','y','C','o','d','e','\0'
3106     };
3107     WCHAR szNumber[10];
3108     HKEY hKey;
3109     ULONG ulIndex = 0;
3110
3111     TRACE("(0x%08lX,0x%08lX,%p)\n", geoclass, reserved, pGeoEnumProc);
3112
3113     if (geoclass != GEOCLASS_NATION || reserved || !pGeoEnumProc)
3114     {
3115         SetLastError(ERROR_INVALID_PARAMETER);
3116         return FALSE;
3117     }
3118
3119     hKey = NLS_RegOpenKey( 0, szCountryListName );
3120
3121     while (NLS_RegEnumSubKey( hKey, ulIndex, szNumber, sizeof(szNumber) ))
3122     {
3123         BOOL bContinue = TRUE;
3124         DWORD dwGeoId;
3125         HKEY hSubKey = NLS_RegOpenKey( hKey, szNumber );
3126
3127         if (hSubKey)
3128         {
3129             if (NLS_RegGetDword( hSubKey, szCountryCodeValueName, &dwGeoId ))
3130             {
3131                 TRACE("Got geoid %ld\n", dwGeoId);
3132
3133                 if (!pGeoEnumProc( dwGeoId ))
3134                     bContinue = FALSE;
3135             }
3136
3137             NtClose( hSubKey );
3138         }
3139
3140         if (!bContinue)
3141             break;
3142
3143         ulIndex++;
3144     }
3145
3146     if (hKey)
3147         NtClose( hKey );
3148
3149     return TRUE;
3150 }
3151
3152 /******************************************************************************
3153  *           InvalidateNLSCache           (KERNEL32.@)
3154  *
3155  * Invalidate the cache of NLS values.
3156  *
3157  * PARAMS
3158  *  None.
3159  *
3160  * RETURNS
3161  *  Success: TRUE.
3162  *  Failure: FALSE.
3163  */
3164 BOOL WINAPI InvalidateNLSCache(void)
3165 {
3166   FIXME("() stub\n");
3167   return FALSE;
3168 }
3169
3170 /******************************************************************************
3171  *           GetUserGeoID (KERNEL32.@)
3172  */
3173 GEOID WINAPI GetUserGeoID( GEOCLASS GeoClass )
3174 {
3175     FIXME("%ld\n",GeoClass);
3176     return GEOID_NOT_AVAILABLE;
3177 }
3178
3179 /******************************************************************************
3180  *           SetUserGeoID (KERNEL32.@)
3181  */
3182 BOOL WINAPI SetUserGeoID( GEOID GeoID )
3183 {
3184     FIXME("%ld\n",GeoID);
3185     return FALSE;
3186 }
3187
3188 /******************************************************************************
3189  *           EnumUILanguagesA (KERNEL32.@)
3190  */
3191 BOOL WINAPI EnumUILanguagesA(UILANGUAGE_ENUMPROCA pUILangEnumProc, DWORD dwFlags, LONG_PTR lParam)
3192 {
3193     static char value[] = "0409";
3194
3195     if(!pUILangEnumProc) {
3196         SetLastError(ERROR_INVALID_PARAMETER);
3197         return FALSE;
3198     }
3199     if(dwFlags) {
3200         SetLastError(ERROR_INVALID_FLAGS);
3201         return FALSE;
3202     }
3203
3204     FIXME("%p, %lx, %lx calling pUILangEnumProc with %s\n",
3205           pUILangEnumProc, dwFlags, lParam, debugstr_a(value));
3206
3207     pUILangEnumProc( value, lParam );
3208     return(TRUE);
3209 }
3210
3211 /******************************************************************************
3212  *           EnumUILanguagesW (KERNEL32.@)
3213  */
3214 BOOL WINAPI EnumUILanguagesW(UILANGUAGE_ENUMPROCW pUILangEnumProc, DWORD dwFlags, LONG_PTR lParam)
3215 {
3216     static WCHAR value[] = {'0','4','0','9',0};
3217
3218     if(!pUILangEnumProc) {
3219         SetLastError(ERROR_INVALID_PARAMETER);
3220         return FALSE;
3221     }
3222     if(dwFlags) {
3223         SetLastError(ERROR_INVALID_FLAGS);
3224         return FALSE;
3225     }
3226
3227     FIXME("%p, %lx, %lx calling pUILangEnumProc with %s\n",
3228           pUILangEnumProc, dwFlags, lParam, debugstr_w(value));
3229
3230     pUILangEnumProc( value, lParam );
3231     return(TRUE);
3232 }