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)checkForRemoteServer;
37 - (void)applicationLaunched:(NSNotification *)note;
38 - (void)applicationTerminated:(NSNotification *)note;
41 static MainController *sharedController;
43 @implementation MainController
45 + (MainController *)sharedController
47 return sharedController;
50 /*************************************************************************/
52 #pragma mark INITIALIZATION/DEALLOCATION METHODS
53 /*************************************************************************/
57 if ( ( self = [super init] ) ) {
58 sharedController = self;
60 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
61 [[PreferencesController sharedPrefs] setController:self];
62 statusWindowController = [StatusWindowController sharedController];
63 menuController = [[MenuController alloc] init];
64 df = [[NSUserDefaults standardUserDefaults] retain];
71 - (void)applicationDidFinishLaunching:(NSNotification *)note
73 //Turn on debug mode if needed
74 if ([df boolForKey:@"ITDebugMode"]) {
78 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
79 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
81 [[PreferencesController sharedPrefs] registerDefaults];
82 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
85 currentRemote = [self loadRemote];
86 [[self currentRemote] begin];
88 //Turn on network stuff if needed
89 networkController = [[NetworkController alloc] init];
90 if ([df boolForKey:@"enableSharing"]) {
91 [self setServerStatus:YES];
92 } else if ([df boolForKey:@"useSharedPlayer"]) {
93 [self checkForRemoteServer];
96 //Setup for notification of the remote player launching or quitting
97 [[[NSWorkspace sharedWorkspace] notificationCenter]
99 selector:@selector(applicationTerminated:)
100 name:NSWorkspaceDidTerminateApplicationNotification
103 [[[NSWorkspace sharedWorkspace] notificationCenter]
105 selector:@selector(applicationLaunched:)
106 name:NSWorkspaceDidLaunchApplicationNotification
109 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
110 [[PreferencesController sharedPrefs] registerDefaults];
113 if ([df boolForKey:@"ITMTNoStatusItem"]) {
116 [StatusItemHack install];
117 statusItem = [[ITStatusItem alloc]
118 initWithStatusBar:[NSStatusBar systemStatusBar]
119 withLength:NSSquareStatusItemLength];
122 bling = [[MTBlingController alloc] init];
124 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
126 selector:@selector(blingTime)
128 repeats:YES] retain];
131 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
132 [self applicationLaunched:nil];
134 if ([df boolForKey:@"LaunchPlayerWithMT"])
137 [self applicationTerminated:nil];
140 [self networkError:localException];
143 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
144 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
146 [networkController startRemoteServerSearch];
150 - (ITMTRemote *)loadRemote
152 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
153 ITDebugLog(@"Gathering remotes.");
155 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
156 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
157 NSString *bundlePath;
159 while ( (bundlePath = [enumerator nextObject]) ) {
160 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
163 Class remoteClass = [remoteBundle principalClass];
165 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
166 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
167 id remote = [remoteClass remote];
168 ITDebugLog(@"Adding remote at path %@", bundlePath);
169 [remoteArray addObject:remote];
174 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
175 // if ( [remoteArray count] > 1 ) {
176 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
178 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
181 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
182 return [remoteArray objectAtIndex:0];
185 /*************************************************************************/
187 #pragma mark INSTANCE METHODS
188 /*************************************************************************/
190 /*- (void)startTimerInNewThread
192 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
193 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
194 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
196 selector:@selector(timerUpdate)
198 repeats:YES] retain];
200 ITDebugLog(@"Timer started.");
204 - (void)setBlingTime:(NSDate*)date
206 NSMutableDictionary *globalPrefs;
208 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
210 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
211 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
213 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
214 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
216 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
218 [globalPrefs release];
221 - (NSDate*)getBlingTime
224 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
229 NSDate *now = [NSDate date];
230 if (![self blingBling]) {
231 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
232 [self setBlingTime:now];
233 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
234 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
235 [self setBlingTime:[now addTimeInterval:-259200]];
237 NSMutableDictionary *globalPrefs;
239 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
240 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
241 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
243 [globalPrefs release];
247 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
249 [statusItem setEnabled:NO];
251 if ([refreshTimer isValid]) {
252 [refreshTimer invalidate];
254 [statusWindowController showRegistrationQueryWindow];
258 [statusItem setEnabled:YES];
260 if (![refreshTimer isValid]) {
261 [refreshTimer release];
262 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
264 selector:@selector(timerUpdate)
266 repeats:YES] retain];
270 [self setBlingTime:nil];
281 if ( ! ([bling checkDone] == 2475) ) {
288 - (BOOL)songIsPlaying
290 NSString *identifier = nil;
292 identifier = [[self currentRemote] playerStateUniqueIdentifier];
294 [self networkError:localException];
296 return ( ! ([identifier isEqualToString:@"0-0"]) );
299 - (BOOL)radioIsPlaying
301 ITMTRemotePlayerPlaylistClass class = nil;
303 class = [[self currentRemote] currentPlaylistClass];
305 [self networkError:localException];
307 return (class == ITMTRemotePlayerRadioPlaylist );
312 NSString *identifier = nil;
314 identifier = [[self currentRemote] playerStateUniqueIdentifier];
316 [self networkError:localException];
318 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
321 - (NSString *)latestSongIdentifier
323 return _latestSongIdentifier;
326 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
328 ITDebugLog(@"Setting latest song identifier:");
329 ITDebugLog(@" - Identifier: %@", newIdentifier);
330 [_latestSongIdentifier autorelease];
331 _latestSongIdentifier = [newIdentifier retain];
336 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
337 ITDebugLog(@"The song changed.");
339 if ([df boolForKey:@"runScripts"]) {
340 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
341 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
342 NSString *nextScript;
343 ITDebugLog(@"Running AppleScripts for song change.");
344 while ( (nextScript = [scriptsEnum nextObject]) ) {
346 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
347 ITDebugLog(@"Running script: %@", nextScript);
348 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
349 ITDebugLog(@"Error running script %@.", nextScript);
351 [currentScript release];
356 [statusItem setEnabled:NO];
359 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
360 [menuController rebuildSubmenus];
362 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
363 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
366 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
368 //Create the tooltip for the status item
369 if ( [df boolForKey:@"showToolTip"] ) {
370 NSString *artist = [[self currentRemote] currentSongArtist];
371 NSString *title = [[self currentRemote] currentSongTitle];
373 ITDebugLog(@"Creating status item tooltip.");
375 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
379 toolTip = @"No Song Playing";
381 [statusItem setToolTip:toolTip];
383 [statusItem setToolTip:nil];
386 [self networkError:localException];
390 [statusItem setEnabled:YES];
393 if ([networkController isConnectedToServer]) {
394 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
400 ITDebugLog(@"Menu clicked.");
401 if ([networkController isConnectedToServer]) {
402 //Used the cached version
407 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
408 [statusItem setMenu:[menuController menu]];
410 [statusItem setMenu:[menuController menuForNoPlayer]];
413 [self networkError:localException];
426 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
427 ITDebugLog(@"Play/Pause toggled");
428 if (state == ITMTRemotePlayerPlaying) {
429 [[self currentRemote] pause];
430 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
431 [[self currentRemote] pause];
432 [[self currentRemote] play];
434 [[self currentRemote] play];
437 [self networkError:localException];
445 ITDebugLog(@"Going to next song.");
447 [[self currentRemote] goToNextSong];
449 [self networkError:localException];
456 ITDebugLog(@"Going to previous song.");
458 [[self currentRemote] goToPreviousSong];
460 [self networkError:localException];
467 ITDebugLog(@"Fast forwarding.");
469 [[self currentRemote] forward];
471 [self networkError:localException];
478 ITDebugLog(@"Rewinding.");
480 [[self currentRemote] rewind];
482 [self networkError:localException];
487 - (void)selectPlaylistAtIndex:(int)index
489 ITDebugLog(@"Selecting playlist %i", index);
491 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
492 //[[self currentRemote] switchToPlaylistAtIndex:index];
494 [self networkError:localException];
499 - (void)selectSongAtIndex:(int)index
501 ITDebugLog(@"Selecting song %i", index);
503 [[self currentRemote] switchToSongAtIndex:index];
505 [self networkError:localException];
510 - (void)selectSongRating:(int)rating
512 ITDebugLog(@"Selecting song rating %i", rating);
514 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
516 [self networkError:localException];
521 - (void)selectEQPresetAtIndex:(int)index
523 ITDebugLog(@"Selecting EQ preset %i", index);
525 [[self currentRemote] switchToEQAtIndex:index];
527 [self networkError:localException];
534 ITDebugLog(@"Beginning show player.");
535 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
536 ITDebugLog(@"Showing player interface.");
538 [[self currentRemote] showPrimaryInterface];
540 [self networkError:localException];
543 ITDebugLog(@"Launching player.");
546 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
548 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
550 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
551 ITDebugLog(@"Error Launching Player");
554 [self networkError:localException];
557 ITDebugLog(@"Finished show player.");
560 - (void)showPreferences
562 ITDebugLog(@"Show preferences.");
563 [[PreferencesController sharedPrefs] showPrefsWindow:self];
566 - (void)showPreferencesAndClose
568 ITDebugLog(@"Show preferences.");
569 [[PreferencesController sharedPrefs] showPrefsWindow:self];
570 [[StatusWindow sharedWindow] setLocked:NO];
571 [[StatusWindow sharedWindow] vanish:self];
572 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
575 - (void)showTestWindow
577 [self showCurrentTrackInfo];
580 - (void)quitMenuTunes
582 ITDebugLog(@"Quitting MenuTunes.");
583 [NSApp terminate:self];
589 - (MenuController *)menuController
591 return menuController;
594 - (void)closePreferences
596 ITDebugLog(@"Preferences closed.");
597 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
602 - (ITMTRemote *)currentRemote
604 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
605 [self networkError:nil];
608 return currentRemote;
619 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
620 ITHotKey *nextHotKey;
621 ITDebugLog(@"Clearing hot keys.");
622 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
623 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
625 ITDebugLog(@"Done clearing hot keys.");
631 ITDebugLog(@"Setting up hot keys.");
633 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
637 if ([df objectForKey:@"PlayPause"] != nil) {
638 ITDebugLog(@"Setting up play pause hot key.");
639 hotKey = [[ITHotKey alloc] init];
640 [hotKey setName:@"PlayPause"];
641 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
642 [hotKey setTarget:self];
643 [hotKey setAction:@selector(playPause)];
644 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
647 if ([df objectForKey:@"NextTrack"] != nil) {
648 ITDebugLog(@"Setting up next track hot key.");
649 hotKey = [[ITHotKey alloc] init];
650 [hotKey setName:@"NextTrack"];
651 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
652 [hotKey setTarget:self];
653 [hotKey setAction:@selector(nextSong)];
654 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
657 if ([df objectForKey:@"PrevTrack"] != nil) {
658 ITDebugLog(@"Setting up previous track hot key.");
659 hotKey = [[ITHotKey alloc] init];
660 [hotKey setName:@"PrevTrack"];
661 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
662 [hotKey setTarget:self];
663 [hotKey setAction:@selector(prevSong)];
664 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
667 if ([df objectForKey:@"ShowPlayer"] != nil) {
668 ITDebugLog(@"Setting up show player hot key.");
669 hotKey = [[ITHotKey alloc] init];
670 [hotKey setName:@"ShowPlayer"];
671 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
672 [hotKey setTarget:self];
673 [hotKey setAction:@selector(showPlayer)];
674 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
677 if ([df objectForKey:@"TrackInfo"] != nil) {
678 ITDebugLog(@"Setting up track info hot key.");
679 hotKey = [[ITHotKey alloc] init];
680 [hotKey setName:@"TrackInfo"];
681 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
682 [hotKey setTarget:self];
683 [hotKey setAction:@selector(showCurrentTrackInfo)];
684 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
687 if ([df objectForKey:@"UpcomingSongs"] != nil) {
688 ITDebugLog(@"Setting up upcoming songs hot key.");
689 hotKey = [[ITHotKey alloc] init];
690 [hotKey setName:@"UpcomingSongs"];
691 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
692 [hotKey setTarget:self];
693 [hotKey setAction:@selector(showUpcomingSongs)];
694 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
697 if ([df objectForKey:@"ToggleLoop"] != nil) {
698 ITDebugLog(@"Setting up toggle loop hot key.");
699 hotKey = [[ITHotKey alloc] init];
700 [hotKey setName:@"ToggleLoop"];
701 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
702 [hotKey setTarget:self];
703 [hotKey setAction:@selector(toggleLoop)];
704 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
707 if ([df objectForKey:@"ToggleShuffle"] != nil) {
708 ITDebugLog(@"Setting up toggle shuffle hot key.");
709 hotKey = [[ITHotKey alloc] init];
710 [hotKey setName:@"ToggleShuffle"];
711 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
712 [hotKey setTarget:self];
713 [hotKey setAction:@selector(toggleShuffle)];
714 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
717 if ([df objectForKey:@"IncrementVolume"] != nil) {
718 ITDebugLog(@"Setting up increment volume hot key.");
719 hotKey = [[ITHotKey alloc] init];
720 [hotKey setName:@"IncrementVolume"];
721 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
722 [hotKey setTarget:self];
723 [hotKey setAction:@selector(incrementVolume)];
724 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
727 if ([df objectForKey:@"DecrementVolume"] != nil) {
728 ITDebugLog(@"Setting up decrement volume hot key.");
729 hotKey = [[ITHotKey alloc] init];
730 [hotKey setName:@"DecrementVolume"];
731 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
732 [hotKey setTarget:self];
733 [hotKey setAction:@selector(decrementVolume)];
734 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
737 if ([df objectForKey:@"IncrementRating"] != nil) {
738 ITDebugLog(@"Setting up increment rating hot key.");
739 hotKey = [[ITHotKey alloc] init];
740 [hotKey setName:@"IncrementRating"];
741 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
742 [hotKey setTarget:self];
743 [hotKey setAction:@selector(incrementRating)];
744 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
747 if ([df objectForKey:@"DecrementRating"] != nil) {
748 ITDebugLog(@"Setting up decrement rating hot key.");
749 hotKey = [[ITHotKey alloc] init];
750 [hotKey setName:@"DecrementRating"];
751 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
752 [hotKey setTarget:self];
753 [hotKey setAction:@selector(decrementRating)];
754 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
756 ITDebugLog(@"Finished setting up hot keys.");
759 - (void)showCurrentTrackInfo
761 ITMTRemotePlayerSource source = 0;
762 NSString *title = nil;
763 NSString *album = nil;
764 NSString *artist = nil;
765 NSString *composer = nil;
766 NSString *time = nil;
767 NSString *track = nil;
771 ITDebugLog(@"Showing track info status window.");
774 source = [[self currentRemote] currentSource];
775 title = [[self currentRemote] currentSongTitle];
777 [self networkError:localException];
782 if ( [df boolForKey:@"showAlbum"] ) {
784 album = [[self currentRemote] currentSongAlbum];
786 [self networkError:localException];
790 if ( [df boolForKey:@"showArtist"] ) {
792 artist = [[self currentRemote] currentSongArtist];
794 [self networkError:localException];
798 if ( [df boolForKey:@"showComposer"] ) {
800 composer = [[self currentRemote] currentSongComposer];
802 [self networkError:localException];
806 if ( [df boolForKey:@"showTime"] ) {
808 time = [NSString stringWithFormat:@"%@: %@ / %@",
810 [[self currentRemote] currentSongElapsed],
811 [[self currentRemote] currentSongLength]];
813 [self networkError:localException];
817 if ( [df boolForKey:@"showTrackNumber"] ) {
822 trackNo = [[self currentRemote] currentSongTrack];
823 trackCount = [[self currentRemote] currentAlbumTrackCount];
825 [self networkError:localException];
828 if ( (trackNo > 0) || (trackCount > 0) ) {
829 track = [NSString stringWithFormat:@"%@: %i %@ %i",
830 @"Track", trackNo, @"of", trackCount];
834 if ( [df boolForKey:@"showTrackRating"] ) {
835 float currentRating = 0;
838 currentRating = [[self currentRemote] currentSongRating];
840 [self networkError:localException];
843 if (currentRating >= 0.0) {
844 rating = ( currentRating * 5 );
848 if ( [df boolForKey:@"showAlbumArtwork"] ) {
849 NSSize oldSize, newSize;
851 art = [[self currentRemote] currentSongAlbumArt];
852 oldSize = [art size];
853 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
854 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
855 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
857 [self networkError:localException];
862 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
864 ITDebugLog(@"Showing current track info status window.");
865 [statusWindowController showSongInfoWindowWithSource:source
876 - (void)showUpcomingSongs
880 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
882 [self networkError:localException];
885 ITDebugLog(@"Showing upcoming songs status window.");
888 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
889 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
890 int curTrack = [[self currentRemote] currentSongIndex];
893 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
895 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
899 if ([songList count] == 0) {
900 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
903 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
905 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
908 [self networkError:localException];
912 - (void)incrementVolume
915 float volume = [[self currentRemote] volume];
916 float dispVol = volume;
917 ITDebugLog(@"Incrementing volume.");
926 ITDebugLog(@"Setting volume to %f", volume);
927 [[self currentRemote] setVolume:volume];
929 // Show volume status window
930 [statusWindowController showVolumeWindowWithLevel:dispVol];
932 [self networkError:localException];
936 - (void)decrementVolume
939 float volume = [[self currentRemote] volume];
940 float dispVol = volume;
941 ITDebugLog(@"Decrementing volume.");
950 ITDebugLog(@"Setting volume to %f", volume);
951 [[self currentRemote] setVolume:volume];
953 //Show volume status window
954 [statusWindowController showVolumeWindowWithLevel:dispVol];
956 [self networkError:localException];
960 - (void)incrementRating
963 float rating = [[self currentRemote] currentSongRating];
964 ITDebugLog(@"Incrementing rating.");
966 if ([[self currentRemote] currentPlaylistIndex] == 0) {
967 ITDebugLog(@"No song playing, rating change aborted.");
975 ITDebugLog(@"Setting rating to %f", rating);
976 [[self currentRemote] setCurrentSongRating:rating];
978 //Show rating status window
979 [statusWindowController showRatingWindowWithRating:rating];
981 [self networkError:localException];
985 - (void)decrementRating
988 float rating = [[self currentRemote] currentSongRating];
989 ITDebugLog(@"Decrementing rating.");
991 if ([[self currentRemote] currentPlaylistIndex] == 0) {
992 ITDebugLog(@"No song playing, rating change aborted.");
1000 ITDebugLog(@"Setting rating to %f", rating);
1001 [[self currentRemote] setCurrentSongRating:rating];
1003 //Show rating status window
1004 [statusWindowController showRatingWindowWithRating:rating];
1006 [self networkError:localException];
1013 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1014 ITDebugLog(@"Toggling repeat mode.");
1015 switch (repeatMode) {
1016 case ITMTRemotePlayerRepeatOff:
1017 repeatMode = ITMTRemotePlayerRepeatAll;
1019 case ITMTRemotePlayerRepeatAll:
1020 repeatMode = ITMTRemotePlayerRepeatOne;
1022 case ITMTRemotePlayerRepeatOne:
1023 repeatMode = ITMTRemotePlayerRepeatOff;
1026 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1027 [[self currentRemote] setRepeatMode:repeatMode];
1029 //Show loop status window
1030 [statusWindowController showRepeatWindowWithMode:repeatMode];
1032 [self networkError:localException];
1036 - (void)toggleShuffle
1039 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1040 ITDebugLog(@"Toggling shuffle mode.");
1041 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1042 //Show shuffle status window
1043 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1044 [statusWindowController showShuffleWindow:newShuffleEnabled];
1046 [self networkError:localException];
1050 - (void)registerNowOK
1052 [[StatusWindow sharedWindow] setLocked:NO];
1053 [[StatusWindow sharedWindow] vanish:self];
1054 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1059 - (void)registerNowCancel
1061 [[StatusWindow sharedWindow] setLocked:NO];
1062 [[StatusWindow sharedWindow] vanish:self];
1063 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1065 [NSApp terminate:self];
1068 /*************************************************************************/
1070 #pragma mark NETWORK HANDLERS
1071 /*************************************************************************/
1073 - (void)setServerStatus:(BOOL)newStatus
1077 [networkController setServerStatus:YES];
1080 [networkController setServerStatus:NO];
1084 - (int)connectToServer
1087 ITDebugLog(@"Attempting to connect to shared remote.");
1088 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1091 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1092 currentRemote = [[[networkController networkObject] remote] retain];
1094 [self setupHotKeys];
1095 //playerRunningState = ITMTRemotePlayerRunning;
1096 playerRunningState = [[self currentRemote] playerRunningState];
1098 [refreshTimer invalidate];
1099 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1101 selector:@selector(timerUpdate)
1103 repeats:YES] retain];
1105 ITDebugLog(@"Connection successful.");
1107 } else if (result == 0) {
1108 ITDebugLog(@"Connection failed.");
1109 currentRemote = [remoteArray objectAtIndex:0];
1112 //Do something about the password being invalid
1113 ITDebugLog(@"Connection failed.");
1114 currentRemote = [remoteArray objectAtIndex:0];
1119 - (BOOL)disconnectFromServer
1121 ITDebugLog(@"Disconnecting from shared remote.");
1123 [currentRemote release];
1124 currentRemote = [remoteArray objectAtIndex:0];
1125 [networkController disconnect];
1127 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1128 [self applicationLaunched:nil];
1130 [self applicationTerminated:nil];
1136 - (void)checkForRemoteServer
1138 ITDebugLog(@"Checking for remote server.");
1139 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:nil];
1142 - (void)runRemoteServerCheck:(id)sender
1144 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1145 ITDebugLog(@"Remote server check running.");
1146 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1147 ITDebugLog(@"Remote server found.");
1148 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1150 ITDebugLog(@"Remote server not found.");
1151 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1156 - (void)remoteServerFound:(id)sender
1158 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1159 [[StatusWindowController sharedController] showReconnectQueryWindow];
1163 - (void)remoteServerNotFound:(id)sender
1165 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1168 - (void)networkError:(NSException *)exception
1170 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1171 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1172 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);
1173 if ([self disconnectFromServer]) {
1174 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1175 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:YES];
1177 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1184 if ([self connectToServer] == 0) {
1185 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:YES];
1187 [[StatusWindow sharedWindow] setLocked:NO];
1188 [[StatusWindow sharedWindow] vanish:self];
1189 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1192 - (void)cancelReconnect
1194 [[StatusWindow sharedWindow] setLocked:NO];
1195 [[StatusWindow sharedWindow] vanish:self];
1196 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1199 /*************************************************************************/
1201 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1202 /*************************************************************************/
1204 - (void)applicationLaunched:(NSNotification *)note
1207 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1208 ITDebugLog(@"Remote application launched.");
1209 playerRunningState = ITMTRemotePlayerRunning;
1210 [[self currentRemote] begin];
1211 [self setLatestSongIdentifier:@""];
1213 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1215 selector:@selector(timerUpdate)
1217 repeats:YES] retain];
1218 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1219 [self setupHotKeys];
1222 [self networkError:localException];
1226 - (void)applicationTerminated:(NSNotification *)note
1229 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1230 ITDebugLog(@"Remote application terminated.");
1231 playerRunningState = ITMTRemotePlayerNotRunning;
1232 [[self currentRemote] halt];
1233 [refreshTimer invalidate];
1234 [refreshTimer release];
1236 [self clearHotKeys];
1238 if ([df objectForKey:@"ShowPlayer"] != nil) {
1240 ITDebugLog(@"Setting up show player hot key.");
1241 hotKey = [[ITHotKey alloc] init];
1242 [hotKey setName:@"ShowPlayer"];
1243 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1244 [hotKey setTarget:self];
1245 [hotKey setAction:@selector(showPlayer)];
1246 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1250 [self networkError:localException];
1255 /*************************************************************************/
1257 #pragma mark NSApplication DELEGATE METHODS
1258 /*************************************************************************/
1260 - (void)applicationWillTerminate:(NSNotification *)note
1262 [networkController stopRemoteServerSearch];
1263 [self clearHotKeys];
1264 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1268 /*************************************************************************/
1270 #pragma mark DEALLOCATION METHOD
1271 /*************************************************************************/
1275 [self applicationTerminated:nil];
1277 [statusItem release];
1278 [statusWindowController release];
1279 [menuController release];
1280 [networkController release];