Commits

Vladimir Kolev committed 8f9391c

Merge changes, remove unused imports from Song.py, pep8 - removing unneded whitespaces

Comments (0)

Files changed (14)

lib/AbstractSongList.py

     This class represents a Song list linked with a TreeView  
     and a ListStore. also provides several facilities to manage the list.
     """
-    
+
     def __init__(self, view):
         """
         Initialize the List
         self._view = view
         self._view.set_model(self.create_model())
         self.create_view()
-    
+
     def create_model(self):
         """
         Return the model used by the list, a derived class must reimplement
         """
         model = gtk.ListStore(object)
         return model
-    
+
     def create_view(self):
         """
         Initialize the TreeView, a derived class must reimplement
         this method.
         """
         pass
-    
+
     def get_view(self):
         return self._view
-        
+
     def get_model(self):
         return self.get_view().get_model()
-    
+
     def append_song(self, song):
         """
         Append a song to the list, a derived class must reimplement
         this method.
         """
         self.get_model().append([song])
-    
+
     def find_song(self, song):
         """
         Return a tuple containing the path and iter for the song passed
             if self.get_model()[iter][0].equals(song):
                 return (self.get_model().get_path(iter), iter)
             iter = self.get_model().iter_next(iter)
-            
+
         return None
-    
+
     def get_song_row(self, song):
         """
         Returns the model row related to the song passed by parameter.
             return None
         else:
             return self.get_model()[iter]
-        
+
     def get_song_path(self, song):
         """
         Returns the path related to the song passed by parameter.
         """
         finded = self.find_song(song)
-        
+
         if finded == None:
             return None
         else:
         Returns the TreeIter related to the song passed by parameter.
         """
         finded = self.find_song(song)
-        
+
         if finded == None:
             return None
         else:
             return finded[1]
-        
+
     def get_song(self, path_or_iter):
         """
         Returns the song related to a path or iter
         """
         return self.get_model()[path_or_iter][0]
-        
-    
+
+
     # Shortcuts to handle the list
-    
+
     def clear(self):
         """
         Clear the list.
         """
         self.get_model().clear()
-        
+
     def __len__(self):
         """
         Allows to do the following: len(songlist)
         """
         return len(self.get_model())
-    
+
     def first(self):
         """
         Returns the first iter of the list.
         """
         return self.get_model().get_iter_first()
-    
+
     def next(self, iter):
         """
         Returns the next iter of the iter passed by parameter
         """
         return self.get_model().iter_next(iter)
-    
+
     def range(self):
         """
         Returns a range from 0 to len-1 to ease the list walking.
         """
         return range(len(self.get_model()))
-    
+
     def get_selected_rows(self):
         return self.get_view().get_selection().get_selected_rows()[1]
-        
+

lib/DownloadList.py

 import gtk
 import os
 import traceback
-    
+
 class DownloadList(AbstractSongList):
     """
     Represent the download list
     """
-    
+
     def __init__(self, view):
         self.__gobject_init__()
         AbstractSongList.__init__(self, view)
         self.downloads_count = 0
-        
+
         gobject.timeout_add(300, self.on_timeout)
-    
+
     def create_model(self):
         # Song, File Name, Speed, Progress, Size, Icon info stock
         return gtk.ListStore(object, str, str, int, str, str)
-    
+
     def __append_song_to_model(self, song):
         song = song.clone()
-        
+
         if self.find_song(song) != None:
             raise Exception()
-        
+
         self.get_model().append([
             song,
             unicode(os.path.basename(song.get_filename()), errors = 'replace'),
             "",
             "gtk-network"
         ])
-            
+
     def append_song(self, song):
         """
         Append song for download, if file exists, tries to continue the download
             self.__append_song_to_model(song);
         except Exception:
             pass
-        
+
     def append_song_restarting(self, song):
         """
         Append song for download, forcing to redownload the file
             self.__append_song_to_model(song);
         except Exception:
             pass
-        
+
     def create_view(self):
         self.get_view().get_selection().set_mode(gtk.SELECTION_MULTIPLE)
-        
+
         column = gtk.TreeViewColumn("", gtk.CellRendererPixbuf(), stock_id = 5)
         column.set_resizable(False)
         self.get_view().append_column(column)
-        
+
         column = gtk.TreeViewColumn(_("File name"), gtk.CellRendererText(), text = 1)
         column.set_resizable(True)
         self.get_view().append_column(column)
         column = gtk.TreeViewColumn(_("Speed"), gtk.CellRendererText(), text = 2)
         column.set_resizable(True)
         self.get_view().append_column(column)
-        
+
         column = gtk.TreeViewColumn(_("Size"), gtk.CellRendererText(), text = 4)
         column.set_resizable(True)
         self.get_view().append_column(column)
-        
+
         column = gtk.TreeViewColumn(_("Download progress"), gtk.CellRendererProgress(), value = 3)
         column.set_resizable(True)
         self.get_view().append_column(column)
-        
+
     def on_timeout(self):
         downcount = 0
         next_download_path = None
         need_download = True
-        
+
         for i in reversed(self.range()):
             row = self.get_model()[i]
             song = self.get_song(i)
             elif song.get_state() == Song.STATE_ERROR:
                 row[2] = ""
                 row[5] = "gtk-dialog-error"
-                
+
         if downcount != self.downloads_count:
             self.downloads_count = downcount
             self.emit("downloads-changed", downcount)
-            
+
         if need_download == True and next_download_path != None:
             self.get_song(next_download_path).resume_download()
-            
+
         return True
-        
+
     def stop_all_downloads(self):
         """
         Stop all downloads in a sync way for quit the main app
             self.get_song(i).pause_download_sync()
 
 gobject.type_register(DownloadList)
-gobject.signal_new("downloads-changed", DownloadList, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_INT,))
+gobject.signal_new("downloads-changed", DownloadList, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_INT,))
 from enviroment import env, config
 import gtk
 import glib
-    
+
 class PlayList (AbstractSongList):
     """
     Represent the PlayList
     """
-    
+
     # Styles
-    TEXT_BELOW_ICONS = "0" 
+    TEXT_BELOW_ICONS = "0"
     TEXT_BESIDE_ICONS = "1"
     ICONS_BIG = "2"
     ICONS_SMALL = "3"
     NOT_SHOW = "4"
-    
+
     ICON_SIZE = 80
-    
+
     def __init__(self, view):
         self.style = PlayList.TEXT_BELOW_ICONS
         AbstractSongList.__init__(self, view)
         self.playing_song = None
-    
+
     def create_model(self):
         # Model: Song, Full label, Sliced label, Big image, Small image, Tooltip
         return gtk.ListStore(object, str, str, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, str)
-    
+
     def get_sliced_string(self, str, max):
         sliced = str[0:max - 3]
         if len(sliced) < len(str):
             return sliced + "..."
         else:
             return str
-        
+
     def create_view(self):
         self.get_view().set_selection_mode(gtk.SELECTION_MULTIPLE)
         self.get_view().set_reorderable(True)
         self.get_view().set_columns(99999)
-        
+
         self.get_view().add_events(gtk.gdk.SCROLL_MASK)
         self.get_view().connect("scroll-event", self.on_mouse_wheel_scroll)
-        
+
         self.set_style(config()["playlist_style"])
-        
+
     def on_mouse_wheel_scroll(self, widget, event):
         # We need to assume that the IconView has a ScrolledWindow as parent 
         adjustment = self.get_view().get_parent().get_hadjustment()
             if newvalue > adjustment.get_upper() - adjustment.get_page_size():
                 newvalue = adjustment.get_upper() - adjustment.get_page_size()
         adjustment.set_value(newvalue)
-        
+
     def set_style(self, style):
         self.style = style
-        
+
         self.get_view().set_tooltip_column(5)
-        
+
         if style == PlayList.TEXT_BELOW_ICONS:
             self.get_view().set_markup_column(2)
             self.get_view().set_pixbuf_column(3)
                 self.get_view().set_item_orientation(gtk.ORIENTATION_VERTICAL)
             self.get_view().set_spacing(0)
             self.get_view().set_item_width(60)
-        
+
         if style == PlayList.NOT_SHOW:
             self.get_view().get_parent().get_parent().hide()
             self.get_view().unselect_all()
         else:
             self.get_view().get_parent().get_parent().show()
-    
+
     def get_style(self):
         return self.style
-        
+
     def get_selected_rows(self):
         return self.get_view().get_selected_items()
-    
+
     def get_playing_song(self):
         """
         Returns the current playing song or None if not playing nothing.
         """
         return self.playing_song
-    
+
     def reload_image(self, path_or_iter):
         song = self.get_song(path_or_iter)
         pixbuf = None
-        
+
         if song.get_cover_pixbuf() != None:
             pixbuf = self.create_cornered_image(song.get_cover_pixbuf())
         else:
             pixbuf = self.create_loading_track_icon()
-            
+
         if self.playing_song != None and song.equals(self.playing_song):
             pixbuf = self.create_play_image(pixbuf)
-        
+
         self.get_model()[path_or_iter][3] = self.scale_big(pixbuf)
         self.get_model()[path_or_iter][4] = self.scale_small(pixbuf)
-    
+
     def set_playing_song(self, song):
         """
         Set the current playing song.
         """
         old_playing_song = self.playing_song
         self.playing_song = song
-        
+
         if old_playing_song != None:
             self.reload_image(self.get_song_path(old_playing_song))
-        
+
         if song != None:
             path = self.get_song_path(song)
             self.reload_image(path)
-            self.get_view().scroll_to_path(path, False, 0, 0) 
-        
-    
+            self.get_view().scroll_to_path(path, False, 0, 0)
+
+
     def append_song(self, song):
         # Change song local ID to fix the search by song
         song = song.clone()
-        
+
         song_string_full = "<span font_size='small'>{title}</span>\n<span font_size='small' fgcolor='#555555'>{artist}</span>".format(
             title = glib.markup_escape_text(song.get_title()),
             artist = glib.markup_escape_text(song.get_artist())
         )
-        
+
         song_string_sliced = "<span font_size='small'>{title}</span>\n<span font_size='small' fgcolor='#555555'>{artist}</span>".format(
             title = self.get_sliced_string(glib.markup_escape_text(song.get_title()), 25),
             artist = self.get_sliced_string(glib.markup_escape_text(song.get_artist()), 20)
         )
-        
+
         tooltip = _("<b>Title:</b> {title}\n<b>Artist:</b> {artist}\n<b>Album:</b> {album}\n<b>Year:</b> {year}").format(
             title = glib.markup_escape_text(song.get_title()),
             artist = glib.markup_escape_text(song.get_artist()),
             album = glib.markup_escape_text(song.get_album()),
             year = song.get_year()
         )
-        
+
         appended_iter = self.get_model().append([
             song,
             song_string_full,
             None,
             tooltip
         ])
-        
+
         self.reload_image(appended_iter)
-        
+
         if song.get_cover_pixbuf() == None:
             song.connect("cover-downloaded", self.on_song_cover_downloaded)
             song.download_cover()
-            
+
     def on_song_cover_downloaded(self, song):
         self.reload_image(self.get_song_path(song))
-        
+
     def create_loading_track_icon(self):
         return gtk.gdk.pixbuf_new_from_file("%s/data/loading.png" % env().BASEPATH)
 
         corners.composite(pixbuf, 0, 0, pixbuf.props.width, pixbuf.props.height,
                           0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)
         return pixbuf
-    
+
     def create_play_image(self, pixbuf):
         """
         Composite play.png with the pixbuf
         play.composite(pixbuf, 0, 0, pixbuf.props.width, pixbuf.props.height,
                           0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)
         return pixbuf
-    
+
     def scale_big(self, pixbuf):
         return pixbuf.scale_simple(80, 80, gtk.gdk.INTERP_HYPER)
-    
+
     def scale_small(self, pixbuf):
         return pixbuf.scale_simple(50, 50, gtk.gdk.INTERP_HYPER)

lib/PlayListStyleWidget.py

 class PlayListStyleWidget(gtk.Button):
     def __init__(self):
         gtk.Button.__init__(self)
-        
+
         self.menu = gtk.Menu()
-        
+
         menu_items = [
             (PlayList.TEXT_BELOW_ICONS, _("Text below icons"),),
             (PlayList.TEXT_BESIDE_ICONS, _("Text beside icons"),),
 #            (PlayList.ICONS_SMALL, _("Icons only (small)"),),
             (PlayList.NOT_SHOW, _("Not show"),),
         ]
-        
+
         first_item_widget = None
-        
+
         for item in menu_items:
             item_widget = gtk.RadioMenuItem(None, item[1])
             if first_item_widget == None:
             else:
                 item_widget.set_group(first_item_widget)
             self.menu.append(item_widget)
-            
+
             if item[0] == str(config()["playlist_style"]):
                 item_widget.set_active(True)
-                
+
             item_widget.connect("activate", self.on_item_activate, item[0])
-        
+
         self.menu.show_all()
-        self.set_image( gtk.image_new_from_file("%s/data/playlist_style.png" % env().BASEPATH) )
+        self.set_image(gtk.image_new_from_file("%s/data/playlist_style.png" % env().BASEPATH))
         self.set_relief(gtk.RELIEF_NONE)
         self.set_focus_on_click(False)
-        
+
         if env().have_playlist_style() == True:
             self.connect("clicked", self.on_clicked)
             self.set_tooltip_text(_("Change the playlist style"))
         else:
             self.set_sensitive(False)
             self.set_tooltip_text(_("Please update your version of PyGtk\nto change the playlist style"))
-    
+
     def on_clicked(self, button):
         self.menu.popup(None, None, self.menu_reposition_callback, 0, 0)
-    
+
     def menu_reposition_callback(self, menu, data = None):
         return (
             self.get_parent_window().get_origin()[0] + self.get_allocation().x,
             self.get_parent_window().get_origin()[1] + self.get_allocation().y + self.get_allocation().height - 5,
             True
         )
-    
+
     def on_item_activate(self, menuitem, style):
         if menuitem.get_active() == True:
             config()["playlist_style"] = style
             config().write()
             self.emit("style-changed", style)
-            
-            
+
+
 gobject.type_register(PlayListStyleWidget)
 gobject.signal_new("style-changed", PlayListStyleWidget, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))

lib/SearchResultList.py

 from AbstractSongList import AbstractSongList
 import gtk
 import glib
-    
+
 class SearchResultList(AbstractSongList):
     """
     Represent the list of search results
     """
-    
+
     def __init__(self, view):
         self.filter_text = ""
         self.modelfilter = None
         self.sortmodel = None
-        
+
         AbstractSongList.__init__(self, view)
-    
+
     def create_model(self):
         # Model: Song, Title, Artist, Album
         model = gtk.ListStore(object, str, str, str)
         self.modelfilter = model.filter_new()
         self.modelfilter.set_visible_func(self.filter_visible_func)
         return gtk.TreeModelSort(self.modelfilter)
-    
+
     def append_song(self, song):
         self.get_full_model().append([
             song,
             song.get_artist(),
             song.get_album()
         ])
-        
+
     def get_model(self):
         return self.modelfilter
-    
+
     def get_sorted_model(self):
         return self.get_view().get_model()
-    
+
     def get_full_model(self):
         return self.get_model().get_model()
-        
+
     def clear(self):
         self.get_full_model().clear()
-        
+
     def create_view(self):
         self.get_view().get_selection().set_mode(gtk.SELECTION_MULTIPLE)
-        
+
         rendererText = gtk.CellRendererText()
         column = gtk.TreeViewColumn(_("Title"), rendererText, markup = 1)
         self.get_view().append_column(column)
         column.set_resizable(True)
         column.set_max_width(150)
         column.set_sort_column_id(3)
-        
+
     def set_filter_text(self, text):
         self.filter_text = " ".join(text.split()).lower()
         self.modelfilter.refilter()
-    
+
     def get_filter_text(self, text):
         return self.filter_text
-    
+
     def filter_visible_func(self, model, iter):
         if self.filter_text == "":
             return True
             song = model[iter][0]
             t = self.filter_text
             return song.get_title().lower().find(t) >= 0 or song.get_artist().lower().find(t) >= 0 or song.get_album().lower().find(t) >= 0
-        
+
     def get_selected_rows(self):
         selection = self.get_view().get_selection().get_selected_rows()[1]
         for i in range(len(selection)):
         self.player_state_timeout_id = None
         self.is_buffering = False
         self.pynotify_object = None
-        
+
         # GtkBuilder initialization
         builder = gtk.Builder()
         builder.set_translation_domain(env().APP)
         builder.add_from_file('%s/data/main_window.ui' % env().BASEPATH)
-        
+
         # Main window and widgets initialization
         self.window = builder.get_object('mainwindow')
         self.window.connect("delete-event", self.window.hide_on_delete)
         self.mainmenu = builder.get_object('mainmenu')
-        
+
         self.vbox_results = builder.get_object('vbox_results')
         self.hbox_filter = builder.get_object('hbox_filter')
-        
+
         self.button_play = builder.get_object('button_play')
         self.widget_image_play = builder.get_object('widget_image_play')
         self.widget_image_stop = builder.get_object('widget_image_stop')
         self.widget_image_buffering = gtk.Image()
         self.widget_image_buffering.set_from_file('%s/data/buffering.gif' % env().BASEPATH)
         self.widget_image_buffering.set_pixel_size(22)
-        
+
         self.label_player_time = builder.get_object('label_player_time')
         self.label_player_trackinfo = builder.get_object('label_player_trackinfo')
         self.seekbar = builder.get_object('seekbar')
         self.button_love = builder.get_object('button_love')
         self.button_songinfo = builder.get_object('button_songinfo')
         self.songinfo = builder.get_object('songinfo')
-        
+
         button_repeat = builder.get_object('togglebutton_repeat')
-        button_repeat.set_active(int(config()['repeat_playlist'])) 
+        button_repeat.set_active(int(config()['repeat_playlist']))
         button_shuffle = builder.get_object('togglebutton_shuffle')
         button_shuffle.set_active(int(config()['shuffle_playlist']))
-        
+
         combo_playlist_style = PlayListStyleWidget()
         combo_playlist_style.connect("style-changed", self.on_playlist_style_changed)
         hbox_playlist_right = builder.get_object('hbox_playlist_right')
         hbox_playlist_right.add(combo_playlist_style)
-        
+
         self.panes = builder.get_object('notebook1')
         self.playview_pane_label = builder.get_object('togglebutton_playlist')
         self.playview_pane_label.get_image().show()
         self.downloads_pane_label = builder.get_object('togglebutton_downloads')
-        
+
         self.entry_search = builder.get_object('toolentry_search')
         self.entry_filter = builder.get_object('entry_filter')
-        
+
         # GStreamer player initialization
         self.player = gst.element_factory_make("playbin2", "player")
         self.player.connect("notify::source", self.on_player_source_setup)
             self.load_saved_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
         else:
             print "Playlist not found"
-            
+
         # Downloads initialization
         if os.path.exists("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME")):
              self.load_downqueue_list("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME"))
-        
+
         # Status icon initialization
         self.staticon = guihelpers.GsharkIndicator(self)
 
         # Pynotify initialization
         if env().HAVE_NOTIFY:
             pynotify.init("gSharkDown")
-            self.pynotify_object = pynotify.Notification("dummy","dummy","dummy")
+            self.pynotify_object = pynotify.Notification("dummy", "dummy", "dummy")
 
         # Scrobbling initialization
         self.lastfm = None
                 self.check_for_updates()
 
         self.window.show_all()
-        
+
         self.on_playlist_row_changed(self.playlist.get_model())
         self.on_playlist_view_selection_changed(self.playlist.get_view())
         self.set_playing_song(None)
         groove.onInitStart(self.on_groove_init_start)
         groove.onInitFinish(self.on_groove_init_finish)
         groove.onInitError(self.on_groove_init_error)
-    
+
     def on_groove_init_start(self):
         self.window.set_title(_("gSharkDown - Initializing Grooveshark..."))
-        
+
     def on_groove_init_finish(self):
         self.window.set_title(_("gSharkDown"))
-        
+
     def on_groove_init_error(self, error):
         guihelpers.ErrorMessage(self.window,
             _(
         else:
             self.window.unfullscreen()
             menuitem.set_label("gtk-fullscreen")
-    
+
     def on_filter_entry_icon_press(self, entry, position, event):
         entry.set_text("")
-    
+
     def on_filter_changed(self, entry, data = None):
         self.result.set_filter_text(entry.get_text())
 
             clipboard = gtk.clipboard_get()
             clipboard.set_text(copystring)
             clipboard.store()
-    
+
     def on_playlist_row_changed(self, widget, path = None, iter = None):
         if len(self.playlist.get_model()) > 0:
             self.playlist_sw.show_all()
             self.playlist_sw.hide_all()
             self.button_playlist_clear.set_sensitive(False)
             self.button_save_playlist.set_sensitive(False)
-            
+
         if self.playlist.get_style() == PlayList.NOT_SHOW:
             self.playlist.set_style(PlayList.NOT_SHOW)
-            
+
         self.update_trackinfo()
-            
+
     def on_playlist_view_selection_changed(self, iconview):
         if len(self.playlist.get_selected_rows()) > 0:
             self.button_playlist_delete.set_sensitive(True)
         else:
             self.button_playlist_delete.set_sensitive(False)
-            
+
     def on_playlist_style_changed(self, widget, style):
         self.playlist.set_style(style)
-    
+
     def on_add_to_playlist(self, widget, data = None):
         """
         Adds selected item from the results to the playlist
 
     def get_playing_iter(self):
         return self.playlist.get_song_iter(self.get_playing_song())
-    
+
     def on_player_message(self, bus, message):
         if message.type == gst.MESSAGE_BUFFERING:
             if message.parse_buffering() >= 100:
                 self.is_buffering = True
         elif message.type == gst.MESSAGE_EOS:
             self.play_next()
-    
+
     def on_player_source_setup(self, player, pspec):
         source = self.player.get_property("source")
         proxy = env().get_proxy()
-        
+
         source.set_property("user-agent", env().USER_AGENT)
-        source.set_property("cookies", ["PHPSESSID="+groove.getSession()])
-        
+        source.set_property("cookies", ["PHPSESSID=" + groove.getSession()])
+
         if proxy != None:
             source.set_property("proxy", "http://" + proxy["host"] + ":" + proxy["port"])
             if proxy["user"] != None:
                 source.set_property("proxy-id", proxy["user"])
                 source.set_property("proxy-pw", proxy["pass"])
-        
+
     def on_player_idle(self):
         try:
             duration = self.player.query_duration(gst.FORMAT_TIME)[0] / gst.SECOND
             self.label_player_time.set_text("%s / %s" % (Song.format_time(cur), Song.format_time(duration)))
         except Exception, e:
             pass
-        
+
         return True
-    
+
     def on_seekbar_change_value(self, range, scroll, value):
         return True
-    
+
     def get_playing_song(self):
         return self.playlist.get_playing_song()
 
 
             self.staticon.change_status_playing()
             self.button_play.set_image(self.widget_image_buffering)
-            
+
             self.button_songinfo.set_sensitive(True)
             self.button_lyrics.set_sensitive(True)
             if env().have_pylast():
                 self.button_love.set_sensitive(True)
-            
+
             self.scrobbled = 0
 
             self.songinfo.set_markup(
             )
             if env().have_notify():
                 self.show_playing_song_notification()
-                
+
             if self.player_state_timeout_id == None:
                 self.player_state_timeout_id = gobject.timeout_add(500, self.on_player_idle)
 
         else:
             if self.play_thread != None:
                 self.play_thread.stop()
-                
+
             if self.player_state_timeout_id != None:
                 gobject.source_remove(self.player_state_timeout_id)
                 self.player_state_timeout_id = None
-                
+
             if env().have_notify():
                 self.pynotify_object.close()
 
             self.staticon.change_status_stopped()
             self.button_play.set_image(self.widget_image_play)
             self.songinfo.set_markup("")
-            
+
             self.button_songinfo.set_sensitive(False)
             self.button_lyrics.set_sensitive(False)
             self.button_love.set_sensitive(False)
                          glib.markup_escape_text(song.get_title())),
             "audio-x-generic")
         self.pynotify_object.show()
-    
+
     def play_first_song(self):
         if len(self.playlist) > 0:
             self.set_playing_song(self.playlist.get_song(0))
         Stop current playing
         """
         self.set_playing_song(None)
-        
+
     def update_trackinfo(self):
         if self.get_playing_song() == None:
             trackinfo_text = ngettext("%d track", "%d tracks", len(self.playlist)) % len(self.playlist)
         else:
             trackinfo_text = _("Track {0} of {1}").format(self.playlist.get_song_path(self.get_playing_song())[0] + 1,
                                                           len(self.playlist))
-            
+
         self.label_player_trackinfo.set_text(trackinfo_text)
 
     def on_volume_change(self, widget, data = 0.5):
         """
         dialog = guihelpers.PreferencesDialog(self)
         dialog.show_all()
-    
+
     def set_search_sensitivity(self, sens):
         self.vbox_results.set_sensitive(sens)
         self.hbox_filter.set_sensitive(sens)
         self.result.get_view().set_headers_visible(sens)
         self.result.get_view().get_column(1).set_visible(sens)
         self.result.get_view().get_column(2).set_visible(sens)
-    
+
     def on_search_grooveshark(self, widget, data = None):
         """
         Starts the search thread
             search_thread = SearchThread(self, widget.get_text(), "Songs")
             search_thread.start()
             self.on_show_playview(self.downloads_pane_label)
-            
+
     def on_search_text_changed(self, widget, data = None):
         t = GroovesharkInitThread()
         t.start()
-    
+
     def query_download_exists(self, filename):
         # Check on downloaded files
         if os.path.exists(filename) == True:
             return True
-        
+
         # Check on the downloads list
         for i in self.downloads.range():
             if filename == self.downloads.get_song(i).get_filename():
                 return True
-            
+
         return False
-    
+
     def get_overwritten_filename(self, filename, use_response = None):
         """
         Gets the file name depending on whether user want to overwrite the file,
                 builder = gtk.Builder()
                 builder.set_translation_domain(env().APP)
                 builder.add_from_file('%s/data/overwrite_dialog.ui' % env().BASEPATH)
-                
+
                 dialog = builder.get_object("dialog")
                 label = builder.get_object("label")
                 checkbox = builder.get_object("checkbutton")
-                
+
                 label.set_text(label.get_text() % filename)
-                
+
                 response = dialog.run()
-                
+
                 checkbox_active = checkbox.get_active()
                 dialog.destroy()
             else:
         else:
             response = 1
             checkbox_active = False
-            
+
         if checkbox_active == True:
             next_response = response
         else:
         select = self.result.get_selected_rows()
         for path in select:
             song = self.result.get_song(path)
-            
+
             if self.downloads.find_song(song) == None:
                 dialog_response = self.get_overwritten_filename(song.get_default_filename(), next_response)
-                
+
                 filename = dialog_response[0]
                 next_response = dialog_response[1]
-    
+
                 if filename != None:
                     song.set_filename(filename)
                     self.downloads.append_song_restarting(song)
         """
         if event.button == 3:
             path = treeview.get_path_at_pos(int(event.x), int(event.y))
-            
+
             if path != None:
                 selection = treeview.get_selection()
                 selected_rows = self.downloads.get_selected_rows()
-                
+
                 if not (path[0] in selected_rows):
                     selection.unselect_all()
                     selection.select_path(path[0])
-                
+
                 selected_rows = self.downloads.get_selected_rows()
                 self.downmenu.get_children()[0].set_sensitive(False)
                 self.downmenu.get_children()[1].set_sensitive(False)
                         self.downmenu.get_children()[1].set_sensitive(True)
                     else:
                         self.downmenu.get_children()[0].set_sensitive(True)
-                    
+
                 self.downmenu.popup(None, None, None, event.button, event.time)
-                
+
                 return True
 
     def on_cancel_all_downloads(self, widget, data = None):
 import gtk
 import gobject
 import threading
-import urllib2
 import pycurl
 import time
 import groove
-import re
 import math
 import covercache
-import sets
 
 class Song(gobject.GObject):
     """
     This class encasuplates a handle song information.
     """
-    
+
     """
     Song data example:
     {
     STATE_CANCELED = 5
     STATE_ERROR = 6
     last_song_local_id = 0
-    
+
     def __init__(self, data):
         """
         @param data: The array data given by GrooveShark. This array also can has a
         """
         self.__gobject_init__()
         Song.last_song_local_id += 1
-        
+
         self.local_id = Song.last_song_local_id
         self.data = data
         self.cover_pixbuf = None
         self.download_thread = None
         self.cover_thread = None
         self.last_error = None
-        
+
         try:
             self.filename = self.data["filename"]
         except KeyError:
             self.filename = self.get_default_filename()
-            
+
         self.connect("download-initializing", self.on_download_initializing)
         self.connect("download-started", self.on_download_started)
         self.connect("download-paused", self.on_download_paused)
         self.connect("download-canceled", self.on_download_canceled)
         self.connect("download-completed", self.on_download_completed)
         self.connect("download-error", self.on_download_error)
-    
+
     def on_download_initializing(self, song):
         print "[Download connecting]", self.get_id()
         self.state = Song.STATE_CONNECTING
-    
+
     def on_download_started(self, song):
         print "[Download started]", self.get_id()
         self.state = Song.STATE_DOWNLOADING
-    
+
     def on_download_paused(self, song):
         print "[Download paused]", self.get_id()
         self.state = Song.STATE_PAUSED
-        
+
     def on_download_canceled(self, song):
         print "[Download canceled]", self.get_id()
         self.state = Song.STATE_CANCELED
-        
+
     def on_download_completed(self, song):
         print "[Download completed]", self.get_id()
         self.state = Song.STATE_COMPLETED
-        
+
     def on_download_error(self, song, error):
         print "[Download error]", self.get_id(), error
         self.state = Song.STATE_ERROR
         self.last_error = error
-    
+
     def __getitem__(self, key):
         """
         Allows to use the song as a dictionary (not recommended, use
         methods instead)
         """
         return self.data[key]
-    
+
     def clone(self):
         """
         Clone the song but changes it local ID to avoid errors during the song searching
         if newsong.get_cover_pixbuf() == None:
             newsong.set_cover_pixbuf(self.get_cover_pixbuf())
         newsong.set_filename(self.get_filename())
-        
+
         return newsong
-    
+
     def equals(self, othersong):
         """
         Compare a song with another
         """
         if othersong == None:
             return False
-        
+
         return self.local_id == othersong.local_id
-    
+
     def get_data(self):
         return self.data
-    
+
     def get_state(self):
         return self.state
-    
+
     def set_state(self, state):
         self.state = state
-    
+
     def get_id(self):
         return self.data['SongID']
-        
+
     def get_title(self):
         return self.data['SongName']
-    
+
     def get_album(self):
         return self.data['AlbumName']
-        
+
     def get_artist(self):
         return self.data['ArtistName']
-        
+
     def get_track_num(self):
         return self.data['TrackNum']
-    
+
     def get_year(self):
         return self.data['Year']
-    
+
     def get_duration(self):
         return self.data['EstimateDuration']
-    
+
     @staticmethod
     def format_time(dur):
         duration = float(dur)
         mins = math.floor(duration / 60)
         secs = duration % 60
-        
+
         return "%02d:%02d" % (mins, secs)
-    
+
     def get_duration_human_readable(self):
         return Song.format_time(self.get_duration()) 
-    
+
     def get_last_error(self):
         return self.last_error
-    
+
     def get_cover_filename(self):
         return self.data['CoverArtFilename']
-    
+
     def get_cover_pixbuf(self):
         """
         Get the pixbuf for the song album cover.
             else:
                 self.set_cover_cached_pixbuf()
         return self.cover_pixbuf
-        
+
     def set_cover_pixbuf(self, pixbuf):
         """
         Set the pixbuf for the song album cover.
         Used by SongCoverThread and clone.
         """
         self.cover_pixbuf = pixbuf
-        
+
     def set_cover_missed_pixbuf(self):
         self.cover_pixbuf = covercache.get_missed_pixbuf()
-        
+
     def set_cover_cached_pixbuf(self):
         self.cover_pixbuf = covercache.get_pixbuf(self)
-        
+
     def download_cover(self):
         """
         Download the album cover, the object will emit the 'cover-downloaded'
         """
         self.cover_thread = SongCoverThread(self)
         self.cover_thread.start()
-        
+
     def cancel_cover_download(self):
         if self.cover_thread != None:
             self.cover_thread.canceled.set()
-        
+
     def start_download(self, restart = False, speed = None):
         """
         Starts the song download, the object will emit various signals to
         """
         if speed == None:
             speed = int(config()["speed_limit"]) * 1024
-        
+
         self.download_thread = DownloadThread(self)
         self.download_thread.restart = restart
         self.download_thread.speed = speed
         self.download_thread.start()
-        
+
     def is_downloading(self):
         """
         Returns true if the download is running
         """
         return self.download_thread != None and self.download_thread.is_alive()
-    
+
     def is_paused(self):
         """
         Returns true if the download was stopped by pausing it
         """
         return self.download_thread != None and self.is_downloading() == False and self.download_thread.is_canceled == False
-        
+
     def pause_download(self):
         """
         Pause the current download
         else:
             self.state = Song.STATE_PAUSED
             self.emit("download-paused")
-        
+
     def cancel_download(self):
         """
         Cancel the current download
             if self.state != Song.STATE_COMPLETED and os.path.exists(self.get_filename()):
                 os.remove(self.get_filename())
             self.emit("download-canceled")
-            
+
     def resume_download(self):
         """
         Resume the file download, the only difference with start_download is that
         """
         if self.is_downloading() == False and self.state != Song.STATE_COMPLETED:
             self.start_download(False)
-    
+
     def reset_unfinished_download_state(self):
         if self.is_downloading() == False and self.state != Song.STATE_COMPLETED:
             self.set_state(Song.STATE_NOT_STARTED)
-        
+
     def pause_download_sync(self):
         """
         Pause the current download and wait until it stops altogether.
         if self.is_downloading():
             self.download_thread.pause()
             self.download_thread.join()
-            
+
     def get_download_progress(self):
         """
         Returns the current download progress in bytes or None if
             return self.download_thread.file_size
         else:
             return None
-    
+
     def get_download_speed(self):
         """
         Returns the current download speed in bytes per second
             return self.download_thread.download_speed
         else:
             return None
-    
+
     def get_filename(self):
         return self.filename
-    
+
     def set_filename(self, value):
         self.filename = value
-        
+
     def get_default_filename(self):
         pattern = config()['file_pattern'] + ".mp3"
         filename = pattern.format(artist = self.get_artist().strip("<>:\"/\|?&*"),
                                   album = self.get_album().strip("<>:\"/\|?&*"))
         filename = filename.replace('/', '-')
         filename = os.path.join(config()['down_path'], filename)
-        
+
         return filename
-    
+
     def get_streaming_url(self):
         try:
             key = groove.getStreamKeyFromSongIDEx(self.get_id())
         except Exception as e:
             print "[Streaming URL error]", e.__str__()
             raise e
-        
+
         print "[Key for song streaming", self.get_id(), "]", key
         playurls = "http://%s/stream.php?streamKey=%s"
         play_url = playurls % (key["result"]["%s" % self.get_id()]["ip"],
                                key["result"]["%s" % self.get_id()]["streamKey"])
-        
+
         return str(play_url)
 
 gobject.type_register(Song)
     This class download a song cover album and notify
     it when download ends. Should not be used directly, use Song instead.
     """
-    
+
     concurrent_downloads = threading.Semaphore(5)
     internal_lock = threading.Semaphore()
     cancel_downloads = threading.Event()
     downloading_events = {}
-    
+
     def __init__(self, song):
         threading.Thread.__init__(self)
         self.song = song
         else:
             SongCoverThread.downloading_events[self.song.get_cover_filename()] = threading.Event()
             SongCoverThread.internal_lock.release()
-        
+
         groove.init()
         SongCoverThread.concurrent_downloads.acquire()
-        
+
         if SongCoverThread.cancel_downloads.is_set() or self.canceled.is_set():
             SongCoverThread.concurrent_downloads.release()
             return
-            
+
         try:
             url = "http://images.grooveshark.com/static/albums/90_%s" % self.song.get_cover_filename()
             print "[Downloading cover]", url
-            
+
             conn = groove.createCurl(str(url))
             conn.set_timeout(10)
-            
+
             try:
                 os.makedirs(os.path.dirname(covercache.get_filename(self.song)))
             except:
                 pass
             file = open(covercache.get_filename(self.song)+".incoming", "wb")
             conn.setopt(pycurl.WRITEDATA, file)
-            
+
             loader = gtk.gdk.PixbufLoader()
             loader.write(conn.perform())
             loader.close()
-            
+
             conn.close()
             file.close()
             os.rename(covercache.get_filename(self.song)+".incoming", covercache.get_filename(self.song))
-            
+
             self.song.cover_pixbuf = loader.get_pixbuf()
         except Exception, e:
             print "Error while downloading cover: ", e
                 os.remove(covercache.get_filename(self.song)+".incoming")
             except:
                 pass
-        
+
         SongCoverThread.concurrent_downloads.release()
-        
+
         SongCoverThread.downloading_events[self.song.get_cover_filename()].set()
         del SongCoverThread.downloading_events[self.song.get_cover_filename()]
         gobject.idle_add( self.song.emit, "cover-downloaded" )
-        
+
 
 class DownloadThread(threading.Thread):
     """
     This class download the song file and notify the progress.
     Should not be used directly, use Song instead.
     """
-    
+
     def __init__(self, song):
         threading.Thread.__init__(self)
 
         self.restart = False
         self.speed = 0
         self.download_progress = None
-        
+
         self.download_speed = None
         self.download_time_start = None
         self.download_size_on_start = None
-        
+
         self.file_size = None
         self.resume_downloaded = 0
-        
+
         self.first_hook = True
         self._stop = threading.Event()
         self.is_canceled = True
 
     def run(self):
         self.song.emit("download-initializing")
-        
+
         self.first_hook = True
         self._stop.clear()
         restart = self.restart
-        
+
         if restart == False and os.path.exists(self.song.get_filename()) == False:
             restart = True
-        
+
         try:
             if restart == True:
                 self.file = open(self.song.get_filename(), "wb")
         except IOError:
             self.song.emit("download-error", _("Failed to create '%s' for writing.") % self.song.get_filename())
             return
-        
+
         try:
             url = self.song.get_streaming_url()
             c = groove.createCurl(url)
                 self.resume_downloaded = 0
             if self.speed != 0:
                 c.setopt(pycurl.MAX_RECV_SPEED_LARGE, self.speed)
-            
+
             c.perform()
             c.close()
-            
+
             self.file.close()
             self.download_progress = 100
             self.song.emit("download-completed")
             os.remove(self.song.get_filename())
             self.song.emit("download-error", e.__str__())
             return
-            
+
         self.song.emit("download-stopped")
-    
+
     def cancel(self):
         self.is_canceled = True
         self._stop.set()
-        
+
     def pause(self):
         self.is_canceled = False
         self._stop.set()
-    
+
     def stopped(self):
         return self._stop.isSet()
-    
+
     def on_header(self, c):
         # If is not partial content (partial content is status code 206)
         if c.get_status() == 200:
             self.file.truncate(0)
-    
+
     def hook(self, downloadTotal, downloadCurrent, uploadTotal, uploadCurrent):
         if self.stopped():
             return True
-        
+
         if downloadTotal > 0:
             if self.first_hook:
                 self.first_hook = False
                 self.song.emit("download-started")
-            
+
             downloadTotal += self.resume_downloaded
             downloadCurrent += self.resume_downloaded
-            
+
             progress = (downloadCurrent / downloadTotal) * 100
             self.download_progress = progress
             self.file_size = downloadTotal
-            
+
             current_time = time.time()
             if current_time - self.download_time_start > 1:
                 self.download_speed = downloadCurrent - self.resume_downloaded - self.download_size_on_start
         else:
             self.download_time_start = time.time()
             self.download_size_on_start = 0
-        
+
         return False
-    

lib/covercache.py

 
 def get_pixbuf(song):
     global _mem_cache
-    
+
     fname = get_filename(song)
     if fname in _mem_cache:
-        return _mem_cache[fname] 
-    
+        return _mem_cache[fname]
+
     if os.path.exists(fname):
         with file(fname, 'a'):
             os.utime(fname, None)
     filelist_full = []
     totalsize = 0
     limitsize = int(config()["cover_cache_limit"])
-    
+
     for f in filelist:
         fname = os.path.join(env().get_config_directory(), "covers", f)
         fstat = os.stat(fname)
-        
+
         filelist_full.append((fname, fstat.st_atime, fstat.st_size))
         totalsize += fstat.st_size
-    
+
     if totalsize > limitsize:
-        filelist_full = sorted(filelist_full, key=lambda file: file[1])
+        filelist_full = sorted(filelist_full, key = lambda file: file[1])
         i = 0
         while totalsize > limitsize:
             file = filelist_full[i]

lib/enviroment.py

 
         # Directory for i18n files
         self.LOCALE_DIR = None
-        
+
         # User agent for HTTP requests
         self.USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/10.0"
 
 
         # The config object
         self._config = None
-        
+
         # The proxy data
         self._proxy = None
 
 
     def set_config(self, config):
         self._config = config
-    
+
     def get_config_directory(self):
         return "%s/.gsharkdown" % os.environ.get("HOME")
-    
+
     def get_config_filename(self):
         """
         Returns the filename for the configuration file
             'proxy_pass': '',
             'cover_cache_limit': 16 * 1024 * 1024,
         }
-        
+
     def _safe_create_dirs(self, dirs):
         if os.path.isdir(dirs) == False:
             try:
         user_config = ConfigObj(self.get_config_filename())
 
         config.merge(user_config)
-        
+
         self._safe_create_dirs(self.get_config_directory())
         self._safe_create_dirs(config['down_path'])
         self._safe_create_dirs(os.path.join(self.get_config_directory(), "covers"))
-        
+
         config.write()
         self.set_config(config)
-        
+
         # Initialize proxy
         # To avoid requests problems with Grooveshark, the proxy is initialized
         # one time and user needs to restart gSharkDown in order to use a new
         # proxy. This should be fixed!
         self.refresh_proxy()
-        
+
     def have_notify(self):
         return int(config()['show_notification']) == 1 and env().HAVE_NOTIFY
-    
+
     def have_pylast(self):
         return int(config()['scrobbling']) == 1 and env().HAVE_PYLAST
-    
+
     def have_playlist_style(self):
         v = gtk.pygtk_version
         return v[0] >= 2 and v[1] >= 22
-    
+
     def refresh_proxy(self):
         if config()["proxy_enabled"] == "auto":
             self._proxy = self.get_system_proxy()
                     self._proxy["pass"] = config()["proxy_pass"]
         else:
             self._proxy = None
-            
+
     def get_system_proxy(self):
         if os.environ.has_key("http_proxy") and os.environ["http_proxy"] != "":
-            proxy_url = "http://"+os.environ["http_proxy"]
+            proxy_url = "http://" + os.environ["http_proxy"]
         else:
             proxy_factory = libproxy.ProxyFactory()
             proxy_url = proxy_factory.getProxies("http://grooveshark.com")[0]
-        
+
         if proxy_url == "direct://":
             proxy = None
         else:
             proxy_url = proxy_url.replace("http://", "")
             if proxy_url.find(":") == -1:
                 proxy_url += ":8080"
-                
+
             proxy = {}
             proxy["host"] = proxy_url.split(":")[0]
             proxy["port"] = proxy_url.split(":")[1]
             proxy["user"] = None
             proxy["pass"] = None
-            
+
         return proxy
-    
+
     def get_proxy(self):
         return self._proxy
 
 
 if sys.version_info[1] >= 6:
     import json
-    
+
 def dummy(error = None):
     pass
 
     c = ipycurl.Curl(url)
     c.setopt(pycurl.USERAGENT, env().USER_AGENT)
     c.set_option(pycurl.FAILONERROR, True)
-    
+
     c.setopt(pycurl.COOKIEFILE, env().get_config_directory() + "/cookie.txt")
     c.setopt(pycurl.COOKIEJAR, env().get_config_directory() + "/cookie.txt")
     c.set_timeout(50)
-    
+
     proxy = env().get_proxy()
     if proxy != None:
         c.setopt(pycurl.PROXY, proxy["host"])
             c.setopt(pycurl.PROXYUSERPWD, proxy["user"] + ":" + proxy["pass"])
     else:
         c.setopt(pycurl.PROXY, "")
-        
+
     return c
 
 def prepToken(method, sectoken):
     p["header"] = h
     p["header"]["client"] = "htmlshark"
     p["header"]["clientRevision"] = "20110906"
-    
+
     conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
     conn.setopt(pycurl.POST, True)
     conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
     conn.setopt(pycurl.HTTPHEADER, [
-        "Referer: "+_referer,
+        "Referer: " + _referer,
         "Accept-Encoding: gzip",
         "Content-Type: application/json"
     ])
     resp = conn.perform()
     conn.close()
-    
+
     gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
     _token = json.JSONDecoder().decode(gzipfile.read())["result"]
 
     and returns them as dictionary.
     """
     init()
-    
+
     p = {}
     p["parameters"] = {}
     p["parameters"]["type"] = _type
     p["header"]["clientRevision"] = "20110906"
     p["header"]["token"] = prepToken("getResultsFromSearch", ":imOnAHorse:")
     p["method"] = "getResultsFromSearch"
-    
+
     conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
     conn.setopt(pycurl.POST, True)
     conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
     ])
     resp = conn.perform()
     conn.close()
-    
+
     gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
     j = json.JSONDecoder().decode(gzipfile.read())
-    result =  j['result']['result']
+    result = j['result']['result']
     if hasattr(result, 'Songs'):
         return result['Songs']
     else:
     Gets the stream URL for Song ID
     """
     init()
-    
+
     p = {}
     p["parameters"] = {}
     p["parameters"]["mobile"] = "false"
     p["header"]["clientRevision"] = "20110906"
     p["header"]["token"] = prepToken("getStreamKeysFromSongIDs", ":theTicketsAreNowDiamonds:")
     p["method"] = "getStreamKeysFromSongIDs"
-    
+
     conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
     conn.setopt(pycurl.POST, True)
     conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
     ])
     resp = conn.perform()
     conn.close()
-    
+
     gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
     j = json.JSONDecoder().decode(gzipfile.read())
-    
+
     if len(j["result"][str(_id)]) == 0:
         raise Exception("The song streaming key is empty")
-    
+
     return j
 
 
 def init():
     global _isInitialized, _initFailed
-    
+
     _initializingLock.acquire()
     if isInitialized():
         _initializingLock.release()
         if _initFailed == True:
             raise Exception(_("Grooveshark is not initialized"))
         return
-    
+
     print "[Initializing Grooveshark]"
-    gobject.idle_add( _onInitStart )
+    gobject.idle_add(_onInitStart)
     while True:
         try:
             conn = createCurl("http://grooveshark.com/")
             conn.perform()
-            
+
             cookielist = conn.get_info(pycurl.INFO_COOKIELIST)
             for cookie in cookielist:
                 cookie = cookie.split("\t")
                 if cookie[5] == "PHPSESSID":
                     h["session"] = cookie[6]
-            
+
             conn.close()
             getToken()
             print "[Grooveshark initialized]"
                 _initFailed = True
                 gobject.idle_add(_onInitError, e.__str__())
                 break
-    
+
     _isInitialized = True
     _initializingLock.release()
-    gobject.idle_add( _onInitFinish )
-    
+    gobject.idle_add(_onInitFinish)
+
     if _initFailed == True:
         raise Exception(_("Grooveshark is not initialized"))
-    
+
 def onInitError(callback):
     global _onInitError
     _onInitError = callback
-    
+
 def onInitStart(callback):
     global _onInitStart
     _onInitStart = callback
-    
+
 def onInitFinish(callback):
     global _onInitFinish
     _onInitFinish = callback
-    
+
 def isInitialized():
     return _isInitialized
 

lib/guihelpers.py

             self.bubble.set_active(int(config()['show_notification']))
         else:
             self.bubble.set_sensitive(False)
-        
+
         self.form_lastfm = builder.get_object("table_lastfm")
         self.lastuser = builder.get_object("entry_lastuser")
         self.lastuser.set_text(config()['lastuser'])
 
         self.form_lastfm.set_sensitive(self.scrobble.get_active())
         builder.connect_signals(self)
-        
-        
+
+
         self.group_custom_proxy = builder.get_object("group_custom_proxy")
         self.radio_proxy_0 = builder.get_object("radio_proxy_0")
         self.radio_proxy_1 = builder.get_object("radio_proxy_1")
         self.entry_proxy_port = builder.get_object("entry_proxy_port")
         self.entry_proxy_user = builder.get_object("entry_proxy_user")
         self.entry_proxy_pass = builder.get_object("entry_proxy_pass")
-        
+
         if config()["proxy_enabled"] == "0":
             self.radio_proxy_0.set_active(True)
         elif config()["proxy_enabled"] == "1":
             self.radio_proxy_1.set_active(True)
         else:
             self.radio_proxy_auto.set_active(True)
-        
+
         self.entry_proxy_host.set_text(config()["proxy_host"])
         self.entry_proxy_port.set_text(config()["proxy_port"])
         if config()["proxy_port"] == "":
             self.entry_proxy_port.set_text("8080")
         self.entry_proxy_user.set_text(config()["proxy_user"])
         self.entry_proxy_pass.set_text(config()["proxy_pass"])
-        
+
         label_proxy_info = builder.get_object("label_proxy_info")
         system_proxy = env().get_system_proxy()
         if system_proxy == None:
             proxy_string = ""
             if system_proxy["user"] != None:
                 proxy_string += system_proxy["user"] + "@"
-            proxy_string += system_proxy["host"] + ":" + system_proxy["port"] 
+            proxy_string += system_proxy["host"] + ":" + system_proxy["port"]
             label_proxy_info.set_label(_("The system proxy is: %s") % proxy_string)
 
     def show_all(self):
 
     def on_scrobble_toggle(self, widget, data = None):
         self.form_lastfm.set_sensitive(widget.get_active())
-            
+
     def on_proxy_radio_changed(self, widget):
         self.group_custom_proxy.set_sensitive(self.radio_proxy_1.get_active())
 
         config()['file_pattern'] = self.file_pattern.get_text()
         config()['speed_limit'] = self.speed.get_value_as_int()
         config()['cover_cache_limit'] = int(self.edit_cover_cache_limit.get_value() * 1024 * 1024)
-        
+
         if self.radio_proxy_0.get_active():
             config()["proxy_enabled"] = "0"
         elif self.radio_proxy_1.get_active():
             config()["proxy_enabled"] = "1"
         else:
             config()["proxy_enabled"] = "auto"
-            
+
         config()["proxy_host"] = self.entry_proxy_host.get_text()
         config()["proxy_port"] = self.entry_proxy_port.get_text()
         config()["proxy_user"] = self.entry_proxy_user.get_text()
         self.app = app
         self.menu = gtk.Menu()
         self.program_changing_show_window = False
-        
+
         self.show_window = gtk.CheckMenuItem(_("Show gSharkDown"))
         self.show_window.connect("toggled", self.on_statusicon_clicked)
-        
+
         about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
         about.connect("activate", self.app.on_show_about)
         prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
         updbut.connect("activate", self.app.on_check_for_updates)
         quiter = gtk.ImageMenuItem(gtk.STOCK_QUIT)
         quiter.connect("activate", self.app.on_quit_app)
-        
+
         self.menu.append(self.show_window)
         self.menu.append(gtk.SeparatorMenuItem())
         self.menu.append(prebut)
         self.menu.append(updbut)
         self.menu.append(about)
         self.menu.append(quiter)
-        
+
         if env().HAVE_INDICATOR == True:
             self.ind = appindicator.Indicator("gsharkdown-client",
                                    "gsharkdown_indicator",
             self.staticon.connect("popup-menu", self.right_click_event)
             self.staticon.connect("activate", self.on_statusicon_clicked)
             self.staticon.set_tooltip(_("gSharkDown"))
-            
+
         app.window.connect("hide", self.on_window_state_changed)
         app.window.connect("show", self.on_window_state_changed)
 
                 self.app.window.hide()
             else:
                 self.app.window.present()
-    
+
     def on_window_state_changed(self, widget):
         self.program_changing_show_window = True
-        self.show_window.set_active( self.app.window.get_visible() )
+        self.show_window.set_active(self.app.window.get_visible())
         self.program_changing_show_window = False
 
     def change_status_playing(self):
             self.ind.set_status(appindicator.STATUS_ATTENTION)
         else:
             self.staticon.set_from_file("%s/data/gsharkdown_16_playing.png" % env().BASEPATH)
-        
+
         self.__change_playbutton_content(gtk.STOCK_MEDIA_STOP, _("Stop"))
 
     def change_status_stopped(self):
             self.ind.set_status(appindicator.STATUS_ACTIVE)
         else:
             self.staticon.set_from_file("%s/data/gsharkdown_16.png" % env().BASEPATH)
-            
+
         self.__change_playbutton_content(gtk.STOCK_MEDIA_PLAY, _("Play"))
-        
+
     def __change_playbutton_content(self, icon_id, label):
         image = gtk.Image()
         image.set_from_stock(icon_id, gtk.ICON_SIZE_MENU)
         self.playbut.set_image(image)
         self.playbut.set_label(label)
-        
+
 class Curl(gobject.GObject):
     def __init__(self, url = None):
         self.__gobject_init__()
-        
+
         self.handle = pycurl.Curl()
         self._header_string = None
         self._headers = None
         self.user_header_callback = None
         self.user_write_callback = None
         self.writedata_option = None
-        
+
         self.set_url(url)
         # Verify that we've got the right site; harmless on a non-SSL connect.
         self.set_option(pycurl.SSL_VERIFYHOST, 2)
         # Setting this option with even a nonexistent file makes libcurl
         # handle cookie capture and playback automatically.
         self.set_option(pycurl.COOKIEFILE, "/dev/null")
-        
+
         self.handle.setopt(pycurl.HEADERFUNCTION, self._default_header_callback)
         self.handle.setopt(pycurl.WRITEFUNCTION, self._default_write_callback)
-    
+
     def _default_header_callback(self, d):
         self._header_string += d
-        
+
         if d == "\r\n":
             self.emit("header-downloaded")
-        
+
         if self.user_header_callback != None:
             return self.user_header_callback(d)
-        
+
     def _default_write_callback(self, d):
         if self._return_transfer == True:
             self._content += d
-            
+
         if self.writedata_option != None:
             self.writedata_option.write(d)
-        
+
         if self.user_write_callback != None:
             return self.user_write_callback(d)
-        
+
     def get_header_string(self):
         return self._header_string
-    
+
     def get_headers(self):
         if self._headers == None:
             data = self._header_string.split("\r\n")
             matches = re.match(r"HTTP/\d\.\d (\d+)", data[0])
             if matches:
                 self._status = int(matches.group(1))
-            
+
             del data[0]
             self._headers = {}
             for httpfield in data:
                     httpkey = httpfield[0].lower().strip()
                     httpvalue = httpfield[1].strip()
                     self._headers[httpkey] = httpvalue
-            
+
         return self._headers
-    
+
     def get_status(self):
         self.get_headers()
         return self._status
-    
+
     def set_timeout(self, timeout):
         "Set timeout for a retrieving an object"
         self.set_option(pycurl.TIMEOUT, timeout)
             self.writedata_option = value
         else:
             self.handle.setopt(option, value)
-        
+
     def setopt(self, option, value):
         "Set an option on the retrieval."
         self.set_option(option, value)
-        
+
     def get_info(self, *args):
         "Get information about retrieval."
         return apply(self.handle.getinfo, args)
-    
+
     def getinfo(self, *args):
         "Get information about retrieval."
         return apply(self.handle.getinfo, args)
-    
+
     def set_return_transfer(self, enable):
         self._return_transfer = bool(enable)
-        
+
     def get_return_transfer(self):
         return self._return_transfer
-    
+
     def perform(self):
         if self._return_transfer == True: