blob: f0baa4cb5abf590ad603ea747dafdc12642e39bc [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.
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800207 GLYPH_MAX_COLORS (int): Maximum colors to use for glyph bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800208 DEFAULT_BACKGROUND (tuple): Default background color.
209 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
210 name and value is a tuple of RGB values.
211 """
212
213 ASSET_DIR = 'assets'
214 DEFAULT_OUTPUT_EXT = '.bmp'
215
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800216 # background colors
217 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
218 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
219 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
220 ASSET_MAX_COLORS = 128
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800221 GLYPH_MAX_COLORS = 7
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800222
223 BACKGROUND_COLORS = {
224 'ic_dropdown': LANG_HEADER_BACKGROUND,
225 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
226 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
227 'ic_globe': LANG_HEADER_BACKGROUND,
228 'ic_search_focus': LINK_SELECTED_BACKGROUND,
229 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
230 'ic_power_focus': LINK_SELECTED_BACKGROUND,
231 }
232
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800233 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800234 """Inits converter.
235
236 Args:
237 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800238 formats: A dictionary of string formats.
239 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800240 output: Output directory.
241 """
242 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800243 self.formats = formats
244 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800245 self.set_dirs(output)
246 self.set_screen()
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800247 self.set_rename_map()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800248 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800249 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800250
251 def set_dirs(self, output):
252 """Sets board output directory and stage directory.
253
254 Args:
255 output: Output directory.
256 """
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800257 self.strings_dir = os.path.join(SCRIPT_BASE, 'strings')
258 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800259 self.output_dir = os.path.join(output, self.board)
260 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
261 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
262 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800263 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
264 self.stage_font_dir = os.path.join(self.stage_dir, 'font')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800265 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
266
267 def set_screen(self):
268 """Sets screen width and height."""
269 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
270
Yu-Ping Wue445e042020-11-19 15:53:42 +0800271 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800272 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800273 # Calculate `panel_stretch`. It's used to shrink images horizontally so
274 # that the resulting images will look proportional to the original image
275 # on the stretched display. If the display is not stretched, meaning the
276 # aspect ratio is same as the screen where images were rendered, no
277 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800278 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800279 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
280 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800281
Yu-Ping Wue445e042020-11-19 15:53:42 +0800282 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800283 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
284 'aspect ratio (%f). It indicates screen will be '
285 'shrunk horizontally. It is currently unsupported.'
286 % (panel_width / panel_height,
287 self.screen_width / self.screen_height))
288
289 # Set up square drawing area
290 self.canvas_px = min(self.screen_width, self.screen_height)
291
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800292 def set_rename_map(self):
293 """Initializes a dict `self.rename_map` for image renaming.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800294
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800295 For each items in the dict, image `key` will be renamed to `value`.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800296 """
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800297 is_detachable = os.getenv('DETACHABLE') == '1'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800298 physical_presence = os.getenv('PHYSICAL_PRESENCE')
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800299 rename_map = {}
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800300
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800301 # Navigation instructions
302 if is_detachable:
303 rename_map.update({
304 'nav-button_power': 'nav-key_enter',
305 'nav-button_volume_up': 'nav-key_up',
306 'nav-button_volume_down': 'nav-key_down',
307 'navigate0_tablet': 'navigate0',
308 'navigate1_tablet': 'navigate1',
309 })
310 else:
311 rename_map.update({
312 'nav-button_power': None,
313 'nav-button_volume_up': None,
314 'nav-button_volume_down': None,
315 'navigate0_tablet': None,
316 'navigate1_tablet': None,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800317 })
318
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800319 # Physical presence confirmation
320 if physical_presence == 'recovery':
321 rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1'
322 rename_map['rec_to_dev_desc1_power'] = None
323 elif physical_presence == 'power':
324 rename_map['rec_to_dev_desc1_phyrec'] = None
325 rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1'
326 else:
327 rename_map['rec_to_dev_desc1_phyrec'] = None
328 rename_map['rec_to_dev_desc1_power'] = None
329 if physical_presence != 'keyboard':
330 raise BuildImageError('Invalid physical presence setting %s for board '
331 '%s' % (physical_presence, self.board))
332
333 # Broken screen
334 if physical_presence == 'recovery':
335 rename_map['broken_desc_phyrec'] = 'broken_desc'
336 rename_map['broken_desc_detach'] = None
337 elif is_detachable:
338 rename_map['broken_desc_phyrec'] = None
339 rename_map['broken_desc_detach'] = 'broken_desc'
340 else:
341 rename_map['broken_desc_phyrec'] = None
342 rename_map['broken_desc_detach'] = None
343
344 # SD card
345 if not self.config[SDCARD_KEY]:
346 rename_map.update({
347 'rec_sel_desc1_no_sd': 'rec_sel_desc1',
348 'rec_sel_desc1_no_phone_no_sd': 'rec_sel_desc1_no_phone',
349 'rec_disk_step1_desc0_no_sd': 'rec_disk_step1_desc0',
350 })
351 else:
352 rename_map.update({
353 'rec_sel_desc1_no_sd': None,
354 'rec_sel_desc1_no_phone_no_sd': None,
355 'rec_disk_step1_desc0_no_sd': None,
356 })
357
358 # Check for duplicate new names
359 new_names = list(new_name for new_name in rename_map.values() if new_name)
360 if len(set(new_names)) != len(new_names):
361 raise BuildImageError('Duplicate values found in rename_map')
362
363 # Map new_name to None to skip image generation for it
364 for new_name in new_names:
365 if new_name not in rename_map:
366 rename_map[new_name] = None
367
368 # Print mapping
369 print('Rename map:')
370 for name, new_name in sorted(rename_map.items()):
371 print(' %s => %s' % (name, new_name))
372
373 self.rename_map = rename_map
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800374
375 def set_locales(self):
376 """Sets a list of locales for which localized images are converted."""
377 # LOCALES environment variable can overwrite boards.yaml
378 env_locales = os.getenv('LOCALES')
379 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800380 if env_locales:
381 locales = env_locales.split()
382 else:
383 locales = self.config[LOCALES_KEY]
384 # Check rtl_locales are contained in locales.
385 unknown_rtl_locales = rtl_locales - set(locales)
386 if unknown_rtl_locales:
387 raise BuildImageError('Unknown locales %s in %s' %
388 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800389 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800390 for code in locales]
391
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800392 @classmethod
393 def get_text_colors(cls, dpi):
394 """Derive maximum text colors from `dpi`."""
395 if dpi < 64:
396 return 2
397 elif dpi < 72:
398 return 3
399 elif dpi < 80:
400 return 4
401 elif dpi < 96:
402 return 5
403 elif dpi < 112:
404 return 6
405 else:
406 return 7
407
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800408 def _to_px(self, length, num_lines=1):
409 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800410 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800411
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800412 def _get_png_height(self, png_file):
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800413 # With small DPI, pango-view may generate an empty file
414 if os.path.getsize(png_file) == 0:
415 return 0
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800416 with Image.open(png_file) as image:
417 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800418
419 def get_num_lines(self, file, one_line_dir):
420 """Gets the number of lines of text in `file`."""
421 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800422 png_name = name + '.png'
423 multi_line_file = os.path.join(os.path.dirname(file), png_name)
424 one_line_file = os.path.join(one_line_dir, png_name)
425 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800426 # `multi_line_file` with `one_line_file`, where the latter is generated
427 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800428 height = self._get_png_height(multi_line_file)
429 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800430 return int(round(height / line_height))
431
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800432 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800433 background):
434 """Converts .svg file to .png file."""
435 background_hex = ''.join(format(x, '02x') for x in background)
436 # If the width/height of the SVG file is specified in points, the
437 # rsvg-convert command with default 90DPI will potentially cause the pixels
438 # at the right/bottom border of the output image to be transparent (or
439 # filled with the specified background color). This seems like an
440 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
441 # to avoid the scaling.
442 command = ['rsvg-convert',
443 '--background-color', "'#%s'" % background_hex,
444 '--dpi-x', '72',
445 '--dpi-y', '72',
446 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800447 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800448 if height_px <= 0:
449 raise BuildImageError('Height of %r <= 0 (%dpx)' %
450 (os.path.basename(svg_file), height_px))
451 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800452 command.append(svg_file)
453 subprocess.check_call(' '.join(command), shell=True)
454
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800455 def convert_to_bitmap(self, input_file, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800456 max_colors):
457 """Converts an image file `input_file` to a BMP file `output`."""
458 image = Image.open(input_file)
459
460 # Process alpha channel and transparency.
461 if image.mode == 'RGBA':
462 target = Image.new('RGB', image.size, background)
463 image.load() # required for image.split()
464 mask = image.split()[-1]
465 target.paste(image, mask=mask)
466 elif (image.mode == 'P') and ('transparency' in image.info):
467 exit('Sorry, PNG with RGBA palette is not supported.')
468 elif image.mode != 'RGB':
469 target = image.convert('RGB')
470 else:
471 target = image
472
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800473 width_px, height_px = image.size
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800474 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800475 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800476 width_px = int(width_px * self.panel_stretch)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800477 target = target.resize((width_px, height_px), Image.BICUBIC)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800478
479 # Export and downsample color space.
480 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
481 ).save(output)
482
483 with open(output, 'rb+') as f:
484 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
485 f.write(bytearray([num_lines]))
486
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800487 def convert(self, file, output, height, max_width, max_colors,
Yu-Ping Wued95df32020-11-04 17:08:15 +0800488 one_line_dir=None):
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800489 """Converts image `file` to bitmap format."""
490 name, ext = os.path.splitext(os.path.basename(file))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800491
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800492 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800493
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800494 # Determine num_lines in order to scale the image
495 if one_line_dir and max_width:
496 num_lines = self.get_num_lines(file, one_line_dir)
497 else:
498 num_lines = 1
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800499
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800500 if ext == '.svg':
501 png_file = os.path.join(self.temp_dir, name + '.png')
502 self.convert_svg_to_png(file, png_file, height, num_lines, background)
503 file = png_file
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800504
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800505 return self.convert_to_bitmap(file, num_lines, background, output,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800506 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800507
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800508 def _bisect_dpi(self, max_dpi, initial_dpi, max_height_px, get_height):
509 """Bisects to find the DPI that produces image height `max_height_px`.
510
511 Args:
512 max_dpi: Maximum DPI for binary search.
513 initial_dpi: Initial DPI to try with in binary search.
514 If specified, the value must be no larger than `max_dpi`.
515 max_height_px: Maximum (target) height to search for.
516 get_height: A function converting DPI to height. The function is called
517 once before returning.
518
519 Returns:
520 The best integer DPI within [1, `max_dpi`].
521 """
522
523 min_dpi = 1
524 first_iter = True
525
526 min_height_px = get_height(min_dpi)
527 if min_height_px > max_height_px:
528 # For some font such as "Noto Sans CJK SC", the generated height cannot
529 # go below a certain value. In this case, find max DPI with
530 # height_px <= min_height_px.
531 while min_dpi < max_dpi:
532 if first_iter and initial_dpi:
533 mid_dpi = initial_dpi
534 else:
535 mid_dpi = (min_dpi + max_dpi + 1) // 2
536 height_px = get_height(mid_dpi)
537 if height_px > min_height_px:
538 max_dpi = mid_dpi - 1
539 else:
540 min_dpi = mid_dpi
541 first_iter = False
542 get_height(max_dpi)
543 return max_dpi
544
545 # Find min DPI with height_px == max_height_px
546 while min_dpi < max_dpi:
547 if first_iter and initial_dpi:
548 mid_dpi = initial_dpi
549 else:
550 mid_dpi = (min_dpi + max_dpi) // 2
551 height_px = get_height(mid_dpi)
552 if height_px == max_height_px:
553 return mid_dpi
554 elif height_px < max_height_px:
555 min_dpi = mid_dpi + 1
556 else:
557 max_dpi = mid_dpi
558 first_iter = False
559 get_height(min_dpi)
560 return min_dpi
561
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800562 def convert_text_to_image(self, locale, input_file, output_file, font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800563 stage_dir, max_colors, height=None, max_width=None,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800564 dpi=None, initial_dpi=None,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800565 bgcolor='#000000', fgcolor='#ffffff',
566 use_svg=False):
567 """Converts text file `input_file` into image file.
568
569 Because pango-view does not support assigning output format options for
570 bitmap, we must create images in SVG/PNG format and then post-process them
571 (e.g. convert into BMP by ImageMagick).
572
573 Args:
574 locale: Locale (language) to select implicit rendering options. None for
575 locale-independent strings.
576 input_file: Path of input text file.
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800577 output_file: Path of output image file.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800578 font: Font name.
579 stage_dir: Directory to store intermediate file(s).
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800580 max_colors: Maximum colors to convert to bitmap.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800581 height: Image height relative to the screen resolution.
582 max_width: Maximum image width relative to the screen resolution.
583 dpi: DPI value passed to pango-view.
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800584 initial_dpi: Initial DPI to try with in binary search.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800585 bgcolor: Background color (#rrggbb).
586 fgcolor: Foreground color (#rrggbb).
587 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
588
589 Returns:
590 Effective DPI, or `None` when not applicable.
591 """
592 one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR)
593 os.makedirs(one_line_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800594
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800595 name, _ = os.path.splitext(os.path.basename(input_file))
596 svg_file = os.path.join(stage_dir, name + '.svg')
597 png_file = os.path.join(stage_dir, name + '.png')
598 png_file_one_line = os.path.join(one_line_dir, name + '.png')
599
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800600 def get_one_line_png_height(dpi):
601 """Generates a one-line PNG using DPI `dpi` and returns its height."""
602 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
603 dpi, bgcolor, fgcolor)
604 return self._get_png_height(png_file_one_line)
605
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800606 if use_svg:
607 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
608 bgcolor, fgcolor, hinting='none')
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800609 return self.convert(svg_file, output_file, height, max_width, max_colors)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800610 else:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800611 if not dpi:
612 raise BuildImageError('DPI must be specified with use_svg=False')
613
614 eff_dpi = dpi
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800615 if locale:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800616 max_height_px = self._to_px(height)
617 height_px = get_one_line_png_height(dpi)
618 if height_px > max_height_px:
619 eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px,
620 get_one_line_png_height)
621 # NOTE: With the same DPI, the height of multi-line PNG is not necessarily
622 # a multiple of the height of one-line PNG. Therefore, even with the
623 # binary search, the height of the resulting multi-line PNG might be
624 # less than "one_line_height * num_lines". We cannot binary-search DPI
625 # for multi-line PNGs because "num_lines" is dependent on DPI.
626 run_pango_view(input_file, png_file, locale, font, height, max_width,
627 eff_dpi, bgcolor, fgcolor)
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800628 self.convert(png_file, output_file, height, max_width, max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800629 one_line_dir=one_line_dir if locale else None)
630 return eff_dpi
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800631
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800632 def convert_sprite_images(self):
633 """Converts sprite images."""
634 names = self.formats[KEY_SPRITE_FILES]
635 styles = self.formats[KEY_STYLES]
636 # Check redundant images
637 for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)):
638 name, _ = os.path.splitext(os.path.basename(filename))
639 if name not in names:
640 raise BuildImageError('Sprite image %r not specified in %s' %
641 (filename, FORMAT_FILE))
642 # Convert images
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800643 for name, category in names.items():
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800644 new_name = self.rename_map.get(name, name)
645 if not new_name:
646 continue
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800647 style = get_config_with_defaults(styles, category)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800648 file = os.path.join(self.ASSET_DIR, name + '.svg')
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800649 output = os.path.join(self.output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800650 height = style[KEY_HEIGHT]
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800651 self.convert(file, output, height, None, self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800652
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800653 def build_generic_strings(self):
654 """Builds images of generic (locale-independent) strings."""
655 dpi = self.config[DPI_KEY]
656
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800657 names = self.formats[KEY_GENERIC_FILES]
658 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800659 fonts = self.formats[KEY_FONTS]
660 default_font = fonts[KEY_DEFAULT]
661
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800662 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
663 name, _ = os.path.splitext(os.path.basename(txt_file))
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800664 new_name = self.rename_map.get(name, name)
665 if not new_name:
666 continue
667 output_file = os.path.join(self.output_dir,
668 new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800669 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800670 style = get_config_with_defaults(styles, category)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800671 self.convert_text_to_image(None, txt_file, output_file, default_font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800672 self.stage_dir, self.text_max_colors,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800673 height=style[KEY_HEIGHT],
674 max_width=style[KEY_MAX_WIDTH],
675 dpi=dpi,
676 bgcolor=style[KEY_BGCOLOR],
677 fgcolor=style[KEY_FGCOLOR])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800678
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800679 def build_locale(self, locale, names, json_dir):
680 """Builds images of strings for `locale`."""
681 dpi = self.config[DPI_KEY]
682 styles = self.formats[KEY_STYLES]
683 fonts = self.formats[KEY_FONTS]
684 font = fonts.get(locale, fonts[KEY_DEFAULT])
685 inputs = parse_locale_json_file(locale, json_dir)
686
687 # Walk locale directory to add pre-generated texts such as language names.
688 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
689 name, _ = os.path.splitext(os.path.basename(txt_file))
690 with open(txt_file, 'r', encoding='utf-8-sig') as f:
691 inputs[name] = f.read().strip()
692
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800693 stage_dir = os.path.join(self.stage_locale_dir, locale)
694 os.makedirs(stage_dir, exist_ok=True)
695 output_dir = os.path.join(self.output_ro_dir, locale)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800696 os.makedirs(output_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800697
698 eff_dpi_counters = defaultdict(Counter)
699 results = []
700 for name, category in sorted(names.items()):
701 # Ignore missing translation
702 if locale != 'en' and name not in inputs:
703 continue
704
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800705 new_name = self.rename_map.get(name, name)
706 if not new_name:
707 continue
708 output_file = os.path.join(output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
709
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800710 # Write to text file
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800711 text_file = os.path.join(stage_dir, name + '.txt')
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800712 with open(text_file, 'w', encoding='utf-8-sig') as f:
713 f.write(inputs[name] + '\n')
714
715 # Convert text to image
716 style = get_config_with_defaults(styles, category)
717 height = style[KEY_HEIGHT]
718 eff_dpi_counter = eff_dpi_counters[height]
719 if eff_dpi_counter:
720 # Find the effective DPI that appears most times for `height`. This
721 # avoid doing the same binary search again and again. In case of a tie,
722 # pick the largest DPI.
723 best_eff_dpi = max(eff_dpi_counter,
724 key=lambda dpi: (eff_dpi_counter[dpi], dpi))
725 else:
726 best_eff_dpi = None
727 eff_dpi = self.convert_text_to_image(locale,
728 text_file,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800729 output_file,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800730 font,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800731 stage_dir,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800732 self.text_max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800733 height=height,
734 max_width=style[KEY_MAX_WIDTH],
735 dpi=dpi,
736 initial_dpi=best_eff_dpi,
737 bgcolor=style[KEY_BGCOLOR],
738 fgcolor=style[KEY_FGCOLOR])
739 eff_dpi_counter[eff_dpi] += 1
740 assert eff_dpi <= dpi
741 if eff_dpi != dpi:
742 results.append(eff_dpi)
743 return results
744
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800745 def _check_text_width(self, names):
746 """Checks if text image will exceed the expected drawing area at runtime."""
747 styles = self.formats[KEY_STYLES]
748
749 for locale_info in self.locales:
750 locale = locale_info.code
751 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
752 for filename in glob.glob(os.path.join(ro_locale_dir,
753 '*' + self.DEFAULT_OUTPUT_EXT)):
754 name, _ = os.path.splitext(os.path.basename(filename))
755 category = names[name]
756 style = get_config_with_defaults(styles, category)
757 height = style[KEY_HEIGHT]
758 max_width = style[KEY_MAX_WIDTH]
759 if not max_width:
760 continue
761 max_width_px = self._to_px(max_width)
762 with open(filename, 'rb') as f:
763 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
764 num_lines = f.read(1)[0]
765 height_px = self._to_px(height * num_lines)
766 with Image.open(filename) as image:
767 width_px = height_px * image.size[0] // image.size[1]
768 if width_px > max_width_px:
769 raise BuildImageError('%s: Image width %dpx greater than max width '
770 '%dpx' % (filename, width_px, max_width_px))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800771
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800772 def _copy_missing_bitmaps(self):
773 """Copy missing (not yet translated) strings from locale 'en'."""
774 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
775 '*' + self.DEFAULT_OUTPUT_EXT))
776 for locale_info in self.locales:
777 locale = locale_info.code
778 if locale == 'en':
779 continue
780 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
781 for en_file in en_files:
782 filename = os.path.basename(en_file)
783 locale_file = os.path.join(ro_locale_dir, filename)
784 if not os.path.isfile(locale_file):
785 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
786 shutil.copyfile(en_file, locale_file)
787
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800788 def build_localized_strings(self):
789 """Builds images of localized strings."""
790 # Sources are one .grd file with identifiers chosen by engineers and
791 # corresponding English texts, as well as a set of .xtb files (one for each
792 # language other than US English) with a mapping from hash to translation.
793 # Because the keys in the .xtb files are a hash of the English source text,
794 # rather than our identifiers, such as "btn_cancel", we use the "grit"
795 # command line tool to process the .grd and .xtb files, producing a set of
796 # .json files mapping our identifier to the translated string, one for every
797 # language including US English.
798
799 # Create a temporary directory to place the translation output from grit in.
800 json_dir = tempfile.mkdtemp()
801
802 # This invokes the grit build command to generate JSON files from the XTB
803 # files containing translations. The results are placed in `json_dir` as
804 # specified in firmware_strings.grd, i.e. one JSON file per locale.
805 subprocess.check_call([
806 'grit',
807 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
808 'build',
809 '-o', os.path.join(json_dir),
810 ])
811
812 # Make a copy to avoid modifying `self.formats`
813 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
814 if DIAGNOSTIC_UI:
815 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
816
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800817 # Ignore SIGINT in child processes
818 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
819 pool = multiprocessing.Pool(multiprocessing.cpu_count())
820 signal.signal(signal.SIGINT, sigint_handler)
821
822 results = []
823 for locale_info in self.locales:
824 locale = locale_info.code
825 print(locale, end=' ', flush=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800826 args = (
827 locale,
828 names,
829 json_dir,
830 )
831 results.append(pool.apply_async(self.build_locale, args))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800832
833 print()
834 pool.close()
835
836 try:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800837 results = [r.get() for r in results]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800838 except KeyboardInterrupt:
839 pool.terminate()
840 pool.join()
841 exit('Aborted by user')
842 else:
843 pool.join()
844
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800845 effective_dpi = [dpi for r in results for dpi in r if dpi]
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800846 if effective_dpi:
847 print('Reducing effective DPI to %d, limited by screen resolution' %
848 max(effective_dpi))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800849
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800850 shutil.rmtree(json_dir)
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800851 self._check_text_width(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800852 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800853
854 def move_language_images(self):
855 """Renames language bitmaps and move to self.output_dir.
856
857 The directory self.output_dir contains locale-independent images, and is
858 used for creating vbgfx.bin by archive_images.py.
859 """
860 for locale_info in self.locales:
861 locale = locale_info.code
862 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
863 old_file = os.path.join(ro_locale_dir, 'language.bmp')
864 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
865 if os.path.exists(new_file):
866 raise BuildImageError('File already exists: %s' % new_file)
867 shutil.move(old_file, new_file)
868
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800869 def build_glyphs(self):
870 """Builds glyphs of ascii characters."""
871 os.makedirs(self.stage_font_dir, exist_ok=True)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800872 font_output_dir = os.path.join(self.output_dir, 'font')
873 os.makedirs(font_output_dir)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800874 # TODO(b/163109632): Parallelize the conversion of glyphs
875 for c in range(ord(' '), ord('~') + 1):
876 name = f'idx{c:03d}_{c:02x}'
877 txt_file = os.path.join(self.stage_font_dir, name + '.txt')
878 with open(txt_file, 'w', encoding='ascii') as f:
879 f.write(chr(c))
880 f.write('\n')
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800881 output_file = os.path.join(font_output_dir,
882 name + self.DEFAULT_OUTPUT_EXT)
883 self.convert_text_to_image(None, txt_file, output_file, GLYPH_FONT,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800884 self.stage_font_dir, self.GLYPH_MAX_COLORS,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800885 height=DEFAULT_GLYPH_HEIGHT,
886 use_svg=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800887
888 def copy_images_to_rw(self):
889 """Copies localized images specified in boards.yaml for RW override."""
890 if not self.config[RW_OVERRIDE_KEY]:
891 print(' No localized images are specified for RW, skipping')
892 return
893
894 for locale_info in self.locales:
895 locale = locale_info.code
896 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
897 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
898 os.makedirs(rw_locale_dir)
899
900 for name in self.config[RW_OVERRIDE_KEY]:
901 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
902 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
903 shutil.copyfile(ro_src, rw_dst)
904
905 def create_locale_list(self):
906 """Creates locale list as a CSV file.
907
908 Each line in the file is of format "code,rtl", where
909 - "code": language code of the locale
910 - "rtl": "1" for right-to-left language, "0" otherwise
911 """
912 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
913 for locale_info in self.locales:
914 f.write('{},{}\n'.format(locale_info.code,
915 int(locale_info.rtl)))
916
917 def build(self):
918 """Builds all images required by a board."""
919 # Clean up output directory
920 if os.path.exists(self.output_dir):
921 shutil.rmtree(self.output_dir)
922 os.makedirs(self.output_dir)
923
924 if not os.path.exists(self.stage_dir):
925 raise BuildImageError('Missing stage folder. Run make in strings dir.')
926
927 # Clean up temp directory
928 if os.path.exists(self.temp_dir):
929 shutil.rmtree(self.temp_dir)
930 os.makedirs(self.temp_dir)
931
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800932 print('Converting sprite images...')
933 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800934
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800935 print('Building generic strings...')
936 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800937
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800938 print('Building localized strings...')
939 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800940
941 print('Moving language images to locale-independent directory...')
942 self.move_language_images()
943
944 print('Creating locale list file...')
945 self.create_locale_list()
946
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800947 print('Building glyphs...')
948 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800949
950 print('Copying specified images to RW packing directory...')
951 self.copy_images_to_rw()
952
953
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800954def main():
955 """Builds bitmaps for firmware screens."""
956 parser = argparse.ArgumentParser()
957 parser.add_argument('board', help='Target board')
958 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800959 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800960
961 with open(FORMAT_FILE, encoding='utf-8') as f:
962 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800963 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
964
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800965 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800966 check_fonts(formats[KEY_FONTS])
967 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800968 converter = Converter(board, formats, board_config, OUTPUT_DIR)
969 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800970
971
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800972if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800973 main()