Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 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 java.awt.Color; |
| 20 | import java.awt.Font; |
| 21 | import java.awt.FontFormatException; |
| 22 | import java.awt.FontMetrics; |
| 23 | import java.awt.Graphics2D; |
| 24 | import java.awt.RenderingHints; |
| 25 | import java.awt.image.BufferedImage; |
| 26 | import java.io.File; |
| 27 | import java.io.IOException; |
| 28 | import java.util.ArrayList; |
| 29 | import java.util.Comparator; |
| 30 | import java.util.List; |
| 31 | import java.util.Locale; |
| 32 | import java.util.Map; |
| 33 | import java.util.TreeMap; |
| 34 | import java.util.StringTokenizer; |
| 35 | |
| 36 | import javax.imageio.ImageIO; |
| 37 | import javax.xml.parsers.DocumentBuilder; |
| 38 | import javax.xml.parsers.DocumentBuilderFactory; |
| 39 | import javax.xml.parsers.ParserConfigurationException; |
| 40 | |
| 41 | import org.w3c.dom.Document; |
| 42 | import org.w3c.dom.Node; |
| 43 | import org.w3c.dom.NodeList; |
| 44 | |
| 45 | /** |
| 46 | * Command line tool to generate the localized image for recovery mode. |
| 47 | */ |
| 48 | public class ImageGenerator { |
| 49 | // Initial height of the image to draw. |
| 50 | private static final int INITIAL_HEIGHT = 20000; |
| 51 | |
| 52 | private static final float DEFAULT_FONT_SIZE = 40; |
| 53 | |
| 54 | // This is the canvas we used to draw texts. |
| 55 | private BufferedImage mBufferedImage; |
| 56 | |
| 57 | // The width in pixels of our image. Once set, its value won't change. |
| 58 | private final int mImageWidth; |
| 59 | |
| 60 | // The current height in pixels of our image. We will adjust the value when drawing more texts. |
| 61 | private int mImageHeight; |
| 62 | |
| 63 | // The current vertical offset in pixels to draw the top edge of new text strings. |
| 64 | private int mVerticalOffset; |
| 65 | |
| 66 | // The font size to draw the texts. |
| 67 | private final float mFontSize; |
| 68 | |
| 69 | // The name description of the text to localize. It's used to find the translated strings in the |
| 70 | // resource file. |
| 71 | private final String mTextName; |
| 72 | |
| 73 | // The directory that contains all the needed font files (e.g. ttf, otf, ttc files). |
| 74 | private final String mFontDirPath; |
| 75 | |
| 76 | // An explicit map from language to the font name to use. |
| 77 | // The map is extracted from frameworks/base/data/fonts/fonts.xml. |
| 78 | // And the language-subtag-registry is found in: |
| 79 | // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry |
| 80 | private static final String DEFAULT_FONT_NAME = "Roboto-Regular"; |
| 81 | private static final Map<String, String> LANGUAGE_TO_FONT_MAP = new TreeMap<String, String>() {{ |
| 82 | put("am", "NotoSansEthiopic-Regular"); |
| 83 | put("ar", "NotoNaskhArabicUI-Regular"); |
| 84 | put("as", "NotoSansBengaliUI-Regular"); |
| 85 | put("bn", "NotoSansBengaliUI-Regular"); |
| 86 | put("fa", "NotoNaskhArabicUI-Regular"); |
| 87 | put("gu", "NotoSansGujaratiUI-Regular"); |
| 88 | put("hi", "NotoSansDevanagariUI-Regular"); |
| 89 | put("hy", "NotoSansArmenian-Regular"); |
| 90 | put("iw", "NotoSansHebrew-Regular"); |
| 91 | put("ja", "NotoSansCJK-Regular"); |
| 92 | put("ka", "NotoSansGeorgian-Regular"); |
| 93 | put("ko", "NotoSansCJK-Regular"); |
| 94 | put("km", "NotoSansKhmerUI-Regular"); |
| 95 | put("kn", "NotoSansKannadaUI-Regular"); |
| 96 | put("lo", "NotoSansLaoUI-Regular"); |
| 97 | put("ml", "NotoSansMalayalamUI-Regular"); |
| 98 | put("mr", "NotoSansDevanagariUI-Regular"); |
| 99 | put("my", "NotoSansMyanmarUI-Regular"); |
| 100 | put("ne", "NotoSansDevanagariUI-Regular"); |
| 101 | put("or", "NotoSansOriya-Regular"); |
| 102 | put("pa", "NotoSansGurmukhiUI-Regular"); |
| 103 | put("si", "NotoSansSinhala-Regular"); |
| 104 | put("ta", "NotoSansTamilUI-Regular"); |
| 105 | put("te", "NotoSansTeluguUI-Regular"); |
| 106 | put("th", "NotoSansThaiUI-Regular"); |
| 107 | put("ur", "NotoNaskhArabicUI-Regular"); |
| 108 | put("zh", "NotoSansCJK-Regular"); |
| 109 | }}; |
| 110 | |
| 111 | /** |
| 112 | * Exception to indicate the failure to find the translated text strings. |
| 113 | */ |
| 114 | public static class LocalizedStringNotFoundException extends Exception { |
| 115 | public LocalizedStringNotFoundException(String message) { |
| 116 | super(message); |
| 117 | } |
| 118 | |
| 119 | public LocalizedStringNotFoundException(String message, Throwable cause) { |
| 120 | super(message, cause); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Initailizes the fields of the image image. |
| 126 | */ |
| 127 | public ImageGenerator(int imageWidth, String textName, float fontSize, String fontDirPath) { |
| 128 | mImageWidth = imageWidth; |
| 129 | mImageHeight = INITIAL_HEIGHT; |
| 130 | mVerticalOffset = 0; |
| 131 | |
| 132 | // Initialize the canvas with the default height. |
| 133 | mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY); |
| 134 | |
| 135 | mTextName = textName; |
| 136 | mFontSize = fontSize; |
| 137 | mFontDirPath = fontDirPath; |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Finds the translated text string for the given textName by parsing the resourceFile. |
| 142 | * Example of the xml fields: |
| 143 | * <resources xmlns:android="http://schemas.android.com/apk/res/android"> |
| 144 | * <string name="recovery_installing_security" msgid="9184031299717114342"> |
| 145 | * "Sicherheitsupdate wird installiert"</string> |
| 146 | * </resources> |
| 147 | * |
| 148 | * @param resourceFile the input resource file in xml format. |
| 149 | * @param textName the name description of the text. |
| 150 | * |
| 151 | * @return the string representation of the translated text. |
| 152 | */ |
| 153 | private String getTextString(File resourceFile, String textName) throws IOException, |
| 154 | ParserConfigurationException, org.xml.sax.SAXException, LocalizedStringNotFoundException { |
| 155 | DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); |
| 156 | DocumentBuilder db = builder.newDocumentBuilder(); |
| 157 | |
| 158 | Document doc = db.parse(resourceFile); |
| 159 | doc.getDocumentElement().normalize(); |
| 160 | |
| 161 | NodeList nodeList = doc.getElementsByTagName("string"); |
| 162 | for (int i = 0; i < nodeList.getLength(); i++) { |
| 163 | Node node = nodeList.item(i); |
| 164 | String name = node.getAttributes().getNamedItem("name").getNodeValue(); |
| 165 | if (name.equals(textName)) { |
| 166 | return node.getTextContent(); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | throw new LocalizedStringNotFoundException(textName + " not found in " |
| 171 | + resourceFile.getName()); |
| 172 | } |
| 173 | |
| 174 | /** |
| 175 | * Constructs the locale from the name of the resource file. |
| 176 | */ |
| 177 | private Locale getLocaleFromFilename(String filename) throws IOException { |
| 178 | // Gets the locale string by trimming the top "values-". |
| 179 | String localeString = filename.substring(7); |
| 180 | if (localeString.matches("[A-Za-z]+")) { |
| 181 | return Locale.forLanguageTag(localeString); |
| 182 | } |
| 183 | if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) { |
| 184 | // "${Language}-r${Region}". e.g. en-rGB |
| 185 | String[] tokens = localeString.split("-r"); |
| 186 | return Locale.forLanguageTag(String.join("-", tokens)); |
| 187 | } |
| 188 | if (localeString.startsWith("b+")) { |
| 189 | // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}" |
| 190 | String[] tokens = localeString.substring(2).split("\\+"); |
| 191 | return Locale.forLanguageTag(String.join("-", tokens)); |
| 192 | } |
| 193 | |
| 194 | throw new IOException("Unrecognized locale string " + localeString); |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource |
| 199 | * directory and collect the translated text. |
| 200 | * |
| 201 | * @param resourcePath the path to the resource directory |
| 202 | * |
| 203 | * @return a map with the locale as key, and translated text as value |
| 204 | * |
| 205 | * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given |
| 206 | * locale |
| 207 | **/ |
| 208 | public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath) throws |
| 209 | IOException, LocalizedStringNotFoundException { |
| 210 | File resourceDir = new File(resourcePath); |
| 211 | if (!resourceDir.isDirectory()) { |
| 212 | throw new LocalizedStringNotFoundException(resourcePath + " is not a directory."); |
| 213 | } |
| 214 | |
| 215 | Map<Locale, String> result = |
| 216 | new TreeMap<Locale, String>(Comparator.comparing(Locale::toLanguageTag)); |
| 217 | |
| 218 | // Find all the localized resource subdirectories in the format of values-$LOCALE |
| 219 | String[] nameList = resourceDir.list( |
| 220 | (File file, String name) -> name.startsWith("values-")); |
| 221 | for (String name : nameList) { |
| 222 | File textFile = new File(resourcePath, name + "/strings.xml"); |
| 223 | String localizedText; |
| 224 | try { |
| 225 | localizedText = getTextString(textFile, mTextName); |
| 226 | } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) { |
| 227 | throw new LocalizedStringNotFoundException( |
| 228 | "Failed to read the translated text for locale " + name, e); |
| 229 | } |
| 230 | |
| 231 | Locale locale = getLocaleFromFilename(name); |
| 232 | // Removes the double quotation mark from the text. |
| 233 | result.put(locale, localizedText.substring(1, localizedText.length() - 1)); |
| 234 | } |
| 235 | |
| 236 | return result; |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Returns a font object associated given the given locale |
| 241 | * |
| 242 | * @throws IOException if the font file fails to open |
| 243 | * @throws FontFormatException if the font file doesn't have the expected format |
| 244 | */ |
| 245 | private Font loadFontsByLocale(String language) throws IOException, FontFormatException { |
| 246 | String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME); |
| 247 | String[] suffixes = {".otf", ".ttf", ".ttc"}; |
| 248 | for (String suffix : suffixes ) { |
| 249 | File fontFile = new File(mFontDirPath, fontName + suffix); |
| 250 | if (fontFile.isFile()) { |
| 251 | return Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize); |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | throw new IOException("Can not find the font file " + fontName + " for language " + language); |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * Separates the text string by spaces and wraps it by words. |
| 260 | **/ |
| 261 | private List<String> wrapTextByWords(String text, FontMetrics metrics) { |
| 262 | List<String> wrappedText = new ArrayList<>(); |
| 263 | StringTokenizer st = new StringTokenizer(text, " \n"); |
| 264 | |
| 265 | StringBuilder line = new StringBuilder(); |
| 266 | while (st.hasMoreTokens()) { |
| 267 | String token = st.nextToken(); |
| 268 | if (metrics.stringWidth(line + token + " ") > mImageWidth) { |
| 269 | wrappedText.add(line.toString()); |
| 270 | line = new StringBuilder(); |
| 271 | } |
| 272 | line.append(token).append(" "); |
| 273 | } |
| 274 | wrappedText.add(line.toString()); |
| 275 | |
| 276 | return wrappedText; |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * Wraps the text with a maximum of mImageWidth pixels per line. |
| 281 | * |
| 282 | * @param text the string representation of text to wrap |
| 283 | * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of |
| 284 | * the text given its string representation |
| 285 | * |
| 286 | * @return a list of strings with their width smaller than mImageWidth pixels |
| 287 | */ |
| 288 | private List<String> wrapText(String text, FontMetrics metrics) { |
| 289 | // TODO(xunchang) handle other cases of text wrapping |
| 290 | // 1. RTL languages: "ar"(Arabic), "fa"(Persian), "he"(Hebrew), "iw"(Hebrew), "ur"(Urdu) |
| 291 | // 2. Language uses characters: CJK, "lo"(lao), "km"(khmer) |
| 292 | |
| 293 | return wrapTextByWords(text, metrics); |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Draws the text string on the canvas for given locale. |
| 298 | * |
| 299 | * @param text the string to draw on canvas |
| 300 | * @param locale the current locale tag of the string to draw |
| 301 | * |
| 302 | * @throws IOException if we cannot find the corresponding font file for the given locale. |
| 303 | * @throws FontFormatException if we failed to load the font file for the given locale. |
| 304 | */ |
| 305 | private void drawText(String text, Locale locale) throws IOException, FontFormatException { |
| 306 | Graphics2D graphics = mBufferedImage.createGraphics(); |
| 307 | graphics.setColor(Color.WHITE); |
| 308 | graphics.setRenderingHint( |
| 309 | RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); |
| 310 | graphics.setFont(loadFontsByLocale(locale.getLanguage())); |
| 311 | |
| 312 | System.out.println("Drawing text for locale " + locale + " text " + text); |
| 313 | |
| 314 | FontMetrics fontMetrics = graphics.getFontMetrics(); |
| 315 | List<String> wrappedText = wrapTextByWords(text, fontMetrics); |
| 316 | for (String line : wrappedText) { |
| 317 | int lineHeight = fontMetrics.getHeight(); |
| 318 | // Doubles the height of the image if we are short of space. |
| 319 | if (mVerticalOffset + lineHeight >= mImageHeight) { |
| 320 | resizeHeight(mImageHeight * 2); |
| 321 | } |
| 322 | |
| 323 | // Draws the text at mVerticalOffset and increments the offset with line space. |
| 324 | int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent(); |
| 325 | graphics.drawString(line, 0, baseLine); |
| 326 | mVerticalOffset += lineHeight; |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | /** |
| 331 | * Redraws the image with the new height. |
| 332 | * |
| 333 | * @param height the new height of the image in pixels. |
| 334 | */ |
| 335 | private void resizeHeight(int height) { |
| 336 | BufferedImage resizedImage = |
| 337 | new BufferedImage(mImageWidth, height, BufferedImage.TYPE_BYTE_GRAY); |
| 338 | Graphics2D graphic = resizedImage.createGraphics(); |
| 339 | graphic.drawImage(mBufferedImage, 0, 0, null); |
| 340 | graphic.dispose(); |
| 341 | |
| 342 | mBufferedImage = resizedImage; |
| 343 | mImageHeight = height; |
| 344 | } |
| 345 | |
| 346 | /** |
| 347 | * This function draws the font characters and saves the result to outputPath. |
| 348 | * |
| 349 | * @param localizedTextMap a map from locale to its translated text string |
| 350 | * @param outputPath the path to write the generated image file. |
| 351 | * |
| 352 | * @throws FontFormatException if there's a format error in one of the font file |
| 353 | * @throws IOException if we cannot find the font file for one of the locale, or we failed to |
| 354 | * write the image file. |
| 355 | */ |
| 356 | public void generateImage(Map<Locale, String> localizedTextMap, String outputPath) throws |
| 357 | FontFormatException, IOException { |
| 358 | for (Locale locale : localizedTextMap.keySet()) { |
| 359 | // TODO(xunchang) reprocess the locales for the same language and make the last locale the |
| 360 | // catch-all type. e.g. "zh-CN, zh-HK, zh-TW" will become "zh-CN, zh-HK, zh" |
| 361 | // Or maybe we don't need to support these variants? |
| 362 | drawText(localizedTextMap.get(locale), locale); |
| 363 | } |
| 364 | |
| 365 | // TODO(xunchang) adjust the width to save some space if all texts are smaller than imageWidth. |
| 366 | resizeHeight(mVerticalOffset); |
| 367 | ImageIO.write(mBufferedImage, "png", new File(outputPath)); |
| 368 | } |
| 369 | |
| 370 | public static void printUsage() { |
| 371 | System.out.println("Usage: java -jar path_to_jar imageWidth textName fontDirectory" |
| 372 | + " resourceDirectory outputFilename"); |
| 373 | } |
| 374 | |
| 375 | public static void main(String[] args) throws NumberFormatException, IOException, |
| 376 | FontFormatException, LocalizedStringNotFoundException { |
| 377 | if (args.length != 5) { |
| 378 | printUsage(); |
| 379 | System.err.println("We expect 5 arguments, get " + args.length); |
| 380 | System.exit(1); |
| 381 | } |
| 382 | |
| 383 | // TODO(xunchang) switch to commandline parser |
| 384 | int imageWidth = Integer.parseUnsignedInt(args[0]); |
| 385 | |
| 386 | ImageGenerator imageGenerator = |
| 387 | new ImageGenerator(imageWidth, args[1], DEFAULT_FONT_SIZE, args[2]); |
| 388 | |
| 389 | Map<Locale, String> localizedStringMap = |
| 390 | imageGenerator.readLocalizedStringFromXmls(args[3]); |
| 391 | imageGenerator.generateImage(localizedStringMap, args[4]); |
| 392 | } |
| 393 | } |
| 394 | |