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 @implementation NSImage (SmoothAdditions)
15 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
18 NSImageRep *rep = [self bestRepresentationForDevice:nil];
20 newImage = [[NSImage alloc] initWithSize:scaledSize];
23 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
24 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
25 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
27 [newImage unlockFocus];
28 return [newImage autorelease];
33 @interface MainController(Private)
34 - (ITMTRemote *)loadRemote;
35 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
36 - (void)applicationLaunched:(NSNotification *)note;
37 - (void)applicationTerminated:(NSNotification *)note;
40 static MainController *sharedController;
42 @implementation MainController
44 + (MainController *)sharedController
46 return sharedController;
49 /*************************************************************************/
51 #pragma mark INITIALIZATION/DEALLOCATION METHODS
52 /*************************************************************************/
56 if ( ( self = [super init] ) ) {
57 sharedController = self;
59 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
60 [[PreferencesController sharedPrefs] setController:self];
61 statusWindowController = [StatusWindowController sharedController];
62 menuController = [[MenuController alloc] init];
63 df = [[NSUserDefaults standardUserDefaults] retain];
70 - (void)applicationDidFinishLaunching:(NSNotification *)note
72 //Turn on debug mode if needed
73 if ([df boolForKey:@"ITDebugMode"]) {
77 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
78 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
80 [[PreferencesController sharedPrefs] registerDefaults];
81 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
84 currentRemote = [self loadRemote];
85 [[self currentRemote] begin];
87 //Turn on network stuff if needed
88 networkController = [[NetworkController alloc] init];
89 if ([df boolForKey:@"enableSharing"]) {
90 [self setServerStatus:YES];
91 } else if ([df boolForKey:@"useSharedPlayer"]) {
92 [self checkForRemoteServer];
95 //Setup for notification of the remote player launching or quitting
96 [[[NSWorkspace sharedWorkspace] notificationCenter]
98 selector:@selector(applicationTerminated:)
99 name:NSWorkspaceDidTerminateApplicationNotification
102 [[[NSWorkspace sharedWorkspace] notificationCenter]
104 selector:@selector(applicationLaunched:)
105 name:NSWorkspaceDidLaunchApplicationNotification
108 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
109 [[PreferencesController sharedPrefs] registerDefaults];
112 if ([df boolForKey:@"ITMTNoStatusItem"]) {
115 [StatusItemHack install];
116 statusItem = [[ITStatusItem alloc]
117 initWithStatusBar:[NSStatusBar systemStatusBar]
118 withLength:NSSquareStatusItemLength];
121 bling = [[MTBlingController alloc] init];
123 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
125 selector:@selector(blingTime)
127 repeats:YES] retain];
130 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
131 [self applicationLaunched:nil];
133 if ([df boolForKey:@"LaunchPlayerWithMT"])
136 [self applicationTerminated:nil];
139 [self networkError:localException];
142 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
143 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
145 [networkController startRemoteServerSearch];
149 - (ITMTRemote *)loadRemote
151 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
152 ITDebugLog(@"Gathering remotes.");
154 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
155 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
156 NSString *bundlePath;
158 while ( (bundlePath = [enumerator nextObject]) ) {
159 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
162 Class remoteClass = [remoteBundle principalClass];
164 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
165 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
166 id remote = [remoteClass remote];
167 ITDebugLog(@"Adding remote at path %@", bundlePath);
168 [remoteArray addObject:remote];
173 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
174 // if ( [remoteArray count] > 1 ) {
175 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
177 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
180 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
181 return [remoteArray objectAtIndex:0];
184 /*************************************************************************/
186 #pragma mark INSTANCE METHODS
187 /*************************************************************************/
189 /*- (void)startTimerInNewThread
191 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
192 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
193 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
195 selector:@selector(timerUpdate)
197 repeats:YES] retain];
199 ITDebugLog(@"Timer started.");
203 - (void)setBlingTime:(NSDate*)date
205 NSMutableDictionary *globalPrefs;
207 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
209 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
210 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
212 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
213 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
215 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
217 [globalPrefs release];
220 - (NSDate*)getBlingTime
223 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
228 NSDate *now = [NSDate date];
229 if (![self blingBling]) {
230 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
231 [self setBlingTime:now];
232 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
233 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
234 [self setBlingTime:[now addTimeInterval:-259200]];
236 NSMutableDictionary *globalPrefs;
238 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
239 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
240 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
242 [globalPrefs release];
246 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
248 [statusItem setEnabled:NO];
250 if ([refreshTimer isValid]) {
251 [refreshTimer invalidate];
253 [statusWindowController showRegistrationQueryWindow];
257 [statusItem setEnabled:YES];
259 if (![refreshTimer isValid]) {
260 [refreshTimer release];
261 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
263 selector:@selector(timerUpdate)
265 repeats:YES] retain];
269 [self setBlingTime:nil];
280 if ( ! ([bling checkDone] == 2475) ) {
287 - (BOOL)songIsPlaying
289 NSString *identifier = nil;
291 identifier = [[self currentRemote] playerStateUniqueIdentifier];
293 [self networkError:localException];
295 return ( ! ([identifier isEqualToString:@"0-0"]) );
298 - (BOOL)radioIsPlaying
300 ITMTRemotePlayerPlaylistClass class = nil;
302 class = [[self currentRemote] currentPlaylistClass];
304 [self networkError:localException];
306 return (class == ITMTRemotePlayerRadioPlaylist );
311 NSString *identifier = nil;
313 identifier = [[self currentRemote] playerStateUniqueIdentifier];
315 [self networkError:localException];
317 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
320 - (NSString *)latestSongIdentifier
322 return _latestSongIdentifier;
325 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
327 ITDebugLog(@"Setting latest song identifier:");
328 ITDebugLog(@" - Identifier: %@", newIdentifier);
329 [_latestSongIdentifier autorelease];
330 _latestSongIdentifier = [newIdentifier retain];
335 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
336 ITDebugLog(@"The song changed.");
338 if ([df boolForKey:@"runScripts"]) {
339 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
340 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
341 NSString *nextScript;
342 ITDebugLog(@"Running AppleScripts for song change.");
343 while ( (nextScript = [scriptsEnum nextObject]) ) {
345 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
346 ITDebugLog(@"Running script: %@", nextScript);
347 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
348 ITDebugLog(@"Error running script %@.", nextScript);
350 [currentScript release];
355 [statusItem setEnabled:NO];
358 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
359 [menuController rebuildSubmenus];
361 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
362 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
365 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
367 //Create the tooltip for the status item
368 if ( [df boolForKey:@"showToolTip"] ) {
369 NSString *artist = [[self currentRemote] currentSongArtist];
370 NSString *title = [[self currentRemote] currentSongTitle];
372 ITDebugLog(@"Creating status item tooltip.");
374 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
378 toolTip = @"No Song Playing";
380 [statusItem setToolTip:toolTip];
382 [statusItem setToolTip:nil];
385 [self networkError:localException];
389 [statusItem setEnabled:YES];
392 if ([networkController isConnectedToServer]) {
393 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
399 ITDebugLog(@"Menu clicked.");
400 if ([networkController isConnectedToServer]) {
401 //Used the cached version
406 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
407 [statusItem setMenu:[menuController menu]];
409 [statusItem setMenu:[menuController menuForNoPlayer]];
412 [self networkError:localException];
425 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
426 ITDebugLog(@"Play/Pause toggled");
427 if (state == ITMTRemotePlayerPlaying) {
428 [[self currentRemote] pause];
429 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
430 [[self currentRemote] pause];
431 [[self currentRemote] play];
433 [[self currentRemote] play];
436 [self networkError:localException];
444 ITDebugLog(@"Going to next song.");
446 [[self currentRemote] goToNextSong];
448 [self networkError:localException];
455 ITDebugLog(@"Going to previous song.");
457 [[self currentRemote] goToPreviousSong];
459 [self networkError:localException];
466 ITDebugLog(@"Fast forwarding.");
468 [[self currentRemote] forward];
470 [self networkError:localException];
477 ITDebugLog(@"Rewinding.");
479 [[self currentRemote] rewind];
481 [self networkError:localException];
486 - (void)selectPlaylistAtIndex:(int)index
488 ITDebugLog(@"Selecting playlist %i", index);
490 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
491 //[[self currentRemote] switchToPlaylistAtIndex:index];
493 [self networkError:localException];
498 - (void)selectSongAtIndex:(int)index
500 ITDebugLog(@"Selecting song %i", index);
502 [[self currentRemote] switchToSongAtIndex:index];
504 [self networkError:localException];
509 - (void)selectSongRating:(int)rating
511 ITDebugLog(@"Selecting song rating %i", rating);
513 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
515 [self networkError:localException];
520 - (void)selectEQPresetAtIndex:(int)index
522 ITDebugLog(@"Selecting EQ preset %i", index);
524 [[self currentRemote] switchToEQAtIndex:index];
526 [self networkError:localException];
533 ITDebugLog(@"Beginning show player.");
534 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
535 ITDebugLog(@"Showing player interface.");
537 [[self currentRemote] showPrimaryInterface];
539 [self networkError:localException];
542 ITDebugLog(@"Launching player.");
545 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
547 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
549 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
550 ITDebugLog(@"Error Launching Player");
553 [self networkError:localException];
556 ITDebugLog(@"Finished show player.");
559 - (void)showPreferences
561 ITDebugLog(@"Show preferences.");
562 [[PreferencesController sharedPrefs] showPrefsWindow:self];
565 - (void)showPreferencesAndClose
567 ITDebugLog(@"Show preferences.");
568 [[PreferencesController sharedPrefs] showPrefsWindow:self];
569 [[StatusWindow sharedWindow] setLocked:NO];
570 [[StatusWindow sharedWindow] vanish:self];
571 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
574 - (void)showTestWindow
576 [self showCurrentTrackInfo];
579 - (void)quitMenuTunes
581 ITDebugLog(@"Quitting MenuTunes.");
582 [NSApp terminate:self];
588 - (MenuController *)menuController
590 return menuController;
593 - (void)closePreferences
595 ITDebugLog(@"Preferences closed.");
596 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
601 - (ITMTRemote *)currentRemote
603 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
604 [self networkError:nil];
607 return currentRemote;
618 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
619 ITHotKey *nextHotKey;
620 ITDebugLog(@"Clearing hot keys.");
621 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
622 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
624 ITDebugLog(@"Done clearing hot keys.");
630 ITDebugLog(@"Setting up hot keys.");
632 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
636 if ([df objectForKey:@"PlayPause"] != nil) {
637 ITDebugLog(@"Setting up play pause hot key.");
638 hotKey = [[ITHotKey alloc] init];
639 [hotKey setName:@"PlayPause"];
640 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
641 [hotKey setTarget:self];
642 [hotKey setAction:@selector(playPause)];
643 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
646 if ([df objectForKey:@"NextTrack"] != nil) {
647 ITDebugLog(@"Setting up next track hot key.");
648 hotKey = [[ITHotKey alloc] init];
649 [hotKey setName:@"NextTrack"];
650 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
651 [hotKey setTarget:self];
652 [hotKey setAction:@selector(nextSong)];
653 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
656 if ([df objectForKey:@"PrevTrack"] != nil) {
657 ITDebugLog(@"Setting up previous track hot key.");
658 hotKey = [[ITHotKey alloc] init];
659 [hotKey setName:@"PrevTrack"];
660 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
661 [hotKey setTarget:self];
662 [hotKey setAction:@selector(prevSong)];
663 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
666 if ([df objectForKey:@"ShowPlayer"] != nil) {
667 ITDebugLog(@"Setting up show player hot key.");
668 hotKey = [[ITHotKey alloc] init];
669 [hotKey setName:@"ShowPlayer"];
670 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
671 [hotKey setTarget:self];
672 [hotKey setAction:@selector(showPlayer)];
673 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
676 if ([df objectForKey:@"TrackInfo"] != nil) {
677 ITDebugLog(@"Setting up track info hot key.");
678 hotKey = [[ITHotKey alloc] init];
679 [hotKey setName:@"TrackInfo"];
680 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
681 [hotKey setTarget:self];
682 [hotKey setAction:@selector(showCurrentTrackInfo)];
683 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
686 if ([df objectForKey:@"UpcomingSongs"] != nil) {
687 ITDebugLog(@"Setting up upcoming songs hot key.");
688 hotKey = [[ITHotKey alloc] init];
689 [hotKey setName:@"UpcomingSongs"];
690 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
691 [hotKey setTarget:self];
692 [hotKey setAction:@selector(showUpcomingSongs)];
693 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
696 if ([df objectForKey:@"ToggleLoop"] != nil) {
697 ITDebugLog(@"Setting up toggle loop hot key.");
698 hotKey = [[ITHotKey alloc] init];
699 [hotKey setName:@"ToggleLoop"];
700 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
701 [hotKey setTarget:self];
702 [hotKey setAction:@selector(toggleLoop)];
703 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
706 if ([df objectForKey:@"ToggleShuffle"] != nil) {
707 ITDebugLog(@"Setting up toggle shuffle hot key.");
708 hotKey = [[ITHotKey alloc] init];
709 [hotKey setName:@"ToggleShuffle"];
710 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
711 [hotKey setTarget:self];
712 [hotKey setAction:@selector(toggleShuffle)];
713 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
716 if ([df objectForKey:@"IncrementVolume"] != nil) {
717 ITDebugLog(@"Setting up increment volume hot key.");
718 hotKey = [[ITHotKey alloc] init];
719 [hotKey setName:@"IncrementVolume"];
720 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
721 [hotKey setTarget:self];
722 [hotKey setAction:@selector(incrementVolume)];
723 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
726 if ([df objectForKey:@"DecrementVolume"] != nil) {
727 ITDebugLog(@"Setting up decrement volume hot key.");
728 hotKey = [[ITHotKey alloc] init];
729 [hotKey setName:@"DecrementVolume"];
730 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
731 [hotKey setTarget:self];
732 [hotKey setAction:@selector(decrementVolume)];
733 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
736 if ([df objectForKey:@"IncrementRating"] != nil) {
737 ITDebugLog(@"Setting up increment rating hot key.");
738 hotKey = [[ITHotKey alloc] init];
739 [hotKey setName:@"IncrementRating"];
740 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
741 [hotKey setTarget:self];
742 [hotKey setAction:@selector(incrementRating)];
743 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
746 if ([df objectForKey:@"DecrementRating"] != nil) {
747 ITDebugLog(@"Setting up decrement rating hot key.");
748 hotKey = [[ITHotKey alloc] init];
749 [hotKey setName:@"DecrementRating"];
750 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
751 [hotKey setTarget:self];
752 [hotKey setAction:@selector(decrementRating)];
753 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
755 ITDebugLog(@"Finished setting up hot keys.");
758 - (void)showCurrentTrackInfo
760 ITMTRemotePlayerSource source = 0;
761 NSString *title = nil;
762 NSString *album = nil;
763 NSString *artist = nil;
764 NSString *composer = nil;
765 NSString *time = nil;
766 NSString *track = nil;
770 ITDebugLog(@"Showing track info status window.");
773 source = [[self currentRemote] currentSource];
774 title = [[self currentRemote] currentSongTitle];
776 [self networkError:localException];
781 if ( [df boolForKey:@"showAlbum"] ) {
783 album = [[self currentRemote] currentSongAlbum];
785 [self networkError:localException];
789 if ( [df boolForKey:@"showArtist"] ) {
791 artist = [[self currentRemote] currentSongArtist];
793 [self networkError:localException];
797 if ( [df boolForKey:@"showComposer"] ) {
799 composer = [[self currentRemote] currentSongComposer];
801 [self networkError:localException];
805 if ( [df boolForKey:@"showTime"] ) {
807 time = [NSString stringWithFormat:@"%@: %@ / %@",
809 [[self currentRemote] currentSongElapsed],
810 [[self currentRemote] currentSongLength]];
812 [self networkError:localException];
816 if ( [df boolForKey:@"showTrackNumber"] ) {
821 trackNo = [[self currentRemote] currentSongTrack];
822 trackCount = [[self currentRemote] currentAlbumTrackCount];
824 [self networkError:localException];
827 if ( (trackNo > 0) || (trackCount > 0) ) {
828 track = [NSString stringWithFormat:@"%@: %i %@ %i",
829 @"Track", trackNo, @"of", trackCount];
833 if ( [df boolForKey:@"showTrackRating"] ) {
834 float currentRating = 0;
837 currentRating = [[self currentRemote] currentSongRating];
839 [self networkError:localException];
842 if (currentRating >= 0.0) {
843 rating = ( currentRating * 5 );
847 if ( [df boolForKey:@"showAlbumArtwork"] ) {
848 NSSize oldSize, newSize;
850 art = [[self currentRemote] currentSongAlbumArt];
851 oldSize = [art size];
852 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
853 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
854 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
856 [self networkError:localException];
861 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
863 ITDebugLog(@"Showing current track info status window.");
864 [statusWindowController showSongInfoWindowWithSource:source
875 - (void)showUpcomingSongs
879 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
881 [self networkError:localException];
884 ITDebugLog(@"Showing upcoming songs status window.");
887 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
888 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
889 int curTrack = [[self currentRemote] currentSongIndex];
892 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
894 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
898 if ([songList count] == 0) {
899 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
902 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
904 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
907 [self networkError:localException];
911 - (void)incrementVolume
914 float volume = [[self currentRemote] volume];
915 float dispVol = volume;
916 ITDebugLog(@"Incrementing volume.");
925 ITDebugLog(@"Setting volume to %f", volume);
926 [[self currentRemote] setVolume:volume];
928 // Show volume status window
929 [statusWindowController showVolumeWindowWithLevel:dispVol];
931 [self networkError:localException];
935 - (void)decrementVolume
938 float volume = [[self currentRemote] volume];
939 float dispVol = volume;
940 ITDebugLog(@"Decrementing volume.");
949 ITDebugLog(@"Setting volume to %f", volume);
950 [[self currentRemote] setVolume:volume];
952 //Show volume status window
953 [statusWindowController showVolumeWindowWithLevel:dispVol];
955 [self networkError:localException];
959 - (void)incrementRating
962 float rating = [[self currentRemote] currentSongRating];
963 ITDebugLog(@"Incrementing rating.");
965 if ([[self currentRemote] currentPlaylistIndex] == 0) {
966 ITDebugLog(@"No song playing, rating change aborted.");
974 ITDebugLog(@"Setting rating to %f", rating);
975 [[self currentRemote] setCurrentSongRating:rating];
977 //Show rating status window
978 [statusWindowController showRatingWindowWithRating:rating];
980 [self networkError:localException];
984 - (void)decrementRating
987 float rating = [[self currentRemote] currentSongRating];
988 ITDebugLog(@"Decrementing rating.");
990 if ([[self currentRemote] currentPlaylistIndex] == 0) {
991 ITDebugLog(@"No song playing, rating change aborted.");
999 ITDebugLog(@"Setting rating to %f", rating);
1000 [[self currentRemote] setCurrentSongRating:rating];
1002 //Show rating status window
1003 [statusWindowController showRatingWindowWithRating:rating];
1005 [self networkError:localException];
1012 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1013 ITDebugLog(@"Toggling repeat mode.");
1014 switch (repeatMode) {
1015 case ITMTRemotePlayerRepeatOff:
1016 repeatMode = ITMTRemotePlayerRepeatAll;
1018 case ITMTRemotePlayerRepeatAll:
1019 repeatMode = ITMTRemotePlayerRepeatOne;
1021 case ITMTRemotePlayerRepeatOne:
1022 repeatMode = ITMTRemotePlayerRepeatOff;
1025 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1026 [[self currentRemote] setRepeatMode:repeatMode];
1028 //Show loop status window
1029 [statusWindowController showRepeatWindowWithMode:repeatMode];
1031 [self networkError:localException];
1035 - (void)toggleShuffle
1038 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1039 ITDebugLog(@"Toggling shuffle mode.");
1040 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1041 //Show shuffle status window
1042 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1043 [statusWindowController showShuffleWindow:newShuffleEnabled];
1045 [self networkError:localException];
1049 - (void)registerNowOK
1051 [[StatusWindow sharedWindow] setLocked:NO];
1052 [[StatusWindow sharedWindow] vanish:self];
1053 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1058 - (void)registerNowCancel
1060 [[StatusWindow sharedWindow] setLocked:NO];
1061 [[StatusWindow sharedWindow] vanish:self];
1062 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1064 [NSApp terminate:self];
1067 /*************************************************************************/
1069 #pragma mark NETWORK HANDLERS
1070 /*************************************************************************/
1072 - (void)setServerStatus:(BOOL)newStatus
1076 [networkController setServerStatus:YES];
1079 [networkController setServerStatus:NO];
1083 - (int)connectToServer
1086 ITDebugLog(@"Attempting to connect to shared remote.");
1087 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1090 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1091 currentRemote = [[[networkController networkObject] remote] retain];
1093 [self setupHotKeys];
1094 //playerRunningState = ITMTRemotePlayerRunning;
1095 playerRunningState = [[self currentRemote] playerRunningState];
1097 [refreshTimer invalidate];
1098 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1100 selector:@selector(timerUpdate)
1102 repeats:YES] retain];
1104 ITDebugLog(@"Connection successful.");
1106 } else if (result == 0) {
1107 ITDebugLog(@"Connection failed.");
1108 currentRemote = [remoteArray objectAtIndex:0];
1111 //Do something about the password being invalid
1112 ITDebugLog(@"Connection failed.");
1113 currentRemote = [remoteArray objectAtIndex:0];
1118 - (BOOL)disconnectFromServer
1120 ITDebugLog(@"Disconnecting from shared remote.");
1122 [currentRemote release];
1123 currentRemote = [remoteArray objectAtIndex:0];
1124 [networkController disconnect];
1126 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1127 [self applicationLaunched:nil];
1129 [self applicationTerminated:nil];
1135 - (void)checkForRemoteServer
1137 ITDebugLog(@"Checking for remote server.");
1138 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:nil];
1141 - (void)runRemoteServerCheck:(id)sender
1143 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1144 ITDebugLog(@"Remote server check running.");
1145 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1146 ITDebugLog(@"Remote server found.");
1147 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1149 ITDebugLog(@"Remote server not found.");
1150 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1155 - (void)remoteServerFound:(id)sender
1157 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1158 [[StatusWindowController sharedController] showReconnectQueryWindow];
1162 - (void)remoteServerNotFound:(id)sender
1164 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1167 - (void)networkError:(NSException *)exception
1169 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1170 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1171 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);
1172 if ([self disconnectFromServer]) {
1173 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1174 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:YES];
1176 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1183 if ([self connectToServer] == 0) {
1184 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:YES];
1186 [[StatusWindow sharedWindow] setLocked:NO];
1187 [[StatusWindow sharedWindow] vanish:self];
1188 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1191 - (void)cancelReconnect
1193 [[StatusWindow sharedWindow] setLocked:NO];
1194 [[StatusWindow sharedWindow] vanish:self];
1195 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1198 /*************************************************************************/
1200 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1201 /*************************************************************************/
1203 - (void)applicationLaunched:(NSNotification *)note
1206 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1207 ITDebugLog(@"Remote application launched.");
1208 playerRunningState = ITMTRemotePlayerRunning;
1209 [[self currentRemote] begin];
1210 [self setLatestSongIdentifier:@""];
1212 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1214 selector:@selector(timerUpdate)
1216 repeats:YES] retain];
1217 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1218 [self setupHotKeys];
1221 [self networkError:localException];
1225 - (void)applicationTerminated:(NSNotification *)note
1228 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1229 ITDebugLog(@"Remote application terminated.");
1230 playerRunningState = ITMTRemotePlayerNotRunning;
1231 [[self currentRemote] halt];
1232 [refreshTimer invalidate];
1233 [refreshTimer release];
1235 [self clearHotKeys];
1237 if ([df objectForKey:@"ShowPlayer"] != nil) {
1239 ITDebugLog(@"Setting up show player hot key.");
1240 hotKey = [[ITHotKey alloc] init];
1241 [hotKey setName:@"ShowPlayer"];
1242 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1243 [hotKey setTarget:self];
1244 [hotKey setAction:@selector(showPlayer)];
1245 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1249 [self networkError:localException];
1254 /*************************************************************************/
1256 #pragma mark NSApplication DELEGATE METHODS
1257 /*************************************************************************/
1259 - (void)applicationWillTerminate:(NSNotification *)note
1261 [networkController stopRemoteServerSearch];
1262 [self clearHotKeys];
1263 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1267 /*************************************************************************/
1269 #pragma mark DEALLOCATION METHOD
1270 /*************************************************************************/
1274 [self applicationTerminated:nil];
1276 [statusItem release];
1277 [statusWindowController release];
1278 [menuController release];
1279 [networkController release];