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