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