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 ITDebugLog(@"Running AppleScripts for song change.");
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 NSLog(@"Running script: %@", nextScript);
356 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
357 ITDebugLog(@"Error running script %@.", nextScript);
359 [currentScript release];
366 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
367 [menuController rebuildSubmenus];
369 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
370 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
373 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
375 //Create the tooltip for the status item
376 if ( [df boolForKey:@"showToolTip"] ) {
377 NSString *artist = [[self currentRemote] currentSongArtist];
378 NSString *title = [[self currentRemote] currentSongTitle];
380 ITDebugLog(@"Creating status item tooltip.");
382 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
386 toolTip = @"No Song Playing";
388 [statusItem setToolTip:toolTip];
390 [statusItem setToolTip:nil];
393 [self networkError:localException];
402 ITDebugLog(@"Menu clicked.");
403 if ([networkController isConnectedToServer]) {
404 //Used the cached version
409 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
410 [statusItem setMenu:[menuController menu]];
412 [statusItem setMenu:[menuController menuForNoPlayer]];
415 [self networkError:localException];
428 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
429 ITDebugLog(@"Play/Pause toggled");
430 if (state == ITMTRemotePlayerPlaying) {
431 [[self currentRemote] pause];
432 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
433 [[self currentRemote] pause];
434 [[self currentRemote] play];
436 [[self currentRemote] play];
439 [self networkError:localException];
447 ITDebugLog(@"Going to next song.");
449 [[self currentRemote] goToNextSong];
451 [self networkError:localException];
458 ITDebugLog(@"Going to previous song.");
460 [[self currentRemote] goToPreviousSong];
462 [self networkError:localException];
469 ITDebugLog(@"Fast forwarding.");
471 [[self currentRemote] forward];
473 [self networkError:localException];
480 ITDebugLog(@"Rewinding.");
482 [[self currentRemote] rewind];
484 [self networkError:localException];
489 - (void)selectPlaylistAtIndex:(int)index
491 ITDebugLog(@"Selecting playlist %i", index);
493 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
494 //[[self currentRemote] switchToPlaylistAtIndex:index];
496 [self networkError:localException];
501 - (void)selectSongAtIndex:(int)index
503 ITDebugLog(@"Selecting song %i", index);
505 [[self currentRemote] switchToSongAtIndex:index];
507 [self networkError:localException];
512 - (void)selectSongRating:(int)rating
514 ITDebugLog(@"Selecting song rating %i", rating);
516 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
518 [self networkError:localException];
523 - (void)selectEQPresetAtIndex:(int)index
525 ITDebugLog(@"Selecting EQ preset %i", index);
527 [[self currentRemote] switchToEQAtIndex:index];
529 [self networkError:localException];
536 ITDebugLog(@"Beginning show player.");
537 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
538 ITDebugLog(@"Showing player interface.");
540 [[self currentRemote] showPrimaryInterface];
542 [self networkError:localException];
545 ITDebugLog(@"Launching player.");
548 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
550 path = [[self currentRemote] playerFullName];
552 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
553 ITDebugLog(@"Error Launching Player");
556 [self networkError:localException];
559 ITDebugLog(@"Finished show player.");
562 - (void)showPreferences
564 ITDebugLog(@"Show preferences.");
565 [[PreferencesController sharedPrefs] showPrefsWindow:self];
568 - (void)showPreferencesAndClose
570 ITDebugLog(@"Show preferences.");
571 [[PreferencesController sharedPrefs] showPrefsWindow:self];
572 [[StatusWindow sharedWindow] setLocked:NO];
573 [[StatusWindow sharedWindow] vanish:self];
574 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
577 - (void)showTestWindow
579 [self showCurrentTrackInfo];
582 - (void)quitMenuTunes
584 ITDebugLog(@"Quitting MenuTunes.");
585 [NSApp terminate:self];
591 - (void)closePreferences
593 ITDebugLog(@"Preferences closed.");
594 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
599 - (ITMTRemote *)currentRemote
601 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
602 [self networkError:nil];
605 return currentRemote;
616 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
617 ITHotKey *nextHotKey;
618 ITDebugLog(@"Clearing hot keys.");
619 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
620 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
622 ITDebugLog(@"Done clearing hot keys.");
628 ITDebugLog(@"Setting up hot keys.");
630 if (playerRunningState == ITMTRemotePlayerNotRunning) {
634 if ([df objectForKey:@"PlayPause"] != nil) {
635 ITDebugLog(@"Setting up play pause hot key.");
636 hotKey = [[ITHotKey alloc] init];
637 [hotKey setName:@"PlayPause"];
638 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
639 [hotKey setTarget:self];
640 [hotKey setAction:@selector(playPause)];
641 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
644 if ([df objectForKey:@"NextTrack"] != nil) {
645 ITDebugLog(@"Setting up next track hot key.");
646 hotKey = [[ITHotKey alloc] init];
647 [hotKey setName:@"NextTrack"];
648 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
649 [hotKey setTarget:self];
650 [hotKey setAction:@selector(nextSong)];
651 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
654 if ([df objectForKey:@"PrevTrack"] != nil) {
655 ITDebugLog(@"Setting up previous track hot key.");
656 hotKey = [[ITHotKey alloc] init];
657 [hotKey setName:@"PrevTrack"];
658 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
659 [hotKey setTarget:self];
660 [hotKey setAction:@selector(prevSong)];
661 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
664 if ([df objectForKey:@"ShowPlayer"] != nil) {
665 ITDebugLog(@"Setting up show player hot key.");
666 hotKey = [[ITHotKey alloc] init];
667 [hotKey setName:@"ShowPlayer"];
668 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
669 [hotKey setTarget:self];
670 [hotKey setAction:@selector(showPlayer)];
671 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
674 if ([df objectForKey:@"TrackInfo"] != nil) {
675 ITDebugLog(@"Setting up track info hot key.");
676 hotKey = [[ITHotKey alloc] init];
677 [hotKey setName:@"TrackInfo"];
678 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
679 [hotKey setTarget:self];
680 [hotKey setAction:@selector(showCurrentTrackInfo)];
681 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
684 if ([df objectForKey:@"UpcomingSongs"] != nil) {
685 ITDebugLog(@"Setting up upcoming songs hot key.");
686 hotKey = [[ITHotKey alloc] init];
687 [hotKey setName:@"UpcomingSongs"];
688 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
689 [hotKey setTarget:self];
690 [hotKey setAction:@selector(showUpcomingSongs)];
691 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
694 if ([df objectForKey:@"ToggleLoop"] != nil) {
695 ITDebugLog(@"Setting up toggle loop hot key.");
696 hotKey = [[ITHotKey alloc] init];
697 [hotKey setName:@"ToggleLoop"];
698 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
699 [hotKey setTarget:self];
700 [hotKey setAction:@selector(toggleLoop)];
701 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
704 if ([df objectForKey:@"ToggleShuffle"] != nil) {
705 ITDebugLog(@"Setting up toggle shuffle hot key.");
706 hotKey = [[ITHotKey alloc] init];
707 [hotKey setName:@"ToggleShuffle"];
708 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
709 [hotKey setTarget:self];
710 [hotKey setAction:@selector(toggleShuffle)];
711 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
714 if ([df objectForKey:@"IncrementVolume"] != nil) {
715 ITDebugLog(@"Setting up increment volume hot key.");
716 hotKey = [[ITHotKey alloc] init];
717 [hotKey setName:@"IncrementVolume"];
718 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
719 [hotKey setTarget:self];
720 [hotKey setAction:@selector(incrementVolume)];
721 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
724 if ([df objectForKey:@"DecrementVolume"] != nil) {
725 ITDebugLog(@"Setting up decrement volume hot key.");
726 hotKey = [[ITHotKey alloc] init];
727 [hotKey setName:@"DecrementVolume"];
728 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
729 [hotKey setTarget:self];
730 [hotKey setAction:@selector(decrementVolume)];
731 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
734 if ([df objectForKey:@"IncrementRating"] != nil) {
735 ITDebugLog(@"Setting up increment rating hot key.");
736 hotKey = [[ITHotKey alloc] init];
737 [hotKey setName:@"IncrementRating"];
738 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
739 [hotKey setTarget:self];
740 [hotKey setAction:@selector(incrementRating)];
741 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
744 if ([df objectForKey:@"DecrementRating"] != nil) {
745 ITDebugLog(@"Setting up decrement rating hot key.");
746 hotKey = [[ITHotKey alloc] init];
747 [hotKey setName:@"DecrementRating"];
748 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
749 [hotKey setTarget:self];
750 [hotKey setAction:@selector(decrementRating)];
751 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
753 ITDebugLog(@"Finished setting up hot keys.");
756 - (void)showCurrentTrackInfo
758 ITMTRemotePlayerSource source = 0;
759 NSString *title = nil;
760 NSString *album = nil;
761 NSString *artist = nil;
762 NSString *time = nil;
763 NSString *track = nil;
768 source = [[self currentRemote] currentSource];
769 title = [[self currentRemote] currentSongTitle];
771 [self networkError:localException];
774 ITDebugLog(@"Showing track info status window.");
778 if ( [df boolForKey:@"showAlbum"] ) {
780 album = [[self currentRemote] currentSongAlbum];
782 [self networkError:localException];
786 if ( [df boolForKey:@"showArtist"] ) {
788 artist = [[self currentRemote] currentSongArtist];
790 [self networkError:localException];
794 if ( [df boolForKey:@"showTime"] ) {
796 time = [NSString stringWithFormat:@"%@: %@ / %@",
798 [[self currentRemote] currentSongElapsed],
799 [[self currentRemote] currentSongLength]];
801 [self networkError:localException];
805 if ( [df boolForKey:@"showTrackNumber"] ) {
810 trackNo = [[self currentRemote] currentSongTrack];
811 trackCount = [[self currentRemote] currentAlbumTrackCount];
813 [self networkError:localException];
816 if ( (trackNo > 0) || (trackCount > 0) ) {
817 track = [NSString stringWithFormat:@"%@: %i %@ %i",
818 @"Track", trackNo, @"of", trackCount];
822 if ( [df boolForKey:@"showTrackRating"] ) {
823 float currentRating = 0;
826 currentRating = [[self currentRemote] currentSongRating];
828 [self networkError:localException];
831 if (currentRating >= 0.0) {
832 rating = ( currentRating * 5 );
836 if ( [df boolForKey:@"showAlbumArtwork"] ) {
837 NSSize oldSize, newSize;
839 art = [[self currentRemote] currentSongAlbumArt];
840 oldSize = [art size];
841 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
842 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
843 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
845 [self networkError:localException];
850 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
852 [statusWindowController showSongInfoWindowWithSource:source
862 - (void)showUpcomingSongs
866 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
868 [self networkError:localException];
871 ITDebugLog(@"Showing upcoming songs status window.");
874 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
875 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
876 int curTrack = [[self currentRemote] currentSongIndex];
879 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
881 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
885 if ([songList count] == 0) {
886 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
889 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
891 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
894 [self networkError:localException];
898 - (void)incrementVolume
901 float volume = [[self currentRemote] volume];
902 float dispVol = volume;
903 ITDebugLog(@"Incrementing volume.");
912 ITDebugLog(@"Setting volume to %f", volume);
913 [[self currentRemote] setVolume:volume];
915 // Show volume status window
916 [statusWindowController showVolumeWindowWithLevel:dispVol];
918 [self networkError:localException];
922 - (void)decrementVolume
925 float volume = [[self currentRemote] volume];
926 float dispVol = volume;
927 ITDebugLog(@"Decrementing volume.");
936 ITDebugLog(@"Setting volume to %f", volume);
937 [[self currentRemote] setVolume:volume];
939 //Show volume status window
940 [statusWindowController showVolumeWindowWithLevel:dispVol];
942 [self networkError:localException];
946 - (void)incrementRating
949 float rating = [[self currentRemote] currentSongRating];
950 ITDebugLog(@"Incrementing rating.");
952 if ([[self currentRemote] currentPlaylistIndex] == 0) {
953 ITDebugLog(@"No song playing, rating change aborted.");
961 ITDebugLog(@"Setting rating to %f", rating);
962 [[self currentRemote] setCurrentSongRating:rating];
964 //Show rating status window
965 [statusWindowController showRatingWindowWithRating:rating];
967 [self networkError:localException];
971 - (void)decrementRating
974 float rating = [[self currentRemote] currentSongRating];
975 ITDebugLog(@"Decrementing rating.");
977 if ([[self currentRemote] currentPlaylistIndex] == 0) {
978 ITDebugLog(@"No song playing, rating change aborted.");
986 ITDebugLog(@"Setting rating to %f", rating);
987 [[self currentRemote] setCurrentSongRating:rating];
989 //Show rating status window
990 [statusWindowController showRatingWindowWithRating:rating];
992 [self networkError:localException];
999 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1000 ITDebugLog(@"Toggling repeat mode.");
1001 switch (repeatMode) {
1002 case ITMTRemotePlayerRepeatOff:
1003 repeatMode = ITMTRemotePlayerRepeatAll;
1005 case ITMTRemotePlayerRepeatAll:
1006 repeatMode = ITMTRemotePlayerRepeatOne;
1008 case ITMTRemotePlayerRepeatOne:
1009 repeatMode = ITMTRemotePlayerRepeatOff;
1012 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1013 [[self currentRemote] setRepeatMode:repeatMode];
1015 //Show loop status window
1016 [statusWindowController showRepeatWindowWithMode:repeatMode];
1018 [self networkError:localException];
1022 - (void)toggleShuffle
1025 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1026 ITDebugLog(@"Toggling shuffle mode.");
1027 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1028 //Show shuffle status window
1029 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1030 [statusWindowController showShuffleWindow:newShuffleEnabled];
1032 [self networkError:localException];
1036 - (void)registerNowOK
1038 [[StatusWindow sharedWindow] setLocked:NO];
1039 [[StatusWindow sharedWindow] vanish:self];
1040 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1045 - (void)registerNowCancel
1047 [[StatusWindow sharedWindow] setLocked:NO];
1048 [[StatusWindow sharedWindow] vanish:self];
1049 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1051 [NSApp terminate:self];
1054 /*************************************************************************/
1056 #pragma mark NETWORK HANDLERS
1057 /*************************************************************************/
1059 - (void)setServerStatus:(BOOL)newStatus
1063 [networkController setServerStatus:YES];
1066 [networkController setServerStatus:NO];
1070 - (int)connectToServer
1073 ITDebugLog(@"Attempting to connect to shared remote.");
1074 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1077 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1078 currentRemote = [[[networkController networkObject] remote] retain];
1079 [refreshTimer invalidate];
1080 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1082 selector:@selector(timerUpdate)
1084 repeats:YES] retain];
1086 ITDebugLog(@"Connection successful.");
1088 } else if (result == 0) {
1089 ITDebugLog(@"Connection failed.");
1090 currentRemote = [remoteArray objectAtIndex:0];
1093 //Do something about the password being invalid
1094 ITDebugLog(@"Connection failed.");
1095 currentRemote = [remoteArray objectAtIndex:0];
1100 - (BOOL)disconnectFromServer
1102 ITDebugLog(@"Disconnecting from shared remote.");
1104 [currentRemote release];
1105 currentRemote = [remoteArray objectAtIndex:0];
1106 [networkController disconnect];
1111 - (void)checkForRemoteServer:(NSTimer *)timer
1113 ITDebugLog(@"Checking for remote server.");
1114 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1115 ITDebugLog(@"Remote server found.");
1117 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1118 [[StatusWindowController sharedController] showReconnectQueryWindow];
1121 ITDebugLog(@"Remote server not found.");
1125 - (void)networkError:(NSException *)exception
1127 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1128 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1129 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);
1130 if ([self disconnectFromServer]) {
1131 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1132 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1134 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1141 if ([self connectToServer] == 0) {
1142 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1144 [[StatusWindow sharedWindow] setLocked:NO];
1145 [[StatusWindow sharedWindow] vanish:self];
1146 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1149 - (void)cancelReconnect
1151 [[StatusWindow sharedWindow] setLocked:NO];
1152 [[StatusWindow sharedWindow] vanish:self];
1153 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1156 /*************************************************************************/
1158 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1159 /*************************************************************************/
1161 - (void)applicationLaunched:(NSNotification *)note
1164 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1165 ITDebugLog(@"Remote application launched.");
1166 playerRunningState = ITMTRemotePlayerRunning;
1167 [[self currentRemote] begin];
1168 [self setLatestSongIdentifier:@""];
1170 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1172 selector:@selector(timerUpdate)
1174 repeats:YES] retain];
1175 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1176 [self setupHotKeys];
1179 [self networkError:localException];
1183 - (void)applicationTerminated:(NSNotification *)note
1186 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1187 ITDebugLog(@"Remote application terminated.");
1188 playerRunningState = ITMTRemotePlayerNotRunning;
1189 [[self currentRemote] halt];
1190 [refreshTimer invalidate];
1191 [refreshTimer release];
1193 [self clearHotKeys];
1195 if ([df objectForKey:@"ShowPlayer"] != nil) {
1197 ITDebugLog(@"Setting up show player hot key.");
1198 hotKey = [[ITHotKey alloc] init];
1199 [hotKey setName:@"ShowPlayer"];
1200 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1201 [hotKey setTarget:self];
1202 [hotKey setAction:@selector(showPlayer)];
1203 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1207 [self networkError:localException];
1212 /*************************************************************************/
1214 #pragma mark NSApplication DELEGATE METHODS
1215 /*************************************************************************/
1217 - (void)applicationWillTerminate:(NSNotification *)note
1219 [networkController stopRemoteServerSearch];
1220 [self clearHotKeys];
1221 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1225 /*************************************************************************/
1227 #pragma mark DEALLOCATION METHOD
1228 /*************************************************************************/
1232 [self applicationTerminated:nil];
1234 [statusItem release];
1235 [statusWindowController release];
1236 [menuController release];
1237 [networkController release];