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 NSMenu (MenuImpl)
18 @interface NSCarbonMenuImpl:NSObject
24 + (void)setupForNoMenuBar;
28 - (void)itemChanged:fp8;
29 - (void)itemAdded:fp8;
30 - (void)itemRemoved:fp8;
31 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
32 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
33 - (void)setupCarbonMenuBar;
34 - (void)setAsMainCarbonMenuBar;
35 - (void)clearAsMainCarbonMenuBar;
36 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
37 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
38 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
42 @implementation NSImage (SmoothAdditions)
44 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
47 NSImageRep *rep = [self bestRepresentationForDevice:nil];
49 newImage = [[NSImage alloc] initWithSize:scaledSize];
52 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
53 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
54 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
56 [newImage unlockFocus];
57 return [newImage autorelease];
62 @interface MainController(Private)
63 - (ITMTRemote *)loadRemote;
64 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
65 - (void)applicationLaunched:(NSNotification *)note;
66 - (void)applicationTerminated:(NSNotification *)note;
69 static MainController *sharedController;
71 @implementation MainController
73 + (MainController *)sharedController
75 return sharedController;
78 /*************************************************************************/
80 #pragma mark INITIALIZATION/DEALLOCATION METHODS
81 /*************************************************************************/
85 if ( ( self = [super init] ) ) {
86 sharedController = self;
88 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
89 [[PreferencesController sharedPrefs] setController:self];
90 statusWindowController = [StatusWindowController sharedController];
91 menuController = [[MenuController alloc] init];
92 df = [[NSUserDefaults standardUserDefaults] retain];
99 - (void)applicationDidFinishLaunching:(NSNotification *)note
101 //Turn on debug mode if needed
102 if ([df boolForKey:@"ITDebugMode"]) {
106 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
107 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
109 [[PreferencesController sharedPrefs] registerDefaults];
110 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
113 currentRemote = [self loadRemote];
114 [[self currentRemote] begin];
116 //Turn on network stuff if needed
117 networkController = [[NetworkController alloc] init];
118 if ([df boolForKey:@"enableSharing"]) {
119 [self setServerStatus:YES];
120 } else if ([df boolForKey:@"useSharedPlayer"]) {
121 [self checkForRemoteServerAndConnectImmediately:YES];
124 //Setup for notification of the remote player launching or quitting
125 [[[NSWorkspace sharedWorkspace] notificationCenter]
127 selector:@selector(applicationTerminated:)
128 name:NSWorkspaceDidTerminateApplicationNotification
131 [[[NSWorkspace sharedWorkspace] notificationCenter]
133 selector:@selector(applicationLaunched:)
134 name:NSWorkspaceDidLaunchApplicationNotification
137 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
138 [[PreferencesController sharedPrefs] registerDefaults];
141 if ([df boolForKey:@"ITMTNoStatusItem"]) {
144 [StatusItemHack install];
145 statusItem = [[ITStatusItem alloc]
146 initWithStatusBar:[NSStatusBar systemStatusBar]
147 withLength:NSSquareStatusItemLength];
150 bling = [[MTBlingController alloc] init];
152 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
154 selector:@selector(blingTime)
156 repeats:YES] retain];
159 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
160 [self applicationLaunched:nil];
162 if ([df boolForKey:@"LaunchPlayerWithMT"])
165 [self applicationTerminated:nil];
168 [self networkError:localException];
171 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
172 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
174 [networkController startRemoteServerSearch];
178 - (ITMTRemote *)loadRemote
180 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
181 ITDebugLog(@"Gathering remotes.");
183 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
184 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
185 NSString *bundlePath;
187 while ( (bundlePath = [enumerator nextObject]) ) {
188 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
191 Class remoteClass = [remoteBundle principalClass];
193 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
194 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
195 id remote = [remoteClass remote];
196 ITDebugLog(@"Adding remote at path %@", bundlePath);
197 [remoteArray addObject:remote];
202 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
203 // if ( [remoteArray count] > 1 ) {
204 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
206 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
209 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
210 return [remoteArray objectAtIndex:0];
213 /*************************************************************************/
215 #pragma mark INSTANCE METHODS
216 /*************************************************************************/
218 /*- (void)startTimerInNewThread
220 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
221 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
222 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
224 selector:@selector(timerUpdate)
226 repeats:YES] retain];
228 ITDebugLog(@"Timer started.");
232 - (void)setBlingTime:(NSDate*)date
234 NSMutableDictionary *globalPrefs;
236 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
238 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
239 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
241 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
242 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
244 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
246 [globalPrefs release];
249 - (NSDate*)getBlingTime
252 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
257 NSDate *now = [NSDate date];
258 if (![self blingBling]) {
259 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
260 [self setBlingTime:now];
261 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
262 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
263 [self setBlingTime:[now addTimeInterval:-259200]];
265 NSMutableDictionary *globalPrefs;
267 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
268 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
269 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
271 [globalPrefs release];
275 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
277 [statusItem setEnabled:NO];
279 if ([refreshTimer isValid]) {
280 [refreshTimer invalidate];
282 [statusWindowController showRegistrationQueryWindow];
286 [statusItem setEnabled:YES];
288 if (![refreshTimer isValid]) {
289 [refreshTimer release];
290 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
292 selector:@selector(timerUpdate)
294 repeats:YES] retain];
298 [self setBlingTime:nil];
309 if ( ! ([bling checkDone] == 2475) ) {
316 - (BOOL)songIsPlaying
318 NSString *identifier = nil;
320 identifier = [[self currentRemote] playerStateUniqueIdentifier];
322 [self networkError:localException];
324 return ( ! ([identifier isEqualToString:@"0-0"]) );
327 - (BOOL)radioIsPlaying
329 ITMTRemotePlayerPlaylistClass class = nil;
331 class = [[self currentRemote] currentPlaylistClass];
333 [self networkError:localException];
335 return (class == ITMTRemotePlayerRadioPlaylist );
340 NSString *identifier = nil;
342 identifier = [[self currentRemote] playerStateUniqueIdentifier];
344 [self networkError:localException];
346 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
349 - (NSString *)latestSongIdentifier
351 return _latestSongIdentifier;
354 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
356 ITDebugLog(@"Setting latest song identifier:");
357 ITDebugLog(@" - Identifier: %@", newIdentifier);
358 [_latestSongIdentifier autorelease];
359 _latestSongIdentifier = [newIdentifier retain];
364 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
365 if (identifier == nil) {
366 if ([statusItem isEnabled]) {
367 [statusItem setToolTip:@"iTunes not responding."];
368 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
370 [statusItem setEnabled:NO];
372 } else if (![statusItem isEnabled]) {
373 [statusItem setEnabled:YES];
374 [statusItem setToolTip:_toolTip];
375 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
379 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
380 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
381 if ([df boolForKey:@"runScripts"]) {
382 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
383 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
384 NSString *nextScript;
385 ITDebugLog(@"Running AppleScripts for song change.");
386 while ( (nextScript = [scriptsEnum nextObject]) ) {
388 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
389 ITDebugLog(@"Running script: %@", nextScript);
390 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
391 ITDebugLog(@"Error running script %@.", nextScript);
393 [currentScript release];
398 [statusItem setEnabled:NO];
401 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
403 if ([menuController rebuildSubmenus]) {
404 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
405 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
407 [self setLatestSongIdentifier:identifier];
408 //Create the tooltip for the status item
409 if ( [df boolForKey:@"showToolTip"] ) {
410 NSString *artist = [[self currentRemote] currentSongArtist];
411 NSString *title = [[self currentRemote] currentSongTitle];
412 ITDebugLog(@"Creating status item tooltip.");
414 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
418 _toolTip = @"No Song Playing";
420 [statusItem setToolTip:_toolTip];
422 [statusItem setToolTip:nil];
426 [self networkError:localException];
429 [statusItem setEnabled:YES];
432 if ([networkController isConnectedToServer]) {
433 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
439 ITDebugLog(@"Menu clicked.");
441 if ( ([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning ) {
442 if ([statusItem isEnabled]) {
443 [statusItem setToolTip:@"iTunes not responding."];
444 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
446 [statusItem setEnabled:NO];
448 } else if (![statusItem isEnabled]) {
449 [statusItem setEnabled:YES];
450 [statusItem setToolTip:_toolTip];
451 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
455 if ([networkController isConnectedToServer]) {
456 //Used the cached version
461 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
462 [statusItem setMenu:[menuController menu]];
464 [statusItem setMenu:[menuController menuForNoPlayer]];
467 [self networkError:localException];
480 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
481 ITDebugLog(@"Play/Pause toggled");
482 if (state == ITMTRemotePlayerPlaying) {
483 [[self currentRemote] pause];
484 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
485 [[self currentRemote] pause];
486 [[self currentRemote] play];
488 [[self currentRemote] play];
491 [self networkError:localException];
499 ITDebugLog(@"Going to next song.");
501 [[self currentRemote] goToNextSong];
503 [self networkError:localException];
510 ITDebugLog(@"Going to previous song.");
512 [[self currentRemote] goToPreviousSong];
514 [self networkError:localException];
521 ITDebugLog(@"Fast forwarding.");
523 [[self currentRemote] forward];
525 [self networkError:localException];
532 ITDebugLog(@"Rewinding.");
534 [[self currentRemote] rewind];
536 [self networkError:localException];
541 - (void)selectPlaylistAtIndex:(int)index
543 ITDebugLog(@"Selecting playlist %i", index);
545 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
546 //[[self currentRemote] switchToPlaylistAtIndex:index];
548 [self networkError:localException];
553 - (void)selectSongAtIndex:(int)index
555 ITDebugLog(@"Selecting song %i", index);
557 [[self currentRemote] switchToSongAtIndex:index];
559 [self networkError:localException];
564 - (void)selectSongRating:(int)rating
566 ITDebugLog(@"Selecting song rating %i", rating);
568 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
570 [self networkError:localException];
575 - (void)selectEQPresetAtIndex:(int)index
577 ITDebugLog(@"Selecting EQ preset %i", index);
580 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
582 [[self currentRemote] switchToEQAtIndex:index];
585 [self networkError:localException];
590 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
592 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
594 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
596 [self networkError:localException];
598 ITDebugLog(@"Done making playlist");
603 ITDebugLog(@"Beginning show player.");
604 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
605 ITDebugLog(@"Showing player interface.");
607 [[self currentRemote] showPrimaryInterface];
609 [self networkError:localException];
612 ITDebugLog(@"Launching player.");
615 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
617 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
619 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
620 ITDebugLog(@"Error Launching Player");
623 [self networkError:localException];
626 ITDebugLog(@"Finished show player.");
629 - (void)showPreferences
631 ITDebugLog(@"Show preferences.");
632 [[PreferencesController sharedPrefs] showPrefsWindow:self];
635 - (void)showPreferencesAndClose
637 ITDebugLog(@"Show preferences.");
638 [[PreferencesController sharedPrefs] showPrefsWindow:self];
639 [[StatusWindow sharedWindow] setLocked:NO];
640 [[StatusWindow sharedWindow] vanish:self];
641 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
644 - (void)showTestWindow
646 [self showCurrentTrackInfo];
649 - (void)quitMenuTunes
651 ITDebugLog(@"Quitting MenuTunes.");
652 [NSApp terminate:self];
658 - (MenuController *)menuController
660 return menuController;
663 - (void)closePreferences
665 ITDebugLog(@"Preferences closed.");
666 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
671 - (ITMTRemote *)currentRemote
673 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
674 [self networkError:nil];
677 return currentRemote;
688 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
689 ITHotKey *nextHotKey;
690 ITDebugLog(@"Clearing hot keys.");
691 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
692 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
694 ITDebugLog(@"Done clearing hot keys.");
700 ITDebugLog(@"Setting up hot keys.");
702 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
706 if ([df objectForKey:@"PlayPause"] != nil) {
707 ITDebugLog(@"Setting up play pause hot key.");
708 hotKey = [[ITHotKey alloc] init];
709 [hotKey setName:@"PlayPause"];
710 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
711 [hotKey setTarget:self];
712 [hotKey setAction:@selector(playPause)];
713 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
716 if ([df objectForKey:@"NextTrack"] != nil) {
717 ITDebugLog(@"Setting up next track hot key.");
718 hotKey = [[ITHotKey alloc] init];
719 [hotKey setName:@"NextTrack"];
720 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
721 [hotKey setTarget:self];
722 [hotKey setAction:@selector(nextSong)];
723 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
726 if ([df objectForKey:@"PrevTrack"] != nil) {
727 ITDebugLog(@"Setting up previous track hot key.");
728 hotKey = [[ITHotKey alloc] init];
729 [hotKey setName:@"PrevTrack"];
730 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
731 [hotKey setTarget:self];
732 [hotKey setAction:@selector(prevSong)];
733 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
736 if ([df objectForKey:@"FastForward"] != nil) {
737 ITDebugLog(@"Setting up fast forward hot key.");
738 hotKey = [[ITHotKey alloc] init];
739 [hotKey setName:@"FastForward"];
740 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
741 [hotKey setTarget:self];
742 [hotKey setAction:@selector(fastForward)];
743 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
746 if ([df objectForKey:@"Rewind"] != nil) {
747 ITDebugLog(@"Setting up rewind hot key.");
748 hotKey = [[ITHotKey alloc] init];
749 [hotKey setName:@"Rewind"];
750 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
751 [hotKey setTarget:self];
752 [hotKey setAction:@selector(rewind)];
753 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
756 if ([df objectForKey:@"ShowPlayer"] != nil) {
757 ITDebugLog(@"Setting up show player hot key.");
758 hotKey = [[ITHotKey alloc] init];
759 [hotKey setName:@"ShowPlayer"];
760 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
761 [hotKey setTarget:self];
762 [hotKey setAction:@selector(showPlayer)];
763 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
766 if ([df objectForKey:@"TrackInfo"] != nil) {
767 ITDebugLog(@"Setting up track info hot key.");
768 hotKey = [[ITHotKey alloc] init];
769 [hotKey setName:@"TrackInfo"];
770 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
771 [hotKey setTarget:self];
772 [hotKey setAction:@selector(showCurrentTrackInfo)];
773 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
776 if ([df objectForKey:@"UpcomingSongs"] != nil) {
777 ITDebugLog(@"Setting up upcoming songs hot key.");
778 hotKey = [[ITHotKey alloc] init];
779 [hotKey setName:@"UpcomingSongs"];
780 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
781 [hotKey setTarget:self];
782 [hotKey setAction:@selector(showUpcomingSongs)];
783 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
786 if ([df objectForKey:@"ToggleLoop"] != nil) {
787 ITDebugLog(@"Setting up toggle loop hot key.");
788 hotKey = [[ITHotKey alloc] init];
789 [hotKey setName:@"ToggleLoop"];
790 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
791 [hotKey setTarget:self];
792 [hotKey setAction:@selector(toggleLoop)];
793 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
796 if ([df objectForKey:@"ToggleShuffle"] != nil) {
797 ITDebugLog(@"Setting up toggle shuffle hot key.");
798 hotKey = [[ITHotKey alloc] init];
799 [hotKey setName:@"ToggleShuffle"];
800 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
801 [hotKey setTarget:self];
802 [hotKey setAction:@selector(toggleShuffle)];
803 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
806 if ([df objectForKey:@"IncrementVolume"] != nil) {
807 ITDebugLog(@"Setting up increment volume hot key.");
808 hotKey = [[ITHotKey alloc] init];
809 [hotKey setName:@"IncrementVolume"];
810 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
811 [hotKey setTarget:self];
812 [hotKey setAction:@selector(incrementVolume)];
813 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
816 if ([df objectForKey:@"DecrementVolume"] != nil) {
817 ITDebugLog(@"Setting up decrement volume hot key.");
818 hotKey = [[ITHotKey alloc] init];
819 [hotKey setName:@"DecrementVolume"];
820 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
821 [hotKey setTarget:self];
822 [hotKey setAction:@selector(decrementVolume)];
823 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
826 if ([df objectForKey:@"IncrementRating"] != nil) {
827 ITDebugLog(@"Setting up increment rating hot key.");
828 hotKey = [[ITHotKey alloc] init];
829 [hotKey setName:@"IncrementRating"];
830 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
831 [hotKey setTarget:self];
832 [hotKey setAction:@selector(incrementRating)];
833 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
836 if ([df objectForKey:@"DecrementRating"] != nil) {
837 ITDebugLog(@"Setting up decrement rating hot key.");
838 hotKey = [[ITHotKey alloc] init];
839 [hotKey setName:@"DecrementRating"];
840 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
841 [hotKey setTarget:self];
842 [hotKey setAction:@selector(decrementRating)];
843 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
846 if ([df objectForKey:@"PopupMenu"] != nil) {
847 ITDebugLog(@"Setting up popup menu hot key.");
848 hotKey = [[ITHotKey alloc] init];
849 [hotKey setName:@"PopupMenu"];
850 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
851 [hotKey setTarget:self];
852 [hotKey setAction:@selector(popupMenu)];
853 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
857 for (i = 0; i <= 5; i++) {
858 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
859 if ([df objectForKey:curName] != nil) {
860 ITDebugLog(@"Setting up set rating %i hot key.", i);
861 hotKey = [[ITHotKey alloc] init];
862 [hotKey setName:curName];
863 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
864 [hotKey setTarget:self];
865 [hotKey setAction:@selector(setRating:)];
866 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
869 ITDebugLog(@"Finished setting up hot keys.");
872 - (void)showCurrentTrackInfo
874 ITMTRemotePlayerSource source = 0;
875 NSString *title = nil;
876 NSString *album = nil;
877 NSString *artist = nil;
878 NSString *composer = nil;
879 NSString *time = nil;
880 NSString *track = nil;
885 ITDebugLog(@"Showing track info status window.");
888 source = [[self currentRemote] currentSource];
889 title = [[self currentRemote] currentSongTitle];
891 [self networkError:localException];
895 if ( [df boolForKey:@"showAlbumArtwork"] ) {
896 NSSize oldSize, newSize;
898 art = [[self currentRemote] currentSongAlbumArt];
899 oldSize = [art size];
900 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
901 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
902 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
904 [self networkError:localException];
908 if ( [df boolForKey:@"showAlbum"] ) {
910 album = [[self currentRemote] currentSongAlbum];
912 [self networkError:localException];
916 if ( [df boolForKey:@"showArtist"] ) {
918 artist = [[self currentRemote] currentSongArtist];
920 [self networkError:localException];
924 if ( [df boolForKey:@"showComposer"] ) {
926 composer = [[self currentRemote] currentSongComposer];
928 [self networkError:localException];
932 if ( [df boolForKey:@"showTime"] ) {
934 time = [NSString stringWithFormat:@"%@: %@ / %@",
935 NSLocalizedString(@"time", @"Time"),
936 [[self currentRemote] currentSongElapsed],
937 [[self currentRemote] currentSongLength]];
939 [self networkError:localException];
943 if ( [df boolForKey:@"showTrackNumber"] ) {
948 trackNo = [[self currentRemote] currentSongTrack];
949 trackCount = [[self currentRemote] currentAlbumTrackCount];
951 [self networkError:localException];
954 if ( (trackNo > 0) || (trackCount > 0) ) {
955 track = [NSString stringWithFormat:@"%@: %i %@ %i",
956 @"Track", trackNo, @"of", trackCount];
960 if ( [df boolForKey:@"showTrackRating"] ) {
961 float currentRating = 0;
964 currentRating = [[self currentRemote] currentSongRating];
966 [self networkError:localException];
969 if (currentRating >= 0.0) {
970 rating = ( currentRating * 5 );
974 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
976 playCount = [[self currentRemote] currentSongPlayCount];
978 [self networkError:localException];
982 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
984 ITDebugLog(@"Showing current track info status window.");
985 [statusWindowController showSongInfoWindowWithSource:source
997 - (void)showUpcomingSongs
1001 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1003 [self networkError:localException];
1006 ITDebugLog(@"Showing upcoming songs status window.");
1009 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1010 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1011 int curTrack = [[self currentRemote] currentSongIndex];
1014 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
1015 if (i <= numSongs) {
1016 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1020 if ([songList count] == 0) {
1021 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1024 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1026 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1029 [self networkError:localException];
1038 NSMenu *menu = [statusItem menu];
1039 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1044 - (void)incrementVolume
1047 float volume = [[self currentRemote] volume];
1048 float dispVol = volume;
1049 ITDebugLog(@"Incrementing volume.");
1058 ITDebugLog(@"Setting volume to %f", volume);
1059 [[self currentRemote] setVolume:volume];
1061 // Show volume status window
1062 [statusWindowController showVolumeWindowWithLevel:dispVol];
1064 [self networkError:localException];
1068 - (void)decrementVolume
1071 float volume = [[self currentRemote] volume];
1072 float dispVol = volume;
1073 ITDebugLog(@"Decrementing volume.");
1082 ITDebugLog(@"Setting volume to %f", volume);
1083 [[self currentRemote] setVolume:volume];
1085 //Show volume status window
1086 [statusWindowController showVolumeWindowWithLevel:dispVol];
1088 [self networkError:localException];
1092 - (void)incrementRating
1095 float rating = [[self currentRemote] currentSongRating];
1096 ITDebugLog(@"Incrementing rating.");
1098 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1099 ITDebugLog(@"No song playing, rating change aborted.");
1107 ITDebugLog(@"Setting rating to %f", rating);
1108 [[self currentRemote] setCurrentSongRating:rating];
1110 //Show rating status window
1111 [statusWindowController showRatingWindowWithRating:rating];
1113 [self networkError:localException];
1117 - (void)decrementRating
1120 float rating = [[self currentRemote] currentSongRating];
1121 ITDebugLog(@"Decrementing rating.");
1123 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1124 ITDebugLog(@"No song playing, rating change aborted.");
1132 ITDebugLog(@"Setting rating to %f", rating);
1133 [[self currentRemote] setCurrentSongRating:rating];
1135 //Show rating status window
1136 [statusWindowController showRatingWindowWithRating:rating];
1138 [self networkError:localException];
1142 - (void)setRating:(ITHotKey *)sender
1144 int stars = [[sender name] characterAtIndex:9] - 48;
1145 [self selectSongRating:stars * 20];
1146 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1152 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1153 ITDebugLog(@"Toggling repeat mode.");
1154 switch (repeatMode) {
1155 case ITMTRemotePlayerRepeatOff:
1156 repeatMode = ITMTRemotePlayerRepeatAll;
1158 case ITMTRemotePlayerRepeatAll:
1159 repeatMode = ITMTRemotePlayerRepeatOne;
1161 case ITMTRemotePlayerRepeatOne:
1162 repeatMode = ITMTRemotePlayerRepeatOff;
1165 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1166 [[self currentRemote] setRepeatMode:repeatMode];
1168 //Show loop status window
1169 [statusWindowController showRepeatWindowWithMode:repeatMode];
1171 [self networkError:localException];
1175 - (void)toggleShuffle
1178 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1179 ITDebugLog(@"Toggling shuffle mode.");
1180 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1181 //Show shuffle status window
1182 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1183 [statusWindowController showShuffleWindow:newShuffleEnabled];
1185 [self networkError:localException];
1189 - (void)registerNowOK
1191 [[StatusWindow sharedWindow] setLocked:NO];
1192 [[StatusWindow sharedWindow] vanish:self];
1193 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1198 - (void)registerNowCancel
1200 [[StatusWindow sharedWindow] setLocked:NO];
1201 [[StatusWindow sharedWindow] vanish:self];
1202 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1204 [NSApp terminate:self];
1207 /*************************************************************************/
1209 #pragma mark NETWORK HANDLERS
1210 /*************************************************************************/
1212 - (void)setServerStatus:(BOOL)newStatus
1216 [networkController setServerStatus:YES];
1219 [networkController setServerStatus:NO];
1223 - (int)connectToServer
1226 ITDebugLog(@"Attempting to connect to shared remote.");
1227 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1230 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1231 currentRemote = [[[networkController networkObject] remote] retain];
1233 [self setupHotKeys];
1234 //playerRunningState = ITMTRemotePlayerRunning;
1235 playerRunningState = [[self currentRemote] playerRunningState];
1237 [refreshTimer invalidate];
1238 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1240 selector:@selector(timerUpdate)
1242 repeats:YES] retain];
1244 ITDebugLog(@"Connection successful.");
1246 } else if (result == 0) {
1247 ITDebugLog(@"Connection failed.");
1248 currentRemote = [remoteArray objectAtIndex:0];
1251 //Do something about the password being invalid
1252 ITDebugLog(@"Connection failed.");
1253 currentRemote = [remoteArray objectAtIndex:0];
1258 - (BOOL)disconnectFromServer
1260 ITDebugLog(@"Disconnecting from shared remote.");
1262 [currentRemote release];
1263 currentRemote = [remoteArray objectAtIndex:0];
1264 [networkController disconnect];
1266 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1267 [self applicationLaunched:nil];
1269 [self applicationTerminated:nil];
1275 - (void)checkForRemoteServer
1277 [self checkForRemoteServerAndConnectImmediately:NO];
1280 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1282 ITDebugLog(@"Checking for remote server.");
1283 if (!_checkingForServer) {
1284 if (!_serverCheckLock) {
1285 _serverCheckLock = [[NSLock alloc] init];
1287 [_serverCheckLock lock];
1288 _checkingForServer = YES;
1289 [_serverCheckLock unlock];
1290 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1294 - (void)runRemoteServerCheck:(id)sender
1296 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1297 ITDebugLog(@"Remote server check running.");
1298 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1299 ITDebugLog(@"Remote server found.");
1300 if ([sender boolValue]) {
1301 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1303 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1306 ITDebugLog(@"Remote server not found.");
1307 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1309 [_serverCheckLock lock];
1310 _checkingForServer = NO;
1311 [_serverCheckLock unlock];
1315 - (void)remoteServerFound:(id)sender
1317 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1318 [[StatusWindowController sharedController] showReconnectQueryWindow];
1322 - (void)remoteServerNotFound:(id)sender
1324 if (![[NetworkController sharedController] isConnectedToServer]) {
1325 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1329 - (void)networkError:(NSException *)exception
1331 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1332 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1333 //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);
1334 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1335 if ([self disconnectFromServer]) {
1336 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1337 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1339 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1346 /*if ([self connectToServer] == 0) {
1347 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1349 [self checkForRemoteServerAndConnectImmediately:YES];
1350 [[StatusWindow sharedWindow] setLocked:NO];
1351 [[StatusWindow sharedWindow] vanish:self];
1352 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1355 - (void)cancelReconnect
1357 [[StatusWindow sharedWindow] setLocked:NO];
1358 [[StatusWindow sharedWindow] vanish:self];
1359 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1362 /*************************************************************************/
1364 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1365 /*************************************************************************/
1367 - (void)applicationLaunched:(NSNotification *)note
1370 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1371 ITDebugLog(@"Remote application launched.");
1372 playerRunningState = ITMTRemotePlayerRunning;
1373 [[self currentRemote] begin];
1374 [self setLatestSongIdentifier:@""];
1376 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1378 selector:@selector(timerUpdate)
1380 repeats:YES] retain];
1381 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1382 [self setupHotKeys];
1385 [self networkError:localException];
1389 - (void)applicationTerminated:(NSNotification *)note
1392 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1393 ITDebugLog(@"Remote application terminated.");
1394 playerRunningState = ITMTRemotePlayerNotRunning;
1395 [[self currentRemote] halt];
1396 [refreshTimer invalidate];
1397 [refreshTimer release];
1399 [statusItem setEnabled:YES];
1400 [statusItem setToolTip:@"iTunes not running."];
1401 [self clearHotKeys];
1403 if ([df objectForKey:@"ShowPlayer"] != nil) {
1405 ITDebugLog(@"Setting up show player hot key.");
1406 hotKey = [[ITHotKey alloc] init];
1407 [hotKey setName:@"ShowPlayer"];
1408 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1409 [hotKey setTarget:self];
1410 [hotKey setAction:@selector(showPlayer)];
1411 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1415 [self networkError:localException];
1420 /*************************************************************************/
1422 #pragma mark NSApplication DELEGATE METHODS
1423 /*************************************************************************/
1425 - (void)applicationWillTerminate:(NSNotification *)note
1427 [networkController stopRemoteServerSearch];
1428 [self clearHotKeys];
1429 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1433 /*************************************************************************/
1435 #pragma mark DEALLOCATION METHOD
1436 /*************************************************************************/
1440 [self applicationTerminated:nil];
1442 [statusItem release];
1443 [statusWindowController release];
1444 [menuController release];
1445 [networkController release];
1446 [_serverCheckLock release];