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