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
;
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 delete ms_languagesDB
;
204 ms_languagesDB
= NULL
;
208 void wxLocale::DoCommonInit()
210 m_pszOldLocale
= NULL
;
212 m_pOldLocale
= wxSetLocale(this);
214 // Set translations object, but only if the user didn't do so yet.
215 // This is to preserve compatibility with wx-2.8 where wxLocale was
216 // the only API for translations. wxLocale works as a stack, with
217 // latest-created one being the active one:
218 // wxLocale loc_fr(wxLANGUAGE_FRENCH);
219 // // _() returns French
221 // wxLocale loc_cs(wxLANGUAGE_CZECH);
222 // // _() returns Czech
224 // // _() returns French again
225 wxTranslations
*oldTrans
= wxTranslations::Get();
227 (m_pOldLocale
&& oldTrans
== &m_pOldLocale
->m_translations
) )
229 wxTranslations::SetNonOwned(&m_translations
);
232 m_language
= wxLANGUAGE_UNKNOWN
;
233 m_initialized
= false;
236 // NB: this function has (desired) side effect of changing current locale
237 bool wxLocale::Init(const wxString
& name
,
238 const wxString
& shortName
,
239 const wxString
& locale
,
241 #if WXWIN_COMPATIBILITY_2_8
242 ,bool bConvertEncoding
246 #if WXWIN_COMPATIBILITY_2_8
247 wxASSERT_MSG( bConvertEncoding
,
248 wxS("wxLocale::Init with bConvertEncoding=false is no longer supported, add charset to your catalogs") );
251 bool ret
= DoInit(name
, shortName
, locale
);
253 // NB: don't use 'lang' here, 'language' may be wxLANGUAGE_DEFAULT
254 wxTranslations
*t
= wxTranslations::Get();
257 t
->SetLanguage(shortName
);
266 bool wxLocale::DoInit(const wxString
& name
,
267 const wxString
& shortName
,
268 const wxString
& locale
)
270 wxASSERT_MSG( !m_initialized
,
271 wxS("you can't call wxLocale::Init more than once") );
273 m_initialized
= true;
275 m_strShort
= shortName
;
276 m_language
= wxLANGUAGE_UNKNOWN
;
278 // change current locale (default: same as long name)
279 wxString
szLocale(locale
);
280 if ( szLocale
.empty() )
282 // the argument to setlocale()
283 szLocale
= shortName
;
285 wxCHECK_MSG( !szLocale
.empty(), false,
286 wxS("no locale to set in wxLocale::Init()") );
289 const char *oldLocale
= wxSetlocale(LC_ALL
, szLocale
);
291 m_pszOldLocale
= wxStrdup(oldLocale
);
293 m_pszOldLocale
= NULL
;
295 if ( m_pszOldLocale
== NULL
)
297 wxLogError(_("locale '%s' can not be set."), szLocale
);
300 // the short name will be used to look for catalog files as well,
301 // so we need something here
302 if ( m_strShort
.empty() ) {
303 // FIXME I don't know how these 2 letter abbreviations are formed,
304 // this wild guess is surely wrong
305 if ( !szLocale
.empty() )
307 m_strShort
+= (wxChar
)wxTolower(szLocale
[0]);
308 if ( szLocale
.length() > 1 )
309 m_strShort
+= (wxChar
)wxTolower(szLocale
[1]);
317 #if defined(__UNIX__) && wxUSE_UNICODE && !defined(__WXMAC__)
318 static const char *wxSetlocaleTryUTF8(int c
, const wxString
& lc
)
320 const char *l
= NULL
;
322 // NB: We prefer to set UTF-8 locale if it's possible and only fall back to
323 // non-UTF-8 locale if it fails
329 buf2
= buf
+ wxS(".UTF-8");
330 l
= wxSetlocale(c
, buf2
);
333 buf2
= buf
+ wxS(".utf-8");
334 l
= wxSetlocale(c
, buf2
);
338 buf2
= buf
+ wxS(".UTF8");
339 l
= wxSetlocale(c
, buf2
);
343 buf2
= buf
+ wxS(".utf8");
344 l
= wxSetlocale(c
, buf2
);
348 // if we can't set UTF-8 locale, try non-UTF-8 one:
350 l
= wxSetlocale(c
, lc
);
355 #define wxSetlocaleTryUTF8(c, lc) wxSetlocale(c, lc)
358 bool wxLocale::Init(int language
, int flags
)
360 #if WXWIN_COMPATIBILITY_2_8
361 wxASSERT_MSG( !(flags
& wxLOCALE_CONV_ENCODING
),
362 wxS("wxLOCALE_CONV_ENCODING is no longer supported, add charset to your catalogs") );
368 if (lang
== wxLANGUAGE_DEFAULT
)
370 // auto detect the language
371 lang
= GetSystemLanguage();
374 // We failed to detect system language, so we will use English:
375 if (lang
== wxLANGUAGE_UNKNOWN
)
380 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
385 wxLogError(wxS("Unknown language %i."), lang
);
389 wxString name
= info
->Description
;
390 wxString canonical
= info
->CanonicalName
;
395 const char *retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
396 #elif defined(__UNIX__) && !defined(__WXMAC__)
397 if (language
!= wxLANGUAGE_DEFAULT
)
398 locale
= info
->CanonicalName
;
400 const char *retloc
= wxSetlocaleTryUTF8(LC_ALL
, locale
);
402 const wxString langOnly
= ExtractLang(locale
);
405 // Some C libraries don't like xx_YY form and require xx only
406 retloc
= wxSetlocaleTryUTF8(LC_ALL
, langOnly
);
410 // some systems (e.g. FreeBSD and HP-UX) don't have xx_YY aliases but
411 // require the full xx_YY.encoding form, so try using UTF-8 because this is
412 // the only thing we can do generically
414 // TODO: add encodings applicable to each language to the lang DB and try
415 // them all in turn here
418 const wxChar
**names
=
419 wxFontMapperBase::GetAllEncodingNames(wxFONTENCODING_UTF8
);
422 retloc
= wxSetlocale(LC_ALL
, locale
+ wxS('.') + *names
++);
427 #endif // wxUSE_FONTMAP
431 // Some C libraries (namely glibc) still use old ISO 639,
432 // so will translate the abbrev for them
434 if ( langOnly
== wxS("he") )
435 localeAlt
= wxS("iw") + ExtractNotLang(locale
);
436 else if ( langOnly
== wxS("id") )
437 localeAlt
= wxS("in") + ExtractNotLang(locale
);
438 else if ( langOnly
== wxS("yi") )
439 localeAlt
= wxS("ji") + ExtractNotLang(locale
);
440 else if ( langOnly
== wxS("nb") )
441 localeAlt
= wxS("no_NO");
442 else if ( langOnly
== wxS("nn") )
443 localeAlt
= wxS("no_NY");
445 if ( !localeAlt
.empty() )
447 retloc
= wxSetlocaleTryUTF8(LC_ALL
, localeAlt
);
449 retloc
= wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(localeAlt
));
457 // at least in AIX 5.2 libc is buggy and the string returned from
458 // setlocale(LC_ALL) can't be passed back to it because it returns 6
459 // strings (one for each locale category), i.e. for C locale we get back
462 // this contradicts IBM own docs but this is not of much help, so just work
463 // around it in the crudest possible manner
464 char* p
= const_cast<char*>(wxStrchr(retloc
, ' '));
469 #elif defined(__WIN32__)
470 const char *retloc
= "C";
471 if ( language
!= wxLANGUAGE_DEFAULT
)
473 if ( info
->WinLang
== 0 )
475 wxLogWarning(wxS("Locale '%s' not supported by OS."), name
.c_str());
476 // retloc already set to "C"
478 else // language supported by Windows
480 // Windows CE doesn't have SetThreadLocale() and there doesn't seem
481 // to be any equivalent
483 const wxUint32 lcid
= info
->GetLCID();
485 // change locale used by Windows functions
486 ::SetThreadLocale(lcid
);
489 // and also call setlocale() to change locale used by the CRT
490 locale
= info
->GetLocaleName();
491 if ( locale
.empty() )
495 else // have a valid locale
497 retloc
= wxSetlocale(LC_ALL
, locale
);
501 else // language == wxLANGUAGE_DEFAULT
503 retloc
= wxSetlocale(LC_ALL
, wxEmptyString
);
506 #if wxUSE_UNICODE && (defined(__VISUALC__) || defined(__MINGW32__))
507 // VC++ setlocale() (also used by Mingw) can't set locale to languages that
508 // can only be written using Unicode, therefore wxSetlocale() call fails
509 // for such languages but we don't want to report it as an error -- so that
510 // at least message catalogs can be used.
513 if ( wxGetANSICodePageForLocale(LOCALE_USER_DEFAULT
).empty() )
515 // we set the locale to a Unicode-only language, don't treat the
516 // inability of CRT to use it as an error
520 #endif // CRT not handling Unicode-only languages
524 #elif defined(__WXMAC__)
525 if (lang
== wxLANGUAGE_DEFAULT
)
526 locale
= wxEmptyString
;
528 locale
= info
->CanonicalName
;
530 const char *retloc
= wxSetlocale(LC_ALL
, locale
);
534 // Some C libraries don't like xx_YY form and require xx only
535 retloc
= wxSetlocale(LC_ALL
, ExtractLang(locale
));
540 #define WX_NO_LOCALE_SUPPORT
543 #ifndef WX_NO_LOCALE_SUPPORT
546 wxLogWarning(_("Cannot set locale to language \"%s\"."), name
.c_str());
548 // continue nevertheless and try to load at least the translations for
552 if ( !DoInit(name
, canonical
, retloc
) )
557 if (IsOk()) // setlocale() succeeded
560 // NB: don't use 'lang' here, 'language'
561 wxTranslations
*t
= wxTranslations::Get();
564 t
->SetLanguage(static_cast<wxLanguage
>(language
));
566 if ( flags
& wxLOCALE_LOAD_DEFAULT
)
571 #endif // !WX_NO_LOCALE_SUPPORT
574 /*static*/ int wxLocale::GetSystemLanguage()
578 // init i to avoid compiler warning
580 count
= ms_languagesDB
->GetCount();
582 #if defined(__UNIX__)
583 // first get the string identifying the language from the environment
586 wxCFRef
<CFLocaleRef
> userLocaleRef(CFLocaleCopyCurrent());
588 // because the locale identifier (kCFLocaleIdentifier) is formatted a little bit differently, eg
589 // az_Cyrl_AZ@calendar=buddhist;currency=JPY we just recreate the base info as expected by wx here
591 wxCFStringRef
str(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleLanguageCode
)));
592 langFull
= str
.AsString()+"_";
593 str
.reset(wxCFRetain((CFStringRef
)CFLocaleGetValue(userLocaleRef
, kCFLocaleCountryCode
)));
594 langFull
+= str
.AsString();
596 if (!wxGetEnv(wxS("LC_ALL"), &langFull
) &&
597 !wxGetEnv(wxS("LC_MESSAGES"), &langFull
) &&
598 !wxGetEnv(wxS("LANG"), &langFull
))
600 // no language specified, treat it as English
601 return wxLANGUAGE_ENGLISH_US
;
604 if ( langFull
== wxS("C") || langFull
== wxS("POSIX") )
606 // default C locale is English too
607 return wxLANGUAGE_ENGLISH_US
;
611 // the language string has the following form
613 // lang[_LANG][.encoding][@modifier]
615 // (see environ(5) in the Open Unix specification)
617 // where lang is the primary language, LANG is a sublang/territory,
618 // encoding is the charset to use and modifier "allows the user to select
619 // a specific instance of localization data within a single category"
621 // for example, the following strings are valid:
626 // de_DE.iso88591@euro
628 // for now we don't use the encoding, although we probably should (doing
629 // translations of the msg catalogs on the fly as required) (TODO)
631 // we need the modified for languages like Valencian: ca_ES@valencia
632 // though, remember it
634 size_t posModifier
= langFull
.find_first_of(wxS("@"));
635 if ( posModifier
!= wxString::npos
)
636 modifier
= langFull
.Mid(posModifier
);
638 size_t posEndLang
= langFull
.find_first_of(wxS("@."));
639 if ( posEndLang
!= wxString::npos
)
641 langFull
.Truncate(posEndLang
);
644 // do we have just the language (or sublang too)?
645 const bool justLang
= langFull
.find('_') == wxString::npos
;
647 // 0. Make sure the lang is according to latest ISO 639
648 // (this is necessary because glibc uses iw and in instead
649 // of he and id respectively).
651 // the language itself (second part is the dialect/sublang)
652 wxString langOrig
= ExtractLang(langFull
);
655 if ( langOrig
== wxS("iw"))
657 else if (langOrig
== wxS("in"))
659 else if (langOrig
== wxS("ji"))
661 else if (langOrig
== wxS("no_NO"))
663 else if (langOrig
== wxS("no_NY"))
665 else if (langOrig
== wxS("no"))
671 if ( lang
!= langOrig
)
673 langFull
= lang
+ ExtractNotLang(langFull
);
676 // 1. Try to find the language either as is:
677 // a) With modifier if set
678 if ( !modifier
.empty() )
680 wxString langFullWithModifier
= langFull
+ modifier
;
681 for ( i
= 0; i
< count
; i
++ )
683 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFullWithModifier
)
688 // b) Without modifier
689 if ( modifier
.empty() || i
== count
)
691 for ( i
= 0; i
< count
; i
++ )
693 if ( ms_languagesDB
->Item(i
).CanonicalName
== langFull
)
698 // 2. If langFull is of the form xx_YY, try to find xx:
699 if ( i
== count
&& !justLang
)
701 for ( i
= 0; i
< count
; i
++ )
703 if ( ms_languagesDB
->Item(i
).CanonicalName
== lang
)
710 // 3. If langFull is of the form xx, try to find any xx_YY record:
711 if ( i
== count
&& justLang
)
713 for ( i
= 0; i
< count
; i
++ )
715 if ( ExtractLang(ms_languagesDB
->Item(i
).CanonicalName
)
726 // In addition to the format above, we also can have full language
727 // names in LANG env var - for example, SuSE is known to use
728 // LANG="german" - so check for use of non-standard format and try to
729 // find the name in verbose description.
730 for ( i
= 0; i
< count
; i
++ )
732 if (ms_languagesDB
->Item(i
).Description
.CmpNoCase(langFull
) == 0)
738 #elif defined(__WIN32__)
739 LCID lcid
= GetUserDefaultLCID();
742 wxUint32 lang
= PRIMARYLANGID(LANGIDFROMLCID(lcid
));
743 wxUint32 sublang
= SUBLANGID(LANGIDFROMLCID(lcid
));
745 for ( i
= 0; i
< count
; i
++ )
747 if (ms_languagesDB
->Item(i
).WinLang
== lang
&&
748 ms_languagesDB
->Item(i
).WinSublang
== sublang
)
754 //else: leave wxlang == wxLANGUAGE_UNKNOWN
759 // we did find a matching entry, use it
760 return ms_languagesDB
->Item(i
).Language
;
763 // no info about this language in the database
764 return wxLANGUAGE_UNKNOWN
;
767 // ----------------------------------------------------------------------------
769 // ----------------------------------------------------------------------------
771 // this is a bit strange as under Windows we get the encoding name using its
772 // numeric value and under Unix we do it the other way round, but this just
773 // reflects the way different systems provide the encoding info
776 wxString
wxLocale::GetSystemEncodingName()
780 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
781 // FIXME: what is the error return value for GetACP()?
782 UINT codepage
= ::GetACP();
783 encname
.Printf(wxS("windows-%u"), codepage
);
784 #elif defined(__WXMAC__)
785 // default is just empty string, this resolves to the default system
787 #elif defined(__UNIX_LIKE__)
789 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
790 // GNU libc provides current character set this way (this conforms
792 char *oldLocale
= strdup(setlocale(LC_CTYPE
, NULL
));
793 setlocale(LC_CTYPE
, "");
794 const char *alang
= nl_langinfo(CODESET
);
795 setlocale(LC_CTYPE
, oldLocale
);
800 encname
= wxString::FromAscii( alang
);
802 else // nl_langinfo() failed
803 #endif // HAVE_LANGINFO_H
805 // if we can't get at the character set directly, try to see if it's in
806 // the environment variables (in most cases this won't work, but I was
808 char *lang
= getenv( "LC_ALL");
809 char *dot
= lang
? strchr(lang
, '.') : NULL
;
812 lang
= getenv( "LC_CTYPE" );
814 dot
= strchr(lang
, '.' );
818 lang
= getenv( "LANG");
820 dot
= strchr(lang
, '.');
825 encname
= wxString::FromAscii( dot
+1 );
834 wxFontEncoding
wxLocale::GetSystemEncoding()
836 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
837 UINT codepage
= ::GetACP();
839 // wxWidgets only knows about CP1250-1257, 874, 932, 936, 949, 950
840 if ( codepage
>= 1250 && codepage
<= 1257 )
842 return (wxFontEncoding
)(wxFONTENCODING_CP1250
+ codepage
- 1250);
845 if ( codepage
== 874 )
847 return wxFONTENCODING_CP874
;
850 if ( codepage
== 932 )
852 return wxFONTENCODING_CP932
;
855 if ( codepage
== 936 )
857 return wxFONTENCODING_CP936
;
860 if ( codepage
== 949 )
862 return wxFONTENCODING_CP949
;
865 if ( codepage
== 950 )
867 return wxFONTENCODING_CP950
;
869 #elif defined(__WXMAC__)
870 CFStringEncoding encoding
= 0 ;
871 encoding
= CFStringGetSystemEncoding() ;
872 return wxMacGetFontEncFromSystemEnc( encoding
) ;
873 #elif defined(__UNIX_LIKE__) && wxUSE_FONTMAP
874 const wxString encname
= GetSystemEncodingName();
875 if ( !encname
.empty() )
877 wxFontEncoding enc
= wxFontMapperBase::GetEncodingFromName(encname
);
879 // on some modern Linux systems (RedHat 8) the default system locale
880 // is UTF8 -- but it isn't supported by wxGTK1 in ANSI build at all so
881 // don't even try to use it in this case
882 #if !wxUSE_UNICODE && \
883 ((defined(__WXGTK__) && !defined(__WXGTK20__)) || defined(__WXMOTIF__))
884 if ( enc
== wxFONTENCODING_UTF8
)
886 // the most similar supported encoding...
887 enc
= wxFONTENCODING_ISO8859_1
;
889 #endif // !wxUSE_UNICODE
891 // GetEncodingFromName() returns wxFONTENCODING_DEFAULT for C locale
892 // (a.k.a. US-ASCII) which is arguably a bug but keep it like this for
893 // backwards compatibility and just take care to not return
894 // wxFONTENCODING_DEFAULT from here as this surely doesn't make sense
895 if ( enc
== wxFONTENCODING_DEFAULT
)
897 // we don't have wxFONTENCODING_ASCII, so use the closest one
898 return wxFONTENCODING_ISO8859_1
;
901 if ( enc
!= wxFONTENCODING_MAX
)
905 //else: return wxFONTENCODING_SYSTEM below
909 return wxFONTENCODING_SYSTEM
;
913 void wxLocale::AddLanguage(const wxLanguageInfo
& info
)
916 ms_languagesDB
->Add(info
);
920 const wxLanguageInfo
*wxLocale::GetLanguageInfo(int lang
)
924 // calling GetLanguageInfo(wxLANGUAGE_DEFAULT) is a natural thing to do, so
926 if ( lang
== wxLANGUAGE_DEFAULT
)
927 lang
= GetSystemLanguage();
929 const size_t count
= ms_languagesDB
->GetCount();
930 for ( size_t i
= 0; i
< count
; i
++ )
932 if ( ms_languagesDB
->Item(i
).Language
== lang
)
934 // We need to create a temporary here in order to make this work with BCC in final build mode
935 wxLanguageInfo
*ptr
= &ms_languagesDB
->Item(i
);
944 wxString
wxLocale::GetLanguageName(int lang
)
946 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
947 return wxEmptyString
;
949 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
951 return wxEmptyString
;
953 return info
->Description
;
957 wxString
wxLocale::GetLanguageCanonicalName(int lang
)
959 if ( lang
== wxLANGUAGE_DEFAULT
|| lang
== wxLANGUAGE_UNKNOWN
)
960 return wxEmptyString
;
962 const wxLanguageInfo
*info
= GetLanguageInfo(lang
);
964 return wxEmptyString
;
966 return info
->CanonicalName
;
970 const wxLanguageInfo
*wxLocale::FindLanguageInfo(const wxString
& locale
)
974 const wxLanguageInfo
*infoRet
= NULL
;
976 const size_t count
= ms_languagesDB
->GetCount();
977 for ( size_t i
= 0; i
< count
; i
++ )
979 const wxLanguageInfo
*info
= &ms_languagesDB
->Item(i
);
981 if ( wxStricmp(locale
, info
->CanonicalName
) == 0 ||
982 wxStricmp(locale
, info
->Description
) == 0 )
984 // exact match, stop searching
989 if ( wxStricmp(locale
, info
->CanonicalName
.BeforeFirst(wxS('_'))) == 0 )
991 // a match -- but maybe we'll find an exact one later, so continue
994 // OTOH, maybe we had already found a language match and in this
995 // case don't overwrite it because the entry for the default
996 // country always appears first in ms_languagesDB
1005 wxString
wxLocale::GetSysName() const
1007 return wxSetlocale(LC_ALL
, NULL
);
1011 wxLocale::~wxLocale()
1013 // Restore old translations object.
1014 // See DoCommonInit() for explanation of why this is needed for backward
1016 if ( wxTranslations::Get() == &m_translations
)
1019 wxTranslations::SetNonOwned(&m_pOldLocale
->m_translations
);
1021 wxTranslations::Set(NULL
);
1024 // restore old locale pointer
1025 wxSetLocale(m_pOldLocale
);
1027 wxSetlocale(LC_ALL
, m_pszOldLocale
);
1028 free((wxChar
*)m_pszOldLocale
); // const_cast
1032 // check if the given locale is provided by OS and C run time
1034 bool wxLocale::IsAvailable(int lang
)
1036 const wxLanguageInfo
*info
= wxLocale::GetLanguageInfo(lang
);
1037 wxCHECK_MSG( info
, false, wxS("invalid language") );
1039 #if defined(__WIN32__)
1040 if ( !info
->WinLang
)
1043 if ( !::IsValidLocale(info
->GetLCID(), LCID_INSTALLED
) )
1046 #elif defined(__UNIX__)
1048 // Test if setting the locale works, then set it back.
1049 const char *oldLocale
= wxSetlocaleTryUTF8(LC_ALL
, info
->CanonicalName
);
1052 // Some C libraries don't like xx_YY form and require xx only
1053 oldLocale
= wxSetlocaleTryUTF8(LC_ALL
, ExtractLang(info
->CanonicalName
));
1057 // restore the original locale
1058 wxSetlocale(LC_ALL
, oldLocale
);
1065 bool wxLocale::AddCatalog(const wxString
& domain
)
1067 wxTranslations
*t
= wxTranslations::Get();
1070 return t
->AddCatalog(domain
);
1073 bool wxLocale::AddCatalog(const wxString
& domain
, wxLanguage msgIdLanguage
)
1075 wxTranslations
*t
= wxTranslations::Get();
1078 return t
->AddCatalog(domain
, msgIdLanguage
);
1081 // add a catalog to our linked list
1082 bool wxLocale::AddCatalog(const wxString
& szDomain
,
1083 wxLanguage msgIdLanguage
,
1084 const wxString
& msgIdCharset
)
1086 wxTranslations
*t
= wxTranslations::Get();
1090 wxUnusedVar(msgIdCharset
);
1091 return t
->AddCatalog(szDomain
, msgIdLanguage
);
1093 return t
->AddCatalog(szDomain
, msgIdLanguage
, msgIdCharset
);
1097 bool wxLocale::IsLoaded(const wxString
& domain
) const
1099 wxTranslations
*t
= wxTranslations::Get();
1102 return t
->IsLoaded(domain
);
1105 wxString
wxLocale::GetHeaderValue(const wxString
& header
,
1106 const wxString
& domain
) const
1108 wxTranslations
*t
= wxTranslations::Get();
1110 return wxEmptyString
;
1111 return t
->GetHeaderValue(header
, domain
);
1114 // ----------------------------------------------------------------------------
1115 // accessors for locale-dependent data
1116 // ----------------------------------------------------------------------------
1118 #if defined(__WXMSW__) || defined(__WXOSX__)
1123 // This function translates from Unicode date formats described at
1125 // http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
1127 // to strftime()-like syntax. This translation is not lossless but we try to do
1130 static wxString
TranslateFromUnicodeFormat(const wxString
& fmt
)
1133 fmtWX
.reserve(fmt
.length());
1136 size_t lastCount
= 0;
1138 const char* formatchars
=
1146 for ( wxString::const_iterator p
= fmt
.begin(); /* end handled inside */; ++p
)
1148 if ( p
!= fmt
.end() )
1156 const wxUniChar ch
= (*p
).GetValue();
1157 if ( ch
.IsAscii() && strchr(formatchars
, ch
) )
1159 // these characters come in groups, start counting them
1166 // interpret any special characters we collected so far
1172 switch ( lastCount
)
1176 // these two are the same as we don't distinguish
1177 // between 1 and 2 digits for days
1190 wxFAIL_MSG( "too many 'd's" );
1195 switch ( lastCount
)
1204 wxFAIL_MSG( "wrong number of 'D's" );
1208 switch ( lastCount
)
1216 wxFAIL_MSG( "wrong number of 'w's" );
1220 switch ( lastCount
)
1235 wxFAIL_MSG( "wrong number of 'E's" );
1240 switch ( lastCount
)
1244 // as for 'd' and 'dd' above
1257 wxFAIL_MSG( "too many 'M's" );
1262 switch ( lastCount
)
1274 wxFAIL_MSG( "wrong number of 'y's" );
1279 switch ( lastCount
)
1287 wxFAIL_MSG( "wrong number of 'H's" );
1292 switch ( lastCount
)
1300 wxFAIL_MSG( "wrong number of 'h's" );
1305 switch ( lastCount
)
1313 wxFAIL_MSG( "wrong number of 'm's" );
1318 switch ( lastCount
)
1326 wxFAIL_MSG( "wrong number of 's's" );
1331 // strftime() doesn't have era string,
1332 // ignore this format
1333 wxASSERT_MSG( lastCount
<= 2, "too many 'g's" );
1343 switch ( lastCount
)
1351 wxFAIL_MSG( "too many 't's" );
1356 wxFAIL_MSG( "unreachable" );
1363 if ( p
== fmt
.end() )
1366 // not a special character so must be just a separator, treat as is
1367 if ( *p
== wxT('%') )
1369 // this one needs to be escaped
1379 } // anonymous namespace
1381 #endif // __WXMSW__ || __WXOSX__
1383 #if defined(__WXMSW__)
1388 LCTYPE
GetLCTYPEFormatFromLocalInfo(wxLocaleInfo index
)
1392 case wxLOCALE_SHORT_DATE_FMT
:
1393 return LOCALE_SSHORTDATE
;
1395 case wxLOCALE_LONG_DATE_FMT
:
1396 return LOCALE_SLONGDATE
;
1398 case wxLOCALE_TIME_FMT
:
1399 return LOCALE_STIMEFORMAT
;
1402 wxFAIL_MSG( "no matching LCTYPE" );
1408 } // anonymous namespace
1411 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory
WXUNUSED(cat
))
1413 wxUint32 lcid
= LOCALE_USER_DEFAULT
;
1414 if ( wxGetLocale() )
1416 const wxLanguageInfo
* const
1417 info
= GetLanguageInfo(wxGetLocale()->GetLanguage());
1419 lcid
= info
->GetLCID();
1429 case wxLOCALE_DECIMAL_POINT
:
1430 if ( ::GetLocaleInfo(lcid
, LOCALE_SDECIMAL
, buf
, WXSIZEOF(buf
)) )
1434 case wxLOCALE_SHORT_DATE_FMT
:
1435 case wxLOCALE_LONG_DATE_FMT
:
1436 case wxLOCALE_TIME_FMT
:
1437 if ( ::GetLocaleInfo(lcid
, GetLCTYPEFormatFromLocalInfo(index
),
1438 buf
, WXSIZEOF(buf
)) )
1440 return TranslateFromUnicodeFormat(buf
);
1444 case wxLOCALE_DATE_TIME_FMT
:
1445 // there doesn't seem to be any specific setting for this, so just
1446 // combine date and time ones
1448 // we use the short date because this is what "%c" uses by default
1449 // ("%#c" uses long date but we have no way to specify the
1450 // alternate representation here)
1452 const wxString datefmt
= GetInfo(wxLOCALE_SHORT_DATE_FMT
);
1453 if ( datefmt
.empty() )
1456 const wxString timefmt
= GetInfo(wxLOCALE_TIME_FMT
);
1457 if ( timefmt
.empty() )
1460 str
<< datefmt
<< ' ' << timefmt
;
1465 wxFAIL_MSG( "unknown wxLocaleInfo" );
1471 #elif defined(__WXOSX__)
1474 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory
WXUNUSED(cat
))
1476 CFLocaleRef userLocaleRefRaw
;
1477 if ( wxGetLocale() )
1479 userLocaleRefRaw
= CFLocaleCreate
1481 kCFAllocatorDefault
,
1482 wxCFStringRef(wxGetLocale()->GetCanonicalName())
1485 else // no current locale, use the default one
1487 userLocaleRefRaw
= CFLocaleCopyCurrent();
1490 wxCFRef
<CFLocaleRef
> userLocaleRef(userLocaleRefRaw
);
1492 CFStringRef cfstr
= 0;
1495 case wxLOCALE_THOUSANDS_SEP
:
1496 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleGroupingSeparator
);
1499 case wxLOCALE_DECIMAL_POINT
:
1500 cfstr
= (CFStringRef
) CFLocaleGetValue(userLocaleRef
, kCFLocaleDecimalSeparator
);
1503 case wxLOCALE_SHORT_DATE_FMT
:
1504 case wxLOCALE_LONG_DATE_FMT
:
1505 case wxLOCALE_DATE_TIME_FMT
:
1506 case wxLOCALE_TIME_FMT
:
1508 CFDateFormatterStyle dateStyle
= kCFDateFormatterNoStyle
;
1509 CFDateFormatterStyle timeStyle
= kCFDateFormatterNoStyle
;
1512 case wxLOCALE_SHORT_DATE_FMT
:
1513 dateStyle
= kCFDateFormatterShortStyle
;
1515 case wxLOCALE_LONG_DATE_FMT
:
1516 dateStyle
= kCFDateFormatterFullStyle
;
1518 case wxLOCALE_DATE_TIME_FMT
:
1519 dateStyle
= kCFDateFormatterFullStyle
;
1520 timeStyle
= kCFDateFormatterMediumStyle
;
1522 case wxLOCALE_TIME_FMT
:
1523 timeStyle
= kCFDateFormatterMediumStyle
;
1526 wxFAIL_MSG( "unexpected time locale" );
1529 wxCFRef
<CFDateFormatterRef
> dateFormatter( CFDateFormatterCreate
1530 (NULL
, userLocaleRef
, dateStyle
, timeStyle
));
1531 wxCFStringRef cfs
= wxCFRetain( CFDateFormatterGetFormat(dateFormatter
));
1532 wxString format
= TranslateFromUnicodeFormat(cfs
.AsString());
1533 // we always want full years
1534 format
.Replace("%y","%Y");
1540 wxFAIL_MSG( "Unknown locale info" );
1544 wxCFStringRef
str(wxCFRetain(cfstr
));
1545 return str
.AsString();
1548 #else // !__WXMSW__ && !__WXOSX__, assume generic POSIX
1553 wxString
GetDateFormatFromLangInfo(wxLocaleInfo index
)
1555 #ifdef HAVE_LANGINFO_H
1556 // array containing parameters for nl_langinfo() indexes by offset of index
1557 // from wxLOCALE_SHORT_DATE_FMT
1558 static const nl_item items
[] =
1560 D_FMT
, D_T_FMT
, D_T_FMT
, T_FMT
,
1563 const int nlidx
= index
- wxLOCALE_SHORT_DATE_FMT
;
1564 if ( nlidx
< 0 || nlidx
>= (int)WXSIZEOF(items
) )
1566 wxFAIL_MSG( "logic error in GetInfo() code" );
1570 const wxString
fmt(nl_langinfo(items
[nlidx
]));
1572 // just return the format returned by nl_langinfo() except for long date
1573 // format which we need to recover from date/time format ourselves (but not
1574 // if we failed completely)
1575 if ( fmt
.empty() || index
!= wxLOCALE_LONG_DATE_FMT
)
1578 // this is not 100% precise but the idea is that a typical date/time format
1579 // under POSIX systems is a combination of a long date format with time one
1580 // so we should be able to get just the long date format by removing all
1581 // time-specific format specifiers
1582 static const char *timeFmtSpecs
= "HIklMpPrRsSTXzZ";
1583 static const char *timeSep
= " :./-";
1585 wxString fmtDateOnly
;
1586 const wxString::const_iterator end
= fmt
.end();
1587 wxString::const_iterator lastSep
= end
;
1588 for ( wxString::const_iterator p
= fmt
.begin(); p
!= end
; ++p
)
1590 if ( strchr(timeSep
, *p
) )
1592 if ( lastSep
== end
)
1595 // skip it for now, we'll discard it if it's followed by a time
1596 // specifier later or add it to fmtDateOnly if it is not
1601 (p
+ 1 != end
) && strchr(timeFmtSpecs
, p
[1]) )
1603 // time specified found: skip it and any preceding separators
1609 if ( lastSep
!= end
)
1611 fmtDateOnly
+= wxString(lastSep
, p
);
1619 #else // !HAVE_LANGINFO_H
1622 // no fallback, let the application deal with unavailability of
1623 // nl_langinfo() itself as there is no good way for us to do it (well, we
1624 // could try to reverse engineer the format from strftime() output but this
1625 // looks like too much trouble considering the relatively small number of
1626 // systems without nl_langinfo() still in use)
1628 #endif // HAVE_LANGINFO_H/!HAVE_LANGINFO_H
1631 } // anonymous namespace
1634 wxString
wxLocale::GetInfo(wxLocaleInfo index
, wxLocaleCategory cat
)
1636 lconv
* const lc
= localeconv();
1642 case wxLOCALE_THOUSANDS_SEP
:
1643 if ( cat
== wxLOCALE_CAT_NUMBER
)
1644 return lc
->thousands_sep
;
1645 else if ( cat
== wxLOCALE_CAT_MONEY
)
1646 return lc
->mon_thousands_sep
;
1648 wxFAIL_MSG( "invalid wxLocaleCategory" );
1652 case wxLOCALE_DECIMAL_POINT
:
1653 if ( cat
== wxLOCALE_CAT_NUMBER
)
1654 return lc
->decimal_point
;
1655 else if ( cat
== wxLOCALE_CAT_MONEY
)
1656 return lc
->mon_decimal_point
;
1658 wxFAIL_MSG( "invalid wxLocaleCategory" );
1661 case wxLOCALE_SHORT_DATE_FMT
:
1662 case wxLOCALE_LONG_DATE_FMT
:
1663 case wxLOCALE_DATE_TIME_FMT
:
1664 case wxLOCALE_TIME_FMT
:
1665 if ( cat
!= wxLOCALE_CAT_DATE
&& cat
!= wxLOCALE_CAT_DEFAULT
)
1667 wxFAIL_MSG( "invalid wxLocaleCategory" );
1671 return GetDateFormatFromLangInfo(index
);
1675 wxFAIL_MSG( "unknown wxLocaleInfo value" );
1683 // ----------------------------------------------------------------------------
1684 // global functions and variables
1685 // ----------------------------------------------------------------------------
1687 // retrieve/change current locale
1688 // ------------------------------
1690 // the current locale object
1691 static wxLocale
*g_pLocale
= NULL
;
1693 wxLocale
*wxGetLocale()
1698 wxLocale
*wxSetLocale(wxLocale
*pLocale
)
1700 wxLocale
*pOld
= g_pLocale
;
1701 g_pLocale
= pLocale
;
1707 // ----------------------------------------------------------------------------
1708 // wxLocale module (for lazy destruction of languagesDB)
1709 // ----------------------------------------------------------------------------
1711 class wxLocaleModule
: public wxModule
1713 DECLARE_DYNAMIC_CLASS(wxLocaleModule
)
1724 wxLocale::DestroyLanguagesDB();
1728 IMPLEMENT_DYNAMIC_CLASS(wxLocaleModule
, wxModule
)
1730 #endif // wxUSE_INTL