1 #import "MainController.h"
2 #import "MenuController.h"
3 #import "PreferencesController.h"
4 #import "NetworkController.h"
5 #import "NetworkObject.h"
6 #import <ITKit/ITHotKeyCenter.h>
7 #import <ITKit/ITHotKey.h>
8 #import <ITKit/ITKeyCombo.h>
9 #import "StatusWindow.h"
10 #import "StatusWindowController.h"
11 #import "StatusItemHack.h"
13 @interface NSImage (WeeAdditions)
14 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize;
17 @implementation NSImage (WeeAdditions)
19 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
22 NSImageRep *rep = [self bestRepresentationForDevice:nil];
24 newImage = [[NSImage alloc] initWithSize:scaledSize];
27 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
28 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
29 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
31 [newImage unlockFocus];
32 return [newImage autorelease];
37 @interface MainController(Private)
38 - (ITMTRemote *)loadRemote;
39 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
40 - (void)applicationLaunched:(NSNotification *)note;
41 - (void)applicationTerminated:(NSNotification *)note;
44 static MainController *sharedController;
46 @implementation MainController
48 + (MainController *)sharedController
50 return sharedController;
53 /*************************************************************************/
55 #pragma mark INITIALIZATION/DEALLOCATION METHODS
56 /*************************************************************************/
60 if ( ( self = [super init] ) ) {
61 sharedController = self;
63 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
64 [[PreferencesController sharedPrefs] setController:self];
65 statusWindowController = [StatusWindowController sharedController];
66 menuController = [[MenuController alloc] init];
67 df = [[NSUserDefaults standardUserDefaults] retain];
74 - (void)applicationDidFinishLaunching:(NSNotification *)note
76 //Turn on debug mode if needed
77 if ([df boolForKey:@"ITDebugMode"]) {
81 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
82 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
84 [[PreferencesController sharedPrefs] registerDefaults];
85 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
88 currentRemote = [self loadRemote];
89 [[self currentRemote] begin];
91 //Turn on network stuff if needed
92 networkController = [[NetworkController alloc] init];
93 if ([df boolForKey:@"enableSharing"]) {
94 [self setServerStatus:YES];
95 } else if ([df boolForKey:@"useSharedPlayer"]) {
96 if ([self connectToServer] == 0) {
97 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
101 //Setup for notification of the remote player launching or quitting
102 [[[NSWorkspace sharedWorkspace] notificationCenter]
104 selector:@selector(applicationTerminated:)
105 name:NSWorkspaceDidTerminateApplicationNotification
108 [[[NSWorkspace sharedWorkspace] notificationCenter]
110 selector:@selector(applicationLaunched:)
111 name:NSWorkspaceDidLaunchApplicationNotification
114 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
115 [[PreferencesController sharedPrefs] registerDefaults];
118 if ([df boolForKey:@"ITMTNoStatusItem"]) {
121 [StatusItemHack install];
122 statusItem = [[ITStatusItem alloc]
123 initWithStatusBar:[NSStatusBar systemStatusBar]
124 withLength:NSSquareStatusItemLength];
127 bling = [[MTBlingController alloc] init];
129 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
131 selector:@selector(blingTime)
133 repeats:YES] retain];
136 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
137 [self applicationLaunched:nil];
139 if ([df boolForKey:@"LaunchPlayerWithMT"])
142 [self applicationTerminated:nil];
145 [self networkError:localException];
148 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
149 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
151 [networkController startRemoteServerSearch];
155 - (ITMTRemote *)loadRemote
157 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
158 ITDebugLog(@"Gathering remotes.");
160 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
161 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
162 NSString *bundlePath;
164 while ( (bundlePath = [enumerator nextObject]) ) {
165 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
168 Class remoteClass = [remoteBundle principalClass];
170 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
171 [remoteClass isKindOfClass:[NSObject class]]) {
172 id remote = [remoteClass remote];
173 ITDebugLog(@"Adding remote at path %@", bundlePath);
174 [remoteArray addObject:remote];
179 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
180 // if ( [remoteArray count] > 1 ) {
181 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
183 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
186 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
187 return [remoteArray objectAtIndex:0];
190 /*************************************************************************/
192 #pragma mark INSTANCE METHODS
193 /*************************************************************************/
195 /*- (void)startTimerInNewThread
197 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
198 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
199 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
201 selector:@selector(timerUpdate)
203 repeats:YES] retain];
205 ITDebugLog(@"Timer started.");
209 - (void)setBlingTime:(NSDate*)date
211 NSMutableDictionary *globalPrefs;
213 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
215 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
216 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
218 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
219 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
221 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
223 [globalPrefs release];
226 - (NSDate*)getBlingTime
229 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
234 NSDate *now = [NSDate date];
235 if (![self blingBling]) {
236 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
237 [self setBlingTime:now];
238 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
239 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
240 [self setBlingTime:[now addTimeInterval:-259200]];
242 NSMutableDictionary *globalPrefs;
244 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
245 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
246 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
248 [globalPrefs release];
252 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
254 [statusItem setEnabled:NO];
256 if ([refreshTimer isValid]) {
257 [refreshTimer invalidate];
259 [statusWindowController showRegistrationQueryWindow];
263 [statusItem setEnabled:YES];
265 if (![refreshTimer isValid]) {
266 [refreshTimer release];
267 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
269 selector:@selector(timerUpdate)
271 repeats:YES] retain];
275 [self setBlingTime:nil];
286 if ( ! ([bling checkDone] == 2475) ) {
293 - (BOOL)songIsPlaying
295 NSString *identifier = nil;
297 identifier = [[self currentRemote] playerStateUniqueIdentifier];
299 [self networkError:localException];
301 return ( ! ([identifier isEqualToString:@"0-0"]) );
304 - (BOOL)radioIsPlaying
306 ITMTRemotePlayerPlaylistClass class = nil;
308 class = [[self currentRemote] currentPlaylistClass];
310 [self networkError:localException];
312 return (class == ITMTRemotePlayerRadioPlaylist );
317 NSString *identifier = nil;
319 identifier = [[self currentRemote] playerStateUniqueIdentifier];
321 [self networkError:localException];
323 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
326 - (NSString *)latestSongIdentifier
328 return _latestSongIdentifier;
331 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
333 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
334 [_latestSongIdentifier autorelease];
335 _latestSongIdentifier = [newIdentifier copy];
340 if ([networkController isConnectedToServer]) {
341 [statusItem setMenu:[menuController menu]];
344 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
345 ITDebugLog(@"The song changed.");
347 if ([df boolForKey:@"runScripts"]) {
348 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
349 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
350 NSString *nextScript;
351 while ( (nextScript = [scriptsEnum nextObject]) ) {
353 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
354 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
355 ITDebugLog(@"Error running script %@.", nextScript);
357 [currentScript release];
364 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
365 [menuController rebuildSubmenus];
367 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
368 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
371 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
373 NSString *artist = [[self currentRemote] currentSongArtist];
374 NSString *title = [[self currentRemote] currentSongTitle];
377 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
381 toolTip = @"No Song Playing";
383 [statusItem setToolTip:toolTip];
385 [self networkError:localException];
394 ITDebugLog(@"Menu clicked.");
395 if ([networkController isConnectedToServer]) {
396 //Used the cached version
401 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
402 [statusItem setMenu:[menuController menu]];
404 [statusItem setMenu:[menuController menuForNoPlayer]];
407 [self networkError:localException];
420 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
421 ITDebugLog(@"Play/Pause toggled");
422 if (state == ITMTRemotePlayerPlaying) {
423 [[self currentRemote] pause];
424 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
425 [[self currentRemote] pause];
426 [[self currentRemote] play];
428 [[self currentRemote] play];
431 [self networkError:localException];
439 ITDebugLog(@"Going to next song.");
441 [[self currentRemote] goToNextSong];
443 [self networkError:localException];
450 ITDebugLog(@"Going to previous song.");
452 [[self currentRemote] goToPreviousSong];
454 [self networkError:localException];
461 ITDebugLog(@"Fast forwarding.");
463 [[self currentRemote] forward];
465 [self networkError:localException];
472 ITDebugLog(@"Rewinding.");
474 [[self currentRemote] rewind];
476 [self networkError:localException];
481 - (void)selectPlaylistAtIndex:(int)index
483 ITDebugLog(@"Selecting playlist %i", index);
485 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
486 //[[self currentRemote] switchToPlaylistAtIndex:index];
488 [self networkError:localException];
493 - (void)selectSongAtIndex:(int)index
495 ITDebugLog(@"Selecting song %i", index);
497 [[self currentRemote] switchToSongAtIndex:index];
499 [self networkError:localException];
504 - (void)selectSongRating:(int)rating
506 ITDebugLog(@"Selecting song rating %i", rating);
508 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
510 [self networkError:localException];
515 - (void)selectEQPresetAtIndex:(int)index
517 ITDebugLog(@"Selecting EQ preset %i", index);
519 [[self currentRemote] switchToEQAtIndex:index];
521 [self networkError:localException];
528 ITDebugLog(@"Beginning show player.");
529 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
530 ITDebugLog(@"Showing player interface.");
532 [[self currentRemote] showPrimaryInterface];
534 [self networkError:localException];
537 ITDebugLog(@"Launching player.");
540 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
542 path = [[self currentRemote] playerFullName];
544 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
545 ITDebugLog(@"Error Launching Player");
548 [self networkError:localException];
551 ITDebugLog(@"Finished show player.");
554 - (void)showPreferences
556 ITDebugLog(@"Show preferences.");
557 [[PreferencesController sharedPrefs] showPrefsWindow:self];
560 - (void)showPreferencesAndClose
562 ITDebugLog(@"Show preferences.");
563 [[PreferencesController sharedPrefs] showPrefsWindow:self];
564 [[StatusWindow sharedWindow] setLocked:NO];
565 [[StatusWindow sharedWindow] vanish:self];
566 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
569 - (void)showTestWindow
571 [self showCurrentTrackInfo];
574 - (void)quitMenuTunes
576 ITDebugLog(@"Quitting MenuTunes.");
577 [NSApp terminate:self];
583 - (void)closePreferences
585 ITDebugLog(@"Preferences closed.");
586 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
591 - (ITMTRemote *)currentRemote
593 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
594 [self networkError:nil];
597 return currentRemote;
608 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
609 ITHotKey *nextHotKey;
610 ITDebugLog(@"Clearing hot keys.");
611 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
612 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
614 ITDebugLog(@"Done clearing hot keys.");
620 ITDebugLog(@"Setting up hot keys.");
622 if (playerRunningState == ITMTRemotePlayerNotRunning) {
626 if ([df objectForKey:@"PlayPause"] != nil) {
627 ITDebugLog(@"Setting up play pause hot key.");
628 hotKey = [[ITHotKey alloc] init];
629 [hotKey setName:@"PlayPause"];
630 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
631 [hotKey setTarget:self];
632 [hotKey setAction:@selector(playPause)];
633 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
636 if ([df objectForKey:@"NextTrack"] != nil) {
637 ITDebugLog(@"Setting up next track hot key.");
638 hotKey = [[ITHotKey alloc] init];
639 [hotKey setName:@"NextTrack"];
640 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
641 [hotKey setTarget:self];
642 [hotKey setAction:@selector(nextSong)];
643 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
646 if ([df objectForKey:@"PrevTrack"] != nil) {
647 ITDebugLog(@"Setting up previous track hot key.");
648 hotKey = [[ITHotKey alloc] init];
649 [hotKey setName:@"PrevTrack"];
650 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
651 [hotKey setTarget:self];
652 [hotKey setAction:@selector(prevSong)];
653 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
656 if ([df objectForKey:@"ShowPlayer"] != nil) {
657 ITDebugLog(@"Setting up show player hot key.");
658 hotKey = [[ITHotKey alloc] init];
659 [hotKey setName:@"ShowPlayer"];
660 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
661 [hotKey setTarget:self];
662 [hotKey setAction:@selector(showPlayer)];
663 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
666 if ([df objectForKey:@"TrackInfo"] != nil) {
667 ITDebugLog(@"Setting up track info hot key.");
668 hotKey = [[ITHotKey alloc] init];
669 [hotKey setName:@"TrackInfo"];
670 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
671 [hotKey setTarget:self];
672 [hotKey setAction:@selector(showCurrentTrackInfo)];
673 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
676 if ([df objectForKey:@"UpcomingSongs"] != nil) {
677 ITDebugLog(@"Setting up upcoming songs hot key.");
678 hotKey = [[ITHotKey alloc] init];
679 [hotKey setName:@"UpcomingSongs"];
680 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
681 [hotKey setTarget:self];
682 [hotKey setAction:@selector(showUpcomingSongs)];
683 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
686 if ([df objectForKey:@"ToggleLoop"] != nil) {
687 ITDebugLog(@"Setting up toggle loop hot key.");
688 hotKey = [[ITHotKey alloc] init];
689 [hotKey setName:@"ToggleLoop"];
690 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
691 [hotKey setTarget:self];
692 [hotKey setAction:@selector(toggleLoop)];
693 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
696 if ([df objectForKey:@"ToggleShuffle"] != nil) {
697 ITDebugLog(@"Setting up toggle shuffle hot key.");
698 hotKey = [[ITHotKey alloc] init];
699 [hotKey setName:@"ToggleShuffle"];
700 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
701 [hotKey setTarget:self];
702 [hotKey setAction:@selector(toggleShuffle)];
703 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
706 if ([df objectForKey:@"IncrementVolume"] != nil) {
707 ITDebugLog(@"Setting up increment volume hot key.");
708 hotKey = [[ITHotKey alloc] init];
709 [hotKey setName:@"IncrementVolume"];
710 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
711 [hotKey setTarget:self];
712 [hotKey setAction:@selector(incrementVolume)];
713 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
716 if ([df objectForKey:@"DecrementVolume"] != nil) {
717 ITDebugLog(@"Setting up decrement volume hot key.");
718 hotKey = [[ITHotKey alloc] init];
719 [hotKey setName:@"DecrementVolume"];
720 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
721 [hotKey setTarget:self];
722 [hotKey setAction:@selector(decrementVolume)];
723 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
726 if ([df objectForKey:@"IncrementRating"] != nil) {
727 ITDebugLog(@"Setting up increment rating hot key.");
728 hotKey = [[ITHotKey alloc] init];
729 [hotKey setName:@"IncrementRating"];
730 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
731 [hotKey setTarget:self];
732 [hotKey setAction:@selector(incrementRating)];
733 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
736 if ([df objectForKey:@"DecrementRating"] != nil) {
737 ITDebugLog(@"Setting up decrement rating hot key.");
738 hotKey = [[ITHotKey alloc] init];
739 [hotKey setName:@"DecrementRating"];
740 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
741 [hotKey setTarget:self];
742 [hotKey setAction:@selector(decrementRating)];
743 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
745 ITDebugLog(@"Finished setting up hot keys.");
748 - (void)showCurrentTrackInfo
750 ITMTRemotePlayerSource source = 0;
751 NSString *title = nil;
752 NSString *album = nil;
753 NSString *artist = nil;
754 NSString *time = nil;
755 NSString *track = nil;
760 source = [[self currentRemote] currentSource];
761 title = [[self currentRemote] currentSongTitle];
763 [self networkError:localException];
766 ITDebugLog(@"Showing track info status window.");
770 if ( [df boolForKey:@"showAlbum"] ) {
772 album = [[self currentRemote] currentSongAlbum];
774 [self networkError:localException];
778 if ( [df boolForKey:@"showArtist"] ) {
780 artist = [[self currentRemote] currentSongArtist];
782 [self networkError:localException];
786 if ( [df boolForKey:@"showTime"] ) {
788 time = [NSString stringWithFormat:@"%@: %@ / %@",
790 [[self currentRemote] currentSongElapsed],
791 [[self currentRemote] currentSongLength]];
793 [self networkError:localException];
797 if ( [df boolForKey:@"showTrackNumber"] ) {
802 trackNo = [[self currentRemote] currentSongTrack];
803 trackCount = [[self currentRemote] currentAlbumTrackCount];
805 [self networkError:localException];
808 if ( (trackNo > 0) || (trackCount > 0) ) {
809 track = [NSString stringWithFormat:@"%@: %i %@ %i",
810 @"Track", trackNo, @"of", trackCount];
814 if ( [df boolForKey:@"showTrackRating"] ) {
815 float currentRating = 0;
818 currentRating = [[self currentRemote] currentSongRating];
820 [self networkError:localException];
823 if (currentRating >= 0.0) {
824 rating = ( currentRating * 5 );
828 if ( [df boolForKey:@"showAlbumArtwork"] ) {
829 NSSize oldSize, newSize;
831 art = [[self currentRemote] currentSongAlbumArt];
832 oldSize = [art size];
833 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
834 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
835 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
837 [self networkError:localException];
842 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
844 [statusWindowController showSongInfoWindowWithSource:source
854 - (void)showUpcomingSongs
858 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
860 [self networkError:localException];
863 ITDebugLog(@"Showing upcoming songs status window.");
866 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
867 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
868 int curTrack = [[self currentRemote] currentSongIndex];
871 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
873 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
877 if ([songList count] == 0) {
878 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
881 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
883 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
886 [self networkError:localException];
890 - (void)incrementVolume
893 float volume = [[self currentRemote] volume];
894 float dispVol = volume;
895 ITDebugLog(@"Incrementing volume.");
904 ITDebugLog(@"Setting volume to %f", volume);
905 [[self currentRemote] setVolume:volume];
907 // Show volume status window
908 [statusWindowController showVolumeWindowWithLevel:dispVol];
910 [self networkError:localException];
914 - (void)decrementVolume
917 float volume = [[self currentRemote] volume];
918 float dispVol = volume;
919 ITDebugLog(@"Decrementing volume.");
928 ITDebugLog(@"Setting volume to %f", volume);
929 [[self currentRemote] setVolume:volume];
931 //Show volume status window
932 [statusWindowController showVolumeWindowWithLevel:dispVol];
934 [self networkError:localException];
938 - (void)incrementRating
941 float rating = [[self currentRemote] currentSongRating];
942 ITDebugLog(@"Incrementing rating.");
944 if ([[self currentRemote] currentPlaylistIndex] == 0) {
945 ITDebugLog(@"No song playing, rating change aborted.");
953 ITDebugLog(@"Setting rating to %f", rating);
954 [[self currentRemote] setCurrentSongRating:rating];
956 //Show rating status window
957 [statusWindowController showRatingWindowWithRating:rating];
959 [self networkError:localException];
963 - (void)decrementRating
966 float rating = [[self currentRemote] currentSongRating];
967 ITDebugLog(@"Decrementing rating.");
969 if ([[self currentRemote] currentPlaylistIndex] == 0) {
970 ITDebugLog(@"No song playing, rating change aborted.");
978 ITDebugLog(@"Setting rating to %f", rating);
979 [[self currentRemote] setCurrentSongRating:rating];
981 //Show rating status window
982 [statusWindowController showRatingWindowWithRating:rating];
984 [self networkError:localException];
991 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
992 ITDebugLog(@"Toggling repeat mode.");
993 switch (repeatMode) {
994 case ITMTRemotePlayerRepeatOff:
995 repeatMode = ITMTRemotePlayerRepeatAll;
997 case ITMTRemotePlayerRepeatAll:
998 repeatMode = ITMTRemotePlayerRepeatOne;
1000 case ITMTRemotePlayerRepeatOne:
1001 repeatMode = ITMTRemotePlayerRepeatOff;
1004 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1005 [[self currentRemote] setRepeatMode:repeatMode];
1007 //Show loop status window
1008 [statusWindowController showRepeatWindowWithMode:repeatMode];
1010 [self networkError:localException];
1014 - (void)toggleShuffle
1017 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1018 ITDebugLog(@"Toggling shuffle mode.");
1019 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1020 //Show shuffle status window
1021 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1022 [statusWindowController showShuffleWindow:newShuffleEnabled];
1024 [self networkError:localException];
1028 - (void)registerNowOK
1030 [[StatusWindow sharedWindow] setLocked:NO];
1031 [[StatusWindow sharedWindow] vanish:self];
1032 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1037 - (void)registerNowCancel
1039 [[StatusWindow sharedWindow] setLocked:NO];
1040 [[StatusWindow sharedWindow] vanish:self];
1041 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1043 [NSApp terminate:self];
1046 /*************************************************************************/
1048 #pragma mark NETWORK HANDLERS
1049 /*************************************************************************/
1051 - (void)setServerStatus:(BOOL)newStatus
1055 [networkController setServerStatus:YES];
1058 [networkController setServerStatus:NO];
1062 - (int)connectToServer
1065 ITDebugLog(@"Attempting to connect to shared remote.");
1066 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1069 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1070 currentRemote = [[[networkController networkObject] remote] retain];
1071 [refreshTimer invalidate];
1072 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1074 selector:@selector(timerUpdate)
1076 repeats:YES] retain];
1078 ITDebugLog(@"Connection successful.");
1080 } else if (result == 0) {
1081 ITDebugLog(@"Connection failed.");
1082 currentRemote = [remoteArray objectAtIndex:0];
1085 //Do something about the password being invalid
1086 ITDebugLog(@"Connection failed.");
1087 currentRemote = [remoteArray objectAtIndex:0];
1092 - (BOOL)disconnectFromServer
1094 ITDebugLog(@"Disconnecting from shared remote.");
1096 [currentRemote release];
1097 currentRemote = [remoteArray objectAtIndex:0];
1098 [networkController disconnect];
1103 - (void)checkForRemoteServer:(NSTimer *)timer
1105 ITDebugLog(@"Checking for remote server.");
1106 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1107 ITDebugLog(@"Remote server found.");
1109 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1110 [[StatusWindowController sharedController] showReconnectQueryWindow];
1113 ITDebugLog(@"Remote server not found.");
1117 - (void)networkError:(NSException *)exception
1119 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1120 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1121 NSRunCriticalAlertPanel(@"Remote MenuTunes Disconnected", @"The MenuTunes server you were connected to stopped responding or quit. MenuTunes will revert back to the local player.", @"OK", nil, nil);
1122 if ([self disconnectFromServer]) {
1123 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1124 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1126 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1133 if ([self connectToServer] == 0) {
1134 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1136 [[StatusWindow sharedWindow] setLocked:NO];
1137 [[StatusWindow sharedWindow] vanish:self];
1138 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1141 - (void)cancelReconnect
1143 [[StatusWindow sharedWindow] setLocked:NO];
1144 [[StatusWindow sharedWindow] vanish:self];
1145 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1148 /*************************************************************************/
1150 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1151 /*************************************************************************/
1153 - (void)applicationLaunched:(NSNotification *)note
1156 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1157 ITDebugLog(@"Remote application launched.");
1158 playerRunningState = ITMTRemotePlayerRunning;
1159 [[self currentRemote] begin];
1160 [self setLatestSongIdentifier:@""];
1162 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1164 selector:@selector(timerUpdate)
1166 repeats:YES] retain];
1167 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1168 [self setupHotKeys];
1171 [self networkError:localException];
1175 - (void)applicationTerminated:(NSNotification *)note
1178 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1179 ITDebugLog(@"Remote application terminated.");
1180 playerRunningState = ITMTRemotePlayerNotRunning;
1181 [[self currentRemote] halt];
1182 [refreshTimer invalidate];
1183 [refreshTimer release];
1185 [self clearHotKeys];
1187 if ([df objectForKey:@"ShowPlayer"] != nil) {
1189 ITDebugLog(@"Setting up show player hot key.");
1190 hotKey = [[ITHotKey alloc] init];
1191 [hotKey setName:@"ShowPlayer"];
1192 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1193 [hotKey setTarget:self];
1194 [hotKey setAction:@selector(showPlayer)];
1195 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1199 [self networkError:localException];
1204 /*************************************************************************/
1206 #pragma mark NSApplication DELEGATE METHODS
1207 /*************************************************************************/
1209 - (void)applicationWillTerminate:(NSNotification *)note
1211 [networkController stopRemoteServerSearch];
1212 [self clearHotKeys];
1213 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1217 /*************************************************************************/
1219 #pragma mark DEALLOCATION METHOD
1220 /*************************************************************************/
1224 [self applicationTerminated:nil];
1226 [statusItem release];
1227 [statusWindowController release];
1228 [menuController release];
1229 [networkController release];