Example #1
1
def startfile(filepath, operation="open"):
    """os.startfile / g_app_info_launch_default_for_uri compat

    This has the similar semantics to os.startfile, where it's
    supported: it launches the given file or folder path with the
    default app. On Windows, operation can be set to "edit" to use the
    default editor for a file. The operation parameter is ignored on
    other systems, and GIO's equivalent routine is used.

    The relevant app is started in the background, and there are no
    means for getting its pid.

    """
    try:
        if os.name == 'nt':
            os.startfile(filepath, operation) # raises: WindowsError
        else:
            uri = GLib.filename_to_uri(filepath)
            Gio.app_info_launch_default_for_uri(uri, None) # raises: GError
        return True
    except:
        logger.exception(
            "Failed to launch the default application for %r (op=%r)",
            filepath,
            operation,
        )
        return False
    def __upgrade_16(self):
        """
            Get ride of paths
        """
        paths = Lp().settings.get_value('music-path')
        uris = []
        for path in paths:
            uris.append(GLib.filename_to_uri(path))
        Lp().settings.set_value('music-uris', GLib.Variant('as', uris))
        with SqlCursor(self._db) as sql:
            sql.execute("ALTER TABLE albums RENAME TO tmp_albums")
            sql.execute('''CREATE TABLE albums (
                                              id INTEGER PRIMARY KEY,
                                              name TEXT NOT NULL,
                                              no_album_artist BOOLEAN NOT NULL,
                                              year INT,
                                              uri TEXT NOT NULL,
                                              popularity INT NOT NULL,
                                              synced INT NOT NULL,
                                              mtime INT NOT NULL)''')

            sql.execute('''INSERT INTO albums(id, name, no_album_artist,
                        year, uri, popularity, synced, mtime) SELECT
                            id, name, no_album_artist,
                            year, path, popularity, synced, mtime FROM
                            tmp_albums''')
            sql.execute("DROP TABLE tmp_albums")
            result = sql.execute("SELECT rowid, uri FROM albums")
            for (rowid, uri) in result:
                if uri.startswith("/"):
                    uri = GLib.filename_to_uri(uri)
                    sql.execute("UPDATE albums set uri=? WHERE rowid=?",
                                (uri, rowid))
            sql.commit()
    def __upgrade_13(self):
        """
            Convert tracks filepath column to uri
        """
        with SqlCursor(self._db) as sql:
            sql.execute("ALTER TABLE tracks RENAME TO tmp_tracks")
            sql.execute('''CREATE TABLE tracks (id INTEGER PRIMARY KEY,
                                              name TEXT NOT NULL,
                                              uri TEXT NOT NULL,
                                              duration INT,
                                              tracknumber INT,
                                              discnumber INT,
                                              discname TEXT,
                                              album_id INT NOT NULL,
                                              year INT,
                                              popularity INT NOT NULL,
                                              ltime INT NOT NULL,
                                              mtime INT NOT NULL,
                                              persistent INT NOT NULL
                                              DEFAULT 1)''')

            sql.execute('''INSERT INTO tracks(id, name, uri, duration,
                        tracknumber, discnumber, discname, album_id,
                        year, popularity, ltime, mtime, persistent) SELECT
                            id, name, filepath, duration,
                            tracknumber, discnumber, discname, album_id,
                            year, popularity, ltime, mtime, persistent FROM
                          tmp_tracks''')
            sql.execute("DROP TABLE tmp_tracks")
            result = sql.execute("SELECT rowid FROM tracks")
            for track_id in list(itertools.chain(*result)):
                result = sql.execute("SELECT uri FROM tracks WHERE rowid=?",
                                     (track_id,))
                v = result.fetchone()
                if v is not None:
                    uri = v[0]
                    if uri.startswith("/"):
                        uri = GLib.filename_to_uri(uri)
                        sql.execute("UPDATE tracks set uri=? WHERE rowid=?",
                                    (uri, track_id))
            sql.commit()
        with SqlCursor(Lp().playlists) as sql:
            sql.execute("ALTER TABLE tracks RENAME TO tmp_tracks")
            sql.execute('''CREATE TABLE tracks (playlist_id INT NOT NULL,
                                                uri TEXT NOT NULL)''')
            sql.execute('''INSERT INTO tracks(playlist_id, uri) SELECT
                            playlist_id, filepath FROM tmp_tracks''')
            sql.execute("DROP TABLE tmp_tracks")
            result = sql.execute("SELECT uri FROM tracks")
            for path in list(itertools.chain(*result)):
                if path.startswith("/"):
                    uri = GLib.filename_to_uri(path)
                    sql.execute("UPDATE tracks set uri=? WHERE uri=?",
                                (uri, path))
            sql.commit()
Example #4
0
 def _on_command_line(self, app, app_cmd_line):
     """
         Handle command line
         @param app as Gio.Application
         @param options as Gio.ApplicationCommandLine
     """
     self._externals_count = 0
     options = app_cmd_line.get_options_dict()
     if options.contains('set-rating'):
         value = options.lookup_value('set-rating').get_int32()
         if value > 0 and value < 6 and\
                 Lp.player.current_track.id is not None:
             Lp.player.current_track.set_popularity(value)
     args = app_cmd_line.get_arguments()
     if len(args) > 1:
         Lp.player.clear_externals()
         for f in args[1:]:
             try:
                 f = GLib.filename_to_uri(f)
             except:
                 pass
             self._parser.parse_async(f, True,
                                      None, None)
     if Lp.window is not None:
         Lp.window.present()
     return 0
Example #5
0
def _filename2uri_freedesktop_canon(path, encoding=None):
    """Filename-to-URI for the thumbnailer.

      >>> path = u'/tmp/smile (\u263a).ora'
      >>> _filename2uri_freedesktop_canon(path, encoding='UTF-8')
      'file:///tmp/smile%20(%E2%98%BA).ora'

    Freedesktop thumbnailing requires the canonical URI for the filename in
    order for the hashes used it generates to be interoperable with other
    programs. In particular, ``()`` brackets must not be encoded.

    :param path: the path to encode; must be a unicode object.
    :param encoding: override the filesystem encoding for testing.
      If left unspecified, then the system filesystem encoding will be assumed:
      see `sys.getfilesystemencoding()`. Normally that's correct.
    :rtype: str, containing a canonical URI.

    """
    # TODO: Investigate whether this could be used as
    # TODO: a general replacement for lib.fileutils.filename2uri().
    assert type(path) is unicode
    assert os.path.isabs(path)
    if encoding is None:
        encoding = sys.getfilesystemencoding()
    path_bytes = path.encode(encoding)
    return GLib.filename_to_uri(path_bytes, None)
Example #6
0
 def parse_playlist(self, playlist_name, callback):
     parser = TotemPlParser.Parser()
     parser.connect('entry-parsed', self._on_entry_parsed, callback)
     parser.parse_async(
         GLib.filename_to_uri(self.get_path_to_playlist(playlist_name), None),
         False, None, None, None
     )
Example #7
0
    def add_to_playlist(self, playlist_name, uris):
        parser = TotemPlParser.Parser()
        playlist = TotemPlParser.Playlist()
        pl_file = Gio.file_new_for_path(self.get_path_to_playlist(playlist_name))

        def parse_callback(parser, uri, metadata, data):
            _iter = playlist.append()
            playlist.set_value(_iter, TotemPlParser.PARSER_FIELD_URI, uri)

        def end_callback(parser, uri, data):
            for uri in uris:
                _iter = playlist.append()
                playlist.set_value(_iter, TotemPlParser.PARSER_FIELD_URI, uri)

                def get_callback(source, param, item):
                    self.emit('song-added-to-playlist', playlist_name, item)
                grilo.get_media_from_uri(uri, get_callback)

            parser.save(playlist, pl_file, playlist_name, TotemPlParser.ParserType.PLS)

        parser.connect('entry-parsed', parse_callback, playlist)
        parser.connect('playlist-ended', end_callback, playlist)
        parser.parse_async(
            GLib.filename_to_uri(self.get_path_to_playlist(playlist_name), None),
            False, None, None, None
        )
Example #8
0
    def __init__(self, pdfname):
        """
        Constructor
        
        Positional arguments:
        pdfname -- The filename of the PDF document, which will be annotated
        """

        self.pdfname = abspath(pdfname)
        uri = GLib.filename_to_uri(self.pdfname, None)
        self.pdf = Poppler.Document.new_from_file(uri, None)
        search.set_pdf(self.pdf)
        self.width = 0
        self.height = 0
        self.pages = []
        history.reset()
                
        for i in range(self.pdf.get_n_pages()):
            page = Page(self, self.pdf.get_page(i), i)
            self.pages.append(page)
            
            self.width = max(self.width, page.width)
            self.height += page.height
            self.num_of_pages = len(self.pages)
        
        print(_("The document has {} pages").format(self.num_of_pages))
Example #9
0
 def get_album_artwork_uri(self, album):
     """
         Look for artwork in dir:
         - favorite from settings first
         - Artist_Album.jpg then
         - Any any supported image otherwise
         @param album as Album
         @return cover uri as string
     """
     if album.id is None:
         return None
     try:
         filename = self.get_album_cache_name(album) + ".jpg"
         uris = [
             # Used when album.uri is readonly
             GLib.filename_to_uri(self._STORE_PATH + "/" + filename),
             # Default favorite artwork
             album.uri + "/" + self.__favorite,
             # Used when having muliple albums in same folder
             album.uri + "/" + filename
         ]
         for uri in uris:
             f = Gio.File.new_for_uri(uri)
             if f.query_exists():
                 return uri
     except:
         pass
     return None
Example #10
0
    def uri(self):
        """Get track file uri

        @return str
        """
        if path.exists(self.path):
            return GLib.filename_to_uri(self.path)
Example #11
0
 def finish(self, item, pixbuf, path, callback, itr):
     try:
         if path:
             item.set_thumbnail(GLib.filename_to_uri(path, None))
         GLib.idle_add(callback, pixbuf, path, itr)
     except Exception as e:
         logger.warn("Error: %s" % e)
Example #12
0
 def get_infos(self, path):
     try:
         uri = GLib.filename_to_uri(path)
         infos = self._tagreader.discover_uri(uri)
         return infos
     except:
         return None
Example #13
0
    def __init__(self, fileName, tipo=None):
        self.operation = Gtk.PrintOperation()
        setting = Gtk.PageSetup()

        st = Gtk.PrintSettings()
        s = Gtk.PageSetup()
        if tipo == "singolo":
            ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
            s.set_paper_size(ps)
            margine_fondo = float(setconf("Stampa", "singolo_margine_basso")or 4.3)
            s.set_bottom_margin(margine_fondo, Gtk.Unit.MM)
            margine_sinistro = float(
                setconf("Stampa", "singolo_margine_sinistro")or 4.3)
            s.set_left_margin(margine_sinistro, Gtk.Unit.MM)
            margine_destro = float(
                setconf("Stampa", "singolo_margine_destro")or 4.3)
            s.set_right_margin(margine_destro, Gtk.Unit.MM)
            margine_alto = float(setconf("Stampa", "singolo_margine_alto")or 4.3)
            s.set_top_margin(margine_alto, Gtk.Unit.MM)
            orientamento = str(setconf("Stampa", "singolo_ori"))
            if orientamento == "orizzontale":
                s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
        elif tipo == "report":
            ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
            s.set_paper_size(ps)
            margine_fondo = float(setconf("Stampa", "report_margine_basso") or 4.3
            )
            s.set_bottom_margin(margine_fondo, Gtk.Unit.MM)
            margine_sinistro = float(
                setconf("Stampa", "report_margine_sinistro")or 4.3)
            s.set_left_margin(margine_sinistro, Gtk.Unit.MM)
            margine_destro = float(
                setconf("Stampa", "report_margine_destro")or 4.3)
            s.set_right_margin(margine_destro, Gtk.Unit.MM)
            margine_alto = float(setconf("Stampa", "report_margine_alto")or 4.3)
            s.set_top_margin(margine_alto, Gtk.Unit.MM)
            orientamento = str(setconf("Stampa", "report_ori"))
            if not orientamento or orientamento == "orizzontale":
                s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
        elif tipo =="label":
            from promogest.lib.PyPDF2.pdf import PdfFileReader
            input1 = PdfFileReader(file(fileName))
            input1.getPage(0).mediaBox
            larg = input1.getPage(0).mediaBox[2]
            alte = input1.getPage(0).mediaBox[3]
            ps = Gtk.PaperSize.new_custom("cc", "cc", alte, larg, Gtk.Unit.POINTS)
            s.set_paper_size(ps)
            s.set_right_margin(0, Gtk.Unit.MM)
            s.set_left_margin(0, Gtk.Unit.MM)
            s.set_bottom_margin(0, Gtk.Unit.MM)
            s.set_top_margin(0, Gtk.Unit.MM)
            s.set_orientation(Gtk.PageOrientation.LANDSCAPE)

        self.operation.set_default_page_setup(s)
        self.operation.connect('begin-print', self.begin_print, None)
        self.operation.connect('draw-page', self.draw_page, None)
        file_uri = GLib.filename_to_uri(os.path.abspath(fileName))

        self.doc = Poppler.Document.new_from_file(file_uri)
Example #14
0
    def _on_row_activated(self, font_list, tree_path, column):
        if column == font_list.get_column(self._ViewColumn.NAME):
            font_set = font_list.get_model()
            path = font_set[tree_path][FontSet.COL_LINKS][0].source
            if not os.path.isfile(path):
                return

            _show_uri(GLib.filename_to_uri(path), self.get_toplevel())
Example #15
0
    def on_wallpaper_downloaded(self, downloader):
        os.rename(downloader.get_downloaded_file(), self.wallpaper_path)

        wallpaper_setting = GSetting('org.gnome.desktop.background.picture-uri')
        wallpaper_setting.set_value(GLib.filename_to_uri(self.wallpaper_path, None))

        n = Notify.Notification.new(self.__title__, "Set wallpaper successfully!", 'ubuntu-tweak')
        n.show()
Example #16
0
 def uri(self):
     """
         Get track file uri
         @return str
     """
     if self._uri is not None:
         return self._uri
     else:
         return GLib.filename_to_uri(self.path)
Example #17
0
def main():
    window = Gtk.Window()
    view = WebKit2.WebView()
    settings = view.get_settings()
    window.connect('destroy', Gtk.main_quit)
    window.add(view)
    view.load_uri(GLib.filename_to_uri(_path.abspath(sys.argv[1]), None))
    window.show_all()
    Gtk.main()
Example #18
0
 def get_infos(self, path):
     """
         Return informations on file at path
         @param path as str
         @return GstPbutils.DiscovererInfo
     """
     uri = GLib.filename_to_uri(path)
     infos = self._tagreader.discover_uri(uri)
     return infos
Example #19
0
 def _startPlaying(self):
     self._alreadyPlaying = True
     name = self._current_url.split("/")[-1]
     if self._convert_button.get_sensitive():
         uri = GLib.filename_to_uri(os.path.join(os.getcwd(), "data", name), None)
     else:
         uri = GLib.filename_to_uri(os.path.join(os.getcwd(), "data", name + ".part"), None)
     if not self._current_entry.audio_only:
         pipe = Gst.parse_launch("uridecodebin uri=" + uri +" name=d ! xvimagesink name=my_video_sink d. ! autoaudiosink")
     else:
         pipe = Gst.parse_launch("uridecodebin uri=" + uri + " ! tee name=t ! queue ! audioresample ! audioconvert ! synaescope shader=3 ! videoconvert ! xvimagesink name=my_video_sink t. ! queue ! audioresample ! audioconvert ! autoaudiosink")
     pipeline = SimplePipeline(pipe, pipe.get_by_name("my_video_sink"))
     pipeline.connect("eos", self._eosCb)
     if self.pipeline:
         self.pipeline.setState(Gst.State.NULL)
     self.pipeline = pipeline
     self.viewer.setPipeline(pipeline)
     self.viewer._playButtonCb(None, None)
Example #20
0
 def _finish(self):
     """
         Notify from main thread when scan finished
     """
     self.stop()
     self.emit("scan-finished")
     if self._missing_codecs is not None:
         Lp.player.load_external(GLib.filename_to_uri(self._missing_codecs))
         Lp.player.play_first_external()
 def get_subject_origin(self, uri):
     scheme = GLib.uri_parse_scheme(uri)
     if scheme == 'file':
         return GLib.path_get_dirname(uri)
     elif scheme in ('http', 'https'):
         scheme, domain = uri.split('://', 1)
         return '%s://%s' % (scheme, domain.split('/', 1)[0])
     else:
         return GLib.filename_to_uri(
             self.get_path(force_directory=True), None)
Example #22
0
 def _finish(self):
     """
         Notify from main thread when scan finished
     """
     Lp().settings.set_value('db-mtime', GLib.Variant('i', int(time())))
     self.stop()
     self.emit("scan-finished")
     if self._missing_codecs is not None:
         Lp().player.load_external(
                                 GLib.filename_to_uri(self._missing_codecs))
         Lp().player.play_first_external()
Example #23
0
  def pixbuf_for(self, full_path, is_dir):
    if is_dir:
      logging.debug('%s is a dir', full_path)
      return self.dir_icon

    uri = GLib.filename_to_uri(full_path)
    gio_file = Gio.File.new_for_path(full_path)
    file_info = gio_file.query_info('*', Gio.FileQueryInfoFlags.NONE, None)
    mtime = file_info.get_attribute_uint64(Gio.FILE_ATTRIBUTE_TIME_MODIFIED)

    # Use existing thumbnail if any.
    if self._thumbnail_factory:
      existing_thumbnail = self._thumbnail_factory.lookup(uri, mtime)
    else:
      existing_thumbnail = file_info.get_attribute_byte_string(Gio.FILE_ATTRIBUTE_THUMBNAIL_PATH)
    if existing_thumbnail:
      logging.debug('%s has existing thumbnail', full_path)
      image = Gtk.Image.new_from_file(existing_thumbnail)
      if image:
        return image.get_pixbuf()
      else:
        logging.debug('%s failed to load existing thumbnail', full_path)

    # Attempt to generate a new thumbnail, saving the result as appropriate.
    if self._thumbnail_factory:
      mime_type = file_info.get_attribute_as_string(Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE)
      if self._thumbnail_factory.can_thumbnail(uri, mime_type, mtime):
        logging.debug('%s can be thumbnailed by GNOME thumbnailer', full_path)
        pixbuf = self._thumbnail_factory.generate_thumbnail(uri, mime_type)
        if pixbuf:
          self._thumbnail_factory.save_thumbnail(pixbuf, uri, mtime)
          return pixbuf
        else:
          logging.debug('%s could NOT be thumbnailed by GNOME thumbnailer after all', full_path)
          self._thumbnail_factory.create_failed_thumbnail(uri, mtime)

    # Use an appropriate icon.
    icon = file_info.get_icon()
    if icon:
      icon_info = self._theme.lookup_by_gicon(icon, _ICON_SIZE, Gtk.IconLookupFlags(0))
      if icon_info:
        loaded_icon = icon_info.load_icon()
        if loaded_icon:
          logging.debug('%s has a suggested icon', full_path)
          return loaded_icon
        else:
          logging.debug('%s icon suggestion could not be loaded', full_path)
      else:
        logging.debug('%s icon suggestion could not be looked up in current theme', full_path)
    else:
      logging.debug('%s has NO particular icon suggestion', full_path)

    # As last resort, use a generic file icon.
    return self.file_icon
Example #24
0
    def _set_grilo_thumbnail_path(self):
        # TODO: This sets the thumbnail path for the Grilo Media object
        # to be used by MPRIS. However, calling this by default for
        # every cache hit is unnecessary.
        album = utils.get_album_title(self._media)
        artist = utils.get_artist_name(self._media)

        success, thumb_file = MediaArt.get_file(artist, album, "album")
        if success:
            self._media.set_thumbnail(
                GLib.filename_to_uri(thumb_file.get_path(), None))
Example #25
0
 def _finish(self):
     """
         Notify from main thread when scan finished
     """
     self.stop()
     self.emit("scan-finished")
     if Lp().settings.get_value('artist-artwork'):
         Lp().art.cache_artists_art()
     if self._missing_codecs is not None:
         Lp().player.load_external(
                                 GLib.filename_to_uri(self._missing_codecs))
         Lp().player.play_first_external()
Example #26
0
	def on_download_requested(self,web_view,download):
		#dest = webkit_download_get_uri()
		#webkit_download_set_destination_uri(download, dest);
		uri = download.get_uri()
		destination_download_uri = GLib.filename_to_uri(GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD) + '/'+ download.get_suggested_filename())
		download.set_destination_uri(destination_download_uri)
		download.connect("notify::status", self.on_notify_status)
		download.connect("notify::progress", self.on_download_progress)
		download.connect("error", self.on_download_error)
		#download.start()

		return True
Example #27
0
        def do_callback(pixbuf):
            if not pixbuf:
                surface = DefaultIcon(self._scale).get(DefaultIcon.Type.music,
                                                       art_size)
            else:
                surface = _make_icon_frame(pixbuf, art_size, self._scale)

                # Sets the thumbnail location for MPRIS to use.
                item.set_thumbnail(GLib.filename_to_uri(thumb_file.get_path(),
                                                        None))

            GLib.idle_add(callback, surface, itr)
            return
Example #28
0
    def __init__(self):
        try:
            Query.music_folder = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC)
            assert Query.music_folder is not None
        except (TypeError, AssertionError):
            logger.warn("XDG Music dir is not set")
            return

        Query.MUSIC_URI = Tracker.sparql_escape_string(GLib.filename_to_uri(Query.music_folder))

        for folder in [Query.music_folder]:
            if os.path.islink(folder):
                logger.warn("%s is a symlink, this folder will be omitted", folder)
Example #29
0
 def load_external(self, uri, name=''):
     try:
         uri = GLib.filename_to_uri(uri)
     except:
         pass
     track = Track()
     track.artist = name
     track.uri = uri
     if track.uri.startswith('file://'):
         track.id = Type.EXTERNALS
     else:
         track.id = Type.RADIOS
     self._external_tracks.append(track)
Example #30
0
 def _finish(self):
     """
         Notify from main thread when scan finished
     """
     if self._progress is not None:
         self._progress.hide()
         self._progress.set_fraction(0.0)
         self._progress = None
     self._in_thread = False
     self._is_locked = False
     self.emit("scan-finished")
     if self._missing_codecs is not None:
         Lp.player.load_external(GLib.filename_to_uri(self._missing_codecs))
         Lp.player.play_first_external()
Example #31
0
    def __init__(self):
        super().__init__()

        # FIXME: This is now duplicated here and in GrlTrackerWrapper.
        try:
            music_folder = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_MUSIC)
            assert music_folder is not None
        except (TypeError, AssertionError):
            self._content_text = _("Your XDG Music directory is not set.")
            return

        music_folder = Tracker.sparql_escape_string(
            GLib.filename_to_uri(music_folder))

        href_text = "<a href='{}'>{}</a>".format(music_folder,
                                                 _("Music folder"))

        # TRANSLATORS: This is a label to display a link to open user's music
        # folder. {} will be replaced with the translated text 'Music folder'
        folder_text = _("The contents of your {} will appear here.")
        self._content_text = folder_text.format(href_text)

        self._state = EmptyView.State.INITIAL
Example #32
0
 def on_show_styles(self, widget, data=None):
     if self.styles_path:
         show_uri(self, GLib.filename_to_uri(self.styles_path, 'file'))
Example #33
0
    def __init__(self):
        """
            Init dialog
        """
        self.__choosers = []
        self.__cover_tid = None
        self.__mix_tid = None
        self.__popover = None

        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Lollypop/SettingsDialog.ui")
        self.__progress = builder.get_object("progress")
        self.__infobar = builder.get_object("infobar")
        self.__reset_button = builder.get_object("reset_button")
        if App().lastfm is not None and App().lastfm.is_goa:
            builder.get_object("lastfm_error_label").set_text(
                _('Using "GNOME Online Accounts" settings'))
        if App().scanner.is_locked():
            builder.get_object("reset_button").set_sensitive(False)
        artists = App().artists.count()
        albums = App().albums.count()
        tracks = App().tracks.count()
        builder.get_object("artists").set_text(
            ngettext("%d artist", "%d artists", artists) % artists)
        builder.get_object("albums").set_text(
            ngettext("%d album", "%d albums", albums) % albums)
        builder.get_object("tracks").set_text(
            ngettext("%d track", "%d tracks", tracks) % tracks)

        self.__popover_transitions = builder.get_object("popover-transitions")
        self.__scale_transition_duration = builder.get_object(
            "scale_transition_duration")
        self.__scale_transition_duration.set_range(1, 20)
        self.__scale_transition_duration.set_value(
            App().settings.get_value("transition-duration").get_int32())

        self.__popover_compilations = builder.get_object(
            "popover-compilations")

        self.__settings_dialog = builder.get_object("settings_dialog")
        self.__settings_dialog.set_transient_for(App().window)

        if App().settings.get_value("disable-csd"):
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object("header_bar")
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        switch_scan = builder.get_object("switch_scan")
        switch_scan.set_state(App().settings.get_value("auto-update"))

        switch_view = builder.get_object("switch_dark")
        if App().gtk_application_prefer_dark_theme:
            switch_view.set_sensitive(False)
        else:
            switch_view.set_state(App().settings.get_value("dark-ui"))

        switch_background = builder.get_object("switch_background")
        switch_background.set_state(
            App().settings.get_value("background-mode"))

        switch_state = builder.get_object("switch_state")
        switch_state.set_state(App().settings.get_value("save-state"))

        switch_network_access = builder.get_object("switch_network_access")
        network_access = App().settings.get_value("network-access")
        switch_network_access.set_state(network_access)

        switch_transitions = builder.get_object("switch_transitions")
        smooth_transitions = App().settings.get_value("smooth-transitions")
        switch_transitions.set_state(smooth_transitions)
        builder.get_object("transitions_button").set_sensitive(
            smooth_transitions)

        switch_mix_party = builder.get_object("switch_mix_party")
        switch_mix_party.set_state(App().settings.get_value("party-mix"))

        switch_artwork_tags = builder.get_object("switch_artwork_tags")
        grid_behaviour = builder.get_object("grid_behaviour")
        # Check for kid3-cli
        self.__check_for_kid3(switch_artwork_tags, grid_behaviour)

        switch_genres = builder.get_object("switch_genres")
        switch_genres.set_state(App().settings.get_value("show-genres"))

        switch_compilations_in_album_view = builder.get_object(
            "switch_compilations_in_album_view")
        switch_compilations_in_album_view.set_state(
            App().settings.get_value("show-compilations-in-album-view"))

        switch_compilations = builder.get_object("switch_compilations")
        show_compilations = App().settings.get_value("show-compilations")
        switch_compilations.set_state(show_compilations)
        builder.get_object("compilations_button").set_sensitive(
            show_compilations)

        switch_artwork = builder.get_object("switch_artwork")
        switch_artwork.set_state(App().settings.get_value("artist-artwork"))

        combo_orderby = builder.get_object("combo_orderby")
        combo_orderby.set_active(App().settings.get_enum(("orderby")))

        combo_preview = builder.get_object("combo_preview")

        scale_coversize = builder.get_object("scale_coversize")
        scale_coversize.set_range(170, 300)
        scale_coversize.set_value(
            App().settings.get_value("cover-size").get_int32())
        self.__settings_dialog.connect("destroy", self.__edit_settings_close)

        self.__flowbox = builder.get_object("flowbox")

        self.__set_outputs(combo_preview)

        builder.connect_signals(self)

        #
        # Music tab
        #
        dirs = []
        for directory in App().settings.get_value("music-uris"):
            dirs.append(directory)

        # Main chooser
        self.__main_chooser = ChooserWidget()
        image = Gtk.Image.new_from_icon_name("list-add-symbolic",
                                             Gtk.IconSize.MENU)
        self.__main_chooser.set_icon(image)
        self.__main_chooser.set_action(self.__add_chooser)
        self.__flowbox.add(self.__main_chooser)
        if len(dirs) > 0:
            uri = dirs.pop(0)
        else:
            filename = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_MUSIC)
            if filename:
                uri = GLib.filename_to_uri(filename)
            else:
                uri = "/opt"

        self.__main_chooser.set_dir(uri)

        # Others choosers
        for directory in dirs:
            self.__add_chooser(directory)

        #
        # Google tab
        #
        key = App().settings.get_value("cs-api-key").get_string() or\
            App().settings.get_default_value("cs-api-key").get_string()
        builder.get_object("cs-entry").set_text(key)

        #
        # ListenBrainz tab
        #
        token = App().settings.get_value(
            "listenbrainz-user-token").get_string()
        builder.get_object("listenbrainz_user_token_entry").set_text(token)

        from lollypop.helper_passwords import PasswordsHelper
        helper = PasswordsHelper()
        #
        # Last.fm tab
        #
        if App().lastfm is not None:
            self.__lastfm_test_image = builder.get_object("lastfm_test_image")
            self.__lastfm_login = builder.get_object("lastfm_login")
            self.__lastfm_password = builder.get_object("lastfm_password")
            helper.get("lastfm", self.__on_get_password)
            if not App().lastfm.is_goa:
                builder.get_object("lastfm_grid").set_sensitive(True)
                builder.get_object("lastfm_error_label").hide()
        #
        # Libre.fm tab
        #
        if App().lastfm is not None:
            self.__librefm_test_image = builder.get_object(
                "librefm_test_image")
            self.__librefm_login = builder.get_object("librefm_login")
            self.__librefm_password = builder.get_object("librefm_password")
            helper.get("librefm", self.__on_get_password)
            builder.get_object("librefm_grid").set_sensitive(True)
            builder.get_object("librefm_error_label").hide()
Example #34
0
    def row_activated(self, tree, path, col):
        uri = GLib.filename_to_uri(
            self.projectDir + "/" + self.listStore[path][m.TITLE] +
            self.listStore[path][m.DATE] + ".webm", None)

        Gio.AppInfo.launch_default_for_uri(uri, None)
Example #35
0
    def save_album_artwork(self, data, album_id):
        """
            Save data for album id
            @param data as bytes
            @param album id as int
        """
        try:
            album = Album(album_id)
            arturi = None
            # Check portal for kid3-cli
            can_set_cover = False
            try:
                bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
                proxy = Gio.DBusProxy.new_sync(
                                            bus, Gio.DBusProxyFlags.NONE, None,
                                            'org.gnome.Lollypop.Portal',
                                            '/org/gnome/LollypopPortal',
                                            'org.gnome.Lollypop.Portal', None)
                can_set_cover = proxy.call_sync(
                                               'CanSetCover', None,
                                               Gio.DBusCallFlags.NO_AUTO_START,
                                               500, None)[0]
            except:
                print("You are missing lollypop-portal: "
                      "https://github.com/gnumdk/lollypop-portal")
            save_to_tags = Lp().settings.get_value('save-to-tags') and\
                can_set_cover and not album.is_web

            uri_count = Lp().albums.get_uri_count(album.uri)
            filename = self.get_album_cache_name(album) + ".jpg"
            if save_to_tags:
                t = Thread(target=self.__save_artwork_tags,
                           args=(data, album))
                t.daemon = True
                t.start()

            store_path = self._STORE_PATH + "/" + filename
            if album.uri == "" or is_readonly(album.uri):
                arturi = GLib.filename_to_uri(store_path)
            # Many albums with same path, suffix with artist_album name
            elif uri_count > 1:
                arturi = album.uri + "/" + filename
                favorite_uri = album.uri + "/" + self.__favorite
                favorite = Lio.File.new_for_uri(favorite_uri)
                if favorite.query_exists():
                    favorite.trash()
            else:
                arturi = album.uri + "/" + self.__favorite
            f = Lio.File.new_for_uri(arturi)
            # Update cover file if exists even if we have written to tags
            if not save_to_tags or f.query_exists():
                stream = Gio.MemoryInputStream.new_from_data(data, None)
                pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale(
                                                               stream,
                                                               ArtSize.MONSTER,
                                                               ArtSize.MONSTER,
                                                               True,
                                                               None)
                stream.close()
                pixbuf.savev(store_path, "jpeg", ["quality"],
                             [str(Lp().settings.get_value(
                                                'cover-quality').get_int32())])
                dst = Lio.File.new_for_uri(arturi)
                src = Lio.File.new_for_path(store_path)
                src.move(dst, Gio.FileCopyFlags.OVERWRITE, None, None)
                del pixbuf
                self.clean_album_cache(album)
                GLib.idle_add(self.album_artwork_update, album.id)
        except Exception as e:
            print("Art::save_album_artwork(): %s" % e)
Example #36
0
 def __on_command_line(self, app, app_cmd_line):
     """
         Handle command line
         @param app as Gio.Application
         @param options as Gio.ApplicationCommandLine
     """
     args = app_cmd_line.get_arguments()
     options = app_cmd_line.get_options_dict()
     if options.contains("debug"):
         self.debug = True
     if options.contains("set-rating"):
         value = options.lookup_value("set-rating").get_string()
         try:
             value = min(max(0, int(value)), 5)
             if self.player.current_track.id is not None:
                 self.player.current_track.set_rate(value)
         except Exception as e:
             Logger.error("Application::__on_command_line(): %s", e)
             pass
     elif options.contains("play-pause"):
         self.player.play_pause()
     elif options.contains("stop"):
         self.player.stop()
     elif options.contains("play-ids"):
         try:
             value = options.lookup_value("play-ids").get_string()
             ids = value.split(";")
             tracks = []
             for id in ids:
                 if id[0:2] == "a:":
                     album = Album(int(id[2:]))
                     tracks += album.tracks
                 else:
                     tracks.append(Track(int(id[2:])))
             self.player.load(tracks[0])
             self.player.populate_playlist_by_tracks(tracks, [Type.SEARCH])
         except Exception as e:
             Logger.error("Application::__on_command_line(): %s", e)
             pass
     elif options.contains("next"):
         self.player.next()
     elif options.contains("prev"):
         self.player.prev()
     elif options.contains("emulate-phone"):
         self.window.container.add_fake_phone()
     elif len(args) > 1:
         uris = []
         pls = []
         for uri in args[1:]:
             try:
                 uri = GLib.filename_to_uri(uri)
             except:
                 pass
             f = Gio.File.new_for_uri(uri)
             if is_audio(f):
                 uris.append(uri)
             elif is_pls(f):
                 pls.append(uri)
         if pls:
             from gi.repository import TotemPlParser
             parser = TotemPlParser.Parser.new()
             parser.connect("entry-parsed", self.__on_entry_parsed, uris)
             parser.parse_async(uri, True, None, self.__on_parse_finished,
                                uris)
         else:
             self.__on_parse_finished(None, None, uris)
     elif self.window is not None:
         self.window.setup()
         if not self.window.is_visible():
             # https://bugzilla.gnome.org/show_bug.cgi?id=766284
             monotonic_time = int(GLib.get_monotonic_time() / 1000)
             self.window.present_with_time(monotonic_time)
             self.player.emit("status-changed")
             self.player.emit("current-changed")
     Gdk.notify_startup_complete()
     return 0
Example #37
0
 def __on_file_scheme(self, request):
     """
         Show populars web pages
         @param request as WebKit2.URISchemeRequest
     """
     try:
         uri = request.get_uri()
         parent = "/".join(uri.rstrip("/").split("/")[:-1])
         f = Gio.File.new_for_uri(uri)
         info = f.query_info("standard::type",
                             Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
                             None)
         if info.get_file_type() == Gio.FileType.DIRECTORY:
             start = Gio.File.new_for_uri(
                 "resource:///org/gnome/Eolie/start_file.html")
             end = Gio.File.new_for_uri(
                 "resource:///org/gnome/Eolie/end_file.html")
             (status, start_content, tag) = start.load_contents(None)
             (status, end_content, tag) = end.load_contents(None)
             html_start = start_content.decode("utf-8")
             html_start = html_start.replace("@PATH@", f.get_path())
             html_start = html_start.replace("@NAME@", _("Name"))
             html_start = html_start.replace("@SIZE@", _("Size"))
             html_start = html_start.replace("@LAST_MODIFICATION@",
                                             _("Last modification"))
             if parent:
                 html_start += '<tr>'\
                               '<td><a class="dir" href="%s">%s</a></td>'\
                               '<td></td>'\
                               '<td></td></tr>' % (
                                   parent, "..")
             try:
                 infos = f.enumerate_children(
                     "standard::name,standard::size,"
                     "standard::type,time::modified",
                     Gio.FileQueryInfoFlags.NONE,
                     None)
                 dirs = {}
                 files = {}
                 for info in infos:
                     name = info.get_name()
                     if f.get_path() == "/":
                         filename = "/%s" % name
                     else:
                         filename = "%s/%s" % (f.get_path(), name)
                     uri = GLib.filename_to_uri(filename)
                     mtime = info.get_attribute_uint64("time::modified")
                     size = round((info.get_size() / 1024), 2)
                     date_str = datetime.fromtimestamp(mtime).strftime(
                         "%Y-%m-%d %H:%M:%S")
                     if info.get_file_type() == Gio.FileType.DIRECTORY:
                         dirs[uri] = (name, size, date_str)
                     else:
                         files[uri] = (name, size, date_str)
                 for uri, (name, size, date_str) in sorted(dirs.items()):
                     html_start += '<tr>'\
                                   '<td><a class="dir" href="%s">'\
                                   '%s</a></td>'\
                                   '<td>%s KB</td>'\
                                   '<td>%s</td></tr>' % (
                                       uri, name, size, date_str)
                 for uri, (name, size, date_str) in sorted(files.items()):
                     html_start += '<tr>'\
                                   '<td><a class="file" href="%s">'\
                                   '%s</a></td>'\
                                   '<td>%s KB</td>'\
                                   '<td>%s</td></tr>' % (
                                       uri, name, size, date_str)
             except Exception as e:
                 infos = []
                 html_start += '<tr>'\
                               '<td>%s</td>'\
                               '<td></td>'\
                               '<td></td></tr>' % e
             html = html_start.encode("utf-8") + end_content
             stream = Gio.MemoryInputStream.new_from_data(html)
             request.finish(stream, -1, "text/html")
         else:
             request.finish(f.read(), -1, None)
     except Exception as e:
         request.get_web_view().emit("load-failed",
                                     WebKit2.LoadEvent.FINISHED,
                                     uri,
                                     GLib.Error(str(e)))
Example #38
0
 def __location_clicked_cb(self, unused_button, directory):
     uri = GLib.filename_to_uri(directory, None)
     Gio.AppInfo.launch_default_for_uri(uri, None)
Example #39
0
    def __on_command_line(self, app, app_cmd_line):
        """
            Handle command line
            @param app as Gio.Application
            @param options as Gio.ApplicationCommandLine
        """
        try:
            args = app_cmd_line.get_arguments()
            options = app_cmd_line.get_options_dict()
            if options.contains("debug"):
                self.debug = True
            # We are forced to enable scrobblers here if we want full debug
            if not self.scrobblers:
                if LastFM is not None:
                    self.scrobblers = [LastFM("lastfm"), LastFM("librefm")]
                self.load_listenbrainz()
            if options.contains("set-rating"):
                value = options.lookup_value("set-rating").get_string()
                try:
                    value = min(max(0, int(value)), 5)
                    if self.player.current_track.id is not None:
                        self.player.current_track.set_rate(value)
                except Exception as e:
                    Logger.error("Application::__on_command_line(): %s", e)
                    pass
            elif options.contains("play-pause"):
                self.player.play_pause()
            elif options.contains("stop"):
                self.player.stop()
            ## anhsirk0 edits
            elif options.contains("set-next"):
                try:
                    track_id = int(args[1])
                    try:
                        self.player.append_to_queue(track_id, notify=True)
                    except:
                        pass
                except:
                    pass

            ## anhsirk0 edits ends

            elif options.contains("play-ids"):
                try:
                    value = options.lookup_value("play-ids").get_string()
                    ids = value.split(";")
                    tracks = []
                    for id in ids:
                        if id[0:2] == "a:":
                            album = Album(int(id[2:]))
                            tracks += album.tracks
                        else:
                            tracks.append(Track(int(id[2:])))
                    self.player.load(tracks[0])
                    self.player.populate_playlist_by_tracks(
                        tracks, [Type.SEARCH])
                except Exception as e:
                    Logger.error("Application::__on_command_line(): %s", e)
                    pass
            elif options.contains("next"):
                self.player.next()
            elif options.contains("prev"):
                self.player.prev()
            elif options.contains("emulate-phone"):
                self.__window.toolbar.end.devices_popover.add_fake_phone()
            elif len(args) > 1:
                uris = []
                pls = []
                for uri in args[1:]:
                    try:
                        uri = GLib.filename_to_uri(uri)
                    except:
                        pass
                    f = Gio.File.new_for_uri(uri)
                    if not f.query_exists():
                        uri = GLib.filename_to_uri(
                            "%s/%s" % (GLib.get_current_dir(), uri))
                        f = Gio.File.new_for_uri(uri)
                    if is_audio(f):
                        uris.append(uri)
                    elif is_pls(f):
                        pls.append(uri)
                    else:
                        info = f.query_info(Gio.FILE_ATTRIBUTE_STANDARD_TYPE,
                                            Gio.FileQueryInfoFlags.NONE, None)
                        if info.get_file_type() == Gio.FileType.DIRECTORY:
                            uris.append(uri)
                if pls:
                    from gi.repository import TotemPlParser
                    parser = TotemPlParser.Parser.new()
                    parser.connect("entry-parsed", self.__on_entry_parsed,
                                   uris)
                    parser.parse_async(uri, True, None,
                                       self.__on_parse_finished, uris)
                else:
                    self.__on_parse_finished(None, None, uris)
            elif self.__window is not None:
                if not self.__window.is_visible():
                    self.__window.present()
                    self.player.emit("status-changed")
                    self.player.emit("current-changed")
            Gdk.notify_startup_complete()
        except Exception as e:
            Logger.error("Application::__on_command_line(): %s", e)
        return 0
Example #40
0
 def finish(self, pixbuf):
     if pixbuf:
         # Cache the path on the original item for faster retrieval
         self.item.set_thumbnail(GLib.filename_to_uri(self.path, None))
     self.callback(pixbuf, self.path, self.data)
Example #41
0
 def __on_command_line(self, app, app_cmd_line):
     """
         Handle command line
         @param app as Gio.Application
         @param options as Gio.ApplicationCommandLine
     """
     try:
         args = app_cmd_line.get_arguments()
         options = app_cmd_line.get_options_dict()
         if options.contains("debug"):
             self.debug = True
         if options.contains("set-rating"):
             value = options.lookup_value("set-rating").get_string()
             try:
                 value = min(max(0, int(value)), 5)
                 if self.player.current_track.id is not None:
                     self.player.current_track.set_rate(value)
             except Exception as e:
                 Logger.error("Application::__on_command_line(): %s", e)
                 pass
         elif options.contains("play-pause"):
             self.player.play_pause()
         elif options.contains("stop"):
             self.player.stop()
         elif options.contains("play-ids"):
             try:
                 value = options.lookup_value("play-ids").get_string()
                 ids = value.split(";")
                 albums = []
                 for id in ids:
                     if id[0:2] == "a:":
                         album = Album(int(id[2:]))
                         self.player.add_album(album)
                         albums.append(album)
                     else:
                         track = Track(int(id[2:]))
                         self.player.add_album(track.album)
                         albums.append(track.album)
                 if albums and albums[0].tracks:
                     self.player.load(albums[0].tracks[0])
             except Exception as e:
                 Logger.error("Application::__on_command_line(): %s", e)
                 pass
         elif options.contains("next"):
             self.player.next()
         elif options.contains("prev"):
             self.player.prev()
         elif options.contains("emulate-phone"):
             self.__window.toolbar.end.devices_popover.add_fake_phone()
         elif len(args) > 1:
             audio_uris = []
             playlist_uris = []
             for uri in args[1:]:
                 parsed = urlparse(uri)
                 if parsed.scheme not in ["http", "https"]:
                     try:
                         uri = GLib.filename_to_uri(uri)
                     except:
                         pass
                     f = Gio.File.new_for_uri(uri)
                     # Try ./filename
                     if not f.query_exists():
                         uri = GLib.filename_to_uri(
                             "%s/%s" % (GLib.get_current_dir(), uri))
                         print(uri)
                         f = Gio.File.new_for_uri(uri)
                 file_type = get_file_type(uri)
                 if file_type == FileType.PLS:
                     playlist_uris.append(uri)
                 else:
                     audio_uris.append(uri)
             if playlist_uris:
                 self.__parse_uris(playlist_uris, audio_uris)
             else:
                 self.__on_parse_finished(None, None, [], audio_uris)
         elif self.__window is not None:
             if not self.__window.is_visible():
                 self.__window.present()
                 emit_signal(self.player, "status-changed")
                 emit_signal(self.player, "current-changed")
         Gdk.notify_startup_complete()
     except Exception as e:
         Logger.error("Application::__on_command_line(): %s", e)
     return 0
Example #42
0
    def _load_track(self, track_id, sql=None):
        stop = False

        # Stop if needed
        if self.context.next == NextContext.STOP_TRACK:
            stop = True

        # Stop if album changed
        new_album_id = Objects.tracks.get_album_id(
                                                track_id,
                                                sql)
        if self.context.next == NextContext.STOP_ALBUM and\
           self.current.album_id != new_album_id:
            stop = True

        # Stop if aartist changed
        new_aartist_id = Objects.tracks.get_aartist_id(
                                                track_id,
                                                sql)
        if self.context.next == NextContext.STOP_ARTIST and\
           self.current.aartist_id != new_aartist_id:
            stop = True

        if stop:
            return False

        self.current.id = track_id
        self.current.title = Objects.tracks.get_name(
                                                self.current.id,
                                                sql)
        self.current.album_id = new_album_id
        self.current.album = Objects.albums.get_name(
                                                self.current.album_id,
                                                sql)
        self.current.aartist_id = new_aartist_id
        self.current.aartist = translate_artist_name(
                                        Objects.artists.get_name(
                                                self.current.aartist_id,
                                                sql))
        artist_name = ""
        for artist_id in Objects.tracks.get_artist_ids(self.current.id,
                                                       sql):
            artist_name += translate_artist_name(
                            Objects.artists.get_name(artist_id, sql)) + ", "
        self.current.artist = artist_name[:-2]

        self.current.genre = Objects.albums.get_genre_name(
                                                self.current.album_id,
                                                sql)
        self.current.duration = Objects.tracks.get_length(self.current.id, sql)
        self.current.number = Objects.tracks.get_number(self.current.id, sql)
        self.current.path = Objects.tracks.get_path(self.current.id, sql)
        if path.exists(self.current.path):
            try:
                self._playbin.set_property('uri',
                                           GLib.filename_to_uri(
                                                        self.current.path))
            except Exception as e:  # Gstreamer error, stop
                print("BasePlayer::_load_track(): ", e)
                self._on_errors()
                return False
        else:
            print("File doesn't exist: ", self.current.path)
            self._on_errors()
            return False
        return True
Example #43
0
	def set_file_to_print (self, file_to_print):
		file_uri = GLib.filename_to_uri(file_to_print)
		try:
			self.doc = Poppler.Document.new_from_file(file_uri)
		except Exception as e:
			self.show_error_message ('no file found at %s'% file_uri)
Example #44
0
 def base_uri(self):
     """
         Get cache base uri
         @return str
     """
     return GLib.filename_to_uri(CACHE_PATH)
Example #45
0
 def generate_uri(self):
     file_uri = GLib.filename_to_uri(self.get_path(), None)
     return self.get_schema() + file_uri[8:]
Example #46
0
def path_to_uri(path):
    #Python's pathname2url doesn't work in quite the same way that Banshee works (the latter
    #doesn't encode & or ' for example), so we're using glib to do it since that's what Banshee
    #ultimately uses
    return GLib.filename_to_uri(path)
Example #47
0
 def __on_command_line(self, app, app_cmd_line):
     """
         Handle command line
         @param app as Gio.Application
         @param options as Gio.ApplicationCommandLine
     """
     self.__externals_count = 0
     options = app_cmd_line.get_options_dict()
     if options.contains('debug'):
         self.debug = True
     if options.contains('set-rating'):
         value = options.lookup_value('set-rating').get_int32()
         if value > 0 and value < 6 and\
                 self.player.current_track.id is not None:
             self.player.current_track.set_popularity(value)
     if options.contains('play-pause'):
         self.player.play_pause()
     elif options.contains('album'):
         try:
             value = options.lookup_value('album').get_string()
             album_ids = value.split(';')
             album = Album(int(album_ids.pop(0)))
             self.player.play_album(album)
             for album_id in album_ids:
                 self.player.add_album(Album(int(album_id)))
         except:
             pass
     elif options.contains('next'):
         self.player.next()
     elif options.contains('prev'):
         self.player.prev()
     elif options.contains('emulate-phone'):
         self.window.add_fake_phone()
     args = app_cmd_line.get_arguments()
     if len(args) > 1:
         self.player.clear_externals()
         for uri in args[1:]:
             try:
                 uri = GLib.filename_to_uri(uri)
             except:
                 pass
             parser = TotemPlParser.Parser.new()
             parser.connect('entry-parsed', self.__on_entry_parsed)
             parser.parse_async(uri, True, None, None)
     if self.window is not None and not self.window.is_visible():
         # self.window.setup_window()
         # self.window.present()
         # Horrible HACK: https://bugzilla.gnome.org/show_bug.cgi?id=774130
         self.window.save_view_state()
         self.window.destroy()
         self.window = Window()
         # If not GNOME/Unity add menu to toolbar
         if not is_gnome() and not is_unity():
             menu = self.__setup_app_menu()
             self.window.setup_menu(menu)
         self.window.connect('delete-event', self.__hide_on_delete)
         self.window.init_list_one()
         self.window.show()
         self.player.emit('status-changed')
         self.player.emit('current-changed')
     return 0
Example #48
0
    def __init__(self, window):
        """
            Init dialog
            @param window as Window
        """
        self.__helper = PasswordsHelper()
        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Eolie/SettingsDialog.ui")

        self.__settings_dialog = builder.get_object("settings_dialog")
        self.__settings_dialog.set_transient_for(window)
        # self.__settings_dialog.connect("destroy", self.__on_destroy)

        if False:
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object("header_bar")
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        download_chooser = builder.get_object("download_chooser")
        dir_uri = El().settings.get_value("download-uri").get_string()
        if not dir_uri:
            directory = GLib.get_user_special_dir(
                                         GLib.UserDirectory.DIRECTORY_DOWNLOAD)
            if directory is not None:
                dir_uri = GLib.filename_to_uri(directory, None)
        if dir_uri:
            download_chooser.set_uri(dir_uri)
        else:
            download_chooser.set_uri("file://" + GLib.getenv("HOME"))

        open_downloads = builder.get_object("open_downloads_check")
        open_downloads.set_active(
                                El().settings.get_value("open-downloads"))

        self.__start_page_uri = builder.get_object("start_page_uri")
        combo_start = builder.get_object("combo_start")
        start_page = El().settings.get_value("start-page").get_string()
        if start_page.startswith("http"):
            combo_start.set_active_id("address")
            self.__start_page_uri.set_text(start_page)
            self.__start_page_uri.show()
        else:
            combo_start.set_active_id(start_page)

        remember_session = builder.get_object("remember_sessions_check")
        remember_session.set_active(
                                El().settings.get_value("remember-session"))

        enable_plugins = builder.get_object("plugins_check")
        enable_plugins.set_active(
                                El().settings.get_value("enable-plugins"))

        self.__fonts_grid = builder.get_object("fonts_grid")
        use_system_fonts = builder.get_object("system_fonts_check")
        use_system_fonts.set_active(
                                El().settings.get_value("use-system-fonts"))
        self.__fonts_grid.set_sensitive(
                            not El().settings.get_value("use-system-fonts"))

        sans_serif_button = builder.get_object("sans_serif_button")
        sans_serif_button.set_font_name(
                       El().settings.get_value("font-sans-serif").get_string())
        serif_button = builder.get_object("serif_button")
        serif_button.set_font_name(
                       El().settings.get_value("font-serif").get_string())
        monospace_button = builder.get_object("monospace_button")
        monospace_button.set_font_name(
                       El().settings.get_value("font-monospace").get_string())

        min_font_size_spin = builder.get_object("min_font_size_spin")
        min_font_size_spin.set_value(
                       El().settings.get_value("min-font-size").get_int32())

        monitor_model = get_current_monitor_model(window)
        zoom_levels = El().settings.get_value("default-zoom-level")
        wanted_zoom_level = 1.0
        try:
            for zoom_level in zoom_levels:
                zoom_splited = zoom_level.split('@')
                if zoom_splited[0] == monitor_model:
                    wanted_zoom_level = float(zoom_splited[1])
        except:
            pass
        default_zoom_level = builder.get_object("default_zoom_level")
        default_zoom_level.set_value(float(wanted_zoom_level))

        cookies_combo = builder.get_object("cookies_combo")
        storage = El().settings.get_enum("cookie-storage")
        cookies_combo.set_active_id(str(storage))

        history_combo = builder.get_object("history_combo")
        storage = El().settings.get_enum("history-storage")
        history_combo.set_active_id(str(storage))

        self.__populars_count = builder.get_object("populars_count")
        if start_page == "popular":
            self.__populars_count.show()
        max_popular_items = El().settings.get_value(
                                              "max-popular-items").get_int32()
        builder.get_object("popular_spin_button").set_value(max_popular_items)
        remember_passwords = builder.get_object("remember_passwords_check")
        remember_passwords.set_active(
                                El().settings.get_value("remember-passwords"))

        tracking_check = builder.get_object("tracking_check")
        tracking_check.set_active(
                                El().settings.get_value("do-not-track"))
        self.__result_label = builder.get_object("result_label")
        self.__sync_button = builder.get_object("sync_button")
        self.__login_entry = builder.get_object("login_entry")
        self.__password_entry = builder.get_object("password_entry")
        self.__result_image = builder.get_object("result_image")
        builder.connect_signals(self)
        self.__helper.get_sync(self.__on_get_sync)

        thread = Thread(target=self.__get_sync_status)
        thread.daemon = True
        thread.start()
Example #49
0
 def __on_command_line(self, app, app_cmd_line):
     """
         Handle command line
         @param app as Gio.Application
         @param options as Gio.ApplicationCommandLine
     """
     self.__externals_count = 0
     args = app_cmd_line.get_arguments()
     options = app_cmd_line.get_options_dict()
     if options.contains("debug"):
         self.debug = True
     if options.contains("set-rating"):
         value = options.lookup_value("set-rating").get_string()
         try:
             value = min(max(0, int(value)), 5)
             if self.player.current_track.id is not None:
                 self.player.current_track.set_rate(value)
         except Exception as e:
             print(e)
             pass
     elif options.contains("play-pause"):
         self.player.play_pause()
     elif options.contains("play-ids"):
         try:
             value = options.lookup_value("play-ids").get_string()
             ids = value.split(";")
             track_ids = []
             for id in ids:
                 if id[0:2] == "a:":
                     album = Album(int(id[2:]))
                     track_ids += album.track_ids
                 else:
                     track_ids.append(int(id[2:]))
             track = Track(track_ids[0])
             self.player.load(track)
             self.player.populate_user_playlist_by_tracks(
                 track_ids, [Type.SEARCH])
         except Exception as e:
             print(e)
             pass
     elif options.contains("next"):
         self.player.next()
     elif options.contains("prev"):
         self.player.prev()
     elif options.contains("emulate-phone"):
         self.window.add_fake_phone()
     elif len(args) > 1:
         self.player.clear_externals()
         for uri in args[1:]:
             try:
                 uri = GLib.filename_to_uri(uri)
             except:
                 pass
             parser = TotemPlParser.Parser.new()
             parser.connect("entry-parsed", self.__on_entry_parsed)
             parser.parse_async(uri, True, None, None)
     elif self.window is not None and self.window.is_visible():
         self.window.present_with_time(Gtk.get_current_event_time())
     elif self.window is not None:
         # self.window.setup_window()
         # self.window.present()
         # Horrible HACK: https://bugzilla.gnome.org/show_bug.cgi?id=774130
         self.window.save_view_state()
         self.window.destroy()
         self.window = Window()
         # If not GNOME/Unity add menu to toolbar
         if not is_gnome() and not is_unity():
             menu = self.__setup_app_menu()
             self.window.setup_menu(menu)
         self.window.connect("delete-event", self.__hide_on_delete)
         self.window.init_list_one()
         self.window.show()
         self.player.emit("status-changed")
         self.player.emit("current-changed")
     return 0
Example #50
0
    def __init__(self):
        """
            Init dialog
        """
        builder = Gtk.Builder()
        builder.add_from_resource('/org/gnome/Eolie/SettingsDialog.ui')
        builder.connect_signals(self)

        self.__settings_dialog = builder.get_object('settings_dialog')
        self.__settings_dialog.set_transient_for(El().active_window)
        # self.__settings_dialog.connect('destroy', self.__on_destroy)

        if False:
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object('header_bar')
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        download_chooser = builder.get_object('download_chooser')
        dir_uri = El().settings.get_value('download-uri').get_string()
        if not dir_uri:
            directory = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_DOWNLOAD)
            dir_uri = GLib.filename_to_uri(directory, None)
        download_chooser.set_uri(dir_uri)

        autostart_downloads = builder.get_object('auto_download_check')
        autostart_downloads.set_active(
            El().settings.get_value('autostart-downloads'))

        combo_engine = builder.get_object('combo_engine')
        combo_engine.set_active_id(
            El().settings.get_value('search-engine').get_string())

        remember_session = builder.get_object('remember_session_check')
        remember_session.set_active(
            El().settings.get_value('remember-session'))

        enable_plugins = builder.get_object('plugins_check')
        enable_plugins.set_active(El().settings.get_value('enable-plugins'))

        self.__fonts_grid = builder.get_object('fonts_grid')
        use_system_fonts = builder.get_object('system_fonts_check')
        use_system_fonts.set_active(
            El().settings.get_value('use-system-fonts'))

        sans_serif_button = builder.get_object('sans_serif_button')
        sans_serif_button.set_font_name(
            El().settings.get_value('font-sans-serif').get_string())
        serif_button = builder.get_object('serif_button')
        serif_button.set_font_name(
            El().settings.get_value('font-serif').get_string())
        monospace_button = builder.get_object('monospace_button')
        monospace_button.set_font_name(
            El().settings.get_value('font-monospace').get_string())

        min_font_size_spin = builder.get_object('min_font_size_spin')
        min_font_size_spin.set_value(
            El().settings.get_value('min-font-size').get_int32())

        cookies_combo = builder.get_object('cookies_combo')
        storage = El().settings.get_enum('cookie-storage')
        cookies_combo.set_active_id(str(storage))

        tracking_check = builder.get_object('tracking_check')
        tracking_check.set_active(El().settings.get_value('do-not-track'))
#!/usr/bin/env python3

import os
import sys
os.environ["GDK_CORE_DEVICE_EVENTS"] = "1"

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('EvinceDocument', '3.0')
gi.require_version('EvinceView', '3.0')
from gi.repository import Gtk, GLib
from gi.repository import EvinceDocument
from gi.repository import EvinceView

wid = int(sys.argv[1])
uri = GLib.filename_to_uri(sys.argv[2])
plug = Gtk.Plug()
plug.construct(wid)
scroll = Gtk.ScrolledWindow()
EvinceDocument.init()
doc = EvinceDocument.Document.factory_get_document(uri)
view = EvinceView.View()
model = EvinceView.DocumentModel()
model.set_document(doc)
view.set_model(model)
scroll.add(view)
plug.add(scroll)

plug.connect("delete-event", Gtk.main_quit)
plug.show_all()
Gtk.main()
Example #52
0
Gst.init(None)
GES.init()

from gi.repository import GstPbutils

# The joys of globals, this needs to be done before
# importing Pipeline
if __name__ == '__main__':
    from pitivi.check import check_requirements
    check_requirements()

from pitivi.utils.pipeline import Pipeline

here = os.path.abspath(os.path.dirname(__file__))

CLAP_ASSET = GLib.filename_to_uri(
    os.path.join(here, '15388__pitx__palma-08.wav'))


class ClapMixer(object):
    def __init__(self):
        self.__timeline = GES.Timeline.new()
        self.__timeline.add_track(GES.AudioTrack.new())
        self.pipeline = Pipeline()
        self.pipeline.set_timeline(self.__timeline)

        self.__clap_asset = None
        self.__clap_layer = None
        self.__asset_layer = None

        self.reset()
Example #53
0
    def __init__(self):
        """
            Init dialog
        """
        self.__choosers = []
        self.__cover_tid = None
        self.__mix_tid = None
        self.__popover = None

        builder = Gtk.Builder()
        builder.add_from_resource('/org/gnome/Lollypop/SettingsDialog.ui')
        if Lp().lastfm is None or Lp().lastfm.is_goa:
            builder.get_object('lastfm_grid').hide()
        if Lp().scanner.is_locked():
            builder.get_object('button').set_sensitive(False)
        builder.get_object('button').connect('clicked',
                                             self.__on_reset_clicked,
                                             builder.get_object('progress'))
        artists = Lp().artists.count()
        albums = Lp().albums.count()
        tracks = Lp().tracks.count()
        builder.get_object('artists').set_text(
            ngettext("%d artist", "%d artists", artists) % artists)
        builder.get_object('albums').set_text(
            ngettext("%d album", "%d albums", albums) % albums)
        builder.get_object('tracks').set_text(
            ngettext("%d track", "%d tracks", tracks) % tracks)

        self.__popover_content = builder.get_object('popover')
        duration = builder.get_object('duration')
        duration.set_range(1, 20)
        duration.set_value(Lp().settings.get_value('mix-duration').get_int32())

        self.__settings_dialog = builder.get_object('settings_dialog')
        self.__settings_dialog.set_transient_for(Lp().window)

        if Lp().settings.get_value('disable-csd'):
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object('header_bar')
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        switch_scan = builder.get_object('switch_scan')
        switch_scan.set_state(Lp().settings.get_value('auto-update'))

        switch_view = builder.get_object('switch_dark')
        switch_view.set_state(Lp().settings.get_value('dark-ui'))

        switch_background = builder.get_object('switch_background')
        switch_background.set_state(Lp().settings.get_value('background-mode'))

        switch_state = builder.get_object('switch_state')
        switch_state.set_state(Lp().settings.get_value('save-state'))

        switch_mix = builder.get_object('switch_mix')
        switch_mix.set_state(Lp().settings.get_value('mix'))

        switch_mix_party = builder.get_object('switch_mix_party')
        switch_mix_party.set_state(Lp().settings.get_value('party-mix'))

        switch_librefm = builder.get_object('switch_librefm')
        switch_librefm.set_state(Lp().settings.get_value('use-librefm'))

        switch_artwork_tags = builder.get_object('switch_artwork_tags')
        if GLib.find_program_in_path("kid3-cli") is None:
            grid = builder.get_object('grid_behaviour')
            h = grid.child_get_property(switch_artwork_tags, 'height')
            w = grid.child_get_property(switch_artwork_tags, 'width')
            l = grid.child_get_property(switch_artwork_tags, 'left-attach')
            t = grid.child_get_property(switch_artwork_tags, 'top-attach')
            switch_artwork_tags.destroy()
            label = Gtk.Label.new(_("You need to install kid3-cli"))
            label.get_style_context().add_class('dim-label')
            label.set_property('halign', Gtk.Align.END)
            label.show()
            grid.attach(label, l, t, w, h)
        else:
            switch_artwork_tags.set_state(
                Lp().settings.get_value('save-to-tags'))

        switch_genres = builder.get_object('switch_genres')
        switch_genres.set_state(Lp().settings.get_value('show-genres'))

        switch_compilations = builder.get_object('switch_compilations')
        switch_compilations.set_state(
            Lp().settings.get_value('show-compilations'))

        switch_artwork = builder.get_object('switch_artwork')
        switch_artwork.set_state(Lp().settings.get_value('artist-artwork'))

        switch_repeat = builder.get_object('switch_repeat')
        switch_repeat.set_state(not Lp().settings.get_value('repeat'))

        combo_orderby = builder.get_object('combo_orderby')
        combo_orderby.set_active(Lp().settings.get_enum(('orderby')))

        combo_preview = builder.get_object('combo_preview')

        scale_coversize = builder.get_object('scale_coversize')
        scale_coversize.set_range(150, 300)
        scale_coversize.set_value(
            Lp().settings.get_value('cover-size').get_int32())
        self.__settings_dialog.connect('destroy', self.__edit_settings_close)

        builder.connect_signals(self)

        main_chooser_box = builder.get_object('main_chooser_box')
        self.__chooser_box = builder.get_object('chooser_box')

        self.__set_outputs(combo_preview)

        #
        # Music tab
        #
        dirs = []
        for directory in Lp().settings.get_value('music-uris'):
            dirs.append(directory)

        # Main chooser
        self.__main_chooser = ChooserWidget()
        image = Gtk.Image.new_from_icon_name("list-add-symbolic",
                                             Gtk.IconSize.MENU)
        self.__main_chooser.set_icon(image)
        self.__main_chooser.set_action(self.__add_chooser)
        main_chooser_box.pack_start(self.__main_chooser, False, True, 0)
        if len(dirs) > 0:
            uri = dirs.pop(0)
        else:
            filename = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_MUSIC)
            if filename:
                uri = GLib.filename_to_uri(filename)
            else:
                uri = ""

        self.__main_chooser.set_dir(uri)

        # Others choosers
        for directory in dirs:
            self.__add_chooser(directory)

        #
        # Google tab
        #
        builder.get_object('cs-entry').set_text(
            Lp().settings.get_value('cs-api-key').get_string())
        #
        # Last.fm tab
        #
        if Lp().lastfm is not None and Secret is not None:
            self.__test_img = builder.get_object('test_img')
            self.__login = builder.get_object('login')
            self.__password = builder.get_object('password')
            schema = Secret.Schema.new("org.gnome.Lollypop",
                                       Secret.SchemaFlags.NONE, SecretSchema)
            Secret.password_lookup(schema, SecretAttributes, None,
                                   self.__on_password_lookup)
            builder.get_object('lastfm_grid').set_sensitive(True)
            builder.get_object('lastfm_error').hide()
            self.__login.set_text(
                Lp().settings.get_value('lastfm-login').get_string())
Example #54
0
    def on_playitem_activated(self, widget):
        rom_uri = GLib.filename_to_uri(self.parent.rom, None)
        if self.recent_manager.has_item(rom_uri) == False:
            self.recent_manager.add_item(rom_uri)

        self.parent.action.thread_rom()
Example #55
0
    def __init__(self):
        """
            Init dialog
        """
        self.__choosers = []
        self.__cover_tid = None
        self.__mix_tid = None
        self.__popover = None

        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Lollypop/SettingsDialog.ui")
        self.__progress = builder.get_object("progress")
        self.__infobar = builder.get_object("infobar")
        self.__reset_button = builder.get_object("reset_button")
        if Lp().lastfm is None or Lp().lastfm.is_goa:
            builder.get_object("lastfm_grid").hide()
        if Lp().scanner.is_locked():
            builder.get_object("reset_button").set_sensitive(False)
        artists = Lp().artists.count()
        albums = Lp().albums.count()
        tracks = Lp().tracks.count()
        builder.get_object("artists").set_text(
            ngettext("%d artist", "%d artists", artists) % artists)
        builder.get_object("albums").set_text(
            ngettext("%d album", "%d albums", albums) % albums)
        builder.get_object("tracks").set_text(
            ngettext("%d track", "%d tracks", tracks) % tracks)

        self.__popover_content = builder.get_object("popover")
        duration = builder.get_object("duration")
        duration.set_range(1, 20)
        duration.set_value(Lp().settings.get_value("mix-duration").get_int32())

        self.__settings_dialog = builder.get_object("settings_dialog")
        self.__settings_dialog.set_transient_for(Lp().window)

        if Lp().settings.get_value("disable-csd"):
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object("header_bar")
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        switch_scan = builder.get_object("switch_scan")
        switch_scan.set_state(Lp().settings.get_value("auto-update"))

        switch_view = builder.get_object("switch_dark")
        if Lp().gtk_application_prefer_dark_theme:
            switch_view.set_sensitive(False)
        else:
            switch_view.set_state(Lp().settings.get_value("dark-ui"))

        switch_background = builder.get_object("switch_background")
        switch_background.set_state(Lp().settings.get_value("background-mode"))

        switch_state = builder.get_object("switch_state")
        switch_state.set_state(Lp().settings.get_value("save-state"))

        switch_mix = builder.get_object("switch_mix")
        switch_mix.set_state(Lp().settings.get_value("mix"))

        self._switch_song_notifications = builder.get_object(
            "switch_song_notifications", )

        self._switch_song_notifications.set_state(
            not Lp().settings.get_value("disable-song-notifications"), )

        self._switch_song_notifications.set_sensitive(
            not Lp().settings.get_value("disable-notifications"), )

        Lp().settings.connect(
            "changed::disable-notifications",
            self._on_notifications_setting_changed,
        )

        self.__helper = TouchHelper(switch_mix, None, None)
        self.__helper.set_long_func(self.__mix_long_func, switch_mix)
        self.__helper.set_short_func(self.__mix_short_func, switch_mix)

        switch_mix_party = builder.get_object("switch_mix_party")
        switch_mix_party.set_state(Lp().settings.get_value("party-mix"))

        switch_artwork_tags = builder.get_object("switch_artwork_tags")
        grid_behaviour = builder.get_object("grid_behaviour")
        # Check portal for kid3-cli
        dbus_helper = DBusHelper()
        dbus_helper.call("CanSetCover", None, self.__on_can_set_cover,
                         (switch_artwork_tags, grid_behaviour))

        if GLib.find_program_in_path("youtube-dl") is None or\
                not Lp().settings.get_value("network-access"):
            builder.get_object("charts_grid").hide()
        else:
            switch_charts = builder.get_object("switch_charts")
            switch_charts.set_state(Lp().settings.get_value("show-charts"))

        switch_genres = builder.get_object("switch_genres")
        switch_genres.set_state(Lp().settings.get_value("show-genres"))

        switch_compilations = builder.get_object("switch_compilations")
        switch_compilations.set_state(
            Lp().settings.get_value("show-compilations"))

        switch_artwork = builder.get_object("switch_artwork")
        switch_artwork.set_state(Lp().settings.get_value("artist-artwork"))

        switch_spotify = builder.get_object("switch_spotify")
        switch_spotify.set_state(Lp().settings.get_value("search-spotify"))

        switch_itunes = builder.get_object("switch_itunes")
        switch_itunes.set_state(Lp().settings.get_value("search-itunes"))

        if GLib.find_program_in_path("youtube-dl") is None:
            builder.get_object("yt-dl").show()

        combo_orderby = builder.get_object("combo_orderby")
        combo_orderby.set_active(Lp().settings.get_enum(("orderby")))

        combo_preview = builder.get_object("combo_preview")

        scale_coversize = builder.get_object("scale_coversize")
        scale_coversize.set_range(150, 300)
        scale_coversize.set_value(
            Lp().settings.get_value("cover-size").get_int32())
        self.__settings_dialog.connect("destroy", self.__edit_settings_close)

        builder.connect_signals(self)

        main_chooser_box = builder.get_object("main_chooser_box")
        self.__chooser_box = builder.get_object("chooser_box")

        self.__set_outputs(combo_preview)

        #
        # Music tab
        #
        dirs = []
        for directory in Lp().settings.get_value("music-uris"):
            dirs.append(directory)

        # Main chooser
        self.__main_chooser = ChooserWidget()
        image = Gtk.Image.new_from_icon_name("list-add-symbolic",
                                             Gtk.IconSize.MENU)
        self.__main_chooser.set_icon(image)
        self.__main_chooser.set_action(self.__add_chooser)
        main_chooser_box.pack_start(self.__main_chooser, False, True, 0)
        if len(dirs) > 0:
            uri = dirs.pop(0)
        else:
            filename = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_MUSIC)
            if filename:
                uri = GLib.filename_to_uri(filename)
            else:
                uri = ""

        self.__main_chooser.set_dir(uri)

        # Others choosers
        for directory in dirs:
            self.__add_chooser(directory)

        #
        # Google tab
        #
        key = Lp().settings.get_value("cs-api-key").get_string() or\
            Lp().settings.get_default_value("cs-api-key").get_string()
        builder.get_object("cs-entry").set_text(key)

        from lollypop.helper_passwords import PasswordsHelper
        helper = PasswordsHelper()
        #
        # Last.fm tab
        #
        if Lp().lastfm is not None:
            self.__lastfm_test_image = builder.get_object("lastfm_test_image")
            self.__lastfm_login = builder.get_object("lastfm_login")
            self.__lastfm_password = builder.get_object("lastfm_password")
            helper.get("lastfm", self.__on_get_password)
            builder.get_object("lastfm_grid").set_sensitive(True)
            builder.get_object("lastfm_error_label").hide()
        #
        # Libre.fm tab
        #
        if Lp().librefm is not None:
            self.__librefm_test_image = builder.get_object(
                "librefm_test_image")
            self.__librefm_login = builder.get_object("librefm_login")
            self.__librefm_password = builder.get_object("librefm_password")
            helper.get("librefm", self.__on_get_password)
            builder.get_object("librefm_grid").set_sensitive(True)
            builder.get_object("librefm_error_label").hide()
Example #56
0
class Query():
    music_folder = None
    MUSIC_URI = None
    download_folder = None
    DOWNLOAD_URI = None
    try:
        music_folder = GLib.get_user_special_dir(
            GLib.UserDirectory.DIRECTORY_MUSIC)
        MUSIC_URI = Tracker.sparql_escape_string(
            GLib.filename_to_uri(music_folder))
        download_folder = GLib.get_user_special_dir(
            GLib.UserDirectory.DIRECTORY_DOWNLOAD)
        DOWNLOAD_URI = Tracker.sparql_escape_string(
            GLib.filename_to_uri(download_folder))

        for folder in [music_folder, download_folder]:
            if os.path.islink(folder):
                logger.warn("%s is a symlink, this folder will be omitted" %
                            folder)
            else:
                i = len(next(os.walk(folder))[2])
                logger.debug("Found %d files in %s" % (i, folder))
    except TypeError:
        logger.warn("XDG user dirs are not set")

    @staticmethod
    def order_by_statement(attr):
        """Returns a SPARQL ORDER BY statement sorting by the given attribute, ignoring
            articles as defined in _("the"). 'Attr' should be given without parentheses,
            e.g., "attr='?author'"."""
        return_statement = "fn:lower-case(%(attribute)s)" % {'attribute': attr}
        # TRANSLATORS: _("the") should be a space-separated list of all-lowercase articles
        # (such as 'the') that should be ignored when alphabetizing artists/albums. This
        # list should include 'the' regardless of language. If some articles occur more
        # frequently than others, most common should appear first, least common last.
        for article in reversed(_("the a an").split(" ")):
            return_statement = '''IF(fn:starts-with(fn:lower-case(%(attribute)s), "%(article)s"),
            fn:substring(fn:lower-case(%(attribute)s), %(substr_start)s),
            %(nested_if)s)''' % {
                'attribute': attr,
                'article': article + " ",
                'substr_start': str(len(article) + 2),
                'nested_if': return_statement
            }
        return return_statement

    @staticmethod
    def all_albums():
        return Query.albums('?album a nmm:MusicAlbum .')

    @staticmethod
    def all_artists():
        return Query.artists('?album a nmm:MusicAlbum .')

    @staticmethod
    def all_songs():
        return Query.songs('?song a nmm:MusicPiece ; a nfo:FileDataObject .')

    @staticmethod
    def all_playlists():
        return Query.playlists('?playlist a nmm:Playlist .')

    @staticmethod
    def all_songs_count():
        query = '''
    SELECT
        COUNT(?song) AS childcount
    WHERE {
        ?song a nmm:MusicPiece ;
              a nfo:FileDataObject
        FILTER (
            tracker:uri-is-descendant(
                '%(music_dir)s', nie:url(?song)
            ) ||
            tracker:uri-is-descendant(
                '%(download_dir)s', nie:url(?song)
            )
        )
        FILTER (
            NOT EXISTS {
                ?song a nmm:Video
            } &&
            NOT EXISTS {
                ?song a nmm:Playlist
            }
        )
    }
    '''.replace('\n', ' ').strip() % {
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }

        return query

    @staticmethod
    def albums(where_clause):
        query = '''
    SELECT DISTINCT
        rdf:type(?album)
        tracker:id(?album) AS id
        (
            SELECT
                nmm:artistName(?artist)
            WHERE {
                ?album nmm:albumArtist ?artist
            }
            LIMIT 1
        ) AS artist
        nie:title(?album) AS title
        nie:title(?album) AS album
        tracker:coalesce(
            (
                SELECT
                    GROUP_CONCAT(
                        nmm:artistName(?artist),
                        ','
                    )
                WHERE {
                    ?album nmm:albumArtist ?artist
                }
            ),
            (
                SELECT
                    GROUP_CONCAT(
                        (
                            SELECT
                                nmm:artistName(nmm:performer(?_12)) AS perf
                            WHERE {
                                ?_12 nmm:musicAlbum ?album
                            }
                            GROUP BY ?perf
                        ),
                        ','
                    ) AS album_performer
                WHERE {
                }
            )
        ) AS author
        xsd:integer(
            tracker:coalesce(
                nmm:albumTrackCount(?album),
                (
                    SELECT
                        COUNT(?_1)
                    WHERE {
                        ?_1 nmm:musicAlbum ?album ;
                            tracker:available 'true'
                        FILTER (
                            tracker:uri-is-descendant(
                                '%(music_dir)s', nie:url(?_1)
                            ) ||
                            tracker:uri-is-descendant(
                                '%(download_dir)s', nie:url(?_1)
                            )
                        )
                        FILTER (
                            NOT EXISTS {
                                ?_1 a nmm:Video
                            } &&
                            NOT EXISTS {
                                ?_1 a nmm:Playlist
                            }
                        )
                    }
                )
            )
        ) AS childcount
        (
            SELECT
                fn:year-from-dateTime(?c)
            WHERE {
                ?_2 nmm:musicAlbum ?album ;
                    nie:contentCreated ?c ;
                    tracker:available 'true'
                FILTER (
                    tracker:uri-is-descendant(
                        '%(music_dir)s', nie:url(?_2)
                    ) ||
                    tracker:uri-is-descendant(
                        '%(download_dir)s', nie:url(?_2)
                    )
                )
                FILTER (
                    NOT EXISTS {
                        ?_2 a nmm:Video
                    } &&
                    NOT EXISTS {
                        ?_2 a nmm:Playlist
                    }
                )
            }
            LIMIT 1
        ) AS creation-date
        {
            %(where_clause)s
            FILTER (
                EXISTS {
                    ?_3 nmm:musicAlbum ?album ;
                        tracker:available 'true'
                    FILTER (
                        tracker:uri-is-descendant(
                            '%(music_dir)s', nie:url(?_3)
                        ) ||
                        tracker:uri-is-descendant(
                            '%(download_dir)s', nie:url(?_3)
                        )
                    )
                    FILTER (
                        NOT EXISTS {
                            ?_3 a nmm:Video
                        } &&
                        NOT EXISTS {
                            ?_3 a nmm:Playlist
                        }
                    )
                }
            )
        }
    ORDER BY %(album_order)s
        %(artist_order)s
        ?albumyear
    '''.replace('\n', ' ').strip() % {
            'where_clause': where_clause.replace('\n', ' ').strip(),
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI,
            'album_order': Query.order_by_statement("?title"),
            'artist_order': Query.order_by_statement("?author")
        }

        return query

    @staticmethod
    def artists(where_clause):
        query = '''
    SELECT DISTINCT
        rdf:type(?album)
        tracker:id(?album) AS id
        (
            SELECT
                nmm:artistName(?artist)
            WHERE {
                ?album nmm:albumArtist ?artist
            }
            LIMIT 1
        ) AS artist
        nie:title(?album) AS title
        nie:title(?album) AS album
        tracker:coalesce(
            (
                SELECT
                    GROUP_CONCAT(
                        nmm:artistName(?artist),
                        ','
                    )
                WHERE {
                    ?album nmm:albumArtist ?artist
                }
            ),
            (
                SELECT
                    GROUP_CONCAT(
                        (
                            SELECT
                                nmm:artistName(nmm:performer(?_12)) AS perf
                            WHERE {
                                ?_12 nmm:musicAlbum ?album
                                FILTER (
                                    tracker:uri-is-descendant(
                                        '%(music_dir)s', nie:url(?_12)
                                    ) ||
                                    tracker:uri-is-descendant(
                                        '%(download_dir)s', nie:url(?_12)
                                    )
                                )
                                FILTER (
                                    NOT EXISTS {
                                        ?_12 a nmm:Video
                                    } &&
                                    NOT EXISTS {
                                        ?_12 a nmm:Playlist
                                    }
                                )
                            }
                            GROUP BY ?perf
                        ),
                        ','
                    ) AS album_performer
                WHERE {
                }
            )
        ) AS author
        xsd:integer(
            tracker:coalesce(
                nmm:albumTrackCount(?album),
                (
                    SELECT
                        COUNT(?_1)
                    WHERE {
                        ?_1 nmm:musicAlbum ?album ;
                        tracker:available 'true'
                        FILTER (
                            tracker:uri-is-descendant(
                                '%(music_dir)s', nie:url(?_1)
                            ) ||
                            tracker:uri-is-descendant(
                                '%(download_dir)s', nie:url(?_1)
                            )
                        )
                        FILTER (
                            NOT EXISTS {
                                ?_1 a nmm:Video
                            } &&
                            NOT EXISTS {
                                ?_1 a nmm:Playlist
                            }
                        )
                    }
                )
            )
        ) AS childcount
        (
            SELECT
                fn:year-from-dateTime(?c)
            WHERE {
                ?_2 nmm:musicAlbum ?album ;
                    nie:contentCreated ?c ;
                    tracker:available 'true'
                FILTER (
                    tracker:uri-is-descendant(
                        '%(music_dir)s', nie:url(?_2)
                    ) ||
                    tracker:uri-is-descendant(
                        '%(download_dir)s', nie:url(?_2)
                    )
                )
                FILTER (
                    NOT EXISTS {
                        ?_2 a nmm:Video
                    } &&
                    NOT EXISTS {
                        ?_2 a nmm:Playlist
                    }
                )
            }
            LIMIT 1
        ) AS creation-date
        {
            %(where_clause)s
            FILTER (
                EXISTS {
                    ?_3 nmm:musicAlbum ?album ;
                        tracker:available 'true'
                    FILTER (
                        tracker:uri-is-descendant(
                            '%(music_dir)s', nie:url(?_3)
                        ) ||
                        tracker:uri-is-descendant(
                            '%(download_dir)s', nie:url(?_3)
                        )
                    )
                    FILTER (
                        NOT EXISTS {
                            ?_3 a nmm:Video
                        } &&
                        NOT EXISTS {
                            ?_3 a nmm:Playlist
                        }
                    )
                }
            )
        }
    ORDER BY %(artist_order)s
        ?albumyear
        %(album_order)s
    '''.replace('\n', ' ').strip() % {
            'where_clause': where_clause.replace('\n', ' ').strip(),
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI,
            'artist_order': Query.order_by_statement("?author"),
            'album_order': Query.order_by_statement("nie:title(?album)")
        }

        return query

    @staticmethod
    def songs(where_clause):
        query = '''
    SELECT DISTINCT
        rdf:type(?song)
        tracker:id(?song) AS id
        nie:url(?song) AS url
        nie:title(?song) AS title
        nmm:artistName(nmm:performer(?song)) AS artist
        nie:title(nmm:musicAlbum(?song)) AS album
        nfo:duration(?song) AS duration
        IF(bound(?tag), 'truth!', '') AS lyrics
        {
            %(where_clause)s
            OPTIONAL {
                ?song nao:hasTag ?tag .
                FILTER( ?tag = nao:predefined-tag-favorite )
            }
            FILTER (
                tracker:uri-is-descendant(
                    '%(music_dir)s', nie:url(?song)
                ) ||
                tracker:uri-is-descendant(
                    '%(download_dir)s', nie:url(?song)
                )
            )
            FILTER (
                NOT EXISTS {
                    ?song a nmm:Video
                } &&
                NOT EXISTS {
                    ?song a nmm:Playlist
                }
            )
        }
    ORDER BY tracker:added(?song)
    '''.replace('\n', ' ').strip() % {
            'where_clause': where_clause.replace('\n', ' ').strip(),
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }

        return query

    @staticmethod
    def playlists(where_clause):
        query = '''
    SELECT DISTINCT
        rdf:type(?playlist)
        tracker:id(?playlist) AS id
        nie:title(?playlist) AS title
        nfo:entryCounter(?playlist) AS childcount
        {
            %(where_clause)s
            OPTIONAL {
                ?playlist a nfo:FileDataObject .
                FILTER (
                    EXISTS {
                        ?playlist tracker:available 'true'
                        FILTER (
                            tracker:uri-is-descendant(
                                '%(music_dir)s', nie:url(?playlist)
                            ) ||
                            tracker:uri-is-descendant(
                                '%(download_dir)s', nie:url(?playlist)
                            )
                        )
                    }
                )
            }
        }
    ORDER BY fn:lower-case(?title)
    '''.replace('\n', ' ').strip() % {
            'where_clause': where_clause.replace('\n', ' ').strip(),
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }

        return query

    @staticmethod
    def album_songs(album_id):
        query = '''
    SELECT DISTINCT
        rdf:type(?song)
        tracker:id(?song) AS id
        nie:url(?song) AS url
        nie:title(?song) AS title
        nmm:artistName(nmm:performer(?song)) AS artist
        nie:title(nmm:musicAlbum(?song)) AS album
        nfo:duration(?song) AS duration
        IF(bound(?tag), 'truth!', '') AS lyrics
    WHERE {
        ?song a nmm:MusicPiece ;
              a nfo:FileDataObject ;
              nmm:musicAlbum ?album .
        OPTIONAL {
            ?song nao:hasTag ?tag .
            FILTER( ?tag = nao:predefined-tag-favorite )
        }
        FILTER (
            tracker:id(?album) = %(album_id)s
        )
        FILTER (
            tracker:uri-is-descendant(
                '%(music_dir)s', nie:url(?song)
            ) ||
            tracker:uri-is-descendant(
                '%(download_dir)s', nie:url(?song)
            )
        )
        FILTER (
            NOT EXISTS {
                ?song a nmm:Video
            } &&
            NOT EXISTS {
                ?song a nmm:Playlist
            }
        )
    }
    ORDER BY
         nmm:setNumber(nmm:musicAlbumDisc(?song))
         nmm:trackNumber(?song)
         tracker:added(?song)
    '''.replace('\n', ' ').strip() % {
            'album_id': album_id,
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }

        return query

    @staticmethod
    def playlist_songs(playlist_id, filter_clause=None):
        query = '''
    SELECT
        rdf:type(?song)
        tracker:id(?entry) AS id
        nie:url(?song) AS url
        nie:title(?song) AS title
        nmm:artistName(nmm:performer(?song)) AS artist
        nie:title(nmm:musicAlbum(?song)) AS album
        nfo:duration(?song) AS duration
        IF(bound(?tag), 'truth!', '') AS lyrics
    WHERE {
        ?playlist a nmm:Playlist ;
            a nfo:MediaList ;
            nfo:hasMediaFileListEntry ?entry .
        ?entry a nfo:MediaFileListEntry ;
            nfo:entryUrl ?url .
        ?song a nmm:MusicPiece ;
             a nfo:FileDataObject ;
             nie:url ?url .
        OPTIONAL {
            ?song nao:hasTag ?tag .
            FILTER( ?tag = nao:predefined-tag-favorite )
        }
        FILTER (
            %(filter_clause)s
        )
        FILTER (
            NOT EXISTS {
                ?song a nmm:Video
            } &&
            NOT EXISTS {
                ?song a nmm:Playlist
            }
        )
    }
    ORDER BY
         nfo:listPosition(?entry)
    '''.replace('\n', ' ').strip() % {
            'playlist_id': playlist_id,
            'filter_clause': filter_clause
            or 'tracker:id(?playlist) = ' + playlist_id,
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }

        return query

    @staticmethod
    def get_album_for_album_id(album_id):
        query = """
    SELECT DISTINCT
        rdf:type(?album)
        tracker:id(?album) AS id
        (
            SELECT
                nmm:artistName(?artist)
            WHERE {
                ?album nmm:albumArtist ?artist
            }
            LIMIT 1
        ) AS artist
        nie:title(?album) AS title
        nie:title(?album) AS album
    WHERE {
        ?album a nmm:MusicAlbum  .
        FILTER (
            tracker:id(?album) = %(album_id)s
        )
    }
    """.replace("\n", " ").strip() % {
            'album_id': album_id,
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }
        return query

    @staticmethod
    def get_album_for_song_id(song_id):
        query = """
    SELECT DISTINCT
        rdf:type(?album)
        tracker:id(?album) AS id
        (
            SELECT
                nmm:artistName(?artist)
            WHERE {
                ?album nmm:albumArtist ?artist
            }
            LIMIT 1
        ) AS artist
        nie:title(?album) AS title
        nie:title(?album) AS album
    WHERE {
        ?song a nmm:MusicPiece ;
              nmm:musicAlbum ?album .
        FILTER (
            tracker:id(?song) = %(song_id)s
        )
        FILTER (
            tracker:uri-is-descendant(
                '%(music_dir)s', nie:url(?song)
            ) ||
            tracker:uri-is-descendant(
                '%(download_dir)s', nie:url(?song)
            )
        )
        FILTER (
            NOT EXISTS {
                ?song a nmm:Video
            } &&
            NOT EXISTS {
                ?song a nmm:Playlist
            }
        )
    }
    """.replace("\n", " ").strip() % {
            'song_id': song_id,
            'music_dir': Query.MUSIC_URI,
            'download_dir': Query.DOWNLOAD_URI
        }
        return query

    @staticmethod
    def update_playcount(song_url):
        query = """
    INSERT OR REPLACE { ?song nie:usageCounter ?playcount . }
    WHERE {
        SELECT
            IF(bound(?usage), (?usage + 1), 1) AS playcount
            ?song
            WHERE {
                ?song a nmm:MusicPiece .
                OPTIONAL { ?song nie:usageCounter ?usage . }
                FILTER ( nie:url(?song) = "%(song_url)s" )
            }
        }
    """.replace("\n", " ").strip() % {
            'song_url': song_url
        }

        return query

    @staticmethod
    def update_last_played(song_url, time):
        query = """
    INSERT OR REPLACE { ?song nfo:fileLastAccessed '%(time)s' . }
    WHERE {
        SELECT
            ?song
            WHERE {
                ?song a nmm:MusicPiece .
                FILTER ( nie:url(?song) = "%(song_url)s" )
            }
        }
    """.replace("\n", " ").strip() % {
            'song_url': song_url,
            'time': time
        }

        return query

    @staticmethod
    def create_playlist(title):
        query = """
    INSERT {
        _:playlist
            a nmm:Playlist ;
            a nfo:MediaList ;
            nie:title "%(title)s" ;
            nfo:entryCounter 0 .
    }
    """.replace("\n", " ").strip() % {
            'title': title
        }
        return query

    @staticmethod
    def create_tag(tag_text):
        query = """
    INSERT OR REPLACE {
        _:tag
            a nao:Tag ;
            rdfs:comment '%(tag_text)s'.
    }
    """.replace("\n", " ").strip() % {
            'tag_text': tag_text
        }
        return query

    @staticmethod
    def create_playlist_with_tag(title, tag_text):
        # TODO: make this an extension of 'create playlist' rather than its own func.?
        # TODO: CREATE TAG IF IT DOESN'T EXIST!
        query = """
    INSERT {
        _:playlist
            a nmm:Playlist ;
            a nfo:MediaList ;
            nie:title "%(title)s" ;
            nfo:entryCounter 0 ;
            nao:hasTag ?tag.
    }
    WHERE {
        SELECT ?tag
        WHERE {
            ?tag a nao:Tag ;
                rdfs:comment '%(tag_text)s'.
        }
    }
    """.replace("\n", " ").strip() % {
            'title': title,
            'tag_text': tag_text
        }
        return query

    @staticmethod
    def delete_playlist(playlist_id):
        query = """
    DELETE {
        ?playlist
            a rdfs:Resource .
        ?entry
            a rdfs:Resource .
    }
    WHERE {
        ?playlist
            a nmm:Playlist ;
            a nfo:MediaList .
        OPTIONAL {
            ?playlist
                nfo:hasMediaFileListEntry ?entry .
        }
        FILTER (
            tracker:id(?playlist) = %(playlist_id)s
        )
    }
    """.replace("\n", " ").strip() % {
            'playlist_id': playlist_id
        }
        return query

    @staticmethod
    def add_song_to_playlist(playlist_id, song_uri):
        query = """
    INSERT OR REPLACE {
        _:entry
            a nfo:MediaFileListEntry ;
            nfo:entryUrl "%(song_uri)s" ;
            nfo:listPosition ?position .
        ?playlist
            nfo:entryCounter ?position ;
            nfo:hasMediaFileListEntry _:entry .
    }
    WHERE {
        SELECT
            ?playlist
            (?counter + 1) AS position
        WHERE {
            ?playlist
                a nmm:Playlist ;
                a nfo:MediaList ;
                nfo:entryCounter ?counter .
            FILTER (
                tracker:id(?playlist) = %(playlist_id)s
            )
        }
    }
    """.replace("\n", " ").strip() % {
            'playlist_id': playlist_id,
            'song_uri': song_uri
        }
        return query

    @staticmethod
    def remove_song_from_playlist(playlist_id, song_id):
        query = """
    INSERT OR REPLACE {
        ?entry
            nfo:listPosition ?position .
    }
    WHERE {
        SELECT
            ?entry
            (?old_position - 1) AS position
        WHERE {
            ?entry
                a nfo:MediaFileListEntry ;
                nfo:listPosition ?old_position .
            ?playlist
                nfo:hasMediaFileListEntry ?entry .
            FILTER (?old_position > ?removed_position)
            {
                SELECT
                    ?playlist
                    ?removed_position
                WHERE {
                    ?playlist
                        a nmm:Playlist ;
                        a nfo:MediaList ;
                        nfo:hasMediaFileListEntry ?removed_entry .
                    ?removed_entry
                        nfo:listPosition ?removed_position .
                    FILTER (
                        tracker:id(?playlist) = %(playlist_id)s &&
                        tracker:id(?removed_entry) = %(song_id)s
                    )
                }
            }
        }
    }
    INSERT OR REPLACE {
        ?playlist
            nfo:entryCounter ?new_counter .
    }
    WHERE {
        SELECT
            ?playlist
            (?counter - 1) AS new_counter
        WHERE {
            ?playlist
                a nmm:Playlist ;
                a nfo:MediaList ;
                nfo:entryCounter ?counter .
            FILTER (
                tracker:id(?playlist) = %(playlist_id)s
            )
        }
    }
    DELETE {
        ?playlist
            nfo:hasMediaFileListEntry ?entry .
        ?entry
            a rdfs:Resource .
    }
    WHERE {
        ?playlist
            a nmm:Playlist ;
            a nfo:MediaList ;
            nfo:hasMediaFileListEntry ?entry .
        FILTER (
            tracker:id(?playlist) = %(playlist_id)s &&
            tracker:id(?entry) = %(song_id)s
        )
    }
    """.replace("\n", " ").strip() % {
            'playlist_id': playlist_id,
            'song_id': song_id
        }
        return query

    @staticmethod
    def get_playlist_with_id(playlist_id):
        query = """
    ?playlist a nmm:Playlist .
    FILTER (
        tracker:id(?playlist) = %(playlist_id)s
    )
    """.replace('\n', ' ').strip() % {
            'playlist_id': playlist_id
        }

        return Query.playlists(query)

    @staticmethod
    def get_playlist_with_tag(playlist_tag):
        query = """
    ?playlist
        a nmm:Playlist ;
        nao:hasTag ?tag .
    ?tag rdfs:comment ?tag_text .
    FILTER ( ?tag_text = '%(playlist_tag)s' )
    """.replace('\n', ' ').strip() % {
            'playlist_tag': playlist_tag
        }

        return Query.playlists(query)

    @staticmethod
    def get_playlist_with_urn(playlist_urn):
        query = """
    SELECT DISTINCT
        tracker:id(<%(playlist_urn)s>) AS id
    WHERE {
        <%(playlist_urn)s> a nmm:Playlist
    }
    """.replace('\n', ' ').strip() % {
            'playlist_urn': playlist_urn
        }
        return query

    @staticmethod
    def get_playlist_song_with_id(playlist_id, entry_id):
        return Query.playlist_songs(playlist_id,
                                    'tracker:id(?entry) = ' + str(entry_id))

    @staticmethod
    def get_playlist_song_with_urn(entry_urn):
        query = """
    SELECT DISTINCT
        tracker:id(<%(entry_urn)s>) AS id
    WHERE {
        <%(entry_urn)s> a nfo:MediaFileListEntry
    }
    """.replace('\n', ' ').strip() % {
            'entry_urn': entry_urn
        }
        return query

    @staticmethod
    def clear_playlist_with_id(playlist_id):
        query = """
        DELETE {
            ?playlist
                nfo:hasMediaFileListEntry ?entry .
            ?entry
                a rdfs:Resource .
        }
        WHERE {
            ?playlist
                a nmm:Playlist ;
                a nfo:MediaList ;
                nfo:hasMediaFileListEntry ?entry .
            FILTER (
                tracker:id(?playlist) = %(playlist_id)s
            )
        }
        """.replace('\n', ' ').strip() % {
            'playlist_id': playlist_id
        }

        return query

    @staticmethod
    def get_most_played_songs():
        # TODO: set playlist size somewhere? Currently default is 50.
        query = """
        SELECT ?url
        WHERE {
            ?song a nmm:MusicPiece ;
                nie:usageCounter ?count ;
                nie:isStoredAs ?as .
          ?as nie:url ?url .
        } ORDER BY DESC(?count) LIMIT 50
        """.replace('\n', ' ').strip()

        return query

    @staticmethod
    def get_never_played_songs():
        query = """
        SELECT ?url
        WHERE {
            ?song a nmm:MusicPiece ;
                nie:isStoredAs ?as .
            ?as nie:url ?url .
            FILTER ( NOT EXISTS { ?song nie:usageCounter ?count .} )
        } ORDER BY nfo:fileLastAccessed(?song)
        """.replace('\n', ' ').strip()

        return query

    def get_recently_played_songs():
        #TODO: or this could take comparison date as an argument so we don't need to make a date string in query.py...
        #TODO: set time interval somewhere? A settings file? (Default is maybe 2 weeks...?)

        days_difference = 7  # currently hardcoding time interval of 7 days
        seconds_difference = days_difference * SECONDS_PER_DAY
        compare_date = time.strftime(
            sparql_midnight_dateTime_format,
            time.gmtime(time.time() - seconds_difference))

        query = """
            SELECT ?url
            WHERE {
                ?song a nmm:MusicPiece ;
                    nie:isStoredAs ?as ;
                    nfo:fileLastAccessed ?last_played .
                ?as nie:url ?url .
                FILTER ( ?last_played > '%(compare_date)s'^^xsd:dateTime )
                FILTER ( EXISTS { ?song nie:usageCounter ?count .} )
            } ORDER BY DESC(?last_played)
            """.replace('\n', ' ').strip() % {
            'compare_date': compare_date
        }

        return query

    def get_recently_added_songs():
        #TODO: or this could take comparison date as an argument so we don't need to make a date string in query.py...
        #TODO: set time interval somewhere? A settings file? (Default is maybe 2 weeks...?)

        days_difference = 7  # currently hardcoding time interval of 7 days
        seconds_difference = days_difference * SECONDS_PER_DAY
        compare_date = time.strftime(
            sparql_midnight_dateTime_format,
            time.gmtime(time.time() - seconds_difference))

        query = """
        SELECT ?url
        WHERE {
            ?song a nmm:MusicPiece ;
                nie:isStoredAs ?as ;
                tracker:added ?added .
            ?as nie:url ?url .
            FILTER ( ?added > '%(compare_date)s'^^xsd:dateTime )
        } ORDER BY DESC(?added)
        """.replace('\n', ' ').strip() % {
            'compare_date': compare_date
        }

        return query

    def get_favorite_songs():
        query = """
    SELECT ?url
    WHERE {
        ?song a nmm:MusicPiece ;
            nie:isStoredAs ?as ;
            nao:hasTag nao:predefined-tag-favorite .
        ?as nie:url ?url .
    } ORDER BY DESC(tracker:added(?song))
    """.replace('\n', ' ').strip()

        return query

    # Functions for search
    # TODO: make those queries actually return something
    @staticmethod
    def get_albums_with_any_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    nmm:musicAlbum(?song) AS album
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(nmm:musicAlbum(?song))), "%(name)s") ||
                        fn:contains(tracker:case-fold(nmm:artistName(nmm:performer(?song))), "%(name)s") ||
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.albums(query)

    @staticmethod
    def get_albums_with_artist_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?album
                WHERE {
                    ?album a nmm:MusicAlbum ;
                        nmm:albumArtist ?artist .
                    FILTER (
                        fn:contains(tracker:case-fold(nmm:artistName(?artist)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.albums(query)

    @staticmethod
    def get_albums_with_album_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?album
                WHERE {
                    ?album a nmm:MusicAlbum .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?album)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.albums(query)

    @staticmethod
    def get_albums_with_track_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    nmm:musicAlbum(?song) AS album
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.albums(query)

    @staticmethod
    def get_artists_with_any_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    nmm:musicAlbum(?song) AS album
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(nmm:musicAlbum(?song))), "%(name)s") ||
                        fn:contains(tracker:case-fold(nmm:artistName(nmm:performer(?song))), "%(name)s") ||
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.artists(query)

    @staticmethod
    def get_artists_with_artist_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?album
                WHERE {
                    ?album a nmm:MusicAlbum ;
                        nmm:albumArtist ?artist .
                    FILTER (
                        fn:contains(tracker:case-fold(nmm:artistName(?artist)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.artists(query)

    @staticmethod
    def get_artists_with_album_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?album
                WHERE {
                    ?album a nmm:MusicAlbum .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?album)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.artists(query)

    @staticmethod
    def get_artists_with_track_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    nmm:musicAlbum(?song) AS album
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.artists(query)

    @staticmethod
    def get_songs_with_any_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?song
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s") ||
                        fn:contains(tracker:case-fold(nmm:artistName(nmm:performer(?song))), "%(name)s") ||
                        fn:contains(tracker:case-fold(nie:title(nmm:musicAlbum(?song))), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.songs(query)

    @staticmethod
    def get_songs_with_artist_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?song
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nmm:artistName(nmm:performer(?song))), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.songs(query)

    @staticmethod
    def get_songs_with_album_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?song
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(nmm:musicAlbum(?song))), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.songs(query)

    @staticmethod
    def get_songs_with_track_match(name):
        name = Tracker.sparql_escape_string(GLib.utf8_casefold(name, -1))
        query = '''
            {
                SELECT DISTINCT
                    ?song
                WHERE {
                    ?song a nmm:MusicPiece .
                    FILTER (
                        fn:contains(tracker:case-fold(nie:title(?song)), "%(name)s")
                    )
                }
            }
            '''.replace('\n', ' ').strip() % {
            'name': name
        }

        return Query.songs(query)

    @staticmethod
    def clear_playlist(playlist_id):
        # TODO is there a way to do this with only one FILTER statement?

        query = """
    DELETE {
        ?playlist
            nfo:hasMediaFileListEntry ?entry .
        ?entry
            a rdfs:Resource .
    }
    WHERE {
        ?playlist
            a nmm:Playlist ;
            a nfo:MediaList ;
            nfo:hasMediaFileListEntry ?entry .
        FILTER (
            tracker:id(?playlist) = %(playlist_id)s
        )
    }
    INSERT OR REPLACE {
        ?playlist nfo:entryCounter '0'
    }
    WHERE {
        ?playlist
            a nmm:Playlist ;
            a nfo:MediaList .
        FILTER (
            tracker:id(?playlist) = %(playlist_id)s
        )
    }
        """.replace("\n", " ").strip() % {
            'playlist_id': playlist_id
        }

        return query

    def add_favorite(song_url):
        query = """
            INSERT {
                ?song nao:hasTag nao:predefined-tag-favorite
            }
            WHERE {
                ?song a nmm:MusicPiece .
                FILTER ( nie:url(?song) = "%(song_url)s" )
            }
        """.replace("\n", " ").strip() % {
            'song_url': song_url
        }

        return query

    def remove_favorite(song_url):
        query = """
            DELETE {
                ?song nao:hasTag nao:predefined-tag-favorite
            }
            WHERE {
                ?song a nmm:MusicPiece .
                FILTER ( nie:url(?song) = "%(song_url)s" )
            }
        """.replace("\n", " ").strip() % {
            'song_url': song_url
        }

        return query
Example #57
0
    def __init__(self):
        """
            Init dialog
        """
        self.__choosers = []
        self.__cover_tid = None
        self.__mix_tid = None
        self.__popover = None

        cs_api_key = Lp().settings.get_value('cs-api-key').get_string()
        default_cs_api_key = Lp().settings.get_default_value(
            'cs-api-key').get_string()
        if (not cs_api_key or
            cs_api_key == default_cs_api_key) and\
                get_network_available() and\
                Lp().notify is not None:
            Lp().notify.send(
                _("Google Web Services need a custom API key"),
                _("Lollypop needs this to search artwork and music."))

        builder = Gtk.Builder()
        builder.add_from_resource('/org/gnome/Lollypop/SettingsDialog.ui')
        self.__progress = builder.get_object('progress')
        self.__infobar = builder.get_object('infobar')
        self.__reset_button = builder.get_object('reset_button')
        if Lp().lastfm is None or Lp().lastfm.is_goa:
            builder.get_object('lastfm_grid').hide()
        if Lp().scanner.is_locked():
            builder.get_object('reset_button').set_sensitive(False)
        artists = Lp().artists.count()
        albums = Lp().albums.count()
        tracks = Lp().tracks.count()
        builder.get_object('artists').set_text(
            ngettext("%d artist", "%d artists", artists) % artists)
        builder.get_object('albums').set_text(
            ngettext("%d album", "%d albums", albums) % albums)
        builder.get_object('tracks').set_text(
            ngettext("%d track", "%d tracks", tracks) % tracks)

        self.__popover_content = builder.get_object('popover')
        duration = builder.get_object('duration')
        duration.set_range(1, 20)
        duration.set_value(Lp().settings.get_value('mix-duration').get_int32())

        self.__settings_dialog = builder.get_object('settings_dialog')
        self.__settings_dialog.set_transient_for(Lp().window)

        if Lp().settings.get_value('disable-csd'):
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object('header_bar')
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        switch_scan = builder.get_object('switch_scan')
        switch_scan.set_state(Lp().settings.get_value('auto-update'))

        switch_view = builder.get_object('switch_dark')
        if Lp().gtk_application_prefer_dark_theme:
            switch_view.set_sensitive(False)
        else:
            switch_view.set_state(Lp().settings.get_value('dark-ui'))

        switch_background = builder.get_object('switch_background')
        switch_background.set_state(Lp().settings.get_value('background-mode'))

        switch_state = builder.get_object('switch_state')
        switch_state.set_state(Lp().settings.get_value('save-state'))

        switch_mix = builder.get_object('switch_mix')
        switch_mix.set_state(Lp().settings.get_value('mix'))
        self.__helper = TouchHelper(switch_mix, None, None)
        self.__helper.set_long_func(self.__mix_long_func, switch_mix)
        self.__helper.set_short_func(self.__mix_short_func, switch_mix)

        switch_mix_party = builder.get_object('switch_mix_party')
        switch_mix_party.set_state(Lp().settings.get_value('party-mix'))

        switch_librefm = builder.get_object('switch_librefm')
        switch_librefm.set_state(Lp().settings.get_value('use-librefm'))

        switch_artwork_tags = builder.get_object('switch_artwork_tags')
        # Check portal for kid3-cli
        can_set_cover = False
        try:
            bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
            proxy = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
                                           'org.gnome.Lollypop.Portal',
                                           '/org/gnome/LollypopPortal',
                                           'org.gnome.Lollypop.Portal', None)
            can_set_cover = proxy.call_sync('CanSetCover', None,
                                            Gio.DBusCallFlags.NO_AUTO_START,
                                            500, None)[0]
        except Exception as e:
            print(
                "You are missing lollypop-portal: "
                "https://github.com/gnumdk/lollypop-portal", e)
        if not can_set_cover:
            grid = builder.get_object('grid_behaviour')
            h = grid.child_get_property(switch_artwork_tags, 'height')
            w = grid.child_get_property(switch_artwork_tags, 'width')
            l = grid.child_get_property(switch_artwork_tags, 'left-attach')
            t = grid.child_get_property(switch_artwork_tags, 'top-attach')
            switch_artwork_tags.destroy()
            label = Gtk.Label.new(_("You need to install kid3-cli"))
            label.get_style_context().add_class('dim-label')
            label.set_property('halign', Gtk.Align.END)
            label.show()
            grid.attach(label, l, t, w, h)
        else:
            switch_artwork_tags.set_state(
                Lp().settings.get_value('save-to-tags'))

        if GLib.find_program_in_path("youtube-dl") is None:
            builder.get_object('charts_grid').hide()
        else:
            switch_charts = builder.get_object('switch_charts')
            switch_charts.set_state(Lp().settings.get_value('show-charts'))

        switch_genres = builder.get_object('switch_genres')
        switch_genres.set_state(Lp().settings.get_value('show-genres'))

        switch_compilations = builder.get_object('switch_compilations')
        switch_compilations.set_state(
            Lp().settings.get_value('show-compilations'))

        switch_artwork = builder.get_object('switch_artwork')
        switch_artwork.set_state(Lp().settings.get_value('artist-artwork'))

        switch_spotify = builder.get_object('switch_spotify')
        switch_spotify.set_state(Lp().settings.get_value('search-spotify'))

        switch_itunes = builder.get_object('switch_itunes')
        switch_itunes.set_state(Lp().settings.get_value('search-itunes'))

        if GLib.find_program_in_path("youtube-dl") is None:
            builder.get_object('yt-dl').show()

        combo_orderby = builder.get_object('combo_orderby')
        combo_orderby.set_active(Lp().settings.get_enum(('orderby')))

        combo_preview = builder.get_object('combo_preview')

        scale_coversize = builder.get_object('scale_coversize')
        scale_coversize.set_range(150, 300)
        scale_coversize.set_value(
            Lp().settings.get_value('cover-size').get_int32())
        self.__settings_dialog.connect('destroy', self.__edit_settings_close)

        builder.connect_signals(self)

        main_chooser_box = builder.get_object('main_chooser_box')
        self.__chooser_box = builder.get_object('chooser_box')

        self.__set_outputs(combo_preview)

        #
        # Music tab
        #
        dirs = []
        for directory in Lp().settings.get_value('music-uris'):
            dirs.append(directory)

        # Main chooser
        self.__main_chooser = ChooserWidget()
        image = Gtk.Image.new_from_icon_name("list-add-symbolic",
                                             Gtk.IconSize.MENU)
        self.__main_chooser.set_icon(image)
        self.__main_chooser.set_action(self.__add_chooser)
        main_chooser_box.pack_start(self.__main_chooser, False, True, 0)
        if len(dirs) > 0:
            uri = dirs.pop(0)
        else:
            filename = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_MUSIC)
            if filename:
                uri = GLib.filename_to_uri(filename)
            else:
                uri = ""

        self.__main_chooser.set_dir(uri)

        # Others choosers
        for directory in dirs:
            self.__add_chooser(directory)

        #
        # Google tab
        #
        builder.get_object('cs-entry').set_text(
            Lp().settings.get_value('cs-api-key').get_string())
        #
        # Last.fm tab
        #
        if Lp().lastfm is not None and Secret is not None:
            self.__test_img = builder.get_object('test_img')
            self.__login = builder.get_object('login')
            self.__password = builder.get_object('password')
            schema = Secret.Schema.new("org.gnome.Lollypop",
                                       Secret.SchemaFlags.NONE, SecretSchema)
            Secret.password_lookup(schema, SecretAttributes, None,
                                   self.__on_password_lookup)
            builder.get_object('lastfm_grid').set_sensitive(True)
            builder.get_object('lastfm_error').hide()
            self.__login.set_text(
                Lp().settings.get_value('lastfm-login').get_string())
Example #58
0
    def __init__(self, window):
        """
            Init dialog
            @param window as Window
        """
        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Eolie/SettingsDialog.ui")

        self.__settings_dialog = builder.get_object("settings_dialog")
        self.__settings_dialog.set_transient_for(window)
        # self.__settings_dialog.connect("destroy", self.__on_destroy)

        if False:
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object("header_bar")
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        download_chooser = builder.get_object("download_chooser")
        dir_uri = El().settings.get_value("download-uri").get_string()
        if not dir_uri:
            directory = GLib.get_user_special_dir(
                GLib.UserDirectory.DIRECTORY_DOWNLOAD)
            if directory is not None:
                dir_uri = GLib.filename_to_uri(directory, None)
        if dir_uri:
            download_chooser.set_uri(dir_uri)
        else:
            download_chooser.set_uri("file://" + GLib.getenv("HOME"))

        open_downloads = builder.get_object("open_downloads_check")
        open_downloads.set_active(El().settings.get_value("open-downloads"))

        self.__start_page_uri = builder.get_object("start_page_uri")
        combo_start = builder.get_object("combo_start")
        start_page = El().settings.get_value("start-page").get_string()
        if start_page.startswith("http"):
            combo_start.set_active_id("address")
            self.__start_page_uri.set_text(start_page)
            self.__start_page_uri.show()
        else:
            combo_start.set_active_id(start_page)

        combo_engine = builder.get_object("combo_engine")
        combo_engine.set_active_id(
            El().settings.get_value("search-engine").get_string())

        remember_session = builder.get_object("remember_sessions_check")
        remember_session.set_active(
            El().settings.get_value("remember-session"))

        enable_plugins = builder.get_object("plugins_check")
        enable_plugins.set_active(El().settings.get_value("enable-plugins"))

        self.__fonts_grid = builder.get_object("fonts_grid")
        use_system_fonts = builder.get_object("system_fonts_check")
        use_system_fonts.set_active(
            El().settings.get_value("use-system-fonts"))
        self.__fonts_grid.set_sensitive(
            not El().settings.get_value("use-system-fonts"))

        sans_serif_button = builder.get_object("sans_serif_button")
        sans_serif_button.set_font_name(
            El().settings.get_value("font-sans-serif").get_string())
        serif_button = builder.get_object("serif_button")
        serif_button.set_font_name(
            El().settings.get_value("font-serif").get_string())
        monospace_button = builder.get_object("monospace_button")
        monospace_button.set_font_name(
            El().settings.get_value("font-monospace").get_string())

        min_font_size_spin = builder.get_object("min_font_size_spin")
        min_font_size_spin.set_value(
            El().settings.get_value("min-font-size").get_int32())

        monitor_model = get_current_monitor_model(window)
        zoom_levels = El().settings.get_value("default-zoom-level")
        wanted_zoom_level = 1.0
        try:
            for zoom_level in zoom_levels:
                zoom_splited = zoom_level.split('@')
                if zoom_splited[0] == monitor_model:
                    wanted_zoom_level = float(zoom_splited[1])
        except:
            pass
        default_zoom_level = builder.get_object("default_zoom_level")
        default_zoom_level.set_value(float(wanted_zoom_level))

        cookies_combo = builder.get_object("cookies_combo")
        storage = El().settings.get_enum("cookie-storage")
        cookies_combo.set_active_id(str(storage))

        if GLib.find_program_in_path("seahorse") is None:
            button = builder.get_object("manage_passwords_button")
            button.set_sensitive(False)
            button.set_label(
                _("Installing seahorse will allow you\n"
                  "managing your passwords"))

        remember_passwords = builder.get_object("remember_passwords_check")
        remember_passwords.set_active(
            El().settings.get_value("remember-passwords"))

        tracking_check = builder.get_object("tracking_check")
        tracking_check.set_active(El().settings.get_value("do-not-track"))
        label = builder.get_object("result_label")
        sync_button = builder.get_object("sync_button")
        if El().sync_worker is not None:
            login_entry = builder.get_object("login_entry")
            login_entry.set_text(El().sync_worker.username)
            password_entry = builder.get_object("password_entry")
            image = builder.get_object("result_image")
            if El().sync_worker.status:
                label.set_text(_("Synchronization is working"))
                image.set_from_icon_name("network-transmit-receive-symbolic",
                                         Gtk.IconSize.MENU)
            sync_button.connect("clicked", self.__on_sync_button_clicked,
                                login_entry, password_entry, label, image)
        else:
            try:
                from eolie.mozilla_sync import SyncWorker
                SyncWorker  # Just make PEP8 happy
            except Exception as e:
                label.set_text(
                    _("Synchronization is not available"
                      " on your computer:\n %s") % e)
                sync_button.set_sensitive(False)

        builder.connect_signals(self)