QuasarAppLib/locales.cpp

86 lines
2.1 KiB
C++
Raw Normal View History

2018-09-29 15:56:04 +03:00
/*
2021-01-05 13:04:05 +03:00
* Copyright (C) 2018-2021 QuasarApp.
2018-09-29 15:56:04 +03:00
* Distributed under the lgplv3 software license, see the accompanying
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
#include "locales.h"
#include <QCoreApplication>
#include <QTranslator>
#include <QLocale>
2021-02-12 12:39:46 +03:00
#include <QLibraryInfo>
#include <QDir>
#include <QRegularExpression>
2021-02-20 12:42:34 +03:00
#include <QLibraryInfo>
2020-05-15 01:43:32 +03:00
#include "params.h"
2018-09-29 15:56:04 +03:00
using namespace QuasarAppUtils;
2021-02-12 12:39:46 +03:00
bool Locales::setLocalePrivate(const QLocale &locale) {
2021-02-15 13:17:28 +03:00
removeOldTranslation();
QFileInfoList qmFiles;
2021-02-12 12:39:46 +03:00
2021-02-15 13:17:28 +03:00
for (const auto &location: qAsConst(_locations)) {
qmFiles += QDir(location).entryInfoList({"*" + locale.bcp47Name() + "*.qm"}, QDir::Files);
}
for (const auto & file: qAsConst(qmFiles)) {
auto translator = new QTranslator();
2021-02-12 12:39:46 +03:00
2021-02-15 13:17:28 +03:00
if(!(translator->load(file.absoluteFilePath()) && QCoreApplication::installTranslator(translator))) {
delete translator;
continue;
2021-02-12 12:39:46 +03:00
}
2021-02-15 13:17:28 +03:00
_translations.push_back(translator);
}
2021-02-12 12:39:46 +03:00
emit sigTranslationChanged();
2021-02-15 13:17:28 +03:00
return _translations.size();
2021-02-12 12:39:46 +03:00
}
bool Locales::setLocale(const QLocale &locale) {
2020-05-16 15:46:41 +03:00
auto obj = instance();
2021-02-12 12:39:46 +03:00
return obj->setLocalePrivate(locale);
2020-05-15 01:43:32 +03:00
}
2021-02-15 13:17:28 +03:00
bool Locales::init(const QLocale &locale, const QSet<QString> & location) {
2021-02-12 13:28:47 +03:00
auto obj = instance();
return obj->initPrivate(locale, location);
}
2021-02-15 13:17:28 +03:00
bool Locales::initPrivate(const QLocale &locale, const QSet<QString> & locations) {
2020-05-15 01:43:32 +03:00
2021-02-20 12:42:34 +03:00
#if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0)
auto defaultTr = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#else
auto defaultTr = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
#endif
2021-02-15 13:17:28 +03:00
_locations = locations;
if (!_locations.contains(defaultTr)) {
_locations += defaultTr;
2018-09-29 15:56:04 +03:00
}
2021-02-15 13:17:28 +03:00
return setLocalePrivate(locale);
2020-05-15 01:43:32 +03:00
}
2020-05-16 15:46:41 +03:00
Locales *Locales::instance() {
static auto instance = new Locales();
return instance;
}
2021-02-15 13:17:28 +03:00
void Locales::removeOldTranslation() {
for (const auto & tr :qAsConst(_translations)) {
QCoreApplication::removeTranslator(tr);
delete tr;
}
}
Locales::~Locales() {
removeOldTranslation();
2018-09-29 15:56:04 +03:00
}