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");
2017-11-13 06:14:52 +00:00
Locale::Locale(std::string_view name, std::string_view 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 = reader.releaseRootNode();
if (m_rootNode)
{
2017-11-13 06:14:52 +00:00
m_langNode = m_rootNode->findMapChild(name.data());
if (!m_langNode)
2017-11-13 06:14:52 +00:00
Log.report(logvisor::Fatal, "no root node '%s' found in locale", name.data());
}
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;
}
2017-11-13 06:14:52 +00:00
static std::string_view RecursiveLookup(const athena::io::YAMLNode* node,
std::string_view::const_iterator start,
std::string_view::const_iterator end)
{
2017-11-13 06:14:52 +00:00
for (std::string_view::const_iterator it = start ; it != end ; ++it)
{
if (*it == '/')
{
2017-11-13 06:14:52 +00:00
const athena::io::YAMLNode* ch = node->findMapChild(std::string(start, it));
if (!ch)
return nullptr;
return RecursiveLookup(ch, it+1, end);
}
}
2017-11-13 06:14:52 +00:00
const athena::io::YAMLNode* ch = node->findMapChild(std::string(start, end));
if (!ch)
2017-11-13 06:14:52 +00:00
return {};
return ch->m_scalarString;
}
2017-11-13 06:14:52 +00:00
std::string_view Translator::translate(std::string_view key) const
{
if (!m_targetLocale->rootNode())
return nullptr;
return RecursiveLookup(m_targetLocale->rootNode(), key.cbegin(), key.cend());
}
2017-11-13 06:14:52 +00:00
std::string_view Translator::translateOr(std::string_view key, std::string_view vor) const
2015-12-31 03:19:03 +00:00
{
2017-11-13 06:14:52 +00:00
std::string_view find = translate(key);
if (!find.empty())
return find;
2015-12-31 03:19:03 +00:00
return vor;
}
}