Source

gSharkDown / lib / guihelpers.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
from enviroment import env, config
import gtk
import os
import sys
import locale
import gettext
import glib
from gettext import gettext as _
import webbrowser

try:
    import appindicator
except:
    pass

try:
    import pynotify
except:
    pass

try:
    import pylast
except:
    pass


class ErrorMessage(gtk.MessageDialog):
    """
    Error Message helper. Displays an Error message whit given
    text content. Used to be shown in Threads
    """

    def __init__(self, parent, message):
        """
        ErrorMessage accepts the the following parameter
        @param parent : The parent window of the error message
        @param message : The error message to be shown
        """
        gtk.MessageDialog.__init__(self, parent,
                            gtk.DIALOG_DESTROY_WITH_PARENT,
                            gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)
        self.set_default_response(gtk.RESPONSE_OK)
        self.set_title(_("Error"))
        self.connect('response', self.handle_clicked)
        
        self.show_all()

    def handle_clicked(self, *args):
        """
        Handler for the dedault dialog response.
        """
        self.destroy()

class InfoDialog(gtk.MessageDialog):
    """
    Informations dialog helper. Displays Information messages
    with given text.
    """

    def __init__(self, parent, message):
        """
        InfoDialog accepts the following parameters
        @param parent : The parent window of the Infor dialog
        @param message : The message to be shown
        """
        gtk.MessageDialog.__init__(self, parent,
                            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                            gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message)
        self.set_default_response(gtk.RESPONSE_OK)
        self.connect('response', self.handle_clicked)

    def handle_clicked(self, *args):
        """
        Handler of the default dialog response
        """
        self.destroy()

class UpdateDialog(gtk.MessageDialog):
    """
    Update dialog helper. Displays information when new version of
    gSharkDown is available.
    """
    def __init__(self, title, message, secondary):
        """
        Accepted parameters:
        @param title : The title of the update box
        @param message : The message of the update dialog
        @param secondary : The secondary message of the update dialog
        """
        gtk.MessageDialog.__init__(self, None,
                                   gtk.DIALOG_DESTROY_WITH_PARENT,
                                   gtk.MESSAGE_INFO, gtk.BUTTONS_OK)
        self.set_title(title)
        self.set_markup(message)
        self.format_secondary_markup(secondary)
        self.set_default_response(gtk.RESPONSE_OK)
        self.connect('response', self.handle_clicked)

    def handle_clicked(self, *args):
        """
        Handler to quit the update dialog
        """
        self.destroy()


class LyricsDialog:
    """
    Lyrics Dialog to be shown in a Thread. requieres the
    .ui file, the name of the artist and song, and the
    lyrics itself.
    """

    def __init__(self, song, lyrics):
        """
        Accepted parameters in the Lyrics dialog
        @param _uifile : the path to the .ui file for the dialog
        @param _artist : The Artist string to search for
        @param _song : The Song title string to search for
        @param _lyrics : The lyrics as string to be shown in the dialog
        """
        self.builder = gtk.Builder()
        self.builder.add_from_file("%s/data/lyrics_dialog.ui" % env().BASEPATH)
        self.lyrics = self.builder.get_object('dialog1')
        self.songlabel = self.builder.get_object('label2')
        self.lyrics_view = self.builder.get_object('textview1')
        self.lyrics_buffer = self.lyrics_view.get_buffer()
        self.lyrics.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK)
        self.lyrics.set_default_response(gtk.RESPONSE_OK)
        self.lyrics.connect('response', self.handle_clicked)
        song_title = glib.markup_escape_text(song.get_artist()) + " - "
        song_title += glib.markup_escape_text(song.get_title())

        self.songlabel.set_text(song_title)
        self.lyrics_buffer.set_text(glib.markup_escape_text(lyrics))

    def show_all(self):
        """
        Wrap the default function of show_all for a dialog
        """
        self.lyrics.show_all()

    def handle_clicked(self, *args):
        """
        Handler for the default dialog response
        """
        self.lyrics.destroy()
        
class SongInfoDialog:
    """
    Dialog that shows detailed song information
    """
    
    def __init__(self, song):
        self.dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
                                      0, gtk.BUTTONS_OK,)
        self.dialog.set_title(_("Song Information - {songid}").format(songid = song.get_id()))
        _title = _("<b>Title:</b> {title}\n").format(title = glib.markup_escape_text(song.get_title()))
        _artist = _("<b>Artist:</b> {artist}\n").format(artist = glib.markup_escape_text(song.get_artist()))
        _duration = "%.2f" % (float(song.get_duration()) / 60)
        _duration = _("<b>Duration:</b> {duration} min\n").format(duration = song.get_duration_human_readable())
        _album = _("<b>Album:</b> {album}\n").format(album = glib.markup_escape_text(song.get_album()))
        _year = _("<b>Year:</b> {year}\n").format(year = song.get_year())
        info = _title + _artist + _duration + _album + _year
        self.dialog.set_markup(info)
        
        if song.get_cover_pixbuf() == None:
            self.set_pixbuf( gtk.gdk.pixbuf_new_from_file("%s/data/loading.png" % env().BASEPATH) )
            song.connect("cover-downloaded", self.on_cover_downloaded)
            song.download_cover()
        else:
            self.set_pixbuf(song.get_cover_pixbuf())
    
    def show_all(self):
        self.dialog.show_all()
        self.dialog.run()
        self.dialog.destroy()
    
    def set_pixbuf(self, pixbuf):
        image = gtk.Image()
        image.set_from_pixbuf(pixbuf)
        self.dialog.set_image(image)
        self.dialog.show_all()
    
    def on_cover_downloaded(self, song):
        self.set_pixbuf(song.get_cover_pixbuf())

class PreferencesDialog:
    """
    Show a dialog for configure the preferences
    """
    def __init__(self, app):
        self.app = app
        
        builder = gtk.Builder()
        builder.set_translation_domain(env().APP)
        builder.add_from_file('%s/data/preferenes_dialog.ui' % env().BASEPATH)
        
        self.prefs = builder.get_object('window1')
        self.dest = builder.get_object('filechooserbutton1')
        self.dest.set_filename(config()['down_path'])
        self.quit_without_confirmation = builder.get_object("checkbutton1")
        self.quit_without_confirmation.set_active(int(config()['quit_without_confirmation']))
        self.bubble = builder.get_object("checkbutton2")
        self.speed = builder.get_object("spinbutton1")
        self.speed.set_value(int(config()['speed_limit']))
        self.file_pattern = builder.get_object("entry1")
        self.file_pattern.set_text(config()['file_pattern'])
        self.startup_check = builder.get_object("checkbutton4")
        self.startup_check.set_active(int(config()['startup_update_check']))
        
        if env().HAVE_NOTIFY:
            self.bubble.set_active(int(config()['show_notification']))
        else:
            self.bubble.set_sensitive(False)
        
        self.lastuser = builder.get_object("entry2")
        self.lastuser.set_text(config()['lastuser'])
        self.lastpass = builder.get_object("entry3")
        self.lastpass.set_visibility(False)
        self.lastpass.set_text(config()['lastpass'])
        self.scrobble = builder.get_object("checkbutton3")
        
        if env().HAVE_PYLAST:
            self.scrobble.set_active(int(config()['scrobbling']))
        else:
            self.scrobble.set_sensitive(False)
        
        self.lastuser.set_sensitive(self.scrobble.get_active())
        self.lastpass.set_sensitive(self.scrobble.get_active())
        builder.connect_signals(self)
    
    def show_all(self):
        self.prefs.show_all()
        
    def on_scrobble_toggle(self, widget, data = None):
        self.lastuser.set_sensitive(widget.get_active())
        self.lastpass.set_sensitive(widget.get_active())
        
    def on_save(self, widget, data = None):
        """
        Saves the information from the Preferences dialog in the
        configuration file
        """
        config()['down_path'] = self.dest.get_filename()
        
        if self.quit_without_confirmation.get_active():
            config()['quit_without_confirmation'] = '1'
        else:
            config()['quit_without_confirmation'] = '0'

        if self.bubble.get_active():
            config()['show_notification'] = 1
        else:
            config()['show_notification'] = 0

        if self.startup_check.get_active():
            config()['startup_update_check'] = 1
        else:
            config()['startup_update_check'] = 0

        config()['file_pattern'] = self.file_pattern.get_text()
        config()['speed_limit'] = self.speed.get_value_as_int()  
        
        try:
            if self.scrobble.get_active():
                lastfm_pass = None
                if config()['lastpass'] == self.lastpass.get_text():
                    lastfm_pass = self.lastpass.get_text()
                else:
                    lastfm_pass = pylast.md5(self.lastpass.get_text())
                
                self.lastfm = pylast.LastFMNetwork(api_key = env().LASTFM_KEY,
                                              api_secret = env().LASTFM_SECRET,
                                              username = self.lastuser.get_text(),
                                              password_hash = lastfm_pass )
                self.app.lovebutton.set_sensitive(True)
                config()['scrobbling'] = 1
                config()['lastuser'] = self.lastuser.get_text()
                config()['lastpass'] = pylast.md5(self.lastpass.get_text())
            else:
                config()['scrobbling'] = 0
                self.app.lovebutton.set_sensitive(False)
                
            config().write()
            self.prefs.destroy()
        except pylast.WSError:
            ErrorMessage(self.prefs, _("Please check your username and password for Last.fm or disable scrobbling"))
            self.lastuser.select_region(0, -1)
            self.lastuser.grab_focus()
            self.lastpass.set_text("")
        
    def on_cancel(self, widget, data = None):
        """
        Closes the Preferences dialog discarding any changes
        """
        self.prefs.destroy()
        
class AboutDialog:
    def __init__(self, app):
        builder = gtk.Builder()
        builder.set_translation_domain(env().APP)
        builder.add_from_file('%s/data/about_dialog.ui' % env().BASEPATH)
        flattr = builder.get_object('flattrbut')
        flattr.connect("clicked", self.on_flattr_this)
        updbtn = builder.get_object('updatbut')
        updbtn.connect("clicked", app.on_check_for_updates)
        about = builder.get_object('aboutdialog1')
        about.run()
        about.destroy()
        
    def on_flattr_this(self, widget, data = None):
        """
        Opens the flattr page for gSharkDown
        """
        webbrowser.open(env().FLATTR_URL)

class GsharkIndicator:
    """
    AppIndicator for gSharkDown
    """

    def __init__(self, instance):
        """
        instance parameter is the main windows class for gSharkDown,
        so we can access the gSharkDown methods.
        """
        if env().HAVE_INDICATOR == True:
            if os.path.exists('/usr/share/pixmaps/gsharkdown'):
                icons_path = '/usr/share/pixmaps/gsharkdown'
            else:
                icons_path = "%s/_pixmaps/gsharkdown" % env().BASEPATH
            self.ind = appindicator.Indicator("gsharkdown-client",
                                    "gsharkdown-messages",
                                    appindicator.CATEGORY_APPLICATION_STATUS,
                                    icons_path)
            self.ind.set_status(appindicator.STATUS_ACTIVE)
            self.ind.set_attention_icon("gsharkdown_16_playing")
            self.ind.set_icon("gsharkdown_16")

            # Create the menu for the appindicator
            menu = gtk.Menu()

            # New menu entry to handle show/hide main window
            show_window = gtk.CheckMenuItem(_("Hide gSharkDown"))
            show_window.connect("toggled", instance.on_statusicon_clicked)

            about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
            about.connect("activate", instance.on_show_about)
            prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
            prefs.connect("activate", instance.on_open_preferences)
            self.playbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PLAY)
            self.playbut.connect("activate", instance.on_play_selected)
            prebut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PREVIOUS)
            prebut.connect("activate", instance.on_play_previous)
            ffbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_NEXT)
            ffbut.connect("activate", instance.on_play_next)

            updimg = gtk.Image()
            updimg.set_from_icon_name('system-software-update',
                                     gtk.ICON_SIZE_MENU)
            updbut = gtk.ImageMenuItem(_("Check for update"))
            updbut.set_image(updimg)
            updbut.connect("activate", instance.on_check_for_updates)
            quiter = gtk.ImageMenuItem(gtk.STOCK_QUIT)
            quiter.connect("activate", instance.on_quit_app)

            menu.append(show_window)
            menu.append(gtk.SeparatorMenuItem())
            menu.append(prebut)
            menu.append(self.playbut)
            menu.append(ffbut)
            menu.append(gtk.SeparatorMenuItem())
            menu.append(about)
            menu.append(updbut)
            menu.append(prefs)
            menu.append(gtk.SeparatorMenuItem())
            menu.append(quiter)
            menu.show_all()

            self.ind.set_menu(menu)
        else:
            self.instance = instance
            self.staticon = gtk.StatusIcon()
            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % env().BASEPATH)
            self.staticon.connect("popup-menu", self.right_click_event)
            self.staticon.connect("activate", self.on_statusicon_clicked)
            self.staticon.set_tooltip(_("gSharkDown :: Player and Downloader"))

    def right_click_event(self, icon, button, time):
        '''
        Handler for the right click event on the StatIcon
        Not usable for the AppIndicator
        '''
        menu = gtk.Menu()

        about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about.connect("activate", self.instance.on_show_about)
        prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        prefs.connect("activate", self.instance.on_open_preferences)
        playbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PLAY)
        playbut.connect("activate", self.instance.on_play_selected)
        prebut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PREVIOUS)
        prebut.connect("activate", self.instance.on_play_previous)
        ffbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_NEXT)
        ffbut.connect("activate", self.instance.on_play_next)

        updimg = gtk.Image()
        updimg.set_from_icon_name('system-software-update',
                                 gtk.ICON_SIZE_MENU)
        updbut = gtk.ImageMenuItem(_("Check for update"))
        updbut.set_image(updimg)
        updbut.connect("activate", self.instance.on_check_for_updates)
        quiter = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quiter.connect("activate", self.instance.on_quit_app)

        menu.append(prebut)
        menu.append(playbut)
        menu.append(ffbut)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(about)
        menu.append(updbut)
        menu.append(prefs)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(quiter)
        menu.show_all()

        menu.popup(None, None, gtk.status_icon_position_menu,
                  button, time, icon)

    def on_statusicon_clicked(self, widget):
        """
        Handler for a click event on the StatIcon
        Not usable for the AppIndicator
        """
        return self.instance.on_statusicon_clicked(widget)

    def change_status_playing(self):
        # Method to change the gSharkDown icon when playing
        if env().HAVE_INDICATOR == True:
            self.ind.set_status(appindicator.STATUS_ATTENTION)
        else:
            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % env().BASEPATH)

    def change_status_stopped(self):
        # Method to change the gSharkDown icon to default
        # when not playing anything.
        if env().HAVE_INDICATOR == True:
            self.ind.set_status(appindicator.STATUS_ACTIVE)
        else:
            self.staticon.set_from_file("%s/data/gsharkdown_16_playing.png" % env().BASEPATH)

    def change_playbutton(self, image):
        if env().HAVE_INDICATOR == True:
            self.playbut.set_image(image)