Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtranslator.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include "qplatformdefs.h"
6
7#include "qtranslator.h"
8
9#ifndef QT_NO_TRANSLATION
10
11#include "qfileinfo.h"
12#include "qstring.h"
13#include "qstringlist.h"
16#include "qdatastream.h"
17#include "qendian.h"
18#include "qfile.h"
19#include "qalgorithms.h"
20#include "qtranslator_p.h"
21#include "qlocale.h"
22#include "qlogging.h"
24#include "qdebug.h"
25#include "qendian.h"
26#include "qresource.h"
27
28#if defined(Q_OS_UNIX) && !defined(Q_OS_INTEGRITY)
29# define QT_USE_MMAP
30# include "private/qcore_unix_p.h"
31// for mmap
32# include <sys/mman.h>
33#endif
34
35#include <stdlib.h>
36#include <new>
37
38#include "qobject_p.h"
39
40#include <vector>
41#include <memory>
42
43#include <QtCore/qreadwritelock.h>
44
46
47Q_STATIC_LOGGING_CATEGORY(lcTranslator, "qt.core.qtranslator")
48
49namespace {
52}
53
54/*
55$ mcookie
563cb86418caef9c95cd211cbf60a1bddd
57$
58*/
59
60// magic number for the file
61static const int MagicLength = 16;
62static const uchar magic[MagicLength] = {
63 0x3c, 0xb8, 0x64, 0x18, 0xca, 0xef, 0x9c, 0x95,
64 0xcd, 0x21, 0x1c, 0xbf, 0x60, 0xa1, 0xbd, 0xdd
65};
66
67static inline QString dotQmLiteral() { return QStringLiteral(".qm"); }
68
69static bool match(const uchar *found, uint foundLen, const char *target, uint targetLen)
70{
71 // catch the case if \a found has a zero-terminating symbol and \a len includes it.
72 // (normalize it to be without the zero-terminating symbol)
73 if (foundLen > 0 && found[foundLen-1] == '\0')
74 --foundLen;
75 return ((targetLen == foundLen) && memcmp(found, target, foundLen) == 0);
76}
77
78static void elfHash_continue(const char *name, uint &h)
79{
80 const uchar *k;
81 uint g;
82
83 k = (const uchar *) name;
84 while (*k) {
85 h = (h << 4) + *k++;
86 if ((g = (h & 0xf0000000)) != 0)
87 h ^= g >> 24;
88 h &= ~g;
89 }
90}
91
92static void elfHash_finish(uint &h)
93{
94 if (!h)
95 h = 1;
96}
97
98static uint elfHash(const char *name)
99{
100 uint hash = 0;
101 elfHash_continue(name, hash);
103 return hash;
104}
105
106/*
107 \internal
108
109 Determines whether \a rules are valid "numerus rules". Test input with this
110 function before calling numerusHelper, below.
111 */
112static bool isValidNumerusRules(const uchar *rules, uint rulesSize)
113{
114 // Disabled computation of maximum numerus return value
115 // quint32 numerus = 0;
116
117 if (rulesSize == 0)
118 return true;
119
120 quint32 offset = 0;
121 do {
122 uchar opcode = rules[offset];
123 uchar op = opcode & Q_OP_MASK;
124
125 if (opcode & 0x80)
126 return false; // Bad op
127
128 if (++offset == rulesSize)
129 return false; // Missing operand
130
131 // right operand
132 ++offset;
133
134 switch (op)
135 {
136 case Q_EQ:
137 case Q_LT:
138 case Q_LEQ:
139 break;
140
141 case Q_BETWEEN:
142 if (offset != rulesSize) {
143 // third operand
144 ++offset;
145 break;
146 }
147 return false; // Missing operand
148
149 default:
150 return false; // Bad op (0)
151 }
152
153 // ++numerus;
154 if (offset == rulesSize)
155 return true;
156
157 } while (((rules[offset] == Q_AND)
158 || (rules[offset] == Q_OR)
159 || (rules[offset] == Q_NEWRULE))
160 && ++offset != rulesSize);
161
162 // Bad op
163 return false;
164}
165
166/*
167 \internal
168
169 This function does no validation of input and assumes it is well-behaved,
170 these assumptions can be checked with isValidNumerusRules, above.
171
172 Determines which translation to use based on the value of \a n. The return
173 value is an index identifying the translation to be used.
174
175 \a rules is a character array of size \a rulesSize containing bytecode that
176 operates on the value of \a n and ultimately determines the result.
177
178 This function has O(1) space and O(rulesSize) time complexity.
179 */
180static uint numerusHelper(int n, const uchar *rules, uint rulesSize)
181{
182 uint result = 0;
183 uint i = 0;
184
185 if (rulesSize == 0)
186 return 0;
187
188 for (;;) {
189 bool orExprTruthValue = false;
190
191 for (;;) {
192 bool andExprTruthValue = true;
193
194 for (;;) {
195 bool truthValue = true;
196 int opcode = rules[i++];
197
198 int leftOperand = n;
199 if (opcode & Q_MOD_10) {
200 leftOperand %= 10;
201 } else if (opcode & Q_MOD_100) {
202 leftOperand %= 100;
203 } else if (opcode & Q_LEAD_1000) {
204 while (leftOperand >= 1000)
205 leftOperand /= 1000;
206 }
207
208 int op = opcode & Q_OP_MASK;
209 int rightOperand = rules[i++];
210
211 switch (op) {
212 case Q_EQ:
213 truthValue = (leftOperand == rightOperand);
214 break;
215 case Q_LT:
216 truthValue = (leftOperand < rightOperand);
217 break;
218 case Q_LEQ:
219 truthValue = (leftOperand <= rightOperand);
220 break;
221 case Q_BETWEEN:
222 int bottom = rightOperand;
223 int top = rules[i++];
224 truthValue = (leftOperand >= bottom && leftOperand <= top);
225 }
226
227 if (opcode & Q_NOT)
228 truthValue = !truthValue;
229
230 andExprTruthValue = andExprTruthValue && truthValue;
231
232 if (i == rulesSize || rules[i] != Q_AND)
233 break;
234 ++i;
235 }
236
237 orExprTruthValue = orExprTruthValue || andExprTruthValue;
238
239 if (i == rulesSize || rules[i] != Q_OR)
240 break;
241 ++i;
242 }
243
244 if (orExprTruthValue)
245 return result;
246
247 ++result;
248
249 if (i == rulesSize)
250 return result;
251
252 i++; // Q_NEWRULE
253 }
254
255 Q_ASSERT(false);
256 return 0;
257}
258
260{
262public:
263 enum { Contexts = 0x2f, Hashes = 0x42, Messages = 0x69, NumerusRules = 0x88, Dependencies = 0x96, Language = 0xa7 };
264
266#if defined(QT_USE_MMAP)
267 used_mmap(0),
268#endif
269 unmapPointer(nullptr), unmapLength(0), resource(nullptr),
270 messageArray(nullptr), offsetArray(nullptr), contextArray(nullptr), numerusRulesArray(nullptr),
273
274#if defined(QT_USE_MMAP)
275 bool used_mmap : 1;
276#endif
277 char *unmapPointer; // used memory (mmap, new or resource file)
279
280 // The resource object in case we loaded the translations from a resource
282
283 // used if the translator has dependencies
285
286 // Pointers and offsets into unmapPointer[unmapLength] array, or user
287 // provided data array
296
297 QString language;
298 QString filePath;
299
300 bool load_translation(const QStringList &languages, const QString &filename, const QString &prefix,
301 const QString &directory, const QString &suffix);
302 bool do_load(const QString &filename, const QString &directory);
303 bool do_load(const uchar *data, qsizetype len, const QString &directory);
304 QString do_translate(const char *context, const char *sourceText, const char *comment,
305 int n) const;
306 void clear();
307};
308
310{
311 Q_DECLARE_PUBLIC(QTranslator)
312public:
313 // Protects data against replaceData()
316
317 void replaceData(std::unique_ptr<QTranslatorData> &newData);
318};
319
320/*!
321 \class QTranslator
322 \inmodule QtCore
323
324 \brief The QTranslator class provides internationalization support for text
325 output.
326
327 \ingroup i18n
328
329 An object of this class contains a set of translations from a
330 source language to a target language. QTranslator provides
331 functions to look up translations in a translation file.
332 Translation files are created using \l{Qt Linguist}.
333
334 The most common use of QTranslator is to: load a translation
335 file, and install it using QCoreApplication::installTranslator().
336
337 Here's an example \c main() function using the
338 QTranslator:
339
340 \snippet hellotrmain.cpp 0
341
342 Note that the translator must be created \e before the
343 application's widgets.
344
345 Most applications will never need to do anything else with this
346 class. The other functions provided by this class are useful for
347 applications that work on translator files.
348
349 \section1 Looking up Translations
350
351 It is possible to look up a translation using translate() (as tr()
352 and QCoreApplication::translate() do). The translate() function takes
353 up to three parameters:
354
355 \list
356 \li The \e context - usually the class name for the tr() caller.
357 \li The \e {source text} - usually the argument to tr().
358 \li The \e disambiguation - an optional string that helps disambiguate
359 different uses of the same text in the same context.
360 \endlist
361
362 For example, the "Cancel" in a dialog might have "Anuluj" when the
363 program runs in Polish (in this case the source text would be
364 "Cancel"). The context would (normally) be the dialog's class
365 name; there would normally be no comment, and the translated text
366 would be "Anuluj".
367
368 But it's not always so simple. The Spanish version of a printer
369 dialog with settings for two-sided printing and binding would
370 probably require both "Activado" and "Activada" as translations
371 for "Enabled". In this case the source text would be "Enabled" in
372 both cases, and the context would be the dialog's class name, but
373 the two items would have disambiguations such as "two-sided printing"
374 for one and "binding" for the other. The disambiguation enables the
375 translator to choose the appropriate gender for the Spanish version,
376 and enables Qt to distinguish between translations.
377
378 \section1 Using Multiple Translations
379
380 Multiple translation files can be installed in an application.
381 Translations are searched for in the reverse order in which they were
382 installed, so the most recently installed translation file is searched
383 for translations first and the earliest translation file is searched
384 last. The search stops as soon as a translation containing a matching
385 string is found.
386
387 This mechanism makes it possible for a specific translation to be
388 "selected" or given priority over the others; simply uninstall the
389 translator from the application by passing it to the
390 QCoreApplication::removeTranslator() function and reinstall it with
391 QCoreApplication::installTranslator(). It will then be the first
392 translation to be searched for matching strings.
393
394 \section1 Security Considerations
395
396 Only install translation files from trusted sources.
397
398 Translation files are binary files that are generated from text-based
399 translation source files. The format of these binary files is strictly
400 defined by Qt and any manipulation of the data in the binary file may
401 crash the application when the file is loaded. Furthermore, even well-formed
402 translation files may contain misleading or malicious translations.
403
404 \sa QCoreApplication::installTranslator(), QCoreApplication::removeTranslator(),
405 QObject::tr(), QCoreApplication::translate(),
406 {Localized Clock Example}, {Arrow Pad Example}, {Troll Print Example}
407*/
408
409/*!
410 Constructs an empty message file object with parent \a parent that
411 is not connected to any file.
412*/
413
414QTranslator::QTranslator(QObject * parent)
415 : QObject(*new QTranslatorPrivate, parent)
416{
417}
418
419/*!
420 Destroys the object and frees any allocated resources.
421*/
422
423QTranslator::~QTranslator()
424{
425 if (QCoreApplication::instanceExists())
426 QCoreApplication::removeTranslator(this);
427}
428
429// Returns the fully qualified name of a readable file, or an empty string
430static QString findTranslationFile(const QString &filename, const QString &directory,
431 const QString &search_delimiters, const QString &suffix)
432{
433 QString prefix;
434 if (QFileInfo(filename).isRelative()) {
435 prefix = directory;
436 if (prefix.size() && !prefix.endsWith(u'/'))
437 prefix += u'/';
438 }
439
440 const QString suffixOrDotQM = suffix.isNull() ? dotQmLiteral() : suffix;
441 QStringView fname(filename);
442 QString realname;
443 const QString delims = search_delimiters.isNull() ? QStringLiteral("_.") : search_delimiters;
444
445 for (;;) {
446 QFileInfo fi;
447
448 realname = prefix + fname + suffixOrDotQM;
449 fi.setFile(realname);
450 if (fi.isReadable() && fi.isFile())
451 return realname;
452
453 realname = prefix + fname;
454 fi.setFile(realname);
455 if (fi.isReadable() && fi.isFile())
456 return realname;
457
458 qsizetype rightmost = 0;
459 for (auto ch : delims)
460 rightmost = std::max(rightmost, fname.lastIndexOf(ch));
461
462 // no truncations? fail
463 if (rightmost == 0)
464 return QString();
465
466 fname.truncate(rightmost);
467 }
468}
469
470/*!
471
472 Loads \a filename + \a suffix (".qm" if the \a suffix is not
473 specified), which may be an absolute file name or relative to \a
474 directory. Returns \c true if the translation is successfully loaded;
475 otherwise returns \c false.
476
477 If \a directory is not specified, the current directory is used
478 (i.e., as \l{QDir::}{currentPath()}).
479
480 The previous contents of this translator object are discarded.
481
482 If the file name does not exist, other file names are tried
483 in the following order:
484
485 \list 1
486 \li File name without \a suffix appended.
487 \li File name with text after a character in \a search_delimiters
488 stripped ("_." is the default for \a search_delimiters if it is
489 an empty string) and \a suffix.
490 \li File name stripped without \a suffix appended.
491 \li File name stripped further, etc.
492 \endlist
493
494 For example, an application running in the fr_CA locale
495 (French-speaking Canada) might call load("foo.fr_ca",
496 "/opt/foolib"). load() would then try to open the first existing
497 readable file from this list:
498
499 \list 1
500 \li \c /opt/foolib/foo.fr_ca.qm
501 \li \c /opt/foolib/foo.fr_ca
502 \li \c /opt/foolib/foo.fr.qm
503 \li \c /opt/foolib/foo.fr
504 \li \c /opt/foolib/foo.qm
505 \li \c /opt/foolib/foo
506 \endlist
507
508 Usually, it is better to use the QTranslator::load(const QLocale &,
509 const QString &, const QString &, const QString &, const QString &)
510 function instead, because it uses \l{QLocale::uiLanguages()} and not simply
511 the locale name, which refers to the formatting of dates and numbers and not
512 necessarily the UI language.
513*/
514
515bool QTranslator::load(const QString & filename, const QString & directory,
516 const QString & search_delimiters,
517 const QString & suffix)
518{
519 Q_D(QTranslator);
520 auto data = std::make_unique<QTranslatorData>();
521 const QString realname = findTranslationFile(filename, directory, search_delimiters, suffix);
522 const bool ok = !realname.isEmpty() && data->do_load(realname, directory);
523 d->replaceData(data);
524 return ok;
525}
526
527bool QTranslatorData::do_load(const QString &realname, const QString &directory)
528{
529 QTranslatorData *d = this;
530 bool ok = false;
531
532 if (realname.startsWith(u':')) {
533 // If the translation is in a non-compressed resource file, the data is already in
534 // memory, so no need to use QFile to copy it again.
535 Q_ASSERT(!d->resource);
536 d->resource = std::make_unique<QResource>(realname);
537 if (resource->isValid() && resource->compressionAlgorithm() == QResource::NoCompression
538 && resource->size() >= MagicLength
539 && !memcmp(resource->data(), magic, MagicLength)) {
540 d->unmapLength = resource->size();
541 d->unmapPointer = reinterpret_cast<char *>(const_cast<uchar *>(resource->data()));
542#if defined(QT_USE_MMAP)
543 d->used_mmap = false;
544#endif
545 ok = true;
546 } else {
547 resource = nullptr;
548 }
549 }
550
551 if (!ok) {
552 QFile file(realname);
553 if (!file.open(QIODevice::ReadOnly | QIODevice::Unbuffered))
554 return false;
555
556 qint64 fileSize = file.size();
557 if (fileSize < MagicLength || fileSize > std::numeric_limits<qsizetype>::max())
558 return false;
559
560 {
561 char magicBuffer[MagicLength];
562 if (MagicLength != file.read(magicBuffer, MagicLength)
563 || memcmp(magicBuffer, magic, MagicLength))
564 return false;
565 }
566
567 d->unmapLength = qsizetype(fileSize);
568
569#ifdef QT_USE_MMAP
570
571#ifndef MAP_FILE
572#define MAP_FILE 0
573#endif
574#ifndef MAP_FAILED
575#define MAP_FAILED reinterpret_cast<void *>(-1)
576#endif
577
578 int fd = file.handle();
579 if (fd >= 0) {
580 int protection = PROT_READ; // read-only memory
581 int flags = MAP_FILE | MAP_PRIVATE; // swap-backed map from file
582 void *ptr = QT_MMAP(nullptr, d->unmapLength,// any address, whole file
583 protection, flags,
584 fd, 0); // from offset 0 of fd
585 if (ptr != MAP_FAILED) {
586 file.close();
587 d->used_mmap = true;
588 d->unmapPointer = static_cast<char *>(ptr);
589 ok = true;
590 }
591 }
592#endif // QT_USE_MMAP
593
594 if (!ok) {
595 d->unmapPointer = new (std::nothrow) char[d->unmapLength];
596 if (d->unmapPointer) {
597 file.seek(0);
598 qint64 readResult = file.read(d->unmapPointer, d->unmapLength);
599 if (readResult == qint64(unmapLength))
600 ok = true;
601 }
602 }
603 }
604
605 if (ok) {
606 const QString base_dir =
607 !directory.isEmpty() ? directory : QFileInfo(realname).absolutePath();
608 if (d->do_load(reinterpret_cast<const uchar *>(d->unmapPointer), d->unmapLength,
609 base_dir)) {
610 d->filePath = realname;
611 return true;
612 }
613 }
614
615#if defined(QT_USE_MMAP)
616 if (used_mmap) {
617 used_mmap = false;
618 munmap(unmapPointer, unmapLength);
619 } else
620#endif
621 if (!d->resource)
622 delete [] unmapPointer;
623
624 d->resource = nullptr;
625 d->unmapPointer = nullptr;
626 d->unmapLength = 0;
627
628 return false;
629}
630
631bool QTranslatorData::load_translation(const QStringList &languages,
632 const QString &filename,
633 const QString &prefix,
634 const QString &directory,
635 const QString &suffix)
636{
637 qCDebug(lcTranslator).noquote().nospace() << "Searching translation for "
638 << filename << prefix << languages << suffix
639 << " in " << directory;
640 QString path;
641 if (QFileInfo(filename).isRelative()) {
642 path = directory;
643 if (!path.isEmpty() && !path.endsWith(u'/'))
644 path += u'/';
645 }
646 const QString suffixOrDotQM = suffix.isNull() ? dotQmLiteral() : suffix;
647
648 QString realname;
649 realname += path + filename + prefix; // using += in the hope for some reserve capacity
650 const qsizetype realNameBaseSize = realname.size();
651
652 // see http://www.unicode.org/reports/tr35/#LanguageMatching for inspiration
653
654 // For each name returned by locale.uiLanguages(), also try a lowercase
655 // version. Since these languages are used to create file names, this is
656 // important on case-sensitive file systems, where otherwise a file called
657 // something like "prefix_en_us.qm" won't be found under the "en_US"
658 // locale. Note that the Qt resource system is always case-sensitive, even
659 // on Windows (in other words: this codepath is *not* UNIX-only).
660
661 auto loadFile = [this, &realname, &directory] { return do_load(realname, directory); };
662
663 for (const QString &localeName : languages) {
664 QString loc = localeName;
665 // First try this given name, then in lower-case form (if different):
666 while (true) {
667 // First, try with suffix:
668 realname += loc + suffixOrDotQM;
669 if (loadFile())
670 return true;
671
672 // Next, try without:
673 realname.truncate(realNameBaseSize + loc.size());
674 if (loadFile())
675 return true;
676 // Reset realname:
677 realname.truncate(realNameBaseSize);
678
679 // Non-trivial while-loop condition:
680 if (loc != localeName) // loc was the lower-case form, we're done.
681 break;
682 loc = std::move(loc).toLower(); // Try lower-case next,
683 if (loc == localeName) // but only if different.
684 break;
685 }
686 }
687
688 const qsizetype realNameBaseSizeFallbacks = path.size() + filename.size();
689
690 // realname == path + filename + prefix;
691 if (!suffix.isNull()) {
692 realname.replace(realNameBaseSizeFallbacks, prefix.size(), suffix);
693 // realname == path + filename;
694 if (loadFile())
695 return true;
696 realname.replace(realNameBaseSizeFallbacks, suffix.size(), prefix);
697 }
698
699 // realname == path + filename + prefix;
700 if (loadFile())
701 return true;
702
703 realname.truncate(realNameBaseSizeFallbacks);
704 // realname == path + filename;
705 return loadFile();
706}
707
708/*!
709 \since 4.8
710
711 Loads \a filename + \a prefix + \l{QLocale::uiLanguages()}{ui language
712 name} + \a suffix (".qm" if the \a suffix is not specified), which may be
713 an absolute file name or relative to \a directory. Returns \c true if the
714 translation is successfully loaded; otherwise returns \c false.
715
716 The previous contents of this translator object are discarded.
717
718 If the file name does not exist, other file names are tried
719 in the following order:
720
721 \list 1
722 \li File name without \a suffix appended.
723 \li File name with ui language part after a "_" character stripped and \a suffix.
724 \li File name with ui language part stripped without \a suffix appended.
725 \li File name with ui language part stripped further, etc.
726 \endlist
727
728 For example, an application running in the \a locale with the following
729 \l{QLocale::uiLanguages()}{ui languages} - "es", "fr-CA", "de" might call
730 load(QLocale(), "foo", ".", "/opt/foolib", ".qm"). load() would
731 replace '-' (dash) with '_' (underscore) in the ui language and then try to
732 open the first existing readable file from this list:
733
734 \list 1
735 \li \c /opt/foolib/foo.es.qm
736 \li \c /opt/foolib/foo.es
737 \li \c /opt/foolib/foo.fr_CA.qm
738 \li \c /opt/foolib/foo.fr_CA
739 \li \c /opt/foolib/foo.fr.qm
740 \li \c /opt/foolib/foo.fr
741 \li \c /opt/foolib/foo.de.qm
742 \li \c /opt/foolib/foo.de
743 \li \c /opt/foolib/foo.qm
744 \li \c /opt/foolib/foo.
745 \li \c /opt/foolib/foo
746 \endlist
747
748 On operating systems where file system is case sensitive, QTranslator also
749 tries to load a lower-cased version of the locale name.
750*/
751bool QTranslator::load(const QLocale & locale,
752 const QString & filename,
753 const QString & prefix,
754 const QString & directory,
755 const QString & suffix)
756{
757 Q_D(QTranslator);
758 const QStringList languages = locale.uiLanguages(QLocale::TagSeparator::Underscore);
759 qCDebug(lcTranslator) << "Requested UI languages" << languages;
760 auto data = std::make_unique<QTranslatorData>();
761 const bool ok = data->load_translation(languages, filename, prefix, directory, suffix);
762 d->replaceData(data);
763 return ok;
764}
765
766/*!
767 \overload load()
768
769 Loads the QM file data \a data of length \a len into the
770 translator.
771
772 The data is not copied. The caller must be able to guarantee that \a data
773 will not be deleted or modified.
774
775 \a directory is only used to specify the base directory when loading the dependencies
776 of a QM file. If the file does not have dependencies, this argument is ignored.
777*/
778bool QTranslator::load(const uchar *data, int len, const QString &directory)
779{
780 Q_D(QTranslator);
781 auto translations = std::make_unique<QTranslatorData>();
782 const bool ok = data && len >= MagicLength && !memcmp(data, magic, MagicLength)
783 && translations->do_load(data, len, directory);
784 d->replaceData(translations);
785 return ok;
786}
787
788static quint8 read8(const uchar *data)
789{
790 return qFromBigEndian<quint8>(data);
791}
792
793static quint16 read16(const uchar *data)
794{
795 return qFromBigEndian<quint16>(data);
796}
797
798static quint32 read32(const uchar *data)
799{
800 return qFromBigEndian<quint32>(data);
801}
802
803bool QTranslatorData::do_load(const uchar *data, qsizetype len, const QString &directory)
804{
805 bool ok = true;
806 const uchar *end = data + len;
807
808 data += MagicLength;
809
810 QStringList dependencies;
811 while (data < end - 5) {
812 quint8 tag = read8(data++);
813 quint32 blockLen = read32(data);
814 data += 4;
815 if (!tag || !blockLen)
816 break;
817 if (quint32(end - data) < blockLen) {
818 ok = false;
819 break;
820 }
821
822 if (tag == QTranslatorData::Language) {
823 language = QString::fromUtf8((const char *)data, blockLen);
824 } else if (tag == QTranslatorData::Contexts) {
825 contextArray = data;
826 contextLength = blockLen;
827 } else if (tag == QTranslatorData::Hashes) {
828 offsetArray = data;
829 offsetLength = blockLen;
830 } else if (tag == QTranslatorData::Messages) {
831 messageArray = data;
832 messageLength = blockLen;
833 } else if (tag == QTranslatorData::NumerusRules) {
834 numerusRulesArray = data;
835 numerusRulesLength = blockLen;
836 } else if (tag == QTranslatorData::Dependencies) {
837 QDataStream stream(QByteArray::fromRawData((const char*)data, blockLen));
838 QString dep;
839 while (!stream.atEnd()) {
840 stream >> dep;
841 dependencies.append(dep);
842 }
843 }
844
845 data += blockLen;
846 }
847
848 if (ok && !isValidNumerusRules(numerusRulesArray, numerusRulesLength))
849 ok = false;
850 if (ok) {
851 subTranslators.reserve(std::size_t(dependencies.size()));
852 for (const QString &dependency : std::as_const(dependencies)) {
853 auto translator = std::make_unique<QTranslator>();
854 ok = translator->load(dependency, directory);
855 if (!ok)
856 break;
857 subTranslators.push_back(std::move(translator));
858 }
859
860 // In case some dependencies fail to load, unload all the other ones too.
861 if (!ok)
862 subTranslators.clear();
863 }
864
865 if (!ok) {
866 messageArray = nullptr;
867 contextArray = nullptr;
868 offsetArray = nullptr;
869 numerusRulesArray = nullptr;
870 messageLength = 0;
871 contextLength = 0;
872 offsetLength = 0;
874 }
875
876 return ok;
877}
878
879static QString getMessage(const uchar *m, const uchar *end, const char *context,
880 const char *sourceText, const char *comment, uint numerus)
881{
882 const uchar *tn = nullptr;
883 uint tn_length = 0;
884 const uint sourceTextLen = uint(strlen(sourceText));
885 const uint contextLen = uint(strlen(context));
886 const uint commentLen = uint(strlen(comment));
887
888 for (;;) {
889 uchar tag = 0;
890 if (m < end)
891 tag = read8(m++);
892 switch ((Tag)tag) {
893 case Tag_End:
894 goto end;
895 case Tag_Translation: {
896 int len = read32(m);
897 if (len & 1)
898 return QString();
899 m += 4;
900 if (!numerus--) {
901 tn_length = len;
902 tn = m;
903 }
904 m += len;
905 break;
906 }
907 case Tag_Obsolete1:
908 m += 4;
909 break;
910 case Tag_SourceText: {
911 quint32 len = read32(m);
912 m += 4;
913 if (!match(m, len, sourceText, sourceTextLen))
914 return QString();
915 m += len;
916 }
917 break;
918 case Tag_Context: {
919 quint32 len = read32(m);
920 m += 4;
921 if (!match(m, len, context, contextLen))
922 return QString();
923 m += len;
924 }
925 break;
926 case Tag_Comment: {
927 quint32 len = read32(m);
928 m += 4;
929 if (*m && !match(m, len, comment, commentLen))
930 return QString();
931 m += len;
932 }
933 break;
934 default:
935 return QString();
936 }
937 }
938end:
939 if (!tn)
940 return QString();
941 QString str(tn_length / 2, Qt::Uninitialized);
942 qFromBigEndian<char16_t>(tn, str.size(), str.data());
943 return str;
944}
945
946QString QTranslatorData::do_translate(const char *context, const char *sourceText,
947 const char *comment, int n) const
948{
949 if (context == nullptr)
950 context = "";
951 if (sourceText == nullptr)
952 sourceText = "";
953 if (comment == nullptr)
954 comment = "";
955
956 uint numerus = 0;
957 size_t numItems = 0;
958
959 if (!offsetLength)
960 goto searchDependencies;
961
962 /*
963 Check if the context belongs to this QTranslator. If many
964 translators are installed, this step is necessary.
965 */
966 if (contextLength) {
967 quint16 hTableSize = read16(contextArray);
968 uint g = elfHash(context) % hTableSize;
969 const uchar *c = contextArray + 2 + (g << 1);
970 quint16 off = read16(c);
971 c += 2;
972 if (off == 0)
973 return QString();
974 c = contextArray + (2 + (hTableSize << 1) + (off << 1));
975
976 const uint contextLen = uint(strlen(context));
977 for (;;) {
978 quint8 len = read8(c++);
979 if (len == 0)
980 return QString();
981 if (match(c, len, context, contextLen))
982 break;
983 c += len;
984 }
985 }
986
987 numItems = offsetLength / (2 * sizeof(quint32));
988 if (!numItems)
989 goto searchDependencies;
990
991 if (n >= 0)
992 numerus = numerusHelper(n, numerusRulesArray, numerusRulesLength);
993
994 for (;;) {
995 quint32 h = 0;
996 elfHash_continue(sourceText, h);
997 elfHash_continue(comment, h);
998 elfHash_finish(h);
999
1000 const uchar *start = offsetArray;
1001 const uchar *end = start + ((numItems - 1) << 3);
1002 while (start <= end) {
1003 const uchar *middle = start + (((end - start) >> 4) << 3);
1004 uint hash = read32(middle);
1005 if (h == hash) {
1006 start = middle;
1007 break;
1008 } else if (hash < h) {
1009 start = middle + 8;
1010 } else {
1011 end = middle - 8;
1012 }
1013 }
1014
1015 if (start <= end) {
1016 // go back on equal key
1017 while (start != offsetArray && read32(start) == read32(start - 8))
1018 start -= 8;
1019
1020 while (start < offsetArray + offsetLength) {
1021 quint32 rh = read32(start);
1022 start += 4;
1023 if (rh != h)
1024 break;
1025 quint32 ro = read32(start);
1026 start += 4;
1027 QString tn = getMessage(messageArray + ro, messageArray + messageLength, context,
1028 sourceText, comment, numerus);
1029 if (!tn.isNull())
1030 return tn;
1031 }
1032 }
1033 if (!comment[0])
1034 break;
1035 comment = "";
1036 }
1037
1038searchDependencies:
1039 for (const auto &translator : subTranslators) {
1040 QString tn = translator->translate(context, sourceText, comment, n);
1041 if (!tn.isNull())
1042 return tn;
1043 }
1044 return QString();
1045}
1046
1047/*
1048 Frees the loaded translations, and resets the data to empty.
1049*/
1050
1052{
1053 if (unmapPointer && unmapLength) {
1054#if defined(QT_USE_MMAP)
1055 if (used_mmap) {
1056 used_mmap = false;
1057 munmap(unmapPointer, unmapLength);
1058 } else
1059#endif
1060 if (!resource)
1061 delete [] unmapPointer;
1062 }
1063
1064 resource = nullptr;
1065 unmapPointer = nullptr;
1066 unmapLength = 0;
1067 messageArray = nullptr;
1068 contextArray = nullptr;
1069 offsetArray = nullptr;
1070 numerusRulesArray = nullptr;
1071 messageLength = 0;
1072 contextLength = 0;
1073 offsetLength = 0;
1075
1076 subTranslators.clear();
1077
1078 language.clear();
1079 filePath.clear();
1080}
1081
1082// Replaces the translations with \a newData, and passes the old ones back in
1083// \a newData. The caller destroys them after the lock is released.
1084void QTranslatorPrivate::replaceData(std::unique_ptr<QTranslatorData> &newData)
1085{
1086 Q_Q(QTranslator);
1087 {
1088 QWriteLocker locker(&lock);
1089 data.swap(newData);
1090 }
1091 if (QCoreApplicationPrivate::isTranslatorInstalled(q))
1092 QCoreApplication::postEvent(QCoreApplication::instance(),
1093 new QEvent(QEvent::LanguageChange));
1094}
1095
1096/*!
1097 \threadsafe
1098
1099 Returns the translation for the key (\a context, \a sourceText,
1100 \a disambiguation). If none is found, also tries (\a context, \a
1101 sourceText, ""). If that still fails, returns a null string.
1102
1103 \note Incomplete translations may result in unexpected behavior:
1104 If no translation for (\a context, \a sourceText, "")
1105 is provided, the method might in this case actually return a
1106 translation for a different \a disambiguation.
1107
1108 If \a n is not -1, it is used to choose an appropriate form for
1109 the translation (e.g. "%n file found" vs. "%n files found").
1110
1111 If you need to programmatically insert translations into a
1112 QTranslator, this function can be reimplemented.
1113
1114 \sa load()
1115*/
1116QString QTranslator::translate(const char *context, const char *sourceText, const char *disambiguation,
1117 int n) const
1118{
1119 Q_D(const QTranslator);
1120 QReadLocker locker(&d->lock);
1121 return d->data->do_translate(context, sourceText, disambiguation, n);
1122}
1123
1124/*!
1125 Returns \c true if this translator is empty, otherwise returns \c false.
1126*/
1127bool QTranslator::isEmpty() const
1128{
1129 Q_D(const QTranslator);
1130 QReadLocker locker(&d->lock);
1131 const QTranslatorData *data = d->data.get();
1132 return !data->messageArray && !data->offsetArray && !data->contextArray
1133 && data->subTranslators.empty();
1134}
1135
1136/*!
1137 \since 5.15
1138
1139 Returns the target language as stored in the translation file.
1140 */
1141QString QTranslator::language() const
1142{
1143 Q_D(const QTranslator);
1144 QReadLocker locker(&d->lock);
1145 return d->data->language;
1146}
1147
1148/*!
1149 \since 5.15
1150
1151 Returns the path of the loaded translation file.
1152
1153 The file path is empty if no translation was loaded yet,
1154 the loading failed, or if the translation was not loaded
1155 from a file.
1156 */
1157QString QTranslator::filePath() const
1158{
1159 Q_D(const QTranslator);
1160 QReadLocker locker(&d->lock);
1161 return d->data->filePath;
1162}
1163
1164QT_END_NAMESPACE
1165
1166#include "moc_qtranslator.cpp"
1167
1168#endif // QT_NO_TRANSLATION
Definition qfile.h:71
\inmodule QtCore
Definition qresource.h:21
const uchar * contextArray
std::vector< std::unique_ptr< QTranslator > > subTranslators
const uchar * offsetArray
const uchar * numerusRulesArray
const uchar * messageArray
bool do_load(const uchar *data, qsizetype len, const QString &directory)
bool do_load(const QString &filename, const QString &directory)
bool load_translation(const QStringList &languages, const QString &filename, const QString &prefix, const QString &directory, const QString &suffix)
std::unique_ptr< QResource > resource
QString do_translate(const char *context, const char *sourceText, const char *comment, int n) const
qsizetype unmapLength
void replaceData(std::unique_ptr< QTranslatorData > &newData)
std::unique_ptr< QTranslatorData > data
Combined button and popup list for selecting options.
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
#define QStringLiteral(str)
Definition qstring.h:1859
static const int MagicLength
static QString getMessage(const uchar *m, const uchar *end, const char *context, const char *sourceText, const char *comment, uint numerus)
static QString findTranslationFile(const QString &filename, const QString &directory, const QString &search_delimiters, const QString &suffix)
static quint32 read32(const uchar *data)
static void elfHash_continue(const char *name, uint &h)
static bool isValidNumerusRules(const uchar *rules, uint rulesSize)
static QString dotQmLiteral()
static uint elfHash(const char *name)
static bool match(const uchar *found, uint foundLen, const char *target, uint targetLen)
static uint numerusHelper(int n, const uchar *rules, uint rulesSize)
static quint8 read8(const uchar *data)
static quint16 read16(const uchar *data)
static const uchar magic[MagicLength]
static void elfHash_finish(uint &h)