64 lines
2.1 KiB
C++
64 lines
2.1 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_table;
|
|
|
|
// 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) {
|
|
auto key = it.key().get_value<std::string>();
|
|
std::string full = prefix;
|
|
if (!full.empty()) {
|
|
full += ".";
|
|
}
|
|
full += key;
|
|
traverse(it.value(), full);
|
|
}
|
|
} else if (node.is_scalar()) {
|
|
try {
|
|
strings_table[prefix] = node.get_value<std::string>();
|
|
} catch (...) {
|
|
// @INTENTIONAL: si el valor no és string vàlid, l'ignorem i continuem.
|
|
}
|
|
}
|
|
}
|
|
|
|
auto load(const char* filename) -> bool {
|
|
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_table.clear();
|
|
traverse(yaml, "");
|
|
std::cout << "Locale loaded: " << strings_table.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_table.find(key);
|
|
if (it != strings_table.end()) {
|
|
return it->second.c_str();
|
|
}
|
|
return key; // fallback: retorna la clau mateixa
|
|
}
|
|
|
|
} // namespace Locale
|