示例#1
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)
示例#2
0
def _init_languages():
    """
    Create the gettext languages.

    @return the gettext object

    """

    # Get locals but ignore the encoding (2 arg).
    default_lc, _ = locale.getdefaultlocale()
    if default_lc:
        languages = [default_lc]

    # Concat all languages (env + default locale),
    #  and here we have the languages and location of the translations
    languages += DEFAULT_LANGUAGES
    mo_location = LOCALE_DIR

    # Lets tell those details to gettext
    #  (nothing to change here for you)
    gettext.install(True, localedir=None, unicode=1)

    gettext.find(APP_NAME, mo_location)

    gettext.textdomain(APP_NAME)

    gettext.bind_textdomain_codeset(APP_NAME, "UTF-8")

    return gettext.translation(APP_NAME, mo_location, languages=languages, fallback=True)
示例#3
0
    def __init__(self):
        locale.setlocale(locale.LC_ALL, "")
        localedir = os.getenv("IBUS_LOCALEDIR")
        gettext.bindtextdomain("ibus-table", localedir)
        gettext.bind_textdomain_codeset("ibus-table", "UTF-8")

        self.__bus = IBus.Bus()
        self.__engine_name = None
        if _OPTIONS.engine_name:
            # If the engine name is specified on the command line, use that:
            self.__engine_name = _OPTIONS.engine_name
        else:
            # If the engine name is not specified on the command line,
            # try to get it from the environment. This is necessary
            # in gnome-shell on Fedora 18,19,20,... because the setup tool is
            # called without command line options there but the
            # environment variable IBUS_ENGINE_NAME is set:
            if 'IBUS_ENGINE_NAME' in os.environ:
                self.__engine_name = os.environ['IBUS_ENGINE_NAME']
            else:
                self.__run_message_dialog(
                    _("IBUS_ENGINE_NAME environment variable is not set."),
                    Gtk.MessageType.WARNING)
        if self.__engine_name is None:
            self.__run_message_dialog(
                _("Cannot determine the engine name. Please use the --engine-name option."),
                Gtk.MessageType.ERROR)
            sys.exit(1)
        short_engine_name = re.sub(
            r'^table:', '', self.__engine_name).replace(" ", "_")
        self.__gsettings = Gio.Settings(
            schema='org.freedesktop.ibus.engine.table',
            path='/org/freedesktop/ibus/engine/table/%s/' %short_engine_name)
        self.__gsettings.connect('changed', self.on_gsettings_value_changed)
示例#4
0
文件: g15locale.py 项目: FPar/gnome15
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
示例#5
0
    def __init__(self,engine):
        locale.setlocale(locale.LC_ALL, "")
        localedir = os.getenv("IBUS_LOCALEDIR")
        gettext.bindtextdomain("ibus-pinyin", localedir)
        gettext.bind_textdomain_codeset("ibus-pinyin", "UTF-8")

        self.__bus = ibus.Bus()
        self.__config = self.__bus.get_config()
        self.__builder = gtk.Builder()
        self.__builder.set_translation_domain("ibus-pinyin")
        self.__builder.add_from_file("ibus-pinyin-preferences.ui")
        self.__dialog = self.__builder.get_object("dialog")
        self.__init_pages()
        
        if engine == "pinyin":
            self.__config_namespace = "engine/Pinyin"
            self.__init_general()
            self.__init_pinyin()
            self.__init_fuzzy()
            self.__init_dictionary()
            self.__init_about()
        elif engine == "bopomofo":
            self.__config_namespace = "engine/Bopomofo"
            self.__init_general()
            self.__init_bopomofo()
            self.__init_fuzzy()
            self.__init_dictionary()
            self.__init_about()
            self.__convert_fuzzy_pinyin_to_bopomofo()
            
        else:
            print("Error: Unknown Engine")
            exit()
        
        self.__pages.set_current_page(0)
示例#6
0
文件: main.py 项目: XueWei/sunpinyin
 def __init_gettext(self):
     locale.setlocale(locale.LC_ALL, "")
     localedir = os.getenv("IBUS_LOCALEDIR")
     gettext.bindtextdomain(GETTEXT_PACKAGE, localedir)
     gettext.bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8")
     glade.bindtextdomain(GETTEXT_PACKAGE, localedir)
     glade.textdomain(GETTEXT_PACKAGE)
示例#7
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
示例#8
0
文件: gtcache.py 项目: nxmirrors/miro
def init():
    global _gtcache
    global codeset
    _gtcache = {}
    if not miro.plat.utils.locale_initialized():
        raise Exception, "locale not initialized"

    language = app.config.get(prefs.LANGUAGE)

    if language != "system":
        os.environ["LANGUAGE"] = language

    # try to set the locale to the platform default, but if that fails
    # log a message and set it to C.
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        print "gtcache.init: setlocale failed.  setting locale to 'C'"
        locale.setlocale(locale.LC_ALL, "C")

    # try to get the locale which might fail despite the above.  see bug #11783.
    try:
        codeset = locale.getlocale()[1]
    except ValueError:
        print "gtcache.init: getlocale failed.  setting locale to 'C'"
        locale.setlocale(locale.LC_ALL, "C")
        codeset = locale.getlocale()[1]

    if codeset is not None:
        codeset = codeset.lower()

    _gt.bindtextdomain("miro", app.config.get(prefs.GETTEXT_PATHNAME))
    _gt.textdomain("miro")
    _gt.bind_textdomain_codeset("miro", "UTF-8")
示例#9
0
	def __init__(self): 
		# Change this variable to your app name!
		#  The translation files will be under
		#  @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@[email protected]
		 
		# This is ok for maemo. Not sure in a regular desktop:
		APP_DIR = os.path.dirname(os.path.abspath(__file__) )
		LOCALE_DIR = os.path.join(APP_DIR, 'locale') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/
		 
		# Now we need to choose the language. We will provide a list, and gettext
		# will use the first translation available in the list
		#
		#  In maemo it is in the LANG environment variable
		#  (on desktop is usually LANGUAGES)
		DEFAULT_LANGUAGES = os.environ.get('LANG', '').split(':')
		DEFAULT_LANGUAGES += ['en_US']
		 
		lc, encoding = locale.getdefaultlocale()
		if lc:
		    loc = [lc]
		 
		# Concat all languages (env + default locale),
		#  and here we have the languages and location of the translations
		loc += DEFAULT_LANGUAGES
		self.mo_location = LOCALE_DIR
		# Lets tell those details to gettext
		#  (nothing to change here for you)
		gettext.install(True, localedir=None, unicode=1)
		 
		gettext.find(APP_NAME, self.mo_location)
		 
		gettext.textdomain (APP_NAME)
		 
		gettext.bind_textdomain_codeset(APP_NAME, "UTF-8")
		self.language = gettext.translation(APP_NAME, self.mo_location, languages=loc, fallback=True)
示例#10
0
文件: main.py 项目: kaio/ibus-table
    def __init__(self):
        locale.setlocale(locale.LC_ALL, "")
        localedir = os.getenv("IBUS_LOCALEDIR")
        gettext.bindtextdomain("ibus-table", localedir)
        gettext.bind_textdomain_codeset("ibus-table", "UTF-8")

        self.__bus = IBus.Bus()
        self.__engine_name = None
        if options.engine_name:
            # If the engine name is specified on the command line, use that:
            self.__engine_name = options.engine_name
        else:
            # If the engine name is not specified on the command line,
            # try to get it from the environment. This is necessary
            # in gnome-shell on Fedora 18,19,20,... because the setup tool is
            # called without command line options there but the
            # environment variable IBUS_ENGINE_NAME is set:
            if 'IBUS_ENGINE_NAME' in os.environ:
                self.__engine_name = os.environ['IBUS_ENGINE_NAME']
            else:
                self.__run_message_dialog(
                    _("IBUS_ENGINE_NAME environment variable is not set."),
                    Gtk.MessageType.WARNING)
        if self.__engine_name == None:
            self.__run_message_dialog(
                _("Cannot determine the engine name. Please use the --engine-name option."),
                Gtk.MessageType.ERROR)
            sys.exit(1)
示例#11
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()))
示例#12
0
    def __init__(self, filename=''):

        self.filename = filename

        if os.path.exists(self.filename):
            logger.debug('using provided file: %s', self.filename)

        self.ind = appindicator.Indicator(
            "revelation-indicator",
            "revelation-indicator-locked",  # defines icon
            appindicator.CATEGORY_APPLICATION_STATUS
        )

        self.ind.set_status(appindicator.STATUS_ACTIVE)

        sys.excepthook = self.__cb_exception

        gettext.bindtextdomain(config.PACKAGE, config.DIR_LOCALE)
        gettext.bind_textdomain_codeset(config.PACKAGE, "UTF-8")
        gettext.textdomain(config.PACKAGE)

        try:
            self.__init_config(filename)
            self.__init_facilities()
            self.__init_ui()

        except config.ConfigError:
            dialog.Error(
                None,
                _('Missing configuration data'),
                _('The applet could not find its configuration data, please'
                  'reinstall Revelation.')
            ).run()
            sys.exit(1)
示例#13
0
def init_locale(localedir=None):
	"""
	Initializes gettext-related stuff
	"""
	global _localedir
	_localedir = localedir
	gettext.bindtextdomain(GETTEXT_DOMAIN, localedir)
	gettext.bind_textdomain_codeset(GETTEXT_DOMAIN, "utf-8")
	gettext.textdomain(GETTEXT_DOMAIN)
示例#14
0
def setJDocEncoding(encoding):
    """
    Switch encoding to a different character set
    @param string encoding
    """
    try:
        gettext.bind_textdomain_codeset('hyperjdoc',encoding.upper())
    except:
        pass
示例#15
0
def init_gettext():
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        os.environ['LC_ALL'] = 'C'
        locale.setlocale(locale.LC_ALL, "")
    gettext.bind_textdomain_codeset(GETTEXT_PROGNAME, locale.nl_langinfo(locale.CODESET))
    gettext.bindtextdomain(GETTEXT_PROGNAME, '/usr/share/locale')
    gettext.textdomain(GETTEXT_PROGNAME)
示例#16
0
def send_note(device, parent):
    builder = Gtk.Builder()
    builder.set_translation_domain('blueman')
    bind_textdomain_codeset('blueman', 'UTF-8')
    builder.add_from_file(UI_PATH + '/note.ui')
    dialog = builder.get_object('dialog')
    dialog.set_transient_for(parent)
    dialog.props.icon_name = 'blueman'
    dialog.connect('response', send_note_cb, device['Address'], builder.get_object('note'))
    dialog.present()
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)
示例#18
0
文件: i18n.py 项目: Acidburn0zzz/ibus
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')
示例#19
0
文件: main.py 项目: juhp/ibus
 def __init__(self):
     super(Setup, self).__init__()
     localedir = os.getenv("IBUS_LOCALEDIR")
     gettext.bindtextdomain("ibus", localedir)
     glade.bindtextdomain("ibus", localedir)
     gettext.bind_textdomain_codeset("ibus", "UTF-8")
     glade.textdomain("ibus")
     glade_file = path.join(path.dirname(__file__), "./setup.glade")
     self.__xml = glade.XML(glade_file)
     self.__bus = None
     self.__init_bus()
     self.__init_ui()
示例#20
0
文件: paths.py 项目: bgeneto/sdaps
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')
示例#21
0
def init_gettext():
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        os.environ['LC_ALL'] = 'C'
        locale.setlocale(locale.LC_ALL, "")
    # Defeat "AttributeError: 'module' object has no attribute 'nl_langinfo'"
    try:
        gettext.bind_textdomain_codeset(GETTEXT_PROGNAME, locale.nl_langinfo(locale.CODESET))
    except AttributeError:
        pass
    gettext.bindtextdomain(GETTEXT_PROGNAME, '/usr/share/locale')
示例#22
0
文件: i18n.py 项目: amigadave/ibus
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")
示例#23
0
文件: main.py 项目: hychen/ibus
 def __init__(self):
     super(Setup, self).__init__()
     localedir = os.getenv("IBUS_LOCALEDIR")
     gettext.bindtextdomain("ibus", localedir)
     gettext.bind_textdomain_codeset("ibus", "UTF-8")
     gtk_builder_file = path.join(path.dirname(__file__), "./setup.ui")
     self.__builder = gtk.Builder()
     self.__builder.set_translation_domain("ibus")
     self.__builder.add_from_file(gtk_builder_file)
     self.__bus = None
     self.__init_bus()
     self.__init_ui()
示例#24
0
def configure_gettext():
    """Configure gettext for all RHSM-related code.

    Since Glade internally uses gettext, we need to use the C-level bindings in locale to adjust the encoding.

    See https://docs.python.org/2/library/locale.html#access-to-message-catalogs

    Exposed as its own function so that it can be called safely in the initial-setup case.
    """
    gettext.bindtextdomain(APP, DIR)
    gettext.textdomain(APP)
    gettext.bind_textdomain_codeset(APP, 'UTF-8')
    locale.bind_textdomain_codeset(APP, 'UTF-8')
示例#25
0
文件: paths.py 项目: crabhi/sdaps
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')
示例#26
0
文件: i18n.py 项目: jfilak/fros
def init(progname, localedir='/usr/share/locale'):
    global GETTEXT_PROGNAME
    GETTEXT_PROGNAME = progname
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        import os
        os.environ['LC_ALL'] = 'C'
        locale.setlocale(locale.LC_ALL, "")

    gettext.bind_textdomain_codeset(progname,
                                    locale.nl_langinfo(locale.CODESET))
    gettext.bindtextdomain(progname, localedir)
    gettext.textdomain(progname)
示例#27
0
文件: environ.py 项目: fuinha/kiwi
    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
示例#28
0
def _init_locale (gettext_domain = None):

    if Paths.locale_dir and gettext_domain is not None:
        try:
            locale.setlocale (locale.LC_ALL, "")
        except locale.Error as exc:
            from warnings import warn
            warn ("locale error: %s" % (exc,),
                  RuntimeWarning,
                  stacklevel = 2)
            Paths.locale_dir = None
        else:
            gettext.bindtextdomain (gettext_domain, Paths.locale_dir)
            gettext.textdomain (gettext_domain)
            gettext.bind_textdomain_codeset (gettext_domain, "UTF-8")
示例#29
0
    def enable_translation(self, domain=None, localedir=None):
        """
        Enables translation for a library

        :param domain: optional, if not specified name sent to constructor
          will be used
        :param localedir: directory to get locales from when running in
          uninstalled mode. If not specified a directory called 'locale' in
          the root will be used.
        """
        if not domain:
            domain = self.name

        if not localedir:
            localedir = 'locale'

        if self.uninstalled:
            try:
                self.add_resource('locale', localedir)
            except EnvironmentError:
                pass

        # XXX: locale should not be a list
        localedir = self._resources.get('locale')
        if not localedir:
            # Only complain when running installed
            if not self.uninstalled:
                log.warn('no localedir for: %s' % domain)

            return
        directory = gettext.bindtextdomain(domain, localedir[0])
        self._check_translation(domain, directory)
        # For libglade, but only on non-win32 systems
        if hasattr(locale, 'bindtextdomain'):
            locale.bindtextdomain(domain, localedir[0])

        # 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 platform.system() == 'Windows':
            from ctypes import cdll
            libintl = cdll.intl
            libintl.bindtextdomain(domain, localedir[0])
            libintl.bind_textdomain_codeset(domain, 'UTF-8')
            del libintl
示例#30
0
    def __init__(self, bus, object_path):
        super(Engine, self).__init__(bus, object_path)

        gettext.bindtextdomain("ibus-xkbc", os.getenv('XKBC_LOCALE_DIR'))
        gettext.bind_textdomain_codeset("ibus-xkbc", "UTF-8")

        self.__prop_dict = {}
        self.__config = Config(bus)
        self.__compose_state = COMPOSE_END
        self.__compose_dict = None

        self.__xkbc = prefs_get_xkbc_db()
        self.__prop_list = self._init_props()

        self.__target_layout_name = prefs_get_last_layout()
        self.__target_layout_id = self.__user_layouts.index(self.__target_layout_name)
示例#31
0
    import gc
    gc.enable()
    gc.collect()
    print "Execution du ramasse-miettes !"
except:
    print "Erreur du ramasse-miettes !"

#------------------------------------------------------------------------------

try:
    import os, sys, time
    import locale, gettext
    if os.name == 'nt':
        lang = os.getenv('LANG')
        if lang is None:
            default_lang, default_enc = locale.getdefaultlocale()
            if default_lang:
                lang = default_lang
        if lang:
            os.environ['LANG'] = lang
    pathname = os.path.dirname(sys.argv[0])
    subdir = "/locale"
    localdir = os.path.abspath(pathname) + subdir
    domain = "messages"
    codeset = "utf-8"
    gettext.bind_textdomain_codeset(domain, codeset)
    gettext.install("messages", localdir)
    print "Internationalisation activee (%s) !" % (os.name)
except:
    print "Erreur du module d'internationalisation !"
示例#32
0
                    break
        elif key == "switch-keys":
            self.__hangul_key_list_str = value.get_string().split(',')
        elif key == "hanja-keys":
            self.__hanja_key_list_str = value.get_string().split(',')

    def __read(self, key):
        return self.__settings.get_value(key)

    def __write(self, key, v):
        self.__settings.set_value(key, v)


if __name__ == "__main__":
    locale.bindtextdomain(config.gettext_package, config.localedir)
    gettext.bind_textdomain_codeset(config.gettext_package, "UTF-8")

    GLib.set_prgname("ibus-setup-hangul")
    GLib.set_application_name(_("IBusHangul Setup"))

    bus = IBus.Bus()
    if bus.is_connected():
        Setup(bus).run()
    else:
        message = _(
            "IBus daemon is not running.\nHangul engine settings cannot be saved."
        )
        dialog = Gtk.MessageDialog(type=Gtk.MessageType.ERROR,
                                   buttons=Gtk.ButtonsType.CLOSE,
                                   message_format=message)
        dialog.run()
示例#33
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0, gettext.bind_textdomain_codeset(self.input(0), self.input(1)))
示例#34
0
def init_gettext(domain, localedir):
    locale.setlocale(locale.LC_ALL, '')
    gettext.bindtextdomain(domain, localedir)
    gettext.bind_textdomain_codeset(domain, 'UTF-8')
    gettext.textdomain(domain)
    gettext.install(domain, localedir, unicode=True)
示例#35
0
文件: main.py 项目: ozzie00/ibus-xkbc
def main():

    # -------------------------------------------------------------
    # Re-create ibus-xkbc/data/xkbc.dat
    # this option is for just maintenance purpose
    shortopt = "c:k"
    try:
        opts, args = getopt.getopt(sys.argv[1:], shortopt)
    except:
        print_help(sys.stderr, 1)

    gettext.bindtextdomain("ibus-xkbc", os.getenv('XKBC_LOCALE_DIR'))
    gettext.bind_textdomain_codeset("ibus-xkbc", "UTF-8")

    vkb_mode = False
    for o, a in opts:
        if o == "-c":
            import prefs
            prefs.recreate_db(a)
            sys.exit(0)
        elif o == "-k":
            vkb_mode = True
        else:
            print_help(sys.stderr, 1)
    # -------------------------------------------------------------

    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    title = UI_TITLE if vkb_mode == False else UI_TITLE_VKB
    window.set_title(title)
    window.set_size_request(400, 500)
    window.connect("delete_event", lambda w, e: gtk.main_quit())

    vbox = gtk.VBox(False, 5)
    notebook = gtk.Notebook()

    # Target Layout
    scrolled_window = gtk.ScrolledWindow()
    scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
    target_layout = layout.TargetLayoutList()
    view = target_layout.get_view()
    scrolled_window.add_with_viewport(view)
    scrolled_window.set_size_request(400, 400)

    notebook.append_page(scrolled_window, gtk.Label(UI_LAYOUT_TAB))

    # Source Layout
    scrolled_window = gtk.ScrolledWindow()
    scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
    source_layout = layout.SourceLayoutList()
    view = source_layout.get_view()
    scrolled_window.add_with_viewport(view)
    scrolled_window.set_size_request(400, 400)

    # Hot key
    hotkey_box = gtk.VBox(False, 0)
    cycle_hotkey_list = hotkey.CycleHotkeyList(window)
    hotkey_box.pack_start(cycle_hotkey_list.get_window(), True, False, 0)
    hotkey_box.pack_start(gtk.HSeparator(), False, False, 0)
    rcycle_hotkey_list = hotkey.RCycleHotkeyList(window)
    hotkey_box.pack_start(rcycle_hotkey_list.get_window(), True, False, 0)

    if vkb_mode == False:
        notebook.append_page(scrolled_window, gtk.Label(UI_SOURCE_LAYOUT_TAB))
        notebook.append_page(hotkey_box, gtk.Label(UI_HOTKEY_TAB))

    button_box = gtk.HBox(False, 10)
    ok_button = gtk.Button(UI_OK)
    ok_button.connect("clicked", target_layout.save_layouts, None)
    ok_button.connect("clicked", source_layout.save_layout, None)
    ok_button.connect("clicked", cycle_hotkey_list.save_hotkey, None)
    ok_button.connect("clicked", rcycle_hotkey_list.save_hotkey, None)
    ok_button.connect("clicked", ok_cb, None)
    cancel_button = gtk.Button(UI_CANCEL)
    cancel_button.connect("clicked", cancel_cb)
    help_button = gtk.Button(UI_HELP)
    help_button.connect("clicked", help_cb, notebook)
    button_box.pack_start(ok_button, True, True, 10)
    button_box.pack_start(cancel_button, True, True, 10)
    button_box.pack_end(help_button, True, True, 10)

    vbox.pack_start(notebook, True, True, 0)
    vbox.pack_start(button_box, True, False, 0)

    window.add(vbox)
    window.show_all()

    gtk.main()
示例#36
0
 def __init_gettext(self):
     locale.setlocale(locale.LC_ALL, "")
     localedir = os.getenv("IBUS_LOCALEDIR")
     gettext.bindtextdomain(GETTEXT_PACKAGE, localedir)
     gettext.bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8")
示例#37
0
    def __init__(self):
        super().__init__(title=_("Bluetooth Devices"))

        self.Config = Config("org.blueman.general")

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/manager-main.ui")

        grid = self.Builder.get_object("grid")
        self.add(grid)
        self.set_name("BluemanManager")

        self.Plugins = PluginManager(ManagerPlugin, blueman.plugins.manager,
                                     self)
        self.Plugins.load_plugin()

        area = MessageArea()
        grid.attach(area, 0, 3, 1, 1)

        self._applethandlerid: Optional[int] = None

        # Add margin for resize grip or it will overlap
        if self.get_has_resize_grip():
            statusbar = self.Builder.get_object("statusbar")
            margin_right = statusbar.get_margin_right()
            statusbar.set_margin_right(margin_right + 10)

        def do_present(time):
            if self.props.visible:
                self.present_with_time(time)

        check_single_instance("blueman-manager", do_present)

        def on_window_delete(window, event):
            w, h = self.get_size()
            x, y = self.get_position()
            self.Config["window-properties"] = [w, h, x, y]
            Gtk.main_quit()

        setup_icon_path()

        try:
            self.Applet = AppletService()
        except DBusProxyFailed:
            print("Blueman applet needs to be running")
            exit()

        manager = Manager()
        try:
            manager.get_adapter(self.Config['last-adapter'])
        except DBusNoSuchAdapterError:
            logging.error('Default adapter not found, trying first available.')
            try:
                manager.get_adapter(None)
            except DBusNoSuchAdapterError:
                logging.error('No adapter(s) found')

        self.connect("delete-event", on_window_delete)
        self.props.icon_name = "blueman"

        w, h, x, y = self.Config["window-properties"]
        if w and h:
            self.resize(w, h)
        if x and y:
            self.move(x, y)

        sw = self.Builder.get_object("scrollview")
        # Disable overlay scrolling
        if Gtk.get_minor_version() >= 16:
            sw.props.overlay_scrolling = False

        self.List = ManagerDeviceList(adapter=self.Config["last-adapter"],
                                      inst=self)

        self.List.show()
        sw.add(self.List)

        self.Toolbar = ManagerToolbar(self)
        self.Menu = ManagerMenu(self)
        self.Stats = ManagerStats(self)

        if self.List.is_valid_adapter():
            self.List.display_known_devices(autoselect=True)

        self.List.connect("adapter-changed", self.on_adapter_changed)

        toolbar = self.Builder.get_object("toolbar")
        statusbar = self.Builder.get_object("statusbar")

        self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
        self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

        self.show()
示例#38
0
import gettext
import random
from .calculate import Crossword, Exportfiles

PY2 = sys.version_info[0] == 2
if PY2:
    from .complexstring2 import ComplexString
    input = raw_input
else:
    from .complexstring import ComplexString

base_dir = os.path.abspath(os.path.dirname(__file__))
d = '/usr/local/share' if 'local' in base_dir.split('/') else '/usr/share'
gettext.bindtextdomain('genxword', os.path.join(d, 'locale'))
if PY2:
    gettext.bind_textdomain_codeset('genxword', codeset='utf-8')
gettext.textdomain('genxword')
_ = gettext.gettext


class Genxword(object):
    def __init__(self, auto=False, mixmode=False):
        self.auto = auto
        self.mixmode = mixmode

    def wlist(self, words, nwords=50):
        """Create a list of words and clues."""
        wordlist = [
            line.strip().split(' ', 1) for line in words if line.strip()
        ]
        if len(wordlist) > nwords:
import gettext
import locale

import xbmc

from resources.lib.xbianconfig import xbianConfig

APP_NAME = "xbian-config"
CODESET = "UTF-8"

gettext.bindtextdomain(APP_NAME)
gettext.textdomain(APP_NAME)
gettext.bind_textdomain_codeset(APP_NAME, CODESET)
gettext.install(APP_NAME)

try:
    xbmc_lang = xbmc.getLanguage(xbmc.ISO_639_1)
except Exception:
    xbmc_lang = None

xbian_lang = xbianConfig('locales', 'select')[0].split('.')[0]
system_lang = locale.getlocale(locale.LC_MESSAGES)[0]
if not system_lang:
    system_lang = locale.getdefaultlocale()[0]

# The priority is: xbmc => xbian => system
languages = [lang for lang in [xbmc_lang, xbian_lang, system_lang] if lang]
language = gettext.translation(APP_NAME,
                               languages=languages,
                               fallback=True,
                               codeset=CODESET)
示例#40
0
__version__ = "4.20"
__author__ = 'Jose Antonio Chavarría'
__license__ = 'GPLv3'
__contact__ = "*****@*****.**"
__homepage__ = "https://github.com/migasfree/migasfree-client/"

# i18n
domain = 'migasfree-client'
if sys.version_info[0] <= 2:
    gettext.install(domain, LOCALE_PATH, unicode=1)
else:
    gettext.install(domain, LOCALE_PATH)

gettext.bindtextdomain(domain, LOCALE_PATH)
if hasattr(gettext, 'bind_textdomain_codeset'):
    gettext.bind_textdomain_codeset(domain, 'UTF-8')
gettext.textdomain(domain)

locale.bindtextdomain(domain, LOCALE_PATH)
if hasattr(locale, 'bind_textdomain_codeset'):
    locale.bind_textdomain_codeset(domain, 'UTF-8')
locale.textdomain(domain)

# http://www.ianbicking.org/illusive-setdefaultencoding.html
# begin unicode hack
import sys

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    # now default encoding is 'utf-8' ;)
    sys.path.append(NETCONFDIR)

# Workaround for buggy gtk/gnome commandline parsing python bindings.
cmdline = sys.argv[1:]
sys.argv = sys.argv[:1]

import locale
try:
    locale.setlocale(locale.LC_ALL, "")
except locale.Error, e:
    import os
    os.environ['LC_ALL'] = 'C'
    locale.setlocale(locale.LC_ALL, "")
import gettext

gettext.bind_textdomain_codeset(PROGNAME, locale.nl_langinfo(locale.CODESET))
gettext.bindtextdomain(PROGNAME, '/usr/share/locale')
gettext.textdomain(PROGNAME)
_ = lambda x: gettext.lgettext(x)
import __builtin__

__builtin__.__dict__['_'] = _

import signal
import os
import os.path

try:
    import gtk
except RuntimeError:
    sys.stderr.write(
示例#42
0
    	logging.info ("Running uninstalled, adding %s to system path" % abspath(root_dir))

# Setup logging
logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M:%S')

# Delay loading of deskbar modules until we have the path set up,
# to allow running in uninstalled mode
check_deskbar_path()
import deskbar
import deskbar.defs
import deskbar.gtkexcepthook

# Setup i18n
gettext.bindtextdomain('deskbar-applet', abspath(join(deskbar.defs.DATA_DIR, "locale")))
if hasattr(gettext, 'bind_textdomain_codeset'):
    gettext.bind_textdomain_codeset('deskbar-applet','UTF-8')
gettext.textdomain('deskbar-applet')

locale.bindtextdomain('deskbar-applet', abspath(join(deskbar.defs.DATA_DIR, "locale")))
if hasattr(locale, 'bind_textdomain_codeset'):
    locale.bind_textdomain_codeset('deskbar-applet','UTF-8')
locale.textdomain('deskbar-applet')

try:
    # attempt to set a name for killall
    import deskbar.osutils
    deskbar.osutils.set_process_name ("deskbar-applet")
except:
    print "Unable to set processName"

# Enable threads
示例#43
0
from os.path import isfile, exists
from os import getpid
from locale import (setlocale as locale_setlocale, bindtextdomain as
                    locale_bindtextdomain)
from gettext import (bindtextdomain, textdomain, bind_textdomain_codeset,
                     gettext as _)

if isfile('../locale/bluemindo.pot'):
    localedir = '../locale'
else:
    localedir = '/usr/share/locale'

locale_bindtextdomain('bluemindo', localedir)
bindtextdomain('bluemindo', localedir)
textdomain('bluemindo')
bind_textdomain_codeset('bluemindo', 'UTF-8')

from gi.repository.Gtk import (Dialog, Label, STOCK_CANCEL, STOCK_OK,
                               ResponseType)

from socket import socket, AF_UNIX, SOCK_DGRAM, error as socket_error
from pickle import dumps
from sys import argv
from os import remove
from os.path import join

from common.config import ConfigLoader
from common.functions import Functions
config = ConfigLoader()
functions = Functions()
示例#44
0
    def __init__(self, applet):
        super().__init__(title=_("Plugins"),
                         icon_name="blueman",
                         name="PluginDialog",
                         border_width=6,
                         default_width=490,
                         default_height=380,
                         resizable=False,
                         visible=False)

        self.applet = applet

        self.Builder = Gtk.Builder(translation_domain="blueman")
        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/applet-plugins-widget.ui")

        self.description = self.Builder.get_object("description")

        self.icon = self.Builder.get_object("icon")
        self.author_txt = self.Builder.get_object("author_txt")
        self.depends_hdr = self.Builder.get_object("depends_hdr")
        self.depends_txt = self.Builder.get_object("depends_txt")
        self.conflicts_hdr = self.Builder.get_object("conflicts_hdr")
        self.conflicts_txt = self.Builder.get_object("conflicts_txt")
        self.plugin_name = self.Builder.get_object("name")

        self.main_container = self.Builder.get_object("main_container")
        self.content_grid = self.Builder.get_object("content")

        self.b_prefs = self.Builder.get_object("b_prefs")
        self.b_prefs.connect("toggled", self.on_prefs_toggled)

        self.add(self.Builder.get_object("all"))

        cr = Gtk.CellRendererToggle()
        cr.connect("toggled", self.on_toggled)

        data = [
            {
                "id": "active",
                "type": bool,
                "renderer": cr,
                "render_attrs": {
                    "active": 0,
                    "activatable": 1,
                    "visible": 1
                }
            },
            {
                "id": "activatable",
                "type": bool
            },
            {
                "id": "icon",
                "type": str,
                "renderer": Gtk.CellRendererPixbuf(),
                "render_attrs": {
                    "icon-name": 2
                }
            },
            # device caption
            {
                "id": "desc",
                "type": str,
                "renderer": Gtk.CellRendererText(),
                "render_attrs": {
                    "markup": 3
                },
                "view_props": {
                    "expand": True
                }
            },
            {
                "id": "name",
                "type": str
            },
        ]

        self.list = GenericList(data, headers_visible=False, visible=True)
        self.list.liststore.set_sort_column_id(3, Gtk.SortType.ASCENDING)
        self.list.liststore.set_sort_func(3, self.list_compare_func)

        self.list.selection.connect("changed", self.on_selection_changed)

        plugin_list = self.Builder.get_object("plugin_list")
        plugin_info = self.Builder.get_object("main_scrolled_window")
        plugin_list.add(self.list)

        # Disable overlay scrolling
        if Gtk.get_minor_version() >= 16:
            plugin_list.props.overlay_scrolling = False
            plugin_info.props.overlay_scrolling = False

        self.populate()

        self.sig_a: int = self.applet.Plugins.connect(
            "plugin-loaded", self.plugin_state_changed, True)
        self.sig_b: int = self.applet.Plugins.connect(
            "plugin-unloaded", self.plugin_state_changed, False)
        self.connect("delete-event", self._on_close)

        self.list.set_cursor(0)
示例#45
0
import locale
import gettext

if platform.system() == "Windows":

    lang = locale.getdefaultlocale()[0][:2]
    try:
        cur_lang = gettext.translation("poker2d",
                                       localedir="./../../locale",
                                       languages=[lang])
        cur_lang.install()
    except IOError:
        _ = lambda text: text

else:
    gettext.bind_textdomain_codeset("poker2d", "UTF-8")
    gettext.install("poker2d")

INTERFACE_READY = "//event/poker3d/pokerinterface/ready"
INTERFACE_GONE = "//event/poker3d/pokerinterface/gone"

INTERFACE_LOGIN = "******"
INTERFACE_LOBBY = "//event/poker3d/pokerinterface/lobby"
INTERFACE_HANDS = "//event/poker3d/pokerinterface/hands"
INTERFACE_SHOW_OUTFITS = "//event/poker3d/pokerinterface/show_outfits"
INTERFACE_OUTFITS_SEX = "//event/poker3d/pokerinterface/outfits_sex"
INTERFACE_OUTFITS_SLOT_TYPE = "//event/poker3d/pokerinterface/outfits_slot_type"
INTERFACE_OUTFITS_SLOT = "//event/poker3d/pokerinterface/outfits_slot"
INTERFACE_OUTFITS_PARAMETER = "//event/poker3d/pokerinterface/outfits_parameter"
INTERFACE_OUTFITS_RANDOM = "//event/poker3d/pokerinterface/outfits_random"
INTERFACE_OUTFITS = "//event/poker3d/pokerinterface/outfits"
示例#46
0
def lgettext(domain_name, coding='utf-8'):
    language_dir = os.path.split(os.path.realpath(__file__))[0]
    gt.bindtextdomain(domain_name, language_dir)
    gt.bind_textdomain_codeset(domain_name, coding)
    gt.textdomain(domain_name)
    return gt.lgettext
示例#47
0
def configRead():
    """ Setup internal variables from config """
    # Section GENERAL
    metaInfo.title_prefix  = config.get('General','title_prefix','HyperSQL')
    metaInfo.encoding      = config.get('General','encoding','utf8')
    gettext.bind_textdomain_codeset('hypersql',metaInfo.encoding.upper())
    #gettext.bind_textdomain_codeset('hyperjdoc',metaInfo.encoding.upper())
    setJDocEncoding(metaInfo.encoding.upper())
    metaInfo.projectInfo   = unicode(config.get('General','project_info',''),metaInfo.encoding)
    infofile               = config.get('General','project_logo_url','')
    if infofile == '':
      metaInfo.projectLogo = config.get('General','project_logo','')
    else:
      metaInfo.projectLogo = infofile
    infofile               = config.get('General','project_info_file','')
    if infofile != '' and os.path.exists(infofile):
        infile = fopen(infofile, "r", metaInfo.encoding)
        fileLines = ''.join(infile.readlines())
        infile.close()
        metaInfo.projectInfo += fileLines
    JavaDocVars['ticket_url']   = config.get('General','ticket_url','')
    JavaDocVars['wiki_url']     = config.get('General','wiki_url','')
    # Section FILENAMES
    metaInfo.topLevelDirectory  = metaInfo.cmdOpts.sourceDir or config.get('FileNames','top_level_directory','.') # directory under which all files will be scanned
    metaInfo.topLevelDirectory  = os.path.normpath(metaInfo.topLevelDirectory) # get rid of trailing DirSeps, if any
    JavaDocVars['top_level_dir_len'] = len(metaInfo.topLevelDirectory)
    metaInfo.rcsnames           = config.getList('FileNames','rcsnames',['RCS','CVS','.svn']) # directories to ignore
    metaInfo.ignorefile         = config.get('FileNames','ignorefile','.hsqlignore') # flag-file indicating to ignore contents of a directory
    metaInfo.sql_file_exts      = config.getList('FileNames','sql_file_exts',['sql', 'pkg', 'pkb', 'pks', 'pls']) # Extensions for files to treat as SQL
    metaInfo.cpp_file_exts      = config.getList('FileNames','cpp_file_exts',['c', 'cpp', 'h']) # Extensions for files to treat as C
    if len(metaInfo.cmdArgs)>0: defCacheDir = os.path.split(sys.argv[0])[0] + os.sep + "cache" + os.sep + metaInfo.cmdArgs[0] + os.sep
    else: defCacheDir = os.path.split(sys.argv[0])[0] + os.sep + "cache" + os.sep
    metaInfo.cacheDirectory     = metaInfo.cmdOpts.cacheDir or config.get('FileNames','cache_dir',defCacheDir)
    if metaInfo.cmdOpts.cache is None: metaInfo.useCache = config.getBool('Process','cache',True)
    else: metaInfo.useCache = metaInfo.cmdOpts.cache
    metaInfo.htmlDir            = metaInfo.cmdOpts.htmlDir or config.get('FileNames','htmlDir',os.path.split(sys.argv[0])[0] + os.sep + "html" + os.sep)
    metaInfo.css_file           = config.get('FileNames','css_file','hypersql.css')
    metaInfo.css_url            = config.get('FileNames','css_url','')
    metaInfo.custom_css_files   = config.getList('FileNames','custom_css_files',[])
    metaInfo.unittest_dir       = config.get('FileNames','unittest_dir',os.path.split(sys.argv[0])[0] + os.sep + "unittests" + os.sep)
    metaInfo.indexPageCount     = 1 # We at least have the main index page
    if metaInfo.cmdOpts.pages is None:   metaInfo.cmdOpts.pages = []
    if metaInfo.cmdOpts.nopages is None: metaInfo.cmdOpts.nopages = []
    # order of metaInfo.pages defines the order of the navbar!
    metaInfo.pages = ['package','package_full','function','procedure','tab','view','mview','synonym','sequence','type','trigger','form','form_full','file','filepath','bug','todo','report','stat','depgraph']
    for page in metaInfo.pages:
        confPage(page)
    # Sections PAGES and PAGENAMES are handled indirectly via confPage() in section FileNames
    # Section DISPLAY
    metaInfo.navbar_elems_per_row = abs(config.getInt('Display','navbar_elems_per_row',4))
    JavaDocVars['link_urls'] = config.getBool('Display','link_urls',True)
    # Section PROCESS
    if metaInfo.cmdOpts.blind_offset is None:
        metaInfo.blindOffset = abs(config.getInt('Process','blind_offset',0)) # we need a positive integer
    else:
        metaInfo.blindOffset = abs(metaInfo.cmdOpts.blind_offset)
    if metaInfo.cmdOpts.source is None:
        metaInfo.includeSource = config.getBool('Process','include_source',True)
    else: metaInfo.includeSource = metaInfo.cmdOpts.source
    metaInfo.includeSourceLimit = config.getInt('Process','include_source_limit',0)*1024
    if metaInfo.cmdOpts.javadoc is None:
        metaInfo.useJavaDoc = config.getBool('Process','javadoc',True)
    else: metaInfo.useJavaDoc = metaInfo.cmdOpts.javadoc
    if metaInfo.useJavaDoc: metaInfo.unittests = config.getBool('Process','export_unittests',False)
    else: metaInfo.unittests = False
    if metaInfo.cmdOpts.linkCalls is None:
        metaInfo.linkCodeCalls = config.getBool('Process','link_code_calls',True)
    else: metaInfo.linkCodeCalls = metaInfo.cmdOpts.linkCalls
    if metaInfo.cmdOpts.scanShortrefs is None:
        metaInfo.scanShortRefs = config.getBool('Process','whereused_scan_shortrefs')
    else: metaInfo.scanShortRefs = metaInfo.cmdOpts.scanShortrefs
    if metaInfo.cmdOpts.scanInString is None:
        metaInfo.scanInString = config.getBool('Process','whereused_scan_instring')
    else:
        metaInfo.scanInString = metaInfo.cmdOpts.scanInString
    # Section VERIFICATION
    JavaDocVars['javadoc_mandatory'] = config.getBool('Verification','javadoc_mandatory',False)
    JavaDocVars['javadoc_mandatory_objects'] = config.getList('Verification','javadoc_mandatory_objects',['func','proc','pkg'])
    if metaInfo.cmdOpts.verifyJavadoc is None:
        JavaDocVars['verification'] = config.getBool('Verification','verify_javadoc',False)
    else: JavaDocVars['verification'] = metaInfo.cmdOpts.verifyJavadoc
    JavaDocVars['javadoc_shortdesc_mode'] = config.get('Verification','javadoc_shortdesc_mode','unit')
    JavaDocVars['author_in_report'] = config.getBool('Verification','author_in_report',False)
    JavaDocVars['mandatory_tags'] = config.getList('Verification','mandatory_tags',[])
    JavaDocVars['mandatory_code_tags'] = config.getList('Verification','mandatory_code_tags',[])
    JavaDocVars['mandatory_code_tags'] = list(set(JavaDocVars['mandatory_code_tags']+JavaDocVars['mandatory_tags']))
    JavaDocVars['mandatory_codetag_objects'] = config.getList('Verification','mandatory_codetag_objects',['func','proc','pkg'])
    JavaDocVars['form_stats'] = config.getBool('Verification','stats_javadoc_forms',False)
    JavaDocVars['verify_forms'] = config.getBool('Verification','verify_forms',False)
    # Section DEPGRAPH
    metaInfo.graphvizMod   = metaInfo.cmdOpts.graphvizProc or config.get('DepGraph','processor','fdp')
    metaInfo.fontName      = metaInfo.cmdOpts.graphvizFont or config.get('DepGraph','fontname','')
    metaInfo.fontSize      = metaInfo.cmdOpts.graphvizFontSize or config.get('DepGraph','fontsize','')
    metaInfo.graphRankSepDot  = metaInfo.cmdOpts.ranksep_dot or config.get('DepGraph','ranksep_dot','')
    metaInfo.graphRankSepTwopi  = metaInfo.cmdOpts.ranksep_twopi or config.get('DepGraph','ranksep_twopi','')
    metaInfo.graphLenNeato = metaInfo.cmdOpts.len_neato or config.get('DepGraph','len_neato','')
    metaInfo.graphLenFdp = metaInfo.cmdOpts.len_fdp or config.get('DepGraph','len_fdp','')
    metaInfo.graphDistCirco = metaInfo.cmdOpts.mindist_circo or config.get('DepGraph','mindist_circo','')
    metaInfo.depGraphObjects = metaInfo.cmdOpts.depObjects or config.getList('DepGraph','objects',['view','pkg','proc','func'])
    metaInfo.makeDepGraph = {}
    metaInfo.makeDepGraph['file2file']     = config.getBool('DepGraph','file2file',True)
    metaInfo.makeDepGraph['file2object']   = config.getBool('DepGraph','file2object',False)
    metaInfo.makeDepGraph['object2file']   = config.getBool('DepGraph','object2file',True)
    metaInfo.makeDepGraph['object2object'] = config.getBool('DepGraph','object2object',True)
    if metaInfo.cmdOpts.graph is not None:
        for name in metaInfo.cmdOpts.graph:
            if metaInfo.cmdOpts.nograph is None or name not in metaInfo.cmdOpts.nograph:
                metaInfo.makeDepGraph[name] = True
    if metaInfo.cmdOpts.nograph is not None:
        for name in metaInfo.cmdOpts.nograph:
            if metaInfo.cmdOpts.graph is None or name not in metaInfo.cmdOpts.graph:
                metaInfo.makeDepGraph[name] = False
    metaInfo.depGraphCount = 0
    if metaInfo.makeDepGraph['file2file']:     metaInfo.depGraphCount += 1
    if metaInfo.makeDepGraph['file2object']:   metaInfo.depGraphCount += 1
    if metaInfo.makeDepGraph['object2file']:   metaInfo.depGraphCount += 1
    if metaInfo.makeDepGraph['object2object']: metaInfo.depGraphCount += 1
    metaInfo.depGraphDelTmp = config.getBool('DepGraph','deltmp',True)
    # Section LOGGING
    if metaInfo.cmdOpts.progress is None:
        metaInfo.printProgress = config.getBool('Logging','progress',True)
    else: metaInfo.printProgress = metaInfo.cmdOpts.progress
    if metaInfo.cmdOpts.verificationLog is None:
        JavaDocVars['verification_log'] = config.getBool('Logging','verification',False)
    else:
        JavaDocVars['verification_log'] = metaInfo.cmdOpts.verificationLog
    # Section COLORS
    confColors('pkg', '#0000ff','#ffffff')
    confColors('proc', '#3366ff','#ffffff')
    confColors('func', '#66aaff','#000000')
    confColors('trigger', '#33ffff','#000000')
    confColors('form','#0066cc','#ffffff')
    confColors('tab', '#774411','#ffffff')
    confColors('view', '#eeaa55','#000000')
    confColors('mview', '#bb6611','#ffffff')
    confColors('synonym', '#00ff00','#000000')
    confColors('sequence', '#ffcc00', '#000000')
    confColors('typ', '#ffff33','#000000')
    confColors('file', '#dddddd','#000000')
    confColors('empty', '#dddddd','#000000')
    confColors('code', '#0000ff','#ffffff')
    confColors('comment', '#bb6611','#ffffff')
    confColors('mixed', '#eeaa55','#000000')
    confColors('bug', '#ff0000','#ffffff')
    confColors('warn', '#eeaa55','#000000')
    confColors('todo', '#3366ff','#ffffff')
    confColors('filebig', '#ff0000','#ffffff')
    confColors('file100k', '#ff4422','#ffffff')
    confColors('file50k', '#eeaa55','#000000')
    confColors('file25k', '#ffcc00','#000000')
    confColors('file10k', '#00ff00','#000000')
    confColors('file1000l', '#0000ff','#ffffff')
    confColors('file400l', '#ffcc00','#000000')
    # JavaDoc types for SQL
    JavaDocVars['otypes'] = {
              'function':  dict(name='function',  otags=['param','return','throws']),
              'procedure': dict(name='procedure', otags=['param','throws']),
              'table':     dict(name='table',     otags=['col']),
              'view':      dict(name='view',      otags=['col']),
              'mview':     dict(name='mview',     otags=['col']),
              'trigger':   dict(name='trigger',   otags=[]),
              'synonym':   dict(name='synonym',   otags=[]),
              'sequence':  dict(name='sequence',  otags=[]),
              'pkg':       dict(name='package',   otags=[]),
              'form':      dict(name='form',      otags=[]),
              'type':      dict(name='type',      otags=[])
    } # supported object types
    JavaDocVars['supertypes'] = ['pkg','form'] # object types with subobjects
示例#48
0
    def __init__(self, device, adapter_path, files):
        super().__init__(
            title=_("Bluetooth File Transfer"),
            name="BluemanSendTo",
            icon_name="blueman",
            border_width=5,
            default_width=400,
            window_position=Gtk.WindowPosition.CENTER,
            type_hint=Gdk.WindowTypeHint.DIALOG
        )

        self.b_cancel = self.add_button("_Stop", Gtk.ResponseType.CLOSE)
        self.b_cancel.props.receives_default = True
        self.b_cancel.props.use_underline = True
        self.b_cancel.connect("clicked", self.on_cancel)

        self.Builder = Gtk.Builder(translation_domain="blueman")
        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/send-dialog.ui")

        grid = self.Builder.get_object("sendto")
        content_area = self.get_content_area()
        content_area.add(grid)

        self.l_dest = self.Builder.get_object("l_dest")
        self.l_file = self.Builder.get_object("l_file")

        self.pb = self.Builder.get_object("pb")
        self.pb.props.text = _("Connecting")

        self.device = device
        self.adapter = Adapter(adapter_path)
        self.manager = Manager()
        self.files: List[Gio.File] = []
        self.num_files = 0
        self.object_push = None
        self.transfer = None

        self.total_bytes = 0
        self.total_transferred = 0

        self._last_bytes = 0
        self._last_update = 0.0

        self.error_dialog = None
        self.cancelling = False

        # bytes transferred on a current transfer
        self.transferred = 0

        self.speed = SpeedCalc(6)

        for file_name in files:
            parsed_file = Gio.File.parse_name(file_name)

            if not parsed_file.query_exists():
                logging.info("Skipping non existing file %s" % parsed_file.get_path())
                continue

            file_info = parsed_file.query_info("standard::*", Gio.FileQueryInfoFlags.NONE)

            if file_info.get_file_type() == Gio.FileType.DIRECTORY:
                logging.info("Skipping directory %s" % parsed_file.get_path())
                continue

            self.files.append(parsed_file)
            self.num_files += 1
            self.total_bytes += file_info.get_size()

        if len(self.files) == 0:
            self.emit("result", False)

        try:
            self.client = Client()
            self.manager.connect_signal('session-added', self.on_session_added)
            self.manager.connect_signal('session-removed', self.on_session_removed)
        except GLib.Error as e:
            if 'StartServiceByName' in e.message:
                logging.debug(e.message)
                d = ErrorDialog(_("obexd not available"), _("Failed to autostart obex service. Make sure the obex "
                                                            "daemon is running"), parent=self.get_toplevel())
                d.run()
                d.destroy()
                self.emit("result", False)
            else:
                # Fail on anything else
                raise

        self.l_file.props.label = self.files[-1].get_basename()

        self.client.connect('session-failed', self.on_session_failed)

        logging.info("Sending to %s" % device['Address'])
        self.l_dest.props.label = device['Alias']

        # Stop discovery if discovering and let adapter settle for a second
        if self.adapter["Discovering"]:
            self.adapter.stop_discovery()
            time.sleep(1)

        self.create_session()

        self.show()