[PATCH 2/3] Adapt to the new localization module

Vratislav Podzimek vpodzime at redhat.com
Fri Jul 12 11:01:37 UTC 2013


Things get different but much simpler with the new version of the module.

Signed-off-by: Vratislav Podzimek <vpodzime at redhat.com>
---
 anaconda                                | 38 +++++------------
 pyanaconda/localization.py              | 18 ++++++++
 pyanaconda/timezone.py                  | 36 ++++------------
 pyanaconda/ui/gui/spokes/langsupport.py | 52 ++++++++++++-----------
 pyanaconda/ui/gui/spokes/welcome.py     | 73 ++++++++++++---------------------
 5 files changed, 90 insertions(+), 127 deletions(-)

diff --git a/anaconda b/anaconda
index 7b2fd0d..78ce02c 100755
--- a/anaconda
+++ b/anaconda
@@ -951,32 +951,15 @@ if __name__ == "__main__":
         else:
             log.error("Unknown method: %s", (anaconda.methodstr,))
 
+    from pyanaconda import localization
     # Set the language before loading an interface, when it may be too late.
     if opts.lang:
-        from pyanaconda.localization import Language, LOCALE_PREFERENCES, expand_langs
-
-        langObj = Language(LOCALE_PREFERENCES, territory=None)
-
-        # Given something other than the long format we prefer?  We need to
-        # dig through supported translations to figure out what the user
-        # meant.
-        foundLang = False
-        if not opts.lang in langObj.translations:
-
-            for trans in langObj.translations.keys():
-                if opts.lang in expand_langs(trans):
-                    opts.lang = trans
-                    foundLang = True
-                    break
-
-            if not foundLang:
-                opts.lang = constants.DEFAULT_LANG
-
-        langObj.set_install_lang(opts.lang)
-        ksdata.lang.lang = opts.lang
-        # report if a language specified by the user
-        # or a default was used
-        ksdata.lang.seen = foundLang
+        locales = localization.get_language_locales(opts.lang)
+        if locales:
+            localization.setup_locale(locales[0], ksdata.lang)
+            ksdata.lang.seen = True
+        else:
+            log.error("Invalid locale '%s' given on command line" % opts.lang)
 
     import blivet
     blivet.enable_installer_mode()
@@ -1024,10 +1007,6 @@ if __name__ == "__main__":
                                          exception.test_exception_handling())
     signal.signal(signal.SIGUSR2, lambda signum, frame: anaconda.dumpState())
 
-    if opts.lang:
-        # this is lame, but make things match what we expect (#443408)
-        opts.lang = opts.lang.replace(".utf8", ".UTF-8")
-
     from blivet import storageInitialize
     from pyanaconda.packaging import payloadInitialize
     from pyanaconda.network import networkInitialize, wait_for_connecting_NM_thread
@@ -1084,6 +1063,9 @@ if __name__ == "__main__":
         if not anaconda.ksdata.timezone.nontp:
             iutil.start_service("chronyd")
 
+    # try to load firmware language
+    localization.load_firmware_language(ksdata.lang)
+
     # FIXME:  This will need to be made cleaner once this file starts to take
     # shape with the new UI code.
     anaconda._intf.setup(ksdata)
diff --git a/pyanaconda/localization.py b/pyanaconda/localization.py
index 3611c87..08a9ec6 100644
--- a/pyanaconda/localization.py
+++ b/pyanaconda/localization.py
@@ -318,6 +318,24 @@ def get_locale_timezones(locale):
                                     territoryId=parts.get("territory", ""),
                                     scriptId=parts.get("script", ""))
 
+def get_locale_territory(locale):
+    """
+    Function returning locale's territory.
+
+    :param locale: locale string (see LANGCODE_RE)
+    :type locale: str
+    :return: territory or None
+    :rtype: str or None
+    :raise InvalidLocaleSpec: if an invalid locale is given (see LANGCODE_RE)
+
+    """
+
+    parts = parse_langcode(locale)
+    if "language" not in parts:
+        raise InvalidLocaleSpec("'%s' is not a valid locale" % locale)
+
+    return parts.get("territory", None)
+
 def write_language_configuration(lang, root):
     """
     Write language configuration to the $root/etc/locale.conf file.
diff --git a/pyanaconda/timezone.py b/pyanaconda/timezone.py
index 1dea80b..5dca6fc 100644
--- a/pyanaconda/timezone.py
+++ b/pyanaconda/timezone.py
@@ -26,9 +26,9 @@ configuration, valid timezones recognition etc.
 
 import os
 import pytz
+import langtable
 from collections import OrderedDict
 
-from pyanaconda import localization
 from pyanaconda import iutil
 from pyanaconda.constants import THREAD_STORAGE
 from pyanaconda.threads import threadMgr
@@ -157,42 +157,24 @@ def save_hw_clock(timezone):
     iutil.execWithRedirect(cmd, args)
 
 
-def get_all_territory_timezones(territory):
-    """
-    Return the list of timezones for a given territory.
-
-    :param territory: either localization.LocaleInfo or territory
-
-    """
-
-    if isinstance(territory, localization.LocaleInfo):
-        territory = territory.territory
-
-    try:
-        timezones = pytz.country_timezones(territory)
-    except KeyError:
-        timezones = list()
-
-    timezones = [zone.encode("utf-8") for zone in timezones]
-    return timezones
-
-
 def get_preferred_timezone(territory):
     """
     Get the preferred timezone for a given territory. Note that this function
     simply returns the first timezone in the list of timezones for a given
     territory.
 
-    :param territory: either localization.LocaleInfo or territory
+    :param territory: territory to get preferred timezone for
+    :type territory: str
+    :return: preferred timezone for the given territory or None if no found
+    :rtype: str or None
 
     """
 
-    try:
-        timezone = get_all_territory_timezones(territory)[0]
-    except IndexError:
-        timezone = None
+    timezones = langtable.list_timezones(territoryId=territory)
+    if not timezones:
+        return None
 
-    return timezone
+    return timezones[0]
 
 def get_all_regions_and_timezones():
     """
diff --git a/pyanaconda/ui/gui/spokes/langsupport.py b/pyanaconda/ui/gui/spokes/langsupport.py
index b071c01..66dbad2 100644
--- a/pyanaconda/ui/gui/spokes/langsupport.py
+++ b/pyanaconda/ui/gui/spokes/langsupport.py
@@ -19,12 +19,13 @@
 # Red Hat Author(s): Radek Vykydal <rvykydal at redhat.com>
 #
 
+# pylint: disable-msg=E0611
 from gi.repository import Gtk, Pango
 from pyanaconda.flags import flags
 from pyanaconda.i18n import _, N_
 from pyanaconda.ui.gui.spokes import NormalSpoke
 from pyanaconda.ui.gui.categories.localization import LocalizationCategory
-from pyanaconda.localization import Language, LOCALE_PREFERENCES, expand_langs
+from pyanaconda import localization
 
 import re
 
@@ -65,14 +66,16 @@ class LangsupportSpoke(NormalSpoke):
             renderer = self.builder.get_object(rend)
             column.set_cell_data_func(renderer, self._mark_selected_bold, idx)
 
-        language = Language(LOCALE_PREFERENCES, territory=None)
         # source of lang code <-> UI name mapping
-        self.locale_infos_for_data = language.translations
-        self.locale_infos_for_ui = language.translations
-
-        for code, info in sorted(self.locale_infos_for_ui.items()):
-            self._add_language(self._langsupportStore, info.display_name,
-                               info.english_name, info.short_name,
+        # (localization.get_available_translations() returns a generator)
+        self.locale_infos_for_data = list(localization.get_available_translations())
+        self.locale_infos_for_ui = self.locale_infos_for_data[:]
+
+        for locale in sorted(self.locale_infos_for_ui):
+            self._add_language(self._langsupportStore,
+                               localization.get_native_name(locale),
+                               localization.get_english_name(locale),
+                               locale,
                                False, True)
 
         self._select_language(self._langsupportStore, self.data.lang.lang)
@@ -85,23 +88,22 @@ class LangsupportSpoke(NormalSpoke):
     def refresh(self):
         self._langsupportEntry.set_text("")
         lang_infos = self._find_localeinfos_for_code(self.data.lang.lang, self.locale_infos_for_ui)
-        lang_short_names = [info.short_name for info in lang_infos]
-        if len(lang_short_names) > 1:
+        if len(lang_infos) > 1:
             log.warning("Found multiple locales for lang %s: %s, picking first" %
-                        (self.data.lang.lang, lang_short_names))
+                        (self.data.lang.lang, lang_infos))
         # Just take the first found
         # TODO - for corner cases choose the one that is common prefix
-        lang_short_names = lang_short_names[:1]
+        lang_infos = lang_infos[:1]
 
-        addsupp_short_names = []
+        addsupp_infos = []
         for code in self.data.lang.addsupport:
             code_infos = self._find_localeinfos_for_code(code, self.locale_infos_for_ui)
-            addsupp_short_names.extend(info.short_name for info in code_infos)
+            addsupp_infos.extend(code_infos)
 
         for row in self._langsupportStore:
-            if row[COL_LANG_SETTING] in addsupp_short_names:
+            if row[COL_LANG_SETTING] in addsupp_infos:
                 row[COL_SELECTED] = True
-            if row[COL_LANG_SETTING] in lang_short_names:
+            if row[COL_LANG_SETTING] in lang_infos:
                 row[COL_SELECTED] = True
                 row[COL_IS_ADDITIONAL] = False
 
@@ -117,7 +119,7 @@ class LangsupportSpoke(NormalSpoke):
             for info in self._find_localeinfos_for_code(code, self.locale_infos_for_data):
                 if info not in infos:
                     infos.append(info)
-        return ", ".join(info.english_name for info in infos)
+        return ", ".join(localization.get_english_name(info) for info in infos)
 
     @property
     def mandatory(self):
@@ -128,13 +130,13 @@ class LangsupportSpoke(NormalSpoke):
         return True
 
     def _find_localeinfos_for_code(self, code, infos):
-        try:
-            retval = [infos[code]]
-        except KeyError:
-            retval = [info for _code, info in infos.items()
-                      if code in expand_langs(_code)]
-            log.debug("locale info found for %s: %s" % (code, retval))
-        return retval
+        if code in infos:
+            return [code]
+        else:
+            retval = [info for info in infos
+                      if code in localization.expand_langs(info)]
+            log.debug("locale infos found for %s: %s" % (code, retval))
+            return retval
 
     def _add_language(self, store, native, english, setting, selected, additional):
         store.append(['<span lang="%s">%s</span>' % (re.sub(r'\..*', '', setting), native),
@@ -142,7 +144,7 @@ class LangsupportSpoke(NormalSpoke):
 
     def _select_language(self, store, language):
         itr = store.get_iter_first()
-        while itr and language not in expand_langs(store[itr][COL_LANG_SETTING]):
+        while itr and language not in localization.expand_langs(store[itr][COL_LANG_SETTING]):
             itr = store.iter_next(itr)
 
         # If we were provided with an unsupported language, just use the default.
diff --git a/pyanaconda/ui/gui/spokes/welcome.py b/pyanaconda/ui/gui/spokes/welcome.py
index 5c3a47f..15d7a04 100644
--- a/pyanaconda/ui/gui/spokes/welcome.py
+++ b/pyanaconda/ui/gui/spokes/welcome.py
@@ -28,7 +28,7 @@ from pyanaconda.ui.gui.hubs.summary import SummaryHub
 from pyanaconda.ui.gui.spokes import StandaloneSpoke
 from pyanaconda.ui.gui.utils import enlightbox
 
-from pyanaconda.localization import Language, LOCALE_PREFERENCES, expand_langs
+from pyanaconda import localization
 from pyanaconda.product import distributionText, isFinal, productName, productVersion
 from pyanaconda import keyboard
 from pyanaconda import timezone
@@ -58,9 +58,8 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
         selected = self.builder.get_object("languageViewSelection")
         (store, itr) = selected.get_selected()
 
-        lang = store[itr][2]
-        self.language.select_translation(lang)
-        self.data.lang.lang = lang
+        locale = store[itr][2]
+        localization.setup_locale(locale, self.data.lang)
 
         # Skip timezone and keyboard default setting for kickstart installs.
         # The user may have provided these values via kickstart and if not, we
@@ -68,22 +67,18 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
         if flags.flags.automatedInstall:
             return
 
-        lang_timezone = None
-        # check if the geolocation lookup returned a time zone
-        # (the geolocation module makes sure that the returned timezone is
-        # either a valid timezone or None)
         geoloc_timezone = geoloc.get_timezone()
+        loc_timezones = localization.get_locale_timezones(self.data.lang.lang)
         if geoloc_timezone:
-            lang_timezone = geoloc_timezone
-        # if no data is provided by Geolocation,
-        # try to get timezone from the current language
-        elif self.language.territory and not self.data.timezone.timezone:
-            lang_timezone = timezone.get_preferred_timezone(self.language.territory)
-
-        if lang_timezone:
-            self.data.timezone.timezone = lang_timezone
-
-        lang_country = self.language.preferred_locale.territory
+            # (the geolocation module makes sure that the returned timezone is
+            # either a valid timezone or None)
+            self.data.timezone.timezone = geoloc_timezone
+        elif loc_timezones and not self.data.timezone.timezone:
+            # no data is provided by Geolocation, try to get timezone from the
+            # current language
+            self.data.timezone.timezone = loc_timezones[0]
+
+        lang_country = localization.get_locale_territory(self.data.lang.lang)
         self._set_keyboard_defaults(store[itr][1], lang_country)
 
     def _set_keyboard_defaults(self, lang_name, country):
@@ -157,24 +152,17 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
         # We can use the territory from geolocation here
         # to preselect the translation, when it's available.
         territory = geoloc.get_territory_code()
-        self.language = Language(LOCALE_PREFERENCES, territory=territory)
-
-        # check if there is one and only one locale for the territory
-        if len(self.language.preferred_locales) != 1:
-            log.info("Didn't get a single locale from Geolocation,"
-                        " falling back to default locale.")
-            self.language = Language(LOCALE_PREFERENCES, territory=None)
-            # Explanation:
-            # Some territories have multiple locales,
-            # for example, the Switzerland has:
-            # de_CH, it_CH and fr_CH
-            # As there is no clear order of preference for them,
-            # it is safer to just fall back to the default locale
+
+        locales = localization.get_territory_locales(territory)
+        if locales and not (self.data.lang.lang and self.data.lang.seen):
+            # get something from the GeoIP lookup and not set in/on the
+            # kickstart/command line
+            localization.setup_locale(locales[0], self.data.lang)
 
         # fill the list with available translations
-        for _code, trans in sorted(self.language.translations.items()):
-            self._addLanguage(store, trans.display_name,
-                              trans.english_name, trans.short_name)
+        for locale in localization.get_available_translations():
+            self._addLanguage(store, localization.get_native_name(locale),
+                              localization.get_english_name(locale), locale)
 
         # Move the default language (whatever was provided on the command line,
         # or by kickstart, or by geoip, or English if nothing else) to the top
@@ -182,16 +170,7 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
         # dropped into the middle of a scrollable list.
         (store, itr) = self._selection.get_selected()
         if not itr:
-            # check if a language was set by kickstart
-            # NOTE: seen means the language was "seen" in
-            # kickstart or boot option, so it overrides
-            # the language detected by geolocation
-            if self.data.lang.lang and self.data.lang.seen:
-                lang = self.data.lang.lang
-            else:
-                lang = self.language.preferred_translation.short_name
-
-            itr = self._selectLanguage(lang)
+            itr = self._selectLanguage(self.data.lang.lang)
 
         # store is the filtered store, and itr is an iter on it.  We need to
         # convert to an iter on the underlying store.
@@ -289,7 +268,8 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
         itr = store.get_iter_first()
         # store[itr][3] is True if this row is a separator in the view, so we
         # want to skip those.
-        while itr and not store[itr][3] and language not in expand_langs(store[itr][2]):
+        while itr and not store[itr][3] \
+                and language not in localization.expand_langs(store[itr][2]):
             itr = store.iter_next(itr)
 
         # If we were provided with an unsupported language, just use the default.
@@ -325,8 +305,7 @@ class WelcomeLanguageSpoke(StandaloneSpoke):
 
         if selected:
             lang = store[selected[0]][2]
-            self.language.set_install_lang(lang)
-            self.language.set_system_lang(lang)
+            localization.setup_locale(lang, self.data.lang)
             self.retranslate(lang)
 
     def on_clear_icon_clicked(self, entry, icon_pos, event):
-- 
1.7.11.7



More information about the anaconda-patches mailing list