This repository was archived by the owner on Feb 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathstringBundle.py
74 lines (59 loc) · 2.32 KB
/
stringBundle.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
if items were added in files in the resources/strings folder,
then execute "pyrcc5 resources.qrc -o resources.py" in the root directory
and execute "pyrcc5 ../resources.qrc -o resources.py" in the libs directory
"""
import re
import os
import sys
import locale
from libs.ustr import ustr
from PyQt5.QtCore import *
class StringBundle:
__create_key = object()
def __init__(self, create_key, locale_str):
assert(create_key == StringBundle.__create_key), "StringBundle must be created using StringBundle.getBundle"
self.id_to_message = {}
paths = self.__create_lookup_fallback_list(locale_str)
for path in paths:
self.__load_bundle(path)
@classmethod
def get_bundle(cls, locale_str=None):
if locale_str is None:
try:
locale_str = locale.getdefaultlocale()[0] if locale.getdefaultlocale() and len(
locale.getdefaultlocale()) > 0 else os.getenv('LANG')
except:
print('Invalid locale')
locale_str = 'en'
return StringBundle(cls.__create_key, locale_str)
def get_string(self, string_id):
assert(string_id in self.id_to_message), "Missing string id : " + string_id
return self.id_to_message[string_id]
def __create_lookup_fallback_list(self, locale_str):
result_paths = []
base_path = ":/strings"
result_paths.append(base_path)
if locale_str is not None:
# Don't follow standard BCP47. Simple fallback
tags = re.split('[^a-zA-Z]', locale_str)
for tag in tags:
last_path = result_paths[-1]
result_paths.append(last_path + '-' + tag)
return result_paths
def __load_bundle(self, path):
PROP_SEPERATOR = '='
f = QFile(path)
if f.exists():
if f.open(QIODevice.ReadOnly | QFile.Text):
text = QTextStream(f)
text.setCodec("UTF-8")
while not text.atEnd():
line = ustr(text.readLine())
key_value = line.split(PROP_SEPERATOR)
key = key_value[0].strip()
value = PROP_SEPERATOR.join(key_value[1:]).strip().strip('"')
self.id_to_message[key] = value
f.close()