blob: 0ef1d710eabbcb73f63e8911606b56b09da83551 [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):
Yu-Ping Wu20913672021-03-24 15:25:10 +0800200 """Converter for converting sprites, texts, and glyphs to bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800201
202 Attributes:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800203 DEFAULT_OUTPUT_EXT (str): Default output file extension.
Yu-Ping Wu20913672021-03-24 15:25:10 +0800204 SPRITE_MAX_COLORS (int): Maximum colors to use for converting image sprites
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800205 to bitmaps.
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800206 GLYPH_MAX_COLORS (int): Maximum colors to use for glyph bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800207 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
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800212 DEFAULT_OUTPUT_EXT = '.bmp'
213
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800214 # background colors
215 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
216 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
217 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800218 SPRITE_MAX_COLORS = 128
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800219 GLYPH_MAX_COLORS = 7
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800220
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')
Yu-Ping Wu20913672021-03-24 15:25:10 +0800256 self.sprite_dir = os.path.join(SCRIPT_BASE, 'sprite')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800257 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800258 self.output_dir = os.path.join(output, self.board)
259 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
260 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
261 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800262 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800263 self.stage_glyph_dir = os.path.join(self.stage_dir, 'glyph')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800264 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
265
266 def set_screen(self):
267 """Sets screen width and height."""
268 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
269
Yu-Ping Wue445e042020-11-19 15:53:42 +0800270 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800271 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800272 # Calculate `panel_stretch`. It's used to shrink images horizontally so
273 # that the resulting images will look proportional to the original image
274 # on the stretched display. If the display is not stretched, meaning the
275 # aspect ratio is same as the screen where images were rendered, no
276 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800277 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800278 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
279 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800280
Yu-Ping Wue445e042020-11-19 15:53:42 +0800281 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800282 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
283 'aspect ratio (%f). It indicates screen will be '
284 'shrunk horizontally. It is currently unsupported.'
285 % (panel_width / panel_height,
286 self.screen_width / self.screen_height))
287
288 # Set up square drawing area
289 self.canvas_px = min(self.screen_width, self.screen_height)
290
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800291 def set_rename_map(self):
292 """Initializes a dict `self.rename_map` for image renaming.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800293
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800294 For each items in the dict, image `key` will be renamed to `value`.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800295 """
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800296 is_detachable = os.getenv('DETACHABLE') == '1'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800297 physical_presence = os.getenv('PHYSICAL_PRESENCE')
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800298 rename_map = {}
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800299
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800300 # Navigation instructions
301 if is_detachable:
302 rename_map.update({
303 'nav-button_power': 'nav-key_enter',
304 'nav-button_volume_up': 'nav-key_up',
305 'nav-button_volume_down': 'nav-key_down',
306 'navigate0_tablet': 'navigate0',
307 'navigate1_tablet': 'navigate1',
308 })
309 else:
310 rename_map.update({
311 'nav-button_power': None,
312 'nav-button_volume_up': None,
313 'nav-button_volume_down': None,
314 'navigate0_tablet': None,
315 'navigate1_tablet': None,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800316 })
317
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800318 # Physical presence confirmation
319 if physical_presence == 'recovery':
320 rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1'
321 rename_map['rec_to_dev_desc1_power'] = None
322 elif physical_presence == 'power':
323 rename_map['rec_to_dev_desc1_phyrec'] = None
324 rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1'
325 else:
326 rename_map['rec_to_dev_desc1_phyrec'] = None
327 rename_map['rec_to_dev_desc1_power'] = None
328 if physical_presence != 'keyboard':
329 raise BuildImageError('Invalid physical presence setting %s for board '
330 '%s' % (physical_presence, self.board))
331
332 # Broken screen
333 if physical_presence == 'recovery':
334 rename_map['broken_desc_phyrec'] = 'broken_desc'
335 rename_map['broken_desc_detach'] = None
336 elif is_detachable:
337 rename_map['broken_desc_phyrec'] = None
338 rename_map['broken_desc_detach'] = 'broken_desc'
339 else:
340 rename_map['broken_desc_phyrec'] = None
341 rename_map['broken_desc_detach'] = None
342
343 # SD card
344 if not self.config[SDCARD_KEY]:
345 rename_map.update({
346 'rec_sel_desc1_no_sd': 'rec_sel_desc1',
347 'rec_sel_desc1_no_phone_no_sd': 'rec_sel_desc1_no_phone',
348 'rec_disk_step1_desc0_no_sd': 'rec_disk_step1_desc0',
349 })
350 else:
351 rename_map.update({
352 'rec_sel_desc1_no_sd': None,
353 'rec_sel_desc1_no_phone_no_sd': None,
354 'rec_disk_step1_desc0_no_sd': None,
355 })
356
357 # Check for duplicate new names
358 new_names = list(new_name for new_name in rename_map.values() if new_name)
359 if len(set(new_names)) != len(new_names):
360 raise BuildImageError('Duplicate values found in rename_map')
361
362 # Map new_name to None to skip image generation for it
363 for new_name in new_names:
364 if new_name not in rename_map:
365 rename_map[new_name] = None
366
367 # Print mapping
368 print('Rename map:')
369 for name, new_name in sorted(rename_map.items()):
370 print(' %s => %s' % (name, new_name))
371
372 self.rename_map = rename_map
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800373
374 def set_locales(self):
375 """Sets a list of locales for which localized images are converted."""
376 # LOCALES environment variable can overwrite boards.yaml
377 env_locales = os.getenv('LOCALES')
378 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800379 if env_locales:
380 locales = env_locales.split()
381 else:
382 locales = self.config[LOCALES_KEY]
383 # Check rtl_locales are contained in locales.
384 unknown_rtl_locales = rtl_locales - set(locales)
385 if unknown_rtl_locales:
386 raise BuildImageError('Unknown locales %s in %s' %
387 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800388 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800389 for code in locales]
390
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800391 @classmethod
392 def get_text_colors(cls, dpi):
393 """Derive maximum text colors from `dpi`."""
394 if dpi < 64:
395 return 2
396 elif dpi < 72:
397 return 3
398 elif dpi < 80:
399 return 4
400 elif dpi < 96:
401 return 5
402 elif dpi < 112:
403 return 6
404 else:
405 return 7
406
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800407 def _to_px(self, length, num_lines=1):
408 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800409 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800410
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800411 def _get_png_height(self, png_file):
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800412 # With small DPI, pango-view may generate an empty file
413 if os.path.getsize(png_file) == 0:
414 return 0
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800415 with Image.open(png_file) as image:
416 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800417
418 def get_num_lines(self, file, one_line_dir):
419 """Gets the number of lines of text in `file`."""
420 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800421 png_name = name + '.png'
422 multi_line_file = os.path.join(os.path.dirname(file), png_name)
423 one_line_file = os.path.join(one_line_dir, png_name)
424 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800425 # `multi_line_file` with `one_line_file`, where the latter is generated
426 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800427 height = self._get_png_height(multi_line_file)
428 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800429 return int(round(height / line_height))
430
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800431 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800432 background):
433 """Converts .svg file to .png file."""
434 background_hex = ''.join(format(x, '02x') for x in background)
435 # If the width/height of the SVG file is specified in points, the
436 # rsvg-convert command with default 90DPI will potentially cause the pixels
437 # at the right/bottom border of the output image to be transparent (or
438 # filled with the specified background color). This seems like an
439 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
440 # to avoid the scaling.
441 command = ['rsvg-convert',
442 '--background-color', "'#%s'" % background_hex,
443 '--dpi-x', '72',
444 '--dpi-y', '72',
445 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800446 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800447 if height_px <= 0:
448 raise BuildImageError('Height of %r <= 0 (%dpx)' %
449 (os.path.basename(svg_file), height_px))
450 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800451 command.append(svg_file)
452 subprocess.check_call(' '.join(command), shell=True)
453
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800454 def convert_to_bitmap(self, input_file, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800455 max_colors):
456 """Converts an image file `input_file` to a BMP file `output`."""
457 image = Image.open(input_file)
458
459 # Process alpha channel and transparency.
460 if image.mode == 'RGBA':
461 target = Image.new('RGB', image.size, background)
462 image.load() # required for image.split()
463 mask = image.split()[-1]
464 target.paste(image, mask=mask)
465 elif (image.mode == 'P') and ('transparency' in image.info):
466 exit('Sorry, PNG with RGBA palette is not supported.')
467 elif image.mode != 'RGB':
468 target = image.convert('RGB')
469 else:
470 target = image
471
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800472 width_px, height_px = image.size
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800473 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800474 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800475 width_px = int(width_px * self.panel_stretch)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800476 target = target.resize((width_px, height_px), Image.BICUBIC)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800477
478 # Export and downsample color space.
479 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
480 ).save(output)
481
482 with open(output, 'rb+') as f:
483 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
484 f.write(bytearray([num_lines]))
485
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800486 def convert(self, file, output, height, max_width, max_colors,
Yu-Ping Wued95df32020-11-04 17:08:15 +0800487 one_line_dir=None):
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800488 """Converts image `file` to bitmap format."""
489 name, ext = os.path.splitext(os.path.basename(file))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800490
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800491 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800492
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800493 # Determine num_lines in order to scale the image
494 if one_line_dir and max_width:
495 num_lines = self.get_num_lines(file, one_line_dir)
496 else:
497 num_lines = 1
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800498
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800499 if ext == '.svg':
500 png_file = os.path.join(self.temp_dir, name + '.png')
501 self.convert_svg_to_png(file, png_file, height, num_lines, background)
502 file = png_file
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800503
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800504 return self.convert_to_bitmap(file, num_lines, background, output,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800505 max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800506
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800507 def _bisect_dpi(self, max_dpi, initial_dpi, max_height_px, get_height):
508 """Bisects to find the DPI that produces image height `max_height_px`.
509
510 Args:
511 max_dpi: Maximum DPI for binary search.
512 initial_dpi: Initial DPI to try with in binary search.
513 If specified, the value must be no larger than `max_dpi`.
514 max_height_px: Maximum (target) height to search for.
515 get_height: A function converting DPI to height. The function is called
516 once before returning.
517
518 Returns:
519 The best integer DPI within [1, `max_dpi`].
520 """
521
522 min_dpi = 1
523 first_iter = True
524
525 min_height_px = get_height(min_dpi)
526 if min_height_px > max_height_px:
527 # For some font such as "Noto Sans CJK SC", the generated height cannot
528 # go below a certain value. In this case, find max DPI with
529 # height_px <= min_height_px.
530 while min_dpi < max_dpi:
531 if first_iter and initial_dpi:
532 mid_dpi = initial_dpi
533 else:
534 mid_dpi = (min_dpi + max_dpi + 1) // 2
535 height_px = get_height(mid_dpi)
536 if height_px > min_height_px:
537 max_dpi = mid_dpi - 1
538 else:
539 min_dpi = mid_dpi
540 first_iter = False
541 get_height(max_dpi)
542 return max_dpi
543
544 # Find min DPI with height_px == max_height_px
545 while min_dpi < max_dpi:
546 if first_iter and initial_dpi:
547 mid_dpi = initial_dpi
548 else:
549 mid_dpi = (min_dpi + max_dpi) // 2
550 height_px = get_height(mid_dpi)
551 if height_px == max_height_px:
552 return mid_dpi
553 elif height_px < max_height_px:
554 min_dpi = mid_dpi + 1
555 else:
556 max_dpi = mid_dpi
557 first_iter = False
558 get_height(min_dpi)
559 return min_dpi
560
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800561 def convert_text_to_image(self, locale, input_file, output_file, font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800562 stage_dir, max_colors, height=None, max_width=None,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800563 dpi=None, initial_dpi=None,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800564 bgcolor='#000000', fgcolor='#ffffff',
565 use_svg=False):
566 """Converts text file `input_file` into image file.
567
568 Because pango-view does not support assigning output format options for
569 bitmap, we must create images in SVG/PNG format and then post-process them
570 (e.g. convert into BMP by ImageMagick).
571
572 Args:
573 locale: Locale (language) to select implicit rendering options. None for
574 locale-independent strings.
575 input_file: Path of input text file.
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800576 output_file: Path of output image file.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800577 font: Font name.
578 stage_dir: Directory to store intermediate file(s).
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800579 max_colors: Maximum colors to convert to bitmap.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800580 height: Image height relative to the screen resolution.
581 max_width: Maximum image width relative to the screen resolution.
582 dpi: DPI value passed to pango-view.
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800583 initial_dpi: Initial DPI to try with in binary search.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800584 bgcolor: Background color (#rrggbb).
585 fgcolor: Foreground color (#rrggbb).
586 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
587
588 Returns:
589 Effective DPI, or `None` when not applicable.
590 """
591 one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR)
592 os.makedirs(one_line_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800593
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800594 name, _ = os.path.splitext(os.path.basename(input_file))
595 svg_file = os.path.join(stage_dir, name + '.svg')
596 png_file = os.path.join(stage_dir, name + '.png')
597 png_file_one_line = os.path.join(one_line_dir, name + '.png')
598
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800599 def get_one_line_png_height(dpi):
600 """Generates a one-line PNG using DPI `dpi` and returns its height."""
601 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
602 dpi, bgcolor, fgcolor)
603 return self._get_png_height(png_file_one_line)
604
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800605 if use_svg:
606 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
607 bgcolor, fgcolor, hinting='none')
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800608 return self.convert(svg_file, output_file, height, max_width, max_colors)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800609 else:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800610 if not dpi:
611 raise BuildImageError('DPI must be specified with use_svg=False')
612
613 eff_dpi = dpi
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800614 if locale:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800615 max_height_px = self._to_px(height)
616 height_px = get_one_line_png_height(dpi)
617 if height_px > max_height_px:
618 eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px,
619 get_one_line_png_height)
620 # NOTE: With the same DPI, the height of multi-line PNG is not necessarily
621 # a multiple of the height of one-line PNG. Therefore, even with the
622 # binary search, the height of the resulting multi-line PNG might be
623 # less than "one_line_height * num_lines". We cannot binary-search DPI
624 # for multi-line PNGs because "num_lines" is dependent on DPI.
625 run_pango_view(input_file, png_file, locale, font, height, max_width,
626 eff_dpi, bgcolor, fgcolor)
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800627 self.convert(png_file, output_file, height, max_width, max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800628 one_line_dir=one_line_dir if locale else None)
629 return eff_dpi
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800630
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800631 def convert_sprite_images(self):
632 """Converts sprite images."""
633 names = self.formats[KEY_SPRITE_FILES]
634 styles = self.formats[KEY_STYLES]
635 # Check redundant images
Yu-Ping Wu20913672021-03-24 15:25:10 +0800636 for filename in glob.glob(os.path.join(self.sprite_dir, SVG_FILES)):
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800637 name, _ = os.path.splitext(os.path.basename(filename))
638 if name not in names:
639 raise BuildImageError('Sprite image %r not specified in %s' %
640 (filename, FORMAT_FILE))
641 # Convert images
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800642 for name, category in names.items():
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800643 new_name = self.rename_map.get(name, name)
644 if not new_name:
645 continue
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800646 style = get_config_with_defaults(styles, category)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800647 file = os.path.join(self.sprite_dir, name + '.svg')
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800648 output = os.path.join(self.output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800649 height = style[KEY_HEIGHT]
Yu-Ping Wu20913672021-03-24 15:25:10 +0800650 self.convert(file, output, height, None, self.SPRITE_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800651
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800652 def build_generic_strings(self):
653 """Builds images of generic (locale-independent) strings."""
654 dpi = self.config[DPI_KEY]
655
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800656 names = self.formats[KEY_GENERIC_FILES]
657 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800658 fonts = self.formats[KEY_FONTS]
659 default_font = fonts[KEY_DEFAULT]
660
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800661 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
662 name, _ = os.path.splitext(os.path.basename(txt_file))
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800663 new_name = self.rename_map.get(name, name)
664 if not new_name:
665 continue
666 output_file = os.path.join(self.output_dir,
667 new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800668 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800669 style = get_config_with_defaults(styles, category)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800670 self.convert_text_to_image(None, txt_file, output_file, default_font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800671 self.stage_dir, self.text_max_colors,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800672 height=style[KEY_HEIGHT],
673 max_width=style[KEY_MAX_WIDTH],
674 dpi=dpi,
675 bgcolor=style[KEY_BGCOLOR],
676 fgcolor=style[KEY_FGCOLOR])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800677
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800678 def build_locale(self, locale, names, json_dir):
679 """Builds images of strings for `locale`."""
680 dpi = self.config[DPI_KEY]
681 styles = self.formats[KEY_STYLES]
682 fonts = self.formats[KEY_FONTS]
683 font = fonts.get(locale, fonts[KEY_DEFAULT])
684 inputs = parse_locale_json_file(locale, json_dir)
685
686 # Walk locale directory to add pre-generated texts such as language names.
687 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
688 name, _ = os.path.splitext(os.path.basename(txt_file))
689 with open(txt_file, 'r', encoding='utf-8-sig') as f:
690 inputs[name] = f.read().strip()
691
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800692 stage_dir = os.path.join(self.stage_locale_dir, locale)
693 os.makedirs(stage_dir, exist_ok=True)
694 output_dir = os.path.join(self.output_ro_dir, locale)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800695 os.makedirs(output_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800696
697 eff_dpi_counters = defaultdict(Counter)
698 results = []
699 for name, category in sorted(names.items()):
700 # Ignore missing translation
701 if locale != 'en' and name not in inputs:
702 continue
703
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800704 new_name = self.rename_map.get(name, name)
705 if not new_name:
706 continue
707 output_file = os.path.join(output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
708
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800709 # Write to text file
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800710 text_file = os.path.join(stage_dir, name + '.txt')
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800711 with open(text_file, 'w', encoding='utf-8-sig') as f:
712 f.write(inputs[name] + '\n')
713
714 # Convert text to image
715 style = get_config_with_defaults(styles, category)
716 height = style[KEY_HEIGHT]
717 eff_dpi_counter = eff_dpi_counters[height]
718 if eff_dpi_counter:
719 # Find the effective DPI that appears most times for `height`. This
720 # avoid doing the same binary search again and again. In case of a tie,
721 # pick the largest DPI.
722 best_eff_dpi = max(eff_dpi_counter,
723 key=lambda dpi: (eff_dpi_counter[dpi], dpi))
724 else:
725 best_eff_dpi = None
726 eff_dpi = self.convert_text_to_image(locale,
727 text_file,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800728 output_file,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800729 font,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800730 stage_dir,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800731 self.text_max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800732 height=height,
733 max_width=style[KEY_MAX_WIDTH],
734 dpi=dpi,
735 initial_dpi=best_eff_dpi,
736 bgcolor=style[KEY_BGCOLOR],
737 fgcolor=style[KEY_FGCOLOR])
738 eff_dpi_counter[eff_dpi] += 1
739 assert eff_dpi <= dpi
740 if eff_dpi != dpi:
741 results.append(eff_dpi)
742 return results
743
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800744 def _check_text_width(self, names):
745 """Checks if text image will exceed the expected drawing area at runtime."""
746 styles = self.formats[KEY_STYLES]
747
748 for locale_info in self.locales:
749 locale = locale_info.code
750 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
751 for filename in glob.glob(os.path.join(ro_locale_dir,
752 '*' + self.DEFAULT_OUTPUT_EXT)):
753 name, _ = os.path.splitext(os.path.basename(filename))
754 category = names[name]
755 style = get_config_with_defaults(styles, category)
756 height = style[KEY_HEIGHT]
757 max_width = style[KEY_MAX_WIDTH]
758 if not max_width:
759 continue
760 max_width_px = self._to_px(max_width)
761 with open(filename, 'rb') as f:
762 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
763 num_lines = f.read(1)[0]
764 height_px = self._to_px(height * num_lines)
765 with Image.open(filename) as image:
766 width_px = height_px * image.size[0] // image.size[1]
767 if width_px > max_width_px:
768 raise BuildImageError('%s: Image width %dpx greater than max width '
769 '%dpx' % (filename, width_px, max_width_px))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800770
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800771 def _copy_missing_bitmaps(self):
772 """Copy missing (not yet translated) strings from locale 'en'."""
773 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
774 '*' + self.DEFAULT_OUTPUT_EXT))
775 for locale_info in self.locales:
776 locale = locale_info.code
777 if locale == 'en':
778 continue
779 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
780 for en_file in en_files:
781 filename = os.path.basename(en_file)
782 locale_file = os.path.join(ro_locale_dir, filename)
783 if not os.path.isfile(locale_file):
784 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
785 shutil.copyfile(en_file, locale_file)
786
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800787 def build_localized_strings(self):
788 """Builds images of localized strings."""
789 # Sources are one .grd file with identifiers chosen by engineers and
790 # corresponding English texts, as well as a set of .xtb files (one for each
791 # language other than US English) with a mapping from hash to translation.
792 # Because the keys in the .xtb files are a hash of the English source text,
793 # rather than our identifiers, such as "btn_cancel", we use the "grit"
794 # command line tool to process the .grd and .xtb files, producing a set of
795 # .json files mapping our identifier to the translated string, one for every
796 # language including US English.
797
798 # Create a temporary directory to place the translation output from grit in.
799 json_dir = tempfile.mkdtemp()
800
801 # This invokes the grit build command to generate JSON files from the XTB
802 # files containing translations. The results are placed in `json_dir` as
803 # specified in firmware_strings.grd, i.e. one JSON file per locale.
804 subprocess.check_call([
805 'grit',
806 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
807 'build',
808 '-o', os.path.join(json_dir),
809 ])
810
811 # Make a copy to avoid modifying `self.formats`
812 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
813 if DIAGNOSTIC_UI:
814 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
815
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800816 # Ignore SIGINT in child processes
817 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
818 pool = multiprocessing.Pool(multiprocessing.cpu_count())
819 signal.signal(signal.SIGINT, sigint_handler)
820
821 results = []
822 for locale_info in self.locales:
823 locale = locale_info.code
824 print(locale, end=' ', flush=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800825 args = (
826 locale,
827 names,
828 json_dir,
829 )
830 results.append(pool.apply_async(self.build_locale, args))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800831
832 print()
833 pool.close()
834
835 try:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800836 results = [r.get() for r in results]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800837 except KeyboardInterrupt:
838 pool.terminate()
839 pool.join()
840 exit('Aborted by user')
841 else:
842 pool.join()
843
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800844 effective_dpi = [dpi for r in results for dpi in r if dpi]
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800845 if effective_dpi:
846 print('Reducing effective DPI to %d, limited by screen resolution' %
847 max(effective_dpi))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800848
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800849 shutil.rmtree(json_dir)
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800850 self._check_text_width(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800851 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800852
853 def move_language_images(self):
854 """Renames language bitmaps and move to self.output_dir.
855
856 The directory self.output_dir contains locale-independent images, and is
857 used for creating vbgfx.bin by archive_images.py.
858 """
859 for locale_info in self.locales:
860 locale = locale_info.code
861 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
862 old_file = os.path.join(ro_locale_dir, 'language.bmp')
863 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
864 if os.path.exists(new_file):
865 raise BuildImageError('File already exists: %s' % new_file)
866 shutil.move(old_file, new_file)
867
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800868 def build_glyphs(self):
869 """Builds glyphs of ascii characters."""
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800870 os.makedirs(self.stage_glyph_dir, exist_ok=True)
871 output_dir = os.path.join(self.output_dir, 'glyph')
872 os.makedirs(output_dir)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800873 # TODO(b/163109632): Parallelize the conversion of glyphs
874 for c in range(ord(' '), ord('~') + 1):
875 name = f'idx{c:03d}_{c:02x}'
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800876 txt_file = os.path.join(self.stage_glyph_dir, name + '.txt')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800877 with open(txt_file, 'w', encoding='ascii') as f:
878 f.write(chr(c))
879 f.write('\n')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800880 output_file = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800881 self.convert_text_to_image(None, txt_file, output_file, GLYPH_FONT,
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800882 self.stage_glyph_dir, self.GLYPH_MAX_COLORS,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800883 height=DEFAULT_GLYPH_HEIGHT,
884 use_svg=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800885
886 def copy_images_to_rw(self):
887 """Copies localized images specified in boards.yaml for RW override."""
888 if not self.config[RW_OVERRIDE_KEY]:
889 print(' No localized images are specified for RW, skipping')
890 return
891
892 for locale_info in self.locales:
893 locale = locale_info.code
894 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
895 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
896 os.makedirs(rw_locale_dir)
897
898 for name in self.config[RW_OVERRIDE_KEY]:
899 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
900 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
901 shutil.copyfile(ro_src, rw_dst)
902
903 def create_locale_list(self):
904 """Creates locale list as a CSV file.
905
906 Each line in the file is of format "code,rtl", where
907 - "code": language code of the locale
908 - "rtl": "1" for right-to-left language, "0" otherwise
909 """
910 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
911 for locale_info in self.locales:
912 f.write('{},{}\n'.format(locale_info.code,
913 int(locale_info.rtl)))
914
915 def build(self):
916 """Builds all images required by a board."""
917 # Clean up output directory
918 if os.path.exists(self.output_dir):
919 shutil.rmtree(self.output_dir)
920 os.makedirs(self.output_dir)
921
922 if not os.path.exists(self.stage_dir):
923 raise BuildImageError('Missing stage folder. Run make in strings dir.')
924
925 # Clean up temp directory
926 if os.path.exists(self.temp_dir):
927 shutil.rmtree(self.temp_dir)
928 os.makedirs(self.temp_dir)
929
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800930 print('Converting sprite images...')
931 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800932
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800933 print('Building generic strings...')
934 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800935
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800936 print('Building localized strings...')
937 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800938
939 print('Moving language images to locale-independent directory...')
940 self.move_language_images()
941
942 print('Creating locale list file...')
943 self.create_locale_list()
944
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800945 print('Building glyphs...')
946 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800947
948 print('Copying specified images to RW packing directory...')
949 self.copy_images_to_rw()
950
951
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800952def main():
953 """Builds bitmaps for firmware screens."""
954 parser = argparse.ArgumentParser()
955 parser.add_argument('board', help='Target board')
956 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800957 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800958
959 with open(FORMAT_FILE, encoding='utf-8') as f:
960 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800961 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
962
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800963 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800964 check_fonts(formats[KEY_FONTS])
965 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800966 converter = Converter(board, formats, board_config, OUTPUT_DIR)
967 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800968
969
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800970if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800971 main()