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 - (void)applicationDidBecomeActive:(NSNotification *)note
180 [[MainController sharedController] showPreferences];
183 - (ITMTRemote *)loadRemote
185 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
186 ITDebugLog(@"Gathering remotes.");
188 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
189 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
190 NSString *bundlePath;
192 while ( (bundlePath = [enumerator nextObject]) ) {
193 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
196 Class remoteClass = [remoteBundle principalClass];
198 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
199 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
200 id remote = [remoteClass remote];
201 ITDebugLog(@"Adding remote at path %@", bundlePath);
202 [remoteArray addObject:remote];
207 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
208 // if ( [remoteArray count] > 1 ) {
209 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
211 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
214 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
215 return [remoteArray objectAtIndex:0];
218 /*************************************************************************/
220 #pragma mark INSTANCE METHODS
221 /*************************************************************************/
223 /*- (void)startTimerInNewThread
225 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
226 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
227 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
229 selector:@selector(timerUpdate)
231 repeats:YES] retain];
233 ITDebugLog(@"Timer started.");
237 - (void)setBlingTime:(NSDate*)date
239 NSMutableDictionary *globalPrefs;
241 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
243 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
244 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
246 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
247 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
249 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
251 [globalPrefs release];
254 - (NSDate*)getBlingTime
257 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
262 NSDate *now = [NSDate date];
263 if (![self blingBling]) {
264 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
265 [self setBlingTime:now];
266 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
267 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
268 [self setBlingTime:[now addTimeInterval:-259200]];
270 NSMutableDictionary *globalPrefs;
272 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
273 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
274 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
276 [globalPrefs release];
280 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
282 [statusItem setEnabled:NO];
284 if ([refreshTimer isValid]) {
285 [refreshTimer invalidate];
287 [statusWindowController showRegistrationQueryWindow];
291 [statusItem setEnabled:YES];
293 if (![refreshTimer isValid]) {
294 [refreshTimer release];
295 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
297 selector:@selector(timerUpdate)
299 repeats:YES] retain];
303 [self setBlingTime:nil];
314 if ( ! ([bling checkDone] == 2475) ) {
321 - (BOOL)songIsPlaying
323 NSString *identifier = nil;
325 identifier = [[self currentRemote] playerStateUniqueIdentifier];
327 [self networkError:localException];
329 return ( ! ([identifier isEqualToString:@"0-0"]) );
332 - (BOOL)radioIsPlaying
334 ITMTRemotePlayerPlaylistClass class = nil;
336 class = [[self currentRemote] currentPlaylistClass];
338 [self networkError:localException];
340 return (class == ITMTRemotePlayerRadioPlaylist );
345 NSString *identifier = nil;
347 identifier = [[self currentRemote] playerStateUniqueIdentifier];
349 [self networkError:localException];
351 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
354 - (NSString *)latestSongIdentifier
356 return _latestSongIdentifier;
359 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
361 ITDebugLog(@"Setting latest song identifier:");
362 ITDebugLog(@" - Identifier: %@", newIdentifier);
363 [_latestSongIdentifier autorelease];
364 _latestSongIdentifier = [newIdentifier retain];
369 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
370 if (identifier == nil) {
371 if ([statusItem isEnabled]) {
372 [statusItem setToolTip:@"iTunes not responding."];
373 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
375 [statusItem setEnabled:NO];
377 } else if (![statusItem isEnabled]) {
378 [statusItem setEnabled:YES];
379 [statusItem setToolTip:_toolTip];
380 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
384 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
385 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
386 if ([df boolForKey:@"runScripts"]) {
387 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
388 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
389 NSString *nextScript;
390 ITDebugLog(@"Running AppleScripts for song change.");
391 while ( (nextScript = [scriptsEnum nextObject]) ) {
393 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
394 ITDebugLog(@"Running script: %@", nextScript);
395 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
396 ITDebugLog(@"Error running script %@.", nextScript);
398 [currentScript release];
403 [statusItem setEnabled:NO];
406 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
408 if ([menuController rebuildSubmenus]) {
409 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
410 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
412 [self setLatestSongIdentifier:identifier];
413 //Create the tooltip for the status item
414 if ( [df boolForKey:@"showToolTip"] ) {
415 NSString *artist = [[self currentRemote] currentSongArtist];
416 NSString *title = [[self currentRemote] currentSongTitle];
417 ITDebugLog(@"Creating status item tooltip.");
419 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
423 _toolTip = @"No Song Playing";
425 [statusItem setToolTip:_toolTip];
427 [statusItem setToolTip:nil];
431 [self networkError:localException];
434 [statusItem setEnabled:YES];
437 if ([networkController isConnectedToServer]) {
438 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
444 ITDebugLog(@"Menu clicked.");
446 if ( ([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning ) {
447 if ([statusItem isEnabled]) {
448 [statusItem setToolTip:@"iTunes not responding."];
449 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
451 [statusItem setEnabled:NO];
453 } else if (![statusItem isEnabled]) {
454 [statusItem setEnabled:YES];
455 [statusItem setToolTip:_toolTip];
456 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
460 if ([networkController isConnectedToServer]) {
461 //Used the cached version
466 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
467 [statusItem setMenu:[menuController menu]];
469 [statusItem setMenu:[menuController menuForNoPlayer]];
472 [self networkError:localException];
485 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
486 ITDebugLog(@"Play/Pause toggled");
487 if (state == ITMTRemotePlayerPlaying) {
488 [[self currentRemote] pause];
489 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
490 [[self currentRemote] pause];
491 [[self currentRemote] play];
493 [[self currentRemote] play];
496 [self networkError:localException];
504 ITDebugLog(@"Going to next song.");
506 [[self currentRemote] goToNextSong];
508 [self networkError:localException];
515 ITDebugLog(@"Going to previous song.");
517 [[self currentRemote] goToPreviousSong];
519 [self networkError:localException];
526 ITDebugLog(@"Fast forwarding.");
528 [[self currentRemote] forward];
530 [self networkError:localException];
537 ITDebugLog(@"Rewinding.");
539 [[self currentRemote] rewind];
541 [self networkError:localException];
546 - (void)selectPlaylistAtIndex:(int)index
548 ITDebugLog(@"Selecting playlist %i", index);
550 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
551 //[[self currentRemote] switchToPlaylistAtIndex:index];
553 [self networkError:localException];
558 - (void)selectSongAtIndex:(int)index
560 ITDebugLog(@"Selecting song %i", index);
562 [[self currentRemote] switchToSongAtIndex:index];
564 [self networkError:localException];
569 - (void)selectSongRating:(int)rating
571 ITDebugLog(@"Selecting song rating %i", rating);
573 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
575 [self networkError:localException];
580 - (void)selectEQPresetAtIndex:(int)index
582 ITDebugLog(@"Selecting EQ preset %i", index);
585 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
587 [[self currentRemote] switchToEQAtIndex:index];
590 [self networkError:localException];
595 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
597 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
599 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
601 [self networkError:localException];
603 ITDebugLog(@"Done making playlist");
608 ITDebugLog(@"Beginning show player.");
609 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
610 ITDebugLog(@"Showing player interface.");
612 [[self currentRemote] showPrimaryInterface];
614 [self networkError:localException];
617 ITDebugLog(@"Launching player.");
620 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
622 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
624 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
625 ITDebugLog(@"Error Launching Player");
628 [self networkError:localException];
631 ITDebugLog(@"Finished show player.");
634 - (void)showPreferences
636 ITDebugLog(@"Show preferences.");
637 [[PreferencesController sharedPrefs] showPrefsWindow:self];
640 - (void)showPreferencesAndClose
642 ITDebugLog(@"Show preferences.");
643 [[PreferencesController sharedPrefs] showPrefsWindow:self];
644 [[StatusWindow sharedWindow] setLocked:NO];
645 [[StatusWindow sharedWindow] vanish:self];
646 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
649 - (void)showTestWindow
651 [self showCurrentTrackInfo];
654 - (void)quitMenuTunes
656 ITDebugLog(@"Quitting MenuTunes.");
657 [NSApp terminate:self];
663 - (MenuController *)menuController
665 return menuController;
668 - (void)closePreferences
670 ITDebugLog(@"Preferences closed.");
671 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
676 - (ITMTRemote *)currentRemote
678 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
679 [self networkError:nil];
682 return currentRemote;
693 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
694 ITHotKey *nextHotKey;
695 ITDebugLog(@"Clearing hot keys.");
696 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
697 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
699 ITDebugLog(@"Done clearing hot keys.");
705 ITDebugLog(@"Setting up hot keys.");
707 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
711 if ([df objectForKey:@"PlayPause"] != nil) {
712 ITDebugLog(@"Setting up play pause hot key.");
713 hotKey = [[ITHotKey alloc] init];
714 [hotKey setName:@"PlayPause"];
715 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
716 [hotKey setTarget:self];
717 [hotKey setAction:@selector(playPause)];
718 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
721 if ([df objectForKey:@"NextTrack"] != nil) {
722 ITDebugLog(@"Setting up next track hot key.");
723 hotKey = [[ITHotKey alloc] init];
724 [hotKey setName:@"NextTrack"];
725 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
726 [hotKey setTarget:self];
727 [hotKey setAction:@selector(nextSong)];
728 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
731 if ([df objectForKey:@"PrevTrack"] != nil) {
732 ITDebugLog(@"Setting up previous track hot key.");
733 hotKey = [[ITHotKey alloc] init];
734 [hotKey setName:@"PrevTrack"];
735 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
736 [hotKey setTarget:self];
737 [hotKey setAction:@selector(prevSong)];
738 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
741 if ([df objectForKey:@"FastForward"] != nil) {
742 ITDebugLog(@"Setting up fast forward hot key.");
743 hotKey = [[ITHotKey alloc] init];
744 [hotKey setName:@"FastForward"];
745 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
746 [hotKey setTarget:self];
747 [hotKey setAction:@selector(fastForward)];
748 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
751 if ([df objectForKey:@"Rewind"] != nil) {
752 ITDebugLog(@"Setting up rewind hot key.");
753 hotKey = [[ITHotKey alloc] init];
754 [hotKey setName:@"Rewind"];
755 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
756 [hotKey setTarget:self];
757 [hotKey setAction:@selector(rewind)];
758 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
761 if ([df objectForKey:@"ShowPlayer"] != nil) {
762 ITDebugLog(@"Setting up show player hot key.");
763 hotKey = [[ITHotKey alloc] init];
764 [hotKey setName:@"ShowPlayer"];
765 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
766 [hotKey setTarget:self];
767 [hotKey setAction:@selector(showPlayer)];
768 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
771 if ([df objectForKey:@"TrackInfo"] != nil) {
772 ITDebugLog(@"Setting up track info hot key.");
773 hotKey = [[ITHotKey alloc] init];
774 [hotKey setName:@"TrackInfo"];
775 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
776 [hotKey setTarget:self];
777 [hotKey setAction:@selector(showCurrentTrackInfo)];
778 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
781 if ([df objectForKey:@"UpcomingSongs"] != nil) {
782 ITDebugLog(@"Setting up upcoming songs hot key.");
783 hotKey = [[ITHotKey alloc] init];
784 [hotKey setName:@"UpcomingSongs"];
785 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
786 [hotKey setTarget:self];
787 [hotKey setAction:@selector(showUpcomingSongs)];
788 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
791 if ([df objectForKey:@"ToggleLoop"] != nil) {
792 ITDebugLog(@"Setting up toggle loop hot key.");
793 hotKey = [[ITHotKey alloc] init];
794 [hotKey setName:@"ToggleLoop"];
795 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
796 [hotKey setTarget:self];
797 [hotKey setAction:@selector(toggleLoop)];
798 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
801 if ([df objectForKey:@"ToggleShuffle"] != nil) {
802 ITDebugLog(@"Setting up toggle shuffle hot key.");
803 hotKey = [[ITHotKey alloc] init];
804 [hotKey setName:@"ToggleShuffle"];
805 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
806 [hotKey setTarget:self];
807 [hotKey setAction:@selector(toggleShuffle)];
808 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
811 if ([df objectForKey:@"IncrementVolume"] != nil) {
812 ITDebugLog(@"Setting up increment volume hot key.");
813 hotKey = [[ITHotKey alloc] init];
814 [hotKey setName:@"IncrementVolume"];
815 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
816 [hotKey setTarget:self];
817 [hotKey setAction:@selector(incrementVolume)];
818 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
821 if ([df objectForKey:@"DecrementVolume"] != nil) {
822 ITDebugLog(@"Setting up decrement volume hot key.");
823 hotKey = [[ITHotKey alloc] init];
824 [hotKey setName:@"DecrementVolume"];
825 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
826 [hotKey setTarget:self];
827 [hotKey setAction:@selector(decrementVolume)];
828 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
831 if ([df objectForKey:@"IncrementRating"] != nil) {
832 ITDebugLog(@"Setting up increment rating hot key.");
833 hotKey = [[ITHotKey alloc] init];
834 [hotKey setName:@"IncrementRating"];
835 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
836 [hotKey setTarget:self];
837 [hotKey setAction:@selector(incrementRating)];
838 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
841 if ([df objectForKey:@"DecrementRating"] != nil) {
842 ITDebugLog(@"Setting up decrement rating hot key.");
843 hotKey = [[ITHotKey alloc] init];
844 [hotKey setName:@"DecrementRating"];
845 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
846 [hotKey setTarget:self];
847 [hotKey setAction:@selector(decrementRating)];
848 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
851 if ([df objectForKey:@"PopupMenu"] != nil) {
852 ITDebugLog(@"Setting up popup menu hot key.");
853 hotKey = [[ITHotKey alloc] init];
854 [hotKey setName:@"PopupMenu"];
855 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
856 [hotKey setTarget:self];
857 [hotKey setAction:@selector(popupMenu)];
858 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
862 for (i = 0; i <= 5; i++) {
863 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
864 if ([df objectForKey:curName] != nil) {
865 ITDebugLog(@"Setting up set rating %i hot key.", i);
866 hotKey = [[ITHotKey alloc] init];
867 [hotKey setName:curName];
868 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
869 [hotKey setTarget:self];
870 [hotKey setAction:@selector(setRating:)];
871 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
874 ITDebugLog(@"Finished setting up hot keys.");
877 - (void)showCurrentTrackInfo
879 ITMTRemotePlayerSource source = 0;
880 NSString *title = nil;
881 NSString *album = nil;
882 NSString *artist = nil;
883 NSString *composer = nil;
884 NSString *time = nil;
885 NSString *track = nil;
890 ITDebugLog(@"Showing track info status window.");
893 source = [[self currentRemote] currentSource];
894 title = [[self currentRemote] currentSongTitle];
896 [self networkError:localException];
900 if ( [df boolForKey:@"showAlbumArtwork"] ) {
901 NSSize oldSize, newSize;
903 art = [[self currentRemote] currentSongAlbumArt];
904 oldSize = [art size];
905 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
906 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
907 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
909 [self networkError:localException];
913 if ( [df boolForKey:@"showAlbum"] ) {
915 album = [[self currentRemote] currentSongAlbum];
917 [self networkError:localException];
921 if ( [df boolForKey:@"showArtist"] ) {
923 artist = [[self currentRemote] currentSongArtist];
925 [self networkError:localException];
929 if ( [df boolForKey:@"showComposer"] ) {
931 composer = [[self currentRemote] currentSongComposer];
933 [self networkError:localException];
937 if ( [df boolForKey:@"showTime"] ) {
939 time = [NSString stringWithFormat:@"%@: %@ / %@",
940 NSLocalizedString(@"time", @"Time"),
941 [[self currentRemote] currentSongElapsed],
942 [[self currentRemote] currentSongLength]];
944 [self networkError:localException];
948 if ( [df boolForKey:@"showTrackNumber"] ) {
953 trackNo = [[self currentRemote] currentSongTrack];
954 trackCount = [[self currentRemote] currentAlbumTrackCount];
956 [self networkError:localException];
959 if ( (trackNo > 0) || (trackCount > 0) ) {
960 track = [NSString stringWithFormat:@"%@: %i %@ %i",
961 @"Track", trackNo, @"of", trackCount];
965 if ( [df boolForKey:@"showTrackRating"] ) {
966 float currentRating = 0;
969 currentRating = [[self currentRemote] currentSongRating];
971 [self networkError:localException];
974 if (currentRating >= 0.0) {
975 rating = ( currentRating * 5 );
979 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
981 playCount = [[self currentRemote] currentSongPlayCount];
983 [self networkError:localException];
987 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
989 ITDebugLog(@"Showing current track info status window.");
990 [statusWindowController showSongInfoWindowWithSource:source
1002 - (void)showUpcomingSongs
1006 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1008 [self networkError:localException];
1011 ITDebugLog(@"Showing upcoming songs status window.");
1014 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1015 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1016 int curTrack = [[self currentRemote] currentSongIndex];
1019 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
1020 if (i <= numSongs) {
1021 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1025 if ([songList count] == 0) {
1026 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1029 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1031 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1034 [self networkError:localException];
1043 NSMenu *menu = [statusItem menu];
1044 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1049 - (void)incrementVolume
1052 float volume = [[self currentRemote] volume];
1053 float dispVol = volume;
1054 ITDebugLog(@"Incrementing volume.");
1063 ITDebugLog(@"Setting volume to %f", volume);
1064 [[self currentRemote] setVolume:volume];
1066 // Show volume status window
1067 [statusWindowController showVolumeWindowWithLevel:dispVol];
1069 [self networkError:localException];
1073 - (void)decrementVolume
1076 float volume = [[self currentRemote] volume];
1077 float dispVol = volume;
1078 ITDebugLog(@"Decrementing volume.");
1087 ITDebugLog(@"Setting volume to %f", volume);
1088 [[self currentRemote] setVolume:volume];
1090 //Show volume status window
1091 [statusWindowController showVolumeWindowWithLevel:dispVol];
1093 [self networkError:localException];
1097 - (void)incrementRating
1100 float rating = [[self currentRemote] currentSongRating];
1101 ITDebugLog(@"Incrementing rating.");
1103 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1104 ITDebugLog(@"No song playing, rating change aborted.");
1112 ITDebugLog(@"Setting rating to %f", rating);
1113 [[self currentRemote] setCurrentSongRating:rating];
1115 //Show rating status window
1116 [statusWindowController showRatingWindowWithRating:rating];
1118 [self networkError:localException];
1122 - (void)decrementRating
1125 float rating = [[self currentRemote] currentSongRating];
1126 ITDebugLog(@"Decrementing rating.");
1128 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1129 ITDebugLog(@"No song playing, rating change aborted.");
1137 ITDebugLog(@"Setting rating to %f", rating);
1138 [[self currentRemote] setCurrentSongRating:rating];
1140 //Show rating status window
1141 [statusWindowController showRatingWindowWithRating:rating];
1143 [self networkError:localException];
1147 - (void)setRating:(ITHotKey *)sender
1149 int stars = [[sender name] characterAtIndex:9] - 48;
1150 [self selectSongRating:stars * 20];
1151 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1157 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1158 ITDebugLog(@"Toggling repeat mode.");
1159 switch (repeatMode) {
1160 case ITMTRemotePlayerRepeatOff:
1161 repeatMode = ITMTRemotePlayerRepeatAll;
1163 case ITMTRemotePlayerRepeatAll:
1164 repeatMode = ITMTRemotePlayerRepeatOne;
1166 case ITMTRemotePlayerRepeatOne:
1167 repeatMode = ITMTRemotePlayerRepeatOff;
1170 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1171 [[self currentRemote] setRepeatMode:repeatMode];
1173 //Show loop status window
1174 [statusWindowController showRepeatWindowWithMode:repeatMode];
1176 [self networkError:localException];
1180 - (void)toggleShuffle
1183 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1184 ITDebugLog(@"Toggling shuffle mode.");
1185 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1186 //Show shuffle status window
1187 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1188 [statusWindowController showShuffleWindow:newShuffleEnabled];
1190 [self networkError:localException];
1194 - (void)registerNowOK
1196 [[StatusWindow sharedWindow] setLocked:NO];
1197 [[StatusWindow sharedWindow] vanish:self];
1198 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1203 - (void)registerNowCancel
1205 [[StatusWindow sharedWindow] setLocked:NO];
1206 [[StatusWindow sharedWindow] vanish:self];
1207 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1209 [NSApp terminate:self];
1212 /*************************************************************************/
1214 #pragma mark NETWORK HANDLERS
1215 /*************************************************************************/
1217 - (void)setServerStatus:(BOOL)newStatus
1221 [networkController setServerStatus:YES];
1224 [networkController setServerStatus:NO];
1228 - (int)connectToServer
1231 ITDebugLog(@"Attempting to connect to shared remote.");
1232 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1235 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1236 currentRemote = [[[networkController networkObject] remote] retain];
1238 [self setupHotKeys];
1239 //playerRunningState = ITMTRemotePlayerRunning;
1240 playerRunningState = [[self currentRemote] playerRunningState];
1242 [refreshTimer invalidate];
1243 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1245 selector:@selector(timerUpdate)
1247 repeats:YES] retain];
1249 ITDebugLog(@"Connection successful.");
1251 } else if (result == 0) {
1252 ITDebugLog(@"Connection failed.");
1253 currentRemote = [remoteArray objectAtIndex:0];
1256 //Do something about the password being invalid
1257 ITDebugLog(@"Connection failed.");
1258 currentRemote = [remoteArray objectAtIndex:0];
1263 - (BOOL)disconnectFromServer
1265 ITDebugLog(@"Disconnecting from shared remote.");
1267 [currentRemote release];
1268 currentRemote = [remoteArray objectAtIndex:0];
1269 [networkController disconnect];
1271 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1272 [self applicationLaunched:nil];
1274 [self applicationTerminated:nil];
1280 - (void)checkForRemoteServer
1282 [self checkForRemoteServerAndConnectImmediately:NO];
1285 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1287 ITDebugLog(@"Checking for remote server.");
1288 if (!_checkingForServer) {
1289 if (!_serverCheckLock) {
1290 _serverCheckLock = [[NSLock alloc] init];
1292 [_serverCheckLock lock];
1293 _checkingForServer = YES;
1294 [_serverCheckLock unlock];
1295 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1299 - (void)runRemoteServerCheck:(id)sender
1301 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1302 ITDebugLog(@"Remote server check running.");
1303 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1304 ITDebugLog(@"Remote server found.");
1305 if ([sender boolValue]) {
1306 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1308 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1311 ITDebugLog(@"Remote server not found.");
1312 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1314 [_serverCheckLock lock];
1315 _checkingForServer = NO;
1316 [_serverCheckLock unlock];
1320 - (void)remoteServerFound:(id)sender
1322 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1323 [[StatusWindowController sharedController] showReconnectQueryWindow];
1327 - (void)remoteServerNotFound:(id)sender
1329 if (![[NetworkController sharedController] isConnectedToServer]) {
1330 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1334 - (void)networkError:(NSException *)exception
1336 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1337 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1338 //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);
1339 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1340 if ([self disconnectFromServer]) {
1341 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1342 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1344 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1351 /*if ([self connectToServer] == 0) {
1352 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1354 [self checkForRemoteServerAndConnectImmediately:YES];
1355 [[StatusWindow sharedWindow] setLocked:NO];
1356 [[StatusWindow sharedWindow] vanish:self];
1357 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1360 - (void)cancelReconnect
1362 [[StatusWindow sharedWindow] setLocked:NO];
1363 [[StatusWindow sharedWindow] vanish:self];
1364 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1367 /*************************************************************************/
1369 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1370 /*************************************************************************/
1372 - (void)applicationLaunched:(NSNotification *)note
1375 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1376 ITDebugLog(@"Remote application launched.");
1377 playerRunningState = ITMTRemotePlayerRunning;
1378 [[self currentRemote] begin];
1379 [self setLatestSongIdentifier:@""];
1381 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1383 selector:@selector(timerUpdate)
1385 repeats:YES] retain];
1386 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1387 [self setupHotKeys];
1390 [self networkError:localException];
1394 - (void)applicationTerminated:(NSNotification *)note
1397 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1398 ITDebugLog(@"Remote application terminated.");
1399 playerRunningState = ITMTRemotePlayerNotRunning;
1400 [[self currentRemote] halt];
1401 [refreshTimer invalidate];
1402 [refreshTimer release];
1404 [statusItem setEnabled:YES];
1405 [statusItem setToolTip:@"iTunes not running."];
1406 [self clearHotKeys];
1408 if ([df objectForKey:@"ShowPlayer"] != nil) {
1410 ITDebugLog(@"Setting up show player hot key.");
1411 hotKey = [[ITHotKey alloc] init];
1412 [hotKey setName:@"ShowPlayer"];
1413 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1414 [hotKey setTarget:self];
1415 [hotKey setAction:@selector(showPlayer)];
1416 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1420 [self networkError:localException];
1425 /*************************************************************************/
1427 #pragma mark NSApplication DELEGATE METHODS
1428 /*************************************************************************/
1430 - (void)applicationWillTerminate:(NSNotification *)note
1432 [networkController stopRemoteServerSearch];
1433 [self clearHotKeys];
1434 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1438 /*************************************************************************/
1440 #pragma mark DEALLOCATION METHOD
1441 /*************************************************************************/
1445 [self applicationTerminated:nil];
1447 [statusItem release];
1448 [statusWindowController release];
1449 [menuController release];
1450 [networkController release];
1451 [_serverCheckLock release];