Debian Codegraph @

core/io/translation_loader_po.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* translation_loader_po.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "translation_loader_po.h"
32
33 #include "core/io/file_access.h"
34 #include "core/string/translation.h"
35
36 Ref<Resource> TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_error) {
37 if (r_error) {
38 *r_error = ERR_FILE_CORRUPT;
39 }
40
41 const String path = f->get_path();
42 Ref<Translation> translation;
43 translation.instantiate();
44 String config;
45
46 uint32_t magic = f->get_32();
47 if (magic == 0x950412de) {
48 // Load binary MO file.
49
50 uint16_t version_maj = f->get_16();
51 uint16_t version_min = f->get_16();
52 ERR_FAIL_COND_V_MSG(version_maj > 1, Ref<Resource>(), vformat("Unsupported MO file %s, version %d.%d.", path, version_maj, version_min));
53
54 uint32_t num_strings = f->get_32();
55 uint32_t id_table_offset = f->get_32();
56 uint32_t trans_table_offset = f->get_32();
57
58 // Read string tables.
59 for (uint32_t i = 0; i < num_strings; i++) {
60 String msg_id;
61 String msg_id_plural;
62 String msg_context;
63
64 // Read id strings and context.
65 {
66 Vector<uint8_t> data;
67 f->seek(id_table_offset + i * 8);
68 uint32_t str_start = 0;
69 uint32_t str_len = f->get_32();
70 uint32_t str_offset = f->get_32();
71
72 data.resize(str_len + 1);
73 f->seek(str_offset);
74 f->get_buffer(data.ptrw(), str_len);
75 data.write[str_len] = 0;
76
77 bool is_plural = false;
78 for (uint32_t j = 0; j < str_len + 1; j++) {
79 if (data[j] == 0x04) {
80 msg_context.clear();
81 msg_context.append_utf8((const char *)data.ptr(), j);
82 str_start = j + 1;
83 }
84 if (data[j] == 0x00) {
85 if (is_plural) {
86 msg_id_plural.clear();
87 msg_id_plural.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
88 } else {
89 msg_id.clear();
90 msg_id.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
91 is_plural = true;
92 }
93 str_start = j + 1;
94 }
95 }
96 }
97
98 // Read translated strings.
99 {
100 Vector<uint8_t> data;
101 f->seek(trans_table_offset + i * 8);
102 uint32_t str_len = f->get_32();
103 uint32_t str_offset = f->get_32();
104
105 data.resize(str_len + 1);
106 f->seek(str_offset);
107 f->get_buffer(data.ptrw(), str_len);
108 data.write[str_len] = 0;
109
110 if (msg_id.is_empty()) {
111 config = String::utf8((const char *)data.ptr(), str_len);
112 // Record plural rule.
113 int p_start = config.find("Plural-Forms");
114 if (p_start != -1) {
115 int p_end = config.find_char('\n', p_start);
116 translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
117 }
118 } else {
119 uint32_t str_start = 0;
120 Vector<String> plural_msg;
121 for (uint32_t j = 0; j < str_len + 1; j++) {
122 if (data[j] == 0x00) {
123 if (msg_id_plural.is_empty()) {
124 translation->add_message(msg_id, String::utf8((const char *)(data.ptr() + str_start), j - str_start), msg_context);
125 } else {
126 plural_msg.push_back(String::utf8((const char *)(data.ptr() + str_start), j - str_start));
127 }
128 str_start = j + 1;
129 }
130 }
131 if (!plural_msg.is_empty()) {
132 translation->add_plural_message(msg_id, plural_msg, msg_context);
133 }
134 }
135 }
136 }
137
138 } else {
139 // Try to load as text PO file.
140 f->seek(0);
141
142 enum Status {
143 STATUS_NONE,
144 STATUS_READING_ID,
145 STATUS_READING_STRING,
146 STATUS_READING_CONTEXT,
147 STATUS_READING_PLURAL,
148 };
149
150 Status status = STATUS_NONE;
151
152 String msg_id;
153 String msg_str;
154 String msg_context;
155 Vector<String> msgs_plural;
156
157 if (r_error) {
158 *r_error = ERR_FILE_CORRUPT;
159 }
160
161 int line = 1;
162 int plural_forms = 0;
163 int plural_index = -1;
164 bool entered_context = false;
165 bool skip_this = false;
166 bool skip_next = false;
167 bool is_eof = false;
168
169 while (!is_eof) {
170 String l = f->get_line().strip_edges();
171 is_eof = f->eof_reached();
172
173 // If we reached last line and it's not a content line, break, otherwise let processing that last loop
174 if (is_eof && l.is_empty()) {
175 if (status == STATUS_READING_ID || status == STATUS_READING_CONTEXT || (status == STATUS_READING_PLURAL && plural_index != plural_forms - 1)) {
176 ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected EOF while reading PO file at: %s:%d.", path, line));
177 } else {
178 break;
179 }
180 }
181
182 if (l.begins_with("msgctxt")) {
183 ERR_FAIL_COND_V_MSG(status != STATUS_READING_STRING && status != STATUS_READING_PLURAL, Ref<Resource>(), vformat("Unexpected 'msgctxt', was expecting 'msgid_plural' or 'msgstr' before 'msgctxt' while parsing: %s:%d.", path, line));
184
185 // In PO file, "msgctxt" appears before "msgid". If we encounter a "msgctxt", we add what we have read
186 // and set "entered_context" to true to prevent adding twice.
187 if (!skip_this && !msg_id.is_empty()) {
188 if (status == STATUS_READING_STRING) {
189 translation->add_message(msg_id, msg_str, msg_context);
190 } else if (status == STATUS_READING_PLURAL) {
191 ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
192 translation->add_plural_message(msg_id, msgs_plural, msg_context);
193 }
194 }
195 msg_context = "";
196 l = l.substr(7).strip_edges();
197 status = STATUS_READING_CONTEXT;
198 entered_context = true;
199 }
200
201 if (l.begins_with("msgid_plural")) {
202 if (plural_forms == 0) {
203 ERR_FAIL_V_MSG(Ref<Resource>(), vformat("PO file uses 'msgid_plural' but 'Plural-Forms' is invalid or missing in header: %s:%d.", path, line));
204 } else if (status != STATUS_READING_ID) {
205 ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected 'msgid_plural', was expecting 'msgid' before 'msgid_plural' while parsing: %s:%d.", path, line));
206 }
207 // We don't record the message in "msgid_plural" itself as tr_n(), TTRN(), RTRN() interfaces provide the plural string already.
208 // We just have to reset variables related to plurals for "msgstr[]" later on.
209 l = l.substr(12).strip_edges();
210 plural_index = -1;
211 msgs_plural.clear();
212 msgs_plural.resize(plural_forms);
213 status = STATUS_READING_PLURAL;
214 } else if (l.begins_with("msgid")) {
215 ERR_FAIL_COND_V_MSG(status == STATUS_READING_ID, Ref<Resource>(), vformat("Unexpected 'msgid', was expecting 'msgstr' while parsing: %s:%d.", path, line));
216
217 if (!msg_id.is_empty()) {
218 if (!skip_this && !entered_context) {
219 if (status == STATUS_READING_STRING) {
220 translation->add_message(msg_id, msg_str, msg_context);
221 } else if (status == STATUS_READING_PLURAL) {
222 ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
223 translation->add_plural_message(msg_id, msgs_plural, msg_context);
224 }
225 }
226 } else if (config.is_empty()) {
227 config = msg_str;
228 // Record plural rule.
229 int p_start = config.find("Plural-Forms");
230 if (p_start != -1) {
231 int p_end = config.find_char('\n', p_start);
232 translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
233 plural_forms = translation->get_nplurals();
234 }
235 }
236
237 l = l.substr(5).strip_edges();
238 status = STATUS_READING_ID;
239 // If we did not encounter msgctxt, we reset context to empty to reset it.
240 if (!entered_context) {
241 msg_context = "";
242 }
243 msg_id = "";
244 msg_str = "";
245 skip_this = skip_next;
246 skip_next = false;
247 entered_context = false;
248 }
249
250 if (l.begins_with("msgstr[")) {
251 ERR_FAIL_COND_V_MSG(status != STATUS_READING_PLURAL, Ref<Resource>(), vformat("Unexpected 'msgstr[]', was expecting 'msgid_plural' before 'msgstr[]' while parsing: %s:%d.", path, line));
252 plural_index++; // Increment to add to the next slot in vector msgs_plural.
253 l = l.substr(9).strip_edges();
254 } else if (l.begins_with("msgstr")) {
255 ERR_FAIL_COND_V_MSG(status != STATUS_READING_ID, Ref<Resource>(), vformat("Unexpected 'msgstr', was expecting 'msgid' before 'msgstr' while parsing: %s:%d.", path, line));
256 l = l.substr(6).strip_edges();
257 status = STATUS_READING_STRING;
258 }
259
260 if (l.is_empty() || l.begins_with("#")) {
261 if (l.contains("fuzzy")) {
262 skip_next = true;
263 }
264 line++;
265 continue; // Nothing to read or comment.
266 }
267
268 ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, Ref<Resource>(), vformat("Invalid line '%s' while parsing: %s:%d.", l, path, line));
269
270 l = l.substr(1);
271 // Find final quote, ignoring escaped ones (\").
272 // The escape_next logic is necessary to properly parse things like \\"
273 // where the backslash is the one being escaped, not the quote.
274 int end_pos = -1;
275 bool escape_next = false;
276 for (int i = 0; i < l.length(); i++) {
277 if (l[i] == '\\' && !escape_next) {
278 escape_next = true;
279 continue;
280 }
281
282 if (l[i] == '"' && !escape_next) {
283 end_pos = i;
284 break;
285 }
286
287 escape_next = false;
288 }
289
290 ERR_FAIL_COND_V_MSG(end_pos == -1, Ref<Resource>(), vformat("Expected '\"' at end of message while parsing: %s:%d.", path, line));
291
292 l = l.substr(0, end_pos);
293 l = l.c_unescape();
294
295 if (status == STATUS_READING_ID) {
296 msg_id += l;
297 } else if (status == STATUS_READING_STRING) {
298 msg_str += l;
299 } else if (status == STATUS_READING_CONTEXT) {
300 msg_context += l;
301 } else if (status == STATUS_READING_PLURAL && plural_index >= 0) {
302 ERR_FAIL_COND_V_MSG(plural_index >= plural_forms, Ref<Resource>(), vformat("Unexpected plural form while parsing: %s:%d.", path, line));
303 msgs_plural.write[plural_index] = msgs_plural[plural_index] + l;
304 }
305
306 line++;
307 }
308
309 // Add the last set of data from last iteration.
310 if (status == STATUS_READING_STRING) {
311 if (!msg_id.is_empty()) {
312 if (!skip_this) {
313 translation->add_message(msg_id, msg_str, msg_context);
314 }
315 } else if (config.is_empty()) {
316 config = msg_str;
317 }
318 } else if (status == STATUS_READING_PLURAL) {
319 if (!skip_this && !msg_id.is_empty()) {
320 ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
321 translation->add_plural_message(msg_id, msgs_plural, msg_context);
322 }
323 }
324 }
325
326 ERR_FAIL_COND_V_MSG(config.is_empty(), Ref<Resource>(), vformat("No config found in file: '%s'.", path));
327
328 Vector<String> configs = config.split("\n");
329 for (int i = 0; i < configs.size(); i++) {
330 String c = configs[i].strip_edges();
331 int p = c.find_char(':');
332 if (p == -1) {
333 continue;
334 }
335 String prop = c.substr(0, p).strip_edges();
336 String value = c.substr(p + 1).strip_edges();
337
338 if (prop == "X-Language" || prop == "Language") {
339 translation->set_locale(value);
340 }
341 }
342
343 if (r_error) {
344 *r_error = OK;
345 }
346
347 return translation;
348 }
349
350 Ref<Resource> TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
351 if (r_error) {
352 *r_error = ERR_CANT_OPEN;
353 }
354
355 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
356 ERR_FAIL_COND_V_MSG(f.is_null(), Ref<Resource>(), vformat("Cannot open file '%s'.", p_path));
357
358 return load_translation(f, r_error);
359 }
360
361 void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
362 p_extensions->push_back("po");
363 p_extensions->push_back("mo");
364 }
365
366 bool TranslationLoaderPO::handles_type(const String &p_type) const {
367 return p_type == "Translation";
368 }
369
370 String TranslationLoaderPO::get_resource_type(const String &p_path) const {
371 if (p_path.has_extension("po") || p_path.has_extension("mo")) {
372 return "Translation";
373 }
374 return "";
375 }