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 ITDebugLog(@"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 - (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) {
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;
774 source = [[self currentRemote] currentSource];
775 title = [[self currentRemote] currentSongTitle];
777 [self networkError:localException];
780 ITDebugLog(@"Showing track info status window.");
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 [statusWindowController showSongInfoWindowWithSource:source
877 - (void)showUpcomingSongs
881 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
883 [self networkError:localException];
886 ITDebugLog(@"Showing upcoming songs status window.");
889 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
890 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
891 int curTrack = [[self currentRemote] currentSongIndex];
894 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
896 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
900 if ([songList count] == 0) {
901 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
904 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
906 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
909 [self networkError:localException];
913 - (void)incrementVolume
916 float volume = [[self currentRemote] volume];
917 float dispVol = volume;
918 ITDebugLog(@"Incrementing volume.");
927 ITDebugLog(@"Setting volume to %f", volume);
928 [[self currentRemote] setVolume:volume];
930 // Show volume status window
931 [statusWindowController showVolumeWindowWithLevel:dispVol];
933 [self networkError:localException];
937 - (void)decrementVolume
940 float volume = [[self currentRemote] volume];
941 float dispVol = volume;
942 ITDebugLog(@"Decrementing volume.");
951 ITDebugLog(@"Setting volume to %f", volume);
952 [[self currentRemote] setVolume:volume];
954 //Show volume status window
955 [statusWindowController showVolumeWindowWithLevel:dispVol];
957 [self networkError:localException];
961 - (void)incrementRating
964 float rating = [[self currentRemote] currentSongRating];
965 ITDebugLog(@"Incrementing rating.");
967 if ([[self currentRemote] currentPlaylistIndex] == 0) {
968 ITDebugLog(@"No song playing, rating change aborted.");
976 ITDebugLog(@"Setting rating to %f", rating);
977 [[self currentRemote] setCurrentSongRating:rating];
979 //Show rating status window
980 [statusWindowController showRatingWindowWithRating:rating];
982 [self networkError:localException];
986 - (void)decrementRating
989 float rating = [[self currentRemote] currentSongRating];
990 ITDebugLog(@"Decrementing rating.");
992 if ([[self currentRemote] currentPlaylistIndex] == 0) {
993 ITDebugLog(@"No song playing, rating change aborted.");
1001 ITDebugLog(@"Setting rating to %f", rating);
1002 [[self currentRemote] setCurrentSongRating:rating];
1004 //Show rating status window
1005 [statusWindowController showRatingWindowWithRating:rating];
1007 [self networkError:localException];
1014 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1015 ITDebugLog(@"Toggling repeat mode.");
1016 switch (repeatMode) {
1017 case ITMTRemotePlayerRepeatOff:
1018 repeatMode = ITMTRemotePlayerRepeatAll;
1020 case ITMTRemotePlayerRepeatAll:
1021 repeatMode = ITMTRemotePlayerRepeatOne;
1023 case ITMTRemotePlayerRepeatOne:
1024 repeatMode = ITMTRemotePlayerRepeatOff;
1027 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1028 [[self currentRemote] setRepeatMode:repeatMode];
1030 //Show loop status window
1031 [statusWindowController showRepeatWindowWithMode:repeatMode];
1033 [self networkError:localException];
1037 - (void)toggleShuffle
1040 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1041 ITDebugLog(@"Toggling shuffle mode.");
1042 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1043 //Show shuffle status window
1044 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1045 [statusWindowController showShuffleWindow:newShuffleEnabled];
1047 [self networkError:localException];
1051 - (void)registerNowOK
1053 [[StatusWindow sharedWindow] setLocked:NO];
1054 [[StatusWindow sharedWindow] vanish:self];
1055 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1060 - (void)registerNowCancel
1062 [[StatusWindow sharedWindow] setLocked:NO];
1063 [[StatusWindow sharedWindow] vanish:self];
1064 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1066 [NSApp terminate:self];
1069 /*************************************************************************/
1071 #pragma mark NETWORK HANDLERS
1072 /*************************************************************************/
1074 - (void)setServerStatus:(BOOL)newStatus
1078 [networkController setServerStatus:YES];
1081 [networkController setServerStatus:NO];
1085 - (int)connectToServer
1088 ITDebugLog(@"Attempting to connect to shared remote.");
1089 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1092 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1093 currentRemote = [[[networkController networkObject] remote] retain];
1094 [refreshTimer invalidate];
1095 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1097 selector:@selector(timerUpdate)
1099 repeats:YES] retain];
1101 ITDebugLog(@"Connection successful.");
1103 } else if (result == 0) {
1104 ITDebugLog(@"Connection failed.");
1105 currentRemote = [remoteArray objectAtIndex:0];
1108 //Do something about the password being invalid
1109 ITDebugLog(@"Connection failed.");
1110 currentRemote = [remoteArray objectAtIndex:0];
1115 - (BOOL)disconnectFromServer
1117 ITDebugLog(@"Disconnecting from shared remote.");
1119 [currentRemote release];
1120 currentRemote = [remoteArray objectAtIndex:0];
1121 [networkController disconnect];
1126 - (void)checkForRemoteServer:(NSTimer *)timer
1128 ITDebugLog(@"Checking for remote server.");
1129 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1130 ITDebugLog(@"Remote server found.");
1132 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1133 [[StatusWindowController sharedController] showReconnectQueryWindow];
1136 ITDebugLog(@"Remote server not found.");
1140 - (void)networkError:(NSException *)exception
1142 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1143 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1144 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);
1145 if ([self disconnectFromServer]) {
1146 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1147 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1149 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1156 if ([self connectToServer] == 0) {
1157 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1159 [[StatusWindow sharedWindow] setLocked:NO];
1160 [[StatusWindow sharedWindow] vanish:self];
1161 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1164 - (void)cancelReconnect
1166 [[StatusWindow sharedWindow] setLocked:NO];
1167 [[StatusWindow sharedWindow] vanish:self];
1168 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1171 /*************************************************************************/
1173 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1174 /*************************************************************************/
1176 - (void)applicationLaunched:(NSNotification *)note
1179 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1180 ITDebugLog(@"Remote application launched.");
1181 playerRunningState = ITMTRemotePlayerRunning;
1182 [[self currentRemote] begin];
1183 [self setLatestSongIdentifier:@""];
1185 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1187 selector:@selector(timerUpdate)
1189 repeats:YES] retain];
1190 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1191 [self setupHotKeys];
1194 [self networkError:localException];
1198 - (void)applicationTerminated:(NSNotification *)note
1201 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1202 ITDebugLog(@"Remote application terminated.");
1203 playerRunningState = ITMTRemotePlayerNotRunning;
1204 [[self currentRemote] halt];
1205 [refreshTimer invalidate];
1206 [refreshTimer release];
1208 [self clearHotKeys];
1210 if ([df objectForKey:@"ShowPlayer"] != nil) {
1212 ITDebugLog(@"Setting up show player hot key.");
1213 hotKey = [[ITHotKey alloc] init];
1214 [hotKey setName:@"ShowPlayer"];
1215 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1216 [hotKey setTarget:self];
1217 [hotKey setAction:@selector(showPlayer)];
1218 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1222 [self networkError:localException];
1227 /*************************************************************************/
1229 #pragma mark NSApplication DELEGATE METHODS
1230 /*************************************************************************/
1232 - (void)applicationWillTerminate:(NSNotification *)note
1234 [networkController stopRemoteServerSearch];
1235 [self clearHotKeys];
1236 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1240 /*************************************************************************/
1242 #pragma mark DEALLOCATION METHOD
1243 /*************************************************************************/
1247 [self applicationTerminated:nil];
1249 [statusItem release];
1250 [statusWindowController release];
1251 [menuController release];
1252 [networkController release];