1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2025-01-07 12:54:00 +00:00
OpenMW/components/lua/l10n.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

71 lines
2.5 KiB
C++
Raw Normal View History

2022-04-10 07:57:02 +00:00
#include "l10n.hpp"
#include <components/debug/debuglog.hpp>
2022-10-02 20:38:37 +00:00
#include <components/l10n/manager.hpp>
2022-04-10 07:57:02 +00:00
2022-10-02 20:38:37 +00:00
namespace
2022-04-10 07:57:02 +00:00
{
2022-10-02 20:38:37 +00:00
struct L10nContext
2022-04-10 07:57:02 +00:00
{
2022-10-02 20:38:37 +00:00
std::shared_ptr<const l10n::MessageBundles> mData;
2022-04-10 07:57:02 +00:00
};
2022-10-02 20:38:37 +00:00
void getICUArgs(std::string_view messageId, const sol::table& table, std::vector<icu::UnicodeString>& argNames,
std::vector<icu::Formattable>& args)
2022-04-10 07:57:02 +00:00
{
for (auto& [key, value] : table)
{
// Argument values
if (value.is<std::string>())
args.push_back(icu::Formattable(value.as<std::string>().c_str()));
// Note: While we pass all numbers as doubles, they still seem to be handled appropriately.
// Numbers can be forced to be integers using the argType number and argStyle integer
// E.g. {var, number, integer}
else if (value.is<double>())
args.push_back(icu::Formattable(value.as<double>()));
else
{
Log(Debug::Error) << "Unrecognized argument type for key \"" << key.as<std::string>()
<< "\" when formatting message \"" << messageId << "\"";
}
// Argument names
const auto str = key.as<std::string>();
argNames.push_back(icu::UnicodeString::fromUTF8(icu::StringPiece(str.data(), str.size())));
2022-04-10 07:57:02 +00:00
}
}
2022-10-02 20:38:37 +00:00
}
2022-04-10 07:57:02 +00:00
2022-10-02 20:38:37 +00:00
namespace sol
{
template <>
struct is_automagical<L10nContext> : std::false_type
2022-04-10 07:57:02 +00:00
{
2022-10-02 20:38:37 +00:00
};
}
2022-04-10 07:57:02 +00:00
2022-10-02 20:38:37 +00:00
namespace LuaUtil
{
sol::function initL10nLoader(lua_State* L, l10n::Manager* manager)
2022-04-10 07:57:02 +00:00
{
sol::state_view lua(L);
2022-10-02 20:38:37 +00:00
sol::usertype<L10nContext> ctxDef = lua.new_usertype<L10nContext>("L10nContext");
ctxDef[sol::meta_function::call]
= [](const L10nContext& ctx, std::string_view key, sol::optional<sol::table> args) {
std::vector<icu::Formattable> argValues;
std::vector<icu::UnicodeString> argNames;
if (args)
getICUArgs(key, *args, argNames, argValues);
return ctx.mData->formatMessage(key, argNames, argValues);
};
return sol::make_object(
lua, [manager](const std::string& contextName, sol::optional<std::string> fallbackLocale) {
if (fallbackLocale)
return L10nContext{ manager->getContext(contextName, *fallbackLocale) };
else
return L10nContext{ manager->getContext(contextName) };
});
2022-04-10 07:57:02 +00:00
}
}