58 lines
1.8 KiB
C++
58 lines
1.8 KiB
C++
#include "core/locale/locale.hpp"
|
|
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <string>
|
|
|
|
#include "external/fkyaml_node.hpp"
|
|
|
|
namespace {
|
|
|
|
// Recorre el node YAML i aplana jerarquies en claus "a.b.c". Claus no
|
|
// cadena (p.ex. llistes o nombres solts) es ignoren silenciosament —
|
|
// només textos útils per traduir acaben al mapping.
|
|
void flatten(const fkyaml::node& node, const std::string& prefix, std::unordered_map<std::string, std::string>& out) {
|
|
for (auto it = node.begin(); it != node.end(); ++it) {
|
|
const std::string KEY = prefix.empty()
|
|
? it.key().get_value<std::string>()
|
|
: prefix + "." + it.key().get_value<std::string>();
|
|
const auto& value = it.value();
|
|
if (value.is_mapping()) {
|
|
flatten(value, KEY, out);
|
|
} else if (value.is_string()) {
|
|
out[KEY] = value.get_value<std::string>();
|
|
}
|
|
}
|
|
}
|
|
|
|
} // namespace
|
|
|
|
auto Locale::get() -> Locale& {
|
|
static Locale instance_;
|
|
return instance_;
|
|
}
|
|
|
|
void Locale::load(const std::string& file_path) {
|
|
std::ifstream file(file_path);
|
|
if (!file.is_open()) {
|
|
std::cerr << "Locale: no s'ha pogut obrir " << file_path << '\n';
|
|
return;
|
|
}
|
|
|
|
try {
|
|
auto yaml = fkyaml::node::deserialize(file);
|
|
strings_.clear();
|
|
flatten(yaml, "", strings_);
|
|
std::cout << "Locale: " << strings_.size() << " traduccions des de " << file_path << '\n';
|
|
} catch (const std::exception& e) {
|
|
std::cerr << "Locale: error parsejant " << file_path << ": " << e.what() << '\n';
|
|
}
|
|
}
|
|
|
|
auto Locale::text(const std::string& key) const -> std::string {
|
|
auto it = strings_.find(key);
|
|
if (it != strings_.end()) { return it->second; }
|
|
std::cerr << "Locale: clau no trobada: " << key << '\n';
|
|
return key;
|
|
}
|