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 #define TRACE_I18N wxS("i18n")
84 // ============================================================================
86 // ============================================================================
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 static wxLocale
*wxSetLocale(wxLocale
*pLocale
);
97 // get just the language part ("en" in "en_GB")
98 inline wxString
ExtractLang(const wxString
& langFull
)
100 return langFull
.BeforeFirst('_');
103 // helper functions of GetSystemLanguage()
106 // get everything else (including the leading '_')
107 inline wxString
ExtractNotLang(const wxString
& langFull
)
109 size_t pos
= langFull
.find('_');
110 if ( pos
!= wxString::npos
)
111 return langFull
.substr(pos
);
118 } // anonymous namespace
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
126 // helper used by wxLanguageInfo::GetLocaleName() and elsewhere to determine
127 // whether the locale is Unicode-only (it is if this function returns empty
129 static wxString
wxGetANSICodePageForLocale(LCID lcid
)
134 if ( ::GetLocaleInfo(lcid
, LOCALE_IDEFAULTANSICODEPAGE
,
135 buffer
, WXSIZEOF(buffer
)) > 0 )
137 if ( buffer
[0] != wxT('0') || buffer
[1] != wxT('\0') )
139 //else: this locale doesn't use ANSI code page
145 wxUint32
wxLanguageInfo::GetLCID() const
147 return MAKELCID(MAKELANGID(WinLang
, WinSublang
), SORT_DEFAULT
);
150 wxString
wxLanguageInfo::GetLocaleName() const
154 const LCID lcid
= GetLCID();
157 buffer
[0] = wxT('\0');
158 if ( !::GetLocaleInfo(lcid
, LOCALE_SENGLANGUAGE
, buffer
, WXSIZEOF(buffer
)) )
160 wxLogLastError(wxT("GetLocaleInfo(LOCALE_SENGLANGUAGE)"));
165 if ( ::GetLocaleInfo(lcid
, LOCALE_SENGCOUNTRY
,
166 buffer
, WXSIZEOF(buffer
)) > 0 )
168 locale
<< wxT('_') << buffer
;
171 const wxString cp
= wxGetANSICodePageForLocale(lcid
);
174 locale
<< wxT('.') << cp
;
180 #endif // __WINDOWS__
182 // ----------------------------------------------------------------------------
184 // ----------------------------------------------------------------------------
186 #include "wx/arrimpl.cpp"
187 WX_DECLARE_EXPORTED_OBJARRAY(wxLanguageInfo
, wxLanguageInfoArray
);
188 WX_DEFINE_OBJARRAY(wxLanguageInfoArray
)
190 wxLanguageInfoArray
*wxLocale::ms_languagesDB
= NULL
;
192 /*static*/ void wxLocale::CreateLanguagesDB()
194 if (ms_languagesDB
== NULL
)
196 ms_languagesDB
= new wxLanguageInfoArray
;
201 /*static*/ void wxLocale::DestroyLanguagesDB()
203 wxDELETE(ms_languagesDB
);
207 void wxLocale::DoCommonInit()
209 // Store the current locale in order to be able to restore it in the dtor.
210 m_pszOldLocale
= wxSetlocale(LC_ALL
, NULL
);
211 if ( m_pszOldLocale
)
212 m_pszOldLocale
= wxStrdup(m_pszOldLocale
);
215 m_pOldLocale
= wxSetLocale(this);
217 // Set translations object, but only if the user didn't do so yet.
218 // This is to preserve compatibility with wx-2.8 where wxLocale was
219 // the only API for translations. wxLocale works as a stack, with
220 // latest-created one being the active one:
221 // wxLocale loc_fr(wxLANGUAGE_FRENCH);
222 // // _() returns French
224 // wxLocale loc_cs(wxLANGUAGE_CZECH);
225 // // _() returns Czech
227 // // _() returns French again
228 wxTranslations
*oldTrans
= wxTranslations::Get();
230 (m_pOldLocale
&& oldTrans
== &m_pOldLocale
->m_translations
) )
232 wxTranslations::SetNonOwned(&m_translations
);
235 m_language
= wxLANGUAGE_UNKNOWN
;
236 m_initialized
= false;
239 // NB: this function has (desired) side effect of changing current locale
240 bool wxLocale::Init(const wxString
& name
,
241 const wxString
& shortName
,
242 const wxString
& locale
,
244 #if WXWIN_COMPATIBILITY_2_8
245 ,bool WXUNUSED_UNLESS_DEBUG(bConvertEncoding
)
249 #if WXWIN_COMPATIBILITY_2_8
250 wxASSERT_MSG( bConvertEncoding
,
251 wxS("wxLocale::Init with bConvertEncoding=false is no longer supported, add charset to your catalogs") );
254 bool ret
= DoInit(name
, shortName
, locale
);
256 // NB: don't use 'lang' here, 'language' may be wxLANGUAGE_DEFAULT
257 wxTranslations
*t
= wxTranslations::Get();
260 t
->SetLanguage(shortName
);
269 bool wxLocale::DoInit(const wxString
& name
,
270 const wxString
& shortName
,
271 const wxString
& locale
)
273 wxASSERT_MSG( !m_initialized
,
274 wxS("you can't call wxLocale::Init more than once") );
276 m_initialized
= true;
278 m_strShort
= shortName
;
279 m_language
= wxLANGUAGE_UNKNOWN
;
281 // change current locale (default: same as long name)
282 wxString
szLocale(locale
);
283 if ( szLocale
.empty() )
285 // the argument to setlocale()
286 szLocale
= shortName
;
288 wxCHECK_MSG( !szLocale
.empty(), false,
289 wxS("no locale to set in wxLocale::Init()") );
292 if ( !wxSetlocale(LC_ALL
, szLocale
) )
294 wxLogError(_("locale '%s' cannot be set."), szLocale
);
297 // the short name will be used to look for catalog files as well,
298 // so we need something here
299 if ( m_strShort
.empty() ) {
300 // FIXME I don't know how these 2 letter abbreviations are formed,
301 // this wild guess is surely wrong
302 if ( !szLocale
.empty() )
304 m_strShort
+= (wxChar
)wxTolower(szLocale
[0]);
305 if ( szLocale
.length() > 1 )
306 m_strShort
+= (wxChar
)wxTolower(szLocale
[1]);
314 #if defined(__UNIX__) && wxUSE_UNICODE && !defined(__WXMAC__)
315 static const char *wxSetlocaleTryUTF8(int c
, const wxString
& lc
)
317 const char *l
= NULL
;
319 // NB: We prefer to set UTF-8 locale if it's possible and only fall back to
320 // non-UTF-8 locale if it fails
326 buf2
= buf
+ wxS(".UTF-8");
327 l
= wxSetlocale(c
, buf2
);
330 buf2
= buf
+ wxS(".utf-8");
331 l
= wxSetlocale(c
, buf2
);
335 buf2
= buf
+ wxS(".UTF8");
336 l
= wxSetlocale(c
, buf2
);
340 buf2
= buf
+ wxS(".utf8");
341 l
= wxSetlocale(c
, buf2
);
345 // if we can't set UTF-8 locale, try non-UTF-8 one:
347 l
= wxSetlocale(c
, lc
);
352 #define wxSetlocaleTryUTF8(c, lc) wxSetlocale(c, lc)
355 bool wxLocale::Init(int language
, int flags
)
357 #if WXWIN_COMPATIBILITY_2_8
358 wxASSERT_MSG( !(flags
& wxLOCALE_CONV_ENCODING
),
359 wxS("wxLOCALE_CONV_ENCODING is no longer supported, add charset to your catalogs") );
365 if (lang
== wxLANGUAGE_DEFAULT
)
367 // auto detect the language
368 lang
= GetSystemLanguage();
371 // We failed to detect system language, so we will use English:
372 if (lang
== wxLANGUAGE_UNKNOWN
)
377 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
382 wxLogError(wxS("Unknown language %i."), lang
);
386 wxString name
= info
->Description
;
387 wxString canonical
= info
->CanonicalName
;
392 const char *retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
393 #elif defined(__UNIX__) && !defined(__WXMAC__)
394 if (language
!= wxLANGUAGE_DEFAULT
)
395 locale
= info
->CanonicalName
;
397 const char *retloc
= wxSetlocaleTryUTF8(LC_ALL
, locale
);
399 const wxString langOnly
= ExtractLang(locale
);
402 // Some C libraries don't like xx_YY form and require xx only
403 retloc
= wxSetlocaleTryUTF8(LC_ALL
, langOnly
);
407 // some systems (e.g. FreeBSD and HP-UX) don't have xx_YY aliases but
408 // require the full xx_YY.encoding form, so try using UTF-8 because this is
409 // the only thing we can do generically
411 // TODO: add encodings applicable to each language to the lang DB and try
412 // them all in turn here
415 const wxChar
**names
=
416 wxFontMapperBase::GetAllEncodingNames(wxFONTENCODING_UTF8
);
419 retloc
= wxSetlocale(LC_ALL
, locale
+ wxS('.') + *names
++);
424 #endif // wxUSE_FONTMAP
428 // Some C libraries (namely glibc) still use old ISO 639,
429 // so will translate the abbrev for them
431 if ( langOnly
== wxS("he") )
432 localeAlt
= wxS("iw") + ExtractNotLang(locale
);
433 else if ( langOnly
== wxS("id") )
434 localeAlt
= wxS("in") + ExtractNotLang(locale
);
435 else if ( langOnly
== wxS("yi") )
436 localeAlt
= wxS("ji") + ExtractNotLang(locale
);
437 else if ( langOnly
== wxS("nb") )
438 localeAlt
= wxS("no_NO");
439 else if ( langOnly
== wxS("nn") )
440 localeAlt
= wxS("no_NY");
442 if ( !localeAlt
.empty() )
444 retloc
= wxSetlocaleTryUTF8(LC_ALL
, localeAlt
);
446 retloc
= wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(localeAlt
));
454 // at least in AIX 5.2 libc is buggy and the string returned from
455 // setlocale(LC_ALL) can't be passed back to it because it returns 6
456 // strings (one for each locale category), i.e. for C locale we get back
459 // this contradicts IBM own docs but this is not of much help, so just work
460 // around it in the crudest possible manner
461 char* p
= const_cast<char*>(wxStrchr(retloc
, ' '));
466 #elif defined(__WIN32__)
467 const char *retloc
= "C";
468 if ( language
!= wxLANGUAGE_DEFAULT
)
470 if ( info
->WinLang
== 0 )
472 wxLogWarning(wxS("Locale '%s' not supported by OS."), name
.c_str());
473 // retloc already set to "C"
475 else // language supported by Windows
477 // Windows CE doesn't have SetThreadLocale() and there doesn't seem
478 // to be any equivalent
480 const wxUint32 lcid
= info
->GetLCID();
482 // change locale used by Windows functions
483 ::SetThreadLocale(lcid
);
486 // and also call setlocale() to change locale used by the CRT
487 locale
= info
->GetLocaleName();
488 if ( locale
.empty() )
492 else // have a valid locale
494 retloc
= wxSetlocale(LC_ALL
, locale
);
498 else // language == wxLANGUAGE_DEFAULT
500 retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
503 #if wxUSE_UNICODE && (defined(__VISUALC__) || defined(__MINGW32__))
504 // VC++ setlocale() (also used by Mingw) can't set locale to languages that
505 // can only be written using Unicode, therefore wxSetlocale() call fails
506 // for such languages but we don't want to report it as an error -- so that
507 // at least message catalogs can be used.
510 if ( wxGetANSICodePageForLocale(LOCALE_USER_DEFAULT
).empty() )
512 // we set the locale to a Unicode-only language, don't treat the
513 // inability of CRT to use it as an error
517 #endif // CRT not handling Unicode-only languages
521 #elif defined(__WXMAC__)
522 if (lang
== wxLANGUAGE_DEFAULT
)
523 locale
= wxEmptyString
;
525 locale
= info
->CanonicalName
;
527 const char *retloc
= wxSetlocale(LC_ALL
, locale
);
531 // Some C libraries don't like xx_YY form and require xx only
532 retloc
= wxSetlocale(LC_ALL
, ExtractLang(locale
));
537 #define WX_NO_LOCALE_SUPPORT
540 #ifndef WX_NO_LOCALE_SUPPORT
543 wxLogWarning(_("Cannot set locale to language \"%s\"."), name
.c_str());
545 // continue nevertheless and try to load at least the translations for
549 if ( !DoInit(name
, canonical
, retloc
) )
554 if (IsOk()) // setlocale() succeeded
557 // NB: don't use 'lang' here, 'language'
558 wxTranslations
*t
= wxTranslations::Get();
561 t
->SetLanguage(static_cast<wxLanguage
>(language
));
563 if ( flags
& wxLOCALE_LOAD_DEFAULT
)
568 #endif // !WX_NO_LOCALE_SUPPORT
575 // Small helper function: get the value of the given environment variable and
576 // return true only if the variable was found and has non-empty value.
577 inline bool wxGetNonEmptyEnvVar(const wxString
& name
, wxString
* value
)
579 return wxGetEnv(name
, value
) && !value
->empty();
583 } // anonymous namespace
585 /*static*/ int wxLocale::GetSystemLanguage()
589 // init i to avoid compiler warning
591 count
= ms_languagesDB
->GetCount();
593 #if defined(__UNIX__)
594 // first get the string identifying the language from the environment
597 wxCFRef
<CFLocaleRef
> userLocaleRef(CFLocaleCopyCurrent());
599 // because the locale identifier (kCFLocaleIdentifier) is formatted a little bit differently, eg
600 // az_Cyrl_AZ@calendar=buddhist;currency=JPY we just recreate the base info as expected by wx here
602 wxCFStringRef
str(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleLanguageCode
)));
603 langFull
= str
.AsString()+"_";
604 str
.reset(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleCountryCode
)));
605 langFull
+= str
.AsString();
607 if (!wxGetNonEmptyEnvVar(wxS("LC_ALL"), &langFull
) &&
608 !wxGetNonEmptyEnvVar(wxS("LC_MESSAGES"), &langFull
) &&
609 !wxGetNonEmptyEnvVar(wxS("LANG"), &langFull
))
611 // no language specified, treat it as English
612 return wxLANGUAGE_ENGLISH_US
;
615 if ( langFull
== wxS("C") || langFull
== wxS("POSIX") )
617 // default C locale is English too
618 return wxLANGUAGE_ENGLISH_US
;
622 // the language string has the following form
624 // lang[_LANG][.encoding][@modifier]
626 // (see environ(5) in the Open Unix specification)
628 // where lang is the primary language, LANG is a sublang/territory,
629 // encoding is the charset to use and modifier "allows the user to select
630 // a specific instance of localization data within a single category"
632 // for example, the following strings are valid:
637 // de_DE.iso88591@euro
639 // for now we don't use the encoding, although we probably should (doing
640 // translations of the msg catalogs on the fly as required) (TODO)
642 // we need the modified for languages like Valencian: ca_ES@valencia
643 // though, remember it
645 size_t posModifier
= langFull
.find_first_of(wxS("@"));
646 if ( posModifier
!= wxString::npos
)
647 modifier
= langFull
.Mid(posModifier
);
649 size_t posEndLang
= langFull
.find_first_of(wxS("@."));
650 if ( posEndLang
!= wxString::npos
)
652 langFull
.Truncate(posEndLang
);
655 // do we have just the language (or sublang too)?
656 const bool justLang
= langFull
.find('_') == wxString::npos
;
658 // 0. Make sure the lang is according to latest ISO 639
659 // (this is necessary because glibc uses iw and in instead
660 // of he and id respectively).
662 // the language itself (second part is the dialect/sublang)
663 wxString langOrig
= ExtractLang(langFull
);
666 if ( langOrig
== wxS("iw"))
668 else if (langOrig
== wxS("in"))
670 else if (langOrig
== wxS("ji"))
672 else if (langOrig
== wxS("no_NO"))
674 else if (langOrig
== wxS("no_NY"))
676 else if (langOrig
== wxS("no"))
682 if ( lang
!= langOrig
)
684 langFull
= lang
+ ExtractNotLang(langFull
);
687 // 1. Try to find the language either as is:
688 // a) With modifier if set
689 if ( !modifier
.empty() )
691 wxString langFullWithModifier
= langFull
+ modifier
;
692 for ( i
= 0; i
< count
; i
++ )
694 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFullWithModifier
)
699 // b) Without modifier
700 if ( modifier
.empty() || i
== count
)
702 for ( i
= 0; i
< count
; i
++ )
704 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFull
)
709 // 2. If langFull is of the form xx_YY, try to find xx:
710 if ( i
== count
&& !justLang
)
712 for ( i
= 0; i
< count
; i
++ )
714 if ( ms_languagesDB
->Item(i
).CanonicalName
== lang
)
721 // 3. If langFull is of the form xx, try to find any xx_YY record:
722 if ( i
== count
&& justLang
)
724 for ( i
= 0; i
< count
; i
++ )
726 if ( ExtractLang(ms_languagesDB
->Item(i
).CanonicalName
)
737 // In addition to the format above, we also can have full language
738 // names in LANG env var - for example, SuSE is known to use
739 // LANG="german" - so check for use of non-standard format and try to
740 // find the name in verbose description.
741 for ( i
= 0; i
< count
; i
++ )
743 if (ms_languagesDB
->Item(i
).Description
.CmpNoCase(langFull
) == 0)
749 #elif defined(__WIN32__)
750 LCID lcid
= GetUserDefaultLCID();
753 wxUint32 lang
= PRIMARYLANGID(LANGIDFROMLCID(lcid
));
754 wxUint32 sublang
= SUBLANGID(LANGIDFROMLCID(lcid
));
756 for ( i
= 0; i
< count
; i
++ )
758 if (ms_languagesDB
->Item(i
).WinLang
== lang
&&
759 ms_languagesDB
->Item(i
).WinSublang
== sublang
)
765 //else: leave wxlang == wxLANGUAGE_UNKNOWN
770 // we did find a matching entry, use it
771 return ms_languagesDB
->Item(i
).Language
;
774 // no info about this language in the database
775 return wxLANGUAGE_UNKNOWN
;
778 // ----------------------------------------------------------------------------
780 // ----------------------------------------------------------------------------
782 // this is a bit strange as under Windows we get the encoding name using its
783 // numeric value and under Unix we do it the other way round, but this just
784 // reflects the way different systems provide the encoding info
787 wxString
wxLocale::GetSystemEncodingName()
791 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
792 // FIXME: what is the error return value for GetACP()?
793 UINT codepage
= ::GetACP();
794 encname
.Printf(wxS("windows-%u"), codepage
);
795 #elif defined(__WXMAC__)
796 encname
= wxCFStringRef::AsString(
797 CFStringGetNameOfEncoding(CFStringGetSystemEncoding())
799 #elif defined(__UNIX_LIKE__)
801 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
802 // GNU libc provides current character set this way (this conforms
804 char *oldLocale
= strdup(setlocale(LC_CTYPE
, NULL
));
805 setlocale(LC_CTYPE
, "");
806 const char *alang
= nl_langinfo(CODESET
);
807 setlocale(LC_CTYPE
, oldLocale
);
812 encname
= wxString::FromAscii( alang
);
814 else // nl_langinfo() failed
815 #endif // HAVE_LANGINFO_H
817 // if we can't get at the character set directly, try to see if it's in
818 // the environment variables (in most cases this won't work, but I was
820 char *lang
= getenv( "LC_ALL");
821 char *dot
= lang
? strchr(lang
, '.') : NULL
;
824 lang
= getenv( "LC_CTYPE" );
826 dot
= strchr(lang
, '.' );
830 lang
= getenv( "LANG");
832 dot
= strchr(lang
, '.');
837 encname
= wxString::FromAscii( dot
+1 );
846 wxFontEncoding
wxLocale::GetSystemEncoding()
848 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
849 UINT codepage
= ::GetACP();
851 // wxWidgets only knows about CP1250-1257, 874, 932, 936, 949, 950
852 if ( codepage
>= 1250 && codepage
<= 1257 )
854 return (wxFontEncoding
)(wxFONTENCODING_CP1250
+ codepage
- 1250);
857 if ( codepage
== 874 )
859 return wxFONTENCODING_CP874
;
862 if ( codepage
== 932 )
864 return wxFONTENCODING_CP932
;
867 if ( codepage
== 936 )
869 return wxFONTENCODING_CP936
;
872 if ( codepage
== 949 )
874 return wxFONTENCODING_CP949
;
877 if ( codepage
== 950 )
879 return wxFONTENCODING_CP950
;
881 #elif defined(__WXMAC__)
882 CFStringEncoding encoding
= 0 ;
883 encoding
= CFStringGetSystemEncoding() ;
884 return wxMacGetFontEncFromSystemEnc( encoding
) ;
885 #elif defined(__UNIX_LIKE__) && wxUSE_FONTMAP
886 const wxString encname
= GetSystemEncodingName();
887 if ( !encname
.empty() )
889 wxFontEncoding enc
= wxFontMapperBase::GetEncodingFromName(encname
);
891 // on some modern Linux systems (RedHat 8) the default system locale
892 // is UTF8 -- but it isn't supported by wxGTK1 in ANSI build at all so
893 // don't even try to use it in this case
894 #if !wxUSE_UNICODE && \
895 ((defined(__WXGTK__) && !defined(__WXGTK20__)) || defined(__WXMOTIF__))
896 if ( enc
== wxFONTENCODING_UTF8
)
898 // the most similar supported encoding...
899 enc
= wxFONTENCODING_ISO8859_1
;
901 #endif // !wxUSE_UNICODE
903 // GetEncodingFromName() returns wxFONTENCODING_DEFAULT for C locale
904 // (a.k.a. US-ASCII) which is arguably a bug but keep it like this for
905 // backwards compatibility and just take care to not return
906 // wxFONTENCODING_DEFAULT from here as this surely doesn't make sense
907 if ( enc
== wxFONTENCODING_DEFAULT
)
909 // we don't have wxFONTENCODING_ASCII, so use the closest one
910 return wxFONTENCODING_ISO8859_1
;
913 if ( enc
!= wxFONTENCODING_MAX
)
917 //else: return wxFONTENCODING_SYSTEM below
921 return wxFONTENCODING_SYSTEM
;
925 void wxLocale::AddLanguage(const wxLanguageInfo
& info
)
928 ms_languagesDB
->Add(info
);
932 const wxLanguageInfo
*wxLocale::GetLanguageInfo(int lang
)
936 // calling GetLanguageInfo(wxLANGUAGE_DEFAULT) is a natural thing to do, so
938 if ( lang
== wxLANGUAGE_DEFAULT
)
939 lang
= GetSystemLanguage();
941 const size_t count
= ms_languagesDB
->GetCount();
942 for ( size_t i
= 0; i
< count
; i
++ )
944 if ( ms_languagesDB
->Item(i
).Language
== lang
)
946 // We need to create a temporary here in order to make this work with BCC in final build mode
947 wxLanguageInfo
*ptr
= &ms_languagesDB
->Item(i
);
956 wxString
wxLocale::GetLanguageName(int lang
)
958 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
959 return wxEmptyString
;
961 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
963 return wxEmptyString
;
965 return info
->Description
;
969 wxString
wxLocale::GetLanguageCanonicalName(int lang
)
971 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
972 return wxEmptyString
;
974 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
976 return wxEmptyString
;
978 return info
->CanonicalName
;
982 const wxLanguageInfo
*wxLocale::FindLanguageInfo(const wxString
& locale
)
986 const wxLanguageInfo
*infoRet
= NULL
;
988 const size_t count
= ms_languagesDB
->GetCount();
989 for ( size_t i
= 0; i
< count
; i
++ )
991 const wxLanguageInfo
*info
= &ms_languagesDB
->Item(i
);
993 if ( wxStricmp(locale
, info
->CanonicalName
) == 0 ||
994 wxStricmp(locale
, info
->Description
) == 0 )
996 // exact match, stop searching
1001 if ( wxStricmp(locale
, info
->CanonicalName
.BeforeFirst(wxS('_'))) == 0 )
1003 // a match -- but maybe we'll find an exact one later, so continue
1006 // OTOH, maybe we had already found a language match and in this
1007 // case don't overwrite it because the entry for the default
1008 // country always appears first in ms_languagesDB
1017 wxString
wxLocale::GetSysName() const
1019 return wxSetlocale(LC_ALL
, NULL
);
1023 wxLocale::~wxLocale()
1025 // Restore old translations object.
1026 // See DoCommonInit() for explanation of why this is needed for backward
1028 if ( wxTranslations::Get() == &m_translations
)
1031 wxTranslations::SetNonOwned(&m_pOldLocale
->m_translations
);
1033 wxTranslations::Set(NULL
);
1036 // restore old locale pointer
1037 wxSetLocale(m_pOldLocale
);
1039 wxSetlocale(LC_ALL
, m_pszOldLocale
);
1040 free(const_cast<char *>(m_pszOldLocale
));
1044 // check if the given locale is provided by OS and C run time
1046 bool wxLocale::IsAvailable(int lang
)
1048 const wxLanguageInfo
*info
= wxLocale::GetLanguageInfo(lang
);
1051 // The language is unknown (this normally only happens when we're
1052 // passed wxLANGUAGE_DEFAULT), so we can't support it.
1053 wxASSERT_MSG( lang
== wxLANGUAGE_DEFAULT
,
1054 wxS("No info for a valid language?") );
1058 #if defined(__WIN32__)
1059 if ( !info
->WinLang
)
1062 if ( !::IsValidLocale(info
->GetLCID(), LCID_INSTALLED
) )
1065 #elif defined(__UNIX__)
1067 // Test if setting the locale works, then set it back.
1068 char * const oldLocale
= wxStrdupA(setlocale(LC_ALL
, NULL
));
1070 // Some platforms don't like xx_YY form and require xx only so test for
1073 available
= wxSetlocaleTryUTF8(LC_ALL
, info
->CanonicalName
) ||
1074 wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(info
->CanonicalName
));
1076 // restore the original locale
1077 wxSetlocale(LC_ALL
, oldLocale
);
1089 bool wxLocale::AddCatalog(const wxString
& domain
)
1091 wxTranslations
*t
= wxTranslations::Get();
1094 return t
->AddCatalog(domain
);
1097 bool wxLocale::AddCatalog(const wxString
& domain
, wxLanguage msgIdLanguage
)
1099 wxTranslations
*t
= wxTranslations::Get();
1102 return t
->AddCatalog(domain
, msgIdLanguage
);
1105 // add a catalog to our linked list
1106 bool wxLocale::AddCatalog(const wxString
& szDomain
,
1107 wxLanguage msgIdLanguage
,
1108 const wxString
& msgIdCharset
)
1110 wxTranslations
*t
= wxTranslations::Get();
1114 wxUnusedVar(msgIdCharset
);
1115 return t
->AddCatalog(szDomain
, msgIdLanguage
);
1117 return t
->AddCatalog(szDomain
, msgIdLanguage
, msgIdCharset
);
1121 bool wxLocale::IsLoaded(const wxString
& domain
) const
1123 wxTranslations
*t
= wxTranslations::Get();
1126 return t
->IsLoaded(domain
);
1129 wxString
wxLocale::GetHeaderValue(const wxString
& header
,
1130 const wxString
& domain
) const
1132 wxTranslations
*t
= wxTranslations::Get();
1134 return wxEmptyString
;
1135 return t
->GetHeaderValue(header
, domain
);
1138 // ----------------------------------------------------------------------------
1139 // accessors for locale-dependent data
1140 // ----------------------------------------------------------------------------
1142 #if defined(__WINDOWS__) || defined(__WXOSX__)
1147 // This function translates from Unicode date formats described at
1149 // http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
1151 // to strftime()-like syntax. This translation is not lossless but we try to do
1154 static wxString
TranslateFromUnicodeFormat(const wxString
& fmt
)
1157 fmtWX
.reserve(fmt
.length());
1160 size_t lastCount
= 0;
1162 const char* formatchars
=
1170 for ( wxString::const_iterator p
= fmt
.begin(); /* end handled inside */; ++p
)
1172 if ( p
!= fmt
.end() )
1180 const wxUniChar ch
= (*p
).GetValue();
1181 if ( ch
.IsAscii() && strchr(formatchars
, ch
) )
1183 // these characters come in groups, start counting them
1190 // interpret any special characters we collected so far
1196 switch ( lastCount
)
1200 // these two are the same as we don't distinguish
1201 // between 1 and 2 digits for days
1214 wxFAIL_MSG( "too many 'd's" );
1219 switch ( lastCount
)
1228 wxFAIL_MSG( "wrong number of 'D's" );
1232 switch ( lastCount
)
1240 wxFAIL_MSG( "wrong number of 'w's" );
1244 switch ( lastCount
)
1259 wxFAIL_MSG( "wrong number of 'E's" );
1264 switch ( lastCount
)
1268 // as for 'd' and 'dd' above
1281 wxFAIL_MSG( "too many 'M's" );
1286 switch ( lastCount
)
1298 wxFAIL_MSG( "wrong number of 'y's" );
1303 switch ( lastCount
)
1311 wxFAIL_MSG( "wrong number of 'H's" );
1316 switch ( lastCount
)
1324 wxFAIL_MSG( "wrong number of 'h's" );
1329 switch ( lastCount
)
1337 wxFAIL_MSG( "wrong number of 'm's" );
1342 switch ( lastCount
)
1350 wxFAIL_MSG( "wrong number of 's's" );
1355 // strftime() doesn't have era string,
1356 // ignore this format
1357 wxASSERT_MSG( lastCount
<= 2, "too many 'g's" );
1367 switch ( lastCount
)
1375 wxFAIL_MSG( "too many 't's" );
1380 wxFAIL_MSG( "unreachable" );
1387 if ( p
== fmt
.end() )
1390 // not a special character so must be just a separator, treat as is
1391 if ( *p
== wxT('%') )
1393 // this one needs to be escaped
1403 } // anonymous namespace
1405 #endif // __WINDOWS__ || __WXOSX__
1407 #if defined(__WINDOWS__)
1412 LCTYPE
GetLCTYPEFormatFromLocalInfo(wxLocaleInfo index
)
1416 case wxLOCALE_SHORT_DATE_FMT
:
1417 return LOCALE_SSHORTDATE
;
1419 case wxLOCALE_LONG_DATE_FMT
:
1420 return LOCALE_SLONGDATE
;
1422 case wxLOCALE_TIME_FMT
:
1423 return LOCALE_STIMEFORMAT
;
1426 wxFAIL_MSG( "no matching LCTYPE" );
1432 } // anonymous namespace
1435 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory cat
)
1437 const wxLanguageInfo
* const
1438 info
= wxGetLocale() ? GetLanguageInfo(wxGetLocale()->GetLanguage())
1442 // wxSetLocale() hadn't been called yet of failed, hence CRT must be
1443 // using "C" locale -- but check it to detect bugs that would happen if
1444 // this were not the case.
1445 wxASSERT_MSG( strcmp(setlocale(LC_ALL
, NULL
), "C") == 0,
1446 wxS("You probably called setlocale() directly instead ")
1447 wxS("of using wxLocale and now there is a ")
1448 wxS("mismatch between C/C++ and Windows locale.\n")
1449 wxS("Things are going to break, please only change ")
1450 wxS("locale by creating wxLocale objects to avoid this!") );
1453 // Return the hard coded values for C locale. This is really the right
1454 // thing to do as there is no LCID we can use in the code below in this
1455 // case, even LOCALE_INVARIANT is not quite the same as C locale (the
1456 // only difference is that it uses %Y instead of %y in the date format
1457 // but this difference is significant enough).
1460 case wxLOCALE_THOUSANDS_SEP
:
1463 case wxLOCALE_DECIMAL_POINT
:
1466 case wxLOCALE_SHORT_DATE_FMT
:
1469 case wxLOCALE_LONG_DATE_FMT
:
1470 return "%A, %B %d, %Y";
1472 case wxLOCALE_TIME_FMT
:
1475 case wxLOCALE_DATE_TIME_FMT
:
1476 return "%m/%d/%y %H:%M:%S";
1479 wxFAIL_MSG( "unknown wxLocaleInfo" );
1483 const wxUint32 lcid
= info
->GetLCID();
1492 case wxLOCALE_THOUSANDS_SEP
:
1493 if ( ::GetLocaleInfo(lcid
, LOCALE_STHOUSAND
, buf
, WXSIZEOF(buf
)) )
1497 case wxLOCALE_DECIMAL_POINT
:
1498 if ( ::GetLocaleInfo(lcid
,
1499 cat
== wxLOCALE_CAT_MONEY
1500 ? LOCALE_SMONDECIMALSEP
1507 // As we get our decimal point separator from Win32 and not the
1508 // CRT there is a possibility of mismatch between them and this
1509 // can easily happen if the user code called setlocale()
1510 // instead of using wxLocale to change the locale. And this can
1511 // result in very strange bugs elsewhere in the code as the
1512 // assumptions that formatted strings do use the decimal
1513 // separator actually fail, so check for it here.
1516 wxString::Format("%.3f", 1.23).find(str
) != wxString::npos
,
1517 "Decimal separator mismatch -- did you use setlocale()?"
1518 "If so, use wxLocale to change the locale instead."
1523 case wxLOCALE_SHORT_DATE_FMT
:
1524 case wxLOCALE_LONG_DATE_FMT
:
1525 case wxLOCALE_TIME_FMT
:
1526 if ( ::GetLocaleInfo(lcid
, GetLCTYPEFormatFromLocalInfo(index
),
1527 buf
, WXSIZEOF(buf
)) )
1529 return TranslateFromUnicodeFormat(buf
);
1533 case wxLOCALE_DATE_TIME_FMT
:
1534 // there doesn't seem to be any specific setting for this, so just
1535 // combine date and time ones
1537 // we use the short date because this is what "%c" uses by default
1538 // ("%#c" uses long date but we have no way to specify the
1539 // alternate representation here)
1541 const wxString datefmt
= GetInfo(wxLOCALE_SHORT_DATE_FMT
);
1542 if ( datefmt
.empty() )
1545 const wxString timefmt
= GetInfo(wxLOCALE_TIME_FMT
);
1546 if ( timefmt
.empty() )
1549 str
<< datefmt
<< ' ' << timefmt
;
1554 wxFAIL_MSG( "unknown wxLocaleInfo" );
1560 #elif defined(__WXOSX__)
1563 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory
WXUNUSED(cat
))
1565 CFLocaleRef userLocaleRefRaw
;
1566 if ( wxGetLocale() )
1568 userLocaleRefRaw
= CFLocaleCreate
1570 kCFAllocatorDefault
,
1571 wxCFStringRef(wxGetLocale()->GetCanonicalName())
1574 else // no current locale, use the default one
1576 userLocaleRefRaw
= CFLocaleCopyCurrent();
1579 wxCFRef
<CFLocaleRef
> userLocaleRef(userLocaleRefRaw
);
1581 CFStringRef cfstr
= 0;
1584 case wxLOCALE_THOUSANDS_SEP
:
1585 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleGroupingSeparator
);
1588 case wxLOCALE_DECIMAL_POINT
:
1589 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleDecimalSeparator
);
1592 case wxLOCALE_SHORT_DATE_FMT
:
1593 case wxLOCALE_LONG_DATE_FMT
:
1594 case wxLOCALE_DATE_TIME_FMT
:
1595 case wxLOCALE_TIME_FMT
:
1597 CFDateFormatterStyle dateStyle
= kCFDateFormatterNoStyle
;
1598 CFDateFormatterStyle timeStyle
= kCFDateFormatterNoStyle
;
1601 case wxLOCALE_SHORT_DATE_FMT
:
1602 dateStyle
= kCFDateFormatterShortStyle
;
1604 case wxLOCALE_LONG_DATE_FMT
:
1605 dateStyle
= kCFDateFormatterFullStyle
;
1607 case wxLOCALE_DATE_TIME_FMT
:
1608 dateStyle
= kCFDateFormatterFullStyle
;
1609 timeStyle
= kCFDateFormatterMediumStyle
;
1611 case wxLOCALE_TIME_FMT
:
1612 timeStyle
= kCFDateFormatterMediumStyle
;
1615 wxFAIL_MSG( "unexpected time locale" );
1618 wxCFRef
<CFDateFormatterRef
> dateFormatter( CFDateFormatterCreate
1619 (NULL
, userLocaleRef
, dateStyle
, timeStyle
));
1620 wxCFStringRef cfs
= wxCFRetain( CFDateFormatterGetFormat(dateFormatter
));
1621 wxString format
= TranslateFromUnicodeFormat(cfs
.AsString());
1622 // we always want full years
1623 format
.Replace("%y","%Y");
1629 wxFAIL_MSG( "Unknown locale info" );
1633 wxCFStringRef
str(wxCFRetain(cfstr
));
1634 return str
.AsString();
1637 #else // !__WINDOWS__ && !__WXOSX__, assume generic POSIX
1642 wxString
GetDateFormatFromLangInfo(wxLocaleInfo index
)
1644 #ifdef HAVE_LANGINFO_H
1645 // array containing parameters for nl_langinfo() indexes by offset of index
1646 // from wxLOCALE_SHORT_DATE_FMT
1647 static const nl_item items
[] =
1649 D_FMT
, D_T_FMT
, D_T_FMT
, T_FMT
,
1652 const int nlidx
= index
- wxLOCALE_SHORT_DATE_FMT
;
1653 if ( nlidx
< 0 || nlidx
>= (int)WXSIZEOF(items
) )
1655 wxFAIL_MSG( "logic error in GetInfo() code" );
1659 const wxString
fmt(nl_langinfo(items
[nlidx
]));
1661 // just return the format returned by nl_langinfo() except for long date
1662 // format which we need to recover from date/time format ourselves (but not
1663 // if we failed completely)
1664 if ( fmt
.empty() || index
!= wxLOCALE_LONG_DATE_FMT
)
1667 // this is not 100% precise but the idea is that a typical date/time format
1668 // under POSIX systems is a combination of a long date format with time one
1669 // so we should be able to get just the long date format by removing all
1670 // time-specific format specifiers
1671 static const char *timeFmtSpecs
= "HIklMpPrRsSTXzZ";
1672 static const char *timeSep
= " :./-";
1674 wxString fmtDateOnly
;
1675 const wxString::const_iterator end
= fmt
.end();
1676 wxString::const_iterator lastSep
= end
;
1677 for ( wxString::const_iterator p
= fmt
.begin(); p
!= end
; ++p
)
1679 if ( strchr(timeSep
, *p
) )
1681 if ( lastSep
== end
)
1684 // skip it for now, we'll discard it if it's followed by a time
1685 // specifier later or add it to fmtDateOnly if it is not
1690 (p
+ 1 != end
) && strchr(timeFmtSpecs
, p
[1]) )
1692 // time specified found: skip it and any preceding separators
1698 if ( lastSep
!= end
)
1700 fmtDateOnly
+= wxString(lastSep
, p
);
1708 #else // !HAVE_LANGINFO_H
1711 // no fallback, let the application deal with unavailability of
1712 // nl_langinfo() itself as there is no good way for us to do it (well, we
1713 // could try to reverse engineer the format from strftime() output but this
1714 // looks like too much trouble considering the relatively small number of
1715 // systems without nl_langinfo() still in use)
1717 #endif // HAVE_LANGINFO_H/!HAVE_LANGINFO_H
1720 } // anonymous namespace
1723 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory cat
)
1725 lconv
* const lc
= localeconv();
1731 case wxLOCALE_THOUSANDS_SEP
:
1732 if ( cat
== wxLOCALE_CAT_NUMBER
)
1733 return lc
->thousands_sep
;
1734 else if ( cat
== wxLOCALE_CAT_MONEY
)
1735 return lc
->mon_thousands_sep
;
1737 wxFAIL_MSG( "invalid wxLocaleCategory" );
1741 case wxLOCALE_DECIMAL_POINT
:
1742 if ( cat
== wxLOCALE_CAT_NUMBER
)
1743 return lc
->decimal_point
;
1744 else if ( cat
== wxLOCALE_CAT_MONEY
)
1745 return lc
->mon_decimal_point
;
1747 wxFAIL_MSG( "invalid wxLocaleCategory" );
1750 case wxLOCALE_SHORT_DATE_FMT
:
1751 case wxLOCALE_LONG_DATE_FMT
:
1752 case wxLOCALE_DATE_TIME_FMT
:
1753 case wxLOCALE_TIME_FMT
:
1754 if ( cat
!= wxLOCALE_CAT_DATE
&& cat
!= wxLOCALE_CAT_DEFAULT
)
1756 wxFAIL_MSG( "invalid wxLocaleCategory" );
1760 return GetDateFormatFromLangInfo(index
);
1764 wxFAIL_MSG( "unknown wxLocaleInfo value" );
1772 // ----------------------------------------------------------------------------
1773 // global functions and variables
1774 // ----------------------------------------------------------------------------
1776 // retrieve/change current locale
1777 // ------------------------------
1779 // the current locale object
1780 static wxLocale
*g_pLocale
= NULL
;
1782 wxLocale
*wxGetLocale()
1787 wxLocale
*wxSetLocale(wxLocale
*pLocale
)
1789 wxLocale
*pOld
= g_pLocale
;
1790 g_pLocale
= pLocale
;
1796 // ----------------------------------------------------------------------------
1797 // wxLocale module (for lazy destruction of languagesDB)
1798 // ----------------------------------------------------------------------------
1800 class wxLocaleModule
: public wxModule
1802 DECLARE_DYNAMIC_CLASS(wxLocaleModule
)
1813 wxLocale::DestroyLanguagesDB();
1817 IMPLEMENT_DYNAMIC_CLASS(wxLocaleModule
, wxModule
)
1819 #endif // wxUSE_INTL