1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/intl.cpp
3 // Purpose: Internationalization and localisation for wxWidgets
4 // Author: Vadim Zeitlin
5 // Modified by: Michael N. Filippov <michael@idisys.iae.nsk.su>
6 // (2003/09/30 - PluralForms support)
9 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ============================================================================
15 // ============================================================================
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
29 // The following define is needed by Innotek's libc to
30 // make the definition of struct localeconv available.
31 #define __INTERNAL_DEFS
37 #include "wx/dynarray.h"
38 #include "wx/string.h"
43 #include "wx/hashmap.h"
44 #include "wx/module.h"
54 #ifdef HAVE_LANGINFO_H
59 #include "wx/msw/private.h"
63 #include "wx/filename.h"
64 #include "wx/tokenzr.h"
65 #include "wx/fontmap.h"
66 #include "wx/scopedptr.h"
67 #include "wx/apptrait.h"
68 #include "wx/stdpaths.h"
69 #include "wx/hashset.h"
71 #if defined(__WXOSX__)
72 #include "wx/osx/core/cfref.h"
73 #include <CoreFoundation/CFLocale.h>
74 #include <CoreFoundation/CFDateFormatter.h>
75 #include "wx/osx/core/cfstring.h"
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 // the constants describing the format of ll_CC locale string
83 static const size_t LEN_LANG
= 2;
84 static const size_t LEN_SUBLANG
= 2;
85 static const size_t LEN_FULL
= LEN_LANG
+ 1 + LEN_SUBLANG
; // 1 for '_'
87 #define TRACE_I18N wxS("i18n")
89 // ============================================================================
91 // ============================================================================
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 static wxLocale
*wxSetLocale(wxLocale
*pLocale
);
102 // get just the language part
103 inline wxString
ExtractLang(const wxString
& langFull
)
105 return langFull
.Left(LEN_LANG
);
108 // helper functions of GetSystemLanguage()
111 // get everything else (including the leading '_')
112 inline wxString
ExtractNotLang(const wxString
& langFull
)
114 return langFull
.Mid(LEN_LANG
);
119 } // anonymous namespace
121 // ----------------------------------------------------------------------------
123 // ----------------------------------------------------------------------------
127 // helper used by wxLanguageInfo::GetLocaleName() and elsewhere to determine
128 // whether the locale is Unicode-only (it is if this function returns empty
130 static wxString
wxGetANSICodePageForLocale(LCID lcid
)
135 if ( ::GetLocaleInfo(lcid
, LOCALE_IDEFAULTANSICODEPAGE
,
136 buffer
, WXSIZEOF(buffer
)) > 0 )
138 if ( buffer
[0] != wxT('0') || buffer
[1] != wxT('\0') )
140 //else: this locale doesn't use ANSI code page
146 wxUint32
wxLanguageInfo::GetLCID() const
148 return MAKELCID(MAKELANGID(WinLang
, WinSublang
), SORT_DEFAULT
);
151 wxString
wxLanguageInfo::GetLocaleName() const
155 const LCID lcid
= GetLCID();
158 buffer
[0] = wxT('\0');
159 if ( !::GetLocaleInfo(lcid
, LOCALE_SENGLANGUAGE
, buffer
, WXSIZEOF(buffer
)) )
161 wxLogLastError(wxT("GetLocaleInfo(LOCALE_SENGLANGUAGE)"));
166 if ( ::GetLocaleInfo(lcid
, LOCALE_SENGCOUNTRY
,
167 buffer
, WXSIZEOF(buffer
)) > 0 )
169 locale
<< wxT('_') << buffer
;
172 const wxString cp
= wxGetANSICodePageForLocale(lcid
);
175 locale
<< wxT('.') << cp
;
183 // ----------------------------------------------------------------------------
185 // ----------------------------------------------------------------------------
187 #include "wx/arrimpl.cpp"
188 WX_DECLARE_EXPORTED_OBJARRAY(wxLanguageInfo
, wxLanguageInfoArray
);
189 WX_DEFINE_OBJARRAY(wxLanguageInfoArray
)
191 wxLanguageInfoArray
*wxLocale::ms_languagesDB
= NULL
;
193 /*static*/ void wxLocale::CreateLanguagesDB()
195 if (ms_languagesDB
== NULL
)
197 ms_languagesDB
= new wxLanguageInfoArray
;
202 /*static*/ void wxLocale::DestroyLanguagesDB()
204 delete ms_languagesDB
;
205 ms_languagesDB
= NULL
;
209 void wxLocale::DoCommonInit()
211 m_pszOldLocale
= NULL
;
213 m_pOldLocale
= wxSetLocale(this);
214 wxTranslations::SetNonOwned(&m_translations
);
216 m_language
= wxLANGUAGE_UNKNOWN
;
217 m_initialized
= false;
220 // NB: this function has (desired) side effect of changing current locale
221 bool wxLocale::Init(const wxString
& name
,
222 const wxString
& shortName
,
223 const wxString
& locale
,
225 #if WXWIN_COMPATIBILITY_2_8
226 ,bool bConvertEncoding
230 #if WXWIN_COMPATIBILITY_2_8
231 wxASSERT_MSG( bConvertEncoding
,
232 wxS("wxLocale::Init with bConvertEncoding=false is no longer supported, add charset to your catalogs") );
235 bool ret
= DoInit(name
, shortName
, locale
);
237 // NB: don't use 'lang' here, 'language' may be wxLANGUAGE_DEFAULT
238 m_translations
.SetLanguage(shortName
);
241 m_translations
.AddStdCatalog();
246 bool wxLocale::DoInit(const wxString
& name
,
247 const wxString
& shortName
,
248 const wxString
& locale
)
250 wxASSERT_MSG( !m_initialized
,
251 wxS("you can't call wxLocale::Init more than once") );
253 m_initialized
= true;
255 m_strShort
= shortName
;
256 m_language
= wxLANGUAGE_UNKNOWN
;
258 // change current locale (default: same as long name)
259 wxString
szLocale(locale
);
260 if ( szLocale
.empty() )
262 // the argument to setlocale()
263 szLocale
= shortName
;
265 wxCHECK_MSG( !szLocale
.empty(), false,
266 wxS("no locale to set in wxLocale::Init()") );
269 const char *oldLocale
= wxSetlocale(LC_ALL
, szLocale
);
271 m_pszOldLocale
= wxStrdup(oldLocale
);
273 m_pszOldLocale
= NULL
;
275 if ( m_pszOldLocale
== NULL
)
277 wxLogError(_("locale '%s' can not be set."), szLocale
);
280 // the short name will be used to look for catalog files as well,
281 // so we need something here
282 if ( m_strShort
.empty() ) {
283 // FIXME I don't know how these 2 letter abbreviations are formed,
284 // this wild guess is surely wrong
285 if ( !szLocale
.empty() )
287 m_strShort
+= (wxChar
)wxTolower(szLocale
[0]);
288 if ( szLocale
.length() > 1 )
289 m_strShort
+= (wxChar
)wxTolower(szLocale
[1]);
297 #if defined(__UNIX__) && wxUSE_UNICODE && !defined(__WXMAC__)
298 static const char *wxSetlocaleTryUTF8(int c
, const wxString
& lc
)
300 const char *l
= NULL
;
302 // NB: We prefer to set UTF-8 locale if it's possible and only fall back to
303 // non-UTF-8 locale if it fails
309 buf2
= buf
+ wxS(".UTF-8");
310 l
= wxSetlocale(c
, buf2
);
313 buf2
= buf
+ wxS(".utf-8");
314 l
= wxSetlocale(c
, buf2
);
318 buf2
= buf
+ wxS(".UTF8");
319 l
= wxSetlocale(c
, buf2
);
323 buf2
= buf
+ wxS(".utf8");
324 l
= wxSetlocale(c
, buf2
);
328 // if we can't set UTF-8 locale, try non-UTF-8 one:
330 l
= wxSetlocale(c
, lc
);
335 #define wxSetlocaleTryUTF8(c, lc) wxSetlocale(c, lc)
338 bool wxLocale::Init(int language
, int flags
)
340 #if WXWIN_COMPATIBILITY_2_8
341 wxASSERT_MSG( !(flags
& wxLOCALE_CONV_ENCODING
),
342 wxS("wxLOCALE_CONV_ENCODING is no longer supported, add charset to your catalogs") );
348 if (lang
== wxLANGUAGE_DEFAULT
)
350 // auto detect the language
351 lang
= GetSystemLanguage();
354 // We failed to detect system language, so we will use English:
355 if (lang
== wxLANGUAGE_UNKNOWN
)
360 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
365 wxLogError(wxS("Unknown language %i."), lang
);
369 wxString name
= info
->Description
;
370 wxString canonical
= info
->CanonicalName
;
375 const char *retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
376 #elif defined(__UNIX__) && !defined(__WXMAC__)
377 if (language
!= wxLANGUAGE_DEFAULT
)
378 locale
= info
->CanonicalName
;
380 const char *retloc
= wxSetlocaleTryUTF8(LC_ALL
, locale
);
382 const wxString langOnly
= ExtractLang(locale
);
385 // Some C libraries don't like xx_YY form and require xx only
386 retloc
= wxSetlocaleTryUTF8(LC_ALL
, langOnly
);
390 // some systems (e.g. FreeBSD and HP-UX) don't have xx_YY aliases but
391 // require the full xx_YY.encoding form, so try using UTF-8 because this is
392 // the only thing we can do generically
394 // TODO: add encodings applicable to each language to the lang DB and try
395 // them all in turn here
398 const wxChar
**names
=
399 wxFontMapperBase::GetAllEncodingNames(wxFONTENCODING_UTF8
);
402 retloc
= wxSetlocale(LC_ALL
, locale
+ wxS('.') + *names
++);
407 #endif // wxUSE_FONTMAP
411 // Some C libraries (namely glibc) still use old ISO 639,
412 // so will translate the abbrev for them
414 if ( langOnly
== wxS("he") )
415 localeAlt
= wxS("iw") + ExtractNotLang(locale
);
416 else if ( langOnly
== wxS("id") )
417 localeAlt
= wxS("in") + ExtractNotLang(locale
);
418 else if ( langOnly
== wxS("yi") )
419 localeAlt
= wxS("ji") + ExtractNotLang(locale
);
420 else if ( langOnly
== wxS("nb") )
421 localeAlt
= wxS("no_NO");
422 else if ( langOnly
== wxS("nn") )
423 localeAlt
= wxS("no_NY");
425 if ( !localeAlt
.empty() )
427 retloc
= wxSetlocaleTryUTF8(LC_ALL
, localeAlt
);
429 retloc
= wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(localeAlt
));
437 // at least in AIX 5.2 libc is buggy and the string returned from
438 // setlocale(LC_ALL) can't be passed back to it because it returns 6
439 // strings (one for each locale category), i.e. for C locale we get back
442 // this contradicts IBM own docs but this is not of much help, so just work
443 // around it in the crudest possible manner
444 char* p
= const_cast<char*>(wxStrchr(retloc
, ' '));
449 #elif defined(__WIN32__)
450 const char *retloc
= "C";
451 if ( language
!= wxLANGUAGE_DEFAULT
)
453 if ( info
->WinLang
== 0 )
455 wxLogWarning(wxS("Locale '%s' not supported by OS."), name
.c_str());
456 // retloc already set to "C"
458 else // language supported by Windows
460 // Windows CE doesn't have SetThreadLocale() and there doesn't seem
461 // to be any equivalent
463 const wxUint32 lcid
= info
->GetLCID();
465 // change locale used by Windows functions
466 ::SetThreadLocale(lcid
);
469 // and also call setlocale() to change locale used by the CRT
470 locale
= info
->GetLocaleName();
471 if ( locale
.empty() )
475 else // have a valid locale
477 retloc
= wxSetlocale(LC_ALL
, locale
);
481 else // language == wxLANGUAGE_DEFAULT
483 retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
486 #if wxUSE_UNICODE && (defined(__VISUALC__) || defined(__MINGW32__))
487 // VC++ setlocale() (also used by Mingw) can't set locale to languages that
488 // can only be written using Unicode, therefore wxSetlocale() call fails
489 // for such languages but we don't want to report it as an error -- so that
490 // at least message catalogs can be used.
493 if ( wxGetANSICodePageForLocale(LOCALE_USER_DEFAULT
).empty() )
495 // we set the locale to a Unicode-only language, don't treat the
496 // inability of CRT to use it as an error
500 #endif // CRT not handling Unicode-only languages
504 #elif defined(__WXMAC__)
505 if (lang
== wxLANGUAGE_DEFAULT
)
506 locale
= wxEmptyString
;
508 locale
= info
->CanonicalName
;
510 const char *retloc
= wxSetlocale(LC_ALL
, locale
);
514 // Some C libraries don't like xx_YY form and require xx only
515 retloc
= wxSetlocale(LC_ALL
, ExtractLang(locale
));
520 #define WX_NO_LOCALE_SUPPORT
523 #ifndef WX_NO_LOCALE_SUPPORT
526 wxLogWarning(_("Cannot set locale to language \"%s\"."), name
.c_str());
528 // continue nevertheless and try to load at least the translations for
532 if ( !DoInit(name
, canonical
, retloc
) )
537 if (IsOk()) // setlocale() succeeded
540 // NB: don't use 'lang' here, 'language'
541 m_translations
.SetLanguage(wx_static_cast(wxLanguage
, language
));
543 if ( flags
& wxLOCALE_LOAD_DEFAULT
)
544 m_translations
.AddStdCatalog();
547 #endif // !WX_NO_LOCALE_SUPPORT
550 /*static*/ int wxLocale::GetSystemLanguage()
554 // init i to avoid compiler warning
556 count
= ms_languagesDB
->GetCount();
558 #if defined(__UNIX__)
559 // first get the string identifying the language from the environment
562 wxCFRef
<CFLocaleRef
> userLocaleRef(CFLocaleCopyCurrent());
564 // because the locale identifier (kCFLocaleIdentifier) is formatted a little bit differently, eg
565 // az_Cyrl_AZ@calendar=buddhist;currency=JPY we just recreate the base info as expected by wx here
567 wxCFStringRef
str(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleLanguageCode
)));
568 langFull
= str
.AsString()+"_";
569 str
.reset(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleCountryCode
)));
570 langFull
+= str
.AsString();
572 if (!wxGetEnv(wxS("LC_ALL"), &langFull
) &&
573 !wxGetEnv(wxS("LC_MESSAGES"), &langFull
) &&
574 !wxGetEnv(wxS("LANG"), &langFull
))
576 // no language specified, treat it as English
577 return wxLANGUAGE_ENGLISH_US
;
580 if ( langFull
== wxS("C") || langFull
== wxS("POSIX") )
582 // default C locale is English too
583 return wxLANGUAGE_ENGLISH_US
;
587 // the language string has the following form
589 // lang[_LANG][.encoding][@modifier]
591 // (see environ(5) in the Open Unix specification)
593 // where lang is the primary language, LANG is a sublang/territory,
594 // encoding is the charset to use and modifier "allows the user to select
595 // a specific instance of localization data within a single category"
597 // for example, the following strings are valid:
602 // de_DE.iso88591@euro
604 // for now we don't use the encoding, although we probably should (doing
605 // translations of the msg catalogs on the fly as required) (TODO)
607 // we need the modified for languages like Valencian: ca_ES@valencia
608 // though, remember it
610 size_t posModifier
= langFull
.find_first_of(wxS("@"));
611 if ( posModifier
!= wxString::npos
)
612 modifier
= langFull
.Mid(posModifier
);
614 size_t posEndLang
= langFull
.find_first_of(wxS("@."));
615 if ( posEndLang
!= wxString::npos
)
617 langFull
.Truncate(posEndLang
);
620 // in addition to the format above, we also can have full language names
621 // in LANG env var - for example, SuSE is known to use LANG="german" - so
624 // do we have just the language (or sublang too)?
625 bool justLang
= langFull
.length() == LEN_LANG
;
627 (langFull
.length() == LEN_FULL
&& langFull
[LEN_LANG
] == wxS('_')) )
629 // 0. Make sure the lang is according to latest ISO 639
630 // (this is necessary because glibc uses iw and in instead
631 // of he and id respectively).
633 // the language itself (second part is the dialect/sublang)
634 wxString langOrig
= ExtractLang(langFull
);
637 if ( langOrig
== wxS("iw"))
639 else if (langOrig
== wxS("in"))
641 else if (langOrig
== wxS("ji"))
643 else if (langOrig
== wxS("no_NO"))
645 else if (langOrig
== wxS("no_NY"))
647 else if (langOrig
== wxS("no"))
653 if ( lang
!= langOrig
)
655 langFull
= lang
+ ExtractNotLang(langFull
);
658 // 1. Try to find the language either as is:
659 // a) With modifier if set
660 if ( !modifier
.empty() )
662 wxString langFullWithModifier
= langFull
+ modifier
;
663 for ( i
= 0; i
< count
; i
++ )
665 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFullWithModifier
)
670 // b) Without modifier
671 if ( modifier
.empty() || i
== count
)
673 for ( i
= 0; i
< count
; i
++ )
675 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFull
)
680 // 2. If langFull is of the form xx_YY, try to find xx:
681 if ( i
== count
&& !justLang
)
683 for ( i
= 0; i
< count
; i
++ )
685 if ( ms_languagesDB
->Item(i
).CanonicalName
== lang
)
692 // 3. If langFull is of the form xx, try to find any xx_YY record:
693 if ( i
== count
&& justLang
)
695 for ( i
= 0; i
< count
; i
++ )
697 if ( ExtractLang(ms_languagesDB
->Item(i
).CanonicalName
)
705 else // not standard format
707 // try to find the name in verbose description
708 for ( i
= 0; i
< count
; i
++ )
710 if (ms_languagesDB
->Item(i
).Description
.CmpNoCase(langFull
) == 0)
716 #elif defined(__WIN32__)
717 LCID lcid
= GetUserDefaultLCID();
720 wxUint32 lang
= PRIMARYLANGID(LANGIDFROMLCID(lcid
));
721 wxUint32 sublang
= SUBLANGID(LANGIDFROMLCID(lcid
));
723 for ( i
= 0; i
< count
; i
++ )
725 if (ms_languagesDB
->Item(i
).WinLang
== lang
&&
726 ms_languagesDB
->Item(i
).WinSublang
== sublang
)
732 //else: leave wxlang == wxLANGUAGE_UNKNOWN
737 // we did find a matching entry, use it
738 return ms_languagesDB
->Item(i
).Language
;
741 // no info about this language in the database
742 return wxLANGUAGE_UNKNOWN
;
745 // ----------------------------------------------------------------------------
747 // ----------------------------------------------------------------------------
749 // this is a bit strange as under Windows we get the encoding name using its
750 // numeric value and under Unix we do it the other way round, but this just
751 // reflects the way different systems provide the encoding info
754 wxString
wxLocale::GetSystemEncodingName()
758 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
759 // FIXME: what is the error return value for GetACP()?
760 UINT codepage
= ::GetACP();
761 encname
.Printf(wxS("windows-%u"), codepage
);
762 #elif defined(__WXMAC__)
763 // default is just empty string, this resolves to the default system
765 #elif defined(__UNIX_LIKE__)
767 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
768 // GNU libc provides current character set this way (this conforms
770 char *oldLocale
= strdup(setlocale(LC_CTYPE
, NULL
));
771 setlocale(LC_CTYPE
, "");
772 const char *alang
= nl_langinfo(CODESET
);
773 setlocale(LC_CTYPE
, oldLocale
);
778 encname
= wxString::FromAscii( alang
);
780 else // nl_langinfo() failed
781 #endif // HAVE_LANGINFO_H
783 // if we can't get at the character set directly, try to see if it's in
784 // the environment variables (in most cases this won't work, but I was
786 char *lang
= getenv( "LC_ALL");
787 char *dot
= lang
? strchr(lang
, '.') : NULL
;
790 lang
= getenv( "LC_CTYPE" );
792 dot
= strchr(lang
, '.' );
796 lang
= getenv( "LANG");
798 dot
= strchr(lang
, '.');
803 encname
= wxString::FromAscii( dot
+1 );
812 wxFontEncoding
wxLocale::GetSystemEncoding()
814 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
815 UINT codepage
= ::GetACP();
817 // wxWidgets only knows about CP1250-1257, 874, 932, 936, 949, 950
818 if ( codepage
>= 1250 && codepage
<= 1257 )
820 return (wxFontEncoding
)(wxFONTENCODING_CP1250
+ codepage
- 1250);
823 if ( codepage
== 874 )
825 return wxFONTENCODING_CP874
;
828 if ( codepage
== 932 )
830 return wxFONTENCODING_CP932
;
833 if ( codepage
== 936 )
835 return wxFONTENCODING_CP936
;
838 if ( codepage
== 949 )
840 return wxFONTENCODING_CP949
;
843 if ( codepage
== 950 )
845 return wxFONTENCODING_CP950
;
847 #elif defined(__WXMAC__)
848 CFStringEncoding encoding
= 0 ;
849 encoding
= CFStringGetSystemEncoding() ;
850 return wxMacGetFontEncFromSystemEnc( encoding
) ;
851 #elif defined(__UNIX_LIKE__) && wxUSE_FONTMAP
852 const wxString encname
= GetSystemEncodingName();
853 if ( !encname
.empty() )
855 wxFontEncoding enc
= wxFontMapperBase::GetEncodingFromName(encname
);
857 // on some modern Linux systems (RedHat 8) the default system locale
858 // is UTF8 -- but it isn't supported by wxGTK1 in ANSI build at all so
859 // don't even try to use it in this case
860 #if !wxUSE_UNICODE && \
861 ((defined(__WXGTK__) && !defined(__WXGTK20__)) || defined(__WXMOTIF__))
862 if ( enc
== wxFONTENCODING_UTF8
)
864 // the most similar supported encoding...
865 enc
= wxFONTENCODING_ISO8859_1
;
867 #endif // !wxUSE_UNICODE
869 // GetEncodingFromName() returns wxFONTENCODING_DEFAULT for C locale
870 // (a.k.a. US-ASCII) which is arguably a bug but keep it like this for
871 // backwards compatibility and just take care to not return
872 // wxFONTENCODING_DEFAULT from here as this surely doesn't make sense
873 if ( enc
== wxFONTENCODING_DEFAULT
)
875 // we don't have wxFONTENCODING_ASCII, so use the closest one
876 return wxFONTENCODING_ISO8859_1
;
879 if ( enc
!= wxFONTENCODING_MAX
)
883 //else: return wxFONTENCODING_SYSTEM below
887 return wxFONTENCODING_SYSTEM
;
891 void wxLocale::AddLanguage(const wxLanguageInfo
& info
)
894 ms_languagesDB
->Add(info
);
898 const wxLanguageInfo
*wxLocale::GetLanguageInfo(int lang
)
902 // calling GetLanguageInfo(wxLANGUAGE_DEFAULT) is a natural thing to do, so
904 if ( lang
== wxLANGUAGE_DEFAULT
)
905 lang
= GetSystemLanguage();
907 const size_t count
= ms_languagesDB
->GetCount();
908 for ( size_t i
= 0; i
< count
; i
++ )
910 if ( ms_languagesDB
->Item(i
).Language
== lang
)
912 // We need to create a temporary here in order to make this work with BCC in final build mode
913 wxLanguageInfo
*ptr
= &ms_languagesDB
->Item(i
);
922 wxString
wxLocale::GetLanguageName(int lang
)
924 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
925 return wxEmptyString
;
927 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
929 return wxEmptyString
;
931 return info
->Description
;
935 wxString
wxLocale::GetLanguageCanonicalName(int lang
)
937 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
938 return wxEmptyString
;
940 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
942 return wxEmptyString
;
944 return info
->CanonicalName
;
948 const wxLanguageInfo
*wxLocale::FindLanguageInfo(const wxString
& locale
)
952 const wxLanguageInfo
*infoRet
= NULL
;
954 const size_t count
= ms_languagesDB
->GetCount();
955 for ( size_t i
= 0; i
< count
; i
++ )
957 const wxLanguageInfo
*info
= &ms_languagesDB
->Item(i
);
959 if ( wxStricmp(locale
, info
->CanonicalName
) == 0 ||
960 wxStricmp(locale
, info
->Description
) == 0 )
962 // exact match, stop searching
967 if ( wxStricmp(locale
, info
->CanonicalName
.BeforeFirst(wxS('_'))) == 0 )
969 // a match -- but maybe we'll find an exact one later, so continue
972 // OTOH, maybe we had already found a language match and in this
973 // case don't overwrite it because the entry for the default
974 // country always appears first in ms_languagesDB
983 wxString
wxLocale::GetSysName() const
985 return wxSetlocale(LC_ALL
, NULL
);
989 wxLocale::~wxLocale()
991 // restore old translations object
992 if ( wxTranslations::Get() == &m_translations
)
995 wxTranslations::SetNonOwned(&m_pOldLocale
->m_translations
);
997 wxTranslations::Set(NULL
);
1000 // restore old locale pointer
1001 wxSetLocale(m_pOldLocale
);
1003 wxSetlocale(LC_ALL
, m_pszOldLocale
);
1004 free((wxChar
*)m_pszOldLocale
); // const_cast
1008 // check if the given locale is provided by OS and C run time
1010 bool wxLocale::IsAvailable(int lang
)
1012 const wxLanguageInfo
*info
= wxLocale::GetLanguageInfo(lang
);
1013 wxCHECK_MSG( info
, false, wxS("invalid language") );
1015 #if defined(__WIN32__)
1016 if ( !info
->WinLang
)
1019 if ( !::IsValidLocale(info
->GetLCID(), LCID_INSTALLED
) )
1022 #elif defined(__UNIX__)
1024 // Test if setting the locale works, then set it back.
1025 const char *oldLocale
= wxSetlocaleTryUTF8(LC_ALL
, info
->CanonicalName
);
1028 // Some C libraries don't like xx_YY form and require xx only
1029 oldLocale
= wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(info
->CanonicalName
));
1033 // restore the original locale
1034 wxSetlocale(LC_ALL
, oldLocale
);
1040 // add a catalog to our linked list
1041 bool wxLocale::AddCatalog(const wxString
& szDomain
,
1042 wxLanguage msgIdLanguage
,
1043 const wxString
& msgIdCharset
)
1046 wxUnusedVar(msgIdCharset
);
1047 return m_translations
.AddCatalog(szDomain
, msgIdLanguage
);
1049 return m_translations
.AddCatalog(szDomain
, msgIdLanguage
, msgIdCharset
);
1053 // ----------------------------------------------------------------------------
1054 // accessors for locale-dependent data
1055 // ----------------------------------------------------------------------------
1057 #if defined(__WXMSW__) || defined(__WXOSX__)
1062 // This function translates from Unicode date formats described at
1064 // http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
1066 // to strftime()-like syntax. This translation is not lossless but we try to do
1069 static wxString
TranslateFromUnicodeFormat(const wxString
& fmt
)
1072 fmtWX
.reserve(fmt
.length());
1075 size_t lastCount
= 0;
1077 const char* formatchars
=
1085 for ( wxString::const_iterator p
= fmt
.begin(); /* end handled inside */; ++p
)
1087 if ( p
!= fmt
.end() )
1095 const wxUniChar ch
= (*p
).GetValue();
1096 if ( ch
.IsAscii() && strchr(formatchars
, ch
) )
1098 // these characters come in groups, start counting them
1105 // interpret any special characters we collected so far
1111 switch ( lastCount
)
1115 // these two are the same as we don't distinguish
1116 // between 1 and 2 digits for days
1129 wxFAIL_MSG( "too many 'd's" );
1134 switch ( lastCount
)
1143 wxFAIL_MSG( "wrong number of 'D's" );
1147 switch ( lastCount
)
1155 wxFAIL_MSG( "wrong number of 'w's" );
1159 switch ( lastCount
)
1174 wxFAIL_MSG( "wrong number of 'E's" );
1179 switch ( lastCount
)
1183 // as for 'd' and 'dd' above
1196 wxFAIL_MSG( "too many 'M's" );
1201 switch ( lastCount
)
1213 wxFAIL_MSG( "wrong number of 'y's" );
1218 switch ( lastCount
)
1226 wxFAIL_MSG( "wrong number of 'H's" );
1231 switch ( lastCount
)
1239 wxFAIL_MSG( "wrong number of 'h's" );
1244 switch ( lastCount
)
1252 wxFAIL_MSG( "wrong number of 'm's" );
1257 switch ( lastCount
)
1265 wxFAIL_MSG( "wrong number of 's's" );
1270 // strftime() doesn't have era string,
1271 // ignore this format
1272 wxASSERT_MSG( lastCount
<= 2, "too many 'g's" );
1282 switch ( lastCount
)
1290 wxFAIL_MSG( "too many 't's" );
1295 wxFAIL_MSG( "unreachable" );
1302 if ( p
== fmt
.end() )
1305 // not a special character so must be just a separator, treat as is
1306 if ( *p
== wxT('%') )
1308 // this one needs to be escaped
1318 } // anonymous namespace
1320 #endif // __WXMSW__ || __WXOSX__
1322 #if defined(__WXMSW__)
1327 LCTYPE
GetLCTYPEFormatFromLocalInfo(wxLocaleInfo index
)
1331 case wxLOCALE_SHORT_DATE_FMT
:
1332 return LOCALE_SSHORTDATE
;
1334 case wxLOCALE_LONG_DATE_FMT
:
1335 return LOCALE_SLONGDATE
;
1337 case wxLOCALE_TIME_FMT
:
1338 return LOCALE_STIMEFORMAT
;
1341 wxFAIL_MSG( "no matching LCTYPE" );
1347 } // anonymous namespace
1350 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory
WXUNUSED(cat
))
1352 wxUint32 lcid
= LOCALE_USER_DEFAULT
;
1353 if ( wxGetLocale() )
1355 const wxLanguageInfo
* const
1356 info
= GetLanguageInfo(wxGetLocale()->GetLanguage());
1358 lcid
= info
->GetLCID();
1368 case wxLOCALE_DECIMAL_POINT
:
1369 if ( ::GetLocaleInfo(lcid
, LOCALE_SDECIMAL
, buf
, WXSIZEOF(buf
)) )
1373 case wxLOCALE_SHORT_DATE_FMT
:
1374 case wxLOCALE_LONG_DATE_FMT
:
1375 case wxLOCALE_TIME_FMT
:
1376 if ( ::GetLocaleInfo(lcid
, GetLCTYPEFormatFromLocalInfo(index
),
1377 buf
, WXSIZEOF(buf
)) )
1379 return TranslateFromUnicodeFormat(buf
);
1383 case wxLOCALE_DATE_TIME_FMT
:
1384 // there doesn't seem to be any specific setting for this, so just
1385 // combine date and time ones
1387 // we use the short date because this is what "%c" uses by default
1388 // ("%#c" uses long date but we have no way to specify the
1389 // alternate representation here)
1391 const wxString datefmt
= GetInfo(wxLOCALE_SHORT_DATE_FMT
);
1392 if ( datefmt
.empty() )
1395 const wxString timefmt
= GetInfo(wxLOCALE_TIME_FMT
);
1396 if ( timefmt
.empty() )
1399 str
<< datefmt
<< ' ' << timefmt
;
1404 wxFAIL_MSG( "unknown wxLocaleInfo" );
1410 #elif defined(__WXOSX__)
1413 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory
WXUNUSED(cat
))
1415 CFLocaleRef userLocaleRefRaw
;
1416 if ( wxGetLocale() )
1418 userLocaleRefRaw
= CFLocaleCreate
1420 kCFAllocatorDefault
,
1421 wxCFStringRef(wxGetLocale()->GetCanonicalName())
1424 else // no current locale, use the default one
1426 userLocaleRefRaw
= CFLocaleCopyCurrent();
1429 wxCFRef
<CFLocaleRef
> userLocaleRef(userLocaleRefRaw
);
1431 CFStringRef cfstr
= 0;
1434 case wxLOCALE_THOUSANDS_SEP
:
1435 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleGroupingSeparator
);
1438 case wxLOCALE_DECIMAL_POINT
:
1439 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleDecimalSeparator
);
1442 case wxLOCALE_SHORT_DATE_FMT
:
1443 case wxLOCALE_LONG_DATE_FMT
:
1444 case wxLOCALE_DATE_TIME_FMT
:
1445 case wxLOCALE_TIME_FMT
:
1447 CFDateFormatterStyle dateStyle
= kCFDateFormatterNoStyle
;
1448 CFDateFormatterStyle timeStyle
= kCFDateFormatterNoStyle
;
1451 case wxLOCALE_SHORT_DATE_FMT
:
1452 dateStyle
= kCFDateFormatterShortStyle
;
1454 case wxLOCALE_LONG_DATE_FMT
:
1455 dateStyle
= kCFDateFormatterFullStyle
;
1457 case wxLOCALE_DATE_TIME_FMT
:
1458 dateStyle
= kCFDateFormatterFullStyle
;
1459 timeStyle
= kCFDateFormatterMediumStyle
;
1461 case wxLOCALE_TIME_FMT
:
1462 timeStyle
= kCFDateFormatterMediumStyle
;
1465 wxFAIL_MSG( "unexpected time locale" );
1468 wxCFRef
<CFDateFormatterRef
> dateFormatter( CFDateFormatterCreate
1469 (NULL
, userLocaleRef
, dateStyle
, timeStyle
));
1470 wxCFStringRef cfs
= wxCFRetain( CFDateFormatterGetFormat(dateFormatter
));
1471 wxString format
= TranslateFromUnicodeFormat(cfs
.AsString());
1472 // we always want full years
1473 format
.Replace("%y","%Y");
1479 wxFAIL_MSG( "Unknown locale info" );
1483 wxCFStringRef
str(wxCFRetain(cfstr
));
1484 return str
.AsString();
1487 #else // !__WXMSW__ && !__WXOSX__, assume generic POSIX
1492 wxString
GetDateFormatFromLangInfo(wxLocaleInfo index
)
1494 #ifdef HAVE_LANGINFO_H
1495 // array containing parameters for nl_langinfo() indexes by offset of index
1496 // from wxLOCALE_SHORT_DATE_FMT
1497 static const nl_item items
[] =
1499 D_FMT
, D_T_FMT
, D_T_FMT
, T_FMT
,
1502 const int nlidx
= index
- wxLOCALE_SHORT_DATE_FMT
;
1503 if ( nlidx
< 0 || nlidx
>= (int)WXSIZEOF(items
) )
1505 wxFAIL_MSG( "logic error in GetInfo() code" );
1509 const wxString
fmt(nl_langinfo(items
[nlidx
]));
1511 // just return the format returned by nl_langinfo() except for long date
1512 // format which we need to recover from date/time format ourselves (but not
1513 // if we failed completely)
1514 if ( fmt
.empty() || index
!= wxLOCALE_LONG_DATE_FMT
)
1517 // this is not 100% precise but the idea is that a typical date/time format
1518 // under POSIX systems is a combination of a long date format with time one
1519 // so we should be able to get just the long date format by removing all
1520 // time-specific format specifiers
1521 static const char *timeFmtSpecs
= "HIklMpPrRsSTXzZ";
1522 static const char *timeSep
= " :./-";
1524 wxString fmtDateOnly
;
1525 const wxString::const_iterator end
= fmt
.end();
1526 wxString::const_iterator lastSep
= end
;
1527 for ( wxString::const_iterator p
= fmt
.begin(); p
!= end
; ++p
)
1529 if ( strchr(timeSep
, *p
) )
1531 if ( lastSep
== end
)
1534 // skip it for now, we'll discard it if it's followed by a time
1535 // specifier later or add it to fmtDateOnly if it is not
1540 (p
+ 1 != end
) && strchr(timeFmtSpecs
, p
[1]) )
1542 // time specified found: skip it and any preceding separators
1548 if ( lastSep
!= end
)
1550 fmtDateOnly
+= wxString(lastSep
, p
);
1558 #else // !HAVE_LANGINFO_H
1561 // no fallback, let the application deal with unavailability of
1562 // nl_langinfo() itself as there is no good way for us to do it (well, we
1563 // could try to reverse engineer the format from strftime() output but this
1564 // looks like too much trouble considering the relatively small number of
1565 // systems without nl_langinfo() still in use)
1567 #endif // HAVE_LANGINFO_H/!HAVE_LANGINFO_H
1570 } // anonymous namespace
1573 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory cat
)
1575 lconv
* const lc
= localeconv();
1581 case wxLOCALE_THOUSANDS_SEP
:
1582 if ( cat
== wxLOCALE_CAT_NUMBER
)
1583 return lc
->thousands_sep
;
1584 else if ( cat
== wxLOCALE_CAT_MONEY
)
1585 return lc
->mon_thousands_sep
;
1587 wxFAIL_MSG( "invalid wxLocaleCategory" );
1591 case wxLOCALE_DECIMAL_POINT
:
1592 if ( cat
== wxLOCALE_CAT_NUMBER
)
1593 return lc
->decimal_point
;
1594 else if ( cat
== wxLOCALE_CAT_MONEY
)
1595 return lc
->mon_decimal_point
;
1597 wxFAIL_MSG( "invalid wxLocaleCategory" );
1600 case wxLOCALE_SHORT_DATE_FMT
:
1601 case wxLOCALE_LONG_DATE_FMT
:
1602 case wxLOCALE_DATE_TIME_FMT
:
1603 case wxLOCALE_TIME_FMT
:
1604 if ( cat
!= wxLOCALE_CAT_DATE
&& cat
!= wxLOCALE_CAT_DEFAULT
)
1606 wxFAIL_MSG( "invalid wxLocaleCategory" );
1610 return GetDateFormatFromLangInfo(index
);
1614 wxFAIL_MSG( "unknown wxLocaleInfo value" );
1622 // ----------------------------------------------------------------------------
1623 // global functions and variables
1624 // ----------------------------------------------------------------------------
1626 // retrieve/change current locale
1627 // ------------------------------
1629 // the current locale object
1630 static wxLocale
*g_pLocale
= NULL
;
1632 wxLocale
*wxGetLocale()
1637 wxLocale
*wxSetLocale(wxLocale
*pLocale
)
1639 wxLocale
*pOld
= g_pLocale
;
1640 g_pLocale
= pLocale
;
1646 // ----------------------------------------------------------------------------
1647 // wxLocale module (for lazy destruction of languagesDB)
1648 // ----------------------------------------------------------------------------
1650 class wxLocaleModule
: public wxModule
1652 DECLARE_DYNAMIC_CLASS(wxLocaleModule
)
1663 wxLocale::DestroyLanguagesDB();
1667 IMPLEMENT_DYNAMIC_CLASS(wxLocaleModule
, wxModule
)
1669 #endif // wxUSE_INTL