def init_list( self): langs = [] import gettext self.languages = {} for lang, language in data.languages.items(): system = gettext.find('BKChem', os.path.normpath(os.path.join( os_support.get_bkchem_run_dir(), '../../../../share/locale')), [lang]) if not system: system = gettext.find('BKChem', None, [lang]) local = gettext.find( 'BKChem', os.path.normpath( os.path.join( os_support.get_bkchem_run_dir(), '../locale')), [lang]) if system or local or lang == "en": lang_text = "%s (%s)" % (language, lang) langs.append( lang_text) self.languages[lang_text] = lang langs.sort() # default default = "%s (default)"%_("System default") self.languages[default] = "default" langs.append( default) self.list = Pmw.ScrolledListBox( self.interior(), #selectioncommand=self.select, labelpos = "n", label_text=_("Available Languages"), listbox_selectmode="single", listbox_width=30, items=langs) del gettext self.list.pack()
def __init__(self): # Change this variable to your app name! # The translation files will be under # @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@[email protected] # This is ok for maemo. Not sure in a regular desktop: APP_DIR = os.path.dirname(os.path.abspath(__file__) ) LOCALE_DIR = os.path.join(APP_DIR, 'locale') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ # Now we need to choose the language. We will provide a list, and gettext # will use the first translation available in the list # # In maemo it is in the LANG environment variable # (on desktop is usually LANGUAGES) DEFAULT_LANGUAGES = os.environ.get('LANG', '').split(':') DEFAULT_LANGUAGES += ['en_US'] lc, encoding = locale.getdefaultlocale() if lc: loc = [lc] # Concat all languages (env + default locale), # and here we have the languages and location of the translations loc += DEFAULT_LANGUAGES self.mo_location = LOCALE_DIR # Lets tell those details to gettext # (nothing to change here for you) gettext.install(True, localedir=None, unicode=1) gettext.find(APP_NAME, self.mo_location) gettext.textdomain (APP_NAME) gettext.bind_textdomain_codeset(APP_NAME, "UTF-8") self.language = gettext.translation(APP_NAME, self.mo_location, languages=loc, fallback=True)
def main(): """Main entry point for the script.""" # Set up message catalog access #t = gettext.translation('messages', './po', fallback=True) t = gettext.translation('messages', 'locale', ['en_US']) #_ = t.ugettext #gettext.bindtextdomain('messages', './po') #print gettext.bindtextdomain('messages') #gettext.textdomain('messages') #print gettext.textdomain() _ = t.gettext print _('test') print _('test-a') print gettext.find('messages') en_us = gettext.translation('messages', 'locale', languages=['en_US']) en_us.install() _ = en_us.gettext print _('test') print _('test-a') print en_us.gettext('test-a') print en_us.gettext('test-b') pass
def get_translation(domain, modfile=None): """ Initialize a translation domain. Unless modfile is supplied, the translation will be searched for in the default location. If it is supplied, it's parent directory will be pre-pended to i18n to get the location to use. Translation objects are cached. Keyword arguments: domain -- translation domain modfile -- module file location (search relative to this file + /i18n) """ if domain in __translations: return __translations[domain] gettext.install (True, localedir=None, unicode=1) translation_location = mo_location if modfile is not None: translation_location = "%s/i18n" % os.path.dirname(modfile) gettext.find(domain, translation_location) locale.bindtextdomain(domain, translation_location) gettext.bindtextdomain(domain, translation_location) gettext.textdomain (domain) gettext.bind_textdomain_codeset(domain, "UTF-8") language = gettext.translation (domain, translation_location, languages=languages, fallback=True) __translations[domain] = language return language
def CheckTranslationAvailability(lang): """Function that check the availabilty for a specified language""" # Package name for gettext PACKAGE = 'nicotine' # Local path where to find translation (mo) files LOCAL_MO_PATH = 'languages' # Message to return to the settingswindow if errors are found msg_alert = "" # We don't need checkr since the user wants the english language if lang == "en": return # We try to find the translation file in the current path if gettext.find(PACKAGE, localedir=LOCAL_MO_PATH, languages=[lang] ) is None: # We try to find the translation file in the global path if gettext.find(PACKAGE, languages=[lang]) is None: msg_alert = _("Translation for '%s' not found.") % (lang) return msg_alert
def _init_languages(): """ Create the gettext languages. @return the gettext object """ # Get locals but ignore the encoding (2 arg). default_lc, _ = locale.getdefaultlocale() if default_lc: languages = [default_lc] # Concat all languages (env + default locale), # and here we have the languages and location of the translations languages += DEFAULT_LANGUAGES mo_location = LOCALE_DIR # Lets tell those details to gettext # (nothing to change here for you) gettext.install(True, localedir=None, unicode=1) gettext.find(APP_NAME, mo_location) gettext.textdomain(APP_NAME) gettext.bind_textdomain_codeset(APP_NAME, "UTF-8") return gettext.translation(APP_NAME, mo_location, languages=languages, fallback=True)
def _init (cls): def callback (widget, allocation): cls.widgets["enterGameNotationFrame"].set_size_request( 223, allocation.height-4) cls.widgets["enterGameNotationSidePanel"].connect_after("size-allocate", callback) flags = [] if isInstalled(): path = gettext.find("pychess") else: path = gettext.find("pychess", localedir=addDataPrefix("lang")) if path: loc = locale.getdefaultlocale()[0][-2:].lower() flags.append(addDataPrefix("flags/%s.png" % loc)) flags.append(addDataPrefix("flags/us.png")) cls.ib = ImageButton(flags) cls.widgets["imageButtonDock"].add(cls.ib) cls.ib.show() cls.sourcebuffer = GtkSource.Buffer() sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer) sourceview.set_tooltip_text( _("Type or paste PGN game or FEN positions here")) cls.widgets["scrolledwindow6"].add(sourceview) sourceview.show() # Pgn format does not allow tabulator sourceview.set_insert_spaces_instead_of_tabs(True) sourceview.set_wrap_mode(Gtk.WrapMode.WORD) man = GtkSource.LanguageManager() # Init new version if hasattr(man.props, 'search_path'): try: path = os.path.join(getDataPrefix(),"gtksourceview-1.0/language-specs") man.props.search_path = man.props.search_path + [path] if 'pgn' in man.get_language_ids(): lang = man.get_language('pgn') cls.sourcebuffer.set_language(lang) else: log.warning("Unable to load pgn syntax-highlighting.") cls.sourcebuffer.set_highlight_syntax(True) except NotImplementedError: # Python 2.7.3 in Ubuntu 12.04 log.warning("Unable to load pgn syntax-highlighting.") # Init old version else: os.environ["XDG_DATA_DIRS"] = getDataPrefix()+":/usr/share/" man = LanguageManager() for lang in man.get_available_languages(): if lang.get_name() == "PGN": cls.sourcebuffer.set_language(lang) break else: log.warning("Unable to load pgn syntax-highlighting.") cls.sourcebuffer.set_highlight(True)
def add_translation(): lc, enc = locale.getdefaultlocale() if os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), "i18n")): # Running locally logging.debug("Running local") gettext.bindtextdomain("youtubed-2x", "i18n") lc, enc = locale.getdefaultlocale() lang = gettext.translation("youtubed-2x", "i18n", languages=[lc], fallback=True) logging.debug(lang) lang.install() # gettext.install ("youtubed-2x", "i18n") gtk.glade.bindtextdomain("youtubed-2x", "i18n") elif gettext.find("youtubed-2x"): # Installed. .mo file is in default locale location logging.debug("Found default locale") gettext.install("youtubed-2x") gtk.glade.bindtextdomain("youtubed-2x") elif WINDOWS and os.path.exists(os.path.join(sys.prefix, "share", "locale")): # Windows when using build made with Py2exe logging.debug("Py2exe build") locale_dir = os.path.join(sys.prefix, "share", "locale") gettext.bindtextdomain("youtubed-2x", locale_dir) lang = gettext.translation("youtubed-2x", locale_dir, languages=[lc], fallback=True) logging.debug(lang) lang.install() # gettext.install ("youtubed-2x", "i18n") gtk.glade.bindtextdomain("youtubed-2x", locale_dir) else: # Installed. Try to discover locale location logging.debug("Installed") locale_dir = None if "XDG_DATA_DIRS" in os.environ: data_dirs = os.environ["XDG_DATA_DIRS"].split(":") for data_dir in data_dirs: mofile = gettext.find("youtubed-2x", os.path.join(data_dir, "locale")) logging.debug(mofile) if mofile: locale_dir = os.path.join(data_dir, "locale") break logging.debug(locale_dir) if locale_dir: gettext.install("youtubed-2x", locale_dir) gtk.glade.bindtextdomain("youtubed-2x", locale_dir) else: # If .mo file could not be found, ignore the issue. # Non-translated strings will be used. Install _() # to global namespace gettext.install("youtubed-2x") gtk.glade.bindtextdomain("youtubed-2x") # gettext.install ("youtubed-2x") gtk.glade.textdomain("youtubed-2x") logging.debug(_)
def test_cached_find(self): domain = 'my-unique-domain' key = (domain, None, None, 0) self.assertNotIn(key, _gettextutils._FIND_CACHE) gettext.find(domain) self.assertIn(key, _gettextutils._FIND_CACHE) _gettextutils._FIND_CACHE[key] = "spoof result" self.assertEqual("spoof result", gettext.find(domain)) _gettextutils._FIND_CACHE.pop(key)
def i18n(self): import gettext import pylons import os.path # Repris de pylons.i18n.translation:_get_translator. conf = pylons.config.current_conf() try: rootdir = conf['pylons.paths']['root'] except KeyError: rootdir = conf['pylons.paths'].get('root_path') localedir = os.path.join(rootdir, 'i18n') lang = get_lang() # Localise le fichier *.mo actuellement chargé # et génère le chemin jusqu'au *.js correspondant. filename = gettext.find(conf['pylons.package'], localedir, languages=lang) js = filename[:-3] + '.js' # Récupère et envoie le contenu du fichier de traduction *.js. fhandle = open(js, 'r') translations = fhandle.read() fhandle.close() # Même chose pour les thèmes themes_filename = gettext.find( 'vigilo-themes', resource_filename('vigilo.themes.i18n', ''), languages=lang) themes_js = themes_filename[:-3] + '.js' fhandle = open(themes_js, 'r') translations += fhandle.read() fhandle.close() # Extensions Enterprise try: ent_filename = gettext.find( 'vigilo-vigigraph-enterprise', resource_filename('vigilo.vigigraph_enterprise.i18n', ''), languages=lang) except ImportError: pass else: # Le nom du fichier sera None s'il n'existe pas # de traductions dans la langue demandée. if ent_filename is not None: fhandle = open(ent_filename[:-3] + '.js', 'r') translations += fhandle.read() fhandle.close() return translations
def __init__(self): # The translation files will be under # @locale_dir@/@LANGUAGE@/LC_MESSAGES/@[email protected] self.app_name = "innstereo" app_dir = abspath(os.path.dirname(__file__)) # Locale are stored in innstereo/locale # .mo files will then be located in innstereo/locale/LANGUAGECODE/LC_MESSAGES/ locale_dir = abspath(join(app_dir, "locale")) if sys.platform == "win32": # Set $LANG on MS Windows for gettext if os.getenv('LANG') is None: lang, enc = locale.getdefaultlocale() #lang is POSIX e.g. de_DE os.environ['LANG'] = lang languages = [lang] # Set LOCALE_DIR for MS Windows import ctypes LIB_INTL = abspath(join(app_dir, "../gnome/libintl-8.dll")) libintl = ctypes.cdll.LoadLibrary(LIB_INTL) lc = locale.setlocale(locale.LC_ALL, "") locale_dir_g = abspath(join(app_dir, "locale")) libintl.bindtextdomain(self.app_name, locale_dir_g) libintl.bind_textdomain_codeset(self.app_name, "UTF-8") else: kwargs = {} if sys.version < '3': kwargs['unicode'] = 1 gettext.install(True, localedir=None, **kwargs) gettext.find(self.app_name, locale_dir) locale.bindtextdomain(self.app_name, locale_dir) # Now we need to choose the language. We will provide a list, and gettext # will use the first translation available in the list default_languages = os.environ.get('LANG', '').split(':') default_languages += ['en_US'] lc, encoding = locale.getdefaultlocale() if lc: languages = [lc] # Concat all languages (env + default locale), # and here we have the languages and location of the translations languages += default_languages gettext.bindtextdomain (self.app_name, locale_dir) gettext.textdomain (self.app_name) self._language = gettext.translation(self.app_name, locale_dir, languages=languages, fallback=True)
def get_translations(): """ Search the Application directory and the Flask-User directory for the Flask-User translations file and return a Translations() object.""" ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'flask_user_translations', None) if translations is None: # Prepare settings domain = 'flask_user' locales = [get_locale()] languages = [str(locale) for locale in locales] # Search Application directory app_dir = os.path.join(current_app.root_path, 'translations') filename = python_gettext.find(domain, app_dir, languages) if filename: translations = support.Translations.load(app_dir, locales, domain=domain) else: # Search Flask-User directory flask_user_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'translations') translations = support.Translations.load(flask_user_dir, locales, domain=domain) ctx.flask_user_translations = translations return ctx.flask_user_translations
def load(cls, dirname=None, locales=None, domain=DEFAULT_DOMAIN): """Load translations from the given directory. :param dirname: the directory containing the ``MO`` files :param locales: the list of locales in order of preference (items in this list can be either `Locale` objects or locale strings) :param domain: the message domain :return: the loaded catalog, or a ``NullTranslations`` instance if no matching translations were found :rtype: `Translations` """ if locales is not None: if not isinstance(locales, (list, tuple)): locales = [locales] locales = [str(l) for l in locales] if not domain: domain = cls.DEFAULT_DOMAIN filename = gettext.find(domain, dirname, locales) import pytest pytest.set_trace() if not filename: return gettext.NullTranslations() with open(filename, 'rb') as fp: return cls(fileobj=fp, domain=domain)
def rebuild_database(pathname, debian_sources=True, appstream_sources=False): #cache = apt.Cache(memonly=True) cache = get_pkg_info() cache.open() old_path = pathname+"_old" rebuild_path = pathname+"_rb" if not os.path.exists(rebuild_path): try: os.makedirs(rebuild_path) except: LOG.warn("Problem creating rebuild path '%s'." % rebuild_path) LOG.warn("Please check you have the relevant permissions.") return False # check permission if not os.access(pathname, os.W_OK): LOG.warn("Cannot write to '%s'." % pathname) LOG.warn("Please check you have the relevant permissions.") return False #check if old unrequired version of db still exists on filesystem if os.path.exists(old_path): LOG.warn("Existing xapian old db was not previously cleaned: '%s'." % old_path) if os.access(old_path, os.W_OK): #remove old unrequired db before beginning shutil.rmtree(old_path) else: LOG.warn("Cannot write to '%s'." % old_path) LOG.warn("Please check you have the relevant permissions.") return False # write it db = xapian.WritableDatabase(rebuild_path, xapian.DB_CREATE_OR_OVERWRITE) if debian_sources: update(db, cache) if appstream_sources: update_from_appstream_xml(db, cache) # write the database version into the filep db.set_metadata("db-schema-version", DB_SCHEMA_VERSION) # update the mo file stamp for the langpack checks mofile = gettext.find("app-install-data") if mofile: mo_time = os.path.getctime(mofile) db.set_metadata("app-install-mo-time", str(mo_time)) db.flush() # use shutil.move() instead of os.rename() as this will automatically # figure out if it can use os.rename or needs to do the move "manually" try: shutil.move(pathname, old_path) shutil.move(rebuild_path, pathname) shutil.rmtree(old_path) return True except: LOG.warn("Cannot copy refreshed database to correct location: '%s'." % pathname) return False
def get_available_languages(domain): """Lists the available languages for the given translation domain. :param domain: the domain to get languages for """ if domain in _AVAILABLE_LANGUAGES: return copy.copy(_AVAILABLE_LANGUAGES[domain]) localedir = '%s_LOCALEDIR' % domain.upper() find = lambda x: gettext.find(domain, localedir=os.environ.get(localedir), languages=[x]) # NOTE(mrodden): en_US should always be available (and first in case # order matters) since our in-line message strings are en_US language_list = ['en_US'] # NOTE(luisg): Babel <1.0 used a function called list(), which was # renamed to locale_identifiers() in >=1.0, the requirements master list # requires >=0.9.6, uncapped, so defensively work with both. We can remove # this check when the master list updates to >=1.0, and all projects udpate list_identifiers = (getattr(localedata, 'list', None) or getattr(localedata, 'locale_identifiers')) locale_identifiers = list_identifiers() for i in locale_identifiers: if find(i) is not None: language_list.append(i) _AVAILABLE_LANGUAGES[domain] = language_list return copy.copy(language_list)
def get_i18n_json(domain=app, localedir=None, languages=None): try: mofile = gettext.find(domain, localedir, languages) translations = gettext.GNUTranslations(open(mofile, 'rb')) return json.dumps(translations._catalog, ensure_ascii=0) except: return '{}'
def initlocalization(): gettext.textdomain("brita") filename = gettext.find("brita") if filename == None: filename = gettext.find("brita", "build/mo") try: if filename != None: trans = gettext.GNUTranslations(open(filename, "rb")) else: trans = gettext.NullTranslations() except IOError: trans = gettext.NullTranslations() trans.install()
def get_available_languages(): # Magic paths copied from pylons.i18n.translation._get_translator localedir = os.path.join(config['pylons.paths']['root'], 'i18n') messagefiles = gettext.find(config['pylons.package'], localedir, languages=babel.Locale('en').languages.keys(), all=True) return [path.split('/')[-3] for path in messagefiles]
def get_available_languages(domain): """Lists the available languages for the given translation domain. :param domain: the domain to get languages for """ if domain in _AVAILABLE_LANGUAGES: return copy.copy(_AVAILABLE_LANGUAGES[domain]) localedir = os.environ.get(_locale.get_locale_dir_variable_name(domain)) find = lambda x: gettext.find(domain, localedir=localedir, languages=[x]) # NOTE(mrodden): en_US should always be available (and first in case # order matters) since our in-line message strings are en_US language_list = ['en_US'] locale_identifiers = localedata.locale_identifiers() language_list.extend(language for language in locale_identifiers if find(language)) # In Babel 1.3, locale_identifiers() doesn't list some OpenStack supported # locales (e.g. 'zh_CN', and 'zh_TW') so we add the locales explicitly if # necessary so that they are listed as supported. aliases = {'zh': 'zh_CN', 'zh_Hant_HK': 'zh_HK', 'zh_Hant': 'zh_TW', 'fil': 'tl_PH'} language_list.extend(alias for locale, alias in six.iteritems(aliases) if (locale in language_list and alias not in language_list)) _AVAILABLE_LANGUAGES[domain] = language_list return copy.copy(language_list)
def _traductions_disponibles(self): global debug lst_lang = [] try: # Par défaut on essaye d'utiliser la langue désignée par la variable d'environement $LANG env_lang = os.environ["LANG"] if ("_" in env_lang): env_lang = env_lang.split('_')[0] if debug: print "LANG=%s (environnement)" % (env_lang) lst_lang.append(env_lang) # Recherche dans l'arborescence standard des fichier de traduction ($lang/LC_MESSAGES/nom_appli.mo) lst_trad = [] for lang in os.listdir(self.rep_trad): if os.path.isdir(os.path.join(self.rep_trad,lang)) and lang != self.source_lang and lang != env_lang: if debug: print "the directorie %s/LC_MESSAGES exist" % (lang) lst_trad.append(lang) for trad in gettext.find(self.appli, self.rep_trad, languages=lst_trad, all=True): if trad != self.source_lang and trad != env_lang: if debug: print "Other available language, found valid .mo : %s)" % (trad) lst_lang.append(trad.split("/",2)[1:2][0]) # En dernier recours on utilise la langue originale du programme source (fallback) if self.source_lang != env_lang: lst_lang.append(self.source_lang) except Exception: print "%s : ERROR : %s" % (sys.argv[0], err) finally: if debug: print "Available langs list : %s" % (lst_lang) return lst_lang
def __init__(self, argparser): from gramps.gen.dbstate import DbState from . import viewmanager from .viewmanager import ViewManager from gramps.cli.arghandler import ArgHandler from .tipofday import TipOfDay from .dialog import WarningDialog import gettext _display_welcome_message() # Append image directory to the theme search path theme = Gtk.IconTheme.get_default() theme.append_search_path(IMAGE_DIR) if lin() and glocale.lang != 'C' and not gettext.find(GTK_GETTEXT_DOMAIN): LOG.warn("GTK translations missing, GUI will be broken, especially for RTL languages!") # Note: the warning dialog below will likely have wrong stock icons! # Translators: the current language will be the one you translate into. WarningDialog( _("Gramps detected an incomplete GTK installation"), _("GTK translations for the current language (%(language)s) " "are missing.\n%(bold_start)sGramps%(bold_end)s will " "proceed nevertheless.\nThe GUI will likely be broken " "as a result, especially for RTL languages!\n\n" "See the Gramps README documentation for installation " "prerequisites,\ntypically located in " "/usr/share/doc/gramps.\n") % { 'language' : glocale.lang , 'bold_start' : '<b>' , 'bold_end' : '</b>' } ) dbstate = DbState() self.vm = ViewManager(dbstate, config.get("interface.view-categories")) self.vm.init_interface() #act based on the given arguments ah = ArgHandler(dbstate, argparser, self.vm, self.argerrorfunc, gui=True) ah.handle_args_gui() if ah.open or ah.imp_db_path: # if we opened or imported something, only show the interface self.vm.post_init_interface(show_manager=False) elif config.get('paths.recent-file') and config.get('behavior.autoload'): # if we need to autoload last seen file, do so filename = config.get('paths.recent-file') if os.path.isdir(filename) and \ os.path.isfile(os.path.join(filename, "name.txt")) and \ ah.check_db(filename): self.vm.post_init_interface(show_manager=False) self.vm.open_activate(filename) else: self.vm.post_init_interface() else: # open without fam tree loaded self.vm.post_init_interface() if config.get('behavior.use-tips'): TipOfDay(self.vm.uistate)
def i18n(self, domain="main", language=None): """ Provides module based localization. Domain is a path relative to SelfPath that specifies the location of the translation catalog. ".." or "../.." or example. Language is the language to use. Really? Yes. """ source_append = "" if domain: domain = os.path.basename(domain) source_append = os.path.dirname(domain) elif self.__i18n_domain__: domain = os.path.basename(self.__i18n_domain__) source_append = os.path.dirname(self.__i18n_domain__) else: domain = self.__class__.__name__.lower() if not language: language = self.__i18n_language__ sources = [ os.path.join(self.get_exec_path(), source_append), os.path.join(self.get_lib_path(), source_append), os.path.join(os.path.dirname(self.get_self_path()), source_append)] for i, s in enumerate(sources): sources[i] = os.path.abspath(s) for i, s in enumerate(sources): sources[i] = os.path.join(s, "locale") sources_ = [] for source in sources: if source not in sources_: sources_.append(source) for source in sources: if gettext.find(domain, source, [language]): return gettext.translation(domain, source, [language]).ugettext return gettext.translation(domain, fallback=True).ugettext
def _get_translation(self, domain = None, localedir = None, languages=None): """ Get a translation of one of our classes. Doesn't return the singleton so that it can be used by get_addon_translation() """ if not domain: domain = self.localedomain if not languages: languages = self.language if not localedir: localedir = self.localedir for lang in languages: if gettext.find(domain, localedir, [lang]): translator = gettext.translation(domain, localedir, [lang], class_ = WearNowTranslations) translator._language = lang return translator elif lang.startswith("en") or lang.startswith("C"): translator = WearNowNullTranslations() translator._language = "en" return translator if not languages or len(languages) == 0: LOG.warning("No language provided, using US English") else: raise ValueError("No usable translations in %s for " % ':'.join(languages)) translator = WearNowNullTranslations() translator._language = "en" return translator
def check_language(lang_code): "Check existance of language files" if gettext.find('baruwa', I18NPATH, [lang_code]) is not None: lang_list = extract_languages() if lang_list and lang_code not in lang_list: return False return True return False
def setUp(self): localedir = os.path.join(configure.localedatadir, 'locale') mo = gettext.find(configure.PACKAGE, localedir, ["nl_NL"]) self.failUnless(mo) self.nl = gettext.translation(configure.PACKAGE, localedir, ["nl_NL"]) self.failUnless(self.nl) self.able = N_("I am a translatable string") self.ed = self.nl.gettext("I am a translated string")
def set_available_locales(): """Set available locales for which we have translations""" global AVAILABLE_LOCALES locales=['en', 'en_US'] # these are available without translations for locale in localedata.list(): if gettext.find('mediagoblin', TRANSLATIONS_PATH, [locale]): locales.append(locale) AVAILABLE_LOCALES = locales
def find_catalog_files(docname, srcdir, locale_dirs, lang, compaction): if not (lang and locale_dirs): return [] domain = find_catalog(docname, compaction) files = [gettext.find(domain, path.join(srcdir, dir_), [lang]) for dir_ in locale_dirs] files = [path.relpath(f, srcdir) for f in files if f] return files
def set_language(lang): __get__logger().debug("Trying to set language to %s", lang) languages.clear() languages.append(lang) __get__logger().debug(gettext.find(APP_NAME, LOCALE_DIR, languages=[lang])) gettext.translation(APP_NAME, LOCALE_DIR, languages=[lang], fallback=True).install() __get__logger().debug("Ready setting language to %s", lang)
def test_iso_codes(): import gettext languages = (lang[0] for lang in settings.LANGUAGES) if not languages: # There are no UI languages, which is a problem, but we won't complain # about that here. languages = ['af', 'ar', 'fr'] return len(gettext.find('iso_639', languages=languages, all=True)) > 0
def get_language_from_request(request): """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """ global _accepted from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') supported = dict(settings.LANGUAGES) if hasattr(request, 'session'): lang_code = request.session.get('django_language', None) if lang_code in supported and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get('django_language', None) if lang_code in supported and lang_code is not None and check_for_language(lang_code): return lang_code accept = request.META.get('HTTP_ACCEPT_LANGUAGE', None) if accept is not None: t = _accepted.get(accept, None) if t is not None: return t def _parsed(el): p = el.find(';q=') if p >= 0: lang = el[:p].strip() order = int(float(el[p+3:].strip())*100) else: lang = el order = 100 p = lang.find('-') if p >= 0: mainlang = lang[:p] else: mainlang = lang return (lang, mainlang, order) langs = [_parsed(el) for el in accept.split(',')] langs.sort(lambda a,b: -1*cmp(a[2], b[2])) for lang, mainlang, order in langs: if lang in supported or mainlang in supported: langfile = gettext_module.find('django', globalpath, [to_locale(lang)]) if langfile: # reconstruct the actual language from the language # filename, because otherwise we might incorrectly # report de_DE if we only have de available, but # did find de_DE because of language normalization lang = langfile[len(globalpath):].split(os.path.sep)[1] _accepted[accept] = lang return lang return settings.LANGUAGE_CODE
def initLocalization(settings): import gettext import os localeDir = os.path.join(os.getcwd(), 'locales') curLang = settings['lang'] #gettext.bindtextdomain('bibledave', localeDir ) #gettext.textdomain('bibledave') #gettext.install('bibledave', localeDir) # print gettext.textdomain(),gettext.bindtextdomain('bibledave') language = [languages[curLang]] l = gettext.find('bibledave', localeDir, language) if l == None: raise "No language file found for language", curLang t = gettext.translation('bibledave', localeDir, language) t.install()
def get_locale_dir(): if os.name == 'nt': return None # try to find domain in localedir path = gettext.find(DOMAIN) if path: # extract localedir from localedir/language/LC_MESSAGES/domain.mo path, tail = os.path.split(path) path, tail = os.path.split(path) localedir, tail = os.path.split(path) elif os.path.exists('/app/share/run-as-flatpak'): # Check if we run as flatpak return '/app/share/locale' else: # fallback to user locale base = os.getenv('XDG_DATA_HOME') if base is None or base[0] != '/': base = os.path.expanduser('~/.local/share') localedir = os.path.join(base, "locale") return localedir
def load(cls, dirname=None, locales=None, domain=None): """Load translations from the given directory. :param dirname: the directory containing the ``MO`` files :param locales: the list of locales in order of preference (items in this list can be either `Locale` objects or locale strings) :param domain: the message domain (default: 'messages') """ if locales is not None: if not isinstance(locales, (list, tuple)): locales = [locales] locales = [str(locale) for locale in locales] if not domain: domain = cls.DEFAULT_DOMAIN filename = gettext.find(domain, dirname, locales) if not filename: return NullTranslations() with open(filename, 'rb') as fp: return cls(fp=fp, domain=domain)
def get_translation_for(package_name): # type: (str) -> gettext.NullTranslations '''Find and return gettext translation for package (Try to find folder manually if setuptools does not exist) ''' if '.' in package_name: package_name = '.'.join(package_name.split('.')[:-1]) localedir = None if pkg_resources is None: mydir = os.path.join(local_dir, 'i18n') else: mydir = pkg_resources.resource_filename(package_name, 'i18n') for localedir in mydir, None: localefile = gettext.find(package_name, localedir) if localefile: break return gettext.translation(package_name, localedir=localedir, fallback=True)
def __init__(self, locale, version): self.pot = POFile(check_for_duplicate=True) self.pot.metadata = { 'Project-Id-Version': version, 'POT-Creation-Date': str(datetime.now()), 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=utf-8', } (Path('.') / 'locale').mkdir(exist_ok=True) self.languages = locale.split('+') for lang in self.languages: if gettext.find('content', localedir=Path('.') / 'locale', languages=[lang]) is None: mo_path = Path( '.') / 'locale' / lang / 'LC_MESSAGES' / 'content.mo' po_path = Path( '.') / 'locale' / lang / 'LC_MESSAGES' / 'content.po' if po_path.exists(): print( f'The file "{str(mo_path)}" not found.\nUsing "{str(po_path)}" instead.' ) pofile(po_path).save_as_mofile(mo_path) print(f'"{str(mo_path)}" generated.') else: print( f'The file "{str(mo_path)}" or "{str(po_path)}" not found.' ) print(f'Using the original Lean files for "{lang}".\n') self.translations = [ gettext.translation('content', localedir=Path('.') / 'locale', languages=[lang], fallback=True) for lang in self.languages ] self.original_texts = [] self.translated_texts = [[] for lang in self.languages] self.occ = None
def _get_translator(lang, tgl=None, tg_config=None, **kwargs): """Utility method to get a valid translator object from a language name""" if tg_config: conf = tg_config else: if tgl: conf = tgl.config else: # pragma: no cover #backward compatibility with explicit calls without #specifying local context or config. conf = tg.config.current_conf() if not lang: return NullTranslations() try: localedir = conf['localedir'] except KeyError: # pragma: no cover localedir = os.path.join(conf['paths']['root'], 'i18n') app_domain = conf['package'].__name__ if not isinstance(lang, list): lang = [lang] mofiles = [] supported_languages = [] for l in lang: mo = _gettext.find(app_domain, localedir=localedir, languages=[l], all=False) if mo is not None: mofiles.append(mo) supported_languages.append(l) try: translator = _translator_from_mofiles(app_domain, mofiles, **kwargs) except IOError as ioe: raise LanguageError('IOError: %s' % ioe) translator.tg_lang = lang translator.tg_supported_lang = supported_languages return translator
def get_translations(): # If there is no context: return None ctx = _request_ctx_stack.top if not ctx: return None # If context exists and contains a cached value, return cached value if hasattr(ctx, 'flask_user_translations'): return ctx.flask_user_translations # If App has not initialized Flask-Babel: return None app_has_initalized_flask_babel = 'babel' in current_app.extensions if not app_has_initalized_flask_babel: # pragma no cover ctx.flask_user_translations = None return ctx.flask_user_translations # Prepare search properties import os import gettext as python_gettext from flask_babel import get_locale, get_translations, support domain = 'flask_user' locales = [get_locale()] languages = [str(locale) for locale in locales] # See if translations exists in Application dir app_dir = os.path.join(current_app.root_path, 'translations') filename = python_gettext.find(domain, app_dir, languages) if filename: ctx.flask_user_translations = support.Translations.load(app_dir, locales, domain=domain) # See if translations exists in Flask-User dir else: flask_user_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'translations') ctx.flask_user_translations = support.Translations.load(flask_user_dir, locales, domain=domain) return ctx.flask_user_translations.merge(get_translations())
def on_event(self, event, extension): # Set language language = self.preferences['main_language'] domain = 'base' local_path = os.path.join(os.path.dirname(__file__), 'locales') logger.debug( f'Extension language is: {language}. Searching translation files in {local_path}.' ) # Only translate if need to if language != 'en': if language in self.LANGUAGES: translation_file_path = gettext.find(domain, local_path, [language]) logger.debug(f'Translation file path: {translation_file_path}') try: translator = gettext.translation(domain=domain, localedir=local_path, languages=[language]) translator.install() except FileNotFoundError: logger.debug( 'Translation file not found. Go with default.') else: global _ _ = translator.gettext # distribute events to proper listeners if extension is not self: raise RuntimeError('Something is very wrong.') if isinstance(event, KeywordQueryEvent): return self.on_keyword_query(event.get_keyword(), event.get_argument()) if isinstance(event, ItemEnterEvent): return self.on_item_enter(event.get_data()) if isinstance(event, SystemExitEvent): return self.on_system_exit() if isinstance(event, PreferencesEvent): return self.on_preferences(event.preferences) if isinstance(event, PreferencesUpdateEvent): return self.on_preferences_update(event.id, event.old_value, event.new_value)
def _gettext_instance(self, domain, origin): """tries to find locale using 1/ self._path, 2/ config.Config.translation, 3/ system-wide place for locale""" import gettext, config # paths to try paths = [config.Config.translation_dir, None] if domain in self._path: paths.insert(0, self._path[domain]) for path in paths: if gettext.find(domain, localedir=path, languages=[self._lang]): return gettext.translation(domain, localedir=path, languages=[self._lang]) # The MO file was not found. paths[-1] = "System_defined_locale_dir" msg = "Translation file not found in paths: '%s', lang: '%s', origin: '%s'" % ( ", ".join(paths), self._lang, origin) if self._fallback or self._lang == origin: return gettext.NullTranslations() else: raise IOError(msg)
def i18n_catalog(context, request): current_language = locale_language = request._LOCALE_ plural = None catalog = {} catalog_js = 'gecoscc_js' locale_path = os.path.join(os.sep.join(str(gecoscc.__file__).split(os.sep)[:-1]), 'locale') if not gettext_module.find(catalog_js, locale_path, [current_language]): settings = get_current_registry().settings locale_language = settings['pyramid.default_locale_name'] # Inspirated by https://github.com/django/django/blob/master/django/views/i18n.py#L192 t = gettext_module.translation(catalog_js, locale_path, [locale_language])._catalog if '' in t: for l in t[''].split('\n'): if l.startswith('Plural-Forms:'): plural = l.split(':', 1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1] pdict = {} maxcnts = {} for k, v in list(t.items()): if k == '': continue if isinstance(k, six.string_types): catalog[k] = v elif isinstance(k, tuple): msgid = k[0] cnt = k[1] maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0)) pdict.setdefault(msgid, {})[cnt] = v else: raise TypeError(k) for k, v in list(pdict.items()): catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)] request.response.headers['Content-Type'] = 'text/javascript' return {'catalog': json.dumps(catalog), 'plural': json.dumps(plural)}
def set_lang(lang=None, localedir=None): """Set the locale""" global _translation, _lang # setup language preference order languages = [] # default language from environment deflang, defencoding = locale.getdefaultlocale() if deflang: languages = [deflang + "." + defencoding] + languages # specified language if lang: languages = [lang] + languages # initialize gettext if localedir is None: localedir = _locale_dir gettext.bindtextdomain(GETTEXT_DOMAIN, localedir) gettext.textdomain(GETTEXT_DOMAIN) # search for language file langfile = gettext.find(GETTEXT_DOMAIN, localedir, languages) # setup language translations if langfile: _lang = os.path.basename(os.path.dirname(os.path.dirname(langfile))) set_env("LANG", _lang) set_env("LANGUAGE", _lang) _translation = gettext.GNUTranslations(open(langfile, "rb")) else: _lang = "" set_env("LANG", _lang) set_env("LANGUAGE", _lang) _translation = gettext.NullTranslations() # install "_" into python builtins _translation.install()
def load(cls, dirname=None, locales=None, domain=DEFAULT_DOMAIN): """Load translations from the given directory. :param dirname: the directory containing the ``MO`` files :param locales: the list of locales in order of preference (items in this list can be either `Locale` objects or locale strings) :param domain: the message domain :return: the loaded catalog, or a ``NullTranslations`` instance if no matching translations were found :rtype: `Translations` """ if locales is not None: if not isinstance(locales, (list, tuple)): locales = [locales] locales = [str(locale) for locale in locales] if not domain: domain = cls.DEFAULT_DOMAIN filename = gettext.find(domain, dirname, locales) if not filename: return gettext.NullTranslations() return cls(fileobj=open(filename, 'rb'), domain=domain)
def get_installed_translations(): # # returns a list of translated installed languages, (de, es)... # and a list of lang/country combos for that language (de_DE, de_AT)... # import locale import gettext la_list = [] la_co_list = [] for (ident, la_co) in locale.windows_locale.iteritems(): if gettext.find("fpdb", localedir="locale", languages=[la_co]): if "_" in la_co: la, co = la_co.split("_", 1) la_list.append(la) else: la_list.append(la_co) la_co_list.append(la_co) # #eliminate dupes # la_set = set(la_list) la_list = list(la_set) la_dict = {} la_co_dict = {} try: from icu import Locale for code in la_list: la_dict[code] = Locale.getDisplayName(Locale(code)) for code in la_co_list: la_co_dict[code] = Locale.getDisplayName(Locale(code)) except: for code in la_list: la_dict[code] = code for code in la_co_list: la_co_dict[code] = code return la_dict, la_co_dict
def _traductions_disponibles(self): global debug lst_lang = [] try: # Par défaut on essaye d'utiliser la langue désignée par la variable d'environement $LANG env_lang = os.environ["LANG"] if ("_" in env_lang): env_lang = env_lang.split('_')[0] if debug: print "LANG=%s (environnement)" % (env_lang) lst_lang.append(env_lang) # Recherche dans l'arborescence standard des fichier de traduction ($lang/LC_MESSAGES/nom_appli.mo) lst_trad = [] for lang in os.listdir(self.rep_trad): if os.path.isdir( os.path.join(self.rep_trad, lang) ) and lang != self.source_lang and lang != env_lang: if debug: print "the directorie %s/LC_MESSAGES exist" % (lang) lst_trad.append(lang) for trad in gettext.find(self.appli, self.rep_trad, languages=lst_trad, all=True): if trad != self.source_lang and trad != env_lang: if debug: print "Other available language, found valid .mo : %s)" % ( trad) lst_lang.append(trad.split("/", 2)[1:2][0]) # En dernier recours on utilise la langue originale du programme source (fallback) if self.source_lang != env_lang: lst_lang.append(self.source_lang) except Exception: print "%s : ERROR : %s" % (sys.argv[0], err) finally: if debug: print "Available langs list : %s" % (lst_lang) return lst_lang
def _translation(path, lang, cache=None): ''' Gets a translation for the given language from the locale path. ''' if cache is None: cache = _cache[path] trans = cache.get(lang) if trans: return trans mofiles = gt.find(config.NAME, path, [lang], True) for mofile in mofiles: lg = _language(path, mofile) tn = cache.get(lg) if tn is None: tn = cache.setdefault(lg, gt.GNUTranslations(open(mofile, 'rb'))) tn.set_output_charset(constants.ENCODING) if trans: trans.add_fallback(tn) else: trans = tn if trans is None: trans = gt.NullTranslations() return cache.setdefault(lang, trans)
def setup(application_name, locale_dir, app_code, app_messages): """Install the error handler :param application_name: It's the application name. It's used to set the domain. :param locale_dir: It's the folder where are located the .po files. Usually APP_FOLDER/i18n/ :param app_messages: Your application messages :param app_code: Application code""" if application_name is None or application_name == "": return (False, 'Application name must be set') if locale_dir is None or locale_dir == "" or not os.path.exists( locale_dir): return (False, 'Locale dir doesn\'t exists') AlienvaultMessageHandler.ERROR_MESSAGE_HASH = app_messages AlienvaultMessageHandler.APP_NAME = application_name AlienvaultMessageHandler.LOCALE_DIR = locale_dir AlienvaultMessageHandler.LANGUAGES = AlienvaultMessageHandler.__get_languages( ) AlienvaultMessageHandler.APP_CODE = app_code gettext.install(True, localedir=None, unicode=True) current_language = 'en_US' for language in AlienvaultMessageHandler.LANGUAGES: if gettext.find( AlienvaultMessageHandler.APP_NAME, AlienvaultMessageHandler.LOCALE_DIR, languages=AlienvaultMessageHandler.LANGUAGES) is not None: current_language = language # Set the text domain gettext.textdomain(AlienvaultMessageHandler.APP_NAME) gettext.bind_textdomain_codeset(AlienvaultMessageHandler.APP_NAME, "UTF-8") AlienvaultMessageHandler.CURRENT_LANGUAGE = gettext.translation( AlienvaultMessageHandler.APP_NAME, AlienvaultMessageHandler.LOCALE_DIR, languages=current_language, fallback=True) return (True, 'OK')
def get_translation_for( package_name: str ) -> gettext.NullTranslations: # type: ignore[misc] """Find and return gettext translation for package (Try to find folder manually if setuptools does not exist) """ if "." in package_name: package_name = ".".join(package_name.split(".")[:-1]) localedir = None if pkg_resources is None: mydir = os.path.join(local_dir, "i18n") else: mydir = pkg_resources.resource_filename(package_name, "i18n") for localedir in mydir, None: localefile = gettext.find(package_name, localedir) if localefile: break return gettext.translation(package_name, localedir=localedir, fallback=True)
def _get_languages(): languages = [] processed_catalogs = set([]) # sorted() here is important to make processed_catalogs checking # work properly. for lang_code, lang_label in sorted(settings.LANGUAGES): if lang_code == 'en': # Add English as source language languages.append( ('en', _get_language_display_name('en', 'English'))) continue found_catalogs = [ gettext_module.find(domain, locale_path, [translation.to_locale(lang_code)]) for locale_path, domain in itertools.product( settings.LOCALE_PATHS, ['django', 'djangojs']) ] if not all(found_catalogs): continue # NOTE(amotoki): # Check if found catalogs are already processed or not. # settings.LANGUAGES can contains languages with a same prefix # like es, es-ar, es-mx. gettext_module.find() searchess Message # catalog for es-ar in the order of 'es_AR' and then 'es'. # If 'es' locale is translated, 'es-ar' is included in the list of # found_catalogs even if 'es-ar' is not translated. # In this case, the list already includes 'es' and # there is no need to include 'es-ar'. result = [catalog in processed_catalogs for catalog in found_catalogs] if any(result): continue processed_catalogs |= set(found_catalogs) languages.append( (lang_code, _get_language_display_name(lang_code, lang_label))) return sorted(languages)
def get_gettext(self, channel=None): """ return a gettext function for the configured language @param channel: ignored, its just for compatibilty with ircClient plugins """ lang = self.config.get("language", None, "main", self.network) if not lang in self.translations and lang: if gettext.find("otfbot", "locale", languages=[lang]): self.translations[lang]=gettext.translation("otfbot", "locale", \ languages=[lang]) else: #no language file found for requested language lang = None if lang: def _(input): return self.translations[lang].gettext(input) else: def _(input): return input return _
def check_database(update: Update, context: CallbackContext): user_data = context.user_data try: user_data['url'] except KeyError: user_data['url'] = data(update.effective_user.id) global lang_code lc = update.effective_user.language_code user_data['lang'] = (lc if lc and gettext.find(domain, "locale", [lc]) else 'en') if lang_code != user_data['lang']: lang_code = user_data['lang'] lang = gettext.translation(domain, "locale", [lang_code]) lang.install(['ngettext']) logging.info( update_object_type(update).__class__.__name__ + " recieved from " + name_and_id(update.effective_user))
def _findLocaleDir(domain): import gettext, sys # try default location first f = gettext.find(domain) if f: return None # next try cwd f = gettext.find(domain, 'locale') if f: return 'locale' # next try python prefix pydir = os.path.join(sys.prefix, 'share', 'locale') f = gettext.find(domain, pydir) if f: return pydir # next try shtoom installation prefix import shtoom # -5 is prefix , lib, pythonN.N, site-packages, shtoom, __init__.pyc prefix = os.path.sep.join(shtoom.__file__.split(os.path.sep)[:-5]) prefixdir = os.path.join(prefix, 'share', 'locale') f = gettext.find(domain, pydir) if f: return prefixdir # Next try alongside 'shtoom' (running from srcdir?) srcdir = os.path.join(os.path.split(shtoom.__file__)[0], 'locale') f = gettext.find(domain, srcdir) if f: return srcdir # Try python installation prefix pydir = os.path.join(sys.prefix, 'share', 'locale') f = gettext.find(domain, pydir) if f: return pydir # just wing it return None
LOCALE_DIR = join(WHERE_AM_I, '..', 'mo') # Currently we run from the app dir. # TODO: Fix this path if we install gnome_usbguard system wide kwargs = {"localedir": LOCALE_DIR} if sys.version_info[0] > 3: # In Python 2, ensure that the _() that gets installed into built-ins # always returns unicodes. This matches the default behavior under # Python 3, although that keyword argument is not present in the # Python 3 API. kwargs['unicode'] = True gettext.install(APP, **kwargs) locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(APP, LOCALE_DIR) # For testing the proper path print(gettext.find(APP, LOCALE_DIR)) print('Applet using locale directory: {}'.format(LOCALE_DIR)) # Gdk.threads_init() APPINDICATOR_ID = 'org.gnome.usbguard.appindicator' class USBGuardAppIndicator(object): """App indicator to handle usb events""" CURRDIR = os.path.dirname(os.path.abspath(__file__)) USBGUARD_ICON_PATH = os.path.join(CURRDIR, 'usbguard-icon.svg') usbguard_app = None notifications = {} screensaver_active = False
import config ## ## I18N ## import locale import gettext domain = config.GETTEXT_PACKAGE() gettext.bindtextdomain(domain, config.GNOMELOCALEDIR()) gettext.textdomain(domain) _ = gettext.gettext # Fallback to english if locale setting is unknown # or translation for this locale is not available if gettext.find(domain) == None: language = "C" else: language = "" try: locale.setlocale(locale.LC_ALL, language) except: warnings.warn_explicit( "Locale not supported by Python. Using the fallback 'C' locale.", Warning, "lang.py", sys.exc_info()[2].tb_frame.f_back.f_lineno) encoding = locale.getpreferredencoding(False) language = locale.getlocale()[0] if language == None: language = "C"
# select base string if _py3k: basestring = str # map between Gedit's translation and PyGtkSpellcheck's _GEDIT_MAP = {'Languages' : 'Languages', 'Ignore All' : 'Ignore _All', 'Suggestions' : 'Suggestions', '(no suggestions)' : '(no suggested words)', 'Add "{}" to Dictionary' : 'Add w_ord', 'Unknown' : 'Unknown'} # translation if gettext.find('gedit'): _gedit = gettext.translation('gedit', fallback=True).gettext _ = lambda message: _gedit(_GEDIT_MAP[message]).replace('_', '') else: locale_name = 'py{}gtkspellcheck'.format(sys.version_info.major) _ = gettext.translation(locale_name, fallback=True).gettext def code_to_name(code, separator='_'): # Escape underscores for GTK menuitems. return code.replace(separator, separator * 2) class SpellChecker(object): """ Main spellchecking class, everything important happens here. :param view: GtkTextView the SpellChecker should be attached to.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ GuizeroApp.py MIT License (c) Faure Systems <dev at faure dot systems> GuizeroApp extends MqttApp. """ from constants import * import gettext import os, platform, signal, yaml try: gettext.find("GuizeroApp") traduction = gettext.translation('GuizeroApp', localedir='locale', languages=['fr']) traduction.install() except: _ = gettext.gettext # cool, this hides PyLint warning Undefined name '_' from MqttApp import MqttApp from guizero import App import sys class GuizeroApp(MqttApp): # __________________________________________________________________
def _init(cls): def callback(widget, allocation): cls.widgets["enterGameNotationFrame"].set_size_request( 223, allocation.height - 4) cls.widgets["enterGameNotationSidePanel"].connect_after( "size-allocate", callback) flags = [] if isInstalled(): path = gettext.find("pychess") else: path = gettext.find("pychess", localedir=addDataPrefix("lang")) if path: default_locale = locale.getdefaultlocale() if default_locale[0] is not None: loc = locale.getdefaultlocale()[0][-2:].lower() flags.append(addDataPrefix("flags/%s.png" % loc)) flags.append(addDataPrefix("flags/us.png")) cls.ib = ImageButton(flags) cls.widgets["imageButtonDock"].add(cls.ib) cls.ib.show() cls.sourcebuffer = GtkSource.Buffer() sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer) sourceview.set_tooltip_text( _("Type or paste PGN game or FEN positions here")) cls.widgets["scrolledwindow6"].add(sourceview) sourceview.show() # Pgn format does not allow tabulator sourceview.set_insert_spaces_instead_of_tabs(True) sourceview.set_wrap_mode(Gtk.WrapMode.WORD) man = GtkSource.LanguageManager() # Init new version if hasattr(man.props, 'search_path'): try: path = os.path.join(getDataPrefix(), "gtksourceview-3.0/language-specs") man.props.search_path = man.props.search_path + [path] if 'pgn' in man.get_language_ids(): lang = man.get_language('pgn') cls.sourcebuffer.set_language(lang) else: log.warning("Unable to load pgn syntax-highlighting.") cls.sourcebuffer.set_highlight_syntax(True) except NotImplementedError: # Python 2.7.3 in Ubuntu 12.04 log.warning("Unable to load pgn syntax-highlighting.") # Init old version else: os.environ["XDG_DATA_DIRS"] = getDataPrefix() + ":/usr/share/" man = GtkSource.LanguageManager() for lang in man.get_available_languages(): if lang.get_name() == "PGN": cls.sourcebuffer.set_language(lang) break else: log.warning("Unable to load pgn syntax-highlighting.") cls.sourcebuffer.set_highlight(True)
"""Base window of application.""" import os import gettext import locale import platform import tkinter as tk from tkinter import font from FinanceApp.month_window import MonthWindow from FinanceApp.statistic_window import StatisticsWindow from FinanceApp.utils import config_widget if platform.system() != 'Windows': locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()) localedir = gettext.find('Months') localedir = localedir if localedir is not None else os.path.dirname(__file__) gettext.install('Months', localedir, names=('ngettext', )) class Application(tk.Frame): """ Main window class. :param master: master window :param title: title of the application """ def __init__(self, master=None, title=_('Finance management app')): """Create main window of application with widgets.""" if not master: master = tk.Tk()
import pygtk pygtk.require("2.0") import gtk import gedit import time import os import sys import getopt import ConfigParser import gettext APP_NAME = "plugin" LOC_PATH = os.path.join( os.path.expanduser("~/.gnome2/gedit/plugins/reopen-tabs/lang")) gettext.find(APP_NAME, LOC_PATH) gettext.install(APP_NAME, LOC_PATH, True) RELOADER_STATE_READY = "ready" RELOADER_STATE_INIT = "init" RELOADER_STATE_RELOADING = "reloading" RELOADER_STATE_DONE = "done" RELOADER_STATE_CLOSING = "closing" def log(msg): print '\033[32m' + msg + '\033[0m' class ReopenTabsPlugin(gedit.Plugin): def __init__(self):
def generate_quest(quest): gettext.find('quest', 'locales', all=True) lang = gettext.translation('quest', localedir='locale', fallback=True) lang.install() quest_reward_type = questreward(quest['quest_reward_type']) quest_type = questtype(quest['quest_type']) if '{0}' in quest_type: quest_type = quest_type.replace('{0}', str(quest['quest_target'])) item_id = 0 item_amount = 1 pokemon_id = '000' pokemon_name = '' item_type = '' pokemon_form = '00' pokemon_costume = '00' pokemon_asset_bundle = '00' if quest_reward_type == _('Item'): item_amount = quest['quest_item_amount'] item_type = rewarditem(quest['quest_item_id']) item_id = quest['quest_item_id'] elif quest_reward_type == _('Stardust'): item_amount = quest['quest_stardust'] item_type = _('Stardust') elif quest_reward_type == _('Pokemon'): item_type = 'Pokemon' pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id']))) pokemon_id = quest['quest_pokemon_id'] pokemon_form = quest['quest_pokemon_form_id'] pokemon_costume = quest['quest_pokemon_costume_id'] if pokemon_form != '00': pokemon_asset_bundle = form_mapper(int(pokemon_id), pokemon_form) elif quest_reward_type == _('Energy'): item_type = _('Mega Energy') if quest['quest_pokemon_id'] and int(quest['quest_pokemon_id']) > 0: pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id']))) pokemon_id = quest['quest_pokemon_id'] else: pokemon_name = '' item_amount = quest['quest_item_amount'] if not quest['task']: quest_task = questtask(quest['quest_type'], quest['quest_condition'], quest['quest_target'], quest['quest_template']) else: quest_task = quest['task'] quest_raw = ({ 'pokestop_id': quest['pokestop_id'], 'name': quest['name'], 'url': quest['image'], 'latitude': quest['latitude'], 'longitude': quest['longitude'], 'timestamp': quest['quest_timestamp'], 'item_id': item_id, 'item_amount': item_amount, 'item_type': item_type, 'pokemon_id': pokemon_id, 'pokemon_name': pokemon_name, 'pokemon_form': pokemon_form, 'pokemon_asset_bundle_id': pokemon_asset_bundle, 'pokemon_costume': pokemon_costume, 'quest_type': quest_type, 'quest_type_raw': quest['quest_type'], 'quest_reward_type': quest_reward_type, 'quest_reward_type_raw': quest['quest_reward_type'], 'quest_task': quest_task, 'quest_target': quest['quest_target'], 'quest_condition': quest['quest_condition'], 'quest_template': quest['quest_template'], }) return quest_raw
def questtask(typeid, condition, target, quest_template): gettext.find('quest', 'locales', all=True) lang = gettext.translation('quest', localedir='locale', fallback=True) lang.install() pokemonTypes = open_json_file('pokemonTypes') items = open_json_file('items') throwTypes = { "10": _("Nice"), "11": _("Great"), "12": _("Excellent"), "13": _("Curveball") } arr = {} arr['0'] = target text = questtype(typeid) # TODO use the dict instead of regex parsing in all logic condition_dict = {} if condition is not None and condition != '': condition_dict = json.loads(condition) if typeid == 4: arr['wb'] = "" arr['type'] = "" arr['poke'] = "" arr['different'] = "" arr['item'] = "" text = _("Catch {0}{different} {type}Pokemon{wb}") match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['type'] = pokemonTypes[pt[0]].title() + _('-type ') else: for ty in pt: arr['type'] += (_('or ') if last == cur else '') + \ pokemonTypes[ty].title() + (_('-type ') if last == cur else '-, ') cur += 1 if re.search(r'"type": 3', condition) is not None: arr['wb'] = _(" with weather boost") elif re.search(r'"type": 21', condition) is not None: arr['different'] = _(" different species of") match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['poke'] = i8ln(pokemonname(pt[0])) else: for ty in pt: arr['poke'] += (_('or ') if last == cur else '') + \ i8ln(pokemonname(ty)) + ('' if last == cur else ', ') cur += 1 text = _('Catch {0} {poke}') elif typeid == 5: text = _("Spin {0} Pokestops or Gyms") if re.search(r'"type": 12', condition) is not None: text = _("Spin {0} Pokestops you haven't visited before") elif typeid == 6: text = _("Hatch {0} Eggs") elif typeid == 7: if re.search(r'"type": 9', condition) is not None: text = _("Win {0} Gym Battles") elif re.search(r'"type": 10', condition) is not None: text = _("Use a supereffective Charged Attack in {0} Gym battles") else: text = _("Battle in a Gym {0} times") elif typeid == 8: if re.search(r'"type": 6', condition) is not None: text = _("Win {0} Raids") if re.search(r'"raid_level": \[3, 4, 5\]', condition) is not None: text = _('Win a level 3 or higher raid') if re.search(r'"raid_level": \[2, 3, 4, 5\]', condition) is not None: text = _('Win a level 2 or higher raid') if re.search(r'"raid_level": \[6\]', condition) is not None: text = _('Win a Mega raid') else: text = _("Battle in {0} Raids") elif typeid == 10: text = _("Transfer {0} Pokemon") elif typeid == 11: text = _("Favourite {0} Pokemon") elif typeid == 13: text = _('Use {0} {type}Berries to help catch Pokemon') arr['type'] = "" match_object = re.search(r'"item": ([0-9]+)', condition) if match_object is not None: arr['type'] = items[match_object.group(1)]['name'].replace( _(' Berry'), '') + " " elif typeid == 14: text = _('Power up Pokemon {0} times') elif typeid == 15 or typeid == 43: arr['mega'] = "" text = _("{mega}Evolve {0} Pokemon") if typeid == 43: arr['mega'] = _("Mega ") for con in condition_dict: if con.get('type', 0) == 11: text = _("Use an item to {mega}evolve {0} Pokemon") # Try to find the exact evolution item needed # [{"type": 11, "with_item": {"item": 1106}}] with_item = con.get('with_item', {}).get('item', None) if with_item is not None: text = _('Use {item} to {mega}evolve {0} Pokemon') arr['item'] = items[str(with_item)]['name'] if con.get('type', 0) == 1: text = _("{mega}Evolve {0} {type}Pokemon") arr['wb'] = "" arr['type'] = "" arr['poke'] = "" match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['type'] = pokemonTypes[pt[0]].title() + _('-type ') else: for ty in pt: arr['type'] += (_('or ') if last == cur else '') + pokemonTypes[ty].title() + ( _('-type ') if last == cur else '-, ') cur += 1 if con.get('type', 0) == 2: arr['wb'] = "" arr['type'] = "" arr['poke'] = "" match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['poke'] = i8ln(pokemonname(pt[0])) else: for ty in pt: arr['poke'] += (_('or ') if last == cur else '') + i8ln(pokemonname(ty)) + ( '' if last == cur else ', ') cur += 1 text = _('{mega}Evolve {0} {poke}') elif typeid == 16: arr['inrow'] = "" arr['curve'] = "" arr['type'] = "" if re.search(r'"type": 14', condition) is not None: arr['inrow'] = _(" in a row") if re.search(r'"type": 15', condition) is not None: arr['curve'] = _("Curveball ") match_object = re.search(r'"throw_type": ([0-9]{2})', condition) if match_object is not None: arr['type'] = throwTypes[match_object.group(1)] + " " text = _("Make {0} {type}{curve}Throws{inrow}") elif typeid == 17: text = _('Earn {0} Candies walking with your buddy') elif typeid == 22: if int(target) == int(1): text = _('Make a new friend') else: text = _('Make {0} new friends') elif typeid == 23: text = _('Trade {0} Pokemon') arr['distance'] = "" if re.search(r'"type": 25', condition) is not None: arr['distance'] = re.search(r'"distance_km": ([0-9, ]+)', condition).group(1) if int(target) == int(1): text = _('Trade Pokemon caught {distance} km apart') else: text = _('Trade {0} Pokemon caught {distance} km apart') elif typeid == 24: text = _('Send {0} gifts to friends') elif typeid == 27: for con in condition_dict: if con.get('type', 0) == 22: # PVP against team leader. text = _('Battle a Team Leader {0} times') elif con.get('type') == 23: gotta_win = con.get('with_pvp_combat', {}).get('requires_win') is True if gotta_win: text = _('Win a battle against another Trainer {0} times') else: text = _('Battle another Trainer {0} times') in_go_battle_league = any(x in con.get( 'with_pvp_combat', {}).get('combat_league_template_id', []) for x in [ "COMBAT_LEAGUE_VS_SEEKER_GREAT", "COMBAT_LEAGUE_VS_SEEKER_ULTRA", "COMBAT_LEAGUE_VS_SEEKER_MASTER" ]) vs_player = any(x in con.get('with_pvp_combat', {}).get( 'combat_league_template_id', []) for x in [ "COMBAT_LEAGUE_DEFAULT_GREAT", "COMBAT_LEAGUE_DEFAULT_ULTRA", "COMBAT_LEAGUE_DEFAULT_MASTER" ]) if not vs_player and in_go_battle_league and gotta_win: text = _('Win in the GO Battle League {0} times') elif in_go_battle_league and not vs_player: text = _('Battle in the GO Battle League {0} times') elif typeid == 28: # Take snapshots quest if re.search(r'"type": 28', condition) is not None: text = _("Take {0} snapshots of your Buddy") elif re.search(r'"type": 2', condition) is not None: arr['poke'] = "" match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['poke'] = i8ln(pokemonname(pt[0])) else: for ty in pt: arr['poke'] += (_('or ') if last == cur else '') + i8ln(pokemonname(ty)) + ( '' if last == cur else ', ') cur += 1 text = _("Take {0} snapshots of {poke}") elif re.search(r'"type": 1', condition) is not None: text = _("Take {0} snapshots of {type} Pokemon") arr['wb'] = "" arr['type'] = "" arr['poke'] = "" match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]', condition) if match_object is not None: pt = match_object.group(1).split(', ') last = len(pt) cur = 1 if last == 1: arr['type'] = pokemonTypes[pt[0]].title() + _('-type ') else: for ty in pt: arr['type'] += (_('or ') if last == cur else '') + pokemonTypes[ty].title() + ( _('-type ') if last == cur else '-, ') cur += 1 elif typeid == 29: # QUEST_BATTLE_TEAM_ROCKET Team Go rucket grunt batles. if int(target) == int(1): text = _('Battle a Team Rocket Grunt') for con in condition_dict: if con.get('type', 0) == 27 and con.get('with_invasion_character', {}).get('category') == 1: text = _('Battle {0} times against the Team GO Rocket Leaders') # TODO Handle category for specific team leaders as well (Arlo, Cliff, Sierra) if con.get('type', 0) == 18: # Condition type 18 means win a battle # TODO change WIN to Defeat like in-game text = text.replace(_('Battle'), _('Defeat')) quest_templates = open_json_file('quest_templates') if quest_template is not None and quest_template in quest_templates: text = _(quest_templates[quest_template]) if int(target) == int(1): text = text.replace(_(' Eggs'), _('n Egg')) text = text.replace(_(' Raids'), _(' Raid')) text = text.replace(_(' Battles'), _(' Battle')) text = text.replace(_(' candies'), _(' candy')) text = text.replace(_(' gifts'), _(' gift')) text = text.replace(_(' Pokestops'), _(' Pokestop')) text = text.replace(_(' {0} snapshots'), _(' a snapshot')) text = text.replace(_('Make {0} {type}{curve}Throws'), _('Make a {type}{curve}Throw')) text = text.replace(_(' {0} times'), '') text = text.replace(_('{0} hearts'), _('a heart')) arr['0'] = _("a") for key, val in arr.items(): text = text.replace('{' + key + '}', str(val)) text = text.replace(' ', ' ').strip() return text