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:");
330 ITDebugLog(@" - Identifier: %@", newIdentifier);
331 [_latestSongIdentifier autorelease];
332 _latestSongIdentifier = [newIdentifier retain];
337 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
338 ITDebugLog(@"The song changed.");
340 if ([df boolForKey:@"runScripts"]) {
341 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
342 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
343 NSString *nextScript;
344 ITDebugLog(@"Running AppleScripts for song change.");
345 while ( (nextScript = [scriptsEnum nextObject]) ) {
347 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
348 ITDebugLog(@"Running script: %@", nextScript);
349 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
350 ITDebugLog(@"Error running script %@.", nextScript);
352 [currentScript release];
357 [statusItem setEnabled:NO];
360 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
361 [menuController rebuildSubmenus];
363 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
364 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
367 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
369 //Create the tooltip for the status item
370 if ( [df boolForKey:@"showToolTip"] ) {
371 NSString *artist = [[self currentRemote] currentSongArtist];
372 NSString *title = [[self currentRemote] currentSongTitle];
374 ITDebugLog(@"Creating status item tooltip.");
376 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
380 toolTip = @"No Song Playing";
382 [statusItem setToolTip:toolTip];
384 [statusItem setToolTip:nil];
387 [self networkError:localException];
391 [statusItem setEnabled:YES];
394 if ([networkController isConnectedToServer]) {
395 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
401 ITDebugLog(@"Menu clicked.");
402 if ([networkController isConnectedToServer]) {
403 //Used the cached version
408 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
409 [statusItem setMenu:[menuController menu]];
411 [statusItem setMenu:[menuController menuForNoPlayer]];
414 [self networkError:localException];
427 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
428 ITDebugLog(@"Play/Pause toggled");
429 if (state == ITMTRemotePlayerPlaying) {
430 [[self currentRemote] pause];
431 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
432 [[self currentRemote] pause];
433 [[self currentRemote] play];
435 [[self currentRemote] play];
438 [self networkError:localException];
446 ITDebugLog(@"Going to next song.");
448 [[self currentRemote] goToNextSong];
450 [self networkError:localException];
457 ITDebugLog(@"Going to previous song.");
459 [[self currentRemote] goToPreviousSong];
461 [self networkError:localException];
468 ITDebugLog(@"Fast forwarding.");
470 [[self currentRemote] forward];
472 [self networkError:localException];
479 ITDebugLog(@"Rewinding.");
481 [[self currentRemote] rewind];
483 [self networkError:localException];
488 - (void)selectPlaylistAtIndex:(int)index
490 ITDebugLog(@"Selecting playlist %i", index);
492 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
493 //[[self currentRemote] switchToPlaylistAtIndex:index];
495 [self networkError:localException];
500 - (void)selectSongAtIndex:(int)index
502 ITDebugLog(@"Selecting song %i", index);
504 [[self currentRemote] switchToSongAtIndex:index];
506 [self networkError:localException];
511 - (void)selectSongRating:(int)rating
513 ITDebugLog(@"Selecting song rating %i", rating);
515 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
517 [self networkError:localException];
522 - (void)selectEQPresetAtIndex:(int)index
524 ITDebugLog(@"Selecting EQ preset %i", index);
526 [[self currentRemote] switchToEQAtIndex:index];
528 [self networkError:localException];
535 ITDebugLog(@"Beginning show player.");
536 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
537 ITDebugLog(@"Showing player interface.");
539 [[self currentRemote] showPrimaryInterface];
541 [self networkError:localException];
544 ITDebugLog(@"Launching player.");
547 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
549 path = [[self currentRemote] playerFullName];
551 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
552 ITDebugLog(@"Error Launching Player");
555 [self networkError:localException];
558 ITDebugLog(@"Finished show player.");
561 - (void)showPreferences
563 ITDebugLog(@"Show preferences.");
564 [[PreferencesController sharedPrefs] showPrefsWindow:self];
567 - (void)showPreferencesAndClose
569 ITDebugLog(@"Show preferences.");
570 [[PreferencesController sharedPrefs] showPrefsWindow:self];
571 [[StatusWindow sharedWindow] setLocked:NO];
572 [[StatusWindow sharedWindow] vanish:self];
573 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
576 - (void)showTestWindow
578 [self showCurrentTrackInfo];
581 - (void)quitMenuTunes
583 ITDebugLog(@"Quitting MenuTunes.");
584 [NSApp terminate:self];
590 - (MenuController *)menuController
592 return menuController;
595 - (void)closePreferences
597 ITDebugLog(@"Preferences closed.");
598 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
603 - (ITMTRemote *)currentRemote
605 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
606 [self networkError:nil];
609 return currentRemote;
620 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
621 ITHotKey *nextHotKey;
622 ITDebugLog(@"Clearing hot keys.");
623 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
624 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
626 ITDebugLog(@"Done clearing hot keys.");
632 ITDebugLog(@"Setting up hot keys.");
634 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
638 if ([df objectForKey:@"PlayPause"] != nil) {
639 ITDebugLog(@"Setting up play pause hot key.");
640 hotKey = [[ITHotKey alloc] init];
641 [hotKey setName:@"PlayPause"];
642 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
643 [hotKey setTarget:self];
644 [hotKey setAction:@selector(playPause)];
645 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
648 if ([df objectForKey:@"NextTrack"] != nil) {
649 ITDebugLog(@"Setting up next track hot key.");
650 hotKey = [[ITHotKey alloc] init];
651 [hotKey setName:@"NextTrack"];
652 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
653 [hotKey setTarget:self];
654 [hotKey setAction:@selector(nextSong)];
655 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
658 if ([df objectForKey:@"PrevTrack"] != nil) {
659 ITDebugLog(@"Setting up previous track hot key.");
660 hotKey = [[ITHotKey alloc] init];
661 [hotKey setName:@"PrevTrack"];
662 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
663 [hotKey setTarget:self];
664 [hotKey setAction:@selector(prevSong)];
665 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
668 if ([df objectForKey:@"ShowPlayer"] != nil) {
669 ITDebugLog(@"Setting up show player hot key.");
670 hotKey = [[ITHotKey alloc] init];
671 [hotKey setName:@"ShowPlayer"];
672 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
673 [hotKey setTarget:self];
674 [hotKey setAction:@selector(showPlayer)];
675 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
678 if ([df objectForKey:@"TrackInfo"] != nil) {
679 ITDebugLog(@"Setting up track info hot key.");
680 hotKey = [[ITHotKey alloc] init];
681 [hotKey setName:@"TrackInfo"];
682 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
683 [hotKey setTarget:self];
684 [hotKey setAction:@selector(showCurrentTrackInfo)];
685 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
688 if ([df objectForKey:@"UpcomingSongs"] != nil) {
689 ITDebugLog(@"Setting up upcoming songs hot key.");
690 hotKey = [[ITHotKey alloc] init];
691 [hotKey setName:@"UpcomingSongs"];
692 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
693 [hotKey setTarget:self];
694 [hotKey setAction:@selector(showUpcomingSongs)];
695 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
698 if ([df objectForKey:@"ToggleLoop"] != nil) {
699 ITDebugLog(@"Setting up toggle loop hot key.");
700 hotKey = [[ITHotKey alloc] init];
701 [hotKey setName:@"ToggleLoop"];
702 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
703 [hotKey setTarget:self];
704 [hotKey setAction:@selector(toggleLoop)];
705 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
708 if ([df objectForKey:@"ToggleShuffle"] != nil) {
709 ITDebugLog(@"Setting up toggle shuffle hot key.");
710 hotKey = [[ITHotKey alloc] init];
711 [hotKey setName:@"ToggleShuffle"];
712 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
713 [hotKey setTarget:self];
714 [hotKey setAction:@selector(toggleShuffle)];
715 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
718 if ([df objectForKey:@"IncrementVolume"] != nil) {
719 ITDebugLog(@"Setting up increment volume hot key.");
720 hotKey = [[ITHotKey alloc] init];
721 [hotKey setName:@"IncrementVolume"];
722 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
723 [hotKey setTarget:self];
724 [hotKey setAction:@selector(incrementVolume)];
725 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
728 if ([df objectForKey:@"DecrementVolume"] != nil) {
729 ITDebugLog(@"Setting up decrement volume hot key.");
730 hotKey = [[ITHotKey alloc] init];
731 [hotKey setName:@"DecrementVolume"];
732 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
733 [hotKey setTarget:self];
734 [hotKey setAction:@selector(decrementVolume)];
735 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
738 if ([df objectForKey:@"IncrementRating"] != nil) {
739 ITDebugLog(@"Setting up increment rating hot key.");
740 hotKey = [[ITHotKey alloc] init];
741 [hotKey setName:@"IncrementRating"];
742 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
743 [hotKey setTarget:self];
744 [hotKey setAction:@selector(incrementRating)];
745 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
748 if ([df objectForKey:@"DecrementRating"] != nil) {
749 ITDebugLog(@"Setting up decrement rating hot key.");
750 hotKey = [[ITHotKey alloc] init];
751 [hotKey setName:@"DecrementRating"];
752 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
753 [hotKey setTarget:self];
754 [hotKey setAction:@selector(decrementRating)];
755 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
757 ITDebugLog(@"Finished setting up hot keys.");
760 - (void)showCurrentTrackInfo
762 ITMTRemotePlayerSource source = 0;
763 NSString *title = nil;
764 NSString *album = nil;
765 NSString *artist = nil;
766 NSString *composer = nil;
767 NSString *time = nil;
768 NSString *track = nil;
772 ITDebugLog(@"Showing track info status window.");
775 source = [[self currentRemote] currentSource];
776 title = [[self currentRemote] currentSongTitle];
778 [self networkError:localException];
783 if ( [df boolForKey:@"showAlbum"] ) {
785 album = [[self currentRemote] currentSongAlbum];
787 [self networkError:localException];
791 if ( [df boolForKey:@"showArtist"] ) {
793 artist = [[self currentRemote] currentSongArtist];
795 [self networkError:localException];
799 if ( [df boolForKey:@"showComposer"] ) {
801 composer = [[self currentRemote] currentSongComposer];
803 [self networkError:localException];
807 if ( [df boolForKey:@"showTime"] ) {
809 time = [NSString stringWithFormat:@"%@: %@ / %@",
811 [[self currentRemote] currentSongElapsed],
812 [[self currentRemote] currentSongLength]];
814 [self networkError:localException];
818 if ( [df boolForKey:@"showTrackNumber"] ) {
823 trackNo = [[self currentRemote] currentSongTrack];
824 trackCount = [[self currentRemote] currentAlbumTrackCount];
826 [self networkError:localException];
829 if ( (trackNo > 0) || (trackCount > 0) ) {
830 track = [NSString stringWithFormat:@"%@: %i %@ %i",
831 @"Track", trackNo, @"of", trackCount];
835 if ( [df boolForKey:@"showTrackRating"] ) {
836 float currentRating = 0;
839 currentRating = [[self currentRemote] currentSongRating];
841 [self networkError:localException];
844 if (currentRating >= 0.0) {
845 rating = ( currentRating * 5 );
849 if ( [df boolForKey:@"showAlbumArtwork"] ) {
850 NSSize oldSize, newSize;
852 art = [[self currentRemote] currentSongAlbumArt];
853 oldSize = [art size];
854 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
855 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
856 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
858 [self networkError:localException];
863 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
865 ITDebugLog(@"Showing current track info status window.");
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];
1095 [self setupHotKeys];
1096 //playerRunningState = ITMTRemotePlayerRunning;
1097 playerRunningState = [[self currentRemote] playerRunningState];
1099 [refreshTimer invalidate];
1100 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1102 selector:@selector(timerUpdate)
1104 repeats:YES] retain];
1106 ITDebugLog(@"Connection successful.");
1108 } else if (result == 0) {
1109 ITDebugLog(@"Connection failed.");
1110 currentRemote = [remoteArray objectAtIndex:0];
1113 //Do something about the password being invalid
1114 ITDebugLog(@"Connection failed.");
1115 currentRemote = [remoteArray objectAtIndex:0];
1120 - (BOOL)disconnectFromServer
1122 ITDebugLog(@"Disconnecting from shared remote.");
1124 [currentRemote release];
1125 currentRemote = [remoteArray objectAtIndex:0];
1126 [networkController disconnect];
1128 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1129 [self applicationLaunched:nil];
1131 [self applicationTerminated:nil];
1137 - (void)checkForRemoteServer:(NSTimer *)timer
1139 ITDebugLog(@"Checking for remote server.");
1140 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1141 ITDebugLog(@"Remote server found.");
1143 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1144 [[StatusWindowController sharedController] showReconnectQueryWindow];
1147 ITDebugLog(@"Remote server not found.");
1151 - (void)networkError:(NSException *)exception
1153 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1154 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1155 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);
1156 if ([self disconnectFromServer]) {
1157 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1158 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1160 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1167 if ([self connectToServer] == 0) {
1168 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1170 [[StatusWindow sharedWindow] setLocked:NO];
1171 [[StatusWindow sharedWindow] vanish:self];
1172 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1175 - (void)cancelReconnect
1177 [[StatusWindow sharedWindow] setLocked:NO];
1178 [[StatusWindow sharedWindow] vanish:self];
1179 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1182 /*************************************************************************/
1184 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1185 /*************************************************************************/
1187 - (void)applicationLaunched:(NSNotification *)note
1190 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1191 ITDebugLog(@"Remote application launched.");
1192 playerRunningState = ITMTRemotePlayerRunning;
1193 [[self currentRemote] begin];
1194 [self setLatestSongIdentifier:@""];
1196 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1198 selector:@selector(timerUpdate)
1200 repeats:YES] retain];
1201 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1202 [self setupHotKeys];
1205 [self networkError:localException];
1209 - (void)applicationTerminated:(NSNotification *)note
1212 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1213 ITDebugLog(@"Remote application terminated.");
1214 playerRunningState = ITMTRemotePlayerNotRunning;
1215 [[self currentRemote] halt];
1216 [refreshTimer invalidate];
1217 [refreshTimer release];
1219 [self clearHotKeys];
1221 if ([df objectForKey:@"ShowPlayer"] != nil) {
1223 ITDebugLog(@"Setting up show player hot key.");
1224 hotKey = [[ITHotKey alloc] init];
1225 [hotKey setName:@"ShowPlayer"];
1226 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1227 [hotKey setTarget:self];
1228 [hotKey setAction:@selector(showPlayer)];
1229 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1233 [self networkError:localException];
1238 /*************************************************************************/
1240 #pragma mark NSApplication DELEGATE METHODS
1241 /*************************************************************************/
1243 - (void)applicationWillTerminate:(NSNotification *)note
1245 [networkController stopRemoteServerSearch];
1246 [self clearHotKeys];
1247 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1251 /*************************************************************************/
1253 #pragma mark DEALLOCATION METHOD
1254 /*************************************************************************/
1258 [self applicationTerminated:nil];
1260 [statusItem release];
1261 [statusWindowController release];
1262 [menuController release];
1263 [networkController release];