Source

gSharkDown / lib / SharkDown.py

The refactoring branch has multiple heads

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
from enviroment import env, config
import os
import sys
import random
from tfuncs import InitThread
from tfuncs import PlayThread
from tfuncs import SearchThread
from tfuncs import KeyListenerThread
from tfuncs import LyricsThread
from tfuncs import UpdateThread
from SearchResultList import SearchResultList
from PlayList import PlayList
from DownloadList import DownloadList
from Song import Song
import guihelpers
import pickle
import gtk
import gst
import glib
import gobject
import locale
import gettext
from gettext import gettext as _

try:
    import pynotify
except:
    pass

try:
    import pylast
except:
    pass

class SharkDown:
    """
    The main application class for gSharkDown
    """

    def __init__(self):
        """
        Initialise the main application window
        """
        gobject.threads_init()
        
        self.working = None
        self.playing = None
        # just to prevend scrobbeling more then once for 
        # track.
        self.scrobbled = 0
        # Download dictionary in form Filename : Thread
        self.last_iter = None
        self.windowstate = 1
        self.current_song = None
        self.play_thread = None
        
        init_thread = InitThread(self)
        init_thread.start()
        
        # Main window initialization
        builder = gtk.Builder()
        builder.set_translation_domain(env().APP)
        builder.add_from_file('%s/data/main_window.ui' % env().BASEPATH)
        self.window = builder.get_object('mainwindow')
        self.window.connect('delete-event', self.on_window_close)
        self.play_button = builder.get_object('toolbutton_play')
        self.ff_button = builder.get_object('toolbutton_play_next')
        self.prev_button = builder.get_object('toolbutton_play_previous')
        self.lyrics_button = builder.get_object('toolbutton_lyrics')
        self.songinfo = builder.get_object('songinfo')
        self.songinfo.set_text("")
        self.prefsmenu = builder.get_object('mainmenu')
        self.lovebutton = builder.get_object('toolbutton3')
        repeat_button = builder.get_object('togglebutton_repeat')
        repeat_button.set_active(int(config()['repeat_playlist']))
        shuffle_button = builder.get_object('togglebutton_shuffle')
        shuffle_button.set_active(int(config()['shuffle_playlist']))
        self.player = gst.element_factory_make("playbin", "player")

        # Completition configuration
        self.entry = builder.get_object('toolentry_search')
        completition = gtk.EntryCompletion()
        comp_store = gtk.ListStore(str)
        completition.set_model(comp_store)
        for item in config()['completition'].split("|"):
            comp_store.append([item])
        completition.set_minimum_key_length(1)
        completition.set_text_column(0)
        self.entry.set_completion(completition)

        # Results List definition
        self.result = SearchResultList(builder.get_object('list_results'))
        self.result.get_view().connect("row-activated", self.on_result_row_activated)

        # Play List definition
        self.sw2 = builder.get_object('scrolledwindow2')
        self.playlist = PlayList(gtk.IconView())
        self.playlist.get_view().connect('item-activated', self.on_playlist_double_click)
        self.playlist.get_view().show()
        self.sw2.add(self.playlist.get_view())

        # Download list definition
        self.downloads = DownloadList(builder.get_object('list_downloads'))
        self.downloads.get_view().hide_all()
        
        # Downloads related initialization
        self.downloads_count = builder.get_object('downloads_count')
        self.downloads_expander = builder.get_object('expander_download')
        self.update_downloads_count()
        self.downmenu = builder.get_object('downloadmenu')
        
        # Song lists initialization
        if os.path.exists("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME")):
            self.load_saved_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
        else:
            print "Playlist not found"
            
        self.staticon = guihelpers.GsharkIndicator(self)
        
        # Set default directory if is empty
        if config()['down_path'] == "":
            config()['down_path'] = env().get_default_down_path()

        # Pynotify initialization
        if int(config()['show_notification']) == 1 and env().HAVE_NOTIFY:
            pynotify.init("gSharkDown")
            
        # Scrobbling initialization
        self.lastfm = ""
        if int(config()['scrobbling']) == 1 and env().HAVE_PYLAST:
            try:
                self.lastfm = pylast.LastFMNetwork(api_key = env().LASTFM_KEY,
                                          api_secret = env().LASTFM_SECRET,
                                          username = config()['lastuser'],
                                          password_hash = config()['lastpass'])
                self.lovebutton.set_sensitive(True)
            except pylast.WSError:
                error = guihelpers.ErrorMessage(self.window,
                            _("Check your password and username for Last.fm"))
                error.show_all()
                pass

        builder.connect_signals(self)
        self.tlisten = KeyListenerThread(self)
        self.tlisten.start()
        
        # Updates checking
        if config()['update_checked'] == 0:
            self.check_for_updates()
        else:
            if config()['startup_update_check'] == 1:
                self.check_for_updates()
        
        self.window.set_sensitive(False)
        self.window.show_all()
 
        
    def on_init_thread_end(self):
        self.window.set_sensitive(True)
        self.entry.set_text("metallica")
        self.on_search_grooveshark(self.entry)
        if os.path.exists("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME")):
            self.load_downqueue_list("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME"))


    def get_iter_last(self, model):
        """
        Get the last iter from a model
        """
        rows = model.iter_n_children(None);
        return model.get_iter([rows - 1]);

    def result_song(self, index):
        return self.result.get_song(index)

    def playlist_song(self, index):
        return self.playlist.get_song(index)

    def show_prefs_menu(self, button, data = None):
        self.prefsmenu.popup(None, None, None, 0, 0)

    def load_saved_playlist(self, path):
        """
        Loads the saved playlist from .pkl file
        """
        file = open(path, 'rb')
        eoferror = True

        while eoferror:
            try:
                song = Song(pickle.load(file))
                self.playlist.append_song(song)
            except:
                eoferror = False
                
        file.close()
                
    def save_playlist(self, path):
        """
        Saves the playlist from the playlist treeview to 
        /home/$USER/.gsharkdown/playlist.pkl
        """
        try:
            output = open(path, 'w')
            for i in self.playlist.range():
                pickle.dump(self.playlist.get_song(i).get_data(), output)
            output.close()
        except:
            error = guihelpers.ErrorMessage(None,
                            _("Error while saving the playlist"))
            error.show_all()

    def load_downqueue_list(self, path):
        """
        Loads the saved playlist from the .pkl file
        """
        file = open(path, 'rb')
        eoferror = True

        while eoferror:
            try:
                song = Song(pickle.load(file))
                self.downloads.append_song(song)
            except:
                eoferror = False
                
        file.close()

    def save_downqueue(self, path):
        """
        Saves the download queue to pickle file in
        /home/$USER/.gsharkdown/downqueue.pkl
        """
        try:
            output = open(path, 'w')
            for i in self.downloads.range():
                song = self.downloads.get_song(i)
                if song.get_download_progress() < 100:
                    data = self.downloads.get_song(i).get_data()
                    data["filename"] = self.downloads.get_song(i).get_filename()
                    pickle.dump(data, output, -1)
            output.close()
        except Exception, e:
            error = guihelpers.ErrorMessage(None,
                            _("Error while saving the download queue"))
            error.show_all()


    def on_playlist_save_as(self, widget, data = None):
        """
        Saves the playlist to .pkl file in directory
        choosen from the user
        """
        savedlg = gtk.FileChooserDialog(_("Save playlist to file"),
                                       None,
                                       gtk.FILE_CHOOSER_ACTION_SAVE,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        response = savedlg.run()

        if response == gtk.RESPONSE_OK:
            filename = savedlg.get_filename()
            if filename[-4:] != ".pkl":
                filename += ".pkl"
            self.save_playlist(filename)
        savedlg.destroy()

    def on_playlist_open(self, widget, data = None):
        """
        Opens a usersaved playlist from .pkl file
        """
        opendlg = gtk.FileChooserDialog(_("Select Playlist to open"),
                                       None,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        openfilter = gtk.FileFilter()
        openfilter.set_name(_('Playlist files'))
        openfilter.add_pattern("*.pkl")

        opendlg.add_filter(openfilter)

        response = opendlg.run()

        if response == gtk.RESPONSE_OK:
            self.playlist.clear()
            self.stop_play()
            self.load_saved_playlist(opendlg.get_filename())
            self.play_first_song()
        opendlg.destroy()

    def on_window_close(self, widget, data = None):
        """
        Closes the main window
        """
        self.window.hide_on_delete()
        self.windowstate = 0
        return True
    
    def check_for_updates(self):
        """
        Checks if a new version of the application is available
        on the application website. NEVER change the VERSION file
        manually!
        """
        t = UpdateThread()
        t.start()
    
    def on_check_for_updates(self, widget, data = None):
        self.check_for_updates()

    def on_statusicon_clicked(self, widget, data = None):
        """
        Executed on left clicking the statusicon
        """
        if(self.windowstate == 0):
            self.window.show_all()
            self.windowstate = 1
        else:
            self.window.hide_on_delete()
            self.windowstate = 0
            return True

    def on_quit_app(self, widget, data = None):
        """
        Confirmation dialog when exiting the application
        """
        if config()['quit_without_confirmation'] == '0':
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                  type = gtk.MESSAGE_QUESTION,
                                  buttons = gtk.BUTTONS_YES_NO,
                                  message_format = _("Are you sure you want to quit gSharkDown?"))
            dialog.set_title(_("Quit?"))
            response = dialog.run()
            dialog.destroy()
        else:
            response = gtk.RESPONSE_YES

        if response == gtk.RESPONSE_YES:
            self.save_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
            self.save_downqueue("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME"))
            self.downloads.stop_all_downloads()
            gtk.main_quit()

    def on_copy_song(self, widget, data = None):
        """
        Copy the selected song name from the results list in the
        GNOME Clipboard
        """
        select = self.result_view.get_selection().get_selected_rows()
        if self.result_view.get_selection().count_selected_rows() > 0:
            song = self.result_song(select[1][0])
            copystring = "%s - %s" % (song['ArtistName'], song['SongName'])
            clipboard = gtk.clipboard_get()
            clipboard.set_text(copystring)
            clipboard.store()

    def on_add_to_playlist(self, widget, data = None):
        """
        Adds selected item from the results to the playlist
        """
        select = self.result.get_view().get_selection().get_selected_rows()
        for item in select[1]:
            song = self.result.get_song(item[0])
            self.playlist.append_song(song)

    def on_remove_from_playlist(self, widget, data = None):
        """
        Removes an item from the playlist and the playitems list
        """
        selection = self.playlist.get_selected_rows()
        if len(selection) > 0:
            for i in selection:
                self.playlist.get_model().remove( self.playlist.get_model().get_iter(i) )
                
            if len(self.playlist) > 0:
                select_path = selection[len(selection) - 1]
                if select_path[0] >= len(self.playlist):
                    select_path = (select_path[0]-1,)
                self.playlist.get_view().select_path(select_path)
                
            if self.get_playing_iter() == None:
                self.stop_play()

    def on_clear_playlist(self, widget, data = None):
        """
        Removes all items from the playlist
        """
        self.stop_play()
        self.playlist.clear()

    def on_toggle_repeat(self, widget, data = None):
        """
        Toggles the configuration option for looping trough the
        playlist
        """
        config()['repeat_playlist'] = int(widget.get_active())
        config().write()

    def on_toggle_shuffle(self, widget, data = None):
        """
        Toggle the configuration option for shuffleing the playlist
        """
        config()['shuffle_playlist'] = int(widget.get_active())
        config().write()

    def on_playlist_double_click(self, widget, path, data = None):
        """
        Starts playling on double click event on the playlist
        treeview.
        """
        self.playlist.get_view().unselect_all()
        self.set_playing_song(self.playlist.get_song(path))

    def on_result_row_activated(self, path, column, data = None):
        """
        On double click in the search treeview the item is added to 
        the playlist and starts playling.
        """
        song = self.result.get_song(column[0])
        self.playlist.append_song(song)
            
    def get_playing_iter(self):
        return self.playlist.get_song_iter(self.get_playing_song())
    
    def get_playing_song(self):
        return self.playlist.get_playing_song()
        
    def set_playing_song(self, song):
        """
        Updates some labels and icons when a song is playing
        """
        self.playlist.set_playing_song(song)
        
        if song != None:
            self.staticon.change_status_playing()
            
            play_stop_image = gtk.Image()
            play_stop_image.set_from_stock(gtk.STOCK_MEDIA_STOP, gtk.ICON_SIZE_MENU)
            self.staticon.change_playbutton(play_stop_image)
            self.play_button.set_stock_id(gtk.STOCK_MEDIA_STOP)

            self.songinfo.set_markup(
                _("<b>Playing:</b> {artist} - {title}").format(artist = glib.markup_escape_text(song.get_artist()),
                                         title = glib.markup_escape_text(song.get_title()))
            )
            if int(config()['show_notification']) == 1:
                n = pynotify.Notification(_("Now playing"),
                    "%s - %s" % (glib.markup_escape_text(song.get_artist()),
                                 glib.markup_escape_text(song.get_title())),
                    "audio-x-generic")
                n.set_timeout(50)
                n.show()
                
            self.player.set_state(gst.STATE_NULL)
            
            if self.play_thread != None:
                # Avoid the current song streaming
                self.play_thread.stop()
                self.play_thread.join();
            self.play_thread = PlayThread(self, song)
            self.play_thread.start()
        else:
            self.staticon.change_status_stopped()
            play_stop_image = gtk.Image()
            play_stop_image.set_from_stock(gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_MENU)
            self.staticon.change_playbutton(play_stop_image)
            self.player.set_state(gst.STATE_NULL)
            self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
            self.songinfo.set_markup("")
    
    def play_first_song(self):
        if len(self.playlist) > 0:
            self.set_playing_song(self.playlist.get_song(0))
    
    def on_play_selected(self, widget, data = None, row = None):
        """
        Starts the play thread
        """
        if self.get_playing_song() == None:
            self.play_first_song()
        else:
            self.stop_play()
            
    def on_play_next(self, widget, data = None):
        self.play_next()
        
    def on_play_previous(self, widget, data = None):
        self.play_previous()
    
    def next_shuffled_index(self):
        path = None
        
        if len(self.playlist) == 1:
            return 0
        
        if self.get_playing_song() != None:
            path = self.playlist.get_song_path(self.get_playing_song())
            
        while True:
            index = random.randint(0, len(self.playlist) - 1)
            if path == None or index != path[0]:
                break
            
        return index
    
    def play_next(self):
        """
        Plays the next item from the playlist
        """
        if len(self.playlist) == 0:
            return
        
        if self.get_playing_song() == None:
            self.play_first_song()
        else:
            if int(config()['shuffle_playlist']) == 1:
                index = self.next_shuffled_index()
            else:
                index = self.playlist.get_song_path(self.get_playing_song())[0] + 1

            if index >= len(self.playlist):
                if int(config()['repeat_playlist']) == 1:
                    index = 0
                else:
                    index = None
                    self.stop_play()
            
            if index != None:
                self.set_playing_song( self.playlist.get_song((index,)) )
        
    def play_previous(self):
        """
        Plays the previous song from the playlist
        """
        if len(self.playlist) == 0:
            return
        
        if self.get_playing_iter() == None:
            self.play_first_song()
        else:
            if int(config()['shuffle_playlist']) == 1:
                index = self.next_shuffled_index()
            else:
                index = self.playlist.get_song_path(self.get_playing_song())[0] - 1

            if index < 0:
                if int(config()['repeat_playlist']) == 1:
                    index = len(self.playlist) - 1
                else:
                    index = 0
            
            self.set_playing_song( self.playlist.get_song((index,)) )

    def stop_play(self):
        """
        Stop current playing
        """
        self.set_playing_song(None)

    def on_volume_change(self, widget, data = 0.5):
        """
        Volume change handler
        """
        self.player.set_property("volume", float(data))
        return True

    def on_show_info(self, widget, data = None):
        """
        Song infromation dialog for first item selected from the search results.
        """
        select = self.result.get_view().get_selection().get_selected_rows()
        if self.result.get_view().get_selection().count_selected_rows() > 0:
            song = self.result.get_song(select[1][0])
            dialog = guihelpers.SongInfoDialog(song)
            dialog.show_all()
            

    def on_show_lyrics(self, widget, data = None):
        """
        Tries to retrieve lyrics for selected song from the playlist.
        """
        if self.current_song != None:
            t = LyricsThread(self, self.current_song)
            t.start()
        else:
            info = guihelpers.InfoDialog(self.window,
                _("There should be a playing song to view\nthe lyrics for it."))
            info.show_all()

    def on_show_about(self, widget, data = None):
        """
        About dialog for the application
        """
        guihelpers.AboutDialog(self)

    def on_open_preferences(self, widget, data = None):
        """
        Preferences dialog with save and close buttons
        """
        dialog = guihelpers.PreferencesDialog(self)
        dialog.show_all()
        
    def on_search_grooveshark(self, widget, data = None):
        """
        Starts the search thread
        """
        if widget.get_text() != "":
            if widget.get_text() in config()['completition'].split("|"):
                pass
            else:
                compl = config()['completition'] + widget.get_text() + "|"
                config()['completition'] = compl
                config().write()
            search_thread = SearchThread(self, widget.get_text(), "Songs")
            search_thread.start()

    def get_overwritten_filename(self, filename):
        """
        Gets the file name depending on whether user want to overwrite the file,
        not overwrite it or not save it. Returns the same filename if user want
        to overwrite, the renamed filename or None if the user cancel Download.
        """
        if os.path.exists(filename) == True:
            dialog = gtk.Dialog(_("Overwrite downloaded file?"),
                         self.window,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         (_("Cancel download"), gtk.RESPONSE_NONE,
                          _("Download and overwrite"), 0,
                          _("Download renamed"), 1))

            label = gtk.Label(_("The file '%s' already exists, maybe you are downloading a file that you downloaded before.\n\nWhat do you want to do?") % filename)
            label.set_line_wrap(True)
            dialog.vbox.pack_start(label)
            label.show()

            dialog.set_default_response(gtk.RESPONSE_NONE)
            dialog.set_resizable(False)
            dialog.set_size_request(600, 175)
            response = dialog.run()
            dialog.destroy()
        else:
            response = 0

        if response == 1:
            i = 1
            newfilename = ""
            while i == 1 or os.path.exists(newfilename):
                i += 1
                split = os.path.splitext(filename)
                newfilename = split[0] + " (%d)" % i + split[1]

            return newfilename
        elif response == 0:
            return filename
        else:
            return None

    def on_download_selected(self, widget, data = None):
        """
        Starts the download thread
        """
        select = self.result.get_view().get_selection().get_selected_rows()
        for path in select[1]:
            song = self.result_song(path[0])
            
            filename = self.get_overwritten_filename(song.get_default_filename())

            if filename != None:
                song.set_filename(filename)
                self.downloads.append_song_restarting(song)

    def update_downloads_count(self):
        """
        Update the label wich indicates the downloads count.
        """
        count = self.downloads.get_model().iter_n_children(None)
        text = gettext.ngettext("Downloading %d file", "Downloading %d files", count) % count
        self.downloads_count.set_label(text)

    def right_click_download(self, treeview, event):
        """
        Executed when the user rightclicks on selected items in the download list.
        Can handle single and multiple selection.
        """
        if event.button == 3:
            path = treeview.get_path_at_pos(int(event.x), int(event.y))
            selection = treeview.get_selection()
            rows = selection.get_selected_rows()
            try:
                if path[0] not in rows[1]:
                    # Unselect if the user click the right button outside 
                    # the selected items - empty field.
                    selection.unselect_all()
                    selection.select_path(path[0])
            except TypeError:
                pass

            # still not sure about this. The point is that there are many rows selected
            # when you click the right mouse button, but then on_cancel_download still 
            # has no idea what is selected.
            if selection.count_selected_rows() > 1:
                self.downmenu.popup(None, None, None, event.button, event.time)
            else:
                self.downmenu.popup(None, None, None, event.button, event.time)

    def on_cancel_all_downloads(self):
        """
        Cancel all downloads
        """
        iter = self.downloads.first()
        while iter != None:
            self.downloads.get_song(iter).cancel_download()
            iter = self.downloads.next(iter)
            
    def on_pause_all_downloads(self):
        """
        Cancel all downloads
        """
        iter = self.downloads.first()
        while iter != None:
            self.downloads.get_song(iter).pause_download()
            iter = self.downloads.next(iter)
            
    def on_resume_all_downloads(self):
        """
        Cancel all downloads
        """
        iter = self.downloads.first()
        while iter != None:
            if self.downloads.get_song(iter).is_downloading() == False:
                self.downloads.get_song(iter).download_file(False)
            iter = self.downloads.next(iter)

    def on_cancel_download(self, menu, data = None):
        """
        Cancel the download. Have to check how to cancel the thread.
        """
        select = self.downloads_view.get_selection().get_selected_rows()
        for path in select[1]:
            self.cancel_download(path, 'cancel')

    def on_stop_download(self, button, data = None):
        """
        TODO: Not yet implemented, have to see how the download
        list will be saved.
        Stop download, in order to be resumed later
        """
        select = self.downloads_view.get_selection().get_selected_rows()
        for path in select[1]:
            self.cancel_download(path, 'stop')

    def on_resume_download(self, button, data = None):
        """
        TODO: Not yet implemnted, after stopping download we have to
        load the download list in order to resume.
        Resume stopped download
        """
        select = self.downloads_view.get_selection().get_selected_rows()
        for path in select[1]:
            for i in range(0, len(self.downqueue)):
                if path == self.downloads.get_path(self.downqueue[i]['iter']):
                    tDownload = DownloadThread(self,
                                               self.downqueue[i]['song'],
                                               self.downqueue[i]['filename'],
                                               0, i)
                    tDownload.start()

        #tDownload = DownloadThread(self, self.downqueue[], filename)
        #tDownload.start()

    def on_love_song(self, button):
        if self.current_song == None:
            info = guihelpers.InfoDialog(self.window,
                    _("There is no song to be loved.\n A song should be playing"))
            info.show_all()
        else:
            try:
                track = self.lastfm.get_track(self.current_song['ArtistName'],
                                          self.current_song['SongName'])
                track.love()
            except pylast.MalformedResponseError, e:
                pass