blob: 19d187d244c54f3b21a4cf21b54cfb403ef7c5d7 [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
xunchangacacc9d2018-11-26 15:01:39 -080019import com.ibm.icu.text.BreakIterator;
20
Tao Bao529bb742018-11-06 11:24:53 -080021import org.apache.commons.cli.CommandLine;
22import org.apache.commons.cli.GnuParser;
23import org.apache.commons.cli.HelpFormatter;
24import org.apache.commons.cli.OptionBuilder;
25import org.apache.commons.cli.Options;
26import org.apache.commons.cli.ParseException;
27import org.w3c.dom.Document;
28import org.w3c.dom.Node;
29import org.w3c.dom.NodeList;
30
Tianjie Xu721f6792018-10-08 17:04:54 -070031import java.awt.Color;
32import java.awt.Font;
33import java.awt.FontFormatException;
34import java.awt.FontMetrics;
35import java.awt.Graphics2D;
36import java.awt.RenderingHints;
Tianjie Xu542c6172018-11-13 16:36:41 -080037import java.awt.font.TextAttribute;
Tianjie Xu721f6792018-10-08 17:04:54 -070038import java.awt.image.BufferedImage;
39import java.io.File;
40import java.io.IOException;
Tianjie Xu542c6172018-11-13 16:36:41 -080041import java.text.AttributedString;
Tianjie Xu721f6792018-10-08 17:04:54 -070042import java.util.ArrayList;
Tianjie Xu22dd0192018-10-17 15:39:00 -070043import java.util.Arrays;
44import java.util.HashSet;
Tianjie Xu721f6792018-10-08 17:04:54 -070045import java.util.List;
46import java.util.Locale;
47import java.util.Map;
Tianjie Xu22dd0192018-10-17 15:39:00 -070048import java.util.Set;
Tao Bao529bb742018-11-06 11:24:53 -080049import java.util.TreeMap;
Tianjie Xu7b636b62018-11-14 16:25:42 -080050import java.util.logging.Level;
51import java.util.logging.Logger;
Tianjie Xu721f6792018-10-08 17:04:54 -070052
53import javax.imageio.ImageIO;
54import javax.xml.parsers.DocumentBuilder;
55import javax.xml.parsers.DocumentBuilderFactory;
56import javax.xml.parsers.ParserConfigurationException;
57
Tianjie Xub97f7e52018-11-12 16:28:14 -080058/** Command line tool to generate the localized image for recovery mode. */
Tianjie Xu721f6792018-10-08 17:04:54 -070059public class ImageGenerator {
Tianjie Xub97f7e52018-11-12 16:28:14 -080060 // Initial height of the image to draw.
61 private static final int INITIAL_HEIGHT = 20000;
Tianjie Xu721f6792018-10-08 17:04:54 -070062
Tianjie Xub97f7e52018-11-12 16:28:14 -080063 private static final float DEFAULT_FONT_SIZE = 40;
Tianjie Xu721f6792018-10-08 17:04:54 -070064
Tianjie Xu7b636b62018-11-14 16:25:42 -080065 private static final Logger LOGGER = Logger.getLogger(ImageGenerator.class.getName());
66
Tianjie Xub97f7e52018-11-12 16:28:14 -080067 // This is the canvas we used to draw texts.
68 private BufferedImage mBufferedImage;
Tianjie Xu721f6792018-10-08 17:04:54 -070069
Tianjie Xub8564e12018-11-12 17:06:14 -080070 // The width in pixels of our image. The value will be adjusted once when we calculate the
71 // maximum width to fit the wrapped text strings.
72 private int mImageWidth;
Tianjie Xu721f6792018-10-08 17:04:54 -070073
Tianjie Xub97f7e52018-11-12 16:28:14 -080074 // The current height in pixels of our image. We will adjust the value when drawing more texts.
75 private int mImageHeight;
Tianjie Xu721f6792018-10-08 17:04:54 -070076
Tianjie Xub97f7e52018-11-12 16:28:14 -080077 // The current vertical offset in pixels to draw the top edge of new text strings.
78 private int mVerticalOffset;
Tianjie Xu721f6792018-10-08 17:04:54 -070079
Tianjie Xub97f7e52018-11-12 16:28:14 -080080 // The font size to draw the texts.
81 private final float mFontSize;
Tianjie Xu721f6792018-10-08 17:04:54 -070082
Tianjie Xub97f7e52018-11-12 16:28:14 -080083 // The name description of the text to localize. It's used to find the translated strings in the
84 // resource file.
85 private final String mTextName;
Tianjie Xu721f6792018-10-08 17:04:54 -070086
Tianjie Xub97f7e52018-11-12 16:28:14 -080087 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
88 private final String mFontDirPath;
Tianjie Xu721f6792018-10-08 17:04:54 -070089
Tianjie Xub8564e12018-11-12 17:06:14 -080090 // Align the text in the center of the image.
91 private final boolean mCenterAlignment;
92
Tianjie Xu542c6172018-11-13 16:36:41 -080093 // Some localized font cannot draw the word "Android" and some PUNCTUATIONS; we need to fall
94 // back to use our default latin font instead.
95 private static final char[] PUNCTUATIONS = {',', ';', '.', '!' };
96
97 private static final String ANDROID_STRING = "Android";
98
99 // The width of the word "Android" when drawing with the default font.
100 private int mAndroidStringWidth;
101
102 // The default Font to draw latin characters. It's loaded from DEFAULT_FONT_NAME.
103 private Font mDefaultFont;
104 // Cache of the loaded fonts for all languages.
105 private Map<String, Font> mLoadedFontMap;
106
Tianjie Xub97f7e52018-11-12 16:28:14 -0800107 // An explicit map from language to the font name to use.
108 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
109 // And the language-subtag-registry is found in:
110 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
111 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
112 private static final Map<String, String> LANGUAGE_TO_FONT_MAP =
113 new TreeMap<String, String>() {
114 {
115 put("am", "NotoSansEthiopic-Regular");
116 put("ar", "NotoNaskhArabicUI-Regular");
117 put("as", "NotoSansBengaliUI-Regular");
118 put("bn", "NotoSansBengaliUI-Regular");
119 put("fa", "NotoNaskhArabicUI-Regular");
120 put("gu", "NotoSansGujaratiUI-Regular");
121 put("hi", "NotoSansDevanagariUI-Regular");
122 put("hy", "NotoSansArmenian-Regular");
123 put("iw", "NotoSansHebrew-Regular");
124 put("ja", "NotoSansCJK-Regular");
125 put("ka", "NotoSansGeorgian-Regular");
126 put("ko", "NotoSansCJK-Regular");
127 put("km", "NotoSansKhmerUI-Regular");
128 put("kn", "NotoSansKannadaUI-Regular");
129 put("lo", "NotoSansLaoUI-Regular");
130 put("ml", "NotoSansMalayalamUI-Regular");
131 put("mr", "NotoSansDevanagariUI-Regular");
132 put("my", "NotoSansMyanmarUI-Regular");
133 put("ne", "NotoSansDevanagariUI-Regular");
134 put("or", "NotoSansOriya-Regular");
135 put("pa", "NotoSansGurmukhiUI-Regular");
136 put("si", "NotoSansSinhala-Regular");
137 put("ta", "NotoSansTamilUI-Regular");
138 put("te", "NotoSansTeluguUI-Regular");
139 put("th", "NotoSansThaiUI-Regular");
140 put("ur", "NotoNaskhArabicUI-Regular");
141 put("zh", "NotoSansCJK-Regular");
142 }
143 };
Tianjie Xu721f6792018-10-08 17:04:54 -0700144
Tianjie Xub97f7e52018-11-12 16:28:14 -0800145 // Languages that write from right to left.
146 private static final Set<String> RTL_LANGUAGE =
147 new HashSet<String>() {
148 {
149 add("ar"); // Arabic
150 add("fa"); // Persian
151 add("he"); // Hebrew
152 add("iw"); // Hebrew
153 add("ur"); // Urdu
154 }
155 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700156
Tianjie Xub97f7e52018-11-12 16:28:14 -0800157 /** Exception to indicate the failure to find the translated text strings. */
158 public static class LocalizedStringNotFoundException extends Exception {
159 public LocalizedStringNotFoundException(String message) {
160 super(message);
161 }
162
163 public LocalizedStringNotFoundException(String message, Throwable cause) {
164 super(message, cause);
165 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700166 }
167
Tianjie Xu542c6172018-11-13 16:36:41 -0800168 /**
169 * This class maintains the content of wrapped text, the attributes to draw these text, and
170 * the width of each wrapped lines.
171 */
172 private class WrappedTextInfo {
173 /** LineInfo holds the AttributedString and width of each wrapped line. */
174 private class LineInfo {
175 public AttributedString mLineContent;
176 public int mLineWidth;
177
178 LineInfo(AttributedString text, int width) {
179 mLineContent = text;
180 mLineWidth = width;
181 }
182 }
183
184 // Maintains the content of each line, as well as the width needed to draw these lines for
185 // a given language.
186 public List<LineInfo> mWrappedLines;
187
188 WrappedTextInfo() {
189 mWrappedLines = new ArrayList<>();
190 }
191
192 /**
193 * Checks if the given text has words "Android" and some PUNCTUATIONS. If it does, and its
194 * associated textFont cannot display them correctly (e.g. for persian and hebrew); sets the
195 * attributes of these substrings to use our default font instead.
196 *
197 * @param text the input string to perform the check on
198 * @param width the pre-calculated width for the given text
199 * @param textFont the localized font to draw the input string
200 * @param fallbackFont our default font to draw latin characters
201 */
202 public void addLine(String text, int width, Font textFont, Font fallbackFont) {
203 AttributedString attributedText = new AttributedString(text);
204 attributedText.addAttribute(TextAttribute.FONT, textFont);
205 attributedText.addAttribute(TextAttribute.SIZE, mFontSize);
206
207 // Skips the check if we don't specify a fallbackFont.
208 if (fallbackFont != null) {
209 // Adds the attribute to use default font to draw the word "Android".
210 if (text.contains(ANDROID_STRING)
211 && textFont.canDisplayUpTo(ANDROID_STRING) != -1) {
212 int index = text.indexOf(ANDROID_STRING);
213 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
214 index + ANDROID_STRING.length());
215 }
216
217 // Adds the attribute to use default font to draw the PUNCTUATIONS ", . !"
218 for (char punctuation : PUNCTUATIONS) {
219 if (text.indexOf(punctuation) != -1 && !textFont.canDisplay(punctuation)) {
220 int index = 0;
221 while ((index = text.indexOf(punctuation, index)) != -1) {
222 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
223 index + 1);
224 index += 1;
225 }
226 }
227 }
228 }
229
230 mWrappedLines.add(new LineInfo(attributedText, width));
231 }
232 }
233
Tianjie Xub97f7e52018-11-12 16:28:14 -0800234 /** Initailizes the fields of the image image. */
Tianjie Xub8564e12018-11-12 17:06:14 -0800235 public ImageGenerator(
236 int initialImageWidth,
237 String textName,
238 float fontSize,
239 String fontDirPath,
240 boolean centerAlignment) {
241 mImageWidth = initialImageWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800242 mImageHeight = INITIAL_HEIGHT;
243 mVerticalOffset = 0;
Tianjie Xu721f6792018-10-08 17:04:54 -0700244
Tianjie Xub97f7e52018-11-12 16:28:14 -0800245 // Initialize the canvas with the default height.
246 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xu721f6792018-10-08 17:04:54 -0700247
Tianjie Xub97f7e52018-11-12 16:28:14 -0800248 mTextName = textName;
249 mFontSize = fontSize;
250 mFontDirPath = fontDirPath;
Tianjie Xu542c6172018-11-13 16:36:41 -0800251 mLoadedFontMap = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800252
253 mCenterAlignment = centerAlignment;
Tianjie Xu721f6792018-10-08 17:04:54 -0700254 }
255
Tianjie Xub97f7e52018-11-12 16:28:14 -0800256 /**
257 * Finds the translated text string for the given textName by parsing the resourceFile. Example
258 * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android">
259 * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate
260 * wird installiert"</string> </resources>
261 *
262 * @param resourceFile the input resource file in xml format.
263 * @param textName the name description of the text.
264 * @return the string representation of the translated text.
265 */
266 private String getTextString(File resourceFile, String textName)
267 throws IOException, ParserConfigurationException, org.xml.sax.SAXException,
268 LocalizedStringNotFoundException {
269 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
270 DocumentBuilder db = builder.newDocumentBuilder();
Tianjie Xu721f6792018-10-08 17:04:54 -0700271
Tianjie Xub97f7e52018-11-12 16:28:14 -0800272 Document doc = db.parse(resourceFile);
273 doc.getDocumentElement().normalize();
Tianjie Xu721f6792018-10-08 17:04:54 -0700274
Tianjie Xub97f7e52018-11-12 16:28:14 -0800275 NodeList nodeList = doc.getElementsByTagName("string");
276 for (int i = 0; i < nodeList.getLength(); i++) {
277 Node node = nodeList.item(i);
278 String name = node.getAttributes().getNamedItem("name").getNodeValue();
279 if (name.equals(textName)) {
280 return node.getTextContent();
281 }
282 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700283
Tianjie Xu721f6792018-10-08 17:04:54 -0700284 throw new LocalizedStringNotFoundException(
Tianjie Xub97f7e52018-11-12 16:28:14 -0800285 textName + " not found in " + resourceFile.getName());
Tianjie Xu721f6792018-10-08 17:04:54 -0700286 }
287
Tianjie Xub97f7e52018-11-12 16:28:14 -0800288 /** Constructs the locale from the name of the resource file. */
289 private Locale getLocaleFromFilename(String filename) throws IOException {
290 // Gets the locale string by trimming the top "values-".
291 String localeString = filename.substring(7);
292 if (localeString.matches("[A-Za-z]+")) {
293 return Locale.forLanguageTag(localeString);
294 }
295 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
296 // "${Language}-r${Region}". e.g. en-rGB
297 String[] tokens = localeString.split("-r");
298 return Locale.forLanguageTag(String.join("-", tokens));
299 }
300 if (localeString.startsWith("b+")) {
301 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
302 String[] tokens = localeString.substring(2).split("\\+");
303 return Locale.forLanguageTag(String.join("-", tokens));
304 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700305
Tianjie Xub97f7e52018-11-12 16:28:14 -0800306 throw new IOException("Unrecognized locale string " + localeString);
Tianjie Xu721f6792018-10-08 17:04:54 -0700307 }
308
Tianjie Xub97f7e52018-11-12 16:28:14 -0800309 /**
310 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
311 * directory and collect the translated text.
312 *
313 * @param resourcePath the path to the resource directory
Tianjie Xu7b636b62018-11-14 16:25:42 -0800314 * @param localesSet a list of supported locales; resources of other locales will be omitted.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800315 * @return a map with the locale as key, and translated text as value
316 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
317 * locale
318 */
Tianjie Xu7b636b62018-11-14 16:25:42 -0800319 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath,
320 Set<String> localesSet) throws IOException, LocalizedStringNotFoundException {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800321 File resourceDir = new File(resourcePath);
322 if (!resourceDir.isDirectory()) {
323 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
324 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700325
Tianjie Xub97f7e52018-11-12 16:28:14 -0800326 Map<Locale, String> result =
327 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus
328 // recovery can find the most relevant locale when going down the list.
329 new TreeMap<>(
330 (Locale l1, Locale l2) -> {
331 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
332 return 0;
333 }
334 if (l1.getLanguage().equals(l2.toLanguageTag())) {
335 return -1;
336 }
337 if (l2.getLanguage().equals(l1.toLanguageTag())) {
338 return 1;
339 }
340 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
341 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700342
Tianjie Xub97f7e52018-11-12 16:28:14 -0800343 // Find all the localized resource subdirectories in the format of values-$LOCALE
344 String[] nameList =
345 resourceDir.list((File file, String name) -> name.startsWith("values-"));
346 for (String name : nameList) {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800347 String localeString = name.substring(7);
348 if (localesSet != null && !localesSet.contains(localeString)) {
349 LOGGER.info("Skip parsing text for locale " + localeString);
350 continue;
351 }
352
Tianjie Xub97f7e52018-11-12 16:28:14 -0800353 File textFile = new File(resourcePath, name + "/strings.xml");
354 String localizedText;
355 try {
356 localizedText = getTextString(textFile, mTextName);
357 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
358 throw new LocalizedStringNotFoundException(
359 "Failed to read the translated text for locale " + name, e);
360 }
361
362 Locale locale = getLocaleFromFilename(name);
363 // Removes the double quotation mark from the text.
364 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
365 }
366
367 return result;
368 }
369
370 /**
371 * Returns a font object associated given the given locale
372 *
373 * @throws IOException if the font file fails to open
374 * @throws FontFormatException if the font file doesn't have the expected format
375 */
376 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800377 if (mLoadedFontMap.containsKey(language)) {
378 return mLoadedFontMap.get(language);
379 }
380
Tianjie Xub97f7e52018-11-12 16:28:14 -0800381 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
382 String[] suffixes = {".otf", ".ttf", ".ttc"};
383 for (String suffix : suffixes) {
384 File fontFile = new File(mFontDirPath, fontName + suffix);
385 if (fontFile.isFile()) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800386 Font result = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
387 mLoadedFontMap.put(language, result);
388 return result;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800389 }
390 }
391
392 throw new IOException(
393 "Can not find the font file " + fontName + " for language " + language);
394 }
395
xunchangacacc9d2018-11-26 15:01:39 -0800396 /**
397 * Wraps the text with a maximum of mImageWidth pixels per line.
398 *
399 * @param text the string representation of text to wrap
400 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
401 * the text given its string representation
402 * @return a WrappedTextInfo class with the width of each AttributedString smaller than
403 * mImageWidth pixels
404 */
405 private WrappedTextInfo wrapText(String text, FontMetrics metrics) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800406 WrappedTextInfo info = new WrappedTextInfo();
xunchangacacc9d2018-11-26 15:01:39 -0800407
408 BreakIterator lineBoundary = BreakIterator.getLineInstance();
409 lineBoundary.setText(text);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800410
Tianjie Xu542c6172018-11-13 16:36:41 -0800411 int lineWidth = 0; // Width of the processed words of the current line.
xunchangacacc9d2018-11-26 15:01:39 -0800412 int start = lineBoundary.first();
Tianjie Xub97f7e52018-11-12 16:28:14 -0800413 StringBuilder line = new StringBuilder();
xunchangacacc9d2018-11-26 15:01:39 -0800414 for (int end = lineBoundary.next(); end != BreakIterator.DONE;
415 start = end, end = lineBoundary.next()) {
416 String token = text.substring(start, end);
417 int tokenWidth = metrics.stringWidth(token);
Tianjie Xu542c6172018-11-13 16:36:41 -0800418 // Handles the width mismatch of the word "Android" between different fonts.
419 if (token.contains(ANDROID_STRING)
420 && metrics.getFont().canDisplayUpTo(ANDROID_STRING) != -1) {
421 tokenWidth = tokenWidth - metrics.stringWidth(ANDROID_STRING) + mAndroidStringWidth;
422 }
423
424 if (lineWidth + tokenWidth > mImageWidth) {
425 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
426
Tianjie Xub97f7e52018-11-12 16:28:14 -0800427 line = new StringBuilder();
Tianjie Xu542c6172018-11-13 16:36:41 -0800428 lineWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800429 }
xunchangacacc9d2018-11-26 15:01:39 -0800430 line.append(token);
Tianjie Xu542c6172018-11-13 16:36:41 -0800431 lineWidth += tokenWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800432 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800433
Tianjie Xu542c6172018-11-13 16:36:41 -0800434 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
435
436 return info;
Tianjie Xu721f6792018-10-08 17:04:54 -0700437 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700438
Tianjie Xub97f7e52018-11-12 16:28:14 -0800439 /**
440 * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the
441 * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h =
442 * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc =
443 * reinterpret_cast<char*>(&row[5]);
444 */
445 private List<Integer> encodeTextInfo(int width, int height, String locale) {
446 List<Integer> info =
447 new ArrayList<>(
448 Arrays.asList(
449 width & 0xff,
450 width >> 8,
451 height & 0xff,
452 height >> 8,
453 locale.length()));
Tianjie Xu721f6792018-10-08 17:04:54 -0700454
Tianjie Xub97f7e52018-11-12 16:28:14 -0800455 byte[] localeBytes = locale.getBytes();
456 for (byte b : localeBytes) {
457 info.add((int) b);
458 }
459 info.add(0);
Tianjie Xu721f6792018-10-08 17:04:54 -0700460
Tianjie Xub97f7e52018-11-12 16:28:14 -0800461 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700462 }
463
Tianjie Xub8564e12018-11-12 17:06:14 -0800464 /** Returns Graphics2D object that uses the given locale. */
465 private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException {
466 Graphics2D graphics = mBufferedImage.createGraphics();
467 graphics.setColor(Color.WHITE);
468 graphics.setRenderingHint(
469 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
470 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
471
472 return graphics;
473 }
474
475 /** Returns the maximum screen width needed to fit the given text after wrapping. */
476 private int measureTextWidth(String text, Locale locale)
477 throws IOException, FontFormatException {
478 Graphics2D graphics = createGraphics(locale);
479 FontMetrics fontMetrics = graphics.getFontMetrics();
xunchangacacc9d2018-11-26 15:01:39 -0800480 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics);
Tianjie Xub8564e12018-11-12 17:06:14 -0800481
482 int textWidth = 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800483 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
484 textWidth = Math.max(textWidth, lineInfo.mLineWidth);
Tianjie Xub8564e12018-11-12 17:06:14 -0800485 }
486
487 // This may happen if one single word is larger than the image width.
488 if (textWidth > mImageWidth) {
489 throw new IllegalStateException(
490 "Wrapped text width "
491 + textWidth
492 + " is larger than image width "
493 + mImageWidth
494 + " for locale: "
495 + locale);
496 }
497
498 return textWidth;
499 }
500
Tianjie Xub97f7e52018-11-12 16:28:14 -0800501 /**
502 * Draws the text string on the canvas for given locale.
503 *
504 * @param text the string to draw on canvas
505 * @param locale the current locale tag of the string to draw
506 * @throws IOException if we cannot find the corresponding font file for the given locale.
507 * @throws FontFormatException if we failed to load the font file for the given locale.
508 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800509 private void drawText(String text, Locale locale, String languageTag)
Tianjie Xub97f7e52018-11-12 16:28:14 -0800510 throws IOException, FontFormatException {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800511 LOGGER.info("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800512
Tianjie Xub8564e12018-11-12 17:06:14 -0800513 Graphics2D graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800514 FontMetrics fontMetrics = graphics.getFontMetrics();
xunchangacacc9d2018-11-26 15:01:39 -0800515 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800516
517 // Marks the start y offset for the text image of current locale; and reserves one line to
518 // encode the image metadata.
519 int currentImageStart = mVerticalOffset;
520 mVerticalOffset += 1;
Tianjie Xu542c6172018-11-13 16:36:41 -0800521 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800522 int lineHeight = fontMetrics.getHeight();
523 // Doubles the height of the image if we are short of space.
524 if (mVerticalOffset + lineHeight >= mImageHeight) {
Tianjie Xub8564e12018-11-12 17:06:14 -0800525 resize(mImageWidth, mImageHeight * 2);
Tianjie Xu542c6172018-11-13 16:36:41 -0800526 // Recreates the graphics since it's attached to the buffered image.
527 graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800528 }
529
530 // Draws the text at mVerticalOffset and increments the offset with line space.
531 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
532
533 // Draws from right if it's an RTL language.
534 int x =
Tianjie Xub8564e12018-11-12 17:06:14 -0800535 mCenterAlignment
Tianjie Xu542c6172018-11-13 16:36:41 -0800536 ? (mImageWidth - lineInfo.mLineWidth) / 2
Tianjie Xub97f7e52018-11-12 16:28:14 -0800537 : RTL_LANGUAGE.contains(languageTag)
Tianjie Xu542c6172018-11-13 16:36:41 -0800538 ? mImageWidth - lineInfo.mLineWidth
Tianjie Xub97f7e52018-11-12 16:28:14 -0800539 : 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800540 graphics.drawString(lineInfo.mLineContent.getIterator(), x, baseLine);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800541
542 mVerticalOffset += lineHeight;
543 }
544
545 // Encodes the metadata of the current localized image as pixels.
546 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
547 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
548 for (int i = 0; i < info.size(); i++) {
549 int[] pixel = {info.get(i)};
550 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
551 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700552 }
553
Tianjie Xub97f7e52018-11-12 16:28:14 -0800554 /**
Tianjie Xub8564e12018-11-12 17:06:14 -0800555 * Redraws the image with the new width and new height.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800556 *
Tianjie Xub8564e12018-11-12 17:06:14 -0800557 * @param width the new width of the image in pixels.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800558 * @param height the new height of the image in pixels.
559 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800560 private void resize(int width, int height) {
561 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800562 Graphics2D graphic = resizedImage.createGraphics();
563 graphic.drawImage(mBufferedImage, 0, 0, null);
564 graphic.dispose();
Tianjie Xu721f6792018-10-08 17:04:54 -0700565
Tianjie Xub97f7e52018-11-12 16:28:14 -0800566 mBufferedImage = resizedImage;
Tianjie Xub8564e12018-11-12 17:06:14 -0800567 mImageWidth = width;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800568 mImageHeight = height;
Tianjie Xu721f6792018-10-08 17:04:54 -0700569 }
570
Tianjie Xub97f7e52018-11-12 16:28:14 -0800571 /**
572 * This function draws the font characters and saves the result to outputPath.
573 *
574 * @param localizedTextMap a map from locale to its translated text string
575 * @param outputPath the path to write the generated image file.
576 * @throws FontFormatException if there's a format error in one of the font file
577 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
578 * write the image file.
579 */
580 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath)
581 throws FontFormatException, IOException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800582 FontMetrics defaultFontMetrics =
583 createGraphics(Locale.forLanguageTag("en")).getFontMetrics();
584 mDefaultFont = defaultFontMetrics.getFont();
585 mAndroidStringWidth = defaultFontMetrics.stringWidth(ANDROID_STRING);
586
Tianjie Xub97f7e52018-11-12 16:28:14 -0800587 Map<String, Integer> languageCount = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800588 int textWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800589 for (Locale locale : localizedTextMap.keySet()) {
590 String language = locale.getLanguage();
591 languageCount.put(language, languageCount.getOrDefault(language, 0) + 1);
Tianjie Xub8564e12018-11-12 17:06:14 -0800592 textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800593 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700594
Tianjie Xub8564e12018-11-12 17:06:14 -0800595 // Removes the black margins to reduce the size of the image.
596 resize(textWidth, mImageHeight);
597
Tianjie Xub97f7e52018-11-12 16:28:14 -0800598 for (Locale locale : localizedTextMap.keySet()) {
599 Integer count = languageCount.get(locale.getLanguage());
600 // Recovery expects en-US instead of en_US.
601 String languageTag = locale.toLanguageTag();
602 if (count == 1) {
603 // Make the last country variant for a given language be the catch-all for that
604 // language.
605 languageTag = locale.getLanguage();
606 } else {
607 languageCount.put(locale.getLanguage(), count - 1);
608 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700609
Tianjie Xub8564e12018-11-12 17:06:14 -0800610 drawText(localizedTextMap.get(locale), locale, languageTag);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800611 }
612
Tianjie Xub8564e12018-11-12 17:06:14 -0800613 resize(mImageWidth, mVerticalOffset);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800614 ImageIO.write(mBufferedImage, "png", new File(outputPath));
615 }
616
617 /** Prints the helper message. */
618 public static void printUsage(Options options) {
619 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
620 }
621
622 /** Creates the command line options. */
623 public static Options createOptions() {
624 Options options = new Options();
625 options.addOption(
626 OptionBuilder.withLongOpt("image_width")
627 .withDescription("The initial width of the image in pixels.")
628 .hasArgs(1)
629 .isRequired()
630 .create());
631
632 options.addOption(
633 OptionBuilder.withLongOpt("text_name")
634 .withDescription(
635 "The description of the text string, e.g. recovery_erasing")
636 .hasArgs(1)
637 .isRequired()
638 .create());
639
640 options.addOption(
641 OptionBuilder.withLongOpt("font_dir")
642 .withDescription(
643 "The directory that contains all the support font format files, "
644 + "e.g. $OUT/system/fonts/")
645 .hasArgs(1)
646 .isRequired()
647 .create());
648
649 options.addOption(
650 OptionBuilder.withLongOpt("resource_dir")
651 .withDescription(
652 "The resource directory that contains all the translated strings in"
653 + " xml format, e.g."
654 + " bootable/recovery/tools/recovery_l10n/res/")
655 .hasArgs(1)
656 .isRequired()
657 .create());
658
659 options.addOption(
660 OptionBuilder.withLongOpt("output_file")
Tianjie Xub8564e12018-11-12 17:06:14 -0800661 .withDescription("Path to the generated image.")
Tianjie Xub97f7e52018-11-12 16:28:14 -0800662 .hasArgs(1)
663 .isRequired()
664 .create());
665
Tianjie Xub8564e12018-11-12 17:06:14 -0800666 options.addOption(
667 OptionBuilder.withLongOpt("center_alignment")
668 .withDescription("Align the text in the center of the screen.")
669 .hasArg(false)
670 .create());
671
Tianjie Xu7b636b62018-11-14 16:25:42 -0800672 options.addOption(
673 OptionBuilder.withLongOpt("verbose")
674 .withDescription("Output the logging above info level.")
675 .hasArg(false)
676 .create());
677
678 options.addOption(
679 OptionBuilder.withLongOpt("locales")
680 .withDescription("A list of android locales separated by ',' e.g."
681 + " 'af,en,zh-rTW'")
682 .hasArg(true)
683 .create());
684
Tianjie Xub97f7e52018-11-12 16:28:14 -0800685 return options;
686 }
687
688 /** The main function parses the command line options and generates the desired text image. */
689 public static void main(String[] args)
690 throws NumberFormatException, IOException, FontFormatException,
691 LocalizedStringNotFoundException {
692 Options options = createOptions();
693 CommandLine cmd;
694 try {
695 cmd = new GnuParser().parse(options, args);
696 } catch (ParseException e) {
697 System.err.println(e.getMessage());
698 printUsage(options);
699 return;
700 }
701
702 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
703
Tianjie Xu7b636b62018-11-14 16:25:42 -0800704 if (cmd.hasOption("verbose")) {
705 LOGGER.setLevel(Level.INFO);
706 } else {
707 LOGGER.setLevel(Level.WARNING);
708 }
709
Tianjie Xub97f7e52018-11-12 16:28:14 -0800710 ImageGenerator imageGenerator =
711 new ImageGenerator(
712 imageWidth,
713 cmd.getOptionValue("text_name"),
714 DEFAULT_FONT_SIZE,
Tianjie Xub8564e12018-11-12 17:06:14 -0800715 cmd.getOptionValue("font_dir"),
716 cmd.hasOption("center_alignment"));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800717
Tianjie Xu7b636b62018-11-14 16:25:42 -0800718 Set<String> localesSet = null;
719 if (cmd.hasOption("locales")) {
720 String[] localesList = cmd.getOptionValue("locales").split(",");
721 localesSet = new HashSet<>(Arrays.asList(localesList));
722 // Ensures that we have the default locale, all english translations are identical.
723 localesSet.add("en-rAU");
724 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800725 Map<Locale, String> localizedStringMap =
Tianjie Xu7b636b62018-11-14 16:25:42 -0800726 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"),
727 localesSet);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800728 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
729 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700730}