blob: e0dda08f657b3c2f12ae01cc3477d7459edddabc [file] [log] [blame]
Yu-Ping Wud71b4452020-06-16 11:00:26 +08001#!/usr/bin/env python
Hung-Te Lin707e2ef2013-08-06 10:20:04 +08002# 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 Wu6e4d3892020-10-19 14:09:37 +08005"""Script to generate bitmaps for firmware screens."""
Hung-Te Lin707e2ef2013-08-06 10:20:04 +08006
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +08007import argparse
8from collections import defaultdict, namedtuple
9import copy
Yu-Ping Wue445e042020-11-19 15:53:42 +080010import fractions
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080011import glob
Jes Klinke1687a992020-06-16 13:47:17 -070012import json
Hung-Te Lin04addcc2015-03-23 18:43:30 +080013import multiprocessing
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080014import os
15import re
Jes Klinke1687a992020-06-16 13:47:17 -070016import shutil
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080017import signal
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080018import subprocess
19import sys
Jes Klinke1687a992020-06-16 13:47:17 -070020import tempfile
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080021from xml.etree import ElementTree
Hung-Te Lin04addcc2015-03-23 18:43:30 +080022
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080023import yaml
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080024from PIL import Image
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080025
26SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080027
28STRINGS_GRD_FILE = 'firmware_strings.grd'
29STRINGS_JSON_FILE_TMPL = '{}.json'
30FORMAT_FILE = 'format.yaml'
31BOARDS_CONFIG_FILE = 'boards.yaml'
32
33TXT_TO_PNG_SVG = os.path.join(SCRIPT_BASE, 'text_to_png_svg')
34STRINGS_DIR = os.path.join(SCRIPT_BASE, 'strings')
35LOCALE_DIR = os.path.join(STRINGS_DIR, 'locale')
36OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build'))
37STAGE_DIR = os.path.join(OUTPUT_DIR, '.stage')
38STAGE_LOCALE_DIR = os.path.join(STAGE_DIR, 'locale')
39STAGE_FONT_DIR = os.path.join(STAGE_DIR, 'font')
40
41ONE_LINE_DIR = 'one_line'
42SVG_FILES = '*.svg'
43PNG_FILES = '*.png'
44
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080045DIAGNOSTIC_UI = os.getenv('DIAGNOSTIC_UI') == '1'
46
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080047# String format YAML key names.
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080048KEY_DEFAULT = '_DEFAULT_'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080049KEY_LOCALES = 'locales'
Yu-Ping Wu338f0832020-10-23 16:14:40 +080050KEY_GENERIC_FILES = 'generic_files'
51KEY_LOCALIZED_FILES = 'localized_files'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080052KEY_DIAGNOSTIC_FILES = 'diagnostic_files'
53KEY_SPRITE_FILES = 'sprite_files'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080054KEY_STYLES = 'styles'
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080055KEY_BGCOLOR = 'bgcolor'
56KEY_FGCOLOR = 'fgcolor'
57KEY_HEIGHT = 'height'
Yu-Ping Wued95df32020-11-04 17:08:15 +080058KEY_MAX_WIDTH = 'max_width'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080059KEY_FONTS = 'fonts'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080060
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080061# Board config YAML key names.
62SCREEN_KEY = 'screen'
63PANEL_KEY = 'panel'
64SDCARD_KEY = 'sdcard'
65BAD_USB3_KEY = 'bad_usb3'
Yu-Ping Wue66a7b02020-11-19 15:18:08 +080066DPI_KEY = 'dpi'
67TEXT_COLORS_KEY = 'text_colors'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080068LOCALES_KEY = 'locales'
69RTL_KEY = 'rtl'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080070RW_OVERRIDE_KEY = 'rw_override'
71
72BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080073
Jes Klinke1687a992020-06-16 13:47:17 -070074# Regular expressions used to eliminate spurious spaces and newlines in
75# translation strings.
76NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
77NEWLINE_REPLACEMENT = r'\1 \2'
78CRLF_PATTERN = re.compile(r'\r\n')
79MULTIBLANK_PATTERN = re.compile(r' *')
80
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +080081GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080082
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080083LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080084
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080085
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080086class DataError(Exception):
87 pass
88
89
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080090class BuildImageError(Exception):
91 """The exception class for all errors generated during build image process."""
92
93
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080094def get_config_with_defaults(configs, key):
95 """Gets config of `key` from `configs`.
96
97 If `key` is not present in `configs`, the default config will be returned.
98 Similarly, if some config values are missing for `key`, the default ones will
99 be used.
100 """
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800101 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800102 config.update(configs.get(key, {}))
103 return config
104
105
Yu-Ping Wued95df32020-11-04 17:08:15 +0800106def convert_text_to_png(locale, input_file, font, output_dir, height=None,
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800107 max_width=None, dpi=None, bgcolor='#000000',
108 fgcolor='#ffffff',
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800109 **options):
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800110 """Converts text files into PNG image files.
111
112 Args:
113 locale: Locale (language) to select implicit rendering options. None for
114 locale-independent strings.
115 input_file: Path of input text file.
116 font: Font spec.
Yu-Ping Wued95df32020-11-04 17:08:15 +0800117 height: Height.
118 max_width: Maximum width.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800119 output_dir: Directory to generate image files.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800120 bgcolor: Background color (#rrggbb).
121 fgcolor: Foreground color (#rrggbb).
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800122 **options: Other options to be added.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800123 """
124 name, _ = os.path.splitext(os.path.basename(input_file))
125 command = [TXT_TO_PNG_SVG, '--outdir=%s' % output_dir]
126 if locale:
127 command.append('--lan=%s' % locale)
128 if font:
129 command.append("--font='%s'" % font)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800130 if height:
131 # Font size should be proportional to the height. Here we use 2 as the
132 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
133 # will be roughly equivalent to setting the screen resolution to 1366x768.
134 font_size = height / 2
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800135 command.append('--point=%r' % font_size)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800136 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800137 # When converting text to PNG by pango-view, the ratio of image height to
138 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
139 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
140 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
141 # the calculation of `font_size` above.
142 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800143 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800144 if dpi:
145 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800146 command.append('--margin=0')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800147 command.append('--bgcolor="%s"' % bgcolor)
148 command.append('--color="%s"' % fgcolor)
149
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800150 for k, v in options.items():
151 command.append('--%s="%s"' % (k, v))
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800152 command.append(input_file)
153
154 return subprocess.call(' '.join(command), shell=True,
155 stdout=subprocess.PIPE) == 0
156
157
158def convert_glyphs():
159 """Converts glyphs of ascii characters."""
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800160 os.makedirs(STAGE_FONT_DIR, exist_ok=True)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800161 # Remove the extra whitespace at the top/bottom within the glyphs
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800162 for c in range(ord(' '), ord('~') + 1):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800163 txt_file = os.path.join(STAGE_FONT_DIR, f'idx{c:03d}_{c:02x}.txt')
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800164 with open(txt_file, 'w', encoding='ascii') as f:
165 f.write(chr(c))
166 f.write('\n')
167 # TODO(b/163109632): Parallelize the conversion of glyphs
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800168 convert_text_to_png(None, txt_file, GLYPH_FONT, STAGE_FONT_DIR)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800169
170
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800171def _load_locale_json_file(locale, json_dir):
Jes Klinke1687a992020-06-16 13:47:17 -0700172 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800173 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800174 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700175 for tag, msgdict in json.load(input_file).items():
176 msgtext = msgdict['message']
177 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
178 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
179 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
180 # Strip any trailing whitespace. A trailing newline appears to make
181 # Pango report a larger layout size than what's actually visible.
182 msgtext = msgtext.strip()
183 result[tag] = msgtext
184 return result
185
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800186
187def parse_locale_json_file(locale, json_dir):
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800188 """Parses given firmware string json file.
Mathew King89d48c62019-02-15 10:08:39 -0700189
190 Args:
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800191 locale: The name of the locale, e.g. "da" or "pt-BR".
Jes Klinke1687a992020-06-16 13:47:17 -0700192 json_dir: Directory containing json output from grit.
Mathew King89d48c62019-02-15 10:08:39 -0700193
194 Returns:
195 A dictionary for mapping of "name to content" for files to be generated.
196 """
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800197 result = _load_locale_json_file(locale, json_dir)
198 original = _load_locale_json_file('en', json_dir)
199 for tag in original:
200 if tag not in result:
201 # Use original English text, in case translation is not yet available
202 print('WARNING: locale "%s", missing entry %s' % (locale, tag))
203 result[tag] = original[tag]
Mathew King89d48c62019-02-15 10:08:39 -0700204
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800205 return result
Mathew King89d48c62019-02-15 10:08:39 -0700206
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800207
208def parse_locale_input_files(locale, json_dir):
209 """Parses all firmware string files for the given locale.
210
211 Args:
212 locale: The name of the locale, e.g. "da" or "pt-BR".
213 json_dir: Directory containing json output from grit.
214
215 Returns:
216 A dictionary for mapping of "name to content" for files to be generated.
217 """
218 result = parse_locale_json_file(locale, json_dir)
219
220 # Walk locale directory to add pre-generated texts such as language names.
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800221 for input_file in glob.glob(os.path.join(LOCALE_DIR, locale, "*.txt")):
Mathew King89d48c62019-02-15 10:08:39 -0700222 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800223 with open(input_file, 'r', encoding='utf-8-sig') as f:
Mathew King89d48c62019-02-15 10:08:39 -0700224 result[name] = f.read().strip()
Shelley Chen2f616ac2017-05-22 13:19:40 -0700225
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800226 return result
227
228
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800229def build_text_files(inputs, files, output_dir):
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800230 """Builds text files from given input data.
231
232 Args:
233 inputs: Dictionary of contents for given file name.
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800234 files: List of files.
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800235 output_dir: Directory to generate text files.
236 """
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800237 for name in files:
238 file_name = os.path.join(output_dir, name + '.txt')
239 with open(file_name, 'w', encoding='utf-8-sig') as f:
240 f.write(inputs[name] + '\n')
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800241
242
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800243def convert_localized_strings(formats, dpi):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800244 """Converts localized strings."""
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800245 # Make a copy of formats to avoid modifying it
246 formats = copy.deepcopy(formats)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800247
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800248 env_locales = os.getenv('LOCALES')
249 if env_locales:
250 locales = env_locales.split()
251 else:
252 locales = formats[KEY_LOCALES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800253
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800254 files = formats[KEY_LOCALIZED_FILES]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800255 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800256 files.update(formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800257
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800258 styles = formats[KEY_STYLES]
259 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800260 default_font = fonts[KEY_DEFAULT]
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800261
Yu-Ping Wu51940352020-09-17 08:48:55 +0800262 # Sources are one .grd file with identifiers chosen by engineers and
263 # corresponding English texts, as well as a set of .xlt files (one for each
264 # language other than US english) with a mapping from hash to translation.
265 # Because the keys in the xlt files are a hash of the English source text,
266 # rather than our identifiers, such as "btn_cancel", we use the "grit"
267 # command line tool to process the .grd and .xlt files, producing a set of
268 # .json files mapping our identifier to the translated string, one for every
269 # language including US English.
Jes Klinke1687a992020-06-16 13:47:17 -0700270
Yu-Ping Wu51940352020-09-17 08:48:55 +0800271 # Create a temporary directory to place the translation output from grit in.
272 json_dir = tempfile.mkdtemp()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800273
Yu-Ping Wu51940352020-09-17 08:48:55 +0800274 # This invokes the grit build command to generate JSON files from the XTB
275 # files containing translations. The results are placed in `json_dir` as
276 # specified in firmware_strings.grd, i.e. one JSON file per locale.
277 subprocess.check_call([
278 'grit',
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800279 '-i', os.path.join(LOCALE_DIR, STRINGS_GRD_FILE),
Yu-Ping Wu51940352020-09-17 08:48:55 +0800280 'build',
281 '-o', os.path.join(json_dir)
282 ])
Jes Klinke1687a992020-06-16 13:47:17 -0700283
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800284 # Ignore SIGINT in child processes
285 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800286 pool = multiprocessing.Pool(multiprocessing.cpu_count())
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800287 signal.signal(signal.SIGINT, sigint_handler)
288
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800289 results = []
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800290 for locale in locales:
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800291 print(locale, end=' ', flush=True)
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800292 inputs = parse_locale_input_files(locale, json_dir)
293 output_dir = os.path.normpath(os.path.join(STAGE_DIR, 'locale', locale))
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800294 if not os.path.exists(output_dir):
295 os.makedirs(output_dir)
Matt Delco4c5580d2019-03-07 14:00:28 -0800296
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800297 build_text_files(inputs, files, output_dir)
Shelley Chen2f616ac2017-05-22 13:19:40 -0700298
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800299 for name, category in files.items():
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800300 style = get_config_with_defaults(styles, category)
301 args = (
302 locale,
303 os.path.join(output_dir, '%s.txt' % name),
304 fonts.get(locale, default_font),
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800305 output_dir,
306 )
307 kwargs = {
Yu-Ping Wued95df32020-11-04 17:08:15 +0800308 'height': style[KEY_HEIGHT],
309 'max_width': style[KEY_MAX_WIDTH],
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800310 'dpi': dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800311 'bgcolor': style[KEY_BGCOLOR],
312 'fgcolor': style[KEY_FGCOLOR],
313 }
314 results.append(pool.apply_async(convert_text_to_png, args, kwargs))
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800315 pool.close()
Jes Klinke1687a992020-06-16 13:47:17 -0700316 if json_dir is not None:
317 shutil.rmtree(json_dir)
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800318 print()
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800319
320 try:
321 success = [r.get() for r in results]
322 except KeyboardInterrupt:
323 pool.terminate()
324 pool.join()
325 exit('Aborted by user')
326 else:
327 pool.join()
328 if not all(success):
329 exit('Failed to render some locales')
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800330
331
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800332def build_strings(formats, board_config):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800333 """Builds text strings."""
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800334 dpi = board_config[DPI_KEY]
335
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800336 # Convert glyphs
337 print('Converting glyphs...')
338 convert_glyphs()
339
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800340 # Convert generic (locale-independent) strings
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800341 files = formats[KEY_GENERIC_FILES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800342 styles = formats[KEY_STYLES]
343 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800344 default_font = fonts[KEY_DEFAULT]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800345
346 for input_file in glob.glob(os.path.join(STRINGS_DIR, '*.txt')):
347 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800348 category = files[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800349 style = get_config_with_defaults(styles, category)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800350 if not convert_text_to_png(None, input_file, default_font, STAGE_DIR,
351 height=style[KEY_HEIGHT],
352 max_width=style[KEY_MAX_WIDTH],
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800353 dpi=dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800354 bgcolor=style[KEY_BGCOLOR],
355 fgcolor=style[KEY_FGCOLOR]):
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800356 exit('Failed to convert text %s' % input_file)
357
358 # Convert localized strings
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800359 convert_localized_strings(formats, dpi)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800360
361
362def load_boards_config(filename):
363 """Loads the configuration of all boards from `filename`.
364
365 Args:
366 filename: File name of a YAML config file.
367
368 Returns:
369 A dictionary mapping each board name to its config.
370 """
371 with open(filename, 'rb') as file:
372 raw = yaml.load(file)
373
374 configs = {}
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800375 default = raw[KEY_DEFAULT]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800376 if not default:
377 raise BuildImageError('Default configuration is not found')
378 for boards, params in raw.items():
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800379 if boards == KEY_DEFAULT:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800380 continue
381 config = copy.deepcopy(default)
382 if params:
383 config.update(params)
384 for board in boards.replace(',', ' ').split():
385 configs[board] = config
386
387 return configs
388
389
390class Converter(object):
391 """Converter from assets, texts, URLs, and fonts to bitmap images.
392
393 Attributes:
394 ASSET_DIR (str): Directory of image assets.
395 DEFAULT_OUTPUT_EXT (str): Default output file extension.
396 DEFAULT_REPLACE_MAP (dict): Default mapping of file replacement. For
397 {'a': 'b'}, "a.*" will be converted to "b.*".
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800398 SCALE_BASE (int): The base for bitmap scales, same as UI_SCALE in
399 depthcharge. For example, if `SCALE_BASE` is 1000, then height = 200 means
400 20% of the screen height. Also see the 'styles' section in format.yaml.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800401 DEFAULT_FONT_HEIGHT (tuple): Height of the font images.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800402 ASSET_MAX_COLORS (int): Maximum colors to use for converting image assets
403 to bitmaps.
404 DEFAULT_BACKGROUND (tuple): Default background color.
405 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
406 name and value is a tuple of RGB values.
407 """
408
409 ASSET_DIR = 'assets'
410 DEFAULT_OUTPUT_EXT = '.bmp'
411
412 DEFAULT_REPLACE_MAP = {
413 'rec_sel_desc1_no_sd': '',
414 'rec_sel_desc1_no_phone_no_sd': '',
415 'rec_disk_step1_desc0_no_sd': '',
416 'rec_to_dev_desc1_phyrec': '',
417 'rec_to_dev_desc1_power': '',
418 'navigate0_tablet': '',
419 'navigate1_tablet': '',
420 'nav-button_power': '',
421 'nav-button_volume_up': '',
422 'nav-button_volume_down': '',
423 'broken_desc_phyrec': '',
424 'broken_desc_detach': '',
425 }
426
427 # scales
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800428 SCALE_BASE = 1000
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800429 DEFAULT_FONT_HEIGHT = 20
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800430
431 # background colors
432 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
433 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
434 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
435 ASSET_MAX_COLORS = 128
436
437 BACKGROUND_COLORS = {
438 'ic_dropdown': LANG_HEADER_BACKGROUND,
439 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
440 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
441 'ic_globe': LANG_HEADER_BACKGROUND,
442 'ic_search_focus': LINK_SELECTED_BACKGROUND,
443 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
444 'ic_power_focus': LINK_SELECTED_BACKGROUND,
445 }
446
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800447 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800448 """Inits converter.
449
450 Args:
451 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800452 formats: A dictionary of string formats.
453 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800454 output: Output directory.
455 """
456 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800457 self.formats = formats
458 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800459 self.set_dirs(output)
460 self.set_screen()
461 self.set_replace_map()
462 self.set_locales()
463 self.text_max_colors = self.config[TEXT_COLORS_KEY]
464
465 def set_dirs(self, output):
466 """Sets board output directory and stage directory.
467
468 Args:
469 output: Output directory.
470 """
471 self.output_dir = os.path.join(output, self.board)
472 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
473 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
474 self.stage_dir = os.path.join(output, '.stage')
475 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
476
477 def set_screen(self):
478 """Sets screen width and height."""
479 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
480
Yu-Ping Wue445e042020-11-19 15:53:42 +0800481 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800482 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800483 # Calculate `panel_stretch`. It's used to shrink images horizontally so
484 # that the resulting images will look proportional to the original image
485 # on the stretched display. If the display is not stretched, meaning the
486 # aspect ratio is same as the screen where images were rendered, no
487 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800488 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800489 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
490 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800491
Yu-Ping Wue445e042020-11-19 15:53:42 +0800492 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800493 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
494 'aspect ratio (%f). It indicates screen will be '
495 'shrunk horizontally. It is currently unsupported.'
496 % (panel_width / panel_height,
497 self.screen_width / self.screen_height))
498
499 # Set up square drawing area
500 self.canvas_px = min(self.screen_width, self.screen_height)
501
502 def set_replace_map(self):
503 """Sets a map replacing images.
504
505 For each (key, value), image 'key' will be replaced by image 'value'.
506 """
507 replace_map = self.DEFAULT_REPLACE_MAP.copy()
508
509 if os.getenv('DETACHABLE') == '1':
510 replace_map.update({
511 'nav-key_enter': 'nav-button_power',
512 'nav-key_up': 'nav-button_volume_up',
513 'nav-key_down': 'nav-button_volume_down',
514 'navigate0': 'navigate0_tablet',
515 'navigate1': 'navigate1_tablet',
516 'broken_desc': 'broken_desc_detach',
517 })
518
519 physical_presence = os.getenv('PHYSICAL_PRESENCE')
520 if physical_presence == 'recovery':
521 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_phyrec'
522 replace_map['broken_desc'] = 'broken_desc_phyrec'
523 elif physical_presence == 'power':
524 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_power'
525 elif physical_presence != 'keyboard':
526 raise BuildImageError('Invalid physical presence setting %s for board %s'
527 % (physical_presence, self.board))
528
529 if not self.config[SDCARD_KEY]:
530 replace_map.update({
531 'rec_sel_desc1': 'rec_sel_desc1_no_sd',
532 'rec_sel_desc1_no_phone': 'rec_sel_desc1_no_phone_no_sd',
533 'rec_disk_step1_desc0': 'rec_disk_step1_desc0_no_sd',
534 })
535
536 self.replace_map = replace_map
537
538 def set_locales(self):
539 """Sets a list of locales for which localized images are converted."""
540 # LOCALES environment variable can overwrite boards.yaml
541 env_locales = os.getenv('LOCALES')
542 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800543 if env_locales:
544 locales = env_locales.split()
545 else:
546 locales = self.config[LOCALES_KEY]
547 # Check rtl_locales are contained in locales.
548 unknown_rtl_locales = rtl_locales - set(locales)
549 if unknown_rtl_locales:
550 raise BuildImageError('Unknown locales %s in %s' %
551 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800552 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800553 for code in locales]
554
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800555 def _get_png_height(self, png_file):
556 with Image.open(png_file) as image:
557 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800558
559 def get_num_lines(self, file, one_line_dir):
560 """Gets the number of lines of text in `file`."""
561 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800562 png_name = name + '.png'
563 multi_line_file = os.path.join(os.path.dirname(file), png_name)
564 one_line_file = os.path.join(one_line_dir, png_name)
565 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800566 # `multi_line_file` with `one_line_file`, where the latter is generated
567 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800568 height = self._get_png_height(multi_line_file)
569 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800570 return int(round(height / line_height))
571
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800572 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800573 background):
574 """Converts .svg file to .png file."""
575 background_hex = ''.join(format(x, '02x') for x in background)
576 # If the width/height of the SVG file is specified in points, the
577 # rsvg-convert command with default 90DPI will potentially cause the pixels
578 # at the right/bottom border of the output image to be transparent (or
579 # filled with the specified background color). This seems like an
580 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
581 # to avoid the scaling.
582 command = ['rsvg-convert',
583 '--background-color', "'#%s'" % background_hex,
584 '--dpi-x', '72',
585 '--dpi-y', '72',
586 '-o', png_file]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800587 height_px = int(self.canvas_px * height / self.SCALE_BASE) * num_lines
588 if height_px <= 0:
589 raise BuildImageError('Height of %r <= 0 (%dpx)' %
590 (os.path.basename(svg_file), height_px))
591 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800592 command.append(svg_file)
593 subprocess.check_call(' '.join(command), shell=True)
594
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800595 def convert_to_bitmap(self, input_file, height, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800596 max_colors):
597 """Converts an image file `input_file` to a BMP file `output`."""
598 image = Image.open(input_file)
599
600 # Process alpha channel and transparency.
601 if image.mode == 'RGBA':
602 target = Image.new('RGB', image.size, background)
603 image.load() # required for image.split()
604 mask = image.split()[-1]
605 target.paste(image, mask=mask)
606 elif (image.mode == 'P') and ('transparency' in image.info):
607 exit('Sorry, PNG with RGBA palette is not supported.')
608 elif image.mode != 'RGB':
609 target = image.convert('RGB')
610 else:
611 target = image
612
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800613 width_px, height_px = image.size
614 max_height_px = int(self.canvas_px * height / self.SCALE_BASE) * num_lines
615 # If the image size is larger than what will be displayed at runtime,
616 # downscale it.
617 if height_px > max_height_px:
618 height_px = max_height_px
619 width_px = height_px * image.size[0] // image.size[1]
620 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800621 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800622 width_px = int(width_px * self.panel_stretch)
623 new_size = width_px, height_px
624 if new_size != image.size:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800625 target = target.resize(new_size, Image.BICUBIC)
626
627 # Export and downsample color space.
628 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
629 ).save(output)
630
631 with open(output, 'rb+') as f:
632 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
633 f.write(bytearray([num_lines]))
634
Yu-Ping Wued95df32020-11-04 17:08:15 +0800635 def convert(self, files, output_dir, heights, max_widths, max_colors,
636 one_line_dir=None):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800637 """Converts file(s) to bitmap format."""
638 if not files:
639 raise BuildImageError('Unable to find file(s) to convert')
640
641 for file in files:
642 name, ext = os.path.splitext(os.path.basename(file))
643 output = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
644
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800645 if name in self.replace_map:
646 name = self.replace_map[name]
647 if not name:
648 continue
649 print('Replace: %s => %s' % (file, name))
650 file = os.path.join(os.path.dirname(file), name + ext)
651
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800652 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
653 height = heights[name]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800654 max_width = max_widths[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800655
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800656 # Determine num_lines in order to scale the image
Yu-Ping Wued95df32020-11-04 17:08:15 +0800657 if one_line_dir and max_width:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800658 num_lines = self.get_num_lines(file, one_line_dir)
659 else:
660 num_lines = 1
661
662 if ext == '.svg':
663 png_file = os.path.join(self.temp_dir, name + '.png')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800664 self.convert_svg_to_png(file, png_file, height, num_lines, background)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800665 file = png_file
666
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800667 self.convert_to_bitmap(file, height, num_lines, background, output,
668 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800669
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800670 def convert_sprite_images(self):
671 """Converts sprite images."""
672 names = self.formats[KEY_SPRITE_FILES]
673 styles = self.formats[KEY_STYLES]
674 # Check redundant images
675 for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)):
676 name, _ = os.path.splitext(os.path.basename(filename))
677 if name not in names:
678 raise BuildImageError('Sprite image %r not specified in %s' %
679 (filename, FORMAT_FILE))
680 # Convert images
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800681 files = []
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800682 heights = {}
683 for name, category in names.items():
684 style = get_config_with_defaults(styles, category)
685 files.append(os.path.join(self.ASSET_DIR, name + '.svg'))
686 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800687 max_widths = defaultdict(lambda: None)
688 self.convert(files, self.output_dir, heights, max_widths,
689 self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800690
691 def convert_generic_strings(self):
692 """Converts generic (locale-independent) strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800693 names = self.formats[KEY_GENERIC_FILES]
694 styles = self.formats[KEY_STYLES]
695 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800696 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800697 for name, category in names.items():
698 style = get_config_with_defaults(styles, category)
699 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800700 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800701
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800702 files = glob.glob(os.path.join(self.stage_dir, PNG_FILES))
Yu-Ping Wued95df32020-11-04 17:08:15 +0800703 self.convert(files, self.output_dir, heights, max_widths,
704 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800705
706 def convert_localized_strings(self):
707 """Converts localized strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800708 names = self.formats[KEY_LOCALIZED_FILES].copy()
709 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800710 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800711 styles = self.formats[KEY_STYLES]
712 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800713 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800714 for name, category in names.items():
715 style = get_config_with_defaults(styles, category)
716 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800717 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800718
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800719 # Using stderr to report progress synchronously
720 print(' processing:', end='', file=sys.stderr, flush=True)
721 for locale_info in self.locales:
722 locale = locale_info.code
723 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
724 stage_locale_dir = os.path.join(STAGE_LOCALE_DIR, locale)
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800725 print(' ' + locale, end='', file=sys.stderr, flush=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800726 os.makedirs(ro_locale_dir)
727 self.convert(
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800728 glob.glob(os.path.join(stage_locale_dir, PNG_FILES)),
Yu-Ping Wued95df32020-11-04 17:08:15 +0800729 ro_locale_dir, heights, max_widths, self.text_max_colors,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800730 one_line_dir=os.path.join(stage_locale_dir, ONE_LINE_DIR))
731 print(file=sys.stderr)
732
733 def move_language_images(self):
734 """Renames language bitmaps and move to self.output_dir.
735
736 The directory self.output_dir contains locale-independent images, and is
737 used for creating vbgfx.bin by archive_images.py.
738 """
739 for locale_info in self.locales:
740 locale = locale_info.code
741 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
742 old_file = os.path.join(ro_locale_dir, 'language.bmp')
743 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
744 if os.path.exists(new_file):
745 raise BuildImageError('File already exists: %s' % new_file)
746 shutil.move(old_file, new_file)
747
748 def convert_fonts(self):
749 """Converts font images"""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800750 heights = defaultdict(lambda: self.DEFAULT_FONT_HEIGHT)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800751 max_widths = defaultdict(lambda: None)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800752 files = glob.glob(os.path.join(STAGE_FONT_DIR, SVG_FILES))
753 font_output_dir = os.path.join(self.output_dir, 'font')
754 os.makedirs(font_output_dir)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800755 self.convert(files, font_output_dir, heights, max_widths,
756 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800757
758 def copy_images_to_rw(self):
759 """Copies localized images specified in boards.yaml for RW override."""
760 if not self.config[RW_OVERRIDE_KEY]:
761 print(' No localized images are specified for RW, skipping')
762 return
763
764 for locale_info in self.locales:
765 locale = locale_info.code
766 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
767 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
768 os.makedirs(rw_locale_dir)
769
770 for name in self.config[RW_OVERRIDE_KEY]:
771 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
772 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
773 shutil.copyfile(ro_src, rw_dst)
774
775 def create_locale_list(self):
776 """Creates locale list as a CSV file.
777
778 Each line in the file is of format "code,rtl", where
779 - "code": language code of the locale
780 - "rtl": "1" for right-to-left language, "0" otherwise
781 """
782 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
783 for locale_info in self.locales:
784 f.write('{},{}\n'.format(locale_info.code,
785 int(locale_info.rtl)))
786
787 def build(self):
788 """Builds all images required by a board."""
789 # Clean up output directory
790 if os.path.exists(self.output_dir):
791 shutil.rmtree(self.output_dir)
792 os.makedirs(self.output_dir)
793
794 if not os.path.exists(self.stage_dir):
795 raise BuildImageError('Missing stage folder. Run make in strings dir.')
796
797 # Clean up temp directory
798 if os.path.exists(self.temp_dir):
799 shutil.rmtree(self.temp_dir)
800 os.makedirs(self.temp_dir)
801
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800802 print('Converting sprite images...')
803 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800804
805 print('Converting generic strings...')
806 self.convert_generic_strings()
807
808 print('Converting localized strings...')
809 self.convert_localized_strings()
810
811 print('Moving language images to locale-independent directory...')
812 self.move_language_images()
813
814 print('Creating locale list file...')
815 self.create_locale_list()
816
817 print('Converting fonts...')
818 self.convert_fonts()
819
820 print('Copying specified images to RW packing directory...')
821 self.copy_images_to_rw()
822
823
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800824def main():
825 """Builds bitmaps for firmware screens."""
826 parser = argparse.ArgumentParser()
827 parser.add_argument('board', help='Target board')
828 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800829 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800830
831 with open(FORMAT_FILE, encoding='utf-8') as f:
832 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800833 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
834
835 # TODO(yupingso): Put everything into Converter class
836 print('Building for ' + board)
837 build_strings(formats, board_config)
838 converter = Converter(board, formats, board_config, OUTPUT_DIR)
839 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800840
841
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800842if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800843 main()