Language.java 7.21 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;
Secretboy's avatar
Secretboy committed
6
import emu.grasscutter.game.player.Player;
7
8
9

import javax.annotation.Nullable;
import java.io.InputStream;
Secretboy-SMR's avatar
Secretboy-SMR committed
10
import java.util.concurrent.ConcurrentHashMap;
11
12
import java.util.Map;

13
14
import static emu.grasscutter.Configuration.*;

15
public final class Language {
16
17
    private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
    
18
    private final JsonObject languageData;
Secretboy's avatar
Secretboy committed
19
    private final String languageCode;
Secretboy-SMR's avatar
Secretboy-SMR committed
20
    private final Map<String, String> cachedTranslations = new ConcurrentHashMap<>();
21
22
23
24
25
26
27

    /**
     * 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
28
29
30
31
        if (cachedLanguages.containsKey(langCode)) {
            return cachedLanguages.get(langCode);
        }

32
33
        var fallbackLanguageCode = Utils.getLanguageCode(FALLBACK_LANGUAGE);
        var description = getLanguageFileDescription(langCode, fallbackLanguageCode);
34
        var actualLanguageCode = description.getLanguageCode();
Secretboy's avatar
Secretboy committed
35

36
37
38
        Language languageInst;
        if (description.getLanguageFile() != null) {
            languageInst = new Language(description);
Secretboy's avatar
Secretboy committed
39
            cachedLanguages.put(actualLanguageCode, languageInst);
40
        } else {
Secretboy's avatar
Secretboy committed
41
42
43
44
            languageInst = cachedLanguages.get(actualLanguageCode);
            cachedLanguages.put(langCode, languageInst);
        }

Secretboy-SMR's avatar
Secretboy-SMR committed
45
        return languageInst;
46
47
48
49
50
51
52
53
54
    }

    /**
     * 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
55
        String translated = Grasscutter.getLanguage().get(key);
56
        
KingRainbow44's avatar
KingRainbow44 committed
57
58
59
60
61
62
        try {
            return translated.formatted(args);
        } catch (Exception exception) {
            Grasscutter.getLogger().error("Failed to format string: " + key, exception);
            return translated;
        }
63
64
    }

Secretboy's avatar
Secretboy committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    /**
     * 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());
        String translated = Grasscutter.getLanguage(langCode).get(key);
        
        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
95
96
97
    /**
     * Reads a file and creates a language instance.
     */
98
    private Language(LanguageStreamDescription description) {
Secretboy's avatar
Secretboy committed
99
        @Nullable JsonObject languageData = null;
100
        languageCode = description.getLanguageCode();
Secretboy's avatar
Secretboy committed
101
102
        
        try {
103
            languageData = Grasscutter.getGsonFactory().fromJson(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
Secretboy's avatar
Secretboy committed
104
        } catch (Exception exception) {
105
            Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
Secretboy's avatar
Secretboy committed
106
107
108
109
110
111
        }
        
        this.languageData = languageData;
    }

    /**
112
     * create a LanguageStreamDescription
Secretboy's avatar
Secretboy committed
113
114
115
     * @param languageCode The name of the language code.
     * @param fallbackLanguageCode The name of the fallback language code.
     */
116
    private static LanguageStreamDescription getLanguageFileDescription(String languageCode, String fallbackLanguageCode) {
Secretboy's avatar
Secretboy committed
117
118
        var fileName = languageCode + ".json";
        var fallback = fallbackLanguageCode + ".json";
119

Secretboy's avatar
Secretboy committed
120
121
        String actualLanguageCode = languageCode;
        if (cachedLanguages.containsKey(actualLanguageCode)) {
122
            return new LanguageStreamDescription(actualLanguageCode, null);
Secretboy's avatar
Secretboy committed
123
        }
124
        
125
        InputStream file = Grasscutter.class.getResourceAsStream("/languages/" + fileName);
Secretboy's avatar
Secretboy committed
126

127
        if (file == null) { // Provided fallback language.
Secretboy's avatar
Secretboy committed
128
129
            actualLanguageCode = fallbackLanguageCode;
            if (cachedLanguages.containsKey(actualLanguageCode)) {
130
                return new LanguageStreamDescription(actualLanguageCode, null);
Secretboy's avatar
Secretboy committed
131
            }
132
            
133
            file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
134
135
            Grasscutter.getLogger().warn("Failed to load language file: " + fileName + ", falling back to: " + fallback);
        }
Secretboy's avatar
Secretboy committed
136

137
        if(file == null) { // Fallback the fallback language.
Secretboy's avatar
Secretboy committed
138
139
            actualLanguageCode = "en-US";
            if (cachedLanguages.containsKey(actualLanguageCode)) {
140
                return new LanguageStreamDescription(actualLanguageCode, null);
Secretboy's avatar
Secretboy committed
141
            }
142
            
143
            file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
144
145
            Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
        }
Secretboy's avatar
Secretboy committed
146

147
148
        if(file == null)
            throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
Secretboy's avatar
Secretboy committed
149

150
        return new LanguageStreamDescription(actualLanguageCode, file);
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    }

    /**
     * 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) {
        if(this.cachedTranslations.containsKey(key)) {
            return this.cachedTranslations.get(key);
        }
        
        String[] keys = key.split("\\.");
        JsonObject object = this.languageData;

        int index = 0;
167
        String result = "This value does not exist. Please report this to the Discord: " + key;
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

        while (true) {
            if(index == keys.length) break;
            
            String currentKey = keys[index++];
            if(object.has(currentKey)) {
                JsonElement element = object.get(currentKey);
                if(element.isJsonObject())
                    object = element.getAsJsonObject();
                else {
                    result = element.getAsString(); break;
                }
            } else break;
        }
        
        this.cachedTranslations.put(key, result); return result;
    }
Secretboy's avatar
Secretboy committed
185

186
187
188
    private static class LanguageStreamDescription {
        private final String languageCode;
        private final InputStream languageFile;
Secretboy's avatar
Secretboy committed
189

190
        public LanguageStreamDescription(String languageCode, InputStream languageFile) {
Secretboy's avatar
Secretboy committed
191
192
193
194
195
196
197
198
199
200
201
202
            this.languageCode = languageCode;
            this.languageFile = languageFile;
        }

        public String getLanguageCode() {
            return languageCode;
        }

        public InputStream getLanguageFile() {
            return languageFile;
        }
    }
203
}