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;
40 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
41 - (void)applicationLaunched:(NSNotification *)note;
42 - (void)applicationTerminated:(NSNotification *)note;
45 static MainController *sharedController;
47 @implementation MainController
49 + (MainController *)sharedController
51 return sharedController;
54 /*************************************************************************/
56 #pragma mark INITIALIZATION/DEALLOCATION METHODS
57 /*************************************************************************/
61 if ( ( self = [super init] ) ) {
62 sharedController = self;
64 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
65 [[PreferencesController sharedPrefs] setController:self];
66 statusWindowController = [StatusWindowController sharedController];
67 menuController = [[MenuController alloc] init];
68 df = [[NSUserDefaults standardUserDefaults] retain];
75 - (void)applicationDidFinishLaunching:(NSNotification *)note
77 //Turn on debug mode if needed
78 if ([df boolForKey:@"ITDebugMode"]) {
82 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
83 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
85 [[PreferencesController sharedPrefs] registerDefaults];
86 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
89 currentRemote = [self loadRemote];
90 [[self currentRemote] begin];
92 //Turn on network stuff if needed
93 networkController = [[NetworkController alloc] init];
94 if ([df boolForKey:@"enableSharing"]) {
95 [self setServerStatus:YES];
96 } else if ([df boolForKey:@"useSharedPlayer"]) {
97 if ([self connectToServer] == 0) {
98 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
102 //Setup for notification of the remote player launching or quitting
103 [[[NSWorkspace sharedWorkspace] notificationCenter]
105 selector:@selector(applicationTerminated:)
106 name:NSWorkspaceDidTerminateApplicationNotification
109 [[[NSWorkspace sharedWorkspace] notificationCenter]
111 selector:@selector(applicationLaunched:)
112 name:NSWorkspaceDidLaunchApplicationNotification
115 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
116 [[PreferencesController sharedPrefs] registerDefaults];
119 if ([df boolForKey:@"ITMTNoStatusItem"]) {
122 [StatusItemHack install];
123 statusItem = [[ITStatusItem alloc]
124 initWithStatusBar:[NSStatusBar systemStatusBar]
125 withLength:NSSquareStatusItemLength];
128 bling = [[MTBlingController alloc] init];
130 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
132 selector:@selector(blingTime)
134 repeats:YES] retain];
137 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
138 [self applicationLaunched:nil];
140 if ([df boolForKey:@"LaunchPlayerWithMT"])
143 [self applicationTerminated:nil];
146 [self networkError:localException];
149 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
150 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
152 [networkController startRemoteServerSearch];
156 - (ITMTRemote *)loadRemote
158 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
159 ITDebugLog(@"Gathering remotes.");
161 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
162 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
163 NSString *bundlePath;
165 while ( (bundlePath = [enumerator nextObject]) ) {
166 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
169 Class remoteClass = [remoteBundle principalClass];
171 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
172 [remoteClass isKindOfClass:[NSObject class]]) {
173 id remote = [remoteClass remote];
174 ITDebugLog(@"Adding remote at path %@", bundlePath);
175 [remoteArray addObject:remote];
180 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
181 // if ( [remoteArray count] > 1 ) {
182 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
184 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
187 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
188 return [remoteArray objectAtIndex:0];
191 /*************************************************************************/
193 #pragma mark INSTANCE METHODS
194 /*************************************************************************/
196 /*- (void)startTimerInNewThread
198 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
199 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
200 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
202 selector:@selector(timerUpdate)
204 repeats:YES] retain];
206 ITDebugLog(@"Timer started.");
210 - (void)setBlingTime:(NSDate*)date
212 NSMutableDictionary *globalPrefs;
214 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
216 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
218 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
220 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
222 [globalPrefs release];
225 - (NSDate*)getBlingTime
228 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
233 NSDate *now = [NSDate date];
234 if (![self blingBling]) {
235 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
236 [self setBlingTime:now];
238 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
240 [statusItem setEnabled:NO];
242 if ([refreshTimer isValid]) {
243 [refreshTimer invalidate];
245 [statusWindowController showRegistrationQueryWindow];
249 [statusItem setEnabled:YES];
251 if (![refreshTimer isValid]) {
252 [refreshTimer release];
253 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
255 selector:@selector(timerUpdate)
257 repeats:YES] retain];
261 [self setBlingTime:nil];
272 if ( ! ([bling checkDone] == 2475) ) {
279 - (BOOL)songIsPlaying
281 NSString *identifier = nil;
283 identifier = [[self currentRemote] playerStateUniqueIdentifier];
285 [self networkError:localException];
287 return ( ! ([identifier isEqualToString:@"0-0"]) );
290 - (BOOL)radioIsPlaying
292 ITMTRemotePlayerPlaylistClass class = nil;
294 class = [[self currentRemote] currentPlaylistClass];
296 [self networkError:localException];
298 return (class == ITMTRemotePlayerRadioPlaylist );
303 NSString *identifier = nil;
305 identifier = [[self currentRemote] playerStateUniqueIdentifier];
307 [self networkError:localException];
309 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
312 - (NSString *)latestSongIdentifier
314 return _latestSongIdentifier;
317 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
319 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
320 [_latestSongIdentifier autorelease];
321 _latestSongIdentifier = [newIdentifier copy];
326 if ([networkController isConnectedToServer]) {
327 [statusItem setMenu:[menuController menu]];
330 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
331 ITDebugLog(@"The song changed.");
333 if ([df boolForKey:@"runScripts"] && [[self currentRemote] currentSongTitle]) {
334 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
335 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
336 NSString *nextScript;
337 while ( (nextScript = [scriptsEnum nextObject]) ) {
339 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
340 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
341 ITDebugLog(@"Error running script %@.", nextScript);
343 [currentScript release];
350 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
351 [menuController rebuildSubmenus];
353 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
354 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
357 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
359 NSString *artist = [[self currentRemote] currentSongArtist];
360 NSString *title = [[self currentRemote] currentSongTitle];
363 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
367 toolTip = @"No Song Playing";
369 [statusItem setToolTip:toolTip];
371 [self networkError:localException];
380 ITDebugLog(@"Menu clicked.");
381 if ([networkController isConnectedToServer]) {
382 //Used the cached version
387 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
388 [statusItem setMenu:[menuController menu]];
390 [statusItem setMenu:[menuController menuForNoPlayer]];
393 [self networkError:localException];
406 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
407 ITDebugLog(@"Play/Pause toggled");
408 if (state == ITMTRemotePlayerPlaying) {
409 [[self currentRemote] pause];
410 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
411 [[self currentRemote] pause];
412 [[self currentRemote] play];
414 [[self currentRemote] play];
417 [self networkError:localException];
425 ITDebugLog(@"Going to next song.");
427 [[self currentRemote] goToNextSong];
429 [self networkError:localException];
436 ITDebugLog(@"Going to previous song.");
438 [[self currentRemote] goToPreviousSong];
440 [self networkError:localException];
447 ITDebugLog(@"Fast forwarding.");
449 [[self currentRemote] forward];
451 [self networkError:localException];
458 ITDebugLog(@"Rewinding.");
460 [[self currentRemote] rewind];
462 [self networkError:localException];
467 - (void)selectPlaylistAtIndex:(int)index
469 ITDebugLog(@"Selecting playlist %i", index);
471 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
472 //[[self currentRemote] switchToPlaylistAtIndex:index];
474 [self networkError:localException];
479 - (void)selectSongAtIndex:(int)index
481 ITDebugLog(@"Selecting song %i", index);
483 [[self currentRemote] switchToSongAtIndex:index];
485 [self networkError:localException];
490 - (void)selectSongRating:(int)rating
492 ITDebugLog(@"Selecting song rating %i", rating);
494 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
496 [self networkError:localException];
501 - (void)selectEQPresetAtIndex:(int)index
503 ITDebugLog(@"Selecting EQ preset %i", index);
505 [[self currentRemote] switchToEQAtIndex:index];
507 [self networkError:localException];
514 ITDebugLog(@"Beginning show player.");
515 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
516 ITDebugLog(@"Showing player interface.");
518 [[self currentRemote] showPrimaryInterface];
520 [self networkError:localException];
523 ITDebugLog(@"Launching player.");
526 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
528 path = [[self currentRemote] playerFullName];
530 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
531 ITDebugLog(@"Error Launching Player");
534 [self networkError:localException];
537 ITDebugLog(@"Finished show player.");
540 - (void)showPreferences
542 ITDebugLog(@"Show preferences.");
543 [[PreferencesController sharedPrefs] showPrefsWindow:self];
546 - (void)showPreferencesAndClose
548 ITDebugLog(@"Show preferences.");
549 [[PreferencesController sharedPrefs] showPrefsWindow:self];
550 [[StatusWindow sharedWindow] setLocked:NO];
551 [[StatusWindow sharedWindow] vanish:self];
552 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
555 - (void)showTestWindow
557 [self showCurrentTrackInfo];
560 - (void)quitMenuTunes
562 ITDebugLog(@"Quitting MenuTunes.");
563 [NSApp terminate:self];
569 - (void)closePreferences
571 ITDebugLog(@"Preferences closed.");
572 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
577 - (ITMTRemote *)currentRemote
579 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
580 [self networkError:nil];
583 return currentRemote;
594 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
595 ITHotKey *nextHotKey;
596 ITDebugLog(@"Clearing hot keys.");
597 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
598 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
600 ITDebugLog(@"Done clearing hot keys.");
606 ITDebugLog(@"Setting up hot keys.");
608 if (playerRunningState == ITMTRemotePlayerNotRunning) {
612 if ([df objectForKey:@"PlayPause"] != nil) {
613 ITDebugLog(@"Setting up play pause hot key.");
614 hotKey = [[ITHotKey alloc] init];
615 [hotKey setName:@"PlayPause"];
616 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
617 [hotKey setTarget:self];
618 [hotKey setAction:@selector(playPause)];
619 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
622 if ([df objectForKey:@"NextTrack"] != nil) {
623 ITDebugLog(@"Setting up next track hot key.");
624 hotKey = [[ITHotKey alloc] init];
625 [hotKey setName:@"NextTrack"];
626 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
627 [hotKey setTarget:self];
628 [hotKey setAction:@selector(nextSong)];
629 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
632 if ([df objectForKey:@"PrevTrack"] != nil) {
633 ITDebugLog(@"Setting up previous track hot key.");
634 hotKey = [[ITHotKey alloc] init];
635 [hotKey setName:@"PrevTrack"];
636 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
637 [hotKey setTarget:self];
638 [hotKey setAction:@selector(prevSong)];
639 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
642 if ([df objectForKey:@"ShowPlayer"] != nil) {
643 ITDebugLog(@"Setting up show player hot key.");
644 hotKey = [[ITHotKey alloc] init];
645 [hotKey setName:@"ShowPlayer"];
646 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
647 [hotKey setTarget:self];
648 [hotKey setAction:@selector(showPlayer)];
649 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
652 if ([df objectForKey:@"TrackInfo"] != nil) {
653 ITDebugLog(@"Setting up track info hot key.");
654 hotKey = [[ITHotKey alloc] init];
655 [hotKey setName:@"TrackInfo"];
656 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
657 [hotKey setTarget:self];
658 [hotKey setAction:@selector(showCurrentTrackInfo)];
659 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
662 if ([df objectForKey:@"UpcomingSongs"] != nil) {
663 ITDebugLog(@"Setting up upcoming songs hot key.");
664 hotKey = [[ITHotKey alloc] init];
665 [hotKey setName:@"UpcomingSongs"];
666 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
667 [hotKey setTarget:self];
668 [hotKey setAction:@selector(showUpcomingSongs)];
669 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
672 if ([df objectForKey:@"ToggleLoop"] != nil) {
673 ITDebugLog(@"Setting up toggle loop hot key.");
674 hotKey = [[ITHotKey alloc] init];
675 [hotKey setName:@"ToggleLoop"];
676 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
677 [hotKey setTarget:self];
678 [hotKey setAction:@selector(toggleLoop)];
679 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
682 if ([df objectForKey:@"ToggleShuffle"] != nil) {
683 ITDebugLog(@"Setting up toggle shuffle hot key.");
684 hotKey = [[ITHotKey alloc] init];
685 [hotKey setName:@"ToggleShuffle"];
686 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
687 [hotKey setTarget:self];
688 [hotKey setAction:@selector(toggleShuffle)];
689 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
692 if ([df objectForKey:@"IncrementVolume"] != nil) {
693 ITDebugLog(@"Setting up increment volume hot key.");
694 hotKey = [[ITHotKey alloc] init];
695 [hotKey setName:@"IncrementVolume"];
696 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
697 [hotKey setTarget:self];
698 [hotKey setAction:@selector(incrementVolume)];
699 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
702 if ([df objectForKey:@"DecrementVolume"] != nil) {
703 ITDebugLog(@"Setting up decrement volume hot key.");
704 hotKey = [[ITHotKey alloc] init];
705 [hotKey setName:@"DecrementVolume"];
706 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
707 [hotKey setTarget:self];
708 [hotKey setAction:@selector(decrementVolume)];
709 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
712 if ([df objectForKey:@"IncrementRating"] != nil) {
713 ITDebugLog(@"Setting up increment rating hot key.");
714 hotKey = [[ITHotKey alloc] init];
715 [hotKey setName:@"IncrementRating"];
716 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
717 [hotKey setTarget:self];
718 [hotKey setAction:@selector(incrementRating)];
719 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
722 if ([df objectForKey:@"DecrementRating"] != nil) {
723 ITDebugLog(@"Setting up decrement rating hot key.");
724 hotKey = [[ITHotKey alloc] init];
725 [hotKey setName:@"DecrementRating"];
726 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
727 [hotKey setTarget:self];
728 [hotKey setAction:@selector(decrementRating)];
729 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
731 ITDebugLog(@"Finished setting up hot keys.");
734 - (void)showCurrentTrackInfo
736 ITMTRemotePlayerSource source = 0;
737 NSString *title = nil;
738 NSString *album = nil;
739 NSString *artist = nil;
740 NSString *time = nil;
741 NSString *track = nil;
746 source = [[self currentRemote] currentSource];
747 title = [[self currentRemote] currentSongTitle];
749 [self networkError:localException];
752 ITDebugLog(@"Showing track info status window.");
756 if ( [df boolForKey:@"showAlbum"] ) {
758 album = [[self currentRemote] currentSongAlbum];
760 [self networkError:localException];
764 if ( [df boolForKey:@"showArtist"] ) {
766 artist = [[self currentRemote] currentSongArtist];
768 [self networkError:localException];
772 if ( [df boolForKey:@"showTime"] ) {
774 time = [NSString stringWithFormat:@"%@: %@ / %@",
776 [[self currentRemote] currentSongElapsed],
777 [[self currentRemote] currentSongLength]];
779 [self networkError:localException];
783 if ( [df boolForKey:@"showTrackNumber"] ) {
788 trackNo = [[self currentRemote] currentSongTrack];
789 trackCount = [[self currentRemote] currentAlbumTrackCount];
791 [self networkError:localException];
794 if ( (trackNo > 0) || (trackCount > 0) ) {
795 track = [NSString stringWithFormat:@"%@: %i %@ %i",
796 @"Track", trackNo, @"of", trackCount];
800 if ( [df boolForKey:@"showTrackRating"] ) {
801 float currentRating = 0;
804 currentRating = [[self currentRemote] currentSongRating];
806 [self networkError:localException];
809 if (currentRating >= 0.0) {
810 rating = ( currentRating * 5 );
814 if ( [df boolForKey:@"showAlbumArtwork"] ) {
816 art = [[self currentRemote] currentSongAlbumArt];
817 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:NSMakeSize(110,110)];
819 [self networkError:localException];
824 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
826 [statusWindowController showSongInfoWindowWithSource:source
836 - (void)showUpcomingSongs
840 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
842 [self networkError:localException];
845 ITDebugLog(@"Showing upcoming songs status window.");
848 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
849 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
850 int curTrack = [[self currentRemote] currentSongIndex];
853 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
855 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
859 if ([songList count] == 0) {
860 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
863 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
865 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
868 [self networkError:localException];
872 - (void)incrementVolume
875 float volume = [[self currentRemote] volume];
876 float dispVol = volume;
877 ITDebugLog(@"Incrementing volume.");
886 ITDebugLog(@"Setting volume to %f", volume);
887 [[self currentRemote] setVolume:volume];
889 // Show volume status window
890 [statusWindowController showVolumeWindowWithLevel:dispVol];
892 [self networkError:localException];
896 - (void)decrementVolume
899 float volume = [[self currentRemote] volume];
900 float dispVol = volume;
901 ITDebugLog(@"Decrementing volume.");
910 ITDebugLog(@"Setting volume to %f", volume);
911 [[self currentRemote] setVolume:volume];
913 //Show volume status window
914 [statusWindowController showVolumeWindowWithLevel:dispVol];
916 [self networkError:localException];
920 - (void)incrementRating
923 float rating = [[self currentRemote] currentSongRating];
924 ITDebugLog(@"Incrementing rating.");
926 if ([[self currentRemote] currentPlaylistIndex] == 0) {
927 ITDebugLog(@"No song playing, rating change aborted.");
935 ITDebugLog(@"Setting rating to %f", rating);
936 [[self currentRemote] setCurrentSongRating:rating];
938 //Show rating status window
939 [statusWindowController showRatingWindowWithRating:rating];
941 [self networkError:localException];
945 - (void)decrementRating
948 float rating = [[self currentRemote] currentSongRating];
949 ITDebugLog(@"Decrementing rating.");
951 if ([[self currentRemote] currentPlaylistIndex] == 0) {
952 ITDebugLog(@"No song playing, rating change aborted.");
960 ITDebugLog(@"Setting rating to %f", rating);
961 [[self currentRemote] setCurrentSongRating:rating];
963 //Show rating status window
964 [statusWindowController showRatingWindowWithRating:rating];
966 [self networkError:localException];
973 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
974 ITDebugLog(@"Toggling repeat mode.");
975 switch (repeatMode) {
976 case ITMTRemotePlayerRepeatOff:
977 repeatMode = ITMTRemotePlayerRepeatAll;
979 case ITMTRemotePlayerRepeatAll:
980 repeatMode = ITMTRemotePlayerRepeatOne;
982 case ITMTRemotePlayerRepeatOne:
983 repeatMode = ITMTRemotePlayerRepeatOff;
986 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
987 [[self currentRemote] setRepeatMode:repeatMode];
989 //Show loop status window
990 [statusWindowController showRepeatWindowWithMode:repeatMode];
992 [self networkError:localException];
996 - (void)toggleShuffle
999 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1000 ITDebugLog(@"Toggling shuffle mode.");
1001 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1002 //Show shuffle status window
1003 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1004 [statusWindowController showShuffleWindow:newShuffleEnabled];
1006 [self networkError:localException];
1010 - (void)registerNowOK
1012 [[StatusWindow sharedWindow] setLocked:NO];
1013 [[StatusWindow sharedWindow] vanish:self];
1014 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1019 - (void)registerNowCancel
1021 [[StatusWindow sharedWindow] setLocked:NO];
1022 [[StatusWindow sharedWindow] vanish:self];
1023 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1025 [NSApp terminate:self];
1028 /*************************************************************************/
1030 #pragma mark NETWORK HANDLERS
1031 /*************************************************************************/
1033 - (void)setServerStatus:(BOOL)newStatus
1037 [networkController setServerStatus:YES];
1040 [networkController setServerStatus:NO];
1044 - (int)connectToServer
1047 ITDebugLog(@"Attempting to connect to shared remote.");
1048 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1051 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1052 currentRemote = [[[networkController networkObject] remote] retain];
1053 [refreshTimer invalidate];
1054 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1056 selector:@selector(timerUpdate)
1058 repeats:YES] retain];
1060 ITDebugLog(@"Connection successful.");
1062 } else if (result == 0) {
1063 ITDebugLog(@"Connection failed.");
1064 currentRemote = [remoteArray objectAtIndex:0];
1067 //Do something about the password being invalid
1068 ITDebugLog(@"Connection failed.");
1069 currentRemote = [remoteArray objectAtIndex:0];
1074 - (BOOL)disconnectFromServer
1076 ITDebugLog(@"Disconnecting from shared remote.");
1078 [currentRemote release];
1079 currentRemote = [remoteArray objectAtIndex:0];
1080 [networkController disconnect];
1085 - (void)checkForRemoteServer:(NSTimer *)timer
1087 ITDebugLog(@"Checking for remote server.");
1088 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1089 ITDebugLog(@"Remote server found.");
1091 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1092 [[StatusWindowController sharedController] showReconnectQueryWindow];
1095 ITDebugLog(@"Remote server not found.");
1099 - (void)networkError:(NSException *)exception
1101 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1102 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1103 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);
1104 if ([self disconnectFromServer]) {
1105 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1106 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1108 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1115 if ([self connectToServer] == 0) {
1116 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1118 [[StatusWindow sharedWindow] setLocked:NO];
1119 [[StatusWindow sharedWindow] vanish:self];
1120 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1123 - (void)cancelReconnect
1125 [[StatusWindow sharedWindow] setLocked:NO];
1126 [[StatusWindow sharedWindow] vanish:self];
1127 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1130 /*************************************************************************/
1132 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1133 /*************************************************************************/
1135 - (void)applicationLaunched:(NSNotification *)note
1138 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1139 ITDebugLog(@"Remote application launched.");
1140 playerRunningState = ITMTRemotePlayerRunning;
1141 [[self currentRemote] begin];
1142 [self setLatestSongIdentifier:@""];
1144 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1146 selector:@selector(timerUpdate)
1148 repeats:YES] retain];
1149 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1150 [self setupHotKeys];
1153 [self networkError:localException];
1157 - (void)applicationTerminated:(NSNotification *)note
1160 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1161 ITDebugLog(@"Remote application terminated.");
1162 playerRunningState = ITMTRemotePlayerNotRunning;
1163 [[self currentRemote] halt];
1164 [refreshTimer invalidate];
1165 [refreshTimer release];
1167 [self clearHotKeys];
1169 if ([df objectForKey:@"ShowPlayer"] != nil) {
1171 ITDebugLog(@"Setting up show player hot key.");
1172 hotKey = [[ITHotKey alloc] init];
1173 [hotKey setName:@"ShowPlayer"];
1174 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1175 [hotKey setTarget:self];
1176 [hotKey setAction:@selector(showPlayer)];
1177 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1181 [self networkError:localException];
1186 /*************************************************************************/
1188 #pragma mark NSApplication DELEGATE METHODS
1189 /*************************************************************************/
1191 - (void)applicationWillTerminate:(NSNotification *)note
1193 [networkController stopRemoteServerSearch];
1194 [self clearHotKeys];
1195 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1199 /*************************************************************************/
1201 #pragma mark DEALLOCATION METHOD
1202 /*************************************************************************/
1206 [self applicationTerminated:nil];
1208 [statusItem release];
1209 [statusWindowController release];
1210 [menuController release];
1211 [networkController release];