CS2-Kit
C++23 library for CS2 Metamod:Source plugin development
Loading...
Searching...
No Matches
Translations.cpp
Go to the documentation of this file.
1#include <CS2Kit/Core/Paths.hpp>
2#include <CS2Kit/Utils/Log.hpp>
3#include <CS2Kit/Utils/Translations.hpp>
4#include <filesystem>
5#include <fstream>
6#include <nlohmann/json.hpp>
7
8namespace CS2Kit::Utils
9{
10
11bool Translations::Load(const std::string& dirPath)
12{
13 _translations.clear();
14 namespace fs = std::filesystem;
15
16 auto resolvedPath = Core::ResolvePath(dirPath);
17
18 if (!fs::exists(resolvedPath) || !fs::is_directory(resolvedPath))
19 {
20 Log::Warn("Translations directory not found: {}", resolvedPath.string());
21 return false;
22 }
23
24 int loaded = 0;
25 for (const auto& entry : fs::directory_iterator(resolvedPath))
26 {
27 if (entry.path().extension() != ".json")
28 continue;
29
30 std::string langCode = entry.path().stem().string();
31 try
32 {
33 std::ifstream file(entry.path());
34 if (!file.is_open())
35 continue;
36
37 auto data = nlohmann::json::parse(file);
38 auto& langMap = _translations[langCode];
39 for (auto& [key, value] : data.items())
40 {
41 if (value.is_string())
42 langMap[key] = value.get<std::string>();
43 }
44
45 ++loaded;
46 Log::Info("Loaded translations: {} ({} keys)", langCode, langMap.size());
47 }
48 catch (const std::exception& e)
49 {
50 Log::Warn("Failed to parse {}: {}", entry.path().string(), e.what());
51 }
52 }
53
54 Log::Info("Loaded {} language(s).", loaded);
55 return loaded > 0;
56}
57
58void Translations::SetLanguage(const std::string& lang)
59{
60 _activeLang = lang;
61}
62
63const std::string& Translations::GetLanguage() const
64{
65 return _activeLang;
66}
67
68std::string Translations::Get(const std::string& key) const
69{
70 auto langIt = _translations.find(_activeLang);
71 if (langIt != _translations.end())
72 {
73 auto keyIt = langIt->second.find(key);
74 if (keyIt != langIt->second.end())
75 return keyIt->second;
76 }
77
78 if (_activeLang != "en")
79 {
80 langIt = _translations.find("en");
81 if (langIt != _translations.end())
82 {
83 auto keyIt = langIt->second.find(key);
84 if (keyIt != langIt->second.end())
85 return keyIt->second;
86 }
87 }
88
89 return key;
90}
91
92} // namespace CS2Kit::Utils
std::filesystem::path ResolvePath(const std::string &relativePath)
Definition Paths.cpp:13