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