blob: 1da43e5c67966dfb5828da3144549c363338d869 [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;
xunchanga48f00a2018-11-26 15:40:28 -080044import java.util.HashMap;
Tianjie Xu22dd0192018-10-17 15:39:00 -070045import java.util.HashSet;
Tianjie Xu721f6792018-10-08 17:04:54 -070046import java.util.List;
47import java.util.Locale;
48import java.util.Map;
Tianjie Xu22dd0192018-10-17 15:39:00 -070049import java.util.Set;
Tao Bao529bb742018-11-06 11:24:53 -080050import java.util.TreeMap;
Tianjie Xu7b636b62018-11-14 16:25:42 -080051import java.util.logging.Level;
52import java.util.logging.Logger;
Tianjie Xu721f6792018-10-08 17:04:54 -070053
54import javax.imageio.ImageIO;
55import javax.xml.parsers.DocumentBuilder;
56import javax.xml.parsers.DocumentBuilderFactory;
57import javax.xml.parsers.ParserConfigurationException;
58
Tianjie Xub97f7e52018-11-12 16:28:14 -080059/** Command line tool to generate the localized image for recovery mode. */
Tianjie Xu721f6792018-10-08 17:04:54 -070060public class ImageGenerator {
Tianjie Xub97f7e52018-11-12 16:28:14 -080061 // Initial height of the image to draw.
62 private static final int INITIAL_HEIGHT = 20000;
Tianjie Xu721f6792018-10-08 17:04:54 -070063
Tianjie Xub97f7e52018-11-12 16:28:14 -080064 private static final float DEFAULT_FONT_SIZE = 40;
Tianjie Xu721f6792018-10-08 17:04:54 -070065
Tianjie Xu7b636b62018-11-14 16:25:42 -080066 private static final Logger LOGGER = Logger.getLogger(ImageGenerator.class.getName());
67
Tianjie Xub97f7e52018-11-12 16:28:14 -080068 // This is the canvas we used to draw texts.
69 private BufferedImage mBufferedImage;
Tianjie Xu721f6792018-10-08 17:04:54 -070070
Tianjie Xub8564e12018-11-12 17:06:14 -080071 // The width in pixels of our image. The value will be adjusted once when we calculate the
72 // maximum width to fit the wrapped text strings.
73 private int mImageWidth;
Tianjie Xu721f6792018-10-08 17:04:54 -070074
Tianjie Xub97f7e52018-11-12 16:28:14 -080075 // The current height in pixels of our image. We will adjust the value when drawing more texts.
76 private int mImageHeight;
Tianjie Xu721f6792018-10-08 17:04:54 -070077
Tianjie Xub97f7e52018-11-12 16:28:14 -080078 // The current vertical offset in pixels to draw the top edge of new text strings.
79 private int mVerticalOffset;
Tianjie Xu721f6792018-10-08 17:04:54 -070080
Tianjie Xub97f7e52018-11-12 16:28:14 -080081 // The font size to draw the texts.
82 private final float mFontSize;
Tianjie Xu721f6792018-10-08 17:04:54 -070083
Tianjie Xub97f7e52018-11-12 16:28:14 -080084 // The name description of the text to localize. It's used to find the translated strings in the
85 // resource file.
86 private final String mTextName;
Tianjie Xu721f6792018-10-08 17:04:54 -070087
Tianjie Xub97f7e52018-11-12 16:28:14 -080088 // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
89 private final String mFontDirPath;
Tianjie Xu721f6792018-10-08 17:04:54 -070090
Tianjie Xub8564e12018-11-12 17:06:14 -080091 // Align the text in the center of the image.
92 private final boolean mCenterAlignment;
93
Tianjie Xu542c6172018-11-13 16:36:41 -080094 // Some localized font cannot draw the word "Android" and some PUNCTUATIONS; we need to fall
95 // back to use our default latin font instead.
xunchang1eeee452018-11-28 23:30:48 -080096 private static final char[] PUNCTUATIONS = {',', ';', '.', '!', '?'};
Tianjie Xu542c6172018-11-13 16:36:41 -080097
98 private static final String ANDROID_STRING = "Android";
99
100 // The width of the word "Android" when drawing with the default font.
101 private int mAndroidStringWidth;
102
103 // The default Font to draw latin characters. It's loaded from DEFAULT_FONT_NAME.
104 private Font mDefaultFont;
105 // Cache of the loaded fonts for all languages.
106 private Map<String, Font> mLoadedFontMap;
107
Tianjie Xub97f7e52018-11-12 16:28:14 -0800108 // An explicit map from language to the font name to use.
109 // The map is extracted from frameworks/base/data/fonts/fonts.xml.
110 // And the language-subtag-registry is found in:
111 // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
112 private static final String DEFAULT_FONT_NAME = "Roboto-Regular";
113 private static final Map<String, String> LANGUAGE_TO_FONT_MAP =
114 new TreeMap<String, String>() {
115 {
116 put("am", "NotoSansEthiopic-Regular");
117 put("ar", "NotoNaskhArabicUI-Regular");
118 put("as", "NotoSansBengaliUI-Regular");
119 put("bn", "NotoSansBengaliUI-Regular");
120 put("fa", "NotoNaskhArabicUI-Regular");
121 put("gu", "NotoSansGujaratiUI-Regular");
122 put("hi", "NotoSansDevanagariUI-Regular");
123 put("hy", "NotoSansArmenian-Regular");
124 put("iw", "NotoSansHebrew-Regular");
125 put("ja", "NotoSansCJK-Regular");
Marek Jeziorek8845e4d2020-02-26 16:43:36 +0000126 put("ka", "NotoSansGeorgian-VF");
Tianjie Xub97f7e52018-11-12 16:28:14 -0800127 put("ko", "NotoSansCJK-Regular");
128 put("km", "NotoSansKhmerUI-Regular");
129 put("kn", "NotoSansKannadaUI-Regular");
130 put("lo", "NotoSansLaoUI-Regular");
131 put("ml", "NotoSansMalayalamUI-Regular");
132 put("mr", "NotoSansDevanagariUI-Regular");
133 put("my", "NotoSansMyanmarUI-Regular");
134 put("ne", "NotoSansDevanagariUI-Regular");
135 put("or", "NotoSansOriya-Regular");
136 put("pa", "NotoSansGurmukhiUI-Regular");
137 put("si", "NotoSansSinhala-Regular");
138 put("ta", "NotoSansTamilUI-Regular");
139 put("te", "NotoSansTeluguUI-Regular");
140 put("th", "NotoSansThaiUI-Regular");
141 put("ur", "NotoNaskhArabicUI-Regular");
142 put("zh", "NotoSansCJK-Regular");
143 }
144 };
Tianjie Xu721f6792018-10-08 17:04:54 -0700145
Tianjie Xub97f7e52018-11-12 16:28:14 -0800146 // Languages that write from right to left.
147 private static final Set<String> RTL_LANGUAGE =
148 new HashSet<String>() {
149 {
150 add("ar"); // Arabic
151 add("fa"); // Persian
152 add("he"); // Hebrew
153 add("iw"); // Hebrew
154 add("ur"); // Urdu
155 }
156 };
Tianjie Xu22dd0192018-10-17 15:39:00 -0700157
Tianjie Xub97f7e52018-11-12 16:28:14 -0800158 /** Exception to indicate the failure to find the translated text strings. */
159 public static class LocalizedStringNotFoundException extends Exception {
160 public LocalizedStringNotFoundException(String message) {
161 super(message);
162 }
163
164 public LocalizedStringNotFoundException(String message, Throwable cause) {
165 super(message, cause);
166 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700167 }
168
Tianjie Xu542c6172018-11-13 16:36:41 -0800169 /**
170 * This class maintains the content of wrapped text, the attributes to draw these text, and
171 * the width of each wrapped lines.
172 */
173 private class WrappedTextInfo {
174 /** LineInfo holds the AttributedString and width of each wrapped line. */
175 private class LineInfo {
176 public AttributedString mLineContent;
177 public int mLineWidth;
178
179 LineInfo(AttributedString text, int width) {
180 mLineContent = text;
181 mLineWidth = width;
182 }
183 }
184
185 // Maintains the content of each line, as well as the width needed to draw these lines for
186 // a given language.
187 public List<LineInfo> mWrappedLines;
188
189 WrappedTextInfo() {
190 mWrappedLines = new ArrayList<>();
191 }
192
193 /**
194 * Checks if the given text has words "Android" and some PUNCTUATIONS. If it does, and its
195 * associated textFont cannot display them correctly (e.g. for persian and hebrew); sets the
196 * attributes of these substrings to use our default font instead.
197 *
198 * @param text the input string to perform the check on
199 * @param width the pre-calculated width for the given text
200 * @param textFont the localized font to draw the input string
201 * @param fallbackFont our default font to draw latin characters
202 */
203 public void addLine(String text, int width, Font textFont, Font fallbackFont) {
204 AttributedString attributedText = new AttributedString(text);
205 attributedText.addAttribute(TextAttribute.FONT, textFont);
206 attributedText.addAttribute(TextAttribute.SIZE, mFontSize);
207
208 // Skips the check if we don't specify a fallbackFont.
209 if (fallbackFont != null) {
210 // Adds the attribute to use default font to draw the word "Android".
211 if (text.contains(ANDROID_STRING)
212 && textFont.canDisplayUpTo(ANDROID_STRING) != -1) {
213 int index = text.indexOf(ANDROID_STRING);
214 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
215 index + ANDROID_STRING.length());
216 }
217
xunchang1eeee452018-11-28 23:30:48 -0800218 // Adds the attribute to use default font to draw the PUNCTUATIONS ", . ; ! ?"
Tianjie Xu542c6172018-11-13 16:36:41 -0800219 for (char punctuation : PUNCTUATIONS) {
xunchang1eeee452018-11-28 23:30:48 -0800220 // TODO (xunchang) handle the RTL language that has different directions for '?'
Tianjie Xu542c6172018-11-13 16:36:41 -0800221 if (text.indexOf(punctuation) != -1 && !textFont.canDisplay(punctuation)) {
222 int index = 0;
223 while ((index = text.indexOf(punctuation, index)) != -1) {
224 attributedText.addAttribute(TextAttribute.FONT, fallbackFont, index,
225 index + 1);
226 index += 1;
227 }
228 }
229 }
230 }
231
232 mWrappedLines.add(new LineInfo(attributedText, width));
233 }
xunchang1eeee452018-11-28 23:30:48 -0800234
235 /** Merges two WrappedTextInfo. */
236 public void addLines(WrappedTextInfo other) {
237 mWrappedLines.addAll(other.mWrappedLines);
238 }
Tianjie Xu542c6172018-11-13 16:36:41 -0800239 }
240
Tianjie Xub97f7e52018-11-12 16:28:14 -0800241 /** Initailizes the fields of the image image. */
Tianjie Xub8564e12018-11-12 17:06:14 -0800242 public ImageGenerator(
243 int initialImageWidth,
244 String textName,
245 float fontSize,
246 String fontDirPath,
247 boolean centerAlignment) {
248 mImageWidth = initialImageWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800249 mImageHeight = INITIAL_HEIGHT;
250 mVerticalOffset = 0;
Tianjie Xu721f6792018-10-08 17:04:54 -0700251
Tianjie Xub97f7e52018-11-12 16:28:14 -0800252 // Initialize the canvas with the default height.
253 mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xu721f6792018-10-08 17:04:54 -0700254
Tianjie Xub97f7e52018-11-12 16:28:14 -0800255 mTextName = textName;
256 mFontSize = fontSize;
257 mFontDirPath = fontDirPath;
Tianjie Xu542c6172018-11-13 16:36:41 -0800258 mLoadedFontMap = new TreeMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800259
260 mCenterAlignment = centerAlignment;
Tianjie Xu721f6792018-10-08 17:04:54 -0700261 }
262
Tianjie Xub97f7e52018-11-12 16:28:14 -0800263 /**
264 * Finds the translated text string for the given textName by parsing the resourceFile. Example
265 * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android">
266 * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate
267 * wird installiert"</string> </resources>
268 *
269 * @param resourceFile the input resource file in xml format.
270 * @param textName the name description of the text.
271 * @return the string representation of the translated text.
272 */
273 private String getTextString(File resourceFile, String textName)
274 throws IOException, ParserConfigurationException, org.xml.sax.SAXException,
275 LocalizedStringNotFoundException {
276 DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
277 DocumentBuilder db = builder.newDocumentBuilder();
Tianjie Xu721f6792018-10-08 17:04:54 -0700278
Tianjie Xub97f7e52018-11-12 16:28:14 -0800279 Document doc = db.parse(resourceFile);
280 doc.getDocumentElement().normalize();
Tianjie Xu721f6792018-10-08 17:04:54 -0700281
Tianjie Xub97f7e52018-11-12 16:28:14 -0800282 NodeList nodeList = doc.getElementsByTagName("string");
283 for (int i = 0; i < nodeList.getLength(); i++) {
284 Node node = nodeList.item(i);
285 String name = node.getAttributes().getNamedItem("name").getNodeValue();
286 if (name.equals(textName)) {
287 return node.getTextContent();
288 }
289 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700290
Tianjie Xu721f6792018-10-08 17:04:54 -0700291 throw new LocalizedStringNotFoundException(
Tianjie Xub97f7e52018-11-12 16:28:14 -0800292 textName + " not found in " + resourceFile.getName());
Tianjie Xu721f6792018-10-08 17:04:54 -0700293 }
294
Tianjie Xub97f7e52018-11-12 16:28:14 -0800295 /** Constructs the locale from the name of the resource file. */
296 private Locale getLocaleFromFilename(String filename) throws IOException {
297 // Gets the locale string by trimming the top "values-".
298 String localeString = filename.substring(7);
299 if (localeString.matches("[A-Za-z]+")) {
300 return Locale.forLanguageTag(localeString);
301 }
302 if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) {
303 // "${Language}-r${Region}". e.g. en-rGB
304 String[] tokens = localeString.split("-r");
305 return Locale.forLanguageTag(String.join("-", tokens));
306 }
307 if (localeString.startsWith("b+")) {
308 // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}"
309 String[] tokens = localeString.substring(2).split("\\+");
310 return Locale.forLanguageTag(String.join("-", tokens));
311 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700312
Tianjie Xub97f7e52018-11-12 16:28:14 -0800313 throw new IOException("Unrecognized locale string " + localeString);
Tianjie Xu721f6792018-10-08 17:04:54 -0700314 }
315
Tianjie Xub97f7e52018-11-12 16:28:14 -0800316 /**
317 * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource
318 * directory and collect the translated text.
319 *
320 * @param resourcePath the path to the resource directory
Tianjie Xu7b636b62018-11-14 16:25:42 -0800321 * @param localesSet a list of supported locales; resources of other locales will be omitted.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800322 * @return a map with the locale as key, and translated text as value
323 * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given
324 * locale
325 */
Tianjie Xu7b636b62018-11-14 16:25:42 -0800326 public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath,
327 Set<String> localesSet) throws IOException, LocalizedStringNotFoundException {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800328 File resourceDir = new File(resourcePath);
329 if (!resourceDir.isDirectory()) {
330 throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
331 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700332
Tianjie Xub97f7e52018-11-12 16:28:14 -0800333 Map<Locale, String> result =
334 // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus
335 // recovery can find the most relevant locale when going down the list.
336 new TreeMap<>(
337 (Locale l1, Locale l2) -> {
338 if (l1.toLanguageTag().equals(l2.toLanguageTag())) {
339 return 0;
340 }
341 if (l1.getLanguage().equals(l2.toLanguageTag())) {
342 return -1;
343 }
344 if (l2.getLanguage().equals(l1.toLanguageTag())) {
345 return 1;
346 }
347 return l1.toLanguageTag().compareTo(l2.toLanguageTag());
348 });
Tianjie Xu721f6792018-10-08 17:04:54 -0700349
Tianjie Xub97f7e52018-11-12 16:28:14 -0800350 // Find all the localized resource subdirectories in the format of values-$LOCALE
351 String[] nameList =
352 resourceDir.list((File file, String name) -> name.startsWith("values-"));
353 for (String name : nameList) {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800354 String localeString = name.substring(7);
355 if (localesSet != null && !localesSet.contains(localeString)) {
356 LOGGER.info("Skip parsing text for locale " + localeString);
357 continue;
358 }
359
Tianjie Xub97f7e52018-11-12 16:28:14 -0800360 File textFile = new File(resourcePath, name + "/strings.xml");
361 String localizedText;
362 try {
363 localizedText = getTextString(textFile, mTextName);
364 } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) {
365 throw new LocalizedStringNotFoundException(
366 "Failed to read the translated text for locale " + name, e);
367 }
368
369 Locale locale = getLocaleFromFilename(name);
370 // Removes the double quotation mark from the text.
371 result.put(locale, localizedText.substring(1, localizedText.length() - 1));
372 }
373
374 return result;
375 }
376
377 /**
378 * Returns a font object associated given the given locale
379 *
380 * @throws IOException if the font file fails to open
381 * @throws FontFormatException if the font file doesn't have the expected format
382 */
383 private Font loadFontsByLocale(String language) throws IOException, FontFormatException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800384 if (mLoadedFontMap.containsKey(language)) {
385 return mLoadedFontMap.get(language);
386 }
387
Tianjie Xub97f7e52018-11-12 16:28:14 -0800388 String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME);
389 String[] suffixes = {".otf", ".ttf", ".ttc"};
390 for (String suffix : suffixes) {
391 File fontFile = new File(mFontDirPath, fontName + suffix);
392 if (fontFile.isFile()) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800393 Font result = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
394 mLoadedFontMap.put(language, result);
395 return result;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800396 }
397 }
398
399 throw new IOException(
400 "Can not find the font file " + fontName + " for language " + language);
401 }
402
xunchang1eeee452018-11-28 23:30:48 -0800403 /** Wraps the text with a maximum of mImageWidth pixels per line. */
xunchangacacc9d2018-11-26 15:01:39 -0800404 private WrappedTextInfo wrapText(String text, FontMetrics metrics) {
Tianjie Xu542c6172018-11-13 16:36:41 -0800405 WrappedTextInfo info = new WrappedTextInfo();
xunchangacacc9d2018-11-26 15:01:39 -0800406
407 BreakIterator lineBoundary = BreakIterator.getLineInstance();
408 lineBoundary.setText(text);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800409
Tianjie Xu542c6172018-11-13 16:36:41 -0800410 int lineWidth = 0; // Width of the processed words of the current line.
xunchangacacc9d2018-11-26 15:01:39 -0800411 int start = lineBoundary.first();
Tianjie Xub97f7e52018-11-12 16:28:14 -0800412 StringBuilder line = new StringBuilder();
xunchangacacc9d2018-11-26 15:01:39 -0800413 for (int end = lineBoundary.next(); end != BreakIterator.DONE;
414 start = end, end = lineBoundary.next()) {
415 String token = text.substring(start, end);
416 int tokenWidth = metrics.stringWidth(token);
Tianjie Xu542c6172018-11-13 16:36:41 -0800417 // Handles the width mismatch of the word "Android" between different fonts.
418 if (token.contains(ANDROID_STRING)
419 && metrics.getFont().canDisplayUpTo(ANDROID_STRING) != -1) {
420 tokenWidth = tokenWidth - metrics.stringWidth(ANDROID_STRING) + mAndroidStringWidth;
421 }
422
423 if (lineWidth + tokenWidth > mImageWidth) {
424 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
425
Tianjie Xub97f7e52018-11-12 16:28:14 -0800426 line = new StringBuilder();
Tianjie Xu542c6172018-11-13 16:36:41 -0800427 lineWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800428 }
xunchangacacc9d2018-11-26 15:01:39 -0800429 line.append(token);
Tianjie Xu542c6172018-11-13 16:36:41 -0800430 lineWidth += tokenWidth;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800431 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800432
Tianjie Xu542c6172018-11-13 16:36:41 -0800433 info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
434
435 return info;
Tianjie Xu721f6792018-10-08 17:04:54 -0700436 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700437
Tianjie Xub97f7e52018-11-12 16:28:14 -0800438 /**
xunchang1eeee452018-11-28 23:30:48 -0800439 * Handles the special characters of the raw text embedded in the xml file; and wraps the text
440 * with a maximum of mImageWidth pixels per line.
441 *
442 * @param text the string representation of text to wrap
443 * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of
444 * the text given its string representation
445 * @return a WrappedTextInfo class with the width of each AttributedString smaller than
446 * mImageWidth pixels
447 */
448 private WrappedTextInfo processAndWrapText(String text, FontMetrics metrics) {
449 // Apostrophe is escaped in the xml file.
450 String processed = text.replace("\\'", "'");
451 // The separator "\n\n" indicates a new line in the text.
452 String[] lines = processed.split("\\\\n\\\\n");
453 WrappedTextInfo result = new WrappedTextInfo();
454 for (String line : lines) {
455 result.addLines(wrapText(line, metrics));
456 }
457
458 return result;
459 }
460
461 /**
Tianjie Xub97f7e52018-11-12 16:28:14 -0800462 * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the
463 * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h =
464 * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc =
465 * reinterpret_cast<char*>(&row[5]);
466 */
467 private List<Integer> encodeTextInfo(int width, int height, String locale) {
468 List<Integer> info =
469 new ArrayList<>(
470 Arrays.asList(
471 width & 0xff,
472 width >> 8,
473 height & 0xff,
474 height >> 8,
475 locale.length()));
Tianjie Xu721f6792018-10-08 17:04:54 -0700476
Tianjie Xub97f7e52018-11-12 16:28:14 -0800477 byte[] localeBytes = locale.getBytes();
478 for (byte b : localeBytes) {
479 info.add((int) b);
480 }
481 info.add(0);
Tianjie Xu721f6792018-10-08 17:04:54 -0700482
Tianjie Xub97f7e52018-11-12 16:28:14 -0800483 return info;
Tianjie Xu22dd0192018-10-17 15:39:00 -0700484 }
485
Tianjie Xub8564e12018-11-12 17:06:14 -0800486 /** Returns Graphics2D object that uses the given locale. */
487 private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException {
488 Graphics2D graphics = mBufferedImage.createGraphics();
489 graphics.setColor(Color.WHITE);
490 graphics.setRenderingHint(
491 RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
492 graphics.setFont(loadFontsByLocale(locale.getLanguage()));
493
494 return graphics;
495 }
496
497 /** Returns the maximum screen width needed to fit the given text after wrapping. */
498 private int measureTextWidth(String text, Locale locale)
499 throws IOException, FontFormatException {
500 Graphics2D graphics = createGraphics(locale);
501 FontMetrics fontMetrics = graphics.getFontMetrics();
xunchang1eeee452018-11-28 23:30:48 -0800502 WrappedTextInfo wrappedTextInfo = processAndWrapText(text, fontMetrics);
Tianjie Xub8564e12018-11-12 17:06:14 -0800503
504 int textWidth = 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800505 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
506 textWidth = Math.max(textWidth, lineInfo.mLineWidth);
Tianjie Xub8564e12018-11-12 17:06:14 -0800507 }
508
509 // This may happen if one single word is larger than the image width.
510 if (textWidth > mImageWidth) {
511 throw new IllegalStateException(
512 "Wrapped text width "
513 + textWidth
514 + " is larger than image width "
515 + mImageWidth
516 + " for locale: "
517 + locale);
518 }
519
520 return textWidth;
521 }
522
Tianjie Xub97f7e52018-11-12 16:28:14 -0800523 /**
524 * Draws the text string on the canvas for given locale.
525 *
526 * @param text the string to draw on canvas
527 * @param locale the current locale tag of the string to draw
528 * @throws IOException if we cannot find the corresponding font file for the given locale.
529 * @throws FontFormatException if we failed to load the font file for the given locale.
530 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800531 private void drawText(String text, Locale locale, String languageTag)
Tianjie Xub97f7e52018-11-12 16:28:14 -0800532 throws IOException, FontFormatException {
Tianjie Xu7b636b62018-11-14 16:25:42 -0800533 LOGGER.info("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800534
Tianjie Xub8564e12018-11-12 17:06:14 -0800535 Graphics2D graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800536 FontMetrics fontMetrics = graphics.getFontMetrics();
xunchang1eeee452018-11-28 23:30:48 -0800537 WrappedTextInfo wrappedTextInfo = processAndWrapText(text, fontMetrics);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800538
539 // Marks the start y offset for the text image of current locale; and reserves one line to
540 // encode the image metadata.
541 int currentImageStart = mVerticalOffset;
542 mVerticalOffset += 1;
Tianjie Xu542c6172018-11-13 16:36:41 -0800543 for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800544 int lineHeight = fontMetrics.getHeight();
545 // Doubles the height of the image if we are short of space.
546 if (mVerticalOffset + lineHeight >= mImageHeight) {
Tianjie Xub8564e12018-11-12 17:06:14 -0800547 resize(mImageWidth, mImageHeight * 2);
Tianjie Xu542c6172018-11-13 16:36:41 -0800548 // Recreates the graphics since it's attached to the buffered image.
549 graphics = createGraphics(locale);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800550 }
551
552 // Draws the text at mVerticalOffset and increments the offset with line space.
553 int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent();
554
555 // Draws from right if it's an RTL language.
556 int x =
Tianjie Xub8564e12018-11-12 17:06:14 -0800557 mCenterAlignment
Tianjie Xu542c6172018-11-13 16:36:41 -0800558 ? (mImageWidth - lineInfo.mLineWidth) / 2
Tianjie Xub97f7e52018-11-12 16:28:14 -0800559 : RTL_LANGUAGE.contains(languageTag)
Tianjie Xu542c6172018-11-13 16:36:41 -0800560 ? mImageWidth - lineInfo.mLineWidth
Tianjie Xub97f7e52018-11-12 16:28:14 -0800561 : 0;
Tianjie Xu542c6172018-11-13 16:36:41 -0800562 graphics.drawString(lineInfo.mLineContent.getIterator(), x, baseLine);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800563
564 mVerticalOffset += lineHeight;
565 }
566
567 // Encodes the metadata of the current localized image as pixels.
568 int currentImageHeight = mVerticalOffset - currentImageStart - 1;
569 List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag);
570 for (int i = 0; i < info.size(); i++) {
571 int[] pixel = {info.get(i)};
572 mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel);
573 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700574 }
575
Tianjie Xub97f7e52018-11-12 16:28:14 -0800576 /**
Tianjie Xub8564e12018-11-12 17:06:14 -0800577 * Redraws the image with the new width and new height.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800578 *
Tianjie Xub8564e12018-11-12 17:06:14 -0800579 * @param width the new width of the image in pixels.
Tianjie Xub97f7e52018-11-12 16:28:14 -0800580 * @param height the new height of the image in pixels.
581 */
Tianjie Xub8564e12018-11-12 17:06:14 -0800582 private void resize(int width, int height) {
583 BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800584 Graphics2D graphic = resizedImage.createGraphics();
585 graphic.drawImage(mBufferedImage, 0, 0, null);
586 graphic.dispose();
Tianjie Xu721f6792018-10-08 17:04:54 -0700587
Tianjie Xub97f7e52018-11-12 16:28:14 -0800588 mBufferedImage = resizedImage;
Tianjie Xub8564e12018-11-12 17:06:14 -0800589 mImageWidth = width;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800590 mImageHeight = height;
Tianjie Xu721f6792018-10-08 17:04:54 -0700591 }
592
Tianjie Xub97f7e52018-11-12 16:28:14 -0800593 /**
594 * This function draws the font characters and saves the result to outputPath.
595 *
596 * @param localizedTextMap a map from locale to its translated text string
597 * @param outputPath the path to write the generated image file.
598 * @throws FontFormatException if there's a format error in one of the font file
599 * @throws IOException if we cannot find the font file for one of the locale, or we failed to
600 * write the image file.
601 */
602 public void generateImage(Map<Locale, String> localizedTextMap, String outputPath)
603 throws FontFormatException, IOException {
Tianjie Xu542c6172018-11-13 16:36:41 -0800604 FontMetrics defaultFontMetrics =
605 createGraphics(Locale.forLanguageTag("en")).getFontMetrics();
606 mDefaultFont = defaultFontMetrics.getFont();
607 mAndroidStringWidth = defaultFontMetrics.stringWidth(ANDROID_STRING);
608
xunchanga48f00a2018-11-26 15:40:28 -0800609 // The last country variant should be the fallback locale for a given language.
610 Map<String, Locale> fallbackLocaleMap = new HashMap<>();
Tianjie Xub8564e12018-11-12 17:06:14 -0800611 int textWidth = 0;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800612 for (Locale locale : localizedTextMap.keySet()) {
xunchanga48f00a2018-11-26 15:40:28 -0800613 // Updates the fallback locale if we have a new language variant. Don't do it for en-XC
614 // as it's a pseudo-locale.
615 if (!locale.toLanguageTag().equals("en-XC")) {
616 fallbackLocaleMap.put(locale.getLanguage(), locale);
617 }
Tianjie Xub8564e12018-11-12 17:06:14 -0800618 textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800619 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700620
Tianjie Xub8564e12018-11-12 17:06:14 -0800621 // Removes the black margins to reduce the size of the image.
622 resize(textWidth, mImageHeight);
623
Tianjie Xub97f7e52018-11-12 16:28:14 -0800624 for (Locale locale : localizedTextMap.keySet()) {
Tianjie Xub97f7e52018-11-12 16:28:14 -0800625 // Recovery expects en-US instead of en_US.
626 String languageTag = locale.toLanguageTag();
xunchanga48f00a2018-11-26 15:40:28 -0800627 Locale fallbackLocale = fallbackLocaleMap.get(locale.getLanguage());
628 if (locale.equals(fallbackLocale)) {
629 // Makes the last country variant for a given language be the catch-all for that
Tianjie Xub97f7e52018-11-12 16:28:14 -0800630 // language.
631 languageTag = locale.getLanguage();
xunchanga48f00a2018-11-26 15:40:28 -0800632 } else if (localizedTextMap.get(locale).equals(localizedTextMap.get(fallbackLocale))) {
633 LOGGER.info("Skip parsing text for duplicate locale " + locale);
634 continue;
Tianjie Xub97f7e52018-11-12 16:28:14 -0800635 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700636
Tianjie Xub8564e12018-11-12 17:06:14 -0800637 drawText(localizedTextMap.get(locale), locale, languageTag);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800638 }
639
Tianjie Xub8564e12018-11-12 17:06:14 -0800640 resize(mImageWidth, mVerticalOffset);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800641 ImageIO.write(mBufferedImage, "png", new File(outputPath));
642 }
643
644 /** Prints the helper message. */
645 public static void printUsage(Options options) {
646 new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options);
647 }
648
649 /** Creates the command line options. */
650 public static Options createOptions() {
651 Options options = new Options();
652 options.addOption(
653 OptionBuilder.withLongOpt("image_width")
654 .withDescription("The initial width of the image in pixels.")
655 .hasArgs(1)
656 .isRequired()
657 .create());
658
659 options.addOption(
660 OptionBuilder.withLongOpt("text_name")
661 .withDescription(
662 "The description of the text string, e.g. recovery_erasing")
663 .hasArgs(1)
664 .isRequired()
665 .create());
666
667 options.addOption(
668 OptionBuilder.withLongOpt("font_dir")
669 .withDescription(
670 "The directory that contains all the support font format files, "
671 + "e.g. $OUT/system/fonts/")
672 .hasArgs(1)
673 .isRequired()
674 .create());
675
676 options.addOption(
677 OptionBuilder.withLongOpt("resource_dir")
678 .withDescription(
679 "The resource directory that contains all the translated strings in"
680 + " xml format, e.g."
681 + " bootable/recovery/tools/recovery_l10n/res/")
682 .hasArgs(1)
683 .isRequired()
684 .create());
685
686 options.addOption(
687 OptionBuilder.withLongOpt("output_file")
Tianjie Xub8564e12018-11-12 17:06:14 -0800688 .withDescription("Path to the generated image.")
Tianjie Xub97f7e52018-11-12 16:28:14 -0800689 .hasArgs(1)
690 .isRequired()
691 .create());
692
Tianjie Xub8564e12018-11-12 17:06:14 -0800693 options.addOption(
694 OptionBuilder.withLongOpt("center_alignment")
695 .withDescription("Align the text in the center of the screen.")
696 .hasArg(false)
697 .create());
698
Tianjie Xu7b636b62018-11-14 16:25:42 -0800699 options.addOption(
700 OptionBuilder.withLongOpt("verbose")
701 .withDescription("Output the logging above info level.")
702 .hasArg(false)
703 .create());
704
705 options.addOption(
706 OptionBuilder.withLongOpt("locales")
707 .withDescription("A list of android locales separated by ',' e.g."
708 + " 'af,en,zh-rTW'")
709 .hasArg(true)
710 .create());
711
Tianjie Xub97f7e52018-11-12 16:28:14 -0800712 return options;
713 }
714
715 /** The main function parses the command line options and generates the desired text image. */
716 public static void main(String[] args)
717 throws NumberFormatException, IOException, FontFormatException,
718 LocalizedStringNotFoundException {
719 Options options = createOptions();
720 CommandLine cmd;
721 try {
722 cmd = new GnuParser().parse(options, args);
723 } catch (ParseException e) {
724 System.err.println(e.getMessage());
725 printUsage(options);
726 return;
727 }
728
729 int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width"));
730
Tianjie Xu7b636b62018-11-14 16:25:42 -0800731 if (cmd.hasOption("verbose")) {
732 LOGGER.setLevel(Level.INFO);
733 } else {
734 LOGGER.setLevel(Level.WARNING);
735 }
736
Tianjie Xub97f7e52018-11-12 16:28:14 -0800737 ImageGenerator imageGenerator =
738 new ImageGenerator(
739 imageWidth,
740 cmd.getOptionValue("text_name"),
741 DEFAULT_FONT_SIZE,
Tianjie Xub8564e12018-11-12 17:06:14 -0800742 cmd.getOptionValue("font_dir"),
743 cmd.hasOption("center_alignment"));
Tianjie Xub97f7e52018-11-12 16:28:14 -0800744
Tianjie Xu7b636b62018-11-14 16:25:42 -0800745 Set<String> localesSet = null;
746 if (cmd.hasOption("locales")) {
747 String[] localesList = cmd.getOptionValue("locales").split(",");
748 localesSet = new HashSet<>(Arrays.asList(localesList));
749 // Ensures that we have the default locale, all english translations are identical.
750 localesSet.add("en-rAU");
751 }
Tianjie Xub97f7e52018-11-12 16:28:14 -0800752 Map<Locale, String> localizedStringMap =
Tianjie Xu7b636b62018-11-14 16:25:42 -0800753 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"),
754 localesSet);
Tianjie Xub97f7e52018-11-12 16:28:14 -0800755 imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
756 }
Tianjie Xu721f6792018-10-08 17:04:54 -0700757}