-
Notifications
You must be signed in to change notification settings - Fork 19
/
coverart_album.py
1861 lines (1437 loc) · 59.9 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 datetime import datetime, date
import os
import cgi
import tempfile
import gc
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
import cairo
from coverart_browser_prefs import GSetting
from coverart_utils import create_pixbuf_from_file_at_size
from coverart_utils import SortedCollection
from coverart_utils import idle_iterator
from coverart_utils import NaturalString
import coverart_rb3compat as rb3compat
from coverart_utils import uniquify_and_sort
from coverart_utils import dumpstack
from coverart_utils import check_lastfm
import rb
# default chunk of entries to process when loading albums
ALBUM_LOAD_CHUNK = 50
# default chunk of albums to process 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.
'''
# signals
__gsignals__ = {
'resized': (GObject.SIGNAL_RUN_LAST, None, ())
}
def __init__(self, size, image):
super(Cover, self).__init__()
assert isinstance(image, str), "image should be a string"
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):
self.pixbuf = create_pixbuf_from_file_at_size(
self.original, size, size)
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, ())
}
__hash__ = GObject.__hash__
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 composer(self):
return self.entry.get_string(RB.RhythmDBPropType.COMPOSER)
@property
def track_number(self):
return self.entry.get_ulong(RB.RhythmDBPropType.TRACK_NUMBER)
@property
def disc_number(self):
return self.entry.get_ulong(RB.RhythmDBPropType.DISC_NUMBER)
@property
def album_artist_sort(self):
sort = self.entry.get_string(
RB.RhythmDBPropType.ALBUM_ARTIST_SORTNAME_FOLDED) or \
self.entry.get_string(RB.RhythmDBPropType.ALBUM_ARTIST_FOLDED) or \
self.entry.get_string(RB.RhythmDBPropType.ARTIST_FOLDED)
return NaturalString(sort)
@property
def album_sort(self):
sort = self.entry.get_string(
RB.RhythmDBPropType.ALBUM_SORTNAME_FOLDED) or \
self.entry.get_string(RB.RhythmDBPropType.ALBUM_FOLDED)
return NaturalString(sort)
@property
def is_saveable(self):
return self.entry.get_entry_type().props.save_to_disk
def create_ext_db_key(self):
'''
Returns an `RB.ExtDBKey` that can be used to access/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, ())
}
__hash__ = GObject.__hash__
def __init__(self, name, artist, cover):
super(Album, self).__init__()
self.name = name
self.artist = artist
self._album_artist_sort = None
self._album_sort = None
self._artists = None
self._titles = None
self._composers = None
self._genres = None
self._tracks = []
self._cover = None
self.cover = cover
self._year = None
self._rating = None
self._duration = None
self._signals_id = {}
@property
def album_artist_sort(self):
if not self._album_artist_sort:
self._album_artist_sort = uniquify_and_sort(
[track.album_artist_sort for track in self._tracks])
return self._album_artist_sort
@property
def album_sort(self):
if not self._album_sort:
self._album_sort = uniquify_and_sort(
[track.album_sort for track in self._tracks])
return self._album_sort
@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 composers(self):
if not self._composers:
composers = [track.composer for track in self._tracks if track.composer]
if composers:
self._composers = ' '.join(set(composers))
return self._composers
@property
def year(self):
if not self._year:
real_years = [track.year for track in self._tracks if track.year != 0]
if len(real_years) > 0:
self._year = min(real_years)
else:
self._year = 0
return self._year
@property
def real_year(self):
'''
return the calculated year e.g. 1989
'''
calc_year = self.year
if calc_year == 0:
calc_year = date.today().year
else:
calc_year = datetime.fromordinal(calc_year).year
return calc_year
@property
def calc_year_sort(self):
'''
returns a str combinationi of real_year + album name
'''
return str(self.real_year) + self.name
@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
self._rating = None
self.emit('modified')
@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:
# if 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.disc_number, 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):
print("_track_modified")
if track.album != self.name:
self._track_deleted(track)
else:
self.emit('modified')
def _track_deleted(self, track):
print("_track_deleted")
self._tracks.remove(track)
# list(map(track.disconnect, self._signals_id[track]))
for signal_id in self._signals_id[track]:
track.disconnect(signal_id)
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._album_artist = None
self._album_artist_sort = None
self._album_sort = None
self._artists = None
self._titles = None
self._genres = None
self._year = None
self._rating = None
self._duration = None
self._composers = None
def __str__(self):
return self.artist + self.name
def __eq__(self, other):
return other and self.name == other.name and \
self.artist == other.artist
def __ne__(self, other):
return not other or \
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 = list(map(RB.search_fold, [album.name, album.artist,
album.artists, album.track_titles, album.composers]))
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 RB.search_fold(album.artist)
return filt
@classmethod
def artist_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in RB.search_fold(album.artists)
return filt
@classmethod
def similar_artist_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 = list(map(RB.search_fold, [album.artist,
album.artists]))
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_name_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in RB.search_fold(album.name)
return filt
@classmethod
def track_title_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in RB.search_fold(
album.track_titles)
return filt
@classmethod
def composer_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
return RB.search_fold(searchtext) in RB.search_fold(
album.composers)
return filt
@classmethod
def genre_filter(cls, searchtext=None):
def filt(album):
if not searchtext:
return True
genres = RB.search_fold(' '.join(album.genres))
return RB.search_fold(searchtext) in genres
return filt
@classmethod
def model_filter(cls, model=None):
if not model or not len(model):
return lambda x: False
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
@classmethod
def decade_filter(cls, searchdecade=None):
'''
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
'''
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,
'quick_artist': AlbumFilters.artist_filter,
'composers': AlbumFilters.composer_filter,
'similar_artist': AlbumFilters.similar_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
}
sort_keys = {
'name': ('album_sort', 'album_sort'),
'artist': ('album_artist_sort', 'album_artist_sort'),
'year': ('year', 'album_sort'),
'rating': ('rating', 'album_sort'),
}
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, ())),
'album-added': ((GObject.SIGNAL_RUN_LAST, None, (object,)))
}
# 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._sortkey = {'type': 'name', 'order': True}
self._tree_store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, object, str,
bool)
# filters
self._filters = {}
# 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(AlbumsModel.columns['show'])
@property
def store(self):
return self._filtered_store
@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):
print("_album_modified")
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:
if (new_pos + 1) >= len(self._albums):
old_album = self._albums[new_pos - 1]
old_iter = \
self._iters[old_album.name][old_album.artist]['iter']
self._tree_store.move_after(tree_iter, old_iter)
else:
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
print("album modified")
print(album)
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 necessary 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}
self.emit('album-added', album)
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.
'''
print("album model remove")
print(album)
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 a specific 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_from_dbentry(self, entry):
'''
Returns the album containing the track corresponding to rhythmdbentry
:param entry: `RhythmDBEntry`
'''
album_artist = entry.get_string(RB.RhythmDBPropType.ALBUM_ARTIST)
album_artist = album_artist if album_artist else entry.get_string(RB.RhythmDBPropType.ARTIST)
album_name = entry.get_string(RB.RhythmDBPropType.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_from_ext_db_key(self, key):
'''
Returns the requested album.
:param key: ext_db_key
'''
# get the album name and artist
name = key.get_field('album')
artist = key.get_field('artist')
# first check if there's a direct match
album = self.get(name, artist) if self.contains(name, artist) else None
if not album:
# get all the albums with the given name and look for a match
albums = [artist['album'] for artist in list(self._iters[name].values())]
for curr_album in albums:
if key.matches(curr_album.create_ext_db_key()):
album = curr_album
break
return 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)
@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(1) 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
def sort(self):
'''
Changes the sorting strategy for the model.
'''
gs = GSetting()
source_settings = gs.get_setting(gs.Path.PLUGIN)
key = source_settings[gs.PluginKey.SORT_BY]