Files
aee/source/core/locale/locale.cpp
2026-04-16 16:21:44 +02:00

56 lines
1.8 KiB
C++

#include "core/locale/locale.hpp"
#include <iostream>
#include <string>
#include <unordered_map>
#include "core/resources/resource_helper.hpp"
#include "external/fkyaml_node.hpp"
namespace Locale {
static std::unordered_map<std::string, std::string> strings_;
// Aplana un node YAML en claus amb notació punt
static void traverse(const fkyaml::node& node, const std::string& prefix) {
if (node.is_mapping()) {
for (auto it = node.begin(); it != node.end(); ++it) {
std::string key = it.key().get_value<std::string>();
std::string full = prefix.empty() ? key : prefix + "." + key;
traverse(it.value(), full);
}
} else if (node.is_scalar()) {
try {
strings_[prefix] = node.get_value<std::string>();
} catch (...) {}
}
}
bool load(const char* filename) {
auto buffer = ResourceHelper::loadFile(filename);
if (buffer.empty()) {
std::cerr << "Locale: unable to load " << filename << '\n';
return false;
}
std::string content(reinterpret_cast<const char*>(buffer.data()), buffer.size());
try {
auto yaml = fkyaml::node::deserialize(content);
strings_.clear();
traverse(yaml, "");
std::cout << "Locale loaded: " << strings_.size() << " string(s) from " << filename << '\n';
return true;
} catch (const fkyaml::exception& e) {
std::cerr << "Locale: error parsing " << filename << ": " << e.what() << '\n';
return false;
}
}
auto get(const char* key) -> const char* {
auto it = strings_.find(key);
if (it != strings_.end()) return it->second.c_str();
return key; // fallback: retorna la clau mateixa
}
} // namespace Locale