def enable_translation(domain, root='..', enable_global=None): installed = importlib.util.find_spec(domain) if installed and pkg_resources.resource_exists(domain, 'locale'): localedir = pkg_resources.resource_filename(domain, 'locale') elif installed: localedir = None else: localedir = os.path.join(root, 'locale') gettext.bindtextdomain(domain, localedir) # For libglade, but only on non-win32 systems if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, localedir) gettext.bind_textdomain_codeset(domain, 'utf-8') if enable_global: gettext.textdomain(domain) # For libglade, but only on non-win32 systems if hasattr(locale, 'textdomain'): locale.textdomain(domain) if platform.system() == 'Windows': from ctypes import cdll libintl = cdll.LoadLibrary("libintl-8.dll") libintl.bindtextdomain(domain, localedir) libintl.bind_textdomain_codeset(domain, 'UTF-8') if enable_global: libintl.textdomain(domain) del libintl
def __init__(self, options=None, args=None, classic=False): # Check for another running instance of the daemon if os.path.isfile(deluge.configmanager.get_config_dir("deluged.pid")): # Get the PID and the port of the supposedly running daemon try: (pid, port) = open(deluge.configmanager.get_config_dir("deluged.pid")).read().strip().split(";") pid = int(pid) port = int(port) except ValueError: pid = None port = None def process_running(pid): if deluge.common.windows_check(): # Do some fancy WMI junk to see if the PID exists in Windows from win32com.client import GetObject def get_proclist(): WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') return [process.Properties_('ProcessID').Value for process in processes] return pid in get_proclist() else: # We can just use os.kill on UNIX to test if the process is running try: os.kill(pid, 0) except OSError: return False else: return True if pid is not None and process_running(pid): # Ok, so a process is running with this PID, let's make doubly-sure # it's a deluged process by trying to open a socket to it's port. import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(("127.0.0.1", port)) except socket.error: # Can't connect, so it must not be a deluged process.. pass else: # This is a deluged! s.close() raise deluge.error.DaemonRunningError("There is a deluge daemon running with this config directory!") # Initialize gettext try: locale.setlocale(locale.LC_ALL, '') if hasattr(locale, "bindtextdomain"): locale.bindtextdomain("deluge", pkg_resources.resource_filename("deluge", "i18n")) if hasattr(locale, "textdomain"): locale.textdomain("deluge") gettext.bindtextdomain("deluge", pkg_resources.resource_filename("deluge", "i18n")) gettext.textdomain("deluge") gettext.install("deluge", pkg_resources.resource_filename("deluge", "i18n")) except Exception, e: log.error("Unable to initialize gettext/locale: %s", e) import __builtin__ __builtin__.__dict__["_"] = lambda x: x
def initialize_gettext(gettext_path): locale.bindtextdomain("pytrainer", gettext_path) locale.textdomain("pytrainer") if sys.version_info[0] == 2: gettext.install("pytrainer", gettext_path, unicode=1) else: gettext.install("pytrainer", gettext_path)
def set_lang(lang, codeset='utf-8', gui=False): if not isinstance(lang, list): lang = [lang] locale_dir = os.path.join(os.path.dirname(__file__), 'i18n') domain = 'irssinotifier' gettext.bindtextdomain(domain, locale_dir) gettext.textdomain(domain) locale.bindtextdomain(domain, locale_dir) locale.textdomain(domain) if gui: import gtk.glade gtk.glade.bindtextdomain(domain) gtk.glade.textdomain(domain) try: translator = gettext.translation(domain, locale_dir, languages=lang, codeset=codeset) except IOError, ioe: lang = ['en'] print 'Language not supportted: %r' % ioe print 'Fallback to english' translator = gettext.translation(domain, locale_dir, languages=lang, codeset=codeset)
def main(): # Avoid duplicate process # From https://stackoverflow.com/questions/788411/check-to-see-if-python-script-is-running procLock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: procLock.bind('\0' + 'indicator-stickynotes') except socket.error: print('Indicator stickynotes already running.') sys.exit() try: locale.setlocale(locale.LC_ALL, '') except: locale.setlocale(locale.LC_ALL, 'C') # If we're running from /usr, then .mo files are not in MO_DIR. if os.path.abspath(__file__)[:4] == '/usr': # Fallback to default locale_dir = None else: locale_dir = os.path.join(os.path.dirname(__file__), MO_DIR) locale.bindtextdomain(LOCALE_DOMAIN, locale_dir) locale.textdomain(LOCALE_DOMAIN) parser = argparse.ArgumentParser(description=_("Sticky Notes")) parser.add_argument("-d", action='store_true', help="use the development" " data file") args = parser.parse_args() indicator = IndicatorStickyNotes(args) # Load global css for the first time. load_global_css() Gtk.main() indicator.save()
def __init__(self, applet, iid, debug_flag, manual_poscorrect): self.__gobject_init__() self.debug_flag = debug_flag self.manual_poscorrect = manual_poscorrect gettext.bindtextdomain(config.GETTEXT_PACKAGE(), config.GNOMELOCALEDIR()) gettext.textdomain(config.GETTEXT_PACKAGE()) locale.bindtextdomain(config.GETTEXT_PACKAGE(), config.GNOMELOCALEDIR()) locale.textdomain(config.GETTEXT_PACKAGE()) self.applet = applet self.__loadIcon__() self.ev_box = gtk.EventBox() self.image = gtk.Image() self.image.set_from_pixbuf(self.iconPixbuf) self.main_loaded = False self.ev_box.add(self.image) self.ev_box.show() self.ev_box.set_events(gtk.gdk.BUTTON_PRESS_MASK) self.ev_box.connect("button_press_event", self.event_box_clicked) self.applet.add(self.ev_box) self.create_menu() self.applet.show_all()
def main(): try: locale.setlocale(locale.LC_ALL, '') except: locale.setlocale(locale.LC_ALL, 'C') # If we're running from /usr, then .mo files are not in MO_DIR. if os.path.abspath(__file__)[:4] == '/usr': # Fallback to default locale_dir = None else: locale_dir = os.path.join(os.path.dirname(__file__), MO_DIR) locale.bindtextdomain(LOCALE_DOMAIN, locale_dir) locale.textdomain(LOCALE_DOMAIN) parser = argparse.ArgumentParser(description=_("Sticky Notes")) parser.add_argument("-d", action='store_true', help="use the development" " data file") args = parser.parse_args() indicator = IndicatorStickyNotes(args) # Load global css for the first time. load_global_css() Gtk.main() indicator.save()
def __new__(cls): """ This method creates and binds the builder window to the class. In order for this to work correctly, the class of the main window in the Glade UI file must be the same as the name of this class. https://eeperry.wordpress.com/2013/01/05/pygtk-new-style-python-class-using-builder/ """ try: # https://askubuntu.com/questions/140552/how-to-make-glade-load-translations-from-opt # For this particular case the locale module needs to be used instead of gettext. # Python's gettext module is pure python, it doesn't actually set the text domain # in a way that the C library can read, but locale does (by calling libc). locale.bindtextdomain('aacircuit', get_path_to_data('locale/')) locale.textdomain('aacircuit') builder = Gtk.Builder() # https://stackoverflow.com/questions/24320502/how-to-translate-pygtk-glade-gtk-builder-application builder.set_translation_domain('aacircuit') builder.add_from_file(get_path_to_data('preferences_dialog.glade')) except IOError: print(_("Failed to load XML GUI file preferences_dialog.glade")) sys.exit(1) new_object = builder.get_object('preferences') new_object.finish_initializing(builder) return new_object
def __init__(self): #setting up localization locales_dir = os.path.join( os.getcwd(), "10_localization", "locale", ) appname = "TUT" #required for showing Glade file translations locale.bindtextdomain(appname, locales_dir) locale.textdomain(locales_dir) #required for code translations gettext.bindtextdomain(appname, locales_dir) gettext.textdomain(appname) self.builder = Gtk.Builder() self.builder.set_translation_domain(appname) self.builder.add_from_file("10_lokalisation.glade") self.builder.connect_signals(Handler()) #translatable strings print(_("It's a trap!")) print(_("""These aren't the droids you're looking for.\n""")) #not translatable nonono = """\"Jar Jar is the key to all of this.\"""" george = "...ruined it." print(nonono, george) window = self.builder.get_object("window") window.show_all()
def __setup_locale(): # Required for Gtk.Builder messages try: locale.textdomain('exaile') except AttributeError: # E.g. Windows pass # Required for dynamically added messages gettextmod.textdomain('exaile') locale_path = None exaile_path = os.environ['EXAILE_DIR'] # If running from source dir, we have to set the paths. # (The test is equivalent to xdg.local_hack but without the xdg import, # which pulls in GLib.) if os.path.exists(os.path.join(exaile_path, 'po')): locale_path = os.path.join(exaile_path, 'po') # Detect the prefix, to see if we need to correct the locale path elif exaile_path.endswith(os.path.join('lib', 'exaile')): exaile_prefix = exaile_path[:-len(os.path.join('lib', 'exaile'))] if os.path.exists(os.path.join(exaile_prefix, 'share', 'locale')): locale_path = os.path.join(exaile_prefix, 'share', 'locale') if locale_path is not None: try: locale.bindtextdomain('exaile', locale_path) except AttributeError: # E.g. Windows pass gettextmod.bindtextdomain('exaile', locale_path)
def main(): try: locale.setlocale(locale.LC_ALL, "") except: locale.setlocale(locale.LC_ALL, "C") # If we're running from /usr, then .mo files are not in MO_DIR. if os.path.abspath(__file__)[:4] == "/usr": # Fallback to default locale_dir = None else: locale_dir = os.path.join(os.path.dirname(__file__), MO_DIR) locale.bindtextdomain(LOCALE_DOMAIN, locale_dir) locale.textdomain(LOCALE_DOMAIN) parser = argparse.ArgumentParser(description=_("Sticky Notes")) parser.add_argument("-d", action="store_true", help="use the development" " data file") args = parser.parse_args() indicator = IndicatorStickyNotes(args) # Load global css for the first time. load_global_css() GLib.idle_add(install_glib_handler, indicator, priority=GLib.PRIORITY_HIGH) Gtk.main() indicator.save()
def __init__(self, locale_path="", app_name="msgu"): self.app_name = app_name if len(locale_path)!=0: self.locale_path = locale_path else: self.locale_path = os.path.join(sys.prefix, 'local', 'share', 'locale') self._languages = {} self._language = None # http://stackoverflow.com/questions/10094335/how-to-bind-a-text-domain-to-a-local-folder-for-gettext-under-gtk3 # https://github.com/dieterv/elib.intl/blob/master/lib/elib/intl/__init__.py locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(self.app_name, self.locale_path) locale.bind_textdomain_codeset(self.app_name, 'UTF-8') locale.textdomain(self.app_name) gettext.bindtextdomain(self.app_name, self.locale_path) gettext.bind_textdomain_codeset(self.app_name, 'UTF-8') gettext.textdomain(self.app_name) #_ = gettext.gettext print( "Using locale folder: {}".format(self.locale_path) ) self.install() #self.update(locale_path, app_name) pass
def setup_translations(setup_pygtk=False): translations_path = resource_filename("deluge", "i18n") log.info("Setting up translations from %s", translations_path) try: if hasattr(locale, "bindtextdomain"): locale.bindtextdomain("deluge", translations_path) if hasattr(locale, "textdomain"): locale.textdomain("deluge") gettext.install("deluge", translations_path, unicode=True) if setup_pygtk: # Even though we're not using glade anymore, let's set it up so that # plugins still using it get properly translated. log.info("Setting up GTK translations from %s", translations_path) import gtk import gtk.glade gtk.glade.bindtextdomain("deluge", translations_path) gtk.glade.textdomain("deluge") except Exception, e: log.error("Unable to initialize gettext/locale!") log.exception(e) import __builtin__ __builtin__.__dict__["_"] = lambda x: x
def main(): locale.bindtextdomain(SHORT_NAME, get_locale_folder()) gettext.bindtextdomain(SHORT_NAME, get_locale_folder()) locale.textdomain(SHORT_NAME) gettext.textdomain(SHORT_NAME) with GLibLogHandler().applicationbound(): app = CoBangApplication() return app.run(sys.argv)
def apply_locale(self , current_lang ): domain = "firstuse" local_path = domain +"/data/locale" # fixme pathlib locale.bindtextdomain(domain , local_path ) locale.textdomain(domain) locale.setlocale(locale.LC_ALL, 'ar_AE.utf8') # note that language is "ar_AE.utf8" not "ar" or "ar_AE" self.builder.set_translation_domain(domain )
def setup_translations(setup_gettext=True, setup_pygtk=False): translations_path = get_translations_path() domain = 'deluge' log.info('Setting up translations from %s', translations_path) if setup_pygtk: try: log.info('Setting up GTK translations from %s', translations_path) if deluge.common.windows_check(): import ctypes try: libintl = ctypes.cdll.intl except WindowsError: # Fallback to named dll. libintl = ctypes.cdll.LoadLibrary('libintl-8.dll') libintl.bindtextdomain( domain, translations_path.encode(sys.getfilesystemencoding())) libintl.textdomain(domain) libintl.bind_textdomain_codeset(domain, 'UTF-8') libintl.gettext.restype = ctypes.c_char_p # Use glade for plugins that still uses it import gtk import gtk.glade gtk.glade.bindtextdomain(domain, translations_path) gtk.glade.textdomain(domain) except Exception as ex: log.error('Unable to initialize glade translation: %s', ex) if setup_gettext: try: if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, translations_path) if hasattr(locale, 'textdomain'): locale.textdomain(domain) gettext.bindtextdomain(domain, translations_path) gettext.bind_textdomain_codeset(domain, 'UTF-8') gettext.textdomain(domain) # Workaround for Python 2 unicode gettext (keyword removed in Py3). kwargs = {} if not deluge.common.PY2 else {'unicode': True} gettext.install(domain, translations_path, names='ngettext', **kwargs) builtins.__dict__['_n'] = builtins.__dict__['ngettext'] except Exception as ex: log.error('Unable to initialize gettext/locale!') log.exception(ex) set_dummy_trans() deluge.common.translate_size_units()
def set_application_domain(self, domain): """ Sets the default application domain @param domain: the domain """ gettext.textdomain(domain) # For libglade, but only on non-win32 systems if hasattr(locale, 'textdomain'): locale.textdomain(domain)
def __init__(self, parent): self.parent = parent self.app = self.parent.app self.INFO_DIR = os.path.join(self.app.BASE_DIR, 'info') locale.bindtextdomain(self.parent.app.domain, os.path.join(self.app.BASE_DIR, 'locale')) locale.textdomain(self.app.domain) self.show = self.Message
def main(): from gi.repository import Gtk from lightdm_gtk_greeter_settings import GtkGreeterSettingsWindow import locale locale.textdomain('lightdm-gtk-greeter-settings') window = GtkGreeterSettingsWindow.GtkGreeterSettingsWindow() window.show() Gtk.main()
def _init_gettext(): """Initialize translation settings.""" locale.setlocale(locale.LC_ALL, "") try: # Not available on all platforms. locale.bindtextdomain("gaupol", aeidon.LOCALE_DIR) locale.textdomain("gaupol") except AttributeError: pass gettext.bindtextdomain("gaupol", aeidon.LOCALE_DIR) gettext.textdomain("gaupol")
def setup_translations(self): gettext.bindtextdomain("kazam", "/usr/share/locale") gettext.textdomain("kazam") locale.bindtextdomain("kazam", "/usr/share/locale") locale.textdomain("kazam") currentLocale = locale.getlocale() try: locale.setlocale(locale.LC_ALL, currentLocale) except Exception as e: logger.exception("EXCEPTION: Setlocale failed, no language support.")
def switch_locale(self, locale_type): """ Change the locale """ locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(locale_type, RB.locale_dir()) locale.textdomain(locale_type) gettext.bindtextdomain(locale_type, RB.locale_dir()) gettext.textdomain(locale_type) gettext.install(locale_type)
def switch_locale(self, locale_type): ''' Change the locale ''' locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(locale_type, RB.locale_dir()) locale.textdomain(locale_type) gettext.bindtextdomain(locale_type, RB.locale_dir()) gettext.textdomain(locale_type) gettext.install(locale_type)
def setup_gettext(domain, data_dir): directory = os.path.abspath(os.path.join(data_dir, "locale")) gettext.bindtextdomain(domain, directory) if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset(domain, 'UTF-8') gettext.textdomain(domain) locale.bindtextdomain(domain, directory) if hasattr(locale, 'bind_textdomain_codeset'): locale.bind_textdomain_codeset(domain, 'UTF-8') locale.textdomain(domain)
def __init__(self, **kwargs): self.ui = None GObject.threads_init() listen() Gtk.Application.__init__(self, application_id='com.github.geigi.cozy') GLib.setenv("PULSE_PROP_media.role", "music", True) import gettext locale.bindtextdomain('cozy', localedir) locale.textdomain('cozy') gettext.install('cozy', localedir)
def main(): import argparse import locale import os from gi.repository import Gtk from lightdm_gtk_greeter_settings import helpers from lightdm_gtk_greeter_settings import GtkGreeterSettingsWindow from lightdm_gtk_greeter_settings.GtkGreeterSettingsWindow import WindowMode locale.textdomain('lightdm-gtk-greeter-settings') parser = argparse.ArgumentParser(description='LightDM Gtk+ Greeter settings editor') parser.add_argument('-s', '--socket-id', action='store', help='Settings manager socket') parser.add_argument('--use-gtk-header', action='store_const', const=True, help='Use GtkHeaderBar') parser.add_argument('--test-socket', action='store_const', const=True) args = parser.parse_args() if args.test_socket: w = Gtk.Window() w.props.title = 'Testing embedded mode' socket = Gtk.Socket.new() w.add(socket) w.show_all() args.socket_id = socket.get_id() try: socket_id = int(args.socket_id or '') except ValueError: socket_id = None if socket_id: window = GtkGreeterSettingsWindow.GtkGreeterSettingsWindow(WindowMode.Embedded) plug = Gtk.Plug.new(socket_id) plug.connect('delete-event', Gtk.main_quit) plug.show() content = window.builder.get_object('content_box') content.reparent(plug) Gtk.main() else: if args.use_gtk_header is None: args.use_gtk_header = helpers.string2bool(os.getenv('GTK_CSD'), False) elif args.use_gtk_header: os.putenv('GTK_CSD', '1') window_mode = WindowMode.Default if args.use_gtk_header: window_mode = WindowMode.GtkHeader window = GtkGreeterSettingsWindow.GtkGreeterSettingsWindow(mode=window_mode) window.show() Gtk.main()
def init_gettext(locale_dir): u'''Initialize gettext using the given directory containing the l10n data. ''' gettext.bindtextdomain('sdaps', locale_dir) if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset('sdaps', 'UTF-8') gettext.textdomain('sdaps') if hasattr(locale, 'bind_textdomain_codeset'): locale.bindtextdomain('sdaps', locale_dir) locale.bind_textdomain_codeset('sdaps', 'UTF-8') locale.textdomain('sdaps')
def _init_gettext(self): """Initialize translation settings.""" with nfoview.util.silent(Exception): # Might fail with misconfigured locales. locale.setlocale(locale.LC_ALL, "") d = nfoview.LOCALE_DIR with nfoview.util.silent(Exception): # Not available on all platforms. locale.bindtextdomain("nfoview", d) locale.textdomain("nfoview") gettext.bindtextdomain("nfoview", d) gettext.textdomain("nfoview")
def bind_locale(self): """Bind the domain for localization. Bind the locale dir with a subdirectory in the current path. Set the domain to the domain with the NAMEASONE constant. """ #next line will bind the locale to our own directory #and is not needed if we want our translation to be system wide locale.bindtextdomain(NAMEASONE, os.path.join(self.BASE_DIR, 'locale')) #this will bind the locale with some name #in order to load the corresponding .mo file for the language locale.textdomain(NAMEASONE)
def init_gettext(locale_dir): u'''Initialize gettext. Tell it, where to find the translation files. ''' gettext.bindtextdomain('sdaps', locale_dir) if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset('sdaps', 'UTF-8') gettext.textdomain('sdaps') if hasattr(locale, 'bind_textdomain_codeset'): locale.bindtextdomain('sdaps', locale_dir) locale.bind_textdomain_codeset('sdaps', 'UTF-8') locale.textdomain('sdaps')
def init(lets_connect: bool, prefix: str): """ Init locale and gettext, returns text domain """ domain = 'LetConnect' if lets_connect else 'eduVPN' directory = os.path.join(prefix, 'share/locale') locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(domain, directory) # type: ignore locale.textdomain(domain) # type: ignore install(domain, names=('gettext', 'ngettext'), localedir=directory) return domain
def setup_translation(): translations_path = get_translations_path() log.info('Setting up translations from %s', translations_path) try: if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(I18N_DOMAIN, translations_path) if hasattr(locale, 'textdomain'): locale.textdomain(I18N_DOMAIN) gettext.bindtextdomain(I18N_DOMAIN, translations_path) gettext.bind_textdomain_codeset(I18N_DOMAIN, 'UTF-8') gettext.textdomain(I18N_DOMAIN) # Workaround for Python 2 unicode gettext (keyword removed in Py3). kwargs = {} if not deluge.common.PY2 else {'unicode': True} gettext.install(I18N_DOMAIN, translations_path, names='ngettext', **kwargs) builtins.__dict__['_n'] = builtins.__dict__['ngettext'] libintl = None if deluge.common.windows_check(): for intl in ('libintl-8.dll', 'intl.dll'): try: libintl = ctypes.cdll.LoadLibrary(intl) except OSError as ex: exception = ex else: break finally: if not libintl: log.error('Unable to initialize gettext/locale!') log.error(exception) setup_mock_translation() elif deluge.common.osx_check(): libintl = ctypes.cdll.LoadLibrary('libintl.dylib') if libintl: libintl.bindtextdomain( I18N_DOMAIN, translations_path.encode(sys.getfilesystemencoding()) ) libintl.textdomain(I18N_DOMAIN) libintl.bind_textdomain_codeset(I18N_DOMAIN, 'UTF-8') libintl.gettext.restype = ctypes.c_char_p except Exception as ex: log.error('Unable to initialize gettext/locale!') log.exception(ex) setup_mock_translation() deluge.common.translate_size_units()
def enable_translation(self, domain=None, enable_global=False): """ Enables translation for a library :param domain: optional, if not specified name sent to constructor will be used :param enable_global: if we should set that domain as the default domain when using gettext without one """ if not domain: domain = self.name if (not self.uninstalled and pkg_resources.resource_exists(domain, 'locale')): localedir = pkg_resources.resource_filename(domain, 'locale') elif not self.uninstalled: localedir = None else: localedir = os.path.join(self.get_root(), 'locale') directory = gettext.bindtextdomain(domain, localedir) self._check_translation(domain, directory) # For libglade, but only on non-win32 systems if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, localedir) # Gtk+ only supports utf-8, it makes no sense to support # other encodings in kiwi it self # This is not present in Python 2.3 if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset(domain, 'utf-8') # FIXME: There's a bug on gtkbuilder where it needs to have the # textdomain set for translations to work, no matter what translation # domain we set on it. We should try to find a way around this or else # we won't be able to translate glades from a domain other than this one if enable_global: gettext.textdomain(domain) # For libglade, but only on non-win32 systems if hasattr(locale, 'textdomain'): locale.textdomain(domain) if platform.system() == 'Windows': from ctypes import cdll libintl = cdll.intl libintl.bindtextdomain(domain, localedir) libintl.bind_textdomain_codeset(domain, 'UTF-8') if enable_global: libintl.textdomain(domain) del libintl
def setup_l10n(): try: locale.setlocale(locale.LC_ALL, '') except locale.Error as e: logger.warning("Cannot setup translations: {}".format(e)) localedir = resource_filename('rafcon', 'locale') # Install gettext globally: Allows to use _("my string") without further imports gettext.install('rafcon', localedir) # Required for glade and the GtkBuilder locale.bindtextdomain('rafcon', localedir) locale.textdomain('rafcon')
def init(app_variant: ApplicationVariant, prefix: str): """ Init locale and gettext, returns text domain """ domain = app_variant.translation_domain directory = os.path.join(prefix, 'share/locale') locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(domain, directory) # type: ignore locale.textdomain(domain) # type: ignore gettext.bindtextdomain(domain, directory) gettext.textdomain(domain) return domain
def set_application_domain(self, domain): """ Sets the default application domain :param domain: the domain """ gettext.textdomain(domain) # For libglade, but only on non-win32 systems if hasattr(locale, 'textdomain'): locale.textdomain(domain) if platform.system() == 'Windows': from ctypes import cdll libintl = cdll.intl libintl.textdomain(domain) del libintl
def setup_translations(): translations_path = resource_filename("mirror", "i18n") log.info("Setting up translations from %s", translations_path) try: if hasattr(locale, "bindtextdomain"): locale.bindtextdomain("mirror", translations_path) if hasattr(locale, "textdomain"): locale.textdomain("mirror") gettext.install("mirror", translations_path, unicode=True) except Exception as e: log.error("Unable to initialize gettext/locale") log.exception(e) import __builtin__ __builtin__.__dict__["_"] = lambda x: x
def setup_translations(): translations_path = resource_filename("mirror", "i18n") log.info("Setting up translations from %s", translations_path) try: if hasattr(locale, "bindtextdomain"): locale.bindtextdomain("mirror", translations_path) if hasattr(locale, "textdomain"): locale.textdomain("mirror") gettext.install("mirror", translations_path, unicode=True) except Exception, e: log.error("Unable to initialize gettext/locale") log.exception(e) import __builtin__ __builtin__.__dict__["_"] = lambda x: x
def __init__(self, **kwargs): self.ui = None listen() Gtk.Application.__init__(self, application_id='com.github.geigi.cozy') GLib.setenv("PULSE_PROP_media.role", "music", True) GLib.set_application_name("Cozy") self.old_except_hook = sys.excepthook sys.excepthook = self.handle_exception import gettext locale.bindtextdomain('com.github.geigi.cozy', localedir) locale.textdomain('com.github.geigi.cozy') gettext.install('com.github.geigi.cozy', localedir)
def bind(localedir=nfoview.LOCALE_DIR): with nfoview.util.silent(Exception): # Set locale to the user's default setting. # Might fail on misconfigured systems. locale.setlocale(locale.LC_ALL, "") # Make translations available to the gettext module. gettext.bindtextdomain("nfoview", localedir) gettext.textdomain("nfoview") with nfoview.util.silent(Exception): # Make translations available to GTK+ as well. # Not available on all platforms. locale.bindtextdomain("nfoview", localedir) locale.textdomain("nfoview") globals()["_translation"] = gettext.translation( "nfoview", localedir=localedir, fallback=True)
def bind(localedir=aeidon.LOCALE_DIR): """Bind translation domains and initialize gettext.""" with aeidon.util.silent(Exception): # Set locale to the user's default setting. # Might fail on misconfigured systems. locale.setlocale(locale.LC_ALL, "") # Make translations available to the gettext module. gettext.bindtextdomain("gaupol", localedir) gettext.textdomain("gaupol") with aeidon.util.silent(Exception): # Make translations available to GTK+ as well. # Not available on all platforms. locale.bindtextdomain("gaupol", localedir) locale.textdomain("gaupol") globals()["_translation"] = gettext.translation( "gaupol", localedir=localedir, fallback=True)
def __init__(self): APP = "vista_ipm" DIR = "locale" gettext.textdomain(APP) gettext.bindtextdomain(APP, DIR) locale.textdomain(APP) locale.bindtextdomain(APP, DIR) locale.setlocale(locale.LC_ALL, '') _ = gettext.gettext builder = Gtk.Builder() builder.add_from_file("interfaz3.glade") builder.connect_signals(self) self.mod = modelo.modelo() self.cont = control.control(builder) self.cont.init_builder() self.cont.init_app(self)
def _install(domain, localedir, asglobal=False): ''' :param domain: translation domain :param localedir: locale directory :param asglobal: if True, installs the function _() in Python�s builtin namespace. Default is False Private function doing all the work for the :func:`elib.intl.install` and :func:`elib.intl.install_module` functions. ''' # prep locale system if asglobal: locale.setlocale(locale.LC_ALL, '') # on windows systems, set the LANGUAGE environment variable if sys.platform == 'win32' or sys.platform == 'nt': _putenv('LANGUAGE', _getscreenlanguage()) #print "=========2>", os.getenv('LANGUAGE') # The locale module on Max OS X lacks bindtextdomain so we specifically # test on linux2 here. See commit 4ae8b26fd569382ab66a9e844daa0e01de409ceb if sys.platform == 'linux2': locale.bindtextdomain(domain, localedir) locale.bind_textdomain_codeset(domain, 'UTF-8') locale.textdomain(domain) # initialize Python's gettext interface gettext.bindtextdomain(domain, localedir) gettext.bind_textdomain_codeset(domain, 'UTF-8') if asglobal: gettext.textdomain(domain) # on windows systems, initialize libintl if sys.platform == 'win32' or sys.platform == 'nt': from ctypes import cdll try : libintl = cdll.intl except : libintl = cdll.LoadLibrary("libintl-8.dll") libintl.bindtextdomain(domain, localedir) libintl.bind_textdomain_codeset(domain, 'UTF-8') if asglobal: libintl.textdomain(domain) del libintl
def bind(): """Bind translation domains and initialize gettext.""" global _translation d = nfoview.LOCALE_DIR with nfoview.util.silent(Exception): # Might fail with misconfigured locales. locale.setlocale(locale.LC_ALL, "") with nfoview.util.silent(Exception): # Not available on all platforms. Seems to be # needed by GTK+ applications and probably others # with C library dependencies that use gettext. locale.bindtextdomain("nfoview", d) locale.textdomain("nfoview") gettext.bindtextdomain("nfoview", d) gettext.textdomain("nfoview") _translation = gettext.translation( "nfoview", localedir=d, fallback=True)
def enable_translation(self, domain=None, enable_global=False): """ Enables translation for a library :param domain: optional, if not specified name sent to constructor will be used :param enable_global: if we should set that domain as the default domain when using gettext without one """ if not domain: domain = self.name if (not self.uninstalled and pkg_resources.resource_exists(domain, 'locale')): localedir = pkg_resources.resource_filename(domain, 'locale') elif not self.uninstalled: localedir = None else: localedir = os.path.join(self.get_root(), 'locale') directory = gettext.bindtextdomain(domain, localedir) self._check_translation(domain, directory) # For libglade, but only on non-win32 systems if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, localedir) # Gtk+ only supports utf-8, it makes no sense to support # other encodings in kiwi it self # This is not present in Python 2.3 if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset(domain, 'utf-8') if enable_global: gettext.textdomain(domain) # For libglade, but only on non-win32 systems if hasattr(locale, 'textdomain'): locale.textdomain(domain) if platform.system() == 'Windows': from ctypes import cdll libintl = cdll.LoadLibrary("libintl-8.dll") libintl.bindtextdomain(domain, localedir) libintl.bind_textdomain_codeset(domain, 'UTF-8') if enable_global: libintl.textdomain(domain) del libintl
def _initResourcesAndLocales(self): # Initialize resources logging.debug("+ Initialize resources...") if not ResourcesConfiguration.initializeResources(): logging.fatal("Error while configuring the resources of Netzob") sys.exit() # Initialiaze gettext gettext.bindtextdomain("netzob", ResourcesConfiguration.getLocaleLocation()) gettext.textdomain("netzob") locale.bindtextdomain("netzob", ResourcesConfiguration.getLocaleLocation()) locale.textdomain("netzob") try: locale.getlocale() except: logging.exception("setlocale failed, resetting to C") locale.setlocale(locale.LC_ALL, "C")
def setup_translations(setup_gettext=True, setup_pygtk=False): translations_path = get_translations_path() domain = 'deluge' log.info('Setting up translations from %s', translations_path) if setup_pygtk: try: log.info('Setting up GTK translations from %s', translations_path) if deluge.common.windows_check(): import ctypes try: libintl = ctypes.cdll.intl except WindowsError: # Fallback to named dll. libintl = ctypes.cdll.LoadLibrary('libintl-8.dll') libintl.bindtextdomain(domain, translations_path.encode(sys.getfilesystemencoding())) libintl.textdomain(domain) libintl.bind_textdomain_codeset(domain, 'UTF-8') libintl.gettext.restype = ctypes.c_char_p # Use glade for plugins that still uses it import gtk import gtk.glade gtk.glade.bindtextdomain(domain, translations_path) gtk.glade.textdomain(domain) except Exception as ex: log.error('Unable to initialize glade translation: %s', ex) if setup_gettext: try: if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, translations_path) if hasattr(locale, 'textdomain'): locale.textdomain(domain) gettext.bindtextdomain(domain, translations_path) gettext.bind_textdomain_codeset(domain, 'UTF-8') gettext.textdomain(domain) gettext.install(domain, translations_path) except Exception as ex: log.error('Unable to initialize gettext/locale!') log.exception(ex) set_dummy_trans() deluge.common.translate_size_units()
def main(): try: locale.setlocale(locale.LC_ALL, '') except: locale.setlocale(locale.LC_ALL, 'C') # If we're running from /usr, then .mo files are not in MO_DIR. if os.path.abspath(__file__)[:4] == '/usr': # Fallback to default locale_dir = None else: locale_dir = os.path.join(os.path.dirname(__file__), MO_DIR) locale.bindtextdomain(LOCALE_DOMAIN, locale_dir) locale.textdomain(LOCALE_DOMAIN) indicator = IndicatorStickyNotes() # Load global css for the first time. load_global_css() Gtk.main() indicator.save()
def start(): """Starts SpiceGUI application.""" import gettext import locale domain = config.DOMAIN locale_path = get_locale_path() gettext.install(domain, locale_path) locale.textdomain(domain) locale.bindtextdomain(domain, locale_path) locale.textdomain(domain) locale.setlocale(locale.LC_ALL, '') import application import sys app = application.SpiceGUI() app.run(sys.argv)
def _init_gettext(): """Initialize translation settings.""" try: # Might fail with misconfigured locales. locale.setlocale(locale.LC_ALL, "") except Exception: print("Failed to set default locale.", file=sys.stderr) print("Please check your locale settings.", file=sys.stderr) print("Falling back to the 'C' locale.", file=sys.stderr) locale.setlocale(locale.LC_ALL, "C") try: # Not available on all platforms. locale.bindtextdomain("gaupol", aeidon.LOCALE_DIR) locale.textdomain("gaupol") except AttributeError: pass gettext.bindtextdomain("gaupol", aeidon.LOCALE_DIR) gettext.textdomain("gaupol")