~laney/ubiquity/lp1715605

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-

# Copyright (C) 2006, 2007, 2008 Canonical Ltd.
# Written by Colin Watson <cjwatson@ubuntu.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from __future__ import print_function

import codecs
from functools import reduce
import locale
import os
import re
import subprocess
import sys

from ubiquity import im_switch, misc


def reset_locale(frontend):
    frontend.start_debconf()
    di_locale = frontend.db.get('debian-installer/locale')
    if not di_locale:
        # TODO cjwatson 2006-07-17: maybe fetch
        # languagechooser/language-name and set a language based on
        # that?
        di_locale = 'en_US.UTF-8'
    if 'LANG' not in os.environ or di_locale != os.environ['LANG']:
        os.environ['LANG'] = di_locale
        os.environ['LANGUAGE'] = di_locale
        try:
            locale.setlocale(locale.LC_ALL, '')
        except locale.Error as e:
            print('locale.setlocale failed: %s (LANG=%s)' % (e, di_locale),
                  file=sys.stderr)
        im_switch.start_im()
    return di_locale


_strip_context_re = None


def strip_context(unused_question, string):
    # po-debconf context
    global _strip_context_re
    if _strip_context_re is None:
        _strip_context_re = re.compile(r'\[\s[^\[\]]*\]$')
    string = _strip_context_re.sub('', string)

    return string


_translations = None


def get_translations(languages=None, core_names=[], extra_prefixes=[]):
    """Returns a dictionary {name: {language: description}} of translatable
    strings.

    If languages is set to a list, then only languages in that list will be
    translated. If core_names is also set to a list, then any names in that
    list will still be translated into all languages. If either is set, then
    the dictionary returned will be built from scratch; otherwise, the last
    cached version will be returned."""

    global _translations
    if (_translations is None or languages is not None or core_names or
            extra_prefixes):
        if languages is None:
            use_langs = None
        else:
            use_langs = set('c')
            for lang in languages:
                ll_cc = lang.lower().split('.')[0]
                ll = ll_cc.split('_')[0]
                use_langs.add(ll_cc)
                use_langs.add(ll)

        prefixes = '|'.join((
            'ubiquity',
            'partman/text/undo_everything',
            'partman/text/unusable',
            'partman-basicfilesystems/bad_mountpoint',
            'partman-basicfilesystems/text/specify_mountpoint',
            'partman-basicmethods/text/format',
            'partman-newworld/no_newworld',
            'partman-partitioning',
            'partman-crypto',
            'partman-target/no_root',
            'partman-target/text/method',
            'grub-installer/bootdev',
            'popularity-contest/participate',
        ))
        prefixes = reduce(lambda x, y: x + '|' + y, extra_prefixes, prefixes)

        _translations = {}
        devnull = open('/dev/null', 'w')
        db = subprocess.Popen(
            ['debconf-copydb', 'templatedb', 'pipe',
             '--config=Name:pipe', '--config=Driver:Pipe',
             '--config=InFd:none',
             '--pattern=^(%s)' % prefixes],
            bufsize=8192, stdout=subprocess.PIPE, stderr=devnull,
            # necessary?
            preexec_fn=misc.regain_privileges)
        question = None
        descriptions = {}
        fieldsplitter = re.compile(br':\s*')

        for line in db.stdout:
            line = line.rstrip(b'\n')
            if b':' not in line:
                if question is not None:
                    _translations[question] = descriptions
                    descriptions = {}
                    question = None
                continue

            (name, value) = fieldsplitter.split(line, 1)
            if value == b'':
                continue
            name = name.lower()
            if name == b'name':
                question = value.decode()
            elif name.startswith(b'description'):
                namebits = name.split(b'-', 1)
                if len(namebits) == 1:
                    lang = 'c'
                    decoded_value = value.decode('ASCII', 'replace')
                else:
                    lang = namebits[1].lower().decode()
                    lang, encoding = lang.split('.', 1)
                    decoded_value = value.decode(encoding, 'replace')
                if (use_langs is None or lang in use_langs or
                        question in core_names):
                    decoded_value = strip_context(question, decoded_value)
                    descriptions[lang] = decoded_value.replace('\\n', '\n')
            elif name.startswith(b'extended_description'):
                namebits = name.split(b'-', 1)
                if len(namebits) == 1:
                    lang = 'c'
                    decoded_value = value.decode('ASCII', 'replace')
                else:
                    lang = namebits[1].lower().decode()
                    lang, encoding = lang.split('.', 1)
                    decoded_value = value.decode(encoding, 'replace')
                if (use_langs is None or lang in use_langs or
                        question in core_names):
                    decoded_value = strip_context(question, decoded_value)
                    if lang not in descriptions:
                        descriptions[lang] = decoded_value.replace('\\n', '\n')
                    # TODO cjwatson 2006-09-04: a bit of a hack to get the
                    # description and extended description separately ...
                    if question in ('grub-installer/bootdev',
                                    'partman-newworld/no_newworld',
                                    'ubiquity/text/error_updating_installer'):
                        descriptions["extended:%s" % lang] = \
                            decoded_value.replace('\\n', '\n')

        db.stdout.close()
        db.wait()
        devnull.close()

    return _translations


string_questions = {
    'new_size_label': 'partman-partitioning/new_size',
    'partition_create_heading_label': 'partman-partitioning/text/new',
    'partition_create_type_label': 'partman-partitioning/new_partition_type',
    'partition_mount_label': (
        'partman-basicfilesystems/text/specify_mountpoint'),
    'partition_use_label': 'partman-target/text/method',
    'partition_create_place_label': 'partman-partitioning/new_partition_place',
    'partition_edit_format_checkbutton': 'partman-basicmethods/text/format',
    'grub_device_dialog': 'grub-installer/bootdev',
    'grub_device_label': 'grub-installer/bootdev',
    'encryption_algorithm': 'partman-crypto/text/specify_cipher',
    'partition_encryption_key_size': 'partman-crypto/text/specify_keysize',
    'crypto_iv_algorithm': 'partman-crypto/text/specify_ivalgorithm',
    # TODO: it would be nice to have a neater way to handle stock buttons
    'quit': 'ubiquity/imported/quit',
    'back': 'ubiquity/imported/go-back',
    'cancelbutton': 'ubiquity/imported/cancel',
    'exitbutton': 'ubiquity/imported/quit',
    'closebutton1': 'ubiquity/imported/close',
    'cancelbutton1': 'ubiquity/imported/cancel',
    'okbutton1': 'ubiquity/imported/ok',
}

string_extended = set()


def map_widget_name(prefix, name):
    """Map a widget name to its translatable template."""
    if prefix is None:
        prefix = 'ubiquity/text'
    if '/' in name and not name.startswith('password/'):
        question = name
    elif name in string_questions:
        question = string_questions[name]
    else:
        if name.endswith('1'):
            name = name[:-1]
        question = '%s/%s' % (prefix, name)
    return question


def get_string(name, lang, prefix=None):
    """Get the translation of a single string."""
    question = map_widget_name(prefix, name)
    translations = get_translations()
    if question not in translations:
        return None

    if lang is None:
        lang = 'c'
    else:
        lang = lang.lower()
    if name in string_extended:
        lang = 'extended:%s' % lang

    if lang in translations[question]:
        text = translations[question][lang]
    else:
        ll_cc = lang.split('.')[0]
        ll = ll_cc.split('_')[0]
        if ll_cc in translations[question]:
            text = translations[question][ll_cc]
        elif ll in translations[question]:
            text = translations[question][ll]
        elif lang.startswith('extended:'):
            text = translations[question]['extended:c']
        else:
            text = translations[question]['c']

    return text


# Based on code by Walter Dörwald:
# http://mail.python.org/pipermail/python-list/2007-January/424460.html
def ascii_transliterate(exc):
    if not isinstance(exc, UnicodeEncodeError):
        raise TypeError("don't know how to handle %r" % exc)
    import unicodedata
    s = unicodedata.normalize('NFD', exc.object[exc.start])[:1]
    if ord(s) in range(128):
        return s, exc.start + 1
    else:
        return '', exc.start + 1


codecs.register_error('ascii_transliterate', ascii_transliterate)


# Returns a tuple of (current language, sorted choices, display map).
def get_languages(current_language_index=-1, only_installable=False):
    import gzip
    import icu

    current_language = "English"

    if only_installable:
        from apt.cache import Cache
        # workaround for an issue where euid != uid and the
        # apt cache has not yet been loaded causing a SystemError
        # when libapt-pkg tries to load the Cache the first time.
        with misc.raised_privileges():
            cache = Cache()

    languagelist = gzip.open(
        '/usr/lib/ubiquity/localechooser/languagelist.data.gz')
    language_display_map = {}
    i = 0
    for line in languagelist:
        line = misc.utf8(line)
        if line == '' or line == '\n':
            continue
        code, name, trans = line.strip('\n').split(':')[1:]
        if code in ('C', 'dz', 'km'):
            i += 1
            continue
        # KDE fails to round-trip strings containing U+FEFF ZERO WIDTH
        # NO-BREAK SPACE, and we don't care about the NBSP anyway, so strip
        # it.
        #   https://bugs.launchpad.net/bugs/1001542
        #   (comment # 5 and on)
        trans = trans.strip(" \ufeff")

        if only_installable:
            pkg_name = 'language-pack-%s' % code
            # special case these
            if pkg_name.endswith('_CN'):
                pkg_name = 'language-pack-zh-hans'
            elif pkg_name.endswith('_TW'):
                pkg_name = 'language-pack-zh-hant'
            elif pkg_name.endswith('_NO'):
                pkg_name = pkg_name.split('_NO')[0]
            elif pkg_name.endswith('_BR'):
                pkg_name = pkg_name.split('_BR')[0]
            try:
                pkg = cache[pkg_name]
                if not (pkg.installed or pkg.candidate):
                    i += 1
                    continue
            except KeyError:
                i += 1
                continue

        language_display_map[trans] = (name, code)
        if i == current_language_index:
            current_language = trans
        i += 1
    languagelist.close()

    if only_installable:
        del cache

    try:
        # Note that we always collate with the 'C' locale.  This is far
        # from ideal.  But proper collation always requires a specific
        # language for its collation rules (languages frequently have
        # custom sorting).  This at least gives us common sorting rules,
        # like stripping accents.
        collator = icu.Collator.createInstance(icu.Locale('C'))
    except Exception:
        collator = None

    def compare_choice(x):
        if language_display_map[x][1] == 'C':
            return None  # place C first
        if collator:
            try:
                return collator.getCollationKey(x).getByteArray()
            except Exception:
                pass
        # Else sort by unicode code point, which isn't ideal either,
        # but also has the virtue of sorting like-glyphs together
        return x

    sorted_choices = sorted(language_display_map, key=compare_choice)

    return current_language, sorted_choices, language_display_map


def default_locales():
    with open('/usr/lib/ubiquity/localechooser/languagelist') as languagelist:
        defaults = {}
        for line in languagelist:
            line = misc.utf8(line)
            if line == '' or line == '\n':
                continue
            bits = line.strip('\n').split(';')
            code = bits[0]
            locale = bits[4]
            defaults[code] = locale
    return defaults

# vim:ai:et:sts=4:tw=80:sw=4: