diff --git a/tkfilebrowser/constants.py b/tkfilebrowser/constants.py index 05346be..256ba59 100644 --- a/tkfilebrowser/constants.py +++ b/tkfilebrowser/constants.py @@ -79,10 +79,53 @@ IM_RECENT_24 = os.path.join(PATH, "images", "recent_24.png") # --- translation -try: - LANG = locale.getdefaultlocale()[0] -except ValueError: - LANG = 'en' +def _get_locale_messages_category(): + try: + category = locale.LC_MESSAGES + except AttributeError: + # LC_MESSAGES may not be available on non-POSIX OSes + category = locale.LC_ALL + return category + + +class _different_locale: + def __init__(self, _locale): + self.locale = _locale + self.oldlocale = None + self.category = _get_locale_messages_category() + + def __enter__(self): + self.oldlocale = locale.setlocale(self.category, None) + locale.setlocale(self.category, self.locale) + + def __exit__(self, *args): + if self.oldlocale is None: + return + locale.setlocale(self.category, self.oldlocale) + + +def _getdefaultlocale(): + category = _get_locale_messages_category() + _locale = locale.setlocale(category, None) + if _locale == 'C': + with _different_locale(''): + # The LC_MESSAGES locale does not seem to be configured: + # get the user preferred locale. + _locale = locale.setlocale(category, None) + lang = _locale.split('.')[0] + if len(lang) > 2 and lang[2] != '_': + lang = lang[:2] + + from babel import Locale + from babel.core import UnknownLocaleError + try: + babel_locale = Locale.parse(lang) + except UnknownLocaleError: + babel_locale = Locale.parse('en') + return babel_locale + + +LOCALE = _getdefaultlocale() EN = {} FR = {"B": "octets", "MB": "Mo", "kB": "ko", "GB": "Go", "TB": "To", @@ -95,8 +138,8 @@ "Shortcuts": "Raccourcis", "Save As": "Enregistrer sous", "Recent": "Récents", "Recently used": "Récemment utilisés"} LANGUAGES = {"fr": FR, "en": EN} -if LANG[:2] == "fr": - TR = LANGUAGES["fr"] +if LOCALE.language in LANGUAGES: + TR = LANGUAGES[LOCALE.language] else: TR = LANGUAGES["en"] @@ -110,15 +153,15 @@ def _(text): def locale_date(date=None): - return format_date(date, 'short', locale=LANG) + return format_date(date, 'short', locale=LOCALE) def locale_datetime(date=None): - return format_datetime(date, 'EEEE HH:mm', locale=LANG) + return format_datetime(date, 'EEEE HH:mm', locale=LOCALE) def locale_number(nb): - return format_number(nb, locale=LANG) + return format_number(nb, locale=LOCALE) SIZES = [_("B"), _("kB"), _("MB"), _("GB"), _("TB")] @@ -126,7 +169,7 @@ def locale_number(nb): # --- locale settings for dates TODAY = locale_date() YEAR = datetime.now().year -DAY = int(format_date(None, 'D', locale=LANG)) +DAY = int(format_date(None, 'D', locale=LOCALE)) # --- functions