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