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 if ([[self currentRemote] playerStateUniqueIdentifier] == nil) {
365 if ([statusItem isEnabled]) {
366 [statusItem setToolTip:@"iTunes not responding."];
369 [statusItem setEnabled:NO];
371 } else if (![statusItem isEnabled]) {
372 [statusItem setEnabled:YES];
373 [statusItem setToolTip:_toolTip];
378 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
379 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
380 if ([df boolForKey:@"runScripts"]) {
381 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
382 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
383 NSString *nextScript;
384 ITDebugLog(@"Running AppleScripts for song change.");
385 while ( (nextScript = [scriptsEnum nextObject]) ) {
387 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
388 ITDebugLog(@"Running script: %@", nextScript);
389 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
390 ITDebugLog(@"Error running script %@.", nextScript);
392 [currentScript release];
397 [statusItem setEnabled:NO];
400 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
401 [menuController rebuildSubmenus];
403 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
404 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
407 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
409 //Create the tooltip for the status item
410 if ( [df boolForKey:@"showToolTip"] ) {
411 NSString *artist = [[self currentRemote] currentSongArtist];
412 NSString *title = [[self currentRemote] currentSongTitle];
413 ITDebugLog(@"Creating status item tooltip.");
415 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
419 _toolTip = @"No Song Playing";
421 [statusItem setToolTip:_toolTip];
423 [statusItem setToolTip:nil];
426 [self networkError:localException];
430 [statusItem setEnabled:YES];
433 if ([networkController isConnectedToServer]) {
434 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
440 ITDebugLog(@"Menu clicked.");
442 if ( ([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning ) {
443 if ([statusItem isEnabled]) {
444 [statusItem setToolTip:@"iTunes not responding."];
447 [statusItem setEnabled:NO];
449 } else if (![statusItem isEnabled]) {
450 [statusItem setEnabled:YES];
451 [statusItem setToolTip:_toolTip];
456 if ([networkController isConnectedToServer]) {
457 //Used the cached version
462 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
463 [statusItem setMenu:[menuController menu]];
465 [statusItem setMenu:[menuController menuForNoPlayer]];
468 [self networkError:localException];
481 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
482 ITDebugLog(@"Play/Pause toggled");
483 if (state == ITMTRemotePlayerPlaying) {
484 [[self currentRemote] pause];
485 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
486 [[self currentRemote] pause];
487 [[self currentRemote] play];
489 [[self currentRemote] play];
492 [self networkError:localException];
500 ITDebugLog(@"Going to next song.");
502 [[self currentRemote] goToNextSong];
504 [self networkError:localException];
511 ITDebugLog(@"Going to previous song.");
513 [[self currentRemote] goToPreviousSong];
515 [self networkError:localException];
522 ITDebugLog(@"Fast forwarding.");
524 [[self currentRemote] forward];
526 [self networkError:localException];
533 ITDebugLog(@"Rewinding.");
535 [[self currentRemote] rewind];
537 [self networkError:localException];
542 - (void)selectPlaylistAtIndex:(int)index
544 ITDebugLog(@"Selecting playlist %i", index);
546 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
547 //[[self currentRemote] switchToPlaylistAtIndex:index];
549 [self networkError:localException];
554 - (void)selectSongAtIndex:(int)index
556 ITDebugLog(@"Selecting song %i", index);
558 [[self currentRemote] switchToSongAtIndex:index];
560 [self networkError:localException];
565 - (void)selectSongRating:(int)rating
567 ITDebugLog(@"Selecting song rating %i", rating);
569 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
571 [self networkError:localException];
576 - (void)selectEQPresetAtIndex:(int)index
578 ITDebugLog(@"Selecting EQ preset %i", index);
581 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
583 [[self currentRemote] switchToEQAtIndex:index];
586 [self networkError:localException];
591 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
593 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
595 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
597 [self networkError:localException];
599 ITDebugLog(@"Done making playlist");
604 ITDebugLog(@"Beginning show player.");
605 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
606 ITDebugLog(@"Showing player interface.");
608 [[self currentRemote] showPrimaryInterface];
610 [self networkError:localException];
613 ITDebugLog(@"Launching player.");
616 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
618 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
620 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
621 ITDebugLog(@"Error Launching Player");
624 [self networkError:localException];
627 ITDebugLog(@"Finished show player.");
630 - (void)showPreferences
632 ITDebugLog(@"Show preferences.");
633 [[PreferencesController sharedPrefs] showPrefsWindow:self];
636 - (void)showPreferencesAndClose
638 ITDebugLog(@"Show preferences.");
639 [[PreferencesController sharedPrefs] showPrefsWindow:self];
640 [[StatusWindow sharedWindow] setLocked:NO];
641 [[StatusWindow sharedWindow] vanish:self];
642 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
645 - (void)showTestWindow
647 [self showCurrentTrackInfo];
650 - (void)quitMenuTunes
652 ITDebugLog(@"Quitting MenuTunes.");
653 [NSApp terminate:self];
659 - (MenuController *)menuController
661 return menuController;
664 - (void)closePreferences
666 ITDebugLog(@"Preferences closed.");
667 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
672 - (ITMTRemote *)currentRemote
674 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
675 [self networkError:nil];
678 return currentRemote;
689 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
690 ITHotKey *nextHotKey;
691 ITDebugLog(@"Clearing hot keys.");
692 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
693 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
695 ITDebugLog(@"Done clearing hot keys.");
701 ITDebugLog(@"Setting up hot keys.");
703 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
707 if ([df objectForKey:@"PlayPause"] != nil) {
708 ITDebugLog(@"Setting up play pause hot key.");
709 hotKey = [[ITHotKey alloc] init];
710 [hotKey setName:@"PlayPause"];
711 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
712 [hotKey setTarget:self];
713 [hotKey setAction:@selector(playPause)];
714 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
717 if ([df objectForKey:@"NextTrack"] != nil) {
718 ITDebugLog(@"Setting up next track hot key.");
719 hotKey = [[ITHotKey alloc] init];
720 [hotKey setName:@"NextTrack"];
721 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
722 [hotKey setTarget:self];
723 [hotKey setAction:@selector(nextSong)];
724 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
727 if ([df objectForKey:@"PrevTrack"] != nil) {
728 ITDebugLog(@"Setting up previous track hot key.");
729 hotKey = [[ITHotKey alloc] init];
730 [hotKey setName:@"PrevTrack"];
731 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
732 [hotKey setTarget:self];
733 [hotKey setAction:@selector(prevSong)];
734 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
737 if ([df objectForKey:@"FastForward"] != nil) {
738 ITDebugLog(@"Setting up fast forward hot key.");
739 hotKey = [[ITHotKey alloc] init];
740 [hotKey setName:@"FastForward"];
741 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
742 [hotKey setTarget:self];
743 [hotKey setAction:@selector(fastForward)];
744 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
747 if ([df objectForKey:@"Rewind"] != nil) {
748 ITDebugLog(@"Setting up rewind hot key.");
749 hotKey = [[ITHotKey alloc] init];
750 [hotKey setName:@"Rewind"];
751 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
752 [hotKey setTarget:self];
753 [hotKey setAction:@selector(rewind)];
754 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
757 if ([df objectForKey:@"ShowPlayer"] != nil) {
758 ITDebugLog(@"Setting up show player hot key.");
759 hotKey = [[ITHotKey alloc] init];
760 [hotKey setName:@"ShowPlayer"];
761 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
762 [hotKey setTarget:self];
763 [hotKey setAction:@selector(showPlayer)];
764 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
767 if ([df objectForKey:@"TrackInfo"] != nil) {
768 ITDebugLog(@"Setting up track info hot key.");
769 hotKey = [[ITHotKey alloc] init];
770 [hotKey setName:@"TrackInfo"];
771 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
772 [hotKey setTarget:self];
773 [hotKey setAction:@selector(showCurrentTrackInfo)];
774 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
777 if ([df objectForKey:@"UpcomingSongs"] != nil) {
778 ITDebugLog(@"Setting up upcoming songs hot key.");
779 hotKey = [[ITHotKey alloc] init];
780 [hotKey setName:@"UpcomingSongs"];
781 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
782 [hotKey setTarget:self];
783 [hotKey setAction:@selector(showUpcomingSongs)];
784 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
787 if ([df objectForKey:@"ToggleLoop"] != nil) {
788 ITDebugLog(@"Setting up toggle loop hot key.");
789 hotKey = [[ITHotKey alloc] init];
790 [hotKey setName:@"ToggleLoop"];
791 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
792 [hotKey setTarget:self];
793 [hotKey setAction:@selector(toggleLoop)];
794 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
797 if ([df objectForKey:@"ToggleShuffle"] != nil) {
798 ITDebugLog(@"Setting up toggle shuffle hot key.");
799 hotKey = [[ITHotKey alloc] init];
800 [hotKey setName:@"ToggleShuffle"];
801 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
802 [hotKey setTarget:self];
803 [hotKey setAction:@selector(toggleShuffle)];
804 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
807 if ([df objectForKey:@"IncrementVolume"] != nil) {
808 ITDebugLog(@"Setting up increment volume hot key.");
809 hotKey = [[ITHotKey alloc] init];
810 [hotKey setName:@"IncrementVolume"];
811 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
812 [hotKey setTarget:self];
813 [hotKey setAction:@selector(incrementVolume)];
814 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
817 if ([df objectForKey:@"DecrementVolume"] != nil) {
818 ITDebugLog(@"Setting up decrement volume hot key.");
819 hotKey = [[ITHotKey alloc] init];
820 [hotKey setName:@"DecrementVolume"];
821 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
822 [hotKey setTarget:self];
823 [hotKey setAction:@selector(decrementVolume)];
824 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
827 if ([df objectForKey:@"IncrementRating"] != nil) {
828 ITDebugLog(@"Setting up increment rating hot key.");
829 hotKey = [[ITHotKey alloc] init];
830 [hotKey setName:@"IncrementRating"];
831 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
832 [hotKey setTarget:self];
833 [hotKey setAction:@selector(incrementRating)];
834 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
837 if ([df objectForKey:@"DecrementRating"] != nil) {
838 ITDebugLog(@"Setting up decrement rating hot key.");
839 hotKey = [[ITHotKey alloc] init];
840 [hotKey setName:@"DecrementRating"];
841 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
842 [hotKey setTarget:self];
843 [hotKey setAction:@selector(decrementRating)];
844 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
847 if ([df objectForKey:@"PopupMenu"] != nil) {
848 ITDebugLog(@"Setting up popup menu hot key.");
849 hotKey = [[ITHotKey alloc] init];
850 [hotKey setName:@"PopupMenu"];
851 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
852 [hotKey setTarget:self];
853 [hotKey setAction:@selector(popupMenu)];
854 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
858 for (i = 0; i <= 5; i++) {
859 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
860 if ([df objectForKey:curName] != nil) {
861 ITDebugLog(@"Setting up set rating %i hot key.", i);
862 hotKey = [[ITHotKey alloc] init];
863 [hotKey setName:curName];
864 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
865 [hotKey setTarget:self];
866 [hotKey setAction:@selector(setRating:)];
867 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
870 ITDebugLog(@"Finished setting up hot keys.");
873 - (void)showCurrentTrackInfo
875 ITMTRemotePlayerSource source = 0;
876 NSString *title = nil;
877 NSString *album = nil;
878 NSString *artist = nil;
879 NSString *composer = nil;
880 NSString *time = nil;
881 NSString *track = nil;
886 ITDebugLog(@"Showing track info status window.");
889 source = [[self currentRemote] currentSource];
890 title = [[self currentRemote] currentSongTitle];
892 [self networkError:localException];
896 if ( [df boolForKey:@"showAlbumArtwork"] ) {
897 NSSize oldSize, newSize;
899 art = [[self currentRemote] currentSongAlbumArt];
900 oldSize = [art size];
901 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
902 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
903 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
905 [self networkError:localException];
909 if ( [df boolForKey:@"showAlbum"] ) {
911 album = [[self currentRemote] currentSongAlbum];
913 [self networkError:localException];
917 if ( [df boolForKey:@"showArtist"] ) {
919 artist = [[self currentRemote] currentSongArtist];
921 [self networkError:localException];
925 if ( [df boolForKey:@"showComposer"] ) {
927 composer = [[self currentRemote] currentSongComposer];
929 [self networkError:localException];
933 if ( [df boolForKey:@"showTime"] ) {
935 time = [NSString stringWithFormat:@"%@: %@ / %@",
936 NSLocalizedString(@"time", @"Time"),
937 [[self currentRemote] currentSongElapsed],
938 [[self currentRemote] currentSongLength]];
940 [self networkError:localException];
944 if ( [df boolForKey:@"showTrackNumber"] ) {
949 trackNo = [[self currentRemote] currentSongTrack];
950 trackCount = [[self currentRemote] currentAlbumTrackCount];
952 [self networkError:localException];
955 if ( (trackNo > 0) || (trackCount > 0) ) {
956 track = [NSString stringWithFormat:@"%@: %i %@ %i",
957 @"Track", trackNo, @"of", trackCount];
961 if ( [df boolForKey:@"showTrackRating"] ) {
962 float currentRating = 0;
965 currentRating = [[self currentRemote] currentSongRating];
967 [self networkError:localException];
970 if (currentRating >= 0.0) {
971 rating = ( currentRating * 5 );
975 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
977 playCount = [[self currentRemote] currentSongPlayCount];
979 [self networkError:localException];
983 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
985 ITDebugLog(@"Showing current track info status window.");
986 [statusWindowController showSongInfoWindowWithSource:source
998 - (void)showUpcomingSongs
1002 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1004 [self networkError:localException];
1007 ITDebugLog(@"Showing upcoming songs status window.");
1010 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1011 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1012 int curTrack = [[self currentRemote] currentSongIndex];
1015 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
1016 if (i <= numSongs) {
1017 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1021 if ([songList count] == 0) {
1022 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1025 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1027 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1030 [self networkError:localException];
1039 NSMenu *menu = [statusItem menu];
1040 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1045 - (void)incrementVolume
1048 float volume = [[self currentRemote] volume];
1049 float dispVol = volume;
1050 ITDebugLog(@"Incrementing volume.");
1059 ITDebugLog(@"Setting volume to %f", volume);
1060 [[self currentRemote] setVolume:volume];
1062 // Show volume status window
1063 [statusWindowController showVolumeWindowWithLevel:dispVol];
1065 [self networkError:localException];
1069 - (void)decrementVolume
1072 float volume = [[self currentRemote] volume];
1073 float dispVol = volume;
1074 ITDebugLog(@"Decrementing volume.");
1083 ITDebugLog(@"Setting volume to %f", volume);
1084 [[self currentRemote] setVolume:volume];
1086 //Show volume status window
1087 [statusWindowController showVolumeWindowWithLevel:dispVol];
1089 [self networkError:localException];
1093 - (void)incrementRating
1096 float rating = [[self currentRemote] currentSongRating];
1097 ITDebugLog(@"Incrementing rating.");
1099 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1100 ITDebugLog(@"No song playing, rating change aborted.");
1108 ITDebugLog(@"Setting rating to %f", rating);
1109 [[self currentRemote] setCurrentSongRating:rating];
1111 //Show rating status window
1112 [statusWindowController showRatingWindowWithRating:rating];
1114 [self networkError:localException];
1118 - (void)decrementRating
1121 float rating = [[self currentRemote] currentSongRating];
1122 ITDebugLog(@"Decrementing rating.");
1124 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1125 ITDebugLog(@"No song playing, rating change aborted.");
1133 ITDebugLog(@"Setting rating to %f", rating);
1134 [[self currentRemote] setCurrentSongRating:rating];
1136 //Show rating status window
1137 [statusWindowController showRatingWindowWithRating:rating];
1139 [self networkError:localException];
1143 - (void)setRating:(ITHotKey *)sender
1145 int stars = [[sender name] characterAtIndex:9] - 48;
1146 [self selectSongRating:stars * 20];
1147 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1153 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1154 ITDebugLog(@"Toggling repeat mode.");
1155 switch (repeatMode) {
1156 case ITMTRemotePlayerRepeatOff:
1157 repeatMode = ITMTRemotePlayerRepeatAll;
1159 case ITMTRemotePlayerRepeatAll:
1160 repeatMode = ITMTRemotePlayerRepeatOne;
1162 case ITMTRemotePlayerRepeatOne:
1163 repeatMode = ITMTRemotePlayerRepeatOff;
1166 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1167 [[self currentRemote] setRepeatMode:repeatMode];
1169 //Show loop status window
1170 [statusWindowController showRepeatWindowWithMode:repeatMode];
1172 [self networkError:localException];
1176 - (void)toggleShuffle
1179 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1180 ITDebugLog(@"Toggling shuffle mode.");
1181 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1182 //Show shuffle status window
1183 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1184 [statusWindowController showShuffleWindow:newShuffleEnabled];
1186 [self networkError:localException];
1190 - (void)registerNowOK
1192 [[StatusWindow sharedWindow] setLocked:NO];
1193 [[StatusWindow sharedWindow] vanish:self];
1194 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1199 - (void)registerNowCancel
1201 [[StatusWindow sharedWindow] setLocked:NO];
1202 [[StatusWindow sharedWindow] vanish:self];
1203 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1205 [NSApp terminate:self];
1208 /*************************************************************************/
1210 #pragma mark NETWORK HANDLERS
1211 /*************************************************************************/
1213 - (void)setServerStatus:(BOOL)newStatus
1217 [networkController setServerStatus:YES];
1220 [networkController setServerStatus:NO];
1224 - (int)connectToServer
1227 ITDebugLog(@"Attempting to connect to shared remote.");
1228 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1231 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1232 currentRemote = [[[networkController networkObject] remote] retain];
1234 [self setupHotKeys];
1235 //playerRunningState = ITMTRemotePlayerRunning;
1236 playerRunningState = [[self currentRemote] playerRunningState];
1238 [refreshTimer invalidate];
1239 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1241 selector:@selector(timerUpdate)
1243 repeats:YES] retain];
1245 ITDebugLog(@"Connection successful.");
1247 } else if (result == 0) {
1248 ITDebugLog(@"Connection failed.");
1249 currentRemote = [remoteArray objectAtIndex:0];
1252 //Do something about the password being invalid
1253 ITDebugLog(@"Connection failed.");
1254 currentRemote = [remoteArray objectAtIndex:0];
1259 - (BOOL)disconnectFromServer
1261 ITDebugLog(@"Disconnecting from shared remote.");
1263 [currentRemote release];
1264 currentRemote = [remoteArray objectAtIndex:0];
1265 [networkController disconnect];
1267 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1268 [self applicationLaunched:nil];
1270 [self applicationTerminated:nil];
1276 - (void)checkForRemoteServer
1278 [self checkForRemoteServerAndConnectImmediately:NO];
1281 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1283 ITDebugLog(@"Checking for remote server.");
1284 if (!_checkingForServer) {
1285 if (!_serverCheckLock) {
1286 _serverCheckLock = [[NSLock alloc] init];
1288 [_serverCheckLock lock];
1289 _checkingForServer = YES;
1290 [_serverCheckLock unlock];
1291 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1295 - (void)runRemoteServerCheck:(id)sender
1297 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1298 ITDebugLog(@"Remote server check running.");
1299 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1300 ITDebugLog(@"Remote server found.");
1301 if ([sender boolValue]) {
1302 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1304 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1307 ITDebugLog(@"Remote server not found.");
1308 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1310 [_serverCheckLock lock];
1311 _checkingForServer = NO;
1312 [_serverCheckLock unlock];
1316 - (void)remoteServerFound:(id)sender
1318 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1319 [[StatusWindowController sharedController] showReconnectQueryWindow];
1323 - (void)remoteServerNotFound:(id)sender
1325 if (![[NetworkController sharedController] isConnectedToServer]) {
1326 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1330 - (void)networkError:(NSException *)exception
1332 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1333 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1334 //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);
1335 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1336 if ([self disconnectFromServer]) {
1337 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1338 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1340 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1347 /*if ([self connectToServer] == 0) {
1348 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1350 [self checkForRemoteServerAndConnectImmediately:YES];
1351 [[StatusWindow sharedWindow] setLocked:NO];
1352 [[StatusWindow sharedWindow] vanish:self];
1353 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1356 - (void)cancelReconnect
1358 [[StatusWindow sharedWindow] setLocked:NO];
1359 [[StatusWindow sharedWindow] vanish:self];
1360 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1363 /*************************************************************************/
1365 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1366 /*************************************************************************/
1368 - (void)applicationLaunched:(NSNotification *)note
1371 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1372 ITDebugLog(@"Remote application launched.");
1373 playerRunningState = ITMTRemotePlayerRunning;
1374 [[self currentRemote] begin];
1375 [self setLatestSongIdentifier:@""];
1377 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1379 selector:@selector(timerUpdate)
1381 repeats:YES] retain];
1382 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1383 [self setupHotKeys];
1386 [self networkError:localException];
1390 - (void)applicationTerminated:(NSNotification *)note
1393 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1394 ITDebugLog(@"Remote application terminated.");
1395 playerRunningState = ITMTRemotePlayerNotRunning;
1396 [[self currentRemote] halt];
1397 [refreshTimer invalidate];
1398 [refreshTimer release];
1400 [statusItem setEnabled:YES];
1401 [statusItem setToolTip:@"iTunes not running."];
1402 [self clearHotKeys];
1404 if ([df objectForKey:@"ShowPlayer"] != nil) {
1406 ITDebugLog(@"Setting up show player hot key.");
1407 hotKey = [[ITHotKey alloc] init];
1408 [hotKey setName:@"ShowPlayer"];
1409 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1410 [hotKey setTarget:self];
1411 [hotKey setAction:@selector(showPlayer)];
1412 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1416 [self networkError:localException];
1421 /*************************************************************************/
1423 #pragma mark NSApplication DELEGATE METHODS
1424 /*************************************************************************/
1426 - (void)applicationWillTerminate:(NSNotification *)note
1428 [networkController stopRemoteServerSearch];
1429 [self clearHotKeys];
1430 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1434 /*************************************************************************/
1436 #pragma mark DEALLOCATION METHOD
1437 /*************************************************************************/
1441 [self applicationTerminated:nil];
1443 [statusItem release];
1444 [statusWindowController release];
1445 [menuController release];
1446 [networkController release];
1447 [_serverCheckLock release];