📄 translator.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.**** This file is part of the Qt Linguist of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://www.trolltech.com/products/qt/opensource.html**** If you are unsure which license is appropriate for your use, please** review the following information:** http://www.trolltech.com/products/qt/licensing.html or contact the** sales department at sales@trolltech.com.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "translator.h"#include <qplatformdefs.h>#ifndef QT_NO_TRANSLATION#include <QFileInfo>#include <QString>#include <QCoreApplication>#include <QDataStream>#include <QFile>#include <QMap>#include <QtAlgorithms>#if defined(Q_OS_UNIX)#define QT_USE_MMAP#endif// most of the headers below are already included in qplatformdefs.h// also this lacks Large File support but that's probably irrelevant#if defined(QT_USE_MMAP)// for mmap#include <sys/mman.h>#include <errno.h>#endif#include <stdlib.h>/*$ mcookie3cb86418caef9c95cd211cbf60a1bddd$*/// magic number for the filestatic const int MagicLength = 16;static const uchar magic[MagicLength] = { 0x3c, 0xb8, 0x64, 0x18, 0xca, 0xef, 0x9c, 0x95, 0xcd, 0x21, 0x1c, 0xbf, 0x60, 0xa1, 0xbd, 0xdd};static bool match(const char* found, const char* target){ // 0 means anything, "" means empty return found == 0 || qstrcmp(found, target) == 0;}#if defined(Q_C_CALLBACKS)extern "C" {#endif/* Yes, unfortunately, we have code here that depends on endianness. The candidate is big endian (it comes from a .qm file) whereas the target endianness depends on the system Qt is running on.*/#ifdef Q_OS_TEMPstatic int __cdecl cmp_uint32_little(const void* target, const void* candidate)#elsestatic int cmp_uint32_little(const void* target, const void* candidate)#endif{ const uchar* t = (const uchar*) target; const uchar* c = (const uchar*) candidate; return t[3] != c[0] ? (int) t[3] - (int) c[0] : t[2] != c[1] ? (int) t[2] - (int) c[1] : t[1] != c[2] ? (int) t[1] - (int) c[2] : (int) t[0] - (int) c[3];}#ifdef Q_OS_TEMPstatic int __cdecl cmp_uint32_big(const void* target, const void* candidate)#elsestatic int cmp_uint32_big(const void* target, const void* candidate)#endif{ const uint* t = (const uint*) target; const uint* c = (const uint*) candidate; return (*t > *c ? 1 : (*t == *c ? 0 : -1));}#if defined(Q_C_CALLBACKS)}#endifstatic uint elfHash(const char * name){ const uchar *k; uint h = 0; uint g; if (name) { k = (const uchar *) name; while (*k) { h = (h << 4) + *k++; if ((g = (h & 0xf0000000)) != 0) h ^= g >> 24; h &= ~g; } } if (!h) h = 1; return h;}extern bool qt_detectRTLLanguage();class TranslatorPrivate{public: struct Offset { Offset() : h(0), o(0) { } Offset(const TranslatorMessage& m, int offset) : h(m.hash()), o(offset) { } bool operator<(const Offset &other) const { return (h != other.h) ? h < other.h : o < other.o; } bool operator==(const Offset &other) const { return h == other.h && o == other.o; } uint h; uint o; }; enum { Contexts = 0x2f, Hashes = 0x42, Messages = 0x69 }; TranslatorPrivate(Translator *qq) : q(qq), unmapPointer(0), unmapLength(0) {} // Translator must finalize this before deallocating it Translator *q; // for mmap'ed files, this is what needs to be unmapped. char *unmapPointer; unsigned int unmapLength; // for squeezed but non-file data, this is what needs to be deleted QByteArray messageArray; QByteArray offsetArray; QByteArray contextArray;#ifndef QT_NO_TRANSLATION_BUILDER QMap<TranslatorMessage, void *> messages;#endif bool do_load(const uchar *data, int len);};/*! \class Translator \brief The Translator class provides internationalization support for text output. \ingroup i18n \ingroup environment \mainclass An object of this class contains a set of TranslatorMessage objects, each of which specifies a translation from a source language to a target language. Translator provides functions to look up translations, add new ones, remove them, load and save them, etc. The most common use of Translator is to: load a translator file created with \l{Qt Linguist Manual}, install it using QApplication::installTranslator(), and use it via QObject::tr(). For example: \code int main(int argc, char ** argv) { QApplication app(argc, argv); Translator translator(0); translator.load("french.qm", "."); app.installTranslator(&translator); MyWidget m; app.setMainWidget(&m); m.show(); return app.exec(); } \endcode Note that the translator must be created \e before the application's main window. Most applications will never need to do anything else with this class. The other functions provided by this class are useful for applications that work on translator files. We call a translation a "messsage". For this reason, translation files are sometimes referred to as "message files". It is possible to lookup a translation using findMessage() (as tr() and QApplication::translate() do) and contains(), to insert a new translation messsage using insert(), and to remove one using remove(). Translation tools often need more information than the bare source text and translation, for example, context information to help the translator. But end-user programs that are using translations usually only need lookup. To cater for these different needs, Translator can use stripped translator files that use the minimum of memory and which support little more functionality than findMessage(). Thus, load() may not load enough information to make anything more than findMessage() work. save() has an argument indicating whether to save just this minimum of information or to save everything. "Everything" means that for each translation item the following information is kept: \list \i The \e {translated text} - the return value from tr(). \i The input key: \list \i The \e {source text} - usually the argument to tr(). \i The \e context - usually the class name for the tr() caller. \i The \e comment - a comment that helps disambiguate different uses of the same text in the same context. \endlist \endlist The minimum for each item is just the information necessary for findMessage() to return the right text. This may include the source, context and comment, but usually it is just a hash value and the translated text. For example, the "Cancel" in a dialog might have "Anuluj" when the program runs in Polish (in this case the source text would be "Cancel"). The context would (normally) be the dialog's class name; there would normally be no comment, and the translated text would be "Anuluj". But it's not always so simple. The Spanish version of a printer dialog with settings for two-sided printing and binding would probably require both "Activado" and "Activada" as translations for "Enabled". In this case the source text would be "Enabled" in both cases, and the context would be the dialog's class name, but the two items would have disambiguating comments such as "two-sided printing" for one and "binding" for the other. The comment enables the translator to choose the appropriate gender for the Spanish version, and enables Qt to distinguish between translations. Note that when Translator loads a stripped file, most functions do not work. The functions that do work with stripped files are explicitly documented as such. \sa TranslatorMessage QApplication::installTranslator() QApplication::removeTranslator() QObject::tr() QApplication::translate()*//*! \enum Translator::SaveMode This enum type defines how Translator writes translation files. There are two modes: \value Everything files are saved with all available information \value Stripped files are saved with just enough information for end-user applications Note that when Translator loads a stripped file, most functions do not work. The functions that do work with stripped files are explicitly documented as such.*//*! Constructs an empty message file object with parent \a parent that is not connected to any file.*/Translator::Translator(QObject * parent) : QTranslator(parent){ d = new TranslatorPrivate(this);}/*! Destroys the object and frees any allocated resources.*/Translator::~Translator(){ if (QCoreApplication::instance()) QCoreApplication::instance()->removeTranslator(this); clear(); delete d;}/*! Loads \a filename + \a suffix (".qm" if the \a suffix is not specified), which may be an absolute file name or relative to \a directory. The previous contents of this translator object is discarded. If the file name does not exist, other file names are tried in the following order: \list 1 \i File name without \a suffix appended. \i File name with text after a character in \a search_delimiters stripped ("_." is the default for \a search_delimiters if it is an empty string) and \a suffix. \i File name stripped without \a suffix appended. \i File name stripped further, etc. \endlist For example, an application running in the fr_CA locale (French-speaking Canada) might call load("foo.fr_ca", "/opt/foolib"). load() would then try to open the first existing readable file from this list: \list 1 \i /opt/foolib/foo.fr_ca.qm \i /opt/foolib/foo.fr_ca \i /opt/foolib/foo.fr.qm \i /opt/foolib/foo.fr \i /opt/foolib/foo.qm \i /opt/foolib/foo \endlist \sa save()*/bool Translator::load(const QString & filename, const QString & directory, const QString & search_delimiters, const QString & suffix){ clear(); QString prefix; if (filename[0] == QLatin1Char('/')#ifdef Q_WS_WIN || (filename[0].isLetter() && filename[1] == QLatin1Char(':')) || filename[0] == QLatin1Char('\\')#endif ) prefix = QLatin1String(""); else prefix = directory; if (prefix.length()) { if (prefix[int(prefix.length()-1)] != QLatin1Char('/')) prefix += QLatin1Char('/'); } QString fname = filename; QString realname; QString delims; delims = search_delimiters.isNull() ? QString::fromLatin1("_.") : search_delimiters; for (;;) { QFileInfo fi; realname = prefix + fname + (suffix.isNull() ? QString::fromLatin1(".qm") : suffix); fi.setFile(realname); if (fi.isReadable()) break; realname = prefix + fname; fi.setFile(realname); if (fi.isReadable()) break; int rightmost = 0; for (int i = 0; i < (int)delims.length(); i++) { int k = fname.lastIndexOf(delims[i]); if (k > rightmost) rightmost = k; } // no truncations? fail if (rightmost == 0) return false; fname.truncate(rightmost); } // realname is now the fully qualified name of a readable file. bool ok = false;#ifdef QT_USE_MMAP#ifndef MAP_FILE#define MAP_FILE 0#endif#ifndef MAP_FAILED#define MAP_FAILED -1#endif int fd = -1; if (!realname.startsWith(QLatin1String(":"))) fd = QT_OPEN(QFile::encodeName(realname), O_RDONLY,#if defined(Q_OS_WIN) _S_IREAD | _S_IWRITE#else 0666#endif ); if (fd >= 0) { struct stat st; if (!fstat(fd, &st)) { char *ptr; ptr = reinterpret_cast<char *>( mmap(0, st.st_size, // any address, whole file PROT_READ, // read-only memory MAP_FILE | MAP_PRIVATE, // swap-backed map from file fd, 0)); // from offset 0 of fd if (ptr && ptr != reinterpret_cast<char *>(MAP_FAILED)) { d->unmapPointer = ptr; d->unmapLength = st.st_size;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -