1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Internationalization and localisation for wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "intl.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
39 #include "wx/string.h"
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 // this should *not* be wxChar, this type must have exactly 8 bits!
52 typedef unsigned char size_t8
;
55 #if defined(__WIN16__)
56 typedef unsigned long size_t32
;
57 #elif defined(__WIN32__)
58 typedef unsigned int size_t32
;
60 // Win64 will have different type sizes
61 #error "Please define a 32 bit type"
64 // SIZEOF_XXX are defined by configure
65 #if defined(SIZEOF_INT) && (SIZEOF_INT == 4)
66 typedef unsigned int size_t32
;
67 #elif defined(SIZEOF_LONG) && (SIZEOF_LONG == 4)
68 typedef unsigned long size_t32
;
70 // assume sizeof(int) == 4 - what else can we do
71 typedef unsigned int size_t32
;
73 // ... but at least check it during run time
74 static class IntSizeChecker
79 // Asserting a sizeof directly causes some compilers to
80 // issue a "using constant in a conditional expression" warning
81 size_t intsize
= sizeof(int);
83 wxASSERT_MSG( intsize
== 4,
84 "size_t32 is incorrectly defined!" );
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 // magic number identifying the .mo format file
95 const size_t32 MSGCATALOG_MAGIC
= 0x950412de;
96 const size_t32 MSGCATALOG_MAGIC_SW
= 0xde120495;
98 // extension of ".mo" files
99 #define MSGCATALOG_EXTENSION ".mo"
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 // suppress further error messages about missing translations
106 // (if you don't have one catalog file, you wouldn't like to see the
107 // error message for each string in it, so normally it's given only
109 void wxSuppressTransErrors();
111 // restore the logging
112 void wxRestoreTransErrors();
114 // get the current state
115 bool wxIsLoggingTransErrors();
117 static wxLocale
*wxSetLocale(wxLocale
*pLocale
);
119 // ----------------------------------------------------------------------------
120 // wxMsgCatalog corresponds to one disk-file message catalog.
122 // This is a "low-level" class and is used only by wxLocale (that's why
123 // it's designed to be stored in a linked list)
124 // ----------------------------------------------------------------------------
133 // load the catalog from disk (szDirPrefix corresponds to language)
134 bool Load(const wxChar
*szDirPrefix
, const wxChar
*szName
);
135 bool IsLoaded() const { return m_pData
!= NULL
; }
137 // get name of the catalog
138 const wxChar
*GetName() const { return m_pszName
; }
140 // get the translated string: returns NULL if not found
141 const char *GetString(const char *sz
) const;
143 // public variable pointing to the next element in a linked list (or NULL)
144 wxMsgCatalog
*m_pNext
;
147 // this implementation is binary compatible with GNU gettext() version 0.10
149 // an entry in the string table
150 struct wxMsgTableEntry
152 size_t32 nLen
; // length of the string
153 size_t32 ofsString
; // pointer to the string
156 // header of a .mo file
157 struct wxMsgCatalogHeader
159 size_t32 magic
, // offset +00: magic id
160 revision
, // +04: revision
161 numStrings
; // +08: number of strings in the file
162 size_t32 ofsOrigTable
, // +0C: start of original string table
163 ofsTransTable
; // +10: start of translated string table
164 size_t32 nHashSize
, // +14: hash table size
165 ofsHashTable
; // +18: offset of hash table start
168 // all data is stored here, NULL if no data loaded
172 size_t32 m_numStrings
, // number of strings in this domain
173 m_nHashSize
; // number of entries in hash table
174 size_t32
*m_pHashTable
; // pointer to hash table
175 wxMsgTableEntry
*m_pOrigTable
, // pointer to original strings
176 *m_pTransTable
; // translated
178 const char *StringAtOfs(wxMsgTableEntry
*pTable
, size_t32 index
) const
179 { return (const char *)(m_pData
+ Swap(pTable
[index
].ofsString
)); }
182 // calculate the hash value of given string
183 static inline size_t32
GetHash(const char *sz
);
184 // big<->little endian
185 inline size_t32
Swap(size_t32 ui
) const;
188 bool HasHashTable() const // true if hash table is present
189 { return m_nHashSize
> 2 && m_pHashTable
!= NULL
; }
191 bool m_bSwapped
; // wrong endianness?
193 wxChar
*m_pszName
; // name of the domain
196 // ----------------------------------------------------------------------------
198 // ----------------------------------------------------------------------------
200 // the list of the directories to search for message catalog files
201 static wxArrayString s_searchPrefixes
;
203 // ============================================================================
205 // ============================================================================
207 // ----------------------------------------------------------------------------
208 // wxMsgCatalog class
209 // ----------------------------------------------------------------------------
211 // calculate hash value using the so called hashpjw function by P.J. Weinberger
212 // [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools]
213 size_t32
wxMsgCatalog::GetHash(const char *sz
)
215 #define HASHWORDBITS 32 // the length of size_t32
219 while ( *sz
!= '\0' ) {
221 hval
+= (size_t32
)*sz
++;
222 g
= hval
& ((size_t32
)0xf << (HASHWORDBITS
- 4));
224 hval
^= g
>> (HASHWORDBITS
- 8);
232 // swap the 2 halves of 32 bit integer if needed
233 size_t32
wxMsgCatalog::Swap(size_t32 ui
) const
235 return m_bSwapped
? (ui
<< 24) | ((ui
& 0xff00) << 8) |
236 ((ui
>> 8) & 0xff00) | (ui
>> 24)
240 wxMsgCatalog::wxMsgCatalog()
246 wxMsgCatalog::~wxMsgCatalog()
249 wxDELETEA(m_pszName
);
252 // small class to suppress the translation erros until exit from current scope
256 NoTransErr() { wxSuppressTransErrors(); }
257 ~NoTransErr() { wxRestoreTransErrors(); }
260 // return all directories to search for given prefix
261 static wxString
GetAllMsgCatalogSubdirs(const wxChar
*prefix
,
266 // search first in prefix/fr/LC_MESSAGES, then in prefix/fr and finally in
267 // prefix (assuming the language is 'fr')
268 searchPath
<< prefix
<< wxFILE_SEP_PATH
<< lang
<< wxFILE_SEP_PATH
269 << _T("LC_MESSAGES") << wxPATH_SEP
270 << prefix
<< wxFILE_SEP_PATH
<< lang
<< wxPATH_SEP
271 << prefix
<< wxPATH_SEP
;
276 // construct the search path for the given language
277 static wxString
GetFullSearchPath(const wxChar
*lang
)
281 // first take the entries explicitly added by the program
282 size_t count
= s_searchPrefixes
.Count();
283 for ( size_t n
= 0; n
< count
; n
++ )
285 searchPath
<< GetAllMsgCatalogSubdirs(s_searchPrefixes
[n
], lang
)
289 // then take the current directory
290 // FIXME it should be the directory of the executable
291 searchPath
<< GetAllMsgCatalogSubdirs(_T("."), lang
) << wxPATH_SEP
;
293 // and finally add some standard ones
295 << GetAllMsgCatalogSubdirs(_T("/usr/share/locale"), lang
) << wxPATH_SEP
296 << GetAllMsgCatalogSubdirs(_T("/usr/lib/locale"), lang
) << wxPATH_SEP
297 << GetAllMsgCatalogSubdirs(_T("/usr/local/share/locale"), lang
);
302 // open disk file and read in it's contents
303 bool wxMsgCatalog::Load(const wxChar
*szDirPrefix
, const wxChar
*szName
)
305 // FIXME VZ: I forgot the exact meaning of LC_PATH - anyone to remind me?
307 const wxChar
*pszLcPath
= wxGetenv("LC_PATH");
308 if ( pszLcPath
!= NULL
)
309 strPath
+= pszLcPath
+ wxString(szDirPrefix
) + MSG_PATH
;
312 wxString searchPath
= GetFullSearchPath(szDirPrefix
);
313 const wxChar
*sublocale
= wxStrchr(szDirPrefix
, _T('_'));
316 // also add just base locale name: for things like "fr_BE" (belgium
317 // french) we should use "fr" if no belgium specific message catalogs
319 searchPath
<< GetFullSearchPath(wxString(szDirPrefix
).
320 Left((size_t)(sublocale
- szDirPrefix
)))
324 wxString strFile
= szName
;
325 strFile
+= MSGCATALOG_EXTENSION
;
327 // don't give translation errors here because the wxstd catalog might
328 // not yet be loaded (and it's normal)
330 // (we're using an object because we have several return paths)
331 NoTransErr noTransErr
;
333 wxLogVerbose(_("looking for catalog '%s' in path '%s'."),
334 szName
, searchPath
.c_str());
336 wxString strFullName
;
337 if ( !wxFindFileInPath(&strFullName
, searchPath
, strFile
) ) {
338 wxLogWarning(_("catalog file for domain '%s' not found."), szName
);
343 wxLogVerbose(_("using catalog '%s' from '%s'."),
344 szName
, strFullName
.c_str());
346 wxFile
fileMsg(strFullName
);
347 if ( !fileMsg
.IsOpened() )
351 off_t nSize
= fileMsg
.Length();
352 if ( nSize
== wxInvalidOffset
)
355 // read the whole file in memory
356 m_pData
= new size_t8
[nSize
];
357 if ( fileMsg
.Read(m_pData
, nSize
) != nSize
) {
363 bool bValid
= (size_t)nSize
> sizeof(wxMsgCatalogHeader
);
365 wxMsgCatalogHeader
*pHeader
= (wxMsgCatalogHeader
*)m_pData
;
367 // we'll have to swap all the integers if it's true
368 m_bSwapped
= pHeader
->magic
== MSGCATALOG_MAGIC_SW
;
370 // check the magic number
371 bValid
= m_bSwapped
|| pHeader
->magic
== MSGCATALOG_MAGIC
;
375 // it's either too short or has incorrect magic number
376 wxLogWarning(_("'%s' is not a valid message catalog."), strFullName
.c_str());
383 m_numStrings
= Swap(pHeader
->numStrings
);
384 m_pOrigTable
= (wxMsgTableEntry
*)(m_pData
+
385 Swap(pHeader
->ofsOrigTable
));
386 m_pTransTable
= (wxMsgTableEntry
*)(m_pData
+
387 Swap(pHeader
->ofsTransTable
));
389 m_nHashSize
= Swap(pHeader
->nHashSize
);
390 m_pHashTable
= (size_t32
*)(m_pData
+ Swap(pHeader
->ofsHashTable
));
392 m_pszName
= new wxChar
[wxStrlen(szName
) + 1];
393 wxStrcpy(m_pszName
, szName
);
395 // everything is fine
399 // search for a string
400 const char *wxMsgCatalog::GetString(const char *szOrig
) const
402 if ( szOrig
== NULL
)
405 if ( HasHashTable() ) { // use hash table for lookup if possible
406 size_t32 nHashVal
= GetHash(szOrig
);
407 size_t32 nIndex
= nHashVal
% m_nHashSize
;
409 size_t32 nIncr
= 1 + (nHashVal
% (m_nHashSize
- 2));
412 size_t32 nStr
= Swap(m_pHashTable
[nIndex
]);
416 if ( strcmp(szOrig
, StringAtOfs(m_pOrigTable
, nStr
- 1)) == 0 )
417 return StringAtOfs(m_pTransTable
, nStr
- 1);
419 if ( nIndex
>= m_nHashSize
- nIncr
)
420 nIndex
-= m_nHashSize
- nIncr
;
425 else { // no hash table: use default binary search
429 while ( bottom
< top
) {
430 current
= (bottom
+ top
) / 2;
431 int res
= strcmp(szOrig
, StringAtOfs(m_pOrigTable
, current
));
435 bottom
= current
+ 1;
437 return StringAtOfs(m_pTransTable
, current
);
445 // ----------------------------------------------------------------------------
447 // ----------------------------------------------------------------------------
451 m_pszOldLocale
= NULL
;
455 // NB: this function has (desired) side effect of changing current locale
456 bool wxLocale::Init(const wxChar
*szName
,
457 const wxChar
*szShort
,
458 const wxChar
*szLocale
,
461 m_strLocale
= szName
;
462 m_strShort
= szShort
;
464 // change current locale (default: same as long name)
465 if ( szLocale
== NULL
)
467 m_pszOldLocale
= wxSetlocale(LC_ALL
, szLocale
);
468 if ( m_pszOldLocale
== NULL
)
469 wxLogError(_("locale '%s' can not be set."), szLocale
);
471 // the short name will be used to look for catalog files as well,
472 // so we need something here
473 if ( m_strShort
.IsEmpty() ) {
474 // FIXME I don't know how these 2 letter abbreviations are formed,
475 // this wild guess is surely wrong
476 m_strShort
= tolower(szLocale
[0]) + tolower(szLocale
[1]);
479 // save the old locale to be able to restore it later
480 m_pOldLocale
= wxSetLocale(this);
482 // load the default catalog with wxWindows standard messages
486 bOk
= AddCatalog(_T("wxstd"));
491 void wxLocale::AddCatalogLookupPathPrefix(const wxString
& prefix
)
493 if ( s_searchPrefixes
.Index(prefix
) == wxNOT_FOUND
)
495 s_searchPrefixes
.Add(prefix
);
497 //else: already have it
501 wxLocale::~wxLocale()
504 wxMsgCatalog
*pTmpCat
;
505 while ( m_pMsgCat
!= NULL
) {
507 m_pMsgCat
= m_pMsgCat
->m_pNext
;
511 // restore old locale
512 wxSetLocale(m_pOldLocale
);
513 wxSetlocale(LC_ALL
, m_pszOldLocale
);
516 // get the translation of given string in current locale
517 const wxMB2WXbuf
wxLocale::GetString(const wxChar
*szOrigString
,
518 const wxChar
*szDomain
) const
520 if ( wxIsEmpty(szOrigString
) )
523 const char *pszTrans
= NULL
;
524 const wxWX2MBbuf szOrgString
= wxConvCurrent
->cWX2MB(szOrigString
);
526 wxMsgCatalog
*pMsgCat
;
527 if ( szDomain
!= NULL
) {
528 pMsgCat
= FindCatalog(szDomain
);
530 // does the catalog exist?
531 if ( pMsgCat
!= NULL
)
532 pszTrans
= pMsgCat
->GetString(szOrgString
);
535 // search in all domains
536 for ( pMsgCat
= m_pMsgCat
; pMsgCat
!= NULL
; pMsgCat
= pMsgCat
->m_pNext
) {
537 pszTrans
= pMsgCat
->GetString(szOrgString
);
538 if ( pszTrans
!= NULL
) // take the first found
543 if ( pszTrans
== NULL
) {
544 if ( wxIsLoggingTransErrors() ) {
545 // suppress further error messages if we're not debugging: this avoids
546 // flooding the user with messages about each and every missing string if,
547 // for example, a whole catalog file is missing.
549 // do it before calling LogWarning to prevent infinite recursion!
551 NoTransErr noTransErr
;
553 wxSuppressTransErrors();
554 #endif // debug/!debug
556 if ( szDomain
!= NULL
)
558 wxLogWarning(_("string '%s' not found in domain '%s' for locale '%s'."),
559 szOrigString
, szDomain
, m_strLocale
.c_str());
563 wxLogWarning(_("string '%s' not found in locale '%s'."),
564 szOrigString
, m_strLocale
.c_str());
568 return (wxMB2WXbuf
)(szOrigString
);
571 return (wxMB2WXbuf
)(wxConvCurrent
->cMB2WX(pszTrans
));
574 // find catalog by name in a linked list, return NULL if !found
575 wxMsgCatalog
*wxLocale::FindCatalog(const wxChar
*szDomain
) const
577 // linear search in the linked list
578 wxMsgCatalog
*pMsgCat
;
579 for ( pMsgCat
= m_pMsgCat
; pMsgCat
!= NULL
; pMsgCat
= pMsgCat
->m_pNext
) {
580 if ( wxStricmp(pMsgCat
->GetName(), szDomain
) == 0 )
587 // check if the given catalog is loaded
588 bool wxLocale::IsLoaded(const wxChar
*szDomain
) const
590 return FindCatalog(szDomain
) != NULL
;
593 // add a catalog to our linked list
594 bool wxLocale::AddCatalog(const wxChar
*szDomain
)
596 wxMsgCatalog
*pMsgCat
= new wxMsgCatalog
;
598 if ( pMsgCat
->Load(m_strShort
, szDomain
) ) {
599 // add it to the head of the list so that in GetString it will
600 // be searched before the catalogs added earlier
601 pMsgCat
->m_pNext
= m_pMsgCat
;
607 // don't add it because it couldn't be loaded anyway
614 // ----------------------------------------------------------------------------
615 // global functions and variables
616 // ----------------------------------------------------------------------------
618 // translation errors logging
619 // --------------------------
621 static bool gs_bGiveTransErrors
= TRUE
;
623 void wxSuppressTransErrors()
625 gs_bGiveTransErrors
= FALSE
;
628 void wxRestoreTransErrors()
630 gs_bGiveTransErrors
= TRUE
;
633 bool wxIsLoggingTransErrors()
635 return gs_bGiveTransErrors
;
638 // retrieve/change current locale
639 // ------------------------------
641 // the current locale object
642 static wxLocale
*g_pLocale
= NULL
;
644 wxLocale
*wxGetLocale()
649 wxLocale
*wxSetLocale(wxLocale
*pLocale
)
651 wxLocale
*pOld
= g_pLocale
;