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 |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 8 | from collections import defaultdict, namedtuple, Counter |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 9 | import copy |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 10 | import glob |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 11 | import json |
Yu-Ping Wu | fc1f4b1 | 2021-03-30 14:10:15 +0800 | [diff] [blame] | 12 | from concurrent.futures import ProcessPoolExecutor |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 13 | import os |
| 14 | import re |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 15 | import shutil |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 16 | import subprocess |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 17 | import sys |
Hung-Te Lin | 04addcc | 2015-03-23 18:43:30 +0800 | [diff] [blame] | 18 | |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 19 | import yaml |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 20 | from PIL import Image |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 21 | |
| 22 | SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__)) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 23 | |
| 24 | STRINGS_GRD_FILE = 'firmware_strings.grd' |
Yu-Ping Wu | 986dd8a | 2021-04-28 16:54:33 +0800 | [diff] [blame] | 25 | STRINGS_JSON_FILE_TMPL = '%s.json' |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 26 | FORMAT_FILE = 'format.yaml' |
| 27 | BOARDS_CONFIG_FILE = 'boards.yaml' |
| 28 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 29 | OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build')) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 30 | |
| 31 | ONE_LINE_DIR = 'one_line' |
| 32 | SVG_FILES = '*.svg' |
| 33 | PNG_FILES = '*.png' |
| 34 | |
| 35 | # String format YAML key names. |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 36 | KEY_DEFAULT = '_DEFAULT_' |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 37 | KEY_GLYPH = '_GLYPH_' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 38 | KEY_LOCALES = 'locales' |
Yu-Ping Wu | 338f083 | 2020-10-23 16:14:40 +0800 | [diff] [blame] | 39 | KEY_GENERIC_FILES = 'generic_files' |
| 40 | KEY_LOCALIZED_FILES = 'localized_files' |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 41 | KEY_SPRITE_FILES = 'sprite_files' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 42 | KEY_STYLES = 'styles' |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 43 | KEY_BGCOLOR = 'bgcolor' |
| 44 | KEY_FGCOLOR = 'fgcolor' |
| 45 | KEY_HEIGHT = 'height' |
Yu-Ping Wu | ed95df3 | 2020-11-04 17:08:15 +0800 | [diff] [blame] | 46 | KEY_MAX_WIDTH = 'max_width' |
Yu-Ping Wu | 177f12c | 2020-11-04 15:55:37 +0800 | [diff] [blame] | 47 | KEY_FONTS = 'fonts' |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 48 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 49 | # Board config YAML key names. |
Yu-Ping Wu | 60b4537 | 2021-03-31 16:56:08 +0800 | [diff] [blame] | 50 | KEY_SCREEN = 'screen' |
Yu-Ping Wu | 60b4537 | 2021-03-31 16:56:08 +0800 | [diff] [blame] | 51 | KEY_SDCARD = 'sdcard' |
| 52 | KEY_DPI = 'dpi' |
| 53 | KEY_RTL = 'rtl' |
| 54 | KEY_RW_OVERRIDE = 'rw_override' |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 55 | |
| 56 | BMP_HEADER_OFFSET_NUM_LINES = 6 |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 57 | |
Jes Klinke | 1687a99 | 2020-06-16 13:47:17 -0700 | [diff] [blame] | 58 | # Regular expressions used to eliminate spurious spaces and newlines in |
| 59 | # translation strings. |
| 60 | NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])') |
| 61 | NEWLINE_REPLACEMENT = r'\1 \2' |
| 62 | CRLF_PATTERN = re.compile(r'\r\n') |
| 63 | MULTIBLANK_PATTERN = re.compile(r' *') |
| 64 | |
Yu-Ping Wu | abb9afb | 2020-10-27 17:15:22 +0800 | [diff] [blame] | 65 | LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl']) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 66 | |
Yu-Ping Wu | 6b282c5 | 2020-03-19 12:54:15 +0800 | [diff] [blame] | 67 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 68 | class BuildImageError(Exception): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 69 | """Exception for all errors generated during build image process.""" |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 70 | |
| 71 | |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 72 | def get_config_with_defaults(configs, key): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 73 | """Gets config of `key` from `configs`. |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 74 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 75 | If `key` is not present in `configs`, the default config will be returned. |
| 76 | Similarly, if some config values are missing for `key`, the default ones |
| 77 | will be used. |
| 78 | """ |
| 79 | config = configs[KEY_DEFAULT].copy() |
| 80 | config.update(configs.get(key, {})) |
| 81 | return config |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 82 | |
| 83 | |
Yu-Ping Wu | c00e171 | 2021-04-13 16:44:12 +0800 | [diff] [blame] | 84 | def load_board_config(filename, board): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 85 | """Loads the configuration of `board` from `filename`. |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 86 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 87 | Args: |
| 88 | filename: File name of a YAML config file. |
| 89 | board: Board name. |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 90 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 91 | Returns: |
| 92 | A dictionary mapping each board name to its config. |
| 93 | """ |
| 94 | with open(filename, 'rb') as file: |
| 95 | raw = yaml.load(file) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 96 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 97 | config = copy.deepcopy(raw[KEY_DEFAULT]) |
| 98 | for boards, params in raw.items(): |
| 99 | if boards == KEY_DEFAULT: |
| 100 | continue |
| 101 | if board not in boards.split(','): |
| 102 | continue |
| 103 | if params: |
| 104 | config.update(params) |
| 105 | break |
| 106 | else: |
| 107 | raise BuildImageError('Board config not found for ' + board) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 108 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 109 | return config |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 110 | |
| 111 | |
| 112 | def check_fonts(fonts): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 113 | """Checks if all fonts are available.""" |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 114 | for locale, font in fonts.items(): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 115 | if subprocess.run(['fc-list', '-q', font], |
| 116 | check=False).returncode != 0: |
| 117 | raise BuildImageError('Font %r not found for locale %r' % |
| 118 | (font, locale)) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 119 | |
| 120 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 121 | def run_pango_view(input_file, |
| 122 | output_file, |
| 123 | locale, |
| 124 | font, |
| 125 | height, |
| 126 | max_width, |
| 127 | dpi, |
| 128 | bgcolor, |
| 129 | fgcolor, |
| 130 | hinting='full'): |
| 131 | """Runs pango-view.""" |
| 132 | command = ['pango-view', '-q'] |
| 133 | if locale: |
| 134 | command += ['--language', locale] |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 135 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 136 | # Font size should be proportional to the height. Here we use 2 as the |
| 137 | # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml |
| 138 | # will be roughly equivalent to setting the screen resolution to 1366x768. |
| 139 | font_size = height / 2 |
| 140 | font_spec = '%s %r' % (font, font_size) |
| 141 | command += ['--font', font_spec] |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 142 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 143 | if max_width: |
| 144 | # When converting text to PNG by pango-view, the ratio of image height |
| 145 | # to the font size is usually no more than 1.1875 (with Roboto). |
| 146 | # Therefore, set the `max_width_pt` as follows to prevent UI drawing |
| 147 | # from exceeding the canvas boundary in depthcharge runtime. The divisor |
| 148 | # 2 is the same in the calculation of `font_size` above. |
| 149 | max_width_pt = int(max_width / 2 * 1.1875) |
| 150 | command.append('--width=%d' % max_width_pt) |
| 151 | if dpi: |
| 152 | command.append('--dpi=%d' % dpi) |
| 153 | command.append('--margin=0') |
| 154 | command += ['--background', bgcolor] |
| 155 | command += ['--foreground', fgcolor] |
| 156 | command += ['--hinting', hinting] |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 157 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 158 | command += ['--output', output_file] |
| 159 | command.append(input_file) |
Yu-Ping Wu | 11027f0 | 2020-10-14 17:35:42 +0800 | [diff] [blame] | 160 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 161 | subprocess.check_call(command, stdout=subprocess.PIPE) |
Yu-Ping Wu | 9704693 | 2021-01-25 17:38:56 +0800 | [diff] [blame] | 162 | |
| 163 | |
Yu-Ping Wu | 703dcfd | 2021-01-08 10:52:10 +0800 | [diff] [blame] | 164 | def parse_locale_json_file(locale, json_dir): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 165 | """Parses given firmware string json file. |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 166 | |
| 167 | Args: |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 168 | locale: The name of the locale, e.g. "da" or "pt-BR". |
| 169 | json_dir: Directory containing json output from grit. |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 170 | |
| 171 | Returns: |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 172 | A dictionary for mapping of "name to content" for files to be generated. |
| 173 | """ |
| 174 | result = {} |
Yu-Ping Wu | 986dd8a | 2021-04-28 16:54:33 +0800 | [diff] [blame] | 175 | filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL % locale) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 176 | with open(filename, encoding='utf-8-sig') as input_file: |
| 177 | for tag, msgdict in json.load(input_file).items(): |
| 178 | msgtext = msgdict['message'] |
| 179 | msgtext = re.sub(CRLF_PATTERN, '\n', msgtext) |
| 180 | msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext) |
| 181 | msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext) |
| 182 | # Strip any trailing whitespace. A trailing newline appears to make |
| 183 | # Pango report a larger layout size than what's actually visible. |
| 184 | msgtext = msgtext.strip() |
| 185 | result[tag] = msgtext |
| 186 | return result |
| 187 | |
| 188 | |
| 189 | class Converter: |
| 190 | """Converter for converting sprites, texts, and glyphs to bitmaps. |
| 191 | |
| 192 | Attributes: |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 193 | SCALE_BASE (int): The base for bitmap scales, same as UI_SCALE in |
| 194 | depthcharge. For example, if SCALE_BASE is 1000, then height = 200 |
| 195 | means 20% of the screen height. Also see the 'styles' section in |
| 196 | format.yaml. |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 197 | SPRITE_MAX_COLORS (int): Maximum colors to use for converting image |
| 198 | sprites to bitmaps. |
| 199 | GLYPH_MAX_COLORS (int): Maximum colors to use for glyph bitmaps. |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 200 | """ |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 201 | SCALE_BASE = 1000 |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 202 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 203 | # Max colors |
| 204 | SPRITE_MAX_COLORS = 128 |
| 205 | GLYPH_MAX_COLORS = 7 |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 206 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 207 | def __init__(self, board, formats, board_config, output): |
| 208 | """Inits converter. |
| 209 | |
| 210 | Args: |
| 211 | board: Board name. |
| 212 | formats: A dictionary of string formats. |
| 213 | board_config: A dictionary of board configurations. |
| 214 | output: Output directory. |
| 215 | """ |
| 216 | self.board = board |
| 217 | self.formats = formats |
| 218 | self.config = board_config |
| 219 | self.set_dirs(output) |
| 220 | self.set_screen() |
| 221 | self.set_rename_map() |
| 222 | self.set_locales() |
| 223 | self.text_max_colors = self.get_text_colors(self.config[KEY_DPI]) |
| 224 | |
| 225 | def set_dirs(self, output): |
| 226 | """Sets board output directory and stage directory. |
| 227 | |
| 228 | Args: |
| 229 | output: Output directory. |
| 230 | """ |
| 231 | self.strings_dir = os.path.join(SCRIPT_BASE, 'strings') |
| 232 | self.sprite_dir = os.path.join(SCRIPT_BASE, 'sprite') |
| 233 | self.locale_dir = os.path.join(self.strings_dir, 'locale') |
| 234 | self.output_dir = os.path.join(output, self.board) |
| 235 | self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro') |
| 236 | self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw') |
| 237 | self.stage_dir = os.path.join(output, '.stage') |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 238 | self.stage_grit_dir = os.path.join(self.stage_dir, 'grit') |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 239 | self.stage_locale_dir = os.path.join(self.stage_dir, 'locale') |
| 240 | self.stage_glyph_dir = os.path.join(self.stage_dir, 'glyph') |
Yu-Ping Wu | f64557d | 2021-04-20 13:56:42 +0800 | [diff] [blame] | 241 | self.stage_sprite_dir = os.path.join(self.stage_dir, 'sprite') |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 242 | |
| 243 | def set_screen(self): |
| 244 | """Sets screen width and height.""" |
| 245 | self.screen_width, self.screen_height = self.config[KEY_SCREEN] |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 246 | # Set up square drawing area |
| 247 | self.canvas_px = min(self.screen_width, self.screen_height) |
| 248 | |
| 249 | def set_rename_map(self): |
| 250 | """Initializes a dict `self.rename_map` for image renaming. |
| 251 | |
| 252 | For each items in the dict, image `key` will be renamed to `value`. |
| 253 | """ |
| 254 | is_detachable = os.getenv('DETACHABLE') == '1' |
| 255 | physical_presence = os.getenv('PHYSICAL_PRESENCE') |
| 256 | rename_map = {} |
| 257 | |
| 258 | # Navigation instructions |
| 259 | if is_detachable: |
| 260 | rename_map.update({ |
| 261 | 'nav-button_power': 'nav-key_enter', |
| 262 | 'nav-button_volume_up': 'nav-key_up', |
| 263 | 'nav-button_volume_down': 'nav-key_down', |
| 264 | 'navigate0_tablet': 'navigate0', |
| 265 | 'navigate1_tablet': 'navigate1', |
| 266 | }) |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 267 | else: |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 268 | rename_map.update({ |
| 269 | 'nav-button_power': None, |
| 270 | 'nav-button_volume_up': None, |
| 271 | 'nav-button_volume_down': None, |
| 272 | 'navigate0_tablet': None, |
| 273 | 'navigate1_tablet': None, |
| 274 | }) |
| 275 | |
| 276 | # Physical presence confirmation |
| 277 | if physical_presence == 'recovery': |
| 278 | rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1' |
| 279 | rename_map['rec_to_dev_desc1_power'] = None |
| 280 | elif physical_presence == 'power': |
| 281 | rename_map['rec_to_dev_desc1_phyrec'] = None |
| 282 | rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1' |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 283 | else: |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 284 | rename_map['rec_to_dev_desc1_phyrec'] = None |
| 285 | rename_map['rec_to_dev_desc1_power'] = None |
| 286 | if physical_presence != 'keyboard': |
| 287 | raise BuildImageError( |
| 288 | 'Invalid physical presence setting %s for board ' |
| 289 | '%s' % (physical_presence, self.board)) |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 290 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 291 | # Broken screen |
| 292 | if physical_presence == 'recovery': |
| 293 | rename_map['broken_desc_phyrec'] = 'broken_desc' |
| 294 | rename_map['broken_desc_detach'] = None |
| 295 | elif is_detachable: |
| 296 | rename_map['broken_desc_phyrec'] = None |
| 297 | rename_map['broken_desc_detach'] = 'broken_desc' |
| 298 | else: |
| 299 | rename_map['broken_desc_phyrec'] = None |
| 300 | rename_map['broken_desc_detach'] = None |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 301 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 302 | # SD card |
| 303 | if not self.config[KEY_SDCARD]: |
| 304 | rename_map.update({ |
| 305 | 'rec_sel_desc1_no_sd': |
| 306 | 'rec_sel_desc1', |
| 307 | 'rec_sel_desc1_no_phone_no_sd': |
| 308 | 'rec_sel_desc1_no_phone', |
| 309 | 'rec_disk_step1_desc0_no_sd': |
| 310 | 'rec_disk_step1_desc0', |
| 311 | }) |
| 312 | else: |
| 313 | rename_map.update({ |
| 314 | 'rec_sel_desc1_no_sd': None, |
| 315 | 'rec_sel_desc1_no_phone_no_sd': None, |
| 316 | 'rec_disk_step1_desc0_no_sd': None, |
| 317 | }) |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 318 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 319 | # Check for duplicate new names |
| 320 | new_names = list(new_name for new_name in rename_map.values() |
| 321 | if new_name) |
| 322 | if len(set(new_names)) != len(new_names): |
| 323 | raise BuildImageError('Duplicate values found in rename_map') |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 324 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 325 | # Map new_name to None to skip image generation for it |
| 326 | for new_name in new_names: |
| 327 | if new_name not in rename_map: |
| 328 | rename_map[new_name] = None |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 329 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 330 | # Print mapping |
| 331 | print('Rename map:') |
| 332 | for name, new_name in sorted(rename_map.items()): |
| 333 | print(' %s => %s' % (name, new_name)) |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 334 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 335 | self.rename_map = rename_map |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 336 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 337 | def set_locales(self): |
| 338 | """Sets a list of locales for which localized images are converted.""" |
| 339 | # LOCALES environment variable can override boards.yaml |
| 340 | env_locales = os.getenv('LOCALES') |
| 341 | rtl_locales = set(self.config[KEY_RTL]) |
| 342 | if env_locales: |
| 343 | locales = env_locales.split() |
| 344 | else: |
| 345 | locales = self.config[KEY_LOCALES] |
| 346 | # Check rtl_locales are contained in locales. |
| 347 | unknown_rtl_locales = rtl_locales - set(locales) |
| 348 | if unknown_rtl_locales: |
| 349 | raise BuildImageError('Unknown locales %s in %s' % |
| 350 | (list(unknown_rtl_locales), KEY_RTL)) |
| 351 | self.locales = [ |
| 352 | LocaleInfo(code, code in rtl_locales) for code in locales |
| 353 | ] |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 354 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 355 | @classmethod |
| 356 | def get_text_colors(cls, dpi): |
| 357 | """Derives maximum text colors from `dpi`.""" |
| 358 | if dpi < 64: |
| 359 | return 2 |
| 360 | if dpi < 72: |
| 361 | return 3 |
| 362 | if dpi < 80: |
| 363 | return 4 |
| 364 | if dpi < 96: |
| 365 | return 5 |
| 366 | if dpi < 112: |
| 367 | return 6 |
| 368 | return 7 |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 369 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 370 | def _to_px(self, length, num_lines=1): |
| 371 | """Converts the relative coordinate to absolute one in pixels.""" |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 372 | return int(self.canvas_px * length / self.SCALE_BASE) * num_lines |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 373 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 374 | @classmethod |
| 375 | def _get_png_height(cls, png_file): |
| 376 | # With small DPI, pango-view may generate an empty file |
| 377 | if os.path.getsize(png_file) == 0: |
| 378 | return 0 |
| 379 | with Image.open(png_file) as image: |
| 380 | return image.size[1] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 381 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 382 | def get_num_lines(self, file, one_line_dir): |
| 383 | """Gets the number of lines of text in `file`.""" |
| 384 | name, _ = os.path.splitext(os.path.basename(file)) |
| 385 | png_name = name + '.png' |
| 386 | multi_line_file = os.path.join(os.path.dirname(file), png_name) |
| 387 | one_line_file = os.path.join(one_line_dir, png_name) |
| 388 | # The number of lines is determined by comparing the height of |
| 389 | # `multi_line_file` with `one_line_file`, where the latter is generated |
| 390 | # without the '--width' option passed to pango-view. |
| 391 | height = self._get_png_height(multi_line_file) |
| 392 | line_height = self._get_png_height(one_line_file) |
| 393 | return int(round(height / line_height)) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 394 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 395 | def convert_svg_to_png(self, |
| 396 | svg_file, |
| 397 | png_file, |
| 398 | height, |
| 399 | bgcolor, |
| 400 | num_lines=1): |
| 401 | """Converts SVG to PNG file.""" |
| 402 | # If the width/height of the SVG file is specified in points, the |
| 403 | # rsvg-convert command with default 90DPI will potentially cause the |
| 404 | # pixels at the right/bottom border of the output image to be |
| 405 | # transparent (or filled with the specified background color). This |
| 406 | # seems like an rsvg-convert issue regarding image scaling. Therefore, |
| 407 | # use 72DPI here to avoid the scaling. |
| 408 | command = [ |
| 409 | 'rsvg-convert', '--background-color', |
| 410 | "'%s'" % bgcolor, '--dpi-x', '72', '--dpi-y', '72', '-o', png_file |
| 411 | ] |
| 412 | height_px = self._to_px(height, num_lines) |
| 413 | if height_px <= 0: |
| 414 | raise BuildImageError('Height of %r <= 0 (%dpx)' % |
| 415 | (os.path.basename(svg_file), height_px)) |
| 416 | command.extend(['--height', '%d' % height_px]) |
| 417 | command.append(svg_file) |
| 418 | subprocess.check_call(' '.join(command), shell=True) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 419 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 420 | def convert_png_to_bmp(self, png_file, bmp_file, max_colors, num_lines=1): |
| 421 | """Converts PNG to BMP file.""" |
| 422 | image = Image.open(png_file) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 423 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 424 | # Process alpha channel and transparency. |
| 425 | if image.mode == 'RGBA': |
| 426 | raise BuildImageError('PNG with RGBA mode is not supported') |
| 427 | if image.mode == 'P' and 'transparency' in image.info: |
| 428 | raise BuildImageError('PNG with RGBA palette is not supported') |
| 429 | if image.mode != 'RGB': |
Yu-Ping Wu | f90b6a4 | 2021-04-23 15:24:33 +0800 | [diff] [blame] | 430 | image = image.convert('RGB') |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 431 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 432 | # Export and downsample color space. |
Yu-Ping Wu | f90b6a4 | 2021-04-23 15:24:33 +0800 | [diff] [blame] | 433 | image.convert('P', |
| 434 | dither=None, |
| 435 | colors=max_colors, |
| 436 | palette=Image.ADAPTIVE).save(bmp_file) |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 437 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 438 | with open(bmp_file, 'rb+') as f: |
| 439 | f.seek(BMP_HEADER_OFFSET_NUM_LINES) |
| 440 | f.write(bytearray([num_lines])) |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 441 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 442 | @classmethod |
| 443 | def _bisect_dpi(cls, max_dpi, initial_dpi, max_height_px, get_height): |
| 444 | """Bisects to find the DPI that produces image height `max_height_px`. |
Yu-Ping Wu | 95493a9 | 2021-03-10 13:10:51 +0800 | [diff] [blame] | 445 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 446 | Args: |
| 447 | max_dpi: Maximum DPI for binary search. |
| 448 | initial_dpi: Initial DPI to try with in binary search. |
| 449 | If specified, the value must be no larger than `max_dpi`. |
| 450 | max_height_px: Maximum (target) height to search for. |
| 451 | get_height: A function converting DPI to height. The function is |
| 452 | called once before returning. |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 453 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 454 | Returns: |
| 455 | The best integer DPI within [1, `max_dpi`]. |
| 456 | """ |
| 457 | min_dpi = 1 |
| 458 | first_iter = True |
Yu-Ping Wu | 49606eb | 2021-03-03 22:43:19 +0800 | [diff] [blame] | 459 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 460 | min_height_px = get_height(min_dpi) |
| 461 | if min_height_px > max_height_px: |
| 462 | # For some font such as "Noto Sans CJK SC", the generated height |
| 463 | # cannot go below a certain value. In this case, find max DPI with |
| 464 | # height_px <= min_height_px. |
| 465 | while min_dpi < max_dpi: |
| 466 | if first_iter and initial_dpi: |
| 467 | mid_dpi = initial_dpi |
| 468 | else: |
| 469 | mid_dpi = (min_dpi + max_dpi + 1) // 2 |
| 470 | height_px = get_height(mid_dpi) |
| 471 | if height_px > min_height_px: |
| 472 | max_dpi = mid_dpi - 1 |
| 473 | else: |
| 474 | min_dpi = mid_dpi |
| 475 | first_iter = False |
| 476 | get_height(max_dpi) |
| 477 | return max_dpi |
Yu-Ping Wu | 2e788b0 | 2021-03-09 13:01:31 +0800 | [diff] [blame] | 478 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 479 | # Find min DPI with height_px == max_height_px |
| 480 | while min_dpi < max_dpi: |
| 481 | if first_iter and initial_dpi: |
| 482 | mid_dpi = initial_dpi |
| 483 | else: |
| 484 | mid_dpi = (min_dpi + max_dpi) // 2 |
| 485 | height_px = get_height(mid_dpi) |
| 486 | if height_px == max_height_px: |
| 487 | return mid_dpi |
| 488 | if height_px < max_height_px: |
| 489 | min_dpi = mid_dpi + 1 |
| 490 | else: |
| 491 | max_dpi = mid_dpi |
| 492 | first_iter = False |
| 493 | get_height(min_dpi) |
| 494 | return min_dpi |
Yu-Ping Wu | 08defcc | 2020-05-07 16:21:03 +0800 | [diff] [blame] | 495 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 496 | def convert_text_to_image(self, |
| 497 | locale, |
| 498 | input_file, |
| 499 | output_file, |
| 500 | font, |
| 501 | stage_dir, |
| 502 | max_colors, |
| 503 | height=None, |
| 504 | max_width=None, |
| 505 | dpi=None, |
| 506 | initial_dpi=None, |
| 507 | bgcolor='#000000', |
| 508 | fgcolor='#ffffff', |
| 509 | use_svg=False): |
| 510 | """Converts text file `input_file` into image file. |
Yu-Ping Wu | 703dcfd | 2021-01-08 10:52:10 +0800 | [diff] [blame] | 511 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 512 | Because pango-view does not support assigning output format options for |
| 513 | bitmap, we must create images in SVG/PNG format and then post-process |
| 514 | them (e.g. convert into BMP by ImageMagick). |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 515 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 516 | Args: |
| 517 | locale: Locale (language) to select implicit rendering options. None |
| 518 | for locale-independent strings. |
| 519 | input_file: Path of input text file. |
| 520 | output_file: Path of output image file. |
| 521 | font: Font name. |
| 522 | stage_dir: Directory to store intermediate file(s). |
| 523 | max_colors: Maximum colors to convert to bitmap. |
| 524 | height: Image height relative to the screen resolution. |
| 525 | max_width: Maximum image width relative to the screen resolution. |
| 526 | dpi: DPI value passed to pango-view. |
| 527 | initial_dpi: Initial DPI to try with in binary search. |
| 528 | bgcolor: Background color (#rrggbb). |
| 529 | fgcolor: Foreground color (#rrggbb). |
| 530 | use_svg: If set to True, generate SVG file. Otherwise, generate PNG |
| 531 | file. |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 532 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 533 | Returns: |
| 534 | Effective DPI, or `None` when not applicable. |
| 535 | """ |
| 536 | one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR) |
| 537 | os.makedirs(one_line_dir, exist_ok=True) |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 538 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 539 | name, _ = os.path.splitext(os.path.basename(input_file)) |
| 540 | svg_file = os.path.join(stage_dir, name + '.svg') |
| 541 | png_file = os.path.join(stage_dir, name + '.png') |
| 542 | png_file_one_line = os.path.join(one_line_dir, name + '.png') |
Yu-Ping Wu | f946dd4 | 2021-02-08 16:32:28 +0800 | [diff] [blame] | 543 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 544 | def get_one_line_png_height(dpi): |
| 545 | """Generates a one-line PNG with `dpi` and returns its height.""" |
| 546 | run_pango_view(input_file, png_file_one_line, locale, font, height, |
| 547 | 0, dpi, bgcolor, fgcolor) |
| 548 | return self._get_png_height(png_file_one_line) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 549 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 550 | if use_svg: |
| 551 | run_pango_view(input_file, |
| 552 | svg_file, |
| 553 | locale, |
| 554 | font, |
| 555 | height, |
| 556 | 0, |
| 557 | dpi, |
| 558 | bgcolor, |
| 559 | fgcolor, |
| 560 | hinting='none') |
| 561 | self.convert_svg_to_png(svg_file, png_file, height, bgcolor) |
| 562 | self.convert_png_to_bmp(png_file, output_file, max_colors) |
| 563 | return None |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 564 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 565 | if not dpi: |
| 566 | raise BuildImageError('DPI must be specified with use_svg=False') |
| 567 | eff_dpi = dpi |
| 568 | max_height_px = self._to_px(height) |
| 569 | height_px = get_one_line_png_height(dpi) |
| 570 | if height_px > max_height_px: |
| 571 | eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px, |
| 572 | get_one_line_png_height) |
| 573 | if max_width: |
| 574 | # NOTE: With the same DPI, the height of multi-line PNG is not |
| 575 | # necessarily a multiple of the height of one-line PNG. Therefore, |
| 576 | # even with the binary search, the height of the resulting |
| 577 | # multi-line PNG might be less than "one_line_height * num_lines". |
| 578 | # We cannot binary-search DPI for multi-line PNGs because |
| 579 | # "num_lines" is dependent on DPI. |
| 580 | run_pango_view(input_file, png_file, locale, font, height, |
| 581 | max_width, eff_dpi, bgcolor, fgcolor) |
| 582 | num_lines = self.get_num_lines(png_file, one_line_dir) |
| 583 | else: |
| 584 | png_file = png_file_one_line |
| 585 | num_lines = 1 |
| 586 | self.convert_png_to_bmp(png_file, |
| 587 | output_file, |
| 588 | max_colors, |
| 589 | num_lines=num_lines) |
| 590 | return eff_dpi |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 591 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 592 | def convert_sprite_images(self): |
| 593 | """Converts sprite images.""" |
| 594 | names = self.formats[KEY_SPRITE_FILES] |
| 595 | styles = self.formats[KEY_STYLES] |
| 596 | # Check redundant images |
| 597 | for filename in glob.glob(os.path.join(self.sprite_dir, SVG_FILES)): |
| 598 | name, _ = os.path.splitext(os.path.basename(filename)) |
| 599 | if name not in names: |
| 600 | raise BuildImageError('Sprite image %r not specified in %s' % |
| 601 | (filename, FORMAT_FILE)) |
| 602 | # Convert images |
Yu-Ping Wu | f64557d | 2021-04-20 13:56:42 +0800 | [diff] [blame] | 603 | os.makedirs(self.stage_sprite_dir, exist_ok=True) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 604 | for name, category in names.items(): |
| 605 | new_name = self.rename_map.get(name, name) |
| 606 | if not new_name: |
| 607 | continue |
| 608 | style = get_config_with_defaults(styles, category) |
| 609 | svg_file = os.path.join(self.sprite_dir, name + '.svg') |
Yu-Ping Wu | f64557d | 2021-04-20 13:56:42 +0800 | [diff] [blame] | 610 | png_file = os.path.join(self.stage_sprite_dir, name + '.png') |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 611 | bmp_file = os.path.join(self.output_dir, new_name + '.bmp') |
| 612 | height = style[KEY_HEIGHT] |
| 613 | bgcolor = style[KEY_BGCOLOR] |
| 614 | self.convert_svg_to_png(svg_file, png_file, height, bgcolor) |
| 615 | self.convert_png_to_bmp(png_file, bmp_file, self.SPRITE_MAX_COLORS) |
Yu-Ping Wu | 675e7e8 | 2021-01-29 08:32:12 +0800 | [diff] [blame] | 616 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 617 | def build_generic_strings(self): |
| 618 | """Builds images of generic (locale-independent) strings.""" |
| 619 | dpi = self.config[KEY_DPI] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 620 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 621 | names = self.formats[KEY_GENERIC_FILES] |
| 622 | styles = self.formats[KEY_STYLES] |
| 623 | fonts = self.formats[KEY_FONTS] |
| 624 | default_font = fonts[KEY_DEFAULT] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 625 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 626 | for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')): |
| 627 | name, _ = os.path.splitext(os.path.basename(txt_file)) |
| 628 | new_name = self.rename_map.get(name, name) |
| 629 | if not new_name: |
| 630 | continue |
| 631 | bmp_file = os.path.join(self.output_dir, new_name + '.bmp') |
| 632 | category = names[name] |
| 633 | style = get_config_with_defaults(styles, category) |
| 634 | if style[KEY_MAX_WIDTH]: |
| 635 | # Setting max_width causes left/right alignment of the text. |
| 636 | # However, generic strings are locale independent, and hence |
| 637 | # shouldn't have text alignment within the bitmap. |
Yu-Ping Wu | 986dd8a | 2021-04-28 16:54:33 +0800 | [diff] [blame] | 638 | raise BuildImageError(f'{name}: {KEY_MAX_WIDTH!r} should be ' |
| 639 | 'null for generic strings') |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 640 | self.convert_text_to_image(None, |
| 641 | txt_file, |
| 642 | bmp_file, |
| 643 | default_font, |
| 644 | self.stage_dir, |
| 645 | self.text_max_colors, |
| 646 | height=style[KEY_HEIGHT], |
| 647 | max_width=None, |
| 648 | dpi=dpi, |
| 649 | bgcolor=style[KEY_BGCOLOR], |
| 650 | fgcolor=style[KEY_FGCOLOR]) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 651 | |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 652 | def build_locale(self, locale, names): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 653 | """Builds images of strings for `locale`.""" |
| 654 | dpi = self.config[KEY_DPI] |
| 655 | styles = self.formats[KEY_STYLES] |
| 656 | fonts = self.formats[KEY_FONTS] |
| 657 | font = fonts.get(locale, fonts[KEY_DEFAULT]) |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 658 | inputs = parse_locale_json_file(locale, self.stage_grit_dir) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 659 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 660 | # Walk locale dir to add pre-generated texts such as language names. |
| 661 | for txt_file in glob.glob( |
| 662 | os.path.join(self.locale_dir, locale, '*.txt')): |
| 663 | name, _ = os.path.splitext(os.path.basename(txt_file)) |
| 664 | with open(txt_file, 'r', encoding='utf-8-sig') as f: |
| 665 | inputs[name] = f.read().strip() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 666 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 667 | stage_dir = os.path.join(self.stage_locale_dir, locale) |
| 668 | os.makedirs(stage_dir, exist_ok=True) |
| 669 | output_dir = os.path.join(self.output_ro_dir, locale) |
| 670 | os.makedirs(output_dir, exist_ok=True) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 671 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 672 | eff_dpi_counters = defaultdict(Counter) |
| 673 | eff_dpi_counter = None |
| 674 | results = [] |
| 675 | for name, category in sorted(names.items()): |
Chung-Sheng Wu | 720e73e | 2021-06-22 17:53:09 +0800 | [diff] [blame] | 676 | if name not in inputs: |
| 677 | raise BuildImageError(f'Locale {locale!r}: ' |
| 678 | f'missing translation: {name!r}') |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 679 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 680 | new_name = self.rename_map.get(name, name) |
| 681 | if not new_name: |
| 682 | continue |
| 683 | output_file = os.path.join(output_dir, new_name + '.bmp') |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 684 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 685 | # Write to text file |
| 686 | text_file = os.path.join(stage_dir, name + '.txt') |
| 687 | with open(text_file, 'w', encoding='utf-8-sig') as f: |
| 688 | f.write(inputs[name] + '\n') |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 689 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 690 | # Convert text to image |
| 691 | style = get_config_with_defaults(styles, category) |
| 692 | height = style[KEY_HEIGHT] |
| 693 | eff_dpi_counter = eff_dpi_counters[height] |
| 694 | if eff_dpi_counter: |
| 695 | # Find the effective DPI that appears most times for `height`. |
| 696 | # This avoid doing the same binary search again and again. In |
| 697 | # case of a tie, pick the largest DPI. |
| 698 | best_eff_dpi = max(eff_dpi_counter, |
| 699 | key=lambda dpi: (eff_dpi_counter[dpi], dpi)) |
| 700 | else: |
| 701 | best_eff_dpi = None |
| 702 | eff_dpi = self.convert_text_to_image( |
| 703 | locale, |
| 704 | text_file, |
| 705 | output_file, |
| 706 | font, |
| 707 | stage_dir, |
| 708 | self.text_max_colors, |
| 709 | height=height, |
| 710 | max_width=style[KEY_MAX_WIDTH], |
| 711 | dpi=dpi, |
| 712 | initial_dpi=best_eff_dpi, |
| 713 | bgcolor=style[KEY_BGCOLOR], |
| 714 | fgcolor=style[KEY_FGCOLOR]) |
| 715 | eff_dpi_counter[eff_dpi] += 1 |
| 716 | assert eff_dpi <= dpi |
| 717 | if eff_dpi != dpi: |
| 718 | results.append(eff_dpi) |
| 719 | return results |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 720 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 721 | def _check_text_width(self, names): |
| 722 | """Checks if text image will exceed the drawing area at runtime.""" |
| 723 | styles = self.formats[KEY_STYLES] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 724 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 725 | for locale_info in self.locales: |
| 726 | locale = locale_info.code |
| 727 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 728 | for filename in glob.glob(os.path.join(ro_locale_dir, '*.bmp')): |
| 729 | name, _ = os.path.splitext(os.path.basename(filename)) |
| 730 | category = names[name] |
| 731 | style = get_config_with_defaults(styles, category) |
| 732 | height = style[KEY_HEIGHT] |
| 733 | max_width = style[KEY_MAX_WIDTH] |
| 734 | if not max_width: |
| 735 | continue |
| 736 | max_width_px = self._to_px(max_width) |
| 737 | with open(filename, 'rb') as f: |
| 738 | f.seek(BMP_HEADER_OFFSET_NUM_LINES) |
| 739 | num_lines = f.read(1)[0] |
| 740 | height_px = self._to_px(height * num_lines) |
| 741 | with Image.open(filename) as image: |
| 742 | width_px = height_px * image.size[0] // image.size[1] |
| 743 | if width_px > max_width_px: |
| 744 | raise BuildImageError( |
| 745 | '%s: Image width %dpx greater than max width ' |
| 746 | '%dpx' % (filename, width_px, max_width_px)) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 747 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 748 | def build_localized_strings(self): |
| 749 | """Builds images of localized strings.""" |
| 750 | # Sources are one .grd file with identifiers chosen by engineers and |
| 751 | # corresponding English texts, as well as a set of .xtb files (one for |
| 752 | # each language other than US English) with a mapping from hash to |
| 753 | # translation. Because the keys in the .xtb files are a hash of the |
| 754 | # English source text, rather than our identifiers, such as |
| 755 | # "btn_cancel", we use the "grit" command line tool to process the .grd |
| 756 | # and .xtb files, producing a set of .json files mapping our identifier |
| 757 | # to the translated string, one for every language including US English. |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 758 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 759 | # This invokes the grit build command to generate JSON files from the |
| 760 | # XTB files containing translations. The results are placed in |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 761 | # `self.stage_grit_dir` as specified in firmware_strings.grd, i.e. one |
| 762 | # JSON file per locale. |
| 763 | os.makedirs(self.stage_grit_dir, exist_ok=True) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 764 | subprocess.check_call([ |
| 765 | 'grit', |
| 766 | '-i', |
| 767 | os.path.join(self.locale_dir, STRINGS_GRD_FILE), |
| 768 | 'build', |
| 769 | '-o', |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 770 | self.stage_grit_dir, |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 771 | ]) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 772 | |
Hsuan Ting Chen | 4b28840 | 2021-07-05 20:02:16 +0800 | [diff] [blame^] | 773 | names = self.formats[KEY_LOCALIZED_FILES] |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 774 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 775 | executor = ProcessPoolExecutor() |
| 776 | futures = [] |
| 777 | for locale_info in self.locales: |
| 778 | locale = locale_info.code |
| 779 | print(locale, end=' ', flush=True) |
Yu-Ping Wu | 08f607b | 2021-04-20 13:11:37 +0800 | [diff] [blame] | 780 | futures.append(executor.submit(self.build_locale, locale, names)) |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 781 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 782 | print() |
| 783 | |
| 784 | try: |
| 785 | results = [future.result() for future in futures] |
| 786 | except KeyboardInterrupt: |
| 787 | executor.shutdown(wait=False) |
| 788 | sys.exit('Aborted by user') |
| 789 | else: |
| 790 | executor.shutdown() |
| 791 | |
| 792 | effective_dpi = [dpi for r in results for dpi in r if dpi] |
| 793 | if effective_dpi: |
| 794 | print( |
| 795 | 'Reducing effective DPI to %d, limited by screen resolution' % |
| 796 | max(effective_dpi)) |
| 797 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 798 | self._check_text_width(names) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 799 | |
| 800 | def move_language_images(self): |
| 801 | """Renames language bitmaps and move to self.output_dir. |
| 802 | |
| 803 | The directory self.output_dir contains locale-independent images, and is |
| 804 | used for creating vbgfx.bin by archive_images.py. |
| 805 | """ |
| 806 | for locale_info in self.locales: |
| 807 | locale = locale_info.code |
| 808 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 809 | old_file = os.path.join(ro_locale_dir, 'language.bmp') |
| 810 | new_file = os.path.join(self.output_dir, |
| 811 | 'language_%s.bmp' % locale) |
| 812 | if os.path.exists(new_file): |
| 813 | raise BuildImageError('File already exists: %s' % new_file) |
| 814 | shutil.move(old_file, new_file) |
| 815 | |
| 816 | def build_glyphs(self): |
| 817 | """Builds glyphs of ascii characters.""" |
| 818 | os.makedirs(self.stage_glyph_dir, exist_ok=True) |
| 819 | output_dir = os.path.join(self.output_dir, 'glyph') |
| 820 | os.makedirs(output_dir) |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 821 | styles = self.formats[KEY_STYLES] |
| 822 | style = get_config_with_defaults(styles, KEY_GLYPH) |
| 823 | height = style[KEY_HEIGHT] |
| 824 | font = self.formats[KEY_FONTS][KEY_GLYPH] |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 825 | executor = ProcessPoolExecutor() |
| 826 | futures = [] |
| 827 | for c in range(ord(' '), ord('~') + 1): |
| 828 | name = f'idx{c:03d}_{c:02x}' |
| 829 | txt_file = os.path.join(self.stage_glyph_dir, name + '.txt') |
| 830 | with open(txt_file, 'w', encoding='ascii') as f: |
| 831 | f.write(chr(c)) |
| 832 | f.write('\n') |
| 833 | output_file = os.path.join(output_dir, name + '.bmp') |
| 834 | futures.append( |
| 835 | executor.submit(self.convert_text_to_image, |
| 836 | None, |
| 837 | txt_file, |
| 838 | output_file, |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 839 | font, |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 840 | self.stage_glyph_dir, |
| 841 | self.GLYPH_MAX_COLORS, |
Yu-Ping Wu | 4c723ea | 2021-04-20 13:20:35 +0800 | [diff] [blame] | 842 | height=height, |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 843 | use_svg=True)) |
| 844 | for future in futures: |
| 845 | future.result() |
| 846 | executor.shutdown() |
| 847 | |
| 848 | def copy_images_to_rw(self): |
| 849 | """Copies localized images specified in boards.yaml for RW override.""" |
| 850 | if not self.config[KEY_RW_OVERRIDE]: |
| 851 | print(' No localized images are specified for RW, skipping') |
| 852 | return |
| 853 | |
| 854 | for locale_info in self.locales: |
| 855 | locale = locale_info.code |
| 856 | ro_locale_dir = os.path.join(self.output_ro_dir, locale) |
| 857 | rw_locale_dir = os.path.join(self.output_rw_dir, locale) |
| 858 | os.makedirs(rw_locale_dir) |
| 859 | |
| 860 | for name in self.config[KEY_RW_OVERRIDE]: |
| 861 | ro_src = os.path.join(ro_locale_dir, name + '.bmp') |
| 862 | rw_dst = os.path.join(rw_locale_dir, name + '.bmp') |
| 863 | shutil.copyfile(ro_src, rw_dst) |
| 864 | |
| 865 | def create_locale_list(self): |
| 866 | """Creates locale list as a CSV file. |
| 867 | |
| 868 | Each line in the file is of format "code,rtl", where |
| 869 | - "code": language code of the locale |
| 870 | - "rtl": "1" for right-to-left language, "0" otherwise |
| 871 | """ |
| 872 | with open(os.path.join(self.output_dir, 'locales'), 'w') as f: |
| 873 | for locale_info in self.locales: |
Yu-Ping Wu | 986dd8a | 2021-04-28 16:54:33 +0800 | [diff] [blame] | 874 | f.write(f'{locale_info.code},{locale_info.rtl:d}\n') |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 875 | |
| 876 | def build(self): |
| 877 | """Builds all images required by a board.""" |
Yu-Ping Wu | f64557d | 2021-04-20 13:56:42 +0800 | [diff] [blame] | 878 | # Clean up output/stage directories |
| 879 | for path in (self.output_dir, self.stage_dir): |
| 880 | if os.path.exists(path): |
| 881 | shutil.rmtree(path) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 882 | os.makedirs(self.output_dir) |
Yu-Ping Wu | f64557d | 2021-04-20 13:56:42 +0800 | [diff] [blame] | 883 | os.makedirs(self.stage_dir) |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 884 | |
| 885 | print('Converting sprite images...') |
| 886 | self.convert_sprite_images() |
| 887 | |
| 888 | print('Building generic strings...') |
| 889 | self.build_generic_strings() |
| 890 | |
| 891 | print('Building localized strings...') |
| 892 | self.build_localized_strings() |
| 893 | |
| 894 | print('Moving language images to locale-independent directory...') |
| 895 | self.move_language_images() |
| 896 | |
| 897 | print('Creating locale list file...') |
| 898 | self.create_locale_list() |
| 899 | |
| 900 | print('Building glyphs...') |
| 901 | self.build_glyphs() |
| 902 | |
| 903 | print('Copying specified images to RW packing directory...') |
| 904 | self.copy_images_to_rw() |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 905 | |
| 906 | |
Yu-Ping Wu | 6e4d389 | 2020-10-19 14:09:37 +0800 | [diff] [blame] | 907 | def main(): |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 908 | """Builds bitmaps for firmware screens.""" |
| 909 | parser = argparse.ArgumentParser() |
| 910 | parser.add_argument('board', help='Target board') |
| 911 | args = parser.parse_args() |
| 912 | board = args.board |
Yu-Ping Wu | 8c8bfc7 | 2020-10-27 16:19:34 +0800 | [diff] [blame] | 913 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 914 | with open(FORMAT_FILE, encoding='utf-8') as f: |
| 915 | formats = yaml.load(f) |
| 916 | board_config = load_board_config(BOARDS_CONFIG_FILE, board) |
Yu-Ping Wu | e66a7b0 | 2020-11-19 15:18:08 +0800 | [diff] [blame] | 917 | |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 918 | print('Building for ' + board) |
| 919 | check_fonts(formats[KEY_FONTS]) |
| 920 | print('Output dir: ' + OUTPUT_DIR) |
| 921 | converter = Converter(board, formats, board_config, OUTPUT_DIR) |
| 922 | converter.build() |
Yu-Ping Wu | 7f6639a | 2020-09-28 15:31:35 +0800 | [diff] [blame] | 923 | |
| 924 | |
Hung-Te Lin | 707e2ef | 2013-08-06 10:20:04 +0800 | [diff] [blame] | 925 | if __name__ == '__main__': |
Yu-Ping Wu | d6a7abb | 2021-04-14 15:36:31 +0800 | [diff] [blame] | 926 | main() |