yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
translator.cc
Go to the documentation of this file.
2
3#include <string>
4#include <unordered_map>
5
7
8namespace yaze {
9namespace i18n {
10namespace {
11
12// Resolved-value store keyed by source CONTENT. unordered_map is node-based, so
13// the std::string values never move on rehash and their c_str() stays valid
14// until the map is cleared (only on a language switch). Handles distinct
15// addresses that hold equal content (e.g. std::string::c_str() sources).
16std::unordered_map<std::string, std::string>& Resolved() {
17 static std::unordered_map<std::string, std::string> store;
18 return store;
19}
20
21// Translates only the visible prefix of an ImGui label, preserving any
22// "##id"/"###id" suffix byte-for-byte.
23std::string Compose(const std::string& source) {
24 const std::string::size_type pos = source.find("##");
25 const std::string visible =
26 (pos == std::string::npos) ? source : source.substr(0, pos);
27 if (visible.empty()) {
28 return source; // pure-id label like "##foo": nothing visible to translate
29 }
30 const std::string* translated = LanguageManager::Get().Find(visible);
31 const std::string& out_visible =
32 (translated != nullptr && !translated->empty()) ? *translated : visible;
33 if (pos == std::string::npos) {
34 return out_visible;
35 }
36 return out_visible + source.substr(pos); // re-attach the id suffix unchanged
37}
38
39const std::string& ResolveByContent(const std::string& key) {
40 auto& store = Resolved();
41 auto it = store.find(key);
42 if (it == store.end()) {
43 it = store.emplace(key, Compose(key)).first;
44 }
45 return it->second;
46}
47
48} // namespace
49
50const char* tr(const char* source) {
51 if (source == nullptr)
52 return "";
53 // Resolve by CONTENT, not by pointer: menus are rebuilt every frame, so a
54 // label's std::string reuses addresses across frames. A pointer-keyed cache
55 // returned the previous frame's translation for a reused address -> the
56 // menu-label flicker. ResolveByContent already caches per unique string.
57 return ResolveByContent(std::string(source)).c_str();
58}
59
60const char* tr(const std::string& source) {
61 return ResolveByContent(source).c_str();
62}
63
65 Resolved().clear();
66}
67
68} // namespace i18n
69} // namespace yaze
const std::string * Find(const std::string &visible_key) const
static LanguageManager & Get()
std::string Compose(const std::string &source)
Definition translator.cc:23
const std::string & ResolveByContent(const std::string &key)
Definition translator.cc:39
std::unordered_map< std::string, std::string > & Resolved()
Definition translator.cc:16
void ClearTranslationCache()
Definition translator.cc:64
const char * tr(const char *source)
Definition translator.cc:50