0
0
Fork 0
mirror of https://github.com/bitcoin/bitcoin.git synced 2025-02-11 11:16:09 -05:00
bitcoin-bitcoin-core/src/util/translation.h

80 lines
2.1 KiB
C
Raw Normal View History

// Copyright (c) 2019-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UTIL_TRANSLATION_H
#define BITCOIN_UTIL_TRANSLATION_H
2019-06-28 11:49:40 +03:00
#include <tinyformat.h>
#include <functional>
#include <string>
2019-06-28 11:49:40 +03:00
/**
* Bilingual messages:
* - in GUI: user's native language + untranslated (i.e. English)
* - in log and stderr: untranslated only
*/
struct bilingual_str {
std::string original;
std::string translated;
2020-05-09 14:43:00 +03:00
bilingual_str& operator+=(const bilingual_str& rhs)
{
original += rhs.original;
translated += rhs.translated;
return *this;
}
bool empty() const
{
return original.empty();
}
2021-06-23 16:34:36 -04:00
void clear()
{
original.clear();
translated.clear();
}
2019-06-28 11:49:40 +03:00
};
2020-05-09 14:43:00 +03:00
inline bilingual_str operator+(bilingual_str lhs, const bilingual_str& rhs)
{
2020-05-09 14:43:00 +03:00
lhs += rhs;
return lhs;
}
/** Mark a bilingual_str as untranslated */
2020-05-05 04:51:29 +03:00
inline bilingual_str Untranslated(std::string original) { return {original, original}; }
// Provide an overload of tinyformat::format which can take bilingual_str arguments.
2019-06-28 11:49:40 +03:00
namespace tinyformat {
template <typename... Args>
bilingual_str format(const bilingual_str& fmt, const Args&... args)
{
const auto translate_arg{[](const auto& arg, bool translated) -> const auto& {
if constexpr (std::is_same_v<decltype(arg), const bilingual_str&>) {
return translated ? arg.translated : arg.original;
} else {
return arg;
}
}};
return bilingual_str{tfm::format(fmt.original, translate_arg(args, false)...),
tfm::format(fmt.translated, translate_arg(args, true)...)};
2019-06-28 11:49:40 +03:00
}
} // namespace tinyformat
/** Translate a message to the native language of the user. */
const extern std::function<std::string(const char*)> G_TRANSLATION_FUN;
/**
* Translation function.
* If no translation function is set, simply return the input.
*/
inline bilingual_str _(const char* psz)
{
return bilingual_str{psz, G_TRANSLATION_FUN ? (G_TRANSLATION_FUN)(psz) : psz};
}
#endif // BITCOIN_UTIL_TRANSLATION_H