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 <ITKit/ITCategory-NSMenu.h>
10 #import "StatusWindow.h"
11 #import "StatusWindowController.h"
12 #import "StatusItemHack.h"
14 @interface NSCarbonMenuImpl:NSObject
20 + (void)setupForNoMenuBar;
24 - (void)itemChanged:fp8;
25 - (void)itemAdded:fp8;
26 - (void)itemRemoved:fp8;
27 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
28 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
29 - (void)setupCarbonMenuBar;
30 - (void)setAsMainCarbonMenuBar;
31 - (void)clearAsMainCarbonMenuBar;
32 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
33 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
34 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
38 @implementation NSImage (SmoothAdditions)
40 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
43 NSImageRep *rep = [self bestRepresentationForDevice:nil];
45 newImage = [[NSImage alloc] initWithSize:scaledSize];
48 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
49 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
50 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
52 [newImage unlockFocus];
53 return [newImage autorelease];
58 @interface MainController(Private)
59 - (ITMTRemote *)loadRemote;
60 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
61 - (void)applicationLaunched:(NSNotification *)note;
62 - (void)applicationTerminated:(NSNotification *)note;
65 static MainController *sharedController;
67 @implementation MainController
69 + (MainController *)sharedController
71 return sharedController;
74 /*************************************************************************/
76 #pragma mark INITIALIZATION/DEALLOCATION METHODS
77 /*************************************************************************/
81 if ( ( self = [super init] ) ) {
82 sharedController = self;
84 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
85 [[PreferencesController sharedPrefs] setController:self];
86 statusWindowController = [StatusWindowController sharedController];
87 menuController = [[MenuController alloc] init];
88 df = [[NSUserDefaults standardUserDefaults] retain];
95 - (void)applicationDidFinishLaunching:(NSNotification *)note
97 //Turn on debug mode if needed
98 if ([df boolForKey:@"ITDebugMode"]) {
102 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
103 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
105 [[PreferencesController sharedPrefs] registerDefaults];
106 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
109 currentRemote = [self loadRemote];
110 [[self currentRemote] begin];
112 //Turn on network stuff if needed
113 networkController = [[NetworkController alloc] init];
114 if ([df boolForKey:@"enableSharing"]) {
115 [self setServerStatus:YES];
116 } else if ([df boolForKey:@"useSharedPlayer"]) {
117 [self checkForRemoteServerAndConnectImmediately:YES];
120 //Setup for notification of the remote player launching or quitting
121 [[[NSWorkspace sharedWorkspace] notificationCenter]
123 selector:@selector(applicationTerminated:)
124 name:NSWorkspaceDidTerminateApplicationNotification
127 [[[NSWorkspace sharedWorkspace] notificationCenter]
129 selector:@selector(applicationLaunched:)
130 name:NSWorkspaceDidLaunchApplicationNotification
133 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
134 [[PreferencesController sharedPrefs] registerDefaults];
137 if ([df boolForKey:@"ITMTNoStatusItem"]) {
140 [StatusItemHack install];
141 statusItem = [[ITStatusItem alloc]
142 initWithStatusBar:[NSStatusBar systemStatusBar]
143 withLength:NSSquareStatusItemLength];
146 bling = [[MTBlingController alloc] init];
148 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
150 selector:@selector(blingTime)
152 repeats:YES] retain];
155 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
156 [self applicationLaunched:nil];
158 if ([df boolForKey:@"LaunchPlayerWithMT"])
161 [self applicationTerminated:nil];
164 [self networkError:localException];
167 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
168 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
170 [networkController startRemoteServerSearch];
174 - (ITMTRemote *)loadRemote
176 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
177 ITDebugLog(@"Gathering remotes.");
179 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
180 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
181 NSString *bundlePath;
183 while ( (bundlePath = [enumerator nextObject]) ) {
184 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
187 Class remoteClass = [remoteBundle principalClass];
189 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
190 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
191 id remote = [remoteClass remote];
192 ITDebugLog(@"Adding remote at path %@", bundlePath);
193 [remoteArray addObject:remote];
198 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
199 // if ( [remoteArray count] > 1 ) {
200 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
202 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
205 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
206 return [remoteArray objectAtIndex:0];
209 /*************************************************************************/
211 #pragma mark INSTANCE METHODS
212 /*************************************************************************/
214 /*- (void)startTimerInNewThread
216 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
217 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
218 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
220 selector:@selector(timerUpdate)
222 repeats:YES] retain];
224 ITDebugLog(@"Timer started.");
228 - (void)setBlingTime:(NSDate*)date
230 NSMutableDictionary *globalPrefs;
232 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
234 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
235 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
237 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
238 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
240 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
242 [globalPrefs release];
245 - (NSDate*)getBlingTime
248 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
253 NSDate *now = [NSDate date];
254 if (![self blingBling]) {
255 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
256 [self setBlingTime:now];
257 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
258 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
259 [self setBlingTime:[now addTimeInterval:-259200]];
261 NSMutableDictionary *globalPrefs;
263 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
264 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
265 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
267 [globalPrefs release];
271 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
273 [statusItem setEnabled:NO];
275 if ([refreshTimer isValid]) {
276 [refreshTimer invalidate];
278 [statusWindowController showRegistrationQueryWindow];
282 [statusItem setEnabled:YES];
284 if (![refreshTimer isValid]) {
285 [refreshTimer release];
286 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
288 selector:@selector(timerUpdate)
290 repeats:YES] retain];
294 [self setBlingTime:nil];
305 if ( ! ([bling checkDone] == 2475) ) {
312 - (BOOL)songIsPlaying
314 NSString *identifier = nil;
316 identifier = [[self currentRemote] playerStateUniqueIdentifier];
318 [self networkError:localException];
320 return ( ! ([identifier isEqualToString:@"0-0"]) );
323 - (BOOL)radioIsPlaying
325 ITMTRemotePlayerPlaylistClass class = nil;
327 class = [[self currentRemote] currentPlaylistClass];
329 [self networkError:localException];
331 return (class == ITMTRemotePlayerRadioPlaylist );
336 NSString *identifier = nil;
338 identifier = [[self currentRemote] playerStateUniqueIdentifier];
340 [self networkError:localException];
342 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
345 - (NSString *)latestSongIdentifier
347 return _latestSongIdentifier;
350 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
352 ITDebugLog(@"Setting latest song identifier:");
353 ITDebugLog(@" - Identifier: %@", newIdentifier);
354 [_latestSongIdentifier autorelease];
355 _latestSongIdentifier = [newIdentifier retain];
360 if ([[self currentRemote] playerStateUniqueIdentifier] == nil) {
361 if ([statusItem isEnabled]) {
362 [statusItem setToolTip:@"iTunes not responding."];
365 [statusItem setEnabled:NO];
367 } else if (![statusItem isEnabled]) {
368 [statusItem setEnabled:YES];
369 [statusItem setToolTip:_toolTip];
374 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
375 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
376 if ([df boolForKey:@"runScripts"]) {
377 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
378 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
379 NSString *nextScript;
380 ITDebugLog(@"Running AppleScripts for song change.");
381 while ( (nextScript = [scriptsEnum nextObject]) ) {
383 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
384 ITDebugLog(@"Running script: %@", nextScript);
385 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
386 ITDebugLog(@"Error running script %@.", nextScript);
388 [currentScript release];
393 [statusItem setEnabled:NO];
396 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
397 [menuController rebuildSubmenus];
399 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
400 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
403 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
405 //Create the tooltip for the status item
406 if ( [df boolForKey:@"showToolTip"] ) {
407 NSString *artist = [[self currentRemote] currentSongArtist];
408 NSString *title = [[self currentRemote] currentSongTitle];
409 ITDebugLog(@"Creating status item tooltip.");
411 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
415 _toolTip = @"No Song Playing";
417 [statusItem setToolTip:_toolTip];
419 [statusItem setToolTip:nil];
422 [self networkError:localException];
426 [statusItem setEnabled:YES];
429 if ([networkController isConnectedToServer]) {
430 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
436 ITDebugLog(@"Menu clicked.");
438 if ([[self currentRemote] playerStateUniqueIdentifier] == nil) {
439 if ([statusItem isEnabled]) {
440 [statusItem setToolTip:@"iTunes not responding."];
443 [statusItem setEnabled:NO];
445 } else if (![statusItem isEnabled]) {
446 [statusItem setEnabled:YES];
447 [statusItem setToolTip:_toolTip];
452 if ([networkController isConnectedToServer]) {
453 //Used the cached version
458 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
459 [statusItem setMenu:[menuController menu]];
461 [statusItem setMenu:[menuController menuForNoPlayer]];
464 [self networkError:localException];
477 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
478 ITDebugLog(@"Play/Pause toggled");
479 if (state == ITMTRemotePlayerPlaying) {
480 [[self currentRemote] pause];
481 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
482 [[self currentRemote] pause];
483 [[self currentRemote] play];
485 [[self currentRemote] play];
488 [self networkError:localException];
496 ITDebugLog(@"Going to next song.");
498 [[self currentRemote] goToNextSong];
500 [self networkError:localException];
507 ITDebugLog(@"Going to previous song.");
509 [[self currentRemote] goToPreviousSong];
511 [self networkError:localException];
518 ITDebugLog(@"Fast forwarding.");
520 [[self currentRemote] forward];
522 [self networkError:localException];
529 ITDebugLog(@"Rewinding.");
531 [[self currentRemote] rewind];
533 [self networkError:localException];
538 - (void)selectPlaylistAtIndex:(int)index
540 ITDebugLog(@"Selecting playlist %i", index);
542 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
543 //[[self currentRemote] switchToPlaylistAtIndex:index];
545 [self networkError:localException];
550 - (void)selectSongAtIndex:(int)index
552 ITDebugLog(@"Selecting song %i", index);
554 [[self currentRemote] switchToSongAtIndex:index];
556 [self networkError:localException];
561 - (void)selectSongRating:(int)rating
563 ITDebugLog(@"Selecting song rating %i", rating);
565 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
567 [self networkError:localException];
572 - (void)selectEQPresetAtIndex:(int)index
574 ITDebugLog(@"Selecting EQ preset %i", index);
577 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
579 [[self currentRemote] switchToEQAtIndex:index];
582 [self networkError:localException];
587 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
589 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
591 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
593 [self networkError:localException];
595 ITDebugLog(@"Done making playlist");
600 ITDebugLog(@"Beginning show player.");
601 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
602 ITDebugLog(@"Showing player interface.");
604 [[self currentRemote] showPrimaryInterface];
606 [self networkError:localException];
609 ITDebugLog(@"Launching player.");
612 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
614 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
616 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
617 ITDebugLog(@"Error Launching Player");
620 [self networkError:localException];
623 ITDebugLog(@"Finished show player.");
626 - (void)showPreferences
628 ITDebugLog(@"Show preferences.");
629 [[PreferencesController sharedPrefs] showPrefsWindow:self];
632 - (void)showPreferencesAndClose
634 ITDebugLog(@"Show preferences.");
635 [[PreferencesController sharedPrefs] showPrefsWindow:self];
636 [[StatusWindow sharedWindow] setLocked:NO];
637 [[StatusWindow sharedWindow] vanish:self];
638 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
641 - (void)showTestWindow
643 [self showCurrentTrackInfo];
646 - (void)quitMenuTunes
648 ITDebugLog(@"Quitting MenuTunes.");
649 [NSApp terminate:self];
655 - (MenuController *)menuController
657 return menuController;
660 - (void)closePreferences
662 ITDebugLog(@"Preferences closed.");
663 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
668 - (ITMTRemote *)currentRemote
670 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
671 [self networkError:nil];
674 return currentRemote;
685 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
686 ITHotKey *nextHotKey;
687 ITDebugLog(@"Clearing hot keys.");
688 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
689 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
691 ITDebugLog(@"Done clearing hot keys.");
697 ITDebugLog(@"Setting up hot keys.");
699 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
703 if ([df objectForKey:@"PlayPause"] != nil) {
704 ITDebugLog(@"Setting up play pause hot key.");
705 hotKey = [[ITHotKey alloc] init];
706 [hotKey setName:@"PlayPause"];
707 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
708 [hotKey setTarget:self];
709 [hotKey setAction:@selector(playPause)];
710 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
713 if ([df objectForKey:@"NextTrack"] != nil) {
714 ITDebugLog(@"Setting up next track hot key.");
715 hotKey = [[ITHotKey alloc] init];
716 [hotKey setName:@"NextTrack"];
717 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
718 [hotKey setTarget:self];
719 [hotKey setAction:@selector(nextSong)];
720 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
723 if ([df objectForKey:@"PrevTrack"] != nil) {
724 ITDebugLog(@"Setting up previous track hot key.");
725 hotKey = [[ITHotKey alloc] init];
726 [hotKey setName:@"PrevTrack"];
727 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
728 [hotKey setTarget:self];
729 [hotKey setAction:@selector(prevSong)];
730 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
733 if ([df objectForKey:@"FastForward"] != nil) {
734 ITDebugLog(@"Setting up fast forward hot key.");
735 hotKey = [[ITHotKey alloc] init];
736 [hotKey setName:@"FastForward"];
737 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
738 [hotKey setTarget:self];
739 [hotKey setAction:@selector(fastForward)];
740 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
743 if ([df objectForKey:@"Rewind"] != nil) {
744 ITDebugLog(@"Setting up rewind hot key.");
745 hotKey = [[ITHotKey alloc] init];
746 [hotKey setName:@"Rewind"];
747 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
748 [hotKey setTarget:self];
749 [hotKey setAction:@selector(rewind)];
750 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
753 if ([df objectForKey:@"ShowPlayer"] != nil) {
754 ITDebugLog(@"Setting up show player hot key.");
755 hotKey = [[ITHotKey alloc] init];
756 [hotKey setName:@"ShowPlayer"];
757 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
758 [hotKey setTarget:self];
759 [hotKey setAction:@selector(showPlayer)];
760 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
763 if ([df objectForKey:@"TrackInfo"] != nil) {
764 ITDebugLog(@"Setting up track info hot key.");
765 hotKey = [[ITHotKey alloc] init];
766 [hotKey setName:@"TrackInfo"];
767 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
768 [hotKey setTarget:self];
769 [hotKey setAction:@selector(showCurrentTrackInfo)];
770 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
773 if ([df objectForKey:@"UpcomingSongs"] != nil) {
774 ITDebugLog(@"Setting up upcoming songs hot key.");
775 hotKey = [[ITHotKey alloc] init];
776 [hotKey setName:@"UpcomingSongs"];
777 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
778 [hotKey setTarget:self];
779 [hotKey setAction:@selector(showUpcomingSongs)];
780 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
783 if ([df objectForKey:@"ToggleLoop"] != nil) {
784 ITDebugLog(@"Setting up toggle loop hot key.");
785 hotKey = [[ITHotKey alloc] init];
786 [hotKey setName:@"ToggleLoop"];
787 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
788 [hotKey setTarget:self];
789 [hotKey setAction:@selector(toggleLoop)];
790 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
793 if ([df objectForKey:@"ToggleShuffle"] != nil) {
794 ITDebugLog(@"Setting up toggle shuffle hot key.");
795 hotKey = [[ITHotKey alloc] init];
796 [hotKey setName:@"ToggleShuffle"];
797 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
798 [hotKey setTarget:self];
799 [hotKey setAction:@selector(toggleShuffle)];
800 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
803 if ([df objectForKey:@"IncrementVolume"] != nil) {
804 ITDebugLog(@"Setting up increment volume hot key.");
805 hotKey = [[ITHotKey alloc] init];
806 [hotKey setName:@"IncrementVolume"];
807 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
808 [hotKey setTarget:self];
809 [hotKey setAction:@selector(incrementVolume)];
810 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
813 if ([df objectForKey:@"DecrementVolume"] != nil) {
814 ITDebugLog(@"Setting up decrement volume hot key.");
815 hotKey = [[ITHotKey alloc] init];
816 [hotKey setName:@"DecrementVolume"];
817 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
818 [hotKey setTarget:self];
819 [hotKey setAction:@selector(decrementVolume)];
820 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
823 if ([df objectForKey:@"IncrementRating"] != nil) {
824 ITDebugLog(@"Setting up increment rating hot key.");
825 hotKey = [[ITHotKey alloc] init];
826 [hotKey setName:@"IncrementRating"];
827 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
828 [hotKey setTarget:self];
829 [hotKey setAction:@selector(incrementRating)];
830 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
833 if ([df objectForKey:@"DecrementRating"] != nil) {
834 ITDebugLog(@"Setting up decrement rating hot key.");
835 hotKey = [[ITHotKey alloc] init];
836 [hotKey setName:@"DecrementRating"];
837 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
838 [hotKey setTarget:self];
839 [hotKey setAction:@selector(decrementRating)];
840 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
843 if ([df objectForKey:@"PopupMenu"] != nil) {
844 ITDebugLog(@"Setting up popup menu hot key.");
845 hotKey = [[ITHotKey alloc] init];
846 [hotKey setName:@"PopupMenu"];
847 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
848 [hotKey setTarget:self];
849 [hotKey setAction:@selector(popupMenu)];
850 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
854 for (i = 0; i <= 5; i++) {
855 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
856 if ([df objectForKey:curName] != nil) {
857 ITDebugLog(@"Setting up set rating %i hot key.", i);
858 hotKey = [[ITHotKey alloc] init];
859 [hotKey setName:curName];
860 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
861 [hotKey setTarget:self];
862 [hotKey setAction:@selector(setRating:)];
863 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
866 ITDebugLog(@"Finished setting up hot keys.");
869 - (void)showCurrentTrackInfo
871 ITMTRemotePlayerSource source = 0;
872 NSString *title = nil;
873 NSString *album = nil;
874 NSString *artist = nil;
875 NSString *composer = nil;
876 NSString *time = nil;
877 NSString *track = nil;
882 ITDebugLog(@"Showing track info status window.");
885 source = [[self currentRemote] currentSource];
886 title = [[self currentRemote] currentSongTitle];
888 [self networkError:localException];
892 if ( [df boolForKey:@"showAlbumArtwork"] ) {
893 NSSize oldSize, newSize;
895 art = [[self currentRemote] currentSongAlbumArt];
896 oldSize = [art size];
897 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
898 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
899 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
901 [self networkError:localException];
905 if ( [df boolForKey:@"showAlbum"] ) {
907 album = [[self currentRemote] currentSongAlbum];
909 [self networkError:localException];
913 if ( [df boolForKey:@"showArtist"] ) {
915 artist = [[self currentRemote] currentSongArtist];
917 [self networkError:localException];
921 if ( [df boolForKey:@"showComposer"] ) {
923 composer = [[self currentRemote] currentSongComposer];
925 [self networkError:localException];
929 if ( [df boolForKey:@"showTime"] ) {
931 time = [NSString stringWithFormat:@"%@: %@ / %@",
932 NSLocalizedString(@"time", @"Time"),
933 [[self currentRemote] currentSongElapsed],
934 [[self currentRemote] currentSongLength]];
936 [self networkError:localException];
940 if ( [df boolForKey:@"showTrackNumber"] ) {
945 trackNo = [[self currentRemote] currentSongTrack];
946 trackCount = [[self currentRemote] currentAlbumTrackCount];
948 [self networkError:localException];
951 if ( (trackNo > 0) || (trackCount > 0) ) {
952 track = [NSString stringWithFormat:@"%@: %i %@ %i",
953 @"Track", trackNo, @"of", trackCount];
957 if ( [df boolForKey:@"showTrackRating"] ) {
958 float currentRating = 0;
961 currentRating = [[self currentRemote] currentSongRating];
963 [self networkError:localException];
966 if (currentRating >= 0.0) {
967 rating = ( currentRating * 5 );
971 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
973 playCount = [[self currentRemote] currentSongPlayCount];
975 [self networkError:localException];
979 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
981 ITDebugLog(@"Showing current track info status window.");
982 [statusWindowController showSongInfoWindowWithSource:source
994 - (void)showUpcomingSongs
998 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1000 [self networkError:localException];
1003 ITDebugLog(@"Showing upcoming songs status window.");
1006 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1007 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1008 int curTrack = [[self currentRemote] currentSongIndex];
1011 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
1012 if (i <= numSongs) {
1013 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1017 if ([songList count] == 0) {
1018 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1021 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1023 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1026 [self networkError:localException];
1035 NSMenu *menu = [statusItem menu];
1036 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1041 - (void)incrementVolume
1044 float volume = [[self currentRemote] volume];
1045 float dispVol = volume;
1046 ITDebugLog(@"Incrementing volume.");
1055 ITDebugLog(@"Setting volume to %f", volume);
1056 [[self currentRemote] setVolume:volume];
1058 // Show volume status window
1059 [statusWindowController showVolumeWindowWithLevel:dispVol];
1061 [self networkError:localException];
1065 - (void)decrementVolume
1068 float volume = [[self currentRemote] volume];
1069 float dispVol = volume;
1070 ITDebugLog(@"Decrementing volume.");
1079 ITDebugLog(@"Setting volume to %f", volume);
1080 [[self currentRemote] setVolume:volume];
1082 //Show volume status window
1083 [statusWindowController showVolumeWindowWithLevel:dispVol];
1085 [self networkError:localException];
1089 - (void)incrementRating
1092 float rating = [[self currentRemote] currentSongRating];
1093 ITDebugLog(@"Incrementing rating.");
1095 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1096 ITDebugLog(@"No song playing, rating change aborted.");
1104 ITDebugLog(@"Setting rating to %f", rating);
1105 [[self currentRemote] setCurrentSongRating:rating];
1107 //Show rating status window
1108 [statusWindowController showRatingWindowWithRating:rating];
1110 [self networkError:localException];
1114 - (void)decrementRating
1117 float rating = [[self currentRemote] currentSongRating];
1118 ITDebugLog(@"Decrementing rating.");
1120 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1121 ITDebugLog(@"No song playing, rating change aborted.");
1129 ITDebugLog(@"Setting rating to %f", rating);
1130 [[self currentRemote] setCurrentSongRating:rating];
1132 //Show rating status window
1133 [statusWindowController showRatingWindowWithRating:rating];
1135 [self networkError:localException];
1139 - (void)setRating:(ITHotKey *)sender
1141 int stars = [[sender name] characterAtIndex:9] - 48;
1142 [self selectSongRating:stars * 20];
1143 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1149 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1150 ITDebugLog(@"Toggling repeat mode.");
1151 switch (repeatMode) {
1152 case ITMTRemotePlayerRepeatOff:
1153 repeatMode = ITMTRemotePlayerRepeatAll;
1155 case ITMTRemotePlayerRepeatAll:
1156 repeatMode = ITMTRemotePlayerRepeatOne;
1158 case ITMTRemotePlayerRepeatOne:
1159 repeatMode = ITMTRemotePlayerRepeatOff;
1162 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1163 [[self currentRemote] setRepeatMode:repeatMode];
1165 //Show loop status window
1166 [statusWindowController showRepeatWindowWithMode:repeatMode];
1168 [self networkError:localException];
1172 - (void)toggleShuffle
1175 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1176 ITDebugLog(@"Toggling shuffle mode.");
1177 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1178 //Show shuffle status window
1179 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1180 [statusWindowController showShuffleWindow:newShuffleEnabled];
1182 [self networkError:localException];
1186 - (void)registerNowOK
1188 [[StatusWindow sharedWindow] setLocked:NO];
1189 [[StatusWindow sharedWindow] vanish:self];
1190 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1195 - (void)registerNowCancel
1197 [[StatusWindow sharedWindow] setLocked:NO];
1198 [[StatusWindow sharedWindow] vanish:self];
1199 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1201 [NSApp terminate:self];
1204 /*************************************************************************/
1206 #pragma mark NETWORK HANDLERS
1207 /*************************************************************************/
1209 - (void)setServerStatus:(BOOL)newStatus
1213 [networkController setServerStatus:YES];
1216 [networkController setServerStatus:NO];
1220 - (int)connectToServer
1223 ITDebugLog(@"Attempting to connect to shared remote.");
1224 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1227 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1228 currentRemote = [[[networkController networkObject] remote] retain];
1230 [self setupHotKeys];
1231 //playerRunningState = ITMTRemotePlayerRunning;
1232 playerRunningState = [[self currentRemote] playerRunningState];
1234 [refreshTimer invalidate];
1235 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1237 selector:@selector(timerUpdate)
1239 repeats:YES] retain];
1241 ITDebugLog(@"Connection successful.");
1243 } else if (result == 0) {
1244 ITDebugLog(@"Connection failed.");
1245 currentRemote = [remoteArray objectAtIndex:0];
1248 //Do something about the password being invalid
1249 ITDebugLog(@"Connection failed.");
1250 currentRemote = [remoteArray objectAtIndex:0];
1255 - (BOOL)disconnectFromServer
1257 ITDebugLog(@"Disconnecting from shared remote.");
1259 [currentRemote release];
1260 currentRemote = [remoteArray objectAtIndex:0];
1261 [networkController disconnect];
1263 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1264 [self applicationLaunched:nil];
1266 [self applicationTerminated:nil];
1272 - (void)checkForRemoteServer
1274 [self checkForRemoteServerAndConnectImmediately:NO];
1277 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1279 ITDebugLog(@"Checking for remote server.");
1280 if (!_checkingForServer) {
1281 if (!_serverCheckLock) {
1282 _serverCheckLock = [[NSLock alloc] init];
1284 [_serverCheckLock lock];
1285 _checkingForServer = YES;
1286 [_serverCheckLock unlock];
1287 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1291 - (void)runRemoteServerCheck:(id)sender
1293 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1294 ITDebugLog(@"Remote server check running.");
1295 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1296 ITDebugLog(@"Remote server found.");
1297 if ([sender boolValue]) {
1298 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1300 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1303 ITDebugLog(@"Remote server not found.");
1304 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1306 [_serverCheckLock lock];
1307 _checkingForServer = NO;
1308 [_serverCheckLock unlock];
1312 - (void)remoteServerFound:(id)sender
1314 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1315 [[StatusWindowController sharedController] showReconnectQueryWindow];
1319 - (void)remoteServerNotFound:(id)sender
1321 if (![[NetworkController sharedController] isConnectedToServer]) {
1322 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1326 - (void)networkError:(NSException *)exception
1328 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1329 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1330 //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);
1331 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1332 if ([self disconnectFromServer]) {
1333 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1334 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1336 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1343 /*if ([self connectToServer] == 0) {
1344 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1346 [self checkForRemoteServerAndConnectImmediately:YES];
1347 [[StatusWindow sharedWindow] setLocked:NO];
1348 [[StatusWindow sharedWindow] vanish:self];
1349 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1352 - (void)cancelReconnect
1354 [[StatusWindow sharedWindow] setLocked:NO];
1355 [[StatusWindow sharedWindow] vanish:self];
1356 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1359 /*************************************************************************/
1361 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1362 /*************************************************************************/
1364 - (void)applicationLaunched:(NSNotification *)note
1367 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1368 ITDebugLog(@"Remote application launched.");
1369 playerRunningState = ITMTRemotePlayerRunning;
1370 [[self currentRemote] begin];
1371 [self setLatestSongIdentifier:@""];
1373 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1375 selector:@selector(timerUpdate)
1377 repeats:YES] retain];
1378 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1379 [self setupHotKeys];
1382 [self networkError:localException];
1386 - (void)applicationTerminated:(NSNotification *)note
1389 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1390 ITDebugLog(@"Remote application terminated.");
1391 playerRunningState = ITMTRemotePlayerNotRunning;
1392 [[self currentRemote] halt];
1393 [refreshTimer invalidate];
1394 [refreshTimer release];
1396 [self clearHotKeys];
1398 if ([df objectForKey:@"ShowPlayer"] != nil) {
1400 ITDebugLog(@"Setting up show player hot key.");
1401 hotKey = [[ITHotKey alloc] init];
1402 [hotKey setName:@"ShowPlayer"];
1403 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1404 [hotKey setTarget:self];
1405 [hotKey setAction:@selector(showPlayer)];
1406 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1410 [self networkError:localException];
1415 /*************************************************************************/
1417 #pragma mark NSApplication DELEGATE METHODS
1418 /*************************************************************************/
1420 - (void)applicationWillTerminate:(NSNotification *)note
1422 [networkController stopRemoteServerSearch];
1423 [self clearHotKeys];
1424 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1428 /*************************************************************************/
1430 #pragma mark DEALLOCATION METHOD
1431 /*************************************************************************/
1435 [self applicationTerminated:nil];
1437 [statusItem release];
1438 [statusWindowController release];
1439 [menuController release];
1440 [networkController release];
1441 [_serverCheckLock release];