Example #1
0
    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():
    # 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()
Example #3
0
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)
Example #4
0
    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
Example #5
0
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
Example #6
0
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)
Example #7
0
def _setup_locale():
	''' setup locales and gettext '''
	import gettext
	import locale

	use_home_dir = sys.platform != 'win32'
	app_config = appconfig.AppConfig('photocat.cfg', __file__,
			use_home_dir=use_home_dir, app_name='photocat')
	locales_dir = app_config.locales_dir
	package_name = 'photocat'
	_LOG.debug('run: locale dir: %s' % locales_dir)
	try:
		locale.bindtextdomain(package_name, locales_dir)
		locale.bind_textdomain_codeset(package_name, "UTF-8")
	except:
		pass
	default_locale = locale.getdefaultlocale()
	locale.setlocale(locale.LC_ALL, '')
	if sys.platform == 'win32':
		os.environ['LC_ALL'] = os.environ.get('LC_ALL') or default_locale[0]
	gettext.install(package_name, localedir=locales_dir, unicode=True,
			names=("ngettext",))
	gettext.bindtextdomain(package_name, locales_dir)
	gettext.bind_textdomain_codeset(package_name, "UTF-8")

	_LOG.debug('locale: %s' % str(locale.getlocale()))
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()
Example #9
0
	def __init__(self, project):
		"""Constructor"""  
		self.project = project
		
		# Setup foreign language support
		langs = []
		lc, encoding = locale.getlocale(locale.LC_MESSAGES)

		if (lc):
			langs = [lc]			
		language = os.environ.get('LANGUAGE', None)
		if (language):
			langs += language.split(":")

		# Set locale specific settings
		locale.setlocale(locale.LC_ALL)
		locale.bindtextdomain("OpenShot", self.project.LOCALE_DIR)
		locale.bind_textdomain_codeset("OpenShot", "UTF-8")

		# Set gettext settings
		gettext.bindtextdomain("OpenShot", self.project.LOCALE_DIR)
		gettext.bind_textdomain_codeset("OpenShot", "UTF-8")
		gettext.textdomain("OpenShot")
		gettext.install(domain="OpenShot")

		# This reference is used by other classes to define the _ method 
		self.lang = gettext.translation("OpenShot", self.project.LOCALE_DIR, languages = langs, fallback = True)
Example #10
0
def setup_locale_and_gettext():
	"""Set up localization with gettext"""
	package_name = "kupfer"
	localedir = "./locale"
	try:
		from kupfer import version_subst
	except ImportError:
		pass
	else:
		package_name = version_subst.PACKAGE_NAME
		localedir = version_subst.LOCALEDIR
	# Install _() builtin for gettext; always returning unicode objects
	# also install ngettext()
	gettext.install(package_name, localedir=localedir, unicode=True,
			names=("ngettext",))
	# For gtk.Builder, we need to call the C library gettext functions
	# As well as set the codeset to avoid locale-dependent translation
	# of the message catalog
	locale.bindtextdomain(package_name, localedir)
	locale.bind_textdomain_codeset(package_name, "UTF-8")
	# to load in current locale properly for sorting etc
	try:
		locale.setlocale(locale.LC_ALL, "")
	except locale.Error, e:
		pass
Example #11
0
def bindtextdomain(app_name, locale_dir=None):
    """
    Bind the domain represented by app_name to the locale directory locale_dir.
    It has the effect of loading translations, enabling applications for different
    languages.

    app_name:
        a domain to look for translations, tipically the name of an application.

    locale_dir:
        a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo
        If omitted or None, then the current binding for app_name is used.
    """
    # installa _() e ngettext() builtin
    gettext.install(app_name, localedir=locale_dir,
                    names=("ngettext",))
    try:
        locale.bindtextdomain(app_name, locale_dir)
        locale.bind_textdomain_codeset(app_name, "UTF-8")
    except AttributeError:
        pass

    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error as e:
        pass
Example #12
0
    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()
Example #13
0
	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
Example #14
0
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 __init__(self, start_files=[]):

        locale_dir = os.path.dirname(__file__)
        locale_dir = os.path.abspath(locale_dir)
        locale_dir += os.sep + "locale"

        locale.setlocale(locale.LC_ALL, "")
        locale.bindtextdomain(self.TRANSL_DOMAIN, locale_dir)

        gettext.bindtextdomain(self.TRANSL_DOMAIN, locale_dir)
        gettext.textdomain(self.TRANSL_DOMAIN)
        
        self._builder = gtk.Builder()
        self._builder.set_translation_domain(self.TRANSL_DOMAIN)
                
        path = get_resource_path("goceditor.ui")
        self._builder.add_from_file(path)
        
        self._create_widgets()
        
        self._builder.connect_signals(self)
        
        for start_file in start_files:
            if not os.path.exists(start_file):
                fd = open(start_file, "w")
                fd.close()
            self._docs_model.load_document(start_file)
Example #16
0
    def __init__(self, dbstate, user, options_class, name, callback=None):
        uistate = user.uistate

        self.label = _("Sources Index")
        self.base = os.path.dirname(__file__)

        ManagedWindow.__init__(self, uistate, [], self.__class__)
        self.set_window(Gtk.Window(), Gtk.Label(), "")

        tool.Tool.__init__(self, dbstate, options_class, name)

        glade_file = os.path.join(USER_PLUGINS, "SourceIndex", "death.glade")

        if gramps.gen.constfunc.lin():
            import locale

            locale.setlocale(locale.LC_ALL, "")
            # This is needed to make gtk.Builder work by specifying the
            # translations directory
            locale.bindtextdomain("addon", self.base + "/locale")

            self.glade = Gtk.Builder()
            self.glade.set_translation_domain("addon")

            self.glade.add_from_file(glade_file)

            from gi.repository import GObject

            GObject.GObject.__init__(self.glade)

            window = self.glade.get_object("edit_death")

            self.set_window(window, self.glade.get_object("title"), self.label)

            # self.wit_button = self.glade.get_object('add_wit')
            self.ok_button = self.glade.get_object("ok")
            self.quit_button = self.glade.get_object("cancel")

        else:

            # Glade class from gui/glade.py and gui/managedwindow.py
            self.top = Glade()
            window = self.top.toplevel
            self.set_window(window, None, glade_file)

            # self.wit_button = self.top.get_object('add_wit')
            self.ok_button = self.top.get_object("ok")
            self.quit_button = self.top.get_object("cancel")

        # self.wit_button.connect('clicked', GtkHandlers.on_witness_clicked)
        self.ok_button.connect("clicked", self.close)
        self.quit_button.connect("clicked", self.close)

        self.window.show()

        # tests
        filename = os.path.join(USER_PLUGINS, "SourceIndex", "test_death.xml")
        self.write_xml(filename, "D0001", "DATE", "NOM")
        self.parse_xml(filename)
Example #17
0
def setup_i18n():
    global _
    locale.setlocale(locale.LC_ALL, '')
    gettext.install(ppm.gettext_app, ppm.gettext_dir)
    gettext.bindtextdomain(ppm.gettext_app, ppm.gettext_dir)
    locale.bindtextdomain(ppm.gettext_app, ppm.gettext_dir)
    _ = gettext.gettext
    logging.debug('Using locale: %s', locale.getlocale())
Example #18
0
def bindtextdomain(*args):
    if hasattr(locale, "bindtextdomain"):
        locale.bindtextdomain(*args)
    elif GLADE:
        glade.bindtextdomain(*args)
    elif otool.exists():  # Could use lsof instead
        intl = ctypes.CDLL(library())
        intl.bindtextdomain(*args)
Example #19
0
    def __init__(self, dbstate, user, options_class, name, callback=None):
        uistate = user.uistate

        self.label = _('Sources Index')
        self.base = os.path.dirname(__file__)

        ManagedWindow.__init__(self, uistate,[], self.__class__)
        self.set_window(Gtk.Window(),Gtk.Label(),'')

        tool.Tool.__init__(self, dbstate, options_class, name)

        glade_file = os.path.join(USER_PLUGINS, "SourceIndex", "index.glade")

        if gramps.gen.constfunc.lin():
            import locale
            locale.setlocale(locale.LC_ALL, '')
            # This is needed to make gtk.Builder work by specifying the
            # translations directory
            locale.bindtextdomain("addon", self.base + "/locale")

            self.glade = Gtk.Builder()
            self.glade.set_translation_domain("addon")

            self.glade.add_from_file(glade_file)

            from gi.repository import GObject
            GObject.GObject.__init__(self.glade)

            self.top = self.glade.get_object('edit_index')

            self.set_window(self.top, self.glade.get_object('title'), self.label)

            self.birth_button = self.glade.get_object('add_b')
            self.death_button = self.glade.get_object('add_d')
            self.marriage_button = self.glade.get_object('add_m')
            self.census_button = self.glade.get_object('add_c')

            self.birth_button.connect('clicked', self.birth_editor)
            self.death_button.connect('clicked', self.death_editor)
            self.marriage_button.connect('clicked', self.marriage_editor)
            self.census_button.connect('clicked', self.census_editor)

        else:

            # Glade class from gui/glade.py and gui/managedwindow.py
            self.define_glade('edit_index', glade_file)
            self.set_window(self._gladeobj.toplevel, None, text=None, msg='Index')

            self.connect_button('add_b', self.birth_editor)
            self.connect_button('add_m', self.marriage_editor)
            self.connect_button('add_d', self.death_editor)
            self.connect_button('add_c', self.census_editor)

        #self.window.connect('delete-event', GladeHandlers.on_quit_clicked)

        self.window.show()
Example #20
0
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 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)
Example #23
0
    def birth_editor(self, widget, data=None):
        """
        Experimental call of the birth editor (see rather 'birth.py')
        """

        glade_file = os.path.join(USER_PLUGINS, "SourceIndex", "birth.glade")

        if gramps.gen.constfunc.lin():
            import locale
            locale.setlocale(locale.LC_ALL, '')
            # This is needed to make gtk.Builder work by specifying the
            # translations directory
            locale.bindtextdomain("addon", self.base + "/locale")

            self.glade = Gtk.Builder()
            self.glade.set_translation_domain("addon")

            self.glade.add_from_file(glade_file)

            from gi.repository import GObject
            GObject.GObject.__init__(self.glade)

            b = self.glade.get_object('edit_birth')

            self.set_window(b, self.glade.get_object('title'), self.label)

            #self.wit_button = self.glade.get_object('add_wit')
            self.ok_button = self.glade.get_object('ok')
            self.quit_button = self.glade.get_object('cancel')

        else:

            # Glade class from gui/glade.py and gui/managedwindow.py
            top = Glade(glade_file)
            b = top.toplevel
            self.set_window(b, title=None, text=glade_file)

            #self.wit_button = top.get_object('add_wit')
            self.ok_button = top.get_object('ok')
            self.quit_button = top.get_object('cancel')

        #self.wit_button.connect('clicked', GtkHandlers.on_witness_clicked)
        self.ok_button.connect('clicked', self.close)
        self.quit_button.connect('clicked', self.close)

        #add_item()
        #close_item()
        #close_track()

        #b.connect('delete-event', GladeHandlers.on_quit_clicked)

        #b.hide()
        b.show()
Example #24
0
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')
Example #25
0
def init():
    localedir = os.getenv("IBUS_LOCALEDIR")
    # Python's locale module doesn't provide all methods on some
    # operating systems like FreeBSD
    try:
        # for non-standard localedir
        locale.bindtextdomain(DOMAINNAME, localedir)
        locale.bind_textdomain_codeset(DOMAINNAME, "UTF-8")
    except AttributeError:
        pass
    gettext.bindtextdomain(DOMAINNAME, localedir)
    gettext.bind_textdomain_codeset(DOMAINNAME, "UTF-8")
Example #26
0
 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")
Example #27
0
def init_textdomain(domainname):
    if domainname == '':
        return
    # Python's locale module doesn't provide all methods on some
    # operating systems like FreeBSD
    try:
        locale.bindtextdomain(domainname, LOCALEDIR)
        locale.bind_textdomain_codeset(domainname, 'UTF-8')
    except AttributeError:
        pass
    gettext.bindtextdomain(domainname, LOCALEDIR)
    gettext.bind_textdomain_codeset(domainname, 'UTF-8')
Example #28
0
    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)
Example #29
0
 def __init__(self):
     title="A localized gui program"
     # localisation stuff
     locale.bindtextdomain(TRANSLATION_DOMAIN, LOCALE_DIR)
     locale.setlocale(locale.LC_ALL, "")
     # import the glade file
     builder = Gtk.Builder()
     builder.set_translation_domain(TRANSLATION_DOMAIN)
     builder.add_from_file("gui.glade")
     # connect the handlers
     builder.connect_signals(Handler())
     window = builder.get_object("MainWindow")
     window.show_all()
Example #30
0
def setup_locale_and_gettext():
    package_name = 'specto'
    # Install _() builtin for gettext; always returning unicode objects
    # also install ngettext()
    gettext.install(package_name, localedir=MESSAGES_DIR, unicode=True,
                    names=("ngettext",))
    locale.bindtextdomain(package_name, MESSAGES_DIR)
    locale.bind_textdomain_codeset(package_name, "UTF-8")

    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error, e:
        pass
Example #31
0
import gettext
import locale
from minigalaxy.config import Config
from minigalaxy.paths import LOCALE_DIR

TRANSLATION_DOMAIN = "minigalaxy"
try:
    locale.setlocale(locale.LC_ALL, '')
except locale.Error:
    print(
        "Unsupported locale detected, continuing without translation support")

try:
    locale.bindtextdomain(TRANSLATION_DOMAIN, LOCALE_DIR)
except AttributeError:
    print(
        "Couldn't run locale.bindtextdomain. Translations might not work correctly."
    )

try:
    locale.textdomain(TRANSLATION_DOMAIN)
except AttributeError:
    print(
        "Couldn't run locale.textdomain. Translations might not work correctly."
    )

gettext.bindtextdomain(TRANSLATION_DOMAIN, LOCALE_DIR)
gettext.textdomain(TRANSLATION_DOMAIN)

current_locale = Config.get("locale")
default_locale = locale.getdefaultlocale()[0]
Example #32
0
# Localization.
locale.setlocale(locale.LC_ALL, '')
extra_locale_dirs = [
    os.path.join(os.getcwd(), "locale"),
]

# this binds system translation
gettext.bindtextdomain('green-recorder')
gettext.textdomain('green-recorder')
gettext.install("green-recorder")

# if there is a translation in the current directory, use it
for locale_dir in extra_locale_dirs:
    if os.path.exists:
        locale.bindtextdomain('green-recorder', locale_dir)
        gettext.bindtextdomain('green-recorder', locale_dir)
        gettext.install("green-recorder", locale_dir)

# Define a loop and connect to the session bus. This is for Wayland recording under GNOME Shell.
loop = GLib.MainLoop()
bus = SessionBus()

# Get the current name of the Videos folder
RecorderDisplay = subprocess.check_output(
    "xdpyinfo | grep 'dimensions:'|awk '{print $2}'", shell=True)[:-1]
DISPLAY = os.environ["DISPLAY"]

DisplayServer = os.getenv('XDG_SESSION_TYPE', 'xorg')

print("You are recording on: " + str(DisplayServer))
Example #33
0
    try:
        opts, args = getopt.getopt(sys.argv[1:], shortopt, longopt)
    except getopt.GetoptError as err:
        print_help(1)

    for o, a in opts:
        if o in ("-h", "--help"):
            print_help(0)
        elif o in ("-d", "--daemonize"):
            daemonize = True
        elif o in ("-i", "--ibus"):
            exec_by_ibus = True
        else:
            sys.stderr.write("Unknown argument: %s\n" % o)
            print_help(1)

    if daemonize:
        if os.fork():
            sys.exit()

    IMApp(exec_by_ibus).run()


if __name__ == "__main__":
    try:
        locale.bindtextdomain(package.get_name(), package.get_localedir())
    except Exception:
        pass
    gettext.bindtextdomain(package.get_name(), package.get_localedir())
    main()
Example #34
0
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject

from consts import *
from hexview import HexView
from backend import GameConquerorBackend
from misc import u
import misc

import locale
import gettext

# In some locale, ',' is used in float numbers
locale.setlocale(locale.LC_NUMERIC, 'C')
locale.bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR)
gettext.install(GETTEXT_PACKAGE, LOCALEDIR, names=('_'))

CLIPBOARD = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
WORK_DIR = os.path.dirname(sys.argv[0])
PROGRESS_INTERVAL = 100  # for scan progress updates
DATA_WORKER_INTERVAL = 500  # for read(update)/write(lock)
SCAN_RESULT_LIST_LIMIT = 1000  # maximal number of entries that can be displayed

SCAN_VALUE_TYPES = misc.build_simple_str_liststore([
    'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64',
    'number', 'bytearray', 'string'
])

LOCK_FLAG_TYPES = misc.build_simple_str_liststore(['=', '+', '-'])
from gi.repository import GObject, Gtk, GLib, Gio
import os, time, difflib, re, gettext, locale, sys

found_terminal = True
try:
    import pty
    from gi.repository import Vte
except (ImportError, Exception):
    found_terminal = False

ABS_PATH = os.path.abspath(__file__)
DIR_PATH = os.path.dirname(os.path.dirname(ABS_PATH)) + "/"

LOCALE_PATH = DIR_PATH + "locale"
DOMAIN = "cinnamon-installer"
locale.bindtextdomain(DOMAIN, LOCALE_PATH)
locale.bind_textdomain_codeset(DOMAIN, "UTF-8")
gettext.bindtextdomain(DOMAIN, LOCALE_PATH)
gettext.bind_textdomain_codeset(DOMAIN, "UTF-8")
gettext.textdomain(DOMAIN)
_ = gettext.gettext

CI_STATUS = {
    "RESOLVING_DEPENDENCIES": "Resolving dep",
    "SETTING_UP": "Setting up",
    "LOADING_CACHE": "Loading cache",
    "AUTHENTICATING": "authenticating",
    "DOWNLOADING": "Downloading",
    "DOWNLOADING_REPO": "Downloading repo",
    "RUNNING": "Running",
    "COMMITTING": "Committing",
def isUnicode(s):
    if sys.version_info[0] < 3:
        return (type(s) == unicode)
    else:
        return (type(s) == str)

def gtkToUnicode(s):
    "convert string returned by GTK to unicode string"
    if sys.version_info[0] < 3:
        return s.decode("utf-8")
    else:
        return s


# translation
APP_NAME = 'file-search'
LOCALE_PATH = os.path.join(resourceDir, 'locale')
t = translation(APP_NAME, LOCALE_PATH, fallback=True)

if hasattr(t, "ugettext"):
    _ = t.ugettext
    ngettext = t.ungettext
else:
    _ = t.gettext
    ngettext = t.ngettext

# set gettext domain for GtkBuilder
locale.bindtextdomain(APP_NAME, LOCALE_PATH)

Example #37
0
    def __init__(self):
        sys.excepthook = self.excepthook
        INIPATH = None
        usage = "usage: %prog [options] myfile.ui"
        parser = OptionParser(usage=usage)
        parser.disable_interspersed_args()
        parser.add_options(options)
        # remove [-ini filepath] that linuxcnc adds if being launched as a screen
        # keep a reference of that path
        for i in range(len(sys.argv)):
            if sys.argv[i] =='-ini':
                # delete -ini
                del sys.argv[i]
                # pop out the ini path
                INIPATH = sys.argv.pop(i)
                break

        (opts, args) = parser.parse_args()

        # initialize QApp so we can pop up dialogs now. 
        self.app = QtWidgets.QApplication(sys.argv)

        # we import here so that the QApp is initialized before
        # the Notify library is loaded because it uses DBusQtMainLoop
        # DBusQtMainLoop must be initialized after to work properly
        from qtvcp import qt_makepins, qt_makegui

        # ToDo: pass specific log levels as an argument, or use an INI setting
        if not opts.debug:
            # Log level defaults to DEBUG, so set higher if not debug
            logger.setGlobalLevel(logger.ERROR)

        # a specific path has been set to load from or...
        # no path set but -ini is present: default qtvcp screen...or
        # oops error
        if args:
            basepath=args[0]
        elif INIPATH:
            basepath = "qt_cnc"
        else:
            log.error('Error in path')
            sys.exit()

        # set paths using basename
        PATH = Paths(basepath, bool(INIPATH))

        #################
        # Screen specific
        #################
        if INIPATH:
            log.debug('Building A Linuxcnc Main Screen')
            import linuxcnc
            # internationalization and localization
            import locale, gettext
            # pull info from the INI file
            self.inifile = linuxcnc.ini(INIPATH)
            self.inipath = INIPATH
            # screens require more path info
            PATH.add_screen_paths()

            # International translation
            locale.setlocale(locale.LC_ALL, '')
            locale.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR)
            gettext.install(PATH.DOMAIN, localedir=PATH.LOCALEDIR, unicode=True)
            gettext.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR)

            # if no handler file specified, use stock test one
            if not opts.usermod:
                log.info('No handler file specified on command line')
                target =  os.path.join(PATH.CONFIGPATH, '%s_handler.py' % PATH.BASENAME)
                source =  os.path.join(PATH.SCREENDIR, 'tester/tester_handler.py')
                if PATH.HANDLER is None:
                    message = ("""
Qtvcp encountered an error; No handler file was found.
Would you like to copy a basic handler file into your config folder?
This handker file will allow display of your screen and basic keyboard jogging.

The new handlerfile's path will be:
%s

Pressing cancel will close linuxcnc.""" % target)
                    rtn = QtWidgets.QMessageBox.critical(None, "QTVCP Error", message,QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
                    if rtn == QtWidgets.QMessageBox.Ok:
                        try:
                            shutil.copy(source, target)
                        except IOError as e:
                            log.critical("Unable to copy handler file. %s" % e)
                            sys.exit(0)
                        except:
                            log.critical("Unexpected error copying handler file:", sys.exc_info())
                            sys.exit(0)
                        opts.usermod = PATH.HANDLER = target
                    else:
                        log.critical('No handler file found or specified. User requested stopping')
                else:
                    opts.usermod = PATH.HANDLER

            # specify the HAL component name if missing
            if opts.component is None:
                log.info('No HAL component base name specified on command line using: {}'.format(PATH.BASENAME))
                opts.component = PATH.BASENAME

        #################
        # VCP specific
        #################
        else:
            log.debug('Building A VCP Panel')
            # if no handler file specified, use stock test one
            if not opts.usermod:
                log.info('No handler file specified - using {}'.format(PATH.HANDLER))
                opts.usermod = PATH.HANDLER

            # specify the HAL component name if missing
            if opts.component is None:
                log.info('No HAL component base name specified - using: {}'.format(PATH.BASENAME))
                opts.component = PATH.BASENAME

        ##############
        # Build ui
        ##############

        #if there was no component name specified use the xml file name
        if opts.component is None:
            opts.component = PATH.BASENAME

        # initialize HAL
        try:
            self.halcomp = hal.component(opts.component)
        except:
            log.critical("Asking for a HAL component using a name that already exists?")
            sys.exit(0)

        # initialize the window
        window = qt_makegui.MyWindow(self.halcomp, PATH)
 
        # load optional user handler file
        if opts.usermod:
            log.debug('Loading the handler file')
            window.load_extension(opts.usermod)
            # do any class patching now
            if "class_patch__" in dir(window.handler_instance):
                window.handler_instance.class_patch__()
            # add filter to catch keyboard events
            log.debug('Adding the key events filter')
            myFilter = qt_makegui.MyEventFilter(window)
            self.app.installEventFilter(myFilter)

        # actually build the widgets
        window.instance()

        # make QT widget HAL pins
        self.panel = qt_makepins.QTPanel(self.halcomp, PATH, window, opts.debug)

        # call handler file's initialized function
        if opts.usermod:
            if "initialized__" in dir(window.handler_instance):
                log.debug('''Calling the handler file's initialized__ function''')
                window.handler_instance.initialized__()
        # All Widgets should be added now - synch them to linuxcnc
        STATUS.forced_update()

        # User components are set up so report that we are ready
        log.debug('Set HAL ready')
        self.halcomp.ready()

        # embed us into an X11 window (such as AXIS)
        if opts.parent:
            window = xembed.reparent_qt_to_x11(window, opts.parent)
            forward = os.environ.get('AXIS_FORWARD_EVENTS_TO', None)
            log.critical('Forwarding events to AXIS is not well tested yet')
            if forward:
                xembed.XEmbedFowarding(window, forward)

        # push the window id for embedment into an external program
        if opts.push_XID:
            wid = int(window.winId())
            print >> sys.stdout,wid
            sys.stdout.flush()

        # for window resize and or position options
        if "+" in opts.geometry:
            log.debug('-g option: moving window')
            try:
                j =  opts.geometry.partition("+")
                pos = j[2].partition("+")
                window.move( int(pos[0]), int(pos[2]) )
            except:
                log.critical("With window position data")
                parser.print_usage()
                sys.exit(1)
        if "x" in opts.geometry:
            log.debug('-g option: resizing')
            try:
                if "+" in opts.geometry:
                    j =  opts.geometry.partition("+")
                    t = j[0].partition("x")
                else:
                    t = window_geometry.partition("x")
                window.resize( int(t[0]), int(t[2]) )
            except:
                log.critical("With window resize data")
                parser.print_usage()
                sys.exit(1)

        # always on top
        if opts.always_top:
            window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        # theme (styles in QT speak) specify a qss file
        if opts.theme:
            window.apply_styles(opts.theme)
        # appy qss file or default theme
        else:
            window.apply_styles()

        # title
        if INIPATH:
            title = 'QTvcp-Screen-%s'% opts.component
        else:
            title = 'QTvcp-Panel-%s'% opts.component
        window.setWindowTitle(title)

        log.debug('Show window')
        # maximize
        if opts.maximum:
            window.showMaximized()
        # fullscreen
        elif opts.fullscreen:
            window.showFullScreen()
        else:
            self.panel.set_preference_geometry()
        window.show()
        if INIPATH:
            self.postgui()

        # catch control c and terminate signals
        signal.signal(signal.SIGTERM, self.shutdown)
        signal.signal(signal.SIGINT, self.shutdown)

        # start loop
        self.app.exec_()

        # now shut it all down
        self.shutdown()
Example #38
0
APP = 'usbguard_gnome'
WHERE_AM_I = abspath(dirname(__file__))
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('New device window using locale directory: {}'.format(LOCALE_DIR))


class USBGuardNewDeviceWindow(Gtk.ApplicationWindow):
    def __init__(self, app, device):
        """ New device window init

        app: application object
        device: Device object
        """

        Gtk.ApplicationWindow.__init__(
Example #39
0
from gi.repository import Gdk, Gio, Gtk, GLib, Handy, GObject, WebKit2, Pango
from os import path, makedirs, listdir, environ
import locale
import json
import threading
from copy import deepcopy
from .fsync import async_function
from time import sleep
from urllib.request import urlretrieve, urlopen

#Init Webkit and Handy libs
Handy.init()
WebKit2.WebView()

locale.bindtextdomain(
    'fontdownloader',
    path.join(path.dirname(__file__).split('fontdownloader')[0], 'locale'))
locale.textdomain('fontdownloader')

webfontsData = json.load(
    open(
        path.join(
            path.dirname(__file__).split('fontdownloader')[0],
            'fontdownloader/fontdownloader/webfonts.json'), 'r'))

SAMPLE_STRING = Pango.language_get_default().get_sample_string()


#Here we import the font-box template which is used for the fonts' boxes
@Gtk.Template(resource_path='/org/gustavoperedo/FontDownloader/font-box.ui')
class FontBox(Gtk.Box):
    def __init__(self, datadir=None, logdir=None):
        DistUpgradeView.__init__(self)
        self.logdir = logdir
        if not datadir or datadir == '.':
            localedir=os.path.join(os.getcwd(),"mo")
            gladedir=os.getcwd()
        else:
            localedir="/usr/share/locale/"
            gladedir=os.path.join(datadir, "gtkbuilder")

        # check if we have a display etc
        Gtk.init_check(sys.argv)

        try:
            locale.bindtextdomain("ubuntu-release-upgrader",localedir)
            gettext.textdomain("ubuntu-release-upgrader")
        except Exception as e:
            logging.warning("Error setting locales (%s)" % e)

        SimpleGtkbuilderApp.__init__(self,
                                     gladedir+"/DistUpgrade.ui",
                                     "ubuntu-release-upgrader")

        icons = Gtk.IconTheme.get_default()
        try:
            self.window_main.set_default_icon(icons.load_icon("system-software-update", 32, 0))
        except GObject.GError as e:
            logging.debug("error setting default icon, ignoring (%s)" % e)
            pass

        # terminal stuff
        self.create_terminal()

        self.prev_step = 0 # keep a record of the latest step
        # we don't use this currently
        #self.window_main.set_keep_above(True)
        self.icontheme = Gtk.IconTheme.get_default()
        self._webkit_view = None
        self.window_main.realize()
        self.window_main.get_window().set_functions(Gdk.WMFunction.MOVE)
        self._opCacheProgress = GtkOpProgress(self.progressbar_cache)
        self._acquireProgress = GtkAcquireProgressAdapter(self)
        self._cdromProgress = GtkCdromProgressAdapter(self)
        self._installProgress = GtkInstallProgressAdapter(self)
        # details dialog
        self.details_list = Gtk.TreeStore(GObject.TYPE_STRING)
        column = Gtk.TreeViewColumn("")
        render = Gtk.CellRendererText()
        column.pack_start(render, True)
        column.add_attribute(render, "markup", 0)
        self.treeview_details.append_column(column)
        self.details_list.set_sort_column_id(0, Gtk.SortType.ASCENDING)
        self.treeview_details.set_model(self.details_list)
        # lp: #1072460
        self.dialog_changes.set_resizable(False)
        def _activated(w):
            # the *current* expanded state which will change after the signal
            expanded = self.expander_details.get_expanded()
            self.dialog_changes.set_resizable(not expanded)
        self.expander_details.connect("activate", _activated)
        # FIXME: portme
        # Use italic style in the status labels
        #attrlist=Pango.AttrList()
        #attr = Pango.AttrStyle(Pango.Style.ITALIC, 0, -1)
        #attr = Pango.AttrScale(Pango.SCALE_SMALL, 0, -1)
        #attrlist.insert(attr)
        #self.label_status.set_property("attributes", attrlist)
        # reasonable fault handler
        sys.excepthook = self._handleException
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

from gi.repository import Gtk  # pylint: disable=E0611
from operator import itemgetter
from accomplishments_viewer_lib.helpers import get_builder

import gettext
import locale
from accomplishments.util.paths import locale_dir
locale.bindtextdomain('accomplishments-viewer', locale_dir)
gettext.bindtextdomain('accomplishments-viewer', locale_dir)
locale.textdomain('accomplishments-viewer')


class EditExtrainfoDialog(Gtk.Dialog):
    __gtype_name__ = "EditExtrainfoDialog"

    def __new__(cls):
        """Special static method that's automatically called by Python when
        constructing a new instance of this class.

        Returns a fully instantiated EditExtrainfoDialog object.
        """
        builder = get_builder('EditExtrainfoDialog')
        new_object = builder.get_object('edit_extrainfo_dialog')
Example #42
0
    json.dumps = json.write
    json.loads = json.read

    def dump(obj, fp, **kw):
        fp.write(json.dumps(obj))

    def load(fp, **kw):
        return json.loads(fp.read())

    json.dump = dump
    json.load = load

# Initialize gettext
try:
    if hasattr(locale, "bindtextdomain"):
        locale.bindtextdomain("deluge", pkg_resources.resource_filename("deluge", "i18n"))
    if hasattr(locale, "textdomain"):
        locale.textdomain("deluge")
    gettext.install("deluge", pkg_resources.resource_filename("deluge", "i18n"), unicode=True)
except Exception, e:
    log.error("Unable to initialize gettext/locale!")
    log.exception(e)
    import __builtin__
    __builtin__.__dict__["_"] = lambda x: x

LT_TORRENT_STATE = {
    "Queued": 0,
    "Checking": 1,
    "Downloading Metadata": 2,
    "Downloading": 3,
    "Finished": 4,
Example #43
0
def main():
    """
    Start the Safe Eyes.
    """
    system_locale = gettext.translation(
        'safeeyes',
        localedir=Utility.LOCALE_PATH,
        languages=[Utility.system_locale(), 'en_US'],
        fallback=True)
    system_locale.install()
    # locale.bindtextdomain is required for Glade files
    # gettext.bindtextdomain(gettext.textdomain(), Utility.LOCALE_PATH)
    locale.bindtextdomain('safeeyes', Utility.LOCALE_PATH)

    parser = argparse.ArgumentParser(prog='safeeyes',
                                     description=_('description'))
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-a',
                       '--about',
                       help=_('show the about dialog'),
                       action='store_true')
    group.add_argument(
        '-d',
        '--disable',
        help=_('disable the currently running safeeyes instance'),
        action='store_true')
    group.add_argument(
        '-e',
        '--enable',
        help=_('enable the currently running safeeyes instance'),
        action='store_true')
    group.add_argument('-q',
                       '--quit',
                       help=_('quit the running safeeyes instance and exit'),
                       action='store_true')
    group.add_argument('-s',
                       '--settings',
                       help=_('show the settings dialog'),
                       action='store_true')
    group.add_argument('-t',
                       '--take-break',
                       help=_('Take a break now').lower(),
                       action='store_true')
    parser.add_argument('--debug',
                        help=_('start safeeyes in debug mode'),
                        action='store_true')
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s ' + SAFE_EYES_VERSION)
    args = parser.parse_args()

    # Initialize the logging
    Utility.intialize_logging(args.debug)
    config = Config()

    if __running():
        logging.info("Safe Eyes is already running")
        rpc_client = RPCClient(config.get('rpc_port'))
        if args.about:
            rpc_client.show_about()
        elif args.disable:
            rpc_client.disable_safeeyes()
        elif args.enable:
            rpc_client.enable_safeeyes()
        elif args.settings:
            rpc_client.show_settings()
        elif args.take_break:
            rpc_client.take_break()
        elif args.quit:
            rpc_client.quit()
        else:
            # Default behavior is opening settings
            rpc_client.show_settings()
        sys.exit(0)
    elif not args.quit:
        logging.info("Starting Safe Eyes")
        safeeyes = SafeEyes(system_locale, config)
        safeeyes.start()
        Timer(1.0, lambda: __evaluate_arguments(args, safeeyes)).start()
        Gtk.main()
Example #44
0
import os
import gettext
import locale

from . import gv

# translate strings in python files
localedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'locale')
gettext.install(gv.domain, localedir)

# translate strings in glade files
try:
    locale.bindtextdomain(gv.domain, localedir)
except AttributeError as ae:
    # we get this on windows
    pass
Example #45
0
def ApplyTranslation():
    """Function dealing with translations and locales.

    We try to autodetect the language and fix the locale.

    If something goes wrong we fall back to no translation.

    This function also try to find translation files in the project path first:
    $(PROJECT_PATH)/mo/$(LANG)/LC_MESSAGES/nicotine.mo

    If no translations are found we fall back to the system path for locates:
    GNU/Linux: /usr/share/locale/$(LANG)/LC_MESSAGES
    Windows: %PYTHONHOME%\\share\\locale\\$(LANG)\\LC_MESSAGES

    Note: To the best of my knowledge when we are in a python venv
    falling back to the system path does not work."""

    # Package name for gettext
    PACKAGE = 'nicotine'

    # Local path where to find translation (mo) files
    LOCAL_MO_PATH = 'mo'

    # Python 2.7.X is build via Visual Studio 2008 on Windows:
    # https://stackoverflow.com/questions/32037573/load-gtk-glade-translations-in-windows-using-python-pygobject
    # https://docs.python.org/devguide/setup.html#windows
    # The locales table for VS2008 can be found here:
    # https://msdn.microsoft.com/en-us/library/cdax410z(v=vs.90).aspx
    # https://msdn.microsoft.com/en-us/library/39cwe7zf(v=vs.90).aspx
    def _build_localename_win(localetuple):
        """ Builds a locale code from the given tuple (language code, encoding).
            No aliasing or normalizing takes place."""

        language, encoding = localetuple

        if language is None:
            language = 'C'

        if encoding is None:
            return language
        else:
            return language + '.' + encoding

    # Locales handling
    if win32:

        # On windows python can get a normalize tuple (language code, encoding)
        locale_win = locale.getdefaultlocale()

        # Build a locale name compatible with gettext
        locale_win_gettext = _build_localename_win(locale_win)

        # Fix environnement variables
        os.environ['LC_ALL'] = locale_win_gettext

    else:
        # Unix locales handling: We let the system handle the locales
        try:
            locale.setlocale(locale.LC_ALL, '')
        except Exception as e:
            print("Error while attempting to set locale: %s" % e)

    # Gettext handling
    if gettext.find(PACKAGE, localedir=LOCAL_MO_PATH) is None:

        # Locales are not in the current dir
        # We let gettext handle the situation: if if found them in the system dir
        # the app will be trnaslated, if not it will be untranslated.
        gettext.install(PACKAGE)

    else:

        # Locales are in the current dir: install them
        if win32:

            # On windows we use libintl-8.dll: the core DLL of GNU gettext-runtime on Windows
            import ctypes

            libintl = ctypes.cdll.LoadLibrary("libintl-8.dll")

            libintl.bindtextdomain(PACKAGE, LOCAL_MO_PATH)
            libintl.bind_textdomain_codeset(PACKAGE, "UTF-8")

        else:
            locale.bindtextdomain(PACKAGE, LOCAL_MO_PATH)
            gettext.bindtextdomain(PACKAGE, LOCAL_MO_PATH)

        tr = gettext.translation(PACKAGE, localedir=LOCAL_MO_PATH)
        tr.install()

    gettext.textdomain(PACKAGE)
Example #46
0
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
""" Initializes support for translations """

import locale
import gettext

# Fallback to LANG C if unsupported locale
try:
    locale.setlocale(locale.LC_ALL, '')
except:
    locale.setlocale(locale.LC_ALL, 'C')

GETTEXT_DOMAIN = 'gtg'
LOCALE_PATH = gettext.bindtextdomain(GETTEXT_DOMAIN)

gettext.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH)
locale.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH)
gettext.textdomain(GETTEXT_DOMAIN)
locale.textdomain(GETTEXT_DOMAIN)

translation = gettext.translation(GETTEXT_DOMAIN, LOCALE_PATH, fallback=True)

_ = translation.gettext
ngettext = translation.ngettext
Example #47
0
    else:
        if not IS_LINUX:
            if IS_DARWIN:
                s_path = f"{GTK_PATH + '/' + UI_RESOURCES_PATH if GTK_PATH else UI_RESOURCES_PATH}mac_style.css"
            else:
                s_path = f"{UI_RESOURCES_PATH}win_style.css"

            style_provider = Gtk.CssProvider()
            style_provider.load_from_path(s_path)
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), style_provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

if IS_LINUX:
    if UI_RESOURCES_PATH == BASE_PATH:
        locale.bindtextdomain(TEXT_DOMAIN, LANG_PATH)
    # Init notify
    try:
        gi.require_version("Notify", "0.7")
        from gi.repository import Notify
    except ImportError:
        pass
    else:
        NOTIFY_IS_INIT = Notify.init("DemonEditor")
elif IS_DARWIN:
    import gettext

    if GTK_PATH:
        LANG_PATH = GTK_PATH + "/share/locale"
    gettext.bindtextdomain(TEXT_DOMAIN, LANG_PATH)
    # For launching from the bundle.
Example #48
0
    ngettext = t.ngettext

if ui.win32:
    try:
        # Workaround for bug 650
        from gtk.glade import bindtextdomain
        bindtextdomain(textdomain, locale_dir)
        del bindtextdomain
    except:
        # Ignore for QML UI or missing glade module
        pass
del t

# Set up textdomain for gtk.Builder (this accesses the C library functions)
if hasattr(locale, 'bindtextdomain'):
    locale.bindtextdomain(textdomain, locale_dir)

del locale_dir

# Set up socket timeouts to fix bug 174
SOCKET_TIMEOUT = 60
import socket
socket.setdefaulttimeout(SOCKET_TIMEOUT)
del socket
del SOCKET_TIMEOUT

# Variables reserved for GUI-specific use (will be set accordingly)
ui_folders = []
credits_file = None
icon_file = None
images_folder = None
Example #49
0
import locale
import logging
import os.path
import re
import subprocess
import sys

from gi.repository import Gtk, Gdk, Notify

import dnfdaemon.client

import yumex.config as config

LOCALE_DIR = os.path.join(sys.prefix, 'share', 'locale')
locale.setlocale(locale.LC_ALL, '')
locale.bindtextdomain('yumex-dnf', LOCALE_DIR)
gettext.bindtextdomain('yumex-dnf', LOCALE_DIR)
gettext.textdomain('yumex-dnf')
_ = gettext.gettext
P_ = gettext.ngettext

logger = logging.getLogger('yumex.misc')


class QueueEmptyError(Exception):
    def __init__(self):
        super(QueueEmptyError, self).__init__()


class TransactionBuildError(Exception):
    def __init__(self, msgs):
Example #50
0
build_proc = None
make_depends = set()
base_devel = ('autoconf', 'automake', 'binutils', 'bison', 'fakeroot', 'file',
              'findutils', 'flex', 'gawk', 'gcc', 'gettext', 'grep', 'groff',
              'gzip', 'libtool', 'm4', 'make', 'patch', 'pkg-config', 'sed',
              'sudo', 'texinfo', 'util-linux', 'which')
build_depends = set()
handle = None
syncdbs = None
localdb = None
colors_regexp = re.compile('\\033\[(\d;)?\d*m')

# i18n
import gettext
import locale
locale.bindtextdomain('pamac', '/usr/share/locale')
gettext.bindtextdomain('pamac', '/usr/share/locale')
gettext.textdomain('pamac')
_ = gettext.gettext

interface = Gtk.Builder()
interface.set_translation_domain('pamac')

interface.add_from_file('/usr/share/pamac/gui/dialogs.ui')
ErrorDialog = interface.get_object('ErrorDialog')
WarningDialog = interface.get_object('WarningDialog')
#InfoDialog = interface.get_object('InfoDialog')
QuestionDialog = interface.get_object('QuestionDialog')
ConfDialog = interface.get_object('ConfDialog')
transaction_sum = interface.get_object('transaction_sum')
sum_top_label = interface.get_object('sum_top_label')
Example #51
0
    def __init_first_instance(self):
        """
        Initialize the primary locale from whatever might be
        available. We only do this once, and the resulting
        GrampsLocale is returned by default.
        """
        global _hdlr
        _hdlr = logging.StreamHandler()
        _hdlr.setFormatter(logging.Formatter(fmt="%(name)s.%(levelname)s: %(message)s"))
        LOG.addHandler(_hdlr)

        #Now that we have a logger set up we can issue the icu error if needed.
        if not HAVE_ICU:
            LOG.warning(_icu_err)

        # Even the first instance can be overridden by passing lang
        # and languages to the constructor. If it isn't (which is the
        # expected behavior), do platform-specific setup:
        if not (self.lang and self.language):
            if sys.platform == 'darwin':
                from . import maclocale
                maclocale.mac_setup_localization(self)
            elif sys.platform == 'win32':
                self._win_init_environment()
            else:
                self._init_from_environment()
        else:
            self.numeric = self.currency = self.calendar = self.collation = self.lang

        if not self.lang:
            self.lang = 'en_US.UTF-8'
        if not self.language:
            self.language.append('en')
        if not self.localedir and not self.lang.startswith('en'):
            LOG.warning("No translations for %s were found, setting localization to U.S. English", self.localedomain)
            self.lang = 'en_US.UTF-8'
            self.language = ['en']

#Next, we need to know what is the encoding from the native
#environment. This is used by python standard library funcions which
#localize their output, e.g. time.strftime(). NB: encoding is a class variable.
        if not self.encoding:
            self.encoding = (locale.getpreferredencoding()
                             or sys.getdefaultencoding())
        LOG.debug("Setting encoding to %s", self.encoding)

        # Make sure that self.lang and self.language are reflected
        # back into the environment for Gtk to use when its
        # initialized. If self.lang isn't 'C', make sure that it has a
        # 'UTF-8' suffix, because that's all that GtkBuilder can
        # digest.

        # Gtk+ has an 'en' po, but we don't. This is worked-around for
        # our GrampsTranslation class but that isn't used to retrieve
        # translations in GtkBuilder (glade), a direct call to libintl
        # (gettext) is. If 'en' is in the translation list it gets
        # skipped in favor of the next language, which can cause
        # inappropriate translations of strings in glade/ui files. To
        # prevent this, if 'en' is in self.language it's the last
        # entry:

        if 'en' in self.language:
            self.language = self.language[:self.language.index('en') + 1]

        # Linux note: You'll get unsupported locale errors from Gtk
        # and untranslated strings if the requisite UTF-8 locale isn't
        # installed. This is particularly a problem on Debian and
        # Debian-derived distributions which by default don't install
        # a lot of locales.
        lang = locale.normalize(self.language[0] if self.language[0] else 'C')
        check_lang = lang.split('.')
        if not check_lang[0]  in ('C', 'en'):
            if len(check_lang) < 2  or check_lang[1] not in ("utf-8", "UTF-8"):
                lang = '.'.join((check_lang[0], 'UTF-8'))

        os.environ["LANG"] = lang
        #We need to convert 'en' and 'en_US' to 'C' to avoid confusing
        #GtkBuilder when it's retrieving strings from our Glade files
        #since we have neither an en.po nor an en_US.po.

        os.environ["LANGUAGE"] = ':'.join(self.language)

        # GtkBuilder uses GLib's g_dgettext wrapper, which oddly is bound
        # with locale instead of gettext. Win32 doesn't support bindtextdomain.
        if self.localedir:
            if not sys.platform == 'win32':
                locale.bindtextdomain(self.localedomain, self.localedir)
            else:
                self._win_bindtextdomain(self.localedomain.encode('utf-8'),
                                         self.localedir.encode('utf-8'))
Example #52
0
    def __init__(self, dbstate, user, options_class, name, callback=None):
        uistate = user.uistate

        self.label = _('Sources Index')
        self.base = os.path.dirname(__file__)

        ManagedWindow.__init__(self, uistate,[], self.__class__)
        self.set_window(Gtk.Window(),Gtk.Label(),'')

        tool.Tool.__init__(self, dbstate, options_class, name)

        glade_file = os.path.join(USER_PLUGINS, "SourceIndex", "birth.glade")

        if gramps.gen.constfunc.lin():
            import locale
            locale.setlocale(locale.LC_ALL, '')
            # This is needed to make gtk.Builder work by specifying the
            # translations directory
            locale.bindtextdomain("addon", self.base + "/locale")

            self.glade = Gtk.Builder()
            self.glade.set_translation_domain("addon")

            #self.glade = GladeWidgetsWrapper(glade_file, self)
            self.glade.add_from_file(glade_file)

            from gi.repository import GObject
            GObject.GObject.__init__(self.glade)

            window = self.glade.get_object('edit_birth')

            self.set_window(window, self.glade.get_object('title'), self.label)

            #self.wit_button = self.glade.get_object('add_wit')
            self.ok_button = self.glade.get_object('ok')
            self.quit_button = self.glade.get_object('cancel')

        else:

            # Glade class from gui/glade.py and gui/managedwindow.py
            self.glade = Glade(glade_file)
            #self.glade = GladeWidgetsWrapper(glade_file, self)

            self.top = Glade()
            window = self.top.toplevel
            self.set_window(window, None, glade_file)

            #self.wit_button = self.top.get_object('add_wit')
            self.ok_button = self.top.get_object('ok')
            self.quit_button = self.top.get_object('cancel')

        #self.wit_button.connect('clicked', GtkHandlers.on_witness_clicked)
        self.ok_button.connect('clicked', self.close)
        self.quit_button.connect('clicked', self.close)

        #GObject.__init__() takes exactly 0 arguments
        #self.text = Gtk.EntryBuffer('Gtk.Entry._get...', 5)

        # tests
        path = os.path.join(USER_PLUGINS, 'SourceIndex')
        self.rinfo = 'Library of usercity'
        callnumber = 'BX42_xzertra58364' # inherited or seizure
        source_handle = '_123456789' # or call the source title
        citation_handle = '_987654321'  # or call any id
        self.avol = 'Page 105 n°56'
        self.aname = 'Civil book (Birth 1650)'
        separator = 'ↄ'
        name = self.rinfo + separator + callnumber +  separator \
        + source_handle + separator + citation_handle + separator \
        + self.avol + separator + self.aname + '.xml'
        filename = os.path.join(path, name)
        self.write_xml(
            filename,
            'B0001',
            'DATE',
            'PRÉNOM'
            )

        #self._setup_fields()

        self.window.show()

        self.parse_xml(filename)
Example #53
0
    def display(self):

        if lin():
            import locale, os
            locale.setlocale(locale.LC_ALL, '')
            # This is needed to make gtk.Builder work by specifying the
            # translations directory
            base = os.path.dirname(__file__)
            locale.bindtextdomain("addon", base + "/locale")

            self.glade = Gtk.Builder()
            self.glade.set_translation_domain("addon")

            path = base + "/changenames.glade"
            self.glade.add_from_file(path)

            from gi.repository import GObject
            GObject.GObject.__init__(self.glade)

            self.top = self.glade.get_object('changenames')

            self.glade.connect_signals({
                "destroy_passed_object" : self.close,
                "on_ok_clicked" : self.on_ok_clicked,
                "on_help_clicked" : self.on_help_clicked,
                "on_edit_clicked" : self.on_edit_clicked,
                "on_delete_event"   : self.close,
                })

            self.list = self.glade.get_object("list")
            self.set_window(self.top, self.glade.get_object('title'), self.label)

        else:
            self.top = Glade("changenames.glade")

            window = self.top.toplevel
            self.top.connect_signals({
                "destroy_passed_object" : self.close,
                "on_ok_clicked" : self.on_ok_clicked,
                "on_help_clicked" : self.on_help_clicked,
                "on_edit_clicked" : self.on_edit_clicked,
                "on_delete_event"   : self.close,
                })

            self.list = self.top.get_object("list")
            self.set_window(window,self.top.get_object('title'),self.label)

        # selected, original name, changed, count
        self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING,
                                   GObject.TYPE_STRING, GObject.TYPE_INT)
        self.handles = {}

        r = Gtk.CellRendererToggle()
        r.connect('toggled',self.toggled)
        c = Gtk.TreeViewColumn(_('Select'),r,active=0)
        self.list.append_column(c)

        c = Gtk.TreeViewColumn(_('Original Name'),
                               Gtk.CellRendererText(),text=1)
        self.list.append_column(c)

        c = Gtk.TreeViewColumn(_('Capitalization Change'),
                               Gtk.CellRendererText(),text=2)
        self.list.append_column(c)

        c = Gtk.TreeViewColumn(_('Affected Names'),
                               Gtk.CellRendererText(),text=3)
        self.list.append_column(c)

        self.list.set_model(self.model)

        self.iter_list = []
        self.progress.set_pass(_('Building display'),len(self.name_list))
        for name, count in self.name_list:
            handle = self.model.append()
            self.model.set_value(handle,0, False)
            self.model.set_value(handle,1, name)
            namecap = capitalize(name)
            self.model.set_value(handle,2, namecap)
            self.model.set_value(handle,3, count)
            self.iter_list.append(handle)
            self.progress.step()
        self.progress.close()

        self.show()
Example #54
0
    os.environ['LANG'] = user_locale

try:
    if not os.path.exists(locale_dir):
        raise RuntimeError('translations not installed')
    t = gettext.translation('bleachbit', locale_dir)
    _ = t.ugettext
except:

    def _(msg):
        """Dummy replacement for ugettext"""
        return msg


try:
    locale.bindtextdomain('bleachbit', locale_dir)
except AttributeError:
    if sys.platform.startswith('win'):
        try:
            # We're on Windows; try and use libintl-8.dll instead
            import ctypes
            libintl = ctypes.cdll.LoadLibrary('libintl-8.dll')
        except OSError:
            # libintl-8.dll isn't available; give up
            pass
        else:
            # bindtextdomain can not handle Unicode
            if isinstance(locale_dir, unicode):
                path = locale_dir.encode('utf-8')
            else:
                path = locale_dir
Example #55
0
    LANG = get_default_lang()
    if os.name == 'nt':
        # Set the env var on Windows because gettext.find() uses it to
        # find the translation
        # Use LANGUAGE instead of LANG, LANG sets LC_ALL and thus
        # doesn't retain other region settings like LC_TIME

        # See https://gitlab.gnome.org/GNOME/pygobject/-/issues/442
        LANG = 'en'
        os.environ['LANGUAGE'] = LANG
except Exception as error:
    print('Failed to determine default language', file=sys.stderr)
    import traceback
    traceback.print_exc()

# Search for the translation in all locale dirs
for dir_ in iter_locale_dirs():
    try:
        _translation = gettext.translation(DOMAIN, dir_)
        _ = _translation.gettext
        if hasattr(locale, 'bindtextdomain'):
            locale.bindtextdomain(DOMAIN, dir_)  # type: ignore
    except OSError:
        continue
    else:
        break
else:
    print('No translations found', file=sys.stderr)
    print('Dirs searched: %s' % get_locale_dirs(), file=sys.stderr)
    _ = _translation.gettext
Example #56
0
from gi.repository import Gio  # noqa

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk  # noqa

gi.require_version('Secret', '1')
from gi.repository import Secret  # noqa

gi.require_version('Notify', '0.7')
from gi.repository import Notify  # noqa

gi.require_version('Wnck', '3.0')
from gi.repository import Wnck  # noqa

_ = locale.gettext
locale.bindtextdomain("gnome-gmail", "/usr/share/locale")
locale.textdomain("gnome-gmail")
try:
    locale.setlocale(locale.LC_ALL, '')
except locale.Error:
    locale.setlocale(locale.LC_CTYPE, "en_US.UTF-8")

try:
    environ = os.environ['XDG_CURRENT_DESKTOP']
    environ = environ.split(':')[-1]
except:
    environ = 'GNOME'

config = None
oauthport = 27478
Example #57
0
    # must be done before importing any translated python modules
    # (to get global strings translated, especially brushsettings.py)
    import gettext
    import locale
    if sys.platform == 'win32':
        os.environ['LANG'] = locale.getdefaultlocale()[0]

    # Internationalization voodoo
    # https://bugzilla.gnome.org/show_bug.cgi?id=574520#c26
    #locale.setlocale(locale.LC_ALL, '')  #needed?
    logger.debug("getlocale(): %r", locale.getlocale())
    logger.debug("localepath: %r", localepath)
    logger.debug("localepath_brushlib: %r", localepath_brushlib)

    # Low-level bindtextdomain, required for GtkBuilder stuff.
    locale.bindtextdomain("mypaint", localepath)
    locale.bindtextdomain("libmypaint", localepath_brushlib)
    locale.textdomain("mypaint")

    # Python gettext module.
    # See http://docs.python.org/release/2.7/library/locale.html
    gettext.bindtextdomain("mypaint", localepath)
    gettext.bindtextdomain("libmypaint", localepath_brushlib)
    gettext.textdomain("mypaint")

    from gui import main
    version = main.MYPAINT_VERSION
    if version.endswith("+git"):
        try:
            version += _MYPAINT_BUILD_GIT_REVISION
        except NameError:
Example #58
0
#!/usr/bin/python3

import gettext
import os
import locale

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio

from plugins.easybuttons import easyButton
from plugins.execute import Execute

# i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale")
locale.bindtextdomain("mintmenu", "/usr/share/linuxmint/locale")
locale.textdomain("mintmenu")


class pluginclass(object):
    def __init__(self, mintMenuWin, toggleButton, de):

        self.mintMenuWin = mintMenuWin
        self.toggleButton = toggleButton
        self.de = de

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mintmenu")
        self.builder.add_from_file("/usr/share/linuxmint/mintmenu/system.ui")

        self.systemBtnHolder = self.builder.get_object("system_button_holder")
Example #59
0
from gi.repository import GLib
from gkraken.util.log import set_log_level
from gkraken.repository import KrakenRepository
from gkraken.di import INJECTOR
from gkraken.app import Application

WHERE_AM_I = abspath(dirname(__file__))
LOCALE_DIR = join(WHERE_AM_I, 'mo')

set_log_level(logging.INFO)

LOG = logging.getLogger(__name__)

# POSIX locale settings
locale.setlocale(locale.LC_ALL, locale.getlocale())
locale.bindtextdomain(APP_PACKAGE_NAME, LOCALE_DIR)

gettext.bindtextdomain(APP_PACKAGE_NAME, LOCALE_DIR)
gettext.textdomain(APP_PACKAGE_NAME)


def _cleanup() -> None:
    LOG.debug("cleanup")
    composite_disposable = INJECTOR.get(CompositeDisposable)
    composite_disposable.dispose()
    database = INJECTOR.get(SqliteDatabase)
    database.close()
    kraken_repository = INJECTOR.get(KrakenRepository)
    kraken_repository.cleanup()
    # futures.thread._threads_queues.clear()
Example #60
0
# file: share/when-wizard/modules/power-reboot.py
# -*- coding: utf-8 -*-
#
# Task plugin to reboot the system
# Copyright (c) 2015-2018 Francesco Garosi
# Released under the BSD License (see LICENSE file)
# NOTE: the consolekit package is a *mandatory* requirement

import locale
from plugin import TaskPlugin, PLUGIN_CONST, plugin_name

# setup i18n for both applet text and dialogs
locale.setlocale(locale.LC_ALL, locale.getlocale())
locale.bindtextdomain(APP_NAME, APP_LOCALE_FOLDER)
locale.textdomain(APP_NAME)
_ = locale.gettext

HELP = _("""\
This action reboots your Workstation, exactly in the same way as you would
do using the session shutdown menu. Your computer closes all applications and
flushes all data to disk to enable a clean restart, however be sure that your
data is saved (or at least auto-saved) before letting the computer restart.
""")

# see: http://superuser.com/a/533684/471608
# I also like `gdbus` as a command, it is probably more gnome-ish;
# the reason for the one-minute sleep is that the user may want to do
# something before shutting down, such as write an e-mail or send a message
# through another action
REBOOT_COMMAND = """\
sleep 60 && \