50 lines
1.3 KiB
C++
50 lines
1.3 KiB
C++
#include "localization.h"
|
|
#include "yamlparser.h"
|
|
#include <QDebug>
|
|
|
|
Localization& Localization::instance()
|
|
{
|
|
static Localization s_instance;
|
|
return s_instance;
|
|
}
|
|
|
|
Localization::Localization()
|
|
: m_loaded(false)
|
|
{
|
|
}
|
|
|
|
void Localization::flattenNode(const YamlNode &node, const QString &prefix)
|
|
{
|
|
if (!node.value.isEmpty()) {
|
|
m_strings[prefix] = node.value;
|
|
}
|
|
for (auto it = node.children.begin(); it != node.children.end(); ++it) {
|
|
QString nextPrefix = prefix.isEmpty() ? it.key() : (prefix + "." + it.key());
|
|
flattenNode(it.value(), nextPrefix);
|
|
}
|
|
}
|
|
|
|
bool Localization::loadFile(const QString &filePath)
|
|
{
|
|
YamlNode root = YamlParser::parseFile(filePath);
|
|
if (root.children.isEmpty() && root.value.isEmpty()) {
|
|
qWarning() << "Failed to parse localization file:" << filePath;
|
|
return false;
|
|
}
|
|
|
|
m_strings.clear();
|
|
flattenNode(root, "");
|
|
m_loaded = true;
|
|
qDebug() << "Localization loaded" << m_strings.size() << "keys from" << filePath;
|
|
return true;
|
|
}
|
|
|
|
QString Localization::get(const QString &key, const QString &defaultVal) const
|
|
{
|
|
auto it = m_strings.find(key);
|
|
if (it != m_strings.end()) {
|
|
return it.value();
|
|
}
|
|
return defaultVal.isEmpty() ? key : defaultVal;
|
|
}
|