Page MenuHomePhorge

l10n-provider.cpp
No OneTemporary

Size
2 KB
Referenced Files
None
Subscribers
None

l10n-provider.cpp

/*
* This file is part of kazv.
* SPDX-FileCopyrightText: 2021-2024 tusooa <tusooa@kazv.moe>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <kazv-defs.hpp>
#include "l10n-provider.hpp"
#include <optional>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringBuilder>
#include <QDir>
#include <stdexcept>
#include "kazv-path-config.hpp"
using namespace Qt::Literals::StringLiterals;
static QString l10nConfigFile()
{
return u":/l10n/config.json"_s;
}
static QString dirForLocale(QString locale)
{
return u":/l10n/"_s + locale;
}
static QString readWholeFile(QString path)
{
QFile f(path);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw std::runtime_error("Cannot open " + path.toStdString() + " for reading.");
}
QTextStream stream(&f);
stream.setEncoding(QStringConverter::Utf8);
return stream.readAll();
}
struct L10nProviderPrivate
{
std::optional<QJsonObject> cachedLocaleToNameMap;
QMap<QString, QString> cachedFtlData;
void cacheAvailableLocales();
void cacheFtlDataFor(QString locale);
};
void L10nProviderPrivate::cacheAvailableLocales()
{
if (cachedLocaleToNameMap.has_value()) {
return;
} else {
auto fn = l10nConfigFile();
auto content = readWholeFile(fn);
auto j = QJsonDocument::fromJson(content.toUtf8());
auto availableLocales = j[u"availableLocales"_s].toObject();
cachedLocaleToNameMap = std::move(availableLocales);
}
}
void L10nProviderPrivate::cacheFtlDataFor(QString locale)
{
if (cachedFtlData.contains(locale)) {
return;
}
auto dn = dirForLocale(locale);
auto files = QDir(dn).entryInfoList(QStringList{u"*.ftl"_s}, QDir::NoFilter, QDir::Name);
QString s;
const QString newline = u"\n"_s;
for (auto f : files) {
auto fn = f.absoluteFilePath();
s.append(readWholeFile(fn));
s.append(newline);
}
cachedFtlData[locale] = s;
}
L10nProvider::L10nProvider(QObject *parent)
: QObject(parent)
, m_d(new L10nProviderPrivate)
{
}
L10nProvider::~L10nProvider() = default;
QStringList L10nProvider::availableLocaleCodes()
{
m_d->cacheAvailableLocales();
return m_d->cachedLocaleToNameMap.value().keys();
}
QJsonObject L10nProvider::availableLocaleToNameMap()
{
m_d->cacheAvailableLocales();
return m_d->cachedLocaleToNameMap.value();
}
QJsonObject L10nProvider::getFtlData(QStringList desiredLocales)
{
QJsonObject data;
for (auto locale : desiredLocales) {
m_d->cacheFtlDataFor(locale);
data[locale] = m_d->cachedFtlData[locale];
}
return data;
}

File Metadata

Mime Type
text/x-c
Expires
Tue, Nov 26, 2:05 PM (1 d, 10 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
40359
Default Alt Text
l10n-provider.cpp (2 KB)

Event Timeline