def get_file_items(self, window, files): paths = [] for file in files: if self.valid_file(file): path = urllib.unquote(file.get_uri()[7:]) paths.append(path) if len(paths) < 1: return locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain(APP) gettext.textdomain(APP) _ = gettext.gettext tooltip_message = gettext.ngettext('Sign selected file with Digidoc3 Client', 'Sign selected files with Digidoc3 Client', len(paths)) item = nautilus.MenuItem('DigidocSigner', _('Sign with ID card'), tooltip_message) item.set_property('icon', 'qdigidoc-client') item.connect('activate', self.menu_activate_cb, paths) return item,
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 __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)
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, title, data_path=None): self.title = title self.data_path = data_path self.direction = NEXT self.gettext_domain = "checkbox" gettext.textdomain(self.gettext_domain)
def main(): app = wx.App() gettext.bindtextdomain('uhope') gettext.textdomain('uhope') microhope(None,-1,'uHOPE','size') app.MainLoop()
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,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 bindtextdomain(app_name, lang='',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. """ module_logger.debug("bindtextdomain called with: %s %s %s" %\ (app_name, lang,locale_dir)) module_logger.debug("Setting gvr_gtk to locale: %s" % lang) try: import locale import gettext ## locale.setlocale(locale.LC_ALL, lang) gtk.glade.bindtextdomain(app_name, locale_dir) gettext.textdomain(app_name) gettext.install(app_name, locale_dir, unicode=1) except (IOError,locale.Error), e: print "Warning", app_name, e __builtin__.__dict__["_"] = lambda x : x
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 set_locales(self): """internationalization config. Use only once.""" domain = self.distro + '-installer' bindtextdomain(domain, LOCALEDIR) textdomain(domain) install(domain, LOCALEDIR, unicode=1)
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_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_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_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__(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__(self, request): self.request = request self.collection = self.get_collection() localedir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'locale') gettext.bindtextdomain('gecoscc', localedir) gettext.textdomain('gecoscc') self._ = gettext.gettext
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 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 __init__(self): # i18n languages = [] lc, encoding = locale.getdefaultlocale() if lc: languages = [lc] languages += constants.DEFAULT_LANGUAGES gettext.bindtextdomain(constants.SF_COMPACT_NAME, constants.LOCALE_DIR) gettext.textdomain(constants.SF_COMPACT_NAME) language = gettext.translation(constants.SF_COMPACT_NAME, constants.LOCALE_DIR, languages = languages, fallback = True) _ = language.gettext self.series_manager = SeriesManager() self.settings = Settings() self.settingsWrapper = SettingsWrapper() load_conf_item = AsyncItem(self.settings.load, (constants.SF_CONF_FILE,), self._settings_load_finished) load_shows_item = AsyncItem(self.series_manager.load, (constants.SF_DB_FILE,), self._load_finished) self.request = AsyncWorker(True) self.request.queue.put(load_conf_item) self.request.queue.put(load_shows_item) self.request.start() self.version = constants.SF_VERSION
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 _
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) if metadata.artist:
#!/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
# 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)
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 ' + '.'.join([str(Gtk.get_major_version()), \
# This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. ### END LICENSE import gettext from gettext import gettext as _ gettext.textdomain('mangar') from gi.repository import Gtk # pylint: disable=E0611 from gi.repository import Gio # pylint: disable=E0611 from gi.repository import Gdk from gi.repository import GObject from gi.repository import Notify import logging logger = logging.getLogger('mangar') from mangar_lib import Window from mangar.AboutMangarDialog import AboutMangarDialog from mangar.PreferencesMangarDialog import PreferencesMangarDialog
#!/usr/bin/python3 import getpass import sys import os from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QComboBox,QPushButton,QVBoxLayout,\ QDialog,QGridLayout,QLineEdit,QFileDialog,QCheckBox,QFrame from PyQt5 import QtGui from PyQt5.QtCore import QSize,Qt import gettext import subprocess import locale QString=type("") QInt=type(0) TAB_BTN_SIZE=96 BTN_SIZE=128 gettext.textdomain('lliuwin') _ = gettext.gettext SRC="/usr/share/lliuwin" RSRC="%s/rsrc"%SRC #Translations WLC_MSG=_("Welcome to LliureX 19. Let's do some final adjustments") USR_MSG=_("Configure new account") AVA_MSG=_("You can also define an avatar for your user") LNG_MSG=_("Locale") HOST_MSG=_("Hostname") ERR_PASS_MATCH=_("Passwords don't match") ERR_PASS_LEN=_("Password length must be at least 6 characters long") ERR_PASS_LONG=_("Password length must be 30 characters maximun") ERR_USR_LEN=_("User name must be at least 2 characters long")
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
# This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. ### END LICENSE import gtk from transcribe.helpers import get_builder import gettext from gettext import gettext as _ gettext.textdomain('transcribe') class AboutTranscribeDialog(gtk.AboutDialog): __gtype_name__ = "AboutTranscribeDialog" def __new__(cls): """Special static method that's automatically called by Python when constructing a new instance of this class. Returns a fully instantiated AboutTranscribeDialog object. """ builder = get_builder('AboutTranscribeDialog') new_object = builder.get_object("about_transcribe_dialog") new_object.finish_initializing(builder) return new_object
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # This file is in the public domain ### END LICENSE from gi.repository import Gtk # pylint: disable=E0611 from tilegen_lib.helpers import get_builder import gettext from gettext import gettext as _ gettext.textdomain('tilegen') from tilegen import rendering import mapnik as mapnik from tilegen import functions as func from tilegen import xmlFunctions as xmlFunc from tilegen import gdal_functions as gdal from tilegen import postgreFunctions as postgre import os from multiprocessing import Pool, Process import multiprocessing import time import pprocess import xml.etree.ElementTree as xml import time from threading import Thread
# PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. ### END LICENSE """ This module contain classes related to the creation, management and displaying of properties in emulica. """ import random, logging, locale, re import gettext from gettext import gettext as _ gettext.textdomain('emulica') import emulation gettext.install('emulica') logger = logging.getLogger('emulica.properties') class Registry(dict): """ Properties can be attached to every products and module (including models). They basically consist in a (name, value) pair. Moreover, a PropertyDisplay can also be used. If so the property is said to be "displayable"; such properties can be presented in the user interface, and modified. Properties that don't have any PropertyDisplay object associated are not displayed by the PropertyWindow UI.
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # This file is in the public domain ### END LICENSE # This is your preferences dialog. # # Define your preferences in # data/glib-2.0/schemas/net.launchpad.myapp.gschema.xml # See http://developer.gnome.org/gio/stable/GSettings.html for more info. from gi.repository import Gio # pylint: disable=E0611 import gettext from gettext import gettext as _ gettext.textdomain('myapp') import logging logger = logging.getLogger('myapp') from myapp_lib.PreferencesDialog import PreferencesDialog class PreferencesMyappDialog(PreferencesDialog): __gtype_name__ = "PreferencesMyappDialog" def finish_initializing(self, builder): # pylint: disable=E1002 """Set up the preferences dialog""" super(PreferencesMyappDialog, self).finish_initializing(builder) # Bind each preference widget to gsettings
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()
#!/usr/bin/env python3 import sys import os from PyQt5 import uic from PyQt5.QtGui import QIcon,QPixmap from PyQt5.QtCore import Qt,QEvent,QPoint,QSize from PyQt5.QtWidgets import QLabel, QWidget, QToolButton,QVBoxLayout,QHBoxLayout,QMenu,QToolTip from . import settings import gettext gettext.textdomain(settings.TEXT_DOMAIN) _ = gettext.gettext class ConfigurationBox(QWidget): def __init__(self): super(ConfigurationBox, self).__init__() # Call the inherited classes __init__ method self.core=Core.Core.get_core() ui_file=self.core.rsrc_dir+"configurationBox.ui" uic.loadUi(ui_file, self) # Load the .ui fil self.boxConfigurations=self.findChild(QVBoxLayout,'configurationBox') self.scrollArea=self.findChild(QWidget,'scrollAreaWidgetContents') self.scrollArea.setStyleSheet("background-color:white") self.boxConfigurations.setAlignment(Qt.AlignTop) def drawConfigurationList(self): self.jre_alternatives={} self.firefox_alternatives={} self.cpanel_alternatives={}
# Library General Public License for more details. # # 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 from gi.repository import Gtk, GObject, Gio, GdkPixbuf, Gdk, GMenu, GLib import cgi import os import gettext import subprocess import shutil 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 self.editor = MenuEditor()
# # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. ### END LICENSE # This is your preferences dialog. # # Define your preferences in # data/glib-2.0/schemas/net.launchpad.pastebin.gschema.xml # See http://developer.gnome.org/gio/stable/GSettings.html for more info. from gi.repository import Gio # pylint: disable=E0611 import gettext from gettext import gettext as _ gettext.textdomain('pastebin') import logging logger = logging.getLogger('pastebin') from pastebin_lib.PreferencesDialog import PreferencesDialog class PreferencesPastebinDialog(PreferencesDialog): __gtype_name__ = "PreferencesPastebinDialog" def finish_initializing(self, builder): # pylint: disable=E1002 """Set up the preferences dialog""" super(PreferencesPastebinDialog, self).finish_initializing(builder) # Bind each preference widget to gsettings
''' expEYES program Author : Ajith Kumar B.P, [email protected] License : GNU GPL version 3 ''' import gettext gettext.bindtextdomain("expeyes") gettext.textdomain('expeyes') _ = gettext.gettext from Tkinter import * import expeyes.eyes as eyes, expeyes.eyeplot as eyeplot, expeyes.eyemath as eyemath, time, sys TIMER = 10 WIDTH = 600 # width of drawing canvas HEIGHT = 400 # height VSET = 0 # this will change in the loop VSETMIN = 0 # may change this to -5 for zeners VSETMAX = 4.5 STEP = 0.050 # 50 mV MINX = 0 # may change this to -5 for zeners MAXX = 3 # No diode will go beyond this MINY = 0 # may change this to -5 for zeners MAXY = 5 # Maximum possible current history = [] # Data store trial = 0 # trial number data = [[], []] # Current & Voltage index = 0 running = False
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. ### END LICENSE import logging logger = logging.getLogger('lightread') import urllib import gettext from gettext import gettext as _ gettext.textdomain('lightread') import subprocess, os, json from gi.repository import Gtk, Gdk, WebKit, Notify, Soup # pylint: disable=E0611 try: from gi.repository import Unity, Dbusmenu except ImportError: pass from lightread_lib import Window from lightread_lib.helpers import get_media_file from lightread.AboutLightreadDialog import AboutLightreadDialog try: from lightread.LightreadIndicator import LightreadIndicator except ImportError: pass
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 print("Error setting up the translations: %s" % (e))
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()
# Depends: python3-pyinotify # Documentation: http://pyinotify.sourceforge.net/ import pyinotify from os.path import abspath, dirname, join from gi.repository import GObject, GdkPixbuf # Need to initiate threads for Gtk, # or else EventHandler will not get called from ThreadedNotifier GObject.threads_init() # i18n: http://docs.python.org/3/library/gettext.html import gettext from gettext import gettext as _ gettext.textdomain('updatemanager') class EventHandler(pyinotify.ProcessEvent): def __init__(self, statusIcon, umglobal, umrefresh): self.executing = False self.statusIcon = statusIcon self.umglobal = umglobal self.umrefresh = umrefresh def process_IN_CREATE(self, event): print((">>> process_IN_CREATE: %s" % event.pathname)) if not self.executing: if event.pathname == self.umglobal.umfiles['umrefresh']: print(("Creating: %s" % event.pathname)) self.executing = True
def test_textdomain(self): self.assertEqual(gettext.textdomain(), 'gettext')
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(): 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"))
import gettext from lios import macros gettext.bindtextdomain(macros.app_name, '/usr/share/locale') gettext.textdomain(macros.app_name) _ = gettext.gettext
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 get_theme_colors(self):
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 MAX_NICK = 18
""" 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 colorsys import Utils, CSSManager COLOUR_PICKER_LAYOUT_FILE = "resources/colour_picker.gtkbuilder" COLOUR_PICKER_CSS_FILE = "colour_picker.css" COLOUR_PICKER_BUTTON_CSS_FILE = "colour_picker_button.css" WIDTH_REQUEST = 500 HEIGHT_REQUEST = 400 button_css = """ button { background-color: $bgcolour; background-image: none; margin-right: 10px; border: 1px solid #202020; }
import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print _('This is a translatable string.')
from gwibber.microblog.util import facelib from gwibber.microblog.util import resources from gwibber.microblog.util.const import * # Try to import * from custom, install custom.py to include packaging # customizations like distro API keys, etc try: from gwibber.microblog.util.custom import * except: pass import json, urlparse, gnomekeyring, uuid import gettext from gettext import gettext as _ if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset('gwibber', 'UTF-8') gettext.textdomain('gwibber') """ gtk.gdk.threads_init() APP_KEY = "71b85c6d8cb5bbb9f1a3f8bbdcdd4b05" """ class AccountWidget(gtk.VBox): """AccountWidget: A widget that provides a user interface for configuring facebook accounts in Gwibber """ def __init__(self, account=None, dialog=None): """Creates the account pane for configuring facebook accounts""" gtk.VBox.__init__(self, False, 20) self.ui = gtk.Builder() self.ui.set_translation_domain("gwibber")
# -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*- from ubiquity import misc, plugin, validation import os import inspect import gettext NAME = 'lliurexSystemAddons' AFTER = 'lliurexExtrapackages' BEFORE = 'usersetup' WEIGHT = 40 gettext.textdomain('ubilliurexsystemaddons') _ = gettext.gettext class PageKde(plugin.PluginUI): plugin_title = 'lliurex/text/breadcrumb_systemAddons' plugin_breadcrumb = 'lliurex/text/breadcrumb_systemAddons' plugin_prefix = 'lliurex/text' def __init__(self, controller, *args, **kwargs): from PyQt5.QtGui import QPixmap, QIcon, QFont from PyQt5.QtWidgets import QWidget, QFrame, QVBoxLayout, QScrollArea, QGridLayout, QHBoxLayout, QLabel, QSizePolicy, QRadioButton from PyQt5.QtCore import Qt self.configuration = { 'flash': True, 'statistics': True, 'inventory': False } self.controller = controller