1#######
2
3#
4#  ITunesCommunication.py
5#  PyObjC2Test
6#
7#
8# This is a variation on the ITunesCommuncation that uses a the 'appscript'
9# module for the inter-application communication.
10
11import objc
12from Foundation import *
13from AppKit import *
14
15from PyObjCTools import NibClassBuilder
16
17from appscript import *
18
19# We tell NibClassBuilder to examine and remember all
20# classes from the CDInfoDocument NIB file. This way,
21# we can subclass our ITunesCommunication from AutoBaseClass
22# later on, and its actual baseclass will be ITunesCommunication
23# from the NIB file.
24# Since the NIB files are in the application, NOT the plugin, we
25# need to specify this explicitly.  Typicaly, NIB files would be in the
26# plugins.
27NibClassBuilder.extractClasses("CDInfoDocument", bundle=NSBundle.mainBundle())
28
29class ITunesCommunication(NibClassBuilder.AutoBaseClass):
30    def init(self):
31        self = super(ITunesCommunication, self).init()
32        if self is None:
33            return None
34        return self
35
36    def getITunesInfo(self):
37        try:
38            track = app('iTunes.app').current_track.get()
39        except Exception:
40            NSRunAlertPanel(
41                u'iTunes Communication Error',
42                u'iTunes failed to return the current track',
43                None,
44                None,
45                None)
46        else:
47            return track.album.get(), track.artist.get(), track.genre.get()
48
49    def askITunes_(self, obj):
50        # obj is the button the user pressed. We can go from here
51        # to the document (an instance of CDInfoDocument)
52        document = obj.window().windowController().document()
53        # Try to get the iTunes info
54        info = self.getITunesInfo()
55        if info is None:
56            return
57        album, artist, genre = info
58        document.setCDTitle_(album)
59        document.setBandName_(artist)
60        document.setMusicGenre_(genre)
61