blob: 4a2e1941f42855d3b06492ee776667739295a254 [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'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080067LOCALES_KEY = 'locales'
68RTL_KEY = 'rtl'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080069RW_OVERRIDE_KEY = 'rw_override'
70
71BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080072
Jes Klinke1687a992020-06-16 13:47:17 -070073# Regular expressions used to eliminate spurious spaces and newlines in
74# translation strings.
75NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
76NEWLINE_REPLACEMENT = r'\1 \2'
77CRLF_PATTERN = re.compile(r'\r\n')
78MULTIBLANK_PATTERN = re.compile(r' *')
79
Yu-Ping Wu3d07a062021-01-26 18:10:32 +080080# The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if
81# `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also
82# see the 'styles' section in format.yaml.
83SCALE_BASE = 1000
84DEFAULT_GLYPH_HEIGHT = 20
85
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +080086GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080087
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080088LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080089
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080090
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080091class DataError(Exception):
92 pass
93
94
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080095class BuildImageError(Exception):
96 """The exception class for all errors generated during build image process."""
97
98
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080099def get_config_with_defaults(configs, key):
100 """Gets config of `key` from `configs`.
101
102 If `key` is not present in `configs`, the default config will be returned.
103 Similarly, if some config values are missing for `key`, the default ones will
104 be used.
105 """
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800106 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800107 config.update(configs.get(key, {}))
108 return config
109
110
Yu-Ping Wued95df32020-11-04 17:08:15 +0800111def convert_text_to_png(locale, input_file, font, output_dir, height=None,
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800112 max_width=None, dpi=None, bgcolor='#000000',
113 fgcolor='#ffffff',
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800114 **options):
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800115 """Converts text files into PNG image files.
116
117 Args:
118 locale: Locale (language) to select implicit rendering options. None for
119 locale-independent strings.
120 input_file: Path of input text file.
121 font: Font spec.
Yu-Ping Wued95df32020-11-04 17:08:15 +0800122 height: Height.
123 max_width: Maximum width.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800124 output_dir: Directory to generate image files.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800125 bgcolor: Background color (#rrggbb).
126 fgcolor: Foreground color (#rrggbb).
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800127 **options: Other options to be added.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800128 """
129 name, _ = os.path.splitext(os.path.basename(input_file))
130 command = [TXT_TO_PNG_SVG, '--outdir=%s' % output_dir]
131 if locale:
132 command.append('--lan=%s' % locale)
133 if font:
134 command.append("--font='%s'" % font)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800135 if height:
136 # Font size should be proportional to the height. Here we use 2 as the
137 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
138 # will be roughly equivalent to setting the screen resolution to 1366x768.
139 font_size = height / 2
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800140 command.append('--point=%r' % font_size)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800141 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800142 # When converting text to PNG by pango-view, the ratio of image height to
143 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
144 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
145 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
146 # the calculation of `font_size` above.
147 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800148 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800149 if dpi:
150 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800151 command.append('--margin=0')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800152 command.append('--bgcolor="%s"' % bgcolor)
153 command.append('--color="%s"' % fgcolor)
154
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800155 for k, v in options.items():
156 command.append('--%s="%s"' % (k, v))
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800157 command.append(input_file)
158
159 return subprocess.call(' '.join(command), shell=True,
160 stdout=subprocess.PIPE) == 0
161
162
163def convert_glyphs():
164 """Converts glyphs of ascii characters."""
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800165 os.makedirs(STAGE_FONT_DIR, exist_ok=True)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800166 # Remove the extra whitespace at the top/bottom within the glyphs
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800167 for c in range(ord(' '), ord('~') + 1):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800168 txt_file = os.path.join(STAGE_FONT_DIR, f'idx{c:03d}_{c:02x}.txt')
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800169 with open(txt_file, 'w', encoding='ascii') as f:
170 f.write(chr(c))
171 f.write('\n')
172 # TODO(b/163109632): Parallelize the conversion of glyphs
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800173 convert_text_to_png(None, txt_file, GLYPH_FONT, STAGE_FONT_DIR,
174 height=DEFAULT_GLYPH_HEIGHT)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800175
176
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800177def parse_locale_json_file(locale, json_dir):
178 """Parses given firmware string json file.
179
180 Args:
181 locale: The name of the locale, e.g. "da" or "pt-BR".
182 json_dir: Directory containing json output from grit.
183
184 Returns:
185 A dictionary for mapping of "name to content" for files to be generated.
186 """
Jes Klinke1687a992020-06-16 13:47:17 -0700187 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800188 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800189 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700190 for tag, msgdict in json.load(input_file).items():
191 msgtext = msgdict['message']
192 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
193 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
194 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
195 # Strip any trailing whitespace. A trailing newline appears to make
196 # Pango report a larger layout size than what's actually visible.
197 msgtext = msgtext.strip()
198 result[tag] = msgtext
199 return result
200
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800201
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800202def parse_locale_input_files(locale, json_dir):
203 """Parses all firmware string files for the given locale.
204
205 Args:
206 locale: The name of the locale, e.g. "da" or "pt-BR".
207 json_dir: Directory containing json output from grit.
208
209 Returns:
210 A dictionary for mapping of "name to content" for files to be generated.
211 """
212 result = parse_locale_json_file(locale, json_dir)
213
214 # Walk locale directory to add pre-generated texts such as language names.
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800215 for input_file in glob.glob(os.path.join(LOCALE_DIR, locale, "*.txt")):
Mathew King89d48c62019-02-15 10:08:39 -0700216 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800217 with open(input_file, 'r', encoding='utf-8-sig') as f:
Mathew King89d48c62019-02-15 10:08:39 -0700218 result[name] = f.read().strip()
Shelley Chen2f616ac2017-05-22 13:19:40 -0700219
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800220 return result
221
222
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800223def convert_localized_strings(formats, dpi):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800224 """Converts localized strings."""
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800225 # Make a copy of formats to avoid modifying it
226 formats = copy.deepcopy(formats)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800227
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800228 env_locales = os.getenv('LOCALES')
229 if env_locales:
230 locales = env_locales.split()
231 else:
232 locales = formats[KEY_LOCALES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800233
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800234 files = formats[KEY_LOCALIZED_FILES]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800235 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800236 files.update(formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800237
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800238 styles = formats[KEY_STYLES]
239 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800240 default_font = fonts[KEY_DEFAULT]
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800241
Yu-Ping Wu51940352020-09-17 08:48:55 +0800242 # Sources are one .grd file with identifiers chosen by engineers and
243 # corresponding English texts, as well as a set of .xlt files (one for each
244 # language other than US english) with a mapping from hash to translation.
245 # Because the keys in the xlt files are a hash of the English source text,
246 # rather than our identifiers, such as "btn_cancel", we use the "grit"
247 # command line tool to process the .grd and .xlt files, producing a set of
248 # .json files mapping our identifier to the translated string, one for every
249 # language including US English.
Jes Klinke1687a992020-06-16 13:47:17 -0700250
Yu-Ping Wu51940352020-09-17 08:48:55 +0800251 # Create a temporary directory to place the translation output from grit in.
252 json_dir = tempfile.mkdtemp()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800253
Yu-Ping Wu51940352020-09-17 08:48:55 +0800254 # This invokes the grit build command to generate JSON files from the XTB
255 # files containing translations. The results are placed in `json_dir` as
256 # specified in firmware_strings.grd, i.e. one JSON file per locale.
257 subprocess.check_call([
258 'grit',
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800259 '-i', os.path.join(LOCALE_DIR, STRINGS_GRD_FILE),
Yu-Ping Wu51940352020-09-17 08:48:55 +0800260 'build',
261 '-o', os.path.join(json_dir)
262 ])
Jes Klinke1687a992020-06-16 13:47:17 -0700263
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800264 # Ignore SIGINT in child processes
265 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800266 pool = multiprocessing.Pool(multiprocessing.cpu_count())
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800267 signal.signal(signal.SIGINT, sigint_handler)
268
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800269 results = []
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800270 for locale in locales:
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800271 print(locale, end=' ', flush=True)
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800272 inputs = parse_locale_input_files(locale, json_dir)
273 output_dir = os.path.normpath(os.path.join(STAGE_DIR, 'locale', locale))
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800274 if not os.path.exists(output_dir):
275 os.makedirs(output_dir)
Matt Delco4c5580d2019-03-07 14:00:28 -0800276
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800277 for name, category in files.items():
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800278 # Ignore missing translation
279 if locale != 'en' and name not in inputs:
280 continue
281
282 # Write to text file
283 text_file = os.path.join(output_dir, name + '.txt')
284 with open(text_file, 'w', encoding='utf-8-sig') as f:
285 f.write(inputs[name] + '\n')
286
287 # Convert to PNG file
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800288 style = get_config_with_defaults(styles, category)
289 args = (
290 locale,
291 os.path.join(output_dir, '%s.txt' % name),
292 fonts.get(locale, default_font),
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800293 output_dir,
294 )
295 kwargs = {
Yu-Ping Wued95df32020-11-04 17:08:15 +0800296 'height': style[KEY_HEIGHT],
297 'max_width': style[KEY_MAX_WIDTH],
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800298 'dpi': dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800299 'bgcolor': style[KEY_BGCOLOR],
300 'fgcolor': style[KEY_FGCOLOR],
301 }
302 results.append(pool.apply_async(convert_text_to_png, args, kwargs))
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800303 pool.close()
Jes Klinke1687a992020-06-16 13:47:17 -0700304 if json_dir is not None:
305 shutil.rmtree(json_dir)
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800306 print()
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800307
308 try:
309 success = [r.get() for r in results]
310 except KeyboardInterrupt:
311 pool.terminate()
312 pool.join()
313 exit('Aborted by user')
314 else:
315 pool.join()
316 if not all(success):
317 exit('Failed to render some locales')
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800318
319
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800320def build_strings(formats, board_config):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800321 """Builds text strings."""
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800322 dpi = board_config[DPI_KEY]
323
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800324 # Convert glyphs
325 print('Converting glyphs...')
326 convert_glyphs()
327
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800328 # Convert generic (locale-independent) strings
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800329 files = formats[KEY_GENERIC_FILES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800330 styles = formats[KEY_STYLES]
331 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800332 default_font = fonts[KEY_DEFAULT]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800333
334 for input_file in glob.glob(os.path.join(STRINGS_DIR, '*.txt')):
335 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800336 category = files[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800337 style = get_config_with_defaults(styles, category)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800338 if not convert_text_to_png(None, input_file, default_font, STAGE_DIR,
339 height=style[KEY_HEIGHT],
340 max_width=style[KEY_MAX_WIDTH],
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800341 dpi=dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800342 bgcolor=style[KEY_BGCOLOR],
343 fgcolor=style[KEY_FGCOLOR]):
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800344 exit('Failed to convert text %s' % input_file)
345
346 # Convert localized strings
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800347 convert_localized_strings(formats, dpi)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800348
349
350def load_boards_config(filename):
351 """Loads the configuration of all boards from `filename`.
352
353 Args:
354 filename: File name of a YAML config file.
355
356 Returns:
357 A dictionary mapping each board name to its config.
358 """
359 with open(filename, 'rb') as file:
360 raw = yaml.load(file)
361
362 configs = {}
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800363 default = raw[KEY_DEFAULT]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800364 if not default:
365 raise BuildImageError('Default configuration is not found')
366 for boards, params in raw.items():
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800367 if boards == KEY_DEFAULT:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800368 continue
369 config = copy.deepcopy(default)
370 if params:
371 config.update(params)
372 for board in boards.replace(',', ' ').split():
373 configs[board] = config
374
375 return configs
376
377
378class Converter(object):
379 """Converter from assets, texts, URLs, and fonts to bitmap images.
380
381 Attributes:
382 ASSET_DIR (str): Directory of image assets.
383 DEFAULT_OUTPUT_EXT (str): Default output file extension.
384 DEFAULT_REPLACE_MAP (dict): Default mapping of file replacement. For
385 {'a': 'b'}, "a.*" will be converted to "b.*".
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800386 ASSET_MAX_COLORS (int): Maximum colors to use for converting image assets
387 to bitmaps.
388 DEFAULT_BACKGROUND (tuple): Default background color.
389 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
390 name and value is a tuple of RGB values.
391 """
392
393 ASSET_DIR = 'assets'
394 DEFAULT_OUTPUT_EXT = '.bmp'
395
396 DEFAULT_REPLACE_MAP = {
397 'rec_sel_desc1_no_sd': '',
398 'rec_sel_desc1_no_phone_no_sd': '',
399 'rec_disk_step1_desc0_no_sd': '',
400 'rec_to_dev_desc1_phyrec': '',
401 'rec_to_dev_desc1_power': '',
402 'navigate0_tablet': '',
403 'navigate1_tablet': '',
404 'nav-button_power': '',
405 'nav-button_volume_up': '',
406 'nav-button_volume_down': '',
407 'broken_desc_phyrec': '',
408 'broken_desc_detach': '',
409 }
410
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800411 # background colors
412 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
413 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
414 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
415 ASSET_MAX_COLORS = 128
416
417 BACKGROUND_COLORS = {
418 'ic_dropdown': LANG_HEADER_BACKGROUND,
419 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
420 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
421 'ic_globe': LANG_HEADER_BACKGROUND,
422 'ic_search_focus': LINK_SELECTED_BACKGROUND,
423 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
424 'ic_power_focus': LINK_SELECTED_BACKGROUND,
425 }
426
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800427 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800428 """Inits converter.
429
430 Args:
431 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800432 formats: A dictionary of string formats.
433 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800434 output: Output directory.
435 """
436 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800437 self.formats = formats
438 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800439 self.set_dirs(output)
440 self.set_screen()
441 self.set_replace_map()
442 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800443 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu354a7002021-01-07 16:07:02 +0800444 self.dpi_warning_printed = False
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800445
446 def set_dirs(self, output):
447 """Sets board output directory and stage directory.
448
449 Args:
450 output: Output directory.
451 """
452 self.output_dir = os.path.join(output, self.board)
453 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
454 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
455 self.stage_dir = os.path.join(output, '.stage')
456 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
457
458 def set_screen(self):
459 """Sets screen width and height."""
460 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
461
Yu-Ping Wue445e042020-11-19 15:53:42 +0800462 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800463 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800464 # Calculate `panel_stretch`. It's used to shrink images horizontally so
465 # that the resulting images will look proportional to the original image
466 # on the stretched display. If the display is not stretched, meaning the
467 # aspect ratio is same as the screen where images were rendered, no
468 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800469 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800470 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
471 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800472
Yu-Ping Wue445e042020-11-19 15:53:42 +0800473 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800474 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
475 'aspect ratio (%f). It indicates screen will be '
476 'shrunk horizontally. It is currently unsupported.'
477 % (panel_width / panel_height,
478 self.screen_width / self.screen_height))
479
480 # Set up square drawing area
481 self.canvas_px = min(self.screen_width, self.screen_height)
482
483 def set_replace_map(self):
484 """Sets a map replacing images.
485
486 For each (key, value), image 'key' will be replaced by image 'value'.
487 """
488 replace_map = self.DEFAULT_REPLACE_MAP.copy()
489
490 if os.getenv('DETACHABLE') == '1':
491 replace_map.update({
492 'nav-key_enter': 'nav-button_power',
493 'nav-key_up': 'nav-button_volume_up',
494 'nav-key_down': 'nav-button_volume_down',
495 'navigate0': 'navigate0_tablet',
496 'navigate1': 'navigate1_tablet',
497 'broken_desc': 'broken_desc_detach',
498 })
499
500 physical_presence = os.getenv('PHYSICAL_PRESENCE')
501 if physical_presence == 'recovery':
502 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_phyrec'
503 replace_map['broken_desc'] = 'broken_desc_phyrec'
504 elif physical_presence == 'power':
505 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_power'
506 elif physical_presence != 'keyboard':
507 raise BuildImageError('Invalid physical presence setting %s for board %s'
508 % (physical_presence, self.board))
509
510 if not self.config[SDCARD_KEY]:
511 replace_map.update({
512 'rec_sel_desc1': 'rec_sel_desc1_no_sd',
513 'rec_sel_desc1_no_phone': 'rec_sel_desc1_no_phone_no_sd',
514 'rec_disk_step1_desc0': 'rec_disk_step1_desc0_no_sd',
515 })
516
517 self.replace_map = replace_map
518
519 def set_locales(self):
520 """Sets a list of locales for which localized images are converted."""
521 # LOCALES environment variable can overwrite boards.yaml
522 env_locales = os.getenv('LOCALES')
523 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800524 if env_locales:
525 locales = env_locales.split()
526 else:
527 locales = self.config[LOCALES_KEY]
528 # Check rtl_locales are contained in locales.
529 unknown_rtl_locales = rtl_locales - set(locales)
530 if unknown_rtl_locales:
531 raise BuildImageError('Unknown locales %s in %s' %
532 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800533 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800534 for code in locales]
535
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800536 @classmethod
537 def get_text_colors(cls, dpi):
538 """Derive maximum text colors from `dpi`."""
539 if dpi < 64:
540 return 2
541 elif dpi < 72:
542 return 3
543 elif dpi < 80:
544 return 4
545 elif dpi < 96:
546 return 5
547 elif dpi < 112:
548 return 6
549 else:
550 return 7
551
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800552 def _to_px(self, length, num_lines=1):
553 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800554 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800555
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800556 def _get_png_height(self, png_file):
557 with Image.open(png_file) as image:
558 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800559
560 def get_num_lines(self, file, one_line_dir):
561 """Gets the number of lines of text in `file`."""
562 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800563 png_name = name + '.png'
564 multi_line_file = os.path.join(os.path.dirname(file), png_name)
565 one_line_file = os.path.join(one_line_dir, png_name)
566 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800567 # `multi_line_file` with `one_line_file`, where the latter is generated
568 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800569 height = self._get_png_height(multi_line_file)
570 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800571 return int(round(height / line_height))
572
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800573 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800574 background):
575 """Converts .svg file to .png file."""
576 background_hex = ''.join(format(x, '02x') for x in background)
577 # If the width/height of the SVG file is specified in points, the
578 # rsvg-convert command with default 90DPI will potentially cause the pixels
579 # at the right/bottom border of the output image to be transparent (or
580 # filled with the specified background color). This seems like an
581 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
582 # to avoid the scaling.
583 command = ['rsvg-convert',
584 '--background-color', "'#%s'" % background_hex,
585 '--dpi-x', '72',
586 '--dpi-y', '72',
587 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800588 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800589 if height_px <= 0:
590 raise BuildImageError('Height of %r <= 0 (%dpx)' %
591 (os.path.basename(svg_file), height_px))
592 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800593 command.append(svg_file)
594 subprocess.check_call(' '.join(command), shell=True)
595
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800596 def convert_to_bitmap(self, input_file, height, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800597 max_colors):
598 """Converts an image file `input_file` to a BMP file `output`."""
599 image = Image.open(input_file)
600
601 # Process alpha channel and transparency.
602 if image.mode == 'RGBA':
603 target = Image.new('RGB', image.size, background)
604 image.load() # required for image.split()
605 mask = image.split()[-1]
606 target.paste(image, mask=mask)
607 elif (image.mode == 'P') and ('transparency' in image.info):
608 exit('Sorry, PNG with RGBA palette is not supported.')
609 elif image.mode != 'RGB':
610 target = image.convert('RGB')
611 else:
612 target = image
613
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800614 width_px, height_px = image.size
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800615 max_height_px = self._to_px(height, num_lines)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800616 # If the image size is larger than what will be displayed at runtime,
617 # downscale it.
618 if height_px > max_height_px:
Yu-Ping Wu354a7002021-01-07 16:07:02 +0800619 if not self.dpi_warning_printed:
620 print('Reducing effective DPI to %d, limited by screen resolution' %
621 (self.config[DPI_KEY] * max_height_px // height_px))
622 self.dpi_warning_printed = True
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800623 height_px = max_height_px
624 width_px = height_px * image.size[0] // image.size[1]
625 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800626 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800627 width_px = int(width_px * self.panel_stretch)
628 new_size = width_px, height_px
629 if new_size != image.size:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800630 target = target.resize(new_size, Image.BICUBIC)
631
632 # Export and downsample color space.
633 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
634 ).save(output)
635
636 with open(output, 'rb+') as f:
637 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
638 f.write(bytearray([num_lines]))
639
Yu-Ping Wued95df32020-11-04 17:08:15 +0800640 def convert(self, files, output_dir, heights, max_widths, max_colors,
641 one_line_dir=None):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800642 """Converts file(s) to bitmap format."""
643 if not files:
644 raise BuildImageError('Unable to find file(s) to convert')
645
646 for file in files:
647 name, ext = os.path.splitext(os.path.basename(file))
648 output = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
649
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800650 if name in self.replace_map:
651 name = self.replace_map[name]
652 if not name:
653 continue
654 print('Replace: %s => %s' % (file, name))
655 file = os.path.join(os.path.dirname(file), name + ext)
656
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800657 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
658 height = heights[name]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800659 max_width = max_widths[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800660
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800661 # Determine num_lines in order to scale the image
Yu-Ping Wued95df32020-11-04 17:08:15 +0800662 if one_line_dir and max_width:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800663 num_lines = self.get_num_lines(file, one_line_dir)
664 else:
665 num_lines = 1
666
667 if ext == '.svg':
668 png_file = os.path.join(self.temp_dir, name + '.png')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800669 self.convert_svg_to_png(file, png_file, height, num_lines, background)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800670 file = png_file
671
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800672 self.convert_to_bitmap(file, height, num_lines, background, output,
673 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800674
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800675 def convert_sprite_images(self):
676 """Converts sprite images."""
677 names = self.formats[KEY_SPRITE_FILES]
678 styles = self.formats[KEY_STYLES]
679 # Check redundant images
680 for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)):
681 name, _ = os.path.splitext(os.path.basename(filename))
682 if name not in names:
683 raise BuildImageError('Sprite image %r not specified in %s' %
684 (filename, FORMAT_FILE))
685 # Convert images
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800686 files = []
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800687 heights = {}
688 for name, category in names.items():
689 style = get_config_with_defaults(styles, category)
690 files.append(os.path.join(self.ASSET_DIR, name + '.svg'))
691 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800692 max_widths = defaultdict(lambda: None)
693 self.convert(files, self.output_dir, heights, max_widths,
694 self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800695
696 def convert_generic_strings(self):
697 """Converts generic (locale-independent) strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800698 names = self.formats[KEY_GENERIC_FILES]
699 styles = self.formats[KEY_STYLES]
700 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800701 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800702 for name, category in names.items():
703 style = get_config_with_defaults(styles, category)
704 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800705 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800706
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800707 files = glob.glob(os.path.join(self.stage_dir, PNG_FILES))
Yu-Ping Wued95df32020-11-04 17:08:15 +0800708 self.convert(files, self.output_dir, heights, max_widths,
709 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800710
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800711 def _check_text_width(self, output_dir, heights, max_widths):
712 """Check if the width of text image will exceed canvas boundary."""
713 for filename in glob.glob(os.path.join(output_dir,
714 '*' + self.DEFAULT_OUTPUT_EXT)):
715 name, _ = os.path.splitext(os.path.basename(filename))
716 max_width = max_widths[name]
717 if not max_width:
718 continue
719 max_width_px = self._to_px(max_width)
720 with open(filename, 'rb') as f:
721 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
722 num_lines = f.read(1)[0]
723 height_px = self._to_px(heights[name] * num_lines)
724 with Image.open(filename) as image:
725 width_px = height_px * image.size[0] // image.size[1]
726 if width_px > max_width_px:
727 raise BuildImageError('%s: Image width %dpx greater than max width '
728 '%dpx' % (filename, width_px, max_width_px))
729
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800730 def _copy_missing_bitmaps(self):
731 """Copy missing (not yet translated) strings from locale 'en'."""
732 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
733 '*' + self.DEFAULT_OUTPUT_EXT))
734 for locale_info in self.locales:
735 locale = locale_info.code
736 if locale == 'en':
737 continue
738 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
739 for en_file in en_files:
740 filename = os.path.basename(en_file)
741 locale_file = os.path.join(ro_locale_dir, filename)
742 if not os.path.isfile(locale_file):
743 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
744 shutil.copyfile(en_file, locale_file)
745
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800746 def convert_localized_strings(self):
747 """Converts localized strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800748 names = self.formats[KEY_LOCALIZED_FILES].copy()
749 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800750 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800751 styles = self.formats[KEY_STYLES]
752 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800753 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800754 for name, category in names.items():
755 style = get_config_with_defaults(styles, category)
756 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800757 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800758
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800759 # Using stderr to report progress synchronously
760 print(' processing:', end='', file=sys.stderr, flush=True)
761 for locale_info in self.locales:
762 locale = locale_info.code
763 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
764 stage_locale_dir = os.path.join(STAGE_LOCALE_DIR, locale)
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800765 print(' ' + locale, end='', file=sys.stderr, flush=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800766 os.makedirs(ro_locale_dir)
767 self.convert(
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800768 glob.glob(os.path.join(stage_locale_dir, PNG_FILES)),
Yu-Ping Wued95df32020-11-04 17:08:15 +0800769 ro_locale_dir, heights, max_widths, self.text_max_colors,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800770 one_line_dir=os.path.join(stage_locale_dir, ONE_LINE_DIR))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800771 self._check_text_width(ro_locale_dir, heights, max_widths)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800772 print(file=sys.stderr)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800773 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800774
775 def move_language_images(self):
776 """Renames language bitmaps and move to self.output_dir.
777
778 The directory self.output_dir contains locale-independent images, and is
779 used for creating vbgfx.bin by archive_images.py.
780 """
781 for locale_info in self.locales:
782 locale = locale_info.code
783 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
784 old_file = os.path.join(ro_locale_dir, 'language.bmp')
785 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
786 if os.path.exists(new_file):
787 raise BuildImageError('File already exists: %s' % new_file)
788 shutil.move(old_file, new_file)
789
790 def convert_fonts(self):
791 """Converts font images"""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800792 heights = defaultdict(lambda: DEFAULT_GLYPH_HEIGHT)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800793 max_widths = defaultdict(lambda: None)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800794 files = glob.glob(os.path.join(STAGE_FONT_DIR, SVG_FILES))
795 font_output_dir = os.path.join(self.output_dir, 'font')
796 os.makedirs(font_output_dir)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800797 self.convert(files, font_output_dir, heights, max_widths,
798 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800799
800 def copy_images_to_rw(self):
801 """Copies localized images specified in boards.yaml for RW override."""
802 if not self.config[RW_OVERRIDE_KEY]:
803 print(' No localized images are specified for RW, skipping')
804 return
805
806 for locale_info in self.locales:
807 locale = locale_info.code
808 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
809 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
810 os.makedirs(rw_locale_dir)
811
812 for name in self.config[RW_OVERRIDE_KEY]:
813 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
814 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
815 shutil.copyfile(ro_src, rw_dst)
816
817 def create_locale_list(self):
818 """Creates locale list as a CSV file.
819
820 Each line in the file is of format "code,rtl", where
821 - "code": language code of the locale
822 - "rtl": "1" for right-to-left language, "0" otherwise
823 """
824 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
825 for locale_info in self.locales:
826 f.write('{},{}\n'.format(locale_info.code,
827 int(locale_info.rtl)))
828
829 def build(self):
830 """Builds all images required by a board."""
831 # Clean up output directory
832 if os.path.exists(self.output_dir):
833 shutil.rmtree(self.output_dir)
834 os.makedirs(self.output_dir)
835
836 if not os.path.exists(self.stage_dir):
837 raise BuildImageError('Missing stage folder. Run make in strings dir.')
838
839 # Clean up temp directory
840 if os.path.exists(self.temp_dir):
841 shutil.rmtree(self.temp_dir)
842 os.makedirs(self.temp_dir)
843
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800844 print('Converting sprite images...')
845 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800846
847 print('Converting generic strings...')
848 self.convert_generic_strings()
849
850 print('Converting localized strings...')
851 self.convert_localized_strings()
852
853 print('Moving language images to locale-independent directory...')
854 self.move_language_images()
855
856 print('Creating locale list file...')
857 self.create_locale_list()
858
859 print('Converting fonts...')
860 self.convert_fonts()
861
862 print('Copying specified images to RW packing directory...')
863 self.copy_images_to_rw()
864
865
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800866def main():
867 """Builds bitmaps for firmware screens."""
868 parser = argparse.ArgumentParser()
869 parser.add_argument('board', help='Target board')
870 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800871 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800872
873 with open(FORMAT_FILE, encoding='utf-8') as f:
874 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800875 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
876
877 # TODO(yupingso): Put everything into Converter class
878 print('Building for ' + board)
879 build_strings(formats, board_config)
880 converter = Converter(board, formats, board_config, OUTPUT_DIR)
881 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800882
883
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800884if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800885 main()