QML: Correct threading to load images
[mussorgsky] / src / qml / controller.py
1 # -*- coding: utf-8 -*-
2 import os
3 import sys
4 from PySide import QtCore
5 from PySide import QtGui
6 from PySide import QtDeclarative
7
8 from aa_search import MussorgskyAlbumArt
9
10 from tracker_backend_gi import TrackerBackendGI
11
12 from albumItem import AlbumItem
13 from aa_spec import getCoverArtThumbFileName
14
15
16 class DownloadThread (QtCore.QThread):
17
18     def __init__ (self, model, album):
19         QtCore.QThread.__init__ (self)
20         self.downloader = MussorgskyAlbumArt ()
21         self.model = model
22         self.album = album
23
24     def run (self):
25         print "Running the thread"
26         MAX_OPTIONS = 4
27         counter = 0
28         for img, thumb in self.downloader.get_alternatives (self.album.artist,
29                                                             self.album.title, MAX_OPTIONS):
30             if counter >= MAX_OPTIONS:
31                 break
32
33             print counter, "Setting url", img
34             self.model.updateData (counter, img)
35             counter += 1
36
37
38 class MussorgskyController (QtCore.QObject):
39
40     def __init__ (self):
41         QtCore.QObject.__init__ (self)
42         self.download = None
43         self.tracker = TrackerBackendGI ()
44
45     @QtCore.Slot (QtCore.QObject, QtCore.QObject)
46     def albumSelected (self, model, album):
47         """
48         Starts a thread to look for possible images online.
49         The thread will update the model (and the changes are visible in the UI)
50         """
51         print "clicked on", album.title
52         self.download = DownloadThread (model, album)
53         self.download.start ()
54
55
56     def get_all_albums (self):
57         """
58         Return a list of AlbumItem objects to build the model
59         This is not called from QML, no need to make it a slot
60         """
61         results = []
62         for album_title, album_artist in self.tracker.get_all_albums ():
63             album_art = getCoverArtThumbFileName (album_title)
64             if (not os.path.exists (album_art)):
65                 album_art = None
66             
67             results.append (AlbumItem (album_title, album_artist, album_art))
68         return results