Beispiel #1
0
    def __init__(self):
        """
            Create application
        """
        Gtk.Application.__init__(
                            self,
                            application_id='org.gnome.Lollypop',
                            flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        self.set_property('register-session', True)
        GLib.setenv('PULSE_PROP_media.role', 'music', True)
        GLib.setenv('PULSE_PROP_application.icon_name', 'lollypop', True)

        # Ideally, we will be able to delete this once Flatpak has a solution
        # for SSL certificate management inside of applications.
        if GLib.file_test("/app", GLib.FileTest.EXISTS):
            paths = ["/etc/ssl/certs/ca-certificates.crt",
                     "/etc/pki/tls/cert.pem",
                     "/etc/ssl/cert.pem"]
            for path in paths:
                if GLib.file_test(path, GLib.FileTest.EXISTS):
                    GLib.setenv('SSL_CERT_FILE', path, True)
                    break

        self.cursors = {}
        self.window = None
        self.notify = None
        self.lastfm = None
        self.debug = False
        self.__externals_count = 0
        self.__init_proxy()
        GLib.set_application_name('Lollypop')
        GLib.set_prgname('lollypop')
        self.add_main_option("play-ids", b'a', GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING, "Play ids", None)
        self.add_main_option("debug", b'd', GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Debug lollypop", None)
        self.add_main_option("set-rating", b'r', GLib.OptionFlags.NONE,
                             GLib.OptionArg.INT, "Rate the current track",
                             None)
        self.add_main_option("play-pause", b't', GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Toggle playback",
                             None)
        self.add_main_option("next", b'n', GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to next track",
                             None)
        self.add_main_option("prev", b'p', GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to prev track",
                             None)
        self.add_main_option("emulate-phone", b'e', GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE,
                             "Emulate an Android Phone",
                             None)
        self.connect('command-line', self.__on_command_line)
        self.connect('activate', self.__on_activate)
        self.register(None)
        if self.get_is_remote():
            Gdk.notify_startup_complete()
        self.__listen_to_gnome_sm()
Beispiel #2
0
    def find_file(self, base=""):
        dir = os.path.join("demos", "data")
        logo_file = os.path.join(dir, "gtk-logo-rgb.gif")
        base_file = os.path.join(dir, base)

        if GLib.file_test(logo_file, GLib.FileTest.EXISTS) and GLib.file_test(base_file, GLib.FileTest.EXISTS):
            return base_file
        else:
            filename = os.path.join(_DEMOCODEDIR, base)
            if GLib.file_test(filename, GLib.FileTest.EXISTS):
                return filename

            # can't find the file
            raise IOError('Cannot find demo data file "%s"' % base)
Beispiel #3
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")
Beispiel #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))
        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
Beispiel #5
0
	def _UpdatePreview(self,e) :
		PreviewURI = self.FileChooserDialog.get_preview_uri()
		PreviewFile = self.FileChooserDialog.get_preview_file()
		if PreviewURI!=None and PreviewFile !=None :
			if not GLib.file_test(PreviewFile.get_path(),GLib.FileTest.IS_DIR) :
				PreviewFileInfo = PreviewFile.query_info("*",Gio.FileQueryInfoFlags.NONE,None)
				mtime = PreviewFileInfo.get_attribute_uint64(Gio.FILE_ATTRIBUTE_TIME_MODIFIED)
				ThumbnailFactory = GnomeDesktop.DesktopThumbnailFactory.new(GnomeDesktop.DesktopThumbnailSize.NORMAL)
				ThumbnailPath = ThumbnailFactory.lookup(PreviewURI,mtime)
				if ThumbnailPath != None :
					pixbuf = GdkPixbuf.Pixbuf.new_from_file(ThumbnailPath)
					self.PreviewImage.set_from_pixbuf(pixbuf)
					self.FileChooserDialog.set_preview_widget_active(True)
				else :
					mimetype, enc = mimetypes.guess_type(PreviewURI,True)
					pixbuf = ThumbnailFactory.generate_thumbnail(PreviewURI,mimetype)
					ThumbnailFactory.save_thumbnail(pixbuf,PreviewURI,mtime)
					self.PreviewImage.set_from_pixbuf(pixbuf)
					self.FileChooserDialog.set_preview_widget_active(True)

				PreviewWidth = pixbuf.get_option("tEXt::Thumb::Image::Width")
				PreviewHeight = pixbuf.get_option("tEXt::Thumb::Image::Height")
				self.Label_Size.set_label( PreviewWidth + " x " + PreviewHeight)
			else :
				self.FileChooserDialog.set_preview_widget_active(False)
		else :
			self.FileChooserDialog.set_preview_widget_active(False)
Beispiel #6
0
    def _files_exist(self, base_names):
        for name in base_names:
            path = os.path.join(self.save_location, name)
            print(
                "(server side) Checking if file or folder %s already exists." %
                (path, ))
            if GLib.file_test(path, GLib.FileTest.EXISTS):
                return True

        return False
Beispiel #7
0
    def _is_file(self, path):
        """
        Check if the given path is a file

        :return: A boolean representing if the given path is a file
        """
        if not GLib.file_test(path, GLib.FileTest.IS_REGULAR):
            return False

        return True
Beispiel #8
0
def files_exist(base_names):
    for name in base_names:
        path = os.path.join(prefs.get_save_path(), name)
        logging.debug(
            "(server side) Checking if file or folder %s already exists." %
            (path, ))
        if GLib.file_test(path, GLib.FileTest.EXISTS):
            return True

    return False
Beispiel #9
0
    def __init__(self):
        """
            Create database tables or manage update if needed
        """
        self.__cancellable = Gio.Cancellable.new()
        self.__task_helper = TaskHelper()
        self.__adblock_mtime = int(time())

        # Lazy loading if not empty
        if not GLib.file_test(self.DB_PATH, GLib.FileTest.IS_REGULAR):
            try:
                if not GLib.file_test(EOLIE_DATA_PATH, GLib.FileTest.IS_DIR):
                    GLib.mkdir_with_parents(EOLIE_DATA_PATH, 0o0750)
                # Create db schema
                with SqlCursor(self) as sql:
                    sql.execute(self.__create_adblock)
                    sql.execute(self.__create_adblock_css)
                    sql.commit()
            except Exception as e:
                print("DatabaseAdblock::__init__(): %s" % e)
Beispiel #10
0
 def get_artist_artwork_path(self, artist):
     """
         True if artist artwork exists
         @param artist as str
         @return str/None
     """
     encoded = self.encode_artist_name(artist)
     filepath = "%s/%s.jpg" % (ARTISTS_PATH, encoded)
     if GLib.file_test(filepath, GLib.FileTest.EXISTS):
         return filepath
     return None
Beispiel #11
0
 def __init__(self):
     """
         Create database tables or manage update if needed
     """
     upgrade = DatabaseUpgrade(Type.BOOKMARK)
     self.thread_lock = Lock()
     if not GLib.file_test(self.DB_PATH, GLib.FileTest.IS_REGULAR):
         try:
             if not GLib.file_test(EOLIE_DATA_PATH, GLib.FileTest.IS_DIR):
                 GLib.mkdir_with_parents(EOLIE_DATA_PATH, 0o0750)
             # Create db schema
             with SqlCursor(self) as sql:
                 sql.execute(self.__create_bookmarks)
                 sql.execute(self.__create_tags)
                 sql.execute(self.__create_bookmarks_tags)
                 sql.execute(self.__create_parents)
                 sql.execute("PRAGMA user_version=%s" % upgrade.version)
         except Exception as e:
             Logger.error("DatabaseBookmarks::__init__(): %s", e)
     else:
         upgrade.upgrade(self)
    def start_xorg(klass):
        '''start X.org server with dummy driver'''

        conf = os.path.join(os.path.dirname(__file__), 'xorg-dummy.conf')

        # some distros like Fedora install Xorg as suid root; copy it into our
        # workdir to drop the suid bit and run it as user
        if GLib.file_test('/usr/libexec/Xorg.bin',
                          GLib.FileTest.IS_EXECUTABLE):
            xorg = '/usr/libexec/Xorg.bin'
        else:
            out = GLib.find_program_in_path('Xorg')
            if not out:
                sys.stderr.write('ERROR: Xorg not installed\n')
                sys.exit(1)
            xorg = os.path.join(klass.workdir, 'Xorg')
            shutil.copy(out, xorg)

        display_num = 99

        if os.path.isfile('/tmp/.X%d-lock' % display_num):
            sys.stderr.write(
                'Cannot start X.org, an instance already exists\n')
            sys.exit(1)

        # You can rename the log file to *.log if you want to see it on test
        # case failures
        log = os.path.join(klass.workdir, 'Xorg.out')
        klass.xorg = subprocess.Popen(
            [xorg, '-config', conf, '-logfile', log,
             ':%d' % display_num],
            stderr=subprocess.PIPE)
        os.environ['DISPLAY'] = ':%d' % display_num

        # wait until the server is ready
        timeout = 50
        while timeout > 0:
            time.sleep(0.1)
            timeout -= 1
            if klass.xorg.poll():
                # ended prematurely
                timeout = -1
                break
            if subprocess.call(['xprop', '-root'],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE) == 0:
                break
        if timeout <= 0:
            with open(log) as f:
                sys.stderr.write(
                    'Cannot start X.org with dummy driver.  Log:\n%s\n--------'
                    % f.read())
            sys.exit(1)
Beispiel #13
0
 def __init__(self):
     """
         Create database tables or manage update if needed
     """
     upgrade = DatabaseUpgrade(Type.HISTORY)
     self.thread_lock = Lock()
     if not GLib.file_test(self.DB_PATH, GLib.FileTest.IS_REGULAR):
         try:
             if not GLib.file_test(EOLIE_DATA_PATH, GLib.FileTest.IS_DIR):
                 GLib.mkdir_with_parents(EOLIE_DATA_PATH, 0o0750)
             # Create db schema
             with SqlCursor(self) as sql:
                 sql.execute(self.__create_history)
                 sql.execute(self.__create_history_atime)
                 sql.execute(self.__create_history_orderby_idx)
                 sql.execute(self.__create_history_where_idx)
                 sql.execute("PRAGMA user_version=%s" % upgrade.version)
         except Exception as e:
             Logger.error("DatabaseHistory::__init__(): %s", e)
     else:
         upgrade.upgrade(self)
Beispiel #14
0
 def get_favicon_path(self, uri):
     """
         Return favicon cache path for uri
         @param uri as str/None
         @return str/None
     """
     if uri is None:
         return None
     for favicon_type in ["favicon", "favicon_alt"]:
         favicon_path = self.get_path(uri, favicon_type)
         if GLib.file_test(favicon_path, GLib.FileTest.IS_REGULAR):
             return favicon_path
     return None
Beispiel #15
0
    def _get_file_package(self, file):
        '''Return the package a file belongs to.
        Return None if the file is not shipped by any package.
        '''
        # check if the file is a diversion
        divert = "/usr/bin/dpkg-divert"
        if (not GLib.file_test(divert, GLib.FileTest.EXISTS)):
            divert = "/usr/sbin/dpkg-divert"
        if (GLib.file_test(divert, GLib.FileTest.EXISTS)):
            dpkg = subprocess.Popen([divert, "--list", file],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            out = dpkg.communicate()[0].decode("UTF-8")
            if dpkg.returncode == 0 and out:
                pkg = out.split()[-1]
                if pkg != "hardening-wrapper":
                    return pkg

        fname = os.path.splitext(os.path.basename(file))[0].lower()

        all_lists = []
        likely_lists = []
        for f in glob.glob("/var/lib/dpkg/info/*.list"):
            p = os.path.splitext(os.path.basename(f))[0].lower().split(":")[0]
            if p in fname or fname in p:
                likely_lists.append(f)
            else:
                all_lists.append(f)

        # first check the likely packages
        match = self.__fgrep_files(file, likely_lists)
        if not match:
            match = self.__fgrep_files(file, all_lists)

        if match:
            return os.path.splitext(os.path.basename(match))[0].split(":")[0]

        return None
Beispiel #16
0
    def _get_file_package(self, file):
        '''Return the package a file belongs to.
        Return None if the file is not shipped by any package.
        '''
        # check if the file is a diversion
        divert = "/usr/bin/dpkg-divert"
        if(not GLib.file_test(divert, GLib.FileTest.EXISTS)):
            divert = "/usr/sbin/dpkg-divert"
        if(GLib.file_test(divert, GLib.FileTest.EXISTS)):
            dpkg = subprocess.Popen([divert, "--list", file],
                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out = dpkg.communicate()[0].decode("UTF-8")
            if dpkg.returncode == 0 and out:
                pkg = out.split()[-1]
                if pkg != "hardening-wrapper":
                    return pkg

        fname = os.path.splitext(os.path.basename(file))[0].lower()

        all_lists = []
        likely_lists = []
        for f in glob.glob("/var/lib/dpkg/info/*.list"):
            p = os.path.splitext(os.path.basename(f))[0].lower().split(":")[0]
            if p in fname or fname in p:
                likely_lists.append(f)
            else:
                all_lists.append(f)

        # first check the likely packages
        match = self.__fgrep_files(file, likely_lists)
        if not match:
            match = self.__fgrep_files(file, all_lists)

        if match:
            return os.path.splitext(os.path.basename(match))[0].split(":")[0]

        return None
Beispiel #17
0
 def create_db(self):
     """
         Create databse
     """
     if not GLib.file_test(EOLIE_DATA_PATH, GLib.FileTest.IS_DIR):
         GLib.mkdir_with_parents(EOLIE_DATA_PATH, 0o0750)
     # If DB schema changed, remove it
     if GLib.file_test(self.__DB_PATH, GLib.FileTest.IS_REGULAR):
         with SqlCursor(self) as sql:
             result = sql.execute("PRAGMA user_version")
             v = result.fetchone()
             if v is None or v[0] != self.__SCHEMA_VERSION:
                 f = Gio.File.new_for_path(self.__DB_PATH)
                 f.delete()
     if not GLib.file_test(self.__DB_PATH, GLib.FileTest.IS_REGULAR):
         try:
             # Create db schema
             with SqlCursor(self) as sql:
                 sql.execute(self.__create_adblock)
                 sql.execute(self.__create_adblock_re)
                 sql.execute(self.__create_adblock_re_domain)
                 sql.execute(self.__create_adblock_re_domain_ex)
                 sql.execute(self.__create_adblock_css)
                 sql.execute(self.__create_adblock_cache)
                 sql.execute(self.__create_adblock_idx)
                 sql.execute(self.__create_adblock_re_idx)
                 sql.execute(self.__create_adblock_re_domain_idx)
                 sql.execute(self.__create_adblock_re_domain_regex_idx)
                 sql.execute(self.__create_adblock_re_domain_ex_idx)
                 sql.execute(self.__create_adblock_re_domain_regex_ex_idx)
                 sql.execute(self.__create_adblock_css_black_idx)
                 sql.execute(self.__create_adblock_css_white_idx)
                 sql.execute(self.__create_adblock_cache_idx)
                 sql.execute("PRAGMA user_version=%s" %
                             self.__SCHEMA_VERSION)
         except Exception as e:
             Logger.error("DatabaseAdblock::__init__(): %s", e)
Beispiel #18
0
Datei: ffs.py Projekt: jku/ffs
    def start_sharing(self, files):
        if self.shared_file != None:
            self.stop_sharing()

        if len(files) > 1 or GLib.file_test(files[0], GLib.FileTest.IS_DIR):
            self.archive_state = ArchiveState.FAILED
            self.shared_file = self.zipper.create_archive(files, self.on_archive_ready)
            self.archive_state = ArchiveState.PREPARING
        elif len(files) == 1:
            self.archive_state = ArchiveState.NA
            self.shared_file = files[0]

        self.download_count = 0
        self.download_finished_count = 0
        self.change_callback()
Beispiel #19
0
    def update(self):
        """
            Update database
        """
        if not Gio.NetworkMonitor.get_default().get_network_available():
            return
        # Update adblock_js repo
        git = GLib.find_program_in_path("git")
        if git is None:
            Logger.info(_("For stronger ad blocking, install git command"))
        else:
            if GLib.file_test(ADBLOCK_JS, GLib.FileTest.IS_DIR):
                argv = [git,
                        "-C",
                        ADBLOCK_JS,
                        "pull",
                        "https://gitlab.gnome.org/gnumdk/eolie-adblock.git"]
            else:
                argv = [git,
                        "clone",
                        "https://gitlab.gnome.org/gnumdk/eolie-adblock.git",
                        ADBLOCK_JS]
            (pid, a1, a2, a3) = GLib.spawn_async(
                argv,
                flags=GLib.SpawnFlags.STDOUT_TO_DEV_NULL)
            GLib.spawn_close_pid(pid)

        # DB version is last successful sync mtime
        try:
            version = load(open(EOLIE_DATA_PATH + "/adblock.bin", "rb"))
        except:
            version = 0
        self.__cancellable.reset()
        if self.__adblock_mtime - version > self.__UPDATE:
            # Update host rules
            uris = list(self.__URIS)
            locales = GLib.get_language_names()
            user_locale = locales[0].split("_")[0]
            try:
                uris += self.__CSS_URIS +\
                    [self.__CSS_LOCALIZED_URIS[user_locale]]
            except:
                uris += self.__CSS_URIS
            uri = uris.pop(0)
            self.__task_helper.load_uri_content(uri,
                                                self.__cancellable,
                                                self.__on_load_uri_content,
                                                uris)
Beispiel #20
0
 def artist_artwork_exists(self, artist):
     """
         True if artist artwork exists
         @param artist as str
         @return (bool, path)
     """
     escaped_artist = escape(artist)
     # Search in store
     paths = [
         "%s/%s.jpg" % (self._INFO_PATH, escaped_artist),
         "%s/web_%s.jpg" % (self._INFO_PATH, escaped_artist)
     ]
     for path in paths:
         if GLib.file_test(path, GLib.FileTest.EXISTS):
             return (True, path)
     return (False, None)
Beispiel #21
0
	def _UpdatePreview(self,e) :
		uri = self.FileChooserDialog.get_preview_uri()
		if uri!=None :
			if not GLib.file_test(GLib.filename_from_uri(uri,""),GLib.FileTest.IS_DIR) :
				file = Gio.File.new_for_uri(uri)
				file_info = file.query_info("*",Gio.FileQueryInfoFlags.NONE,None)
				mtime = file_info.get_attribute_uint64(Gio.FILE_ATTRIBUTE_TIME_MODIFIED)
				ThumbnailFactory = GnomeDesktop.DesktopThumbnailFactory.new(GnomeDesktop.DesktopThumbnailSize.NORMAL)
				thumbpath = ThumbnailFactory.lookup(uri,mtime)
				pixbuf = GdkPixbuf.Pixbuf.new_from_file(thumbpath)
				self.PreviewImage.set_from_pixbuf(pixbuf)
				self.FileChooserDialog.set_preview_widget_active(True)
			else :
				self.FileChooserDialog.set_preview_widget_active(False)
		else :
			self.FileChooserDialog.set_preview_widget_active(False)
Beispiel #22
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()
    def start_xorg(klass):
        '''start X.org server with dummy driver'''

        conf = os.path.join(os.path.dirname(__file__), 'xorg-dummy.conf')

        # some distros like Fedora install Xorg as suid root; copy it into our
        # workdir to drop the suid bit and run it as user
        if GLib.file_test('/usr/libexec/Xorg.bin', GLib.FileTest.IS_EXECUTABLE):
            xorg = '/usr/libexec/Xorg.bin'
        else:
            out = GLib.find_program_in_path ('Xorg')
            if not out:
                sys.stderr.write('ERROR: Xorg not installed\n')
                sys.exit(1)
            xorg = os.path.join(klass.workdir, 'Xorg')
            shutil.copy(out, xorg)

        display_num = 99

        if os.path.isfile('/tmp/.X%d-lock' % display_num):
            sys.stderr.write('Cannot start X.org, an instance already exists\n')
            sys.exit(1)

        # You can rename the log file to *.log if you want to see it on test
        # case failures
        log = os.path.join(klass.workdir, 'Xorg.out')
        klass.xorg = subprocess.Popen([xorg, '-config', conf, '-logfile', log, ':%d' % display_num],
                                      stderr=subprocess.PIPE)
        os.environ['DISPLAY'] = ':%d' % display_num

        # wait until the server is ready
        timeout = 50
        while timeout > 0:
            time.sleep(0.1)
            timeout -= 1
            if klass.xorg.poll():
                # ended prematurely
                timeout = -1
                break
            if subprocess.call(['xprop', '-root'], stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE) == 0:
                break
        if timeout <= 0:
            with open(log) as f:
                sys.stderr.write('Cannot start X.org with dummy driver.  Log:\n%s\n--------' % f.read())
            sys.exit(1)
Beispiel #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()
Beispiel #25
0
    def update(self):
        """
            Update database
        """
        if not Gio.NetworkMonitor.get_default().get_network_available():
            return
        # Update adblock_js repo
        git = GLib.find_program_in_path("git")
        if git is None:
            print(_("For stronger ad blocking, install git command"))
        else:
            if GLib.file_test(ADBLOCK_JS, GLib.FileTest.IS_DIR):
                argv = [git, "-C", ADBLOCK_JS, "pull"]
            else:
                argv = [
                    git, "clone",
                    "https://gitlab.gnome.org/gnumdk/eolie-adblock.git",
                    ADBLOCK_JS
                ]
            (pid, a1, a2,
             a3) = GLib.spawn_async(argv,
                                    flags=GLib.SpawnFlags.STDOUT_TO_DEV_NULL)
            GLib.spawn_close_pid(pid)

        # Check entries in DB, do we need to update?
        mtime = 0
        with SqlCursor(self) as sql:
            result = sql.execute("SELECT mtime FROM adblock\
                                  ORDER BY mtime LIMIT 1")
            v = result.fetchone()
            if v is not None:
                mtime = v[0]
        self.__cancellable.reset()
        if self.__adblock_mtime - mtime > self.__UPDATE:
            # Update host rules
            uris = list(self.__URIS)
            uri = uris.pop(0)
            self.__task_helper.load_uri_content(uri, self.__cancellable,
                                                self.__on_load_uri_content,
                                                uris)
        else:
            self.__on_save_rules()
Beispiel #26
0
 def _UpdatePreview(self, e):
     uri = self.FileChooserDialog.get_preview_uri()
     if uri != None:
         if not GLib.file_test(GLib.filename_from_uri(uri, ""),
                               GLib.FileTest.IS_DIR):
             file = Gio.File.new_for_uri(uri)
             file_info = file.query_info("*", Gio.FileQueryInfoFlags.NONE,
                                         None)
             mtime = file_info.get_attribute_uint64(
                 Gio.FILE_ATTRIBUTE_TIME_MODIFIED)
             ThumbnailFactory = GnomeDesktop.DesktopThumbnailFactory.new(
                 GnomeDesktop.DesktopThumbnailSize.NORMAL)
             thumbpath = ThumbnailFactory.lookup(uri, mtime)
             pixbuf = GdkPixbuf.Pixbuf.new_from_file(thumbpath)
             self.PreviewImage.set_from_pixbuf(pixbuf)
             self.FileChooserDialog.set_preview_widget_active(True)
         else:
             self.FileChooserDialog.set_preview_widget_active(False)
     else:
         self.FileChooserDialog.set_preview_widget_active(False)
Beispiel #27
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.')
Beispiel #28
0
    def _check_generate_menu(self, items):
        """Show the menu?"""
        # No items selected
        if not len(items):
            return False

        for item in items:
            if item.is_directory():
                self.type = 'Link'
            elif GLib.file_test(item.get_name(), GLib.FileTest.IS_EXECUTABLE):
                self.type = 'Application'
            else:
                self.type = 'Link'

        for item in items:  # XXX how useful ?
            if item.is_gone():
                continue
            self.execpath = urllib.unquote(item.get_uri()[7:])

        # All OK > Generate menu
        return True
Beispiel #29
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.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.registry = Grl.Registry.get_default()

        self.sparqltracker = TrackerWrapper().tracker
Beispiel #30
0
    def __init__(self, version):
        """
            Create application
            @param version as str
        """
        Gtk.Application.__init__(
            self,
            application_id="org.gnome.Lollypop",
            flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        self.__version = version
        self.set_property("register-session", True)
        GLib.setenv("PULSE_PROP_media.role", "music", True)
        GLib.setenv("PULSE_PROP_application.icon_name", "org.gnome.Lollypop",
                    True)

        # Ideally, we will be able to delete this once Flatpak has a solution
        # for SSL certificate management inside of applications.
        if GLib.file_test("/app", GLib.FileTest.EXISTS):
            paths = [
                "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/cert.pem",
                "/etc/ssl/cert.pem"
            ]
            for path in paths:
                if GLib.file_test(path, GLib.FileTest.EXISTS):
                    GLib.setenv("SSL_CERT_FILE", path, True)
                    break

        self.cursors = {}
        self.window = None
        self.notify = None
        self.lastfm = None
        self.librefm = None
        self.debug = False
        self.__fs = None
        self.__externals_count = 0
        self.__init_proxy()
        GLib.set_application_name("Lollypop")
        GLib.set_prgname("lollypop")
        self.add_main_option("play-ids", b"a", GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING, "Play ids", None)
        self.add_main_option("debug", b"d", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Debug lollypop", None)
        self.add_main_option("set-rating", b"r", GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING, "Rate the current track",
                             None)
        self.add_main_option("play-pause", b"t", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Toggle playback", None)
        self.add_main_option("next", b"n", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to next track", None)
        self.add_main_option("prev", b"p", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to prev track", None)
        self.add_main_option("emulate-phone", b"e", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Emulate an Android Phone",
                             None)
        self.add_main_option("version", b"V", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Lollypop version", None)
        self.connect("command-line", self.__on_command_line)
        self.connect("handle-local-options", self.__on_handle_local_options)
        self.connect("activate", self.__on_activate)
        self.register(None)
        if self.get_is_remote():
            Gdk.notify_startup_complete()
        self.__listen_to_gnome_sm()
Beispiel #31
0
    def __init__(self, version):
        """
            Create application
            @param version as str
        """
        Gtk.Application.__init__(
            self,
            application_id="org.gnome.Lollypop",
            flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        self.__version = version
        self.set_property("register-session", True)
        signal(SIGINT, lambda a, b: self.quit())
        signal(SIGTERM, lambda a, b: self.quit())
        # Set main thread name
        # We force it to current python 3.6 name, to be sure in case of
        # change in python
        current_thread().setName("MainThread")
        set_proxy_from_gnome()
        GLib.setenv("PULSE_PROP_media.role", "music", True)
        GLib.setenv("PULSE_PROP_application.icon_name", "org.gnome.Lollypop",
                    True)
        # Fix proxy for python
        proxy = GLib.environ_getenv(GLib.get_environ(), "all_proxy")
        if proxy is not None and proxy.startswith("socks://"):
            proxy = proxy.replace("socks://", "socks4://")
            from os import environ
            environ["all_proxy"] = proxy
            environ["ALL_PROXY"] = proxy
        # Ideally, we will be able to delete this once Flatpak has a solution
        # for SSL certificate management inside of applications.
        if GLib.file_test("/app", GLib.FileTest.EXISTS):
            paths = [
                "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/cert.pem",
                "/etc/ssl/cert.pem"
            ]
            for path in paths:
                if GLib.file_test(path, GLib.FileTest.EXISTS):
                    GLib.setenv("SSL_CERT_FILE", path, True)
                    break
        self.cursors = {}
        self.notify = None
        self.scrobblers = []
        self.debug = False
        self.shown_sidebar_tooltip = False
        self.__window = None
        self.__fs_window = None
        self.__scanner_timeout_id = None
        self.__scanner_uris = []
        GLib.set_application_name("Lollypop")
        GLib.set_prgname("lollypop")
        self.add_main_option("play-ids", b"a", GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING, "Play ids", None)
        self.add_main_option("debug", b"d", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Debug Lollypop", None)
        self.add_main_option("set-rating", b"r", GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING, "Rate the current track",
                             None)
        self.add_main_option("play-pause", b"t", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Toggle playback", None)
        self.add_main_option("stop", b"s", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Stop playback", None)
        self.add_main_option("next", b"n", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to next track", None)
        self.add_main_option("prev", b"p", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Go to prev track", None)
        ## anhsirk0 edits
        self.add_main_option("set-next", b"m", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Set next track by track id",
                             None)
        ## anhsirk0 edits ends

        self.add_main_option("emulate-phone", b"e", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Emulate a Librem phone",
                             None)
        self.add_main_option("version", b"v", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Lollypop version", None)
        self.connect("command-line", self.__on_command_line)
        self.connect("handle-local-options", self.__on_handle_local_options)
        self.connect("activate", self.__on_activate)
        self.connect("shutdown", lambda a: self.__save_state())
        self.register(None)
        if self.get_is_remote():
            Gdk.notify_startup_complete()
Beispiel #32
0
 def _check_executable(self, file):
     """True if the file seems executable"""
     return GLib.file_test(file.get_location().get_path(),
                           GLib.FileTest.IS_EXECUTABLE)
Beispiel #33
0
 def __init__(self, version, extension_dir):
     """
         Create application
         @param version as str
         @param extension_dir as str
     """
     self.__version = version
     self.__state_cache = []
     signal(SIGINT, lambda a, b: self.quit())
     signal(SIGTERM, lambda a, b: self.quit())
     # Set main thread name
     # We force it to current python 3.6 name, to be sure in case of
     # change in python
     current_thread().setName("MainThread")
     # First check WebKit2 version
     if WebKit2.MINOR_VERSION < 20:
         exit("You need WebKit2GTK >= 2.20")
     Gtk.Application.__init__(
         self,
         application_id="org.gnome.Eolie",
         flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
     self.set_property("register-session", True)
     # Fix proxy for python
     proxy = GLib.environ_getenv(GLib.get_environ(), "all_proxy")
     if proxy is not None and proxy.startswith("socks://"):
         proxy = proxy.replace("socks://", "socks4://")
         from os import environ
         environ["all_proxy"] = proxy
         environ["ALL_PROXY"] = proxy
     # Ideally, we will be able to delete this once Flatpak has a solution
     # for SSL certificate management inside of applications.
     if GLib.file_test("/app", GLib.FileTest.EXISTS):
         paths = [
             "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/cert.pem",
             "/etc/ssl/cert.pem"
         ]
         for path in paths:
             if GLib.file_test(path, GLib.FileTest.EXISTS):
                 GLib.setenv("SSL_CERT_FILE", path, True)
                 break
     self.sync_worker = None  # Not initialised
     self.__extension_dir = extension_dir
     self.show_tls = False
     self.cursors = {}
     GLib.set_application_name('Eolie')
     GLib.set_prgname('org.gnome.Eolie')
     self.add_main_option("private", b'p', GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Add a private page", None)
     self.add_main_option("new", b'n', GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Add a new window", None)
     self.add_main_option("disable-artwork-cache", b'a',
                          GLib.OptionFlags.NONE, GLib.OptionArg.NONE,
                          "Do not use cache for art", None)
     self.add_main_option("show-tls", b't', GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Show TLS info", None)
     self.connect("activate", self.__on_activate)
     self.connect("handle-local-options", self.__on_handle_local_options)
     self.connect("command-line", self.__on_command_line)
     self.register(None)
     if self.get_is_remote():
         Gdk.notify_startup_complete()
Beispiel #34
0
        def new(*args, **kwargs):
            return Gtk.Box(*args, **kwargs)

    Gtk.Box = gtk_box


def gtk_process_events():
    while Gtk.events_pending():
        Gtk.main_iteration()


IconTheme = Gtk.IconTheme.get_default()
try:
    for dir in IconDir:
        if GLib.file_test(dir, GLib.FileTest.IS_DIR) and \
           dir not in IconTheme.get_search_path():
            IconTheme.prepend_search_path(dir)
except (AttributeError, NameError, TypeError):
    for dir in IconDir:
        if GLib.file_test(dir, GLib.FileTest.IS_DIR):
            IconTheme.prepend_search_path(dir)


def protect_pango_markup(str_, quote=True):
    return html_escape(str_, quote) if str_ else ""


def protect_markup_dict(dict_):
    return dict((k, protect_pango_markup(v)) for (k, v) in dict_.items())
Beispiel #35
0
def check_current():
    if (glib.file_test('/etc/prime/current_type', glib.FileTest.EXISTS)):
        return glib.file_get_contents('/etc/prime/current_type')[1].decode("utf-8").strip()
    else:
        return ''
Beispiel #36
0
	def _UpdatePreview(self,e) :
		PreviewURI = self.FileChooserDialog.get_preview_uri()
		PreviewFile = self.FileChooserDialog.get_preview_file()
		if PreviewURI!=None and PreviewFile !=None :
			if not GLib.file_test(PreviewFile.get_path(),GLib.FileTest.IS_DIR) :
				PreviewFileInfo = PreviewFile.query_info("*",Gio.FileQueryInfoFlags.NONE,None)
				mimetype = PreviewFileInfo.get_content_type();
				name = PreviewFile.get_basename()
				xml = name[len(name)-3:len(name)].lower() == 'xml'
				if not xml :
					mtime = PreviewFileInfo.get_modification_time().tv_sec
					ThumbnailFactory = GnomeDesktop.DesktopThumbnailFactory.new(GnomeDesktop.DesktopThumbnailSize.NORMAL)
					ThumbnailPath = ThumbnailFactory.lookup(PreviewURI,mtime)
					if ThumbnailPath != None :
						pixbuf = GdkPixbuf.Pixbuf.new_from_file(ThumbnailPath)
					else :
						pixbuf = ThumbnailFactory.generate_thumbnail(PreviewURI,mimetype)
						ThumbnailFactory.save_thumbnail(pixbuf,PreviewURI,mtime)
					self.PreviewImage.set_from_pixbuf(pixbuf)
					PreviewWidth = pixbuf.get_option("tEXt::Thumb::Image::Width")
					PreviewHeight = pixbuf.get_option("tEXt::Thumb::Image::Height")
					self.Label_Size.set_label( PreviewWidth + " x " + PreviewHeight)
					self.FileChooserDialog.set_preview_widget_active(True)
					self.LabelInfo.hide()
					self.PreviewImage.show()
					self.Label_Size.show()
					self.xmlBox.hide()

				else :
					xml_file_path = PreviewFile.get_path()
					xml_data = file(xml_file_path,'r').read()
					root = etree.fromstring(xml_data)
					if root.tag == "background" :
						nodeset = root.xpath('/background/static/file')
						for i in range(len(self.listImage)) :
							self.listImage.pop(0)
						if len(nodeset) :
							for i in range(len(nodeset)):
								background_path = nodeset[i].text
								gfile = Gio.File.new_for_path(background_path)
								fileInfo = gfile.query_info("*",Gio.FileQueryInfoFlags.NONE,None)
								mtime = fileInfo.get_modification_time().tv_sec
								mimetype = fileInfo.get_content_type()
								name = fileInfo.get_name()
								uri = gfile.get_uri()
								ThumbnailFactory = GnomeDesktop.DesktopThumbnailFactory.new(GnomeDesktop.DesktopThumbnailSize.NORMAL)
								ThumbnailPath = ThumbnailFactory.lookup(uri,mtime)
								if ThumbnailPath :
									pixbuf = GdkPixbuf.Pixbuf.new_from_file(ThumbnailPath)
								else :
									pixbuf = ThumbnailFactory.generate_thumbnail(uri,mimetype)
									ThumbnailFactory.save_thumbnail(pixbuf,uri,mtime)
								self.listImage.append(pixbuf)
								self.LabelInfo.hide()
								self.PreviewImage.show()
								self.Label_Size.show()
								self.xmlBox.show()
								self.listImageIndex = 0;
								self.change_pixbuf(self,0)
							self.FileChooserDialog.set_preview_widget_active(True)
						else :
							self.LabelInfo.set_text("No Image")
							self.LabelInfo.show()
							self.PreviewImage.hide()
							self.Label_Size.hide()
							self.xmlBox.hide()
							self.FileChooserDialog.set_preview_widget_active(True)
					else :
						self.LabelInfo.set_text("Invalid XML Background")
						self.LabelInfo.show()
						self.PreviewImage.hide()
						self.Label_Size.hide()
						self.xmlBox.hide()
						self.FileChooserDialog.set_preview_widget_active(True)
			else :
				self.FileChooserDialog.set_preview_widget_active(False)
		else :
			self.FileChooserDialog.set_preview_widget_active(False)
Beispiel #37
0
            gtk_box_real.__init__ (self, *args, **kwargs)
            if orientation:
                gtk_box_real.set_orientation(self, orientation)

        def new(*args, **kwargs):
            return Gtk.Box(*args, **kwargs)
    Gtk.Box = gtk_box

def gtk_process_events ():
    while Gtk.events_pending ():
        Gtk.main_iteration ()

IconTheme = Gtk.IconTheme.get_default()
try:
    for dir in IconDir:
        if GLib.file_test(dir, GLib.FileTest.IS_DIR) and \
           dir not in IconTheme.get_search_path():
            IconTheme.prepend_search_path(dir)
except (AttributeError, NameError, TypeError):
    for dir in IconDir:
        if GLib.file_test(dir, GLib.FileTest.IS_DIR):
            IconTheme.prepend_search_path(dir)

def protect_pango_markup (str_, quote=True):
    return html_escape(str_, quote) if str_ else ""

def protect_markup_dict (dict_):
    return dict((k, protect_pango_markup (v)) for (k, v) in dict_.items())

class Image (Gtk.Image):
Beispiel #38
0
    def open(self, epub_path: str):
        """
        Open an epub file from the path provided

        :param epub_path: The path to the epub file
        :raises BookError: When the file or format is incorrect.
        """
        if not GLib.file_test(epub_path, GLib.FileTest.EXISTS):
            raise BookError(0, _('File does not exist'), epub_path)

        if not GLib.file_test(epub_path, GLib.FileTest.IS_REGULAR):
            raise BookError(0, _('Is a directory'), epub_path)

        epub_zip = self._open_zip_archive(epub_path)

        if epub_zip is None:
            raise BookError(0, _('Could not read zip format'), epub_path)

        if not self._has_epub_mime(epub_zip):
            raise BookError(0, _('Unrecognized file format'), epub_path)

        try:
            opf_path = self._read_opf_path(epub_zip)
            if opf_path is None:
                raise BookError(0, '')
        except BookError:
            raise BookError(0, _('Broken or missing OPF file'), epub_path)

        try:
            opf_content = self._read_inner_zip_path(epub_zip, opf_path)
        except BookError:
            raise BookError(0, _('Could not read OPF file'), epub_path)

        opf_mime = 'application/oebps-package+xml'
        opf_elem = self._bytes_to_elem(opf_content, opf_mime)
        opf_elem = opf_elem.getroot()

        self.version = opf_elem.get('version')
        self.metadata = self._get_opf_metadata(opf_elem)
        self.identifier = self.metadata.get('identifier', [''])[0]
        self.title = self.metadata.get('title', [''])[0]
        self.language = self.metadata.get('language', [''])[0]

        opf_resources = self._get_opf_resources(opf_path, opf_elem, epub_zip)
        self.resources = opf_resources[0]
        self.resources_by_id = opf_resources[1]
        self.cover_doc = ''
        self.cover = ''

        # TODO: Cover EPUB2 (from OPF manifest)
        #         img_types = [
        #             'image/gif',
        #             'image/jpeg',
        #             'image/jpg',
        #             'image/png',
        #             'image/svg+xml'
        #         ]
        #         if res_type in img_types:
        #             if 'cover-image' in res_props:
        #                 self.cover_img = res_path
        #
        # TODO: Cover EPUB3 (from OPF manifest)
        #         if res_type == 'application/xhtml+xml':
        #             elif 'cover' in res_props:
        #                 self.cover_doc = res_path
        #
        # TODO: Cover EPUB3 (from guide)
        #                 if ref_type == 'cover':
        #                     if not self.cover_doc:
        #                         self.cover_doc = ref_href

        self.direction = self._get_opf_progression_direction(opf_elem)
        self.spine_primary, self.spine_auxiliary = self._get_opf_spine(
            opf_elem)
        self.guide = self._get_opf_guide(opf_path, opf_elem)
        # TODO: self.navigation = self._get_opf_navigation(opf_elem)
        self.pages_positions = self._calculate_pages_positions()

        self.toc_path = self._get_toc_path(opf_elem)
        self.path = epub_path
Beispiel #39
0
    def __init__(self, view, window):
        """
            Init child
            @param view as View
            @param window as Window
        """
        Gtk.FlowBoxChild.__init__(self)
        self.__view = view
        self.__window = window
        self.__favicon = None
        self.__connected_ids = []
        self.__scroll_timeout_id = None
        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Eolie/PagesManagerChild.ui")
        builder.connect_signals(self)
        self.__indicator_label = LabelIndicator()
        self.__indicator_label.mark_unshown(view.webview)
        self.__indicator_label.set_hexpand(True)
        self.__indicator_label.set_margin_right(4)
        self.__indicator_label.set_property("halign", Gtk.Align.CENTER)
        self.__indicator_label.set_property("valign", Gtk.Align.CENTER)
        self.__indicator_label.set_ellipsize(Pango.EllipsizeMode.END)
        self.__indicator_label.show()
        if view.webview.title:
            self.__indicator_label.set_text(view.webview.title)
        builder.get_object("grid").attach(self.__indicator_label, 0, 0, 1, 1)
        self.__image = builder.get_object("image")
        self.__close_button = builder.get_object("close_button")
        self.__audio_indicator = builder.get_object("audio_indicator")
        if view.webview.is_playing_audio():
            self.__audio_indicator.show()
        self.__close_button.get_image().set_from_icon_name(
                                                  "window-close-symbolic",
                                                  Gtk.IconSize.INVALID)
        self.__close_button.get_image().set_property("pixel-size",
                                                     ArtSize.FAVICON)
        self.__spinner = builder.get_object("spinner")
        self.add(builder.get_object("widget"))

        self.get_style_context().add_class("sidebar-item")

        self.set_property("has-tooltip", True)
        self.set_property("halign", Gtk.Align.START)
        self.set_margin_start(20)
        self.set_margin_end(20)
        self.set_margin_top(20)
        self.set_margin_bottom(20)
        self.set_size_request(ArtSize.START_WIDTH +
                              ArtSize.PREVIEW_WIDTH_MARGIN,
                              ArtSize.START_HEIGHT +
                              ArtSize.PREVIEW_WIDTH_MARGIN)
        self.connect("query-tooltip", self.__on_query_tooltip)
        view.connect("destroying", self.__on_view_destroying)
        self.__connected_signals = []
        self.__connected_signals.append(
            self.__view.webview.connect("favicon-changed",
                                        self.__on_webview_favicon_changed))
        self.__connected_signals.append(
            self.__view.webview.connect(
                                    "notify::is-playing-audio",
                                    self.__on_webview_notify_is_playing_audio))
        self.__connected_signals.append(
            self.__view.webview.connect("uri-changed",
                                        self.__on_webview_uri_changed))
        self.__connected_signals.append(
            self.__view.webview.connect("title-changed",
                                        self.__on_webview_title_changed))
        self.__connected_signals.append(
            self.__view.webview.connect("scroll-event",
                                        self.__on_webview_scroll_event))
        self.__connected_signals.append(
            self.__view.webview.connect("load-changed",
                                        self.__on_webview_load_changed))
        self.__connected_signals.append(
            self.__view.webview.connect("shown",
                                        self.__on_webview_shown))
        self.__set_favicon_artwork()
        if self.__view.webview.uri is not None:
            artwork_path = El().art.get_path(self.__view.webview.uri, "start")
            if artwork_path is not None and\
                    GLib.file_test(artwork_path, GLib.FileTest.IS_REGULAR):
                self.__image.set_from_file(artwork_path)
Beispiel #40
0
 def __on_populars_scheme(self, request):
     """
         Show populars web pages
         @param request as WebKit2.URISchemeRequest
     """
     uri = request.get_uri()
     parsed = urlparse(uri)
     items = []
     start_page = App().settings.get_value("start-page").get_string()
     wanted = App().settings.get_value("max-popular-items").get_int32()
     if start_page == "popular_book":
         reset_function = "reset_bookmark"
         for (item_id, uri, title) in App().bookmarks.get_populars(wanted):
             items.append((title, uri, "", 1))
     else:
         reset_function = "reset_history"
         for (item_id, uri,
              netloc, title, count) in App().history.get_populars(
                 parsed.netloc,
                 wanted):
             items.append((title, uri, netloc, count))
     start = Gio.File.new_for_uri("resource:///org/gnome/Eolie/start.html")
     end = Gio.File.new_for_uri("resource:///org/gnome/Eolie/end.html")
     (status, start_content, tag) = start.load_contents(None)
     (status, end_content, tag) = end.load_contents(None)
     # Update start
     html_start = start_content.decode("utf-8")
     html_start = html_start.replace("@TITLE@", _("Popular pages"))
     fake = Gtk.Entry.new()
     style_context = fake.get_style_context()
     (found, color) = style_context.lookup_color("theme_selected_bg_color")
     if found:
         color.alpha = 0.2
         html_start = html_start.replace("@BACKGROUND_COLOR@",
                                         color.to_string())
     else:
         html_start = html_start.replace("@BACKGROUND_COLOR@",
                                         "rgba(74,144,217,0.2)")
     idx = 0
     for (title, uri, netloc, count) in items:
         element_id = "element_%s" % idx
         idx += 1
         if count == 1:  # No navigation for one page
             netloc = uri
         path = App().art.get_path(uri, "start")
         if path is None or\
                 not GLib.file_test(path, GLib.FileTest.IS_REGULAR):
             continue
         favicon_path = App().art.get_favicon_path(netloc)
         if favicon_path is not None:
             favicon_uri = "file://%s" % favicon_path
         else:
             favicon_uri = "internal://applications-internet"
         html_start += '<a class="child" id="%s"\
                        title="%s" href="%s">\
                        <img src="file://%s"></img>\
                        <div class="caption">%s\
                        <img onclick="%s(event, %s, %s)"\
                             class="close_button">\
                        <img class="favicon" src="%s">\
                        </img></img></div></a>' % (
             element_id, title, netloc, path,
             title, reset_function,
             "'%s'" % netloc,
             "'%s'" % element_id, favicon_uri)
     html = html_start.encode("utf-8") + end_content
     stream = Gio.MemoryInputStream.new_from_data(html)
     request.finish(stream, -1, "text/html")
Beispiel #41
0
    def __init(self):
        """
            Init main application
        """
        self.settings = Settings.new()

        # Init extensions
        GLib.setenv("PYTHONPATH", self.__extension_dir, True)

        # Create favicon path
        if not GLib.file_test(self.__FAVICONS_PATH, GLib.FileTest.IS_DIR):
            GLib.mkdir_with_parents(self.__FAVICONS_PATH, 0o0750)

        # Add a global DBus helper
        self.helper = DBusHelper()
        # First init sync worker
        from eolie.mozilla_sync import SyncWorker
        if SyncWorker.check_modules():
            self.sync_worker = SyncWorker()
            # Run a first sync in 10 seconds, speed up app start
            GLib.timeout_add_seconds(10, self.sync_worker.sync, False)
            # Then run a sync every hour
            GLib.timeout_add_seconds(3600, self.sync_worker.sync, True)
        else:
            self.sync_worker = None
        if self.prefers_app_menu():
            menu = self.get_app_menu()
            self.set_app_menu(menu)
        cssProviderFile = Gio.File.new_for_uri(
            'resource:///org/gnome/Eolie/application.css')
        cssProvider = Gtk.CssProvider()
        cssProvider.load_from_file(cssProviderFile)
        screen = Gdk.Screen.get_default()
        styleContext = Gtk.StyleContext()
        styleContext.add_provider_for_screen(screen, cssProvider,
                                             Gtk.STYLE_PROVIDER_PRIORITY_USER)
        self.history = DatabaseHistory()
        self.bookmarks = DatabaseBookmarks()
        # We store cursors for main thread
        SqlCursor.add(self.history)
        SqlCursor.add(self.bookmarks)
        self.websettings = DatabaseSettings()
        self.adblock = DatabaseAdblock()
        self.adblock.update()
        self.phishing = DatabasePhishing()
        self.adblock_exceptions = DatabaseExceptions("adblock")
        # Do not remove this!
        self.update_default_style_sheet()
        self.popup_exceptions = DatabaseExceptions("popups")
        self.image_exceptions = DatabaseExceptions("images")
        if self.settings.get_user_value("jsblock") is not None:
            self.js_exceptions = DatabaseExceptions("js")
        else:
            self.js_exceptions = None
        self.phishing.update()
        self.art = Art()
        self.search = Search()
        self.download_manager = DownloadManager()
        self.pages_menu = PagesMenu()

        # Check MOZ_PLUGIN_PATH
        if self.settings.get_value('enable-plugins') and\
                not GLib.getenv("MOZ_PLUGIN_PATH"):
            print("You need to set MOZ_PLUGIN_PATH to use plugins")

        # https://wiki.ubuntu.com/Unity/LauncherAPI
        self.__unity = None
        if is_unity():
            try:
                gi.require_version('Unity', '7.0')
                from gi.repository import Unity
                self.__unity = Unity.LauncherEntry.get_for_desktop_id(
                    "org.gnome.Eolie.desktop")
            except:
                pass

        # Init profiles
        self.set_profiles()

        shortcut_action = Gio.SimpleAction.new('shortcut',
                                               GLib.VariantType.new('s'))
        shortcut_action.connect('activate', self.__on_shortcut_action)
        self.add_action(shortcut_action)
        self.set_accels_for_action("win.shortcut::expose", ["<Alt>e"])
        self.set_accels_for_action("win.exceptions::site", ["<Control>e"])
        self.set_accels_for_action("win.shortcut::show_left_panel", ["F9"])
        self.set_accels_for_action("win.shortcut::uri",
                                   ["<Control>l", "<Control>b"])
        self.set_accels_for_action("win.shortcut::new_page", ["<Control>t"])
        self.set_accels_for_action("win.shortcut::last_page",
                                   ["<Control><Shift>t"])
        self.set_accels_for_action("app.shortcut::new_window", ["<Control>n"])
        self.set_accels_for_action("win.shortcut::private",
                                   ["<Control><Shift>p"])
        self.set_accels_for_action("win.shortcut::close_page", ["<Control>w"])
        self.set_accels_for_action("win.shortcut::quit", ["<Control>q"])
        self.set_accels_for_action("win.shortcut::save", ["<Control><Shift>s"])
        self.set_accels_for_action("win.shortcut::filter", ["<Control>i"])
        self.set_accels_for_action("win.shortcut::reload",
                                   ["<Control>r", "F5"])
        self.set_accels_for_action("win.shortcut::home", ["<Control>Home"])
        self.set_accels_for_action("win.shortcut::find", ["<Control>f"])
        self.set_accels_for_action("win.shortcut::print", ["<Control>p"])
        self.set_accels_for_action("win.shortcut::source",
                                   ["<Control><Shift>c"])
        self.set_accels_for_action("win.shortcut::history", ["<Control>h"])
        self.set_accels_for_action("win.shortcut::search", ["<Control>k"])
        self.set_accels_for_action("win.shortcut::fullscreen", ["F11"])
        self.set_accels_for_action("app.settings", ["<Control>s"])
        self.set_accels_for_action("win.shortcut::backward",
                                   ["<Alt>Left", "XF86Back"])
        self.set_accels_for_action("win.shortcut::forward",
                                   ["<Alt>Right", "XF86Forward"])
        self.set_accels_for_action("win.shortcut::next",
                                   ["<Control>Tab", "<Control>Page_Down"])
        self.set_accels_for_action("win.shortcut::previous",
                                   ["<Control><Shift>Tab", "<Control>Page_Up"])
        self.set_accels_for_action("win.shortcut::next_site",
                                   ["<Control>twosuperior"])
        self.set_accels_for_action("win.shortcut::previous_site",
                                   ["<Control><Shift>twosuperior"])
        self.set_accels_for_action(
            "win.shortcut::zoom_in",
            ["<Control>KP_Add", "<Control>plus", "<Control>equal"])
        self.set_accels_for_action("win.shortcut::zoom_out",
                                   ["<Control>KP_Subtract", "<Control>minus"])
        self.set_accels_for_action("win.shortcut::zoom_default",
                                   ["<Control>KP_0", "<Control>0"])
 def _check_executable(self, file):
     """True if the file seems executable"""
     return GLib.file_test(file.get_location().get_path(), GLib.FileTest.IS_EXECUTABLE)
Beispiel #43
0
 def __init__(self, version, data_dir):
     """
         Create application
         @param version as str
         @param data_dir as str
     """
     Gtk.Application.__init__(
         self,
         application_id="org.gnome.Lollypop",
         flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
     self.__version = version
     self.__data_dir = data_dir
     self.set_property("register-session", True)
     signal(SIGINT, lambda a, b: self.quit())
     signal(SIGTERM, lambda a, b: self.quit())
     # Set main thread name
     # We force it to current python 3.6 name, to be sure in case of
     # change in python
     current_thread().setName("MainThread")
     (self.__proxy_host, self.__proxy_port) = init_proxy_from_gnome()
     GLib.setenv("PULSE_PROP_media.role", "music", True)
     GLib.setenv("PULSE_PROP_application.icon_name", "org.gnome.Lollypop",
                 True)
     # Ideally, we will be able to delete this once Flatpak has a solution
     # for SSL certificate management inside of applications.
     if GLib.file_test("/app", GLib.FileTest.EXISTS):
         paths = [
             "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/cert.pem",
             "/etc/ssl/cert.pem"
         ]
         for path in paths:
             if GLib.file_test(path, GLib.FileTest.EXISTS):
                 GLib.setenv("SSL_CERT_FILE", path, True)
                 break
     self.cursors = {}
     self.debug = False
     self.shown_sidebar_tooltip = False
     self.__window = None
     self.__fs_window = None
     settings = Gio.Settings.new("org.gnome.desktop.interface")
     self.animations = settings.get_value("enable-animations").get_boolean()
     GLib.set_application_name("Lollypop")
     GLib.set_prgname("lollypop")
     self.add_main_option("play-ids", b"a", GLib.OptionFlags.NONE,
                          GLib.OptionArg.STRING, "Play ids", None)
     self.add_main_option("debug", b"d", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Debug Lollypop", None)
     self.add_main_option("set-rating", b"r", GLib.OptionFlags.NONE,
                          GLib.OptionArg.STRING, "Rate the current track",
                          None)
     self.add_main_option("play-pause", b"t", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Toggle playback", None)
     self.add_main_option("stop", b"s", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Stop playback", None)
     self.add_main_option("next", b"n", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Go to next track", None)
     self.add_main_option("prev", b"p", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Go to prev track", None)
     self.add_main_option("emulate-phone", b"e", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Emulate a Librem phone",
                          None)
     self.add_main_option("version", b"v", GLib.OptionFlags.NONE,
                          GLib.OptionArg.NONE, "Lollypop version", None)
     self.connect("command-line", self.__on_command_line)
     self.connect("handle-local-options", self.__on_handle_local_options)
     self.connect("activate", self.__on_activate)
     self.connect("shutdown", lambda a: self.__save_state())
     self.register(None)
     if self.get_is_remote():
         Gdk.notify_startup_complete()
     if GLib.environ_getenv(GLib.get_environ(), "DEBUG_LEAK") is not None:
         import gc
         gc.set_debug(gc.DEBUG_LEAK)