Debian Codegraph @

Source/Core/DolphinQt/Translation.cpp

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2017 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/Translation.h"
5
6 #include <algorithm>
7 #include <cstring>
8 #include <iterator>
9 #include <string>
10
11 #include <fmt/format.h>
12
13 #include <QApplication>
14 #include <QLocale>
15 #include <QTranslator>
16
17 #include "Common/FileUtil.h"
18 #include "Common/IOFile.h"
19 #include "Common/Logging/Log.h"
20 #include "Common/MsgHandler.h"
21
22 #include "Core/Config/MainSettings.h"
23
24 #include "DolphinQt/QtUtils/ModalMessageBox.h"
25
26 #include "UICommon/UICommon.h"
27
28 constexpr u32 MO_MAGIC_NUMBER = 0x950412de;
29
30 static u16 ReadU16(const char* data)
31 {
32 u16 value;
33 std::memcpy(&value, data, sizeof(value));
34 return value;
35 }
36
37 static u32 ReadU32(const char* data)
38 {
39 u32 value;
40 std::memcpy(&value, data, sizeof(value));
41 return value;
42 }
43
44 class MoIterator
45 {
46 public:
47 using iterator_category = std::random_access_iterator_tag;
48 using value_type = const char*;
49 using difference_type = s64;
50 using pointer = value_type;
51 using reference = value_type;
52
53 explicit MoIterator(const char* data, u32 table_offset, u32 index = 0)
54 : m_data{data}, m_table_offset{table_offset}, m_index{index}
55 {
56 }
57
58 // This is the actual underlying logic of accessing a Mo file. Patterned after the
59 // boost::iterator_facade library, which nicely separates out application logic from
60 // iterator-concept logic.
61 void advance(difference_type n) { m_index += n; }
62 difference_type distance_to(const MoIterator& other) const
63 {
64 return static_cast<difference_type>(other.m_index) - m_index;
65 }
66 reference dereference() const
67 {
68 u32 offset = ReadU32(&m_data[m_table_offset + m_index * 8 + 4]);
69 return &m_data[offset];
70 }
71
72 // Needed for Iterator concept
73 reference operator*() const { return dereference(); }
74 MoIterator& operator++()
75 {
76 advance(1);
77 return *this;
78 }
79
80 // Needed for InputIterator concept
81 bool operator==(const MoIterator& other) const { return distance_to(other) == 0; }
82 pointer operator->() const { return dereference(); }
83 MoIterator operator++(int)
84 {
85 MoIterator tmp(*this);
86 advance(1);
87 return tmp;
88 }
89
90 // Needed for BidirectionalIterator concept
91 MoIterator& operator--()
92 {
93 advance(-1);
94 return *this;
95 }
96 MoIterator operator--(int)
97 {
98 MoIterator tmp(*this);
99 advance(-1);
100 return tmp;
101 }
102
103 // Needed for RandomAccessIterator concept
104 bool operator<(const MoIterator& other) const { return distance_to(other) > 0; }
105 bool operator<=(const MoIterator& other) const { return distance_to(other) >= 0; }
106 bool operator>(const MoIterator& other) const { return distance_to(other) < 0; }
107 bool operator>=(const MoIterator& other) const { return distance_to(other) <= 0; }
108 reference operator[](difference_type n) const { return *(*this + n); }
109 MoIterator& operator+=(difference_type n)
110 {
111 advance(n);
112 return *this;
113 }
114 MoIterator& operator-=(difference_type n)
115 {
116 advance(-n);
117 return *this;
118 }
119 friend MoIterator operator+(difference_type n, const MoIterator& it) { return it + n; }
120 friend MoIterator operator+(const MoIterator& it, difference_type n)
121 {
122 MoIterator tmp(it);
123 tmp += n;
124 return tmp;
125 }
126 difference_type operator-(const MoIterator& other) const { return other.distance_to(*this); }
127 friend MoIterator operator-(difference_type n, const MoIterator& it) { return it - n; }
128 friend MoIterator operator-(const MoIterator& it, difference_type n)
129 {
130 MoIterator tmp(it);
131 tmp -= n;
132 return tmp;
133 }
134
135 private:
136 const char* m_data;
137 u32 m_table_offset;
138 u32 m_index;
139 };
140
141 class MoFile
142 {
143 public:
144 MoFile() = default;
145 explicit MoFile(const std::string& filename)
146 {
147 File::IOFile file(filename, "rb");
148 m_data.resize(file.GetSize());
149 file.ReadBytes(m_data.data(), m_data.size());
150
151 if (!file)
152 {
153 WARN_LOG_FMT(COMMON, "Error reading MO file '{}'", filename);
154 m_data = {};
155 return;
156 }
157
158 const u32 magic = ReadU32(&m_data[0]);
159 if (magic != MO_MAGIC_NUMBER)
160 {
161 ERROR_LOG_FMT(COMMON, "MO file '{}' has bad magic number {:x}\n", filename, magic);
162 m_data = {};
163 return;
164 }
165
166 const u16 version_major = ReadU16(&m_data[4]);
167 if (version_major > 1)
168 {
169 ERROR_LOG_FMT(COMMON, "MO file '{}' has unsupported version number {}", filename,
170 version_major);
171 m_data = {};
172 return;
173 }
174
175 m_number_of_strings = ReadU32(&m_data[8]);
176 m_offset_original_table = ReadU32(&m_data[12]);
177 m_offset_translation_table = ReadU32(&m_data[16]);
178 }
179
180 u32 GetNumberOfStrings() const { return m_number_of_strings; }
181 const char* Translate(const char* original_string) const
182 {
183 const MoIterator begin(m_data.data(), m_offset_original_table);
184 const MoIterator end(m_data.data(), m_offset_original_table, m_number_of_strings);
185 auto iter = std::lower_bound(begin, end, original_string,
186 [](const char* a, const char* b) { return strcmp(a, b) < 0; });
187
188 if (iter == end || strcmp(*iter, original_string) != 0)
189 return nullptr;
190
191 u32 offset = ReadU32(&m_data[m_offset_translation_table + std::distance(begin, iter) * 8 + 4]);
192 return &m_data[offset];
193 }
194
195 private:
196 std::vector<char> m_data;
197 u32 m_number_of_strings = 0;
198 u32 m_offset_original_table = 0;
199 u32 m_offset_translation_table = 0;
200 };
201
202 class MoTranslator : public QTranslator
203 {
204 public:
205 using QTranslator::QTranslator;
206
207 bool isEmpty() const override { return m_mo_file.GetNumberOfStrings() == 0; }
208 bool load(const std::string& filename)
209 {
210 m_mo_file = MoFile(filename);
211 return !isEmpty();
212 }
213
214 QString translate(const char* context, const char* source_text,
215 const char* disambiguation = nullptr, int n = -1) const override
216 {
217 const char* translated_text;
218
219 if (disambiguation)
220 {
221 std::string combined_string = disambiguation;
222 combined_string += '\4';
223 combined_string += source_text;
224 translated_text = m_mo_file.Translate(combined_string.c_str());
225 }
226 else
227 {
228 translated_text = m_mo_file.Translate(source_text);
229 }
230
231 return QString::fromUtf8(translated_text ? translated_text : source_text);
232 }
233
234 private:
235 MoFile m_mo_file;
236 };
237
238 static QStringList FindPossibleLanguageCodes(const QString& exact_language_code)
239 {
240 QStringList possible_language_codes;
241 possible_language_codes << exact_language_code;
242
243 // Qt likes to separate language, script, and country by hyphen, but on disk they're separated by
244 // underscores.
245 possible_language_codes.replaceInStrings(QStringLiteral("-"), QStringLiteral("_"));
246
247 // Try successively dropping subtags (like the stock QTranslator, and as specified by RFC 4647
248 // "Matching of Language Tags").
249 // Example: fr_Latn_CA -> fr_Latn -> fr
250 for (auto lang : QStringList(possible_language_codes))
251 {
252 while (lang.contains(QLatin1Char('_')))
253 {
254 lang = lang.left(lang.lastIndexOf(QLatin1Char('_')));
255 possible_language_codes << lang;
256 }
257 }
258
259 // On macOS, Chinese (Simplified) and Chinese (Traditional) are represented as zh-Hans and
260 // zh-Hant, but on Linux they're represented as zh-CN and zh-TW. Qt should probably include the
261 // script subtags on Linux, but it doesn't.
262 const int hans_index = possible_language_codes.indexOf(QStringLiteral("zh_Hans"));
263 if (hans_index != -1)
264 possible_language_codes.insert(hans_index + 1, QStringLiteral("zh_CN"));
265 const int hant_index = possible_language_codes.indexOf(QStringLiteral("zh_Hant"));
266 if (hant_index != -1)
267 possible_language_codes.insert(hant_index + 1, QStringLiteral("zh_TW"));
268
269 return possible_language_codes;
270 }
271
272 static bool TryInstallTranslator(const QString& exact_language_code)
273 {
274 for (const auto& qlang : FindPossibleLanguageCodes(exact_language_code))
275 {
276 std::string lang = qlang.toStdString();
277 auto filename =
278 #if defined _WIN32
279 fmt::format("{}/Languages/{}.mo", File::GetExeDirectory(), lang)
280 #elif defined __APPLE__
281 fmt::format("{}/Contents/Resources/{}.lproj/dolphin-emu.mo", File::GetBundleDirectory(),
282 lang)
283 #elif defined LINUX_LOCAL_DEV
284 fmt::format("{}/../Source/Core/DolphinQt/{}/dolphin-emu.mo", File::GetExeDirectory(), lang)
285 #else
286 fmt::format("{}/locale/{}/LC_MESSAGES/dolphin-emu.mo", DATA_ROOT_DIR, lang)
287 #endif
288 ;
289
290 auto* translator = new MoTranslator(QApplication::instance());
291 if (translator->load(filename))
292 {
293 QApplication::instance()->installTranslator(translator);
294
295 QLocale::setDefault(QLocale(exact_language_code));
296 UICommon::SetLocale(exact_language_code.toStdString());
297
298 return true;
299 }
300 translator->deleteLater();
301 }
302 ERROR_LOG_FMT(COMMON, "No suitable translation file found");
303 return false;
304 }
305
306 void Translation::Initialize()
307 {
308 // Hook up Dolphin internal translation
309 Common::RegisterStringTranslator(
310 [](const char* text) { return QObject::tr(text).toStdString(); });
311
312 // Hook up Qt translations
313 std::string configured_language = Config::Get(Config::MAIN_INTERFACE_LANGUAGE);
314 if (!configured_language.empty())
315 {
316 if (TryInstallTranslator(QString::fromStdString(configured_language)))
317 return;
318
319 ModalMessageBox::warning(
320 nullptr, QObject::tr("Error"),
321 QObject::tr("Error loading selected language. Falling back to system default."));
322 Config::SetBase(Config::MAIN_INTERFACE_LANGUAGE, "");
323 }
324
325 for (const auto& lang : QLocale::system().uiLanguages())
326 {
327 if (TryInstallTranslator(lang))
328 break;
329 }
330 }