Language.java 18.9 KB
Newer Older
1
2
3
4
5
package emu.grasscutter.utils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import emu.grasscutter.Grasscutter;
AnimeGitB's avatar
AnimeGitB committed
6
7
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.ResourceLoader;
Secretboy's avatar
Secretboy committed
8
import emu.grasscutter.game.player.Player;
AnimeGitB's avatar
AnimeGitB committed
9
10
11
12
13
14
15
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.EqualsAndHashCode;
16
17

import javax.annotation.Nullable;
18
19
20

import static emu.grasscutter.config.Configuration.*;

AnimeGitB's avatar
AnimeGitB committed
21
22
23
24
25
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
26
import java.io.InputStream;
AnimeGitB's avatar
AnimeGitB committed
27
28
29
30
31
32
33
34
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
Secretboy-SMR's avatar
Secretboy-SMR committed
35
import java.util.concurrent.ConcurrentHashMap;
AnimeGitB's avatar
AnimeGitB committed
36
37
38
39
40
41
42
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
43
44
45
import java.util.Map;

public final class Language {
46
    private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
github-actions's avatar
github-actions committed
47

48
    private final JsonObject languageData;
Secretboy's avatar
Secretboy committed
49
    private final String languageCode;
Secretboy-SMR's avatar
Secretboy-SMR committed
50
    private final Map<String, String> cachedTranslations = new ConcurrentHashMap<>();
51
52
53
54
55
56
57

    /**
     * Creates a language instance from a code.
     * @param langCode The language code.
     * @return A language instance.
     */
    public static Language getLanguage(String langCode) {
Secretboy-SMR's avatar
Secretboy-SMR committed
58
59
60
61
        if (cachedLanguages.containsKey(langCode)) {
            return cachedLanguages.get(langCode);
        }

62
63
        var fallbackLanguageCode = Utils.getLanguageCode(FALLBACK_LANGUAGE);
        var description = getLanguageFileDescription(langCode, fallbackLanguageCode);
64
        var actualLanguageCode = description.getLanguageCode();
Secretboy's avatar
Secretboy committed
65

66
67
68
        Language languageInst;
        if (description.getLanguageFile() != null) {
            languageInst = new Language(description);
Secretboy's avatar
Secretboy committed
69
            cachedLanguages.put(actualLanguageCode, languageInst);
70
        } else {
Secretboy's avatar
Secretboy committed
71
72
73
74
            languageInst = cachedLanguages.get(actualLanguageCode);
            cachedLanguages.put(langCode, languageInst);
        }

Secretboy-SMR's avatar
Secretboy-SMR committed
75
        return languageInst;
76
77
78
79
80
81
82
83
84
    }

    /**
     * Returns the translated value from the key while substituting arguments.
     * @param key The key of the translated value to return.
     * @param args The arguments to substitute.
     * @return A translated value with arguments substituted.
     */
    public static String translate(String key, Object... args) {
KingRainbow44's avatar
KingRainbow44 committed
85
        String translated = Grasscutter.getLanguage().get(key);
github-actions's avatar
github-actions committed
86

AnimeGitB's avatar
AnimeGitB committed
87
88
89
90
91
92
93
94
        for (int i = 0; i < args.length; i++) {
            args[i] = switch(args[i].getClass().getSimpleName()) {
                case "String" -> args[i];
                case "TextStrings" -> ((TextStrings) args[i]).get(0).replace("\\\\n", "\\n");  // TODO: Change this to server language
                default -> args[i].toString();
            };
        }

KingRainbow44's avatar
KingRainbow44 committed
95
96
97
98
99
100
        try {
            return translated.formatted(args);
        } catch (Exception exception) {
            Grasscutter.getLogger().error("Failed to format string: " + key, exception);
            return translated;
        }
101
102
    }

Secretboy's avatar
Secretboy committed
103
104
105
106
107
108
109
110
111
112
113
114
115
    /**
     * Returns the translated value from the key while substituting arguments.
     * @param player Target player
     * @param key The key of the translated value to return.
     * @param args The arguments to substitute.
     * @return A translated value with arguments substituted.
     */
    public static String translate(Player player, String key, Object... args) {
        if (player == null) {
            return translate(key, args);
        }

        var langCode = Utils.getLanguageCode(player.getAccount().getLocale());
116
        String translated = getLanguage(langCode).get(key);
github-actions's avatar
github-actions committed
117

AnimeGitB's avatar
AnimeGitB committed
118
119
120
121
122
123
124
125
        for (int i = 0; i < args.length; i++) {
            args[i] = switch(args[i].getClass().getSimpleName()) {
                case "String" -> args[i];
                case "TextStrings" -> ((TextStrings) args[i]).getGC(langCode).replace("\\\\n", "\n");  // Note that we don't unescape \n for server console
                default -> args[i].toString();
            };
        }

Secretboy's avatar
Secretboy committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        try {
            return translated.formatted(args);
        } catch (Exception exception) {
            Grasscutter.getLogger().error("Failed to format string: " + key, exception);
            return translated;
        }
    }

    /**
     * get language code
     */
    public String getLanguageCode() {
        return languageCode;
    }

Secretboy's avatar
Secretboy committed
141
142
143
    /**
     * Reads a file and creates a language instance.
     */
144
    private Language(LanguageStreamDescription description) {
Secretboy's avatar
Secretboy committed
145
        @Nullable JsonObject languageData = null;
146
        languageCode = description.getLanguageCode();
github-actions's avatar
github-actions committed
147

Secretboy's avatar
Secretboy committed
148
        try {
149
            languageData = JsonUtils.decode(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
Secretboy's avatar
Secretboy committed
150
        } catch (Exception exception) {
151
            Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
Secretboy's avatar
Secretboy committed
152
        }
github-actions's avatar
github-actions committed
153

Secretboy's avatar
Secretboy committed
154
155
156
157
        this.languageData = languageData;
    }

    /**
158
     * create a LanguageStreamDescription
Secretboy's avatar
Secretboy committed
159
160
161
     * @param languageCode The name of the language code.
     * @param fallbackLanguageCode The name of the fallback language code.
     */
162
    private static LanguageStreamDescription getLanguageFileDescription(String languageCode, String fallbackLanguageCode) {
Secretboy's avatar
Secretboy committed
163
164
        var fileName = languageCode + ".json";
        var fallback = fallbackLanguageCode + ".json";
github-actions's avatar
github-actions committed
165

166
        String actualLanguageCode = languageCode;
167
        InputStream file = Grasscutter.class.getResourceAsStream("/languages/" + fileName);
Secretboy's avatar
Secretboy committed
168

169
        if (file == null) { // Provided fallback language.
170
            Grasscutter.getLogger().warn("Failed to load language file: " + fileName + ", falling back to: " + fallback);
Secretboy's avatar
Secretboy committed
171
172
            actualLanguageCode = fallbackLanguageCode;
            if (cachedLanguages.containsKey(actualLanguageCode)) {
173
                return new LanguageStreamDescription(actualLanguageCode, null);
Secretboy's avatar
Secretboy committed
174
            }
github-actions's avatar
github-actions committed
175

176
            file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
177
        }
Secretboy's avatar
Secretboy committed
178

github-actions's avatar
github-actions committed
179
        if (file == null) { // Fallback the fallback language.
180
            Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
Secretboy's avatar
Secretboy committed
181
182
            actualLanguageCode = "en-US";
            if (cachedLanguages.containsKey(actualLanguageCode)) {
183
                return new LanguageStreamDescription(actualLanguageCode, null);
Secretboy's avatar
Secretboy committed
184
            }
github-actions's avatar
github-actions committed
185

186
            file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
187
        }
Secretboy's avatar
Secretboy committed
188

github-actions's avatar
github-actions committed
189
        if (file == null)
190
            throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
Secretboy's avatar
Secretboy committed
191

192
        return new LanguageStreamDescription(actualLanguageCode, file);
193
194
195
196
197
198
199
200
    }

    /**
     * Returns the value (as a string) from a nested key.
     * @param key The key to look for.
     * @return The value (as a string) from a nested key.
     */
    public String get(String key) {
github-actions's avatar
github-actions committed
201
        if (this.cachedTranslations.containsKey(key)) {
202
203
            return this.cachedTranslations.get(key);
        }
github-actions's avatar
github-actions committed
204

205
206
207
208
        String[] keys = key.split("\\.");
        JsonObject object = this.languageData;

        int index = 0;
209
210
211
        String valueNotFoundPattern = "This value does not exist. Please report this to the Discord: ";
        String result = valueNotFoundPattern + key;
        boolean isValueFound = false;
212
213

        while (true) {
github-actions's avatar
github-actions committed
214
215
            if (index == keys.length) break;

216
            String currentKey = keys[index++];
github-actions's avatar
github-actions committed
217
            if (object.has(currentKey)) {
218
                JsonElement element = object.get(currentKey);
github-actions's avatar
github-actions committed
219
                if (element.isJsonObject())
220
221
                    object = element.getAsJsonObject();
                else {
222
                    isValueFound = true;
223
224
225
226
                    result = element.getAsString(); break;
                }
            } else break;
        }
227
228

        if (!isValueFound && !languageCode.equals("en-US")) {
229
            var englishValue = getLanguage("en-US").get(key);
230
231
232
233
            if (!englishValue.contains(valueNotFoundPattern)) {
                result += "\nhere is english version:\n" + englishValue;
            }
        }
github-actions's avatar
github-actions committed
234

235
236
        this.cachedTranslations.put(key, result); return result;
    }
Secretboy's avatar
Secretboy committed
237

238
239
240
    private static class LanguageStreamDescription {
        private final String languageCode;
        private final InputStream languageFile;
Secretboy's avatar
Secretboy committed
241

242
        public LanguageStreamDescription(String languageCode, InputStream languageFile) {
Secretboy's avatar
Secretboy committed
243
244
245
246
247
248
249
250
251
252
253
254
            this.languageCode = languageCode;
            this.languageFile = languageFile;
        }

        public String getLanguageCode() {
            return languageCode;
        }

        public InputStream getLanguageFile() {
            return languageFile;
        }
    }
AnimeGitB's avatar
AnimeGitB committed
255
256
257
258

    private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE02;
    @EqualsAndHashCode public static class TextStrings implements Serializable {
        public static final String[] ARR_LANGUAGES = {"EN", "CHS", "CHT", "JP", "KR", "DE", "ES", "FR", "ID", "PT", "RU", "TH", "VI"};
259
        public static final String[] ARR_GC_LANGUAGES = {"en-US", "zh-CN", "zh-TW", "en-US", "ko-KR", "en-US", "es-ES", "fr-FR", "en-US", "en-US", "ru-RU", "en-US", "en-US"};  // TODO: Update the placeholder en-US entries if we ever add GC translations for the missing client languages
AnimeGitB's avatar
AnimeGitB committed
260
261
262
263
264
265
266
        public static final int NUM_LANGUAGES = ARR_LANGUAGES.length;
        public static final List<String> LIST_LANGUAGES = Arrays.asList(ARR_LANGUAGES);
        public static final Object2IntMap<String> MAP_LANGUAGES =  // Map "EN": 0, "CHS": 1, ..., "VI": 12
            new Object2IntOpenHashMap<>(
                IntStream.range(0, ARR_LANGUAGES.length)
                .boxed()
                .collect(Collectors.toMap(i -> ARR_LANGUAGES[i], i -> i)));
AnimeGitB's avatar
AnimeGitB committed
267
268
269
270
271
        public static final Object2IntMap<String> MAP_GC_LANGUAGES =  // Map "en-US": 0, "zh-CN": 1, ...
            new Object2IntOpenHashMap<>(
                IntStream.range(0, ARR_GC_LANGUAGES.length)
                .boxed()
                .collect(Collectors.toMap(i -> ARR_GC_LANGUAGES[i], i -> i, (i1, i2) -> i1)));  // Have to handle duplicates referring back to the first
AnimeGitB's avatar
AnimeGitB committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        public String[] strings = new String[ARR_LANGUAGES.length];

        public TextStrings() {};

        public TextStrings(String init) {
            for (int i = 0; i < NUM_LANGUAGES; i++)
                this.strings[i] = init;
        };

        public TextStrings(List<String> strings, int key) {
            // Some hashes don't have strings for some languages :(
            String nullReplacement = "[N/A] %d".formatted((long) key & 0xFFFFFFFFL);
            for (int i = 0; i < NUM_LANGUAGES; i++) {  // Find first non-null if there is any
                String s = strings.get(i);
                if (s != null) {
                    nullReplacement = "[%s] - %s".formatted(ARR_LANGUAGES[i], s);
                    break;
                }
            }
            for (int i = 0; i < NUM_LANGUAGES; i++) {
                String s = strings.get(i);
                if (s != null)
                    this.strings[i] = s;
                else
                    this.strings[i] = nullReplacement;
            }
        }

300
301
302
303
304
305
306
307
        public static List<Language> getLanguages() {
            return Arrays.stream(ARR_GC_LANGUAGES).map(Language::getLanguage).toList();
        }

        public String get(int languageIndex) {
            return strings[languageIndex];
        }

AnimeGitB's avatar
AnimeGitB committed
308
309
310
311
        public String get(String languageCode) {
            return strings[MAP_LANGUAGES.getOrDefault(languageCode, 0)];
        }

AnimeGitB's avatar
AnimeGitB committed
312
313
314
315
        public String getGC(String languageCode) {
            return strings[MAP_GC_LANGUAGES.getOrDefault(languageCode, 0)];
        }

AnimeGitB's avatar
AnimeGitB committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        public boolean set(String languageCode, String string) {
            int index = MAP_LANGUAGES.getOrDefault(languageCode, -1);
            if (index < 0) return false;
            strings[index] = string;
            return true;
        }
    }

    private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");

    private static Int2ObjectMap<String> loadTextMapFile(String language, IntSet nameHashes) {
        Int2ObjectMap<String> output = new Int2ObjectOpenHashMap<>();
        try (BufferedReader file = new BufferedReader(new FileReader(Utils.toFilePath(RESOURCE("TextMap/TextMap"+language+".json")), StandardCharsets.UTF_8))) {
            Matcher matcher = textMapKeyValueRegex.matcher("");
            return new Int2ObjectOpenHashMap<>(
                file.lines()
                    .sequential()
                    .map(matcher::reset)  // Side effects, but it's faster than making a new one
                    .filter(Matcher::find)
                    .filter(m -> nameHashes.contains((int) Long.parseLong(m.group(1))))  // TODO: Cache this parse somehow
                    .collect(Collectors.toMap(
                        m -> (int) Long.parseLong(m.group(1)),
                        m -> m.group(2).replace("\\\"", "\""))));
        } catch (Exception e) {
            Grasscutter.getLogger().error("Error loading textmap: " + language);
            Grasscutter.getLogger().error(e.toString());
        }
        return output;
    }

    private static Int2ObjectMap<TextStrings> loadTextMapFiles(IntSet nameHashes) {
        Map<Integer, Int2ObjectMap<String>> mapLanguageMaps =  // Separate step to process the textmaps in parallel
            TextStrings.LIST_LANGUAGES.parallelStream().collect(
            Collectors.toConcurrentMap(s -> TextStrings.MAP_LANGUAGES.getInt(s), s -> loadTextMapFile(s, nameHashes)));
        List<Int2ObjectMap<String>> languageMaps = 
            IntStream.range(0, TextStrings.NUM_LANGUAGES)
            .mapToObj(i -> mapLanguageMaps.get(i))
            .collect(Collectors.toList());

        Map<TextStrings, TextStrings> canonicalTextStrings = new HashMap<>();
        return new Int2ObjectOpenHashMap<TextStrings>(
            nameHashes
            .intStream()
            .boxed()
            .collect(Collectors.toMap(key -> key, key -> {
                TextStrings t = new TextStrings(
                    IntStream.range(0, TextStrings.NUM_LANGUAGES)
                    .mapToObj(i -> languageMaps.get(i).get((int) key))
                    .collect(Collectors.toList()), (int) key);
                return canonicalTextStrings.computeIfAbsent(t, x -> t);
                }))
            );
    }

    private static Int2ObjectMap<TextStrings> loadTextMapsCache() throws Exception {
        try (ObjectInputStream file = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(TEXTMAP_CACHE_PATH), 0x100000))) {
            final int fileVersion = file.readInt();
            if (fileVersion != TEXTMAP_CACHE_VERSION)
                throw new Exception("Invalid cache version");
            return (Int2ObjectMap<TextStrings>) file.readObject();
        }
    }

    private static void saveTextMapsCache(Int2ObjectMap<TextStrings> input) throws IOException {
        try {
            Files.createDirectory(Path.of("cache"));
        } catch (FileAlreadyExistsException ignored) {};
        try (ObjectOutputStream file = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(TEXTMAP_CACHE_PATH, StandardOpenOption.CREATE), 0x100000))) {
            file.writeInt(TEXTMAP_CACHE_VERSION);
            file.writeObject(input);
        }
    }

    private static Int2ObjectMap<TextStrings> textMapStrings;
    private static final Path TEXTMAP_CACHE_PATH = Path.of(Utils.toFilePath("cache/TextMapCache.bin"));

    public static Int2ObjectMap<TextStrings> getTextMapStrings() {
        if (textMapStrings == null)
            loadTextMaps();
        return textMapStrings;
    }

    public static TextStrings getTextMapKey(long hash) {
AnimeGitB's avatar
AnimeGitB committed
399
400
        if (textMapStrings == null)
            loadTextMaps();
AnimeGitB's avatar
AnimeGitB committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        return textMapStrings.get((int) hash);
    }

    public static void loadTextMaps() {
        // Check system timestamps on cache and resources
        try {
            long cacheModified = Files.getLastModifiedTime(TEXTMAP_CACHE_PATH).toMillis();

            long textmapsModified = Files.list(Path.of(RESOURCE("TextMap")))
                .filter(path -> path.toString().endsWith(".json"))
                .map(path -> {
                    try {
                        return Files.getLastModifiedTime(path).toMillis();
                    } catch (Exception ignored) {
                        Grasscutter.getLogger().debug("Exception while checking modified time: ", path);
                        return Long.MAX_VALUE;  // Don't use cache, something has gone wrong
                    }
                })
                .max(Long::compare)
                .get();

                Grasscutter.getLogger().debug("Cache modified %d, textmap modified %d".formatted(cacheModified, textmapsModified));
            if (textmapsModified < cacheModified) {
                // Try loading from cache
                Grasscutter.getLogger().info("Loading cached TextMaps");
                textMapStrings = loadTextMapsCache();
                return;
            }
        } catch (Exception e) {
            Grasscutter.getLogger().debug("Exception while checking cache: ", e);
        };

        // Regenerate cache
        Grasscutter.getLogger().info("Generating TextMaps cache");
        ResourceLoader.loadAll();
        IntSet usedHashes = new IntOpenHashSet();
        GameData.getAvatarDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
AnimeGitB's avatar
AnimeGitB committed
438
439
440
        GameData.getAvatarSkillDataMap().forEach((k, v) -> {
            usedHashes.add((int) v.getNameTextMapHash());
        });
AnimeGitB's avatar
AnimeGitB committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
        GameData.getItemDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
        GameData.getMonsterDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
        GameData.getMainQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getTitleTextMapHash()));
        GameData.getQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getDescTextMapHash()));
        // Incidental strings
        usedHashes.add((int) 4233146695L);  // Character
        usedHashes.add((int) 4231343903L);  // Weapon
        usedHashes.add((int)  332935371L);  // Standard Wish
        usedHashes.add((int) 2272170627L);  // Character Event Wish
        usedHashes.add((int) 3352513147L);  // Character Event Wish-2
        usedHashes.add((int) 2864268523L);  // Weapon Event Wish

        textMapStrings = loadTextMapFiles(usedHashes);
        try {
            saveTextMapsCache(textMapStrings);
        } catch (IOException e) {
            Grasscutter.getLogger().error("Failed to save TextMap cache: ", e);
        };
    }
460
}