blob: 1e50bb487736fec64ec0ea35b9906c297beb810f [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
Yu-Ping Wu49606eb2021-03-03 22:43:19 +08008from collections import defaultdict, namedtuple, Counter
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +08009import 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
Jes Klinke1687a992020-06-16 13:47:17 -070019import tempfile
Hung-Te Lin04addcc2015-03-23 18:43:30 +080020
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080021import yaml
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080022from PIL import Image
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080023
24SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080025
26STRINGS_GRD_FILE = 'firmware_strings.grd'
27STRINGS_JSON_FILE_TMPL = '{}.json'
28FORMAT_FILE = 'format.yaml'
29BOARDS_CONFIG_FILE = 'boards.yaml'
30
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080031OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build'))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080032
33ONE_LINE_DIR = 'one_line'
34SVG_FILES = '*.svg'
35PNG_FILES = '*.png'
36
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080037DIAGNOSTIC_UI = os.getenv('DIAGNOSTIC_UI') == '1'
38
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080039# String format YAML key names.
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080040KEY_DEFAULT = '_DEFAULT_'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080041KEY_LOCALES = 'locales'
Yu-Ping Wu338f0832020-10-23 16:14:40 +080042KEY_GENERIC_FILES = 'generic_files'
43KEY_LOCALIZED_FILES = 'localized_files'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080044KEY_DIAGNOSTIC_FILES = 'diagnostic_files'
45KEY_SPRITE_FILES = 'sprite_files'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080046KEY_STYLES = 'styles'
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080047KEY_BGCOLOR = 'bgcolor'
48KEY_FGCOLOR = 'fgcolor'
49KEY_HEIGHT = 'height'
Yu-Ping Wued95df32020-11-04 17:08:15 +080050KEY_MAX_WIDTH = 'max_width'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080051KEY_FONTS = 'fonts'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080052
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080053# Board config YAML key names.
54SCREEN_KEY = 'screen'
55PANEL_KEY = 'panel'
56SDCARD_KEY = 'sdcard'
57BAD_USB3_KEY = 'bad_usb3'
Yu-Ping Wue66a7b02020-11-19 15:18:08 +080058DPI_KEY = 'dpi'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080059LOCALES_KEY = 'locales'
60RTL_KEY = 'rtl'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080061RW_OVERRIDE_KEY = 'rw_override'
62
63BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080064
Jes Klinke1687a992020-06-16 13:47:17 -070065# Regular expressions used to eliminate spurious spaces and newlines in
66# translation strings.
67NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
68NEWLINE_REPLACEMENT = r'\1 \2'
69CRLF_PATTERN = re.compile(r'\r\n')
70MULTIBLANK_PATTERN = re.compile(r' *')
71
Yu-Ping Wu3d07a062021-01-26 18:10:32 +080072# The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if
73# `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also
74# see the 'styles' section in format.yaml.
75SCALE_BASE = 1000
76DEFAULT_GLYPH_HEIGHT = 20
77
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +080078GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080079
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080080LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080081
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080082
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080083class DataError(Exception):
84 pass
85
86
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080087class BuildImageError(Exception):
88 """The exception class for all errors generated during build image process."""
89
90
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080091def get_config_with_defaults(configs, key):
92 """Gets config of `key` from `configs`.
93
94 If `key` is not present in `configs`, the default config will be returned.
95 Similarly, if some config values are missing for `key`, the default ones will
96 be used.
97 """
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080098 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080099 config.update(configs.get(key, {}))
100 return config
101
102
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800103def load_boards_config(filename):
104 """Loads the configuration of all boards from `filename`.
105
106 Args:
107 filename: File name of a YAML config file.
108
109 Returns:
110 A dictionary mapping each board name to its config.
111 """
112 with open(filename, 'rb') as file:
113 raw = yaml.load(file)
114
115 configs = {}
116 default = raw[KEY_DEFAULT]
117 if not default:
118 raise BuildImageError('Default configuration is not found')
119 for boards, params in raw.items():
120 if boards == KEY_DEFAULT:
121 continue
122 config = copy.deepcopy(default)
123 if params:
124 config.update(params)
125 for board in boards.replace(',', ' ').split():
126 configs[board] = config
127
128 return configs
129
130
131def check_fonts(fonts):
132 """Check if all fonts are available."""
133 for locale, font in fonts.items():
134 if subprocess.run(['fc-list', '-q', font]).returncode != 0:
135 raise BuildImageError('Font %r not found for locale %r'
136 % (font, locale))
137
138
Yu-Ping Wu97046932021-01-25 17:38:56 +0800139def run_pango_view(input_file, output_file, locale, font, height, max_width,
140 dpi, bgcolor, fgcolor, hinting='full'):
141 """Run pango-view."""
142 command = ['pango-view', '-q']
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800143 if locale:
Yu-Ping Wu97046932021-01-25 17:38:56 +0800144 command += ['--language', locale]
145
146 # Font size should be proportional to the height. Here we use 2 as the
147 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
148 # will be roughly equivalent to setting the screen resolution to 1366x768.
149 font_size = height / 2
150 font_spec = '%s %r' % (font, font_size)
151 command += ['--font', font_spec]
152
Yu-Ping Wued95df32020-11-04 17:08:15 +0800153 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800154 # When converting text to PNG by pango-view, the ratio of image height to
155 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
156 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
157 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
158 # the calculation of `font_size` above.
159 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800160 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800161 if dpi:
162 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800163 command.append('--margin=0')
Yu-Ping Wu97046932021-01-25 17:38:56 +0800164 command += ['--background', bgcolor]
165 command += ['--foreground', fgcolor]
166 command += ['--hinting', hinting]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800167
Yu-Ping Wu97046932021-01-25 17:38:56 +0800168 command += ['--output', output_file]
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800169 command.append(input_file)
170
Yu-Ping Wu97046932021-01-25 17:38:56 +0800171 subprocess.check_call(command, stdout=subprocess.PIPE)
172
173
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800174def parse_locale_json_file(locale, json_dir):
175 """Parses given firmware string json file.
176
177 Args:
178 locale: The name of the locale, e.g. "da" or "pt-BR".
179 json_dir: Directory containing json output from grit.
180
181 Returns:
182 A dictionary for mapping of "name to content" for files to be generated.
183 """
Jes Klinke1687a992020-06-16 13:47:17 -0700184 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800185 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800186 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700187 for tag, msgdict in json.load(input_file).items():
188 msgtext = msgdict['message']
189 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
190 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
191 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
192 # Strip any trailing whitespace. A trailing newline appears to make
193 # Pango report a larger layout size than what's actually visible.
194 msgtext = msgtext.strip()
195 result[tag] = msgtext
196 return result
197
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800198
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800199class Converter(object):
200 """Converter from assets, texts, URLs, and fonts to bitmap images.
201
202 Attributes:
203 ASSET_DIR (str): Directory of image assets.
204 DEFAULT_OUTPUT_EXT (str): Default output file extension.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800205 ASSET_MAX_COLORS (int): Maximum colors to use for converting image assets
206 to bitmaps.
207 DEFAULT_BACKGROUND (tuple): Default background color.
208 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
209 name and value is a tuple of RGB values.
210 """
211
212 ASSET_DIR = 'assets'
213 DEFAULT_OUTPUT_EXT = '.bmp'
214
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800215 # background colors
216 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
217 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
218 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
219 ASSET_MAX_COLORS = 128
220
221 BACKGROUND_COLORS = {
222 'ic_dropdown': LANG_HEADER_BACKGROUND,
223 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
224 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
225 'ic_globe': LANG_HEADER_BACKGROUND,
226 'ic_search_focus': LINK_SELECTED_BACKGROUND,
227 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
228 'ic_power_focus': LINK_SELECTED_BACKGROUND,
229 }
230
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800231 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800232 """Inits converter.
233
234 Args:
235 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800236 formats: A dictionary of string formats.
237 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800238 output: Output directory.
239 """
240 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800241 self.formats = formats
242 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800243 self.set_dirs(output)
244 self.set_screen()
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800245 self.set_rename_map()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800246 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800247 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800248
249 def set_dirs(self, output):
250 """Sets board output directory and stage directory.
251
252 Args:
253 output: Output directory.
254 """
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800255 self.strings_dir = os.path.join(SCRIPT_BASE, 'strings')
256 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800257 self.output_dir = os.path.join(output, self.board)
258 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
259 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
260 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800261 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
262 self.stage_font_dir = os.path.join(self.stage_dir, 'font')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800263 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
264
265 def set_screen(self):
266 """Sets screen width and height."""
267 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
268
Yu-Ping Wue445e042020-11-19 15:53:42 +0800269 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800270 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800271 # Calculate `panel_stretch`. It's used to shrink images horizontally so
272 # that the resulting images will look proportional to the original image
273 # on the stretched display. If the display is not stretched, meaning the
274 # aspect ratio is same as the screen where images were rendered, no
275 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800276 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800277 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
278 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800279
Yu-Ping Wue445e042020-11-19 15:53:42 +0800280 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800281 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
282 'aspect ratio (%f). It indicates screen will be '
283 'shrunk horizontally. It is currently unsupported.'
284 % (panel_width / panel_height,
285 self.screen_width / self.screen_height))
286
287 # Set up square drawing area
288 self.canvas_px = min(self.screen_width, self.screen_height)
289
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800290 def set_rename_map(self):
291 """Initializes a dict `self.rename_map` for image renaming.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800292
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800293 For each items in the dict, image `key` will be renamed to `value`.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800294 """
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800295 is_detachable = os.getenv('DETACHABLE') == '1'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800296 physical_presence = os.getenv('PHYSICAL_PRESENCE')
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800297 rename_map = {}
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800298
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800299 # Navigation instructions
300 if is_detachable:
301 rename_map.update({
302 'nav-button_power': 'nav-key_enter',
303 'nav-button_volume_up': 'nav-key_up',
304 'nav-button_volume_down': 'nav-key_down',
305 'navigate0_tablet': 'navigate0',
306 'navigate1_tablet': 'navigate1',
307 })
308 else:
309 rename_map.update({
310 'nav-button_power': None,
311 'nav-button_volume_up': None,
312 'nav-button_volume_down': None,
313 'navigate0_tablet': None,
314 'navigate1_tablet': None,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800315 })
316
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800317 # Physical presence confirmation
318 if physical_presence == 'recovery':
319 rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1'
320 rename_map['rec_to_dev_desc1_power'] = None
321 elif physical_presence == 'power':
322 rename_map['rec_to_dev_desc1_phyrec'] = None
323 rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1'
324 else:
325 rename_map['rec_to_dev_desc1_phyrec'] = None
326 rename_map['rec_to_dev_desc1_power'] = None
327 if physical_presence != 'keyboard':
328 raise BuildImageError('Invalid physical presence setting %s for board '
329 '%s' % (physical_presence, self.board))
330
331 # Broken screen
332 if physical_presence == 'recovery':
333 rename_map['broken_desc_phyrec'] = 'broken_desc'
334 rename_map['broken_desc_detach'] = None
335 elif is_detachable:
336 rename_map['broken_desc_phyrec'] = None
337 rename_map['broken_desc_detach'] = 'broken_desc'
338 else:
339 rename_map['broken_desc_phyrec'] = None
340 rename_map['broken_desc_detach'] = None
341
342 # SD card
343 if not self.config[SDCARD_KEY]:
344 rename_map.update({
345 'rec_sel_desc1_no_sd': 'rec_sel_desc1',
346 'rec_sel_desc1_no_phone_no_sd': 'rec_sel_desc1_no_phone',
347 'rec_disk_step1_desc0_no_sd': 'rec_disk_step1_desc0',
348 })
349 else:
350 rename_map.update({
351 'rec_sel_desc1_no_sd': None,
352 'rec_sel_desc1_no_phone_no_sd': None,
353 'rec_disk_step1_desc0_no_sd': None,
354 })
355
356 # Check for duplicate new names
357 new_names = list(new_name for new_name in rename_map.values() if new_name)
358 if len(set(new_names)) != len(new_names):
359 raise BuildImageError('Duplicate values found in rename_map')
360
361 # Map new_name to None to skip image generation for it
362 for new_name in new_names:
363 if new_name not in rename_map:
364 rename_map[new_name] = None
365
366 # Print mapping
367 print('Rename map:')
368 for name, new_name in sorted(rename_map.items()):
369 print(' %s => %s' % (name, new_name))
370
371 self.rename_map = rename_map
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800372
373 def set_locales(self):
374 """Sets a list of locales for which localized images are converted."""
375 # LOCALES environment variable can overwrite boards.yaml
376 env_locales = os.getenv('LOCALES')
377 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800378 if env_locales:
379 locales = env_locales.split()
380 else:
381 locales = self.config[LOCALES_KEY]
382 # Check rtl_locales are contained in locales.
383 unknown_rtl_locales = rtl_locales - set(locales)
384 if unknown_rtl_locales:
385 raise BuildImageError('Unknown locales %s in %s' %
386 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800387 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800388 for code in locales]
389
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800390 @classmethod
391 def get_text_colors(cls, dpi):
392 """Derive maximum text colors from `dpi`."""
393 if dpi < 64:
394 return 2
395 elif dpi < 72:
396 return 3
397 elif dpi < 80:
398 return 4
399 elif dpi < 96:
400 return 5
401 elif dpi < 112:
402 return 6
403 else:
404 return 7
405
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800406 def _to_px(self, length, num_lines=1):
407 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800408 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800409
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800410 def _get_png_height(self, png_file):
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800411 # With small DPI, pango-view may generate an empty file
412 if os.path.getsize(png_file) == 0:
413 return 0
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800414 with Image.open(png_file) as image:
415 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800416
417 def get_num_lines(self, file, one_line_dir):
418 """Gets the number of lines of text in `file`."""
419 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800420 png_name = name + '.png'
421 multi_line_file = os.path.join(os.path.dirname(file), png_name)
422 one_line_file = os.path.join(one_line_dir, png_name)
423 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800424 # `multi_line_file` with `one_line_file`, where the latter is generated
425 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800426 height = self._get_png_height(multi_line_file)
427 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800428 return int(round(height / line_height))
429
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800430 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800431 background):
432 """Converts .svg file to .png file."""
433 background_hex = ''.join(format(x, '02x') for x in background)
434 # If the width/height of the SVG file is specified in points, the
435 # rsvg-convert command with default 90DPI will potentially cause the pixels
436 # at the right/bottom border of the output image to be transparent (or
437 # filled with the specified background color). This seems like an
438 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
439 # to avoid the scaling.
440 command = ['rsvg-convert',
441 '--background-color', "'#%s'" % background_hex,
442 '--dpi-x', '72',
443 '--dpi-y', '72',
444 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800445 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800446 if height_px <= 0:
447 raise BuildImageError('Height of %r <= 0 (%dpx)' %
448 (os.path.basename(svg_file), height_px))
449 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800450 command.append(svg_file)
451 subprocess.check_call(' '.join(command), shell=True)
452
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800453 def convert_to_bitmap(self, input_file, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800454 max_colors):
455 """Converts an image file `input_file` to a BMP file `output`."""
456 image = Image.open(input_file)
457
458 # Process alpha channel and transparency.
459 if image.mode == 'RGBA':
460 target = Image.new('RGB', image.size, background)
461 image.load() # required for image.split()
462 mask = image.split()[-1]
463 target.paste(image, mask=mask)
464 elif (image.mode == 'P') and ('transparency' in image.info):
465 exit('Sorry, PNG with RGBA palette is not supported.')
466 elif image.mode != 'RGB':
467 target = image.convert('RGB')
468 else:
469 target = image
470
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800471 width_px, height_px = image.size
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800472 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800473 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800474 width_px = int(width_px * self.panel_stretch)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800475 target = target.resize((width_px, height_px), Image.BICUBIC)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800476
477 # Export and downsample color space.
478 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
479 ).save(output)
480
481 with open(output, 'rb+') as f:
482 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
483 f.write(bytearray([num_lines]))
484
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800485 def convert(self, file, output_dir, height, max_width, max_colors,
Yu-Ping Wued95df32020-11-04 17:08:15 +0800486 one_line_dir=None):
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800487 """Converts image `file` to bitmap format."""
488 name, ext = os.path.splitext(os.path.basename(file))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800489
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800490 if name in self.rename_map:
491 new_name = self.rename_map[name]
492 if not new_name:
493 return
494 else:
495 new_name = name
496 output = os.path.join(output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800497
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800498 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800499
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800500 # Determine num_lines in order to scale the image
501 if one_line_dir and max_width:
502 num_lines = self.get_num_lines(file, one_line_dir)
503 else:
504 num_lines = 1
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800505
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800506 if ext == '.svg':
507 png_file = os.path.join(self.temp_dir, name + '.png')
508 self.convert_svg_to_png(file, png_file, height, num_lines, background)
509 file = png_file
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800510
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800511 return self.convert_to_bitmap(file, num_lines, background, output,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800512 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800513
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800514 def _bisect_dpi(self, max_dpi, initial_dpi, max_height_px, get_height):
515 """Bisects to find the DPI that produces image height `max_height_px`.
516
517 Args:
518 max_dpi: Maximum DPI for binary search.
519 initial_dpi: Initial DPI to try with in binary search.
520 If specified, the value must be no larger than `max_dpi`.
521 max_height_px: Maximum (target) height to search for.
522 get_height: A function converting DPI to height. The function is called
523 once before returning.
524
525 Returns:
526 The best integer DPI within [1, `max_dpi`].
527 """
528
529 min_dpi = 1
530 first_iter = True
531
532 min_height_px = get_height(min_dpi)
533 if min_height_px > max_height_px:
534 # For some font such as "Noto Sans CJK SC", the generated height cannot
535 # go below a certain value. In this case, find max DPI with
536 # height_px <= min_height_px.
537 while min_dpi < max_dpi:
538 if first_iter and initial_dpi:
539 mid_dpi = initial_dpi
540 else:
541 mid_dpi = (min_dpi + max_dpi + 1) // 2
542 height_px = get_height(mid_dpi)
543 if height_px > min_height_px:
544 max_dpi = mid_dpi - 1
545 else:
546 min_dpi = mid_dpi
547 first_iter = False
548 get_height(max_dpi)
549 return max_dpi
550
551 # Find min DPI with height_px == max_height_px
552 while min_dpi < max_dpi:
553 if first_iter and initial_dpi:
554 mid_dpi = initial_dpi
555 else:
556 mid_dpi = (min_dpi + max_dpi) // 2
557 height_px = get_height(mid_dpi)
558 if height_px == max_height_px:
559 return mid_dpi
560 elif height_px < max_height_px:
561 min_dpi = mid_dpi + 1
562 else:
563 max_dpi = mid_dpi
564 first_iter = False
565 get_height(min_dpi)
566 return min_dpi
567
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800568 def convert_text_to_image(self, locale, input_file, font, stage_dir,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800569 output_dir, height=None, max_width=None,
570 dpi=None, initial_dpi=None,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800571 bgcolor='#000000', fgcolor='#ffffff',
572 use_svg=False):
573 """Converts text file `input_file` into image file.
574
575 Because pango-view does not support assigning output format options for
576 bitmap, we must create images in SVG/PNG format and then post-process them
577 (e.g. convert into BMP by ImageMagick).
578
579 Args:
580 locale: Locale (language) to select implicit rendering options. None for
581 locale-independent strings.
582 input_file: Path of input text file.
583 font: Font name.
584 stage_dir: Directory to store intermediate file(s).
585 output_dir: Directory to store output image file.
586 height: Image height relative to the screen resolution.
587 max_width: Maximum image width relative to the screen resolution.
588 dpi: DPI value passed to pango-view.
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800589 initial_dpi: Initial DPI to try with in binary search.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800590 bgcolor: Background color (#rrggbb).
591 fgcolor: Foreground color (#rrggbb).
592 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
593
594 Returns:
595 Effective DPI, or `None` when not applicable.
596 """
597 one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR)
598 os.makedirs(one_line_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800599
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800600 name, _ = os.path.splitext(os.path.basename(input_file))
601 svg_file = os.path.join(stage_dir, name + '.svg')
602 png_file = os.path.join(stage_dir, name + '.png')
603 png_file_one_line = os.path.join(one_line_dir, name + '.png')
604
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800605 def get_one_line_png_height(dpi):
606 """Generates a one-line PNG using DPI `dpi` and returns its height."""
607 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
608 dpi, bgcolor, fgcolor)
609 return self._get_png_height(png_file_one_line)
610
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800611 if use_svg:
612 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
613 bgcolor, fgcolor, hinting='none')
614 return self.convert(svg_file, output_dir, height, max_width,
615 self.text_max_colors)
616 else:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800617 if not dpi:
618 raise BuildImageError('DPI must be specified with use_svg=False')
619
620 eff_dpi = dpi
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800621 if locale:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800622 max_height_px = self._to_px(height)
623 height_px = get_one_line_png_height(dpi)
624 if height_px > max_height_px:
625 eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px,
626 get_one_line_png_height)
627 # NOTE: With the same DPI, the height of multi-line PNG is not necessarily
628 # a multiple of the height of one-line PNG. Therefore, even with the
629 # binary search, the height of the resulting multi-line PNG might be
630 # less than "one_line_height * num_lines". We cannot binary-search DPI
631 # for multi-line PNGs because "num_lines" is dependent on DPI.
632 run_pango_view(input_file, png_file, locale, font, height, max_width,
633 eff_dpi, bgcolor, fgcolor)
634 self.convert(png_file, output_dir, height, max_width,
635 self.text_max_colors,
636 one_line_dir=one_line_dir if locale else None)
637 return eff_dpi
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800638
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800639 def convert_sprite_images(self):
640 """Converts sprite images."""
641 names = self.formats[KEY_SPRITE_FILES]
642 styles = self.formats[KEY_STYLES]
643 # Check redundant images
644 for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)):
645 name, _ = os.path.splitext(os.path.basename(filename))
646 if name not in names:
647 raise BuildImageError('Sprite image %r not specified in %s' %
648 (filename, FORMAT_FILE))
649 # Convert images
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800650 for name, category in names.items():
651 style = get_config_with_defaults(styles, category)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800652 file = os.path.join(self.ASSET_DIR, name + '.svg')
653 height = style[KEY_HEIGHT]
654 self.convert(file, self.output_dir, height, None, self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800655
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800656 def build_generic_strings(self):
657 """Builds images of generic (locale-independent) strings."""
658 dpi = self.config[DPI_KEY]
659
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800660 names = self.formats[KEY_GENERIC_FILES]
661 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800662 fonts = self.formats[KEY_FONTS]
663 default_font = fonts[KEY_DEFAULT]
664
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800665 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
666 name, _ = os.path.splitext(os.path.basename(txt_file))
667 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800668 style = get_config_with_defaults(styles, category)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800669 self.convert_text_to_image(None, txt_file, default_font, self.stage_dir,
670 self.output_dir,
671 height=style[KEY_HEIGHT],
672 max_width=style[KEY_MAX_WIDTH],
673 dpi=dpi,
674 bgcolor=style[KEY_BGCOLOR],
675 fgcolor=style[KEY_FGCOLOR])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800676
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800677 def build_locale(self, locale, names, json_dir):
678 """Builds images of strings for `locale`."""
679 dpi = self.config[DPI_KEY]
680 styles = self.formats[KEY_STYLES]
681 fonts = self.formats[KEY_FONTS]
682 font = fonts.get(locale, fonts[KEY_DEFAULT])
683 inputs = parse_locale_json_file(locale, json_dir)
684
685 # Walk locale directory to add pre-generated texts such as language names.
686 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
687 name, _ = os.path.splitext(os.path.basename(txt_file))
688 with open(txt_file, 'r', encoding='utf-8-sig') as f:
689 inputs[name] = f.read().strip()
690
691 output_dir = os.path.join(self.stage_locale_dir, locale)
692 os.makedirs(output_dir, exist_ok=True)
693 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
694 os.makedirs(ro_locale_dir, exist_ok=True)
695
696 eff_dpi_counters = defaultdict(Counter)
697 results = []
698 for name, category in sorted(names.items()):
699 # Ignore missing translation
700 if locale != 'en' and name not in inputs:
701 continue
702
703 # Write to text file
704 text_file = os.path.join(output_dir, name + '.txt')
705 with open(text_file, 'w', encoding='utf-8-sig') as f:
706 f.write(inputs[name] + '\n')
707
708 # Convert text to image
709 style = get_config_with_defaults(styles, category)
710 height = style[KEY_HEIGHT]
711 eff_dpi_counter = eff_dpi_counters[height]
712 if eff_dpi_counter:
713 # Find the effective DPI that appears most times for `height`. This
714 # avoid doing the same binary search again and again. In case of a tie,
715 # pick the largest DPI.
716 best_eff_dpi = max(eff_dpi_counter,
717 key=lambda dpi: (eff_dpi_counter[dpi], dpi))
718 else:
719 best_eff_dpi = None
720 eff_dpi = self.convert_text_to_image(locale,
721 text_file,
722 font,
723 output_dir,
724 ro_locale_dir,
725 height=height,
726 max_width=style[KEY_MAX_WIDTH],
727 dpi=dpi,
728 initial_dpi=best_eff_dpi,
729 bgcolor=style[KEY_BGCOLOR],
730 fgcolor=style[KEY_FGCOLOR])
731 eff_dpi_counter[eff_dpi] += 1
732 assert eff_dpi <= dpi
733 if eff_dpi != dpi:
734 results.append(eff_dpi)
735 return results
736
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800737 def _check_text_width(self, names):
738 """Checks if text image will exceed the expected drawing area at runtime."""
739 styles = self.formats[KEY_STYLES]
740
741 for locale_info in self.locales:
742 locale = locale_info.code
743 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
744 for filename in glob.glob(os.path.join(ro_locale_dir,
745 '*' + self.DEFAULT_OUTPUT_EXT)):
746 name, _ = os.path.splitext(os.path.basename(filename))
747 category = names[name]
748 style = get_config_with_defaults(styles, category)
749 height = style[KEY_HEIGHT]
750 max_width = style[KEY_MAX_WIDTH]
751 if not max_width:
752 continue
753 max_width_px = self._to_px(max_width)
754 with open(filename, 'rb') as f:
755 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
756 num_lines = f.read(1)[0]
757 height_px = self._to_px(height * num_lines)
758 with Image.open(filename) as image:
759 width_px = height_px * image.size[0] // image.size[1]
760 if width_px > max_width_px:
761 raise BuildImageError('%s: Image width %dpx greater than max width '
762 '%dpx' % (filename, width_px, max_width_px))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800763
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800764 def _copy_missing_bitmaps(self):
765 """Copy missing (not yet translated) strings from locale 'en'."""
766 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
767 '*' + self.DEFAULT_OUTPUT_EXT))
768 for locale_info in self.locales:
769 locale = locale_info.code
770 if locale == 'en':
771 continue
772 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
773 for en_file in en_files:
774 filename = os.path.basename(en_file)
775 locale_file = os.path.join(ro_locale_dir, filename)
776 if not os.path.isfile(locale_file):
777 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
778 shutil.copyfile(en_file, locale_file)
779
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800780 def build_localized_strings(self):
781 """Builds images of localized strings."""
782 # Sources are one .grd file with identifiers chosen by engineers and
783 # corresponding English texts, as well as a set of .xtb files (one for each
784 # language other than US English) with a mapping from hash to translation.
785 # Because the keys in the .xtb files are a hash of the English source text,
786 # rather than our identifiers, such as "btn_cancel", we use the "grit"
787 # command line tool to process the .grd and .xtb files, producing a set of
788 # .json files mapping our identifier to the translated string, one for every
789 # language including US English.
790
791 # Create a temporary directory to place the translation output from grit in.
792 json_dir = tempfile.mkdtemp()
793
794 # This invokes the grit build command to generate JSON files from the XTB
795 # files containing translations. The results are placed in `json_dir` as
796 # specified in firmware_strings.grd, i.e. one JSON file per locale.
797 subprocess.check_call([
798 'grit',
799 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
800 'build',
801 '-o', os.path.join(json_dir),
802 ])
803
804 # Make a copy to avoid modifying `self.formats`
805 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
806 if DIAGNOSTIC_UI:
807 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
808
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800809 # Ignore SIGINT in child processes
810 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
811 pool = multiprocessing.Pool(multiprocessing.cpu_count())
812 signal.signal(signal.SIGINT, sigint_handler)
813
814 results = []
815 for locale_info in self.locales:
816 locale = locale_info.code
817 print(locale, end=' ', flush=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800818 args = (
819 locale,
820 names,
821 json_dir,
822 )
823 results.append(pool.apply_async(self.build_locale, args))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800824
825 print()
826 pool.close()
827
828 try:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800829 results = [r.get() for r in results]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800830 except KeyboardInterrupt:
831 pool.terminate()
832 pool.join()
833 exit('Aborted by user')
834 else:
835 pool.join()
836
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800837 effective_dpi = [dpi for r in results for dpi in r if dpi]
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800838 if effective_dpi:
839 print('Reducing effective DPI to %d, limited by screen resolution' %
840 max(effective_dpi))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800841
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800842 shutil.rmtree(json_dir)
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800843 self._check_text_width(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800844 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800845
846 def move_language_images(self):
847 """Renames language bitmaps and move to self.output_dir.
848
849 The directory self.output_dir contains locale-independent images, and is
850 used for creating vbgfx.bin by archive_images.py.
851 """
852 for locale_info in self.locales:
853 locale = locale_info.code
854 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
855 old_file = os.path.join(ro_locale_dir, 'language.bmp')
856 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
857 if os.path.exists(new_file):
858 raise BuildImageError('File already exists: %s' % new_file)
859 shutil.move(old_file, new_file)
860
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800861 def build_glyphs(self):
862 """Builds glyphs of ascii characters."""
863 os.makedirs(self.stage_font_dir, exist_ok=True)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800864 font_output_dir = os.path.join(self.output_dir, 'font')
865 os.makedirs(font_output_dir)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800866 # TODO(b/163109632): Parallelize the conversion of glyphs
867 for c in range(ord(' '), ord('~') + 1):
868 name = f'idx{c:03d}_{c:02x}'
869 txt_file = os.path.join(self.stage_font_dir, name + '.txt')
870 with open(txt_file, 'w', encoding='ascii') as f:
871 f.write(chr(c))
872 f.write('\n')
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800873 self.convert_text_to_image(None, txt_file, GLYPH_FONT,
874 self.stage_font_dir, font_output_dir,
875 height=DEFAULT_GLYPH_HEIGHT,
876 use_svg=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800877
878 def copy_images_to_rw(self):
879 """Copies localized images specified in boards.yaml for RW override."""
880 if not self.config[RW_OVERRIDE_KEY]:
881 print(' No localized images are specified for RW, skipping')
882 return
883
884 for locale_info in self.locales:
885 locale = locale_info.code
886 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
887 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
888 os.makedirs(rw_locale_dir)
889
890 for name in self.config[RW_OVERRIDE_KEY]:
891 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
892 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
893 shutil.copyfile(ro_src, rw_dst)
894
895 def create_locale_list(self):
896 """Creates locale list as a CSV file.
897
898 Each line in the file is of format "code,rtl", where
899 - "code": language code of the locale
900 - "rtl": "1" for right-to-left language, "0" otherwise
901 """
902 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
903 for locale_info in self.locales:
904 f.write('{},{}\n'.format(locale_info.code,
905 int(locale_info.rtl)))
906
907 def build(self):
908 """Builds all images required by a board."""
909 # Clean up output directory
910 if os.path.exists(self.output_dir):
911 shutil.rmtree(self.output_dir)
912 os.makedirs(self.output_dir)
913
914 if not os.path.exists(self.stage_dir):
915 raise BuildImageError('Missing stage folder. Run make in strings dir.')
916
917 # Clean up temp directory
918 if os.path.exists(self.temp_dir):
919 shutil.rmtree(self.temp_dir)
920 os.makedirs(self.temp_dir)
921
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800922 print('Converting sprite images...')
923 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800924
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800925 print('Building generic strings...')
926 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800927
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800928 print('Building localized strings...')
929 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800930
931 print('Moving language images to locale-independent directory...')
932 self.move_language_images()
933
934 print('Creating locale list file...')
935 self.create_locale_list()
936
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800937 print('Building glyphs...')
938 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800939
940 print('Copying specified images to RW packing directory...')
941 self.copy_images_to_rw()
942
943
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800944def main():
945 """Builds bitmaps for firmware screens."""
946 parser = argparse.ArgumentParser()
947 parser.add_argument('board', help='Target board')
948 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800949 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800950
951 with open(FORMAT_FILE, encoding='utf-8') as f:
952 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800953 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
954
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800955 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800956 check_fonts(formats[KEY_FONTS])
957 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800958 converter = Converter(board, formats, board_config, OUTPUT_DIR)
959 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800960
961
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800962if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800963 main()