Implemented SHCreateStdEnumFmtEtc.
[wine] / dlls / kernel / 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <string.h>
28 #include <stdio.h>
29 #include <ctype.h>
30 #include <stdlib.h>
31
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winuser.h"  /* for RT_STRINGW */
35 #include "ntddk.h"
36 #include "wine/unicode.h"
37 #include "winnls.h"
38 #include "winerror.h"
39 #include "thread.h"
40 #include "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(nls);
43
44 #define LOCALE_LOCALEINFOFLAGSMASK (LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP|LOCALE_RETURN_NUMBER)
45
46 extern void CODEPAGE_Init( UINT ansi, UINT oem, UINT mac, LCID lcid );
47
48 #define NLS_MAX_LANGUAGES 20
49 typedef struct {
50     char lang[128];
51     char country[128];
52     LANGID found_lang_id[NLS_MAX_LANGUAGES];
53     char found_language[NLS_MAX_LANGUAGES][3];
54     char found_country[NLS_MAX_LANGUAGES][3];
55     int n_found;
56 } LANG_FIND_DATA;
57
58
59 /***********************************************************************
60  *              get_lcid_codepage
61  *
62  * Retrieve the ANSI codepage for a given locale.
63  */
64 inline static UINT get_lcid_codepage( LCID lcid )
65 {
66     UINT ret;
67     if (!GetLocaleInfoW( lcid, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER, (WCHAR *)&ret,
68                          sizeof(ret)/sizeof(WCHAR) )) ret = 0;
69     return ret;
70 }
71
72
73 /***********************************************************************
74  *              update_registry
75  *
76  * Update registry contents on startup if the user locale has changed.
77  * This simulates the action of the Windows control panel.
78  */
79 inline static void update_registry( LCID lcid )
80 {
81     char buffer[20];
82     WCHAR bufferW[80];
83     DWORD count = sizeof(buffer);
84     HKEY hkey;
85
86     if (RegCreateKeyExA( HKEY_CURRENT_USER, "Control Panel\\International", 0, NULL,
87                          0, KEY_ALL_ACCESS, NULL, &hkey, NULL ))
88         return;  /* don't do anything if we can't create the registry key */
89
90     if (!RegQueryValueExA( hkey, "Locale", NULL, NULL, (LPBYTE)buffer, &count ))
91     {
92         if (strtol( buffer, NULL, 16 ) == lcid)  /* already set correctly */
93         {
94             RegCloseKey( hkey );
95             return;
96         }
97         TRACE( "updating registry, locale changed %s -> %08lx\n", buffer, lcid );
98     }
99     else TRACE( "updating registry, locale changed none -> %08lx\n", lcid );
100
101     sprintf( buffer, "%08lx", lcid );
102     RegSetValueExA( hkey, "Locale", 0, REG_SZ, (LPBYTE)buffer, strlen(buffer)+1 );
103     RegCloseKey( hkey );
104
105 #define UPDATE_VALUE(lctype) do { \
106     GetLocaleInfoW( lcid, (lctype)|LOCALE_NOUSEROVERRIDE, bufferW, sizeof(bufferW)/sizeof(WCHAR) ); \
107     SetLocaleInfoW( lcid, (lctype), bufferW ); } while (0)
108
109     UPDATE_VALUE(LOCALE_SLANGUAGE);
110     UPDATE_VALUE(LOCALE_SCOUNTRY);
111     UPDATE_VALUE(LOCALE_ICOUNTRY);
112     UPDATE_VALUE(LOCALE_S1159);
113     UPDATE_VALUE(LOCALE_S2359);
114     UPDATE_VALUE(LOCALE_STIME);
115     UPDATE_VALUE(LOCALE_ITIME);
116     UPDATE_VALUE(LOCALE_ITLZERO);
117     UPDATE_VALUE(LOCALE_SSHORTDATE);
118     UPDATE_VALUE(LOCALE_IDATE);
119     UPDATE_VALUE(LOCALE_SLONGDATE);
120     UPDATE_VALUE(LOCALE_SDATE);
121     UPDATE_VALUE(LOCALE_SCURRENCY);
122     UPDATE_VALUE(LOCALE_ICURRENCY);
123     UPDATE_VALUE(LOCALE_INEGCURR);
124     UPDATE_VALUE(LOCALE_ICURRDIGITS);
125     UPDATE_VALUE(LOCALE_SDECIMAL);
126     UPDATE_VALUE(LOCALE_SLIST);
127     UPDATE_VALUE(LOCALE_STHOUSAND);
128     UPDATE_VALUE(LOCALE_IDIGITS);
129     UPDATE_VALUE(LOCALE_ILZERO);
130     UPDATE_VALUE(LOCALE_IMEASURE);
131 #undef UPDATE_VALUE
132 }
133
134
135 /***********************************************************************
136  *           find_language_id_proc
137  */
138 static BOOL CALLBACK find_language_id_proc( HMODULE hModule, LPCSTR type,
139                                             LPCSTR name, WORD LangID, LPARAM lParam )
140 {
141     LANG_FIND_DATA *l_data = (LANG_FIND_DATA *)lParam;
142     LCID lcid = MAKELCID(LangID, SORT_DEFAULT);
143     char buf_language[128];
144     char buf_country[128];
145     char buf_en_language[128];
146
147     TRACE("%04X\n", (UINT)LangID);
148     if(PRIMARYLANGID(LangID) == LANG_NEUTRAL)
149         return TRUE; /* continue search */
150
151     buf_language[0] = 0;
152     buf_country[0] = 0;
153
154     GetLocaleInfoA(lcid, LOCALE_SISO639LANGNAME|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
155                    buf_language, sizeof(buf_language));
156     TRACE("LOCALE_SISO639LANGNAME: %s\n", buf_language);
157
158     GetLocaleInfoA(lcid, LOCALE_SISO3166CTRYNAME|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
159                    buf_country, sizeof(buf_country));
160     TRACE("LOCALE_SISO3166CTRYNAME: %s\n", buf_country);
161
162     if(l_data->lang && strlen(l_data->lang) > 0 && !strcasecmp(l_data->lang, buf_language))
163     {
164         if(l_data->country && strlen(l_data->country) > 0)
165         {
166             if(!strcasecmp(l_data->country, buf_country))
167             {
168                 l_data->found_lang_id[0] = LangID;
169                 l_data->n_found = 1;
170                 TRACE("Found lang_id %04X for %s_%s\n", LangID, l_data->lang, l_data->country);
171                 return FALSE; /* stop enumeration */
172             }
173         }
174         else /* l_data->country not specified */
175         {
176             if(l_data->n_found < NLS_MAX_LANGUAGES)
177             {
178                 l_data->found_lang_id[l_data->n_found] = LangID;
179                 strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
180                 strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
181                 l_data->n_found++;
182                 TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
183                 return TRUE; /* continue search */
184             }
185         }
186     }
187
188     /* Just in case, check LOCALE_SENGLANGUAGE too,
189      * in hope that possible alias name might have that value.
190      */
191     buf_en_language[0] = 0;
192     GetLocaleInfoA(lcid, LOCALE_SENGLANGUAGE|LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP,
193                    buf_en_language, sizeof(buf_en_language));
194     TRACE("LOCALE_SENGLANGUAGE: %s\n", buf_en_language);
195
196     if(l_data->lang && strlen(l_data->lang) > 0 && !strcasecmp(l_data->lang, buf_en_language))
197     {
198         l_data->found_lang_id[l_data->n_found] = LangID;
199         strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
200         strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
201         l_data->n_found++;
202         TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
203     }
204
205     return TRUE; /* continue search */
206 }
207
208
209 /***********************************************************************
210  *           get_language_id
211  *
212  * INPUT:
213  *      Lang: a string whose two first chars are the iso name of a language.
214  *      Country: a string whose two first chars are the iso name of country
215  *      Charset: a string defining the chosen charset encoding
216  *      Dialect: a string defining a variation of the locale
217  *
218  *      all those values are from the standardized format of locale
219  *      name in unix which is: Lang[_Country][.Charset][@Dialect]
220  *
221  * RETURNS:
222  *      the numeric code of the language used by Windows
223  *
224  * FIXME: Charset and Dialect are not handled
225  */
226 static LANGID get_language_id(LPCSTR Lang, LPCSTR Country, LPCSTR Charset, LPCSTR Dialect)
227 {
228     LANG_FIND_DATA l_data;
229     char lang_string[256];
230
231     if(!Lang)
232     {
233         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
234         goto END;
235     }
236
237     memset(&l_data, 0, sizeof(LANG_FIND_DATA));
238     strncpy(l_data.lang, Lang, sizeof(l_data.lang));
239
240     if(Country && strlen(Country) > 0)
241         strncpy(l_data.country, Country, sizeof(l_data.country));
242
243     EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), RT_STRINGA,
244                            (LPCSTR)LOCALE_ILANGUAGE, find_language_id_proc, (LPARAM)&l_data);
245
246     strcpy(lang_string, l_data.lang);
247     if(l_data.country && strlen(l_data.country) > 0)
248     {
249         strcat(lang_string, "_");
250         strcat(lang_string, l_data.country);
251     }
252
253     if(!l_data.n_found)
254     {
255         if(l_data.country && strlen(l_data.country) > 0)
256         {
257             MESSAGE("Warning: Language '%s' was not found, retrying without country name...\n", lang_string);
258             l_data.country[0] = 0;
259             EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), RT_STRINGA,
260                                    (LPCSTR)LOCALE_ILANGUAGE, find_language_id_proc, (LONG)&l_data);
261         }
262     }
263
264     /* Re-evaluate lang_string */
265     strcpy(lang_string, l_data.lang);
266     if(l_data.country && strlen(l_data.country) > 0)
267     {
268         strcat(lang_string, "_");
269         strcat(lang_string, l_data.country);
270     }
271
272     if(!l_data.n_found)
273     {
274         MESSAGE("Warning: Language '%s' was not recognized, defaulting to English\n", lang_string);
275         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
276     }
277     else
278     {
279         if(l_data.n_found == 1)
280             TRACE("For language '%s' lang_id %04X was found\n", lang_string, l_data.found_lang_id[0]);
281         else /* l_data->n_found > 1 */
282         {
283             int i;
284             MESSAGE("For language '%s' several language ids were found:\n", lang_string);
285             for(i = 0; i < l_data.n_found; i++)
286                 MESSAGE("%s_%s - %04X; ", l_data.found_language[i], l_data.found_country[i], l_data.found_lang_id[i]);
287
288             MESSAGE("\nInstead of using first in the list, suggest to define\n"
289                     "your LANG environment variable like this: LANG=%s_%s\n",
290                     l_data.found_language[0], l_data.found_country[0]);
291         }
292     }
293 END:
294     TRACE("Returning %04X\n", l_data.found_lang_id[0]);
295     return l_data.found_lang_id[0];
296 }
297
298
299 /***********************************************************************
300  *              init_default_lcid
301  */
302 static LCID init_default_lcid(void)
303 {
304     char buf[256];
305     char *lang,*country,*charset,*dialect,*next;
306     LCID ret = 0;
307
308     if (GetEnvironmentVariableA( "LC_ALL", buf, sizeof(buf) ) ||
309         GetEnvironmentVariableA( "LC_CTYPE", buf, sizeof(buf) ) ||
310         GetEnvironmentVariableA( "LANGUAGE", buf, sizeof(buf) ) ||
311         GetEnvironmentVariableA( "LC_MESSAGES", buf, sizeof(buf) ) ||
312         GetEnvironmentVariableA( "LANG", buf, sizeof(buf) ))
313     {
314         if (!strcmp(buf,"POSIX") || !strcmp(buf,"C")) goto done;
315
316         lang=buf;
317
318         do {
319             next=strchr(lang,':'); if (next) *next++='\0';
320             dialect=strchr(lang,'@'); if (dialect) *dialect++='\0';
321             charset=strchr(lang,'.'); if (charset) *charset++='\0';
322             country=strchr(lang,'_'); if (country) *country++='\0';
323
324             ret = get_language_id(lang, country, charset, dialect);
325
326             lang=next;
327         } while (lang && !ret);
328
329         if (!ret) MESSAGE("Warning: language '%s' not recognized, defaulting to English\n", buf);
330     }
331
332  done:
333     if (!ret) ret = MAKELCID( MAKELANGID(LANG_ENGLISH,SUBLANG_DEFAULT), SORT_DEFAULT) ;
334     return ret;
335 }
336
337
338 /******************************************************************************
339  *              get_locale_value_name
340  *
341  * Gets the registry value name for a given lctype.
342  */
343 static const WCHAR *get_locale_value_name( DWORD lctype )
344 {
345     static const WCHAR iCalendarTypeW[] = {'i','C','a','l','e','n','d','a','r','T','y','p','e',0};
346     static const WCHAR iCountryW[] = {'i','C','o','u','n','t','r','y',0};
347     static const WCHAR iCurrDigitsW[] = {'i','C','u','r','r','D','i','g','i','t','s',0};
348     static const WCHAR iCurrencyW[] = {'i','C','u','r','r','e','n','c','y',0};
349     static const WCHAR iDateW[] = {'i','D','a','t','e',0};
350     static const WCHAR iDigitsW[] = {'i','D','i','g','i','t','s',0};
351     static const WCHAR iFirstDayOfWeekW[] = {'i','F','i','r','s','t','D','a','y','O','f','W','e','e','k',0};
352     static const WCHAR iFirstWeekOfYearW[] = {'i','F','i','r','s','t','W','e','e','k','O','f','Y','e','a','r',0};
353     static const WCHAR iLDateW[] = {'i','L','D','a','t','e',0};
354     static const WCHAR iLZeroW[] = {'i','L','Z','e','r','o',0};
355     static const WCHAR iMeasureW[] = {'i','M','e','a','s','u','r','e',0};
356     static const WCHAR iNegCurrW[] = {'i','N','e','g','C','u','r','r',0};
357     static const WCHAR iNegNumberW[] = {'i','N','e','g','N','u','m','b','e','r',0};
358     static const WCHAR iPaperSizeW[] = {'i','P','a','p','e','r','S','i','z','e',0};
359     static const WCHAR iTLZeroW[] = {'i','T','L','Z','e','r','o',0};
360     static const WCHAR iTimeW[] = {'i','T','i','m','e',0};
361     static const WCHAR s1159W[] = {'s','1','1','5','9',0};
362     static const WCHAR s2359W[] = {'s','2','3','5','9',0};
363     static const WCHAR sCountryW[] = {'s','C','o','u','n','t','r','y',0};
364     static const WCHAR sCurrencyW[] = {'s','C','u','r','r','e','n','c','y',0};
365     static const WCHAR sDateW[] = {'s','D','a','t','e',0};
366     static const WCHAR sDecimalW[] = {'s','D','e','c','i','m','a','l',0};
367     static const WCHAR sGroupingW[] = {'s','G','r','o','u','p','i','n','g',0};
368     static const WCHAR sLanguageW[] = {'s','L','a','n','g','u','a','g','e',0};
369     static const WCHAR sListW[] = {'s','L','i','s','t',0};
370     static const WCHAR sLongDateW[] = {'s','L','o','n','g','D','a','t','e',0};
371     static const WCHAR sMonDecimalSepW[] = {'s','M','o','n','D','e','c','i','m','a','l','S','e','p',0};
372     static const WCHAR sMonGroupingW[] = {'s','M','o','n','G','r','o','u','p','i','n','g',0};
373     static const WCHAR sMonThousandSepW[] = {'s','M','o','n','T','h','o','u','s','a','n','d','S','e','p',0};
374     static const WCHAR sNegativeSignW[] = {'s','N','e','g','a','t','i','v','e','S','i','g','n',0};
375     static const WCHAR sPositiveSignW[] = {'s','P','o','s','i','t','i','v','e','S','i','g','n',0};
376     static const WCHAR sShortDateW[] = {'s','S','h','o','r','t','D','a','t','e',0};
377     static const WCHAR sThousandW[] = {'s','T','h','o','u','s','a','n','d',0};
378     static const WCHAR sTimeFormatW[] = {'s','T','i','m','e','F','o','r','m','a','t',0};
379     static const WCHAR sTimeW[] = {'s','T','i','m','e',0};
380     static const WCHAR sYearMonthW[] = {'s','Y','e','a','r','M','o','n','t','h',0};
381
382     switch (lctype & ~LOCALE_LOCALEINFOFLAGSMASK)
383     {
384     /* These values are used by SetLocaleInfo and GetLocaleInfo, and
385      * the values are stored in the registry, confirmed under Windows.
386      */
387     case LOCALE_ICALENDARTYPE:    return iCalendarTypeW;
388     case LOCALE_ICURRDIGITS:      return iCurrDigitsW;
389     case LOCALE_ICURRENCY:        return iCurrencyW;
390     case LOCALE_IDIGITS:          return iDigitsW;
391     case LOCALE_IFIRSTDAYOFWEEK:  return iFirstDayOfWeekW;
392     case LOCALE_IFIRSTWEEKOFYEAR: return iFirstWeekOfYearW;
393     case LOCALE_ILZERO:           return iLZeroW;
394     case LOCALE_IMEASURE:         return iMeasureW;
395     case LOCALE_INEGCURR:         return iNegCurrW;
396     case LOCALE_INEGNUMBER:       return iNegNumberW;
397     case LOCALE_IPAPERSIZE:       return iPaperSizeW;
398     case LOCALE_ITIME:            return iTimeW;
399     case LOCALE_S1159:            return s1159W;
400     case LOCALE_S2359:            return s2359W;
401     case LOCALE_SCURRENCY:        return sCurrencyW;
402     case LOCALE_SDATE:            return sDateW;
403     case LOCALE_SDECIMAL:         return sDecimalW;
404     case LOCALE_SGROUPING:        return sGroupingW;
405     case LOCALE_SLIST:            return sListW;
406     case LOCALE_SLONGDATE:        return sLongDateW;
407     case LOCALE_SMONDECIMALSEP:   return sMonDecimalSepW;
408     case LOCALE_SMONGROUPING:     return sMonGroupingW;
409     case LOCALE_SMONTHOUSANDSEP:  return sMonThousandSepW;
410     case LOCALE_SNEGATIVESIGN:    return sNegativeSignW;
411     case LOCALE_SPOSITIVESIGN:    return sPositiveSignW;
412     case LOCALE_SSHORTDATE:       return sShortDateW;
413     case LOCALE_STHOUSAND:        return sThousandW;
414     case LOCALE_STIME:            return sTimeW;
415     case LOCALE_STIMEFORMAT:      return sTimeFormatW;
416     case LOCALE_SYEARMONTH:       return sYearMonthW;
417
418     /* The following are not listed under MSDN as supported,
419      * but seem to be used and also stored in the registry.
420      */
421     case LOCALE_ICOUNTRY:         return iCountryW;
422     case LOCALE_IDATE:            return iDateW;
423     case LOCALE_ILDATE:           return iLDateW;
424     case LOCALE_ITLZERO:          return iTLZeroW;
425     case LOCALE_SCOUNTRY:         return sCountryW;
426     case LOCALE_SLANGUAGE:        return sLanguageW;
427     }
428     return NULL;
429 }
430
431
432 /******************************************************************************
433  *              get_registry_locale_info
434  *
435  * Retrieve user-modified locale info from the registry.
436  * Return length, 0 on error, -1 if not found.
437  */
438 static INT get_registry_locale_info( LPCWSTR value, LPWSTR buffer, INT len )
439 {
440     DWORD size;
441     INT ret;
442     HKEY hkey;
443     NTSTATUS status;
444     UNICODE_STRING nameW;
445     KEY_VALUE_PARTIAL_INFORMATION *info;
446     static const int info_size = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data);
447
448     if (RegOpenKeyExA( HKEY_CURRENT_USER, "Control Panel\\International", 0, KEY_READ, &hkey))
449         return -1;
450
451     RtlInitUnicodeString( &nameW, value );
452     size = info_size + len * sizeof(WCHAR);
453
454     if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
455     {
456         RegCloseKey( hkey );
457         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
458         return 0;
459     }
460
461     status = NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, info, size, &size );
462     if (status == STATUS_BUFFER_OVERFLOW && !buffer) status = 0;
463
464     if (!status)
465     {
466         ret = (size - info_size) / sizeof(WCHAR);
467         /* append terminating null if needed */
468         if (!ret || ((WCHAR *)info->Data)[ret-1])
469         {
470             if (ret < len || !buffer) ret++;
471             else
472             {
473                 SetLastError( ERROR_INSUFFICIENT_BUFFER );
474                 ret = 0;
475             }
476         }
477         if (ret && buffer)
478         {
479             memcpy( buffer, info->Data, (ret-1) * sizeof(WCHAR) );
480             buffer[ret-1] = 0;
481         }
482     }
483     else
484     {
485         if (status == STATUS_OBJECT_NAME_NOT_FOUND) ret = -1;
486         else
487         {
488             SetLastError( RtlNtStatusToDosError(status) );
489             ret = 0;
490         }
491     }
492     RegCloseKey( hkey );
493     HeapFree( GetProcessHeap(), 0, info );
494     return ret;
495 }
496
497
498 /******************************************************************************
499  *              GetLocaleInfoA (KERNEL32.@)
500  *
501  * NOTES
502  *  LANG_NEUTRAL is equal to LOCALE_SYSTEM_DEFAULT
503  *
504  *  MS online documentation states that the string returned is NULL terminated
505  *  except for LOCALE_FONTSIGNATURE  which "will return a non-NULL
506  *  terminated string".
507  */
508 INT WINAPI GetLocaleInfoA( LCID lcid, LCTYPE lctype, LPSTR buffer, INT len )
509 {
510     WCHAR *bufferW;
511     INT lenW, ret;
512
513     if (len < 0 || (len && !buffer))
514     {
515         SetLastError( ERROR_INVALID_PARAMETER );
516         return 0;
517     }
518     if (!len) buffer = NULL;
519
520     if (!(lenW = GetLocaleInfoW( lcid, lctype, NULL, 0 ))) return 0;
521
522     if (!(bufferW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
523     {
524         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
525         return 0;
526     }
527     if ((ret = GetLocaleInfoW( lcid, lctype, bufferW, lenW )))
528     {
529         if ((lctype & LOCALE_RETURN_NUMBER) ||
530             ((lctype & ~LOCALE_LOCALEINFOFLAGSMASK) == LOCALE_FONTSIGNATURE))
531         {
532             /* it's not an ASCII string, just bytes */
533             ret *= sizeof(WCHAR);
534             if (buffer)
535             {
536                 if (ret <= len) memcpy( buffer, bufferW, ret );
537                 else
538                 {
539                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
540                     ret = 0;
541                 }
542             }
543         }
544         else
545         {
546             UINT codepage = CP_ACP;
547             if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
548             ret = WideCharToMultiByte( codepage, 0, bufferW, ret, buffer, len, NULL, NULL );
549         }
550     }
551     HeapFree( GetProcessHeap(), 0, bufferW );
552     return ret;
553 }
554
555
556 /******************************************************************************
557  *              GetLocaleInfoW (KERNEL32.@)
558  *
559  * NOTES
560  *  LANG_NEUTRAL is equal to LOCALE_SYSTEM_DEFAULT
561  *
562  *  MS online documentation states that the string returned is NULL terminated
563  *  except for LOCALE_FONTSIGNATURE  which "will return a non-NULL
564  *  terminated string".
565  */
566 INT WINAPI GetLocaleInfoW( LCID lcid, LCTYPE lctype, LPWSTR buffer, INT len )
567 {
568     LANGID lang_id;
569     HRSRC hrsrc;
570     HGLOBAL hmem;
571     HMODULE hModule;
572     INT ret;
573     UINT lcflags;
574     const WCHAR *p;
575     int i;
576
577     if (len < 0 || (len && !buffer))
578     {
579         SetLastError( ERROR_INVALID_PARAMETER );
580         return 0;
581     }
582     if (!len) buffer = NULL;
583
584     if (lcid == LOCALE_NEUTRAL || lcid == LANG_SYSTEM_DEFAULT) lcid = GetSystemDefaultLCID();
585     else if (lcid == LANG_USER_DEFAULT) lcid = GetUserDefaultLCID();
586
587     lcflags = lctype & LOCALE_LOCALEINFOFLAGSMASK;
588     lctype &= ~LOCALE_LOCALEINFOFLAGSMASK;
589
590     /* first check for overrides in the registry */
591
592     if (!(lcflags & LOCALE_NOUSEROVERRIDE) && lcid == GetUserDefaultLCID())
593     {
594         const WCHAR *value = get_locale_value_name(lctype);
595
596         if (value && ((ret = get_registry_locale_info( value, buffer, len )) != -1)) return ret;
597     }
598
599     /* now load it from kernel resources */
600
601     lang_id = LANGIDFROMLCID( lcid );
602
603     /* replace SUBLANG_NEUTRAL by SUBLANG_DEFAULT */
604     if (SUBLANGID(lang_id) == SUBLANG_NEUTRAL)
605         lang_id = MAKELANGID(PRIMARYLANGID(lang_id), SUBLANG_DEFAULT);
606
607     hModule = GetModuleHandleA( "kernel32.dll" );
608     if (!(hrsrc = FindResourceExW( hModule, RT_STRINGW, (LPCWSTR)((lctype >> 4) + 1), lang_id )))
609     {
610         SetLastError( ERROR_INVALID_FLAGS );  /* no such lctype */
611         return 0;
612     }
613     if (!(hmem = LoadResource( hModule, hrsrc )))
614         return 0;
615
616     p = LockResource( hmem );
617     for (i = 0; i < (lctype & 0x0f); i++) p += *p + 1;
618
619     if (lcflags & LOCALE_RETURN_NUMBER) ret = sizeof(UINT)/sizeof(WCHAR);
620     else ret = (lctype == LOCALE_FONTSIGNATURE) ? *p : *p + 1;
621
622     if (!buffer) return ret;
623
624     if (ret > len)
625     {
626         SetLastError( ERROR_INSUFFICIENT_BUFFER );
627         return 0;
628     }
629
630     if (lcflags & LOCALE_RETURN_NUMBER)
631     {
632         UINT number;
633         WCHAR *end, *tmp = HeapAlloc( GetProcessHeap(), 0, (*p + 1) * sizeof(WCHAR) );
634         if (!tmp) return 0;
635         memcpy( tmp, p + 1, *p * sizeof(WCHAR) );
636         tmp[*p] = 0;
637         number = strtolW( tmp, &end, 10 );
638         if (!*end)
639             memcpy( buffer, &number, sizeof(number) );
640         else  /* invalid number */
641         {
642             SetLastError( ERROR_INVALID_FLAGS );
643             ret = 0;
644         }
645         HeapFree( GetProcessHeap(), 0, tmp );
646
647         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning number %d\n",
648                lcid, lctype, buffer, len, number );
649     }
650     else
651     {
652         memcpy( buffer, p + 1, *p * sizeof(WCHAR) );
653         if (lctype != LOCALE_FONTSIGNATURE) buffer[ret-1] = 0;
654
655         TRACE( "(lcid=0x%lx,lctype=0x%lx,%p,%d) returning %d %s\n",
656                lcid, lctype, buffer, len, ret, debugstr_w(buffer) );
657     }
658     return ret;
659 }
660
661
662 /******************************************************************************
663  *              SetLocaleInfoA  [KERNEL32.@]
664  */
665 BOOL WINAPI SetLocaleInfoA(LCID lcid, LCTYPE lctype, LPCSTR data)
666 {
667     UINT codepage = CP_ACP;
668     WCHAR *strW;
669     DWORD len;
670     BOOL ret;
671
672     if (lcid == LOCALE_NEUTRAL || lcid == LANG_SYSTEM_DEFAULT) lcid = GetSystemDefaultLCID();
673     else if (lcid == LANG_USER_DEFAULT) lcid = GetUserDefaultLCID();
674
675     if (!(lctype & LOCALE_USE_CP_ACP)) codepage = get_lcid_codepage( lcid );
676     len = MultiByteToWideChar( codepage, 0, data, -1, NULL, 0 );
677     if (!(strW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
678     {
679         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
680         return FALSE;
681     }
682     MultiByteToWideChar( codepage, 0, data, -1, strW, len );
683     ret = SetLocaleInfoW( lcid, lctype, strW );
684     HeapFree( GetProcessHeap(), 0, strW );
685     return ret;
686 }
687
688
689 /******************************************************************************
690  *              SetLocaleInfoW  (KERNEL32.@)
691  */
692 BOOL WINAPI SetLocaleInfoW( LCID lcid, LCTYPE lctype, LPCWSTR data )
693 {
694     const WCHAR *value;
695     const WCHAR intlW[] = {'i','n','t','l',0 };
696     UNICODE_STRING valueW;
697     NTSTATUS status;
698     HKEY hkey;
699
700     if (lcid == LOCALE_NEUTRAL || lcid == LANG_SYSTEM_DEFAULT) lcid = GetSystemDefaultLCID();
701     else if (lcid == LANG_USER_DEFAULT) lcid = GetUserDefaultLCID();
702
703     if (!(value = get_locale_value_name( lctype )))
704     {
705         SetLastError( ERROR_INVALID_PARAMETER );
706         return FALSE;
707     }
708     if (lcid != GetUserDefaultLCID()) return TRUE;  /* fake success */
709
710     TRACE("setting %lx to %s\n", lctype, debugstr_w(data) );
711
712     /* FIXME: should check that data to set is sane */
713
714     /* FIXME: profile functions should map to registry */
715     WriteProfileStringW( intlW, value, data );
716
717     if (RegCreateKeyExA( HKEY_CURRENT_USER, "Control Panel\\International", 0, NULL,
718                          0, KEY_ALL_ACCESS, NULL, &hkey, NULL )) return FALSE;
719     RtlInitUnicodeString( &valueW, value );
720     status = NtSetValueKey( hkey, &valueW, 0, REG_SZ, data, (strlenW(data)+1)*sizeof(WCHAR) );
721     RegCloseKey( hkey );
722
723     if (status) SetLastError( RtlNtStatusToDosError(status) );
724     return !status;
725     return TRUE;
726 }
727
728
729 /***********************************************************************
730  *           GetThreadLocale    (KERNEL32.@)
731  */
732 LCID WINAPI GetThreadLocale(void)
733 {
734     LCID ret = NtCurrentTeb()->CurrentLocale;
735     if (!ret) NtCurrentTeb()->CurrentLocale = ret = GetUserDefaultLCID();
736     return ret;
737 }
738
739
740 /**********************************************************************
741  *           SetThreadLocale    (KERNEL32.@)
742  *
743  * FIXME
744  *  check if lcid is a valid cp
745  */
746 BOOL WINAPI SetThreadLocale( LCID lcid ) /* [in] Locale identifier */
747 {
748     if (lcid == LOCALE_NEUTRAL || lcid == LANG_SYSTEM_DEFAULT) lcid = GetSystemDefaultLCID();
749     else if (lcid == LANG_USER_DEFAULT) lcid = GetUserDefaultLCID();
750
751     NtCurrentTeb()->CurrentLocale = lcid;
752     NtCurrentTeb()->code_page = get_lcid_codepage( lcid );
753     return TRUE;
754 }
755
756
757
758 /******************************************************************************
759  *           GetStringTypeW    (KERNEL32.@)
760  */
761 BOOL WINAPI GetStringTypeW( DWORD type, LPCWSTR src, INT count, LPWORD chartype )
762 {
763     if (count == -1) count = strlenW(src) + 1;
764     switch(type)
765     {
766     case CT_CTYPE1:
767         while (count--) *chartype++ = get_char_typeW( *src++ ) & 0xfff;
768         break;
769     case CT_CTYPE2:
770         while (count--) *chartype++ = get_char_typeW( *src++ ) >> 12;
771         break;
772     case CT_CTYPE3:
773     {
774         WARN("CT_CTYPE3: semi-stub.\n");
775         while (count--)
776         {
777             int c = *src;
778             WORD type1, type3 = 0; /* C3_NOTAPPLICABLE */
779
780             type1 = get_char_typeW( *src++ ) & 0xfff;
781             /* try to construct type3 from type1 */
782             if(type1 & C1_SPACE) type3 |= C3_SYMBOL;
783             if(type1 & C1_ALPHA) type3 |= C3_ALPHA;
784             if ((c>=0x30A0)&&(c<=0x30FF)) type3 |= C3_KATAKANA;
785             if ((c>=0x3040)&&(c<=0x309F)) type3 |= C3_HIRAGANA;
786             if ((c>=0x4E00)&&(c<=0x9FAF)) type3 |= C3_IDEOGRAPH;
787             if ((c>=0x0600)&&(c<=0x06FF)) type3 |= C3_KASHIDA;
788             if ((c>=0x3000)&&(c<=0x303F)) type3 |= C3_SYMBOL;
789
790             if ((c>=0xFF00)&&(c<=0xFF60)) type3 |= C3_FULLWIDTH;
791             if ((c>=0xFF00)&&(c<=0xFF20)) type3 |= C3_SYMBOL;
792             if ((c>=0xFF3B)&&(c<=0xFF40)) type3 |= C3_SYMBOL;
793             if ((c>=0xFF5B)&&(c<=0xFF60)) type3 |= C3_SYMBOL;
794             if ((c>=0xFF21)&&(c<=0xFF3A)) type3 |= C3_ALPHA;
795             if ((c>=0xFF41)&&(c<=0xFF5A)) type3 |= C3_ALPHA;
796             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_FULLWIDTH;
797             if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_SYMBOL;
798
799             if ((c>=0xFF61)&&(c<=0xFFDC)) type3 |= C3_HALFWIDTH;
800             if ((c>=0xFF61)&&(c<=0xFF64)) type3 |= C3_SYMBOL;
801             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_KATAKANA;
802             if ((c>=0xFF65)&&(c<=0xFF9F)) type3 |= C3_ALPHA;
803             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_HALFWIDTH;
804             if ((c>=0xFFE8)&&(c<=0xFFEE)) type3 |= C3_SYMBOL;
805             *chartype++ = type3;
806         }
807         break;
808     }
809     default:
810         SetLastError( ERROR_INVALID_PARAMETER );
811         return FALSE;
812     }
813     return TRUE;
814 }
815
816
817 /******************************************************************************
818  *           GetStringTypeExW    (KERNEL32.@)
819  */
820 BOOL WINAPI GetStringTypeExW( LCID locale, DWORD type, LPCWSTR src, INT count, LPWORD chartype )
821 {
822     /* locale is ignored for Unicode */
823     return GetStringTypeW( type, src, count, chartype );
824 }
825
826
827 /******************************************************************************
828  *           GetStringTypeA    (KERNEL32.@)
829  */
830 BOOL WINAPI GetStringTypeA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
831 {
832     UINT cp;
833     INT countW;
834     LPWSTR srcW;
835     BOOL ret = FALSE;
836
837     if(count == -1) count = strlen(src) + 1;
838
839     if (!(cp = get_lcid_codepage( locale )))
840     {
841         FIXME("For locale %04lx using current ANSI code page\n", locale);
842         cp = GetACP();
843     }
844
845     countW = MultiByteToWideChar(cp, 0, src, count, NULL, 0);
846     if((srcW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
847     {
848         MultiByteToWideChar(cp, 0, src, count, srcW, countW);
849     /*
850      * NOTE: the target buffer has 1 word for each CHARACTER in the source
851      * string, with multibyte characters there maybe be more bytes in count
852      * than character space in the buffer!
853      */
854         ret = GetStringTypeW(type, srcW, countW, chartype);
855         HeapFree(GetProcessHeap(), 0, srcW);
856     }
857     return ret;
858 }
859
860 /******************************************************************************
861  *           GetStringTypeExA    (KERNEL32.@)
862  */
863 BOOL WINAPI GetStringTypeExA( LCID locale, DWORD type, LPCSTR src, INT count, LPWORD chartype )
864 {
865     return GetStringTypeA(locale, type, src, count, chartype);
866 }
867
868
869 /******************************************************************************
870  *              LOCALE_Init
871  */
872 void LOCALE_Init(void)
873 {
874     UINT ansi = 1252, oem = 437, mac = 10000;
875     LCID lcid = init_default_lcid();
876
877     GetLocaleInfoW( lcid, LOCALE_IDEFAULTANSICODEPAGE | LOCALE_RETURN_NUMBER,
878                     (LPWSTR)&ansi, sizeof(ansi)/sizeof(WCHAR) );
879     GetLocaleInfoW( lcid, LOCALE_IDEFAULTMACCODEPAGE | LOCALE_RETURN_NUMBER,
880                     (LPWSTR)&mac, sizeof(mac)/sizeof(WCHAR) );
881     GetLocaleInfoW( lcid, LOCALE_IDEFAULTCODEPAGE | LOCALE_RETURN_NUMBER,
882                     (LPWSTR)&oem, sizeof(oem)/sizeof(WCHAR) );
883
884     CODEPAGE_Init( ansi, oem, mac, lcid );
885     update_registry( lcid );
886 }