blob: 601abe59fff43f076ef3cb2fcf41727282a2468e [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 Wucc86d6a2020-11-27 12:48:19 +080080GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080081
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080082LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080083
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080084
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080085class DataError(Exception):
86 pass
87
88
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080089class BuildImageError(Exception):
90 """The exception class for all errors generated during build image process."""
91
92
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080093def 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 Wu177f12c2020-11-04 15:55:37 +0800100 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800101 config.update(configs.get(key, {}))
102 return config
103
104
Yu-Ping Wued95df32020-11-04 17:08:15 +0800105def convert_text_to_png(locale, input_file, font, output_dir, height=None,
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800106 max_width=None, dpi=None, bgcolor='#000000',
107 fgcolor='#ffffff',
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800108 **options):
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800109 """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 Wued95df32020-11-04 17:08:15 +0800116 height: Height.
117 max_width: Maximum width.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800118 output_dir: Directory to generate image files.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800119 bgcolor: Background color (#rrggbb).
120 fgcolor: Foreground color (#rrggbb).
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800121 **options: Other options to be added.
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800122 """
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 Wue66a7b02020-11-19 15:18:08 +0800129 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 Wu11027f02020-10-14 17:35:42 +0800134 command.append('--point=%r' % font_size)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800135 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800136 # 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 Wued95df32020-11-04 17:08:15 +0800142 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800143 if dpi:
144 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800145 command.append('--margin=0')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800146 command.append('--bgcolor="%s"' % bgcolor)
147 command.append('--color="%s"' % fgcolor)
148
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800149 for k, v in options.items():
150 command.append('--%s="%s"' % (k, v))
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800151 command.append(input_file)
152
153 return subprocess.call(' '.join(command), shell=True,
154 stdout=subprocess.PIPE) == 0
155
156
157def convert_glyphs():
158 """Converts glyphs of ascii characters."""
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800159 os.makedirs(STAGE_FONT_DIR, exist_ok=True)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800160 # Remove the extra whitespace at the top/bottom within the glyphs
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800161 for c in range(ord(' '), ord('~') + 1):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800162 txt_file = os.path.join(STAGE_FONT_DIR, f'idx{c:03d}_{c:02x}.txt')
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800163 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 Wucc86d6a2020-11-27 12:48:19 +0800167 convert_text_to_png(None, txt_file, GLYPH_FONT, STAGE_FONT_DIR)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800168
169
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800170def 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 Klinke1687a992020-06-16 13:47:17 -0700180 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800181 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800182 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700183 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 Wuae79af62020-09-23 16:48:06 +0800194
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800195def 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 Wu8f633b82020-09-22 14:27:57 +0800208 for input_file in glob.glob(os.path.join(LOCALE_DIR, locale, "*.txt")):
Mathew King89d48c62019-02-15 10:08:39 -0700209 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800210 with open(input_file, 'r', encoding='utf-8-sig') as f:
Mathew King89d48c62019-02-15 10:08:39 -0700211 result[name] = f.read().strip()
Shelley Chen2f616ac2017-05-22 13:19:40 -0700212
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800213 return result
214
215
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800216def convert_localized_strings(formats, dpi):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800217 """Converts localized strings."""
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800218 # Make a copy of formats to avoid modifying it
219 formats = copy.deepcopy(formats)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800220
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800221 env_locales = os.getenv('LOCALES')
222 if env_locales:
223 locales = env_locales.split()
224 else:
225 locales = formats[KEY_LOCALES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800226
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800227 files = formats[KEY_LOCALIZED_FILES]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800228 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800229 files.update(formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800230
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800231 styles = formats[KEY_STYLES]
232 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800233 default_font = fonts[KEY_DEFAULT]
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800234
Yu-Ping Wu51940352020-09-17 08:48:55 +0800235 # 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 Klinke1687a992020-06-16 13:47:17 -0700243
Yu-Ping Wu51940352020-09-17 08:48:55 +0800244 # Create a temporary directory to place the translation output from grit in.
245 json_dir = tempfile.mkdtemp()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800246
Yu-Ping Wu51940352020-09-17 08:48:55 +0800247 # 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 Wu8f633b82020-09-22 14:27:57 +0800252 '-i', os.path.join(LOCALE_DIR, STRINGS_GRD_FILE),
Yu-Ping Wu51940352020-09-17 08:48:55 +0800253 'build',
254 '-o', os.path.join(json_dir)
255 ])
Jes Klinke1687a992020-06-16 13:47:17 -0700256
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800257 # Ignore SIGINT in child processes
258 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800259 pool = multiprocessing.Pool(multiprocessing.cpu_count())
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800260 signal.signal(signal.SIGINT, sigint_handler)
261
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800262 results = []
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800263 for locale in locales:
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800264 print(locale, end=' ', flush=True)
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800265 inputs = parse_locale_input_files(locale, json_dir)
266 output_dir = os.path.normpath(os.path.join(STAGE_DIR, 'locale', locale))
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800267 if not os.path.exists(output_dir):
268 os.makedirs(output_dir)
Matt Delco4c5580d2019-03-07 14:00:28 -0800269
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800270 for name, category in files.items():
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800271 # 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 Wu8c8bfc72020-10-27 16:19:34 +0800281 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 Wu8c8bfc72020-10-27 16:19:34 +0800286 output_dir,
287 )
288 kwargs = {
Yu-Ping Wued95df32020-11-04 17:08:15 +0800289 'height': style[KEY_HEIGHT],
290 'max_width': style[KEY_MAX_WIDTH],
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800291 'dpi': dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800292 'bgcolor': style[KEY_BGCOLOR],
293 'fgcolor': style[KEY_FGCOLOR],
294 }
295 results.append(pool.apply_async(convert_text_to_png, args, kwargs))
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800296 pool.close()
Jes Klinke1687a992020-06-16 13:47:17 -0700297 if json_dir is not None:
298 shutil.rmtree(json_dir)
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800299 print()
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800300
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 Lin707e2ef2013-08-06 10:20:04 +0800311
312
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800313def build_strings(formats, board_config):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800314 """Builds text strings."""
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800315 dpi = board_config[DPI_KEY]
316
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800317 # Convert glyphs
318 print('Converting glyphs...')
319 convert_glyphs()
320
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800321 # Convert generic (locale-independent) strings
Yu-Ping Wu338f0832020-10-23 16:14:40 +0800322 files = formats[KEY_GENERIC_FILES]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800323 styles = formats[KEY_STYLES]
324 fonts = formats[KEY_FONTS]
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800325 default_font = fonts[KEY_DEFAULT]
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800326
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 Wu338f0832020-10-23 16:14:40 +0800329 category = files[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800330 style = get_config_with_defaults(styles, category)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800331 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 Wue66a7b02020-11-19 15:18:08 +0800334 dpi=dpi,
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800335 bgcolor=style[KEY_BGCOLOR],
336 fgcolor=style[KEY_FGCOLOR]):
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800337 exit('Failed to convert text %s' % input_file)
338
339 # Convert localized strings
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800340 convert_localized_strings(formats, dpi)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800341
342
343def 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 Wu177f12c2020-11-04 15:55:37 +0800356 default = raw[KEY_DEFAULT]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800357 if not default:
358 raise BuildImageError('Default configuration is not found')
359 for boards, params in raw.items():
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800360 if boards == KEY_DEFAULT:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800361 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
371class 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 Wu177f12c2020-11-04 15:55:37 +0800379 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 Wu8c8bfc72020-10-27 16:19:34 +0800382 DEFAULT_FONT_HEIGHT (tuple): Height of the font images.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800383 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 Wu177f12c2020-11-04 15:55:37 +0800409 SCALE_BASE = 1000
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800410 DEFAULT_FONT_HEIGHT = 20
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800411
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 Wu8c8bfc72020-10-27 16:19:34 +0800428 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800429 """Inits converter.
430
431 Args:
432 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800433 formats: A dictionary of string formats.
434 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800435 output: Output directory.
436 """
437 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800438 self.formats = formats
439 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800440 self.set_dirs(output)
441 self.set_screen()
442 self.set_replace_map()
443 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800444 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu354a7002021-01-07 16:07:02 +0800445 self.dpi_warning_printed = False
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800446
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 Wue445e042020-11-19 15:53:42 +0800463 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800464 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800465 # 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 Wu6e4d3892020-10-19 14:09:37 +0800470 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800471 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
472 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800473
Yu-Ping Wue445e042020-11-19 15:53:42 +0800474 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800475 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 Wu6e4d3892020-10-19 14:09:37 +0800525 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 Wuabb9afb2020-10-27 17:15:22 +0800534 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800535 for code in locales]
536
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800537 @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 Wu08defcc2020-05-07 16:21:03 +0800553 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 Wue66a7b02020-11-19 15:18:08 +0800557 def _get_png_height(self, png_file):
558 with Image.open(png_file) as image:
559 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800560
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 Wue66a7b02020-11-19 15:18:08 +0800564 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 Wu6e4d3892020-10-19 14:09:37 +0800568 # `multi_line_file` with `one_line_file`, where the latter is generated
569 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800570 height = self._get_png_height(multi_line_file)
571 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800572 return int(round(height / line_height))
573
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800574 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800575 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 Wu08defcc2020-05-07 16:21:03 +0800589 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800590 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 Wu6e4d3892020-10-19 14:09:37 +0800594 command.append(svg_file)
595 subprocess.check_call(' '.join(command), shell=True)
596
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800597 def convert_to_bitmap(self, input_file, height, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800598 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 Wue66a7b02020-11-19 15:18:08 +0800615 width_px, height_px = image.size
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800616 max_height_px = self._to_px(height, num_lines)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800617 # 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 Wu354a7002021-01-07 16:07:02 +0800620 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 Wue66a7b02020-11-19 15:18:08 +0800624 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 Wue445e042020-11-19 15:53:42 +0800627 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800628 width_px = int(width_px * self.panel_stretch)
629 new_size = width_px, height_px
630 if new_size != image.size:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800631 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 Wued95df32020-11-04 17:08:15 +0800641 def convert(self, files, output_dir, heights, max_widths, max_colors,
642 one_line_dir=None):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800643 """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 Wu6e4d3892020-10-19 14:09:37 +0800651 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 Wu8c8bfc72020-10-27 16:19:34 +0800658 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
659 height = heights[name]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800660 max_width = max_widths[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800661
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800662 # Determine num_lines in order to scale the image
Yu-Ping Wued95df32020-11-04 17:08:15 +0800663 if one_line_dir and max_width:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800664 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 Wu8c8bfc72020-10-27 16:19:34 +0800670 self.convert_svg_to_png(file, png_file, height, num_lines, background)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800671 file = png_file
672
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800673 self.convert_to_bitmap(file, height, num_lines, background, output,
674 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800675
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800676 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 Wu6e4d3892020-10-19 14:09:37 +0800687 files = []
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800688 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 Wued95df32020-11-04 17:08:15 +0800693 max_widths = defaultdict(lambda: None)
694 self.convert(files, self.output_dir, heights, max_widths,
695 self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800696
697 def convert_generic_strings(self):
698 """Converts generic (locale-independent) strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800699 names = self.formats[KEY_GENERIC_FILES]
700 styles = self.formats[KEY_STYLES]
701 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800702 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800703 for name, category in names.items():
704 style = get_config_with_defaults(styles, category)
705 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800706 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800707
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800708 files = glob.glob(os.path.join(self.stage_dir, PNG_FILES))
Yu-Ping Wued95df32020-11-04 17:08:15 +0800709 self.convert(files, self.output_dir, heights, max_widths,
710 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800711
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800712 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 Wu703dcfd2021-01-08 10:52:10 +0800731 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 Wu6e4d3892020-10-19 14:09:37 +0800747 def convert_localized_strings(self):
748 """Converts localized strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800749 names = self.formats[KEY_LOCALIZED_FILES].copy()
750 if DIAGNOSTIC_UI:
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800751 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800752 styles = self.formats[KEY_STYLES]
753 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800754 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800755 for name, category in names.items():
756 style = get_config_with_defaults(styles, category)
757 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800758 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800759
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800760 # 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 Wuabb9afb2020-10-27 17:15:22 +0800766 print(' ' + locale, end='', file=sys.stderr, flush=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800767 os.makedirs(ro_locale_dir)
768 self.convert(
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800769 glob.glob(os.path.join(stage_locale_dir, PNG_FILES)),
Yu-Ping Wued95df32020-11-04 17:08:15 +0800770 ro_locale_dir, heights, max_widths, self.text_max_colors,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800771 one_line_dir=os.path.join(stage_locale_dir, ONE_LINE_DIR))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800772 self._check_text_width(ro_locale_dir, heights, max_widths)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800773 print(file=sys.stderr)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800774 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800775
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 Wu8c8bfc72020-10-27 16:19:34 +0800793 heights = defaultdict(lambda: self.DEFAULT_FONT_HEIGHT)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800794 max_widths = defaultdict(lambda: None)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800795 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 Wued95df32020-11-04 17:08:15 +0800798 self.convert(files, font_output_dir, heights, max_widths,
799 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800800
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 Wu177f12c2020-11-04 15:55:37 +0800845 print('Converting sprite images...')
846 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800847
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 Wu6e4d3892020-10-19 14:09:37 +0800867def 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 Wue66a7b02020-11-19 15:18:08 +0800872 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800873
874 with open(FORMAT_FILE, encoding='utf-8') as f:
875 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800876 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 Wu7f6639a2020-09-28 15:31:35 +0800883
884
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800885if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800886 main()