blob: c5af24685a3ba648950bbd52124ea4800f891f3f [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.
5"""Build localized text resources by extracting firmware localization strings
6 and convert into TXT and PNG files into stage folder.
7
8Usage:
9 ./build.py <locale-list>
10"""
11
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +080012import signal
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080013import enum
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080014import glob
Jes Klinke1687a992020-06-16 13:47:17 -070015import json
Hung-Te Lin04addcc2015-03-23 18:43:30 +080016import multiprocessing
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080017import os
18import re
Jes Klinke1687a992020-06-16 13:47:17 -070019import shutil
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080020import subprocess
21import sys
Jes Klinke1687a992020-06-16 13:47:17 -070022import tempfile
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +080023import copy
Hung-Te Lin04addcc2015-03-23 18:43:30 +080024
Hung-Te Lindf738512018-09-14 08:39:27 +080025from PIL import Image
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080026import yaml
27
28SCRIPT_BASE = os.path.dirname(os.path.abspath(__file__))
Yu-Ping Wu10cf2892020-08-10 17:20:11 +080029DEFAULT_NAME = '_DEFAULT_'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080030KEY_LOCALES = 'locales'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080031KEY_FILES = 'files'
32KEY_FONTS = 'fonts'
33KEY_STYLES = 'styles'
Matt Delco4c5580d2019-03-07 14:00:28 -080034DIAGNOSTIC_FILES = 'diagnostic_files'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080035
Jes Klinke1687a992020-06-16 13:47:17 -070036STRINGS_GRD_FILE = 'firmware_strings.grd'
37STRINGS_JSON_FILE_TMPL = '{}.json'
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080038FORMAT_FILE = 'format.yaml'
Yu-Ping Wu8f633b82020-09-22 14:27:57 +080039TXT_TO_PNG_SVG = os.path.join(SCRIPT_BASE, 'text_to_png_svg')
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +080040STRINGS_DIR = os.path.join(SCRIPT_BASE, 'strings')
41LOCALE_DIR = os.path.join(STRINGS_DIR, 'locale')
Yu-Ping Wuae79af62020-09-23 16:48:06 +080042STAGE_DIR = os.path.join(os.getenv('OUTPUT',
43 os.path.join(SCRIPT_BASE, 'build')),
44 '.stage')
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080045
Jes Klinke1687a992020-06-16 13:47:17 -070046# Regular expressions used to eliminate spurious spaces and newlines in
47# translation strings.
48NEWLINE_PATTERN = re.compile(r'([^\n])\n([^\n])')
49NEWLINE_REPLACEMENT = r'\1 \2'
50CRLF_PATTERN = re.compile(r'\r\n')
51MULTIBLANK_PATTERN = re.compile(r' *')
52
Yu-Ping Wu6b282c52020-03-19 12:54:15 +080053
Hung-Te Lin707e2ef2013-08-06 10:20:04 +080054class DataError(Exception):
55 pass
56
57
Yu-Ping Wuae79af62020-09-23 16:48:06 +080058def _load_locale_json_file(locale, json_dir):
Jes Klinke1687a992020-06-16 13:47:17 -070059 result = {}
Yu-Ping Wuae79af62020-09-23 16:48:06 +080060 filename = os.path.join(json_dir, STRINGS_JSON_FILE_TMPL.format(locale))
Yu-Ping Wud71b4452020-06-16 11:00:26 +080061 with open(filename, encoding='utf-8-sig') as input_file:
Jes Klinke1687a992020-06-16 13:47:17 -070062 for tag, msgdict in json.load(input_file).items():
63 msgtext = msgdict['message']
64 msgtext = re.sub(CRLF_PATTERN, '\n', msgtext)
65 msgtext = re.sub(NEWLINE_PATTERN, NEWLINE_REPLACEMENT, msgtext)
66 msgtext = re.sub(MULTIBLANK_PATTERN, ' ', msgtext)
67 # Strip any trailing whitespace. A trailing newline appears to make
68 # Pango report a larger layout size than what's actually visible.
69 msgtext = msgtext.strip()
70 result[tag] = msgtext
71 return result
72
Yu-Ping Wuae79af62020-09-23 16:48:06 +080073
74def parse_locale_json_file(locale, json_dir):
75 """Parses given firmware string json file for build_text_files.
Mathew King89d48c62019-02-15 10:08:39 -070076
77 Args:
Yu-Ping Wu8f633b82020-09-22 14:27:57 +080078 locale: The name of the locale, e.g. "da" or "pt-BR".
Jes Klinke1687a992020-06-16 13:47:17 -070079 json_dir: Directory containing json output from grit.
Mathew King89d48c62019-02-15 10:08:39 -070080
81 Returns:
82 A dictionary for mapping of "name to content" for files to be generated.
83 """
Yu-Ping Wuae79af62020-09-23 16:48:06 +080084 result = _load_locale_json_file(locale, json_dir)
85 original = _load_locale_json_file('en', json_dir)
86 for tag in original:
87 if tag not in result:
88 # Use original English text, in case translation is not yet available
89 print('WARNING: locale "%s", missing entry %s' % (locale, tag))
90 result[tag] = original[tag]
Mathew King89d48c62019-02-15 10:08:39 -070091
Yu-Ping Wuae79af62020-09-23 16:48:06 +080092 return result
Mathew King89d48c62019-02-15 10:08:39 -070093
Yu-Ping Wuae79af62020-09-23 16:48:06 +080094
95def parse_locale_input_files(locale, json_dir):
96 """Parses all firmware string files for the given locale.
97
98 Args:
99 locale: The name of the locale, e.g. "da" or "pt-BR".
100 json_dir: Directory containing json output from grit.
101
102 Returns:
103 A dictionary for mapping of "name to content" for files to be generated.
104 """
105 result = parse_locale_json_file(locale, json_dir)
106
107 # Walk locale directory to add pre-generated texts such as language names.
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800108 for input_file in glob.glob(os.path.join(LOCALE_DIR, locale, "*.txt")):
Mathew King89d48c62019-02-15 10:08:39 -0700109 name, _ = os.path.splitext(os.path.basename(input_file))
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800110 with open(input_file, 'r', encoding='utf-8-sig') as f:
Mathew King89d48c62019-02-15 10:08:39 -0700111 result[name] = f.read().strip()
Shelley Chen2f616ac2017-05-22 13:19:40 -0700112
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800113 return result
114
115
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800116def create_file(file_name, contents, output_dir):
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800117 """Creates a text file in output directory by given contents.
118
119 Args:
120 file_name: Output file name without extension.
121 contents: A list of strings for file content.
122 output_dir: The directory to store output file.
123 """
124 output_name = os.path.join(output_dir, file_name + '.txt')
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800125 with open(output_name, 'w', encoding='utf-8-sig') as f:
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800126 f.write('\n'.join(contents) + '\n')
127
128
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800129def build_text_files(inputs, files, output_dir):
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800130 """Builds text files from given input data.
131
132 Args:
133 inputs: Dictionary of contents for given file name.
134 files: List of file records: [name, content].
135 output_dir: Directory to generate text files.
136 """
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800137 for file_name, file_content in files.items():
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800138 if file_content is None:
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800139 create_file(file_name, [inputs[file_name]], output_dir)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800140 else:
141 contents = []
142 for data in file_content:
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800143 contents.append(inputs[data])
144 create_file(file_name, contents, output_dir)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800145
146
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800147def convert_text_to_png(locale, input_file, style, font, output_dir):
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800148 """Converts text files into PNG image files.
149
150 Args:
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800151 locale: Locale (language) to select implicit rendering options. None for
152 locale-independent strings.
153 input_file: Path of input text file.
154 style: Style options.
155 font: Font spec.
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800156 output_dir: Directory to generate image files.
157 """
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800158 name, _ = os.path.splitext(os.path.basename(input_file))
159 command = [TXT_TO_PNG_SVG, '--outdir=%s' % output_dir]
160 if locale:
161 command.append('--lan=%s' % locale)
162 if style:
163 command.append(style)
Yu-Ping Wu10cf2892020-08-10 17:20:11 +0800164 if font:
165 command.append("--font='%s'" % font)
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800166 font_size = os.getenv('FONTSIZE')
167 if font_size:
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800168 command.append('--point=%r' % font_size)
Yu-Ping Wu51940352020-09-17 08:48:55 +0800169 command.append('--margin="0 0"')
170 # TODO(b/159399377): Set different widths for titles and descriptions.
171 # Currently only wrap lines for descriptions.
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800172 if '_desc' in name:
Yu-Ping Wu51940352020-09-17 08:48:55 +0800173 # Without the --width option set, the minimum height of the output SVG
174 # image is roughly 22px (for locale 'en'). With --width=WIDTH passed to
175 # pango-view, the width of the output seems to always be (WIDTH * 4 / 3),
176 # regardless of the font being used. Therefore, set the max_width in
177 # points as follows to prevent drawing from exceeding canvas boundary in
178 # depthcharge runtime.
179 # Some of the numbers below are from depthcharge:
180 # - 1000: UI_SCALE
181 # - 50: UI_MARGIN_H
182 # - 228: UI_REC_QR_SIZE
183 # - 24: UI_REC_QR_MARGIN_H
184 # - 24: UI_DESC_TEXT_HEIGHT
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800185 if name == 'rec_phone_step2_desc':
Yu-Ping Wu51940352020-09-17 08:48:55 +0800186 max_width = 1000 - 50 * 2 - 228 - 24 * 2
187 else:
188 max_width = 1000 - 50 * 2
189 max_width_pt = int(22 * max_width / 24 / (4 / 3))
190 command.append('--width=%d' % max_width_pt)
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800191 command.append(input_file)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800192
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800193 return subprocess.call(' '.join(command), shell=True,
194 stdout=subprocess.PIPE) == 0
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800195
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800196
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800197def convert_localized_strings(formats, locales):
198 """Converts localized strings for |locales|."""
199 # Make a copy of formats to avoid modifying it
200 formats = copy.deepcopy(formats)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800201
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800202 if not locales:
203 env_locales = os.getenv('LOCALES')
204 if env_locales:
205 locales = env_locales.split()
206 else:
207 locales = formats[KEY_LOCALES]
208
209 styles = formats[KEY_STYLES]
210 fonts = formats[KEY_FONTS]
211 default_font = fonts.get(DEFAULT_NAME)
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800212
Yu-Ping Wu51940352020-09-17 08:48:55 +0800213 # Sources are one .grd file with identifiers chosen by engineers and
214 # corresponding English texts, as well as a set of .xlt files (one for each
215 # language other than US english) with a mapping from hash to translation.
216 # Because the keys in the xlt files are a hash of the English source text,
217 # rather than our identifiers, such as "btn_cancel", we use the "grit"
218 # command line tool to process the .grd and .xlt files, producing a set of
219 # .json files mapping our identifier to the translated string, one for every
220 # language including US English.
Jes Klinke1687a992020-06-16 13:47:17 -0700221
Yu-Ping Wu51940352020-09-17 08:48:55 +0800222 # Create a temporary directory to place the translation output from grit in.
223 json_dir = tempfile.mkdtemp()
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800224
Yu-Ping Wu51940352020-09-17 08:48:55 +0800225 # This invokes the grit build command to generate JSON files from the XTB
226 # files containing translations. The results are placed in `json_dir` as
227 # specified in firmware_strings.grd, i.e. one JSON file per locale.
228 subprocess.check_call([
229 'grit',
Yu-Ping Wu8f633b82020-09-22 14:27:57 +0800230 '-i', os.path.join(LOCALE_DIR, STRINGS_GRD_FILE),
Yu-Ping Wu51940352020-09-17 08:48:55 +0800231 'build',
232 '-o', os.path.join(json_dir)
233 ])
Jes Klinke1687a992020-06-16 13:47:17 -0700234
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800235 # Ignore SIGINT in child processes
236 sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800237 pool = multiprocessing.Pool(multiprocessing.cpu_count())
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800238 signal.signal(signal.SIGINT, sigint_handler)
239
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800240 results = []
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800241 for locale in locales:
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800242 print(locale, end=' ', flush=True)
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800243 inputs = parse_locale_input_files(locale, json_dir)
244 output_dir = os.path.normpath(os.path.join(STAGE_DIR, 'locale', locale))
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800245 if not os.path.exists(output_dir):
246 os.makedirs(output_dir)
Julius Wernera77900c2018-02-01 17:39:07 -0800247 files = formats[KEY_FILES]
Matt Delco4c5580d2019-03-07 14:00:28 -0800248
249 # Now parse strings for optional features
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800250 if os.getenv('DIAGNOSTIC_UI') == '1' and DIAGNOSTIC_FILES in formats:
Matt Delco4c5580d2019-03-07 14:00:28 -0800251 files.update(formats[DIAGNOSTIC_FILES])
252
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800253 build_text_files(inputs, files, output_dir)
Shelley Chen2f616ac2017-05-22 13:19:40 -0700254
Yu-Ping Wuae79af62020-09-23 16:48:06 +0800255 results += [pool.apply_async(convert_text_to_png,
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800256 (locale,
257 os.path.join(output_dir, '%s.txt' % name),
258 styles.get(name),
259 fonts.get(locale, default_font),
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800260 output_dir))
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800261 for name in formats[KEY_FILES]]
Hung-Te Lin04addcc2015-03-23 18:43:30 +0800262 pool.close()
Jes Klinke1687a992020-06-16 13:47:17 -0700263 if json_dir is not None:
264 shutil.rmtree(json_dir)
Yu-Ping Wud71b4452020-06-16 11:00:26 +0800265 print()
Yu-Ping Wuc90a22f2020-04-24 11:17:15 +0800266
267 try:
268 success = [r.get() for r in results]
269 except KeyboardInterrupt:
270 pool.terminate()
271 pool.join()
272 exit('Aborted by user')
273 else:
274 pool.join()
275 if not all(success):
276 exit('Failed to render some locales')
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800277
278
Yu-Ping Wu7f6639a2020-09-28 15:31:35 +0800279def main(argv):
280 with open(FORMAT_FILE, encoding='utf-8') as f:
281 formats = yaml.load(f)
282
283 # Convert generic (locale-independent) strings
284 styles = formats[KEY_STYLES]
285 fonts = formats[KEY_FONTS]
286 default_font = fonts.get(DEFAULT_NAME)
287
288 for input_file in glob.glob(os.path.join(STRINGS_DIR, '*.txt')):
289 name, _ = os.path.splitext(os.path.basename(input_file))
290 style = styles.get(name)
291 if not convert_text_to_png(None, input_file, style, default_font,
292 STAGE_DIR):
293 exit('Failed to convert text %s' % input_file)
294
295 # Convert localized strings
296 convert_localized_strings(formats, argv)
297
298
Hung-Te Lin707e2ef2013-08-06 10:20:04 +0800299if __name__ == '__main__':
300 main(sys.argv[1:])