blob: 8730945b5be2e41536b88d0d10a570ea06e02c9d [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 Xub97f7e52018-11-12 16:28:14 -080053/** Command line tool to generate the localized image for recovery mode. */
Tianjie Xu721f6792018-10-08 17:04:54 -070054public class ImageGenerator {
Tianjie Xub97f7e52018-11-12 16:28:14 -080055 // Initial height of the image to draw.
56 private static final int INITIAL_HEIGHT = 20000;
Tianjie Xu721f6792018-10-08 17:04:54 -070057
Tianjie Xub97f7e52018-11-12 16:28:14 -080058 private static final float DEFAULT_FONT_SIZE = 40;
Tianjie Xu721f6792018-10-08 17:04:54 -070059
Tianjie Xub97f7e52018-11-12 16:28:14 -080060 // This is the canvas we used to draw texts.
61 private BufferedImage mBufferedImage;
Tianjie Xu721f6792018-10-08 17:04:54 -070062
Tianjie Xub8564e12018-11-12 17:06:14 -080063 // The width in pixels of our image. The value will be adjusted once when we calculate the
64 // maximum width to fit the wrapped text strings.
65 private int mImageWidth;
Tianjie Xu721f6792018-10-08 17:04:54 -070066
Tianjie Xub97f7e52018-11-12 16:28:14 -080067 // The current height in pixels of our image. We will adjust the value when drawing more texts.
68 private int mImageHeight;
Tianjie Xu721f6792018-10-08 17:04:54 -070069
Tianjie Xub97f7e52018-11-12 16:28:14 -080070 // The current vertical offset in pixels to draw the top edge of new text strings.
71 private int mVerticalOffset;
Tianjie Xu721f6792018-10-08 17:04:54 -070072
Tianjie Xub97f7e52018-11-12 16:28:14 -080073 // The font size to draw the texts.
74 private final float mFontSize;
Tianjie Xu721f6792018-10-08 17:04:54 -070075
Tianjie Xub97f7e52018-11-12 16:28:14 -080076 // The name description of the text to localize. It's used to find the translated strings in the
77 // resource file.
78 private final String mTextName;
Tianjie Xu721f6792018-10-08 17:04:54 -070079
Tianjie Xub97f7e52018-11-12 16:28:14 -080080 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
81 private final String mFontDirPath;
Tianjie Xu721f6792018-10-08 17:04:54 -070082
Tianjie Xub8564e12018-11-12 17:06:14 -080083 // Align the text in the center of the image.
84 private final boolean mCenterAlignment;
85
Tianjie Xub97f7e52018-11-12 16:28:14 -080086 // An explicit map from language to the font name to use.
87 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
88 // And the language-subtag-registry is found in:
89 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
90 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
91 private static final Map<String, String> LANGUAGE_TO_FONT_MAP =
92 new TreeMap<String, String>() {
93 {
94 put("am", "NotoSansEthiopic-Regular");
95 put("ar", "NotoNaskhArabicUI-Regular");
96 put("as", "NotoSansBengaliUI-Regular");
97 put("bn", "NotoSansBengaliUI-Regular");
98 put("fa", "NotoNaskhArabicUI-Regular");
99 put("gu", "NotoSansGujaratiUI-Regular");
100 put("hi", "NotoSansDevanagariUI-Regular");
101 put("hy", "NotoSansArmenian-Regular");
102 put("iw", "NotoSansHebrew-Regular");
103 put("ja", "NotoSansCJK-Regular");
104 put("ka", "NotoSansGeorgian-Regular");
105 put("ko", "NotoSansCJK-Regular");
106 put("km", "NotoSansKhmerUI-Regular");
107 put("kn", "NotoSansKannadaUI-Regular");
108 put("lo", "NotoSansLaoUI-Regular");
109 put("ml", "NotoSansMalayalamUI-Regular");
110 put("mr", "NotoSansDevanagariUI-Regular");
111 put("my", "NotoSansMyanmarUI-Regular");
112 put("ne", "NotoSansDevanagariUI-Regular");
113 put("or", "NotoSansOriya-Regular");
114 put("pa", "NotoSansGurmukhiUI-Regular");
115 put("si", "NotoSansSinhala-Regular");
116 put("ta", "NotoSansTamilUI-Regular");
117 put("te", "NotoSansTeluguUI-Regular");
118 put("th", "NotoSansThaiUI-Regular");
119 put("ur", "NotoNaskhArabicUI-Regular");
120 put("zh", "NotoSansCJK-Regular");
121 }
122 };
Tianjie Xu721f6792018-10-08 17:04:54 -0700123
Tianjie Xub97f7e52018-11-12 16:28:14 -0800124 // Languages that write from right to left.
125 private static final Set<String> RTL_LANGUAGE =
126 new HashSet<String>() {
127 {
128 add("ar"); // Arabic
129 add("fa"); // Persian
130 add("he"); // Hebrew
131 add("iw"); // Hebrew
132 add("ur"); // Urdu
133 }
134 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700135
Tianjie Xub97f7e52018-11-12 16:28:14 -0800136 // Languages that breaks on arbitrary characters.
Tianjie Xub8564e12018-11-12 17:06:14 -0800137 // TODO(xunchang) switch to icu library if possible. For example, for Thai and Khmer, there is
138 // no space between words; and word breaking is based on grammatical analysis and on word
139 // matching in dictionaries.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800140 private static final Set<String> LOGOGRAM_LANGUAGE =
141 new HashSet<String>() {
142 {
143 add("ja"); // Japanese
144 add("km"); // Khmer
145 add("ko"); // Korean
146 add("lo"); // Lao
Tianjie Xub8564e12018-11-12 17:06:14 -0800147 add("th"); // Thai
Tianjie Xub97f7e52018-11-12 16:28:14 -0800148 add("zh"); // Chinese
149 }
150 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700151
Tianjie Xub97f7e52018-11-12 16:28:14 -0800152 /** Exception to indicate the failure to find the translated text strings. */
153 public static class LocalizedStringNotFoundException extends Exception {
154 public LocalizedStringNotFoundException(String message) {
155 super(message);
156 }
157
158 public LocalizedStringNotFoundException(String message, Throwable cause) {
159 super(message, cause);
160 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700161 }
162
Tianjie Xub97f7e52018-11-12 16:28:14 -0800163 /** Initailizes the fields of the image image. */
Tianjie Xub8564e12018-11-12 17:06:14 -0800164 public ImageGenerator(
165 int initialImageWidth,
166 String textName,
167 float fontSize,
168 String fontDirPath,
169 boolean centerAlignment) {
170 mImageWidth = initialImageWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800171 mImageHeight = INITIAL_HEIGHT;
172 mVerticalOffset = 0;
Tianjie Xu721f6792018-10-08 17:04:54 -0700173
Tianjie Xub97f7e52018-11-12 16:28:14 -0800174 // Initialize the canvas with the default height.
175 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xu721f6792018-10-08 17:04:54 -0700176
Tianjie Xub97f7e52018-11-12 16:28:14 -0800177 mTextName = textName;
178 mFontSize = fontSize;
179 mFontDirPath = fontDirPath;
Tianjie Xub8564e12018-11-12 17:06:14 -0800180
181 mCenterAlignment = centerAlignment;
Tianjie Xu721f6792018-10-08 17:04:54 -0700182 }
183
Tianjie Xub97f7e52018-11-12 16:28:14 -0800184 /**
185 * Finds the translated text string for the given textName by parsing the resourceFile. Example
186 * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android">
187 * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate
188 * wird installiert"</string> </resources>
189 *
190 * @param resourceFile the input resource file in xml format.
191 * @param textName the name description of the text.
192 * @return the string representation of the translated text.
193 */
194 private String getTextString(File resourceFile, String textName)
195 throws IOException, ParserConfigurationException, org.xml.sax.SAXException,
196 LocalizedStringNotFoundException {
197 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
198 DocumentBuilder db = builder.newDocumentBuilder();
Tianjie Xu721f6792018-10-08 17:04:54 -0700199
Tianjie Xub97f7e52018-11-12 16:28:14 -0800200 Document doc = db.parse(resourceFile);
201 doc.getDocumentElement().normalize();
Tianjie Xu721f6792018-10-08 17:04:54 -0700202
Tianjie Xub97f7e52018-11-12 16:28:14 -0800203 NodeList nodeList = doc.getElementsByTagName("string");
204 for (int i = 0; i < nodeList.getLength(); i++) {
205 Node node = nodeList.item(i);
206 String name = node.getAttributes().getNamedItem("name").getNodeValue();
207 if (name.equals(textName)) {
208 return node.getTextContent();
209 }
210 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700211
Tianjie Xu721f6792018-10-08 17:04:54 -0700212 throw new LocalizedStringNotFoundException(
Tianjie Xub97f7e52018-11-12 16:28:14 -0800213 textName + " not found in " + resourceFile.getName());
Tianjie Xu721f6792018-10-08 17:04:54 -0700214 }
215
Tianjie Xub97f7e52018-11-12 16:28:14 -0800216 /** Constructs the locale from the name of the resource file. */
217 private Locale getLocaleFromFilename(String filename) throws IOException {
218 // Gets the locale string by trimming the top "values-".
219 String localeString = filename.substring(7);
220 if (localeString.matches("[A-Za-z]+")) {
221 return Locale.forLanguageTag(localeString);
222 }
223 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
224 // "${Language}-r${Region}". e.g. en-rGB
225 String[] tokens = localeString.split("-r");
226 return Locale.forLanguageTag(String.join("-", tokens));
227 }
228 if (localeString.startsWith("b+")) {
229 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
230 String[] tokens = localeString.substring(2).split("\\+");
231 return Locale.forLanguageTag(String.join("-", tokens));
232 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700233
Tianjie Xub97f7e52018-11-12 16:28:14 -0800234 throw new IOException("Unrecognized locale string " + localeString);
Tianjie Xu721f6792018-10-08 17:04:54 -0700235 }
236
Tianjie Xub97f7e52018-11-12 16:28:14 -0800237 /**
238 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
239 * directory and collect the translated text.
240 *
241 * @param resourcePath the path to the resource directory
242 * @return a map with the locale as key, and translated text as value
243 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
244 * locale
245 */
246 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath)
247 throws IOException, LocalizedStringNotFoundException {
248 File resourceDir = new File(resourcePath);
249 if (!resourceDir.isDirectory()) {
250 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
251 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700252
Tianjie Xub97f7e52018-11-12 16:28:14 -0800253 Map<Locale, String> result =
254 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus
255 // recovery can find the most relevant locale when going down the list.
256 new TreeMap<>(
257 (Locale l1, Locale l2) -> {
258 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
259 return 0;
260 }
261 if (l1.getLanguage().equals(l2.toLanguageTag())) {
262 return -1;
263 }
264 if (l2.getLanguage().equals(l1.toLanguageTag())) {
265 return 1;
266 }
267 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
268 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700269
Tianjie Xub97f7e52018-11-12 16:28:14 -0800270 // Find all the localized resource subdirectories in the format of values-$LOCALE
271 String[] nameList =
272 resourceDir.list((File file, String name) -> name.startsWith("values-"));
273 for (String name : nameList) {
274 File textFile = new File(resourcePath, name + "/strings.xml");
275 String localizedText;
276 try {
277 localizedText = getTextString(textFile, mTextName);
278 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
279 throw new LocalizedStringNotFoundException(
280 "Failed to read the translated text for locale " + name, e);
281 }
282
283 Locale locale = getLocaleFromFilename(name);
284 // Removes the double quotation mark from the text.
285 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
286 }
287
288 return result;
289 }
290
291 /**
292 * Returns a font object associated given the given locale
293 *
294 * @throws IOException if the font file fails to open
295 * @throws FontFormatException if the font file doesn't have the expected format
296 */
297 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
298 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
299 String[] suffixes = {".otf", ".ttf", ".ttc"};
300 for (String suffix : suffixes) {
301 File fontFile = new File(mFontDirPath, fontName + suffix);
302 if (fontFile.isFile()) {
303 return Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
304 }
305 }
306
307 throw new IOException(
308 "Can not find the font file " + fontName + " for language " + language);
309 }
310
311 /** Separates the text string by spaces and wraps it by words. */
312 private List<String> wrapTextByWords(String text, FontMetrics metrics) {
313 List<String> wrappedText = new ArrayList<>();
314 StringTokenizer st = new StringTokenizer(text, " \n");
315
Tianjie Xub97f7e52018-11-12 16:28:14 -0800316 StringBuilder line = new StringBuilder();
317 while (st.hasMoreTokens()) {
318 String token = st.nextToken();
319 if (metrics.stringWidth(line + token + " ") > mImageWidth) {
320 wrappedText.add(line.toString());
321 line = new StringBuilder();
322 }
323 line.append(token).append(" ");
324 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700325 wrappedText.add(line.toString());
Tianjie Xub97f7e52018-11-12 16:28:14 -0800326
327 return wrappedText;
Tianjie Xu721f6792018-10-08 17:04:54 -0700328 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700329
Tianjie Xub97f7e52018-11-12 16:28:14 -0800330 /** One character is a word for CJK. */
331 private List<String> wrapTextByCharacters(String text, FontMetrics metrics) {
332 List<String> wrappedText = new ArrayList<>();
Tianjie Xu721f6792018-10-08 17:04:54 -0700333
Tianjie Xub97f7e52018-11-12 16:28:14 -0800334 StringBuilder line = new StringBuilder();
335 for (char token : text.toCharArray()) {
336 if (metrics.stringWidth(line + Character.toString(token)) > mImageWidth) {
337 wrappedText.add(line.toString());
338 line = new StringBuilder();
339 }
340 line.append(token);
341 }
Tianjie Xu22dd0192018-10-17 15:39:00 -0700342 wrappedText.add(line.toString());
Tianjie Xu22dd0192018-10-17 15:39:00 -0700343
Tianjie Xub97f7e52018-11-12 16:28:14 -0800344 return wrappedText;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700345 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700346
Tianjie Xub97f7e52018-11-12 16:28:14 -0800347 /**
348 * Wraps the text with a maximum of mImageWidth pixels per line.
349 *
350 * @param text the string representation of text to wrap
351 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
352 * the text given its string representation
353 * @return a list of strings with their width smaller than mImageWidth pixels
354 */
355 private List<String> wrapText(String text, FontMetrics metrics, String language) {
356 if (LOGOGRAM_LANGUAGE.contains(language)) {
357 return wrapTextByCharacters(text, metrics);
358 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700359
Tianjie Xub97f7e52018-11-12 16:28:14 -0800360 return wrapTextByWords(text, metrics);
Tianjie Xu721f6792018-10-08 17:04:54 -0700361 }
Tianjie Xu22dd0192018-10-17 15:39:00 -0700362
Tianjie Xub97f7e52018-11-12 16:28:14 -0800363 /**
364 * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the
365 * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h =
366 * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc =
367 * reinterpret_cast<char*>(&row[5]);
368 */
369 private List<Integer> encodeTextInfo(int width, int height, String locale) {
370 List<Integer> info =
371 new ArrayList<>(
372 Arrays.asList(
373 width & 0xff,
374 width >> 8,
375 height & 0xff,
376 height >> 8,
377 locale.length()));
Tianjie Xu721f6792018-10-08 17:04:54 -0700378
Tianjie Xub97f7e52018-11-12 16:28:14 -0800379 byte[] localeBytes = locale.getBytes();
380 for (byte b : localeBytes) {
381 info.add((int) b);
382 }
383 info.add(0);
Tianjie Xu721f6792018-10-08 17:04:54 -0700384
Tianjie Xub97f7e52018-11-12 16:28:14 -0800385 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700386 }
387
Tianjie Xub8564e12018-11-12 17:06:14 -0800388 /** Returns Graphics2D object that uses the given locale. */
389 private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException {
390 Graphics2D graphics = mBufferedImage.createGraphics();
391 graphics.setColor(Color.WHITE);
392 graphics.setRenderingHint(
393 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
394 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
395
396 return graphics;
397 }
398
399 /** Returns the maximum screen width needed to fit the given text after wrapping. */
400 private int measureTextWidth(String text, Locale locale)
401 throws IOException, FontFormatException {
402 Graphics2D graphics = createGraphics(locale);
403 FontMetrics fontMetrics = graphics.getFontMetrics();
404 List<String> wrappedText = wrapText(text, fontMetrics, locale.getLanguage());
405
406 int textWidth = 0;
407 for (String line : wrappedText) {
408 textWidth = Math.max(textWidth, fontMetrics.stringWidth(line));
409 }
410
411 // This may happen if one single word is larger than the image width.
412 if (textWidth > mImageWidth) {
413 throw new IllegalStateException(
414 "Wrapped text width "
415 + textWidth
416 + " is larger than image width "
417 + mImageWidth
418 + " for locale: "
419 + locale);
420 }
421
422 return textWidth;
423 }
424
Tianjie Xub97f7e52018-11-12 16:28:14 -0800425 /**
426 * Draws the text string on the canvas for given locale.
427 *
428 * @param text the string to draw on canvas
429 * @param locale the current locale tag of the string to draw
430 * @throws IOException if we cannot find the corresponding font file for the given locale.
431 * @throws FontFormatException if we failed to load the font file for the given locale.
432 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800433 private void drawText(String text, Locale locale, String languageTag)
Tianjie Xub97f7e52018-11-12 16:28:14 -0800434 throws IOException, FontFormatException {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800435 System.out.println("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
436
Tianjie Xub8564e12018-11-12 17:06:14 -0800437 Graphics2D graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800438 FontMetrics fontMetrics = graphics.getFontMetrics();
439 List<String> wrappedText = wrapText(text, fontMetrics, locale.getLanguage());
440
441 // Marks the start y offset for the text image of current locale; and reserves one line to
442 // encode the image metadata.
443 int currentImageStart = mVerticalOffset;
444 mVerticalOffset += 1;
445 for (String line : wrappedText) {
446 int lineHeight = fontMetrics.getHeight();
447 // Doubles the height of the image if we are short of space.
448 if (mVerticalOffset + lineHeight >= mImageHeight) {
Tianjie Xub8564e12018-11-12 17:06:14 -0800449 resize(mImageWidth, mImageHeight * 2);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800450 }
451
452 // Draws the text at mVerticalOffset and increments the offset with line space.
453 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
454
455 // Draws from right if it's an RTL language.
456 int x =
Tianjie Xub8564e12018-11-12 17:06:14 -0800457 mCenterAlignment
Tianjie Xub97f7e52018-11-12 16:28:14 -0800458 ? (mImageWidth - fontMetrics.stringWidth(line)) / 2
459 : RTL_LANGUAGE.contains(languageTag)
460 ? mImageWidth - fontMetrics.stringWidth(line)
461 : 0;
462
463 graphics.drawString(line, x, baseLine);
464
465 mVerticalOffset += lineHeight;
466 }
467
468 // Encodes the metadata of the current localized image as pixels.
469 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
470 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
471 for (int i = 0; i < info.size(); i++) {
472 int[] pixel = {info.get(i)};
473 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
474 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700475 }
476
Tianjie Xub97f7e52018-11-12 16:28:14 -0800477 /**
Tianjie Xub8564e12018-11-12 17:06:14 -0800478 * Redraws the image with the new width and new height.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800479 *
Tianjie Xub8564e12018-11-12 17:06:14 -0800480 * @param width the new width of the image in pixels.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800481 * @param height the new height of the image in pixels.
482 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800483 private void resize(int width, int height) {
484 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800485 Graphics2D graphic = resizedImage.createGraphics();
486 graphic.drawImage(mBufferedImage, 0, 0, null);
487 graphic.dispose();
Tianjie Xu721f6792018-10-08 17:04:54 -0700488
Tianjie Xub97f7e52018-11-12 16:28:14 -0800489 mBufferedImage = resizedImage;
Tianjie Xub8564e12018-11-12 17:06:14 -0800490 mImageWidth = width;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800491 mImageHeight = height;
Tianjie Xu721f6792018-10-08 17:04:54 -0700492 }
493
Tianjie Xub97f7e52018-11-12 16:28:14 -0800494 /**
495 * This function draws the font characters and saves the result to outputPath.
496 *
497 * @param localizedTextMap a map from locale to its translated text string
498 * @param outputPath the path to write the generated image file.
499 * @throws FontFormatException if there's a format error in one of the font file
500 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
501 * write the image file.
502 */
503 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath)
504 throws FontFormatException, IOException {
505 Map<String, Integer> languageCount = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800506 int textWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800507 for (Locale locale : localizedTextMap.keySet()) {
508 String language = locale.getLanguage();
509 languageCount.put(language, languageCount.getOrDefault(language, 0) + 1);
Tianjie Xub8564e12018-11-12 17:06:14 -0800510 textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800511 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700512
Tianjie Xub8564e12018-11-12 17:06:14 -0800513 // Removes the black margins to reduce the size of the image.
514 resize(textWidth, mImageHeight);
515
Tianjie Xub97f7e52018-11-12 16:28:14 -0800516 for (Locale locale : localizedTextMap.keySet()) {
517 Integer count = languageCount.get(locale.getLanguage());
518 // Recovery expects en-US instead of en_US.
519 String languageTag = locale.toLanguageTag();
520 if (count == 1) {
521 // Make the last country variant for a given language be the catch-all for that
522 // language.
523 languageTag = locale.getLanguage();
524 } else {
525 languageCount.put(locale.getLanguage(), count - 1);
526 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700527
Tianjie Xub8564e12018-11-12 17:06:14 -0800528 drawText(localizedTextMap.get(locale), locale, languageTag);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800529 }
530
Tianjie Xub8564e12018-11-12 17:06:14 -0800531 resize(mImageWidth, mVerticalOffset);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800532 ImageIO.write(mBufferedImage, "png", new File(outputPath));
533 }
534
535 /** Prints the helper message. */
536 public static void printUsage(Options options) {
537 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
538 }
539
540 /** Creates the command line options. */
541 public static Options createOptions() {
542 Options options = new Options();
543 options.addOption(
544 OptionBuilder.withLongOpt("image_width")
545 .withDescription("The initial width of the image in pixels.")
546 .hasArgs(1)
547 .isRequired()
548 .create());
549
550 options.addOption(
551 OptionBuilder.withLongOpt("text_name")
552 .withDescription(
553 "The description of the text string, e.g. recovery_erasing")
554 .hasArgs(1)
555 .isRequired()
556 .create());
557
558 options.addOption(
559 OptionBuilder.withLongOpt("font_dir")
560 .withDescription(
561 "The directory that contains all the support font format files, "
562 + "e.g. $OUT/system/fonts/")
563 .hasArgs(1)
564 .isRequired()
565 .create());
566
567 options.addOption(
568 OptionBuilder.withLongOpt("resource_dir")
569 .withDescription(
570 "The resource directory that contains all the translated strings in"
571 + " xml format, e.g."
572 + " bootable/recovery/tools/recovery_l10n/res/")
573 .hasArgs(1)
574 .isRequired()
575 .create());
576
577 options.addOption(
578 OptionBuilder.withLongOpt("output_file")
Tianjie Xub8564e12018-11-12 17:06:14 -0800579 .withDescription("Path to the generated image.")
Tianjie Xub97f7e52018-11-12 16:28:14 -0800580 .hasArgs(1)
581 .isRequired()
582 .create());
583
Tianjie Xub8564e12018-11-12 17:06:14 -0800584 options.addOption(
585 OptionBuilder.withLongOpt("center_alignment")
586 .withDescription("Align the text in the center of the screen.")
587 .hasArg(false)
588 .create());
589
Tianjie Xub97f7e52018-11-12 16:28:14 -0800590 return options;
591 }
592
593 /** The main function parses the command line options and generates the desired text image. */
594 public static void main(String[] args)
595 throws NumberFormatException, IOException, FontFormatException,
596 LocalizedStringNotFoundException {
597 Options options = createOptions();
598 CommandLine cmd;
599 try {
600 cmd = new GnuParser().parse(options, args);
601 } catch (ParseException e) {
602 System.err.println(e.getMessage());
603 printUsage(options);
604 return;
605 }
606
607 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
608
609 ImageGenerator imageGenerator =
610 new ImageGenerator(
611 imageWidth,
612 cmd.getOptionValue("text_name"),
613 DEFAULT_FONT_SIZE,
Tianjie Xub8564e12018-11-12 17:06:14 -0800614 cmd.getOptionValue("font_dir"),
615 cmd.hasOption("center_alignment"));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800616
617 Map<Locale, String> localizedStringMap =
618 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"));
619 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
620 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700621}