i18n.py 7.91 KB
Newer Older
Philipp Auersperg's avatar
Philipp Auersperg committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
# R2 SOLUTIONS PROPRIETARY AND CONFIDENTIAL
#
# 2012-2018 r2 Solutions GmbH
# All Rights Reserved
#
# NOTICE: All information contained herein is, and remains the property of
# r2 Solutions GmbH and its suppliers, if any. The intellectual and technical
# concepts contained herein are proprietary to r2 Solutions GmbH and its
# suppliers. Dissemination of this information or reproduction of this material
# is strictly forbidden unless prior written permission is obtained from
# r2 Solutions GmbH.
#
from os.path import dirname
from os.path import join
import gettext

from kivy.properties import StringProperty
from kivy.uix.screenmanager import Screen
from kivy.app import App

try:
    from jnius import autoclass
except ImportError:
Philipp Auersperg's avatar
Philipp Auersperg committed
25
    autoclass = None
Philipp Auersperg's avatar
Philipp Auersperg committed
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

class I18NContainerBehavior(object):
    """
    Mixin class for Widgets that contain I18NProps in their widget tree
    inheriting classes are responsible to call init_i18n,
    binds on parent to track removing from the widget tree
    """

    def init_i18n(self):
        self.bind(parent=self.on_parent_changed)

    def on_parent_changed(self, *a):
        if self.parent is None:
            self.unbind_observers()

    def walk_widget_tree(self, func, root=None):
        """
        walk through widgets depth first
        :param func: function that takes a widget as paraeter
        :param root:
        :return: None
        """
        if root is None:
            root = self

        func(root)

        for c in root.children:
            self.walk_widget_tree(func, c)

    def unbind_obj(self, obj):
        i18nstr.unbind_obj(obj)

    # @timer
    def unbind_observers(self):
        # print("#obs before:", len(i18nstr.observers))
        self.walk_widget_tree(lambda x: self.unbind_obj(x))
        # print("#obs after:", len(i18nstr.observers))


class I18NScreen(Screen, I18NContainerBehavior):
    """
    Use this class instead of Screen if the widget tree contains I18NProps
    """
    def __init__(self, **kw):
        super().__init__(**kw)
        self.init_i18n()


class I18NObserver(object):
    """
    Observer class for language switching
    """

    def __init__(self, prop, obj):
        """
        stores a property and its object
        :param prop: StringProperty holding an i18n string (contains a msgid)
        :param obj: associated object
        """
        # self.msgid = prop.msgid
        self.obj = obj
        self.prop = prop

    def __call__(self, *a, **kw):
        translation = i18nstr.translate(self.prop.msgid, *a, **kw)
        self.prop.set(self.obj, translation)


class I18NProperty(StringProperty):
    """
    i18n aware String property for kivy
    usage:

    from i18n import I18NProperty as _
    ...

    Builder.load_string('''
    <Foo>:
        Button:
            text:root.text1
    ''')

    class Foo(BoxLayout):
        text1=_('text1')
        text2=_('text2')


    and languages can be switched by:
    _.switch_lang('en')

    the widgets displaying the string properties update automatically

    for translation tasks install the depenencies
    - lingua
    - Babel

    use the following makefile (i18n.mk) for creating the translations:
    - create and update pot and po files by calling ``make -f i18n.mk po``
    - create the binary translation files with ``make -f i18n.mk mo``

        .PHONY: po mo

        LCDIR=../locale
        SOURCES=station.py
        DOMAIN=default
        POTCREATE=../bin/pot-create
        LANGUAGES=ch de en fr

        po:
            ${POTCREATE} ${SOURCES}
            mkdir -p po

            # create pot files if not present
            for lang in ${LANGUAGES}; do \
                if [ ! -f po/$${lang}.po ] ; \
                    then \
                        msginit -i messages.pot --locale $${lang} -o po/$${lang}.po; \
                    fi;\
            done

            #update them if necessary
            for lang in ${LANGUAGES}; do \
                msgmerge --update --no-fuzzy-matching --backup=off po/$${lang}.po messages.pot; \
            done

        mo:
            mkdir -p ${LCDIR}
            for lang in ${LANGUAGES}; do \
                mkdir -p ${LCDIR}/$${lang}/LC_MESSAGES; \
                msgfmt -c -o ${LCDIR}/$${lang}/LC_MESSAGES/${DOMAIN}.mo po/$${lang}.po; \
            done
    """

    def __init__(self, text, default=None, *a, **kw):
        print("init:", a, kw)
        self.default = default
        self.msgid = text
        super().__init__(i18nstr.translate(text), *a, **kw)

    def get(self, obj, *a, **kw):
        if not self.already_got(obj):
            # on first call translate and bind
            # if self.msgid=='successmsg':
            #     import pdb;pdb.set_trace()
            res = i18nstr.translate(self.msgid, default=self.default)
            self.set(obj, res)
            self.mark_got(obj)
            i18nstr.bind(self, obj)
        else:
            res = super().get(obj, *a, **kw)

        return res

    @property
    def markername(self):
        return '__got_%s' % self.name

    def mark_got(self, obj):
        """
        get already called on that object?
        :param obj:
        :return: bool
        """
        setattr(obj, self.markername, True)

    def already_got(self, obj):
        return getattr(obj, self.markername, False)

    @staticmethod
    def switch_lang(lang):
        i18nstr.switch_lang(lang)


class i18nstr(str):
    """i18n aware string, this one is kivy-independent"""
    observers = []
    lang = None
    current_language = 'en'
    domain = 'default'

    def __new__(cls, s, *args, **kwargs):
        if cls.lang is None:
            cls.switch_lang(cls.current_language)
        t = cls.translate(s, *args, **kwargs)
        res = super().__new__(cls, t)
        return res

    @classmethod
    def translate(cls, s, default=None, *args, **kwargs):
        if default is None:
            default = s
        translated = cls.lang(s)
        if translated == s:
            return default.format(*args, **kwargs)
        return translated.format(*args, **kwargs)

    @classmethod
    def bind(cls, prop, obj):
        """
        binds an observer for kivy StringPrperties
        :param prop: a StringPrperty
        :param obj: instance holding that property
        :return: None
        """
        cls.observers.append(I18NObserver(prop, obj))

    @classmethod
    def unbind_prop(cls, prop):
        cls.observers = [o for o in cls.observers if o.prop is not prop]

    @classmethod
    def unbind_obj(cls, obj):
        cls.observers = [o for o in cls.observers if o.obj is not obj]

    @staticmethod
    def get_locale_dir():
Philipp Auersperg's avatar
Philipp Auersperg committed
243
244
245
246
247
        res = join(dirname(__file__), '../../../', 'locale')
        # appdir = App.get_running_app().directory
        # return join(appdir, 'locale')
        # import pdb;pdb.set_trace()
        return res
Philipp Auersperg's avatar
Philipp Auersperg committed
248
249
250
251
252

    @classmethod
    def switch_lang(cls, lang):
        """get the right locale directory, and instanciate a gettext"""
        # print('i18nstr::switch_language:', lang)
Philipp Auersperg's avatar
Philipp Auersperg committed
253
254
255
256
257
258
259
        locale_dir = cls.get_locale_dir()
        print('locale_dir:', locale_dir)
        import os
        try:
            print ('contains:', os.listdir(locale_dir))
        except Exception as e:
            print('fuck:', e)
Philipp Auersperg's avatar
Philipp Auersperg committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        locales = gettext.translation(
            cls.domain,
            locale_dir,
            languages=[lang]
        )
        cls.locales = locales
        cls.lang = locales.gettext
        cls.current_language = lang
        # update all the kv rules attached to this text
        for callback in cls.observers:
            callback()

    @classmethod
    def notify_all(cls):
        for callback in cls.observers:
            callback()

Philipp Auersperg's avatar
Philipp Auersperg committed
277
278
279
280
281
    @staticmethod
    def get_system_language():
        if autoclass:
            JavaUtilLocale = autoclass('java.util.Locale')
            jlocale = JavaUtilLocale
Philipp Auersperg's avatar
Philipp Auersperg committed
282

Philipp Auersperg's avatar
Philipp Auersperg committed
283
284
285
            locale = jlocale.getDefault()
            return locale.language
        else:
Philipp Auersperg's avatar
i18n    
Philipp Auersperg committed
286
            return 'de'
Philipp Auersperg's avatar
Philipp Auersperg committed
287
            raise AttributeError("have no locale, need android")
Philipp Auersperg's avatar
Philipp Auersperg committed
288

Philipp Auersperg's avatar
Philipp Auersperg committed
289
i18nstr.switch_lang('en')
Philipp Auersperg's avatar
Philipp Auersperg committed
290
291