blob: 55732b9ef7b7d19258d8dc95c1c5d6ca61ae6c86 [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
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +080013from concurrent.futures import ProcessPoolExecutor
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080014import os
15import re
Jes Klinke1687a992020-06-16 13:47:17 -070016import shutil
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080017import subprocess
Jes Klinke1687a992020-06-16 13:47:17 -070018import tempfile
Hung-Te Lin04addcc2015-03-23 18:43:30 +080019
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080020import yaml
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080021from PIL import Image
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080022
23SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080024
25STRINGS_GRD_FILE = 'firmware_strings.grd'
26STRINGS_JSON_FILE_TMPL = '{}.json'
27FORMAT_FILE = 'format.yaml'
28BOARDS_CONFIG_FILE = 'boards.yaml'
29
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080030OUTPUT_DIR = os.getenv('OUTPUT', os.path.join(SCRIPT_BASE, 'build'))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080031
32ONE_LINE_DIR = 'one_line'
33SVG_FILES = '*.svg'
34PNG_FILES = '*.png'
35
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080036DIAGNOSTIC_UI = os.getenv('DIAGNOSTIC_UI') == '1'
37
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080038# String format YAML key names.
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080039KEY_DEFAULT = '_DEFAULT_'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080040KEY_LOCALES = 'locales'
Yu-Ping Wu338f0832020-10-23 16:14:40 +080041KEY_GENERIC_FILES = 'generic_files'
42KEY_LOCALIZED_FILES = 'localized_files'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080043KEY_DIAGNOSTIC_FILES = 'diagnostic_files'
44KEY_SPRITE_FILES = 'sprite_files'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080045KEY_STYLES = 'styles'
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080046KEY_BGCOLOR = 'bgcolor'
47KEY_FGCOLOR = 'fgcolor'
48KEY_HEIGHT = 'height'
Yu-Ping Wued95df32020-11-04 17:08:15 +080049KEY_MAX_WIDTH = 'max_width'
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080050KEY_FONTS = 'fonts'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080051
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080052# Board config YAML key names.
Yu-Ping Wu60b45372021-03-31 16:56:08 +080053KEY_SCREEN = 'screen'
54KEY_PANEL = 'panel'
55KEY_SDCARD = 'sdcard'
56KEY_DPI = 'dpi'
57KEY_RTL = 'rtl'
58KEY_RW_OVERRIDE = 'rw_override'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080059
60BMP_HEADER_OFFSET_NUM_LINES = 6
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080061
Jes Klinke1687a992020-06-16 13:47:17 -070062# Regular expressions used to eliminate spurious spaces and newlines in
63# translation strings.
64NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
65NEWLINE_REPLACEMENT = r'\1 \2'
66CRLF_PATTERN = re.compile(r'\r\n')
67MULTIBLANK_PATTERN = re.compile(r' *')
68
Yu-Ping Wu3d07a062021-01-26 18:10:32 +080069# The base for bitmap scales, same as UI_SCALE in depthcharge. For example, if
70# `SCALE_BASE` is 1000, then height = 200 means 20% of the screen height. Also
71# see the 'styles' section in format.yaml.
72SCALE_BASE = 1000
73DEFAULT_GLYPH_HEIGHT = 20
74
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +080075GLYPH_FONT = 'Cousine'
Yu-Ping Wu11027f02020-10-14 17:35:42 +080076
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +080077LocaleInfo = namedtuple('LocaleInfo', ['code', 'rtl'])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080078
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080079
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080080class DataError(Exception):
81 pass
82
83
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +080084class BuildImageError(Exception):
85 """The exception class for all errors generated during build image process."""
86
87
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080088def get_config_with_defaults(configs, key):
89 """Gets config of `key` from `configs`.
90
91 If `key` is not present in `configs`, the default config will be returned.
92 Similarly, if some config values are missing for `key`, the default ones will
93 be used.
94 """
Yu-Ping Wu177f12c2020-11-04 15:55:37 +080095 config = configs[KEY_DEFAULT].copy()
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +080096 config.update(configs.get(key, {}))
97 return config
98
99
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800100def load_boards_config(filename):
101 """Loads the configuration of all boards from `filename`.
102
103 Args:
104 filename: File name of a YAML config file.
105
106 Returns:
107 A dictionary mapping each board name to its config.
108 """
109 with open(filename, 'rb') as file:
110 raw = yaml.load(file)
111
112 configs = {}
113 default = raw[KEY_DEFAULT]
114 if not default:
115 raise BuildImageError('Default configuration is not found')
116 for boards, params in raw.items():
117 if boards == KEY_DEFAULT:
118 continue
119 config = copy.deepcopy(default)
120 if params:
121 config.update(params)
122 for board in boards.replace(',', ' ').split():
123 configs[board] = config
124
125 return configs
126
127
128def check_fonts(fonts):
129 """Check if all fonts are available."""
130 for locale, font in fonts.items():
131 if subprocess.run(['fc-list', '-q', font]).returncode != 0:
132 raise BuildImageError('Font %r not found for locale %r'
133 % (font, locale))
134
135
Yu-Ping Wu97046932021-01-25 17:38:56 +0800136def run_pango_view(input_file, output_file, locale, font, height, max_width,
137 dpi, bgcolor, fgcolor, hinting='full'):
138 """Run pango-view."""
139 command = ['pango-view', '-q']
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800140 if locale:
Yu-Ping Wu97046932021-01-25 17:38:56 +0800141 command += ['--language', locale]
142
143 # Font size should be proportional to the height. Here we use 2 as the
144 # divisor so that setting dpi to 96 (pango-view's default) in boards.yaml
145 # will be roughly equivalent to setting the screen resolution to 1366x768.
146 font_size = height / 2
147 font_spec = '%s %r' % (font, font_size)
148 command += ['--font', font_spec]
149
Yu-Ping Wued95df32020-11-04 17:08:15 +0800150 if max_width:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800151 # When converting text to PNG by pango-view, the ratio of image height to
152 # the font size is usually no more than 1.1875 (with Roboto). Therefore,
153 # set the `max_width_pt` as follows to prevent UI drawing from exceeding
154 # the canvas boundary in depthcharge runtime. The divisor 2 is the same in
155 # the calculation of `font_size` above.
156 max_width_pt = int(max_width / 2 * 1.1875)
Yu-Ping Wued95df32020-11-04 17:08:15 +0800157 command.append('--width=%d' % max_width_pt)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800158 if dpi:
159 command.append('--dpi=%d' % dpi)
Yu-Ping Wucc86d6a2020-11-27 12:48:19 +0800160 command.append('--margin=0')
Yu-Ping Wu97046932021-01-25 17:38:56 +0800161 command += ['--background', bgcolor]
162 command += ['--foreground', fgcolor]
163 command += ['--hinting', hinting]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800164
Yu-Ping Wu97046932021-01-25 17:38:56 +0800165 command += ['--output', output_file]
Yu-Ping Wu11027f02020-10-14 17:35:42 +0800166 command.append(input_file)
167
Yu-Ping Wu97046932021-01-25 17:38:56 +0800168 subprocess.check_call(command, stdout=subprocess.PIPE)
169
170
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800171def parse_locale_json_file(locale, json_dir):
172 """Parses given firmware string json file.
173
174 Args:
175 locale: The name of the locale, e.g. "da" or "pt-BR".
176 json_dir: Directory containing json output from grit.
177
178 Returns:
179 A dictionary for mapping of "name to content" for files to be generated.
180 """
Jes Klinke1687a992020-06-16 13:47:17 -0700181 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800182 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800183 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -0700184 for tag, msgdict in json.load(input_file).items():
185 msgtext = msgdict['message']
186 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
187 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
188 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
189 # Strip any trailing whitespace. A trailing newline appears to make
190 # Pango report a larger layout size than what's actually visible.
191 msgtext = msgtext.strip()
192 result[tag] = msgtext
193 return result
194
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800195
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800196class Converter(object):
Yu-Ping Wu20913672021-03-24 15:25:10 +0800197 """Converter for converting sprites, texts, and glyphs to bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800198
199 Attributes:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800200 DEFAULT_OUTPUT_EXT (str): Default output file extension.
Yu-Ping Wu20913672021-03-24 15:25:10 +0800201 SPRITE_MAX_COLORS (int): Maximum colors to use for converting image sprites
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800202 to bitmaps.
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800203 GLYPH_MAX_COLORS (int): Maximum colors to use for glyph bitmaps.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800204 DEFAULT_BACKGROUND (tuple): Default background color.
205 BACKGROUND_COLORS (dict): Background color of each image. Key is the image
206 name and value is a tuple of RGB values.
207 """
208
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800209 DEFAULT_OUTPUT_EXT = '.bmp'
210
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800211 # background colors
212 DEFAULT_BACKGROUND = (0x20, 0x21, 0x24)
213 LANG_HEADER_BACKGROUND = (0x16, 0x17, 0x19)
214 LINK_SELECTED_BACKGROUND = (0x2a, 0x2f, 0x39)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800215 SPRITE_MAX_COLORS = 128
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800216 GLYPH_MAX_COLORS = 7
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800217
218 BACKGROUND_COLORS = {
219 'ic_dropdown': LANG_HEADER_BACKGROUND,
220 'ic_dropleft_focus': LINK_SELECTED_BACKGROUND,
221 'ic_dropright_focus': LINK_SELECTED_BACKGROUND,
222 'ic_globe': LANG_HEADER_BACKGROUND,
223 'ic_search_focus': LINK_SELECTED_BACKGROUND,
224 'ic_settings_focus': LINK_SELECTED_BACKGROUND,
225 'ic_power_focus': LINK_SELECTED_BACKGROUND,
226 }
227
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800228 def __init__(self, board, formats, board_config, output):
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800229 """Inits converter.
230
231 Args:
232 board: Board name.
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800233 formats: A dictionary of string formats.
234 board_config: A dictionary of board configurations.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800235 output: Output directory.
236 """
237 self.board = board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800238 self.formats = formats
239 self.config = board_config
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800240 self.set_dirs(output)
241 self.set_screen()
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800242 self.set_rename_map()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800243 self.set_locales()
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800244 self.text_max_colors = self.get_text_colors(self.config[KEY_DPI])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800245
246 def set_dirs(self, output):
247 """Sets board output directory and stage directory.
248
249 Args:
250 output: Output directory.
251 """
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800252 self.strings_dir = os.path.join(SCRIPT_BASE, 'strings')
Yu-Ping Wu20913672021-03-24 15:25:10 +0800253 self.sprite_dir = os.path.join(SCRIPT_BASE, 'sprite')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800254 self.locale_dir = os.path.join(self.strings_dir, 'locale')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800255 self.output_dir = os.path.join(output, self.board)
256 self.output_ro_dir = os.path.join(self.output_dir, 'locale', 'ro')
257 self.output_rw_dir = os.path.join(self.output_dir, 'locale', 'rw')
258 self.stage_dir = os.path.join(output, '.stage')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800259 self.stage_locale_dir = os.path.join(self.stage_dir, 'locale')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800260 self.stage_glyph_dir = os.path.join(self.stage_dir, 'glyph')
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800261 self.temp_dir = os.path.join(self.stage_dir, 'tmp')
262
263 def set_screen(self):
264 """Sets screen width and height."""
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800265 self.screen_width, self.screen_height = self.config[KEY_SCREEN]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800266
Yu-Ping Wue445e042020-11-19 15:53:42 +0800267 self.panel_stretch = fractions.Fraction(1)
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800268 if self.config[KEY_PANEL]:
Yu-Ping Wue445e042020-11-19 15:53:42 +0800269 # Calculate `panel_stretch`. It's used to shrink images horizontally so
270 # that the resulting images will look proportional to the original image
271 # on the stretched display. If the display is not stretched, meaning the
272 # aspect ratio is same as the screen where images were rendered, no
273 # shrinking is performed.
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800274 panel_width, panel_height = self.config[KEY_PANEL]
Yu-Ping Wue445e042020-11-19 15:53:42 +0800275 self.panel_stretch = fractions.Fraction(self.screen_width * panel_height,
276 self.screen_height * panel_width)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800277
Yu-Ping Wue445e042020-11-19 15:53:42 +0800278 if self.panel_stretch > 1:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800279 raise BuildImageError('Panel aspect ratio (%f) is smaller than screen '
280 'aspect ratio (%f). It indicates screen will be '
281 'shrunk horizontally. It is currently unsupported.'
282 % (panel_width / panel_height,
283 self.screen_width / self.screen_height))
284
285 # Set up square drawing area
286 self.canvas_px = min(self.screen_width, self.screen_height)
287
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800288 def set_rename_map(self):
289 """Initializes a dict `self.rename_map` for image renaming.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800290
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800291 For each items in the dict, image `key` will be renamed to `value`.
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800292 """
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800293 is_detachable = os.getenv('DETACHABLE') == '1'
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800294 physical_presence = os.getenv('PHYSICAL_PRESENCE')
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800295 rename_map = {}
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800296
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800297 # Navigation instructions
298 if is_detachable:
299 rename_map.update({
300 'nav-button_power': 'nav-key_enter',
301 'nav-button_volume_up': 'nav-key_up',
302 'nav-button_volume_down': 'nav-key_down',
303 'navigate0_tablet': 'navigate0',
304 'navigate1_tablet': 'navigate1',
305 })
306 else:
307 rename_map.update({
308 'nav-button_power': None,
309 'nav-button_volume_up': None,
310 'nav-button_volume_down': None,
311 'navigate0_tablet': None,
312 'navigate1_tablet': None,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800313 })
314
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800315 # Physical presence confirmation
316 if physical_presence == 'recovery':
317 rename_map['rec_to_dev_desc1_phyrec'] = 'rec_to_dev_desc1'
318 rename_map['rec_to_dev_desc1_power'] = None
319 elif physical_presence == 'power':
320 rename_map['rec_to_dev_desc1_phyrec'] = None
321 rename_map['rec_to_dev_desc1_power'] = 'rec_to_dev_desc1'
322 else:
323 rename_map['rec_to_dev_desc1_phyrec'] = None
324 rename_map['rec_to_dev_desc1_power'] = None
325 if physical_presence != 'keyboard':
326 raise BuildImageError('Invalid physical presence setting %s for board '
327 '%s' % (physical_presence, self.board))
328
329 # Broken screen
330 if physical_presence == 'recovery':
331 rename_map['broken_desc_phyrec'] = 'broken_desc'
332 rename_map['broken_desc_detach'] = None
333 elif is_detachable:
334 rename_map['broken_desc_phyrec'] = None
335 rename_map['broken_desc_detach'] = 'broken_desc'
336 else:
337 rename_map['broken_desc_phyrec'] = None
338 rename_map['broken_desc_detach'] = None
339
340 # SD card
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800341 if not self.config[KEY_SDCARD]:
Yu-Ping Wu3d272e72021-03-01 12:01:55 +0800342 rename_map.update({
343 'rec_sel_desc1_no_sd': 'rec_sel_desc1',
344 'rec_sel_desc1_no_phone_no_sd': 'rec_sel_desc1_no_phone',
345 'rec_disk_step1_desc0_no_sd': 'rec_disk_step1_desc0',
346 })
347 else:
348 rename_map.update({
349 'rec_sel_desc1_no_sd': None,
350 'rec_sel_desc1_no_phone_no_sd': None,
351 'rec_disk_step1_desc0_no_sd': None,
352 })
353
354 # Check for duplicate new names
355 new_names = list(new_name for new_name in rename_map.values() if new_name)
356 if len(set(new_names)) != len(new_names):
357 raise BuildImageError('Duplicate values found in rename_map')
358
359 # Map new_name to None to skip image generation for it
360 for new_name in new_names:
361 if new_name not in rename_map:
362 rename_map[new_name] = None
363
364 # Print mapping
365 print('Rename map:')
366 for name, new_name in sorted(rename_map.items()):
367 print(' %s => %s' % (name, new_name))
368
369 self.rename_map = rename_map
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800370
371 def set_locales(self):
372 """Sets a list of locales for which localized images are converted."""
373 # LOCALES environment variable can overwrite boards.yaml
374 env_locales = os.getenv('LOCALES')
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800375 rtl_locales = set(self.config[KEY_RTL])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800376 if env_locales:
377 locales = env_locales.split()
378 else:
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800379 locales = self.config[KEY_LOCALES]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800380 # Check rtl_locales are contained in locales.
381 unknown_rtl_locales = rtl_locales - set(locales)
382 if unknown_rtl_locales:
383 raise BuildImageError('Unknown locales %s in %s' %
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800384 (list(unknown_rtl_locales), KEY_RTL))
Yu-Ping Wuabb9afb2020-10-27 17:15:22 +0800385 self.locales = [LocaleInfo(code, code in rtl_locales)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800386 for code in locales]
387
Yu-Ping Wu96cf0022021-01-07 15:55:49 +0800388 @classmethod
389 def get_text_colors(cls, dpi):
390 """Derive maximum text colors from `dpi`."""
391 if dpi < 64:
392 return 2
393 elif dpi < 72:
394 return 3
395 elif dpi < 80:
396 return 4
397 elif dpi < 96:
398 return 5
399 elif dpi < 112:
400 return 6
401 else:
402 return 7
403
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800404 def _to_px(self, length, num_lines=1):
405 """Converts the relative coordinate to absolute one in pixels."""
Yu-Ping Wu3d07a062021-01-26 18:10:32 +0800406 return int(self.canvas_px * length / SCALE_BASE) * num_lines
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800407
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800408 def _get_png_height(self, png_file):
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800409 # With small DPI, pango-view may generate an empty file
410 if os.path.getsize(png_file) == 0:
411 return 0
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800412 with Image.open(png_file) as image:
413 return image.size[1]
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800414
415 def get_num_lines(self, file, one_line_dir):
416 """Gets the number of lines of text in `file`."""
417 name, _ = os.path.splitext(os.path.basename(file))
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800418 png_name = name + '.png'
419 multi_line_file = os.path.join(os.path.dirname(file), png_name)
420 one_line_file = os.path.join(one_line_dir, png_name)
421 # The number of lines is determined by comparing the height of
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800422 # `multi_line_file` with `one_line_file`, where the latter is generated
423 # without the '--width' option passed to pango-view.
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800424 height = self._get_png_height(multi_line_file)
425 line_height = self._get_png_height(one_line_file)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800426 return int(round(height / line_height))
427
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800428 def convert_svg_to_png(self, svg_file, png_file, height, num_lines,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800429 background):
430 """Converts .svg file to .png file."""
431 background_hex = ''.join(format(x, '02x') for x in background)
432 # If the width/height of the SVG file is specified in points, the
433 # rsvg-convert command with default 90DPI will potentially cause the pixels
434 # at the right/bottom border of the output image to be transparent (or
435 # filled with the specified background color). This seems like an
436 # rsvg-convert issue regarding image scaling. Therefore, use 72DPI here
437 # to avoid the scaling.
438 command = ['rsvg-convert',
439 '--background-color', "'#%s'" % background_hex,
440 '--dpi-x', '72',
441 '--dpi-y', '72',
442 '-o', png_file]
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800443 height_px = self._to_px(height, num_lines)
Yu-Ping Wue445e042020-11-19 15:53:42 +0800444 if height_px <= 0:
445 raise BuildImageError('Height of %r <= 0 (%dpx)' %
446 (os.path.basename(svg_file), height_px))
447 command.extend(['--height', '%d' % height_px])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800448 command.append(svg_file)
449 subprocess.check_call(' '.join(command), shell=True)
450
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800451 def convert_to_bitmap(self, input_file, num_lines, background, output,
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800452 max_colors):
453 """Converts an image file `input_file` to a BMP file `output`."""
454 image = Image.open(input_file)
455
456 # Process alpha channel and transparency.
457 if image.mode == 'RGBA':
458 target = Image.new('RGB', image.size, background)
459 image.load() # required for image.split()
460 mask = image.split()[-1]
461 target.paste(image, mask=mask)
462 elif (image.mode == 'P') and ('transparency' in image.info):
463 exit('Sorry, PNG with RGBA palette is not supported.')
464 elif image.mode != 'RGB':
465 target = image.convert('RGB')
466 else:
467 target = image
468
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800469 width_px, height_px = image.size
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800470 # Stretch image horizontally for stretched display.
Yu-Ping Wue445e042020-11-19 15:53:42 +0800471 if self.panel_stretch != 1:
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800472 width_px = int(width_px * self.panel_stretch)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800473 target = target.resize((width_px, height_px), Image.BICUBIC)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800474
475 # Export and downsample color space.
476 target.convert('P', dither=None, colors=max_colors, palette=Image.ADAPTIVE
477 ).save(output)
478
479 with open(output, 'rb+') as f:
480 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
481 f.write(bytearray([num_lines]))
482
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800483 def convert(self, file, output, height, max_width, max_colors,
Yu-Ping Wued95df32020-11-04 17:08:15 +0800484 one_line_dir=None):
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800485 """Converts image `file` to bitmap format."""
486 name, ext = os.path.splitext(os.path.basename(file))
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800487
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800488 background = self.BACKGROUND_COLORS.get(name, self.DEFAULT_BACKGROUND)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800489
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800490 # Determine num_lines in order to scale the image
491 if one_line_dir and max_width:
492 num_lines = self.get_num_lines(file, one_line_dir)
493 else:
494 num_lines = 1
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800495
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800496 if ext == '.svg':
497 png_file = os.path.join(self.temp_dir, name + '.png')
498 self.convert_svg_to_png(file, png_file, height, num_lines, background)
499 file = png_file
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800500
Yu-Ping Wub87a47d2021-03-30 14:10:22 +0800501 self.convert_to_bitmap(file, num_lines, background, output, max_colors)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800502
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800503 def _bisect_dpi(self, max_dpi, initial_dpi, max_height_px, get_height):
504 """Bisects to find the DPI that produces image height `max_height_px`.
505
506 Args:
507 max_dpi: Maximum DPI for binary search.
508 initial_dpi: Initial DPI to try with in binary search.
509 If specified, the value must be no larger than `max_dpi`.
510 max_height_px: Maximum (target) height to search for.
511 get_height: A function converting DPI to height. The function is called
512 once before returning.
513
514 Returns:
515 The best integer DPI within [1, `max_dpi`].
516 """
517
518 min_dpi = 1
519 first_iter = True
520
521 min_height_px = get_height(min_dpi)
522 if min_height_px > max_height_px:
523 # For some font such as "Noto Sans CJK SC", the generated height cannot
524 # go below a certain value. In this case, find max DPI with
525 # height_px <= min_height_px.
526 while min_dpi < max_dpi:
527 if first_iter and initial_dpi:
528 mid_dpi = initial_dpi
529 else:
530 mid_dpi = (min_dpi + max_dpi + 1) // 2
531 height_px = get_height(mid_dpi)
532 if height_px > min_height_px:
533 max_dpi = mid_dpi - 1
534 else:
535 min_dpi = mid_dpi
536 first_iter = False
537 get_height(max_dpi)
538 return max_dpi
539
540 # Find min DPI with height_px == max_height_px
541 while min_dpi < max_dpi:
542 if first_iter and initial_dpi:
543 mid_dpi = initial_dpi
544 else:
545 mid_dpi = (min_dpi + max_dpi) // 2
546 height_px = get_height(mid_dpi)
547 if height_px == max_height_px:
548 return mid_dpi
549 elif height_px < max_height_px:
550 min_dpi = mid_dpi + 1
551 else:
552 max_dpi = mid_dpi
553 first_iter = False
554 get_height(min_dpi)
555 return min_dpi
556
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800557 def convert_text_to_image(self, locale, input_file, output_file, font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800558 stage_dir, max_colors, height=None, max_width=None,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800559 dpi=None, initial_dpi=None,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800560 bgcolor='#000000', fgcolor='#ffffff',
561 use_svg=False):
562 """Converts text file `input_file` into image file.
563
564 Because pango-view does not support assigning output format options for
565 bitmap, we must create images in SVG/PNG format and then post-process them
566 (e.g. convert into BMP by ImageMagick).
567
568 Args:
569 locale: Locale (language) to select implicit rendering options. None for
570 locale-independent strings.
571 input_file: Path of input text file.
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800572 output_file: Path of output image file.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800573 font: Font name.
574 stage_dir: Directory to store intermediate file(s).
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800575 max_colors: Maximum colors to convert to bitmap.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800576 height: Image height relative to the screen resolution.
577 max_width: Maximum image width relative to the screen resolution.
578 dpi: DPI value passed to pango-view.
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800579 initial_dpi: Initial DPI to try with in binary search.
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800580 bgcolor: Background color (#rrggbb).
581 fgcolor: Foreground color (#rrggbb).
582 use_svg: If set to True, generate SVG file. Otherwise, generate PNG file.
583
584 Returns:
585 Effective DPI, or `None` when not applicable.
586 """
587 one_line_dir = os.path.join(stage_dir, ONE_LINE_DIR)
588 os.makedirs(one_line_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800589
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800590 name, _ = os.path.splitext(os.path.basename(input_file))
591 svg_file = os.path.join(stage_dir, name + '.svg')
592 png_file = os.path.join(stage_dir, name + '.png')
593 png_file_one_line = os.path.join(one_line_dir, name + '.png')
594
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800595 def get_one_line_png_height(dpi):
596 """Generates a one-line PNG using DPI `dpi` and returns its height."""
597 run_pango_view(input_file, png_file_one_line, locale, font, height, 0,
598 dpi, bgcolor, fgcolor)
599 return self._get_png_height(png_file_one_line)
600
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800601 if use_svg:
602 run_pango_view(input_file, svg_file, locale, font, height, 0, dpi,
603 bgcolor, fgcolor, hinting='none')
Yu-Ping Wub87a47d2021-03-30 14:10:22 +0800604 self.convert(svg_file, output_file, height, max_width, max_colors)
605 return None
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800606 else:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800607 if not dpi:
608 raise BuildImageError('DPI must be specified with use_svg=False')
609
610 eff_dpi = dpi
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800611 if locale:
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800612 max_height_px = self._to_px(height)
613 height_px = get_one_line_png_height(dpi)
614 if height_px > max_height_px:
615 eff_dpi = self._bisect_dpi(dpi, initial_dpi, max_height_px,
616 get_one_line_png_height)
617 # NOTE: With the same DPI, the height of multi-line PNG is not necessarily
618 # a multiple of the height of one-line PNG. Therefore, even with the
619 # binary search, the height of the resulting multi-line PNG might be
620 # less than "one_line_height * num_lines". We cannot binary-search DPI
621 # for multi-line PNGs because "num_lines" is dependent on DPI.
622 run_pango_view(input_file, png_file, locale, font, height, max_width,
623 eff_dpi, bgcolor, fgcolor)
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800624 self.convert(png_file, output_file, height, max_width, max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800625 one_line_dir=one_line_dir if locale else None)
626 return eff_dpi
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800627
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800628 def convert_sprite_images(self):
629 """Converts sprite images."""
630 names = self.formats[KEY_SPRITE_FILES]
631 styles = self.formats[KEY_STYLES]
632 # Check redundant images
Yu-Ping Wu20913672021-03-24 15:25:10 +0800633 for filename in glob.glob(os.path.join(self.sprite_dir, SVG_FILES)):
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800634 name, _ = os.path.splitext(os.path.basename(filename))
635 if name not in names:
636 raise BuildImageError('Sprite image %r not specified in %s' %
637 (filename, FORMAT_FILE))
638 # Convert images
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800639 for name, category in names.items():
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800640 new_name = self.rename_map.get(name, name)
641 if not new_name:
642 continue
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800643 style = get_config_with_defaults(styles, category)
Yu-Ping Wu20913672021-03-24 15:25:10 +0800644 file = os.path.join(self.sprite_dir, name + '.svg')
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800645 output = os.path.join(self.output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800646 height = style[KEY_HEIGHT]
Yu-Ping Wu20913672021-03-24 15:25:10 +0800647 self.convert(file, output, height, None, self.SPRITE_MAX_COLORS)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800648
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800649 def build_generic_strings(self):
650 """Builds images of generic (locale-independent) strings."""
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800651 dpi = self.config[KEY_DPI]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800652
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800653 names = self.formats[KEY_GENERIC_FILES]
654 styles = self.formats[KEY_STYLES]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800655 fonts = self.formats[KEY_FONTS]
656 default_font = fonts[KEY_DEFAULT]
657
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800658 for txt_file in glob.glob(os.path.join(self.strings_dir, '*.txt')):
659 name, _ = os.path.splitext(os.path.basename(txt_file))
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800660 new_name = self.rename_map.get(name, name)
661 if not new_name:
662 continue
663 output_file = os.path.join(self.output_dir,
664 new_name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800665 category = names[name]
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800666 style = get_config_with_defaults(styles, category)
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800667 self.convert_text_to_image(None, txt_file, output_file, default_font,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800668 self.stage_dir, self.text_max_colors,
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800669 height=style[KEY_HEIGHT],
670 max_width=style[KEY_MAX_WIDTH],
671 dpi=dpi,
672 bgcolor=style[KEY_BGCOLOR],
673 fgcolor=style[KEY_FGCOLOR])
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800674
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800675 def build_locale(self, locale, names, json_dir):
676 """Builds images of strings for `locale`."""
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800677 dpi = self.config[KEY_DPI]
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800678 styles = self.formats[KEY_STYLES]
679 fonts = self.formats[KEY_FONTS]
680 font = fonts.get(locale, fonts[KEY_DEFAULT])
681 inputs = parse_locale_json_file(locale, json_dir)
682
683 # Walk locale directory to add pre-generated texts such as language names.
684 for txt_file in glob.glob(os.path.join(self.locale_dir, locale, '*.txt')):
685 name, _ = os.path.splitext(os.path.basename(txt_file))
686 with open(txt_file, 'r', encoding='utf-8-sig') as f:
687 inputs[name] = f.read().strip()
688
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800689 stage_dir = os.path.join(self.stage_locale_dir, locale)
690 os.makedirs(stage_dir, exist_ok=True)
691 output_dir = os.path.join(self.output_ro_dir, locale)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800692 os.makedirs(output_dir, exist_ok=True)
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800693
694 eff_dpi_counters = defaultdict(Counter)
695 results = []
696 for name, category in sorted(names.items()):
697 # Ignore missing translation
698 if locale != 'en' and name not in inputs:
699 continue
700
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800701 new_name = self.rename_map.get(name, name)
702 if not new_name:
703 continue
704 output_file = os.path.join(output_dir, new_name + self.DEFAULT_OUTPUT_EXT)
705
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800706 # Write to text file
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800707 text_file = os.path.join(stage_dir, name + '.txt')
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800708 with open(text_file, 'w', encoding='utf-8-sig') as f:
709 f.write(inputs[name] + '\n')
710
711 # Convert text to image
712 style = get_config_with_defaults(styles, category)
713 height = style[KEY_HEIGHT]
714 eff_dpi_counter = eff_dpi_counters[height]
715 if eff_dpi_counter:
716 # Find the effective DPI that appears most times for `height`. This
717 # avoid doing the same binary search again and again. In case of a tie,
718 # pick the largest DPI.
719 best_eff_dpi = max(eff_dpi_counter,
720 key=lambda dpi: (eff_dpi_counter[dpi], dpi))
721 else:
722 best_eff_dpi = None
723 eff_dpi = self.convert_text_to_image(locale,
724 text_file,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800725 output_file,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800726 font,
Yu-Ping Wu95493a92021-03-10 13:10:51 +0800727 stage_dir,
Yu-Ping Wu22dc45f2021-03-24 14:54:36 +0800728 self.text_max_colors,
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800729 height=height,
730 max_width=style[KEY_MAX_WIDTH],
731 dpi=dpi,
732 initial_dpi=best_eff_dpi,
733 bgcolor=style[KEY_BGCOLOR],
734 fgcolor=style[KEY_FGCOLOR])
735 eff_dpi_counter[eff_dpi] += 1
736 assert eff_dpi <= dpi
737 if eff_dpi != dpi:
738 results.append(eff_dpi)
739 return results
740
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800741 def _check_text_width(self, names):
742 """Checks if text image will exceed the expected drawing area at runtime."""
743 styles = self.formats[KEY_STYLES]
744
745 for locale_info in self.locales:
746 locale = locale_info.code
747 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
748 for filename in glob.glob(os.path.join(ro_locale_dir,
749 '*' + self.DEFAULT_OUTPUT_EXT)):
750 name, _ = os.path.splitext(os.path.basename(filename))
751 category = names[name]
752 style = get_config_with_defaults(styles, category)
753 height = style[KEY_HEIGHT]
754 max_width = style[KEY_MAX_WIDTH]
755 if not max_width:
756 continue
757 max_width_px = self._to_px(max_width)
758 with open(filename, 'rb') as f:
759 f.seek(BMP_HEADER_OFFSET_NUM_LINES)
760 num_lines = f.read(1)[0]
761 height_px = self._to_px(height * num_lines)
762 with Image.open(filename) as image:
763 width_px = height_px * image.size[0] // image.size[1]
764 if width_px > max_width_px:
765 raise BuildImageError('%s: Image width %dpx greater than max width '
766 '%dpx' % (filename, width_px, max_width_px))
Yu-Ping Wu08defcc2020-05-07 16:21:03 +0800767
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800768 def _copy_missing_bitmaps(self):
769 """Copy missing (not yet translated) strings from locale 'en'."""
770 en_files = glob.glob(os.path.join(self.output_ro_dir, 'en',
771 '*' + self.DEFAULT_OUTPUT_EXT))
772 for locale_info in self.locales:
773 locale = locale_info.code
774 if locale == 'en':
775 continue
776 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
777 for en_file in en_files:
778 filename = os.path.basename(en_file)
779 locale_file = os.path.join(ro_locale_dir, filename)
780 if not os.path.isfile(locale_file):
781 print("WARNING: Locale '%s': copying '%s'" % (locale, filename))
782 shutil.copyfile(en_file, locale_file)
783
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800784 def build_localized_strings(self):
785 """Builds images of localized strings."""
786 # Sources are one .grd file with identifiers chosen by engineers and
787 # corresponding English texts, as well as a set of .xtb files (one for each
788 # language other than US English) with a mapping from hash to translation.
789 # Because the keys in the .xtb files are a hash of the English source text,
790 # rather than our identifiers, such as "btn_cancel", we use the "grit"
791 # command line tool to process the .grd and .xtb files, producing a set of
792 # .json files mapping our identifier to the translated string, one for every
793 # language including US English.
794
795 # Create a temporary directory to place the translation output from grit in.
796 json_dir = tempfile.mkdtemp()
797
798 # This invokes the grit build command to generate JSON files from the XTB
799 # files containing translations. The results are placed in `json_dir` as
800 # specified in firmware_strings.grd, i.e. one JSON file per locale.
801 subprocess.check_call([
802 'grit',
803 '-i', os.path.join(self.locale_dir, STRINGS_GRD_FILE),
804 'build',
805 '-o', os.path.join(json_dir),
806 ])
807
808 # Make a copy to avoid modifying `self.formats`
809 names = copy.deepcopy(self.formats[KEY_LOCALIZED_FILES])
810 if DIAGNOSTIC_UI:
811 names.update(self.formats[KEY_DIAGNOSTIC_FILES])
812
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800813 executor = ProcessPoolExecutor()
814 futures = []
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800815 for locale_info in self.locales:
816 locale = locale_info.code
817 print(locale, end=' ', flush=True)
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800818 futures.append(executor.submit(self.build_locale, locale, names,
819 json_dir))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800820
821 print()
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800822
823 try:
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800824 results = [future.result() for future in futures]
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800825 except KeyboardInterrupt:
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800826 executor.shutdown(wait=False)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800827 exit('Aborted by user')
828 else:
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800829 executor.shutdown()
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800830
Yu-Ping Wu49606eb2021-03-03 22:43:19 +0800831 effective_dpi = [dpi for r in results for dpi in r if dpi]
Yu-Ping Wuf946dd42021-02-08 16:32:28 +0800832 if effective_dpi:
833 print('Reducing effective DPI to %d, limited by screen resolution' %
834 max(effective_dpi))
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800835
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800836 shutil.rmtree(json_dir)
Yu-Ping Wu2e788b02021-03-09 13:01:31 +0800837 self._check_text_width(names)
Yu-Ping Wu703dcfd2021-01-08 10:52:10 +0800838 self._copy_missing_bitmaps()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800839
840 def move_language_images(self):
841 """Renames language bitmaps and move to self.output_dir.
842
843 The directory self.output_dir contains locale-independent images, and is
844 used for creating vbgfx.bin by archive_images.py.
845 """
846 for locale_info in self.locales:
847 locale = locale_info.code
848 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
849 old_file = os.path.join(ro_locale_dir, 'language.bmp')
850 new_file = os.path.join(self.output_dir, 'language_%s.bmp' % locale)
851 if os.path.exists(new_file):
852 raise BuildImageError('File already exists: %s' % new_file)
853 shutil.move(old_file, new_file)
854
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800855 def build_glyphs(self):
856 """Builds glyphs of ascii characters."""
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800857 os.makedirs(self.stage_glyph_dir, exist_ok=True)
858 output_dir = os.path.join(self.output_dir, 'glyph')
859 os.makedirs(output_dir)
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800860 executor = ProcessPoolExecutor()
861 futures = []
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800862 for c in range(ord(' '), ord('~') + 1):
863 name = f'idx{c:03d}_{c:02x}'
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800864 txt_file = os.path.join(self.stage_glyph_dir, name + '.txt')
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800865 with open(txt_file, 'w', encoding='ascii') as f:
866 f.write(chr(c))
867 f.write('\n')
Yu-Ping Wu31a6e6b2021-03-24 15:08:53 +0800868 output_file = os.path.join(output_dir, name + self.DEFAULT_OUTPUT_EXT)
Yu-Ping Wufc1f4b12021-03-30 14:10:15 +0800869 futures.append(executor.submit(self.convert_text_to_image, None, txt_file,
870 output_file, GLYPH_FONT,
871 self.stage_glyph_dir,
872 self.GLYPH_MAX_COLORS,
873 height=DEFAULT_GLYPH_HEIGHT,
874 use_svg=True))
875 for future in futures:
876 future.result()
877 executor.shutdown()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800878
879 def copy_images_to_rw(self):
880 """Copies localized images specified in boards.yaml for RW override."""
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800881 if not self.config[KEY_RW_OVERRIDE]:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800882 print(' No localized images are specified for RW, skipping')
883 return
884
885 for locale_info in self.locales:
886 locale = locale_info.code
Chung-Sheng Wucd3b4e22021-04-01 18:50:20 +0800887 ro_locale_dir = os.path.join(self.output_ro_dir, locale)
888 rw_locale_dir = os.path.join(self.output_rw_dir, locale)
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800889 os.makedirs(rw_locale_dir)
890
Yu-Ping Wu60b45372021-03-31 16:56:08 +0800891 for name in self.config[KEY_RW_OVERRIDE]:
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800892 ro_src = os.path.join(ro_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
893 rw_dst = os.path.join(rw_locale_dir, name + self.DEFAULT_OUTPUT_EXT)
894 shutil.copyfile(ro_src, rw_dst)
895
896 def create_locale_list(self):
897 """Creates locale list as a CSV file.
898
899 Each line in the file is of format "code,rtl", where
900 - "code": language code of the locale
901 - "rtl": "1" for right-to-left language, "0" otherwise
902 """
903 with open(os.path.join(self.output_dir, 'locales'), 'w') as f:
904 for locale_info in self.locales:
905 f.write('{},{}\n'.format(locale_info.code,
906 int(locale_info.rtl)))
907
908 def build(self):
909 """Builds all images required by a board."""
910 # Clean up output directory
911 if os.path.exists(self.output_dir):
912 shutil.rmtree(self.output_dir)
913 os.makedirs(self.output_dir)
914
915 if not os.path.exists(self.stage_dir):
916 raise BuildImageError('Missing stage folder. Run make in strings dir.')
917
918 # Clean up temp directory
919 if os.path.exists(self.temp_dir):
920 shutil.rmtree(self.temp_dir)
921 os.makedirs(self.temp_dir)
922
Yu-Ping Wu177f12c2020-11-04 15:55:37 +0800923 print('Converting sprite images...')
924 self.convert_sprite_images()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800925
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800926 print('Building generic strings...')
927 self.build_generic_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800928
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800929 print('Building localized strings...')
930 self.build_localized_strings()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800931
932 print('Moving language images to locale-independent directory...')
933 self.move_language_images()
934
935 print('Creating locale list file...')
936 self.create_locale_list()
937
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800938 print('Building glyphs...')
939 self.build_glyphs()
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800940
941 print('Copying specified images to RW packing directory...')
942 self.copy_images_to_rw()
943
944
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800945def main():
946 """Builds bitmaps for firmware screens."""
947 parser = argparse.ArgumentParser()
948 parser.add_argument('board', help='Target board')
949 args = parser.parse_args()
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800950 board = args.board
Yu-Ping Wu8c8bfc72020-10-27 16:19:34 +0800951
952 with open(FORMAT_FILE, encoding='utf-8') as f:
953 formats = yaml.load(f)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800954 board_config = load_boards_config(BOARDS_CONFIG_FILE)[board]
955
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800956 print('Building for ' + board)
Yu-Ping Wu675e7e82021-01-29 08:32:12 +0800957 check_fonts(formats[KEY_FONTS])
958 print('Output dir: ' + OUTPUT_DIR)
Yu-Ping Wue66a7b02020-11-19 15:18:08 +0800959 converter = Converter(board, formats, board_config, OUTPUT_DIR)
960 converter.build()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800961
962
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800963if __name__ == '__main__':
Yu-Ping Wu6e4d3892020-10-19 14:09:37 +0800964 main()