utilities
Loading...
Searching...
No Matches
gQtTranslation.cc
Go to the documentation of this file.
1#include "gQtTranslation.h"
2
3#include <gemc/glogging/gmessageCatalog.h>
4#include <QLibraryInfo>
5#include <QLocale>
6#include <QTranslator>
7#include <QVariant>
8
9#include <vector>
10
11// Q_INIT_RESOURCE must resolve the generated resource symbol in the global namespace.
12static void initializeGuiResources() { Q_INIT_RESOURCE(gemc_gui_translations); }
13
14void gemc::installGuiTranslations(QCoreApplication& application, const GOptions* options) {
15 initializeGuiResources();
16 const auto language = GMessageCatalog::load(options)->language();
17 if (auto* previous = application.findChild<QObject*>("gemcGuiTranslators", Qt::FindDirectChildrenOnly)) {
18 delete previous; // QTranslator unregisters itself when destroyed.
19 }
20 auto* owner = new QObject(&application);
21 owner->setObjectName("gemcGuiTranslators");
22 application.setProperty("gemcGuiLanguage", QString::fromStdString(language));
23 if (language == "en" || language.starts_with("en-")) return;
24
25 auto* standard = new QTranslator(owner);
26 const auto locale = QLocale(QString::fromStdString(language).replace('-', '_'));
27 if (standard->load(locale, "qtbase", "_", QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
28 application.installTranslator(standard);
29 }
30
31 const auto separator = language.find('-');
32 const auto base = language.substr(0, separator);
33 auto* embedded = new QTranslator(owner);
34 if (embedded->load(QString::fromStdString(":/gemc/gui/" + base + ".qm"))) {
35 application.installTranslator(embedded);
36 }
37
38 std::vector<std::string> variants{base};
39 if (base != language) variants.push_back(language);
40 const auto directories = GMessageCatalog::searchDirectories(options);
41 for (const auto& variant : variants) {
42 // Install low-priority files first: Qt checks the most recently installed translator first.
43 for (auto directory = directories.rbegin(); directory != directories.rend(); ++directory) {
44 for (const auto& path : {*directory / "gui" / (variant + ".qm"), *directory / (variant + ".qm")}) {
45 std::error_code error;
46 if (!std::filesystem::is_regular_file(path, error)) continue;
47 auto* translator = new QTranslator(owner);
48 if (translator->load(QString::fromStdString(path.string()))) {
49 application.installTranslator(translator);
50 } else {
51 qWarning("Ignoring invalid GUI translation catalog: %s", path.string().c_str());
52 delete translator;
53 }
54 }
55 }
56 }
57}
static std::shared_ptr< const GMessageCatalog > load(const GOptions *options=nullptr)
static std::vector< std::filesystem::path > searchDirectories(const GOptions *options=nullptr)
void installGuiTranslations(QCoreApplication &application, const GOptions *options=nullptr)
Install GUI translations before constructing widgets, using the same language as GLogger.