blob: b4ae52e7d9a48c69312bb70ba801f16f1f558a2c [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'
Yu-Ping Wue66a7b02020-11-19 15:18:08 +080057DPI_KEY = 'dpi'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080058LOCALES_KEY = 'locales'
59RTL_KEY = 'rtl'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080060RW_OVERRIDE_KEY = 'rw_override'
61
62BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080063
Jes Klinke1687a992020-06-16 13:47:17 -070064# Regular expressions used to eliminate spurious spaces and newlines in
65# translation strings.
66NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
67NEWLINE_REPLACEMENT = r'\1 \2'
68CRLF_PATTERN = re.compile(r'\r\n')
69MULTIBLANK_PATTERN = re.compile(r' *')
70
Yu-Ping Wu3d07a062021-01-26 18:10:32 +080071# The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if
72# `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also
73# see the 'styles' section in format.yaml.
74SCALE_BASE = 1000
75DEFAULT_GLYPH_HEIGHT = 20
76
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +080077GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080078
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080079LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080080
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080081
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080082class DataError(Exception):
83 pass
84
85
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080086class BuildImageError(Exception):
87 """The exception class for all errors generated during build image process."""
88
89
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080090def get_config_with_defaults(configs, key):
91 """Gets config of `key` from `configs`.
92
93 If `key` is not present in `configs`, the default config will be returned.
94 Similarly, if some config values are missing for `key`, the default ones will
95 be used.
96 """
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080097 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080098 config.update(configs.get(key, {}))
99 return config
100
101
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800102def load_boards_config(filename):
103 """Loads the configuration of all boards from `filename`.
104
105 Args:
106 filename: File name of a YAML config file.
107
108 Returns:
109 A dictionary mapping each board name to its config.
110 """
111 with open(filename, 'rb') as file:
112 raw = yaml.load(file)
113
114 configs = {}
115 default = raw[KEY_DEFAULT]
116 if not default:
117 raise BuildImageError('Default configuration is not found')
118 for boards, params in raw.items():
119 if boards == KEY_DEFAULT:
120 continue
121 config = copy.deepcopy(default)
122 if params:
123 config.update(params)
124 for board in boards.replace(',', ' ').split():
125 configs[board] = config
126
127 return configs
128
129
130def check_fonts(fonts):
131 """Check if all fonts are available."""
132 for locale, font in fonts.items():
133 if subprocess.run(['fc-list', '-q', font]).returncode != 0:
134 raise BuildImageError('Font %r not found for locale %r'
135 % (font, locale))
136
137
Yu-Ping Wu97046932021-01-25 17:38:56 +0800138def run_pango_view(input_file, output_file, locale, font, height, max_width,
139 dpi, bgcolor, fgcolor, hinting='full'):
140 """Run pango-view."""
141 command = ['pango-view', '-q']
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800142 if locale:
Yu-Ping Wu97046932021-01-25 17:38:56 +0800143 command += ['--language', locale]
144
145 # Font size should be proportional to the height. Here we use 2 as the
146 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
147 # will be roughly equivalent to setting the screen resolution to 1366x768.
148 font_size = height / 2
149 font_spec = '%s %r' % (font, font_size)
150 command += ['--font', font_spec]
151
Yu-Ping Wued95df32020-11-04 17:08:15 +0800152 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800153 # When converting text to PNG by pango-view, the ratio of image height to
154 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
155 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
156 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
157 # the calculation of `font_size` above.
158 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800159 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800160 if dpi:
161 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800162 command.append('--margin=0')
Yu-Ping Wu97046932021-01-25 17:38:56 +0800163 command += ['--background', bgcolor]
164 command += ['--foreground', fgcolor]
165 command += ['--hinting', hinting]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800166
Yu-Ping Wu97046932021-01-25 17:38:56 +0800167 command += ['--output', output_file]
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800168 command.append(input_file)
169
Yu-Ping Wu97046932021-01-25 17:38:56 +0800170 subprocess.check_call(command, stdout=subprocess.PIPE)
171
172
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800173def parse_locale_json_file(locale, json_dir):
174 """Parses given firmware string json file.
175
176 Args:
177 locale: The name of the locale, e.g. "da" or "pt-BR".
178 json_dir: Directory containing json output from grit.
179
180 Returns:
181 A dictionary for mapping of "name to content" for files to be generated.
182 """
Jes Klinke1687a992020-06-16 13:47:17 -0700183 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800184 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800185 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700186 for tag, msgdict in json.load(input_file).items():
187 msgtext = msgdict['message']
188 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
189 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
190 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
191 # Strip any trailing whitespace. A trailing newline appears to make
192 # Pango report a larger layout size than what's actually visible.
193 msgtext = msgtext.strip()
194 result[tag] = msgtext
195 return result
196
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800197
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800198class Converter(object):
Yu-Ping Wu20913672021-03-24 15:25:10 +0800199 """Converter for converting sprites, texts, and glyphs to bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800200
201 Attributes:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800202 DEFAULT_OUTPUT_EXT (str): Default output file extension.
Yu-Ping Wu20913672021-03-24 15:25:10 +0800203 SPRITE_MAX_COLORS (int): Maximum colors to use for converting image sprites
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800204 to bitmaps.
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800205 GLYPH_MAX_COLORS (int): Maximum colors to use for glyph bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800206 DEFAULT_BACKGROUND (tuple): Default background color.
207 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
208 name and value is a tuple of RGB values.
209 """
210
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800211 DEFAULT_OUTPUT_EXT = '.bmp'
212
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800213 # background colors
214 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
215 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
216 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800217 SPRITE_MAX_COLORS = 128
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800218 GLYPH_MAX_COLORS = 7
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800219
220 BACKGROUND_COLORS = {
221 'ic_dropdown': LANG_HEADER_BACKGROUND,
222 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
223 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
224 'ic_globe': LANG_HEADER_BACKGROUND,
225 'ic_search_focus': LINK_SELECTED_BACKGROUND,
226 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
227 'ic_power_focus': LINK_SELECTED_BACKGROUND,
228 }
229
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800230 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800231 """Inits converter.
232
233 Args:
234 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800235 formats: A dictionary of string formats.
236 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800237 output: Output directory.
238 """
239 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800240 self.formats = formats
241 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800242 self.set_dirs(output)
243 self.set_screen()
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800244 self.set_rename_map()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800245 self.set_locales()
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800246 self.text_max_colors = self.get_text_colors(self.config[DPI_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800247
248 def set_dirs(self, output):
249 """Sets board output directory and stage directory.
250
251 Args:
252 output: Output directory.
253 """
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800254 self.strings_dir = os.path.join(SCRIPT_BASE, 'strings')
Yu-Ping Wu20913672021-03-24 15:25:10 +0800255 self.sprite_dir = os.path.join(SCRIPT_BASE, 'sprite')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800256 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800257 self.output_dir = os.path.join(output, self.board)
258 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
259 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
260 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800261 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800262 self.stage_glyph_dir = os.path.join(self.stage_dir, 'glyph')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800263 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
264
265 def set_screen(self):
266 """Sets screen width and height."""
267 self.screen_width, self.screen_height = self.config[SCREEN_KEY]
268
Yu-Ping Wue445e042020-11-19 15:53:42 +0800269 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800270 if self.config[PANEL_KEY]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800271 # Calculate `panel_stretch`. It's used to shrink images horizontally so
272 # that the resulting images will look proportional to the original image
273 # on the stretched display. If the display is not stretched, meaning the
274 # aspect ratio is same as the screen where images were rendered, no
275 # shrinking is performed.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800276 panel_width, panel_height = self.config[PANEL_KEY]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800277 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
278 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800279
Yu-Ping Wue445e042020-11-19 15:53:42 +0800280 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800281 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
282 'aspect ratio (%f). It indicates screen will be '
283 'shrunk horizontally. It is currently unsupported.'
284 % (panel_width / panel_height,
285 self.screen_width / self.screen_height))
286
287 # Set up square drawing area
288 self.canvas_px = min(self.screen_width, self.screen_height)
289
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800290 def set_rename_map(self):
291 """Initializes a dict `self.rename_map` for image renaming.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800292
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800293 For each items in the dict, image `key` will be renamed to `value`.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800294 """
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800295 is_detachable = os.getenv('DETACHABLE') == '1'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800296 physical_presence = os.getenv('PHYSICAL_PRESENCE')
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800297 rename_map = {}
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800298
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800299 # Navigation instructions
300 if is_detachable:
301 rename_map.update({
302 'nav-button_power': 'nav-key_enter',
303 'nav-button_volume_up': 'nav-key_up',
304 'nav-button_volume_down': 'nav-key_down',
305 'navigate0_tablet': 'navigate0',
306 'navigate1_tablet': 'navigate1',
307 })
308 else:
309 rename_map.update({
310 'nav-button_power': None,
311 'nav-button_volume_up': None,
312 'nav-button_volume_down': None,
313 'navigate0_tablet': None,
314 'navigate1_tablet': None,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800315 })
316
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800317 # Physical presence confirmation
318 if physical_presence == 'recovery':
319 rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1'
320 rename_map['rec_to_dev_desc1_power'] = None
321 elif physical_presence == 'power':
322 rename_map['rec_to_dev_desc1_phyrec'] = None
323 rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1'
324 else:
325 rename_map['rec_to_dev_desc1_phyrec'] = None
326 rename_map['rec_to_dev_desc1_power'] = None
327 if physical_presence != 'keyboard':
328 raise BuildImageError('Invalid physical presence setting %s for board '
329 '%s' % (physical_presence, self.board))
330
331 # Broken screen
332 if physical_presence == 'recovery':
333 rename_map['broken_desc_phyrec'] = 'broken_desc'
334 rename_map['broken_desc_detach'] = None
335 elif is_detachable:
336 rename_map['broken_desc_phyrec'] = None
337 rename_map['broken_desc_detach'] = 'broken_desc'
338 else:
339 rename_map['broken_desc_phyrec'] = None
340 rename_map['broken_desc_detach'] = None
341
342 # SD card
343 if not self.config[SDCARD_KEY]:
344 rename_map.update({
345 'rec_sel_desc1_no_sd': 'rec_sel_desc1',
346 'rec_sel_desc1_no_phone_no_sd': 'rec_sel_desc1_no_phone',
347 'rec_disk_step1_desc0_no_sd': 'rec_disk_step1_desc0',
348 })
349 else:
350 rename_map.update({
351 'rec_sel_desc1_no_sd': None,
352 'rec_sel_desc1_no_phone_no_sd': None,
353 'rec_disk_step1_desc0_no_sd': None,
354 })
355
356 # Check for duplicate new names
357 new_names = list(new_name for new_name in rename_map.values() if new_name)
358 if len(set(new_names)) != len(new_names):
359 raise BuildImageError('Duplicate values found in rename_map')
360
361 # Map new_name to None to skip image generation for it
362 for new_name in new_names:
363 if new_name not in rename_map:
364 rename_map[new_name] = None
365
366 # Print mapping
367 print('Rename map:')
368 for name, new_name in sorted(rename_map.items()):
369 print(' %s => %s' % (name, new_name))
370
371 self.rename_map = rename_map
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800372
373 def set_locales(self):
374 """Sets a list of locales for which localized images are converted."""
375 # LOCALES environment variable can overwrite boards.yaml
376 env_locales = os.getenv('LOCALES')
377 rtl_locales = set(self.config[RTL_KEY])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800378 if env_locales:
379 locales = env_locales.split()
380 else:
381 locales = self.config[LOCALES_KEY]
382 # Check rtl_locales are contained in locales.
383 unknown_rtl_locales = rtl_locales - set(locales)
384 if unknown_rtl_locales:
385 raise BuildImageError('Unknown locales %s in %s' %
386 (list(unknown_rtl_locales), RTL_KEY))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800387 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800388 for code in locales]
389
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800390 @classmethod
391 def get_text_colors(cls, dpi):
392 """Derive maximum text colors from `dpi`."""
393 if dpi < 64:
394 return 2
395 elif dpi < 72:
396 return 3
397 elif dpi < 80:
398 return 4
399 elif dpi < 96:
400 return 5
401 elif dpi < 112:
402 return 6
403 else:
404 return 7
405
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800406 def _to_px(self, length, num_lines=1):
407 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800408 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800409
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800410 def _get_png_height(self, png_file):
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800411 # With small DPI, pango-view may generate an empty file
412 if os.path.getsize(png_file) == 0:
413 return 0
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800414 with Image.open(png_file) as image:
415 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800416
417 def get_num_lines(self, file, one_line_dir):
418 """Gets the number of lines of text in `file`."""
419 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800420 png_name = name + '.png'
421 multi_line_file = os.path.join(os.path.dirname(file), png_name)
422 one_line_file = os.path.join(one_line_dir, png_name)
423 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800424 # `multi_line_file` with `one_line_file`, where the latter is generated
425 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800426 height = self._get_png_height(multi_line_file)
427 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800428 return int(round(height / line_height))
429
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800430 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800431 background):
432 """Converts .svg file to .png file."""
433 background_hex = ''.join(format(x, '02x') for x in background)
434 # If the width/height of the SVG file is specified in points, the
435 # rsvg-convert command with default 90DPI will potentially cause the pixels
436 # at the right/bottom border of the output image to be transparent (or
437 # filled with the specified background color). This seems like an
438 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
439 # to avoid the scaling.
440 command = ['rsvg-convert',
441 '--background-color', "'#%s'" % background_hex,
442 '--dpi-x', '72',
443 '--dpi-y', '72',
444 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800445 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800446 if height_px <= 0:
447 raise BuildImageError('Height of %r <= 0 (%dpx)' %
448 (os.path.basename(svg_file), height_px))
449 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800450 command.append(svg_file)
451 subprocess.check_call(' '.join(command), shell=True)
452
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800453 def convert_to_bitmap(self, input_file, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800454 max_colors):
455 """Converts an image file `input_file` to a BMP file `output`."""
456 image = Image.open(input_file)
457
458 # Process alpha channel and transparency.
459 if image.mode == 'RGBA':
460 target = Image.new('RGB', image.size, background)
461 image.load() # required for image.split()
462 mask = image.split()[-1]
463 target.paste(image, mask=mask)
464 elif (image.mode == 'P') and ('transparency' in image.info):
465 exit('Sorry, PNG with RGBA palette is not supported.')
466 elif image.mode != 'RGB':
467 target = image.convert('RGB')
468 else:
469 target = image
470
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800471 width_px, height_px = image.size
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800472 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800473 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800474 width_px = int(width_px * self.panel_stretch)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800475 target = target.resize((width_px, height_px), Image.BICUBIC)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800476
477 # Export and downsample color space.
478 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
479 ).save(output)
480
481 with open(output, 'rb+') as f:
482 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
483 f.write(bytearray([num_lines]))
484
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800485 def convert(self, file, output, height, max_width, max_colors,
Yu-Ping Wued95df32020-11-04 17:08:15 +0800486 one_line_dir=None):
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800487 """Converts image `file` to bitmap format."""
488 name, ext = os.path.splitext(os.path.basename(file))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800489
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800490 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800491
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800492 # Determine num_lines in order to scale the image
493 if one_line_dir and max_width:
494 num_lines = self.get_num_lines(file, one_line_dir)
495 else:
496 num_lines = 1
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800497
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800498 if ext == '.svg':
499 png_file = os.path.join(self.temp_dir, name + '.png')
500 self.convert_svg_to_png(file, png_file, height, num_lines, background)
501 file = png_file
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800502
Yu-Ping Wub87a47d2021-03-30 14:10:22 +0800503 self.convert_to_bitmap(file, num_lines, background, output, max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800504
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800505 def _bisect_dpi(self, max_dpi, initial_dpi, max_height_px, get_height):
506 """Bisects to find the DPI that produces image height `max_height_px`.
507
508 Args:
509 max_dpi: Maximum DPI for binary search.
510 initial_dpi: Initial DPI to try with in binary search.
511 If specified, the value must be no larger than `max_dpi`.
512 max_height_px: Maximum (target) height to search for.
513 get_height: A function converting DPI to height. The function is called
514 once before returning.
515
516 Returns:
517 The best integer DPI within [1, `max_dpi`].
518 """
519
520 min_dpi = 1
521 first_iter = True
522
523 min_height_px = get_height(min_dpi)
524 if min_height_px > max_height_px:
525 # For some font such as "Noto Sans CJK SC", the generated height cannot
526 # go below a certain value. In this case, find max DPI with
527 # height_px <= min_height_px.
528 while min_dpi < max_dpi:
529 if first_iter and initial_dpi:
530 mid_dpi = initial_dpi
531 else:
532 mid_dpi = (min_dpi + max_dpi + 1) // 2
533 height_px = get_height(mid_dpi)
534 if height_px > min_height_px:
535 max_dpi = mid_dpi - 1
536 else:
537 min_dpi = mid_dpi
538 first_iter = False
539 get_height(max_dpi)
540 return max_dpi
541
542 # Find min DPI with height_px == max_height_px
543 while min_dpi < max_dpi:
544 if first_iter and initial_dpi:
545 mid_dpi = initial_dpi
546 else:
547 mid_dpi = (min_dpi + max_dpi) // 2
548 height_px = get_height(mid_dpi)
549 if height_px == max_height_px:
550 return mid_dpi
551 elif height_px < max_height_px:
552 min_dpi = mid_dpi + 1
553 else:
554 max_dpi = mid_dpi
555 first_iter = False
556 get_height(min_dpi)
557 return min_dpi
558
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800559 def convert_text_to_image(self, locale, input_file, output_file, font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800560 stage_dir, max_colors, height=None, max_width=None,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800561 dpi=None, initial_dpi=None,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800562 bgcolor='#000000', fgcolor='#ffffff',
563 use_svg=False):
564 """Converts text file `input_file` into image file.
565
566 Because pango-view does not support assigning output format options for
567 bitmap, we must create images in SVG/PNG format and then post-process them
568 (e.g. convert into BMP by ImageMagick).
569
570 Args:
571 locale: Locale (language) to select implicit rendering options. None for
572 locale-independent strings.
573 input_file: Path of input text file.
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800574 output_file: Path of output image file.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800575 font: Font name.
576 stage_dir: Directory to store intermediate file(s).
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800577 max_colors: Maximum colors to convert to bitmap.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800578 height: Image height relative to the screen resolution.
579 max_width: Maximum image width relative to the screen resolution.
580 dpi: DPI value passed to pango-view.
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800581 initial_dpi: Initial DPI to try with in binary search.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800582 bgcolor: Background color (#rrggbb).
583 fgcolor: Foreground color (#rrggbb).
584 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
585
586 Returns:
587 Effective DPI, or `None` when not applicable.
588 """
589 one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR)
590 os.makedirs(one_line_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800591
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800592 name, _ = os.path.splitext(os.path.basename(input_file))
593 svg_file = os.path.join(stage_dir, name + '.svg')
594 png_file = os.path.join(stage_dir, name + '.png')
595 png_file_one_line = os.path.join(one_line_dir, name + '.png')
596
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800597 def get_one_line_png_height(dpi):
598 """Generates a one-line PNG using DPI `dpi` and returns its height."""
599 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
600 dpi, bgcolor, fgcolor)
601 return self._get_png_height(png_file_one_line)
602
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800603 if use_svg:
604 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
605 bgcolor, fgcolor, hinting='none')
Yu-Ping Wub87a47d2021-03-30 14:10:22 +0800606 self.convert(svg_file, output_file, height, max_width, max_colors)
607 return None
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800608 else:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800609 if not dpi:
610 raise BuildImageError('DPI must be specified with use_svg=False')
611
612 eff_dpi = dpi
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800613 if locale:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800614 max_height_px = self._to_px(height)
615 height_px = get_one_line_png_height(dpi)
616 if height_px > max_height_px:
617 eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px,
618 get_one_line_png_height)
619 # NOTE: With the same DPI, the height of multi-line PNG is not necessarily
620 # a multiple of the height of one-line PNG. Therefore, even with the
621 # binary search, the height of the resulting multi-line PNG might be
622 # less than "one_line_height * num_lines". We cannot binary-search DPI
623 # for multi-line PNGs because "num_lines" is dependent on DPI.
624 run_pango_view(input_file, png_file, locale, font, height, max_width,
625 eff_dpi, bgcolor, fgcolor)
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800626 self.convert(png_file, output_file, height, max_width, max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800627 one_line_dir=one_line_dir if locale else None)
628 return eff_dpi
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800629
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800630 def convert_sprite_images(self):
631 """Converts sprite images."""
632 names = self.formats[KEY_SPRITE_FILES]
633 styles = self.formats[KEY_STYLES]
634 # Check redundant images
Yu-Ping Wu20913672021-03-24 15:25:10 +0800635 for filename in glob.glob(os.path.join(self.sprite_dir, SVG_FILES)):
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800636 name, _ = os.path.splitext(os.path.basename(filename))
637 if name not in names:
638 raise BuildImageError('Sprite image %r not specified in %s' %
639 (filename, FORMAT_FILE))
640 # Convert images
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800641 for name, category in names.items():
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800642 new_name = self.rename_map.get(name, name)
643 if not new_name:
644 continue
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800645 style = get_config_with_defaults(styles, category)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800646 file = os.path.join(self.sprite_dir, name + '.svg')
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800647 output = os.path.join(self.output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800648 height = style[KEY_HEIGHT]
Yu-Ping Wu20913672021-03-24 15:25:10 +0800649 self.convert(file, output, height, None, self.SPRITE_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800650
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800651 def build_generic_strings(self):
652 """Builds images of generic (locale-independent) strings."""
653 dpi = self.config[DPI_KEY]
654
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800655 names = self.formats[KEY_GENERIC_FILES]
656 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800657 fonts = self.formats[KEY_FONTS]
658 default_font = fonts[KEY_DEFAULT]
659
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800660 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
661 name, _ = os.path.splitext(os.path.basename(txt_file))
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800662 new_name = self.rename_map.get(name, name)
663 if not new_name:
664 continue
665 output_file = os.path.join(self.output_dir,
666 new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800667 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800668 style = get_config_with_defaults(styles, category)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800669 self.convert_text_to_image(None, txt_file, output_file, default_font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800670 self.stage_dir, self.text_max_colors,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800671 height=style[KEY_HEIGHT],
672 max_width=style[KEY_MAX_WIDTH],
673 dpi=dpi,
674 bgcolor=style[KEY_BGCOLOR],
675 fgcolor=style[KEY_FGCOLOR])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800676
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800677 def build_locale(self, locale, names, json_dir):
678 """Builds images of strings for `locale`."""
679 dpi = self.config[DPI_KEY]
680 styles = self.formats[KEY_STYLES]
681 fonts = self.formats[KEY_FONTS]
682 font = fonts.get(locale, fonts[KEY_DEFAULT])
683 inputs = parse_locale_json_file(locale, json_dir)
684
685 # Walk locale directory to add pre-generated texts such as language names.
686 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
687 name, _ = os.path.splitext(os.path.basename(txt_file))
688 with open(txt_file, 'r', encoding='utf-8-sig') as f:
689 inputs[name] = f.read().strip()
690
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800691 stage_dir = os.path.join(self.stage_locale_dir, locale)
692 os.makedirs(stage_dir, exist_ok=True)
693 output_dir = os.path.join(self.output_ro_dir, locale)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800694 os.makedirs(output_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800695
696 eff_dpi_counters = defaultdict(Counter)
697 results = []
698 for name, category in sorted(names.items()):
699 # Ignore missing translation
700 if locale != 'en' and name not in inputs:
701 continue
702
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800703 new_name = self.rename_map.get(name, name)
704 if not new_name:
705 continue
706 output_file = os.path.join(output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
707
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800708 # Write to text file
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800709 text_file = os.path.join(stage_dir, name + '.txt')
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800710 with open(text_file, 'w', encoding='utf-8-sig') as f:
711 f.write(inputs[name] + '\n')
712
713 # Convert text to image
714 style = get_config_with_defaults(styles, category)
715 height = style[KEY_HEIGHT]
716 eff_dpi_counter = eff_dpi_counters[height]
717 if eff_dpi_counter:
718 # Find the effective DPI that appears most times for `height`. This
719 # avoid doing the same binary search again and again. In case of a tie,
720 # pick the largest DPI.
721 best_eff_dpi = max(eff_dpi_counter,
722 key=lambda dpi: (eff_dpi_counter[dpi], dpi))
723 else:
724 best_eff_dpi = None
725 eff_dpi = self.convert_text_to_image(locale,
726 text_file,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800727 output_file,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800728 font,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800729 stage_dir,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800730 self.text_max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800731 height=height,
732 max_width=style[KEY_MAX_WIDTH],
733 dpi=dpi,
734 initial_dpi=best_eff_dpi,
735 bgcolor=style[KEY_BGCOLOR],
736 fgcolor=style[KEY_FGCOLOR])
737 eff_dpi_counter[eff_dpi] += 1
738 assert eff_dpi <= dpi
739 if eff_dpi != dpi:
740 results.append(eff_dpi)
741 return results
742
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800743 def _check_text_width(self, names):
744 """Checks if text image will exceed the expected drawing area at runtime."""
745 styles = self.formats[KEY_STYLES]
746
747 for locale_info in self.locales:
748 locale = locale_info.code
749 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
750 for filename in glob.glob(os.path.join(ro_locale_dir,
751 '*' + self.DEFAULT_OUTPUT_EXT)):
752 name, _ = os.path.splitext(os.path.basename(filename))
753 category = names[name]
754 style = get_config_with_defaults(styles, category)
755 height = style[KEY_HEIGHT]
756 max_width = style[KEY_MAX_WIDTH]
757 if not max_width:
758 continue
759 max_width_px = self._to_px(max_width)
760 with open(filename, 'rb') as f:
761 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
762 num_lines = f.read(1)[0]
763 height_px = self._to_px(height * num_lines)
764 with Image.open(filename) as image:
765 width_px = height_px * image.size[0] // image.size[1]
766 if width_px > max_width_px:
767 raise BuildImageError('%s: Image width %dpx greater than max width '
768 '%dpx' % (filename, width_px, max_width_px))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800769
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800770 def _copy_missing_bitmaps(self):
771 """Copy missing (not yet translated) strings from locale 'en'."""
772 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
773 '*' + self.DEFAULT_OUTPUT_EXT))
774 for locale_info in self.locales:
775 locale = locale_info.code
776 if locale == 'en':
777 continue
778 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
779 for en_file in en_files:
780 filename = os.path.basename(en_file)
781 locale_file = os.path.join(ro_locale_dir, filename)
782 if not os.path.isfile(locale_file):
783 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
784 shutil.copyfile(en_file, locale_file)
785
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800786 def build_localized_strings(self):
787 """Builds images of localized strings."""
788 # Sources are one .grd file with identifiers chosen by engineers and
789 # corresponding English texts, as well as a set of .xtb files (one for each
790 # language other than US English) with a mapping from hash to translation.
791 # Because the keys in the .xtb files are a hash of the English source text,
792 # rather than our identifiers, such as "btn_cancel", we use the "grit"
793 # command line tool to process the .grd and .xtb files, producing a set of
794 # .json files mapping our identifier to the translated string, one for every
795 # language including US English.
796
797 # Create a temporary directory to place the translation output from grit in.
798 json_dir = tempfile.mkdtemp()
799
800 # This invokes the grit build command to generate JSON files from the XTB
801 # files containing translations. The results are placed in `json_dir` as
802 # specified in firmware_strings.grd, i.e. one JSON file per locale.
803 subprocess.check_call([
804 'grit',
805 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
806 'build',
807 '-o', os.path.join(json_dir),
808 ])
809
810 # Make a copy to avoid modifying `self.formats`
811 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
812 if DIAGNOSTIC_UI:
813 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
814
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800815 # Ignore SIGINT in child processes
816 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
817 pool = multiprocessing.Pool(multiprocessing.cpu_count())
818 signal.signal(signal.SIGINT, sigint_handler)
819
820 results = []
821 for locale_info in self.locales:
822 locale = locale_info.code
823 print(locale, end=' ', flush=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800824 args = (
825 locale,
826 names,
827 json_dir,
828 )
829 results.append(pool.apply_async(self.build_locale, args))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800830
831 print()
832 pool.close()
833
834 try:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800835 results = [r.get() for r in results]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800836 except KeyboardInterrupt:
837 pool.terminate()
838 pool.join()
839 exit('Aborted by user')
840 else:
841 pool.join()
842
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800843 effective_dpi = [dpi for r in results for dpi in r if dpi]
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800844 if effective_dpi:
845 print('Reducing effective DPI to %d, limited by screen resolution' %
846 max(effective_dpi))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800847
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800848 shutil.rmtree(json_dir)
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800849 self._check_text_width(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800850 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800851
852 def move_language_images(self):
853 """Renames language bitmaps and move to self.output_dir.
854
855 The directory self.output_dir contains locale-independent images, and is
856 used for creating vbgfx.bin by archive_images.py.
857 """
858 for locale_info in self.locales:
859 locale = locale_info.code
860 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
861 old_file = os.path.join(ro_locale_dir, 'language.bmp')
862 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
863 if os.path.exists(new_file):
864 raise BuildImageError('File already exists: %s' % new_file)
865 shutil.move(old_file, new_file)
866
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800867 def build_glyphs(self):
868 """Builds glyphs of ascii characters."""
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800869 os.makedirs(self.stage_glyph_dir, exist_ok=True)
870 output_dir = os.path.join(self.output_dir, 'glyph')
871 os.makedirs(output_dir)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800872 # TODO(b/163109632): Parallelize the conversion of glyphs
873 for c in range(ord(' '), ord('~') + 1):
874 name = f'idx{c:03d}_{c:02x}'
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800875 txt_file = os.path.join(self.stage_glyph_dir, name + '.txt')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800876 with open(txt_file, 'w', encoding='ascii') as f:
877 f.write(chr(c))
878 f.write('\n')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800879 output_file = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800880 self.convert_text_to_image(None, txt_file, output_file, GLYPH_FONT,
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800881 self.stage_glyph_dir, self.GLYPH_MAX_COLORS,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800882 height=DEFAULT_GLYPH_HEIGHT,
883 use_svg=True)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800884
885 def copy_images_to_rw(self):
886 """Copies localized images specified in boards.yaml for RW override."""
887 if not self.config[RW_OVERRIDE_KEY]:
888 print(' No localized images are specified for RW, skipping')
889 return
890
891 for locale_info in self.locales:
892 locale = locale_info.code
893 rw_locale_dir = os.path.join(self.output_ro_dir, locale)
894 ro_locale_dir = os.path.join(self.output_rw_dir, locale)
895 os.makedirs(rw_locale_dir)
896
897 for name in self.config[RW_OVERRIDE_KEY]:
898 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
899 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
900 shutil.copyfile(ro_src, rw_dst)
901
902 def create_locale_list(self):
903 """Creates locale list as a CSV file.
904
905 Each line in the file is of format "code,rtl", where
906 - "code": language code of the locale
907 - "rtl": "1" for right-to-left language, "0" otherwise
908 """
909 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
910 for locale_info in self.locales:
911 f.write('{},{}\n'.format(locale_info.code,
912 int(locale_info.rtl)))
913
914 def build(self):
915 """Builds all images required by a board."""
916 # Clean up output directory
917 if os.path.exists(self.output_dir):
918 shutil.rmtree(self.output_dir)
919 os.makedirs(self.output_dir)
920
921 if not os.path.exists(self.stage_dir):
922 raise BuildImageError('Missing stage folder. Run make in strings dir.')
923
924 # Clean up temp directory
925 if os.path.exists(self.temp_dir):
926 shutil.rmtree(self.temp_dir)
927 os.makedirs(self.temp_dir)
928
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800929 print('Converting sprite images...')
930 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800931
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800932 print('Building generic strings...')
933 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800934
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800935 print('Building localized strings...')
936 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800937
938 print('Moving language images to locale-independent directory...')
939 self.move_language_images()
940
941 print('Creating locale list file...')
942 self.create_locale_list()
943
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800944 print('Building glyphs...')
945 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800946
947 print('Copying specified images to RW packing directory...')
948 self.copy_images_to_rw()
949
950
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800951def main():
952 """Builds bitmaps for firmware screens."""
953 parser = argparse.ArgumentParser()
954 parser.add_argument('board', help='Target board')
955 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800956 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800957
958 with open(FORMAT_FILE, encoding='utf-8') as f:
959 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800960 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
961
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800962 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800963 check_fonts(formats[KEY_FONTS])
964 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800965 converter = Converter(board, formats, board_config, OUTPUT_DIR)
966 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800967
968
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800969if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800970 main()