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