1# ***** BEGIN GPL LICENSE BLOCK *****
2#
3# This program is free software; you can redistribute it and/or
4# modify it under the terms of the GNU General Public License
5# as published by the Free Software Foundation; either version 2
6# of the License, or (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software Foundation,
15# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16#
17# ***** END GPL LICENSE BLOCK *****
18
19# <pep8 compliant>
20
21# Global settings used by all scripts in this dir.
22# XXX Before any use of the tools in this dir, please make a copy of this file
23#     named "setting.py"
24# XXX This is a template, most values should be OK, but some you’ll have to
25#     edit (most probably, BLENDER_EXEC and SOURCE_DIR).
26
27
28import json
29import os
30import sys
31import types
32
33import bpy
34
35###############################################################################
36# MISC
37###############################################################################
38
39# The languages defined in Blender.
40LANGUAGES_CATEGORIES = (
41    # Min completeness level, UI english label.
42    (0.95, "Complete"),
43    (0.33, "In Progress"),
44    (-1.0, "Starting"),
45)
46LANGUAGES = (
47    # ID, UI english label, ISO code.
48    (0, "Automatic (Automatic)", "DEFAULT"),
49    (1, "English (English)", "en_US"),
50    (2, "Japanese (日本語)", "ja_JP"),
51    (3, "Dutch (Nederlandse taal)", "nl_NL"),
52    (4, "Italian (Italiano)", "it_IT"),
53    (5, "German (Deutsch)", "de_DE"),
54    (6, "Finnish (Suomi)", "fi_FI"),
55    (7, "Swedish (Svenska)", "sv_SE"),
56    (8, "French (Français)", "fr_FR"),
57    (9, "Spanish (Español)", "es"),
58    (10, "Catalan (Català)", "ca_AD"),
59    (11, "Czech (Český)", "cs_CZ"),
60    (12, "Portuguese (Português)", "pt_PT"),
61    (13, "Simplified Chinese (简体中文)", "zh_CN"),
62    (14, "Traditional Chinese (繁體中文)", "zh_TW"),
63    (15, "Russian (Русский)", "ru_RU"),
64    (16, "Croatian (Hrvatski)", "hr_HR"),
65    (17, "Serbian (Српски)", "sr_RS"),
66    (18, "Ukrainian (Український)", "uk_UA"),
67    (19, "Polish (Polski)", "pl_PL"),
68    (20, "Romanian (Român)", "ro_RO"),
69    # Using the utf8 flipped form of Arabic (العربية).
70    (21, "Arabic (ﺔﻴﺑﺮﻌﻟﺍ)", "ar_EG"),
71    (22, "Bulgarian (Български)", "bg_BG"),
72    (23, "Greek (Ελληνικά)", "el_GR"),
73    (24, "Korean (한국 언어)", "ko_KR"),
74    (25, "Nepali (नेपाली)", "ne_NP"),
75    # Using the utf8 flipped form of Persian (فارسی).
76    (26, "Persian (ﯽﺳﺭﺎﻓ)", "fa_IR"),
77    (27, "Indonesian (Bahasa indonesia)", "id_ID"),
78    (28, "Serbian Latin (Srpski latinica)", "sr_RS@latin"),
79    (29, "Kyrgyz (Кыргыз тили)", "ky_KG"),
80    (30, "Turkish (Türkçe)", "tr_TR"),
81    (31, "Hungarian (Magyar)", "hu_HU"),
82    (32, "Brazilian Portuguese (Português do Brasil)", "pt_BR"),
83    # Using the utf8 flipped form of Hebrew (עִבְרִית)).
84    (33, "Hebrew (תירִבְעִ)", "he_IL"),
85    (34, "Estonian (Eestlane)", "et_EE"),
86    (35, "Esperanto (Esperanto)", "eo"),
87    (36, "Spanish from Spain (Español de España)", "es_ES"),
88    (37, "Amharic (አማርኛ)", "am_ET"),
89    (38, "Uzbek (Oʻzbek)", "uz_UZ"),
90    (39, "Uzbek Cyrillic (Ўзбек)", "uz_UZ@cyrillic"),
91    (40, "Hindi (मानक हिन्दी)", "hi_IN"),
92    (41, "Vietnamese (tiếng Việt)", "vi_VN"),
93    (42, "Basque (Euskara)", "eu_EU"),
94    (43, "Hausa (Hausa)", "ha"),
95    (44, "Kazakh (қазақша)", "kk_KZ"),
96    (45, "Abkhaz (Аԥсуа бызшәа)", "ab"),
97    (46, "Thai (ภาษาไทย)", "th_TH"),
98    (47, "Slovak (Slovenčina)", "sk_SK"),
99)
100
101# Default context, in py!
102DEFAULT_CONTEXT = bpy.app.translations.contexts.default
103
104# Name of language file used by Blender to generate translations' menu.
105LANGUAGES_FILE = "languages"
106
107# The min level of completeness for a po file to be imported from /branches into /trunk, as a percentage.
108IMPORT_MIN_LEVEL = 0.0
109
110# Languages in /branches we do not want to import in /trunk currently...
111IMPORT_LANGUAGES_SKIP = {
112    'am_ET', 'bg_BG', 'fi_FI', 'el_GR', 'et_EE', 'ne_NP', 'ro_RO', 'uz_UZ', 'uz_UZ@cyrillic', 'kk_KZ', 'es_ES',
113}
114
115# Languages that need RTL pre-processing.
116IMPORT_LANGUAGES_RTL = {
117    'ar_EG', 'fa_IR', 'he_IL',
118}
119
120# The comment prefix used in generated messages.txt file.
121MSG_COMMENT_PREFIX = "#~ "
122
123# The comment prefix used in generated messages.txt file.
124MSG_CONTEXT_PREFIX = "MSGCTXT:"
125
126# The default comment prefix used in po's.
127PO_COMMENT_PREFIX = "# "
128
129# The comment prefix used to mark sources of msgids, in po's.
130PO_COMMENT_PREFIX_SOURCE = "#: "
131
132# The comment prefix used to mark sources of msgids, in po's.
133PO_COMMENT_PREFIX_SOURCE_CUSTOM = "#. :src: "
134
135# The general "generated" comment prefix, in po's.
136PO_COMMENT_PREFIX_GENERATED = "#. "
137
138# The comment prefix used to comment entries in po's.
139PO_COMMENT_PREFIX_MSG = "#~ "
140
141# The comment prefix used to mark fuzzy msgids, in po's.
142PO_COMMENT_FUZZY = "#, fuzzy"
143
144# The prefix used to define context, in po's.
145PO_MSGCTXT = "msgctxt "
146
147# The prefix used to define msgid, in po's.
148PO_MSGID = "msgid "
149
150# The prefix used to define msgstr, in po's.
151PO_MSGSTR = "msgstr "
152
153# The 'header' key of po files.
154PO_HEADER_KEY = (DEFAULT_CONTEXT, "")
155
156PO_HEADER_MSGSTR = (
157    "Project-Id-Version: {blender_ver} ({blender_hash})\\n\n"
158    "Report-Msgid-Bugs-To: \\n\n"
159    "POT-Creation-Date: {time}\\n\n"
160    "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\n"
161    "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\n"
162    "Language-Team: LANGUAGE <LL@li.org>\\n\n"
163    "Language: {uid}\\n\n"
164    "MIME-Version: 1.0\\n\n"
165    "Content-Type: text/plain; charset=UTF-8\\n\n"
166    "Content-Transfer-Encoding: 8bit\n"
167)
168PO_HEADER_COMMENT_COPYRIGHT = (
169    "# Blender's translation file (po format).\n"
170    "# Copyright (C) {year} The Blender Foundation.\n"
171    "# This file is distributed under the same license as the Blender package.\n"
172    "#\n"
173)
174PO_HEADER_COMMENT = (
175    "# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n"
176    "#"
177)
178
179TEMPLATE_ISO_ID = "__TEMPLATE__"
180
181# Num buttons report their label with a trailing ': '...
182NUM_BUTTON_SUFFIX = ": "
183
184# Undocumented operator placeholder string.
185UNDOC_OPS_STR = "(undocumented operator)"
186
187# The gettext domain.
188DOMAIN = "blender"
189
190# Our own "gettext" stuff.
191# File type (ext) to parse.
192PYGETTEXT_ALLOWED_EXTS = {".c", ".cpp", ".cxx", ".hpp", ".hxx", ".h"}
193
194# Max number of contexts into a BLT_I18N_MSGID_MULTI_CTXT macro...
195PYGETTEXT_MAX_MULTI_CTXT = 16
196
197# Where to search contexts definitions, relative to SOURCE_DIR (defined below).
198PYGETTEXT_CONTEXTS_DEFSRC = os.path.join("source", "blender", "blentranslation", "BLT_translation.h")
199
200# Regex to extract contexts defined in BLT_translation.h
201# XXX Not full-proof, but should be enough here!
202PYGETTEXT_CONTEXTS = "#define\\s+(BLT_I18NCONTEXT_[A-Z_0-9]+)\\s+\"([^\"]*)\""
203
204# Keywords' regex.
205# XXX Most unfortunately, we can't use named backreferences inside character sets,
206#     which makes the regexes even more twisty... :/
207_str_base = (
208    # Match void string
209    "(?P<{_}1>[\"'])(?P={_}1)"  # Get opening quote (' or "), and closing immediately.
210    "|"
211    # Or match non-void string
212    "(?P<{_}2>[\"'])"  # Get opening quote (' or ").
213        "(?{capt}(?:"
214            # This one is for crazy things like "hi \\\\\" folks!"...
215            r"(?:(?!<\\)(?:\\\\)*\\(?=(?P={_}2)))|"
216            # The most common case.
217            ".(?!(?P={_}2))"
218        ")+.)"  # Don't forget the last char!
219    "(?P={_}2)"  # And closing quote.
220)
221str_clean_re = _str_base.format(_="g", capt="P<clean>")
222_inbetween_str_re = (
223    # XXX Strings may have comments between their pieces too, not only spaces!
224    r"(?:\s*(?:"
225        # A C comment
226        r"/\*.*(?!\*/).\*/|"
227        # Or a C++ one!
228        r"//[^\n]*\n"
229    # And we are done!
230    r")?)*"
231)
232# Here we have to consider two different cases (empty string and other).
233_str_whole_re = (
234    _str_base.format(_="{_}1_", capt=":") +
235    # Optional loop start, this handles "split" strings...
236    "(?:(?<=[\"'])" + _inbetween_str_re + "(?=[\"'])(?:"
237        + _str_base.format(_="{_}2_", capt=":") +
238    # End of loop.
239    "))*"
240)
241_ctxt_re_gen = lambda uid : r"(?P<ctxt_raw{uid}>(?:".format(uid=uid) + \
242                            _str_whole_re.format(_="_ctxt{uid}".format(uid=uid)) + \
243                            r")|(?:[A-Z_0-9]+))"
244_ctxt_re = _ctxt_re_gen("")
245_msg_re = r"(?P<msg_raw>" + _str_whole_re.format(_="_msg") + r")"
246PYGETTEXT_KEYWORDS = (() +
247    tuple((r"{}\(\s*" + _msg_re + r"\s*\)").format(it)
248          for it in ("IFACE_", "TIP_", "DATA_", "N_")) +
249
250    tuple((r"{}\(\s*" + _ctxt_re + r"\s*,\s*" + _msg_re + r"\s*\)").format(it)
251          for it in ("CTX_IFACE_", "CTX_TIP_", "CTX_DATA_", "CTX_N_")) +
252
253    tuple(("{}\\((?:[^\"',]+,){{1,2}}\\s*" + _msg_re + r"\s*(?:\)|,)").format(it)
254          for it in ("BKE_report", "BKE_reportf", "BKE_reports_prepend", "BKE_reports_prependf",
255                     "CTX_wm_operator_poll_msg_set")) +
256
257    tuple(("{}\\((?:[^\"',]+,){{3}}\\s*" + _msg_re + r"\s*\)").format(it)
258          for it in ("BMO_error_raise",)) +
259
260    tuple(("{}\\((?:[^\"',]+,)\\s*" + _msg_re + r"\s*(?:\)|,)").format(it)
261          for it in ("modifier_setError",)) +
262
263    tuple((r"{}\(\s*" + _msg_re + r"\s*,\s*(?:" +
264           r"\s*,\s*)?(?:".join(_ctxt_re_gen(i) for i in range(PYGETTEXT_MAX_MULTI_CTXT)) + r")?\s*\)").format(it)
265          for it in ("BLT_I18N_MSGID_MULTI_CTXT",))
266)
267
268# Check printf mismatches between msgid and msgstr.
269CHECK_PRINTF_FORMAT = (
270    r"(?!<%)(?:%%)*%"          # Beginning, with handling for crazy things like '%%%%%s'
271    r"[-+#0]?"                 # Flags (note: do not add the ' ' (space) flag here, generates too much false positives!)
272    r"(?:\*|[0-9]+)?"          # Width
273    r"(?:\.(?:\*|[0-9]+))?"    # Precision
274    r"(?:[hljztL]|hh|ll)?"     # Length
275    r"[tldiuoxXfFeEgGaAcspn]"  # Specifiers (note we have Blender-specific %t and %l ones too)
276)
277
278# Should po parser warn when finding a first letter not capitalized?
279WARN_MSGID_NOT_CAPITALIZED = True
280
281# Strings that should not raise above warning!
282WARN_MSGID_NOT_CAPITALIZED_ALLOWED = {
283    "",                              # Simplifies things... :p
284    "ac3",
285    "along X",
286    "along Y",
287    "along Z",
288    "along %s X",
289    "along %s Y",
290    "along %s Z",
291    "along local Z",
292    "arccos(A)",
293    "arcsin(A)",
294    "arctan(A)",
295    "ascii",
296    "author",                        # Addons' field. :/
297    "bItasc",
298    "cos(A)",
299    "cosh(A)",
300    "dbl-",                          # Compacted for 'double', for keymap items.
301    "description",                   # Addons' field. :/
302    "dx",
303    "fBM",
304    "flac",
305    "fps: %.2f",
306    "fps: %i",
307    "gimbal",
308    "global",
309    "glTF 2.0 (.glb/.gltf)",
310    "glTF Binary (.glb)",
311    "glTF Embedded (.gltf)",
312    "glTF Separate (.gltf + .bin + textures)",
313    "invoke() needs to be called before execute()",
314    "iScale",
315    "iso-8859-15",
316    "iTaSC",
317    "iTaSC parameters",
318    "kb",
319    "local",
320    "location",                      # Addons' field. :/
321    "locking %s X",
322    "locking %s Y",
323    "locking %s Z",
324    "mkv",
325    "mm",
326    "mp2",
327    "mp3",
328    "normal",
329    "ogg",
330    "p0",
331    "px",
332    "re",
333    "res",
334    "rv",
335    "sin(A)",
336    "sin(x) / x",
337    "sinh(A)",
338    "sqrt(x*x+y*y+z*z)",
339    "sRGB",
340    "tan(A)",
341    "tanh(A)",
342    "utf-8",
343    "uv_on_emitter() requires a modifier from an evaluated object",
344    "var",
345    "vBVH",
346    "view",
347    "wav",
348    "wmOwnerID '%s' not in workspace '%s'",
349    "y",
350    # Sub-strings.
351    "available with",
352    "brown fox",
353    "can't save image while rendering",
354    "constructive modifier",
355    "cursor",
356    "custom",
357    "custom matrix",
358    "custom orientation",
359    "edge data",
360    "exp(A)",
361    "expected a timeline/animation area to be active",
362    "expected a view3d region",
363    "expected a view3d region & editcurve",
364    "expected a view3d region & editmesh",
365    "face data",
366    "gimbal",
367    "global",
368    "image file not found",
369    "image format is read-only",
370    "image path can't be written to",
371    "in memory to enable editing!",
372    "insufficient content",
373    "jumps over",
374    "left",
375    "local",
376    "multi-res modifier",
377    "non-triangle face",
378    "normal",
379    "performance impact!",
380    "right",
381    "the lazy dog",
382    "unable to load movie clip",
383    "unable to load text",
384    "unable to open the file",
385    "unknown error reading file",
386    "unknown error stating file",
387    "unknown error writing file",
388    "unsupported font format",
389    "unsupported format",
390    "unsupported image format",
391    "unsupported movie clip format",
392    "vertex data",
393    "verts only",
394    "view",
395    "virtual parents",
396}
397WARN_MSGID_NOT_CAPITALIZED_ALLOWED |= set(lng[2] for lng in LANGUAGES)
398
399WARN_MSGID_END_POINT_ALLOWED = {
400    "Circle|Alt .",
401    "Float Neg. Exp.",
402    "Max Ext.",
403    "Newer graphics drivers may be available to improve Blender support.",
404    "Numpad .",
405    "Pad.",
406    "    RNA Path: bpy.types.",
407    "Temp. Diff.",
408    "Temperature Diff.",
409    "The program will now close.",
410    "Your graphics card or driver has limited support. It may work, but with issues.",
411    "Your graphics card or driver is not supported.",
412}
413
414PARSER_CACHE_HASH = 'sha1'
415
416PARSER_TEMPLATE_ID = "__POT__"
417PARSER_PY_ID = "__PY__"
418
419PARSER_PY_MARKER_BEGIN = "\n# ##### BEGIN AUTOGENERATED I18N SECTION #####\n"
420PARSER_PY_MARKER_END = "\n# ##### END AUTOGENERATED I18N SECTION #####\n"
421
422PARSER_MAX_FILE_SIZE = 2 ** 24  # in bytes, i.e. 16 Mb.
423
424###############################################################################
425# PATHS
426###############################################################################
427
428# The Python3 executable.You’ll likely have to edit it in your user_settings.py
429# if you’re under Windows.
430PYTHON3_EXEC = "python3"
431
432# The Blender executable!
433# This is just an example, you’ll have to edit it in your user_settings.py!
434BLENDER_EXEC = os.path.abspath(os.path.join("foo", "bar", "blender"))
435# check for blender.bin
436if not os.path.exists(BLENDER_EXEC):
437    if os.path.exists(BLENDER_EXEC + ".bin"):
438        BLENDER_EXEC = BLENDER_EXEC + ".bin"
439
440# The gettext msgfmt "compiler". You’ll likely have to edit it in your user_settings.py if you’re under Windows.
441GETTEXT_MSGFMT_EXECUTABLE = "msgfmt"
442
443# The FriBidi C compiled library (.so under Linux, .dll under windows...).
444# You’ll likely have to edit it in your user_settings.py if you’re under Windows., e.g. using the included one:
445#     FRIBIDI_LIB = os.path.join(TOOLS_DIR, "libfribidi.dll")
446FRIBIDI_LIB = "libfribidi.so.0"
447
448# The name of the (currently empty) file that must be present in a po's directory to enable rtl-preprocess.
449RTL_PREPROCESS_FILE = "is_rtl"
450
451# The Blender source root path.
452# This is just an example, you’ll have to override it in your user_settings.py!
453SOURCE_DIR = os.path.abspath(os.path.join("blender"))
454
455# The bf-translation repository (you'll have to override this in your user_settings.py).
456I18N_DIR = os.path.abspath(os.path.join("i18n"))
457
458# The /branches path (relative to I18N_DIR).
459REL_BRANCHES_DIR = os.path.join("branches")
460
461# The /trunk path (relative to I18N_DIR).
462REL_TRUNK_DIR = os.path.join("trunk")
463
464# The /trunk/po path (relative to I18N_DIR).
465REL_TRUNK_PO_DIR = os.path.join(REL_TRUNK_DIR, "po")
466
467# The /trunk/mo path (relative to I18N_DIR).
468REL_TRUNK_MO_DIR = os.path.join(REL_TRUNK_DIR, "locale")
469
470
471# The path to the *git* translation repository (relative to SOURCE_DIR).
472REL_GIT_I18N_DIR = os.path.join("release/datafiles/locale")
473
474
475# The /po path of the *git* translation repository (relative to REL_GIT_I18N_DIR).
476REL_GIT_I18N_PO_DIR = os.path.join("po")
477
478
479# The Blender source path to check for i18n macros (relative to SOURCE_DIR).
480REL_POTFILES_SOURCE_DIR = os.path.join("source")
481
482# The template messages file (relative to I18N_DIR).
483REL_FILE_NAME_POT = os.path.join(REL_BRANCHES_DIR, DOMAIN + ".pot")
484
485# Mo root datapath.
486REL_MO_PATH_ROOT = os.path.join(REL_TRUNK_DIR, "locale")
487
488# Mo path generator for a given language.
489REL_MO_PATH_TEMPLATE = os.path.join(REL_MO_PATH_ROOT, "{}", "LC_MESSAGES")
490
491# Mo path generator for a given language (relative to any "locale" dir).
492MO_PATH_ROOT_RELATIVE = os.path.join("locale")
493MO_PATH_TEMPLATE_RELATIVE = os.path.join(MO_PATH_ROOT_RELATIVE, "{}", "LC_MESSAGES")
494
495# Mo file name.
496MO_FILE_NAME = DOMAIN + ".mo"
497
498# Where to search for py files that may contain ui strings (relative to one of the 'resource_path' of Blender).
499CUSTOM_PY_UI_FILES = [
500    os.path.join("scripts", "startup", "bl_ui"),
501    os.path.join("scripts", "modules", "rna_prop_ui.py"),
502]
503
504# An optional text file listing files to force include/exclude from py_xgettext process.
505SRC_POTFILES = ""
506
507# A cache storing validated msgids, to avoid re-spellchecking them.
508SPELL_CACHE = os.path.join("/tmp", ".spell_cache")
509
510# Threshold defining whether a new msgid is similar enough with an old one to reuse its translation...
511SIMILAR_MSGID_THRESHOLD = 0.75
512
513# Additional import paths to add to sys.path (';' separated)...
514INTERN_PY_SYS_PATHS = ""
515
516# Custom override settings must be one dir above i18n tools itself!
517sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
518try:
519    from bl_i18n_settings_override import *
520except ImportError:  # If no i18n_override_settings available, it’s no error!
521    pass
522
523# Override with custom user settings, if available.
524try:
525    from settings_user import *
526except ImportError:  # If no user_settings available, it’s no error!
527    pass
528
529
530for p in set(INTERN_PY_SYS_PATHS.split(";")):
531    if p:
532        sys.path.append(p)
533
534
535# The settings class itself!
536def _do_get(ref, path):
537    return os.path.normpath(os.path.join(ref, path))
538
539
540def _do_set(ref, path):
541    path = os.path.normpath(path)
542    # If given path is absolute, make it relative to current ref one (else we consider it is already the case!)
543    if os.path.isabs(path):
544        # can't always find the relative path (between drive letters on windows)
545        try:
546            return os.path.relpath(path, ref)
547        except ValueError:
548            pass
549    return path
550
551
552def _gen_get_set_path(ref, name):
553    def _get(self):
554        return _do_get(getattr(self, ref), getattr(self, name))
555
556    def _set(self, value):
557        setattr(self, name, _do_set(getattr(self, ref), value))
558    return _get, _set
559
560
561def _check_valid_data(uid, val):
562    return not uid.startswith("_") and type(val) not in tuple(types.__dict__.values()) + (type,)
563
564
565class I18nSettings:
566    """
567    Class allowing persistence of our settings!
568    Saved in JSon format, so settings should be JSon'able objects!
569    """
570    _settings = None
571
572    def __new__(cls, *args, **kwargs):
573        # Addon preferences are singleton by definition, so is this class!
574        if not I18nSettings._settings:
575            cls._settings = super(I18nSettings, cls).__new__(cls)
576            cls._settings.__dict__ = {uid: val for uid, val in globals().items() if _check_valid_data(uid, val)}
577        return I18nSettings._settings
578
579    def __getstate__(self):
580        return self.to_dict()
581
582    def __setstate__(self, mapping):
583        return self.from_dict(mapping)
584
585    def from_dict(self, mapping):
586        # Special case... :/
587        if "INTERN_PY_SYS_PATHS" in mapping:
588            self.PY_SYS_PATHS = mapping["INTERN_PY_SYS_PATHS"]
589        self.__dict__.update(mapping)
590
591    def to_dict(self):
592        glob = globals()
593        return {uid: val for uid, val in self.__dict__.items() if _check_valid_data(uid, val) and uid in glob}
594
595    def from_json(self, string):
596        self.from_dict(dict(json.loads(string)))
597
598    def to_json(self):
599        # Only save the diff from default i18n_settings!
600        glob = globals()
601        export_dict = {uid: val for uid, val in self.__dict__.items() if _check_valid_data(uid, val) and glob.get(uid) != val}
602        return json.dumps(export_dict)
603
604    def load(self, fname, reset=False):
605        reset = reset or fname is None
606        if reset:
607            self.__dict__ = {uid: data for uid, data in globals().items() if not uid.startswith("_")}
608        if fname is None:
609            return
610        if isinstance(fname, str):
611            if not os.path.isfile(fname):
612                # Assume it is already real JSon string...
613                self.from_json(fname)
614                return
615            with open(fname, encoding="utf8") as f:
616                self.from_json(f.read())
617        # Else assume fname is already a file(like) object!
618        else:
619            self.from_json(fname.read())
620
621    def save(self, fname):
622        if isinstance(fname, str):
623            with open(fname, 'w', encoding="utf8") as f:
624                f.write(self.to_json())
625        # Else assume fname is already a file(like) object!
626        else:
627            fname.write(self.to_json())
628
629    BRANCHES_DIR = property(*(_gen_get_set_path("I18N_DIR", "REL_BRANCHES_DIR")))
630    TRUNK_DIR = property(*(_gen_get_set_path("I18N_DIR", "REL_TRUNK_DIR")))
631    TRUNK_PO_DIR = property(*(_gen_get_set_path("I18N_DIR", "REL_TRUNK_PO_DIR")))
632    TRUNK_MO_DIR = property(*(_gen_get_set_path("I18N_DIR", "REL_TRUNK_MO_DIR")))
633    GIT_I18N_ROOT = property(*(_gen_get_set_path("SOURCE_DIR", "REL_GIT_I18N_DIR")))
634    GIT_I18N_PO_DIR = property(*(_gen_get_set_path("GIT_I18N_ROOT", "REL_GIT_I18N_PO_DIR")))
635    POTFILES_SOURCE_DIR = property(*(_gen_get_set_path("SOURCE_DIR", "REL_POTFILES_SOURCE_DIR")))
636    FILE_NAME_POT = property(*(_gen_get_set_path("I18N_DIR", "REL_FILE_NAME_POT")))
637    MO_PATH_ROOT = property(*(_gen_get_set_path("I18N_DIR", "REL_MO_PATH_ROOT")))
638    MO_PATH_TEMPLATE = property(*(_gen_get_set_path("I18N_DIR", "REL_MO_PATH_TEMPLATE")))
639
640    def _get_py_sys_paths(self):
641        return self.INTERN_PY_SYS_PATHS
642
643    def _set_py_sys_paths(self, val):
644        old_paths = set(self.INTERN_PY_SYS_PATHS.split(";")) - {""}
645        new_paths = set(val.split(";")) - {""}
646        for p in old_paths - new_paths:
647            if p in sys.path:
648                sys.path.remove(p)
649        for p in new_paths - old_paths:
650            sys.path.append(p)
651        self.INTERN_PY_SYS_PATHS = val
652    PY_SYS_PATHS = property(_get_py_sys_paths, _set_py_sys_paths)
653