add locale class

This commit is contained in:
Vaxry 2025-11-09 14:12:25 +00:00
parent a5b1113633
commit a3f9419f89
Signed by: vaxry
GPG key ID: 665806380871D640
4 changed files with 64 additions and 26 deletions

View file

@ -13,6 +13,22 @@ namespace Hyprutils::I18n {
typedef std::unordered_map<std::string, std::string> translationVarMap;
typedef std::function<std::string(const translationVarMap&)> translationFn;
class CI18nLocale {
public:
~CI18nLocale() = default;
std::string locale();
std::string stem();
std::string full();
private:
CI18nLocale(std::string fullLocale);
std::string m_locale, m_rawFullLocale;
friend class CI18nEngine;
};
class CI18nEngine {
public:
CI18nEngine();
@ -31,7 +47,7 @@ namespace Hyprutils::I18n {
std::string localizeEntry(const std::string& locale, uint64_t key, const translationVarMap& map);
std::string getSystemLocale();
CI18nLocale getSystemLocale();
private:
Memory::CUniquePointer<SI18nEngineImpl> m_impl;

View file

@ -105,28 +105,6 @@ std::string CI18nEngine::localizeEntry(const std::string& locale, uint64_t key,
return rawStr;
}
std::string CI18nEngine::getSystemLocale() {
std::locale locale("");
auto localeStr = locale.name();
// localeStr is very arbitrary... from my testing, it can be:
// en_US.UTF-8
// LC_CTYPE=en_US
// POSIX
// *
//
// We only return e.g. en_US or pl_PL, or pl
if (localeStr == "POSIX")
return "en_US";
if (localeStr == "*")
return "en_US";
if (localeStr.contains('='))
localeStr = localeStr.substr(localeStr.find('=') + 1);
if (localeStr.contains('.'))
localeStr = localeStr.substr(0, localeStr.find('.'));
return localeStr;
CI18nLocale CI18nEngine::getSystemLocale() {
return CI18nLocale(std::locale("").name());
}

44
src/i18n/I18nLocale.cpp Normal file
View file

@ -0,0 +1,44 @@
#include <hyprutils/i18n/I18nEngine.hpp>
using namespace Hyprutils::I18n;
static std::string extractLocale(std::string locale) {
// localeStr is very arbitrary... from my testing, it can be:
// en_US.UTF-8
// LC_CTYPE=en_US
// POSIX
// *
//
// We only return e.g. en_US or pl_PL, or pl
if (locale == "POSIX")
return "en_US";
if (locale == "*")
return "en_US";
if (locale.contains('='))
locale = locale.substr(locale.find('=') + 1);
if (locale.contains('.'))
locale = locale.substr(0, locale.find('.'));
return locale;
}
CI18nLocale::CI18nLocale(std::string fullLocale) : m_rawFullLocale(std::move(fullLocale)) {
m_locale = extractLocale(m_rawFullLocale);
}
std::string CI18nLocale::locale() {
return m_locale;
}
std::string CI18nLocale::stem() {
if (m_locale.contains('_'))
return m_locale.substr(0, m_locale.find('_'));
return m_locale;
}
std::string CI18nLocale::full() {
return m_rawFullLocale;
}

View file

@ -15,7 +15,7 @@ int main(int argc, char** argv, char** envp) {
CI18nEngine engine;
std::println("System locale: {}", engine.getSystemLocale());
std::println("System locale: {}, stem: {}", engine.getSystemLocale().locale(), engine.getSystemLocale().stem());
engine.setFallbackLocale("en_US");