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