载入中...
搜索中...
未找到
I18n.cpp
浏览该文件的文档.
1#include "i18n/I18n.h"
3
4#include "common/Json.h"
5#include "common/Module.h"
9
10#include <squirrel.h>
11#include <simplesquirrel/simplesquirrel.hpp>
12
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <set>
17#include <sstream>
18#include <unordered_set>
19#include <vector>
20
21namespace eve::i18n {
22
24
25namespace {
26
27bool isPluralCategory(const std::string& key) {
28 static const char* cats[] = {"zero", "one", "two", "few", "many", "other"};
29 for (const char* c : cats)
30 if (key == c) return true;
31 return false;
32}
33
35std::string numberToString(double v) {
36 std::ostringstream os;
37 os << v;
38 return os.str();
39}
40
41bool validIdentifier(const std::string& value) {
42 if (value.empty() || value.size() > 64) return false;
43 for (const unsigned char ch : value)
44 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' ||
45 ch == '_'))
46 return false;
47 return true;
48}
49
50bool collectPlaceholders(const std::string& text, std::set<std::string>& result, std::string& error) {
51 result.clear();
52 for (size_t offset = 0; offset < text.size();) {
53 if (text[offset] == '}') {
54 error = "unmatched closing placeholder brace";
55 return false;
56 }
57 if (text[offset] != '{') {
58 ++offset;
59 continue;
60 }
61 const size_t close = text.find('}', offset + 1);
62 if (close == std::string::npos) {
63 error = "unterminated placeholder";
64 return false;
65 }
66 const std::string name = text.substr(offset + 1, close - offset - 1);
67 if (!validIdentifier(name)) {
68 error = "placeholder names must be stable identifiers";
69 return false;
70 }
71 result.insert(name);
72 offset = close + 1;
73 }
74 return true;
75}
76
77bool flattenStrict(eve::json::Value node, const std::string& prefix, int depth,
78 std::unordered_map<std::string, std::string>& strings,
79 std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& plurals,
80 std::string& error, std::string& errorPath) {
81 if (depth > 16) {
82 error = "locale nesting exceeds 16 levels";
83 errorPath = prefix;
84 return false;
85 }
86 if (!node.isObject() || node.size() == 0) {
87 error = "translation namespaces must be non-empty objects";
88 errorPath = prefix;
89 return false;
90 }
91 const std::vector<std::string> names = node.keys();
92 bool allPlural = true;
93 bool anyPlural = false;
94 for (const auto& name : names) {
95 if (isPluralCategory(name))
96 anyPlural = true;
97 else
98 allPlural = false;
99 if (!validIdentifier(name)) {
100 error = "translation key segments must be stable identifiers";
101 errorPath = prefix + "." + name;
102 return false;
103 }
104 }
105 if (anyPlural && !allPlural) {
106 error = "plural categories cannot be mixed with namespace keys";
107 errorPath = prefix;
108 return false;
109 }
110 if (allPlural) {
111 if (prefix.empty() || !node.has("other")) {
112 error = "plural tables require a non-empty key and an other form";
113 errorPath = prefix;
114 return false;
115 }
116 std::unordered_map<std::string, std::string> forms;
117 for (const auto& name : names) {
118 const auto value = node.get(name.c_str());
119 if (!value.isString() || value.asString().empty() || value.asString().size() > 16384) {
120 error = "plural forms must be non-empty strings of at most 16384 bytes";
121 errorPath = prefix + "." + name;
122 return false;
123 }
124 forms.emplace(name, value.asString());
125 }
126 plurals.emplace(prefix, std::move(forms));
127 return true;
128 }
129 for (const auto& name : names) {
130 const auto value = node.get(name.c_str());
131 const std::string path = prefix.empty() ? name : prefix + "." + name;
132 if (value.isString()) {
133 if (value.asString().empty() || value.asString().size() > 16384) {
134 error = "translations must be non-empty strings of at most 16384 bytes";
135 errorPath = path;
136 return false;
137 }
138 strings.emplace(path, value.asString());
139 } else if (value.isObject()) {
140 if (!flattenStrict(value, path, depth + 1, strings, plurals, error, errorPath)) return false;
141 } else {
142 error = "translations must be strings, namespaces, or plural tables";
143 errorPath = path;
144 return false;
145 }
146 if (strings.size() + plurals.size() > 10000) {
147 error = "a locale may contain at most 10000 translation keys";
148 errorPath = path;
149 return false;
150 }
151 }
152 return true;
153}
154
155void flatten(eve::json::Value node, const std::string& prefix, std::unordered_map<std::string, std::string>& strings,
156 std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& plurals) {
157 if (node.isObject()) {
158 const std::vector<std::string> names = node.keys();
159 // A plain object of plural categories is a plural form table.
160 bool allCats = !names.empty();
161 bool allStrings = true;
162 for (const auto& k : names) {
163 if (!isPluralCategory(k)) {
164 allCats = false;
165 break;
166 }
167 if (!node.get(k.c_str()).isString()) allStrings = false;
168 }
169 if (allCats && allStrings && !prefix.empty()) {
170 std::unordered_map<std::string, std::string> forms;
171 for (const auto& k : names) forms[k] = node.getString(k.c_str());
172 plurals[prefix] = std::move(forms);
173 return;
174 }
175 for (const auto& k : names) {
176 const std::string path = prefix.empty() ? k : prefix + "." + k;
177 flatten(node.get(k.c_str()), path, strings, plurals);
178 }
179 return;
180 }
181 if (prefix.empty()) return;
182 // Scalars stringify; arrays and nulls are not translatable and are skipped.
183 if (node.isString() || node.isNumber() || node.isBool()) strings[prefix] = node.asString();
184}
185
186bool parseLocale(const std::string& text, std::unordered_map<std::string, std::string>& strings,
187 std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& plurals,
188 std::string* error) {
190 if (!doc.valid()) return false;
191 if (!doc.root().isObject()) {
192 if (error) *error = "locale root must be a JSON object";
193 return false;
194 }
195 strings.clear();
196 plurals.clear();
197 flatten(doc.root(), "", strings, plurals);
198 return true;
199}
200
201int64_t fileModtime(const std::string& path) {
202 auto* fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
203 if (!fs) fs = eve::filesystem::Filesystem::create();
205 if (!fs->getInfo(path, info)) return -1;
206 return info.modtime;
207}
208
209// Convert a Squirrel table (or null) into a string params map.
210std::unordered_map<std::string, std::string> readParams(ssq::Object params) {
211 std::unordered_map<std::string, std::string> out;
212 HSQUIRRELVM vm = params.getHandle();
213 if (!vm) return out;
214 const HSQOBJECT raw = params.getRaw();
215 if (raw._type != OT_TABLE) return out;
216
217 const SQInteger top = sq_gettop(vm);
218 sq_pushobject(vm, raw);
219 sq_pushnull(vm); // iterator
220 while (SQ_SUCCEEDED(sq_next(vm, -2))) {
221 // key at -2, value at -1
222 const SQChar* k = nullptr;
223 if (sq_gettype(vm, -2) == OT_STRING && SQ_SUCCEEDED(sq_getstring(vm, -2, &k)) && k) {
224 std::string v;
225 const SQObjectType vt = sq_gettype(vm, -1);
226 if (vt == OT_STRING) {
227 const SQChar* sv = nullptr;
228 if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sv)) && sv) v = sv;
229 } else if (vt == OT_INTEGER) {
230 SQInteger iv = 0;
231 if (SQ_SUCCEEDED(sq_getinteger(vm, -1, &iv))) v = std::to_string(iv);
232 } else if (vt == OT_FLOAT) {
233 SQFloat fv = 0;
234 if (SQ_SUCCEEDED(sq_getfloat(vm, -1, &fv))) v = numberToString(fv);
235 } else if (vt == OT_BOOL) {
236 SQBool bv = SQFalse;
237 if (SQ_SUCCEEDED(sq_getbool(vm, -1, &bv))) v = bv ? "true" : "false";
238 }
239 out[k] = std::move(v);
240 }
241 sq_pop(vm, 2);
242 }
243 sq_settop(vm, top);
244 return out;
245}
246
247} // namespace
248
249// ---------------------------------------------------------------------------
250// Module implementation
251// ---------------------------------------------------------------------------
252
253I18n::Locale* I18n::findLocale(const std::string& lang) {
254 auto it = locales_.find(lang);
255 return it == locales_.end() ? nullptr : &it->second;
256}
257
258const I18n::Locale* I18n::findLocale(const std::string& lang) const {
259 auto it = locales_.find(lang);
260 return it == locales_.end() ? nullptr : &it->second;
261}
262
263eve::Result<void> I18n::replaceLocaleFromJson(const std::string& lang, const std::string& json) {
264 if (lang.empty())
266 eve::DiagnosticCode::InvalidArgument, "locale identifier must not be empty", "locale", {}, "i18n.bundle"));
267 Locale loc;
268 std::string error;
269 if (!parseLocale(json, loc.strings, loc.plurals, &error))
271 error.empty() ? "invalid locale JSON" : error,
272 "locale." + lang, {}, "i18n.bundle"));
273 loc.path = "";
274 loc.modtime = -1;
275 locales_[lang] = std::move(loc);
277}
278
279bool I18n::loadFromJson(const std::string& lang, const std::string& json) {
280 return replaceLocaleFromJson(lang, json).ok();
281}
282
284 std::string parseError;
285 const auto document = eve::json::Document::parse(json, &parseError);
286 if (!document.valid())
288 eve::DiagnosticCode::ParseError, parseError.empty() ? "invalid localization bundle JSON" : parseError, "$",
289 {}, "i18n.bundle"));
290 const auto root = document.root();
291 if (!root.isObject())
293 "localization bundle root must be an object", "$", {},
294 "i18n.bundle"));
295 const std::unordered_set<std::string> rootFields = {"schema", "version", "defaultLocale", "locales"};
296 for (const auto& field : root.keys())
297 if (!rootFields.contains(field))
299 "localization bundle contains an unknown field",
300 "$." + field, {}, "i18n.bundle"));
301 const auto schema = root.get("schema");
302 const auto version = root.get("version");
303 const auto defaultLocale = root.get("defaultLocale");
304 const auto locales = root.get("locales");
305 if (!schema.isString() || schema.asString() != "eve.i18n.bundle")
307 "localization bundle schema id is invalid", "$.schema",
308 {}, "i18n.bundle"));
309 if (!version.isInt64() || version.asInt64() != 1)
311 "unsupported localization bundle schema version",
312 "$.version", {}, "i18n.bundle"));
313 if (!defaultLocale.isString() || !validIdentifier(defaultLocale.asString()))
315 "defaultLocale must be a stable locale identifier",
316 "$.defaultLocale", {}, "i18n.bundle"));
317 if (!locales.isObject() || locales.size() == 0 || locales.size() > 32)
319 "locales must contain between 1 and 32 locale objects",
320 "$.locales", {}, "i18n.bundle"));
321 if (!locales.has(defaultLocale.asString().c_str()))
323 "defaultLocale is not present in locales",
324 "$.defaultLocale", {}, "i18n.bundle"));
325
326 std::unordered_map<std::string, Locale> proposed;
327 for (const auto& lang : locales.keys()) {
328 if (!validIdentifier(lang))
330 "locale names must be stable identifiers",
331 "$.locales." + lang, {}, "i18n.bundle"));
332 Locale candidate;
333 std::string error;
334 std::string errorPath;
335 if (!flattenStrict(locales.get(lang.c_str()), "", 0, candidate.strings, candidate.plurals, error, errorPath))
338 "$.locales." + lang + (errorPath.empty() ? "" : "." + errorPath), {}, "i18n.bundle"));
339 proposed.emplace(lang, std::move(candidate));
340 }
341
342 const Locale& source = proposed.at(defaultLocale.asString());
343 for (const auto& [lang, locale] : proposed) {
344 for (const auto& [key, sourceText] : source.strings) {
345 const auto translated = locale.strings.find(key);
346 if (translated == locale.strings.end())
348 eve::DiagnosticCode::NotFound, "locale is missing a required singular translation",
349 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
350 std::set<std::string> expected;
351 std::set<std::string> actual;
352 std::string placeholderError;
353 if (!collectPlaceholders(sourceText, expected, placeholderError))
356 "$.locales." + defaultLocale.asString() + "." + key, {}, "i18n.bundle"));
357 if (!collectPlaceholders(translated->second, actual, placeholderError))
360 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
361 if (expected != actual)
363 eve::DiagnosticCode::InvalidArgument, "translation placeholders do not match the default locale",
364 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
365 }
366 for (const auto& [key, translated] : locale.strings)
367 if (!source.strings.contains(key))
370 "locale contains a singular key absent from the default locale",
371 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
372 for (const auto& [key, sourceForms] : source.plurals) {
373 const auto translated = locale.plurals.find(key);
374 if (translated == locale.plurals.end())
376 eve::DiagnosticCode::NotFound, "locale is missing a required plural translation",
377 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
378 for (const auto& [form, translatedText] : translated->second) {
379 const auto exactSource = sourceForms.find(form);
380 const auto fallbackSource = sourceForms.find("other");
381 const std::string& sourceText =
382 exactSource != sourceForms.end() ? exactSource->second : fallbackSource->second;
383 std::set<std::string> expected;
384 std::set<std::string> actual;
385 std::string placeholderError;
386 if (!collectPlaceholders(sourceText, expected, placeholderError))
388 eve::DiagnosticCode::InvalidArgument, placeholderError,
389 "$.locales." + defaultLocale.asString() + "." + key + "." + form, {}, "i18n.bundle"));
390 if (!collectPlaceholders(translatedText, actual, placeholderError))
393 "$.locales." + lang + "." + key + "." + form, {}, "i18n.bundle"));
394 if (expected != actual)
396 eve::DiagnosticCode::InvalidArgument, "plural placeholders do not match the default locale",
397 "$.locales." + lang + "." + key + "." + form, {}, "i18n.bundle"));
398 }
399 }
400 for (const auto& [key, forms] : locale.plurals) {
401 (void)forms;
402 if (!source.plurals.contains(key))
404 eve::DiagnosticCode::InvalidArgument, "locale contains a plural key absent from the default locale",
405 "$.locales." + lang + "." + key, {}, "i18n.bundle"));
406 }
407 }
408
409 const std::string nextDefault = defaultLocale.asString();
410 const std::string nextLanguage = proposed.contains(language_) ? language_ : nextDefault;
411 locales_ = std::move(proposed);
412 defaultLanguage_ = nextDefault;
413 language_ = nextLanguage;
414 return eve::Result<int>::success(static_cast<int>(locales_.size()), eve::Status::success(eve::StatusCode::Applied));
415}
416
417eve::Result<void> I18n::replaceLocaleFromFile(const std::string& lang, const std::string& path) {
418 if (lang.empty() || path.empty())
420 "locale identifier and VFS path must not be empty",
421 "locale.file", {}, "i18n.bundle"));
422
423 auto* fs = ModuleManager::getInstance<filesystem::Filesystem>("Filesystem");
424 if (!fs) fs = filesystem::Filesystem::create();
425
426 filesystem::FileData* fd = nullptr;
427 try {
428 fd = fs->read(path);
429 } catch (...) {
430 delete fd;
432 eve::DiagnosticCode::NotFound, "locale file could not be read", path, {}, "i18n.bundle"));
433 }
434 if (fd == nullptr || fd->getData() == nullptr || fd->getSize() == 0) {
435 delete fd;
437 eve::DiagnosticCode::NotFound, "locale file is missing or empty", path, {}, "i18n.bundle"));
438 }
439
440 std::string text(static_cast<const char*>(fd->getData()), fd->getSize());
441 delete fd;
442
443 Locale loc;
444 std::string error;
445 if (!parseLocale(text, loc.strings, loc.plurals, &error))
447 eve::DiagnosticCode::ParseError, error.empty() ? "invalid locale JSON" : error, path, {}, "i18n.bundle"));
448
449 loc.path = path;
450 loc.modtime = fileModtime(path);
451 fs->watch(path);
452 locales_[lang] = std::move(loc);
454}
455
456bool I18n::loadFromFile(const std::string& lang, const std::string& path) {
457 return replaceLocaleFromFile(lang, path).ok();
458}
459
460void I18n::unload(const std::string& lang) { locales_.erase(lang); }
461
462void I18n::clear() { locales_.clear(); }
463
464eve::Result<void> I18n::selectLanguage(const std::string& lang) {
465 if (!hasLanguage(lang))
467 eve::DiagnosticCode::NotFound, "language has not been admitted", "language." + lang, {}, "i18n.bundle"));
468 language_ = lang;
470}
471
472bool I18n::setLanguage(const std::string& lang) { return selectLanguage(lang).ok(); }
473
474std::string I18n::getLanguageAt(int index) const {
475 if (index < 0 || size_t(index) >= locales_.size()) return {};
476 std::vector<std::string> langs;
477 langs.reserve(locales_.size());
478 for (const auto& [lang, loc] : locales_) langs.push_back(lang);
479 std::sort(langs.begin(), langs.end());
480 return langs[size_t(index)];
481}
482
483bool I18n::hasLanguage(const std::string& lang) const { return findLocale(lang) != nullptr; }
484
485bool I18n::hasInLanguage(const std::string& lang, const std::string& key) const {
486 const Locale* locale = findLocale(lang);
487 return locale && (locale->strings.contains(key) || locale->plurals.contains(key));
488}
489
491 if (key.empty() || key.back() == '.')
493 "translation key must not be empty", "requiredKey", {},
494 "i18n.bundle"));
495 size_t offset = 0;
496 while (offset < key.size()) {
497 const size_t separator = key.find('.', offset);
498 const std::string segment = key.substr(offset, separator == std::string::npos ? std::string::npos
499 : separator - offset);
500 if (!validIdentifier(segment))
502 eve::DiagnosticCode::InvalidArgument, "translation key segments must be stable identifiers",
503 "requiredKey." + key, {}, "i18n.bundle"));
504 if (separator == std::string::npos) break;
505 offset = separator + 1;
506 }
507 if (locales_.empty())
509 eve::DiagnosticCode::NotFound, "no locales have been admitted", "locales", {}, "i18n.bundle"));
510 std::vector<std::string> languages;
511 languages.reserve(locales_.size());
512 for (const auto& [language, locale] : locales_) languages.push_back(language);
513 std::sort(languages.begin(), languages.end());
514 for (const auto& language : languages)
515 if (!hasInLanguage(language, key))
517 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "required translation key is missing",
518 "locales." + language + "." + key, {}, "i18n.bundle"));
519 return eve::Result<int>::success(static_cast<int>(languages.size()));
520}
521
522int I18n::getKeyCount(const std::string& lang) const {
523 const Locale* locale = findLocale(lang);
524 return locale ? static_cast<int>(locale->strings.size() + locale->plurals.size()) : 0;
525}
526
527bool I18n::has(const std::string& key) const {
528 const Locale* cur = findLocale(language_);
529 if (cur && (cur->strings.find(key) != cur->strings.end() || cur->plurals.find(key) != cur->plurals.end()))
530 return true;
531 if (defaultLanguage_ != language_) {
532 if (const Locale* def = findLocale(defaultLanguage_))
533 if (def->strings.find(key) != def->strings.end() || def->plurals.find(key) != def->plurals.end())
534 return true;
535 }
536 return false;
537}
538
539std::string I18n::get(const std::string& key) const {
540 if (const Locale* cur = findLocale(language_)) {
541 auto it = cur->strings.find(key);
542 if (it != cur->strings.end()) return it->second;
543 }
544 if (defaultLanguage_ != language_) {
545 if (const Locale* def = findLocale(defaultLanguage_)) {
546 auto it = def->strings.find(key);
547 if (it != def->strings.end()) return it->second;
548 }
549 }
550 return key;
551}
552
553std::string I18n::formatString(const std::string& tpl,
554 const std::unordered_map<std::string, std::string>& params) const {
555 std::string out;
556 out.reserve(tpl.size());
557 for (size_t i = 0; i < tpl.size();) {
558 if (tpl[i] == '{') {
559 const size_t close = tpl.find('}', i + 1);
560 if (close != std::string::npos) {
561 const std::string key = tpl.substr(i + 1, close - i - 1);
562 const auto it = params.find(key);
563 if (it != params.end()) {
564 out += it->second;
565 i = close + 1;
566 continue;
567 }
568 }
569 }
570 out += tpl[i++];
571 }
572 return out;
573}
574
575std::string I18n::getWithParams(const std::string& key,
576 const std::unordered_map<std::string, std::string>& params) const {
577 return formatString(get(key), params);
578}
579
580std::string I18n::getPlural(const std::string& key, int n) const { return getPluralWithParams(key, n, {}); }
581
582std::string I18n::getPluralWithParams(const std::string& key, int n,
583 const std::unordered_map<std::string, std::string>& params) const {
584 std::unordered_map<std::string, std::string> merged = params;
585 merged["n"] = std::to_string(n);
586
587 const Locale* cur = findLocale(language_);
588 const Locale* def = (defaultLanguage_ != language_) ? findLocale(defaultLanguage_) : nullptr;
589 if (!cur && !def) return key;
590
591 // Look up in the current language first, then fall back to the default.
592 std::string current;
593 if (const Locale* loc = cur) {
594 const auto pit = loc->plurals.find(key);
595 if (pit != loc->plurals.end()) {
596 const std::string form = pluralForm(language_, n);
597 auto it = pit->second.find(form);
598 if (it == pit->second.end()) it = pit->second.find("other");
599 if (it == pit->second.end()) it = pit->second.find("one");
600 if (it != pit->second.end()) return formatString(it->second, merged);
601 } else {
602 const auto sit = loc->strings.find(key);
603 if (sit != loc->strings.end()) return formatString(sit->second, merged);
604 }
605 }
606 if (const Locale* loc = def) {
607 const auto pit = loc->plurals.find(key);
608 if (pit != loc->plurals.end()) {
609 const std::string form = pluralForm(defaultLanguage_, n);
610 auto it = pit->second.find(form);
611 if (it == pit->second.end()) it = pit->second.find("other");
612 if (it == pit->second.end()) it = pit->second.find("one");
613 if (it != pit->second.end()) return formatString(it->second, merged);
614 } else {
615 const auto sit = loc->strings.find(key);
616 if (sit != loc->strings.end()) return formatString(sit->second, merged);
617 }
618 }
619 return key;
620}
621
622std::string I18n::pluralForm(const std::string& lang, int n) const {
623 std::string base = lang;
624 if (const size_t dash = base.find('-'); dash != std::string::npos) base = base.substr(0, dash);
625 if (const size_t under = base.find('_'); under != std::string::npos) base = base.substr(0, under);
626
627 if (base == "zh" || base == "ja" || base == "ko" || base == "th" || base == "vi" || base == "id" || base == "ms" ||
628 base == "tr" || base == "my")
629 return "other";
630
631 if (base == "fr" || base == "pt") return (n == 0 || n == 1) ? "one" : "other";
632
633 if (base == "ru" || base == "uk" || base == "be") {
634 const int mod10 = n % 10;
635 const int mod100 = n % 100;
636 if (mod10 == 1 && mod100 != 11) return "one";
637 if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return "few";
638 return "many";
639 }
640
641 if (base == "pl") {
642 const int mod10 = n % 10;
643 const int mod100 = n % 100;
644 if (n == 1) return "one";
645 if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return "few";
646 return "many";
647 }
648
649 if (base == "cs" || base == "sk") {
650 if (n == 1) return "one";
651 if (n >= 2 && n <= 4) return "few";
652 return "other";
653 }
654
655 return (n == 1) ? "one" : "other";
656}
657
658int I18n::update(float dt) {
659 (void)dt;
660 if (!autoReload_) return 0;
661
662 // Collect dirty entries first so reloading cannot invalidate the iterator.
663 std::vector<std::string> dirty;
664 for (const auto& [lang, loc] : locales_) {
665 if (loc.path.empty()) continue;
666 const int64_t mt = fileModtime(loc.path);
667 if (mt >= 0 && mt != loc.modtime) dirty.push_back(lang);
668 }
669
670 int reloaded = 0;
671 for (const std::string& lang : dirty) {
672 if (replaceLocaleFromFile(lang, locales_[lang].path).ok()) ++reloaded;
673 }
674 return reloaded;
675}
676
677// ---------------------------------------------------------------------------
678// Script binding
679// ---------------------------------------------------------------------------
680
681void I18n::expose(ssq::Table& table) {
682 auto cls = table.addClass(name, I18n::create, false);
683 expose(cls);
684}
685
686void I18n::expose(ssq::Class& cls) {
687 cls.addFunc("getName", &I18n::getName);
688 cls.addFunc("loadFromJson", &I18n::loadFromJson);
689 cls.addFunc("loadFromFile", &I18n::loadFromFile);
690 cls.addFunc("replaceLocaleFromJson", [vm = cls.getHandle()](I18n* self, const std::string& lang,
691 const std::string& json) {
692 if (!self)
693 return eve::script::projectResult(vm, eve::Result<void>::failure(eve::Diagnostic::error(
694 eve::DiagnosticCode::InvalidArgument,
695 "I18n receiver must not be null", "i18n", {}, "i18n.squirrel")));
696 return eve::script::projectResult(vm, self->replaceLocaleFromJson(lang, json));
697 });
698 cls.addFunc("replaceLocaleFromFile", [vm = cls.getHandle()](I18n* self, const std::string& lang,
699 const std::string& path) {
700 if (!self)
703 "I18n receiver must not be null", "i18n", {}, "i18n.squirrel")));
704 return eve::script::projectResult(vm, self->replaceLocaleFromFile(lang, path));
705 });
706 cls.addFunc("replaceBundleFromJson", [vm = cls.getHandle()](I18n* self, const std::string& json) {
707 if (!self)
711 "I18n receiver must not be null", "i18n", {}, "i18n.squirrel")),
712 [](int count) { return eve::Value(count); });
713 return eve::script::projectResult(vm, self->replaceBundleFromJson(json),
714 [](int count) { return eve::Value(count); });
715 });
716 cls.addFunc("unload", &I18n::unload);
717 cls.addFunc("clear", &I18n::clear);
718 cls.addFunc("setLanguage", &I18n::setLanguage);
719 cls.addFunc("selectLanguage", [vm = cls.getHandle()](I18n* self, const std::string& lang) {
720 if (!self)
723 "I18n receiver must not be null", "i18n", {}, "i18n.squirrel")));
724 return eve::script::projectResult(vm, self->selectLanguage(lang));
725 });
726 cls.addFunc("getLanguage", &I18n::getLanguage);
727 cls.addFunc("setDefaultLanguage", &I18n::setDefaultLanguage);
728 cls.addFunc("getDefaultLanguage", &I18n::getDefaultLanguage);
729 cls.addFunc("getLanguageCount", &I18n::getLanguageCount);
730 cls.addFunc("getLanguageAt", &I18n::getLanguageAt);
731 cls.addFunc("hasLanguage", &I18n::hasLanguage);
732 cls.addFunc("hasInLanguage", &I18n::hasInLanguage);
733 cls.addFunc("validateKeyCoverage", [vm = cls.getHandle()](I18n* self, const std::string& key) {
734 if (!self)
738 "I18n receiver must not be null", "i18n", {}, "i18n.squirrel")),
739 [](int count) { return eve::Value(count); });
740 return eve::script::projectResult(vm, self->validateKeyCoverage(key),
741 [](int count) { return eve::Value(count); });
742 });
743 cls.addFunc("getKeyCount", &I18n::getKeyCount);
744 cls.addFunc("has", &I18n::has);
745 cls.addFunc("get", &I18n::get);
746 cls.addFunc("getWithParams", [](I18n* self, const std::string& key, ssq::Object params) -> std::string {
747 return self->getWithParams(key, readParams(params));
748 });
749 cls.addFunc("getPlural", &I18n::getPlural);
750 cls.addFunc("getPluralWithParams",
751 [](I18n* self, const std::string& key, int n, ssq::Object params) -> std::string {
752 return self->getPluralWithParams(key, n, readParams(params));
753 });
754 cls.addFunc("setAutoReload", &I18n::setAutoReload);
755 cls.addFunc("isAutoReload", &I18n::isAutoReload);
756 cls.addFunc("update", &I18n::update);
757}
758
759} // namespace eve::i18n
int root
Definition AnimSmr.cpp:119
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
double raw
glm::vec3 n
Definition Grass.cpp:63
float v
std::int32_t c
size_t offset
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
double dt
std::string error
Definition Package.cpp:174
bool dirty
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
const RoadNode * node
std::string text
ScriptStructure out
std::string_view source
double current
int count
The single Squirrel projection for common Result, Status and Value.
Share string attribute map operations through the Windows Foundation DLL.
std::uint32_t depth
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
virtual std::string getName() const =0
Returns the name.
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Data buffer paired with a filename (used for type identification).
Definition FileData.h:14
size_t getSize() const
Byte length of the owned buffer.
Definition FileData.h:29
void * getData() const
Pointer to the owned byte buffer.
Definition FileData.h:27
Game localization (i18n) module.
Definition I18n.h:39
bool loadFromJson(const std::string &lang, const std::string &json)
Compatibility-only bool projection of replaceLocaleFromJson.
Definition I18n.cpp:279
std::string getDefaultLanguage() const
Returns the default language.
Definition I18n.h:107
std::string getPluralWithParams(const std::string &key, int n, const std::unordered_map< std::string, std::string > &params) const
Returns the plural with params.
Definition I18n.cpp:582
bool hasLanguage(const std::string &lang) const
True when language.
Definition I18n.cpp:483
int update(float dt)
Re-read changed locale files; returns the number of reloads performed.
Definition I18n.cpp:658
void setAutoReload(bool enable)
Sets the auto reload.
Definition I18n.h:142
bool isAutoReload() const
True when auto reload.
Definition I18n.h:144
eve::Result< void > selectLanguage(const std::string &lang)
Select an admitted language with a structured missing-locale diagnostic.
Definition I18n.cpp:464
bool loadFromFile(const std::string &lang, const std::string &path)
Compatibility-only bool projection of replaceLocaleFromFile.
Definition I18n.cpp:456
std::string getWithParams(const std::string &key, const std::unordered_map< std::string, std::string > &params) const
Returns the with params.
Definition I18n.cpp:575
void unload(const std::string &lang)
卸载 / 清空语言表。
Definition I18n.cpp:460
bool hasInLanguage(const std::string &lang, const std::string &key) const
Return whether one exact locale owns key, without default-language substitution.
Definition I18n.cpp:485
std::string getLanguage() const
Returns the language.
Definition I18n.h:103
bool setLanguage(const std::string &lang)
Compatibility-only bool projection of selectLanguage.
Definition I18n.cpp:472
void clear()
Clears .
Definition I18n.cpp:462
bool has(const std::string &key) const
翻译查找:按键(点号命名空间)取字符串。
Definition I18n.cpp:527
I18n()=default
I 18 n.
std::string getLanguageAt(int index) const
Returns the language at.
Definition I18n.cpp:474
eve::Result< void > replaceLocaleFromJson(const std::string &lang, const std::string &json)
Atomically replace one locale from JSON with structured failure details.
Definition I18n.cpp:263
int getKeyCount(const std::string &lang) const
Return the number of singular and plural keys owned by one locale, or zero if absent.
Definition I18n.cpp:522
eve::Result< int > validateKeyCoverage(const std::string &key) const
Validate that every admitted locale owns one exact product key.
Definition I18n.cpp:490
std::string getPlural(const std::string &key, int n) const
Returns the plural.
Definition I18n.cpp:580
eve::Result< void > replaceLocaleFromFile(const std::string &lang, const std::string &path)
Atomically replace one locale from a VFS file with structured failure details.
Definition I18n.cpp:417
std::string get(const std::string &key) const
Returns the value.
Definition I18n.cpp:539
void setDefaultLanguage(const std::string &lang)
Sets the default language.
Definition I18n.h:105
int getLanguageCount() const
Returns the language count.
Definition I18n.h:109
eve::Result< int > replaceBundleFromJson(const std::string &json)
Atomically replace every locale from one strictly validated product bundle.
Definition I18n.cpp:283
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
bool isObject() const
True when object.
Definition Json.cpp:332
SQInteger top
Definition Snapshot.cpp:115
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
glm::uvec4 info