Yu-Ping Wu | d71b445 | 2020-06-16 11:00:26 +0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 2 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 5 | """Script to generate bitmaps for firmware screens.""" |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 6 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 7 | import argparse |
| 8 | from collections import defaultdict, namedtuple |
| 9 | import copy |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 10 | import fractions |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 11 | import glob |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 12 | import json |
Hung-Te Lin | 04addcc | 2015-03-23 18:43:30 +0800 | [diff] [blame] | 13 | import multiprocessing |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 14 | import os |
| 15 | import re |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 16 | import shutil |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 17 | import signal |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 18 | import subprocess |
| 19 | import sys |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 20 | import tempfile |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 21 | from xml.etree import ElementTree |
Hung-Te Lin | 04addcc | 2015-03-23 18:43:30 +0800 | [diff] [blame] | 22 | |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 23 | import yaml |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 24 | from PIL import Image |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 25 | |
| 26 | SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__)) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 27 | |
| 28 | STRINGS_GRD_FILE = 'firmware_strings.grd' |
| 29 | STRINGS_JSON_FILE_TMPL = '{}.json' |
| 30 | FORMAT_FILE = 'format.yaml' |
| 31 | BOARDS_CONFIG_FILE = 'boards.yaml' |
| 32 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 33 | OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build')) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 34 | |
| 35 | ONE_LINE_DIR = 'one_line' |
| 36 | SVG_FILES = '*.svg' |
| 37 | PNG_FILES = '*.png' |
| 38 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 39 | DIAGNOSTIC_UI = os.getenv('DIAGNOSTIC_UI') == '1' |
| 40 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 41 | # String format YAML key names. |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 42 | KEY_DEFAULT = '_DEFAULT_' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 43 | KEY_LOCALES = 'locales' |
Yu-Ping Wu | 338f083 | 2020-10-23 16:14:40 +0800 | [diff] [blame] | 44 | KEY_GENERIC_FILES = 'generic_files' |
| 45 | KEY_LOCALIZED_FILES = 'localized_files' |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 46 | KEY_DIAGNOSTIC_FILES = 'diagnostic_files' |
| 47 | KEY_SPRITE_FILES = 'sprite_files' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 48 | KEY_STYLES = 'styles' |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 49 | KEY_BGCOLOR = 'bgcolor' |
| 50 | KEY_FGCOLOR = 'fgcolor' |
| 51 | KEY_HEIGHT = 'height' |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 52 | KEY_MAX_WIDTH = 'max_width' |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 53 | KEY_FONTS = 'fonts' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 54 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 55 | # Board config YAML key names. |
| 56 | SCREEN_KEY = 'screen' |
| 57 | PANEL_KEY = 'panel' |
| 58 | SDCARD_KEY = 'sdcard' |
| 59 | BAD_USB3_KEY = 'bad_usb3' |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 60 | DPI_KEY = 'dpi' |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 61 | LOCALES_KEY = 'locales' |
| 62 | RTL_KEY = 'rtl' |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 63 | RW_OVERRIDE_KEY = 'rw_override' |
| 64 | |
| 65 | BMP_HEADER_OFFSET_NUM_LINES = 6 |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 66 | |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 67 | # Regular expressions used to eliminate spurious spaces and newlines in |
| 68 | # translation strings. |
| 69 | NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])') |
| 70 | NEWLINE_REPLACEMENT = r'\1 \2' |
| 71 | CRLF_PATTERN = re.compile(r'\r\n') |
| 72 | MULTIBLANK_PATTERN = re.compile(r' *') |
| 73 | |
Yu-Ping Wu | 3d07a06 | 2021-01-26 18:10:32 +0800 | [diff] [blame] | 74 | # The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if |
| 75 | # `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also |
| 76 | # see the 'styles' section in format.yaml. |
| 77 | SCALE_BASE = 1000 |
| 78 | DEFAULT_GLYPH_HEIGHT = 20 |
| 79 | |
Yu-Ping Wu | cc86d6a | 2020-11-27 12:48:19 +0800 | [diff] [blame] | 80 | GLYPH_FONT = 'Cousine' |
Yu-Ping Wu | 11027f0 | 2020-10-14 17:35:42 +0800 | [diff] [blame] | 81 | |
Yu-Ping Wu | abb9afb | 2020-10-27 17:15:22 +0800 | [diff] [blame] | 82 | LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl']) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 83 | |
Yu-Ping Wu | 6b282c5 | 2020-03-19 12:54:15 +0800 | [diff] [blame] | 84 | |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 85 | class DataError(Exception): |
| 86 | pass |
| 87 | |
| 88 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 89 | class BuildImageError(Exception): |
| 90 | """The exception class for all errors generated during build image process.""" |
| 91 | |
| 92 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 93 | def get_config_with_defaults(configs, key): |
| 94 | """Gets config of `key` from `configs`. |
| 95 | |
| 96 | If `key` is not present in `configs`, the default config will be returned. |
| 97 | Similarly, if some config values are missing for `key`, the default ones will |
| 98 | be used. |
| 99 | """ |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 100 | config = configs[KEY_DEFAULT].copy() |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 101 | config.update(configs.get(key, {})) |
| 102 | return config |
| 103 | |
| 104 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 105 | def load_boards_config(filename): |
| 106 | """Loads the configuration of all boards from `filename`. |
| 107 | |
| 108 | Args: |
| 109 | filename: File name of a YAML config file. |
| 110 | |
| 111 | Returns: |
| 112 | A dictionary mapping each board name to its config. |
| 113 | """ |
| 114 | with open(filename, 'rb') as file: |
| 115 | raw = yaml.load(file) |
| 116 | |
| 117 | configs = {} |
| 118 | default = raw[KEY_DEFAULT] |
| 119 | if not default: |
| 120 | raise BuildImageError('Default configuration is not found') |
| 121 | for boards, params in raw.items(): |
| 122 | if boards == KEY_DEFAULT: |
| 123 | continue |
| 124 | config = copy.deepcopy(default) |
| 125 | if params: |
| 126 | config.update(params) |
| 127 | for board in boards.replace(',', ' ').split(): |
| 128 | configs[board] = config |
| 129 | |
| 130 | return configs |
| 131 | |
| 132 | |
| 133 | def check_fonts(fonts): |
| 134 | """Check if all fonts are available.""" |
| 135 | for locale, font in fonts.items(): |
| 136 | if subprocess.run(['fc-list', '-q', font]).returncode != 0: |
| 137 | raise BuildImageError('Font %r not found for locale %r' |
| 138 | % (font, locale)) |
| 139 | |
| 140 | |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 141 | def run_pango_view(input_file, output_file, locale, font, height, max_width, |
| 142 | dpi, bgcolor, fgcolor, hinting='full'): |
| 143 | """Run pango-view.""" |
| 144 | command = ['pango-view', '-q'] |
Yu-Ping Wu | 11027f0 | 2020-10-14 17:35:42 +0800 | [diff] [blame] | 145 | if locale: |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 146 | command += ['--language', locale] |
| 147 | |
| 148 | # Font size should be proportional to the height. Here we use 2 as the |
| 149 | # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml |
| 150 | # will be roughly equivalent to setting the screen resolution to 1366x768. |
| 151 | font_size = height / 2 |
| 152 | font_spec = '%s %r' % (font, font_size) |
| 153 | command += ['--font', font_spec] |
| 154 | |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 155 | if max_width: |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 156 | # When converting text to PNG by pango-view, the ratio of image height to |
| 157 | # the font size is usually no more than 1.1875 (with Roboto). Therefore, |
| 158 | # set the `max_width_pt` as follows to prevent UI drawing from exceeding |
| 159 | # the canvas boundary in depthcharge runtime. The divisor 2 is the same in |
| 160 | # the calculation of `font_size` above. |
| 161 | max_width_pt = int(max_width / 2 * 1.1875) |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 162 | command.append('--width=%d' % max_width_pt) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 163 | if dpi: |
| 164 | command.append('--dpi=%d' % dpi) |
Yu-Ping Wu | cc86d6a | 2020-11-27 12:48:19 +0800 | [diff] [blame] | 165 | command.append('--margin=0') |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 166 | command += ['--background', bgcolor] |
| 167 | command += ['--foreground', fgcolor] |
| 168 | command += ['--hinting', hinting] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 169 | |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 170 | command += ['--output', output_file] |
Yu-Ping Wu | 11027f0 | 2020-10-14 17:35:42 +0800 | [diff] [blame] | 171 | command.append(input_file) |
| 172 | |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 173 | subprocess.check_call(command, stdout=subprocess.PIPE) |
| 174 | |
| 175 | |
| 176 | def convert_text_to_image(locale, input_file, font, output_dir, height=None, |
| 177 | max_width=None, dpi=None, bgcolor='#000000', |
| 178 | fgcolor='#ffffff', use_svg=False): |
| 179 | """Converts text file `input_file` into image file(s). |
| 180 | |
| 181 | Because pango-view does not support assigning output format options for |
| 182 | bitmap, we must create images in SVG/PNG format and then post-process them |
| 183 | (e.g. convert into BMP by ImageMagick). |
| 184 | |
| 185 | Args: |
| 186 | locale: Locale (language) to select implicit rendering options. None for |
| 187 | locale-independent strings. |
| 188 | input_file: Path of input text file. |
| 189 | font: Font name. |
| 190 | height: Image height relative to the screen resolution. |
| 191 | max_width: Maximum image width relative to the screen resolution. |
| 192 | output_dir: Directory to generate image files. |
| 193 | bgcolor: Background color (#rrggbb). |
| 194 | fgcolor: Foreground color (#rrggbb). |
| 195 | use_svg: If set to True, generate SVG file. Otherwise, generate PNG file. |
| 196 | """ |
| 197 | os.makedirs(os.path.join(output_dir, ONE_LINE_DIR), exist_ok=True) |
| 198 | name, _ = os.path.splitext(os.path.basename(input_file)) |
| 199 | svg_file = os.path.join(output_dir, name + '.svg') |
| 200 | png_file = os.path.join(output_dir, name + '.png') |
| 201 | png_file_one_line = os.path.join(output_dir, ONE_LINE_DIR, name + '.png') |
| 202 | |
| 203 | if use_svg: |
| 204 | run_pango_view(input_file, svg_file, locale, font, height, 0, dpi, |
| 205 | bgcolor, fgcolor, hinting='none') |
| 206 | else: |
| 207 | run_pango_view(input_file, png_file, locale, font, height, max_width, dpi, |
| 208 | bgcolor, fgcolor) |
| 209 | if locale: |
| 210 | run_pango_view(input_file, png_file_one_line, locale, font, height, 0, |
| 211 | dpi, bgcolor, fgcolor) |
Yu-Ping Wu | 11027f0 | 2020-10-14 17:35:42 +0800 | [diff] [blame] | 212 | |
| 213 | |
Yu-Ping Wu | 703dcfd | 2021-01-08 10:52:10 +0800 | [diff] [blame] | 214 | def parse_locale_json_file(locale, json_dir): |
| 215 | """Parses given firmware string json file. |
| 216 | |
| 217 | Args: |
| 218 | locale: The name of the locale, e.g. "da" or "pt-BR". |
| 219 | json_dir: Directory containing json output from grit. |
| 220 | |
| 221 | Returns: |
| 222 | A dictionary for mapping of "name to content" for files to be generated. |
| 223 | """ |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 224 | result = {} |
Yu-Ping Wu | ae79af6 | 2020-09-23 16:48:06 +0800 | [diff] [blame] | 225 | filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale)) |
Yu-Ping Wu | d71b445 | 2020-06-16 11:00:26 +0800 | [diff] [blame] | 226 | with open(filename, encoding='utf-8-sig') as input_file: |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 227 | for tag, msgdict in json.load(input_file).items(): |
| 228 | msgtext = msgdict['message'] |
| 229 | msgtext = re.sub(CRLF_PATTERN, '\n', msgtext) |
| 230 | msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext) |
| 231 | msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext) |
| 232 | # Strip any trailing whitespace. A trailing newline appears to make |
| 233 | # Pango report a larger layout size than what's actually visible. |
| 234 | msgtext = msgtext.strip() |
| 235 | result[tag] = msgtext |
| 236 | return result |
| 237 | |
Yu-Ping Wu | ae79af6 | 2020-09-23 16:48:06 +0800 | [diff] [blame] | 238 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 239 | class Converter(object): |
| 240 | """Converter from assets, texts, URLs, and fonts to bitmap images. |
| 241 | |
| 242 | Attributes: |
| 243 | ASSET_DIR (str): Directory of image assets. |
| 244 | DEFAULT_OUTPUT_EXT (str): Default output file extension. |
| 245 | DEFAULT_REPLACE_MAP (dict): Default mapping of file replacement. For |
| 246 | {'a': 'b'}, "a.*" will be converted to "b.*". |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 247 | ASSET_MAX_COLORS (int): Maximum colors to use for converting image assets |
| 248 | to bitmaps. |
| 249 | DEFAULT_BACKGROUND (tuple): Default background color. |
| 250 | BACKGROUND_COLORS (dict): Background color of each image. Key is the image |
| 251 | name and value is a tuple of RGB values. |
| 252 | """ |
| 253 | |
| 254 | ASSET_DIR = 'assets' |
| 255 | DEFAULT_OUTPUT_EXT = '.bmp' |
| 256 | |
| 257 | DEFAULT_REPLACE_MAP = { |
| 258 | 'rec_sel_desc1_no_sd': '', |
| 259 | 'rec_sel_desc1_no_phone_no_sd': '', |
| 260 | 'rec_disk_step1_desc0_no_sd': '', |
| 261 | 'rec_to_dev_desc1_phyrec': '', |
| 262 | 'rec_to_dev_desc1_power': '', |
| 263 | 'navigate0_tablet': '', |
| 264 | 'navigate1_tablet': '', |
| 265 | 'nav-button_power': '', |
| 266 | 'nav-button_volume_up': '', |
| 267 | 'nav-button_volume_down': '', |
| 268 | 'broken_desc_phyrec': '', |
| 269 | 'broken_desc_detach': '', |
| 270 | } |
| 271 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 272 | # background colors |
| 273 | DEFAULT_BACKGROUND = (0x20, 0x21, 0x24) |
| 274 | LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19) |
| 275 | LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39) |
| 276 | ASSET_MAX_COLORS = 128 |
| 277 | |
| 278 | BACKGROUND_COLORS = { |
| 279 | 'ic_dropdown': LANG_HEADER_BACKGROUND, |
| 280 | 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND, |
| 281 | 'ic_dropright_focus': LINK_SELECTED_BACKGROUND, |
| 282 | 'ic_globe': LANG_HEADER_BACKGROUND, |
| 283 | 'ic_search_focus': LINK_SELECTED_BACKGROUND, |
| 284 | 'ic_settings_focus': LINK_SELECTED_BACKGROUND, |
| 285 | 'ic_power_focus': LINK_SELECTED_BACKGROUND, |
| 286 | } |
| 287 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 288 | def __init__(self, board, formats, board_config, output): |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 289 | """Inits converter. |
| 290 | |
| 291 | Args: |
| 292 | board: Board name. |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 293 | formats: A dictionary of string formats. |
| 294 | board_config: A dictionary of board configurations. |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 295 | output: Output directory. |
| 296 | """ |
| 297 | self.board = board |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 298 | self.formats = formats |
| 299 | self.config = board_config |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 300 | self.set_dirs(output) |
| 301 | self.set_screen() |
| 302 | self.set_replace_map() |
| 303 | self.set_locales() |
Yu-Ping Wu | 96cf002 | 2021-01-07 15:55:49 +0800 | [diff] [blame] | 304 | self.text_max_colors = self.get_text_colors(self.config[DPI_KEY]) |
Yu-Ping Wu | 354a700 | 2021-01-07 16:07:02 +0800 | [diff] [blame] | 305 | self.dpi_warning_printed = False |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 306 | |
| 307 | def set_dirs(self, output): |
| 308 | """Sets board output directory and stage directory. |
| 309 | |
| 310 | Args: |
| 311 | output: Output directory. |
| 312 | """ |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 313 | self.strings_dir = os.path.join(SCRIPT_BASE, 'strings') |
| 314 | self.locale_dir = os.path.join(self.strings_dir, 'locale') |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 315 | self.output_dir = os.path.join(output, self.board) |
| 316 | self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro') |
| 317 | self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw') |
| 318 | self.stage_dir = os.path.join(output, '.stage') |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 319 | self.stage_locale_dir = os.path.join(self.stage_dir, 'locale') |
| 320 | self.stage_font_dir = os.path.join(self.stage_dir, 'font') |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 321 | self.temp_dir = os.path.join(self.stage_dir, 'tmp') |
| 322 | |
| 323 | def set_screen(self): |
| 324 | """Sets screen width and height.""" |
| 325 | self.screen_width, self.screen_height = self.config[SCREEN_KEY] |
| 326 | |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 327 | self.panel_stretch = fractions.Fraction(1) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 328 | if self.config[PANEL_KEY]: |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 329 | # Calculate `panel_stretch`. It's used to shrink images horizontally so |
| 330 | # that the resulting images will look proportional to the original image |
| 331 | # on the stretched display. If the display is not stretched, meaning the |
| 332 | # aspect ratio is same as the screen where images were rendered, no |
| 333 | # shrinking is performed. |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 334 | panel_width, panel_height = self.config[PANEL_KEY] |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 335 | self.panel_stretch = fractions.Fraction(self.screen_width * panel_height, |
| 336 | self.screen_height * panel_width) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 337 | |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 338 | if self.panel_stretch > 1: |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 339 | raise BuildImageError('Panel aspect ratio (%f) is smaller than screen ' |
| 340 | 'aspect ratio (%f). It indicates screen will be ' |
| 341 | 'shrunk horizontally. It is currently unsupported.' |
| 342 | % (panel_width / panel_height, |
| 343 | self.screen_width / self.screen_height)) |
| 344 | |
| 345 | # Set up square drawing area |
| 346 | self.canvas_px = min(self.screen_width, self.screen_height) |
| 347 | |
| 348 | def set_replace_map(self): |
| 349 | """Sets a map replacing images. |
| 350 | |
| 351 | For each (key, value), image 'key' will be replaced by image 'value'. |
| 352 | """ |
| 353 | replace_map = self.DEFAULT_REPLACE_MAP.copy() |
| 354 | |
| 355 | if os.getenv('DETACHABLE') == '1': |
| 356 | replace_map.update({ |
| 357 | 'nav-key_enter': 'nav-button_power', |
| 358 | 'nav-key_up': 'nav-button_volume_up', |
| 359 | 'nav-key_down': 'nav-button_volume_down', |
| 360 | 'navigate0': 'navigate0_tablet', |
| 361 | 'navigate1': 'navigate1_tablet', |
| 362 | 'broken_desc': 'broken_desc_detach', |
| 363 | }) |
| 364 | |
| 365 | physical_presence = os.getenv('PHYSICAL_PRESENCE') |
| 366 | if physical_presence == 'recovery': |
| 367 | replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_phyrec' |
| 368 | replace_map['broken_desc'] = 'broken_desc_phyrec' |
| 369 | elif physical_presence == 'power': |
| 370 | replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_power' |
| 371 | elif physical_presence != 'keyboard': |
| 372 | raise BuildImageError('Invalid physical presence setting %s for board %s' |
| 373 | % (physical_presence, self.board)) |
| 374 | |
| 375 | if not self.config[SDCARD_KEY]: |
| 376 | replace_map.update({ |
| 377 | 'rec_sel_desc1': 'rec_sel_desc1_no_sd', |
| 378 | 'rec_sel_desc1_no_phone': 'rec_sel_desc1_no_phone_no_sd', |
| 379 | 'rec_disk_step1_desc0': 'rec_disk_step1_desc0_no_sd', |
| 380 | }) |
| 381 | |
| 382 | self.replace_map = replace_map |
| 383 | |
| 384 | def set_locales(self): |
| 385 | """Sets a list of locales for which localized images are converted.""" |
| 386 | # LOCALES environment variable can overwrite boards.yaml |
| 387 | env_locales = os.getenv('LOCALES') |
| 388 | rtl_locales = set(self.config[RTL_KEY]) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 389 | if env_locales: |
| 390 | locales = env_locales.split() |
| 391 | else: |
| 392 | locales = self.config[LOCALES_KEY] |
| 393 | # Check rtl_locales are contained in locales. |
| 394 | unknown_rtl_locales = rtl_locales - set(locales) |
| 395 | if unknown_rtl_locales: |
| 396 | raise BuildImageError('Unknown locales %s in %s' % |
| 397 | (list(unknown_rtl_locales), RTL_KEY)) |
Yu-Ping Wu | abb9afb | 2020-10-27 17:15:22 +0800 | [diff] [blame] | 398 | self.locales = [LocaleInfo(code, code in rtl_locales) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 399 | for code in locales] |
| 400 | |
Yu-Ping Wu | 96cf002 | 2021-01-07 15:55:49 +0800 | [diff] [blame] | 401 | @classmethod |
| 402 | def get_text_colors(cls, dpi): |
| 403 | """Derive maximum text colors from `dpi`.""" |
| 404 | if dpi < 64: |
| 405 | return 2 |
| 406 | elif dpi < 72: |
| 407 | return 3 |
| 408 | elif dpi < 80: |
| 409 | return 4 |
| 410 | elif dpi < 96: |
| 411 | return 5 |
| 412 | elif dpi < 112: |
| 413 | return 6 |
| 414 | else: |
| 415 | return 7 |
| 416 | |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 417 | def _to_px(self, length, num_lines=1): |
| 418 | """Converts the relative coordinate to absolute one in pixels.""" |
Yu-Ping Wu | 3d07a06 | 2021-01-26 18:10:32 +0800 | [diff] [blame] | 419 | return int(self.canvas_px * length / SCALE_BASE) * num_lines |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 420 | |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 421 | def _get_png_height(self, png_file): |
| 422 | with Image.open(png_file) as image: |
| 423 | return image.size[1] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 424 | |
| 425 | def get_num_lines(self, file, one_line_dir): |
| 426 | """Gets the number of lines of text in `file`.""" |
| 427 | name, _ = os.path.splitext(os.path.basename(file)) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 428 | png_name = name + '.png' |
| 429 | multi_line_file = os.path.join(os.path.dirname(file), png_name) |
| 430 | one_line_file = os.path.join(one_line_dir, png_name) |
| 431 | # The number of lines is determined by comparing the height of |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 432 | # `multi_line_file` with `one_line_file`, where the latter is generated |
| 433 | # without the '--width' option passed to pango-view. |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 434 | height = self._get_png_height(multi_line_file) |
| 435 | line_height = self._get_png_height(one_line_file) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 436 | return int(round(height / line_height)) |
| 437 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 438 | def convert_svg_to_png(self, svg_file, png_file, height, num_lines, |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 439 | background): |
| 440 | """Converts .svg file to .png file.""" |
| 441 | background_hex = ''.join(format(x, '02x') for x in background) |
| 442 | # If the width/height of the SVG file is specified in points, the |
| 443 | # rsvg-convert command with default 90DPI will potentially cause the pixels |
| 444 | # at the right/bottom border of the output image to be transparent (or |
| 445 | # filled with the specified background color). This seems like an |
| 446 | # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here |
| 447 | # to avoid the scaling. |
| 448 | command = ['rsvg-convert', |
| 449 | '--background-color', "'#%s'" % background_hex, |
| 450 | '--dpi-x', '72', |
| 451 | '--dpi-y', '72', |
| 452 | '-o', png_file] |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 453 | height_px = self._to_px(height, num_lines) |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 454 | if height_px <= 0: |
| 455 | raise BuildImageError('Height of %r <= 0 (%dpx)' % |
| 456 | (os.path.basename(svg_file), height_px)) |
| 457 | command.extend(['--height', '%d' % height_px]) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 458 | command.append(svg_file) |
| 459 | subprocess.check_call(' '.join(command), shell=True) |
| 460 | |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 461 | def convert_to_bitmap(self, input_file, height, num_lines, background, output, |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 462 | max_colors): |
| 463 | """Converts an image file `input_file` to a BMP file `output`.""" |
| 464 | image = Image.open(input_file) |
| 465 | |
| 466 | # Process alpha channel and transparency. |
| 467 | if image.mode == 'RGBA': |
| 468 | target = Image.new('RGB', image.size, background) |
| 469 | image.load() # required for image.split() |
| 470 | mask = image.split()[-1] |
| 471 | target.paste(image, mask=mask) |
| 472 | elif (image.mode == 'P') and ('transparency' in image.info): |
| 473 | exit('Sorry, PNG with RGBA palette is not supported.') |
| 474 | elif image.mode != 'RGB': |
| 475 | target = image.convert('RGB') |
| 476 | else: |
| 477 | target = image |
| 478 | |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 479 | width_px, height_px = image.size |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 480 | max_height_px = self._to_px(height, num_lines) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 481 | # If the image size is larger than what will be displayed at runtime, |
| 482 | # downscale it. |
| 483 | if height_px > max_height_px: |
Yu-Ping Wu | 354a700 | 2021-01-07 16:07:02 +0800 | [diff] [blame] | 484 | if not self.dpi_warning_printed: |
| 485 | print('Reducing effective DPI to %d, limited by screen resolution' % |
| 486 | (self.config[DPI_KEY] * max_height_px // height_px)) |
| 487 | self.dpi_warning_printed = True |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 488 | height_px = max_height_px |
| 489 | width_px = height_px * image.size[0] // image.size[1] |
| 490 | # Stretch image horizontally for stretched display. |
Yu-Ping Wu | e445e04 | 2020-11-19 15:53:42 +0800 | [diff] [blame] | 491 | if self.panel_stretch != 1: |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 492 | width_px = int(width_px * self.panel_stretch) |
| 493 | new_size = width_px, height_px |
| 494 | if new_size != image.size: |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 495 | target = target.resize(new_size, Image.BICUBIC) |
| 496 | |
| 497 | # Export and downsample color space. |
| 498 | target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE |
| 499 | ).save(output) |
| 500 | |
| 501 | with open(output, 'rb+') as f: |
| 502 | f.seek(BMP_HEADER_OFFSET_NUM_LINES) |
| 503 | f.write(bytearray([num_lines])) |
| 504 | |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 505 | def convert(self, files, output_dir, heights, max_widths, max_colors, |
| 506 | one_line_dir=None): |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 507 | """Converts file(s) to bitmap format.""" |
| 508 | if not files: |
| 509 | raise BuildImageError('Unable to find file(s) to convert') |
| 510 | |
| 511 | for file in files: |
| 512 | name, ext = os.path.splitext(os.path.basename(file)) |
| 513 | output = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT) |
| 514 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 515 | if name in self.replace_map: |
| 516 | name = self.replace_map[name] |
| 517 | if not name: |
| 518 | continue |
| 519 | print('Replace: %s => %s' % (file, name)) |
| 520 | file = os.path.join(os.path.dirname(file), name + ext) |
| 521 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 522 | background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND) |
| 523 | height = heights[name] |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 524 | max_width = max_widths[name] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 525 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 526 | # Determine num_lines in order to scale the image |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 527 | if one_line_dir and max_width: |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 528 | num_lines = self.get_num_lines(file, one_line_dir) |
| 529 | else: |
| 530 | num_lines = 1 |
| 531 | |
| 532 | if ext == '.svg': |
| 533 | png_file = os.path.join(self.temp_dir, name + '.png') |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 534 | self.convert_svg_to_png(file, png_file, height, num_lines, background) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 535 | file = png_file |
| 536 | |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 537 | self.convert_to_bitmap(file, height, num_lines, background, output, |
| 538 | max_colors) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 539 | |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 540 | def convert_sprite_images(self): |
| 541 | """Converts sprite images.""" |
| 542 | names = self.formats[KEY_SPRITE_FILES] |
| 543 | styles = self.formats[KEY_STYLES] |
| 544 | # Check redundant images |
| 545 | for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)): |
| 546 | name, _ = os.path.splitext(os.path.basename(filename)) |
| 547 | if name not in names: |
| 548 | raise BuildImageError('Sprite image %r not specified in %s' % |
| 549 | (filename, FORMAT_FILE)) |
| 550 | # Convert images |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 551 | files = [] |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 552 | heights = {} |
| 553 | for name, category in names.items(): |
| 554 | style = get_config_with_defaults(styles, category) |
| 555 | files.append(os.path.join(self.ASSET_DIR, name + '.svg')) |
| 556 | heights[name] = style[KEY_HEIGHT] |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 557 | max_widths = defaultdict(lambda: None) |
| 558 | self.convert(files, self.output_dir, heights, max_widths, |
| 559 | self.ASSET_MAX_COLORS) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 560 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 561 | def build_generic_strings(self): |
| 562 | """Builds images of generic (locale-independent) strings.""" |
| 563 | dpi = self.config[DPI_KEY] |
| 564 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 565 | names = self.formats[KEY_GENERIC_FILES] |
| 566 | styles = self.formats[KEY_STYLES] |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 567 | fonts = self.formats[KEY_FONTS] |
| 568 | default_font = fonts[KEY_DEFAULT] |
| 569 | |
| 570 | files = [] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 571 | heights = {} |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 572 | max_widths = {} |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 573 | for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')): |
| 574 | name, _ = os.path.splitext(os.path.basename(txt_file)) |
| 575 | category = names[name] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 576 | style = get_config_with_defaults(styles, category) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 577 | convert_text_to_image(None, txt_file, default_font, self.stage_dir, |
| 578 | height=style[KEY_HEIGHT], |
| 579 | max_width=style[KEY_MAX_WIDTH], |
| 580 | dpi=dpi, |
| 581 | bgcolor=style[KEY_BGCOLOR], |
| 582 | fgcolor=style[KEY_FGCOLOR]) |
| 583 | files.append(os.path.join(self.stage_dir, name + '.png')) |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 584 | heights[name] = style[KEY_HEIGHT] |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 585 | max_widths[name] = style[KEY_MAX_WIDTH] |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 586 | self.convert(files, self.output_dir, heights, max_widths, |
| 587 | self.text_max_colors) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 588 | |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 589 | def _check_text_width(self, output_dir, heights, max_widths): |
| 590 | """Check if the width of text image will exceed canvas boundary.""" |
| 591 | for filename in glob.glob(os.path.join(output_dir, |
| 592 | '*' + self.DEFAULT_OUTPUT_EXT)): |
| 593 | name, _ = os.path.splitext(os.path.basename(filename)) |
| 594 | max_width = max_widths[name] |
| 595 | if not max_width: |
| 596 | continue |
| 597 | max_width_px = self._to_px(max_width) |
| 598 | with open(filename, 'rb') as f: |
| 599 | f.seek(BMP_HEADER_OFFSET_NUM_LINES) |
| 600 | num_lines = f.read(1)[0] |
| 601 | height_px = self._to_px(heights[name] * num_lines) |
| 602 | with Image.open(filename) as image: |
| 603 | width_px = height_px * image.size[0] // image.size[1] |
| 604 | if width_px > max_width_px: |
| 605 | raise BuildImageError('%s: Image width %dpx greater than max width ' |
| 606 | '%dpx' % (filename, width_px, max_width_px)) |
| 607 | |
Yu-Ping Wu | 703dcfd | 2021-01-08 10:52:10 +0800 | [diff] [blame] | 608 | def _copy_missing_bitmaps(self): |
| 609 | """Copy missing (not yet translated) strings from locale 'en'.""" |
| 610 | en_files = glob.glob(os.path.join(self.output_ro_dir, 'en', |
| 611 | '*' + self.DEFAULT_OUTPUT_EXT)) |
| 612 | for locale_info in self.locales: |
| 613 | locale = locale_info.code |
| 614 | if locale == 'en': |
| 615 | continue |
| 616 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 617 | for en_file in en_files: |
| 618 | filename = os.path.basename(en_file) |
| 619 | locale_file = os.path.join(ro_locale_dir, filename) |
| 620 | if not os.path.isfile(locale_file): |
| 621 | print("WARNING: Locale '%s': copying '%s'" % (locale, filename)) |
| 622 | shutil.copyfile(en_file, locale_file) |
| 623 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 624 | def generate_localized_pngs(self, names, json_dir): |
| 625 | """Generates PNG files for localized strings.""" |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 626 | styles = self.formats[KEY_STYLES] |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 627 | fonts = self.formats[KEY_FONTS] |
| 628 | default_font = fonts[KEY_DEFAULT] |
| 629 | dpi = self.config[DPI_KEY] |
| 630 | |
| 631 | # Ignore SIGINT in child processes |
| 632 | sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 633 | pool = multiprocessing.Pool(multiprocessing.cpu_count()) |
| 634 | signal.signal(signal.SIGINT, sigint_handler) |
| 635 | |
| 636 | results = [] |
| 637 | for locale_info in self.locales: |
| 638 | locale = locale_info.code |
| 639 | print(locale, end=' ', flush=True) |
| 640 | inputs = parse_locale_json_file(locale, json_dir) |
| 641 | |
| 642 | # Walk locale directory to add pre-generated texts such as language names. |
| 643 | for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')): |
| 644 | name, _ = os.path.splitext(os.path.basename(txt_file)) |
| 645 | with open(txt_file, 'r', encoding='utf-8-sig') as f: |
| 646 | inputs[name] = f.read().strip() |
| 647 | |
| 648 | output_dir = os.path.join(self.stage_locale_dir, locale) |
| 649 | os.makedirs(output_dir, exist_ok=True) |
| 650 | |
| 651 | for name, category in names.items(): |
| 652 | # Ignore missing translation |
| 653 | if locale != 'en' and name not in inputs: |
| 654 | continue |
| 655 | |
| 656 | # Write to text file |
| 657 | text_file = os.path.join(output_dir, name + '.txt') |
| 658 | with open(text_file, 'w', encoding='utf-8-sig') as f: |
| 659 | f.write(inputs[name] + '\n') |
| 660 | |
| 661 | # Convert to PNG file |
| 662 | style = get_config_with_defaults(styles, category) |
| 663 | args = ( |
| 664 | locale, |
| 665 | os.path.join(output_dir, '%s.txt' % name), |
| 666 | fonts.get(locale, default_font), |
| 667 | output_dir, |
| 668 | ) |
| 669 | kwargs = { |
| 670 | 'height': style[KEY_HEIGHT], |
| 671 | 'max_width': style[KEY_MAX_WIDTH], |
| 672 | 'dpi': dpi, |
| 673 | 'bgcolor': style[KEY_BGCOLOR], |
| 674 | 'fgcolor': style[KEY_FGCOLOR], |
| 675 | } |
| 676 | results.append(pool.apply_async(convert_text_to_image, args, kwargs)) |
| 677 | |
| 678 | print() |
| 679 | pool.close() |
| 680 | |
| 681 | try: |
| 682 | for r in results: |
| 683 | r.get() |
| 684 | except KeyboardInterrupt: |
| 685 | pool.terminate() |
| 686 | pool.join() |
| 687 | exit('Aborted by user') |
| 688 | else: |
| 689 | pool.join() |
| 690 | |
| 691 | def convert_localized_pngs(self, names): |
| 692 | """Converts PNGs of localized strings to BMPs.""" |
| 693 | styles = self.formats[KEY_STYLES] |
| 694 | fonts = self.formats[KEY_FONTS] |
| 695 | default_font = fonts[KEY_DEFAULT] |
| 696 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 697 | heights = {} |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 698 | max_widths = {} |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 699 | for name, category in names.items(): |
| 700 | style = get_config_with_defaults(styles, category) |
| 701 | heights[name] = style[KEY_HEIGHT] |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 702 | max_widths[name] = style[KEY_MAX_WIDTH] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 703 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 704 | # Using stderr to report progress synchronously |
| 705 | print(' processing:', end='', file=sys.stderr, flush=True) |
| 706 | for locale_info in self.locales: |
| 707 | locale = locale_info.code |
| 708 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 709 | stage_locale_dir = os.path.join(self.stage_locale_dir, locale) |
Yu-Ping Wu | abb9afb | 2020-10-27 17:15:22 +0800 | [diff] [blame] | 710 | print(' ' + locale, end='', file=sys.stderr, flush=True) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 711 | os.makedirs(ro_locale_dir) |
| 712 | self.convert( |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 713 | glob.glob(os.path.join(stage_locale_dir, PNG_FILES)), |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 714 | ro_locale_dir, heights, max_widths, self.text_max_colors, |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 715 | one_line_dir=os.path.join(stage_locale_dir, ONE_LINE_DIR)) |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 716 | self._check_text_width(ro_locale_dir, heights, max_widths) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 717 | print(file=sys.stderr) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 718 | |
| 719 | def build_localized_strings(self): |
| 720 | """Builds images of localized strings.""" |
| 721 | # Sources are one .grd file with identifiers chosen by engineers and |
| 722 | # corresponding English texts, as well as a set of .xlt files (one for each |
| 723 | # language other than US English) with a mapping from hash to translation. |
| 724 | # Because the keys in the xlt files are a hash of the English source text, |
| 725 | # rather than our identifiers, such as "btn_cancel", we use the "grit" |
| 726 | # command line tool to process the .grd and .xlt files, producing a set of |
| 727 | # .json files mapping our identifier to the translated string, one for every |
| 728 | # language including US English. |
| 729 | |
| 730 | # Create a temporary directory to place the translation output from grit in. |
| 731 | json_dir = tempfile.mkdtemp() |
| 732 | |
| 733 | # This invokes the grit build command to generate JSON files from the XTB |
| 734 | # files containing translations. The results are placed in `json_dir` as |
| 735 | # specified in firmware_strings.grd, i.e. one JSON file per locale. |
| 736 | subprocess.check_call([ |
| 737 | 'grit', |
| 738 | '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE), |
| 739 | 'build', |
| 740 | '-o', os.path.join(json_dir), |
| 741 | ]) |
| 742 | |
| 743 | # Make a copy to avoid modifying `self.formats` |
| 744 | names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES]) |
| 745 | if DIAGNOSTIC_UI: |
| 746 | names.update(self.formats[KEY_DIAGNOSTIC_FILES]) |
| 747 | |
| 748 | # TODO(b/163109632): Merge generate_localized_pngs() and |
| 749 | # convert_localized_pngs(), and parallelize them altogether. |
| 750 | self.generate_localized_pngs(names, json_dir) |
| 751 | shutil.rmtree(json_dir) |
| 752 | |
| 753 | self.convert_localized_pngs(names) |
Yu-Ping Wu | 703dcfd | 2021-01-08 10:52:10 +0800 | [diff] [blame] | 754 | self._copy_missing_bitmaps() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 755 | |
| 756 | def move_language_images(self): |
| 757 | """Renames language bitmaps and move to self.output_dir. |
| 758 | |
| 759 | The directory self.output_dir contains locale-independent images, and is |
| 760 | used for creating vbgfx.bin by archive_images.py. |
| 761 | """ |
| 762 | for locale_info in self.locales: |
| 763 | locale = locale_info.code |
| 764 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 765 | old_file = os.path.join(ro_locale_dir, 'language.bmp') |
| 766 | new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale) |
| 767 | if os.path.exists(new_file): |
| 768 | raise BuildImageError('File already exists: %s' % new_file) |
| 769 | shutil.move(old_file, new_file) |
| 770 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 771 | def build_glyphs(self): |
| 772 | """Builds glyphs of ascii characters.""" |
| 773 | os.makedirs(self.stage_font_dir, exist_ok=True) |
| 774 | files = [] |
| 775 | # TODO(b/163109632): Parallelize the conversion of glyphs |
| 776 | for c in range(ord(' '), ord('~') + 1): |
| 777 | name = f'idx{c:03d}_{c:02x}' |
| 778 | txt_file = os.path.join(self.stage_font_dir, name + '.txt') |
| 779 | with open(txt_file, 'w', encoding='ascii') as f: |
| 780 | f.write(chr(c)) |
| 781 | f.write('\n') |
| 782 | convert_text_to_image(None, txt_file, GLYPH_FONT, self.stage_font_dir, |
| 783 | height=DEFAULT_GLYPH_HEIGHT, use_svg=True) |
| 784 | files.append(os.path.join(self.stage_font_dir, name + '.svg')) |
Yu-Ping Wu | 3d07a06 | 2021-01-26 18:10:32 +0800 | [diff] [blame] | 785 | heights = defaultdict(lambda: DEFAULT_GLYPH_HEIGHT) |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 786 | max_widths = defaultdict(lambda: None) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 787 | font_output_dir = os.path.join(self.output_dir, 'font') |
| 788 | os.makedirs(font_output_dir) |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 789 | self.convert(files, font_output_dir, heights, max_widths, |
| 790 | self.text_max_colors) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 791 | |
| 792 | def copy_images_to_rw(self): |
| 793 | """Copies localized images specified in boards.yaml for RW override.""" |
| 794 | if not self.config[RW_OVERRIDE_KEY]: |
| 795 | print(' No localized images are specified for RW, skipping') |
| 796 | return |
| 797 | |
| 798 | for locale_info in self.locales: |
| 799 | locale = locale_info.code |
| 800 | rw_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 801 | ro_locale_dir = os.path.join(self.output_rw_dir, locale) |
| 802 | os.makedirs(rw_locale_dir) |
| 803 | |
| 804 | for name in self.config[RW_OVERRIDE_KEY]: |
| 805 | ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT) |
| 806 | rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT) |
| 807 | shutil.copyfile(ro_src, rw_dst) |
| 808 | |
| 809 | def create_locale_list(self): |
| 810 | """Creates locale list as a CSV file. |
| 811 | |
| 812 | Each line in the file is of format "code,rtl", where |
| 813 | - "code": language code of the locale |
| 814 | - "rtl": "1" for right-to-left language, "0" otherwise |
| 815 | """ |
| 816 | with open(os.path.join(self.output_dir, 'locales'), 'w') as f: |
| 817 | for locale_info in self.locales: |
| 818 | f.write('{},{}\n'.format(locale_info.code, |
| 819 | int(locale_info.rtl))) |
| 820 | |
| 821 | def build(self): |
| 822 | """Builds all images required by a board.""" |
| 823 | # Clean up output directory |
| 824 | if os.path.exists(self.output_dir): |
| 825 | shutil.rmtree(self.output_dir) |
| 826 | os.makedirs(self.output_dir) |
| 827 | |
| 828 | if not os.path.exists(self.stage_dir): |
| 829 | raise BuildImageError('Missing stage folder. Run make in strings dir.') |
| 830 | |
| 831 | # Clean up temp directory |
| 832 | if os.path.exists(self.temp_dir): |
| 833 | shutil.rmtree(self.temp_dir) |
| 834 | os.makedirs(self.temp_dir) |
| 835 | |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 836 | print('Converting sprite images...') |
| 837 | self.convert_sprite_images() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 838 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 839 | print('Building generic strings...') |
| 840 | self.build_generic_strings() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 841 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 842 | print('Building localized strings...') |
| 843 | self.build_localized_strings() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 844 | |
| 845 | print('Moving language images to locale-independent directory...') |
| 846 | self.move_language_images() |
| 847 | |
| 848 | print('Creating locale list file...') |
| 849 | self.create_locale_list() |
| 850 | |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 851 | print('Building glyphs...') |
| 852 | self.build_glyphs() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 853 | |
| 854 | print('Copying specified images to RW packing directory...') |
| 855 | self.copy_images_to_rw() |
| 856 | |
| 857 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 858 | def main(): |
| 859 | """Builds bitmaps for firmware screens.""" |
| 860 | parser = argparse.ArgumentParser() |
| 861 | parser.add_argument('board', help='Target board') |
| 862 | args = parser.parse_args() |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 863 | board = args.board |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 864 | |
| 865 | with open(FORMAT_FILE, encoding='utf-8') as f: |
| 866 | formats = yaml.load(f) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 867 | board_config = load_boards_config(BOARDS_CONFIG_FILE)[board] |
| 868 | |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 869 | print('Building for ' + board) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame^] | 870 | check_fonts(formats[KEY_FONTS]) |
| 871 | print('Output dir: ' + OUTPUT_DIR) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 872 | converter = Converter(board, formats, board_config, OUTPUT_DIR) |
| 873 | converter.build() |
Yu-Ping Wu | 7f6639a | 2020-09-28 15:31:35 +0800 | [diff] [blame] | 874 | |
| 875 | |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 876 | if __name__ == '__main__': |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 877 | main() |