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