Source

ITunesBridged / iTunesBridgedAppController.py

Full commit
#
#  iTunesBridgedAppController.py
#  iTunesBridged
#
#  Created by Kevin Mitchell on 1/13/08.
#
#  Copyright (c) 2008 Kevin A. Mitchell
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

from Foundation import *
from ScriptingBridge import SBApplication
from objc import ivar

def fourCharCode(x):
	return ord(x[0]) << 24 | ord(x[1]) << 16 | ord(x[2]) << 8 | ord(x[3])

# Scripting Bridge doesn't do constants yet, but we can define them by using sdef and sdp
# From iTunes.h	
# Converted with: sdef /Applications/iTunes.app/ | sdp -fh --basename iTunes 
iTunesEPlSStopped = fourCharCode('kPSS')
iTunesEPlSPlaying = fourCharCode('kPSP')
iTunesEPlSPaused = fourCharCode('kPSp')
iTunesEPlSFastForwarding = fourCharCode('kPSF')
iTunesEPlSRewinding = fourCharCode('kPSR')

class iTunesBridgedAppController(NSObject):
	iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
	
	trackName = ivar("trackName")
	playPauseButton = ivar("playPauseButton")

	def awakeFromNib(self):
		NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, 'playerInfoChanged:', 'com.apple.iTunes.playerInfo', None)
		if self.iTunes.isRunning():
			if self.iTunes.playerState() == iTunesEPlSPlaying:
				self.updatePlayPauseButton_('Playing')
			self.trackName = self.iTunes.currentTrack().name()

	def updatePlayPauseButton_(self, state):
		NSLog("state: %@", state)
		if state == 'Playing':
			title = "Pause"
		else:
			title = "Play"
		self.playPauseButton.setTitle_(title)

	def playPause_(self, sender):
		NSLog("Play/Pause")			
		self.iTunes.playpause()

	def playerInfoChanged_(self, notification):
		NSLog("playerInfoChanged: %@", notification.userInfo().description())
		info = notification.userInfo()
		self.trackName = info.get('Name', '')
		self.updatePlayPauseButton_(info.get('Player State', 'Paused'))

iTunesBridgedAppController.exposeBinding_("trackName")