Home | History | Annotate | Download | only in image_generator
      1 /*
      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 
     17 package com.android.recovery.tools;
     18 
     19 import com.ibm.icu.text.BreakIterator;
     20 
     21 import org.apache.commons.cli.CommandLine;
     22 import org.apache.commons.cli.GnuParser;
     23 import org.apache.commons.cli.HelpFormatter;
     24 import org.apache.commons.cli.OptionBuilder;
     25 import org.apache.commons.cli.Options;
     26 import org.apache.commons.cli.ParseException;
     27 import org.w3c.dom.Document;
     28 import org.w3c.dom.Node;
     29 import org.w3c.dom.NodeList;
     30 
     31 import java.awt.Color;
     32 import java.awt.Font;
     33 import java.awt.FontFormatException;
     34 import java.awt.FontMetrics;
     35 import java.awt.Graphics2D;
     36 import java.awt.RenderingHints;
     37 import java.awt.font.TextAttribute;
     38 import java.awt.image.BufferedImage;
     39 import java.io.File;
     40 import java.io.IOException;
     41 import java.text.AttributedString;
     42 import java.util.ArrayList;
     43 import java.util.Arrays;
     44 import java.util.HashMap;
     45 import java.util.HashSet;
     46 import java.util.List;
     47 import java.util.Locale;
     48 import java.util.Map;
     49 import java.util.Set;
     50 import java.util.TreeMap;
     51 import java.util.logging.Level;
     52 import java.util.logging.Logger;
     53 
     54 import javax.imageio.ImageIO;
     55 import javax.xml.parsers.DocumentBuilder;
     56 import javax.xml.parsers.DocumentBuilderFactory;
     57 import javax.xml.parsers.ParserConfigurationException;
     58 
     59 /** Command line tool to generate the localized image for recovery mode. */
     60 public class ImageGenerator {
     61     // Initial height of the image to draw.
     62     private static final int INITIAL_HEIGHT = 20000;
     63 
     64     private static final float DEFAULT_FONT_SIZE = 40;
     65 
     66     private static final Logger LOGGER = Logger.getLogger(ImageGenerator.class.getName());
     67 
     68     // This is the canvas we used to draw texts.
     69     private BufferedImage mBufferedImage;
     70 
     71     // 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;
     74 
     75     // The current height in pixels of our image. We will adjust the value when drawing more texts.
     76     private int mImageHeight;
     77 
     78     // The current vertical offset in pixels to draw the top edge of new text strings.
     79     private int mVerticalOffset;
     80 
     81     // The font size to draw the texts.
     82     private final float mFontSize;
     83 
     84     // 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;
     87 
     88     // The directory that contains all the needed font files (e.g. ttf, otf, ttc files).
     89     private final String mFontDirPath;
     90 
     91     // Align the text in the center of the image.
     92     private final boolean mCenterAlignment;
     93 
     94     // Some localized font cannot draw the word "Android" and some PUNCTUATIONS; we need to fall
     95     // back to use our default latin font instead.
     96     private static final char[] PUNCTUATIONS = {',', ';', '.', '!', '?'};
     97 
     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 
    108     // 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");
    126                     put("ka", "NotoSansGeorgian-Regular");
    127                     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             };
    145 
    146     // 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             };
    157 
    158     /** 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         }
    167     }
    168 
    169     /**
    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 
    218                 // Adds the attribute to use default font to draw the PUNCTUATIONS ", . ; ! ?"
    219                 for (char punctuation : PUNCTUATIONS) {
    220                     // TODO (xunchang) handle the RTL language that has different directions for '?'
    221                     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         }
    234 
    235         /** Merges two WrappedTextInfo. */
    236         public void addLines(WrappedTextInfo other) {
    237             mWrappedLines.addAll(other.mWrappedLines);
    238         }
    239     }
    240 
    241     /** Initailizes the fields of the image image. */
    242     public ImageGenerator(
    243             int initialImageWidth,
    244             String textName,
    245             float fontSize,
    246             String fontDirPath,
    247             boolean centerAlignment) {
    248         mImageWidth = initialImageWidth;
    249         mImageHeight = INITIAL_HEIGHT;
    250         mVerticalOffset = 0;
    251 
    252         // Initialize the canvas with the default height.
    253         mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY);
    254 
    255         mTextName = textName;
    256         mFontSize = fontSize;
    257         mFontDirPath = fontDirPath;
    258         mLoadedFontMap = new TreeMap<>();
    259 
    260         mCenterAlignment = centerAlignment;
    261     }
    262 
    263     /**
    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();
    278 
    279         Document doc = db.parse(resourceFile);
    280         doc.getDocumentElement().normalize();
    281 
    282         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         }
    290 
    291         throw new LocalizedStringNotFoundException(
    292                 textName + " not found in " + resourceFile.getName());
    293     }
    294 
    295     /** 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         }
    312 
    313         throw new IOException("Unrecognized locale string " + localeString);
    314     }
    315 
    316     /**
    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
    321      * @param localesSet a list of supported locales; resources of other locales will be omitted.
    322      * @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      */
    326     public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath,
    327             Set<String> localesSet) throws IOException, LocalizedStringNotFoundException {
    328         File resourceDir = new File(resourcePath);
    329         if (!resourceDir.isDirectory()) {
    330             throw new LocalizedStringNotFoundException(resourcePath + " is not a directory.");
    331         }
    332 
    333         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                         });
    349 
    350         // 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) {
    354             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 
    360             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 {
    384         if (mLoadedFontMap.containsKey(language)) {
    385             return mLoadedFontMap.get(language);
    386         }
    387 
    388         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()) {
    393                 Font result = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize);
    394                 mLoadedFontMap.put(language, result);
    395                 return result;
    396             }
    397         }
    398 
    399         throw new IOException(
    400                 "Can not find the font file " + fontName + " for language " + language);
    401     }
    402 
    403     /** Wraps the text with a maximum of mImageWidth pixels per line. */
    404     private WrappedTextInfo wrapText(String text, FontMetrics metrics) {
    405         WrappedTextInfo info = new WrappedTextInfo();
    406 
    407         BreakIterator lineBoundary = BreakIterator.getLineInstance();
    408         lineBoundary.setText(text);
    409 
    410         int lineWidth = 0;  // Width of the processed words of the current line.
    411         int start = lineBoundary.first();
    412         StringBuilder line = new StringBuilder();
    413         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);
    417             // 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 
    426                 line = new StringBuilder();
    427                 lineWidth = 0;
    428             }
    429             line.append(token);
    430             lineWidth += tokenWidth;
    431         }
    432 
    433         info.addLine(line.toString(), lineWidth, metrics.getFont(), mDefaultFont);
    434 
    435         return info;
    436     }
    437 
    438     /**
    439      * 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     /**
    462      * 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()));
    476 
    477         byte[] localeBytes = locale.getBytes();
    478         for (byte b : localeBytes) {
    479             info.add((int) b);
    480         }
    481         info.add(0);
    482 
    483         return info;
    484     }
    485 
    486     /** 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();
    502         WrappedTextInfo wrappedTextInfo = processAndWrapText(text, fontMetrics);
    503 
    504         int textWidth = 0;
    505         for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
    506             textWidth = Math.max(textWidth, lineInfo.mLineWidth);
    507         }
    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 
    523     /**
    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      */
    531     private void drawText(String text, Locale locale, String languageTag)
    532             throws IOException, FontFormatException {
    533         LOGGER.info("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text);
    534 
    535         Graphics2D graphics = createGraphics(locale);
    536         FontMetrics fontMetrics = graphics.getFontMetrics();
    537         WrappedTextInfo wrappedTextInfo = processAndWrapText(text, fontMetrics);
    538 
    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;
    543         for (WrappedTextInfo.LineInfo lineInfo : wrappedTextInfo.mWrappedLines) {
    544             int lineHeight = fontMetrics.getHeight();
    545             // Doubles the height of the image if we are short of space.
    546             if (mVerticalOffset + lineHeight >= mImageHeight) {
    547                 resize(mImageWidth, mImageHeight * 2);
    548                 // Recreates the graphics since it's attached to the buffered image.
    549                 graphics = createGraphics(locale);
    550             }
    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 =
    557                     mCenterAlignment
    558                             ? (mImageWidth - lineInfo.mLineWidth) / 2
    559                             : RTL_LANGUAGE.contains(languageTag)
    560                                     ? mImageWidth - lineInfo.mLineWidth
    561                                     : 0;
    562             graphics.drawString(lineInfo.mLineContent.getIterator(), x, baseLine);
    563 
    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         }
    574     }
    575 
    576     /**
    577      * Redraws the image with the new width and new height.
    578      *
    579      * @param width the new width of the image in pixels.
    580      * @param height the new height of the image in pixels.
    581      */
    582     private void resize(int width, int height) {
    583         BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    584         Graphics2D graphic = resizedImage.createGraphics();
    585         graphic.drawImage(mBufferedImage, 0, 0, null);
    586         graphic.dispose();
    587 
    588         mBufferedImage = resizedImage;
    589         mImageWidth = width;
    590         mImageHeight = height;
    591     }
    592 
    593     /**
    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 {
    604         FontMetrics defaultFontMetrics =
    605                 createGraphics(Locale.forLanguageTag("en")).getFontMetrics();
    606         mDefaultFont = defaultFontMetrics.getFont();
    607         mAndroidStringWidth = defaultFontMetrics.stringWidth(ANDROID_STRING);
    608 
    609         // The last country variant should be the fallback locale for a given language.
    610         Map<String, Locale> fallbackLocaleMap = new HashMap<>();
    611         int textWidth = 0;
    612         for (Locale locale : localizedTextMap.keySet()) {
    613             // 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             }
    618             textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale));
    619         }
    620 
    621         // Removes the black margins to reduce the size of the image.
    622         resize(textWidth, mImageHeight);
    623 
    624         for (Locale locale : localizedTextMap.keySet()) {
    625             // Recovery expects en-US instead of en_US.
    626             String languageTag = locale.toLanguageTag();
    627             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
    630                 // language.
    631                 languageTag = locale.getLanguage();
    632             } else if (localizedTextMap.get(locale).equals(localizedTextMap.get(fallbackLocale))) {
    633                 LOGGER.info("Skip parsing text for duplicate locale " + locale);
    634                 continue;
    635             }
    636 
    637             drawText(localizedTextMap.get(locale), locale, languageTag);
    638         }
    639 
    640         resize(mImageWidth, mVerticalOffset);
    641         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")
    688                         .withDescription("Path to the generated image.")
    689                         .hasArgs(1)
    690                         .isRequired()
    691                         .create());
    692 
    693         options.addOption(
    694                 OptionBuilder.withLongOpt("center_alignment")
    695                         .withDescription("Align the text in the center of the screen.")
    696                         .hasArg(false)
    697                         .create());
    698 
    699         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 
    712         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 
    731         if (cmd.hasOption("verbose")) {
    732             LOGGER.setLevel(Level.INFO);
    733         } else {
    734             LOGGER.setLevel(Level.WARNING);
    735         }
    736 
    737         ImageGenerator imageGenerator =
    738                 new ImageGenerator(
    739                         imageWidth,
    740                         cmd.getOptionValue("text_name"),
    741                         DEFAULT_FONT_SIZE,
    742                         cmd.getOptionValue("font_dir"),
    743                         cmd.hasOption("center_alignment"));
    744 
    745         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         }
    752         Map<Locale, String> localizedStringMap =
    753                 imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir"),
    754                         localesSet);
    755         imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file"));
    756     }
    757 }
    758