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 | |
Tao Bao | 529bb74 | 2018-11-06 11:24:53 -0800 | [diff] [blame] | 19 | import org.apache.commons.cli.CommandLine; |
| 20 | import org.apache.commons.cli.GnuParser; |
| 21 | import org.apache.commons.cli.HelpFormatter; |
| 22 | import org.apache.commons.cli.OptionBuilder; |
| 23 | import org.apache.commons.cli.Options; |
| 24 | import org.apache.commons.cli.ParseException; |
| 25 | import org.w3c.dom.Document; |
| 26 | import org.w3c.dom.Node; |
| 27 | import org.w3c.dom.NodeList; |
| 28 | |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 29 | import java.awt.Color; |
| 30 | import java.awt.Font; |
| 31 | import java.awt.FontFormatException; |
| 32 | import java.awt.FontMetrics; |
| 33 | import java.awt.Graphics2D; |
| 34 | import java.awt.RenderingHints; |
| 35 | import java.awt.image.BufferedImage; |
| 36 | import java.io.File; |
| 37 | import java.io.IOException; |
| 38 | import java.util.ArrayList; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 39 | import java.util.Arrays; |
| 40 | import java.util.HashSet; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 41 | import java.util.List; |
| 42 | import java.util.Locale; |
| 43 | import java.util.Map; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 44 | import java.util.Set; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 45 | import java.util.StringTokenizer; |
Tao Bao | 529bb74 | 2018-11-06 11:24:53 -0800 | [diff] [blame] | 46 | import java.util.TreeMap; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 47 | |
| 48 | import javax.imageio.ImageIO; |
| 49 | import javax.xml.parsers.DocumentBuilder; |
| 50 | import javax.xml.parsers.DocumentBuilderFactory; |
| 51 | import javax.xml.parsers.ParserConfigurationException; |
| 52 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 53 | /** Command line tool to generate the localized image for recovery mode. */ |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 54 | public class ImageGenerator { |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 55 | // Initial height of the image to draw. |
| 56 | private static final int INITIAL_HEIGHT = 20000; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 57 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 58 | private static final float DEFAULT_FONT_SIZE = 40; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 59 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 60 | // This is the canvas we used to draw texts. |
| 61 | private BufferedImage mBufferedImage; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 62 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 63 | // The width in pixels of our image. The value will be adjusted once when we calculate the |
| 64 | // maximum width to fit the wrapped text strings. |
| 65 | private int mImageWidth; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 66 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 67 | // The current height in pixels of our image. We will adjust the value when drawing more texts. |
| 68 | private int mImageHeight; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 69 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 70 | // The current vertical offset in pixels to draw the top edge of new text strings. |
| 71 | private int mVerticalOffset; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 72 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 73 | // The font size to draw the texts. |
| 74 | private final float mFontSize; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 75 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 76 | // The name description of the text to localize. It's used to find the translated strings in the |
| 77 | // resource file. |
| 78 | private final String mTextName; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 79 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 80 | // The directory that contains all the needed font files (e.g. ttf, otf, ttc files). |
| 81 | private final String mFontDirPath; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 82 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 83 | // Align the text in the center of the image. |
| 84 | private final boolean mCenterAlignment; |
| 85 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 86 | // An explicit map from language to the font name to use. |
| 87 | // The map is extracted from frameworks/base/data/fonts/fonts.xml. |
| 88 | // And the language-subtag-registry is found in: |
| 89 | // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry |
| 90 | private static final String DEFAULT_FONT_NAME = "Roboto-Regular"; |
| 91 | private static final Map<String, String> LANGUAGE_TO_FONT_MAP = |
| 92 | new TreeMap<String, String>() { |
| 93 | { |
| 94 | put("am", "NotoSansEthiopic-Regular"); |
| 95 | put("ar", "NotoNaskhArabicUI-Regular"); |
| 96 | put("as", "NotoSansBengaliUI-Regular"); |
| 97 | put("bn", "NotoSansBengaliUI-Regular"); |
| 98 | put("fa", "NotoNaskhArabicUI-Regular"); |
| 99 | put("gu", "NotoSansGujaratiUI-Regular"); |
| 100 | put("hi", "NotoSansDevanagariUI-Regular"); |
| 101 | put("hy", "NotoSansArmenian-Regular"); |
| 102 | put("iw", "NotoSansHebrew-Regular"); |
| 103 | put("ja", "NotoSansCJK-Regular"); |
| 104 | put("ka", "NotoSansGeorgian-Regular"); |
| 105 | put("ko", "NotoSansCJK-Regular"); |
| 106 | put("km", "NotoSansKhmerUI-Regular"); |
| 107 | put("kn", "NotoSansKannadaUI-Regular"); |
| 108 | put("lo", "NotoSansLaoUI-Regular"); |
| 109 | put("ml", "NotoSansMalayalamUI-Regular"); |
| 110 | put("mr", "NotoSansDevanagariUI-Regular"); |
| 111 | put("my", "NotoSansMyanmarUI-Regular"); |
| 112 | put("ne", "NotoSansDevanagariUI-Regular"); |
| 113 | put("or", "NotoSansOriya-Regular"); |
| 114 | put("pa", "NotoSansGurmukhiUI-Regular"); |
| 115 | put("si", "NotoSansSinhala-Regular"); |
| 116 | put("ta", "NotoSansTamilUI-Regular"); |
| 117 | put("te", "NotoSansTeluguUI-Regular"); |
| 118 | put("th", "NotoSansThaiUI-Regular"); |
| 119 | put("ur", "NotoNaskhArabicUI-Regular"); |
| 120 | put("zh", "NotoSansCJK-Regular"); |
| 121 | } |
| 122 | }; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 123 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 124 | // Languages that write from right to left. |
| 125 | private static final Set<String> RTL_LANGUAGE = |
| 126 | new HashSet<String>() { |
| 127 | { |
| 128 | add("ar"); // Arabic |
| 129 | add("fa"); // Persian |
| 130 | add("he"); // Hebrew |
| 131 | add("iw"); // Hebrew |
| 132 | add("ur"); // Urdu |
| 133 | } |
| 134 | }; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 135 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 136 | // Languages that breaks on arbitrary characters. |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 137 | // TODO(xunchang) switch to icu library if possible. For example, for Thai and Khmer, there is |
| 138 | // no space between words; and word breaking is based on grammatical analysis and on word |
| 139 | // matching in dictionaries. |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 140 | private static final Set<String> LOGOGRAM_LANGUAGE = |
| 141 | new HashSet<String>() { |
| 142 | { |
| 143 | add("ja"); // Japanese |
| 144 | add("km"); // Khmer |
| 145 | add("ko"); // Korean |
| 146 | add("lo"); // Lao |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 147 | add("th"); // Thai |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 148 | add("zh"); // Chinese |
| 149 | } |
| 150 | }; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 151 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 152 | /** Exception to indicate the failure to find the translated text strings. */ |
| 153 | public static class LocalizedStringNotFoundException extends Exception { |
| 154 | public LocalizedStringNotFoundException(String message) { |
| 155 | super(message); |
| 156 | } |
| 157 | |
| 158 | public LocalizedStringNotFoundException(String message, Throwable cause) { |
| 159 | super(message, cause); |
| 160 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 161 | } |
| 162 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 163 | /** Initailizes the fields of the image image. */ |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 164 | public ImageGenerator( |
| 165 | int initialImageWidth, |
| 166 | String textName, |
| 167 | float fontSize, |
| 168 | String fontDirPath, |
| 169 | boolean centerAlignment) { |
| 170 | mImageWidth = initialImageWidth; |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 171 | mImageHeight = INITIAL_HEIGHT; |
| 172 | mVerticalOffset = 0; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 173 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 174 | // Initialize the canvas with the default height. |
| 175 | mBufferedImage = new BufferedImage(mImageWidth, mImageHeight, BufferedImage.TYPE_BYTE_GRAY); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 176 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 177 | mTextName = textName; |
| 178 | mFontSize = fontSize; |
| 179 | mFontDirPath = fontDirPath; |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 180 | |
| 181 | mCenterAlignment = centerAlignment; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 182 | } |
| 183 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 184 | /** |
| 185 | * Finds the translated text string for the given textName by parsing the resourceFile. Example |
| 186 | * of the xml fields: <resources xmlns:android="http://schemas.android.com/apk/res/android"> |
| 187 | * <string name="recovery_installing_security" msgid="9184031299717114342"> "Sicherheitsupdate |
| 188 | * wird installiert"</string> </resources> |
| 189 | * |
| 190 | * @param resourceFile the input resource file in xml format. |
| 191 | * @param textName the name description of the text. |
| 192 | * @return the string representation of the translated text. |
| 193 | */ |
| 194 | private String getTextString(File resourceFile, String textName) |
| 195 | throws IOException, ParserConfigurationException, org.xml.sax.SAXException, |
| 196 | LocalizedStringNotFoundException { |
| 197 | DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); |
| 198 | DocumentBuilder db = builder.newDocumentBuilder(); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 199 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 200 | Document doc = db.parse(resourceFile); |
| 201 | doc.getDocumentElement().normalize(); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 202 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 203 | NodeList nodeList = doc.getElementsByTagName("string"); |
| 204 | for (int i = 0; i < nodeList.getLength(); i++) { |
| 205 | Node node = nodeList.item(i); |
| 206 | String name = node.getAttributes().getNamedItem("name").getNodeValue(); |
| 207 | if (name.equals(textName)) { |
| 208 | return node.getTextContent(); |
| 209 | } |
| 210 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 211 | |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 212 | throw new LocalizedStringNotFoundException( |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 213 | textName + " not found in " + resourceFile.getName()); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 214 | } |
| 215 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 216 | /** Constructs the locale from the name of the resource file. */ |
| 217 | private Locale getLocaleFromFilename(String filename) throws IOException { |
| 218 | // Gets the locale string by trimming the top "values-". |
| 219 | String localeString = filename.substring(7); |
| 220 | if (localeString.matches("[A-Za-z]+")) { |
| 221 | return Locale.forLanguageTag(localeString); |
| 222 | } |
| 223 | if (localeString.matches("[A-Za-z]+-r[A-Za-z]+")) { |
| 224 | // "${Language}-r${Region}". e.g. en-rGB |
| 225 | String[] tokens = localeString.split("-r"); |
| 226 | return Locale.forLanguageTag(String.join("-", tokens)); |
| 227 | } |
| 228 | if (localeString.startsWith("b+")) { |
| 229 | // The special case of b+sr+Latn, which has the form "b+${Language}+${ScriptName}" |
| 230 | String[] tokens = localeString.substring(2).split("\\+"); |
| 231 | return Locale.forLanguageTag(String.join("-", tokens)); |
| 232 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 233 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 234 | throw new IOException("Unrecognized locale string " + localeString); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 235 | } |
| 236 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 237 | /** |
| 238 | * Iterates over the xml files in the format of values-$LOCALE/strings.xml under the resource |
| 239 | * directory and collect the translated text. |
| 240 | * |
| 241 | * @param resourcePath the path to the resource directory |
| 242 | * @return a map with the locale as key, and translated text as value |
| 243 | * @throws LocalizedStringNotFoundException if we cannot find the translated text for the given |
| 244 | * locale |
| 245 | */ |
| 246 | public Map<Locale, String> readLocalizedStringFromXmls(String resourcePath) |
| 247 | throws IOException, LocalizedStringNotFoundException { |
| 248 | File resourceDir = new File(resourcePath); |
| 249 | if (!resourceDir.isDirectory()) { |
| 250 | throw new LocalizedStringNotFoundException(resourcePath + " is not a directory."); |
| 251 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 252 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 253 | Map<Locale, String> result = |
| 254 | // Overrides the string comparator so that sr is sorted behind sr-Latn. And thus |
| 255 | // recovery can find the most relevant locale when going down the list. |
| 256 | new TreeMap<>( |
| 257 | (Locale l1, Locale l2) -> { |
| 258 | if (l1.toLanguageTag().equals(l2.toLanguageTag())) { |
| 259 | return 0; |
| 260 | } |
| 261 | if (l1.getLanguage().equals(l2.toLanguageTag())) { |
| 262 | return -1; |
| 263 | } |
| 264 | if (l2.getLanguage().equals(l1.toLanguageTag())) { |
| 265 | return 1; |
| 266 | } |
| 267 | return l1.toLanguageTag().compareTo(l2.toLanguageTag()); |
| 268 | }); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 269 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 270 | // Find all the localized resource subdirectories in the format of values-$LOCALE |
| 271 | String[] nameList = |
| 272 | resourceDir.list((File file, String name) -> name.startsWith("values-")); |
| 273 | for (String name : nameList) { |
| 274 | File textFile = new File(resourcePath, name + "/strings.xml"); |
| 275 | String localizedText; |
| 276 | try { |
| 277 | localizedText = getTextString(textFile, mTextName); |
| 278 | } catch (IOException | ParserConfigurationException | org.xml.sax.SAXException e) { |
| 279 | throw new LocalizedStringNotFoundException( |
| 280 | "Failed to read the translated text for locale " + name, e); |
| 281 | } |
| 282 | |
| 283 | Locale locale = getLocaleFromFilename(name); |
| 284 | // Removes the double quotation mark from the text. |
| 285 | result.put(locale, localizedText.substring(1, localizedText.length() - 1)); |
| 286 | } |
| 287 | |
| 288 | return result; |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Returns a font object associated given the given locale |
| 293 | * |
| 294 | * @throws IOException if the font file fails to open |
| 295 | * @throws FontFormatException if the font file doesn't have the expected format |
| 296 | */ |
| 297 | private Font loadFontsByLocale(String language) throws IOException, FontFormatException { |
| 298 | String fontName = LANGUAGE_TO_FONT_MAP.getOrDefault(language, DEFAULT_FONT_NAME); |
| 299 | String[] suffixes = {".otf", ".ttf", ".ttc"}; |
| 300 | for (String suffix : suffixes) { |
| 301 | File fontFile = new File(mFontDirPath, fontName + suffix); |
| 302 | if (fontFile.isFile()) { |
| 303 | return Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(mFontSize); |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | throw new IOException( |
| 308 | "Can not find the font file " + fontName + " for language " + language); |
| 309 | } |
| 310 | |
| 311 | /** Separates the text string by spaces and wraps it by words. */ |
| 312 | private List<String> wrapTextByWords(String text, FontMetrics metrics) { |
| 313 | List<String> wrappedText = new ArrayList<>(); |
| 314 | StringTokenizer st = new StringTokenizer(text, " \n"); |
| 315 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 316 | StringBuilder line = new StringBuilder(); |
| 317 | while (st.hasMoreTokens()) { |
| 318 | String token = st.nextToken(); |
| 319 | if (metrics.stringWidth(line + token + " ") > mImageWidth) { |
| 320 | wrappedText.add(line.toString()); |
| 321 | line = new StringBuilder(); |
| 322 | } |
| 323 | line.append(token).append(" "); |
| 324 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 325 | wrappedText.add(line.toString()); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 326 | |
| 327 | return wrappedText; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 328 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 329 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 330 | /** One character is a word for CJK. */ |
| 331 | private List<String> wrapTextByCharacters(String text, FontMetrics metrics) { |
| 332 | List<String> wrappedText = new ArrayList<>(); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 333 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 334 | StringBuilder line = new StringBuilder(); |
| 335 | for (char token : text.toCharArray()) { |
| 336 | if (metrics.stringWidth(line + Character.toString(token)) > mImageWidth) { |
| 337 | wrappedText.add(line.toString()); |
| 338 | line = new StringBuilder(); |
| 339 | } |
| 340 | line.append(token); |
| 341 | } |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 342 | wrappedText.add(line.toString()); |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 343 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 344 | return wrappedText; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 345 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 346 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 347 | /** |
| 348 | * Wraps the text with a maximum of mImageWidth pixels per line. |
| 349 | * |
| 350 | * @param text the string representation of text to wrap |
| 351 | * @param metrics the metrics of the Font used to draw the text; it gives the width in pixels of |
| 352 | * the text given its string representation |
| 353 | * @return a list of strings with their width smaller than mImageWidth pixels |
| 354 | */ |
| 355 | private List<String> wrapText(String text, FontMetrics metrics, String language) { |
| 356 | if (LOGOGRAM_LANGUAGE.contains(language)) { |
| 357 | return wrapTextByCharacters(text, metrics); |
| 358 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 359 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 360 | return wrapTextByWords(text, metrics); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 361 | } |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 362 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 363 | /** |
| 364 | * Encodes the information of the text image for |locale|. According to minui/resources.cpp, the |
| 365 | * width, height and locale of the image is decoded as: int w = (row[1] << 8) | row[0]; int h = |
| 366 | * (row[3] << 8) | row[2]; __unused int len = row[4]; char* loc = |
| 367 | * reinterpret_cast<char*>(&row[5]); |
| 368 | */ |
| 369 | private List<Integer> encodeTextInfo(int width, int height, String locale) { |
| 370 | List<Integer> info = |
| 371 | new ArrayList<>( |
| 372 | Arrays.asList( |
| 373 | width & 0xff, |
| 374 | width >> 8, |
| 375 | height & 0xff, |
| 376 | height >> 8, |
| 377 | locale.length())); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 378 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 379 | byte[] localeBytes = locale.getBytes(); |
| 380 | for (byte b : localeBytes) { |
| 381 | info.add((int) b); |
| 382 | } |
| 383 | info.add(0); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 384 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 385 | return info; |
Tianjie Xu | 22dd019 | 2018-10-17 15:39:00 -0700 | [diff] [blame] | 386 | } |
| 387 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 388 | /** Returns Graphics2D object that uses the given locale. */ |
| 389 | private Graphics2D createGraphics(Locale locale) throws IOException, FontFormatException { |
| 390 | Graphics2D graphics = mBufferedImage.createGraphics(); |
| 391 | graphics.setColor(Color.WHITE); |
| 392 | graphics.setRenderingHint( |
| 393 | RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); |
| 394 | graphics.setFont(loadFontsByLocale(locale.getLanguage())); |
| 395 | |
| 396 | return graphics; |
| 397 | } |
| 398 | |
| 399 | /** Returns the maximum screen width needed to fit the given text after wrapping. */ |
| 400 | private int measureTextWidth(String text, Locale locale) |
| 401 | throws IOException, FontFormatException { |
| 402 | Graphics2D graphics = createGraphics(locale); |
| 403 | FontMetrics fontMetrics = graphics.getFontMetrics(); |
| 404 | List<String> wrappedText = wrapText(text, fontMetrics, locale.getLanguage()); |
| 405 | |
| 406 | int textWidth = 0; |
| 407 | for (String line : wrappedText) { |
| 408 | textWidth = Math.max(textWidth, fontMetrics.stringWidth(line)); |
| 409 | } |
| 410 | |
| 411 | // This may happen if one single word is larger than the image width. |
| 412 | if (textWidth > mImageWidth) { |
| 413 | throw new IllegalStateException( |
| 414 | "Wrapped text width " |
| 415 | + textWidth |
| 416 | + " is larger than image width " |
| 417 | + mImageWidth |
| 418 | + " for locale: " |
| 419 | + locale); |
| 420 | } |
| 421 | |
| 422 | return textWidth; |
| 423 | } |
| 424 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 425 | /** |
| 426 | * Draws the text string on the canvas for given locale. |
| 427 | * |
| 428 | * @param text the string to draw on canvas |
| 429 | * @param locale the current locale tag of the string to draw |
| 430 | * @throws IOException if we cannot find the corresponding font file for the given locale. |
| 431 | * @throws FontFormatException if we failed to load the font file for the given locale. |
| 432 | */ |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 433 | private void drawText(String text, Locale locale, String languageTag) |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 434 | throws IOException, FontFormatException { |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 435 | System.out.println("Encoding \"" + locale + "\" as \"" + languageTag + "\": " + text); |
| 436 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 437 | Graphics2D graphics = createGraphics(locale); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 438 | FontMetrics fontMetrics = graphics.getFontMetrics(); |
| 439 | List<String> wrappedText = wrapText(text, fontMetrics, locale.getLanguage()); |
| 440 | |
| 441 | // Marks the start y offset for the text image of current locale; and reserves one line to |
| 442 | // encode the image metadata. |
| 443 | int currentImageStart = mVerticalOffset; |
| 444 | mVerticalOffset += 1; |
| 445 | for (String line : wrappedText) { |
| 446 | int lineHeight = fontMetrics.getHeight(); |
| 447 | // Doubles the height of the image if we are short of space. |
| 448 | if (mVerticalOffset + lineHeight >= mImageHeight) { |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 449 | resize(mImageWidth, mImageHeight * 2); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 450 | } |
| 451 | |
| 452 | // Draws the text at mVerticalOffset and increments the offset with line space. |
| 453 | int baseLine = mVerticalOffset + lineHeight - fontMetrics.getDescent(); |
| 454 | |
| 455 | // Draws from right if it's an RTL language. |
| 456 | int x = |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 457 | mCenterAlignment |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 458 | ? (mImageWidth - fontMetrics.stringWidth(line)) / 2 |
| 459 | : RTL_LANGUAGE.contains(languageTag) |
| 460 | ? mImageWidth - fontMetrics.stringWidth(line) |
| 461 | : 0; |
| 462 | |
| 463 | graphics.drawString(line, x, baseLine); |
| 464 | |
| 465 | mVerticalOffset += lineHeight; |
| 466 | } |
| 467 | |
| 468 | // Encodes the metadata of the current localized image as pixels. |
| 469 | int currentImageHeight = mVerticalOffset - currentImageStart - 1; |
| 470 | List<Integer> info = encodeTextInfo(mImageWidth, currentImageHeight, languageTag); |
| 471 | for (int i = 0; i < info.size(); i++) { |
| 472 | int[] pixel = {info.get(i)}; |
| 473 | mBufferedImage.getRaster().setPixel(i, currentImageStart, pixel); |
| 474 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 475 | } |
| 476 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 477 | /** |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 478 | * Redraws the image with the new width and new height. |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 479 | * |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 480 | * @param width the new width of the image in pixels. |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 481 | * @param height the new height of the image in pixels. |
| 482 | */ |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 483 | private void resize(int width, int height) { |
| 484 | BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 485 | Graphics2D graphic = resizedImage.createGraphics(); |
| 486 | graphic.drawImage(mBufferedImage, 0, 0, null); |
| 487 | graphic.dispose(); |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 488 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 489 | mBufferedImage = resizedImage; |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 490 | mImageWidth = width; |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 491 | mImageHeight = height; |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 492 | } |
| 493 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 494 | /** |
| 495 | * This function draws the font characters and saves the result to outputPath. |
| 496 | * |
| 497 | * @param localizedTextMap a map from locale to its translated text string |
| 498 | * @param outputPath the path to write the generated image file. |
| 499 | * @throws FontFormatException if there's a format error in one of the font file |
| 500 | * @throws IOException if we cannot find the font file for one of the locale, or we failed to |
| 501 | * write the image file. |
| 502 | */ |
| 503 | public void generateImage(Map<Locale, String> localizedTextMap, String outputPath) |
| 504 | throws FontFormatException, IOException { |
| 505 | Map<String, Integer> languageCount = new TreeMap<>(); |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 506 | int textWidth = 0; |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 507 | for (Locale locale : localizedTextMap.keySet()) { |
| 508 | String language = locale.getLanguage(); |
| 509 | languageCount.put(language, languageCount.getOrDefault(language, 0) + 1); |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 510 | textWidth = Math.max(textWidth, measureTextWidth(localizedTextMap.get(locale), locale)); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 511 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 512 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 513 | // Removes the black margins to reduce the size of the image. |
| 514 | resize(textWidth, mImageHeight); |
| 515 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 516 | for (Locale locale : localizedTextMap.keySet()) { |
| 517 | Integer count = languageCount.get(locale.getLanguage()); |
| 518 | // Recovery expects en-US instead of en_US. |
| 519 | String languageTag = locale.toLanguageTag(); |
| 520 | if (count == 1) { |
| 521 | // Make the last country variant for a given language be the catch-all for that |
| 522 | // language. |
| 523 | languageTag = locale.getLanguage(); |
| 524 | } else { |
| 525 | languageCount.put(locale.getLanguage(), count - 1); |
| 526 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 527 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 528 | drawText(localizedTextMap.get(locale), locale, languageTag); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 529 | } |
| 530 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 531 | resize(mImageWidth, mVerticalOffset); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 532 | ImageIO.write(mBufferedImage, "png", new File(outputPath)); |
| 533 | } |
| 534 | |
| 535 | /** Prints the helper message. */ |
| 536 | public static void printUsage(Options options) { |
| 537 | new HelpFormatter().printHelp("java -jar path_to_jar [required_options]", options); |
| 538 | } |
| 539 | |
| 540 | /** Creates the command line options. */ |
| 541 | public static Options createOptions() { |
| 542 | Options options = new Options(); |
| 543 | options.addOption( |
| 544 | OptionBuilder.withLongOpt("image_width") |
| 545 | .withDescription("The initial width of the image in pixels.") |
| 546 | .hasArgs(1) |
| 547 | .isRequired() |
| 548 | .create()); |
| 549 | |
| 550 | options.addOption( |
| 551 | OptionBuilder.withLongOpt("text_name") |
| 552 | .withDescription( |
| 553 | "The description of the text string, e.g. recovery_erasing") |
| 554 | .hasArgs(1) |
| 555 | .isRequired() |
| 556 | .create()); |
| 557 | |
| 558 | options.addOption( |
| 559 | OptionBuilder.withLongOpt("font_dir") |
| 560 | .withDescription( |
| 561 | "The directory that contains all the support font format files, " |
| 562 | + "e.g. $OUT/system/fonts/") |
| 563 | .hasArgs(1) |
| 564 | .isRequired() |
| 565 | .create()); |
| 566 | |
| 567 | options.addOption( |
| 568 | OptionBuilder.withLongOpt("resource_dir") |
| 569 | .withDescription( |
| 570 | "The resource directory that contains all the translated strings in" |
| 571 | + " xml format, e.g." |
| 572 | + " bootable/recovery/tools/recovery_l10n/res/") |
| 573 | .hasArgs(1) |
| 574 | .isRequired() |
| 575 | .create()); |
| 576 | |
| 577 | options.addOption( |
| 578 | OptionBuilder.withLongOpt("output_file") |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 579 | .withDescription("Path to the generated image.") |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 580 | .hasArgs(1) |
| 581 | .isRequired() |
| 582 | .create()); |
| 583 | |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 584 | options.addOption( |
| 585 | OptionBuilder.withLongOpt("center_alignment") |
| 586 | .withDescription("Align the text in the center of the screen.") |
| 587 | .hasArg(false) |
| 588 | .create()); |
| 589 | |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 590 | return options; |
| 591 | } |
| 592 | |
| 593 | /** The main function parses the command line options and generates the desired text image. */ |
| 594 | public static void main(String[] args) |
| 595 | throws NumberFormatException, IOException, FontFormatException, |
| 596 | LocalizedStringNotFoundException { |
| 597 | Options options = createOptions(); |
| 598 | CommandLine cmd; |
| 599 | try { |
| 600 | cmd = new GnuParser().parse(options, args); |
| 601 | } catch (ParseException e) { |
| 602 | System.err.println(e.getMessage()); |
| 603 | printUsage(options); |
| 604 | return; |
| 605 | } |
| 606 | |
| 607 | int imageWidth = Integer.parseUnsignedInt(cmd.getOptionValue("image_width")); |
| 608 | |
| 609 | ImageGenerator imageGenerator = |
| 610 | new ImageGenerator( |
| 611 | imageWidth, |
| 612 | cmd.getOptionValue("text_name"), |
| 613 | DEFAULT_FONT_SIZE, |
Tianjie Xu | b8564e1 | 2018-11-12 17:06:14 -0800 | [diff] [blame] | 614 | cmd.getOptionValue("font_dir"), |
| 615 | cmd.hasOption("center_alignment")); |
Tianjie Xu | b97f7e5 | 2018-11-12 16:28:14 -0800 | [diff] [blame] | 616 | |
| 617 | Map<Locale, String> localizedStringMap = |
| 618 | imageGenerator.readLocalizedStringFromXmls(cmd.getOptionValue("resource_dir")); |
| 619 | imageGenerator.generateImage(localizedStringMap, cmd.getOptionValue("output_file")); |
| 620 | } |
Tianjie Xu | 721f679 | 2018-10-08 17:04:54 -0700 | [diff] [blame] | 621 | } |