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