Skip to content

Commit

Permalink
add pgettext_lazy function
Browse files Browse the repository at this point in the history
  • Loading branch information
SoulMelody committed Jun 28, 2024
1 parent 2618900 commit 65da104
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
17 changes: 17 additions & 0 deletions libresvip/utils/translation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import contextlib
import contextvars
import gettext
import sys
from typing import Optional

from libresvip.core.config import get_ui_settings
Expand All @@ -23,6 +24,22 @@ def gettext_lazy(message: str) -> str:
return gettext.gettext(message)


def pgettext_lazy(context: Optional[str], message: str) -> str:
if context is None:
frame = sys._getframe(1)
context = frame.f_globals.get("__package__")
if context is None:
return gettext_lazy(message)
if not message:
return message
with contextlib.suppress(LookupError):
if (translation := singleton_translation) is not None or (
translation := lazy_translation.get(None)
) is not None:
return translation.pgettext(context, message)
return gettext.pgettext(context, message)


# convertion functions copied from pydub
def get_translation(
domain: str = PACKAGE_NAME, lang: Optional[str] = None
Expand Down
7 changes: 2 additions & 5 deletions libresvip/web/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
from libresvip.utils.search import find_index
from libresvip.utils.text import shorten_error_message, supported_charset_names
from libresvip.utils.translation import get_translation, lazy_translation
from libresvip.utils.translation import gettext_lazy as _
from libresvip.web.elements import QFab, QFabAction

if TYPE_CHECKING:
Expand Down Expand Up @@ -239,11 +240,7 @@ def save_settings() -> None:
context.client.on_disconnect(save_settings)

translation = get_translation()

def _(message: str) -> str:
if message.strip():
return translation.gettext(message)
return message
lazy_translation.set(translation)

def plugin_info(attr_name: str) -> None:
attr = getattr(selected_formats, attr_name)
Expand Down

0 comments on commit 65da104

Please sign in to comment.