Files
FWS-PacManage/preferences/language-manager.cpp
BlackAngelTV 9c30268810 refactor(tree): move the journal and the preferences out of src/ and include/
The journal and the preferences were two of the many things src/ held, so
"where does this live" meant reading the file to find out. They now have a
folder each — logging/ and preferences/ — with the header next to its
source, the way pages/ has always been laid out.

Flat #include still resolves: the folders join the include path.
2026-09-29 21:24:27 +02:00

234 lines
8.2 KiB
C++

#include "language-manager.h"
#include "app-settings.h"
#include <QCoreApplication>
#include <QDir>
#include <QEvent>
#include <QFile>
#include <QHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLocale>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QTranslator>
#ifdef PACMANAGER_HAS_WIDGETS
#include <QApplication>
#include <QWidget>
#endif
namespace {
// Kept alive for the whole process: a QTranslator that is destroyed takes the
// installed translation with it.
QTranslator* g_translator = nullptr;
QString catalogueFileName(const QString& code) {
return code + QStringLiteral(".json");
}
// The catalogue compiled into the binary, so the languages the application
// ships with work wherever it is installed from.
QString builtinCatalogueFileName(const QString& code) {
return QStringLiteral(":/translations/") + catalogueFileName(code);
}
QString qmCatalogueFileName(const QString& code) {
return QStringLiteral("pacmanager_%1.qm").arg(code);
}
// A catalogue read as it is: no compilation step, so a new language is one text
// file. Qt only ever asks translate() for a (context, source) pair; both the
// bare source and the "context::source" form are looked up, the second first,
// so a catalogue can disambiguate a string two classes share.
class JsonTranslator : public QTranslator {
public:
bool load(const QString& fileName) {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) return false;
QJsonParseError error{};
const QJsonDocument document =
QJsonDocument::fromJson(file.readAll(), &error);
if (error.error != QJsonParseError::NoError || !document.isObject()) {
return false;
}
const QJsonObject root = document.object();
for (auto it = root.constBegin(); it != root.constEnd(); ++it) {
if (it.value().isString()) m_entries.insert(it.key(), it.value().toString());
}
return !m_entries.isEmpty();
}
QString translate(const char* context, const char* sourceText,
const char* disambiguation, int n) const override {
Q_UNUSED(disambiguation)
Q_UNUSED(n)
if (!sourceText) return QString();
const QString source = QString::fromUtf8(sourceText);
if (context) {
const QString qualified =
QString::fromUtf8(context) + QLatin1String("::") + source;
const auto it = m_entries.constFind(qualified);
if (it != m_entries.constEnd()) return it.value();
}
const auto it = m_entries.constFind(source);
return it != m_entries.constEnd() ? it.value() : QString();
}
private:
QHash<QString, QString> m_entries;
};
// First non-empty value of an environment variable.
QString envLocale(const char* name) {
const QByteArray value = qgetenv(name);
return value.isEmpty() ? QString() : QString::fromUtf8(value).trimmed();
}
// What an FWS install leaves behind: archinstall and friends write the chosen
// locale to /etc/locale.conf as LANG=fr_FR.UTF-8, which a session started
// before the change (or a bare .desktop launch) may not export.
QString localeConfLanguage() {
QFile file(QStringLiteral("/etc/locale.conf"));
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return QString();
static const QRegularExpression assignment(
QStringLiteral("^\\s*LANG\\s*=\\s*\"?([^\"\\s]+)"), QRegularExpression::MultilineOption);
const QString content = QString::fromUtf8(file.readAll());
return assignment.match(content).captured(1);
}
} // namespace
QStringList LanguageManager::searchPaths() {
QStringList paths;
// Next to the settings the user just chose: where a catalogue installed by
// hand belongs.
paths << AppSettings::instance().logDirectory() + QStringLiteral("/translations");
const QString data = QStandardPaths::writableLocation(
QStandardPaths::AppDataLocation);
if (!data.isEmpty()) paths << data + QStringLiteral("/translations");
// Running from a build tree, the catalogues sit beside the binary.
paths << QCoreApplication::applicationDirPath() + QStringLiteral("/translations");
QStringList existing;
for (const QString& path : paths) {
if (QDir(path).exists()) existing << path;
}
return existing;
}
QString LanguageManager::systemLanguage() {
// LC_ALL overrides everything, then LC_MESSAGES for messages alone, then
// LANG. @modifier suffixes (LANG=fr_FR.UTF-8@euro) are dropped.
for (const char* name : {"LC_ALL", "LC_MESSAGES", "LANG"}) {
QString value = envLocale(name);
const int at = value.indexOf(QLatin1Char('@'));
if (at >= 0) value.truncate(at);
if (!value.isEmpty()) return value;
}
const QString fromFile = localeConfLanguage();
if (!fromFile.isEmpty()) return fromFile;
return QLocale::system().name();
}
QString LanguageManager::resolve(const QString& code) {
const QString wanted = AppSettings::sanitizeLanguage(code);
if (wanted != QLatin1String("system")) return wanted;
// "system" follows what the system asks for, but only into a language the
// app knows: a desktop set to Esperanto should leave the interface in its
// own language rather than install nothing at all.
const QString locale = systemLanguage().left(2).toLower();
if (AppSettings::knownLanguages().contains(locale)) return locale;
return QStringLiteral("fr");
}
bool LanguageManager::isTranslationAvailable(const QString& code) {
const QString resolved = resolve(code);
if (QFile::exists(builtinCatalogueFileName(resolved))) return true;
for (const QString& path : searchPaths()) {
const QString in = path + QLatin1Char('/') + catalogueFileName(resolved);
const QString qm = path + QLatin1Char('/') + qmCatalogueFileName(resolved);
if (QFile::exists(in) || QFile::exists(qm)) return true;
}
return false;
}
QString LanguageManager::searchPathHint() {
return searchPaths().isEmpty() ? QString() : searchPaths().first();
}
QString LanguageManager::activeCode() {
return g_translator ? g_translator->language() : QString();
}
bool LanguageManager::apply(const QString& code) {
const QString resolved = resolve(code);
// The previous catalogue goes first, so a language the user just left does
// not keep translating part of the interface.
if (g_translator) {
QCoreApplication::removeTranslator(g_translator);
delete g_translator;
g_translator = nullptr;
}
bool installed = false;
// A user-installed catalogue wins over the one compiled in: that is what
// "drop a file in translations/" is for.
for (const QString& path : searchPaths()) {
// A .qm compiled from a .ts wins when one is there: Qt Linguist is the
// better tool when a translator has one, and it is still supported.
QTranslator* candidate = new QTranslator();
if (candidate->load(qmCatalogueFileName(resolved), path)) {
g_translator = candidate;
installed = true;
break;
}
delete candidate;
JsonTranslator* json = new JsonTranslator();
if (json->load(path + QLatin1Char('/') + catalogueFileName(resolved))) {
g_translator = json;
installed = true;
break;
}
delete json;
}
if (!installed) {
JsonTranslator* builtin = new JsonTranslator();
if (builtin->load(builtinCatalogueFileName(resolved))) {
g_translator = builtin;
installed = true;
} else {
delete builtin;
}
}
if (g_translator) QCoreApplication::installTranslator(g_translator);
// No catalogue: the widgets still get the event, so switching back to an
// untranslated language restores the original wording instead of leaving
// the previous translation in place. QApplication is only reached when the
// Widgets module is in: LanguageManager is also used headless, by the tests.
#ifdef PACMANAGER_HAS_WIDGETS
const QWidgetList widgets = QApplication::allWidgets();
for (QWidget* widget : widgets) {
QEvent event(QEvent::LanguageChange);
QCoreApplication::sendEvent(widget, &event);
}
#endif
return installed;
}