create_string_rc.py revision 5821806d5e7f356e8fa4b058a389a808ea183019
1#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium 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
6"""This script generates an rc file and header (setup_strings.{rc,h}) to be
7included in setup.exe. The rc file includes translations for strings pulled
8from generated_resource.grd and the localized .xtb files.
9
10The header file includes IDs for each string, but also has values to allow
11getting a string based on a language offset.  For example, the header file
12looks like this:
13
14#define IDS_L10N_OFFSET_AR 0
15#define IDS_L10N_OFFSET_BG 1
16#define IDS_L10N_OFFSET_CA 2
17...
18#define IDS_L10N_OFFSET_ZH_TW 41
19
20#define IDS_MY_STRING_AR 1600
21#define IDS_MY_STRING_BG 1601
22...
23#define IDS_MY_STRING_BASE IDS_MY_STRING_AR
24
25This allows us to lookup an an ID for a string by adding IDS_MY_STRING_BASE and
26IDS_L10N_OFFSET_* for the language we are interested in.
27"""
28
29import glob
30import os
31import sys
32from xml.dom import minidom
33
34# We are expected to use ../../../../third_party/python_24/python.exe
35from google import path_utils
36
37# Quick hack to fix the path.
38sys.path.append(os.path.abspath('../../tools/grit/grit/extern'))
39sys.path.append(os.path.abspath('../tools/grit/grit/extern'))
40import FP
41
42# The IDs of strings we want to import from generated_resources.grd and include
43# in setup.exe's resources.
44kStringIds = [
45  'IDS_PRODUCT_NAME',
46  'IDS_SXS_SHORTCUT_NAME',
47  'IDS_PRODUCT_APP_HOST_NAME',
48  'IDS_PRODUCT_BINARIES_NAME',
49  'IDS_PRODUCT_DESCRIPTION',
50  'IDS_PRODUCT_FRAME_NAME',
51  'IDS_UNINSTALL_CHROME',
52  'IDS_ABOUT_VERSION_COMPANY_NAME',
53  'IDS_INSTALL_HIGHER_VERSION',
54  'IDS_INSTALL_HIGHER_VERSION_APP_HOST',
55  'IDS_INSTALL_HIGHER_VERSION_CF',
56  'IDS_INSTALL_HIGHER_VERSION_CB_CF',
57  'IDS_INSTALL_SYSTEM_LEVEL_EXISTS',
58  'IDS_INSTALL_FAILED',
59  'IDS_SAME_VERSION_REPAIR_FAILED',
60  'IDS_SAME_VERSION_REPAIR_FAILED_CF',
61  'IDS_SETUP_PATCH_FAILED',
62  'IDS_INSTALL_OS_NOT_SUPPORTED',
63  'IDS_INSTALL_OS_ERROR',
64  'IDS_INSTALL_TEMP_DIR_FAILED',
65  'IDS_INSTALL_UNCOMPRESSION_FAILED',
66  'IDS_INSTALL_INVALID_ARCHIVE',
67  'IDS_INSTALL_INSUFFICIENT_RIGHTS',
68  'IDS_INSTALL_NO_PRODUCTS_TO_UPDATE',
69  'IDS_UNINSTALL_COMPLETE',
70  'IDS_INSTALL_DIR_IN_USE',
71  'IDS_INSTALL_NON_MULTI_INSTALLATION_EXISTS',
72  'IDS_INSTALL_MULTI_INSTALLATION_EXISTS',
73  'IDS_INSTALL_READY_MODE_REQUIRES_CHROME',
74  'IDS_INSTALL_INCONSISTENT_UPDATE_POLICY',
75  'IDS_OEM_MAIN_SHORTCUT_NAME',
76  'IDS_SHORTCUT_TOOLTIP',
77  'IDS_SHORTCUT_NEW_WINDOW',
78  'IDS_APP_LAUNCHER_PRODUCT_DESCRIPTION',
79  'IDS_APP_LAUNCHER_SHORTCUT_TOOLTIP',
80  'IDS_UNINSTALL_APP_LAUNCHER',
81]
82
83# The ID of the first resource string.
84kFirstResourceID = 1600
85
86
87class TranslationStruct:
88  """A helper struct that holds information about a single translation."""
89  def __init__(self, resource_id_str, language, translation):
90    self.resource_id_str = resource_id_str
91    self.language = language
92    self.translation = translation
93
94  def __cmp__(self, other):
95    """Allow TranslationStructs to be sorted by id."""
96    id_result = cmp(self.resource_id_str, other.resource_id_str)
97    return cmp(self.language, other.language) if id_result == 0 else id_result
98
99
100def CollectTranslatedStrings(branding):
101  """Collects all the translations for all the strings specified by kStringIds.
102  Returns a list of tuples of (string_id, language, translated string). The
103  list is sorted by language codes."""
104  strings_file = 'app/chromium_strings.grd'
105  translation_files = 'chromium_strings*.xtb'
106  if branding == 'Chrome':
107    strings_file = 'app/google_chrome_strings.grd'
108    translation_files = 'google_chrome_strings*.xtb'
109  kGeneratedResourcesPath = os.path.join(path_utils.ScriptDir(), '..', '..',
110                                         '..', strings_file)
111  kTranslationDirectory = os.path.join(path_utils.ScriptDir(), '..', '..',
112                                       '..', 'app', 'resources')
113  kTranslationFiles = glob.glob(os.path.join(kTranslationDirectory,
114                                             translation_files))
115
116  # Get the strings out of generated_resources.grd.
117  dom = minidom.parse(kGeneratedResourcesPath)
118  # message_nodes is a list of message dom nodes corresponding to the string
119  # ids we care about.  We want to make sure that this list is in the same
120  # order as kStringIds so we can associate them together.
121  message_nodes = []
122  all_message_nodes = dom.getElementsByTagName('message')
123  for string_id in kStringIds:
124    message_nodes.append([x for x in all_message_nodes if
125                          x.getAttribute('name') == string_id][0])
126  message_texts = [node.firstChild.nodeValue.strip() for node in message_nodes]
127
128  # The fingerprint of the string is the message ID in the translation files
129  # (xtb files).
130  translation_ids = [str(FP.FingerPrint(text)) for text in message_texts]
131
132  # Manually put _EN_US in the list of translated strings because it doesn't
133  # have a .xtb file.
134  translated_strings = []
135  for string_id, message_text in zip(kStringIds, message_texts):
136    translated_strings.append(TranslationStruct(string_id,
137                                                'EN_US',
138                                                message_text))
139
140  # Gather the translated strings from the .xtb files.  If an .xtb file doesn't
141  # have the string we want, use the en-US string.
142  for xtb_filename in kTranslationFiles:
143    dom = minidom.parse(xtb_filename)
144    language = dom.documentElement.getAttribute('lang')
145    language = language.replace('-', '_').upper()
146    translation_nodes = {}
147    for translation_node in dom.getElementsByTagName('translation'):
148      translation_id = translation_node.getAttribute('id')
149      if translation_id in translation_ids:
150        translation_nodes[translation_id] = (translation_node.firstChild
151                                                             .nodeValue
152                                                             .strip())
153    for i, string_id in enumerate(kStringIds):
154      translated_string = translation_nodes.get(translation_ids[i],
155                                                message_texts[i])
156      translated_strings.append(TranslationStruct(string_id,
157                                                  language,
158                                                  translated_string))
159
160  translated_strings.sort()
161  return translated_strings
162
163
164def WriteRCFile(translated_strings, out_filename):
165  """Writes a resource (rc) file with all the language strings provided in
166  |translated_strings|."""
167  kHeaderText = (
168    u'#include "%s.h"\n\n'
169    u'STRINGTABLE\n'
170    u'BEGIN\n'
171  ) % os.path.basename(out_filename)
172  kFooterText = (
173    u'END\n'
174  )
175  lines = [kHeaderText]
176  for translation_struct in translated_strings:
177    # Escape special characters for the rc file.
178    translation = (translation_struct.translation.replace('"', '""')
179                                                 .replace('\t', '\\t')
180                                                 .replace('\n', '\\n'))
181    lines.append(u'  %s "%s"\n' % (translation_struct.resource_id_str + '_'
182                                       + translation_struct.language,
183                                   translation))
184  lines.append(kFooterText)
185  outfile = open(out_filename + '.rc', 'wb')
186  outfile.write(''.join(lines).encode('utf-16'))
187  outfile.close()
188
189
190def WriteHeaderFile(translated_strings, out_filename):
191  """Writes a .h file with resource ids.  This file can be included by the
192  executable to refer to identifiers."""
193  lines = []
194  do_languages_lines = ['\n#define DO_LANGUAGES']
195  installer_string_mapping_lines = ['\n#define DO_INSTALLER_STRING_MAPPING']
196
197  # Write the values for how the languages ids are offset.
198  seen_languages = set()
199  offset_id = 0
200  for translation_struct in translated_strings:
201    lang = translation_struct.language
202    if lang not in seen_languages:
203      seen_languages.add(lang)
204      lines.append('#define IDS_L10N_OFFSET_%s %s' % (lang, offset_id))
205      do_languages_lines.append('  HANDLE_LANGUAGE(%s, IDS_L10N_OFFSET_%s)'
206                                % (lang.replace('_', '-').lower(), lang))
207      offset_id += 1
208    else:
209      break
210
211  # Write the resource ids themselves.
212  resource_id = kFirstResourceID
213  for translation_struct in translated_strings:
214    lines.append('#define %s %s' % (translation_struct.resource_id_str + '_'
215                                        + translation_struct.language,
216                                    resource_id))
217    resource_id += 1
218
219  # Write out base ID values.
220  for string_id in kStringIds:
221    lines.append('#define %s_BASE %s_%s' % (string_id,
222                                            string_id,
223                                            translated_strings[0].language))
224    installer_string_mapping_lines.append('  HANDLE_STRING(%s_BASE, %s)'
225                                          % (string_id, string_id))
226
227  outfile = open(out_filename, 'wb')
228  outfile.write('\n'.join(lines))
229  outfile.write('\n#ifndef RC_INVOKED')
230  outfile.write(' \\\n'.join(do_languages_lines))
231  outfile.write(' \\\n'.join(installer_string_mapping_lines))
232  # .rc files must end in a new line
233  outfile.write('\n#endif  // ndef RC_INVOKED\n')
234  outfile.close()
235
236
237def main(argv):
238  # TODO: Use optparse to parse command line flags.
239  if len(argv) < 2:
240    print 'Usage:\n  %s <output_directory> [branding]' % argv[0]
241    return 1
242  branding = ''
243  if (len(sys.argv) > 2):
244    branding = argv[2]
245  translated_strings = CollectTranslatedStrings(branding)
246  kFilebase = os.path.join(argv[1], 'installer_util_strings')
247  WriteRCFile(translated_strings, kFilebase)
248  WriteHeaderFile(translated_strings, kFilebase + '.h')
249  return 0
250
251
252if '__main__' == __name__:
253  sys.exit(main(sys.argv))
254