blob: 0a1c85b59c0f1830a63fe194027e1e08e5104a9f [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;
Tianjie Xu542c6172018-11-13 16:36:41 -080035import java.awt.font.TextAttribute;
Tianjie Xu721f6792018-10-08 17:04:54 -070036import java.awt.image.BufferedImage;
37import java.io.File;
38import java.io.IOException;
Tianjie Xu542c6172018-11-13 16:36:41 -080039import java.text.AttributedString;
Tianjie Xu721f6792018-10-08 17:04:54 -070040import java.util.ArrayList;
Tianjie Xu22dd0192018-10-17 15:39:00 -070041import java.util.Arrays;
42import java.util.HashSet;
Tianjie Xu721f6792018-10-08 17:04:54 -070043import java.util.List;
44import java.util.Locale;
45import java.util.Map;
Tianjie Xu22dd0192018-10-17 15:39:00 -070046import java.util.Set;
Tianjie Xu721f6792018-10-08 17:04:54 -070047import java.util.StringTokenizer;
Tao Bao529bb742018-11-06 11:24:53 -080048import java.util.TreeMap;
Tianjie Xu721f6792018-10-08 17:04:54 -070049
50import javax.imageio.ImageIO;
51import javax.xml.parsers.DocumentBuilder;
52import javax.xml.parsers.DocumentBuilderFactory;
53import javax.xml.parsers.ParserConfigurationException;
54
Tianjie Xub97f7e52018-11-12 16:28:14 -080055/** Command line tool to generate the localized image for recovery mode. */
Tianjie Xu721f6792018-10-08 17:04:54 -070056public class ImageGenerator {
Tianjie Xub97f7e52018-11-12 16:28:14 -080057 // Initial height of the image to draw.
58 private static final int INITIAL_HEIGHT = 20000;
Tianjie Xu721f6792018-10-08 17:04:54 -070059
Tianjie Xub97f7e52018-11-12 16:28:14 -080060 private static final float DEFAULT_FONT_SIZE = 40;
Tianjie Xu721f6792018-10-08 17:04:54 -070061
Tianjie Xub97f7e52018-11-12 16:28:14 -080062 // This is the canvas we used to draw texts.
63 private BufferedImage mBufferedImage;
Tianjie Xu721f6792018-10-08 17:04:54 -070064
Tianjie Xub8564e12018-11-12 17:06:14 -080065 // The width in pixels of our image. The value will be adjusted once when we calculate the
66 // maximum width to fit the wrapped text strings.
67 private int mImageWidth;
Tianjie Xu721f6792018-10-08 17:04:54 -070068
Tianjie Xub97f7e52018-11-12 16:28:14 -080069 // The current height in pixels of our image. We will adjust the value when drawing more texts.
70 private int mImageHeight;
Tianjie Xu721f6792018-10-08 17:04:54 -070071
Tianjie Xub97f7e52018-11-12 16:28:14 -080072 // The current vertical offset in pixels to draw the top edge of new text strings.
73 private int mVerticalOffset;
Tianjie Xu721f6792018-10-08 17:04:54 -070074
Tianjie Xub97f7e52018-11-12 16:28:14 -080075 // The font size to draw the texts.
76 private final float mFontSize;
Tianjie Xu721f6792018-10-08 17:04:54 -070077
Tianjie Xub97f7e52018-11-12 16:28:14 -080078 // The name description of the text to localize. It's used to find the translated strings in the
79 // resource file.
80 private final String mTextName;
Tianjie Xu721f6792018-10-08 17:04:54 -070081
Tianjie Xub97f7e52018-11-12 16:28:14 -080082 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
83 private final String mFontDirPath;
Tianjie Xu721f6792018-10-08 17:04:54 -070084
Tianjie Xub8564e12018-11-12 17:06:14 -080085 // Align the text in the center of the image.
86 private final boolean mCenterAlignment;
87
Tianjie Xu542c6172018-11-13 16:36:41 -080088 // Some localized font cannot draw the word "Android" and some PUNCTUATIONS; we need to fall
89 // back to use our default latin font instead.
90 private static final char[] PUNCTUATIONS = {',', ';', '.', '!' };
91
92 private static final String ANDROID_STRING = "Android";
93
94 // The width of the word "Android" when drawing with the default font.
95 private int mAndroidStringWidth;
96
97 // The default Font to draw latin characters. It's loaded from DEFAULT_FONT_NAME.
98 private Font mDefaultFont;
99 // Cache of the loaded fonts for all languages.
100 private Map<String, Font> mLoadedFontMap;
101
Tianjie Xub97f7e52018-11-12 16:28:14 -0800102 // An explicit map from language to the font name to use.
103 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
104 // And the language-subtag-registry is found in:
105 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
106 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
107 private static final Map<String, String> LANGUAGE_TO_FONT_MAP =
108 new TreeMap<String, String>() {
109 {
110 put("am", "NotoSansEthiopic-Regular");
111 put("ar", "NotoNaskhArabicUI-Regular");
112 put("as", "NotoSansBengaliUI-Regular");
113 put("bn", "NotoSansBengaliUI-Regular");
114 put("fa", "NotoNaskhArabicUI-Regular");
115 put("gu", "NotoSansGujaratiUI-Regular");
116 put("hi", "NotoSansDevanagariUI-Regular");
117 put("hy", "NotoSansArmenian-Regular");
118 put("iw", "NotoSansHebrew-Regular");
119 put("ja", "NotoSansCJK-Regular");
120 put("ka", "NotoSansGeorgian-Regular");
121 put("ko", "NotoSansCJK-Regular");
122 put("km", "NotoSansKhmerUI-Regular");
123 put("kn", "NotoSansKannadaUI-Regular");
124 put("lo", "NotoSansLaoUI-Regular");
125 put("ml", "NotoSansMalayalamUI-Regular");
126 put("mr", "NotoSansDevanagariUI-Regular");
127 put("my", "NotoSansMyanmarUI-Regular");
128 put("ne", "NotoSansDevanagariUI-Regular");
129 put("or", "NotoSansOriya-Regular");
130 put("pa", "NotoSansGurmukhiUI-Regular");
131 put("si", "NotoSansSinhala-Regular");
132 put("ta", "NotoSansTamilUI-Regular");
133 put("te", "NotoSansTeluguUI-Regular");
134 put("th", "NotoSansThaiUI-Regular");
135 put("ur", "NotoNaskhArabicUI-Regular");
136 put("zh", "NotoSansCJK-Regular");
137 }
138 };
Tianjie Xu721f6792018-10-08 17:04:54 -0700139
Tianjie Xub97f7e52018-11-12 16:28:14 -0800140 // Languages that write from right to left.
141 private static final Set<String> RTL_LANGUAGE =
142 new HashSet<String>() {
143 {
144 add("ar"); // Arabic
145 add("fa"); // Persian
146 add("he"); // Hebrew
147 add("iw"); // Hebrew
148 add("ur"); // Urdu
149 }
150 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700151
Tianjie Xub97f7e52018-11-12 16:28:14 -0800152 // Languages that breaks on arbitrary characters.
Tianjie Xub8564e12018-11-12 17:06:14 -0800153 // TODO(xunchang) switch to icu library if possible. For example, for Thai and Khmer, there is
154 // no space between words; and word breaking is based on grammatical analysis and on word
155 // matching in dictionaries.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800156 private static final Set<String> LOGOGRAM_LANGUAGE =
157 new HashSet<String>() {
158 {
159 add("ja"); // Japanese
160 add("km"); // Khmer
161 add("ko"); // Korean
162 add("lo"); // Lao
Tianjie Xub8564e12018-11-12 17:06:14 -0800163 add("th"); // Thai
Tianjie Xub97f7e52018-11-12 16:28:14 -0800164 add("zh"); // Chinese
165 }
166 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700167
Tianjie Xub97f7e52018-11-12 16:28:14 -0800168 /** Exception to indicate the failure to find the translated text strings. */
169 public static class LocalizedStringNotFoundException extends Exception {
170 public LocalizedStringNotFoundException(String message) {
171 super(message);
172 }
173
174 public LocalizedStringNotFoundException(String message, Throwable cause) {
175 super(message, cause);
176 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700177 }
178
Tianjie Xu542c6172018-11-13 16:36:41 -0800179 /**
180 * This class maintains the content of wrapped text, the attributes to draw these text, and
181 * the width of each wrapped lines.
182 */
183 private class WrappedTextInfo {
184 /** LineInfo holds the AttributedString and width of each wrapped line. */
185 private class LineInfo {
186 public AttributedString mLineContent;
187 public int mLineWidth;
188
189 LineInfo(AttributedString text, int width) {
190 mLineContent = text;
191 mLineWidth = width;
192 }
193 }
194
195 // Maintains the content of each line, as well as the width needed to draw these lines for
196 // a given language.
197 public List<LineInfo> mWrappedLines;
198
199 WrappedTextInfo() {
200 mWrappedLines = new ArrayList<>();
201 }
202
203 /**
204 * Checks if the given text has words "Android" and some PUNCTUATIONS. If it does, and its
205 * associated textFont cannot display them correctly (e.g. for persian and hebrew); sets the
206 * attributes of these substrings to use our default font instead.
207 *
208 * @param text the input string to perform the check on
209 * @param width the pre-calculated width for the given text
210 * @param textFont the localized font to draw the input string
211 * @param fallbackFont our default font to draw latin characters
212 */
213 public void addLine(String text, int width, Font textFont, Font fallbackFont) {
214 AttributedString attributedText = new AttributedString(text);
215 attributedText.addAttribute(TextAttribute.FONT, textFont);
216 attributedText.addAttribute(TextAttribute.SIZE, mFontSize);
217
218 // Skips the check if we don't specify a fallbackFont.
219 if (fallbackFont != null) {
220 // Adds the attribute to use default font to draw the word "Android".
221 if (text.contains(ANDROID_STRING)
222 && textFont.canDisplayUpTo(ANDROID_STRING) != -1) {
223 int index = text.indexOf(ANDROID_STRING);
224 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
225 index + ANDROID_STRING.length());
226 }
227
228 // Adds the attribute to use default font to draw the PUNCTUATIONS ", . !"
229 for (char punctuation : PUNCTUATIONS) {
230 if (text.indexOf(punctuation) != -1 && !textFont.canDisplay(punctuation)) {
231 int index = 0;
232 while ((index = text.indexOf(punctuation, index)) != -1) {
233 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
234 index + 1);
235 index += 1;
236 }
237 }
238 }
239 }
240
241 mWrappedLines.add(new LineInfo(attributedText, width));
242 }
243 }
244
Tianjie Xub97f7e52018-11-12 16:28:14 -0800245 /** Initailizes the fields of the image image. */
Tianjie Xub8564e12018-11-12 17:06:14 -0800246 public ImageGenerator(
247 int initialImageWidth,
248 String textName,
249 float fontSize,
250 String fontDirPath,
251 boolean centerAlignment) {
252 mImageWidth = initialImageWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800253 mImageHeight = INITIAL_HEIGHT;
254 mVerticalOffset = 0;
Tianjie Xu721f6792018-10-08 17:04:54 -0700255
Tianjie Xub97f7e52018-11-12 16:28:14 -0800256 // Initialize the canvas with the default height.
257 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xu721f6792018-10-08 17:04:54 -0700258
Tianjie Xub97f7e52018-11-12 16:28:14 -0800259 mTextName = textName;
260 mFontSize = fontSize;
261 mFontDirPath = fontDirPath;
Tianjie Xu542c6172018-11-13 16:36:41 -0800262 mLoadedFontMap = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800263
264 mCenterAlignment = centerAlignment;
Tianjie Xu721f6792018-10-08 17:04:54 -0700265 }
266
Tianjie Xub97f7e52018-11-12 16:28:14 -0800267 /**
268 * Finds the translated text string for the given textName by parsing the resourceFile. Example
269 * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android">
270 * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate
271 * wird installiert"</string> </resources>
272 *
273 * @param resourceFile the input resource file in xml format.
274 * @param textName the name description of the text.
275 * @return the string representation of the translated text.
276 */
277 private String getTextString(File resourceFile, String textName)
278 throws IOException, ParserConfigurationException, org.xml.sax.SAXException,
279 LocalizedStringNotFoundException {
280 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
281 DocumentBuilder db = builder.newDocumentBuilder();
Tianjie Xu721f6792018-10-08 17:04:54 -0700282
Tianjie Xub97f7e52018-11-12 16:28:14 -0800283 Document doc = db.parse(resourceFile);
284 doc.getDocumentElement().normalize();
Tianjie Xu721f6792018-10-08 17:04:54 -0700285
Tianjie Xub97f7e52018-11-12 16:28:14 -0800286 NodeList nodeList = doc.getElementsByTagName("string");
287 for (int i = 0; i < nodeList.getLength(); i++) {
288 Node node = nodeList.item(i);
289 String name = node.getAttributes().getNamedItem("name").getNodeValue();
290 if (name.equals(textName)) {
291 return node.getTextContent();
292 }
293 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700294
Tianjie Xu721f6792018-10-08 17:04:54 -0700295 throw new LocalizedStringNotFoundException(
Tianjie Xub97f7e52018-11-12 16:28:14 -0800296 textName + " not found in " + resourceFile.getName());
Tianjie Xu721f6792018-10-08 17:04:54 -0700297 }
298
Tianjie Xub97f7e52018-11-12 16:28:14 -0800299 /** Constructs the locale from the name of the resource file. */
300 private Locale getLocaleFromFilename(String filename) throws IOException {
301 // Gets the locale string by trimming the top "values-".
302 String localeString = filename.substring(7);
303 if (localeString.matches("[A-Za-z]+")) {
304 return Locale.forLanguageTag(localeString);
305 }
306 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
307 // "${Language}-r${Region}". e.g. en-rGB
308 String[] tokens = localeString.split("-r");
309 return Locale.forLanguageTag(String.join("-", tokens));
310 }
311 if (localeString.startsWith("b+")) {
312 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
313 String[] tokens = localeString.substring(2).split("\\+");
314 return Locale.forLanguageTag(String.join("-", tokens));
315 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700316
Tianjie Xub97f7e52018-11-12 16:28:14 -0800317 throw new IOException("Unrecognized locale string " + localeString);
Tianjie Xu721f6792018-10-08 17:04:54 -0700318 }
319
Tianjie Xub97f7e52018-11-12 16:28:14 -0800320 /**
321 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
322 * directory and collect the translated text.
323 *
324 * @param resourcePath the path to the resource directory
325 * @return a map with the locale as key, and translated text as value
326 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
327 * locale
328 */
329 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath)
330 throws IOException, LocalizedStringNotFoundException {
331 File resourceDir = new File(resourcePath);
332 if (!resourceDir.isDirectory()) {
333 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
334 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700335
Tianjie Xub97f7e52018-11-12 16:28:14 -0800336 Map<Locale, String> result =
337 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus
338 // recovery can find the most relevant locale when going down the list.
339 new TreeMap<>(
340 (Locale l1, Locale l2) -> {
341 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
342 return 0;
343 }
344 if (l1.getLanguage().equals(l2.toLanguageTag())) {
345 return -1;
346 }
347 if (l2.getLanguage().equals(l1.toLanguageTag())) {
348 return 1;
349 }
350 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
351 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700352
Tianjie Xub97f7e52018-11-12 16:28:14 -0800353 // Find all the localized resource subdirectories in the format of values-$LOCALE
354 String[] nameList =
355 resourceDir.list((File file, String name) -> name.startsWith("values-"));
356 for (String name : nameList) {
357 File textFile = new File(resourcePath, name + "/strings.xml");
358 String localizedText;
359 try {
360 localizedText = getTextString(textFile, mTextName);
361 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
362 throw new LocalizedStringNotFoundException(
363 "Failed to read the translated text for locale " + name, e);
364 }
365
366 Locale locale = getLocaleFromFilename(name);
367 // Removes the double quotation mark from the text.
368 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
369 }
370
371 return result;
372 }
373
374 /**
375 * Returns a font object associated given the given locale
376 *
377 * @throws IOException if the font file fails to open
378 * @throws FontFormatException if the font file doesn't have the expected format
379 */
380 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800381 if (mLoadedFontMap.containsKey(language)) {
382 return mLoadedFontMap.get(language);
383 }
384
Tianjie Xub97f7e52018-11-12 16:28:14 -0800385 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
386 String[] suffixes = {".otf", ".ttf", ".ttc"};
387 for (String suffix : suffixes) {
388 File fontFile = new File(mFontDirPath, fontName + suffix);
389 if (fontFile.isFile()) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800390 Font result = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
391 mLoadedFontMap.put(language, result);
392 return result;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800393 }
394 }
395
396 throw new IOException(
397 "Can not find the font file " + fontName + " for language " + language);
398 }
399
400 /** Separates the text string by spaces and wraps it by words. */
Tianjie Xu542c6172018-11-13 16:36:41 -0800401 private WrappedTextInfo wrapTextByWords(String text, FontMetrics metrics) {
402 WrappedTextInfo info = new WrappedTextInfo();
Tianjie Xub97f7e52018-11-12 16:28:14 -0800403 StringTokenizer st = new StringTokenizer(text, " \n");
404
Tianjie Xu542c6172018-11-13 16:36:41 -0800405 int lineWidth = 0; // Width of the processed words of the current line.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800406 StringBuilder line = new StringBuilder();
407 while (st.hasMoreTokens()) {
408 String token = st.nextToken();
Tianjie Xu542c6172018-11-13 16:36:41 -0800409 int tokenWidth = metrics.stringWidth(token + " ");
410 // Handles the width mismatch of the word "Android" between different fonts.
411 if (token.contains(ANDROID_STRING)
412 && metrics.getFont().canDisplayUpTo(ANDROID_STRING) != -1) {
413 tokenWidth = tokenWidth - metrics.stringWidth(ANDROID_STRING) + mAndroidStringWidth;
414 }
415
416 if (lineWidth + tokenWidth > mImageWidth) {
417 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
418
Tianjie Xub97f7e52018-11-12 16:28:14 -0800419 line = new StringBuilder();
Tianjie Xu542c6172018-11-13 16:36:41 -0800420 lineWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800421 }
422 line.append(token).append(" ");
Tianjie Xu542c6172018-11-13 16:36:41 -0800423 lineWidth += tokenWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800424 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800425
Tianjie Xu542c6172018-11-13 16:36:41 -0800426 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
427
428 return info;
Tianjie Xu721f6792018-10-08 17:04:54 -0700429 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700430
Tianjie Xub97f7e52018-11-12 16:28:14 -0800431 /** One character is a word for CJK. */
Tianjie Xu542c6172018-11-13 16:36:41 -0800432 private WrappedTextInfo wrapTextByCharacters(String text, FontMetrics metrics) {
433 WrappedTextInfo info = new WrappedTextInfo();
434 // TODO (xunchang) handle the text wrapping with logogram language mixed with latin.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800435 StringBuilder line = new StringBuilder();
436 for (char token : text.toCharArray()) {
437 if (metrics.stringWidth(line + Character.toString(token)) > mImageWidth) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800438 info.addLine(line.toString(), metrics.stringWidth(line.toString()),
439 metrics.getFont(), null);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800440 line = new StringBuilder();
441 }
442 line.append(token);
443 }
Tianjie Xu542c6172018-11-13 16:36:41 -0800444 info.addLine(line.toString(), metrics.stringWidth(line.toString()), metrics.getFont(),
445 null);
Tianjie Xu22dd0192018-10-17 15:39:00 -0700446
Tianjie Xu542c6172018-11-13 16:36:41 -0800447 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700448 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700449
Tianjie Xub97f7e52018-11-12 16:28:14 -0800450 /**
451 * Wraps the text with a maximum of mImageWidth pixels per line.
452 *
453 * @param text the string representation of text to wrap
454 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
455 * the text given its string representation
Tianjie Xu542c6172018-11-13 16:36:41 -0800456 * @return a WrappedTextInfo class with the width of each AttributedString smaller than
457 * mImageWidth pixels
Tianjie Xub97f7e52018-11-12 16:28:14 -0800458 */
Tianjie Xu542c6172018-11-13 16:36:41 -0800459 private WrappedTextInfo wrapText(String text, FontMetrics metrics, String language) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800460 if (LOGOGRAM_LANGUAGE.contains(language)) {
461 return wrapTextByCharacters(text, metrics);
462 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700463
Tianjie Xub97f7e52018-11-12 16:28:14 -0800464 return wrapTextByWords(text, metrics);
Tianjie Xu721f6792018-10-08 17:04:54 -0700465 }
Tianjie Xu22dd0192018-10-17 15:39:00 -0700466
Tianjie Xub97f7e52018-11-12 16:28:14 -0800467 /**
468 * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the
469 * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h =
470 * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc =
471 * reinterpret_cast<char*>(&row[5]);
472 */
473 private List<Integer> encodeTextInfo(int width, int height, String locale) {
474 List<Integer> info =
475 new ArrayList<>(
476 Arrays.asList(
477 width & 0xff,
478 width >> 8,
479 height & 0xff,
480 height >> 8,
481 locale.length()));
Tianjie Xu721f6792018-10-08 17:04:54 -0700482
Tianjie Xub97f7e52018-11-12 16:28:14 -0800483 byte[] localeBytes = locale.getBytes();
484 for (byte b : localeBytes) {
485 info.add((int) b);
486 }
487 info.add(0);
Tianjie Xu721f6792018-10-08 17:04:54 -0700488
Tianjie Xub97f7e52018-11-12 16:28:14 -0800489 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700490 }
491
Tianjie Xub8564e12018-11-12 17:06:14 -0800492 /** Returns Graphics2D object that uses the given locale. */
493 private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException {
494 Graphics2D graphics = mBufferedImage.createGraphics();
495 graphics.setColor(Color.WHITE);
496 graphics.setRenderingHint(
497 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
498 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
499
500 return graphics;
501 }
502
503 /** Returns the maximum screen width needed to fit the given text after wrapping. */
504 private int measureTextWidth(String text, Locale locale)
505 throws IOException, FontFormatException {
506 Graphics2D graphics = createGraphics(locale);
507 FontMetrics fontMetrics = graphics.getFontMetrics();
Tianjie Xu542c6172018-11-13 16:36:41 -0800508 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics, locale.getLanguage());
Tianjie Xub8564e12018-11-12 17:06:14 -0800509
510 int textWidth = 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800511 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
512 textWidth = Math.max(textWidth, lineInfo.mLineWidth);
Tianjie Xub8564e12018-11-12 17:06:14 -0800513 }
514
515 // This may happen if one single word is larger than the image width.
516 if (textWidth > mImageWidth) {
517 throw new IllegalStateException(
518 "Wrapped text width "
519 + textWidth
520 + " is larger than image width "
521 + mImageWidth
522 + " for locale: "
523 + locale);
524 }
525
526 return textWidth;
527 }
528
Tianjie Xub97f7e52018-11-12 16:28:14 -0800529 /**
530 * Draws the text string on the canvas for given locale.
531 *
532 * @param text the string to draw on canvas
533 * @param locale the current locale tag of the string to draw
534 * @throws IOException if we cannot find the corresponding font file for the given locale.
535 * @throws FontFormatException if we failed to load the font file for the given locale.
536 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800537 private void drawText(String text, Locale locale, String languageTag)
Tianjie Xub97f7e52018-11-12 16:28:14 -0800538 throws IOException, FontFormatException {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800539 System.out.println("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
540
Tianjie Xub8564e12018-11-12 17:06:14 -0800541 Graphics2D graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800542 FontMetrics fontMetrics = graphics.getFontMetrics();
Tianjie Xu542c6172018-11-13 16:36:41 -0800543 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics, locale.getLanguage());
Tianjie Xub97f7e52018-11-12 16:28:14 -0800544
545 // Marks the start y offset for the text image of current locale; and reserves one line to
546 // encode the image metadata.
547 int currentImageStart = mVerticalOffset;
548 mVerticalOffset += 1;
Tianjie Xu542c6172018-11-13 16:36:41 -0800549 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800550 int lineHeight = fontMetrics.getHeight();
551 // Doubles the height of the image if we are short of space.
552 if (mVerticalOffset + lineHeight >= mImageHeight) {
Tianjie Xub8564e12018-11-12 17:06:14 -0800553 resize(mImageWidth, mImageHeight * 2);
Tianjie Xu542c6172018-11-13 16:36:41 -0800554 // Recreates the graphics since it's attached to the buffered image.
555 graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800556 }
557
558 // Draws the text at mVerticalOffset and increments the offset with line space.
559 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
560
561 // Draws from right if it's an RTL language.
562 int x =
Tianjie Xub8564e12018-11-12 17:06:14 -0800563 mCenterAlignment
Tianjie Xu542c6172018-11-13 16:36:41 -0800564 ? (mImageWidth - lineInfo.mLineWidth) / 2
Tianjie Xub97f7e52018-11-12 16:28:14 -0800565 : RTL_LANGUAGE.contains(languageTag)
Tianjie Xu542c6172018-11-13 16:36:41 -0800566 ? mImageWidth - lineInfo.mLineWidth
Tianjie Xub97f7e52018-11-12 16:28:14 -0800567 : 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800568 graphics.drawString(lineInfo.mLineContent.getIterator(), x, baseLine);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800569
570 mVerticalOffset += lineHeight;
571 }
572
573 // Encodes the metadata of the current localized image as pixels.
574 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
575 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
576 for (int i = 0; i < info.size(); i++) {
577 int[] pixel = {info.get(i)};
578 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
579 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700580 }
581
Tianjie Xub97f7e52018-11-12 16:28:14 -0800582 /**
Tianjie Xub8564e12018-11-12 17:06:14 -0800583 * Redraws the image with the new width and new height.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800584 *
Tianjie Xub8564e12018-11-12 17:06:14 -0800585 * @param width the new width of the image in pixels.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800586 * @param height the new height of the image in pixels.
587 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800588 private void resize(int width, int height) {
589 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800590 Graphics2D graphic = resizedImage.createGraphics();
591 graphic.drawImage(mBufferedImage, 0, 0, null);
592 graphic.dispose();
Tianjie Xu721f6792018-10-08 17:04:54 -0700593
Tianjie Xub97f7e52018-11-12 16:28:14 -0800594 mBufferedImage = resizedImage;
Tianjie Xub8564e12018-11-12 17:06:14 -0800595 mImageWidth = width;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800596 mImageHeight = height;
Tianjie Xu721f6792018-10-08 17:04:54 -0700597 }
598
Tianjie Xub97f7e52018-11-12 16:28:14 -0800599 /**
600 * This function draws the font characters and saves the result to outputPath.
601 *
602 * @param localizedTextMap a map from locale to its translated text string
603 * @param outputPath the path to write the generated image file.
604 * @throws FontFormatException if there's a format error in one of the font file
605 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
606 * write the image file.
607 */
608 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath)
609 throws FontFormatException, IOException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800610 FontMetrics defaultFontMetrics =
611 createGraphics(Locale.forLanguageTag("en")).getFontMetrics();
612 mDefaultFont = defaultFontMetrics.getFont();
613 mAndroidStringWidth = defaultFontMetrics.stringWidth(ANDROID_STRING);
614
Tianjie Xub97f7e52018-11-12 16:28:14 -0800615 Map<String, Integer> languageCount = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800616 int textWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800617 for (Locale locale : localizedTextMap.keySet()) {
618 String language = locale.getLanguage();
619 languageCount.put(language, languageCount.getOrDefault(language, 0) + 1);
Tianjie Xub8564e12018-11-12 17:06:14 -0800620 textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800621 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700622
Tianjie Xub8564e12018-11-12 17:06:14 -0800623 // Removes the black margins to reduce the size of the image.
624 resize(textWidth, mImageHeight);
625
Tianjie Xub97f7e52018-11-12 16:28:14 -0800626 for (Locale locale : localizedTextMap.keySet()) {
627 Integer count = languageCount.get(locale.getLanguage());
628 // Recovery expects en-US instead of en_US.
629 String languageTag = locale.toLanguageTag();
630 if (count == 1) {
631 // Make the last country variant for a given language be the catch-all for that
632 // language.
633 languageTag = locale.getLanguage();
634 } else {
635 languageCount.put(locale.getLanguage(), count - 1);
636 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700637
Tianjie Xub8564e12018-11-12 17:06:14 -0800638 drawText(localizedTextMap.get(locale), locale, languageTag);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800639 }
640
Tianjie Xub8564e12018-11-12 17:06:14 -0800641 resize(mImageWidth, mVerticalOffset);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800642 ImageIO.write(mBufferedImage, "png", new File(outputPath));
643 }
644
645 /** Prints the helper message. */
646 public static void printUsage(Options options) {
647 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
648 }
649
650 /** Creates the command line options. */
651 public static Options createOptions() {
652 Options options = new Options();
653 options.addOption(
654 OptionBuilder.withLongOpt("image_width")
655 .withDescription("The initial width of the image in pixels.")
656 .hasArgs(1)
657 .isRequired()
658 .create());
659
660 options.addOption(
661 OptionBuilder.withLongOpt("text_name")
662 .withDescription(
663 "The description of the text string, e.g. recovery_erasing")
664 .hasArgs(1)
665 .isRequired()
666 .create());
667
668 options.addOption(
669 OptionBuilder.withLongOpt("font_dir")
670 .withDescription(
671 "The directory that contains all the support font format files, "
672 + "e.g. $OUT/system/fonts/")
673 .hasArgs(1)
674 .isRequired()
675 .create());
676
677 options.addOption(
678 OptionBuilder.withLongOpt("resource_dir")
679 .withDescription(
680 "The resource directory that contains all the translated strings in"
681 + " xml format, e.g."
682 + " bootable/recovery/tools/recovery_l10n/res/")
683 .hasArgs(1)
684 .isRequired()
685 .create());
686
687 options.addOption(
688 OptionBuilder.withLongOpt("output_file")
Tianjie Xub8564e12018-11-12 17:06:14 -0800689 .withDescription("Path to the generated image.")
Tianjie Xub97f7e52018-11-12 16:28:14 -0800690 .hasArgs(1)
691 .isRequired()
692 .create());
693
Tianjie Xub8564e12018-11-12 17:06:14 -0800694 options.addOption(
695 OptionBuilder.withLongOpt("center_alignment")
696 .withDescription("Align the text in the center of the screen.")
697 .hasArg(false)
698 .create());
699
Tianjie Xub97f7e52018-11-12 16:28:14 -0800700 return options;
701 }
702
703 /** The main function parses the command line options and generates the desired text image. */
704 public static void main(String[] args)
705 throws NumberFormatException, IOException, FontFormatException,
706 LocalizedStringNotFoundException {
707 Options options = createOptions();
708 CommandLine cmd;
709 try {
710 cmd = new GnuParser().parse(options, args);
711 } catch (ParseException e) {
712 System.err.println(e.getMessage());
713 printUsage(options);
714 return;
715 }
716
717 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
718
719 ImageGenerator imageGenerator =
720 new ImageGenerator(
721 imageWidth,
722 cmd.getOptionValue("text_name"),
723 DEFAULT_FONT_SIZE,
Tianjie Xub8564e12018-11-12 17:06:14 -0800724 cmd.getOptionValue("font_dir"),
725 cmd.hasOption("center_alignment"));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800726
727 Map<Locale, String> localizedStringMap =
728 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"));
729 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
730 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700731}