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