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 "AudioscrobblerController.h"
13 #import "StatusItemHack.h"
15 @interface NSMenu (MenuImpl)
19 @interface NSCarbonMenuImpl:NSObject
25 + (void)setupForNoMenuBar;
29 - (void)itemChanged:fp8;
30 - (void)itemAdded:fp8;
31 - (void)itemRemoved:fp8;
32 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
33 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
34 - (void)setupCarbonMenuBar;
35 - (void)setAsMainCarbonMenuBar;
36 - (void)clearAsMainCarbonMenuBar;
37 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
38 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
39 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
43 @implementation NSImage (SmoothAdditions)
45 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
48 NSImageRep *rep = [self bestRepresentationForDevice:nil];
50 newImage = [[NSImage alloc] initWithSize:scaledSize];
53 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
54 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
55 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
57 [newImage unlockFocus];
58 return [newImage autorelease];
63 @interface MainController(Private)
64 - (ITMTRemote *)loadRemote;
65 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
66 - (void)applicationLaunched:(NSNotification *)note;
67 - (void)applicationTerminated:(NSNotification *)note;
69 - (void)invalidateStatusWindowUpdateTimer;
72 static MainController *sharedController;
74 @implementation MainController
76 + (MainController *)sharedController
78 return sharedController;
81 /*************************************************************************/
83 #pragma mark INITIALIZATION/DEALLOCATION METHODS
84 /*************************************************************************/
88 if ( ( self = [super init] ) ) {
89 sharedController = self;
91 _statusWindowUpdateTimer = nil;
92 _audioscrobblerTimer = nil;
94 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
95 [[PreferencesController sharedPrefs] setController:self];
96 statusWindowController = [StatusWindowController sharedController];
97 menuController = [[MenuController alloc] init];
98 df = [[NSUserDefaults standardUserDefaults] retain];
104 - (void)applicationDidFinishLaunching:(NSNotification *)note
106 NSString *iTunesPath = [df stringForKey:@"CustomPlayerPath"];
107 NSDictionary *iTunesInfoPlist;
110 //Turn on debug mode if needed
111 /*if ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)
112 if ((GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0)
113 if ((GetCurrentKeyModifiers() & (shiftKey | rightShiftKey)) != 0)*/
114 if ([df boolForKey:@"ITDebugMode"] || ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)) {
116 [[StatusWindowController sharedController] showDebugModeEnabledWindow];
119 //Check if iTunes 4.7 or later is installed
121 iTunesPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"];
123 iTunesInfoPlist = [[NSBundle bundleWithPath:iTunesPath] infoDictionary];
124 iTunesVersion = [[iTunesInfoPlist objectForKey:@"CFBundleVersion"] floatValue];
125 ITDebugLog(@"iTunes version found: %f.", iTunesVersion);
126 if (iTunesVersion >= 4.7) {
132 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
133 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
135 [[PreferencesController sharedPrefs] registerDefaults];
136 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
139 currentRemote = [self loadRemote];
140 [[self currentRemote] begin];
142 [[self currentRemote] currentSongElapsed];
144 //Turn on network stuff if needed
145 networkController = [[NetworkController alloc] init];
146 if ([df boolForKey:@"enableSharing"]) {
147 [self setServerStatus:YES];
148 } else if ([df boolForKey:@"useSharedPlayer"]) {
149 [self checkForRemoteServerAndConnectImmediately:YES];
152 //Setup for notification of the remote player launching or quitting
153 [[[NSWorkspace sharedWorkspace] notificationCenter]
155 selector:@selector(applicationTerminated:)
156 name:NSWorkspaceDidTerminateApplicationNotification
159 [[[NSWorkspace sharedWorkspace] notificationCenter]
161 selector:@selector(applicationLaunched:)
162 name:NSWorkspaceDidLaunchApplicationNotification
165 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
166 [[PreferencesController sharedPrefs] registerDefaults];
169 if ([df boolForKey:@"ITMTNoStatusItem"]) {
172 [StatusItemHack install];
173 statusItem = [[ITStatusItem alloc]
174 initWithStatusBar:[NSStatusBar systemStatusBar]
175 withLength:NSSquareStatusItemLength];
179 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
180 [self applicationLaunched:nil];
182 if ([df boolForKey:@"LaunchPlayerWithMT"])
185 [self applicationTerminated:nil];
188 [self networkError:localException];
191 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
192 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
194 if ([df boolForKey:@"audioscrobblerEnabled"]) {
195 if ([PreferencesController getKeychainItemPasswordForUser:[df stringForKey:@"audioscrobblerUser"]] != nil) {
196 [[AudioscrobblerController sharedController] attemptHandshake:NO];
200 [networkController startRemoteServerSearch];
202 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
210 - (ITMTRemote *)loadRemote
212 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
213 ITDebugLog(@"Gathering remotes.");
215 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
216 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
217 NSString *bundlePath;
219 while ( (bundlePath = [enumerator nextObject]) ) {
220 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
223 Class remoteClass = [remoteBundle principalClass];
225 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
226 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
227 id remote = [remoteClass remote];
228 ITDebugLog(@"Adding remote at path %@", bundlePath);
229 [remoteArray addObject:remote];
234 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
235 // if ( [remoteArray count] > 1 ) {
236 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
238 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
241 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
242 return [remoteArray objectAtIndex:0];
245 /*************************************************************************/
247 #pragma mark INSTANCE METHODS
248 /*************************************************************************/
250 /*- (void)startTimerInNewThread
252 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
253 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
254 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
256 selector:@selector(timerUpdate)
258 repeats:YES] retain];
260 ITDebugLog(@"Timer started.");
264 - (BOOL)songIsPlaying
266 NSString *identifier = nil;
268 identifier = [[self currentRemote] playerStateUniqueIdentifier];
270 [self networkError:localException];
272 return ( ! ([identifier isEqualToString:@"0-0"]) );
275 - (BOOL)radioIsPlaying
277 ITMTRemotePlayerPlaylistClass class = ITMTRemotePlayerLibraryPlaylist;
279 class = [[self currentRemote] currentPlaylistClass];
281 [self networkError:localException];
283 return (class == ITMTRemotePlayerRadioPlaylist );
288 NSString *identifier = nil;
290 identifier = [[self currentRemote] playerStateUniqueIdentifier];
292 [self networkError:localException];
294 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
297 - (NSString *)latestSongIdentifier
299 return _latestSongIdentifier;
302 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
304 ITDebugLog(@"Setting latest song identifier:");
305 ITDebugLog(@" - Identifier: %@", newIdentifier);
306 [_latestSongIdentifier autorelease];
307 _latestSongIdentifier = [newIdentifier retain];
312 NSString *identifier = nil;
314 identifier = [[self currentRemote] playerStateUniqueIdentifier];
316 [self networkError:localException];
318 if (refreshTimer && identifier == nil) {
319 if ([statusItem isEnabled]) {
320 [statusItem setToolTip:@"iTunes not responding."];
322 [statusItem setEnabled:NO];
324 } else if (![statusItem isEnabled]) {
325 [statusItem setEnabled:YES];
326 [statusItem setToolTip:_toolTip];
330 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
331 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
332 if ([df boolForKey:@"runScripts"]) {
333 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
334 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
335 NSString *nextScript;
336 ITDebugLog(@"Running AppleScripts for song change.");
337 while ( (nextScript = [scriptsEnum nextObject]) ) {
339 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
340 ITDebugLog(@"Running script: %@", nextScript);
341 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
342 ITDebugLog(@"Error running script %@.", nextScript);
344 [currentScript release];
349 [statusItem setEnabled:NO];
352 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
354 if ([menuController rebuildSubmenus]) {
355 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
356 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
358 [self setLatestSongIdentifier:identifier];
359 //Create the tooltip for the status item
360 if ( [df boolForKey:@"showToolTip"] ) {
361 NSString *artist = [[self currentRemote] currentSongArtist];
362 NSString *title = [[self currentRemote] currentSongTitle];
363 ITDebugLog(@"Creating status item tooltip.");
365 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
369 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
371 [statusItem setToolTip:_toolTip];
373 [statusItem setToolTip:nil];
377 if ([df boolForKey:@"audioscrobblerEnabled"]) {
378 int length = [[self currentRemote] currentSongDuration];
380 _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
381 [_audioscrobblerTimer invalidate];
382 [_audioscrobblerTimer release];
383 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
384 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
387 _audioscrobblerTimer = nil;
390 [self networkError:localException];
393 [statusItem setEnabled:YES];
396 if ([networkController isConnectedToServer]) {
397 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
403 ITDebugLog(@"Menu clicked.");
405 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
407 if ([statusItem isEnabled]) {
408 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
410 [statusItem setEnabled:NO];
412 NSMenu *menu = [[NSMenu alloc] init];
413 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
414 [statusItem setMenu:[menu autorelease]];
417 } else if (![statusItem isEnabled]) {
418 [statusItem setEnabled:YES];
419 [statusItem setToolTip:_toolTip];
423 if ([networkController isConnectedToServer]) {
424 //Used the cached version
429 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
430 [statusItem setMenu:[menuController menu]];
432 [statusItem setMenu:[menuController menuForNoPlayer]];
435 [self networkError:localException];
439 - (void)trackChanged:(NSNotification *)note
441 //If we're running the timer, shut it off since we don't need it!
442 /*if (refreshTimer && [refreshTimer isValid]) {
443 ITDebugLog(@"Invalidating refresh timer.");
444 [refreshTimer invalidate];
445 [refreshTimer release];
449 if (![self songChanged]) {
452 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
453 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
454 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
456 [_lastTrackInfo release];
457 _lastTrackInfo = [[note userInfo] retain];
459 [self setLatestSongIdentifier:identifier];
460 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
461 if ([df boolForKey:@"runScripts"]) {
462 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
463 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
464 NSString *nextScript;
465 ITDebugLog(@"Running AppleScripts for song change.");
466 while ( (nextScript = [scriptsEnum nextObject]) ) {
468 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
469 ITDebugLog(@"Running script: %@", nextScript);
470 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
471 ITDebugLog(@"Error running script %@.", nextScript);
473 [currentScript release];
477 [statusItem setEnabled:NO];
480 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
482 if ([menuController rebuildSubmenus]) {
483 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
484 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
486 [self setLatestSongIdentifier:identifier];
487 //Create the tooltip for the status item
488 if ( [df boolForKey:@"showToolTip"] ) {
489 ITDebugLog(@"Creating status item tooltip.");
490 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
492 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
496 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
498 [statusItem setToolTip:_toolTip];
500 [statusItem setToolTip:nil];
504 if ([df boolForKey:@"audioscrobblerEnabled"]) {
505 int length = [[self currentRemote] currentSongDuration];
507 _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
508 [_audioscrobblerTimer invalidate];
509 [_audioscrobblerTimer release];
510 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
511 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
514 _audioscrobblerTimer = nil;
517 [self networkError:localException];
520 [statusItem setEnabled:YES];
522 if ([networkController isConnectedToServer]) {
523 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
527 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
529 ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
531 if ([df boolForKey:@"audioscrobblerEnabled"]) {
533 int elapsed = [[self currentRemote] currentSongPlayed], length = [[self currentRemote] currentSongDuration], requiredInterval = ((length / 2 < 240) ? length / 2 : 240);
534 if ((abs(elapsed - requiredInterval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
535 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
536 if (title && artist) {
537 ITDebugLog(@"Audioscrobbler: Submitting current track");
538 [[AudioscrobblerController sharedController] submitTrack:title
540 album:[[self currentRemote] currentSongAlbum]
541 length:[[self currentRemote] currentSongDuration]];
543 } else if (requiredInterval - elapsed > 0) {
544 _audioscrobblerInterval = requiredInterval - elapsed;
545 [_audioscrobblerTimer release];
546 ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", _audioscrobblerInterval);
547 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
548 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
551 [self networkError:localException];
565 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
566 ITDebugLog(@"Play/Pause toggled");
567 if (state == ITMTRemotePlayerPlaying) {
568 [[self currentRemote] pause];
569 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
570 [[self currentRemote] pause];
571 [[self currentRemote] play];
573 [[self currentRemote] play];
576 [self networkError:localException];
586 ITDebugLog(@"Going to next song.");
588 [[self currentRemote] goToNextSong];
590 [self networkError:localException];
599 ITDebugLog(@"Going to previous song.");
601 [[self currentRemote] goToPreviousSong];
603 [self networkError:localException];
612 ITDebugLog(@"Fast forwarding.");
614 [[self currentRemote] forward];
616 [self networkError:localException];
625 ITDebugLog(@"Rewinding.");
627 [[self currentRemote] rewind];
629 [self networkError:localException];
636 - (void)selectPlaylistAtIndex:(int)index
638 ITDebugLog(@"Selecting playlist %i", index);
640 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
641 //[[self currentRemote] switchToPlaylistAtIndex:index];
643 [self networkError:localException];
650 - (void)selectSongAtIndex:(int)index
652 ITDebugLog(@"Selecting song %i", index);
654 [[self currentRemote] switchToSongAtIndex:index];
656 [self networkError:localException];
663 - (void)selectSongRating:(int)rating
665 ITDebugLog(@"Selecting song rating %i", rating);
667 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
669 [self networkError:localException];
676 - (void)selectEQPresetAtIndex:(int)index
678 ITDebugLog(@"Selecting EQ preset %i", index);
681 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
683 [[self currentRemote] switchToEQAtIndex:index];
686 [self networkError:localException];
693 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
695 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
697 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
699 [self networkError:localException];
701 ITDebugLog(@"Done making playlist");
706 ITDebugLog(@"Beginning show player.");
707 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
708 ITDebugLog(@"Showing player interface.");
710 [[self currentRemote] showPrimaryInterface];
712 [self networkError:localException];
715 ITDebugLog(@"Launching player.");
718 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
720 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
722 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
723 ITDebugLog(@"Error Launching Player");
726 [self networkError:localException];
729 ITDebugLog(@"Finished show player.");
732 - (void)showPreferences
734 ITDebugLog(@"Show preferences.");
735 [[PreferencesController sharedPrefs] showPrefsWindow:self];
738 - (void)showPreferencesAndClose
740 ITDebugLog(@"Show preferences.");
741 [[PreferencesController sharedPrefs] showPrefsWindow:self];
742 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
743 [[StatusWindow sharedWindow] vanish:self];
744 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
747 - (void)showTestWindow
749 [self showCurrentTrackInfo];
752 - (void)quitMenuTunes
754 ITDebugLog(@"Quitting MenuTunes.");
755 [NSApp terminate:self];
761 - (MenuController *)menuController
763 return menuController;
766 - (void)closePreferences
768 ITDebugLog(@"Preferences closed.");
769 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
774 - (ITMTRemote *)currentRemote
776 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
777 [self networkError:nil];
780 return currentRemote;
791 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
792 ITHotKey *nextHotKey;
793 ITDebugLog(@"Clearing hot keys.");
794 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
795 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
797 ITDebugLog(@"Done clearing hot keys.");
803 ITDebugLog(@"Setting up hot keys.");
805 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
809 if ([df objectForKey:@"PlayPause"] != nil) {
810 ITDebugLog(@"Setting up play pause hot key.");
811 hotKey = [[ITHotKey alloc] init];
812 [hotKey setName:@"PlayPause"];
813 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
814 [hotKey setTarget:self];
815 [hotKey setAction:@selector(playPause)];
816 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
819 if ([df objectForKey:@"NextTrack"] != nil) {
820 ITDebugLog(@"Setting up next track hot key.");
821 hotKey = [[ITHotKey alloc] init];
822 [hotKey setName:@"NextTrack"];
823 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
824 [hotKey setTarget:self];
825 [hotKey setAction:@selector(nextSong)];
826 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
829 if ([df objectForKey:@"PrevTrack"] != nil) {
830 ITDebugLog(@"Setting up previous track hot key.");
831 hotKey = [[ITHotKey alloc] init];
832 [hotKey setName:@"PrevTrack"];
833 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
834 [hotKey setTarget:self];
835 [hotKey setAction:@selector(prevSong)];
836 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
839 if ([df objectForKey:@"FastForward"] != nil) {
840 ITDebugLog(@"Setting up fast forward hot key.");
841 hotKey = [[ITHotKey alloc] init];
842 [hotKey setName:@"FastForward"];
843 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
844 [hotKey setTarget:self];
845 [hotKey setAction:@selector(fastForward)];
846 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
849 if ([df objectForKey:@"Rewind"] != nil) {
850 ITDebugLog(@"Setting up rewind hot key.");
851 hotKey = [[ITHotKey alloc] init];
852 [hotKey setName:@"Rewind"];
853 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
854 [hotKey setTarget:self];
855 [hotKey setAction:@selector(rewind)];
856 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
859 if ([df objectForKey:@"ShowPlayer"] != nil) {
860 ITDebugLog(@"Setting up show player hot key.");
861 hotKey = [[ITHotKey alloc] init];
862 [hotKey setName:@"ShowPlayer"];
863 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
864 [hotKey setTarget:self];
865 [hotKey setAction:@selector(showPlayer)];
866 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
869 if ([df objectForKey:@"TrackInfo"] != nil) {
870 ITDebugLog(@"Setting up track info hot key.");
871 hotKey = [[ITHotKey alloc] init];
872 [hotKey setName:@"TrackInfo"];
873 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
874 [hotKey setTarget:self];
875 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
876 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
879 if ([df objectForKey:@"AlbumArt"] != nil) {
880 ITDebugLog(@"Setting up album art hot key.");
881 hotKey = [[ITHotKey alloc] init];
882 [hotKey setName:@"AlbumArt"];
883 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"AlbumArt"]]];
884 [hotKey setTarget:self];
885 [hotKey setAction:@selector(showCurrentAlbumArtHotKey)];
886 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
889 if ([df objectForKey:@"UpcomingSongs"] != nil) {
890 ITDebugLog(@"Setting up upcoming songs hot key.");
891 hotKey = [[ITHotKey alloc] init];
892 [hotKey setName:@"UpcomingSongs"];
893 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
894 [hotKey setTarget:self];
895 [hotKey setAction:@selector(showUpcomingSongs)];
896 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
899 if ([df objectForKey:@"ToggleLoop"] != nil) {
900 ITDebugLog(@"Setting up toggle loop hot key.");
901 hotKey = [[ITHotKey alloc] init];
902 [hotKey setName:@"ToggleLoop"];
903 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
904 [hotKey setTarget:self];
905 [hotKey setAction:@selector(toggleLoop)];
906 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
909 if ([df objectForKey:@"ToggleShuffle"] != nil) {
910 ITDebugLog(@"Setting up toggle shuffle hot key.");
911 hotKey = [[ITHotKey alloc] init];
912 [hotKey setName:@"ToggleShuffle"];
913 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
914 [hotKey setTarget:self];
915 [hotKey setAction:@selector(toggleShuffle)];
916 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
919 if ([df objectForKey:@"IncrementVolume"] != nil) {
920 ITDebugLog(@"Setting up increment volume hot key.");
921 hotKey = [[ITHotKey alloc] init];
922 [hotKey setName:@"IncrementVolume"];
923 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
924 [hotKey setTarget:self];
925 [hotKey setAction:@selector(incrementVolume)];
926 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
929 if ([df objectForKey:@"DecrementVolume"] != nil) {
930 ITDebugLog(@"Setting up decrement volume hot key.");
931 hotKey = [[ITHotKey alloc] init];
932 [hotKey setName:@"DecrementVolume"];
933 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
934 [hotKey setTarget:self];
935 [hotKey setAction:@selector(decrementVolume)];
936 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
939 if ([df objectForKey:@"IncrementRating"] != nil) {
940 ITDebugLog(@"Setting up increment rating hot key.");
941 hotKey = [[ITHotKey alloc] init];
942 [hotKey setName:@"IncrementRating"];
943 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
944 [hotKey setTarget:self];
945 [hotKey setAction:@selector(incrementRating)];
946 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
949 if ([df objectForKey:@"DecrementRating"] != nil) {
950 ITDebugLog(@"Setting up decrement rating hot key.");
951 hotKey = [[ITHotKey alloc] init];
952 [hotKey setName:@"DecrementRating"];
953 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
954 [hotKey setTarget:self];
955 [hotKey setAction:@selector(decrementRating)];
956 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
959 if ([df objectForKey:@"ToggleShufflability"] != nil) {
960 ITDebugLog(@"Setting up toggle song shufflability hot key.");
961 hotKey = [[ITHotKey alloc] init];
962 [hotKey setName:@"ToggleShufflability"];
963 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
964 [hotKey setTarget:self];
965 [hotKey setAction:@selector(toggleSongShufflable)];
966 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
969 if ([df objectForKey:@"PopupMenu"] != nil) {
970 ITDebugLog(@"Setting up popup menu hot key.");
971 hotKey = [[ITHotKey alloc] init];
972 [hotKey setName:@"PopupMenu"];
973 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
974 [hotKey setTarget:self];
975 [hotKey setAction:@selector(popupMenu)];
976 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
980 for (i = 0; i <= 5; i++) {
981 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
982 if ([df objectForKey:curName] != nil) {
983 ITDebugLog(@"Setting up set rating %i hot key.", i);
984 hotKey = [[ITHotKey alloc] init];
985 [hotKey setName:curName];
986 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
987 [hotKey setTarget:self];
988 [hotKey setAction:@selector(setRating:)];
989 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
992 ITDebugLog(@"Finished setting up hot keys.");
995 - (void)showCurrentTrackInfoHotKey
997 //If we're already visible and the setting says so, vanish instead of displaying again.
998 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
999 ITDebugLog(@"Track window is already visible, hiding track window.");
1000 [self invalidateStatusWindowUpdateTimer];
1001 [[StatusWindow sharedWindow] vanish:nil];
1004 [self showCurrentTrackInfo];
1007 - (void)showCurrentAlbumArtHotKey
1009 //If we're already visible and the setting says so, vanish instead of displaying again.
1010 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowAlbumArtType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1011 ITDebugLog(@"Art window is already visible, hiding track window.");
1012 [[StatusWindow sharedWindow] vanish:nil];
1015 [self showCurrentAlbumArt];
1018 - (void)showCurrentAlbumArt
1022 art = [[self currentRemote] currentSongAlbumArt];
1024 [self networkError:localException];
1028 NSSize oldSize = [art size], newSize;
1029 if (oldSize.width > 300 && oldSize.height > 300) {
1030 if (oldSize.width > oldSize.height) {
1031 newSize = NSMakeSize(300, oldSize.height * (300.0f / oldSize.width));
1033 newSize = NSMakeSize(oldSize.width * (300.0f / oldSize.height), 300);
1039 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1041 [statusWindowController showAlbumArtWindowWithImage:art];
1043 NSString *string = nil;
1045 if ([[self currentRemote] currentSongTitle]) {
1046 string = NSLocalizedString(@"noAlbumArt", @"No art for current song.");
1048 string = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1051 [self networkError:localException];
1053 //Show the no song playing window if there is no album art or no track is playing
1054 [statusWindowController showAlbumArtWindowWithErrorText:string];
1058 - (void)showCurrentTrackInfo
1060 ITMTRemotePlayerSource source = 0;
1061 NSString *title = nil;
1062 NSString *album = nil;
1063 NSString *artist = nil;
1064 NSString *composer = nil;
1065 NSString *time = nil;
1066 NSString *track = nil;
1071 ITDebugLog(@"Showing track info status window.");
1074 source = [[self currentRemote] currentSource];
1075 title = [[self currentRemote] currentSongTitle];
1077 [self networkError:localException];
1081 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1082 NSSize oldSize, newSize;
1084 art = [[self currentRemote] currentSongAlbumArt];
1085 oldSize = [art size];
1086 if (oldSize.width > oldSize.height) {
1087 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1089 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1090 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1092 [self networkError:localException];
1096 if ( [df boolForKey:@"showAlbum"] ) {
1098 album = [[self currentRemote] currentSongAlbum];
1100 [self networkError:localException];
1104 if ( [df boolForKey:@"showArtist"] ) {
1106 artist = [[self currentRemote] currentSongArtist];
1108 [self networkError:localException];
1112 if ( [df boolForKey:@"showComposer"] ) {
1114 composer = [[self currentRemote] currentSongComposer];
1116 [self networkError:localException];
1120 if ( [df boolForKey:@"showTime"] ) {
1122 time = [NSString stringWithFormat:@"%@: %@ / %@",
1123 NSLocalizedString(@"time", @"Time"),
1124 [[self currentRemote] currentSongElapsed],
1125 [[self currentRemote] currentSongLength]];
1127 [self networkError:localException];
1129 _timeUpdateCount = 0;
1130 [self invalidateStatusWindowUpdateTimer];
1131 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1134 if ( [df boolForKey:@"showTrackNumber"] ) {
1139 trackNo = [[self currentRemote] currentSongTrack];
1140 trackCount = [[self currentRemote] currentAlbumTrackCount];
1142 [self networkError:localException];
1145 if ( (trackNo > 0) || (trackCount > 0) ) {
1146 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1147 @"Track", trackNo, @"of", trackCount];
1151 if ( [df boolForKey:@"showTrackRating"] ) {
1152 float currentRating = 0;
1155 currentRating = [[self currentRemote] currentSongRating];
1157 [self networkError:localException];
1160 if (currentRating >= 0.0) {
1161 rating = ( currentRating * 5 );
1165 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1167 playCount = [[self currentRemote] currentSongPlayCount];
1169 [self networkError:localException];
1173 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1175 ITDebugLog(@"Showing current track info status window.");
1176 [statusWindowController showSongInfoWindowWithSource:source
1188 - (void)updateTime:(NSTimer *)timer
1190 StatusWindow *sw = (StatusWindow *)[StatusWindow sharedWindow];
1192 if ([statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [sw visibilityState] != ITWindowHiddenState) {
1193 NSString *time = nil, *length;
1195 length = [[self currentRemote] currentSongLength];
1197 time = [NSString stringWithFormat:@"%@: %@ / %@",
1198 NSLocalizedString(@"time", @"Time"),
1199 [[self currentRemote] currentSongElapsed],
1201 [[StatusWindowController sharedController] updateTime:time];
1204 [self networkError:localException];
1207 [self invalidateStatusWindowUpdateTimer];
1211 - (void)invalidateStatusWindowUpdateTimer
1213 if (_statusWindowUpdateTimer) {
1214 [_statusWindowUpdateTimer invalidate];
1215 _statusWindowUpdateTimer = nil;
1219 - (void)showUpcomingSongs
1223 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1225 [self networkError:localException];
1228 [self invalidateStatusWindowUpdateTimer];
1230 ITDebugLog(@"Showing upcoming songs status window.");
1233 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1234 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1235 int curTrack = [[self currentRemote] currentSongIndex];
1238 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1239 if ([[self currentRemote] songEnabledAtIndex:i]) {
1240 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1242 numSongsInAdvance++;
1246 if ([songList count] == 0) {
1247 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1250 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1252 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1255 [self networkError:localException];
1264 NSMenu *menu = [statusItem menu];
1265 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1270 - (void)incrementVolume
1273 float volume = [[self currentRemote] volume];
1274 float dispVol = volume;
1275 ITDebugLog(@"Incrementing volume.");
1284 ITDebugLog(@"Setting volume to %f", volume);
1285 [[self currentRemote] setVolume:volume];
1287 // Show volume status window
1288 [self invalidateStatusWindowUpdateTimer];
1289 [statusWindowController showVolumeWindowWithLevel:dispVol];
1291 [self networkError:localException];
1295 - (void)decrementVolume
1298 float volume = [[self currentRemote] volume];
1299 float dispVol = volume;
1300 ITDebugLog(@"Decrementing volume.");
1309 ITDebugLog(@"Setting volume to %f", volume);
1310 [[self currentRemote] setVolume:volume];
1312 //Show volume status window
1313 [self invalidateStatusWindowUpdateTimer];
1314 [statusWindowController showVolumeWindowWithLevel:dispVol];
1316 [self networkError:localException];
1320 - (void)incrementRating
1323 float rating = [[self currentRemote] currentSongRating];
1324 ITDebugLog(@"Incrementing rating.");
1326 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1327 ITDebugLog(@"No song playing, rating change aborted.");
1335 ITDebugLog(@"Setting rating to %f", rating);
1336 [[self currentRemote] setCurrentSongRating:rating];
1338 //Show rating status window
1339 [self invalidateStatusWindowUpdateTimer];
1340 [statusWindowController showRatingWindowWithRating:rating];
1342 [self networkError:localException];
1346 - (void)decrementRating
1349 float rating = [[self currentRemote] currentSongRating];
1350 ITDebugLog(@"Decrementing rating.");
1352 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1353 ITDebugLog(@"No song playing, rating change aborted.");
1361 ITDebugLog(@"Setting rating to %f", rating);
1362 [[self currentRemote] setCurrentSongRating:rating];
1364 //Show rating status window
1365 [self invalidateStatusWindowUpdateTimer];
1366 [statusWindowController showRatingWindowWithRating:rating];
1368 [self networkError:localException];
1372 - (void)setRating:(ITHotKey *)sender
1374 if ([self songIsPlaying]) {
1375 int stars = [[sender name] characterAtIndex:9] - 48;
1376 [self selectSongRating:stars * 20];
1377 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1384 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1385 ITDebugLog(@"Toggling repeat mode.");
1386 switch (repeatMode) {
1387 case ITMTRemotePlayerRepeatOff:
1388 repeatMode = ITMTRemotePlayerRepeatAll;
1390 case ITMTRemotePlayerRepeatAll:
1391 repeatMode = ITMTRemotePlayerRepeatOne;
1393 case ITMTRemotePlayerRepeatOne:
1394 repeatMode = ITMTRemotePlayerRepeatOff;
1397 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1398 [[self currentRemote] setRepeatMode:repeatMode];
1400 //Show loop status window
1401 [self invalidateStatusWindowUpdateTimer];
1402 [statusWindowController showRepeatWindowWithMode:repeatMode];
1404 [self networkError:localException];
1408 - (void)toggleShuffle
1411 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1412 ITDebugLog(@"Toggling shuffle mode.");
1413 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1414 //Show shuffle status window
1415 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1416 [self invalidateStatusWindowUpdateTimer];
1417 [statusWindowController showShuffleWindow:newShuffleEnabled];
1419 [self networkError:localException];
1423 - (void)toggleSongShufflable
1425 if ([self songIsPlaying]) {
1427 BOOL flag = ![[self currentRemote] currentSongShufflable];
1428 ITDebugLog(@"Toggling shufflability.");
1429 [[self currentRemote] setCurrentSongShufflable:flag];
1430 //Show song shufflability status window
1431 [self invalidateStatusWindowUpdateTimer];
1432 [statusWindowController showSongShufflabilityWindow:flag];
1434 [self networkError:localException];
1439 /*************************************************************************/
1441 #pragma mark NETWORK HANDLERS
1442 /*************************************************************************/
1444 - (void)setServerStatus:(BOOL)newStatus
1448 [networkController setServerStatus:YES];
1451 [networkController setServerStatus:NO];
1455 - (int)connectToServer
1458 ITDebugLog(@"Attempting to connect to shared remote.");
1459 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1462 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1463 currentRemote = [[[networkController networkObject] remote] retain];
1465 [self setupHotKeys];
1466 //playerRunningState = ITMTRemotePlayerRunning;
1467 playerRunningState = [[self currentRemote] playerRunningState];
1468 if (_needsPolling) {
1470 [refreshTimer invalidate];
1474 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1476 selector:@selector(timerUpdate)
1478 repeats:YES] retain];
1481 ITDebugLog(@"Connection successful.");
1483 } else if (result == 0) {
1484 ITDebugLog(@"Connection failed.");
1485 currentRemote = [remoteArray objectAtIndex:0];
1488 //Do something about the password being invalid
1489 ITDebugLog(@"Connection failed.");
1490 currentRemote = [remoteArray objectAtIndex:0];
1495 - (BOOL)disconnectFromServer
1497 ITDebugLog(@"Disconnecting from shared remote.");
1499 [currentRemote release];
1500 currentRemote = [remoteArray objectAtIndex:0];
1501 [networkController disconnect];
1503 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1505 [self applicationLaunched:nil];
1507 [self applicationTerminated:nil];
1516 - (void)checkForRemoteServer
1518 [self checkForRemoteServerAndConnectImmediately:NO];
1521 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1523 ITDebugLog(@"Checking for remote server.");
1524 if (!_checkingForServer) {
1525 if (!_serverCheckLock) {
1526 _serverCheckLock = [[NSLock alloc] init];
1528 [_serverCheckLock lock];
1529 _checkingForServer = YES;
1530 [_serverCheckLock unlock];
1531 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1535 - (void)runRemoteServerCheck:(id)sender
1537 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1538 ITDebugLog(@"Remote server check running.");
1539 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1540 ITDebugLog(@"Remote server found.");
1541 if ([sender boolValue]) {
1542 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1544 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1547 ITDebugLog(@"Remote server not found.");
1548 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1550 [_serverCheckLock lock];
1551 _checkingForServer = NO;
1552 [_serverCheckLock unlock];
1556 - (void)remoteServerFound:(id)sender
1558 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1559 [self invalidateStatusWindowUpdateTimer];
1560 [[StatusWindowController sharedController] showReconnectQueryWindow];
1564 - (void)remoteServerNotFound:(id)sender
1566 if (![[NetworkController sharedController] isConnectedToServer]) {
1567 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1571 - (void)networkError:(NSException *)exception
1573 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1574 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1575 //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);
1576 [self invalidateStatusWindowUpdateTimer];
1577 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1578 if ([self disconnectFromServer]) {
1579 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1580 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1582 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1589 /*if ([self connectToServer] == 0) {
1590 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1592 [self checkForRemoteServerAndConnectImmediately:YES];
1593 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1594 [[StatusWindow sharedWindow] vanish:self];
1595 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1598 - (void)cancelReconnect
1600 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1601 [[StatusWindow sharedWindow] vanish:self];
1602 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1605 /*************************************************************************/
1607 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1608 /*************************************************************************/
1610 - (void)applicationLaunched:(NSNotification *)note
1613 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1614 ITDebugLog(@"Remote application launched.");
1615 playerRunningState = ITMTRemotePlayerRunning;
1616 [[self currentRemote] begin];
1617 [self setLatestSongIdentifier:@""];
1619 if (_needsPolling) {
1620 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1622 selector:@selector(timerUpdate)
1624 repeats:YES] retain];
1626 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1627 if (![df boolForKey:@"UsePollingOnly"]) {
1628 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1630 [self setupHotKeys];
1633 [self networkError:localException];
1637 - (void)applicationTerminated:(NSNotification *)note
1640 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1641 ITDebugLog(@"Remote application terminated.");
1642 playerRunningState = ITMTRemotePlayerNotRunning;
1643 [[self currentRemote] halt];
1644 [refreshTimer invalidate];
1645 [refreshTimer release];
1647 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1648 [statusItem setEnabled:YES];
1649 [statusItem setToolTip:@"iTunes not running."];
1650 [self clearHotKeys];
1653 if ([df objectForKey:@"ShowPlayer"] != nil) {
1655 ITDebugLog(@"Setting up show player hot key.");
1656 hotKey = [[ITHotKey alloc] init];
1657 [hotKey setName:@"ShowPlayer"];
1658 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1659 [hotKey setTarget:self];
1660 [hotKey setAction:@selector(showPlayer)];
1661 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1665 [self networkError:localException];
1670 /*************************************************************************/
1672 #pragma mark NSApplication DELEGATE METHODS
1673 /*************************************************************************/
1675 - (void)applicationWillTerminate:(NSNotification *)note
1677 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1678 [networkController stopRemoteServerSearch];
1679 [self clearHotKeys];
1680 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1683 - (void)applicationDidBecomeActive:(NSNotification *)note
1685 //This appears to not work in 10.4
1686 if (_open && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1687 [[MainController sharedController] showPreferences];
1691 /*************************************************************************/
1693 #pragma mark DEALLOCATION METHOD
1694 /*************************************************************************/
1698 [self applicationTerminated:nil];
1699 [statusItem release];
1700 [statusWindowController release];
1701 [menuController release];
1702 [networkController release];
1703 [_serverCheckLock release];