blob: a9008327ffea4a40c3d59e122c2e4a6717fc0f11 [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
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080033OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build'))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080034
35ONE_LINE_DIR = 'one_line'
36SVG_FILES = '*.svg'
37PNG_FILES = '*.png'
38
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080039DIAGNOSTIC_UI = os.getenv('DIAGNOSTIC_UI') == '1'
40
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080041# String format YAML key names.
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080042KEY_DEFAULT = '_DEFAULT_'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080043KEY_LOCALES = 'locales'
Yu-Ping Wu338f0832020-10-23 16:14:40 +080044KEY_GENERIC_FILES = 'generic_files'
45KEY_LOCALIZED_FILES = 'localized_files'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080046KEY_DIAGNOSTIC_FILES = 'diagnostic_files'
47KEY_SPRITE_FILES = 'sprite_files'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080048KEY_STYLES = 'styles'
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080049KEY_BGCOLOR = 'bgcolor'
50KEY_FGCOLOR = 'fgcolor'
51KEY_HEIGHT = 'height'
Yu-Ping Wued95df32020-11-04 17:08:15 +080052KEY_MAX_WIDTH = 'max_width'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080053KEY_FONTS = 'fonts'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080054
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080055# Board config YAML key names.
56SCREEN_KEY = 'screen'
57PANEL_KEY = 'panel'
58SDCARD_KEY = 'sdcard'
59BAD_USB3_KEY = 'bad_usb3'
Yu-Ping Wue66a7b02020-11-19 15:18:08 +080060DPI_KEY = 'dpi'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080061LOCALES_KEY = 'locales'
62RTL_KEY = 'rtl'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080063RW_OVERRIDE_KEY = 'rw_override'
64
65BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080066
Jes Klinke1687a992020-06-16 13:47:17 -070067# Regular expressions used to eliminate spurious spaces and newlines in
68# translation strings.
69NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
70NEWLINE_REPLACEMENT = r'\1 \2'
71CRLF_PATTERN = re.compile(r'\r\n')
72MULTIBLANK_PATTERN = re.compile(r' *')
73
Yu-Ping Wu3d07a062021-01-26 18:10:32 +080074# The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if
75# `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also
76# see the 'styles' section in format.yaml.
77SCALE_BASE = 1000
78DEFAULT_GLYPH_HEIGHT = 20
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 Wu675e7e82021-01-29 08:32:12 +0800105def load_boards_config(filename):
106 """Loads the configuration of all boards from `filename`.
107
108 Args:
109 filename: File name of a YAML config file.
110
111 Returns:
112 A dictionary mapping each board name to its config.
113 """
114 with open(filename, 'rb') as file:
115 raw = yaml.load(file)
116
117 configs = {}
118 default = raw[KEY_DEFAULT]
119 if not default:
120 raise BuildImageError('Default configuration is not found')
121 for boards, params in raw.items():
122 if boards == KEY_DEFAULT:
123 continue
124 config = copy.deepcopy(default)
125 if params:
126 config.update(params)
127 for board in boards.replace(',', ' ').split():
128 configs[board] = config
129
130 return configs
131
132
133def check_fonts(fonts):
134 """Check if all fonts are available."""
135 for locale, font in fonts.items():
136 if subprocess.run(['fc-list', '-q', font]).returncode != 0:
137 raise BuildImageError('Font %r not found for locale %r'
138 % (font, locale))
139
140
Yu-Ping Wu97046932021-01-25 17:38:56 +0800141def run_pango_view(input_file, output_file, locale, font, height, max_width,
142 dpi, bgcolor, fgcolor, hinting='full'):
143 """Run pango-view."""
144 command = ['pango-view', '-q']
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800145 if locale:
Yu-Ping Wu97046932021-01-25 17:38:56 +0800146 command += ['--language', locale]
147
148 # Font size should be proportional to the height. Here we use 2 as the
149 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
150 # will be roughly equivalent to setting the screen resolution to 1366x768.
151 font_size = height / 2
152 font_spec = '%s %r' % (font, font_size)
153 command += ['--font', font_spec]
154
Yu-Ping Wued95df32020-11-04 17:08:15 +0800155 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800156 # When converting text to PNG by pango-view, the ratio of image height to
157 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
158 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
159 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
160 # the calculation of `font_size` above.
161 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800162 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800163 if dpi:
164 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800165 command.append('--margin=0')
Yu-Ping Wu97046932021-01-25 17:38:56 +0800166 command += ['--background', bgcolor]
167 command += ['--foreground', fgcolor]
168 command += ['--hinting', hinting]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800169
Yu-Ping Wu97046932021-01-25 17:38:56 +0800170 command += ['--output', output_file]
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800171 command.append(input_file)
172
Yu-Ping Wu97046932021-01-25 17:38:56 +0800173 subprocess.check_call(command, stdout=subprocess.PIPE)
174
175
176def convert_text_to_image(locale, input_file, font, output_dir, height=None,
177 max_width=None, dpi=None, bgcolor='#000000',
178 fgcolor='#ffffff', use_svg=False):
179 """Converts text file `input_file` into image file(s).
180
181 Because pango-view does not support assigning output format options for
182 bitmap, we must create images in SVG/PNG format and then post-process them
183 (e.g. convert into BMP by ImageMagick).
184
185 Args:
186 locale: Locale (language) to select implicit rendering options. None for
187 locale-independent strings.
188 input_file: Path of input text file.
189 font: Font name.
190 height: Image height relative to the screen resolution.
191 max_width: Maximum image width relative to the screen resolution.
192 output_dir: Directory to generate image files.
193 bgcolor: Background color (#rrggbb).
194 fgcolor: Foreground color (#rrggbb).
195 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
196 """
197 os.makedirs(os.path.join(output_dir, ONE_LINE_DIR), exist_ok=True)
198 name, _ = os.path.splitext(os.path.basename(input_file))
199 svg_file = os.path.join(output_dir, name + '.svg')
200 png_file = os.path.join(output_dir, name + '.png')
201 png_file_one_line = os.path.join(output_dir, ONE_LINE_DIR, name + '.png')
202
203 if use_svg:
204 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
205 bgcolor, fgcolor, hinting='none')
206 else:
207 run_pango_view(input_file, png_file, locale, font, height, max_width, dpi,
208 bgcolor, fgcolor)
209 if locale:
210 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
211 dpi, bgcolor, fgcolor)
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800212
213
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800214def parse_locale_json_file(locale, json_dir):
215 """Parses given firmware string json file.
216
217 Args:
218 locale: The name of the locale, e.g. "da" or "pt-BR".
219 json_dir: Directory containing json output from grit.
220
221 Returns:
222 A dictionary for mapping of "name to content" for files to be generated.
223 """
Jes Klinke1687a992020-06-16 13:47:17 -0700224 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800225 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800226 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700227 for tag, msgdict in json.load(input_file).items():
228 msgtext = msgdict['message']
229 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
230 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
231 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
232 # Strip any trailing whitespace. A trailing newline appears to make
233 # Pango report a larger layout size than what's actually visible.
234 msgtext = msgtext.strip()
235 result[tag] = msgtext
236 return result
237
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800238
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800239class Converter(object):
240 """Converter from assets, texts, URLs, and fonts to bitmap images.
241
242 Attributes:
243 ASSET_DIR (str): Directory of image assets.
244 DEFAULT_OUTPUT_EXT (str): Default output file extension.
245 DEFAULT_REPLACE_MAP (dict): Default mapping of file replacement. For
246 {'a': 'b'}, "a.*" will be converted to "b.*".
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800247 ASSET_MAX_COLORS (int): Maximum colors to use for converting image assets
248 to bitmaps.
249 DEFAULT_BACKGROUND (tuple): Default background color.
250 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
251 name and value is a tuple of RGB values.
252 """
253
254 ASSET_DIR = 'assets'
255 DEFAULT_OUTPUT_EXT = '.bmp'
256
257 DEFAULT_REPLACE_MAP = {
258 'rec_sel_desc1_no_sd': '',
259 'rec_sel_desc1_no_phone_no_sd': '',
260 'rec_disk_step1_desc0_no_sd': '',
261 'rec_to_dev_desc1_phyrec': '',
262 'rec_to_dev_desc1_power': '',
263 'navigate0_tablet': '',
264 'navigate1_tablet': '',
265 'nav-button_power': '',
266 'nav-button_volume_up': '',
267 'nav-button_volume_down': '',
268 'broken_desc_phyrec': '',
269 'broken_desc_detach': '',
270 }
271
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800272 # background colors
273 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
274 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
275 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
276 ASSET_MAX_COLORS = 128
277
278 BACKGROUND_COLORS = {
279 'ic_dropdown': LANG_HEADER_BACKGROUND,
280 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
281 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
282 'ic_globe': LANG_HEADER_BACKGROUND,
283 'ic_search_focus': LINK_SELECTED_BACKGROUND,
284 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
285 'ic_power_focus': LINK_SELECTED_BACKGROUND,
286 }
287
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800288 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800289 """Inits converter.
290
291 Args:
292 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800293 formats: A dictionary of string formats.
294 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800295 output: Output directory.
296 """
297 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800298 self.formats = formats
299 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800300 self.set_dirs(output)
301 self.set_screen()
302 self.set_replace_map()
303 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800304 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu354a7002021-01-07 16:07:02 +0800305 self.dpi_warning_printed = False
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800306
307 def set_dirs(self, output):
308 """Sets board output directory and stage directory.
309
310 Args:
311 output: Output directory.
312 """
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800313 self.strings_dir = os.path.join(SCRIPT_BASE, 'strings')
314 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800315 self.output_dir = os.path.join(output, self.board)
316 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
317 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
318 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800319 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
320 self.stage_font_dir = os.path.join(self.stage_dir, 'font')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800321 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
322
323 def set_screen(self):
324 """Sets screen width and height."""
325 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
326
Yu-Ping Wue445e042020-11-19 15:53:42 +0800327 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800328 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800329 # Calculate `panel_stretch`. It's used to shrink images horizontally so
330 # that the resulting images will look proportional to the original image
331 # on the stretched display. If the display is not stretched, meaning the
332 # aspect ratio is same as the screen where images were rendered, no
333 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800334 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800335 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
336 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800337
Yu-Ping Wue445e042020-11-19 15:53:42 +0800338 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800339 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
340 'aspect ratio (%f). It indicates screen will be '
341 'shrunk horizontally. It is currently unsupported.'
342 % (panel_width / panel_height,
343 self.screen_width / self.screen_height))
344
345 # Set up square drawing area
346 self.canvas_px = min(self.screen_width, self.screen_height)
347
348 def set_replace_map(self):
349 """Sets a map replacing images.
350
351 For each (key, value), image 'key' will be replaced by image 'value'.
352 """
353 replace_map = self.DEFAULT_REPLACE_MAP.copy()
354
355 if os.getenv('DETACHABLE') == '1':
356 replace_map.update({
357 'nav-key_enter': 'nav-button_power',
358 'nav-key_up': 'nav-button_volume_up',
359 'nav-key_down': 'nav-button_volume_down',
360 'navigate0': 'navigate0_tablet',
361 'navigate1': 'navigate1_tablet',
362 'broken_desc': 'broken_desc_detach',
363 })
364
365 physical_presence = os.getenv('PHYSICAL_PRESENCE')
366 if physical_presence == 'recovery':
367 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_phyrec'
368 replace_map['broken_desc'] = 'broken_desc_phyrec'
369 elif physical_presence == 'power':
370 replace_map['rec_to_dev_desc1'] = 'rec_to_dev_desc1_power'
371 elif physical_presence != 'keyboard':
372 raise BuildImageError('Invalid physical presence setting %s for board %s'
373 % (physical_presence, self.board))
374
375 if not self.config[SDCARD_KEY]:
376 replace_map.update({
377 'rec_sel_desc1': 'rec_sel_desc1_no_sd',
378 'rec_sel_desc1_no_phone': 'rec_sel_desc1_no_phone_no_sd',
379 'rec_disk_step1_desc0': 'rec_disk_step1_desc0_no_sd',
380 })
381
382 self.replace_map = replace_map
383
384 def set_locales(self):
385 """Sets a list of locales for which localized images are converted."""
386 # LOCALES environment variable can overwrite boards.yaml
387 env_locales = os.getenv('LOCALES')
388 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800389 if env_locales:
390 locales = env_locales.split()
391 else:
392 locales = self.config[LOCALES_KEY]
393 # Check rtl_locales are contained in locales.
394 unknown_rtl_locales = rtl_locales - set(locales)
395 if unknown_rtl_locales:
396 raise BuildImageError('Unknown locales %s in %s' %
397 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800398 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800399 for code in locales]
400
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800401 @classmethod
402 def get_text_colors(cls, dpi):
403 """Derive maximum text colors from `dpi`."""
404 if dpi < 64:
405 return 2
406 elif dpi < 72:
407 return 3
408 elif dpi < 80:
409 return 4
410 elif dpi < 96:
411 return 5
412 elif dpi < 112:
413 return 6
414 else:
415 return 7
416
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800417 def _to_px(self, length, num_lines=1):
418 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800419 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800420
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800421 def _get_png_height(self, png_file):
422 with Image.open(png_file) as image:
423 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800424
425 def get_num_lines(self, file, one_line_dir):
426 """Gets the number of lines of text in `file`."""
427 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800428 png_name = name + '.png'
429 multi_line_file = os.path.join(os.path.dirname(file), png_name)
430 one_line_file = os.path.join(one_line_dir, png_name)
431 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800432 # `multi_line_file` with `one_line_file`, where the latter is generated
433 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800434 height = self._get_png_height(multi_line_file)
435 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800436 return int(round(height / line_height))
437
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800438 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800439 background):
440 """Converts .svg file to .png file."""
441 background_hex = ''.join(format(x, '02x') for x in background)
442 # If the width/height of the SVG file is specified in points, the
443 # rsvg-convert command with default 90DPI will potentially cause the pixels
444 # at the right/bottom border of the output image to be transparent (or
445 # filled with the specified background color). This seems like an
446 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
447 # to avoid the scaling.
448 command = ['rsvg-convert',
449 '--background-color', "'#%s'" % background_hex,
450 '--dpi-x', '72',
451 '--dpi-y', '72',
452 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800453 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800454 if height_px <= 0:
455 raise BuildImageError('Height of %r <= 0 (%dpx)' %
456 (os.path.basename(svg_file), height_px))
457 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800458 command.append(svg_file)
459 subprocess.check_call(' '.join(command), shell=True)
460
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800461 def convert_to_bitmap(self, input_file, height, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800462 max_colors):
463 """Converts an image file `input_file` to a BMP file `output`."""
464 image = Image.open(input_file)
465
466 # Process alpha channel and transparency.
467 if image.mode == 'RGBA':
468 target = Image.new('RGB', image.size, background)
469 image.load() # required for image.split()
470 mask = image.split()[-1]
471 target.paste(image, mask=mask)
472 elif (image.mode == 'P') and ('transparency' in image.info):
473 exit('Sorry, PNG with RGBA palette is not supported.')
474 elif image.mode != 'RGB':
475 target = image.convert('RGB')
476 else:
477 target = image
478
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800479 width_px, height_px = image.size
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800480 max_height_px = self._to_px(height, num_lines)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800481 # If the image size is larger than what will be displayed at runtime,
482 # downscale it.
483 if height_px > max_height_px:
Yu-Ping Wu354a7002021-01-07 16:07:02 +0800484 if not self.dpi_warning_printed:
485 print('Reducing effective DPI to %d, limited by screen resolution' %
486 (self.config[DPI_KEY] * max_height_px // height_px))
487 self.dpi_warning_printed = True
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800488 height_px = max_height_px
489 width_px = height_px * image.size[0] // image.size[1]
490 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800491 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800492 width_px = int(width_px * self.panel_stretch)
493 new_size = width_px, height_px
494 if new_size != image.size:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800495 target = target.resize(new_size, Image.BICUBIC)
496
497 # Export and downsample color space.
498 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
499 ).save(output)
500
501 with open(output, 'rb+') as f:
502 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
503 f.write(bytearray([num_lines]))
504
Yu-Ping Wued95df32020-11-04 17:08:15 +0800505 def convert(self, files, output_dir, heights, max_widths, max_colors,
506 one_line_dir=None):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800507 """Converts file(s) to bitmap format."""
508 if not files:
509 raise BuildImageError('Unable to find file(s) to convert')
510
511 for file in files:
512 name, ext = os.path.splitext(os.path.basename(file))
513 output = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
514
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800515 if name in self.replace_map:
516 name = self.replace_map[name]
517 if not name:
518 continue
519 print('Replace: %s => %s' % (file, name))
520 file = os.path.join(os.path.dirname(file), name + ext)
521
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800522 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
523 height = heights[name]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800524 max_width = max_widths[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800525
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800526 # Determine num_lines in order to scale the image
Yu-Ping Wued95df32020-11-04 17:08:15 +0800527 if one_line_dir and max_width:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800528 num_lines = self.get_num_lines(file, one_line_dir)
529 else:
530 num_lines = 1
531
532 if ext == '.svg':
533 png_file = os.path.join(self.temp_dir, name + '.png')
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800534 self.convert_svg_to_png(file, png_file, height, num_lines, background)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800535 file = png_file
536
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800537 self.convert_to_bitmap(file, height, num_lines, background, output,
538 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800539
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800540 def convert_sprite_images(self):
541 """Converts sprite images."""
542 names = self.formats[KEY_SPRITE_FILES]
543 styles = self.formats[KEY_STYLES]
544 # Check redundant images
545 for filename in glob.glob(os.path.join(self.ASSET_DIR, SVG_FILES)):
546 name, _ = os.path.splitext(os.path.basename(filename))
547 if name not in names:
548 raise BuildImageError('Sprite image %r not specified in %s' %
549 (filename, FORMAT_FILE))
550 # Convert images
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800551 files = []
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800552 heights = {}
553 for name, category in names.items():
554 style = get_config_with_defaults(styles, category)
555 files.append(os.path.join(self.ASSET_DIR, name + '.svg'))
556 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800557 max_widths = defaultdict(lambda: None)
558 self.convert(files, self.output_dir, heights, max_widths,
559 self.ASSET_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800560
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800561 def build_generic_strings(self):
562 """Builds images of generic (locale-independent) strings."""
563 dpi = self.config[DPI_KEY]
564
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800565 names = self.formats[KEY_GENERIC_FILES]
566 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800567 fonts = self.formats[KEY_FONTS]
568 default_font = fonts[KEY_DEFAULT]
569
570 files = []
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800571 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800572 max_widths = {}
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800573 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
574 name, _ = os.path.splitext(os.path.basename(txt_file))
575 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800576 style = get_config_with_defaults(styles, category)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800577 convert_text_to_image(None, txt_file, default_font, self.stage_dir,
578 height=style[KEY_HEIGHT],
579 max_width=style[KEY_MAX_WIDTH],
580 dpi=dpi,
581 bgcolor=style[KEY_BGCOLOR],
582 fgcolor=style[KEY_FGCOLOR])
583 files.append(os.path.join(self.stage_dir, name + '.png'))
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800584 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800585 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800586 self.convert(files, self.output_dir, heights, max_widths,
587 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800588
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800589 def _check_text_width(self, output_dir, heights, max_widths):
590 """Check if the width of text image will exceed canvas boundary."""
591 for filename in glob.glob(os.path.join(output_dir,
592 '*' + self.DEFAULT_OUTPUT_EXT)):
593 name, _ = os.path.splitext(os.path.basename(filename))
594 max_width = max_widths[name]
595 if not max_width:
596 continue
597 max_width_px = self._to_px(max_width)
598 with open(filename, 'rb') as f:
599 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
600 num_lines = f.read(1)[0]
601 height_px = self._to_px(heights[name] * num_lines)
602 with Image.open(filename) as image:
603 width_px = height_px * image.size[0] // image.size[1]
604 if width_px > max_width_px:
605 raise BuildImageError('%s: Image width %dpx greater than max width '
606 '%dpx' % (filename, width_px, max_width_px))
607
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800608 def _copy_missing_bitmaps(self):
609 """Copy missing (not yet translated) strings from locale 'en'."""
610 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
611 '*' + self.DEFAULT_OUTPUT_EXT))
612 for locale_info in self.locales:
613 locale = locale_info.code
614 if locale == 'en':
615 continue
616 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
617 for en_file in en_files:
618 filename = os.path.basename(en_file)
619 locale_file = os.path.join(ro_locale_dir, filename)
620 if not os.path.isfile(locale_file):
621 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
622 shutil.copyfile(en_file, locale_file)
623
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800624 def generate_localized_pngs(self, names, json_dir):
625 """Generates PNG files for localized strings."""
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800626 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800627 fonts = self.formats[KEY_FONTS]
628 default_font = fonts[KEY_DEFAULT]
629 dpi = self.config[DPI_KEY]
630
631 # Ignore SIGINT in child processes
632 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
633 pool = multiprocessing.Pool(multiprocessing.cpu_count())
634 signal.signal(signal.SIGINT, sigint_handler)
635
636 results = []
637 for locale_info in self.locales:
638 locale = locale_info.code
639 print(locale, end=' ', flush=True)
640 inputs = parse_locale_json_file(locale, json_dir)
641
642 # Walk locale directory to add pre-generated texts such as language names.
643 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
644 name, _ = os.path.splitext(os.path.basename(txt_file))
645 with open(txt_file, 'r', encoding='utf-8-sig') as f:
646 inputs[name] = f.read().strip()
647
648 output_dir = os.path.join(self.stage_locale_dir, locale)
649 os.makedirs(output_dir, exist_ok=True)
650
651 for name, category in names.items():
652 # Ignore missing translation
653 if locale != 'en' and name not in inputs:
654 continue
655
656 # Write to text file
657 text_file = os.path.join(output_dir, name + '.txt')
658 with open(text_file, 'w', encoding='utf-8-sig') as f:
659 f.write(inputs[name] + '\n')
660
661 # Convert to PNG file
662 style = get_config_with_defaults(styles, category)
663 args = (
664 locale,
665 os.path.join(output_dir, '%s.txt' % name),
666 fonts.get(locale, default_font),
667 output_dir,
668 )
669 kwargs = {
670 'height': style[KEY_HEIGHT],
671 'max_width': style[KEY_MAX_WIDTH],
672 'dpi': dpi,
673 'bgcolor': style[KEY_BGCOLOR],
674 'fgcolor': style[KEY_FGCOLOR],
675 }
676 results.append(pool.apply_async(convert_text_to_image, args, kwargs))
677
678 print()
679 pool.close()
680
681 try:
682 for r in results:
683 r.get()
684 except KeyboardInterrupt:
685 pool.terminate()
686 pool.join()
687 exit('Aborted by user')
688 else:
689 pool.join()
690
691 def convert_localized_pngs(self, names):
692 """Converts PNGs of localized strings to BMPs."""
693 styles = self.formats[KEY_STYLES]
694 fonts = self.formats[KEY_FONTS]
695 default_font = fonts[KEY_DEFAULT]
696
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800697 heights = {}
Yu-Ping Wued95df32020-11-04 17:08:15 +0800698 max_widths = {}
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800699 for name, category in names.items():
700 style = get_config_with_defaults(styles, category)
701 heights[name] = style[KEY_HEIGHT]
Yu-Ping Wued95df32020-11-04 17:08:15 +0800702 max_widths[name] = style[KEY_MAX_WIDTH]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800703
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800704 # Using stderr to report progress synchronously
705 print(' processing:', end='', file=sys.stderr, flush=True)
706 for locale_info in self.locales:
707 locale = locale_info.code
708 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800709 stage_locale_dir = os.path.join(self.stage_locale_dir, locale)
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800710 print(' ' + locale, end='', file=sys.stderr, flush=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800711 os.makedirs(ro_locale_dir)
712 self.convert(
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800713 glob.glob(os.path.join(stage_locale_dir, PNG_FILES)),
Yu-Ping Wued95df32020-11-04 17:08:15 +0800714 ro_locale_dir, heights, max_widths, self.text_max_colors,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800715 one_line_dir=os.path.join(stage_locale_dir, ONE_LINE_DIR))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800716 self._check_text_width(ro_locale_dir, heights, max_widths)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800717 print(file=sys.stderr)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800718
719 def build_localized_strings(self):
720 """Builds images of localized strings."""
721 # Sources are one .grd file with identifiers chosen by engineers and
722 # corresponding English texts, as well as a set of .xlt files (one for each
723 # language other than US English) with a mapping from hash to translation.
724 # Because the keys in the xlt files are a hash of the English source text,
725 # rather than our identifiers, such as "btn_cancel", we use the "grit"
726 # command line tool to process the .grd and .xlt files, producing a set of
727 # .json files mapping our identifier to the translated string, one for every
728 # language including US English.
729
730 # Create a temporary directory to place the translation output from grit in.
731 json_dir = tempfile.mkdtemp()
732
733 # This invokes the grit build command to generate JSON files from the XTB
734 # files containing translations. The results are placed in `json_dir` as
735 # specified in firmware_strings.grd, i.e. one JSON file per locale.
736 subprocess.check_call([
737 'grit',
738 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
739 'build',
740 '-o', os.path.join(json_dir),
741 ])
742
743 # Make a copy to avoid modifying `self.formats`
744 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
745 if DIAGNOSTIC_UI:
746 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
747
748 # TODO(b/163109632): Merge generate_localized_pngs() and
749 # convert_localized_pngs(), and parallelize them altogether.
750 self.generate_localized_pngs(names, json_dir)
751 shutil.rmtree(json_dir)
752
753 self.convert_localized_pngs(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800754 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800755
756 def move_language_images(self):
757 """Renames language bitmaps and move to self.output_dir.
758
759 The directory self.output_dir contains locale-independent images, and is
760 used for creating vbgfx.bin by archive_images.py.
761 """
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 old_file = os.path.join(ro_locale_dir, 'language.bmp')
766 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
767 if os.path.exists(new_file):
768 raise BuildImageError('File already exists: %s' % new_file)
769 shutil.move(old_file, new_file)
770
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800771 def build_glyphs(self):
772 """Builds glyphs of ascii characters."""
773 os.makedirs(self.stage_font_dir, exist_ok=True)
774 files = []
775 # TODO(b/163109632): Parallelize the conversion of glyphs
776 for c in range(ord(' '), ord('~') + 1):
777 name = f'idx{c:03d}_{c:02x}'
778 txt_file = os.path.join(self.stage_font_dir, name + '.txt')
779 with open(txt_file, 'w', encoding='ascii') as f:
780 f.write(chr(c))
781 f.write('\n')
782 convert_text_to_image(None, txt_file, GLYPH_FONT, self.stage_font_dir,
783 height=DEFAULT_GLYPH_HEIGHT, use_svg=True)
784 files.append(os.path.join(self.stage_font_dir, name + '.svg'))
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800785 heights = defaultdict(lambda: DEFAULT_GLYPH_HEIGHT)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800786 max_widths = defaultdict(lambda: None)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800787 font_output_dir = os.path.join(self.output_dir, 'font')
788 os.makedirs(font_output_dir)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800789 self.convert(files, font_output_dir, heights, max_widths,
790 self.text_max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800791
792 def copy_images_to_rw(self):
793 """Copies localized images specified in boards.yaml for RW override."""
794 if not self.config[RW_OVERRIDE_KEY]:
795 print(' No localized images are specified for RW, skipping')
796 return
797
798 for locale_info in self.locales:
799 locale = locale_info.code
800 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
801 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
802 os.makedirs(rw_locale_dir)
803
804 for name in self.config[RW_OVERRIDE_KEY]:
805 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
806 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
807 shutil.copyfile(ro_src, rw_dst)
808
809 def create_locale_list(self):
810 """Creates locale list as a CSV file.
811
812 Each line in the file is of format "code,rtl", where
813 - "code": language code of the locale
814 - "rtl": "1" for right-to-left language, "0" otherwise
815 """
816 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
817 for locale_info in self.locales:
818 f.write('{},{}\n'.format(locale_info.code,
819 int(locale_info.rtl)))
820
821 def build(self):
822 """Builds all images required by a board."""
823 # Clean up output directory
824 if os.path.exists(self.output_dir):
825 shutil.rmtree(self.output_dir)
826 os.makedirs(self.output_dir)
827
828 if not os.path.exists(self.stage_dir):
829 raise BuildImageError('Missing stage folder. Run make in strings dir.')
830
831 # Clean up temp directory
832 if os.path.exists(self.temp_dir):
833 shutil.rmtree(self.temp_dir)
834 os.makedirs(self.temp_dir)
835
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800836 print('Converting sprite images...')
837 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800838
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800839 print('Building generic strings...')
840 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800841
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800842 print('Building localized strings...')
843 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800844
845 print('Moving language images to locale-independent directory...')
846 self.move_language_images()
847
848 print('Creating locale list file...')
849 self.create_locale_list()
850
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800851 print('Building glyphs...')
852 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800853
854 print('Copying specified images to RW packing directory...')
855 self.copy_images_to_rw()
856
857
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800858def main():
859 """Builds bitmaps for firmware screens."""
860 parser = argparse.ArgumentParser()
861 parser.add_argument('board', help='Target board')
862 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800863 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800864
865 with open(FORMAT_FILE, encoding='utf-8') as f:
866 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800867 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
868
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800869 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800870 check_fonts(formats[KEY_FONTS])
871 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800872 converter = Converter(board, formats, board_config, OUTPUT_DIR)
873 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800874
875
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800876if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800877 main()