Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/core/string/translation_po.cpp
9903 views
1
/**************************************************************************/
2
/* translation_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_po.h"
32
33
#ifdef DEBUG_TRANSLATION_PO
34
#include "core/io/file_access.h"
35
36
void TranslationPO::print_translation_map() {
37
Error err;
38
Ref<FileAccess> file = FileAccess::open("translation_map_print_test.txt", FileAccess::WRITE, &err);
39
if (err != OK) {
40
ERR_PRINT("Failed to open translation_map_print_test.txt");
41
return;
42
}
43
44
file->store_line("NPlural : " + String::num_int64(get_plural_forms()));
45
file->store_line("Plural rule : " + get_plural_rule());
46
file->store_line("");
47
48
List<StringName> context_l;
49
translation_map.get_key_list(&context_l);
50
for (const StringName &ctx : context_l) {
51
file->store_line(" ===== Context: " + String::utf8(String(ctx).utf8()) + " ===== ");
52
const HashMap<StringName, Vector<StringName>> &inner_map = translation_map[ctx];
53
54
List<StringName> id_l;
55
inner_map.get_key_list(&id_l);
56
for (const StringName &id : id_l) {
57
file->store_line("msgid: " + String::utf8(String(id).utf8()));
58
for (int i = 0; i < inner_map[id].size(); i++) {
59
file->store_line("msgstr[" + String::num_int64(i) + "]: " + String::utf8(String(inner_map[id][i]).utf8()));
60
}
61
file->store_line("");
62
}
63
}
64
}
65
#endif
66
67
Dictionary TranslationPO::_get_messages() const {
68
// Return translation_map as a Dictionary.
69
70
Dictionary d;
71
72
for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
73
Dictionary d2;
74
75
for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
76
d2[E2.key] = E2.value;
77
}
78
79
d[E.key] = d2;
80
}
81
82
return d;
83
}
84
85
void TranslationPO::_set_messages(const Dictionary &p_messages) {
86
// Construct translation_map from a Dictionary.
87
88
for (const KeyValue<Variant, Variant> &kv : p_messages) {
89
const Dictionary &id_str_map = kv.value;
90
91
HashMap<StringName, Vector<StringName>> temp_map;
92
for (const KeyValue<Variant, Variant> &kv_id : id_str_map) {
93
StringName id = kv_id.key;
94
temp_map[id] = kv_id.value;
95
}
96
97
translation_map[kv.key] = temp_map;
98
}
99
}
100
101
Vector<String> TranslationPO::get_translated_message_list() const {
102
Vector<String> msgs;
103
for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
104
if (E.key != StringName()) {
105
continue;
106
}
107
108
for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
109
for (const StringName &E3 : E2.value) {
110
msgs.push_back(E3);
111
}
112
}
113
}
114
115
return msgs;
116
}
117
118
Vector<String> TranslationPO::_get_message_list() const {
119
// Return all keys in translation_map.
120
121
List<StringName> msgs;
122
get_message_list(&msgs);
123
124
Vector<String> v;
125
for (const StringName &E : msgs) {
126
v.push_back(E);
127
}
128
129
return v;
130
}
131
132
int TranslationPO::_get_plural_index(int p_n) const {
133
// Get a number between [0;number of plural forms).
134
135
input_val.clear();
136
input_val.push_back(p_n);
137
138
return _eq_test(equi_tests, 0);
139
}
140
141
int TranslationPO::_eq_test(const Ref<EQNode> &p_node, const Variant &p_result) const {
142
if (p_node.is_valid()) {
143
Error err = expr->parse(p_node->regex, input_name);
144
ERR_FAIL_COND_V_MSG(err != OK, 0, vformat("Cannot parse expression \"%s\". Error: %s", p_node->regex, expr->get_error_text()));
145
146
Variant result = expr->execute(input_val);
147
ERR_FAIL_COND_V_MSG(expr->has_execute_failed(), 0, vformat("Cannot evaluate expression \"%s\".", p_node->regex));
148
149
if (bool(result)) {
150
return _eq_test(p_node->left, result);
151
} else {
152
return _eq_test(p_node->right, result);
153
}
154
} else {
155
return p_result;
156
}
157
}
158
159
int TranslationPO::_find_unquoted(const String &p_src, char32_t p_chr) const {
160
const int len = p_src.length();
161
if (len == 0) {
162
return -1;
163
}
164
165
const char32_t *src = p_src.get_data();
166
bool in_quote = false;
167
for (int i = 0; i < len; i++) {
168
if (in_quote) {
169
if (src[i] == ')') {
170
in_quote = false;
171
}
172
} else {
173
if (src[i] == '(') {
174
in_quote = true;
175
} else if (src[i] == p_chr) {
176
return i;
177
}
178
}
179
}
180
181
return -1;
182
}
183
184
void TranslationPO::_cache_plural_tests(const String &p_plural_rule, Ref<EQNode> &p_node) {
185
// Some examples of p_plural_rule passed in can have the form:
186
// "n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5" (Arabic)
187
// "n >= 2" (French) // When evaluating the last, especially careful with this one.
188
// "n != 1" (English)
189
190
String rule = p_plural_rule;
191
if (rule.begins_with("(") && rule.ends_with(")")) {
192
int bcount = 0;
193
for (int i = 1; i < rule.length() - 1 && bcount >= 0; i++) {
194
if (rule[i] == '(') {
195
bcount++;
196
} else if (rule[i] == ')') {
197
bcount--;
198
}
199
}
200
if (bcount == 0) {
201
rule = rule.substr(1, rule.length() - 2);
202
}
203
}
204
205
int first_ques_mark = _find_unquoted(rule, '?');
206
int first_colon = _find_unquoted(rule, ':');
207
208
if (first_ques_mark == -1) {
209
p_node->regex = rule.strip_edges();
210
return;
211
}
212
213
p_node->regex = rule.substr(0, first_ques_mark).strip_edges();
214
215
p_node->left.instantiate();
216
_cache_plural_tests(rule.substr(first_ques_mark + 1, first_colon - first_ques_mark - 1).strip_edges(), p_node->left);
217
p_node->right.instantiate();
218
_cache_plural_tests(rule.substr(first_colon + 1).strip_edges(), p_node->right);
219
}
220
221
void TranslationPO::set_plural_rule(const String &p_plural_rule) {
222
// Set plural_forms and plural_rule.
223
// p_plural_rule passed in has the form "Plural-Forms: nplurals=2; plural=(n >= 2);".
224
225
int first_semi_col = p_plural_rule.find_char(';');
226
plural_forms = p_plural_rule.substr(p_plural_rule.find_char('=') + 1, first_semi_col - (p_plural_rule.find_char('=') + 1)).to_int();
227
228
int expression_start = p_plural_rule.find_char('=', first_semi_col) + 1;
229
int second_semi_col = p_plural_rule.rfind_char(';');
230
plural_rule = p_plural_rule.substr(expression_start, second_semi_col - expression_start).strip_edges();
231
232
// Setup the cache to make evaluating plural rule faster later on.
233
equi_tests.instantiate();
234
_cache_plural_tests(plural_rule, equi_tests);
235
236
expr.instantiate();
237
input_name.push_back("n");
238
}
239
240
void TranslationPO::add_message(const StringName &p_src_text, const StringName &p_xlated_text, const StringName &p_context) {
241
HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
242
243
if (map_id_str.has(p_src_text)) {
244
WARN_PRINT(vformat("Double translations for \"%s\" under the same context \"%s\" for locale \"%s\".\nThere should only be one unique translation for a given string under the same context.", String(p_src_text), String(p_context), get_locale()));
245
map_id_str[p_src_text].set(0, p_xlated_text);
246
} else {
247
map_id_str[p_src_text].push_back(p_xlated_text);
248
}
249
}
250
251
void TranslationPO::add_plural_message(const StringName &p_src_text, const Vector<String> &p_plural_xlated_texts, const StringName &p_context) {
252
ERR_FAIL_COND_MSG(p_plural_xlated_texts.size() != plural_forms, vformat("Trying to add plural texts that don't match the required number of plural forms for locale \"%s\".", get_locale()));
253
254
HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
255
256
if (map_id_str.has(p_src_text)) {
257
WARN_PRINT(vformat("Double translations for \"%s\" under the same context \"%s\" for locale %s.\nThere should only be one unique translation for a given string under the same context.", p_src_text, p_context, get_locale()));
258
map_id_str[p_src_text].clear();
259
}
260
261
for (int i = 0; i < p_plural_xlated_texts.size(); i++) {
262
map_id_str[p_src_text].push_back(p_plural_xlated_texts[i]);
263
}
264
}
265
266
int TranslationPO::get_plural_forms() const {
267
return plural_forms;
268
}
269
270
String TranslationPO::get_plural_rule() const {
271
return plural_rule;
272
}
273
274
StringName TranslationPO::get_message(const StringName &p_src_text, const StringName &p_context) const {
275
if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
276
return StringName();
277
}
278
ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), vformat("Source text \"%s\" is registered but doesn't have a translation. Please report this bug.", String(p_src_text)));
279
280
return translation_map[p_context][p_src_text][0];
281
}
282
283
StringName TranslationPO::get_plural_message(const StringName &p_src_text, const StringName &p_plural_text, int p_n, const StringName &p_context) const {
284
ERR_FAIL_COND_V_MSG(p_n < 0, StringName(), "N passed into translation to get a plural message should not be negative. For negative numbers, use singular translation please. Search \"gettext PO Plural Forms\" online for the documentation on translating negative numbers.");
285
286
// If the query is the same as last time, return the cached result.
287
if (p_n == last_plural_n && p_context == last_plural_context && p_src_text == last_plural_key) {
288
return translation_map[p_context][p_src_text][last_plural_mapped_index];
289
}
290
291
if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
292
return StringName();
293
}
294
ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), vformat("Source text \"%s\" is registered but doesn't have a translation. Please report this bug.", String(p_src_text)));
295
296
int plural_index = _get_plural_index(p_n);
297
ERR_FAIL_COND_V_MSG(plural_index < 0 || translation_map[p_context][p_src_text].size() < plural_index + 1, StringName(), "Plural index returned or number of plural translations is not valid. Please report this bug.");
298
299
// Cache result so that if the next entry is the same, we can return directly.
300
// _get_plural_index(p_n) can get very costly, especially when evaluating long plural-rule (Arabic)
301
last_plural_key = p_src_text;
302
last_plural_context = p_context;
303
last_plural_n = p_n;
304
last_plural_mapped_index = plural_index;
305
306
return translation_map[p_context][p_src_text][plural_index];
307
}
308
309
void TranslationPO::erase_message(const StringName &p_src_text, const StringName &p_context) {
310
if (!translation_map.has(p_context)) {
311
return;
312
}
313
314
translation_map[p_context].erase(p_src_text);
315
}
316
317
void TranslationPO::get_message_list(List<StringName> *r_messages) const {
318
// OptimizedTranslation uses this function to get the list of msgid.
319
// Return all the keys of translation_map under "" context.
320
321
for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
322
if (E.key != StringName()) {
323
continue;
324
}
325
326
for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
327
r_messages->push_back(E2.key);
328
}
329
}
330
}
331
332
int TranslationPO::get_message_count() const {
333
int count = 0;
334
335
for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
336
count += E.value.size();
337
}
338
339
return count;
340
}
341
342
void TranslationPO::_bind_methods() {
343
ClassDB::bind_method(D_METHOD("get_plural_forms"), &TranslationPO::get_plural_forms);
344
ClassDB::bind_method(D_METHOD("get_plural_rule"), &TranslationPO::get_plural_rule);
345
}
346
347