msctf: Correct index for being unable to pop last context. We need to leave one behind.
[wine] / dlls / msvcrt / locale.c
1 /*
2  * msvcrt.dll locale functions
3  *
4  * Copyright 2000 Jon Griffiths
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <locale.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winuser.h"
31 #include "winnls.h"
32
33 #include "msvcrt.h"
34 #include "mtdll.h"
35
36 #include "wine/debug.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
39
40 /* FIXME: Need to hold locale for each LC_* type and aggregate
41  * string to produce lc_all.
42  */
43 #define MAX_ELEM_LEN 64 /* Max length of country/language/CP string */
44 #define MAX_LOCALE_LENGTH 256
45 char MSVCRT_current_lc_all[MAX_LOCALE_LENGTH] = { 0 };
46 LCID MSVCRT_current_lc_all_lcid = 0;
47 int MSVCRT___lc_codepage = 0;
48 int MSVCRT___lc_collate_cp = 0;
49 HANDLE MSVCRT___lc_handle[MSVCRT_LC_MAX - MSVCRT_LC_MIN + 1] = { 0 };
50
51 /* MT */
52 #define LOCK_LOCALE   _mlock(_SETLOCALE_LOCK);
53 #define UNLOCK_LOCALE _munlock(_SETLOCALE_LOCK);
54
55 #define MSVCRT_LEADBYTE  0x8000
56
57 /* Friendly country strings & iso codes for synonym support.
58  * Based on MS documentation for setlocale().
59  */
60 static const char * const _country_synonyms[] =
61 {
62   "Hong Kong","HK",
63   "Hong-Kong","HK",
64   "New Zealand","NZ",
65   "New-Zealand","NZ",
66   "PR China","CN",
67   "PR-China","CN",
68   "United Kingdom","GB",
69   "United-Kingdom","GB",
70   "Britain","GB",
71   "England","GB",
72   "Great Britain","GB",
73   "United States","US",
74   "United-States","US",
75   "America","US"
76 };
77
78 /* INTERNAL: Map a synonym to an ISO code */
79 static void remap_synonym(char *name)
80 {
81   size_t i;
82   for (i = 0; i < sizeof(_country_synonyms)/sizeof(char*); i += 2 )
83   {
84     if (!strcasecmp(_country_synonyms[i],name))
85     {
86       TRACE(":Mapping synonym %s to %s\n",name,_country_synonyms[i+1]);
87       name[0] = _country_synonyms[i+1][0];
88       name[1] = _country_synonyms[i+1][1];
89       name[2] = '\0';
90       return;
91     }
92   }
93 }
94
95 /* Note: Flags are weighted in order of matching importance */
96 #define FOUND_LANGUAGE         0x4
97 #define FOUND_COUNTRY          0x2
98 #define FOUND_CODEPAGE         0x1
99
100 typedef struct {
101   char search_language[MAX_ELEM_LEN];
102   char search_country[MAX_ELEM_LEN];
103   char search_codepage[MAX_ELEM_LEN];
104   char found_language[MAX_ELEM_LEN];
105   char found_country[MAX_ELEM_LEN];
106   char found_codepage[MAX_ELEM_LEN];
107   unsigned int match_flags;
108   LANGID found_lang_id;
109 } locale_search_t;
110
111 #define CONTINUE_LOOKING TRUE
112 #define STOP_LOOKING     FALSE
113
114 /* INTERNAL: Get and compare locale info with a given string */
115 static int compare_info(LCID lcid, DWORD flags, char* buff, const char* cmp)
116 {
117   buff[0] = 0;
118   GetLocaleInfoA(lcid, flags|LOCALE_NOUSEROVERRIDE,buff, MAX_ELEM_LEN);
119   if (!buff[0] || !cmp[0])
120     return 0;
121   /* Partial matches are allowed, e.g. "Germ" matches "Germany" */
122   return !strncasecmp(cmp, buff, strlen(cmp));
123 }
124
125 static BOOL CALLBACK
126 find_best_locale_proc(HMODULE hModule, LPCSTR type, LPCSTR name, WORD LangID, LONG_PTR lParam)
127 {
128   locale_search_t *res = (locale_search_t *)lParam;
129   const LCID lcid = MAKELCID(LangID, SORT_DEFAULT);
130   char buff[MAX_ELEM_LEN];
131   unsigned int flags = 0;
132
133   if(PRIMARYLANGID(LangID) == LANG_NEUTRAL)
134     return CONTINUE_LOOKING;
135
136   /* Check Language */
137   if (compare_info(lcid,LOCALE_SISO639LANGNAME,buff,res->search_language) ||
138       compare_info(lcid,LOCALE_SABBREVLANGNAME,buff,res->search_language) ||
139       compare_info(lcid,LOCALE_SENGLANGUAGE,buff,res->search_language))
140   {
141     TRACE(":Found language: %s->%s\n", res->search_language, buff);
142     flags |= FOUND_LANGUAGE;
143     memcpy(res->found_language,res->search_language,MAX_ELEM_LEN);
144   }
145   else if (res->match_flags & FOUND_LANGUAGE)
146   {
147     return CONTINUE_LOOKING;
148   }
149
150   /* Check Country */
151   if (compare_info(lcid,LOCALE_SISO3166CTRYNAME,buff,res->search_country) ||
152       compare_info(lcid,LOCALE_SABBREVCTRYNAME,buff,res->search_country) ||
153       compare_info(lcid,LOCALE_SENGCOUNTRY,buff,res->search_country))
154   {
155     TRACE("Found country:%s->%s\n", res->search_country, buff);
156     flags |= FOUND_COUNTRY;
157     memcpy(res->found_country,res->search_country,MAX_ELEM_LEN);
158   }
159   else if (res->match_flags & FOUND_COUNTRY)
160   {
161     return CONTINUE_LOOKING;
162   }
163
164   /* Check codepage */
165   if (compare_info(lcid,LOCALE_IDEFAULTCODEPAGE,buff,res->search_codepage) ||
166       (compare_info(lcid,LOCALE_IDEFAULTANSICODEPAGE,buff,res->search_codepage)))
167   {
168     TRACE("Found codepage:%s->%s\n", res->search_codepage, buff);
169     flags |= FOUND_CODEPAGE;
170     memcpy(res->found_codepage,res->search_codepage,MAX_ELEM_LEN);
171   }
172   else if (res->match_flags & FOUND_CODEPAGE)
173   {
174     return CONTINUE_LOOKING;
175   }
176
177   if (flags > res->match_flags)
178   {
179     /* Found a better match than previously */
180     res->match_flags = flags;
181     res->found_lang_id = LangID;
182   }
183   if ((flags & (FOUND_LANGUAGE | FOUND_COUNTRY | FOUND_CODEPAGE)) ==
184         (FOUND_LANGUAGE | FOUND_COUNTRY | FOUND_CODEPAGE))
185   {
186     TRACE(":found exact locale match\n");
187     return STOP_LOOKING;
188   }
189   return CONTINUE_LOOKING;
190 }
191
192 extern int atoi(const char *);
193
194 /* Internal: Find the LCID for a locale specification */
195 static LCID MSVCRT_locale_to_LCID(locale_search_t* locale)
196 {
197   LCID lcid;
198   EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), (LPSTR)RT_STRING,
199                          (LPCSTR)LOCALE_ILANGUAGE,find_best_locale_proc,
200                          (LONG_PTR)locale);
201
202   if (!locale->match_flags)
203     return 0;
204
205   /* If we were given something that didn't match, fail */
206   if (locale->search_country[0] && !(locale->match_flags & FOUND_COUNTRY))
207     return 0;
208
209   lcid =  MAKELCID(locale->found_lang_id, SORT_DEFAULT);
210
211   /* Populate partial locale, translating LCID to locale string elements */
212   if (!locale->found_codepage[0])
213   {
214     /* Even if a codepage is not enumerated for a locale
215      * it can be set if valid */
216     if (locale->search_codepage[0])
217     {
218       if (IsValidCodePage(atoi(locale->search_codepage)))
219         memcpy(locale->found_codepage,locale->search_codepage,MAX_ELEM_LEN);
220       else
221       {
222         /* Special codepage values: OEM & ANSI */
223         if (strcasecmp(locale->search_codepage,"OCP"))
224         {
225           GetLocaleInfoA(lcid, LOCALE_IDEFAULTCODEPAGE,
226                          locale->found_codepage, MAX_ELEM_LEN);
227         }
228         if (strcasecmp(locale->search_codepage,"ACP"))
229         {
230           GetLocaleInfoA(lcid, LOCALE_IDEFAULTANSICODEPAGE,
231                          locale->found_codepage, MAX_ELEM_LEN);
232         }
233         else
234           return 0;
235
236         if (!atoi(locale->found_codepage))
237            return 0;
238       }
239     }
240     else
241     {
242       /* Prefer ANSI codepages if present */
243       GetLocaleInfoA(lcid, LOCALE_IDEFAULTANSICODEPAGE,
244                      locale->found_codepage, MAX_ELEM_LEN);
245       if (!locale->found_codepage[0] || !atoi(locale->found_codepage))
246           GetLocaleInfoA(lcid, LOCALE_IDEFAULTCODEPAGE,
247                          locale->found_codepage, MAX_ELEM_LEN);
248     }
249   }
250   GetLocaleInfoA(lcid, LOCALE_SENGLANGUAGE|LOCALE_NOUSEROVERRIDE,
251                  locale->found_language, MAX_ELEM_LEN);
252   GetLocaleInfoA(lcid, LOCALE_SENGCOUNTRY|LOCALE_NOUSEROVERRIDE,
253                  locale->found_country, MAX_ELEM_LEN);
254   return lcid;
255 }
256
257 /* INTERNAL: Set ctype behaviour for a codepage */
258 static void msvcrt_set_ctype(unsigned int codepage, LCID lcid)
259 {
260   CPINFO cp;
261
262   memset(&cp, 0, sizeof(CPINFO));
263
264   if (GetCPInfo(codepage, &cp))
265   {
266     int i;
267     char str[3];
268     unsigned char *traverse = cp.LeadByte;
269
270     memset(MSVCRT_current_ctype, 0, sizeof(MSVCRT__ctype));
271     MSVCRT___lc_codepage = codepage;
272     MSVCRT___lc_collate_cp = codepage;
273
274     /* Switch ctype macros to MBCS if needed */
275     MSVCRT___mb_cur_max = cp.MaxCharSize;
276
277     /* Set remaining ctype flags: FIXME: faster way to do this? */
278     str[1] = str[2] = 0;
279     for (i = 0; i < 256; i++)
280     {
281       if (!(MSVCRT__pctype[i] & MSVCRT_LEADBYTE))
282       {
283         str[0] = i;
284         GetStringTypeA(lcid, CT_CTYPE1, str, 1, MSVCRT__pctype + i);
285       }
286     }
287
288     /* Set leadbyte flags */
289     while (traverse[0] || traverse[1])
290     {
291       for( i = traverse[0]; i <= traverse[1]; i++ )
292         MSVCRT_current_ctype[i+1] |= MSVCRT_LEADBYTE;
293       traverse += 2;
294     };
295   }
296 }
297
298
299 /*********************************************************************
300  *              setlocale (MSVCRT.@)
301  */
302 char* CDECL MSVCRT_setlocale(int category, const char* locale)
303 {
304   LCID lcid = 0;
305   locale_search_t lc;
306   int haveLang, haveCountry, haveCP;
307   char* next;
308   int lc_all = 0;
309
310   TRACE("(%d %s)\n",category,locale);
311
312   if (category < MSVCRT_LC_MIN || category > MSVCRT_LC_MAX)
313     return NULL;
314
315   if (locale == NULL)
316   {
317     /* Report the current Locale */
318     return MSVCRT_current_lc_all;
319   }
320
321   LOCK_LOCALE;
322
323   if (locale[0] == 'L' && locale[1] == 'C' && locale[2] == '_')
324   {
325     FIXME(":restore previous locale not implemented!\n");
326     /* FIXME: Easiest way to do this is parse the string and
327      * call this function recursively with its elements,
328      * Where they differ for each lc_ type.
329      */
330     UNLOCK_LOCALE;
331     return MSVCRT_current_lc_all;
332   }
333
334   /* Default Locale: Special case handling */
335   if (!strlen(locale) || ((toupper(locale[0]) == 'C') && !locale[1]))
336   {
337     MSVCRT_current_lc_all[0] = 'C';
338     MSVCRT_current_lc_all[1] = '\0';
339     MSVCRT___lc_codepage = GetACP();
340     MSVCRT___lc_collate_cp = GetACP();
341
342     switch (category) {
343     case MSVCRT_LC_ALL:
344       lc_all = 1; /* Fall through all cases ... */
345     case MSVCRT_LC_COLLATE:
346       if (!lc_all) break;
347     case MSVCRT_LC_CTYPE:
348       /* Restore C locale ctype info */
349       MSVCRT___mb_cur_max = 1;
350       memcpy(MSVCRT_current_ctype, MSVCRT__ctype, sizeof(MSVCRT__ctype));
351       if (!lc_all) break;
352     case MSVCRT_LC_MONETARY:
353       if (!lc_all) break;
354     case MSVCRT_LC_NUMERIC:
355       if (!lc_all) break;
356     case MSVCRT_LC_TIME:
357       break;
358     }
359     UNLOCK_LOCALE;
360     return MSVCRT_current_lc_all;
361   }
362
363   /* Get locale elements */
364   haveLang = haveCountry = haveCP = 0;
365   memset(&lc,0,sizeof(lc));
366
367   next = strchr(locale,'_');
368   if (next && next != locale)
369   {
370     haveLang = 1;
371     memcpy(lc.search_language,locale,next-locale);
372     locale += next-locale+1;
373   }
374
375   next = strchr(locale,'.');
376   if (next)
377   {
378     haveCP = 1;
379     if (next == locale)
380     {
381       locale++;
382       lstrcpynA(lc.search_codepage, locale, MAX_ELEM_LEN);
383     }
384     else
385     {
386       if (haveLang)
387       {
388         haveCountry = 1;
389         memcpy(lc.search_country,locale,next-locale);
390         locale += next-locale+1;
391       }
392       else
393       {
394         haveLang = 1;
395         memcpy(lc.search_language,locale,next-locale);
396         locale += next-locale+1;
397       }
398       lstrcpynA(lc.search_codepage, locale, MAX_ELEM_LEN);
399     }
400   }
401   else
402   {
403     if (haveLang)
404     {
405       haveCountry = 1;
406       lstrcpynA(lc.search_country, locale, MAX_ELEM_LEN);
407     }
408     else
409     {
410       haveLang = 1;
411       lstrcpynA(lc.search_language, locale, MAX_ELEM_LEN);
412     }
413   }
414
415   if (haveCountry)
416     remap_synonym(lc.search_country);
417
418   if (haveCP && !haveCountry && !haveLang)
419   {
420     FIXME(":Codepage only locale not implemented\n");
421     /* FIXME: Use default lang/country and skip locale_to_LCID()
422      * call below...
423      */
424     UNLOCK_LOCALE;
425     return NULL;
426   }
427
428   lcid = MSVCRT_locale_to_LCID(&lc);
429
430   TRACE(":found LCID %d\n",lcid);
431
432   if (lcid == 0)
433   {
434     UNLOCK_LOCALE;
435     return NULL;
436   }
437
438   MSVCRT_current_lc_all_lcid = lcid;
439
440   snprintf(MSVCRT_current_lc_all,MAX_LOCALE_LENGTH,"%s_%s.%s",
441            lc.found_language,lc.found_country,lc.found_codepage);
442
443   switch (category) {
444   case MSVCRT_LC_ALL:
445     lc_all = 1; /* Fall through all cases ... */
446   case MSVCRT_LC_COLLATE:
447     if (!lc_all) break;
448   case MSVCRT_LC_CTYPE:
449     msvcrt_set_ctype(atoi(lc.found_codepage),lcid);
450     if (!lc_all) break;
451   case MSVCRT_LC_MONETARY:
452     if (!lc_all) break;
453   case MSVCRT_LC_NUMERIC:
454     if (!lc_all) break;
455   case MSVCRT_LC_TIME:
456     break;
457   }
458   UNLOCK_LOCALE;
459   return MSVCRT_current_lc_all;
460 }
461
462 /*********************************************************************
463  *              setlocale (MSVCRT.@)
464  */
465 MSVCRT_wchar_t* CDECL MSVCRT__wsetlocale(int category, const MSVCRT_wchar_t* locale)
466 {
467   static MSVCRT_wchar_t fake[] = {
468     'E','n','g','l','i','s','h','_','U','n','i','t','e','d',' ',
469     'S','t','a','t','e','s','.','1','2','5','2',0 };
470
471   FIXME("%d %s\n", category, debugstr_w(locale));
472
473   return fake;
474 }
475
476 /*********************************************************************
477  *              _Getdays (MSVCRT.@)
478  */
479 const char* CDECL _Getdays(void)
480 {
481   static const char MSVCRT_days[] = ":Sun:Sunday:Mon:Monday:Tue:Tuesday:Wed:"
482                             "Wednesday:Thu:Thursday:Fri:Friday:Sat:Saturday";
483   /* FIXME: Use locale */
484   TRACE("(void) semi-stub\n");
485   return MSVCRT_days;
486 }
487
488 /*********************************************************************
489  *              _Getmonths (MSVCRT.@)
490  */
491 const char* CDECL _Getmonths(void)
492 {
493   static const char MSVCRT_months[] = ":Jan:January:Feb:February:Mar:March:Apr:"
494                 "April:May:May:Jun:June:Jul:July:Aug:August:Sep:September:Oct:"
495                 "October:Nov:November:Dec:December";
496   /* FIXME: Use locale */
497   TRACE("(void) semi-stub\n");
498   return MSVCRT_months;
499 }
500
501 /*********************************************************************
502  *              _Gettnames (MSVCRT.@)
503  */
504 const char* CDECL _Gettnames(void)
505 {
506   /* FIXME: */
507   TRACE("(void) stub\n");
508   return "";
509 }
510
511 /*********************************************************************
512  *              _Strftime (MSVCRT.@)
513  */
514 const char* CDECL _Strftime(char *out, unsigned int len, const char *fmt,
515                             const void *tm, void *foo)
516 {
517   /* FIXME: */
518   TRACE("(%p %d %s %p %p) stub\n", out, len, fmt, tm, foo);
519   return "";
520 }
521
522 /*********************************************************************
523  *              __crtLCMapStringA (MSVCRT.@)
524  */
525 int CDECL __crtLCMapStringA(
526   LCID lcid, DWORD mapflags, const char* src, int srclen, char* dst,
527   int dstlen, unsigned int codepage, int xflag
528 ) {
529   FIXME("(lcid %x, flags %x, %s(%d), %p(%d), %x, %d), partial stub!\n",
530         lcid,mapflags,src,srclen,dst,dstlen,codepage,xflag);
531   /* FIXME: A bit incorrect. But msvcrt itself just converts its
532    * arguments to wide strings and then calls LCMapStringW
533    */
534   return LCMapStringA(lcid,mapflags,src,srclen,dst,dstlen);
535 }
536
537 /*********************************************************************
538  *              __crtCompareStringA (MSVCRT.@)
539  */
540 int CDECL __crtCompareStringA( LCID lcid, DWORD flags, const char *src1, int len1,
541                                const char *src2, int len2 )
542 {
543     FIXME("(lcid %x, flags %x, %s(%d), %s(%d), partial stub\n",
544           lcid, flags, debugstr_a(src1), len1, debugstr_a(src2), len2 );
545     /* FIXME: probably not entirely right */
546     return CompareStringA( lcid, flags, src1, len1, src2, len2 );
547 }
548
549 /*********************************************************************
550  *              __crtCompareStringW (MSVCRT.@)
551  */
552 int CDECL __crtCompareStringW( LCID lcid, DWORD flags, const MSVCRT_wchar_t *src1, int len1,
553                                const MSVCRT_wchar_t *src2, int len2 )
554 {
555     FIXME("(lcid %x, flags %x, %s(%d), %s(%d), partial stub\n",
556           lcid, flags, debugstr_w(src1), len1, debugstr_w(src2), len2 );
557     /* FIXME: probably not entirely right */
558     return CompareStringW( lcid, flags, src1, len1, src2, len2 );
559 }
560
561 /*********************************************************************
562  *              __crtGetLocaleInfoW (MSVCRT.@)
563  */
564 int CDECL __crtGetLocaleInfoW( LCID lcid, LCTYPE type, MSVCRT_wchar_t *buffer, int len )
565 {
566     FIXME("(lcid %x, type %x, %p(%d), partial stub\n", lcid, type, buffer, len );
567     /* FIXME: probably not entirely right */
568     return GetLocaleInfoW( lcid, type, buffer, len );
569 }
570
571 /*********************************************************************
572  *              localeconv (MSVCRT.@)
573  */
574 struct MSVCRT_lconv * CDECL MSVCRT_localeconv(void) {
575
576   struct lconv *ylconv;
577   static struct MSVCRT_lconv xlconv;
578
579   ylconv = localeconv();
580
581 #define X(x) xlconv.x = ylconv->x;
582   X(decimal_point);
583   X(thousands_sep);
584   X(grouping);
585   X(int_curr_symbol);
586   X(currency_symbol);
587   X(mon_decimal_point);
588   X(mon_thousands_sep);
589   X(mon_grouping);
590   X(positive_sign);
591   X(negative_sign);
592   X(int_frac_digits);
593   X(frac_digits);
594   X(p_cs_precedes);
595   X(p_sep_by_space);
596   X(n_cs_precedes);
597   X(n_sep_by_space);
598   X(p_sign_posn);
599   X(n_sign_posn);
600   return &xlconv;
601 }
602
603 /*********************************************************************
604  *              __lconv_init (MSVCRT.@)
605  */
606 void CDECL __lconv_init(void)
607 {
608   FIXME(" stub\n");
609 }