-
Notifications
You must be signed in to change notification settings - Fork 0
/
coverart_album.py
1690 lines (1287 loc) · 53.2 KB
/
coverart_album.py
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- Mode: python; coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
#
# Copyright (C) 2012 - fossfreedom
# Copyright (C) 2012 - Agustin Carrasco
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
'''
Structures and managers to work with albums on Rhythmbox. This module provides
the base model for the plugin to work on top of.
'''
from gi.repository import RB
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Pango
import cairo
from coverart_browser_prefs import GSetting
from coverart_utils import SortedCollection
from coverart_utils import idle_iterator
from coverart_utils import NaturalString
from urlparse import urlparse
from datetime import datetime, date
import urllib
import os
import cgi
import tempfile
import rb
import gc
# default chunk of entries to procces when loading albums
ALBUM_LOAD_CHUNK = 50
# default chunk of albums to procces when loading covers
COVER_LOAD_CHUNK = 5
class Cover(GObject.Object):
'''
Cover of an Album. It may be initialized either by a file path to the image
to use or by a previously allocated pixbuf.
:param size: `int` size in pixels of the side of the cover (asuming a
square-shapped cover).
:param image: `str` containing a path of an image from where to create
the cover or `GdkPixbuf.Pixbuf` containing the cover.
'''
# signals
__gsignals__ = {
'resized': (GObject.SIGNAL_RUN_LAST, None, ())
}
def __init__(self, size, image):
super(Cover, self).__init__()
self.original = image
self._create_pixbuf(size)
def resize(self, size):
'''
Resizes the cover's pixbuf.
'''
if self.size != size:
self._create_pixbuf(size)
self.emit('resized')
def _create_pixbuf(self, size):
try:
self.pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.original,
size, size)
if self.pixbuf.get_width() != self.pixbuf.get_height():
self.pixbuf = self.pixbuf.scale_simple(size, size,
GdkPixbuf.InterpType.BILINEAR)
except:
self.pixbuf = self.original.scale_simple(size, size,
GdkPixbuf.InterpType.BILINEAR)
self.size = size
class Shadow(Cover):
SIZE = 120.
WIDTH = 11
def __init__(self, size, image):
super(Shadow, self).__init__(size, image)
self._calculate_sizes(size)
def resize(self, size):
super(Shadow, self).resize(size)
self._calculate_sizes(size)
def _calculate_sizes(self, size):
self.width = int(size / self.SIZE * self.WIDTH)
self.cover_size = self.size - self.width * 2
class ShadowedCover(Cover):
def __init__(self, shadow, image):
super(ShadowedCover, self).__init__(shadow.cover_size, image)
self._shadow = shadow
self._add_shadow()
def resize(self, size):
if self.size != self._shadow.cover_size:
self._create_pixbuf(self._shadow.cover_size)
self._add_shadow()
self.emit('resized')
def _add_shadow(self):
pix = self._shadow.pixbuf
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pix.get_width(),
pix.get_height())
context = cairo.Context(surface)
# draw shadow
Gdk.cairo_set_source_pixbuf(context, pix, 0, 0)
context.paint()
# draw cover
Gdk.cairo_set_source_pixbuf(context, self.pixbuf, self._shadow.width,
self._shadow.width)
context.paint()
self.pixbuf = Gdk.pixbuf_get_from_surface(surface, 0, 0,
self._shadow.size, self._shadow.size)
class Track(GObject.Object):
'''
A music track. Provides methods to access to most of the tracks data from
Rhythmbox's database.
:param entry: `RB.RhythmbDBEntry` rhythmbox's database entry for the track.
:param db: `RB.RhythmbDB` instance. It's needed to update the track's
values.
'''
# signals
__gsignals__ = {
'modified': (GObject.SIGNAL_RUN_LAST, None, ()),
'deleted': (GObject.SIGNAL_RUN_LAST, None, ())
}
def __init__(self, entry, db=None):
super(Track, self).__init__()
self.entry = entry
self._db = db
def __eq__(self, other):
return rb.entry_equal(self.entry, other.entry)
@property
def title(self):
return self.entry.get_string(RB.RhythmDBPropType.TITLE)
@property
def artist(self):
return self.entry.get_string(RB.RhythmDBPropType.ARTIST)
@property
def album(self):
return self.entry.get_string(RB.RhythmDBPropType.ALBUM)
@property
def album_artist(self):
return self.entry.get_string(RB.RhythmDBPropType.ALBUM_ARTIST)
@property
def genre(self):
return self.entry.get_string(RB.RhythmDBPropType.GENRE)
@property
def year(self):
return self.entry.get_ulong(RB.RhythmDBPropType.DATE)
@property
def rating(self):
return self.entry.get_double(RB.RhythmDBPropType.RATING)
@rating.setter
def rating(self, new_rating):
self._db.entry_set(self.entry, RB.RhythmDBPropType.RATING, new_rating)
@property
def duration(self):
return self.entry.get_ulong(RB.RhythmDBPropType.DURATION)
@property
def location(self):
return self.entry.get_string(RB.RhythmDBPropType.LOCATION)
@property
def track_number(self):
return self.entry.get_ulong(RB.RhythmDBPropType.TRACK_NUMBER)
def create_ext_db_key(self):
'''
Returns an `RB.ExtDBKey` that can be used to acces/write some other
track specific data on an `RB.ExtDB`.
'''
return self.entry.create_ext_db_key(RB.RhythmDBPropType.ALBUM)
class Album(GObject.Object):
'''
An album. It's conformed from one or more tracks, and many of it's
information is deduced from them.
:param name: `str` name of the album.
:param cover: `Cover` cover for this album.
'''
# signals
__gsignals__ = {
'modified': (GObject.SIGNAL_RUN_FIRST, None, ()),
'emptied': (GObject.SIGNAL_RUN_LAST, None, ()),
'cover-updated': (GObject.SIGNAL_RUN_LAST, None, ())
}
def __init__(self, name, artist, cover):
super(Album, self).__init__()
self.name = name
self.artist = artist
self._artists = None
self._titles = None
self._genres = None
self._tracks = []
self._cover = None
self.cover = cover
self._year = None
self._rating = None
self._duration = None
self._calc_name = None
self._calc_artist = None
self._signals_id = {}
'''
we use a calculated album name for filters
this is lower case with unicode chars stripped out
'''
@property
def calc_name(self):
if not self._calc_name and self.name:
self._calc_name = NaturalString(RB.search_fold(self.name))
return self._calc_name
'''
we use a calculated album artist for filters
this is lower case with unicode chars stripped out
'''
@property
def calc_artist(self):
if not self._calc_artist and self.artist:
self._calc_artist = RB.search_fold(self.artist)
return self._calc_artist
'''
we use a calculated set of track artists for search filters
this is lower case with unicode chars stripped out
'''
@property
def calc_artists(self):
if not self._calc_artists:
self._calc_artists = RB.search_fold(self.artists)
return self._calc_artists
@property
def artists(self):
if not self._artists:
self._artists = ', '.join(
set([track.artist for track in self._tracks]))
return self._artists
@property
def track_titles(self):
if not self._titles:
self._titles = ' '.join(
set([track.title for track in self._tracks]))
return self._titles
@property
def year(self):
if not self._year:
self._year = min([track.year for track in self._tracks])
return self._year
@property
def genres(self):
if not self._genres:
self._genres = set([track.genre for track in self._tracks])
return self._genres
@property
def rating(self):
if not self._rating:
ratings = [track.rating for track in self._tracks
if track.rating and track.rating != 0]
if len(ratings) > 0:
self._rating = sum(ratings) / len(self._tracks)
else:
self._rating = 0
return self._rating
@rating.setter
def rating(self, new_rating):
for track in self._tracks:
track.rating = new_rating
@property
def track_count(self):
return len(self._tracks)
@property
def duration(self):
if not self._duration:
self._duration = sum([track.duration for track in self._tracks])
return self._duration
@property
def cover(self):
return self._cover
@cover.setter
def cover(self, new_cover):
if self._cover:
self._cover.disconnect(self._cover_resized_id)
self._cover = new_cover
self._cover_resized_id = self._cover.connect('resized',
lambda *args: self.emit('cover-updated'))
self.emit('cover-updated')
def get_tracks(self, rating_threshold=0):
'''
Returns the tracks on this album. If rating_threshold is provided,
only those tracks over the threshold will be returned. The track list
returned is ordered by track number.
:param rating_threshold: `float` threshold over which the rating of the
track should be to be returned.
'''
if not rating_threshold or not self.rating:
# if no song has rating, or no threshold is set, return all
tracks = self._tracks
else:
# otherwise, only return the entries over the threshold
tracks = [track for track in self._tracks
if track.rating >= rating_threshold]
return sorted(tracks, key=lambda track: track.track_number)
def add_track(self, track):
'''
Adds a track to the album.
:param track: `Track` track to be added.
'''
self._tracks.append(track)
ids = (track.connect('modified', self._track_modified),
track.connect('deleted', self._track_deleted))
self._signals_id[track] = ids
self.emit('modified')
def _track_modified(self, track):
if track.album != self.name:
self._track_deleted(track)
else:
self.emit('modified')
def _track_deleted(self, track):
self._tracks.remove(track)
map(track.disconnect, self._signals_id[track])
del self._signals_id[track]
if len(self._tracks) == 0:
self.emit('emptied')
else:
self.emit('modified')
def create_ext_db_key(self):
'''
Creates a `RB.ExtDBKey` from this album's tracks.
'''
return self._tracks[0].create_ext_db_key()
def do_modified(self):
self._artists = None
self._titles = None
self._genres = None
self._year = None
self._rating = None
self._duration = None
self._calc_artists = None
def __str__(self):
return self.artist + self.name
def __eq__(self, other):
if other == None:
return False
return self.name == other.name and \
self.artist == other.artist
def __ne__(self, other):
if other == None:
return True
return (self.name+self.artist) != (other.name+other.artist)
class AlbumFilters(object):
@classmethod
def nay_filter(cls, *args):
def filt(*args):
return False
return filt
@classmethod
def global_filter(cls, searchtext=None):
def filt(album):
# this filter is more complicated: for each word in the search
# text, it tries to find at least one match on the params of
# the album. If no match is given, then the album doesn't match
if not searchtext:
return True
words = RB.search_fold(searchtext).split()
params = [album.calc_name, album.calc_artist,
album.calc_artists, album.track_titles.lower()]
matches = []
for word in words:
match = False
for param in params:
if word in param:
match = True
break
matches.append(match)
return False not in matches
return filt
@classmethod
def album_artist_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in album.calc_artist
return filt
@classmethod
def artist_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in album.calc_artists
return filt
@classmethod
def album_name_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in album.calc_name
return filt
@classmethod
def track_title_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return searchtext.lower() in album.track_titles.lower()
return filt
@classmethod
def genre_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return searchtext in album.genres
return filt
@classmethod
def model_filter(cls, model=None):
if not model or not len(model):
return lambda x: True
albums = set()
for row in model:
entry = model[row.path][0]
albums.add(Track(entry).album)
def filt(album):
return album.name in albums
return filt
'''
the year is in RATA DIE format so need to extract the year
the searchdecade param can be None meaning all results
or -1 for all albums older than our standard range which is 1930
or an actual decade for 1930 to 2020
'''
@classmethod
def decade_filter(cls, searchdecade=None):
def filt(album):
if not searchdecade:
return True
if album.year == 0:
year = date.today().year
else:
year = datetime.fromordinal(album.year).year
year=int(round(year-5, -1))
if searchdecade > 0:
return searchdecade == year
else:
return year < 1930
return filt
AlbumFilters.keys = {'nay': AlbumFilters.nay_filter,
'all': AlbumFilters.global_filter,
'album_artist': AlbumFilters.album_artist_filter,
'artist': AlbumFilters.artist_filter,
'album_name': AlbumFilters.album_name_filter,
'track': AlbumFilters.track_title_filter,
'genre': AlbumFilters.genre_filter,
'model': AlbumFilters.model_filter,
'decade': AlbumFilters.decade_filter
}
class AlbumsModel(GObject.Object):
'''
Model that contains albums, keeps them sorted, filtered and provides an
external `Gtk.TreeModel` interface to use as part of a Gtk interface.
The `Gtk.TreeModel` haves the following structure:
column 0 -> string containing the album name and artist
column 1 -> pixbuf of the album's cover.
column 2 -> instance of the album itself.
column 3 -> markup text showed under the cover.
column 4 -> boolean that indicates if the row should be shown
'''
# signals
__gsignals__ = {
'generate-tooltip': (GObject.SIGNAL_RUN_LAST, str, (object,)),
'generate-markup': (GObject.SIGNAL_RUN_LAST, str, (object,)),
'album-updated': ((GObject.SIGNAL_RUN_LAST, None, (object, object))),
'visual-updated': ((GObject.SIGNAL_RUN_LAST, None, (object, object))),
'filter-changed': ((GObject.SIGNAL_RUN_FIRST, None, ()))
}
# list of columns names and positions on the TreeModel
columns = {'tooltip': 0, 'pixbuf': 1, 'album': 2, 'markup': 3, 'show': 4}
def __init__(self):
super(AlbumsModel, self).__init__()
self._iters = {}
self._albums = SortedCollection(
key=lambda album: getattr(album, 'name'))
self._tree_store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, object, str,
bool)
self._tree_store
# filters
self._filters = {}
# sorting direction
self._asc = True
# sorting idle call
self._sort_process = None
# create the filtered store that's used with the view
self._filtered_store = self._tree_store.filter_new()
self._filtered_store.set_visible_column(4)
@property
def store(self):
return self._filtered_store
@idle_iterator
def _sort(self):
def process(album, data):
values = self._generate_values(album)
tree_iter = self._tree_store.append(values)
self._iters[album.name][album.artist]['iter'] = tree_iter
def error(exception):
print 'Error while adding albums to the model: ' + str(exception)
def finish(data):
self._sort_process = None
self.remove_filter('nay')
return ALBUM_LOAD_CHUNK, process, None, error, finish
@idle_iterator
def _recreate_text(self):
def process(album, data):
tree_iter = self._iters[album.name][album.artist]['iter']
markup = self.emit('generate-markup', album)
self._tree_store.set(tree_iter, self.columns['markup'],
markup)
self._emit_signal(tree_iter, 'visual-updated')
def error(exception):
print 'Error while recreating text: ' + str(exception)
return ALBUM_LOAD_CHUNK, process, None, error, None
def _album_modified(self, album):
tree_iter = self._iters[album.name][album.artist]['iter']
if self._tree_store.iter_is_valid(tree_iter):
# only update if the iter is valid
# generate and update values
tooltip, pixbuf, album, markup, hidden =\
self._generate_values(album)
self._tree_store.set(tree_iter, self.columns['tooltip'], tooltip,
self.columns['markup'], markup, self.columns['show'], hidden)
# reorder the album
new_pos = self._albums.reorder(album)
if new_pos != -1:
old_album = self._albums[new_pos + 1]
old_iter =\
self._iters[old_album.name][old_album.artist]['iter']
self._tree_store.move_before(tree_iter, old_iter)
# inform that the album is updated
self._emit_signal(tree_iter, 'album_updated')
def _cover_updated(self, album):
tree_iter = self._iters[album.name][album.artist]['iter']
if self._tree_store.iter_is_valid(tree_iter):
# only update if the iter is valid
pixbuf = album.cover.pixbuf
self._tree_store.set_value(tree_iter, self.columns['pixbuf'],
pixbuf)
self._emit_signal(tree_iter, 'visual-updated')
def _emit_signal(self, tree_iter, signal):
# we get the filtered path and iter since that's what the outside world
# interacts with
tree_path = self._filtered_store.convert_child_path_to_path(
self._tree_store.get_path(tree_iter))
if tree_path:
# if there's no path, the album doesn't show on the filtered model
# so no one needs to know
tree_iter = self._filtered_store.get_iter(tree_path)
self.emit(signal, tree_path, tree_iter)
def add(self, album):
'''
Add an album to the model.
:param album: `Album` to be added to the model.
'''
# generate necesary values
values = self._generate_values(album)
# insert the values
tree_iter = self._tree_store.insert(self._albums.insert(album), values)
# connect signals
ids = (album.connect('modified', self._album_modified),
album.connect('cover-updated', self._cover_updated),
album.connect('emptied', self.remove))
if not album.name in self._iters:
self._iters[album.name] = {}
self._iters[album.name][album.artist] = {'album': album,
'iter': tree_iter, 'ids': ids}
return tree_iter
def _generate_values(self, album):
tooltip = self.emit('generate-tooltip', album)
markup = self.emit('generate-markup', album)
pixbuf = album.cover.pixbuf
hidden = self._album_filter(album)
return tooltip, pixbuf, album, markup, hidden
def remove(self, album):
'''
Removes this album from the model.
:param album: `Album` to be removed from the model.
'''
self._albums.remove(album)
self._tree_store.remove(self._iters[album.name][album.artist]['iter'])
# disconnect signals
for sig_id in self._iters[album.name][album.artist]['ids']:
album.disconnect(sig_id)
del self._iters[album.name][album.artist]
def contains(self, album_name, album_artist):
'''
Indicates if the model contains an especific album.
:param album_name: `str` name of the album.
'''
return album_name in self._iters \
and album_artist in self._iters[album_name]
def get(self, album_name, album_artist):
'''
Returns the requested album.
:param album_name: `str` name of the album.
'''
return self._iters[album_name][album_artist]['album']
def get_all(self):
'''
Returns a collection of all the albums in this model.
'''
return self._albums
def get_from_path(self, path):
'''
Returns an album referenced by a `Gtk.TreeModel` path.
:param path: `Gtk.TreePath` referencing the album.
'''
return self._filtered_store[path][self.columns['album']]
def get_path(self, album):
return self._filtered_store.convert_child_path_to_path(
self._tree_store.get_path(
self._iters[album.name][album.artist]['iter']))
def find_first_visible(self, filter_key, filter_arg, start=None,
backwards=False):
album_filter = AlbumFilters.keys[filter_key](filter_arg)
albums = reversed(self._albums) if backwards else self._albums
ini = albums.index(start) + 1 if start else 0
for i in range(ini, len(albums)):
album = albums[i]
if album_filter(album) and self._album_filter(album):
return album
return None
def show(self, album, show):
'''
Unfilters an album, making it visible to the publicly available model's
`Gtk.TreeModel`
:param album: `Album` to show or hide.
:param show: `bool` indcating whether to show(True) or hide(False) the
album.
'''
album_iter = self._iters[album.name][album.artist]['iter']
if self._tree_store.iter_is_valid(album_iter):
self._tree_store.set_value(album_iter, self.columns['show'], show)
def sort(self, key, asc):
'''
Changes the sorting strategy for the model.
:param key: `str`attribute of the `Album` class by which the sort
should be performed.
:param asc: `bool` indicating whether it should be sorted in
ascending(True) or descending(False) direction.
'''
if key == 'name':
key = 'calc_name'
elif key == 'artist':
key = 'calc_artist'
self._albums.key = lambda album: getattr(album, key)
if asc != self._asc:
self._albums = reversed(self._albums)
self._asc = asc
self._tree_store.clear()
# add the nay filter
self.replace_filter('nay', refilter=False)
if self._sort_process:
# stop the previous sort process if there's one
self._sort_process.stop()
# load the albums back to the model
self._sort_process = self._sort(iter(self._albums))
def replace_filter(self, filter_key, filter_arg=None, refilter=True):
'''
Adds or replaces a filter by it's filter_key.
:param filter_key: `str` key of the filter method to use. This should
be one of the available keys on the `AlbumFilters` class.
:param filter_arg: `object` any object that the correspondant filter
method may need to perform the filtering process.
:param refilter: `bool` indicating whether to force a refilter and
emit the 'filter-changed' signal(True) or not(False).
'''
self._filters[filter_key] = AlbumFilters.keys[filter_key](filter_arg)
if refilter:
self.emit('filter-changed')
def remove_filter(self, filter_key, refilter=True):
'''
Removes a filter by it's filter_key
:param filter_key: `str` key of the filter method to use. This should
be one of the available keys on the `AlbumFilters` class.
:param refilter: `bool` indicating whether to force a refilter and
emit the 'filter-changed' signal(True) or not(False).
'''
if filter_key in self._filters:
del self._filters[filter_key]
if refilter:
self.emit('filter-changed')
def clear_filters(self):
'''
Clears all filters on the model.
'''
if self._filters:
self._filters.clear()
self.emit('filter-changed')
def do_filter_changed(self):
map(self.show, self._albums, map(self._album_filter, self._albums))
def _album_filter(self, album):
for f in self._filters.values():
if not f(album):
return False
return True
def recreate_text(self):
'''
Forces the recreation and update of the markup text for each album.
'''
self._recreate_text(iter(self._albums))
class AlbumLoader(GObject.Object):
'''
Loads and updates Rhythmbox's tracks and albums, updating the model
accordingly.
:param album_manager: `AlbumManager` responsible for this loader.
'''
# signals
__gsignals__ = {
'albums-load-finished': (GObject.SIGNAL_RUN_LAST, None, (object,)),
'model-load-finished': (GObject.SIGNAL_RUN_LAST, None, ())
}
def __init__(self, album_manager):
super(AlbumLoader, self).__init__()
self._album_manager = album_manager
self._tracks = {}
self._connect_signals()
def _connect_signals(self):
# connect signals for updating the albums
self.entry_changed_id = self._album_manager.db.connect('entry-changed',
self._entry_changed_callback)
self.entry_added_id = self._album_manager.db.connect('entry-added',
self._entry_added_callback)
self.entry_deleted_id = self._album_manager.db.connect('entry-deleted',
self._entry_deleted_callback)
@idle_iterator
def _load_albums(self):
def process(row, data):
entry = data['model'][row.path][0]
# allocate the track
track = Track(entry, self._album_manager.db)
self._tracks[track.location] = track
album_name = track.album
album_artist = track.album_artist
album_artist = album_artist if album_artist else track.artist
if album_name not in data['albums']:
data['albums'][album_name] = {}
if album_artist in data['albums'][album_name]:
album = data['albums'][album_name][album_artist]
else:
album = Album(album_name, album_artist,
self._album_manager.cover_man.unknown_cover)
data['albums'][album_name][album_artist] = album
album.add_track(track)
def after(data):
# update the progress
data['progress'] += ALBUM_LOAD_CHUNK
self._album_manager.progress = data['progress'] / data['total']