metaforce/specter/lib/Translator.cpp

70 lines
2.0 KiB
C++
Raw Normal View History

2016-03-04 23:03:47 +00:00
#include "specter/Translator.hpp"
#include "logvisor/logvisor.hpp"
2016-03-04 23:03:47 +00:00
namespace specter
{
2016-03-04 23:03:47 +00:00
static logvisor::Module Log("specter::Translator");
Locale::Locale(const std::string& name, const std::string& fullName,
const unsigned char* yamlSource, size_t yamlLength)
: m_name(name), m_fullName(fullName)
{
2016-03-04 23:03:47 +00:00
athena::io::YAMLDocReader reader;
2016-01-04 23:58:38 +00:00
yaml_parser_set_input_string(reader.getParser(), yamlSource, yamlLength);
2016-08-22 03:47:34 +00:00
reader.parse(nullptr);
m_rootNode = std::move(reader.releaseRootNode());
if (m_rootNode)
{
m_langNode = m_rootNode->findMapChild(name.c_str());
if (!m_langNode)
2016-03-04 23:03:47 +00:00
Log.report(logvisor::Fatal, "no root node '%s' found in locale", name.c_str());
}
else
2016-03-04 23:03:47 +00:00
Log.report(logvisor::Warning, "locale empty");
}
void Translator::setLocale(const Locale* targetLocale)
{
if (!targetLocale)
2016-03-04 23:03:47 +00:00
Log.report(logvisor::Fatal, "null locale");
m_targetLocale = targetLocale;
}
2016-03-04 23:03:47 +00:00
static const std::string* RecursiveLookup(const athena::io::YAMLNode* node,
std::string::const_iterator start,
std::string::const_iterator end)
{
for (std::string::const_iterator it = start ; it != end ; ++it)
{
if (*it == '/')
{
2016-03-04 23:03:47 +00:00
const athena::io::YAMLNode* ch = node->findMapChild(std::string(start, it).c_str());
if (!ch)
return nullptr;
return RecursiveLookup(ch, it+1, end);
}
}
2016-03-04 23:03:47 +00:00
const athena::io::YAMLNode* ch = node->findMapChild(std::string(start, end).c_str());
if (!ch)
return nullptr;
return &ch->m_scalarString;
}
2015-12-31 03:19:03 +00:00
const std::string* Translator::translate(const std::string& key) const
{
if (!m_targetLocale->rootNode())
return nullptr;
return RecursiveLookup(m_targetLocale->rootNode(), key.cbegin(), key.cend());
}
2015-12-31 03:19:03 +00:00
std::string Translator::translateOr(const std::string& key, const char* vor) const
{
const std::string* find = translate(key);
2015-12-31 03:19:03 +00:00
if (find)
return *find;
return vor;
}
}