diff --git a/src/kirigamiplugin.h b/src/kirigamiplugin.h --- a/src/kirigamiplugin.h +++ b/src/kirigamiplugin.h @@ -33,6 +33,7 @@ Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: + void initializeEngine(QQmlEngine *engine, const char *uri) override; void registerTypes(const char *uri) override; #ifdef KIRIGAMI_BUILD_TYPE_STATIC diff --git a/src/kirigamiplugin.cpp b/src/kirigamiplugin.cpp --- a/src/kirigamiplugin.cpp +++ b/src/kirigamiplugin.cpp @@ -31,12 +31,17 @@ #include "scenepositionattached.h" #include "wheelhandler.h" +#include +#include +#include #include #include #include #include #include #include +#include +#include #include "libkirigami/platformtheme.h" @@ -77,6 +82,64 @@ #endif } +bool loadTranslation(const QString &localeDirName) +{ + QString subPath = QStringLiteral("locale/") + localeDirName + QStringLiteral("/LC_MESSAGES/libkirigami2plugin_qt.qm"); + +#if defined(Q_OS_ANDROID) + const QString fullPath = QDir::homePath() + QStringLiteral("/../qt-reserved-files/share/") + subPath; + if (!QFile::exists(fullPath)) { + return false; + } +#else + const QString fullPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, subPath); + if (fullPath.isEmpty()) { + return false; + } +#endif + QTranslator *translator = new QTranslator(QCoreApplication::instance()); + if (!translator->load(fullPath)) { + delete translator; + return false; + } + QCoreApplication::instance()->installTranslator(translator); + return true; +} + +void loadTranslations() +{ + // The way Qt translation system handles plural forms makes it necessary to + // have a translation file which contains only plural forms for `en`. That's + // why we load the `en` translation unconditionally, then load the + // translation for the current locale to overload it. + loadTranslation(QStringLiteral("en")); + + QLocale locale = QLocale::system(); + if (locale.name() != QStringLiteral("en")) { + if (!loadTranslation(locale.name())) { + if (!loadTranslation(locale.bcp47Name())) { + const int i = locale.name().indexOf(QLatin1Char('_')); + if (i > 0) { + loadTranslation(locale.name().left(i)); + } + } + } + } +} + +void KirigamiPlugin::initializeEngine(QQmlEngine *engine, const char *uri) +{ + Q_UNUSED(engine) + Q_ASSERT(QLatin1String(uri) == QLatin1String("org.kde.kirigami")); + + static bool translationsLoaded = false; + if (!translationsLoaded) { + translationsLoaded = true; + + loadTranslations(); + } +} + void KirigamiPlugin::registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("org.kde.kirigami"));