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