Ejemplo n.º 1
0
def init_submodule(name):
    if moduledir != pkgdatadir:
        # Running from source tree, add './name' to search paths

        submoduledir = GLib.build_filenamev([_base, name])
        libpath = GLib.build_filenamev([submoduledir, '.libs'])
        GIRepository.Repository.prepend_search_path(submoduledir)
        GIRepository.Repository.prepend_library_path(libpath)
    else:
        # Running installed, submodule is in $(pkglibdir), nothing to do
        pass
Ejemplo n.º 2
0
def init_submodule(name):
    if moduledir != pkgdatadir:
        # Running from source tree, add './name' to search paths

        submoduledir = GLib.build_filenamev([_base, name])
        libpath = GLib.build_filenamev([submoduledir, ".libs"])
        GIRepository.Repository.prepend_search_path(submoduledir)
        GIRepository.Repository.prepend_library_path(libpath)
    else:
        # Running installed, submodule is in $(pkglibdir), nothing to do
        pass
def main():
    ext_path = GLib.path_get_dirname(os.path.realpath(__file__))

    md_file = Gio.file_new_for_path(GLib.build_filenamev([ ext_path, MD_NAME ]))
    [ values, _, err_str ] = read_json_file(md_file)

    # look for an existing locale directory
    locale_dirs = [ GLib.build_filenamev([ ext_path, LOCALE_SUBDIR ]) ]
    if err_str != None:
        print(err_str)
    else:
        if values['system-locale-dir'] != None:
            locale_dirs += [ values['system-locale-dir'] ]

    if values['gettext-domain'] != None:
        for i in range(len(locale_dirs)):
            directory = Gio.file_new_for_path(locale_dirs[i])

            if (directory.query_file_type(Gio.FileQueryInfoFlags.NONE, None) ==
                    Gio.FileType.DIRECTORY):
                gettext.textdomain(values['gettext-domain'])
                gettext.bindtextdomain(values['gettext-domain'],
                    directory.get_path())
                break

    parser = OptionParser(g(ERR_USAGE),
        description = "",
        option_list = [
            make_option('--file', '-f',
                type = 'filename',
                action = 'store',
                dest = 'filename',
                help=g(ERR_FILE_HELP)
            )
        ])
    try:
        parser.parse_args()
    except Exception as e:
        sys.stderr.write("%s\n" % g(ERR_WRONG_ARGS))
        return

    if parser.values.filename == None:
        filename = GLib.build_filenamev(DEFAULT_OPTION_FILE_PARTS)
        sys.stderr.write(g(WARN_DEF_OPT_FILE) % filename)
    else:
        filename = parser.values.filename

    configurator = Configurator(filename)
    configurator.run(None)
Ejemplo n.º 4
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(),
                                                  "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))

        Grl.init(None)
        self.options = Grl.OperationOptions()
        self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY |
                                          Grl.ResolutionFlags.IDLE_RELAY)

        self.full_options = Grl.OperationOptions()
        self.full_options.set_resolution_flags(Grl.ResolutionFlags.FULL |
                                               Grl.ResolutionFlags.IDLE_RELAY)

        self.sources = {}
        self.blacklist = ['grl-filesystem', 'grl-bookmarks', 'grl-metadata-store', 'grl-podcasts']
        self.tracker = None
        self.changed_media_ids = []
        self.pending_event_id = 0
        self.changes_pending = {'Albums': False, 'Artists': False, 'Songs': False}
        self.pending_changed_medias = []

        self.registry = Grl.Registry.get_default()

        self.sparqltracker = TrackerWrapper().tracker
Ejemplo n.º 5
0
    def new_record_setup_done(self, button):

        self.currentRecording.close()

        dateStamp = datetime.today().strftime("%d-%m-at-%Hh%Mm")
        currentRecording = self.currentRecording

        finalFile = GLib.build_filenamev([
            self.projectDir,
            currentRecording.recordingTitle + dateStamp + ".webm"
        ])

        finalFile = self.make_unique_file(finalFile)

        self.listItr = self.listStore.append([
            currentRecording.recordingTitle,
            dateStamp,
            0,  #duration
            False
        ])

        self.mainWindow.iconify()
        self.icon.set_visible(True)

        self.primary = isrRecord.Record(finalFile, currentRecording.player,
                                        self.record_stopped_cb)

        if (self.primary is not None):
            self.primary.record(1)
            self.isRecording += 1
            self.stopRecordButton.show()
            self.recordingInfoBar.show()
            self.eosSpinner.hide()
            self.enable_buttons(False)
Ejemplo n.º 6
0
    def __init__ (self, bus, engine, datadir, gettext_package):
        self.__config = Config(bus, engine, self.on_value_changed)

        ui_file = GLib.build_filenamev([datadir, "setup.ui"])
        self.__builder = Gtk.Builder()
        self.__builder.set_translation_domain(gettext_package)
        self.__builder.add_from_file(ui_file)

        for option in options:
            prepare_func = getattr(self, "prepare_%s" % option["widget"])
            prepare_func(option)

        self.__window = self.__builder.get_object("setup_dialog")
        self.__window.set_title(titles[engine])

        try:
            # Pretend to be a GNOME Control Center dialog if appropriate
            self.gnome_cc_xid = int(GLib.getenv('GNOME_CONTROL_CENTER_XID'))
            self.__window.set_wmclass('gnome-control-center',
                                      'Gnome-control-center')
            self.__window.set_modal(True)
            self.__window.connect('notify::window', self.set_transient)
            self.__window.set_type_hint(Gdk.WindowTypeHint.DIALOG)

        except:
            # No problem here, we're just a normal dialog
            pass

        self.__window.show()
Ejemplo n.º 7
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(),
                                                  "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))
        self.options = Grl.OperationOptions()
        self.options.set_flags(Grl.ResolutionFlags.FAST_ONLY |
                               Grl.ResolutionFlags.IDLE_RELAY)

        self.full_options = Grl.OperationOptions()
        self.full_options.set_flags(Grl.ResolutionFlags.FULL |
                                    Grl.ResolutionFlags.IDLE_RELAY)

        self.sources = {}
        self.tracker = None
        self.changed_media_ids = []
        self.pending_event_id = 0

        self.registry = Grl.Registry.get_default()
        self.registry.connect('source_added', self._on_source_added)
        self.registry.connect('source_removed', self._on_source_removed)

        try:
            self.registry.load_all_plugins()
        except GLib.GError:
            logger.error('Failed to load plugins.')
        if self.tracker is not None:
            logger.debug("tracker found")
Ejemplo n.º 8
0
    def new_record_setup_done (self, button):

        self.currentRecording.close ()

        dateStamp = datetime.today().strftime ("%d-%m-at-%Hh%Mm")
        currentRecording = self.currentRecording

        finalFile = GLib.build_filenamev ([self.projectDir,
                                           currentRecording.recordingTitle+dateStamp+".webm"])

        finalFile = self.make_unique_file (finalFile)

        self.listItr = self.listStore.append ([currentRecording.recordingTitle,
                                               dateStamp,
                                               0, #duration
                                               False])

        self.mainWindow.iconify ()
        self.icon.set_visible (True)

        self.primary = isrRecord.Record (finalFile,
                                         currentRecording.player,
                                         self.record_stopped_cb)

        if (self.primary is not None):
            self.primary.record (1)
            self.isRecording += 1
            self.stopRecordButton.show ()
            self.recordingInfoBar.show ()
            self.eosSpinner.hide ()
            self.enable_buttons (False)
Ejemplo n.º 9
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(),
                                                  "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))
        self.options = Grl.OperationOptions()
        self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY |
                                          Grl.ResolutionFlags.IDLE_RELAY)

        self.full_options = Grl.OperationOptions()
        self.full_options.set_resolution_flags(Grl.ResolutionFlags.FULL |
                                               Grl.ResolutionFlags.IDLE_RELAY)

        self.sources = {}
        self.blacklist = ['grl-filesystem', 'grl-bookmarks', 'grl-metadata-store', 'grl-podcasts']
        self.tracker = None
        self.changed_media_ids = []
        self.pending_event_id = 0
        self.changes_pending = {'Albums': False, 'Artists': False, 'Songs': False}
        self.pending_changed_medias = []

        self.registry = Grl.Registry.get_default()

        self.sparqltracker = TrackerWrapper().tracker
Ejemplo n.º 10
0
    def get_dest_file(self):
        """
        Create / find the file used to store lights.
        """

        data_dir = GLib.get_user_config_dir()
        dest = GLib.build_filenamev([data_dir, "lights.json"])
        return Gio.File.new_for_path(dest)
Ejemplo n.º 11
0
 def __format_row(self, a):
     gmap = {'feed':'missing', 'category':'gtk-directory'}
     # icon
     try:
         stock = self.__setup_icons(GLib.build_filenamev([FAVICON_PATH, a['id']]), a['id'])
         if stock:
             gmap[a['id']] = a['id']
     except Exception, e:
         self.log.exception(e)
Ejemplo n.º 12
0
 def records_set_fields(self, songs):
     for song in songs:
         gfile = Gio.File.new_for_path(
             GLib.build_filenamev(
                 [self.unit.unit_songlist.config.music_dir, song['file']]))
         if gfile.query_exists():
             song['_gfile'] = gfile
         else:
             song['_status'] = self.RECORD_UNDEFINED
     super().records_set_fields(songs)
Ejemplo n.º 13
0
 def __init__(self, uri, artist, album, callback, data=None):
     self.uri = uri
     self.artist = artist
     self.album = album
     self.callback = callback
     self.data = data
     self.callbacks = []
     self.path = ''
     self.key = AlbumArtCache.get_default()._keybuilder_funcs[0].__call__(artist, album)
     self.path = GLib.build_filenamev([AlbumArtCache.get_default().cacheDir, self.key])
     self.stream = None
     self.started = False
Ejemplo n.º 14
0
def urlretrieve(url):
    url_file = Gio.File.new_for_uri(url)
    outputfile = url_file.get_basename()
    local_outputfilename = GLib.build_filenamev([os.environ['ABS_TOP_SRCDIR'], '..', 'xmimsim.wiki', outputfile])
    local_outputfile = Gio.File.new_for_path(local_outputfilename)
    local_outputfile_copy = Gio.File.new_for_path(outputfile)

    try:
        logging.debug("trying to copy {}".format(local_outputfilename))
        local_outputfile.copy(local_outputfile_copy, Gio.FileCopyFlags.OVERWRITE)
    except Exception as e:
        logging.debug("local copying failed: {}".format(e))
        _urlretrieve(url, outputfile)
Ejemplo n.º 15
0
    def _try_load(self):
        if self.key_index >= 2:
            if self.icon_format == 'jpeg':
                self.key_index = 0
                self.icon_format = 'png'
            else:
                self._on_try_load_finished(None)
                return

        self.key = AlbumArtCache.get_default()._keybuilder_funcs[self.key_index].__call__(self.artist, self.album)
        self.path = GLib.build_filenamev([AlbumArtCache.get_default().cacheDir, '%s.%s' % (self.key, self.icon_format)])
        f = Gio.File.new_for_path(self.path)

        f.read_async(GLib.PRIORITY_DEFAULT, None, self._on_read_ready, None)
Ejemplo n.º 16
0
 def __init__(self, uri, artist, album, callback, data=None):
     self.uri = uri
     self.artist = artist
     self.album = album
     self.callback = callback
     self.data = data
     self.callbacks = []
     self.path = ''
     self.key = AlbumArtCache.get_default()._keybuilder_funcs[0].__call__(
         artist, album)
     self.path = GLib.build_filenamev(
         [AlbumArtCache.get_default().cacheDir, self.key])
     self.stream = None
     self.started = False
Ejemplo n.º 17
0
    def __init__(self, size, scale):
        super().__init__()

        self._size = size
        self._scale = scale

        self._default_icon = DefaultIcon().get(
            DefaultIcon.Type.ARTIST, self._size, self._scale)

        cache_dir = GLib.build_filenamev(
            [GLib.get_user_cache_dir(), "media-art"])
        cache_dir_file = Gio.File.new_for_path(cache_dir)
        cache_dir_file.query_info_async(
            Gio.FILE_ATTRIBUTE_ACCESS_CAN_READ, Gio.FileQueryInfoFlags.NONE,
            GLib.PRIORITY_LOW, None, self._cache_dir_info_read, None)
Ejemplo n.º 18
0
    def load_contents_async_callback(self, file, result, data=None):
        try:
            success, contents, etag_out = file.load_contents_finish(result)
        except GLib.Error:
            self.clear_image()
            return

        if contents:
            cache_name = GLib.build_filenamev([
                GLib.get_user_cache_dir(), "cinnamon-screensaver-albumart-temp"
            ])
            cache_file = Gio.File.new_for_path(cache_name)

            cache_file.replace_contents_async(
                contents, None, False, Gio.FileCreateFlags.REPLACE_DESTINATION,
                self.cancellable, self.on_file_written)
Ejemplo n.º 19
0
    def __init__(self, engine, datadir, gettext_package):
        self.settings = Gio.Settings("org.cangjians.ibus.%s" % engine)
        self.settings.connect("changed", self.on_value_changed)

        ui_file = GLib.build_filenamev([datadir, "setup.ui"])
        self.__builder = Gtk.Builder()
        self.__builder.set_translation_domain(gettext_package)
        self.__builder.add_from_file(ui_file)

        for key in ("version", ):
            combo = self.__builder.get_object(key)
            active = self.__get_active_combo_index(combo.get_model(),
                                                   self.settings.get_int(key))
            combo.set_active(active)
            combo.connect("changed", self.on_combo_changed, key)
            setattr(self, "widget_%s" % key, combo)

        for key in ("include-allzh", "include-jp", "include-zhuyin",
                    "include-symbols"):
            switch = self.__builder.get_object(key)
            switch.set_active(self.settings.get_boolean(key))
            switch.connect("notify::active", self.on_switch_toggled, key)
            setattr(self, "widget_%s" % key, switch)

        self.__window = self.__builder.get_object("setup_dialog")

        if engine == "cangjie":
            title = dgettext(gettext_package, "Cangjie Preferences")
        elif engine == "quick":
            title = dgettext(gettext_package, "Quick Preferences")

        self.__window.set_title(title)

        try:
            # Pretend to be a GNOME Control Center dialog if appropriate
            self.gnome_cc_xid = int(GLib.getenv('GNOME_CONTROL_CENTER_XID'))
            self.__window.set_wmclass('gnome-control-center',
                                      'Gnome-control-center')
            self.__window.set_modal(True)
            self.__window.connect('notify::window', self.set_transient)
            self.__window.set_type_hint(Gdk.WindowTypeHint.DIALOG)

        except:
            # No problem here, we're just a normal dialog
            pass

        self.__window.show()
Ejemplo n.º 20
0
    def __init__ (self, engine, datadir, gettext_package):
        self.settings = Gio.Settings("org.cangjians.ibus.%s" % engine)
        self.settings.connect("changed", self.on_value_changed)

        ui_file = GLib.build_filenamev([datadir, "setup.ui"])
        self.__builder = Gtk.Builder()
        self.__builder.set_translation_domain(gettext_package)
        self.__builder.add_from_file(ui_file)

        for key in ("version", ):
            combo = self.__builder.get_object(key)
            active = self.__get_active_combo_index(combo.get_model(),
                                                   self.settings.get_int(key))
            combo.set_active(active)
            combo.connect("changed", self.on_combo_changed, key)
            setattr(self, "widget_%s" % key, combo)

        for key in ("include-allzh", "include-jp",
                    "include-zhuyin", "include-symbols"):
            switch = self.__builder.get_object(key)
            switch.set_active(self.settings.get_boolean(key))
            switch.connect("notify::active", self.on_switch_toggled, key)
            setattr(self, "widget_%s" % key, switch)

        self.__window = self.__builder.get_object("setup_dialog")

        if engine == "cangjie":
            title = dgettext(gettext_package, "Cangjie Preferences")
        elif engine == "quick":
            title = dgettext(gettext_package, "Quick Preferences")

        self.__window.set_title(title)

        try:
            # Pretend to be a GNOME Control Center dialog if appropriate
            self.gnome_cc_xid = int(GLib.getenv('GNOME_CONTROL_CENTER_XID'))
            self.__window.set_wmclass('gnome-control-center',
                                      'Gnome-control-center')
            self.__window.set_modal(True)
            self.__window.connect('notify::window', self.set_transient)
            self.__window.set_type_hint(Gdk.WindowTypeHint.DIALOG)

        except:
            # No problem here, we're just a normal dialog
            pass

        self.__window.show()
Ejemplo n.º 21
0
    def __init__(self):
        super().__init__()

        self.playlist_path = GLib.build_filenamev(
            [GLib.get_user_data_dir(), "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))

        Grl.init(None)
        self.options = Grl.OperationOptions()
        self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY
                                          | Grl.ResolutionFlags.IDLE_RELAY)

        self.full_options = Grl.OperationOptions()
        self.full_options.set_resolution_flags(
            Grl.ResolutionFlags.FULL | Grl.ResolutionFlags.IDLE_RELAY)

        self.props.sources = {}

        self.blacklist = [
            'grl-filesystem', 'grl-bookmarks', 'grl-metadata-store',
            'grl-podcasts', 'grl-spotify-cover'
        ]
        self.tracker = None
        self.changed_media_ids = []
        self.pending_event_id = 0
        self.changes_pending = {
            'Albums': False,
            'Artists': False,
            'Songs': False
        }
        self.pending_changed_medias = []

        self._thumbnail_sources = []
        self._thumbnail_sources_timeout = None

        self.registry = Grl.Registry.get_default()

        self._tracker_wrapper = TrackerWrapper()
        self.tracker_sparql = self._tracker_wrapper.props.tracker
        self._tracker_wrapper.bind_property(
            "tracker-available", self, "tracker-available",
            GObject.BindingFlags.BIDIRECTIONAL
            | GObject.BindingFlags.SYNC_CREATE)

        self._find_sources()
Ejemplo n.º 22
0
    def __init__(self, exec_by_ibus, engine_name):
        component_path = GLib.build_filenamev([datadir, "..", "ibus", "component", "%s.xml" % engine_name])
        self.__component = IBus.Component.new_from_file(component_path)

        self.__mainloop = GLib.MainLoop()

        self.__bus = IBus.Bus()
        self.__bus.connect("disconnected", self.__bus_disconnected_cb)

        self.__factory = IBus.Factory.new(self.__bus.get_connection())
        engine_classtype = "Engine%s" % engine_name.capitalize()
        self.__factory.add_engine(engine_name, GObject.type_from_name(engine_classtype))

        if exec_by_ibus:
            self.__bus.request_name(self.__component.get_name(), 0)
        else:
            self.__bus.register_component(self.__component)
Ejemplo n.º 23
0
    def load_contents_async_callback(self, file, result, data=None):
        try:
            success, contents, etag_out = file.load_contents_finish(result)
        except GLib.Error:
            self.clear_image()
            return

        if contents:
            cache_name = GLib.build_filenamev([GLib.get_user_cache_dir(), "cinnamon-screensaver-albumart-temp"])
            cache_file = Gio.File.new_for_path(cache_name)

            cache_file.replace_contents_async(contents,
                                              None,
                                              False,
                                              Gio.FileCreateFlags.REPLACE_DESTINATION,
                                              self.cancellable,
                                              self.on_file_written)
Ejemplo n.º 24
0
    def __init__(self):
        super().__init__()

        self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(),
                                                  "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))

        Grl.init(None)
        self.options = Grl.OperationOptions()
        self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY |
                                          Grl.ResolutionFlags.IDLE_RELAY)

        self.full_options = Grl.OperationOptions()
        self.full_options.set_resolution_flags(Grl.ResolutionFlags.FULL |
                                               Grl.ResolutionFlags.IDLE_RELAY)

        self.props.sources = {}

        self.blacklist = [
            'grl-filesystem',
            'grl-bookmarks',
            'grl-metadata-store',
            'grl-podcasts',
            'grl-spotify-cover'
        ]
        self.tracker = None
        self.changed_media_ids = []
        self.pending_event_id = 0
        self.changes_pending = {'Albums': False, 'Artists': False, 'Songs': False}
        self.pending_changed_medias = []

        self._thumbnail_sources = []
        self._thumbnail_sources_timeout = None

        self.registry = Grl.Registry.get_default()

        self._tracker_wrapper = TrackerWrapper()
        self.tracker_sparql = self._tracker_wrapper.props.tracker
        self._tracker_wrapper.bind_property(
            "tracker-available", self, "tracker-available",
            GObject.BindingFlags.BIDIRECTIONAL |
            GObject.BindingFlags.SYNC_CREATE)

        self._find_sources()
Ejemplo n.º 25
0
    def _tryLoad(self, size, artist, album, i, format, callback):
        if i >= self._keybuilder_funcs.length:
            if format == 'jpeg':
                self._tryLoad(size, artist, album, 0, 'png', callback)
            else:
                callback(None)
            return

        key = self._keybuilder_funcs[i].call(self, artist, album)
        path = GLib.build_filenamev([self.cacheDir, key + '.' + format])
        file = Gio.File.new_for_path(path)

        def on_read_ready(object, res):
            try:
                stream = object.read_finish(res)

                def on_pixbuf_ready(source, res):
                    try:
                        pixbuf = GdkPixbuf.Pixbuf.new_from_stream_finish(res)
                        width = pixbuf.get_width()
                        height = pixbuf.get_height()
                        if width >= size or height >= size:
                            scale = max(width, height) / size
                            callback(pixbuf.scale_simple(width / scale,
                                                         height / scale, 2),
                                     path)

                            return
                    except GLib.Error as error:
                        if self.logLookupErrors:
                            print("ERROR:", error)

                    self._tryLoad(size, artist, album, ++i, format, callback)

                GdkPixbuf.Pixbuf.new_from_stream_async(stream, None,
                                                       on_pixbuf_ready)
                return

            except GLib.Error as error:
                if (self.logLookupErrors):
                    print("ERROR:", error)

            self._tryLoad(size, artist, album, ++i, format, callback)

        file.read_async(GLib.PRIORITY_DEFAULT, None, on_read_ready)
Ejemplo n.º 26
0
    def _try_load(self):
        if self.key_index >= 2:
            if self.icon_format == 'jpeg':
                self.key_index = 0
                self.icon_format = 'png'
            else:
                self._on_try_load_finished(None)
                return

        self.key = AlbumArtCache.get_default()._keybuilder_funcs[
            self.key_index].__call__(self.artist, self.album)
        self.path = GLib.build_filenamev([
            AlbumArtCache.get_default().cacheDir,
            '%s.%s' % (self.key, self.icon_format)
        ])
        f = Gio.File.new_for_path(self.path)

        f.read_async(GLib.PRIORITY_DEFAULT, None, self._on_read_ready, None)
Ejemplo n.º 27
0
 def __init__(self, path="brss.log", name="BRss"):
     self.logger = logging.getLogger(name)
     self.logger.setLevel(logging.DEBUG)
     logpath = GLib.build_filenamev([BASE_PATH, path])
     self.usrlog  = logging.FileHandler(logpath, 'w')
     settings = Gio.Settings.new(BASE_KEY)
     settings.connect("changed::enable-debug", self.enable_debug)
     self.enable_debug(settings)
     # useful for debugging
     self.console = logging.StreamHandler()
     self.console.setLevel(logging.DEBUG)
     self.enable_debug(settings)
     mfmt = logging.Formatter("%(asctime)-15s %(levelname)-8s %(message)s")
     # add formatter to ch
     self.usrlog.setFormatter(mfmt)
     # add channels to logger
     self.logger.addHandler(self.usrlog)
     self.logger.addHandler(self.console)
Ejemplo n.º 28
0
    def __init__(self, bus, engine):
        self.__config = Config(bus, engine, self.on_value_changed)

        ui_file = GLib.build_filenamev([datadir, "setup.ui"])
        self.__builder = Gtk.Builder()
        self.__builder.set_translation_domain(gettext_package)
        self.__builder.add_from_file(ui_file)

        for option in options:
            if option["name"] == "punctuation_chars":
                self.__prepare_combo(option)

            else:
                self.__prepare_button(option)

        self.__window = self.__builder.get_object("setup_dialog")
        self.__window.set_title("%s settings" % engine.capitalize())
        self.__window.show()
Ejemplo n.º 29
0
    def __init__(self, exec_by_ibus, engine_name, componentdir):
        component_path = GLib.build_filenamev(
            [componentdir, "%s.xml" % engine_name])
        self.__component = IBus.Component.new_from_file(component_path)

        self.__mainloop = GLib.MainLoop()

        self.__bus = IBus.Bus()
        self.__bus.connect("disconnected", self.__bus_disconnected_cb)

        self.__factory = IBus.Factory.new(self.__bus.get_connection())
        engine_classtype = "Engine%s" % engine_name.capitalize()
        self.__factory.add_engine(engine_name,
                                  GObject.type_from_name(engine_classtype))

        if exec_by_ibus:
            self.__bus.request_name(self.__component.get_name(), 0)
        else:
            self.__bus.register_component(self.__component)
Ejemplo n.º 30
0
 def update_row(self, item):
     #find the item
     self.log.debug("Updating row {0}".format(item['id']))
     iter = self.__search(1, item['id'])
     if iter:
         for k,v in item.iteritems():
             try:
                 self.store.set_value(iter, self.lmap.index(k), v)
             except Exception, e:
                 #~ self.log.exception(e)
                 pass # we don't really care about this one
         piter = self.store.iter_parent(iter)
         if piter:
             # setup favicon
             stock_id = self.store.get_value(iter, self.lmap.index('id'))
             path = GLib.build_filenamev([FAVICON_PATH, stock_id])
             if self.__setup_icons(path, stock_id):
                 self.store.set_value(iter, self.lmap.index('stock-id'), stock_id)
             self.__recount_category(self.store, piter)
Ejemplo n.º 31
0
    def _try_load(self, size, artist, album, i, icon_format, callback):
        if i >= len(self._keybuilder_funcs):
            if icon_format == "jpeg":
                self._try_load(size, artist, album, 0, "png", callback)
            else:
                callback(None, None)
            return

        key = self._keybuilder_funcs[i].__call__(artist, album)
        path = GLib.build_filenamev([self.cacheDir, key + "." + icon_format])
        f = Gio.File.new_for_path(path)

        def on_read_ready(obj, res, data=None):
            try:
                stream = obj.read_finish(res)

                def on_pixbuf_ready(source, res, data=None):
                    try:
                        pixbuf = GdkPixbuf.Pixbuf.new_from_stream_finish(res)
                        width = pixbuf.get_width()
                        height = pixbuf.get_height()
                        if width >= size or height >= size:
                            scale = max(width, height) / size
                            callback(pixbuf.scale_simple(width / scale, height / scale, 2), path)

                            return
                    except Exception as error:
                        if self.logLookupErrors:
                            print("ERROR:", error)

                    self._try_load(size, artist, album, i + 1, icon_format, callback)

                GdkPixbuf.Pixbuf.new_from_stream_async(stream, None, on_pixbuf_ready, None)
                return

            except Exception as error:
                if self.logLookupErrors:
                    print("ERROR:", error)

            self._try_load(size, artist, album, i + 1, icon_format, callback)

        f.read_async(GLib.PRIORITY_DEFAULT, None, on_read_ready, None)
Ejemplo n.º 32
0
        def read_async_ready(outstream, res, error):
            try:
                stream = f.read_finish(res)
                path = GLib.build_filenamev([self.cacheDir, key])

                try:
                    streamInfo = stream.query_info("standard::content-type", None)
                    contentType = streamInfo.get_content_type()

                    if contentType == "image/png":
                        path += ".png"
                    elif contentType == "image/jpeg":
                        path += ".jpeg"
                    else:
                        print("Thumbnail format not supported, not caching")
                        stream.close(None)
                        return
                except Exception as e:
                    print("Failed to query thumbnail content type")
                    path += ".jpeg"
                    return

                def replace_async_ready(new_file, res, error):
                    outstream = new_file.replace_finish(res)

                    def splice_async_ready(outstream, res, error):
                        if outstream.splice_finish(res) > 0:
                            for values in self.requested_uris[uri]:
                                callback, width, height = values
                                pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(path, height, width, True)
                                callback(pixbuf, path)
                            del self.requested_uris[uri]

                    outstream.splice_async(stream, Gio.IOStreamSpliceFlags.NONE, 300, None, splice_async_ready, None)

                newFile = Gio.File.new_for_path(path)
                newFile.replace_async(
                    None, False, Gio.FileCreateFlags.REPLACE_DESTINATION, 300, None, replace_async_ready, None
                )

            except Exception as e:
                print(e)
Ejemplo n.º 33
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(),
                                                  "gnome-music", "playlists"])
        if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)):
            GLib.mkdir_with_parents(self.playlist_path, int("0755", 8))
        self.options = Grl.OperationOptions()
        self.options.set_flags(Grl.ResolutionFlags.FULL |
                               Grl.ResolutionFlags.IDLE_RELAY)

        self.sources = {}
        self.tracker = None

        self.registry = Grl.Registry.get_default()
        self.registry.connect('source_added', self._on_source_added)
        self.registry.connect('source_removed', self._on_source_removed)

        try:
            self.registry.load_all_plugins()
        except GLib.GError:
            print('Failed to load plugins.')
Ejemplo n.º 34
0
    def __init__(self, coreobject, uri):
        """Initialize StoreArtistArt

        :param coreobject: The CoreArtist or CoreAlbum to store art for
        :param string uri: The art uri
        """
        self._coreobject = coreobject

        self._log = MusicLogger()
        self._soup_session = Soup.Session.new()

        if (uri is None or uri == ""):
            self._coreobject.props.thumbnail = "generic"
            return

        cache_dir = GLib.build_filenamev(
            [GLib.get_user_cache_dir(), "media-art"])
        cache_dir_file = Gio.File.new_for_path(cache_dir)
        cache_dir_file.query_info_async(Gio.FILE_ATTRIBUTE_ACCESS_CAN_READ,
                                        Gio.FileQueryInfoFlags.NONE,
                                        GLib.PRIORITY_LOW, None,
                                        self._cache_dir_info_read, uri)
Ejemplo n.º 35
0
def init(_name, _version, _prefix, _libdir, _flags=0):
    """
    @params: package parameters

    Initialize directories and global variables. Must be called
    before any of other API in Package is used.
    @params must be an object with at least the following keys:
    - name: the package name ($(PACKAGE_NAME) in autotools)
    - version: the package version
    - prefix: the installation prefix

    init() will take care to check if the program is running from
    the source directory or not, by looking for a 'src' directory.

    At the end, the global variable 'pkg' will contain the
    Package module (imports.package). Additionally, the following
    module variables will be available:
    - name, version: same as in @params
    - prefix: the installation prefix (as passed in @params)
    - datadir, libdir: the final datadir and libdir when installed;
                       usually, these would be prefix + '/share' and
                       and prefix + '/lib' (or '/lib64')
    - pkgdatadir: the directory to look for private data files, such as
                  images, stylesheets and UI definitions;
                  this will be datadir + name when installed and
                  './data' when running from the source tree
    - pkglibdir: the directory to look for private typelibs and C
                 libraries;
                 this will be libdir + name when installed and
                 './lib' when running from the source tree
    - moduledir: the directory to look for JS modules;
                 this will be pkglibdir when installed and
                 './src' when running from the source tree
    - localedir: the directory containing gettext translation files;
                 this will be datadir + '/locale' when installed
                 and './po' in the source tree

    All paths are absolute and will not end with '/'.

    As a side effect, init() calls GLib.set_prgname().
    """

    import builtins
    builtins.__dict__['pkg'] = sys.modules[__name__]

    global name, version, appFlags, prefix, libdir, datadir
    global pkglibdir, libpath, pkgdatadir, localedir, moduledir
    global _base

    name = _name
    version = _version
    appFlags = _flags

    # Must call it first, because it can only be called
    # once, and other library calls might have it as a
    # side effect
    GLib.set_prgname(name)

    prefix = _prefix
    libdir = _libdir
    datadir = GLib.build_filenamev([prefix, 'share'])

    if _runningFromSource():
        print('Running from source tree, using local files')

        # Running from source directory
        _base = GLib.get_current_dir()
        pkglibdir = GLib.build_filenamev([_base, 'lib'])
        libpath = GLib.build_filenamev([pkglibdir, '.libs'])
        girpath = pkglibdir
        pkgdatadir = GLib.build_filenamev([_base, 'data'])
        localedir = GLib.build_filenamev([_base, 'po'])
        moduledir = GLib.build_filenamev([_base, 'src'])
    else:
        appFlags |= Gio.ApplicationFlags.IS_SERVICE

        _base = prefix
        pkglibdir = GLib.build_filenamev([libdir, name])
        libpath = pkglibdir
        girpath = GLib.build_filenamev([pkglibdir, 'girepository-1.0'])
        pkgdatadir = GLib.build_filenamev([datadir, name])
        localedir = GLib.build_filenamev([datadir, 'locale'])
        moduledir = pkgdatadir

    sys.path.insert(0, moduledir)
    GIRepository.Repository.prepend_search_path(girpath)
    GIRepository.Repository.prepend_library_path(libpath)

    try:
        resource = Gio.Resource.load(
            GLib.build_filenamev([pkgdatadir, name + '.data.gresource']))
        resource._register()
    except e:
        pass
Ejemplo n.º 36
0
def get_module_data_path(name):
    engine = Peas.Engine.get_default()
    plugin = engine.get_plugin_info('autotools_templates')
    data_dir = plugin.get_data_dir()
    return GLib.build_filenamev([data_dir, name])
Ejemplo n.º 37
0
def get_module_data_path(name):
    engine = Peas.Engine.get_default()
    plugin = engine.get_plugin_info('rustup_plugin')
    data_dir = plugin.get_data_dir()
    return GLib.build_filenamev([data_dir, name])
Ejemplo n.º 38
0
def init_resources():
    resource = Gio.Resource.load(
        GLib.build_filenamev([pkgdatadir, name + '.gresource']))
    resource._register()
Ejemplo n.º 39
0
 def get_config_file(self):
     path = GLib.build_pathv(
         '/', (GLib.get_user_config_dir(), 'ga-dashlet', None))
     GLib.mkdir_with_parents(path, 0o700)
     return GLib.build_filenamev((path, 'settings.ini'))
Ejemplo n.º 40
0
 def _get_autosave_filename(self):
     return GLib.build_filenamev([GLib.get_user_data_dir(), 'autosave'])
Ejemplo n.º 41
0
    def startup(self, application):
        self.display = Gdk.Display.get_default()
        self.manager = self.display.get_device_manager()
        self.screen = Gdk.Screen.get_default()
        # device-added works in Gdk_test.py but not here
        # self.manager.connect('device-added', self.device_changed)
        # self.manager.connect('device-changed', self.device_changed)
        self.screen.connect("monitors-changed", self.monitors_changed)
        self.screen.connect("size-changed", self.reset_outline)

        name = "pointer-config"
        alt = [GLib.get_user_data_dir()] + list(GLib.get_system_data_dirs())
        alt = filter(GLib.path_is_absolute, alt)
        path = [GLib.build_filenamev((p, "locale")) for p in alt]
        path = [p for p in path if gettext.find(name, p)] + [None]
        gettext.bindtextdomain(name, path[0])
        gettext.textdomain(name)
        gettext.install(name, path[0])
        _ = gettext.lgettext
        GLib.set_application_name(_("Pointer Config"))

        for sub in alt:
            builder = Gtk.Builder()
            builder.set_translation_domain(name)
            path = GLib.build_filenamev((sub, name, name + ".glade"))
            try:
                builder.add_from_file(path)
                break
            except GLib.GError:
                pass
        else:
            sys.exit("failed to load " + name + ".glade")
        builder.connect_signals(self)

        self.outline = Outline()
        obj = (
            "window_main",
            "store_type",
            "combo_rotation",
            "store_rotation",
            "check_left",
            "spin_left",
            "check_top",
            "spin_top",
            "check_width",
            "spin_width",
            "check_height",
            "spin_height",
            "button_cursor",
            "radio_absolute",
            "radio_relative",
            "tree_properties",
            "store_properties",
            "column_properties",
            "text_properties",
            "selection_properties",
            "grid_options",
            "check_auto",
            "check_outline",
            "button_colour",
            "spin_size",
            "button_apply",
            "dialog_about",
            "menu_status",
        )
        for name in obj:
            setattr(self, name, builder.get_object(name))

        path = "/pointer-config/"
        self.settings = Gio.Settings(application.get_application_id(), path)
        param = dict()
        for key, _ in self.store_type:
            child = self.settings.get_child(key)
            if child.get_boolean("auto"):
                param[key] = get_params(child)
        call_xinput(self.manager.list_devices(Gdk.DeviceType.SLAVE), param)

        self.add_window(self.window_main)
Ejemplo n.º 42
0
import sys
from gi.repository import GdkPixbuf
from gi.repository import GLib

__version__         = '0.9'
__authors__         = ["Bidossessi SODONON"]
__maintainers__     = ["Bidossessi SODONON"]
__documenters__     = ["Bidossessi SODONON"]
__artists__         = ["Bidossessi SODONON"]

BASE_KEY            = 'com.itgears.BRss'
ENGINE_DBUS_KEY     = 'com.itgears.BRss.Engine'
ENGINE_DBUS_PATH    = '/com/itgears/BRss/Engine'
READER_DBUS_KEY     = 'com.itgears.BRss.Reader'
READER_DBUS_PATH    = '/com/itgears/BRss/Reader'
BASE_PATH           = GLib.build_filenamev([GLib.get_user_config_dir(),'brss'])
FAVICON_PATH        = GLib.build_filenamev([BASE_PATH, 'favicons'])
IMAGES_PATH         = GLib.build_filenamev([BASE_PATH, 'images'])
DB_PATH             = GLib.build_filenamev([BASE_PATH, 'brss.db'])
base_dir            = Gio.file_new_for_path(BASE_PATH)
favicon_dir         = Gio.file_new_for_path(FAVICON_PATH)
images_dir          = Gio.file_new_for_path(IMAGES_PATH)

def init_dirs():
    try:
        base_dir.make_directory(None)
    except:pass
    try:favicon_dir.make_directory(None)
    except:pass
    try:images_dir.make_directory(None)
    except:pass
Ejemplo n.º 43
0
def get_module_data_path(name):
    engine = Peas.Engine.get_default()
    plugin = engine.get_plugin_info('autotools_templates')
    data_dir = plugin.get_data_dir()
    return GLib.build_filenamev([data_dir, name])
Ejemplo n.º 44
0
def make_path(type, filename):
    """Return a data opml path"""
    return GLib.build_filenamev([sys.prefix, 'share', type, filename])
Ejemplo n.º 45
0
def init_resources():
    resource = Gio.Resource.load(GLib.build_filenamev([pkgdatadir,
                                                       name + '.gresource']))
    resource._register()
Ejemplo n.º 46
0
def get_module_data_path(name):
    engine = Peas.Engine.get_default()
    plugin = engine.get_plugin_info('rustup_plugin')
    data_dir = plugin.get_data_dir()
    return GLib.build_filenamev([data_dir, name])
Ejemplo n.º 47
0
def init(_name, _version, _prefix, _libdir, _flags=0):
    """
    @params: package parameters

    Initialize directories and global variables. Must be called
    before any of other API in Package is used.
    @params must be an object with at least the following keys:
    - name: the package name ($(PACKAGE_NAME) in autotools)
    - version: the package version
    - prefix: the installation prefix

    init() will take care to check if the program is running from
    the source directory or not, by looking for a 'src' directory.

    At the end, the global variable 'pkg' will contain the
    Package module (imports.package). Additionally, the following
    module variables will be available:
    - name, version: same as in @params
    - prefix: the installation prefix (as passed in @params)
    - datadir, libdir: the final datadir and libdir when installed;
                       usually, these would be prefix + '/share' and
                       and prefix + '/lib' (or '/lib64')
    - pkgdatadir: the directory to look for private data files, such as
                  images, stylesheets and UI definitions;
                  this will be datadir + name when installed and
                  './data' when running from the source tree
    - pkglibdir: the directory to look for private typelibs and C
                 libraries;
                 this will be libdir + name when installed and
                 './lib' when running from the source tree
    - moduledir: the directory to look for JS modules;
                 this will be pkglibdir when installed and
                 './src' when running from the source tree
    - localedir: the directory containing gettext translation files;
                 this will be datadir + '/locale' when installed
                 and './po' in the source tree

    All paths are absolute and will not end with '/'.

    As a side effect, init() calls GLib.set_prgname().
    """

    import builtins

    builtins.__dict__["pkg"] = sys.modules[__name__]

    global name, version, appFlags, prefix, libdir, datadir
    global pkglibdir, libpath, pkgdatadir, localedir, moduledir
    global _base

    name = _name
    version = _version
    appFlags = _flags

    # Must call it first, because it can only be called
    # once, and other library calls might have it as a
    # side effect
    GLib.set_prgname(name)

    prefix = _prefix
    libdir = _libdir
    datadir = GLib.build_filenamev([prefix, "share"])

    if _runningFromSource():
        print("Running from source tree, using local files")

        # Running from source directory
        _base = GLib.get_current_dir()
        pkglibdir = GLib.build_filenamev([_base, "lib"])
        libpath = GLib.build_filenamev([pkglibdir, ".libs"])
        girpath = pkglibdir
        pkgdatadir = GLib.build_filenamev([_base, "data"])
        localedir = GLib.build_filenamev([_base, "po"])
        moduledir = GLib.build_filenamev([_base, "src"])
    else:
        appFlags |= Gio.ApplicationFlags.IS_SERVICE

        _base = prefix
        pkglibdir = GLib.build_filenamev([libdir, name])
        libpath = pkglibdir
        girpath = GLib.build_filenamev([pkglibdir, "girepository-1.0"])
        pkgdatadir = GLib.build_filenamev([datadir, name])
        localedir = GLib.build_filenamev([datadir, "locale"])
        moduledir = pkgdatadir

    sys.path.insert(0, moduledir)
    GIRepository.Repository.prepend_search_path(girpath)
    GIRepository.Repository.prepend_library_path(libpath)

    try:
        resource = Gio.Resource.load(GLib.build_filenamev([pkgdatadir, name + ".data.gresource"]))
        resource._register()
    except e:
        pass
Ejemplo n.º 48
0
def get_store_data():
	return GLib.build_filenamev([GLib.get_user_data_dir(), '.streamy.conf'])