nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
translations.cc
Go to the documentation of this file.
2
3#include <raylib.h>
4
5#include <algorithm>
6#include <array>
7#include <bitset>
8#include <cctype>
9#include <cstddef>
10#include <cstdint>
11#include <functional>
12#include <map>
13#include <optional>
14#include <string>
15#include <string_view>
16#include <utility>
17#include <vector>
18
19#include "absl/status/status.h"
20#include "absl/status/statusor.h"
21#include "absl/strings/numbers.h"
22#include "absl/strings/str_cat.h"
23#include "content/text.h"
24
25namespace nanommo {
26
27namespace {
28
29// Works out a Plural-Forms expression for a count, reading it as it goes, from
30// the loosest of C's operators to the tightest. One it can't read, or that
31// divides by nothing, isn't ok.
32class Expression {
33 public:
34 Expression(std::string_view text, uint64_t n) : text_(text), n_(n) {}
35
36 std::optional<uint64_t> Evaluate() {
37 const uint64_t value = Ternary();
38 Skip();
39 if (!ok_ || at_ != text_.size()) {
40 return std::nullopt;
41 }
42 return value;
43 }
44
45 private:
46 // Expressions inside expressions, in brackets or after a ?, deeper than any
47 // language's rule goes, and nowhere near deep enough to run out of stack.
48 static constexpr int kDeepest = 32;
49
50 // condition ? then : otherwise, which goes to the right.
51 uint64_t Ternary() {
52 if (depth_ == kDeepest) {
53 ok_ = false;
54 return 0;
55 }
56 ++depth_;
57 uint64_t value = Or();
58 if (Take("?")) {
59 const uint64_t then = Ternary();
60 ok_ = ok_ && Take(":");
61 const uint64_t otherwise = Ternary();
62 value = value != 0 ? then : otherwise;
63 }
64 --depth_;
65 return value;
66 }
67
68 uint64_t Or() {
69 uint64_t value = And();
70 while (Take("||")) {
71 const uint64_t right = And();
72 value = value != 0 || right != 0 ? 1 : 0;
73 }
74 return value;
75 }
76
77 uint64_t And() {
78 uint64_t value = Equality();
79 while (Take("&&")) {
80 const uint64_t right = Equality();
81 value = value != 0 && right != 0 ? 1 : 0;
82 }
83 return value;
84 }
85
86 uint64_t Equality() {
87 uint64_t value = Comparison();
88 while (true) {
89 if (Take("==")) {
90 value = value == Comparison() ? 1 : 0;
91 } else if (Take("!=")) {
92 value = value != Comparison() ? 1 : 0;
93 } else {
94 return value;
95 }
96 }
97 }
98
99 uint64_t Comparison() {
100 uint64_t value = Remainder();
101 while (true) {
102 // The two-letter ones first, or "<=" would read as "<".
103 if (Take("<=")) {
104 value = value <= Remainder() ? 1 : 0;
105 } else if (Take(">=")) {
106 value = value >= Remainder() ? 1 : 0;
107 } else if (Take("<")) {
108 value = value < Remainder() ? 1 : 0;
109 } else if (Take(">")) {
110 value = value > Remainder() ? 1 : 0;
111 } else {
112 return value;
113 }
114 }
115 }
116
117 uint64_t Remainder() {
118 uint64_t value = Primary();
119 while (Take("%")) {
120 const uint64_t by = Primary();
121 if (by == 0) {
122 ok_ = false;
123 return 0;
124 }
125 value %= by;
126 }
127 return value;
128 }
129
130 // n, a number, or an expression in brackets.
131 uint64_t Primary() {
132 if (Take("(")) {
133 const uint64_t value = Ternary();
134 ok_ = ok_ && Take(")");
135 return value;
136 }
137 if (Take("n")) {
138 return n_;
139 }
140 const std::size_t start = at_;
141 while (at_ < text_.size() &&
142 std::isdigit(static_cast<unsigned char>(text_[at_])) != 0) {
143 ++at_;
144 }
145 uint64_t number = 0;
146 if (!absl::SimpleAtoi(text_.substr(start, at_ - start), &number)) {
147 ok_ = false;
148 }
149 return number;
150 }
151
152 void Skip() {
153 while (at_ < text_.size() &&
154 std::isspace(static_cast<unsigned char>(text_[at_])) != 0) {
155 ++at_;
156 }
157 }
158
159 bool Take(std::string_view token) {
160 Skip();
161 if (!text_.substr(at_).starts_with(token)) {
162 return false;
163 }
164 at_ += token.size();
165 return true;
166 }
167
168 std::string_view text_;
169 uint64_t n_;
170 std::size_t at_ = 0;
171 int depth_ = 0;
172 bool ok_ = true;
173};
174
175// What a PO file says of one string: its context, its English, and its
176// English plural, with a translation for each form, or one.
177struct Entry {
178 std::string context;
179 std::string id;
180 std::optional<std::string> plural;
181 std::vector<std::string> strings;
182 bool fuzzy = false;
183};
184
185// A quoted string, as PO files and C write them, with its escapes.
186absl::StatusOr<std::string> Unquote(std::string_view quoted) {
187 if (quoted.size() < 2 || quoted.front() != '"' || quoted.back() != '"') {
188 return absl::InvalidArgumentError("expected a string in quotes");
189 }
190 std::string text;
191 for (std::size_t i = 1; i + 1 < quoted.size(); ++i) {
192 const char c = quoted[i];
193 if (c == '"') {
194 return absl::InvalidArgumentError("a quote that isn't escaped");
195 }
196 if (c != '\\') {
197 text += c;
198 continue;
199 }
200 if (i + 2 >= quoted.size()) {
201 return absl::InvalidArgumentError("a string that ends in a backslash");
202 }
203 switch (quoted[++i]) {
204 case 'n':
205 text += '\n';
206 break;
207 case 't':
208 text += '\t';
209 break;
210 case 'r':
211 text += '\r';
212 break;
213 case '"':
214 text += '"';
215 break;
216 case '\\':
217 text += '\\';
218 break;
219 default:
220 return absl::InvalidArgumentError(
221 absl::StrCat("an escape there isn't: \\", quoted.substr(i, 1)));
222 }
223 }
224 return text;
225}
226
227std::string_view Trimmed(std::string_view line) {
228 while (!line.empty() &&
229 std::isspace(static_cast<unsigned char>(line.front())) != 0) {
230 line.remove_prefix(1);
231 }
232 while (!line.empty() &&
233 std::isspace(static_cast<unsigned char>(line.back())) != 0) {
234 line.remove_suffix(1);
235 }
236 return line;
237}
238
239// Each entry in the file, the header first, as it has them: a keyword and its
240// string on a line, more of the string on the lines after it, in quotes, and
241// comments, of which only "#, fuzzy" matters here. Obsolete entries, "#~",
242// are comments too.
243absl::StatusOr<std::vector<Entry>> ReadEntries(std::string_view po) {
244 std::vector<Entry> entries;
245 Entry entry;
246 // Whether the entry has its msgctxt or its msgid yet, and its msgid.
247 bool started = false;
248 bool has_id = false;
249 // A "#, fuzzy" for the entry to come.
250 bool fuzzy = false;
251 // Where the next line in quotes goes on.
252 std::string* last = nullptr;
253 const auto finish = [&] {
254 if (started) {
255 entries.push_back(std::move(entry));
256 }
257 entry = Entry();
258 started = false;
259 has_id = false;
260 last = nullptr;
261 };
262 const auto start = [&] {
263 entry.fuzzy = fuzzy;
264 fuzzy = false;
265 started = true;
266 };
267 int number = 0;
268 for (std::size_t at = 0; at <= po.size();) {
269 std::size_t end = po.find('\n', at);
270 if (end == std::string_view::npos) {
271 end = po.size();
272 }
273 const std::string_view line = Trimmed(po.substr(at, end - at));
274 at = end + 1;
275 ++number;
276 const auto error = [number](std::string_view why) {
277 return absl::InvalidArgumentError(
278 absl::StrCat("line ", number, ": ", why));
279 };
280 if (line.empty()) {
281 continue;
282 }
283 // A comment after an entry's strings is the next one's.
284 const bool complete = !entry.strings.empty();
285 if (line.front() == '#') {
286 if (complete) {
287 finish();
288 } else if (started) {
289 return error("a comment in the middle of an entry");
290 }
291 fuzzy = fuzzy || (line.starts_with("#,") &&
292 line.find("fuzzy") != std::string_view::npos);
293 continue;
294 }
295 if (line.front() == '"') {
296 if (last == nullptr) {
297 return error("a string that follows no keyword");
298 }
299 absl::StatusOr<std::string> more = Unquote(line);
300 if (!more.ok()) {
301 return error(more.status().message());
302 }
303 *last += *more;
304 continue;
305 }
306 const std::size_t space = line.find_first_of(" \t");
307 if (space == std::string_view::npos) {
308 return error(absl::StrCat("a keyword without a string: ", line));
309 }
310 const std::string_view keyword = line.substr(0, space);
311 absl::StatusOr<std::string> text = Unquote(Trimmed(line.substr(space)));
312 if (!text.ok()) {
313 return error(text.status().message());
314 }
315 // A new entry starts at its context, or at its English.
316 if ((keyword == "msgctxt" || keyword == "msgid") && complete) {
317 finish();
318 }
319 if (keyword == "msgctxt") {
320 if (started) {
321 return error("a msgctxt in the middle of an entry");
322 }
323 start();
324 entry.context = *std::move(text);
325 last = &entry.context;
326 } else if (keyword == "msgid") {
327 if (has_id) {
328 return error("a second msgid in an entry");
329 }
330 if (!started) {
331 start();
332 }
333 has_id = true;
334 entry.id = *std::move(text);
335 last = &entry.id;
336 } else if (keyword == "msgid_plural") {
337 if (!has_id || entry.plural || complete) {
338 return error("a msgid_plural that isn't after a msgid");
339 }
340 entry.plural = *std::move(text);
341 last = &*entry.plural;
342 } else if (keyword == "msgstr") {
343 if (!has_id || entry.plural || complete) {
344 return error("a msgstr that isn't after a msgid");
345 }
346 entry.strings.push_back(*std::move(text));
347 last = &entry.strings.back();
348 } else if (keyword.starts_with("msgstr[") && keyword.ends_with("]")) {
349 const std::string form = absl::StrCat(entry.strings.size());
350 if (!entry.plural || keyword.substr(7, keyword.size() - 8) != form) {
351 return error(absl::StrCat("expected msgstr[", form, "]"));
352 }
353 entry.strings.push_back(*std::move(text));
354 last = &entry.strings.back();
355 } else {
356 return error(absl::StrCat("a keyword there isn't: ", keyword));
357 }
358 }
359 if (started && entry.strings.empty()) {
360 return absl::InvalidArgumentError("the last entry has no msgstr");
361 }
362 finish();
363 return entries;
364}
365
366// The placeholders a string has, $0 to $9, as absl::Substitute reads them,
367// for whom $$ is a dollar.
368std::bitset<10> Placeholders(std::string_view text) {
369 std::bitset<10> found;
370 for (std::size_t i = 0; i + 1 < text.size(); ++i) {
371 if (text[i] != '$') {
372 continue;
373 }
374 const char next = text[++i];
375 if (next >= '0' && next <= '9') {
376 found.set(static_cast<std::size_t>(next - '0'));
377 }
378 }
379 return found;
380}
381
382std::string Key(std::string_view context, std::string_view text) {
383 return context.empty() ? std::string(text)
384 : absl::StrCat(context, "\x04", text);
385}
386
387// A header's field, such as "Plural-Forms", or nothing.
388std::optional<std::string_view> HeaderField(std::string_view header,
389 std::string_view name) {
390 for (std::size_t start = 0; start < header.size();) {
391 std::size_t end = header.find('\n', start);
392 if (end == std::string_view::npos) {
393 end = header.size();
394 }
395 const std::string_view line = header.substr(start, end - start);
396 start = end + 1;
397 if (line.starts_with(name) && line.substr(name.size()).starts_with(":")) {
398 return Trimmed(line.substr(name.size() + 1));
399 }
400 }
401 return std::nullopt;
402}
403
404} // namespace
405
406absl::StatusOr<PluralRule> PluralRule::Parse(std::string_view forms) {
407 const std::size_t count = forms.find("nplurals=");
408 const std::size_t plural = forms.find("plural=", count + 1);
409 if (count == std::string_view::npos || plural == std::string_view::npos) {
410 return absl::InvalidArgumentError(
411 absl::StrCat("Plural-Forms without nplurals= and plural=: ", forms));
412 }
413 PluralRule rule;
414 const std::string_view number =
415 Trimmed(forms.substr(count + 9, forms.find(';', count) - count - 9));
416 if (!absl::SimpleAtoi(number, &rule.forms_) || rule.forms_ < 1) {
417 return absl::InvalidArgumentError(
418 absl::StrCat("nplurals isn't a number of forms: ", number));
419 }
420 std::string_view expression = forms.substr(plural + 7);
421 expression = Trimmed(expression.substr(0, expression.find(';')));
422 rule.plural_ = std::string(expression);
423 // Any count goes round to one of these, as the rules take n % 100 or
424 // n % 10 and no more.
425 for (uint64_t n = 0; n < 1000; ++n) {
426 const std::optional<uint64_t> form = Expression(expression, n).Evaluate();
427 if (!form) {
428 return absl::InvalidArgumentError(
429 absl::StrCat("a plural rule that can't be read: ", expression));
430 }
431 if (*form >= static_cast<uint64_t>(rule.forms_)) {
432 return absl::InvalidArgumentError(
433 absl::StrCat("the plural rule picks form ", *form, " for ", n,
434 ", of ", rule.forms_));
435 }
436 }
437 return rule;
438}
439
440int PluralRule::Form(uint64_t n) const {
441 const std::optional<uint64_t> form = Expression(plural_, n).Evaluate();
442 return form && *form < static_cast<uint64_t>(forms_) ? static_cast<int>(*form)
443 : 0;
444}
445
446absl::StatusOr<Catalog> Catalog::Parse(std::string_view po) {
447 absl::StatusOr<std::vector<Entry>> entries = ReadEntries(po);
448 if (!entries.ok()) {
449 return entries.status();
450 }
451 Catalog catalog;
452 for (const Entry& entry : *entries) {
453 // The header, which is the translation of nothing.
454 if (entry.id.empty() && entry.context.empty()) {
455 if (const std::optional<std::string_view> forms =
456 HeaderField(entry.strings.front(), "Plural-Forms")) {
457 absl::StatusOr<PluralRule> rule = PluralRule::Parse(*forms);
458 if (!rule.ok()) {
459 return rule.status();
460 }
461 catalog.plurals_ = *std::move(rule);
462 }
463 continue;
464 }
465 const std::bitset<10> english =
466 Placeholders(entry.id) | Placeholders(entry.plural.value_or(""));
467 const bool translated =
468 !entry.fuzzy &&
469 std::ranges::none_of(entry.strings, &std::string::empty) &&
470 std::ranges::all_of(entry.strings, [&](const std::string& text) {
471 return (Placeholders(text) & ~english).none();
472 });
473 if (translated) {
474 catalog.translations_[Key(entry.context, entry.id)] = entry.strings;
475 }
476 }
477 return catalog;
478}
479
480absl::StatusOr<Catalog> Catalog::PseudoFrom(std::string_view pot) {
481 absl::StatusOr<std::vector<Entry>> entries = ReadEntries(pot);
482 if (!entries.ok()) {
483 return entries.status();
484 }
485 Catalog catalog;
486 for (const Entry& entry : *entries) {
487 if (entry.id.empty() && entry.context.empty()) {
488 continue;
489 }
490 std::vector<std::string>& made =
491 catalog.translations_[Key(entry.context, entry.id)];
492 made.push_back(Pseudo(entry.id));
493 if (entry.plural) {
494 made.push_back(Pseudo(*entry.plural));
495 }
496 }
497 return catalog;
498}
499
500const char* Catalog::Find(std::string_view context,
501 std::string_view text) const {
502 const auto found = context.empty() ? translations_.find(text)
503 : translations_.find(Key(context, text));
504 return found != translations_.end() && found->second.size() == 1
505 ? found->second.front().c_str()
506 : nullptr;
507}
508
509const char* Catalog::Find(std::string_view context, std::string_view one,
510 uint64_t n) const {
511 const auto found = context.empty() ? translations_.find(one)
512 : translations_.find(Key(context, one));
513 if (found == translations_.end() ||
514 static_cast<int>(found->second.size()) != plurals_.forms()) {
515 return nullptr;
516 }
517 return found->second[static_cast<std::size_t>(plurals_.Form(n))].c_str();
518}
519
520std::string Pseudo(std::string_view english) {
521 // Romanian's own marks where it has them, so that the fonts show they've
522 // got them, and another of Latin's elsewhere.
523 static constexpr std::array<std::pair<char, std::string_view>, 20> kMarked = {
524 {{'a', "ă"}, {'c', "ç"}, {'e', "é"}, {'i', "î"}, {'n', "ñ"},
525 {'o', "ö"}, {'s', "ș"}, {'t', "ț"}, {'u', "ü"}, {'y', "ý"},
526 {'A', "Ă"}, {'C', "Ç"}, {'E', "É"}, {'I', "Î"}, {'N', "Ñ"},
527 {'O', "Ö"}, {'S', "Ș"}, {'T', "Ț"}, {'U', "Ü"}, {'Y', "Ý"}}};
528 std::string made = "[";
529 std::size_t letters = 0;
530 for (std::size_t i = 0; i < english.size(); ++i) {
531 const char c = english[i];
532 // A placeholder stays as it is, for absl::Substitute.
533 if (c == '$' && i + 1 < english.size()) {
534 made += english.substr(i, 2);
535 ++i;
536 continue;
537 }
538 if (std::isalpha(static_cast<unsigned char>(c)) != 0) {
539 ++letters;
540 }
541 const auto marked = std::ranges::find(
542 kMarked, c, &std::pair<char, std::string_view>::first);
543 if (marked != kMarked.end()) {
544 made += marked->second;
545 } else {
546 made += c;
547 }
548 }
549 // A third longer, as many languages are longer than English.
550 absl::StrAppend(&made, " ", std::string((letters + 2) / 3, '~'), "]");
551 return made;
552}
553
554namespace {
555
556// The language in use, and the labels TrLabel has made for it, which ImGui
557// only reads, so each is made once.
558struct InUse {
559 std::optional<Catalog> catalog;
560 std::map<std::string, std::string, std::less<>> labels;
561};
562
563InUse& Current() {
564 static InUse& in_use = *new InUse;
565 return in_use;
566}
567
568} // namespace
569
570std::string LanguageFolder() {
571 return std::string(GetApplicationDirectory()) + "po";
572}
573
574absl::Status UseLanguage(std::string_view code, const std::string& folder) {
575 Current() = InUse();
576 if (code.empty()) {
577 return absl::OkStatus();
578 }
579 const bool pseudo = code == kPseudo;
580 const std::string file = pseudo ? "nanommo.pot" : absl::StrCat(code, ".po");
581 const absl::StatusOr<std::string> text =
582 ReadFile(absl::StrCat(folder, "/", file));
583 if (!text.ok()) {
584 return text.status();
585 }
586 absl::StatusOr<Catalog> catalog =
587 pseudo ? Catalog::PseudoFrom(*text) : Catalog::Parse(*text);
588 if (!catalog.ok()) {
589 return absl::InvalidArgumentError(
590 absl::StrCat(code, ": ", catalog.status().message()));
591 }
592 Current().catalog = *std::move(catalog);
593 return absl::OkStatus();
594}
595
596const char* Tr(const char* text) { return Tr("", text); }
597
598const char* Tr(std::string_view context, const char* text) {
599 const std::optional<Catalog>& catalog = Current().catalog;
600 const char* found = catalog ? catalog->Find(context, text) : nullptr;
601 return found != nullptr ? found : text;
602}
603
604const char* TrN(const char* one, const char* many, uint64_t n) {
605 return TrN("", one, many, n);
606}
607
608const char* TrN(std::string_view context, const char* one, const char* many,
609 uint64_t n) {
610 const std::optional<Catalog>& catalog = Current().catalog;
611 const char* found = catalog ? catalog->Find(context, one, n) : nullptr;
612 if (found != nullptr) {
613 return found;
614 }
615 return n == 1 ? one : many;
616}
617
618const char* TrLabel(const char* label) {
619 const std::string_view all = label;
620 const std::string_view shown = all.substr(0, all.find("##"));
621 const std::optional<Catalog>& catalog = Current().catalog;
622 const char* translated =
623 catalog && !shown.empty() ? catalog->Find("", shown) : nullptr;
624 if (translated == nullptr) {
625 return label;
626 }
627 auto& labels = Current().labels;
628 auto made = labels.find(all);
629 if (made == labels.end()) {
630 made = labels.emplace(all, absl::StrCat(translated, "###", all)).first;
631 }
632 return made->second.c_str();
633}
634
635} // namespace nanommo
static absl::StatusOr< Catalog > Parse(std::string_view po)
const char * Find(std::string_view context, std::string_view text) const
The translation, or null for one there isn't.
static absl::StatusOr< Catalog > PseudoFrom(std::string_view pot)
static absl::StatusOr< PluralRule > Parse(std::string_view forms)
int Form(uint64_t n) const
The form for the count, from 0.
PluralRule()=default
English's: one form for 1, and the other for any other count.
Definition chat.cc:9
std::string Pseudo(std::string_view english)
The English made over for the pseudo-language: "[Șéțțîñgș ~~~]".
const char * Tr(const char *text)
const char * TrN(const char *one, const char *many, uint64_t n)
The form for the count: in English, one for 1 and many for the rest.
const char * TrLabel(const char *label)
constexpr std::string_view kPseudo
The pseudo-language's code: it's made from the template, nanommo.pot.
absl::StatusOr< std::string > ReadFile(const std::string &path)
Definition text.cc:43
std::string LanguageFolder()
Where the PO files are, next to the client.
absl::Status UseLanguage(std::string_view code, const std::string &folder)