Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only import the translation used #451

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 57 additions & 32 deletions i18n/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ def remove_unnecessary():
def bake_translations():
"""Bakes all translations into a translations.py file inside the krux namespace"""
translation_table = {}
translation_index = []
translation_filenames = [
f
for f in listdir(TRANSLATION_FILES_DIR)
Expand All @@ -183,39 +184,63 @@ def bake_translations():
lookup = {}
for slug, translation in list(translations.items()):
lookup[binascii.crc32(slug.encode("utf-8"))] = translation
translation_table[basename(translation_filename).split(".")[0]] = lookup

with open(
join(SRC_DIR, "krux", "translations.py"), "w", encoding="utf8", newline="\n"
) as translations:
translations.write(
"""# The MIT License (MIT)

# Copyright (c) 2021-2024 Krux contributors

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.\n"""
i18n_locale = basename(translation_filename).split(".")[0]
translation_index.append(i18n_locale)
translation_table[i18n_locale] = lookup

file_header = """# The MIT License (MIT)

# Copyright (c) 2021-2024 Krux contributors

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.\n\n"""

translation_file_prefix = "translations"
translation_file_extension = ".py"

# Write translations index file
filepath = join(
SRC_DIR, "krux", translation_file_prefix + translation_file_extension
)
with open(filepath, "w", encoding="utf8", newline="\n") as translations:
translations.write(file_header)
translations.write("translation_index = ")
translations.write(repr(translation_index))
translations.write("\n\n")
print("Baked", filepath)

# Write each translation file
for key, value in translation_table.items():
filepath = join(
SRC_DIR,
"krux",
translation_file_prefix
+ "_"
+ key.replace("-", "_")
+ translation_file_extension,
)
translations.write("# pylint: disable=C0301\n")
translations.write("translation_table = ")
translations.write(repr(translation_table))
translations.write("\n")
print("Baked " + SRC_DIR + "/krux/" + "translations.py")
with open(filepath, "w", encoding="utf8", newline="\n") as translations:
translations.write(file_header)
translations.write("# pylint: disable=C0301, C0103\n\n")
translations.write("translation_dict = ")
translations.write(repr(value))
translations.write("\n\n")
print("Baked", filepath)


def create_translation_file(locale):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ docs = "poetry run mkdocs serve"
# translations tasks
i18n = "python i18n/i18n.py"
i18n-bake = "python i18n/i18n.py clean prettify bake"
format-translations = "black src/krux/translations.py"
format-translations = "black src/krux/translations*"
i18n-build = ["i18n-bake", "format-translations", "i18n validate"]
# aliases
translations.ref = "i18n-build"
Expand Down
22 changes: 10 additions & 12 deletions src/boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,38 +44,36 @@ def draw_splash():

def check_for_updates():
"""Checks SD card, if a valid firmware is found asks if user wants to update the device"""
from krux import firmware
import krux.firmware

if firmware.upgrade():
if krux.firmware.upgrade():
power_manager.shutdown()

# Unimport firware
sys.modules.pop("krux.firmware")
del sys.modules["krux"].firmware
del firmware
del krux.firmware
del sys.modules["krux.firmware"]


def login(ctx_login):
"""Loads and run the Login page"""
from krux.pages.login import Login
import krux.pages.login

login_start_from = None
while True:
if not Login(ctx_login).run(login_start_from):
if not krux.pages.login.Login(ctx_login).run(login_start_from):
break

if ctx_login.wallet is not None:
# Have a loaded wallet
break
# Login closed due to change of locale at Settings
login_start_from = (
Login.SETTINGS_MENU_INDEX
krux.pages.login.Login.SETTINGS_MENU_INDEX
) # will start Login again from Settings index

# Unimport Login the free memory
sys.modules.pop("krux.pages.login")
del sys.modules["krux"].pages.login
del Login
# Unimport login
del krux.pages.login
del sys.modules["krux.pages.login"]


def home(ctx_home):
Expand Down
36 changes: 24 additions & 12 deletions src/krux/krux_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
MAIN_TXT,
TEST_TXT,
)
from .translations import translation_table
from .key import SCRIPT_LONG_NAMES
from krux.translations import translation_index

BAUDRATES = [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200]

Expand All @@ -53,18 +53,31 @@

THERMAL_ADAFRUIT_TXT = "thermal/adafruit"

TRANSLATION_LOOKUP_TABLE = "translation_dict"
DEFAULT_LOCALE = "en-US"

def translations(locale):

def _get_locale_module(locale):
"""Get the name of the module based on the locale"""
return "krux.translations_" + locale.replace("-", "_")


def _translations(locale):
"""Returns the translations map for the given locale"""
if locale in translation_table:
return translation_table[locale]
return None
if locale == DEFAULT_LOCALE:
return None

translations_module = __import__(
_get_locale_module(locale), None, None, TRANSLATION_LOOKUP_TABLE
)

return getattr(translations_module, TRANSLATION_LOOKUP_TABLE)


def t(slug):
"""Translates a slug according to the current locale"""
slug_id = binascii.crc32(slug.encode("utf-8"))
lookup = translations(Settings().i18n.locale)
lookup = _translations(Settings().i18n.locale)
if not lookup or slug_id not in lookup:
return slug
return lookup[slug_id]
Expand All @@ -77,7 +90,7 @@ class DefaultWallet(SettingsNamespace):
network = CategorySetting("network", MAIN_TXT, [MAIN_TXT, TEST_TXT])
multisig = CategorySetting("multisig", False, [False, True])
script_type = CategorySetting(
"script_type", "Native Segwit - 84", list(SCRIPT_LONG_NAMES.keys())
"script_type", "Native Segwit - 84", tuple(SCRIPT_LONG_NAMES.keys())
)

def label(self, attr):
Expand All @@ -93,9 +106,8 @@ class I18nSettings(SettingsNamespace):
"""I18n-specific settings"""

namespace = "settings.i18n"
DEFAULT_LOCALE = "en-US"
locale = CategorySetting(
"locale", DEFAULT_LOCALE, list(translation_table.keys()) + [DEFAULT_LOCALE]
"locale", DEFAULT_LOCALE, translation_index + [DEFAULT_LOCALE]
)

def label(self, attr):
Expand Down Expand Up @@ -204,7 +216,7 @@ class PrinterSettings(SettingsNamespace):
"cnc/file": ("cnc", "FilePrinter"),
}
namespace = "settings.printer"
driver = CategorySetting("driver", "none", list(PRINTERS.keys()))
driver = CategorySetting("driver", "none", tuple(PRINTERS.keys()))

def __init__(self):
self.thermal = ThermalSettings()
Expand Down Expand Up @@ -335,7 +347,7 @@ class EncryptionSettings(SettingsNamespace):
PBKDF2_HMAC_CBC: AES_CBC_NAME,
}
namespace = "settings.encryption"
version = CategorySetting("version", AES_ECB_NAME, list(VERSION_NAMES.values()))
version = CategorySetting("version", AES_ECB_NAME, tuple(VERSION_NAMES.values()))
pbkdf2_iterations = NumberSetting(int, "pbkdf2_iterations", 100000, [1, 500000])

def label(self, attr):
Expand Down Expand Up @@ -367,7 +379,7 @@ class ThemeSettings(SettingsNamespace):
PINK_THEME: PINK_THEME_NAME,
}
namespace = "settings.appearance"
theme = CategorySetting("theme", DARK_THEME_NAME, list(THEME_NAMES.values()))
theme = CategorySetting("theme", DARK_THEME_NAME, tuple(THEME_NAMES.values()))
screensaver_time = NumberSetting(int, "screensaver_time", 5, [0, 30])

def label(self, attr):
Expand Down
10 changes: 6 additions & 4 deletions src/krux/pages/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,15 +754,17 @@ def load_key_from_tiny_seed_image(self, grid_type="Tiny Seed"):

def tools(self):
"""Handler for the 'Tools' menu item"""
from .tools import Tools
import krux.pages.tools

tools = krux.pages.tools.Tools(self.ctx)
while True:
if Tools(self.ctx).run() == MENU_EXIT:
if tools.run() == MENU_EXIT:
break

# Unimport tools
sys.modules.pop("krux.pages.tools")
del sys.modules["krux.pages"].tools
del tools
del krux.pages.tools
del sys.modules["krux.pages.tools"]

return MENU_CONTINUE

Expand Down
Loading