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