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