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 if ([self connectToServer] == 0) {
93 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
97 //Setup for notification of the remote player launching or quitting
98 [[[NSWorkspace sharedWorkspace] notificationCenter]
100 selector:@selector(applicationTerminated:)
101 name:NSWorkspaceDidTerminateApplicationNotification
104 [[[NSWorkspace sharedWorkspace] notificationCenter]
106 selector:@selector(applicationLaunched:)
107 name:NSWorkspaceDidLaunchApplicationNotification
110 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
111 [[PreferencesController sharedPrefs] registerDefaults];
114 if ([df boolForKey:@"ITMTNoStatusItem"]) {
117 [StatusItemHack install];
118 statusItem = [[ITStatusItem alloc]
119 initWithStatusBar:[NSStatusBar systemStatusBar]
120 withLength:NSSquareStatusItemLength];
123 bling = [[MTBlingController alloc] init];
125 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
127 selector:@selector(blingTime)
129 repeats:YES] retain];
132 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
133 [self applicationLaunched:nil];
135 if ([df boolForKey:@"LaunchPlayerWithMT"])
138 [self applicationTerminated:nil];
141 [self networkError:localException];
144 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
145 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
147 [networkController startRemoteServerSearch];
151 - (ITMTRemote *)loadRemote
153 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
154 ITDebugLog(@"Gathering remotes.");
156 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
157 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
158 NSString *bundlePath;
160 while ( (bundlePath = [enumerator nextObject]) ) {
161 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
164 Class remoteClass = [remoteBundle principalClass];
166 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
167 [remoteClass isKindOfClass:[NSObject class]]) {
168 id remote = [remoteClass remote];
169 ITDebugLog(@"Adding remote at path %@", bundlePath);
170 [remoteArray addObject:remote];
175 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
176 // if ( [remoteArray count] > 1 ) {
177 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
179 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
182 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
183 return [remoteArray objectAtIndex:0];
186 /*************************************************************************/
188 #pragma mark INSTANCE METHODS
189 /*************************************************************************/
191 /*- (void)startTimerInNewThread
193 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
194 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
195 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
197 selector:@selector(timerUpdate)
199 repeats:YES] retain];
201 ITDebugLog(@"Timer started.");
205 - (void)setBlingTime:(NSDate*)date
207 NSMutableDictionary *globalPrefs;
209 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
211 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
212 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
214 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
215 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
217 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
219 [globalPrefs release];
222 - (NSDate*)getBlingTime
225 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
230 NSDate *now = [NSDate date];
231 if (![self blingBling]) {
232 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
233 [self setBlingTime:now];
234 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
235 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
236 [self setBlingTime:[now addTimeInterval:-259200]];
238 NSMutableDictionary *globalPrefs;
240 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
241 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
242 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
244 [globalPrefs release];
248 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
250 [statusItem setEnabled:NO];
252 if ([refreshTimer isValid]) {
253 [refreshTimer invalidate];
255 [statusWindowController showRegistrationQueryWindow];
259 [statusItem setEnabled:YES];
261 if (![refreshTimer isValid]) {
262 [refreshTimer release];
263 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
265 selector:@selector(timerUpdate)
267 repeats:YES] retain];
271 [self setBlingTime:nil];
282 if ( ! ([bling checkDone] == 2475) ) {
289 - (BOOL)songIsPlaying
291 NSString *identifier = nil;
293 identifier = [[self currentRemote] playerStateUniqueIdentifier];
295 [self networkError:localException];
297 return ( ! ([identifier isEqualToString:@"0-0"]) );
300 - (BOOL)radioIsPlaying
302 ITMTRemotePlayerPlaylistClass class = nil;
304 class = [[self currentRemote] currentPlaylistClass];
306 [self networkError:localException];
308 return (class == ITMTRemotePlayerRadioPlaylist );
313 NSString *identifier = nil;
315 identifier = [[self currentRemote] playerStateUniqueIdentifier];
317 [self networkError:localException];
319 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
322 - (NSString *)latestSongIdentifier
324 return _latestSongIdentifier;
327 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
329 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
330 [_latestSongIdentifier autorelease];
331 _latestSongIdentifier = [newIdentifier copy];
336 if ([networkController isConnectedToServer]) {
337 [statusItem setMenu:[menuController menu]];
340 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
341 ITDebugLog(@"The song changed.");
343 if ([df boolForKey:@"runScripts"]) {
344 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
345 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
346 NSString *nextScript;
347 ITDebugLog(@"Running AppleScripts for song change.");
348 while ( (nextScript = [scriptsEnum nextObject]) ) {
350 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
351 ITDebugLog(@"Running script: %@", nextScript);
352 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
353 ITDebugLog(@"Error running script %@.", nextScript);
355 [currentScript release];
362 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
363 [menuController rebuildSubmenus];
365 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
366 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
369 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
371 //Create the tooltip for the status item
372 if ( [df boolForKey:@"showToolTip"] ) {
373 NSString *artist = [[self currentRemote] currentSongArtist];
374 NSString *title = [[self currentRemote] currentSongTitle];
376 ITDebugLog(@"Creating status item tooltip.");
378 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
382 toolTip = @"No Song Playing";
384 [statusItem setToolTip:toolTip];
386 [statusItem setToolTip:nil];
389 [self networkError:localException];
398 ITDebugLog(@"Menu clicked.");
399 if ([networkController isConnectedToServer]) {
400 //Used the cached version
405 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
406 [statusItem setMenu:[menuController menu]];
408 [statusItem setMenu:[menuController menuForNoPlayer]];
411 [self networkError:localException];
424 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
425 ITDebugLog(@"Play/Pause toggled");
426 if (state == ITMTRemotePlayerPlaying) {
427 [[self currentRemote] pause];
428 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
429 [[self currentRemote] pause];
430 [[self currentRemote] play];
432 [[self currentRemote] play];
435 [self networkError:localException];
443 ITDebugLog(@"Going to next song.");
445 [[self currentRemote] goToNextSong];
447 [self networkError:localException];
454 ITDebugLog(@"Going to previous song.");
456 [[self currentRemote] goToPreviousSong];
458 [self networkError:localException];
465 ITDebugLog(@"Fast forwarding.");
467 [[self currentRemote] forward];
469 [self networkError:localException];
476 ITDebugLog(@"Rewinding.");
478 [[self currentRemote] rewind];
480 [self networkError:localException];
485 - (void)selectPlaylistAtIndex:(int)index
487 ITDebugLog(@"Selecting playlist %i", index);
489 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
490 //[[self currentRemote] switchToPlaylistAtIndex:index];
492 [self networkError:localException];
497 - (void)selectSongAtIndex:(int)index
499 ITDebugLog(@"Selecting song %i", index);
501 [[self currentRemote] switchToSongAtIndex:index];
503 [self networkError:localException];
508 - (void)selectSongRating:(int)rating
510 ITDebugLog(@"Selecting song rating %i", rating);
512 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
514 [self networkError:localException];
519 - (void)selectEQPresetAtIndex:(int)index
521 ITDebugLog(@"Selecting EQ preset %i", index);
523 [[self currentRemote] switchToEQAtIndex:index];
525 [self networkError:localException];
532 ITDebugLog(@"Beginning show player.");
533 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
534 ITDebugLog(@"Showing player interface.");
536 [[self currentRemote] showPrimaryInterface];
538 [self networkError:localException];
541 ITDebugLog(@"Launching player.");
544 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
546 path = [[self currentRemote] playerFullName];
548 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
549 ITDebugLog(@"Error Launching Player");
552 [self networkError:localException];
555 ITDebugLog(@"Finished show player.");
558 - (void)showPreferences
560 ITDebugLog(@"Show preferences.");
561 [[PreferencesController sharedPrefs] showPrefsWindow:self];
564 - (void)showPreferencesAndClose
566 ITDebugLog(@"Show preferences.");
567 [[PreferencesController sharedPrefs] showPrefsWindow:self];
568 [[StatusWindow sharedWindow] setLocked:NO];
569 [[StatusWindow sharedWindow] vanish:self];
570 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
573 - (void)showTestWindow
575 [self showCurrentTrackInfo];
578 - (void)quitMenuTunes
580 ITDebugLog(@"Quitting MenuTunes.");
581 [NSApp terminate:self];
587 - (MenuController *)menuController
589 return menuController;
592 - (void)closePreferences
594 ITDebugLog(@"Preferences closed.");
595 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
600 - (ITMTRemote *)currentRemote
602 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
603 [self networkError:nil];
606 return currentRemote;
617 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
618 ITHotKey *nextHotKey;
619 ITDebugLog(@"Clearing hot keys.");
620 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
621 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
623 ITDebugLog(@"Done clearing hot keys.");
629 ITDebugLog(@"Setting up hot keys.");
631 if (playerRunningState == ITMTRemotePlayerNotRunning) {
635 if ([df objectForKey:@"PlayPause"] != nil) {
636 ITDebugLog(@"Setting up play pause hot key.");
637 hotKey = [[ITHotKey alloc] init];
638 [hotKey setName:@"PlayPause"];
639 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
640 [hotKey setTarget:self];
641 [hotKey setAction:@selector(playPause)];
642 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
645 if ([df objectForKey:@"NextTrack"] != nil) {
646 ITDebugLog(@"Setting up next track hot key.");
647 hotKey = [[ITHotKey alloc] init];
648 [hotKey setName:@"NextTrack"];
649 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
650 [hotKey setTarget:self];
651 [hotKey setAction:@selector(nextSong)];
652 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
655 if ([df objectForKey:@"PrevTrack"] != nil) {
656 ITDebugLog(@"Setting up previous track hot key.");
657 hotKey = [[ITHotKey alloc] init];
658 [hotKey setName:@"PrevTrack"];
659 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
660 [hotKey setTarget:self];
661 [hotKey setAction:@selector(prevSong)];
662 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
665 if ([df objectForKey:@"ShowPlayer"] != nil) {
666 ITDebugLog(@"Setting up show player hot key.");
667 hotKey = [[ITHotKey alloc] init];
668 [hotKey setName:@"ShowPlayer"];
669 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
670 [hotKey setTarget:self];
671 [hotKey setAction:@selector(showPlayer)];
672 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
675 if ([df objectForKey:@"TrackInfo"] != nil) {
676 ITDebugLog(@"Setting up track info hot key.");
677 hotKey = [[ITHotKey alloc] init];
678 [hotKey setName:@"TrackInfo"];
679 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
680 [hotKey setTarget:self];
681 [hotKey setAction:@selector(showCurrentTrackInfo)];
682 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
685 if ([df objectForKey:@"UpcomingSongs"] != nil) {
686 ITDebugLog(@"Setting up upcoming songs hot key.");
687 hotKey = [[ITHotKey alloc] init];
688 [hotKey setName:@"UpcomingSongs"];
689 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
690 [hotKey setTarget:self];
691 [hotKey setAction:@selector(showUpcomingSongs)];
692 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
695 if ([df objectForKey:@"ToggleLoop"] != nil) {
696 ITDebugLog(@"Setting up toggle loop hot key.");
697 hotKey = [[ITHotKey alloc] init];
698 [hotKey setName:@"ToggleLoop"];
699 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
700 [hotKey setTarget:self];
701 [hotKey setAction:@selector(toggleLoop)];
702 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
705 if ([df objectForKey:@"ToggleShuffle"] != nil) {
706 ITDebugLog(@"Setting up toggle shuffle hot key.");
707 hotKey = [[ITHotKey alloc] init];
708 [hotKey setName:@"ToggleShuffle"];
709 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
710 [hotKey setTarget:self];
711 [hotKey setAction:@selector(toggleShuffle)];
712 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
715 if ([df objectForKey:@"IncrementVolume"] != nil) {
716 ITDebugLog(@"Setting up increment volume hot key.");
717 hotKey = [[ITHotKey alloc] init];
718 [hotKey setName:@"IncrementVolume"];
719 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
720 [hotKey setTarget:self];
721 [hotKey setAction:@selector(incrementVolume)];
722 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
725 if ([df objectForKey:@"DecrementVolume"] != nil) {
726 ITDebugLog(@"Setting up decrement volume hot key.");
727 hotKey = [[ITHotKey alloc] init];
728 [hotKey setName:@"DecrementVolume"];
729 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
730 [hotKey setTarget:self];
731 [hotKey setAction:@selector(decrementVolume)];
732 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
735 if ([df objectForKey:@"IncrementRating"] != nil) {
736 ITDebugLog(@"Setting up increment rating hot key.");
737 hotKey = [[ITHotKey alloc] init];
738 [hotKey setName:@"IncrementRating"];
739 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
740 [hotKey setTarget:self];
741 [hotKey setAction:@selector(incrementRating)];
742 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
745 if ([df objectForKey:@"DecrementRating"] != nil) {
746 ITDebugLog(@"Setting up decrement rating hot key.");
747 hotKey = [[ITHotKey alloc] init];
748 [hotKey setName:@"DecrementRating"];
749 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
750 [hotKey setTarget:self];
751 [hotKey setAction:@selector(decrementRating)];
752 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
754 ITDebugLog(@"Finished setting up hot keys.");
757 - (void)showCurrentTrackInfo
759 ITMTRemotePlayerSource source = 0;
760 NSString *title = nil;
761 NSString *album = nil;
762 NSString *artist = nil;
763 NSString *composer = nil;
764 NSString *time = nil;
765 NSString *track = nil;
770 source = [[self currentRemote] currentSource];
771 title = [[self currentRemote] currentSongTitle];
773 [self networkError:localException];
776 ITDebugLog(@"Showing track info status window.");
780 if ( [df boolForKey:@"showAlbum"] ) {
782 album = [[self currentRemote] currentSongAlbum];
784 [self networkError:localException];
788 if ( [df boolForKey:@"showArtist"] ) {
790 artist = [[self currentRemote] currentSongArtist];
792 [self networkError:localException];
796 if ( [df boolForKey:@"showComposer"] ) {
798 composer = [[self currentRemote] currentSongComposer];
800 [self networkError:localException];
804 if ( [df boolForKey:@"showTime"] ) {
806 time = [NSString stringWithFormat:@"%@: %@ / %@",
808 [[self currentRemote] currentSongElapsed],
809 [[self currentRemote] currentSongLength]];
811 [self networkError:localException];
815 if ( [df boolForKey:@"showTrackNumber"] ) {
820 trackNo = [[self currentRemote] currentSongTrack];
821 trackCount = [[self currentRemote] currentAlbumTrackCount];
823 [self networkError:localException];
826 if ( (trackNo > 0) || (trackCount > 0) ) {
827 track = [NSString stringWithFormat:@"%@: %i %@ %i",
828 @"Track", trackNo, @"of", trackCount];
832 if ( [df boolForKey:@"showTrackRating"] ) {
833 float currentRating = 0;
836 currentRating = [[self currentRemote] currentSongRating];
838 [self networkError:localException];
841 if (currentRating >= 0.0) {
842 rating = ( currentRating * 5 );
846 if ( [df boolForKey:@"showAlbumArtwork"] ) {
847 NSSize oldSize, newSize;
849 art = [[self currentRemote] currentSongAlbumArt];
850 oldSize = [art size];
851 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
852 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
853 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
855 [self networkError:localException];
860 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
862 [statusWindowController showSongInfoWindowWithSource:source
873 - (void)showUpcomingSongs
877 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
879 [self networkError:localException];
882 ITDebugLog(@"Showing upcoming songs status window.");
885 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
886 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
887 int curTrack = [[self currentRemote] currentSongIndex];
890 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
892 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
896 if ([songList count] == 0) {
897 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
900 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
902 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
905 [self networkError:localException];
909 - (void)incrementVolume
912 float volume = [[self currentRemote] volume];
913 float dispVol = volume;
914 ITDebugLog(@"Incrementing volume.");
923 ITDebugLog(@"Setting volume to %f", volume);
924 [[self currentRemote] setVolume:volume];
926 // Show volume status window
927 [statusWindowController showVolumeWindowWithLevel:dispVol];
929 [self networkError:localException];
933 - (void)decrementVolume
936 float volume = [[self currentRemote] volume];
937 float dispVol = volume;
938 ITDebugLog(@"Decrementing volume.");
947 ITDebugLog(@"Setting volume to %f", volume);
948 [[self currentRemote] setVolume:volume];
950 //Show volume status window
951 [statusWindowController showVolumeWindowWithLevel:dispVol];
953 [self networkError:localException];
957 - (void)incrementRating
960 float rating = [[self currentRemote] currentSongRating];
961 ITDebugLog(@"Incrementing rating.");
963 if ([[self currentRemote] currentPlaylistIndex] == 0) {
964 ITDebugLog(@"No song playing, rating change aborted.");
972 ITDebugLog(@"Setting rating to %f", rating);
973 [[self currentRemote] setCurrentSongRating:rating];
975 //Show rating status window
976 [statusWindowController showRatingWindowWithRating:rating];
978 [self networkError:localException];
982 - (void)decrementRating
985 float rating = [[self currentRemote] currentSongRating];
986 ITDebugLog(@"Decrementing rating.");
988 if ([[self currentRemote] currentPlaylistIndex] == 0) {
989 ITDebugLog(@"No song playing, rating change aborted.");
997 ITDebugLog(@"Setting rating to %f", rating);
998 [[self currentRemote] setCurrentSongRating:rating];
1000 //Show rating status window
1001 [statusWindowController showRatingWindowWithRating:rating];
1003 [self networkError:localException];
1010 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1011 ITDebugLog(@"Toggling repeat mode.");
1012 switch (repeatMode) {
1013 case ITMTRemotePlayerRepeatOff:
1014 repeatMode = ITMTRemotePlayerRepeatAll;
1016 case ITMTRemotePlayerRepeatAll:
1017 repeatMode = ITMTRemotePlayerRepeatOne;
1019 case ITMTRemotePlayerRepeatOne:
1020 repeatMode = ITMTRemotePlayerRepeatOff;
1023 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1024 [[self currentRemote] setRepeatMode:repeatMode];
1026 //Show loop status window
1027 [statusWindowController showRepeatWindowWithMode:repeatMode];
1029 [self networkError:localException];
1033 - (void)toggleShuffle
1036 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1037 ITDebugLog(@"Toggling shuffle mode.");
1038 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1039 //Show shuffle status window
1040 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1041 [statusWindowController showShuffleWindow:newShuffleEnabled];
1043 [self networkError:localException];
1047 - (void)registerNowOK
1049 [[StatusWindow sharedWindow] setLocked:NO];
1050 [[StatusWindow sharedWindow] vanish:self];
1051 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1056 - (void)registerNowCancel
1058 [[StatusWindow sharedWindow] setLocked:NO];
1059 [[StatusWindow sharedWindow] vanish:self];
1060 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1062 [NSApp terminate:self];
1065 /*************************************************************************/
1067 #pragma mark NETWORK HANDLERS
1068 /*************************************************************************/
1070 - (void)setServerStatus:(BOOL)newStatus
1074 [networkController setServerStatus:YES];
1077 [networkController setServerStatus:NO];
1081 - (int)connectToServer
1084 ITDebugLog(@"Attempting to connect to shared remote.");
1085 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1088 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1089 currentRemote = [[[networkController networkObject] remote] retain];
1090 [refreshTimer invalidate];
1091 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1093 selector:@selector(timerUpdate)
1095 repeats:YES] retain];
1097 ITDebugLog(@"Connection successful.");
1099 } else if (result == 0) {
1100 ITDebugLog(@"Connection failed.");
1101 currentRemote = [remoteArray objectAtIndex:0];
1104 //Do something about the password being invalid
1105 ITDebugLog(@"Connection failed.");
1106 currentRemote = [remoteArray objectAtIndex:0];
1111 - (BOOL)disconnectFromServer
1113 ITDebugLog(@"Disconnecting from shared remote.");
1115 [currentRemote release];
1116 currentRemote = [remoteArray objectAtIndex:0];
1117 [networkController disconnect];
1122 - (void)checkForRemoteServer:(NSTimer *)timer
1124 ITDebugLog(@"Checking for remote server.");
1125 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1126 ITDebugLog(@"Remote server found.");
1128 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1129 [[StatusWindowController sharedController] showReconnectQueryWindow];
1132 ITDebugLog(@"Remote server not found.");
1136 - (void)networkError:(NSException *)exception
1138 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1139 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1140 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);
1141 if ([self disconnectFromServer]) {
1142 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1143 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1145 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1152 if ([self connectToServer] == 0) {
1153 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1155 [[StatusWindow sharedWindow] setLocked:NO];
1156 [[StatusWindow sharedWindow] vanish:self];
1157 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1160 - (void)cancelReconnect
1162 [[StatusWindow sharedWindow] setLocked:NO];
1163 [[StatusWindow sharedWindow] vanish:self];
1164 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1167 /*************************************************************************/
1169 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1170 /*************************************************************************/
1172 - (void)applicationLaunched:(NSNotification *)note
1175 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1176 ITDebugLog(@"Remote application launched.");
1177 playerRunningState = ITMTRemotePlayerRunning;
1178 [[self currentRemote] begin];
1179 [self setLatestSongIdentifier:@""];
1181 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1183 selector:@selector(timerUpdate)
1185 repeats:YES] retain];
1186 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1187 [self setupHotKeys];
1190 [self networkError:localException];
1194 - (void)applicationTerminated:(NSNotification *)note
1197 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1198 ITDebugLog(@"Remote application terminated.");
1199 playerRunningState = ITMTRemotePlayerNotRunning;
1200 [[self currentRemote] halt];
1201 [refreshTimer invalidate];
1202 [refreshTimer release];
1204 [self clearHotKeys];
1206 if ([df objectForKey:@"ShowPlayer"] != nil) {
1208 ITDebugLog(@"Setting up show player hot key.");
1209 hotKey = [[ITHotKey alloc] init];
1210 [hotKey setName:@"ShowPlayer"];
1211 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1212 [hotKey setTarget:self];
1213 [hotKey setAction:@selector(showPlayer)];
1214 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1218 [self networkError:localException];
1223 /*************************************************************************/
1225 #pragma mark NSApplication DELEGATE METHODS
1226 /*************************************************************************/
1228 - (void)applicationWillTerminate:(NSNotification *)note
1230 [networkController stopRemoteServerSearch];
1231 [self clearHotKeys];
1232 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1236 /*************************************************************************/
1238 #pragma mark DEALLOCATION METHOD
1239 /*************************************************************************/
1243 [self applicationTerminated:nil];
1245 [statusItem release];
1246 [statusWindowController release];
1247 [menuController release];
1248 [networkController release];