blob: 9d882678a581850c6ccadef670dd9d6949c408aa [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 Xu7b636b62018-11-14 16:25:42 -080049import java.util.logging.Level;
50import java.util.logging.Logger;
Tianjie Xu721f6792018-10-08 17:04:54 -070051
52import javax.imageio.ImageIO;
53import javax.xml.parsers.DocumentBuilder;
54import javax.xml.parsers.DocumentBuilderFactory;
55import javax.xml.parsers.ParserConfigurationException;
56
Tianjie Xub97f7e52018-11-12 16:28:14 -080057/** Command line tool to generate the localized image for recovery mode. */
Tianjie Xu721f6792018-10-08 17:04:54 -070058public class ImageGenerator {
Tianjie Xub97f7e52018-11-12 16:28:14 -080059 // Initial height of the image to draw.
60 private static final int INITIAL_HEIGHT = 20000;
Tianjie Xu721f6792018-10-08 17:04:54 -070061
Tianjie Xub97f7e52018-11-12 16:28:14 -080062 private static final float DEFAULT_FONT_SIZE = 40;
Tianjie Xu721f6792018-10-08 17:04:54 -070063
Tianjie Xu7b636b62018-11-14 16:25:42 -080064 private static final Logger LOGGER = Logger.getLogger(ImageGenerator.class.getName());
65
Tianjie Xub97f7e52018-11-12 16:28:14 -080066 // This is the canvas we used to draw texts.
67 private BufferedImage mBufferedImage;
Tianjie Xu721f6792018-10-08 17:04:54 -070068
Tianjie Xub8564e12018-11-12 17:06:14 -080069 // The width in pixels of our image. The value will be adjusted once when we calculate the
70 // maximum width to fit the wrapped text strings.
71 private int mImageWidth;
Tianjie Xu721f6792018-10-08 17:04:54 -070072
Tianjie Xub97f7e52018-11-12 16:28:14 -080073 // The current height in pixels of our image. We will adjust the value when drawing more texts.
74 private int mImageHeight;
Tianjie Xu721f6792018-10-08 17:04:54 -070075
Tianjie Xub97f7e52018-11-12 16:28:14 -080076 // The current vertical offset in pixels to draw the top edge of new text strings.
77 private int mVerticalOffset;
Tianjie Xu721f6792018-10-08 17:04:54 -070078
Tianjie Xub97f7e52018-11-12 16:28:14 -080079 // The font size to draw the texts.
80 private final float mFontSize;
Tianjie Xu721f6792018-10-08 17:04:54 -070081
Tianjie Xub97f7e52018-11-12 16:28:14 -080082 // The name description of the text to localize. It's used to find the translated strings in the
83 // resource file.
84 private final String mTextName;
Tianjie Xu721f6792018-10-08 17:04:54 -070085
Tianjie Xub97f7e52018-11-12 16:28:14 -080086 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
87 private final String mFontDirPath;
Tianjie Xu721f6792018-10-08 17:04:54 -070088
Tianjie Xub8564e12018-11-12 17:06:14 -080089 // Align the text in the center of the image.
90 private final boolean mCenterAlignment;
91
Tianjie Xu542c6172018-11-13 16:36:41 -080092 // Some localized font cannot draw the word "Android" and some PUNCTUATIONS; we need to fall
93 // back to use our default latin font instead.
94 private static final char[] PUNCTUATIONS = {',', ';', '.', '!' };
95
96 private static final String ANDROID_STRING = "Android";
97
98 // The width of the word "Android" when drawing with the default font.
99 private int mAndroidStringWidth;
100
101 // The default Font to draw latin characters. It's loaded from DEFAULT_FONT_NAME.
102 private Font mDefaultFont;
103 // Cache of the loaded fonts for all languages.
104 private Map<String, Font> mLoadedFontMap;
105
Tianjie Xub97f7e52018-11-12 16:28:14 -0800106 // An explicit map from language to the font name to use.
107 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
108 // And the language-subtag-registry is found in:
109 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
110 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
111 private static final Map<String, String> LANGUAGE_TO_FONT_MAP =
112 new TreeMap<String, String>() {
113 {
114 put("am", "NotoSansEthiopic-Regular");
115 put("ar", "NotoNaskhArabicUI-Regular");
116 put("as", "NotoSansBengaliUI-Regular");
117 put("bn", "NotoSansBengaliUI-Regular");
118 put("fa", "NotoNaskhArabicUI-Regular");
119 put("gu", "NotoSansGujaratiUI-Regular");
120 put("hi", "NotoSansDevanagariUI-Regular");
121 put("hy", "NotoSansArmenian-Regular");
122 put("iw", "NotoSansHebrew-Regular");
123 put("ja", "NotoSansCJK-Regular");
124 put("ka", "NotoSansGeorgian-Regular");
125 put("ko", "NotoSansCJK-Regular");
126 put("km", "NotoSansKhmerUI-Regular");
127 put("kn", "NotoSansKannadaUI-Regular");
128 put("lo", "NotoSansLaoUI-Regular");
129 put("ml", "NotoSansMalayalamUI-Regular");
130 put("mr", "NotoSansDevanagariUI-Regular");
131 put("my", "NotoSansMyanmarUI-Regular");
132 put("ne", "NotoSansDevanagariUI-Regular");
133 put("or", "NotoSansOriya-Regular");
134 put("pa", "NotoSansGurmukhiUI-Regular");
135 put("si", "NotoSansSinhala-Regular");
136 put("ta", "NotoSansTamilUI-Regular");
137 put("te", "NotoSansTeluguUI-Regular");
138 put("th", "NotoSansThaiUI-Regular");
139 put("ur", "NotoNaskhArabicUI-Regular");
140 put("zh", "NotoSansCJK-Regular");
141 }
142 };
Tianjie Xu721f6792018-10-08 17:04:54 -0700143
Tianjie Xub97f7e52018-11-12 16:28:14 -0800144 // Languages that write from right to left.
145 private static final Set<String> RTL_LANGUAGE =
146 new HashSet<String>() {
147 {
148 add("ar"); // Arabic
149 add("fa"); // Persian
150 add("he"); // Hebrew
151 add("iw"); // Hebrew
152 add("ur"); // Urdu
153 }
154 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700155
Tianjie Xub97f7e52018-11-12 16:28:14 -0800156 // Languages that breaks on arbitrary characters.
Tianjie Xub8564e12018-11-12 17:06:14 -0800157 // TODO(xunchang) switch to icu library if possible. For example, for Thai and Khmer, there is
158 // no space between words; and word breaking is based on grammatical analysis and on word
159 // matching in dictionaries.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800160 private static final Set<String> LOGOGRAM_LANGUAGE =
161 new HashSet<String>() {
162 {
163 add("ja"); // Japanese
164 add("km"); // Khmer
165 add("ko"); // Korean
166 add("lo"); // Lao
Tianjie Xub8564e12018-11-12 17:06:14 -0800167 add("th"); // Thai
Tianjie Xub97f7e52018-11-12 16:28:14 -0800168 add("zh"); // Chinese
169 }
170 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700171
Tianjie Xub97f7e52018-11-12 16:28:14 -0800172 /** Exception to indicate the failure to find the translated text strings. */
173 public static class LocalizedStringNotFoundException extends Exception {
174 public LocalizedStringNotFoundException(String message) {
175 super(message);
176 }
177
178 public LocalizedStringNotFoundException(String message, Throwable cause) {
179 super(message, cause);
180 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700181 }
182
Tianjie Xu542c6172018-11-13 16:36:41 -0800183 /**
184 * This class maintains the content of wrapped text, the attributes to draw these text, and
185 * the width of each wrapped lines.
186 */
187 private class WrappedTextInfo {
188 /** LineInfo holds the AttributedString and width of each wrapped line. */
189 private class LineInfo {
190 public AttributedString mLineContent;
191 public int mLineWidth;
192
193 LineInfo(AttributedString text, int width) {
194 mLineContent = text;
195 mLineWidth = width;
196 }
197 }
198
199 // Maintains the content of each line, as well as the width needed to draw these lines for
200 // a given language.
201 public List<LineInfo> mWrappedLines;
202
203 WrappedTextInfo() {
204 mWrappedLines = new ArrayList<>();
205 }
206
207 /**
208 * Checks if the given text has words "Android" and some PUNCTUATIONS. If it does, and its
209 * associated textFont cannot display them correctly (e.g. for persian and hebrew); sets the
210 * attributes of these substrings to use our default font instead.
211 *
212 * @param text the input string to perform the check on
213 * @param width the pre-calculated width for the given text
214 * @param textFont the localized font to draw the input string
215 * @param fallbackFont our default font to draw latin characters
216 */
217 public void addLine(String text, int width, Font textFont, Font fallbackFont) {
218 AttributedString attributedText = new AttributedString(text);
219 attributedText.addAttribute(TextAttribute.FONT, textFont);
220 attributedText.addAttribute(TextAttribute.SIZE, mFontSize);
221
222 // Skips the check if we don't specify a fallbackFont.
223 if (fallbackFont != null) {
224 // Adds the attribute to use default font to draw the word "Android".
225 if (text.contains(ANDROID_STRING)
226 && textFont.canDisplayUpTo(ANDROID_STRING) != -1) {
227 int index = text.indexOf(ANDROID_STRING);
228 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
229 index + ANDROID_STRING.length());
230 }
231
232 // Adds the attribute to use default font to draw the PUNCTUATIONS ", . !"
233 for (char punctuation : PUNCTUATIONS) {
234 if (text.indexOf(punctuation) != -1 && !textFont.canDisplay(punctuation)) {
235 int index = 0;
236 while ((index = text.indexOf(punctuation, index)) != -1) {
237 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
238 index + 1);
239 index += 1;
240 }
241 }
242 }
243 }
244
245 mWrappedLines.add(new LineInfo(attributedText, width));
246 }
247 }
248
Tianjie Xub97f7e52018-11-12 16:28:14 -0800249 /** Initailizes the fields of the image image. */
Tianjie Xub8564e12018-11-12 17:06:14 -0800250 public ImageGenerator(
251 int initialImageWidth,
252 String textName,
253 float fontSize,
254 String fontDirPath,
255 boolean centerAlignment) {
256 mImageWidth = initialImageWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800257 mImageHeight = INITIAL_HEIGHT;
258 mVerticalOffset = 0;
Tianjie Xu721f6792018-10-08 17:04:54 -0700259
Tianjie Xub97f7e52018-11-12 16:28:14 -0800260 // Initialize the canvas with the default height.
261 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xu721f6792018-10-08 17:04:54 -0700262
Tianjie Xub97f7e52018-11-12 16:28:14 -0800263 mTextName = textName;
264 mFontSize = fontSize;
265 mFontDirPath = fontDirPath;
Tianjie Xu542c6172018-11-13 16:36:41 -0800266 mLoadedFontMap = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800267
268 mCenterAlignment = centerAlignment;
Tianjie Xu721f6792018-10-08 17:04:54 -0700269 }
270
Tianjie Xub97f7e52018-11-12 16:28:14 -0800271 /**
272 * Finds the translated text string for the given textName by parsing the resourceFile. Example
273 * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android">
274 * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate
275 * wird installiert"</string> </resources>
276 *
277 * @param resourceFile the input resource file in xml format.
278 * @param textName the name description of the text.
279 * @return the string representation of the translated text.
280 */
281 private String getTextString(File resourceFile, String textName)
282 throws IOException, ParserConfigurationException, org.xml.sax.SAXException,
283 LocalizedStringNotFoundException {
284 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
285 DocumentBuilder db = builder.newDocumentBuilder();
Tianjie Xu721f6792018-10-08 17:04:54 -0700286
Tianjie Xub97f7e52018-11-12 16:28:14 -0800287 Document doc = db.parse(resourceFile);
288 doc.getDocumentElement().normalize();
Tianjie Xu721f6792018-10-08 17:04:54 -0700289
Tianjie Xub97f7e52018-11-12 16:28:14 -0800290 NodeList nodeList = doc.getElementsByTagName("string");
291 for (int i = 0; i < nodeList.getLength(); i++) {
292 Node node = nodeList.item(i);
293 String name = node.getAttributes().getNamedItem("name").getNodeValue();
294 if (name.equals(textName)) {
295 return node.getTextContent();
296 }
297 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700298
Tianjie Xu721f6792018-10-08 17:04:54 -0700299 throw new LocalizedStringNotFoundException(
Tianjie Xub97f7e52018-11-12 16:28:14 -0800300 textName + " not found in " + resourceFile.getName());
Tianjie Xu721f6792018-10-08 17:04:54 -0700301 }
302
Tianjie Xub97f7e52018-11-12 16:28:14 -0800303 /** Constructs the locale from the name of the resource file. */
304 private Locale getLocaleFromFilename(String filename) throws IOException {
305 // Gets the locale string by trimming the top "values-".
306 String localeString = filename.substring(7);
307 if (localeString.matches("[A-Za-z]+")) {
308 return Locale.forLanguageTag(localeString);
309 }
310 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
311 // "${Language}-r${Region}". e.g. en-rGB
312 String[] tokens = localeString.split("-r");
313 return Locale.forLanguageTag(String.join("-", tokens));
314 }
315 if (localeString.startsWith("b+")) {
316 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
317 String[] tokens = localeString.substring(2).split("\\+");
318 return Locale.forLanguageTag(String.join("-", tokens));
319 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700320
Tianjie Xub97f7e52018-11-12 16:28:14 -0800321 throw new IOException("Unrecognized locale string " + localeString);
Tianjie Xu721f6792018-10-08 17:04:54 -0700322 }
323
Tianjie Xub97f7e52018-11-12 16:28:14 -0800324 /**
325 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
326 * directory and collect the translated text.
327 *
328 * @param resourcePath the path to the resource directory
Tianjie Xu7b636b62018-11-14 16:25:42 -0800329 * @param localesSet a list of supported locales; resources of other locales will be omitted.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800330 * @return a map with the locale as key, and translated text as value
331 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
332 * locale
333 */
Tianjie Xu7b636b62018-11-14 16:25:42 -0800334 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath,
335 Set<String> localesSet) throws IOException, LocalizedStringNotFoundException {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800336 File resourceDir = new File(resourcePath);
337 if (!resourceDir.isDirectory()) {
338 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
339 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700340
Tianjie Xub97f7e52018-11-12 16:28:14 -0800341 Map<Locale, String> result =
342 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus
343 // recovery can find the most relevant locale when going down the list.
344 new TreeMap<>(
345 (Locale l1, Locale l2) -> {
346 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
347 return 0;
348 }
349 if (l1.getLanguage().equals(l2.toLanguageTag())) {
350 return -1;
351 }
352 if (l2.getLanguage().equals(l1.toLanguageTag())) {
353 return 1;
354 }
355 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
356 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700357
Tianjie Xub97f7e52018-11-12 16:28:14 -0800358 // Find all the localized resource subdirectories in the format of values-$LOCALE
359 String[] nameList =
360 resourceDir.list((File file, String name) -> name.startsWith("values-"));
361 for (String name : nameList) {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800362 String localeString = name.substring(7);
363 if (localesSet != null && !localesSet.contains(localeString)) {
364 LOGGER.info("Skip parsing text for locale " + localeString);
365 continue;
366 }
367
Tianjie Xub97f7e52018-11-12 16:28:14 -0800368 File textFile = new File(resourcePath, name + "/strings.xml");
369 String localizedText;
370 try {
371 localizedText = getTextString(textFile, mTextName);
372 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
373 throw new LocalizedStringNotFoundException(
374 "Failed to read the translated text for locale " + name, e);
375 }
376
377 Locale locale = getLocaleFromFilename(name);
378 // Removes the double quotation mark from the text.
379 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
380 }
381
382 return result;
383 }
384
385 /**
386 * Returns a font object associated given the given locale
387 *
388 * @throws IOException if the font file fails to open
389 * @throws FontFormatException if the font file doesn't have the expected format
390 */
391 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800392 if (mLoadedFontMap.containsKey(language)) {
393 return mLoadedFontMap.get(language);
394 }
395
Tianjie Xub97f7e52018-11-12 16:28:14 -0800396 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
397 String[] suffixes = {".otf", ".ttf", ".ttc"};
398 for (String suffix : suffixes) {
399 File fontFile = new File(mFontDirPath, fontName + suffix);
400 if (fontFile.isFile()) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800401 Font result = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
402 mLoadedFontMap.put(language, result);
403 return result;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800404 }
405 }
406
407 throw new IOException(
408 "Can not find the font file " + fontName + " for language " + language);
409 }
410
411 /** Separates the text string by spaces and wraps it by words. */
Tianjie Xu542c6172018-11-13 16:36:41 -0800412 private WrappedTextInfo wrapTextByWords(String text, FontMetrics metrics) {
413 WrappedTextInfo info = new WrappedTextInfo();
Tianjie Xub97f7e52018-11-12 16:28:14 -0800414 StringTokenizer st = new StringTokenizer(text, " \n");
415
Tianjie Xu542c6172018-11-13 16:36:41 -0800416 int lineWidth = 0; // Width of the processed words of the current line.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800417 StringBuilder line = new StringBuilder();
418 while (st.hasMoreTokens()) {
419 String token = st.nextToken();
Tianjie Xu542c6172018-11-13 16:36:41 -0800420 int tokenWidth = metrics.stringWidth(token + " ");
421 // Handles the width mismatch of the word "Android" between different fonts.
422 if (token.contains(ANDROID_STRING)
423 && metrics.getFont().canDisplayUpTo(ANDROID_STRING) != -1) {
424 tokenWidth = tokenWidth - metrics.stringWidth(ANDROID_STRING) + mAndroidStringWidth;
425 }
426
427 if (lineWidth + tokenWidth > mImageWidth) {
428 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
429
Tianjie Xub97f7e52018-11-12 16:28:14 -0800430 line = new StringBuilder();
Tianjie Xu542c6172018-11-13 16:36:41 -0800431 lineWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800432 }
433 line.append(token).append(" ");
Tianjie Xu542c6172018-11-13 16:36:41 -0800434 lineWidth += tokenWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800435 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800436
Tianjie Xu542c6172018-11-13 16:36:41 -0800437 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
438
439 return info;
Tianjie Xu721f6792018-10-08 17:04:54 -0700440 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700441
Tianjie Xub97f7e52018-11-12 16:28:14 -0800442 /** One character is a word for CJK. */
Tianjie Xu542c6172018-11-13 16:36:41 -0800443 private WrappedTextInfo wrapTextByCharacters(String text, FontMetrics metrics) {
444 WrappedTextInfo info = new WrappedTextInfo();
445 // TODO (xunchang) handle the text wrapping with logogram language mixed with latin.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800446 StringBuilder line = new StringBuilder();
447 for (char token : text.toCharArray()) {
448 if (metrics.stringWidth(line + Character.toString(token)) > mImageWidth) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800449 info.addLine(line.toString(), metrics.stringWidth(line.toString()),
450 metrics.getFont(), null);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800451 line = new StringBuilder();
452 }
453 line.append(token);
454 }
Tianjie Xu542c6172018-11-13 16:36:41 -0800455 info.addLine(line.toString(), metrics.stringWidth(line.toString()), metrics.getFont(),
456 null);
Tianjie Xu22dd0192018-10-17 15:39:00 -0700457
Tianjie Xu542c6172018-11-13 16:36:41 -0800458 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700459 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700460
Tianjie Xub97f7e52018-11-12 16:28:14 -0800461 /**
462 * Wraps the text with a maximum of mImageWidth pixels per line.
463 *
464 * @param text the string representation of text to wrap
465 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
466 * the text given its string representation
Tianjie Xu542c6172018-11-13 16:36:41 -0800467 * @return a WrappedTextInfo class with the width of each AttributedString smaller than
468 * mImageWidth pixels
Tianjie Xub97f7e52018-11-12 16:28:14 -0800469 */
Tianjie Xu542c6172018-11-13 16:36:41 -0800470 private WrappedTextInfo wrapText(String text, FontMetrics metrics, String language) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800471 if (LOGOGRAM_LANGUAGE.contains(language)) {
472 return wrapTextByCharacters(text, metrics);
473 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700474
Tianjie Xub97f7e52018-11-12 16:28:14 -0800475 return wrapTextByWords(text, metrics);
Tianjie Xu721f6792018-10-08 17:04:54 -0700476 }
Tianjie Xu22dd0192018-10-17 15:39:00 -0700477
Tianjie Xub97f7e52018-11-12 16:28:14 -0800478 /**
479 * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the
480 * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h =
481 * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc =
482 * reinterpret_cast<char*>(&row[5]);
483 */
484 private List<Integer> encodeTextInfo(int width, int height, String locale) {
485 List<Integer> info =
486 new ArrayList<>(
487 Arrays.asList(
488 width & 0xff,
489 width >> 8,
490 height & 0xff,
491 height >> 8,
492 locale.length()));
Tianjie Xu721f6792018-10-08 17:04:54 -0700493
Tianjie Xub97f7e52018-11-12 16:28:14 -0800494 byte[] localeBytes = locale.getBytes();
495 for (byte b : localeBytes) {
496 info.add((int) b);
497 }
498 info.add(0);
Tianjie Xu721f6792018-10-08 17:04:54 -0700499
Tianjie Xub97f7e52018-11-12 16:28:14 -0800500 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700501 }
502
Tianjie Xub8564e12018-11-12 17:06:14 -0800503 /** Returns Graphics2D object that uses the given locale. */
504 private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException {
505 Graphics2D graphics = mBufferedImage.createGraphics();
506 graphics.setColor(Color.WHITE);
507 graphics.setRenderingHint(
508 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
509 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
510
511 return graphics;
512 }
513
514 /** Returns the maximum screen width needed to fit the given text after wrapping. */
515 private int measureTextWidth(String text, Locale locale)
516 throws IOException, FontFormatException {
517 Graphics2D graphics = createGraphics(locale);
518 FontMetrics fontMetrics = graphics.getFontMetrics();
Tianjie Xu542c6172018-11-13 16:36:41 -0800519 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics, locale.getLanguage());
Tianjie Xub8564e12018-11-12 17:06:14 -0800520
521 int textWidth = 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800522 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
523 textWidth = Math.max(textWidth, lineInfo.mLineWidth);
Tianjie Xub8564e12018-11-12 17:06:14 -0800524 }
525
526 // This may happen if one single word is larger than the image width.
527 if (textWidth > mImageWidth) {
528 throw new IllegalStateException(
529 "Wrapped text width "
530 + textWidth
531 + " is larger than image width "
532 + mImageWidth
533 + " for locale: "
534 + locale);
535 }
536
537 return textWidth;
538 }
539
Tianjie Xub97f7e52018-11-12 16:28:14 -0800540 /**
541 * Draws the text string on the canvas for given locale.
542 *
543 * @param text the string to draw on canvas
544 * @param locale the current locale tag of the string to draw
545 * @throws IOException if we cannot find the corresponding font file for the given locale.
546 * @throws FontFormatException if we failed to load the font file for the given locale.
547 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800548 private void drawText(String text, Locale locale, String languageTag)
Tianjie Xub97f7e52018-11-12 16:28:14 -0800549 throws IOException, FontFormatException {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800550 LOGGER.info("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800551
Tianjie Xub8564e12018-11-12 17:06:14 -0800552 Graphics2D graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800553 FontMetrics fontMetrics = graphics.getFontMetrics();
Tianjie Xu542c6172018-11-13 16:36:41 -0800554 WrappedTextInfo wrappedTextInfo = wrapText(text, fontMetrics, locale.getLanguage());
Tianjie Xub97f7e52018-11-12 16:28:14 -0800555
556 // Marks the start y offset for the text image of current locale; and reserves one line to
557 // encode the image metadata.
558 int currentImageStart = mVerticalOffset;
559 mVerticalOffset += 1;
Tianjie Xu542c6172018-11-13 16:36:41 -0800560 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800561 int lineHeight = fontMetrics.getHeight();
562 // Doubles the height of the image if we are short of space.
563 if (mVerticalOffset + lineHeight >= mImageHeight) {
Tianjie Xub8564e12018-11-12 17:06:14 -0800564 resize(mImageWidth, mImageHeight * 2);
Tianjie Xu542c6172018-11-13 16:36:41 -0800565 // Recreates the graphics since it's attached to the buffered image.
566 graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800567 }
568
569 // Draws the text at mVerticalOffset and increments the offset with line space.
570 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
571
572 // Draws from right if it's an RTL language.
573 int x =
Tianjie Xub8564e12018-11-12 17:06:14 -0800574 mCenterAlignment
Tianjie Xu542c6172018-11-13 16:36:41 -0800575 ? (mImageWidth - lineInfo.mLineWidth) / 2
Tianjie Xub97f7e52018-11-12 16:28:14 -0800576 : RTL_LANGUAGE.contains(languageTag)
Tianjie Xu542c6172018-11-13 16:36:41 -0800577 ? mImageWidth - lineInfo.mLineWidth
Tianjie Xub97f7e52018-11-12 16:28:14 -0800578 : 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800579 graphics.drawString(lineInfo.mLineContent.getIterator(), x, baseLine);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800580
581 mVerticalOffset += lineHeight;
582 }
583
584 // Encodes the metadata of the current localized image as pixels.
585 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
586 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
587 for (int i = 0; i < info.size(); i++) {
588 int[] pixel = {info.get(i)};
589 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
590 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700591 }
592
Tianjie Xub97f7e52018-11-12 16:28:14 -0800593 /**
Tianjie Xub8564e12018-11-12 17:06:14 -0800594 * Redraws the image with the new width and new height.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800595 *
Tianjie Xub8564e12018-11-12 17:06:14 -0800596 * @param width the new width of the image in pixels.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800597 * @param height the new height of the image in pixels.
598 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800599 private void resize(int width, int height) {
600 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800601 Graphics2D graphic = resizedImage.createGraphics();
602 graphic.drawImage(mBufferedImage, 0, 0, null);
603 graphic.dispose();
Tianjie Xu721f6792018-10-08 17:04:54 -0700604
Tianjie Xub97f7e52018-11-12 16:28:14 -0800605 mBufferedImage = resizedImage;
Tianjie Xub8564e12018-11-12 17:06:14 -0800606 mImageWidth = width;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800607 mImageHeight = height;
Tianjie Xu721f6792018-10-08 17:04:54 -0700608 }
609
Tianjie Xub97f7e52018-11-12 16:28:14 -0800610 /**
611 * This function draws the font characters and saves the result to outputPath.
612 *
613 * @param localizedTextMap a map from locale to its translated text string
614 * @param outputPath the path to write the generated image file.
615 * @throws FontFormatException if there's a format error in one of the font file
616 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
617 * write the image file.
618 */
619 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath)
620 throws FontFormatException, IOException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800621 FontMetrics defaultFontMetrics =
622 createGraphics(Locale.forLanguageTag("en")).getFontMetrics();
623 mDefaultFont = defaultFontMetrics.getFont();
624 mAndroidStringWidth = defaultFontMetrics.stringWidth(ANDROID_STRING);
625
Tianjie Xub97f7e52018-11-12 16:28:14 -0800626 Map<String, Integer> languageCount = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800627 int textWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800628 for (Locale locale : localizedTextMap.keySet()) {
629 String language = locale.getLanguage();
630 languageCount.put(language, languageCount.getOrDefault(language, 0) + 1);
Tianjie Xub8564e12018-11-12 17:06:14 -0800631 textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800632 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700633
Tianjie Xub8564e12018-11-12 17:06:14 -0800634 // Removes the black margins to reduce the size of the image.
635 resize(textWidth, mImageHeight);
636
Tianjie Xub97f7e52018-11-12 16:28:14 -0800637 for (Locale locale : localizedTextMap.keySet()) {
638 Integer count = languageCount.get(locale.getLanguage());
639 // Recovery expects en-US instead of en_US.
640 String languageTag = locale.toLanguageTag();
641 if (count == 1) {
642 // Make the last country variant for a given language be the catch-all for that
643 // language.
644 languageTag = locale.getLanguage();
645 } else {
646 languageCount.put(locale.getLanguage(), count - 1);
647 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700648
Tianjie Xub8564e12018-11-12 17:06:14 -0800649 drawText(localizedTextMap.get(locale), locale, languageTag);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800650 }
651
Tianjie Xub8564e12018-11-12 17:06:14 -0800652 resize(mImageWidth, mVerticalOffset);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800653 ImageIO.write(mBufferedImage, "png", new File(outputPath));
654 }
655
656 /** Prints the helper message. */
657 public static void printUsage(Options options) {
658 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
659 }
660
661 /** Creates the command line options. */
662 public static Options createOptions() {
663 Options options = new Options();
664 options.addOption(
665 OptionBuilder.withLongOpt("image_width")
666 .withDescription("The initial width of the image in pixels.")
667 .hasArgs(1)
668 .isRequired()
669 .create());
670
671 options.addOption(
672 OptionBuilder.withLongOpt("text_name")
673 .withDescription(
674 "The description of the text string, e.g. recovery_erasing")
675 .hasArgs(1)
676 .isRequired()
677 .create());
678
679 options.addOption(
680 OptionBuilder.withLongOpt("font_dir")
681 .withDescription(
682 "The directory that contains all the support font format files, "
683 + "e.g. $OUT/system/fonts/")
684 .hasArgs(1)
685 .isRequired()
686 .create());
687
688 options.addOption(
689 OptionBuilder.withLongOpt("resource_dir")
690 .withDescription(
691 "The resource directory that contains all the translated strings in"
692 + " xml format, e.g."
693 + " bootable/recovery/tools/recovery_l10n/res/")
694 .hasArgs(1)
695 .isRequired()
696 .create());
697
698 options.addOption(
699 OptionBuilder.withLongOpt("output_file")
Tianjie Xub8564e12018-11-12 17:06:14 -0800700 .withDescription("Path to the generated image.")
Tianjie Xub97f7e52018-11-12 16:28:14 -0800701 .hasArgs(1)
702 .isRequired()
703 .create());
704
Tianjie Xub8564e12018-11-12 17:06:14 -0800705 options.addOption(
706 OptionBuilder.withLongOpt("center_alignment")
707 .withDescription("Align the text in the center of the screen.")
708 .hasArg(false)
709 .create());
710
Tianjie Xu7b636b62018-11-14 16:25:42 -0800711 options.addOption(
712 OptionBuilder.withLongOpt("verbose")
713 .withDescription("Output the logging above info level.")
714 .hasArg(false)
715 .create());
716
717 options.addOption(
718 OptionBuilder.withLongOpt("locales")
719 .withDescription("A list of android locales separated by ',' e.g."
720 + " 'af,en,zh-rTW'")
721 .hasArg(true)
722 .create());
723
Tianjie Xub97f7e52018-11-12 16:28:14 -0800724 return options;
725 }
726
727 /** The main function parses the command line options and generates the desired text image. */
728 public static void main(String[] args)
729 throws NumberFormatException, IOException, FontFormatException,
730 LocalizedStringNotFoundException {
731 Options options = createOptions();
732 CommandLine cmd;
733 try {
734 cmd = new GnuParser().parse(options, args);
735 } catch (ParseException e) {
736 System.err.println(e.getMessage());
737 printUsage(options);
738 return;
739 }
740
741 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
742
Tianjie Xu7b636b62018-11-14 16:25:42 -0800743 if (cmd.hasOption("verbose")) {
744 LOGGER.setLevel(Level.INFO);
745 } else {
746 LOGGER.setLevel(Level.WARNING);
747 }
748
Tianjie Xub97f7e52018-11-12 16:28:14 -0800749 ImageGenerator imageGenerator =
750 new ImageGenerator(
751 imageWidth,
752 cmd.getOptionValue("text_name"),
753 DEFAULT_FONT_SIZE,
Tianjie Xub8564e12018-11-12 17:06:14 -0800754 cmd.getOptionValue("font_dir"),
755 cmd.hasOption("center_alignment"));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800756
Tianjie Xu7b636b62018-11-14 16:25:42 -0800757 Set<String> localesSet = null;
758 if (cmd.hasOption("locales")) {
759 String[] localesList = cmd.getOptionValue("locales").split(",");
760 localesSet = new HashSet<>(Arrays.asList(localesList));
761 // Ensures that we have the default locale, all english translations are identical.
762 localesSet.add("en-rAU");
763 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800764 Map<Locale, String> localizedStringMap =
Tianjie Xu7b636b62018-11-14 16:25:42 -0800765 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"),
766 localesSet);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800767 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
768 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700769}