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:nil];
93 /*if ([self connectToServer] == 0) {
94 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
98 //Setup for notification of the remote player launching or quitting
99 [[[NSWorkspace sharedWorkspace] notificationCenter]
101 selector:@selector(applicationTerminated:)
102 name:NSWorkspaceDidTerminateApplicationNotification
105 [[[NSWorkspace sharedWorkspace] notificationCenter]
107 selector:@selector(applicationLaunched:)
108 name:NSWorkspaceDidLaunchApplicationNotification
111 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
112 [[PreferencesController sharedPrefs] registerDefaults];
115 if ([df boolForKey:@"ITMTNoStatusItem"]) {
118 [StatusItemHack install];
119 statusItem = [[ITStatusItem alloc]
120 initWithStatusBar:[NSStatusBar systemStatusBar]
121 withLength:NSSquareStatusItemLength];
124 bling = [[MTBlingController alloc] init];
126 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
128 selector:@selector(blingTime)
130 repeats:YES] retain];
133 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
134 [self applicationLaunched:nil];
136 if ([df boolForKey:@"LaunchPlayerWithMT"])
139 [self applicationTerminated:nil];
142 [self networkError:localException];
145 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
146 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
148 [networkController startRemoteServerSearch];
152 - (ITMTRemote *)loadRemote
154 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
155 ITDebugLog(@"Gathering remotes.");
157 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
158 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
159 NSString *bundlePath;
161 while ( (bundlePath = [enumerator nextObject]) ) {
162 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
165 Class remoteClass = [remoteBundle principalClass];
167 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
168 [remoteClass isKindOfClass:[NSObject class]]) {
169 id remote = [remoteClass remote];
170 ITDebugLog(@"Adding remote at path %@", bundlePath);
171 [remoteArray addObject:remote];
176 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
177 // if ( [remoteArray count] > 1 ) {
178 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
180 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
183 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
184 return [remoteArray objectAtIndex:0];
187 /*************************************************************************/
189 #pragma mark INSTANCE METHODS
190 /*************************************************************************/
192 /*- (void)startTimerInNewThread
194 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
195 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
196 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
198 selector:@selector(timerUpdate)
200 repeats:YES] retain];
202 ITDebugLog(@"Timer started.");
206 - (void)setBlingTime:(NSDate*)date
208 NSMutableDictionary *globalPrefs;
210 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
212 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
213 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
215 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
216 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
218 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
220 [globalPrefs release];
223 - (NSDate*)getBlingTime
226 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
231 NSDate *now = [NSDate date];
232 if (![self blingBling]) {
233 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
234 [self setBlingTime:now];
235 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
236 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
237 [self setBlingTime:[now addTimeInterval:-259200]];
239 NSMutableDictionary *globalPrefs;
241 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
242 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
243 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
245 [globalPrefs release];
249 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
251 [statusItem setEnabled:NO];
253 if ([refreshTimer isValid]) {
254 [refreshTimer invalidate];
256 [statusWindowController showRegistrationQueryWindow];
260 [statusItem setEnabled:YES];
262 if (![refreshTimer isValid]) {
263 [refreshTimer release];
264 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
266 selector:@selector(timerUpdate)
268 repeats:YES] retain];
272 [self setBlingTime:nil];
283 if ( ! ([bling checkDone] == 2475) ) {
290 - (BOOL)songIsPlaying
292 NSString *identifier = nil;
294 identifier = [[self currentRemote] playerStateUniqueIdentifier];
296 [self networkError:localException];
298 return ( ! ([identifier isEqualToString:@"0-0"]) );
301 - (BOOL)radioIsPlaying
303 ITMTRemotePlayerPlaylistClass class = nil;
305 class = [[self currentRemote] currentPlaylistClass];
307 [self networkError:localException];
309 return (class == ITMTRemotePlayerRadioPlaylist );
314 NSString *identifier = nil;
316 identifier = [[self currentRemote] playerStateUniqueIdentifier];
318 [self networkError:localException];
320 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
323 - (NSString *)latestSongIdentifier
325 return _latestSongIdentifier;
328 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
330 ITDebugLog(@"Setting latest song identifier:");
331 ITDebugLog(@" - Identifier: %@", newIdentifier);
332 [_latestSongIdentifier autorelease];
333 _latestSongIdentifier = [newIdentifier retain];
338 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
339 ITDebugLog(@"The song changed.");
341 if ([df boolForKey:@"runScripts"]) {
342 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
343 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
344 NSString *nextScript;
345 ITDebugLog(@"Running AppleScripts for song change.");
346 while ( (nextScript = [scriptsEnum nextObject]) ) {
348 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
349 ITDebugLog(@"Running script: %@", nextScript);
350 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
351 ITDebugLog(@"Error running script %@.", nextScript);
353 [currentScript release];
358 [statusItem setEnabled:NO];
361 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
362 [menuController rebuildSubmenus];
364 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
365 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
368 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
370 //Create the tooltip for the status item
371 if ( [df boolForKey:@"showToolTip"] ) {
372 NSString *artist = [[self currentRemote] currentSongArtist];
373 NSString *title = [[self currentRemote] currentSongTitle];
375 ITDebugLog(@"Creating status item tooltip.");
377 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
381 toolTip = @"No Song Playing";
383 [statusItem setToolTip:toolTip];
385 [statusItem setToolTip:nil];
388 [self networkError:localException];
392 [statusItem setEnabled:YES];
395 if ([networkController isConnectedToServer]) {
396 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
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 pathITDebugLog(@"Showing player interface."); = [[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 - (MenuController *)menuController
593 return menuController;
596 - (void)closePreferences
598 ITDebugLog(@"Preferences closed.");
599 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
604 - (ITMTRemote *)currentRemote
606 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
607 [self networkError:nil];
610 return currentRemote;
621 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
622 ITHotKey *nextHotKey;
623 ITDebugLog(@"Clearing hot keys.");
624 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
625 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
627 ITDebugLog(@"Done clearing hot keys.");
633 ITDebugLog(@"Setting up hot keys.");
635 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
639 if ([df objectForKey:@"PlayPause"] != nil) {
640 ITDebugLog(@"Setting up play pause hot key.");
641 hotKey = [[ITHotKey alloc] init];
642 [hotKey setName:@"PlayPause"];
643 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
644 [hotKey setTarget:self];
645 [hotKey setAction:@selector(playPause)];
646 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
649 if ([df objectForKey:@"NextTrack"] != nil) {
650 ITDebugLog(@"Setting up next track hot key.");
651 hotKey = [[ITHotKey alloc] init];
652 [hotKey setName:@"NextTrack"];
653 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
654 [hotKey setTarget:self];
655 [hotKey setAction:@selector(nextSong)];
656 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
659 if ([df objectForKey:@"PrevTrack"] != nil) {
660 ITDebugLog(@"Setting up previous track hot key.");
661 hotKey = [[ITHotKey alloc] init];
662 [hotKey setName:@"PrevTrack"];
663 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
664 [hotKey setTarget:self];
665 [hotKey setAction:@selector(prevSong)];
666 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
669 if ([df objectForKey:@"ShowPlayer"] != nil) {
670 ITDebugLog(@"Setting up show player hot key.");
671 hotKey = [[ITHotKey alloc] init];
672 [hotKey setName:@"ShowPlayer"];
673 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
674 [hotKey setTarget:self];
675 [hotKey setAction:@selector(showPlayer)];
676 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
679 if ([df objectForKey:@"TrackInfo"] != nil) {
680 ITDebugLog(@"Setting up track info hot key.");
681 hotKey = [[ITHotKey alloc] init];
682 [hotKey setName:@"TrackInfo"];
683 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
684 [hotKey setTarget:self];
685 [hotKey setAction:@selector(showCurrentTrackInfo)];
686 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
689 if ([df objectForKey:@"UpcomingSongs"] != nil) {
690 ITDebugLog(@"Setting up upcoming songs hot key.");
691 hotKey = [[ITHotKey alloc] init];
692 [hotKey setName:@"UpcomingSongs"];
693 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
694 [hotKey setTarget:self];
695 [hotKey setAction:@selector(showUpcomingSongs)];
696 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
699 if ([df objectForKey:@"ToggleLoop"] != nil) {
700 ITDebugLog(@"Setting up toggle loop hot key.");
701 hotKey = [[ITHotKey alloc] init];
702 [hotKey setName:@"ToggleLoop"];
703 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
704 [hotKey setTarget:self];
705 [hotKey setAction:@selector(toggleLoop)];
706 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
709 if ([df objectForKey:@"ToggleShuffle"] != nil) {
710 ITDebugLog(@"Setting up toggle shuffle hot key.");
711 hotKey = [[ITHotKey alloc] init];
712 [hotKey setName:@"ToggleShuffle"];
713 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
714 [hotKey setTarget:self];
715 [hotKey setAction:@selector(toggleShuffle)];
716 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
719 if ([df objectForKey:@"IncrementVolume"] != nil) {
720 ITDebugLog(@"Setting up increment volume hot key.");
721 hotKey = [[ITHotKey alloc] init];
722 [hotKey setName:@"IncrementVolume"];
723 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
724 [hotKey setTarget:self];
725 [hotKey setAction:@selector(incrementVolume)];
726 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
729 if ([df objectForKey:@"DecrementVolume"] != nil) {
730 ITDebugLog(@"Setting up decrement volume hot key.");
731 hotKey = [[ITHotKey alloc] init];
732 [hotKey setName:@"DecrementVolume"];
733 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
734 [hotKey setTarget:self];
735 [hotKey setAction:@selector(decrementVolume)];
736 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
739 if ([df objectForKey:@"IncrementRating"] != nil) {
740 ITDebugLog(@"Setting up increment rating hot key.");
741 hotKey = [[ITHotKey alloc] init];
742 [hotKey setName:@"IncrementRating"];
743 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
744 [hotKey setTarget:self];
745 [hotKey setAction:@selector(incrementRating)];
746 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
749 if ([df objectForKey:@"DecrementRating"] != nil) {
750 ITDebugLog(@"Setting up decrement rating hot key.");
751 hotKey = [[ITHotKey alloc] init];
752 [hotKey setName:@"DecrementRating"];
753 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
754 [hotKey setTarget:self];
755 [hotKey setAction:@selector(decrementRating)];
756 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
758 ITDebugLog(@"Finished setting up hot keys.");
761 - (void)showCurrentTrackInfo
763 ITMTRemotePlayerSource source = 0;
764 NSString *title = nil;
765 NSString *album = nil;
766 NSString *artist = nil;
767 NSString *composer = nil;
768 NSString *time = nil;
769 NSString *track = nil;
773 ITDebugLog(@"Showing track info status window.");
776 source = [[self currentRemote] currentSource];
777 title = [[self currentRemote] currentSongTitle];
779 [self networkError:localException];
784 if ( [df boolForKey:@"showAlbum"] ) {
786 album = [[self currentRemote] currentSongAlbum];
788 [self networkError:localException];
792 if ( [df boolForKey:@"showArtist"] ) {
794 artist = [[self currentRemote] currentSongArtist];
796 [self networkError:localException];
800 if ( [df boolForKey:@"showComposer"] ) {
802 composer = [[self currentRemote] currentSongComposer];
804 [self networkError:localException];
808 if ( [df boolForKey:@"showTime"] ) {
810 time = [NSString stringWithFormat:@"%@: %@ / %@",
812 [[self currentRemote] currentSongElapsed],
813 [[self currentRemote] currentSongLength]];
815 [self networkError:localException];
819 if ( [df boolForKey:@"showTrackNumber"] ) {
824 trackNo = [[self currentRemote] currentSongTrack];
825 trackCount = [[self currentRemote] currentAlbumTrackCount];
827 [self networkError:localException];
830 if ( (trackNo > 0) || (trackCount > 0) ) {
831 track = [NSString stringWithFormat:@"%@: %i %@ %i",
832 @"Track", trackNo, @"of", trackCount];
836 if ( [df boolForKey:@"showTrackRating"] ) {
837 float currentRating = 0;
840 currentRating = [[self currentRemote] currentSongRating];
842 [self networkError:localException];
845 if (currentRating >= 0.0) {
846 rating = ( currentRating * 5 );
850 if ( [df boolForKey:@"showAlbumArtwork"] ) {
851 NSSize oldSize, newSize;
853 art = [[self currentRemote] currentSongAlbumArt];
854 oldSize = [art size];
855 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
856 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
857 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
859 [self networkError:localException];
864 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
866 ITDebugLog(@"Showing current track info status window.");
867 [statusWindowController showSongInfoWindowWithSource:source
878 - (void)showUpcomingSongs
882 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
884 [self networkError:localException];
887 ITDebugLog(@"Showing upcoming songs status window.");
890 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
891 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
892 int curTrack = [[self currentRemote] currentSongIndex];
895 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
897 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
901 if ([songList count] == 0) {
902 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
905 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
907 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
910 [self networkError:localException];
914 - (void)incrementVolume
917 float volume = [[self currentRemote] volume];
918 float dispVol = volume;
919 ITDebugLog(@"Incrementing volume.");
928 ITDebugLog(@"Setting volume to %f", volume);
929 [[self currentRemote] setVolume:volume];
931 // Show volume status window
932 [statusWindowController showVolumeWindowWithLevel:dispVol];
934 [self networkError:localException];
938 - (void)decrementVolume
941 float volume = [[self currentRemote] volume];
942 float dispVol = volume;
943 ITDebugLog(@"Decrementing volume.");
952 ITDebugLog(@"Setting volume to %f", volume);
953 [[self currentRemote] setVolume:volume];
955 //Show volume status window
956 [statusWindowController showVolumeWindowWithLevel:dispVol];
958 [self networkError:localException];
962 - (void)incrementRating
965 float rating = [[self currentRemote] currentSongRating];
966 ITDebugLog(@"Incrementing rating.");
968 if ([[self currentRemote] currentPlaylistIndex] == 0) {
969 ITDebugLog(@"No song playing, rating change aborted.");
977 ITDebugLog(@"Setting rating to %f", rating);
978 [[self currentRemote] setCurrentSongRating:rating];
980 //Show rating status window
981 [statusWindowController showRatingWindowWithRating:rating];
983 [self networkError:localException];
987 - (void)decrementRating
990 float rating = [[self currentRemote] currentSongRating];
991 ITDebugLog(@"Decrementing rating.");
993 if ([[self currentRemote] currentPlaylistIndex] == 0) {
994 ITDebugLog(@"No song playing, rating change aborted.");
1002 ITDebugLog(@"Setting rating to %f", rating);
1003 [[self currentRemote] setCurrentSongRating:rating];
1005 //Show rating status window
1006 [statusWindowController showRatingWindowWithRating:rating];
1008 [self networkError:localException];
1015 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1016 ITDebugLog(@"Toggling repeat mode.");
1017 switch (repeatMode) {
1018 case ITMTRemotePlayerRepeatOff:
1019 repeatMode = ITMTRemotePlayerRepeatAll;
1021 case ITMTRemotePlayerRepeatAll:
1022 repeatMode = ITMTRemotePlayerRepeatOne;
1024 case ITMTRemotePlayerRepeatOne:
1025 repeatMode = ITMTRemotePlayerRepeatOff;
1028 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1029 [[self currentRemote] setRepeatMode:repeatMode];
1031 //Show loop status window
1032 [statusWindowController showRepeatWindowWithMode:repeatMode];
1034 [self networkError:localException];
1038 - (void)toggleShuffle
1041 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1042 ITDebugLog(@"Toggling shuffle mode.");
1043 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1044 //Show shuffle status window
1045 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1046 [statusWindowController showShuffleWindow:newShuffleEnabled];
1048 [self networkError:localException];
1052 - (void)registerNowOK
1054 [[StatusWindow sharedWindow] setLocked:NO];
1055 [[StatusWindow sharedWindow] vanish:self];
1056 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1061 - (void)registerNowCancel
1063 [[StatusWindow sharedWindow] setLocked:NO];
1064 [[StatusWindow sharedWindow] vanish:self];
1065 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1067 [NSApp terminate:self];
1070 /*************************************************************************/
1072 #pragma mark NETWORK HANDLERS
1073 /*************************************************************************/
1075 - (void)setServerStatus:(BOOL)newStatus
1079 [networkController setServerStatus:YES];
1082 [networkController setServerStatus:NO];
1086 - (int)connectToServer
1089 ITDebugLog(@"Attempting to connect to shared remote.");
1090 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1093 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1094 currentRemote = [[[networkController networkObject] remote] retain];
1096 [self setupHotKeys];
1097 //playerRunningState = ITMTRemotePlayerRunning;
1098 playerRunningState = [[self currentRemote] playerRunningState];
1100 [refreshTimer invalidate];
1101 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1103 selector:@selector(timerUpdate)
1105 repeats:YES] retain];
1107 ITDebugLog(@"Connection successful.");
1109 } else if (result == 0) {
1110 ITDebugLog(@"Connection failed.");
1111 currentRemote = [remoteArray objectAtIndex:0];
1114 //Do something about the password being invalid
1115 ITDebugLog(@"Connection failed.");
1116 currentRemote = [remoteArray objectAtIndex:0];
1121 - (BOOL)disconnectFromServer
1123 ITDebugLog(@"Disconnecting from shared remote.");
1125 [currentRemote release];
1126 currentRemote = [remoteArray objectAtIndex:0];
1127 [networkController disconnect];
1129 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1130 [self applicationLaunched:nil];
1132 [self applicationTerminated:nil];
1138 - (void)checkForRemoteServer:(NSTimer *)timer
1140 ITDebugLog(@"Checking for remote server.");
1143 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:nil];
1144 //[timer invalidate];
1147 /*if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1148 ITDebugLog(@"Remote server found.");
1150 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1151 [[StatusWindowController sharedController] showReconnectQueryWindow];
1154 ITDebugLog(@"Remote server not found.");
1158 - (void)runRemoteServerCheck:(id)sender
1160 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1161 ITDebugLog(@"Remote server check running.");
1162 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1163 ITDebugLog(@"Remote server found.");
1164 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1166 ITDebugLog(@"Remote server not found.");
1167 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1172 - (void)remoteServerFound:(id)sender
1174 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1175 [[StatusWindowController sharedController] showReconnectQueryWindow];
1179 - (void)remoteServerNotFound:(id)sender
1181 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:NO];
1184 - (void)networkError:(NSException *)exception
1186 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1187 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1188 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);
1189 if ([self disconnectFromServer]) {
1190 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1191 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1193 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1200 if ([self connectToServer] == 0) {
1201 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1203 [[StatusWindow sharedWindow] setLocked:NO];
1204 [[StatusWindow sharedWindow] vanish:self];
1205 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1208 - (void)cancelReconnect
1210 [[StatusWindow sharedWindow] setLocked:NO];
1211 [[StatusWindow sharedWindow] vanish:self];
1212 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1215 /*************************************************************************/
1217 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1218 /*************************************************************************/
1220 - (void)applicationLaunched:(NSNotification *)note
1223 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1224 ITDebugLog(@"Remote application launched.");
1225 playerRunningState = ITMTRemotePlayerRunning;
1226 [[self currentRemote] begin];
1227 [self setLatestSongIdentifier:@""];
1229 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1231 selector:@selector(timerUpdate)
1233 repeats:YES] retain];
1234 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1235 [self setupHotKeys];
1238 [self networkError:localException];
1242 - (void)applicationTerminated:(NSNotification *)note
1245 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1246 ITDebugLog(@"Remote application terminated.");
1247 playerRunningState = ITMTRemotePlayerNotRunning;
1248 [[self currentRemote] halt];
1249 [refreshTimer invalidate];
1250 [refreshTimer release];
1252 [self clearHotKeys];
1254 if ([df objectForKey:@"ShowPlayer"] != nil) {
1256 ITDebugLog(@"Setting up show player hot key.");
1257 hotKey = [[ITHotKey alloc] init];
1258 [hotKey setName:@"ShowPlayer"];
1259 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1260 [hotKey setTarget:self];
1261 [hotKey setAction:@selector(showPlayer)];
1262 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1266 [self networkError:localException];
1271 /*************************************************************************/
1273 #pragma mark NSApplication DELEGATE METHODS
1274 /*************************************************************************/
1276 - (void)applicationWillTerminate:(NSNotification *)note
1278 [networkController stopRemoteServerSearch];
1279 [self clearHotKeys];
1280 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1284 /*************************************************************************/
1286 #pragma mark DEALLOCATION METHOD
1287 /*************************************************************************/
1291 [self applicationTerminated:nil];
1293 [statusItem release];
1294 [statusWindowController release];
1295 [menuController release];
1296 [networkController release];