forked from chr314/nautilus-copy-path
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translation.py
52 lines (43 loc) · 1.79 KB
/
translation.py
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
import locale
import json
import glob
import os
class Translation:
_translations_path = os.path.join(os.path.dirname(__file__), 'translations')
_translations = []
_default_translations = []
@staticmethod
def select_language(lang_code="auto"):
if not lang_code or lang_code == "auto":
default_locale = locale.getdefaultlocale()[0]
try:
lang = default_locale.split("_")
lang_code = lang[0] if len(lang) else "en"
except AttributeError:
lang_code = "en"
if lang_code in Translation.available_languages():
Translation.lang_code = lang_code
else:
Translation.lang_code = "en"
Translation._load_lang(Translation.lang_code)
@staticmethod
def _load_lang(lang_code):
file_path = Translation._translations_path + '/' + lang_code + ".json"
if os.path.isfile(file_path):
with open(file_path) as json_file:
Translation._translations = json.load(json_file)
file_path_en = Translation._translations_path + "/en.json"
if os.path.isfile(file_path_en):
with open(file_path_en) as json_file:
Translation._default_translations = json.load(json_file)
@staticmethod
def available_languages():
return [os.path.splitext(os.path.basename(x))[0] for x in glob.glob(Translation._translations_path + '/*.json')]
@staticmethod
def t(translation):
if not Translation._translations:
Translation.select_language()
if translation in Translation._translations:
return Translation._translations[translation]
elif translation in Translation._default_translations:
return Translation._default_translations[translation]