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"];
217 [globalPrefs setObject:[NSNumber numberWithInt:1200] forKey:@"ITMTTrialVers"];
219 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
220 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
222 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
224 [globalPrefs release];
227 - (NSDate*)getBlingTime
230 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
235 NSDate *now = [NSDate date];
236 if (![self blingBling]) {
237 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
238 [self setBlingTime:now];
239 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < 1200) {
240 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
241 [self setBlingTime:[now addTimeInterval:-259200]];
243 NSMutableDictionary *globalPrefs;
245 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
246 [globalPrefs setObject:[NSNumber numberWithInt:1200] forKey:@"ITMTTrialVers"];
247 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
249 [globalPrefs release];
253 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
255 [statusItem setEnabled:NO];
257 if ([refreshTimer isValid]) {
258 [refreshTimer invalidate];
260 [statusWindowController showRegistrationQueryWindow];
264 [statusItem setEnabled:YES];
266 if (![refreshTimer isValid]) {
267 [refreshTimer release];
268 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
270 selector:@selector(timerUpdate)
272 repeats:YES] retain];
276 [self setBlingTime:nil];
287 if ( ! ([bling checkDone] == 2475) ) {
294 - (BOOL)songIsPlaying
296 NSString *identifier = nil;
298 identifier = [[self currentRemote] playerStateUniqueIdentifier];
300 [self networkError:localException];
302 return ( ! ([identifier isEqualToString:@"0-0"]) );
305 - (BOOL)radioIsPlaying
307 ITMTRemotePlayerPlaylistClass class = nil;
309 class = [[self currentRemote] currentPlaylistClass];
311 [self networkError:localException];
313 return (class == ITMTRemotePlayerRadioPlaylist );
318 NSString *identifier = nil;
320 identifier = [[self currentRemote] playerStateUniqueIdentifier];
322 [self networkError:localException];
324 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
327 - (NSString *)latestSongIdentifier
329 return _latestSongIdentifier;
332 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
334 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
335 [_latestSongIdentifier autorelease];
336 _latestSongIdentifier = [newIdentifier copy];
341 if ([networkController isConnectedToServer]) {
342 [statusItem setMenu:[menuController menu]];
345 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
346 ITDebugLog(@"The song changed.");
348 if ([df boolForKey:@"runScripts"]) {
349 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
350 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
351 NSString *nextScript;
352 while ( (nextScript = [scriptsEnum nextObject]) ) {
354 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
355 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
356 ITDebugLog(@"Error running script %@.", nextScript);
358 [currentScript release];
365 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
366 [menuController rebuildSubmenus];
368 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
369 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
372 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
374 NSString *artist = [[self currentRemote] currentSongArtist];
375 NSString *title = [[self currentRemote] currentSongTitle];
378 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
382 toolTip = @"No Song Playing";
384 [statusItem setToolTip:toolTip];
386 [self networkError:localException];
395 ITDebugLog(@"Menu clicked.");
396 if ([networkController isConnectedToServer]) {
397 //Used the cached version
402 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
403 [statusItem setMenu:[menuController menu]];
405 [statusItem setMenu:[menuController menuForNoPlayer]];
408 [self networkError:localException];
421 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
422 ITDebugLog(@"Play/Pause toggled");
423 if (state == ITMTRemotePlayerPlaying) {
424 [[self currentRemote] pause];
425 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
426 [[self currentRemote] pause];
427 [[self currentRemote] play];
429 [[self currentRemote] play];
432 [self networkError:localException];
440 ITDebugLog(@"Going to next song.");
442 [[self currentRemote] goToNextSong];
444 [self networkError:localException];
451 ITDebugLog(@"Going to previous song.");
453 [[self currentRemote] goToPreviousSong];
455 [self networkError:localException];
462 ITDebugLog(@"Fast forwarding.");
464 [[self currentRemote] forward];
466 [self networkError:localException];
473 ITDebugLog(@"Rewinding.");
475 [[self currentRemote] rewind];
477 [self networkError:localException];
482 - (void)selectPlaylistAtIndex:(int)index
484 ITDebugLog(@"Selecting playlist %i", index);
486 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
487 //[[self currentRemote] switchToPlaylistAtIndex:index];
489 [self networkError:localException];
494 - (void)selectSongAtIndex:(int)index
496 ITDebugLog(@"Selecting song %i", index);
498 [[self currentRemote] switchToSongAtIndex:index];
500 [self networkError:localException];
505 - (void)selectSongRating:(int)rating
507 ITDebugLog(@"Selecting song rating %i", rating);
509 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
511 [self networkError:localException];
516 - (void)selectEQPresetAtIndex:(int)index
518 ITDebugLog(@"Selecting EQ preset %i", index);
520 [[self currentRemote] switchToEQAtIndex:index];
522 [self networkError:localException];
529 ITDebugLog(@"Beginning show player.");
530 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
531 ITDebugLog(@"Showing player interface.");
533 [[self currentRemote] showPrimaryInterface];
535 [self networkError:localException];
538 ITDebugLog(@"Launching player.");
541 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
543 path = [[self currentRemote] playerFullName];
545 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
546 ITDebugLog(@"Error Launching Player");
549 [self networkError:localException];
552 ITDebugLog(@"Finished show player.");
555 - (void)showPreferences
557 ITDebugLog(@"Show preferences.");
558 [[PreferencesController sharedPrefs] showPrefsWindow:self];
561 - (void)showPreferencesAndClose
563 ITDebugLog(@"Show preferences.");
564 [[PreferencesController sharedPrefs] showPrefsWindow:self];
565 [[StatusWindow sharedWindow] setLocked:NO];
566 [[StatusWindow sharedWindow] vanish:self];
567 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
570 - (void)showTestWindow
572 [self showCurrentTrackInfo];
575 - (void)quitMenuTunes
577 ITDebugLog(@"Quitting MenuTunes.");
578 [NSApp terminate:self];
584 - (void)closePreferences
586 ITDebugLog(@"Preferences closed.");
587 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
592 - (ITMTRemote *)currentRemote
594 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
595 [self networkError:nil];
598 return currentRemote;
609 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
610 ITHotKey *nextHotKey;
611 ITDebugLog(@"Clearing hot keys.");
612 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
613 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
615 ITDebugLog(@"Done clearing hot keys.");
621 ITDebugLog(@"Setting up hot keys.");
623 if (playerRunningState == ITMTRemotePlayerNotRunning) {
627 if ([df objectForKey:@"PlayPause"] != nil) {
628 ITDebugLog(@"Setting up play pause hot key.");
629 hotKey = [[ITHotKey alloc] init];
630 [hotKey setName:@"PlayPause"];
631 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
632 [hotKey setTarget:self];
633 [hotKey setAction:@selector(playPause)];
634 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
637 if ([df objectForKey:@"NextTrack"] != nil) {
638 ITDebugLog(@"Setting up next track hot key.");
639 hotKey = [[ITHotKey alloc] init];
640 [hotKey setName:@"NextTrack"];
641 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
642 [hotKey setTarget:self];
643 [hotKey setAction:@selector(nextSong)];
644 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
647 if ([df objectForKey:@"PrevTrack"] != nil) {
648 ITDebugLog(@"Setting up previous track hot key.");
649 hotKey = [[ITHotKey alloc] init];
650 [hotKey setName:@"PrevTrack"];
651 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
652 [hotKey setTarget:self];
653 [hotKey setAction:@selector(prevSong)];
654 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
657 if ([df objectForKey:@"ShowPlayer"] != nil) {
658 ITDebugLog(@"Setting up show player hot key.");
659 hotKey = [[ITHotKey alloc] init];
660 [hotKey setName:@"ShowPlayer"];
661 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
662 [hotKey setTarget:self];
663 [hotKey setAction:@selector(showPlayer)];
664 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
667 if ([df objectForKey:@"TrackInfo"] != nil) {
668 ITDebugLog(@"Setting up track info hot key.");
669 hotKey = [[ITHotKey alloc] init];
670 [hotKey setName:@"TrackInfo"];
671 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
672 [hotKey setTarget:self];
673 [hotKey setAction:@selector(showCurrentTrackInfo)];
674 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
677 if ([df objectForKey:@"UpcomingSongs"] != nil) {
678 ITDebugLog(@"Setting up upcoming songs hot key.");
679 hotKey = [[ITHotKey alloc] init];
680 [hotKey setName:@"UpcomingSongs"];
681 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
682 [hotKey setTarget:self];
683 [hotKey setAction:@selector(showUpcomingSongs)];
684 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
687 if ([df objectForKey:@"ToggleLoop"] != nil) {
688 ITDebugLog(@"Setting up toggle loop hot key.");
689 hotKey = [[ITHotKey alloc] init];
690 [hotKey setName:@"ToggleLoop"];
691 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
692 [hotKey setTarget:self];
693 [hotKey setAction:@selector(toggleLoop)];
694 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
697 if ([df objectForKey:@"ToggleShuffle"] != nil) {
698 ITDebugLog(@"Setting up toggle shuffle hot key.");
699 hotKey = [[ITHotKey alloc] init];
700 [hotKey setName:@"ToggleShuffle"];
701 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
702 [hotKey setTarget:self];
703 [hotKey setAction:@selector(toggleShuffle)];
704 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
707 if ([df objectForKey:@"IncrementVolume"] != nil) {
708 ITDebugLog(@"Setting up increment volume hot key.");
709 hotKey = [[ITHotKey alloc] init];
710 [hotKey setName:@"IncrementVolume"];
711 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
712 [hotKey setTarget:self];
713 [hotKey setAction:@selector(incrementVolume)];
714 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
717 if ([df objectForKey:@"DecrementVolume"] != nil) {
718 ITDebugLog(@"Setting up decrement volume hot key.");
719 hotKey = [[ITHotKey alloc] init];
720 [hotKey setName:@"DecrementVolume"];
721 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
722 [hotKey setTarget:self];
723 [hotKey setAction:@selector(decrementVolume)];
724 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
727 if ([df objectForKey:@"IncrementRating"] != nil) {
728 ITDebugLog(@"Setting up increment rating hot key.");
729 hotKey = [[ITHotKey alloc] init];
730 [hotKey setName:@"IncrementRating"];
731 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
732 [hotKey setTarget:self];
733 [hotKey setAction:@selector(incrementRating)];
734 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
737 if ([df objectForKey:@"DecrementRating"] != nil) {
738 ITDebugLog(@"Setting up decrement rating hot key.");
739 hotKey = [[ITHotKey alloc] init];
740 [hotKey setName:@"DecrementRating"];
741 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
742 [hotKey setTarget:self];
743 [hotKey setAction:@selector(decrementRating)];
744 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
746 ITDebugLog(@"Finished setting up hot keys.");
749 - (void)showCurrentTrackInfo
751 ITMTRemotePlayerSource source = 0;
752 NSString *title = nil;
753 NSString *album = nil;
754 NSString *artist = nil;
755 NSString *time = nil;
756 NSString *track = nil;
761 source = [[self currentRemote] currentSource];
762 title = [[self currentRemote] currentSongTitle];
764 [self networkError:localException];
767 ITDebugLog(@"Showing track info status window.");
771 if ( [df boolForKey:@"showAlbum"] ) {
773 album = [[self currentRemote] currentSongAlbum];
775 [self networkError:localException];
779 if ( [df boolForKey:@"showArtist"] ) {
781 artist = [[self currentRemote] currentSongArtist];
783 [self networkError:localException];
787 if ( [df boolForKey:@"showTime"] ) {
789 time = [NSString stringWithFormat:@"%@: %@ / %@",
791 [[self currentRemote] currentSongElapsed],
792 [[self currentRemote] currentSongLength]];
794 [self networkError:localException];
798 if ( [df boolForKey:@"showTrackNumber"] ) {
803 trackNo = [[self currentRemote] currentSongTrack];
804 trackCount = [[self currentRemote] currentAlbumTrackCount];
806 [self networkError:localException];
809 if ( (trackNo > 0) || (trackCount > 0) ) {
810 track = [NSString stringWithFormat:@"%@: %i %@ %i",
811 @"Track", trackNo, @"of", trackCount];
815 if ( [df boolForKey:@"showTrackRating"] ) {
816 float currentRating = 0;
819 currentRating = [[self currentRemote] currentSongRating];
821 [self networkError:localException];
824 if (currentRating >= 0.0) {
825 rating = ( currentRating * 5 );
829 if ( [df boolForKey:@"showAlbumArtwork"] ) {
830 NSSize oldSize, newSize;
832 art = [[self currentRemote] currentSongAlbumArt];
833 oldSize = [art size];
834 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
835 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
836 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
838 [self networkError:localException];
843 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
845 [statusWindowController showSongInfoWindowWithSource:source
855 - (void)showUpcomingSongs
859 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
861 [self networkError:localException];
864 ITDebugLog(@"Showing upcoming songs status window.");
867 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
868 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
869 int curTrack = [[self currentRemote] currentSongIndex];
872 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
874 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
878 if ([songList count] == 0) {
879 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
882 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
884 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
887 [self networkError:localException];
891 - (void)incrementVolume
894 float volume = [[self currentRemote] volume];
895 float dispVol = volume;
896 ITDebugLog(@"Incrementing volume.");
905 ITDebugLog(@"Setting volume to %f", volume);
906 [[self currentRemote] setVolume:volume];
908 // Show volume status window
909 [statusWindowController showVolumeWindowWithLevel:dispVol];
911 [self networkError:localException];
915 - (void)decrementVolume
918 float volume = [[self currentRemote] volume];
919 float dispVol = volume;
920 ITDebugLog(@"Decrementing volume.");
929 ITDebugLog(@"Setting volume to %f", volume);
930 [[self currentRemote] setVolume:volume];
932 //Show volume status window
933 [statusWindowController showVolumeWindowWithLevel:dispVol];
935 [self networkError:localException];
939 - (void)incrementRating
942 float rating = [[self currentRemote] currentSongRating];
943 ITDebugLog(@"Incrementing rating.");
945 if ([[self currentRemote] currentPlaylistIndex] == 0) {
946 ITDebugLog(@"No song playing, rating change aborted.");
954 ITDebugLog(@"Setting rating to %f", rating);
955 [[self currentRemote] setCurrentSongRating:rating];
957 //Show rating status window
958 [statusWindowController showRatingWindowWithRating:rating];
960 [self networkError:localException];
964 - (void)decrementRating
967 float rating = [[self currentRemote] currentSongRating];
968 ITDebugLog(@"Decrementing rating.");
970 if ([[self currentRemote] currentPlaylistIndex] == 0) {
971 ITDebugLog(@"No song playing, rating change aborted.");
979 ITDebugLog(@"Setting rating to %f", rating);
980 [[self currentRemote] setCurrentSongRating:rating];
982 //Show rating status window
983 [statusWindowController showRatingWindowWithRating:rating];
985 [self networkError:localException];
992 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
993 ITDebugLog(@"Toggling repeat mode.");
994 switch (repeatMode) {
995 case ITMTRemotePlayerRepeatOff:
996 repeatMode = ITMTRemotePlayerRepeatAll;
998 case ITMTRemotePlayerRepeatAll:
999 repeatMode = ITMTRemotePlayerRepeatOne;
1001 case ITMTRemotePlayerRepeatOne:
1002 repeatMode = ITMTRemotePlayerRepeatOff;
1005 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1006 [[self currentRemote] setRepeatMode:repeatMode];
1008 //Show loop status window
1009 [statusWindowController showRepeatWindowWithMode:repeatMode];
1011 [self networkError:localException];
1015 - (void)toggleShuffle
1018 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1019 ITDebugLog(@"Toggling shuffle mode.");
1020 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1021 //Show shuffle status window
1022 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1023 [statusWindowController showShuffleWindow:newShuffleEnabled];
1025 [self networkError:localException];
1029 - (void)registerNowOK
1031 [[StatusWindow sharedWindow] setLocked:NO];
1032 [[StatusWindow sharedWindow] vanish:self];
1033 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1038 - (void)registerNowCancel
1040 [[StatusWindow sharedWindow] setLocked:NO];
1041 [[StatusWindow sharedWindow] vanish:self];
1042 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1044 [NSApp terminate:self];
1047 /*************************************************************************/
1049 #pragma mark NETWORK HANDLERS
1050 /*************************************************************************/
1052 - (void)setServerStatus:(BOOL)newStatus
1056 [networkController setServerStatus:YES];
1059 [networkController setServerStatus:NO];
1063 - (int)connectToServer
1066 ITDebugLog(@"Attempting to connect to shared remote.");
1067 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1070 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1071 currentRemote = [[[networkController networkObject] remote] retain];
1072 [refreshTimer invalidate];
1073 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1075 selector:@selector(timerUpdate)
1077 repeats:YES] retain];
1079 ITDebugLog(@"Connection successful.");
1081 } else if (result == 0) {
1082 ITDebugLog(@"Connection failed.");
1083 currentRemote = [remoteArray objectAtIndex:0];
1086 //Do something about the password being invalid
1087 ITDebugLog(@"Connection failed.");
1088 currentRemote = [remoteArray objectAtIndex:0];
1093 - (BOOL)disconnectFromServer
1095 ITDebugLog(@"Disconnecting from shared remote.");
1097 [currentRemote release];
1098 currentRemote = [remoteArray objectAtIndex:0];
1099 [networkController disconnect];
1104 - (void)checkForRemoteServer:(NSTimer *)timer
1106 ITDebugLog(@"Checking for remote server.");
1107 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1108 ITDebugLog(@"Remote server found.");
1110 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1111 [[StatusWindowController sharedController] showReconnectQueryWindow];
1114 ITDebugLog(@"Remote server not found.");
1118 - (void)networkError:(NSException *)exception
1120 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1121 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1122 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);
1123 if ([self disconnectFromServer]) {
1124 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1125 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1127 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1134 if ([self connectToServer] == 0) {
1135 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1137 [[StatusWindow sharedWindow] setLocked:NO];
1138 [[StatusWindow sharedWindow] vanish:self];
1139 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1142 - (void)cancelReconnect
1144 [[StatusWindow sharedWindow] setLocked:NO];
1145 [[StatusWindow sharedWindow] vanish:self];
1146 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1149 /*************************************************************************/
1151 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1152 /*************************************************************************/
1154 - (void)applicationLaunched:(NSNotification *)note
1157 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1158 ITDebugLog(@"Remote application launched.");
1159 playerRunningState = ITMTRemotePlayerRunning;
1160 [[self currentRemote] begin];
1161 [self setLatestSongIdentifier:@""];
1163 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1165 selector:@selector(timerUpdate)
1167 repeats:YES] retain];
1168 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1169 [self setupHotKeys];
1172 [self networkError:localException];
1176 - (void)applicationTerminated:(NSNotification *)note
1179 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1180 ITDebugLog(@"Remote application terminated.");
1181 playerRunningState = ITMTRemotePlayerNotRunning;
1182 [[self currentRemote] halt];
1183 [refreshTimer invalidate];
1184 [refreshTimer release];
1186 [self clearHotKeys];
1188 if ([df objectForKey:@"ShowPlayer"] != nil) {
1190 ITDebugLog(@"Setting up show player hot key.");
1191 hotKey = [[ITHotKey alloc] init];
1192 [hotKey setName:@"ShowPlayer"];
1193 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1194 [hotKey setTarget:self];
1195 [hotKey setAction:@selector(showPlayer)];
1196 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1200 [self networkError:localException];
1205 /*************************************************************************/
1207 #pragma mark NSApplication DELEGATE METHODS
1208 /*************************************************************************/
1210 - (void)applicationWillTerminate:(NSNotification *)note
1212 [networkController stopRemoteServerSearch];
1213 [self clearHotKeys];
1214 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1218 /*************************************************************************/
1220 #pragma mark DEALLOCATION METHOD
1221 /*************************************************************************/
1225 [self applicationTerminated:nil];
1227 [statusItem release];
1228 [statusWindowController release];
1229 [menuController release];
1230 [networkController release];