def init(): APP_NAME = "ircbot" langs = ["en_EN", "de_DE"] local_path = os.path.realpath(os.path.dirname(sys.argv[0])) + '/lang/' gettext.bindtextdomain(APP_NAME, local_path) gettext.textdomain(APP_NAME) init._ = gettext.gettext
def __init__(self): super(FractionPresentation, self).__init__() gettext.bindtextdomain("fracciones", "./locale") gettext.textdomain("fracciones") # Change font size #settings = gtk.settings_get_default() #settings.set_string_property("gtk-font-name", "Sans 40", "FractionPresentation") # instantiate logic self.logic = FractionLogic() self.logic.generate() # create main widget: # menu/label/cake/button # 1. Add the menu bar mb = gtk.MenuBar() self.pack_start(mb, False, False, 0) # game menu gamemenu = gtk.Menu() gamem = gtk.MenuItem(_("Game")) gamem.set_submenu(gamemenu) new = gtk.MenuItem(_("New")) new.connect("activate", self.menu_game_new) gamemenu.append(new) exit = gtk.MenuItem(_("Exit")) exit.connect("activate", self.menu_game_exit) gamemenu.append(exit) mb.append(gamem) # help menu helpmenu = gtk.Menu() helpm = gtk.MenuItem(_("Help")) helpm.set_submenu(helpmenu) about = gtk.MenuItem(_("About")) about.connect("activate", self.menu_help_about) helpmenu.append(about) mb.append(helpm) # 2. label label = gtk.Label(_("""Eat %i/%i""") % self.logic.get_current()) self.pack_start(label, False, True) self.label = label # 3. cake aspect = gtk.AspectFrame() cake = gtkcake.Cake(self.logic.get_current()[1]) aspect.add(cake) self.pack_start(aspect) self.cake = cake # 4. button button = gtk.Button(_("Check")) button.connect("clicked", self.check_cake) self.pack_start(button, False, True) # show all widgets self.show_all()
def __init__(self, project): """Constructor""" self.project = project # Setup foreign language support langs = [] lc, encoding = locale.getdefaultlocale() if (lc): langs = [lc] language = os.environ.get('LANGUAGE', None) if (language): langs += language.split(":") # Add languages... for testing #langs += ["es", "fr"] gtk.glade.textdomain("OpenShot") gtk.glade.bindtextdomain("OpenShot", self.project.LOCALE_DIR) gettext.textdomain("OpenShot") gettext.bindtextdomain("OpenShot", self.project.LOCALE_DIR) gettext.install(domain="OpenShot", unicode = True, codeset = 'utf-8') # This reference is used by other classes to define the _ method self.lang = gettext.translation("OpenShot", self.project.LOCALE_DIR, languages = langs, fallback = True)
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 setup_translations(self): gettext.bindtextdomain("kazam", "/usr/share/locale") gettext.textdomain("kazam") try: locale.setlocale(locale.LC_ALL, "") except Exception as e: logger.exception("EXCEPTION: Setlocale failed, no language support.")
def localeInit(): global lang lang = language.getLanguage()[:2] os.environ["LANGUAGE"] = lang gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE)) gettext.textdomain("enigma2") gettext.bindtextdomain(lang, '/usr/lib/enigma2/python/Plugins/Extensions/HbbTV/locale')
def __init__(self): os.nice(20) try: self.application_dir = os.environ["UPDATE_MANAGER_NOTIFIER_ROOT"] except KeyError: self.application_dir = "/" misc.setlocale(locale.LC_ALL, "") gettext.bindtextdomain("pkg", os.path.join( self.application_dir, "usr/share/locale")) gettext.textdomain("pkg") self.pr = None self.last_check_filename = None self.time_until_next_check = 0 self.status_icon = None self.n_updates = 0 self.n_installs = 0 self.n_removes = 0 self.notify = None self.host = None self.last_check_time = 0 self.refresh_period = 0 self.timeout_id = 0 self.terminate_after_activate = False self.client = gconf.client_get_default() self.start_delay = self.get_start_delay() # Allow gtk.main loop to start as quickly as possible gobject.timeout_add(self.start_delay * 1000, self.check_and_start)
def _initGettext(): charset = initLocale() # Try to load gettext module if config.use_i18n: try: import gettext ok = True except ImportError: ok = False else: ok = False # gettext is not available or not needed: use dummy gettext functions if not ok: return (_dummy_gettext, _dummy_ngettext) # Gettext variables package = 'hachoir' locale_dir = path.join(path.dirname(__file__), "..", "locale") # Initialize gettext module gettext.bindtextdomain(package, locale_dir) gettext.textdomain(package) translate = gettext.gettext ngettext = gettext.ngettext # TODO: translate_unicode lambda function really sucks! # => find native function to do that unicode_gettext = lambda text: \ unicode(translate(text), charset) unicode_ngettext = lambda singular, plural, count: \ unicode(ngettext(singular, plural, count), charset) return (unicode_gettext, unicode_ngettext)
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. """ try: import locale import gettext # FIXME: Commented to avoid problems with a .utf8 LANG variable... # locale.setlocale(locale.LC_ALL, "") gettext.bindtextdomain(app_name, locale_dir) gettext.textdomain(app_name) gtk.glade.bindtextdomain(app_name, locale_dir) gtk.glade.textdomain(app_name) gettext.install(app_name, locale_dir, unicode = 1) except (IOError,locale.Error), e: print "Warning", app_name, e __builtins__.__dict__["_"] = lambda x : x
def __init__(self,data_dir,desktop_file_path,pkgname): self.file_path = data_dir self.dfile=Ini(desktop_file_path) self.user_set_img=False gettext.bindtextdomain(pkgname, os.path.dirname(data_dir)+"/locale") gettext.textdomain(pkgname) locale.bind_textdomain_codeset(pkgname,'UTF-8') _ = gettext.gettext self._=_ self.tree = Gtk.Builder() self.tree.set_translation_domain("light-desktop-item-edit")#doesn't work at all self.tree.add_from_file(os.path.join(self.file_path, 'directory-item-edit.ui')) for obj in self.tree.get_objects(): if obj.__gtype__==Gtk.Label.__gtype__ or obj.__gtype__==Gtk.CheckButton.__gtype__: obj.set_label(_(obj.get_label())) self.tree.get_object("dialog").set_title(_("Directory")) self.img=Gtk.Image() self.tree.get_object("icon-button").add(self.img) self.load_desktop_file() self.tree.get_object("ok").connect("released",self.ok_pressed) self.tree.get_object("cancel").connect("released",self.destroy) self.tree.get_object("name").connect("changed",self.name_changed) self.tree.get_object("icon-button").connect("released",self.icon_pressed) self.tree.get_object("icon-name").connect("changed",self.icon_name_changed) w=self.tree.get_object("dialog") w.connect("key-press-event",self.handle_escape) w.show_all() Gtk.main()
def main(): app = wx.App() gettext.bindtextdomain('uhope') gettext.textdomain('uhope') microhope(None,-1,'uHOPE','size') app.MainLoop()
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)
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 __init__(self): gettext.bindtextdomain("video2theora", "po") locale.setlocale(locale.LC_ALL, "") gettext.textdomain("video2theora") gtk.glade.bindtextdomain("video2theora", "po") glade_file=os.path.join("data", "v2t.glade") self.widgets = gtk.glade.XML(glade_file) self.window = self.widgets.get_widget("app_window") self.file_chooser_button = self.widgets.get_widget("filechooserbutton") self.save_folder_button = self.widgets.get_widget("save_folder_button") self.outfile_entry = self.widgets.get_widget("outfile_entry") self.video_quality_slider = self.widgets.get_widget("video_quality_slider") self.video_quality_slider.set_tooltip_text(_("10 for best video quality")) self.video_quality_label = self.widgets.get_widget("video_quality_label") self.audio_quality_slider = self.widgets.get_widget("audio_quality_slider") self.audio_quality_slider.set_tooltip_text(_("10 for best audio quality")) self.audio_quality_label = self.widgets.get_widget("audio_quality_label") self.go_button = self.widgets.get_widget("go_button") self.progress_window = self.widgets.get_widget("progress_window") self.progressbar = self.widgets.get_widget("progressbar") self.progress_cancel = self.widgets.get_widget("cancel_button") self.about_dialog = self.widgets.get_widget("aboutdialog1") self.widgets.signal_autoconnect(self) self.window.connect("delete_event", lambda w,e: gtk.main_quit()) self.progress_window.connect("delete_event", self.on_cancel_button_clicked) self.window.show_all()
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)
def localeInit(): # getLanguage returns e.g. "fi_FI" for "language_country" lang = language.getLanguage()[:2] # Enigma doesn't set this (or LC_ALL, LC_MESSAGES, LANG). gettext needs it! os_environ["LANGUAGE"] = lang print "[FlashBackup] found LANGUAGE=", lang gettext.bindtextdomain("FlashBackup", resolveFilename(SCOPE_PLUGINS, "Extensions/FlashBackup/locale"))
def set_locales(self): """internationalization config. Use only once.""" domain = self.distro + '-installer' bindtextdomain(domain, LOCALEDIR) textdomain(domain) install(domain, LOCALEDIR, unicode=1)
def init_i18n() : locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR) gettext.textdomain(GETTEXT_PACKAGE) lang = gettext.translation(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR) _ = lang.gettext gettext.install(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR)
def __init__(self): fileDirectory = os.path.dirname(__file__) self.preferences = GFrameCatcher.libs.preferences.Preferences() gobject.set_application_name(self.preferences.ProgramName) gettext.bindtextdomain(self.preferences.ProgramName, self.preferences.LocalePath) gettext.textdomain(self.preferences.ProgramName) gettext.install(self.preferences.ProgramName, localedir= self.preferences.LocalePath,unicode= True) self.builder = gtk.Builder() self.builder.add_from_file(os.path.join(fileDirectory , "ui/mainWindow.ui")) self.builder.set_translation_domain(self.preferences.ProgramName) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.window.set_icon(GdkPixbuf.Pixbuf.new_from_file(os.path.join(fileDirectory , "../icons/gframecatcher16.png"))) self.window.set_default_size(int(self.preferences.getValue("Window", "width")), int(self.preferences.getValue("Window", "height"))) self.builder.get_object("toolZoomFitButton").set_active(bool(int(self.preferences.getValue("Window", "zoomFit")))) self.window.show_all() self.MediaInfo = GFrameCatcher.media.mediaLibrary.MediaInfo() self.model = gtk.ListStore(GdkPixbuf.Pixbuf, str) self.builder.get_object("frameView").set_from_pixbuf(None) videoDrop = [("text/uri-list" , 0 , 82 )] # self.builder.get_object("frameIconView").set_model(self.model) # self.builder.get_object("frameIconView").drag_dest_set( # gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP, videoDrop , gtk.gdk.ACTION_COPY # ) self.__imageDrag = [("text/uri-list", 0, 81), ("image/png", 0, 82)] # self.builder.get_object("viewPort").drag_source_set(gtk.gdk.BUTTON1_MASK, self.__imageDrag, gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_COPY) self.builder.get_object("viewPort").drag_dest_unset() self.window.connect("configure-event", self.on_configure_event) self.window.connect("window-state-event", self.on_window_state_event) self.window.connect("destroy", self.on_imageQuit_activate)
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 run(): utils.setproctitle('redshift-gtk') # Internationalisation gettext.bindtextdomain('redshift', defs.LOCALEDIR) gettext.textdomain('redshift') for help_arg in ('-h', '--help'): if help_arg in sys.argv: print(_('Please run `redshift -h` for help output.')) sys.exit(-1) # Create redshift child process controller c = RedshiftController(sys.argv[1:]) def terminate_child(data=None): c.terminate_child() return False # Install signal handlers GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, terminate_child, None) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, terminate_child, None) try: # Create status icon RedshiftStatusIcon(c) # Run main loop Gtk.main() except: c.kill_child() raise
def translate(self): domain = "grape" current_path = os.path.dirname(__file__) locale_path = os.path.join(current_path, "..", "..", "..", "config", "locale") langs = [] lc, encoding = locale.getdefaultlocale() if (lc): langs = [lc] language = os.environ.get('LANGUAGE', None) if (language): langs += language.split(":") # TODO - Configuration file langs += ["pt_BR", "en_US"] gettext.bindtextdomain(domain, locale_path) gettext.textdomain(domain) lang = gettext.translation(domain, locale_path, languages=langs, fallback = True) gettext.install(domain, locale_path) return domain
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)
def set_lang(lang, codeset='utf-8', gui=False): if not isinstance(lang, list): lang = [lang] locale_dir = os.path.join(os.path.dirname(__file__), 'i18n') domain = 'irssinotifier' gettext.bindtextdomain(domain, locale_dir) gettext.textdomain(domain) locale.bindtextdomain(domain, locale_dir) locale.textdomain(domain) if gui: import gtk.glade gtk.glade.bindtextdomain(domain) gtk.glade.textdomain(domain) try: translator = gettext.translation(domain, locale_dir, languages=lang, codeset=codeset) except IOError, ioe: lang = ['en'] print 'Language not supportted: %r' % ioe print 'Fallback to english' translator = gettext.translation(domain, locale_dir, languages=lang, codeset=codeset)
def setup_lang(lang): bindtextdomain("templates", localedir) try: lang = gettext.translation('templates', localedir, [lang]) lang.install() except IOError: pass
def __init__(self, recovery, mode='recovery'): def action_objects(widgets, objects, action): for item in ['button', 'image', 'label']: if action == 'hide': widgets.get_object(objects + '_' + item).hide() else: widgets.get_object(objects + '_' + item).show_all() #setup locales bindtextdomain(DOMAIN, LOCALEDIR) textdomain(DOMAIN) self.tool_widgets = Gtk.Builder() self.tool_widgets.add_from_file(os.path.join(UIDIR, 'tool_selector.ui')) Gtk.Window.set_default_icon_from_file(os.path.join(SVGDIR, 'dell-dvd.svg')) translate_widgets(self.tool_widgets) self.tool_widgets.connect_signals(self) #if running in driver install mode, hide other stuff if mode == 'driver': for item in ['restore_system', 'build_os_media']: action_objects(self.tool_widgets, item, 'hide') action_objects(self.tool_widgets, 'install_drivers', 'show') else: #hide restore from HDD unless there is a recovery partition if not (recovery and os.path.exists('/etc/grub.d/99_dell_recovery')): action_objects(self.tool_widgets, 'restore_system', 'hide') #about dialog self.about_box = None #variables self.rp = recovery self._dbus_iface = None
def init_translations(): import locale #locale.setlocale(locale.LC_ALL, '') import gettext from os.path import pardir, abspath, dirname, join GETTEXT_DOMAIN = 'avernus' LOCALE_PATH = abspath(join(dirname(__file__), pardir, 'build/mo')) if not os.path.isdir(LOCALE_PATH): LOCALE_PATH = '/usr/share/locale' # setup translation languages_used = [] lc = locale.getdefaultlocale()[0] if lc: languages_used = [lc] lang_in_env = os.environ.get('LANGUAGE', None) if lang_in_env: languages_used.extend(lang_in_env.split()) gettext.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH) gettext.textdomain(GETTEXT_DOMAIN) translation = gettext.translation(GETTEXT_DOMAIN, LOCALE_PATH, languages=languages_used, fallback=True) import __builtin__ __builtin__._ = translation.ugettext
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)
def init_locales(): name = "veromix" directory = VEROMIX_BASEDIR + "/data/locale" if "usr/share/veromix" in VEROMIX_BASEDIR: directory = "/usr/share/locale" gettext.bindtextdomain(name, directory) gettext.textdomain(name)
def init_gettext(): '''Convenience function to setup _''' # This is all stolen from src/ufw import gettext kwargs = {} 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("ufw", **kwargs) # Internationalization gettext.bindtextdomain("ufw", \ os.path.join('./locales/mo')) gettext.textdomain("ufw") try: # BAW: I'm not sure why both this and the .install() above is here, but # let's roll with it for now. This is the Python 2 version, which # ensures we get unicodes. _ = gettext.ugettext except AttributeError: # Python 3 always returns unicodes. _ = gettext.gettext return _
sets the window title to user@host. """ # Meta __version__ = '1.2' __license__ = "AGPLv3 or Proprietary (see LICENSE.txt)" __version_info__ = (1, 2) __author__ = 'Dan McDougall <*****@*****.**>' # Import Python stdlib stuff import os, sys, errno, readline, tempfile, base64, binascii, struct, signal, re from subprocess import Popen from optparse import OptionParser # i18n support stuff import gettext gettext.bindtextdomain('ssh_connect', 'i18n') gettext.textdomain('ssh_connect') _ = gettext.gettext # Disable ESC autocomplete for local paths (prevents information disclosure) readline.parse_and_bind('esc: none') # Globals POSIX = 'posix' in sys.builtin_module_names wrapper_script = """\ #!/bin/sh # This variable is for easy retrieval later SSH_SOCKET='{socket}' {cmd} echo '[Press Enter to close this terminal]' read waitforuser
def localeInit(): gettext.bindtextdomain(PluginLanguageDomain, resolveFilename(SCOPE_PLUGINS, PluginLanguagePath))
from Components.Converter.Converter import Converter from os import environ from Components.Element import cached from Tools.Directories import resolveFilename, SCOPE_LANGUAGE, SCOPE_PLUGINS from Components.Language import language import gettext lang = language.getLanguage() environ["LANGUAGE"] = lang[:2] gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE)) gettext.textdomain("enigma2") gettext.bindtextdomain( "KravenFHD", "%s%s" % (resolveFilename(SCOPE_PLUGINS), "Extensions/KravenFHD/locale/")) def _(txt): t = gettext.dgettext("KravenFHD", txt) if t == txt: t = gettext.gettext(txt) return t class KravenFHDTextTranslator(Converter, object): movecopy = 0 currentlyrunning = 1 itfollows = 2 coming = 3 runningsince = 4 preview = 5 runsuntil = 6
try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk except: sys.exit(1) DDUCONFIG = ConfigParser() DDUCONFIG.read( os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "ddu.conf")) ABSPATH = DDUCONFIG.get('general', 'abspath') try: locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain('ddu', '%s/i18n' % ABSPATH) gettext.bindtextdomain('ddu', '%s/i18n' % ABSPATH) gettext.textdomain('ddu') except AttributeError: pass _ = gettext.gettext class RepoDlg: """ manipulate repo dialog """ def __init__(self): uipath = ABSPATH + '/data/hdd.ui' builder = Gtk.Builder() builder.set_translation_domain('ddu')
def test_bindtextdomain(self): self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir)
def localeInit(): gettext.bindtextdomain( "YTTrailer", resolveFilename(SCOPE_PLUGINS, "Extensions/YTTrailer/locale"))
""" This file is part of YAOS and is licenced under the MIT licence. """ import gettext gettext.bindtextdomain('yaosapp', '/lang') gettext.textdomain('yaosapp') _ = gettext.gettext import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, Gio, Gdk, GdkPixbuf, GObject, Pango import Utils import UIController import CSSManager import ZynqScope.ZynqScopeTrigger as zstrig import os, copy import logging log = logging.getLogger() OUTER_TRIGGER_TAB_LAYOUT_FILE = "resources/outer_trigger_tab.gtkbuilder" OUTER_TRIGGER_TAB_CSS_FILE = "trigger_tab.css" EDGE_TRIGGER_LAYOUT_FILE = "resources/edge_trigger_tab.gtkbuilder" ICON_RISE_EDGE = "trigger_rising_edge.svg" ICON_FALL_EDGE = "trigger_falling_edge.svg"
# # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA import gi gi.require_version('Gtk', '3.0') gi.require_version('CMenu', '3.0') from gi.repository import Gtk, GObject, Gdk, CMenu import html import os import gettext import subprocess from cme import config gettext.bindtextdomain(config.GETTEXT_PACKAGE, config.localedir) gettext.textdomain(config.GETTEXT_PACKAGE) _ = gettext.gettext from cme.MenuEditor import MenuEditor from cme import util class MainWindow(object): timer = None #hack to make editing menu properties work edit_pool = [] def __init__(self, datadir, version): self.file_path = datadir self.version = version
def add_translation(): lc, enc = locale.getdefaultlocale() if os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), "i18n")): # Running locally logging.debug("Running local") gettext.bindtextdomain("youtubed-2x", "i18n") lc, enc = locale.getdefaultlocale() lang = gettext.translation("youtubed-2x", "i18n", languages=[lc], fallback=True) logging.debug(lang) lang.install() #gettext.install ("youtubed-2x", "i18n") gtk.glade.bindtextdomain("youtubed-2x", "i18n") elif gettext.find("youtubed-2x"): # Installed. .mo file is in default locale location logging.debug("Found default locale") gettext.install("youtubed-2x") gtk.glade.bindtextdomain("youtubed-2x") elif WINDOWS and os.path.exists(os.path.join(sys.prefix, "share", "locale")): # Windows when using build made with Py2exe logging.debug("Py2exe build") locale_dir = os.path.join(sys.prefix, "share", "locale") gettext.bindtextdomain("youtubed-2x", locale_dir) lang = gettext.translation("youtubed-2x", locale_dir, languages=[lc], fallback=True) logging.debug(lang) lang.install() #gettext.install ("youtubed-2x", "i18n") gtk.glade.bindtextdomain("youtubed-2x", locale_dir) else: # Installed. Try to discover locale location logging.debug("Installed") locale_dir = None if "XDG_DATA_DIRS" in os.environ: data_dirs = os.environ["XDG_DATA_DIRS"].split(":") for data_dir in data_dirs: mofile = gettext.find("youtubed-2x", os.path.join(data_dir, "locale")) logging.debug(mofile) if mofile: locale_dir = os.path.join(data_dir, "locale") break logging.debug(locale_dir) if locale_dir: gettext.install("youtubed-2x", locale_dir) gtk.glade.bindtextdomain("youtubed-2x", locale_dir) else: # If .mo file could not be found, ignore the issue. # Non-translated strings will be used. Install _() # to global namespace gettext.install("youtubed-2x") gtk.glade.bindtextdomain("youtubed-2x") #gettext.install ("youtubed-2x") gtk.glade.textdomain("youtubed-2x") logging.debug(_)
#!/usr/bin/python3 # -*- coding:Utf-8 -*- """ Description : Configuration du handymenu """ import sys import os from gi.repository import Gtk, GObject, Gdk, GdkPixbuf import gettext import locale from hm_utils import * gettext.bindtextdomain('handymenu', '/usr/share/locale') gettext.textdomain('handymenu') _ = gettext.gettext def get_info_desktop(desktopfile): """return infos from a .desktop file""" name, cmd, icon, generic = "", "", "", "" nameloc = False geneloc = False lang = locale.setlocale(locale.LC_ALL, "")[0:2] with open(desktopfile, 'r') as d: df = d.readlines() for l in df: if generic == "" or geneloc == False: if l.startswith('GenericName[{0}]='.format(lang)):
return wrapper # Used as a decorator to run things in the main loop, from another thread def idle(func): def wrapper(*args): GObject.idle_add(func, *args) return wrapper # i18n APP = 'webapp-manager' LOCALE_DIR = "/usr/share/locale" locale.bindtextdomain(APP, LOCALE_DIR) gettext.bindtextdomain(APP, LOCALE_DIR) gettext.textdomain(APP) _ = gettext.gettext # Constants ICE_DIR = os.path.expanduser("~/.local/share/ice") APPS_DIR = os.path.expanduser("~/.local/share/applications") PROFILES_DIR = os.path.join(ICE_DIR, "profiles") FIREFOX_PROFILES_DIR = os.path.join(ICE_DIR, "firefox") FIREFOX_FLATPAK_PROFILES_DIR = os.path.expanduser( "~/.var/app/org.mozilla.firefox/data/ice/firefox") EPIPHANY_PROFILES_DIR = os.path.join(ICE_DIR, "epiphany") FALKON_PROFILES_DIR = os.path.join(ICE_DIR, "falkon") ICONS_DIR = os.path.join(ICE_DIR, "icons") BROWSER_TYPE_FIREFOX, BROWSER_TYPE_FIREFOX_FLATPAK, BROWSER_TYPE_CHROMIUM, BROWSER_TYPE_EPIPHANY, BROWSER_TYPE_FALKON, BROWSER_TYPE_JAK = range( 6)
Developed as a part of GSoC Project License : GNU GPL version 3 connect AATINY85 module to IN1 and IN2 black wire to GND Green is SQR input (pin 2) Red is output (pin 3) Module can be powered using USB or external USB adapter. the second module can be powered fron first from (P2VUSB pin) pin P1 can be touched to groung to RESET ''' from __future__ import print_function import gettext gettext.bindtextdomain("expeyes") gettext.textdomain('expeyes') _ = gettext.gettext import time, math, sys if sys.version_info.major == 3: from tkinter import * #support for python 3 else: from Tkinter import * sys.path = [".."] + sys.path import expeyes.eyesj as eyes import expeyes.eyeplot as eyeplot import expeyes.eyemath as eyemath #from Tkinter import* #import expeyes.eyesj as eyes, expeyes.eyeplot as eyeplot, expeyes.eyemath as eyemath, time, math
sharedir = '/usr/share' if sys.argv[0]: execdir = os.path.dirname(os.path.realpath(sys.argv[0])) basedir = os.path.dirname(execdir) sharedir = os.path.join(basedir, 'share') if not os.path.exists(sharedir): sharedir = basedir localedir = os.path.join(sharedir, 'locale') import locale #for multilanguage support import gettext locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain('pdfshuffler', localedir) gettext.bindtextdomain('pdfshuffler', localedir) gettext.textdomain('pdfshuffler') _ = gettext.gettext APPNAME = 'PdfShuffler' # PDF-Shuffler, PDFShuffler, pdfshuffler VERSION = '0.7.0' WEBSITE = 'https://gna.org/projects/pdfshuffler/' LICENSE = 'GNU General Public License (GPL) Version 3.' try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk except: print('You do not have the required version of GTK+ installed.\n\n' + 'Installed GTK+ version is ' +
#!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function import sys import gi import gettext gettext.bindtextdomain('pyedpro', './locale/') gettext.textdomain('pyedpro') _ = gettext.gettext gi.require_version("Gtk", "3.0") from gi.repository import Gtk from gi.repository import GObject ( COLOR_RED, COLOR_GREEN, COLOR_BLUE ) = list(range(3)) ( SHAPE_SQUARE, SHAPE_RECTANGLE, SHAPE_OVAL, ) = list(range(3)) mained = None
from builtins import map, str, super import gettext import http.client import json from osdlyrics.lyricsource import BaseLyricSourcePlugin, SearchResult from osdlyrics.utils import get_proxy_settings, http_download _ = gettext.gettext NETEASE_HOST = 'music.163.com' NETEASE_SEARCH_URL = '/api/search/get' NETEASE_LYRIC_URL = '/api/song/lyric' gettext.bindtextdomain('osdlyrics') gettext.textdomain('osdlyrics') class NeteaseSource(BaseLyricSourcePlugin): """ Lyric source from music.163.com """ def __init__(self): super().__init__(id='netease', name=_('Netease')) def do_search(self, metadata): # type: (osdlyrics.metadata.Metadata) -> List[SearchResult] keys = [] if metadata.title: keys.append(metadata.title)
CENTER, CORNER, CORNERS from grammar import Grammar from pkg_resources import resource_filename, Requirement from glob import glob import random as r import locale import gettext SBOT_ROOT = resource_filename(Requirement.parse("shoebot"), "") APP = 'shoebot' DIR = sys.prefix + '/share/shoebot/locale' locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain(APP, DIR) # gettext.bindtextdomain(APP) gettext.textdomain(APP) _ = gettext.gettext LIB_DIRS = [ os.path.join(SBOT_ROOT, 'local', 'share', 'shoebot', 'lib'), os.path.join(SBOT_ROOT, 'lib'), os.path.join(SBOT_ROOT, 'share', 'shoebot', 'lib'), os.path.join(sys.prefix, 'share', 'shoebot', 'lib')] for LIB_DIR in LIB_DIRS: if os.path.isdir(LIB_DIR): sys.path.append(LIB_DIR) TOP_LEFT = 1 BOTTOM_LEFT = 2
def __init__(self): self.app = "manjaro-hello" self.dev = "--dev" in sys.argv # Dev mode activated ? # Load preferences if self.dev: self.preferences = read_json("data/preferences.json") self.preferences["data_path"] = "data/" self.preferences["desktop_path"] = os.getcwd( ) + "/{}.desktop".format(self.app) self.preferences["locale_path"] = "locale/" self.preferences["ui_path"] = "ui/{}.glade".format(self.app) else: self.preferences = read_json( "/usr/share/{}/data/preferences.json".format(self.app)) # Get saved infos self.save = read_json(self.preferences["save_path"]) if not self.save: self.save = {"locale": None} # Init window self.builder = Gtk.Builder.new_from_file(self.preferences["ui_path"]) self.builder.connect_signals(self) self.window = self.builder.get_object("window") # Subtitle of headerbar self.builder.get_object("headerbar").props.subtitle = ' '.join( get_lsb_infos()) # Load images if os.path.isfile(self.preferences["logo_path"]): logo = GdkPixbuf.Pixbuf.new_from_file( self.preferences["logo_path"]) self.window.set_icon(logo) self.builder.get_object("distriblogo").set_from_pixbuf(logo) self.builder.get_object("aboutdialog").set_logo(logo) for btn in self.builder.get_object("social").get_children(): icon_path = self.preferences["data_path"] + "img/" + btn.get_name( ) + ".png" self.builder.get_object(btn.get_name()).set_from_file(icon_path) for widget in self.builder.get_object("homepage").get_children(): if isinstance(widget, Gtk.Button) and \ widget.get_image_position() is Gtk.PositionType.RIGHT: img = Gtk.Image.new_from_file(self.preferences["data_path"] + "img/external-link.png") img.set_margin_left(2) widget.set_image(img) # Create pages self.pages = os.listdir("{}/pages/{}".format( self.preferences["data_path"], self.preferences["default_locale"])) for page in self.pages: scrolled_window = Gtk.ScrolledWindow() viewport = Gtk.Viewport(border_width=10) label = Gtk.Label(wrap=True) viewport.add(label) scrolled_window.add(viewport) scrolled_window.show_all() self.builder.get_object("stack").add_named(scrolled_window, page + "page") # Init translation self.default_texts = {} gettext.bindtextdomain(self.app, self.preferences["locale_path"]) gettext.textdomain(self.app) self.builder.get_object("languages").set_active_id( self.get_best_locale()) # Set autostart switcher state self.autostart = os.path.isfile( fix_path(self.preferences["autostart_path"])) self.builder.get_object("autostart").set_active(self.autostart) # Live systems if os.path.exists(self.preferences["live_path"]) and \ os.path.isfile(self.preferences["installer_path"]): self.builder.get_object("installlabel").set_visible(True) self.builder.get_object("install").set_visible(True) self.window.show()
mo_files = _glob( _path.join(location, 'locale', '*', 'LC_MESSAGES', lc_domain + '.mo')) if mo_files: return _path.join(location, 'locale') # del _path import locale locale.setlocale(locale.LC_ALL, '') language, encoding = locale.getlocale() del locale _LOCALE_DOMAIN = _NAME.lower() path = _find_locale_path(_LOCALE_DOMAIN) import gettext as _gettext _gettext.bindtextdomain(_LOCALE_DOMAIN, path) _gettext.textdomain(_LOCALE_DOMAIN) _gettext.install(_LOCALE_DOMAIN) try: unicode _ = lambda x: _gettext.gettext(x).decode('UTF-8') ngettext = lambda *x: _gettext.ngettext(*x).decode('UTF-8') except: _ = _gettext.gettext ngettext = _gettext.ngettext
# -*- coding: utf-8 -*- # Copyright (c) 2007 - Steve Frécinaux <*****@*****.**> # Copyright (c) 2010 - Kenny Meyer <*****@*****.**> # Licence: GPL2 or later from gi.repository import GObject, Gtk, Gedit import os.path import gettext from .store import Session try: from .gpdefs import * gettext.bindtextdomain(GETTEXT_PACKAGE, GP_LOCALEDIR) _ = lambda s: gettext.dgettext(GETTEXT_PACKAGE, s) except: _ = lambda s: s class SessionModel(Gtk.ListStore): OBJECT_COLUMN = 0 NAME_COLUMN = 1 N_COLUMNS = 2 def __init__(self, store): super(SessionModel, self).__init__(GObject.TYPE_PYOBJECT, str) self.store = store for session in store: row = {self.OBJECT_COLUMN: session, self.NAME_COLUMN: session.name} self.append(row.values()) self.store.connect_after('session-added', self.on_session_added)
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.INFO) # 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: PATH.set_paths() # set paths using basename PATH.set_paths(basepath, bool(INIPATH)) # keep track of python version during this transition if sys.version_info.major > 2: ver = 'Python 3' else: ver = 'Python 2' ################# # Screen specific ################# if INIPATH: LOG.info( 'green<Building A Linuxcnc Main Screen with {}>'.format(ver)) 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) 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.info('green<Building A VCP Panel with {}>'.format(ver)) # 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) self.hal = QComponent(self.halcomp) except: LOG.critical( "Asking for a HAL component using a name that already exists?") sys.exit(0) # initialize the window window = qt_makegui.VCPWindow(self.hal, PATH) # load optional user handler file if opts.usermod: LOG.debug('Loading the handler file') window.load_extension(opts.usermod) try: window.web_view = QWebView() except: window.web_view = None # 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.hal, 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() # call a HAL file after widgets built if opts.halfile: if opts.halfile[-4:] == ".tcl": cmd = ["haltcl", opts.halfile] else: cmd = ["halcmd", "-f", opts.halfile] res = subprocess.call(cmd, stdout=sys.stdout, stderr=sys.stderr) if res: print >> sys.stderr, "'%s' exited with %d" % (' '.join(cmd), res) sys.exit(res) # 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) if opts.usermod and "before_loop__" in dir(window.handler_instance): LOG.debug('''Calling the handler file's before_loop__ function''') window.handler_instance.before_loop__() LOG.info('Preference path: {}'.format(PATH.PREFS_FILENAME)) # start loop self.app.exec_() # now shut it all down self.shutdown()
def __init__(self): # i18n languages = [] lc, encoding = locale.getdefaultlocale() if lc: languages = [lc] languages += DEFAULT_LANGUAGES gettext.bindtextdomain(OCRFEEDER_COMPACT_NAME, LOCALE_DIR) gettext.textdomain(OCRFEEDER_COMPACT_NAME) language = gettext.translation(OCRFEEDER_COMPACT_NAME, LOCALE_DIR, languages = languages, fallback = True) _ = language.gettext self.EXPORT_FORMATS = {0: ('ODT', _('ODT')), 1: ('HTML', _('HTML')), 2: ('PDF', _('PDF')), 3: ('TXT', _('Plain Text'))} self.title = OCRFEEDER_STUDIO_NAME self.main_window = widgetPresenter.MainWindow() self.main_window.setTitle(self.title) self.document_generator_manager = DocumentGeneratorManager() self.configuration_manager = ConfigurationManager() self.ocr_engines_manager = OcrEnginesManager(self.configuration_manager) self.configuration_manager.loadConfiguration() user_engines_folder = self.configuration_manager.user_engines_folder self.engines_needing_update = \ self.ocr_engines_manager.makeEnginesFromFolder(user_engines_folder) self.ocr_engines = self.ocr_engines_manager.ocr_engines self.source_images_list_store = SourceImagesListStore() self.source_images_icon_view = SourceImagesSelectorIconView(self.source_images_list_store) self.source_images_icon_view.setDeleteCurrentPageFunction(self.deleteCurrentPage) self.source_images_icon_view.connect('drag_data_received', self.dragDataReceived) self.source_images_icon_view.connect('drag_drop', self.dragDrop) self.source_images_icon_view.get_model().connect('row-inserted', self.__pagesUpdatedCallback) self.source_images_icon_view.get_model().connect('row-deleted', self.__pagesUpdatedCallback) self.source_images_icon_view.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT, [('text/uri-list', 0, self.TARGET_TYPE_URI_LIST)], gtk.gdk.ACTION_COPY) self.source_images_icon_view.show() self.main_window.main_area_left.add_with_viewport(self.source_images_icon_view) self.images_selectable_area = {} self.source_images_controler = ImageReviewer_Controler(self.main_window, self.source_images_icon_view, self.ocr_engines, self.configuration_manager) self.project_name = None toolbar_callback_dict = {'recognizePage': self.__recognizePageAction, 'recognizeDocument': self.__recognizeDocumentAction, 'export_to_odt': self.exportToOdt} menubar_callback_dict = {'exit': self.quit, 'add_image': self.addImage, 'export_to_odt': self.exportToOdt, 'edit_page': self.choosePageSize, 'delete_page': self.deleteCurrentPage, 'export_dialog': self.exportDialog, 'add_folder': self.addFolder, 'import_pdf': self.importPdf, 'save_project': self.saveProject, 'save_project_as': self.saveProjectAs, 'open_project': self.openProject, 'append_project': self.appendProject,'clear': self.clear, 'unpaper': self.unpaper, 'preferences': self.preferences, 'about': self.about, 'ocr_engines': self.ocrEngines, 'zoom_in': self.zoomIn, 'zoom_out': self.zoomOut, 'zoom_fit': self.zoomFit, 'reset_zoom': self.resetZoom, 'recognize_areas': self.source_images_controler.recognizeSelectedAreas, 'import_from_scanner': self.importFromScanner, 'select_next_area': self.source_images_controler.selectNextArea, 'select_previous_area': self.source_images_controler.selectPreviousArea, 'select_all_areas': self.source_images_controler.selectAllAreas, 'delete_selected_areas': self.source_images_controler.deleteSelectedAreas, 'image_deskewer': self.source_images_controler.deskewCurrentImage, 'copy_to_clipboard': self.source_images_controler.copyRecognizedTextToClipboard, 'spell_checker': self.spellChecker, 'help_contents': self.showHelpContents, 'move_page_down': self.movePageDown, 'move_page_up': self.movePageUp, 'select_next_page': self.selectNextPage, 'select_previous_page': self.selectPreviousPage, } self.main_window.setHeader(menubar_callback_dict, toolbar_callback_dict) self.main_window.setDestroyEvent(self.quit) parser = OptionParser(version = '%prog ' + OCRFEEDER_STUDIO_VERSION) parser.add_option('-i', '--images', dest = 'images', action = 'append', type = 'string', metavar = 'IMAGE1 [IMAGE2, ...]', default = [], help = 'images to be automatically added on start-up. ' 'Use the option before every image path.') parser.add_option('-d', '--dir', dest = 'directory', action = 'store', type = 'string', help = 'directory with images to be added' ' automatically on start-up') options, args = parser.parse_args() imgs = options.images if imgs: self.__addImagesToReviewer(imgs) if options.directory: self.__addImagesToReviewer( lib.getImagesFromFolder(options.directory)) self.main_window.setHasSelectedBoxes(False) self.main_window.setHasContentBoxes(False) self.main_window.setNumberOfPages( self.source_images_icon_view.getNumberOfPages()) # Show dialog to choose system-wide OCR engines when no engine was found if not self.ocr_engines: engines = self.configuration_manager.getEnginesInSystem() if engines: add_engines_dialog = widgetPresenter.SystemEnginesDialog(engines) response = add_engines_dialog.run() if response == gtk.RESPONSE_ACCEPT: for engine in add_engines_dialog.getChosenEngines(): self.ocr_engines_manager.addNewEngine(engine) add_engines_dialog.destroy() else: self.__askForEnginesMigration()
lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID() lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID() if lcid_user != lcid_system: lcids = [lcid_user, lcid_system] else: lcids = [lcid_user] language = filter( None, [locale.windows_locale.get(i) for i in lcids]) or None # Set up environment variable os.environ['LANGUAGE'] = ':'.join(language) try: locale.setlocale(locale.LC_ALL, '') if not sys.platform.startswith('win'): locale.bindtextdomain(__GETTEXT_DOMAIN__, __LOCALE_PATH__) locale.bind_textdomain_codeset(__GETTEXT_DOMAIN__, 'UTF-8') gettext.bindtextdomain(__GETTEXT_DOMAIN__, __LOCALE_PATH__) gettext.bind_textdomain_codeset(__GETTEXT_DOMAIN__, 'UTF-8') gettext.textdomain(__GETTEXT_DOMAIN__) gettext.install(__GETTEXT_DOMAIN__, __LOCALE_PATH__, unicode=1) if sys.platform.startswith('win'): try: import ctypes libintl = ctypes.cdll.LoadLibrary("intl.dll") libintl.bindtextdomain(__GETTEXT_DOMAIN__, __LOCALE_PATH__) libintl.bind_textdomain_codeset(__GETTEXT_DOMAIN__, 'UTF-8') except: print("Error Loading translations into gtk.builder files") except Exception as e: #locale.setlocale(locale.LC_ALL, 'C') gettext.install(__GETTEXT_DOMAIN__, __LOCALE_PATH__) #_ = lambda s: s
MACHINE_STATUS_OFFLINE = 0 MACHINE_STATUS_AVAIL = 1 MACHINE_STATUS_BUSY = 2 MACHINE_STATUS_AWAY = 3 ##APP APP_NAME = 'OpenLanhouse' APP_SITE = 'http://openlanhouse.org' APP_COPYRIGHT = 'OpenLanhouse - Copyright (c) 2007-2011' I18N_APP = 'openlh-server' ##Internacionalize locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain(I18N_APP, LOCALE_PATH) gettext.textdomain(I18N_APP) global _ _ = gettext.gettext language = locale.setlocale(locale.LC_ALL, '') end = language.find('.') language = language[:end] ##End internacionalize ##APP Proprerties APP_COMMENTS = _('a Free LAN House Manager') CLIENT_APP_NAME = _('OpenLanHouse - Client') MANAGER_APP_NAME = _('OpenLanHouse - Administration') MIN_NICK = 4
def init_gettext(localepath): """Initialize locales and gettext. This must be done before importing any translated python modules (to get global strings translated, especially brushsettings.py). """ import gettext import locale import lib.i18n # Required in Windows for the "Region and Language" settings # to take effect. lib.i18n.set_i18n_envvars() lib.i18n.fixup_i18n_envvars() # Internationalization # Source of many a problem down the line, so lotsa debugging here. logger.debug("localepath: %r", localepath) logger.debug("getdefaultlocale(): %r", locale.getdefaultlocale()) # Set the user's preferred locale. # https://docs.python.org/2/library/locale.html # Required in Windows for the "Region and Language" settings # to take effect. try: setlocale_result = locale.setlocale(locale.LC_ALL, '') except locale.Error: logger.exception("setlocale(LC_ALL, '') failed") else: logger.debug("setlocale(LC_ALL, ''): %r", setlocale_result) # More debugging: show the state after setlocale(). logger.debug( "getpreferredencoding(): %r", locale.getpreferredencoding(do_setlocale=False), ) locale_categories = [ s for s in dir(locale) if s.startswith("LC_") and s != "LC_ALL" ] for category in sorted(locale_categories): logger.debug( "getlocale(%s): %r", category, locale.getlocale(getattr(locale, category)), ) # Low-level bindtextdomain with paths. # This is still required to hook GtkBuilder up with translated # strings; the gettext() way doesn't cut it for external stuff # yanked in over GI. # https://bugzilla.gnome.org/show_bug.cgi?id=574520#c26 bindtextdomain = None bind_textdomain_codeset = None textdomain = None # Try the POSIX/Linux way first. try: bindtextdomain = locale.bindtextdomain bind_textdomain_codeset = locale.bind_textdomain_codeset textdomain = locale.textdomain except AttributeError: logger.warning("No bindtextdomain builtins found in module 'locale'.") logger.info( "Trying platform-specific fallback hacks to find " "bindtextdomain funcs.", ) # Windows Python binaries tend not to expose bindtextdomain and # its buddies anywhere they can be called. if sys.platform == 'win32': libintl = None import ctypes libnames = [ 'libintl-8.dll', # native for MSYS2's MINGW32 'libintl.dll', # no known cases, but a potential fallback 'intl.dll', # some old recipes off the internet ] for libname in libnames: try: libintl = ctypes.cdll.LoadLibrary(libname) bindtextdomain = libintl.bindtextdomain bindtextdomain.argtypes = ( ctypes.c_char_p, ctypes.c_char_p, ) bindtextdomain.restype = ctypes.c_char_p bind_textdomain_codeset = libintl.bind_textdomain_codeset bind_textdomain_codeset.argtypes = ( ctypes.c_char_p, ctypes.c_char_p, ) bind_textdomain_codeset.restype = ctypes.c_char_p textdomain = libintl.textdomain textdomain.argtypes = (ctypes.c_char_p, ) textdomain.restype = ctypes.c_char_p except Exception: logger.exception( "Windows: attempt to load bindtextdomain funcs " "from %r failed (ctypes)", libname, ) else: logger.info( "Windows: found working bindtextdomain funcs " "in %r (ctypes)", libname, ) break else: logger.error( "No platform-specific fallback for locating bindtextdomain " "is known for %r", sys.platform, ) # Bind text domains, i.e. tell libintl+GtkBuilder and Python's where # to find message catalogs containing translations. textdomains = [ ("mypaint", localepath), # Open question: do we need to bind libmypaint's stuff here too, # now that we have gone sharedlib? It seems to work correctly # under Linux from Python code without an explicit pile of binds. # ("libmypaint", localepath_brushlib), ] defaultdom = "mypaint" codeset = "UTF-8" for dom, path in textdomains: # Some people choose not to install any translation files. if not os.path.isdir(path): logger.warning( "No translations for %s. Missing locale dir %r.", dom, path, ) continue # Only call the C library gettext setup funcs if there's a # complete set from the same source. # Required for translatable strings in GtkBuilder XML # to be translated. if bindtextdomain and bind_textdomain_codeset and textdomain: assert os.path.exists(path) assert os.path.isdir(path) if sys.platform == 'win32': p = bindtextdomain(dom.encode('utf-8'), path.encode('utf-8')) c = bind_textdomain_codeset(dom.encode('utf-8'), codeset.encode('utf-8')) else: p = bindtextdomain(dom, path) c = bind_textdomain_codeset(dom, codeset) logger.debug("C bindtextdomain(%r, %r): %r", dom, path, p) logger.debug( "C bind_textdomain_codeset(%r, %r): %r", dom, codeset, c, ) # Call the implementations in Python's standard gettext module # too. This has proper cross-platform support, but it only # initializes the native Python "gettext" module. # Required for marked strings in Python source to be translated. # See http://docs.python.org/release/2.7/library/locale.html p = gettext.bindtextdomain(dom, path) c = gettext.bind_textdomain_codeset(dom, codeset) logger.debug("Python bindtextdomain(%r, %r): %r", dom, path, p) logger.debug( "Python bind_textdomain_codeset(%r, %r): %r", dom, codeset, c, ) if bindtextdomain and bind_textdomain_codeset and textdomain: if sys.platform == 'win32': d = textdomain(defaultdom.encode('utf-8')) else: d = textdomain(defaultdom) logger.debug("C textdomain(%r): %r", defaultdom, d) d = gettext.textdomain(defaultdom) logger.debug("Python textdomain(%r): %r", defaultdom, d)
def localeInit(): gettext.bindtextdomain( "OFDb", resolveFilename(SCOPE_PLUGINS, "Extensions/OFDb/locale"))
import gettext from lios import macros gettext.bindtextdomain(macros.app_name, '/usr/share/locale') gettext.textdomain(macros.app_name) _ = gettext.gettext
import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print _('This is a translatable string.')
def localeInit(): environ["LANGUAGE"] = language.getLanguage()[:2] bindtextdomain( "MountManager", resolveFilename(SCOPE_PLUGINS, "SystemPlugins/MountManager/locale"))
import sys import apt import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, Gdk, GdkPixbuf #import concurrent.futures import threading from time import sleep import os from handysoft_utils import * from soft_install import * import gettext gettext.bindtextdomain(appname, '/usr/share/locale') gettext.textdomain(appname) _ = gettext.gettext class DialogPackage(Gtk.Dialog): '''permet d'afficher une fenêtre avec des informations détaillées sur un paquet''' def change_bg_on_focus(self,widget,b): widget.modify_bg(Gtk.StateFlags.NORMAL, self.selected_bg_color) widget.modify_bg(Gtk.StateFlags.PRELIGHT, self.selected_bg_color) def change_bg_on_focus_leave(self,widget,b): widget.modify_bg(Gtk.StateFlags.NORMAL, None) widget.modify_bg(Gtk.StateFlags.PRELIGHT, None)
def localeInit(): lang = language.getLanguage() os.environ["LANGUAGE"] = lang[:2] gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE)) gettext.textdomain("enigma2") gettext.bindtextdomain("MediaPlayer2", "%s%s" % (resolveFilename(SCOPE_PLUGINS), "Extensions/MediaPlayer2/locale"))