FR
games/rob-revisited / src / Revisited / I18n / Translator.php · commit f9a1307
<?phpnamespace App\Revisited\I18n;/** * The English of "Rob revisited". The game is written in French; t() turns a French text into the player's language. * *   Translator::boot($engine);            // once, in RevisitedScene::enter(): the language of the page / the saved choice *   $c->text(Translator::t($label), ...);  // every drawn text (Canvas::text / measure do it: docs/i18n-plan.md) *   Translator::setLang('en');             // the Options row: live, no restart (saved as the option rv_lang) * * Lookup: the cache (one array read: the same texts are drawn every frame), then the dictionary * (assets/revisited/lang/en.php, French => English, + en.hand.php), then the same text in capitals ('EN MAIN'), then the templates * of the dictionary ('Jour {0} sur Ysor' matches 'Jour 12 sur Ysor'; the captured parts are translated in turn: * 'Fouiller : caisse' -> 'Search: crate'), then line by line, else the French text itself. */final class Translator{    public const LANGS = ['fr' => 'Français', 'en' => 'English'];    public const OPTION = 'rv_lang';    private const CACHE_MAX = 4096;    private static string $lang = 'fr';    /** @var array<string, string>|null French => English (non-empty values only) */    private static ?array $dict = null;    /** @var array<string, string> lower-case French => English */    private static array $lower = [];    /** @var array<string, string> text => its translation in the current language */    private static array $cache = [];    /** @var array<string, list<string>> bucket (first two letters of the template's prefix, '*' none) => compiled regexes */    private static array $buckets = [];    /** @var list<array{0: list<list<string>>, 1: string}> per MARK: [capture groups (the placeholder names of each), English template] */    private static array $templates = [];    private static int $depth = 0;    /** @var array<string, true> texts t() gave back: given again (a wrapped line, a measured label), they are kept as they are */    private static array $given = [];    /**     * Picks the language: the player's saved choice (rv_lang), else the site's language choice (the option `lang`),     * else the page's (browser: ?lang= or the browser's language, through JUMPHP_LANG = $engine->lang), else on the     * desktop JUMPHP_LANG or the system's LANG; French when nothing says (the game is written in French).     */    public static function boot(object $engine): string    {        $saved = null;        $site = null;        if (isset($engine->options)) {            $v = $engine->options->get(self::OPTION);            $saved = is_string($v) ? $v : null;            $l = $engine->options->get('lang');            $site = is_string($l) && $l !== '' ? $l : null;        }        $page = null;        if (isset($engine->lang) && method_exists($engine->lang, 'getLang')) {            $page = (string) $engine->lang->getLang();        }        $wasm = defined('JUMPHP_WASM') && JUMPHP_WASM;        $forced = defined('JUMPHP_LANG') || (getenv('JUMPHP_LANG') ?: '') !== '';        if ($site === null && !$wasm && !$forced) {            // the desktop has no page: the system's language (project.yaml lang: en is only the engine's default)            $system = (string) (getenv('LC_ALL') ?: getenv('LC_MESSAGES') ?: getenv('LANG') ?: '');            $page = $system === '' || preg_match('/^(C|POSIX)([._].*)?$/i', $system) ? 'fr' : $system;        }        self::setLang(self::detect($saved, $site ?? $page ?? 'fr'));        return self::$lang;    }    /** The language: the saved choice wins, else the page's / system's ('fr', 'fr-CA', 'fr_FR.UTF-8' -> fr; anything else -> en). */    public static function detect(?string $saved, ?string $page): string    {        if ($saved !== null && isset(self::LANGS[$saved])) {            return $saved;        }        return str_starts_with(strtolower((string) $page), 'fr') ? 'fr' : 'en';    }    public static function lang(): string    {        return self::$lang;    }    public static function setLang(string $lang): void    {        $lang = isset(self::LANGS[$lang]) ? $lang : 'fr';        if ($lang !== self::$lang) {            self::$lang = $lang;            self::$cache = [];            self::$given = [];        }    }    /** Sets the language and remembers it (the Options row). */    public static function choose(object $engine, string $lang): void    {        self::setLang($lang);        if (isset($engine->options)) {            $engine->options->set(self::OPTION, self::$lang);        }    }    /** The next language (the Options row cycles through them). */    public static function next(): string    {        $keys = array_keys(self::LANGS);        return $keys[(array_search(self::$lang, $keys, true) + 1) % count($keys)];    }    /** @param array<string, string>|null $dict null = assets/revisited/lang/en.php (tests give their own) */    public static function load(?array $dict = null): void    {        if ($dict === null) {            $dir = dirname(__DIR__, 3) . '/assets/revisited/lang/';            $dict = is_file($dir . 'en.php') ? (require $dir . 'en.php') : [];            // the texts the extractor does not see, written by hand (en.php wins)            $hand = is_file($dir . 'en.hand.php') ? (require $dir . 'en.hand.php') : [];            $dict = (is_array($dict) ? $dict : []) + array_filter(is_array($hand) ? $hand : [], static fn ($v) => is_string($v) && $v !== '');        }        self::$dict = array_filter($dict, static fn ($v) => is_string($v) && $v !== '');        self::$lower = [];        foreach (self::$dict as $fr => $en) {            self::$lower[mb_strtolower($fr)] ??= $en;        }        self::$cache = [];        self::$given = [];        self::compile();    }    public static function t(string $fr): string    {        if (self::$lang === 'fr' || $fr === '') {            return $fr;        }        if (isset(self::$cache[$fr])) {            return self::$cache[$fr];        }        if (isset(self::$given[$fr])) {            return $fr;        }        if (self::$dict === null) {            self::load();        }        $en = self::lookup($fr);        if (count(self::$cache) >= self::CACHE_MAX) {            self::$cache = [];            self::$given = [];        }        self::$given[$en] = true;        return self::$cache[$fr] = $en;    }    /** A text already in the player's language (a line cut from a translated text): t() gives it back as it is. */    public static function keep(string $text): string    {        if (self::$lang !== 'fr' && $text !== '' && !isset(self::$cache[$text])) {            if (count(self::$given) >= self::CACHE_MAX * 2) {                self::$given = [];            }            self::$given[$text] = true;        }        return $text;    }    /** t() with {name} values, for code that builds its text: Translator::f('Jour {0} sur Ysor', [12]). */    public static function f(string $fr, array $values): string    {        $text = self::$lang === 'fr' ? $fr : self::t($fr);        foreach ($values as $k => $v) {            $text = str_replace('{' . $k . '}', is_string($v) ? self::t($v) : (string) $v, $text);        }        return $text;    }    /** A decimal number in the player's language: 36,6 (fr) / 36.6 (en). */    public static function num(float $v, int $decimals = 1): string    {        return number_format($v, $decimals, self::$lang === 'fr' ? ',' : '.', self::$lang === 'fr' ? ' ' : ',');    }    /** Is there an English text for it (exact, capitals, or a template)? For tests and the coverage report. */    public static function knows(string $fr): bool    {        if (self::$dict === null) {            self::load();        }        $keep = self::$lang;        self::$lang = 'en';        $ok = self::lookup($fr, true) !== null;        self::$lang = $keep;        return $ok;    }    public static function size(): int    {        if (self::$dict === null) {            self::load();        }        return count(self::$dict ?? []);    }    private static function lookup(string $fr, bool $strict = false): ?string    {        $dict = self::$dict ?? [];        if (isset($dict[$fr])) {            return $dict[$fr];        }        // the same text in capitals ('EN MAIN', titles drawn with mb_strtoupper)        $low = mb_strtolower($fr);        if (isset(self::$lower[$low])) {            $en = self::$lower[$low];            if (mb_strtoupper($fr) === $fr) {                return mb_strtoupper($en);            }            // 'caisse' (a lower-case part of a sentence) -> 'crate'            return preg_match('/^\p{Ll}/u', $fr) && !preg_match('/^\p{Lu}{2}/u', $en) ? mb_strtolower(mb_substr($en, 0, 1)) . mb_substr($en, 1) : $en;        }        // spaces around ('  Jour 3  ', ' (infectée)')        $trim = trim($fr);        if ($trim !== $fr && $trim !== '' && isset($dict[$trim])) {            return str_replace($trim, $dict[$trim], $fr);        }        if (self::$depth < 3) {            self::$depth++;            try {                $en = self::template($fr);                if ($en === null && str_contains($fr, "\n")) {                    $en = implode("\n", array_map([self::class, 'lookupLine'], explode("\n", $fr)));                }                $en ??= self::compose($fr);                $en ??= self::pieces($fr);            } finally {                self::$depth--;            }            if ($en !== null) {                return $en;            }        }        return $strict ? null : $fr;    }    /**     * Texts glued by the code without a template: lists and trades ('2 Peau, 1 Os → 1 Ligne de pêche', 'Arc · 1.20 kg'):     * each piece between separators, and a leading count ('2 Peau' -> '2 Hide'). Null when nothing changed.     */    private static function pieces(string $fr): ?string    {        $parts = preg_split('/( → | · |, | — | \/ |: )/u', $fr, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [$fr];        $changed = false;        foreach ($parts as $i => $p) {            if ($i % 2 === 1 || !preg_match('/\p{L}{2}/u', $p)) {                if ($i % 2 === 1 && $p === ': ') {                    $parts[$i] = ': ';                }                continue;            }            $count = '';            $text = $p;            if (preg_match('/^(\s*[×x]?\s*\d+(?:[.,]\d+)?\s*[×x]?\s*)(\p{L}.*)$/u', $p, $m)) {                [$count, $text] = [$m[1], $m[2]];            }            $en = ($count !== '' || count($parts) > 1) ? self::lookup($text, true) : null;            if ($en !== null && $en !== $text) {                $parts[$i] = $count . $en;                $changed = true;            }        }        return $changed ? implode('', $parts) : null;    }    /**     * Texts the code glues from known parts, in the same order in both languages: "Coupure à la tête (saigne)" (a head,     * then groups in brackets), "Morsure au bras gauche : poser un bandage." (two sides of a French colon), "Coupure à la     * tête" (two known halves, short texts only). Null when a part is unknown.     */    private static function compose(string $fr): ?string    {        // decorations: a bullet before, an arrow or a count after ("• Dormir à l'abri", "Entrer dans la grotte ›", "Silex  ×2")        if (preg_match('/^([•·›‹→\-–—]\s*)(\p{L}.*)$/u', $fr, $m)) {            $t = self::known($m[2]);            return $t === null ? null : $m[1] . $t;        }        if (preg_match('/^(.*\p{L}.*?)(\s+(?:[›‹→]|×\s*\d+))$/u', $fr, $m)) {            $t = self::known($m[1]);            return $t === null ? null : $t . $m[2];        }        // a list of parts: "Nourriture, plantes · est"        if (str_contains($fr, ' · ')) {            $out = [];            foreach (explode(' · ', $fr) as $p) {                $t = preg_match('/\p{L}/u', $p) ? self::known($p) : $p;                if ($t === null) {                    return null;                }                $out[] = $t;            }            return implode(' · ', $out);        }        if (preg_match('/^(.+?)((?: \([^()]+\))+)([.!]?)$/u', $fr, $m)) {            $head = self::known($m[1]);            if ($head !== null && preg_match_all('/ \(([^()]+)\)/u', $m[2], $g)) {                $out = $head;                foreach ($g[1] as $in) {                    $t = self::known($in);                    if ($t === null) {                        return null;                    }                    $out .= ' (' . $t . ')';                }                return $out . $m[3];            }            return null;        }        if (str_contains($fr, ' : ')) {            [$a, $b] = explode(' : ', $fr, 2);            $ta = self::known($a);            $tb = $ta === null ? null : self::known($b);            return $ta !== null && $tb !== null ? $ta . ': ' . $tb : null;        }        $words = explode(' ', $fr);        $n = count($words);        if ($n >= 2 && $n <= 6) {            for ($i = 1; $i < $n; $i++) {                $l = self::lookup(implode(' ', array_slice($words, 0, $i)), true);                if ($l === null) {                    continue;                }                $r = self::lookup(implode(' ', array_slice($words, $i)), true);                if ($r !== null) {                    return $l . ' ' . $r;                }            }        }        return null;    }    /** A part of a glued text: known as it is, or without its final full stop, or glued itself. */    private static function known(string $part): ?string    {        $t = null;        if (preg_match('/^(.+?)([.!?…]+)$/u', $part, $m) && isset(self::$dict[$m[1]])) {            $t = self::$dict[$m[1]] . $m[2];        // "poser un bandage." = the known words and the full stop        }        $t ??= self::lookup($part, true);        if ($t === null && preg_match('/^(.+?)([.!?…]+)$/u', $part, $m)) {            $t = self::lookup($m[1], true);            $t = $t === null ? null : $t . $m[2];        }        if ($t === null && self::$depth < 3) {            self::$depth++;            try {                $t = self::compose($part);            } finally {                self::$depth--;            }        }        return $t;    }    private static function lookupLine(string $line): string    {        return $line === '' ? '' : (self::lookup($line) ?? $line);    }    private static function template(string $fr): ?string    {        $key = self::bucketKey($fr);        foreach ([self::$buckets[$key] ?? [], self::$buckets['*'] ?? []] as $regexes) {            foreach ($regexes as $re) {                if (preg_match($re, $fr, $m) !== 1) {                    continue;                }                [$groups, $en] = self::$templates[(int) $m['MARK']];                $repl = [];                foreach ($groups as $i => $names) {                    $v = $m[$i + 1] ?? '';                    if (count($names) === 1) {                        $repl['{' . $names[0] . '}'] = self::part($v);                        continue;                    }                    // '{0}{1}' (a name, then an optional fragment such as ' (il faut une hache)'): the longest known tail                    $head = $v;                    $tail = '';                    for ($cut = 1, $len = mb_strlen($v); $cut < $len; $cut++) {                        $t = mb_substr($v, $cut);                        if (isset(self::$dict[$t])) {                            $head = mb_substr($v, 0, $cut);                            $tail = $t;                            break;                        }                    }                    $repl['{' . $names[0] . '}'] = self::part($head);                    $repl['{' . $names[1] . '}'] = self::part($tail);                }                return strtr($en, $repl);            }        }        return null;    }    /** A captured part: numbers, times and names stay; texts are translated (an item's name, a part of the body). */    private static function part(string $v): string    {        return preg_match('/\p{L}/u', $v) ? (self::lookup($v) ?? $v) : $v;    }    private static function bucketKey(string $s): string    {        return mb_strtolower(mb_substr($s, 0, 2));    }    /**     * Builds the template regexes: one alternation per bucket (branch reset groups, MARK = the template). Fragments     * ('Attaquer ', ' (il faut une hache)') are templates too: 'Attaquer {0}', '{0} (il faut une hache)'.     */    private static function compile(): void    {        self::$templates = [];        $parts = [];        $list = [];        foreach (self::$dict ?? [] as $fr => $en) {            $fr = (string) $fr;            if (preg_match('/\{\w+\}/', $fr)) {                $list[$fr] = $en;            } elseif (preg_match('/\p{L}/u', $fr) && trim($fr) !== $fr) {                if (rtrim($fr) !== $fr) {                    $list[$fr . '{_t}'] ??= $en . '{_t}';                }                if (ltrim($fr) !== $fr) {                    $list['{_h}' . $fr] ??= '{_h}' . $en;                }            }        }        // the most specific first: more literal text wins over a looser template        uksort($list, static fn ($a, $b) => mb_strlen(preg_replace('/\{\w+\}/', '', $b) ?? '') <=> mb_strlen(preg_replace('/\{\w+\}/', '', $a) ?? '') ?: strcmp($a, $b));        foreach ($list as $fr => $en) {            $pieces = preg_split('/\{(\w+)\}/', $fr, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];            if (count($pieces) < 3 || trim(implode('', array_filter($pieces, static fn ($k) => $k % 2 === 0, ARRAY_FILTER_USE_KEY))) === '') {                continue;                     // '{0} {1}': nothing to anchor on            }            $groups = [];            $re = '';            $last = count($pieces) - 1;            foreach ($pieces as $i => $p) {                if ($i % 2 === 0) {                    $re .= preg_quote($p, '/');                } elseif ($i >= 3 && $pieces[$i - 1] === '' && count($groups[count($groups) - 1]) === 1) {                    $groups[count($groups) - 1][] = $p;   // '{0}{1}': one capture, split when matched                } else {                    $groups[] = [$p];                    $re .= ($i === $last - 1 && $pieces[$last] === '') ? '(.+)' : '(.+?)';                }            }            $id = count(self::$templates);            self::$templates[] = [$groups, $en];            $bucket = mb_strlen($pieces[0]) < 2 ? '*' : self::bucketKey($pieces[0]);            $parts[$bucket][] = $re . '(*MARK:' . $id . ')';        }        self::$buckets = [];        foreach ($parts as $bucket => $alts) {            foreach (array_chunk($alts, 80) as $chunk) {                self::$buckets[$bucket][] = '/^(?|' . implode('|', $chunk) . ')$/su';            }        }    }}