blob: 8cdd4944a19812e8ad0446ce9dad47664f01677c [file] [log] [blame]
Tianjie Xu721f6792018-10-08 17:04:54 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.recovery.tools;
18
Tao Bao529bb742018-11-06 11:24:53 -080019import org.apache.commons.cli.CommandLine;
20import org.apache.commons.cli.GnuParser;
21import org.apache.commons.cli.HelpFormatter;
22import org.apache.commons.cli.OptionBuilder;
23import org.apache.commons.cli.Options;
24import org.apache.commons.cli.ParseException;
25import org.w3c.dom.Document;
26import org.w3c.dom.Node;
27import org.w3c.dom.NodeList;
28
Tianjie Xu721f6792018-10-08 17:04:54 -070029import java.awt.Color;
30import java.awt.Font;
31import java.awt.FontFormatException;
32import java.awt.FontMetrics;
33import java.awt.Graphics2D;
34import java.awt.RenderingHints;
35import java.awt.image.BufferedImage;
36import java.io.File;
37import java.io.IOException;
38import java.util.ArrayList;
Tianjie Xu22dd0192018-10-17 15:39:00 -070039import java.util.Arrays;
40import java.util.HashSet;
Tianjie Xu721f6792018-10-08 17:04:54 -070041import java.util.List;
42import java.util.Locale;
43import java.util.Map;
Tianjie Xu22dd0192018-10-17 15:39:00 -070044import java.util.Set;
Tianjie Xu721f6792018-10-08 17:04:54 -070045import java.util.StringTokenizer;
Tao Bao529bb742018-11-06 11:24:53 -080046import java.util.TreeMap;
Tianjie Xu721f6792018-10-08 17:04:54 -070047
48import javax.imageio.ImageIO;
49import javax.xml.parsers.DocumentBuilder;
50import javax.xml.parsers.DocumentBuilderFactory;
51import javax.xml.parsers.ParserConfigurationException;
52
Tianjie Xu721f6792018-10-08 17:04:54 -070053/**
54 * Command line tool to generate the localized image for recovery mode.
55 */
56public class ImageGenerator {
57 // Initial height of the image to draw.
58 private static final int INITIAL_HEIGHT = 20000;
59
60 private static final float DEFAULT_FONT_SIZE = 40;
61
62 // This is the canvas we used to draw texts.
63 private BufferedImage mBufferedImage;
64
65 // The width in pixels of our image. Once set, its value won't change.
66 private final int mImageWidth;
67
68 // The current height in pixels of our image. We will adjust the value when drawing more texts.
69 private int mImageHeight;
70
71 // The current vertical offset in pixels to draw the top edge of new text strings.
72 private int mVerticalOffset;
73
74 // The font size to draw the texts.
75 private final float mFontSize;
76
77 // The name description of the text to localize. It's used to find the translated strings in the
78 // resource file.
79 private final String mTextName;
80
81 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
82 private final String mFontDirPath;
83
84 // An explicit map from language to the font name to use.
85 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
86 // And the language-subtag-registry is found in:
87 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
88 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
89 private static final Map<String, String> LANGUAGE_TO_FONT_MAP = new TreeMap<String, String>() {{
90 put("am", "NotoSansEthiopic-Regular");
91 put("ar", "NotoNaskhArabicUI-Regular");
92 put("as", "NotoSansBengaliUI-Regular");
93 put("bn", "NotoSansBengaliUI-Regular");
94 put("fa", "NotoNaskhArabicUI-Regular");
95 put("gu", "NotoSansGujaratiUI-Regular");
96 put("hi", "NotoSansDevanagariUI-Regular");
97 put("hy", "NotoSansArmenian-Regular");
98 put("iw", "NotoSansHebrew-Regular");
99 put("ja", "NotoSansCJK-Regular");
100 put("ka", "NotoSansGeorgian-Regular");
101 put("ko", "NotoSansCJK-Regular");
102 put("km", "NotoSansKhmerUI-Regular");
103 put("kn", "NotoSansKannadaUI-Regular");
104 put("lo", "NotoSansLaoUI-Regular");
105 put("ml", "NotoSansMalayalamUI-Regular");
106 put("mr", "NotoSansDevanagariUI-Regular");
107 put("my", "NotoSansMyanmarUI-Regular");
108 put("ne", "NotoSansDevanagariUI-Regular");
109 put("or", "NotoSansOriya-Regular");
110 put("pa", "NotoSansGurmukhiUI-Regular");
111 put("si", "NotoSansSinhala-Regular");
112 put("ta", "NotoSansTamilUI-Regular");
113 put("te", "NotoSansTeluguUI-Regular");
114 put("th", "NotoSansThaiUI-Regular");
115 put("ur", "NotoNaskhArabicUI-Regular");
116 put("zh", "NotoSansCJK-Regular");
117 }};
118
Tianjie Xu22dd0192018-10-17 15:39:00 -0700119 // Languages that write from right to left.
120 private static final Set<String> RTL_LANGUAGE = new HashSet<String>() {{
121 add("ar"); // Arabic
122 add("fa"); // Persian
123 add("he"); // Hebrew
124 add("iw"); // Hebrew
125 add("ur"); // Urdu
126 }};
127
128 // Languages that breaks on arbitrary characters.
129 // TODO(xunchang) switch to icu library if possible.
130 private static final Set<String> LOGOGRAM_LANGUAGE = new HashSet<String>() {{
131 add("ja"); // Japanese
132 add("km"); // Khmer
133 add("ko"); // Korean
134 add("lo"); // Lao
135 add("zh"); // Chinese
136 }};
137
Tianjie Xu721f6792018-10-08 17:04:54 -0700138 /**
139 * Exception to indicate the failure to find the translated text strings.
140 */
141 public static class LocalizedStringNotFoundException extends Exception {
142 public LocalizedStringNotFoundException(String message) {
143 super(message);
144 }
145
146 public LocalizedStringNotFoundException(String message, Throwable cause) {
147 super(message, cause);
148 }
149 }
150
151 /**
152 * Initailizes the fields of the image image.
153 */
154 public ImageGenerator(int imageWidth, String textName, float fontSize, String fontDirPath) {
155 mImageWidth = imageWidth;
156 mImageHeight = INITIAL_HEIGHT;
157 mVerticalOffset = 0;
158
159 // Initialize the canvas with the default height.
160 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
161
162 mTextName = textName;
163 mFontSize = fontSize;
164 mFontDirPath = fontDirPath;
165 }
166
167 /**
168 * Finds the translated text string for the given textName by parsing the resourceFile.
169 * Example of the xml fields:
170 * <resources xmlns:android="http://schemas.android.com/apk/res/android">
171 * <string name="recovery_installing_security" msgid="9184031299717114342">
172 * "Sicherheitsupdate wird installiert"</string>
173 * </resources>
174 *
175 * @param resourceFile the input resource file in xml format.
176 * @param textName the name description of the text.
177 *
178 * @return the string representation of the translated text.
179 */
180 private String getTextString(File resourceFile, String textName) throws IOException,
181 ParserConfigurationException, org.xml.sax.SAXException, LocalizedStringNotFoundException {
182 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
183 DocumentBuilder db = builder.newDocumentBuilder();
184
185 Document doc = db.parse(resourceFile);
186 doc.getDocumentElement().normalize();
187
188 NodeList nodeList = doc.getElementsByTagName("string");
189 for (int i = 0; i < nodeList.getLength(); i++) {
190 Node node = nodeList.item(i);
191 String name = node.getAttributes().getNamedItem("name").getNodeValue();
192 if (name.equals(textName)) {
193 return node.getTextContent();
194 }
195 }
196
197 throw new LocalizedStringNotFoundException(textName + " not found in "
198 + resourceFile.getName());
199 }
200
201 /**
202 * Constructs the locale from the name of the resource file.
203 */
204 private Locale getLocaleFromFilename(String filename) throws IOException {
205 // Gets the locale string by trimming the top "values-".
206 String localeString = filename.substring(7);
207 if (localeString.matches("[A-Za-z]+")) {
208 return Locale.forLanguageTag(localeString);
209 }
210 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
211 // "${Language}-r${Region}". e.g. en-rGB
212 String[] tokens = localeString.split("-r");
213 return Locale.forLanguageTag(String.join("-", tokens));
214 }
215 if (localeString.startsWith("b+")) {
216 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
217 String[] tokens = localeString.substring(2).split("\\+");
218 return Locale.forLanguageTag(String.join("-", tokens));
219 }
220
221 throw new IOException("Unrecognized locale string " + localeString);
222 }
223
224 /**
225 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
226 * directory and collect the translated text.
227 *
228 * @param resourcePath the path to the resource directory
229 *
230 * @return a map with the locale as key, and translated text as value
231 *
232 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
233 * locale
234 **/
235 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath) throws
236 IOException, LocalizedStringNotFoundException {
237 File resourceDir = new File(resourcePath);
238 if (!resourceDir.isDirectory()) {
239 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
240 }
241
242 Map<Locale, String> result =
Tianjie Xu22dd0192018-10-17 15:39:00 -0700243 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus recovery
244 // can find the most relevant locale when going down the list.
245 new TreeMap<>((Locale l1, Locale l2) -> {
246 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
247 return 0;
248 }
249 if (l1.getLanguage().equals(l2.toLanguageTag())) {
250 return -1;
251 }
252 if (l2.getLanguage().equals(l1.toLanguageTag())) {
253 return 1;
254 }
255 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
256 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700257
258 // Find all the localized resource subdirectories in the format of values-$LOCALE
259 String[] nameList = resourceDir.list(
260 (File file, String name) -> name.startsWith("values-"));
261 for (String name : nameList) {
262 File textFile = new File(resourcePath, name + "/strings.xml");
263 String localizedText;
264 try {
265 localizedText = getTextString(textFile, mTextName);
266 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
267 throw new LocalizedStringNotFoundException(
268 "Failed to read the translated text for locale " + name, e);
269 }
270
271 Locale locale = getLocaleFromFilename(name);
272 // Removes the double quotation mark from the text.
273 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
274 }
275
276 return result;
277 }
278
279 /**
280 * Returns a font object associated given the given locale
281 *
282 * @throws IOException if the font file fails to open
283 * @throws FontFormatException if the font file doesn't have the expected format
284 */
285 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
286 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
287 String[] suffixes = {".otf", ".ttf", ".ttc"};
288 for (String suffix : suffixes ) {
289 File fontFile = new File(mFontDirPath, fontName + suffix);
290 if (fontFile.isFile()) {
291 return Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
292 }
293 }
294
295 throw new IOException("Can not find the font file " + fontName + " for language " + language);
296 }
297
298 /**
299 * Separates the text string by spaces and wraps it by words.
300 **/
301 private List<String> wrapTextByWords(String text, FontMetrics metrics) {
302 List<String> wrappedText = new ArrayList<>();
303 StringTokenizer st = new StringTokenizer(text, " \n");
304
Tianjie Xu22dd0192018-10-17 15:39:00 -0700305 // TODO(xunchang). We assume that all words can fit on the screen. Raise an
306 // IllegalStateException if the word is wider than the image width.
Tianjie Xu721f6792018-10-08 17:04:54 -0700307 StringBuilder line = new StringBuilder();
308 while (st.hasMoreTokens()) {
309 String token = st.nextToken();
310 if (metrics.stringWidth(line + token + " ") > mImageWidth) {
311 wrappedText.add(line.toString());
312 line = new StringBuilder();
313 }
314 line.append(token).append(" ");
315 }
316 wrappedText.add(line.toString());
317
318 return wrappedText;
319 }
320
321 /**
Tianjie Xu22dd0192018-10-17 15:39:00 -0700322 * One character is a word for CJK.
323 */
324 private List<String> wrapTextByCharacters(String text, FontMetrics metrics) {
325 List<String> wrappedText = new ArrayList<>();
326
327 StringBuilder line = new StringBuilder();
328 for (char token : text.toCharArray()) {
329 if (metrics.stringWidth(line + Character.toString(token)) > mImageWidth) {
330 wrappedText.add(line.toString());
331 line = new StringBuilder();
332 }
333 line.append(token);
334 }
335 wrappedText.add(line.toString());
336
337 return wrappedText;
338 }
339
340 /**
Tianjie Xu721f6792018-10-08 17:04:54 -0700341 * Wraps the text with a maximum of mImageWidth pixels per line.
342 *
343 * @param text the string representation of text to wrap
344 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
345 * the text given its string representation
346 *
347 * @return a list of strings with their width smaller than mImageWidth pixels
348 */
Tianjie Xu22dd0192018-10-17 15:39:00 -0700349 private List<String> wrapText(String text, FontMetrics metrics, String language) {
350 if (LOGOGRAM_LANGUAGE.contains(language)) {
351 return wrapTextByCharacters(text, metrics);
352 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700353
354 return wrapTextByWords(text, metrics);
355 }
356
357 /**
Tianjie Xu22dd0192018-10-17 15:39:00 -0700358 * Encodes the information of the text image for |locale|.
359 * According to minui/resources.cpp, the width, height and locale of the image is decoded as:
360 * int w = (row[1] << 8) | row[0];
361 * int h = (row[3] << 8) | row[2];
362 * __unused int len = row[4];
363 * char* loc = reinterpret_cast<char*>(&row[5]);
364 */
365 private List<Integer> encodeTextInfo(int width, int height, String locale) {
366 List<Integer> info = new ArrayList<>(Arrays.asList(width & 0xff, width >> 8,
367 height & 0xff, height >> 8, locale.length()));
368
369 byte[] localeBytes = locale.getBytes();
370 for (byte b: localeBytes) {
371 info.add((int)b);
372 }
373 info.add(0);
374
375 return info;
376 }
377
378 /**
Tianjie Xu721f6792018-10-08 17:04:54 -0700379 * Draws the text string on the canvas for given locale.
380 *
381 * @param text the string to draw on canvas
382 * @param locale the current locale tag of the string to draw
383 *
384 * @throws IOException if we cannot find the corresponding font file for the given locale.
385 * @throws FontFormatException if we failed to load the font file for the given locale.
386 */
Tianjie Xu22dd0192018-10-17 15:39:00 -0700387 private void drawText(String text, Locale locale, String languageTag, boolean centralAlignment)
388 throws IOException, FontFormatException {
Tianjie Xu721f6792018-10-08 17:04:54 -0700389 Graphics2D graphics = mBufferedImage.createGraphics();
390 graphics.setColor(Color.WHITE);
391 graphics.setRenderingHint(
392 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
393 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
394
Tianjie Xu22dd0192018-10-17 15:39:00 -0700395 System.out.println("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
Tianjie Xu721f6792018-10-08 17:04:54 -0700396
397 FontMetrics fontMetrics = graphics.getFontMetrics();
Tianjie Xu22dd0192018-10-17 15:39:00 -0700398 List<String> wrappedText = wrapText(text, fontMetrics, locale.getLanguage());
399
400 // Marks the start y offset for the text image of current locale; and reserves one line to
401 // encode the image metadata.
402 int currentImageStart = mVerticalOffset;
403 mVerticalOffset += 1;
Tianjie Xu721f6792018-10-08 17:04:54 -0700404 for (String line : wrappedText) {
405 int lineHeight = fontMetrics.getHeight();
406 // Doubles the height of the image if we are short of space.
407 if (mVerticalOffset + lineHeight >= mImageHeight) {
408 resizeHeight(mImageHeight * 2);
409 }
410
411 // Draws the text at mVerticalOffset and increments the offset with line space.
412 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
Tianjie Xu22dd0192018-10-17 15:39:00 -0700413
414 // Draws from right if it's an RTL language.
415 int x = centralAlignment ? (mImageWidth - fontMetrics.stringWidth(line)) / 2 :
416 RTL_LANGUAGE.contains(languageTag) ? mImageWidth - fontMetrics.stringWidth(line) : 0;
417
418 graphics.drawString(line, x, baseLine);
419
Tianjie Xu721f6792018-10-08 17:04:54 -0700420 mVerticalOffset += lineHeight;
421 }
Tianjie Xu22dd0192018-10-17 15:39:00 -0700422
423 // Encodes the metadata of the current localized image as pixels.
424 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
425 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
426 for (int i = 0; i < info.size(); i++) {
427 int pixel[] = { info.get(i) };
428 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
429 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700430 }
431
432 /**
433 * Redraws the image with the new height.
434 *
435 * @param height the new height of the image in pixels.
436 */
437 private void resizeHeight(int height) {
438 BufferedImage resizedImage =
439 new BufferedImage(mImageWidth, height, BufferedImage.TYPE_BYTE_GRAY);
440 Graphics2D graphic = resizedImage.createGraphics();
441 graphic.drawImage(mBufferedImage, 0, 0, null);
442 graphic.dispose();
443
444 mBufferedImage = resizedImage;
445 mImageHeight = height;
446 }
447
448 /**
449 * This function draws the font characters and saves the result to outputPath.
450 *
451 * @param localizedTextMap a map from locale to its translated text string
452 * @param outputPath the path to write the generated image file.
453 *
454 * @throws FontFormatException if there's a format error in one of the font file
455 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
456 * write the image file.
457 */
458 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath) throws
459 FontFormatException, IOException {
Tianjie Xu22dd0192018-10-17 15:39:00 -0700460 Map<String, Integer> languageCount = new TreeMap<>();
Tianjie Xu721f6792018-10-08 17:04:54 -0700461 for (Locale locale : localizedTextMap.keySet()) {
Tianjie Xu22dd0192018-10-17 15:39:00 -0700462 String language = locale.getLanguage();
463 languageCount.put(language, languageCount.getOrDefault(language, 0) + 1 );
464 }
465
466 for (Locale locale : localizedTextMap.keySet()) {
467 Integer count = languageCount.get(locale.getLanguage());
468 // Recovery expects en-US instead of en_US.
469 String languageTag = locale.toLanguageTag();
470 if (count == 1) {
471 // Make the last country variant for a given language be the catch-all for that language.
472 languageTag = locale.getLanguage();
473 } else {
474 languageCount.put(locale.getLanguage(), count - 1);
475 }
476
477 drawText(localizedTextMap.get(locale), locale, languageTag, false);
Tianjie Xu721f6792018-10-08 17:04:54 -0700478 }
479
480 // TODO(xunchang) adjust the width to save some space if all texts are smaller than imageWidth.
481 resizeHeight(mVerticalOffset);
482 ImageIO.write(mBufferedImage, "png", new File(outputPath));
483 }
484
Tianjie Xuedfeb972018-10-23 12:40:14 -0700485 public static void printUsage(Options options) {
486 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
487
488 }
489
490 public static Options createOptions() {
491 Options options = new Options();
492 options.addOption(OptionBuilder
493 .withLongOpt("image_width")
494 .withDescription("The initial width of the image in pixels.")
495 .hasArgs(1)
496 .isRequired()
497 .create());
498
499 options.addOption(OptionBuilder
500 .withLongOpt("text_name")
501 .withDescription("The description of the text string, e.g. recovery_erasing")
502 .hasArgs(1)
503 .isRequired()
504 .create());
505
506 options.addOption(OptionBuilder
507 .withLongOpt("font_dir")
508 .withDescription("The directory that contains all the support font format files, e.g."
509 + " $OUT/system/fonts/")
510 .hasArgs(1)
511 .isRequired()
512 .create());
513
514 options.addOption(OptionBuilder
515 .withLongOpt("resource_dir")
516 .withDescription("The resource directory that contains all the translated strings in xml"
517 + " format, e.g. bootable/recovery/tools/recovery_l10n/res/")
518 .hasArgs(1)
519 .isRequired()
520 .create());
521
522 options.addOption(OptionBuilder
523 .withLongOpt("output_file")
524 .withDescription("Path to the generated image")
525 .hasArgs(1)
526 .isRequired()
527 .create());
528
529 return options;
Tianjie Xu721f6792018-10-08 17:04:54 -0700530 }
531
532 public static void main(String[] args) throws NumberFormatException, IOException,
533 FontFormatException, LocalizedStringNotFoundException {
Tianjie Xuedfeb972018-10-23 12:40:14 -0700534 Options options = createOptions();
535 CommandLine cmd;
536 try {
537 cmd = new GnuParser().parse(options, args);
538 } catch (ParseException e) {
539 System.err.println(e.getMessage());
540 printUsage(options);
541 return;
Tianjie Xu721f6792018-10-08 17:04:54 -0700542 }
543
Tianjie Xuedfeb972018-10-23 12:40:14 -0700544 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
Tianjie Xu721f6792018-10-08 17:04:54 -0700545
Tianjie Xuedfeb972018-10-23 12:40:14 -0700546 ImageGenerator imageGenerator = new ImageGenerator(imageWidth, cmd.getOptionValue("text_name"),
547 DEFAULT_FONT_SIZE, cmd.getOptionValue("font_dir"));
Tianjie Xu721f6792018-10-08 17:04:54 -0700548
549 Map<Locale, String> localizedStringMap =
Tianjie Xuedfeb972018-10-23 12:40:14 -0700550 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"));
551 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
Tianjie Xu721f6792018-10-08 17:04:54 -0700552 }
553}