forked from Airsaid/AndroidLocalizePlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslateTask.java
More file actions
258 lines (224 loc) · 9.24 KB
/
TranslateTask.java
File metadata and controls
258 lines (224 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
* Copyright 2018 Airsaid. https://github.com/airsaid
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package task;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import constant.Constants;
import logic.ParseStringXml;
import module.AndroidString;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import translate.lang.LANG;
import translate.querier.Querier;
import translate.trans.AbstractTranslator;
import translate.trans.impl.GoogleTranslator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* @author airsaid
*/
public class TranslateTask extends Task.Backgroundable {
private List<LANG> mLanguages;
private List<AndroidString> mAndroidStrings;
private VirtualFile mSelectFile;
private Map<String, List<AndroidString>> mWriteData;
private OnTranslateListener mOnTranslateListener;
public interface OnTranslateListener {
void onTranslateSuccess();
void onTranslateError(Throwable e);
}
public TranslateTask(@Nullable Project project, @Nls @NotNull String title, List<LANG> languages,
List<AndroidString> androidStrings, VirtualFile selectFile) {
super(project, title);
this.mLanguages = languages;
this.mAndroidStrings = androidStrings;
this.mSelectFile = selectFile;
this.mWriteData = new HashMap<>();
}
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
boolean isOverwriteExistingString = PropertiesComponent.getInstance(myProject)
.getBoolean(Constants.KEY_IS_OVERWRITE_EXISTING_STRING);
Querier<AbstractTranslator> translator = new Querier<>();
GoogleTranslator googleTranslator = new GoogleTranslator();
translator.attach(googleTranslator);
mWriteData.clear();
for (LANG toLanguage : mLanguages) {
progressIndicator.setText("Translating in the " + toLanguage.getEnglishName() + " language...");
if (isOverwriteExistingString) {
translate(translator, toLanguage, null);
continue;
}
ApplicationManager.getApplication().runReadAction(() -> {
VirtualFile virtualFile = getVirtualFile(toLanguage);
if (virtualFile == null) {
translate(translator, toLanguage, null);
return;
}
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
if (psiFile == null) {
translate(translator, toLanguage, null);
return;
}
List<AndroidString> androidStrings = ParseStringXml.parse(progressIndicator, psiFile);
translate(translator, toLanguage, androidStrings);
});
}
googleTranslator.close();
writeResultData(progressIndicator);
}
private void translate(Querier<AbstractTranslator> translator, LANG toLanguage, @Nullable List<AndroidString> list) {
List<AndroidString> writeAndroidString = new ArrayList<>();
for (AndroidString androidString : mAndroidStrings) {
if (!androidString.isTranslatable()) {
continue;
}
if (list != null && list.contains(androidString)) {
writeAndroidString.add(new AndroidString(
androidString.getName(), list.get(list.indexOf(androidString)).getValue(), false));
continue;
}
translator.setParams(LANG.Auto, toLanguage, androidString.getValue());
String resultValue = translator.executeSingle();
writeAndroidString.add(new AndroidString(androidString.getName(), resultValue, false));
}
mWriteData.put(toLanguage.getCode(), writeAndroidString);
}
private void writeResultData(ProgressIndicator progressIndicator) {
if (mWriteData == null) {
translateError(new IllegalArgumentException("No translate data."));
return;
}
Set<String> keySet = mWriteData.keySet();
for (String key : keySet) {
File writeFile = getWriteFileForCode(key);
progressIndicator.setText("Write to " + writeFile.getParentFile().getName() + " data...");
write(writeFile, mWriteData.get(key));
refreshAndOpenFile(writeFile);
}
}
private VirtualFile getVirtualFile(LANG lang) {
File file = getStringFile(lang.getCode());
return LocalFileSystem.getInstance().findFileByIoFile(file);
}
private File getStringFile(String langCode) {
return getStringFile(langCode, false);
}
private File getStringFile(String langCode, boolean mkdirs) {
String parentPath = mSelectFile.getParent().getParent().getPath();
File stringFile;
if (mkdirs) {
File parentFile = new File(parentPath, getDirNameForCode(langCode));
if (!parentFile.exists()) {
parentFile.mkdirs();
}
stringFile = new File(parentFile, "strings.xml");
if (!stringFile.exists()) {
try {
stringFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
stringFile = new File(parentPath.concat(File.separator).concat(getDirNameForCode(langCode)), "strings.xml");
}
return stringFile;
}
private File getWriteFileForCode(String langCode) {
return getStringFile(langCode, true);
}
private String getDirNameForCode(String langCode) {
String suffix;
if (langCode.equals(LANG.ChineseSimplified.getCode())) {
suffix = "zh-rCN";
} else if (langCode.equals(LANG.ChineseTraditional.getCode())) {
suffix = "zh-rTW";
} else if (langCode.equals(LANG.Filipino.getCode())) {
suffix = "fil";
} else if (langCode.equals(LANG.Indonesian.getCode())) {
suffix = "in-rID";
} else if (langCode.equals(LANG.Javanese.getCode())) {
suffix = "jv";
} else {
suffix = langCode;
}
return "values-".concat(suffix);
}
private void write(File file, List<AndroidString> androidStrings) {
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), StandardCharsets.UTF_8))) {
bw.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
bw.newLine();
bw.write("<resources>");
bw.newLine();
for (AndroidString androidString : androidStrings) {
bw.write("\t<string name=\"" + androidString.getName() + "\">" + androidString.getValue() + "</string>");
bw.newLine();
}
bw.write("</resources>");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}));
}
private void refreshAndOpenFile(File file) {
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
if (virtualFile != null) {
ApplicationManager.getApplication().invokeLater(() ->
FileEditorManager.getInstance(myProject).openFile(virtualFile, true));
}
}
@Override
public void onSuccess() {
super.onSuccess();
translateSuccess();
}
@Override
public void onThrowable(@NotNull Throwable error) {
super.onThrowable(error);
translateError(error);
}
private void translateSuccess() {
if (mOnTranslateListener != null) {
mOnTranslateListener.onTranslateSuccess();
}
}
private void translateError(Throwable error) {
if (mOnTranslateListener != null) {
mOnTranslateListener.onTranslateError(error);
}
}
/**
* Set translate result listener.
*
* @param listener callback interface. success or fail.
*/
public void setOnTranslateListener(OnTranslateListener listener) {
this.mOnTranslateListener = listener;
}
}