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