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;
68 - (void)invalidateStatusWindowUpdateTimer;
71 static MainController *sharedController;
73 @implementation MainController
75 + (MainController *)sharedController
77 return sharedController;
80 /*************************************************************************/
82 #pragma mark INITIALIZATION/DEALLOCATION METHODS
83 /*************************************************************************/
87 if ( ( self = [super init] ) ) {
88 sharedController = self;
90 _statusWindowUpdateTimer = nil;
92 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
93 [[PreferencesController sharedPrefs] setController:self];
94 statusWindowController = [StatusWindowController sharedController];
95 menuController = [[MenuController alloc] init];
96 df = [[NSUserDefaults standardUserDefaults] retain];
103 - (void)applicationDidFinishLaunching:(NSNotification *)note
105 NSString *iTunesPath = [df stringForKey:@"CustomPlayerPath"];
106 NSDictionary *iTunesInfoPlist;
109 //Turn on debug mode if needed
110 /*if ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)
111 if ((GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0)
112 if ((GetCurrentKeyModifiers() & (shiftKey | rightShiftKey)) != 0)*/
113 if ([df boolForKey:@"ITDebugMode"] || ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)) {
115 [[StatusWindowController sharedController] showDebugModeEnabledWindow];
118 //Check if iTunes 4.7 or later is installed
120 iTunesPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"];
122 iTunesInfoPlist = [[NSBundle bundleWithPath:iTunesPath] infoDictionary];
123 iTunesVersion = [[iTunesInfoPlist objectForKey:@"CFBundleVersion"] floatValue];
124 ITDebugLog(@"iTunes version found: %f.", iTunesVersion);
125 if (iTunesVersion >= 4.7) {
131 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
132 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
134 [[PreferencesController sharedPrefs] registerDefaults];
135 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
138 currentRemote = [self loadRemote];
139 [[self currentRemote] begin];
141 //Turn on network stuff if needed
142 networkController = [[NetworkController alloc] init];
143 if ([df boolForKey:@"enableSharing"]) {
144 [self setServerStatus:YES];
145 } else if ([df boolForKey:@"useSharedPlayer"]) {
146 [self checkForRemoteServerAndConnectImmediately:YES];
149 //Setup for notification of the remote player launching or quitting
150 [[[NSWorkspace sharedWorkspace] notificationCenter]
152 selector:@selector(applicationTerminated:)
153 name:NSWorkspaceDidTerminateApplicationNotification
156 [[[NSWorkspace sharedWorkspace] notificationCenter]
158 selector:@selector(applicationLaunched:)
159 name:NSWorkspaceDidLaunchApplicationNotification
162 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
163 [[PreferencesController sharedPrefs] registerDefaults];
166 if ([df boolForKey:@"ITMTNoStatusItem"]) {
169 [StatusItemHack install];
170 statusItem = [[ITStatusItem alloc]
171 initWithStatusBar:[NSStatusBar systemStatusBar]
172 withLength:NSSquareStatusItemLength];
175 /*bling = [[MTBlingController alloc] init];
177 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
179 selector:@selector(blingTime)
181 repeats:YES] retain];*/
184 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
185 [self applicationLaunched:nil];
187 if ([df boolForKey:@"LaunchPlayerWithMT"])
190 [self applicationTerminated:nil];
193 [self networkError:localException];
196 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
197 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
199 [networkController startRemoteServerSearch];
201 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
203 bling = [[MTBlingController alloc] init];
205 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
207 selector:@selector(blingTime)
209 repeats:YES] retain];
217 - (ITMTRemote *)loadRemote
219 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
220 ITDebugLog(@"Gathering remotes.");
222 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
223 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
224 NSString *bundlePath;
226 while ( (bundlePath = [enumerator nextObject]) ) {
227 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
230 Class remoteClass = [remoteBundle principalClass];
232 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
233 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
234 id remote = [remoteClass remote];
235 ITDebugLog(@"Adding remote at path %@", bundlePath);
236 [remoteArray addObject:remote];
241 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
242 // if ( [remoteArray count] > 1 ) {
243 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
245 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
248 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
249 return [remoteArray objectAtIndex:0];
252 /*************************************************************************/
254 #pragma mark INSTANCE METHODS
255 /*************************************************************************/
257 /*- (void)startTimerInNewThread
259 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
260 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
261 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
263 selector:@selector(timerUpdate)
265 repeats:YES] retain];
267 ITDebugLog(@"Timer started.");
271 - (void)setBlingTime:(NSDate*)date
273 NSMutableDictionary *globalPrefs;
275 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
277 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
278 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
280 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
281 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
283 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
285 [globalPrefs release];
288 - (NSDate*)getBlingTime
291 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
296 NSDate *now = [NSDate date];
297 if (![self blingBling]) {
298 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
299 [self setBlingTime:now];
300 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
301 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
302 [self setBlingTime:[now addTimeInterval:-259200]];
304 NSMutableDictionary *globalPrefs;
306 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
307 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
308 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
310 [globalPrefs release];
314 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
316 [statusItem setEnabled:NO];
317 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
318 if ([refreshTimer isValid]) {
319 [refreshTimer invalidate];
320 [refreshTimer release];
323 [statusWindowController showRegistrationQueryWindow];
327 [statusItem setEnabled:YES];
328 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
329 if (_needsPolling && ![refreshTimer isValid]) {
330 [refreshTimer release];
331 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
333 selector:@selector(timerUpdate)
335 repeats:YES] retain];
339 [self setBlingTime:nil];
350 if ( ! ([bling checkDone] == 2475) ) {
357 - (BOOL)songIsPlaying
359 NSString *identifier = nil;
361 identifier = [[self currentRemote] playerStateUniqueIdentifier];
363 [self networkError:localException];
365 return ( ! ([identifier isEqualToString:@"0-0"]) );
368 - (BOOL)radioIsPlaying
370 ITMTRemotePlayerPlaylistClass class = nil;
372 class = [[self currentRemote] currentPlaylistClass];
374 [self networkError:localException];
376 return (class == ITMTRemotePlayerRadioPlaylist );
381 NSString *identifier = nil;
383 identifier = [[self currentRemote] playerStateUniqueIdentifier];
385 [self networkError:localException];
387 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
390 - (NSString *)latestSongIdentifier
392 return _latestSongIdentifier;
395 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
397 ITDebugLog(@"Setting latest song identifier:");
398 ITDebugLog(@" - Identifier: %@", newIdentifier);
399 [_latestSongIdentifier autorelease];
400 _latestSongIdentifier = [newIdentifier retain];
405 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
406 if (refreshTimer && identifier == nil) {
407 if ([statusItem isEnabled]) {
408 [statusItem setToolTip:@"iTunes not responding."];
410 [statusItem setEnabled:NO];
412 } else if (![statusItem isEnabled]) {
413 [statusItem setEnabled:YES];
414 [statusItem setToolTip:_toolTip];
418 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
419 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
420 if ([df boolForKey:@"runScripts"]) {
421 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
422 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
423 NSString *nextScript;
424 ITDebugLog(@"Running AppleScripts for song change.");
425 while ( (nextScript = [scriptsEnum nextObject]) ) {
427 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
428 ITDebugLog(@"Running script: %@", nextScript);
429 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
430 ITDebugLog(@"Error running script %@.", nextScript);
432 [currentScript release];
437 [statusItem setEnabled:NO];
440 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
442 if ([menuController rebuildSubmenus]) {
443 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
444 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
446 [self setLatestSongIdentifier:identifier];
447 //Create the tooltip for the status item
448 if ( [df boolForKey:@"showToolTip"] ) {
449 NSString *artist = [[self currentRemote] currentSongArtist];
450 NSString *title = [[self currentRemote] currentSongTitle];
451 ITDebugLog(@"Creating status item tooltip.");
453 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
457 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
459 [statusItem setToolTip:_toolTip];
461 [statusItem setToolTip:nil];
465 [self networkError:localException];
468 [statusItem setEnabled:YES];
471 if ([networkController isConnectedToServer]) {
472 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
478 ITDebugLog(@"Menu clicked.");
480 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
482 if ([statusItem isEnabled]) {
483 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
485 [statusItem setEnabled:NO];
487 NSMenu *menu = [[NSMenu alloc] init];
488 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
489 [statusItem setMenu:[menu autorelease]];
492 } else if (![statusItem isEnabled]) {
493 [statusItem setEnabled:YES];
494 [statusItem setToolTip:_toolTip];
498 if ([networkController isConnectedToServer]) {
499 //Used the cached version
504 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
505 [statusItem setMenu:[menuController menu]];
507 [statusItem setMenu:[menuController menuForNoPlayer]];
510 [self networkError:localException];
514 - (void)trackChanged:(NSNotification *)note
516 //If we're running the timer, shut it off since we don't need it!
517 /*if (refreshTimer && [refreshTimer isValid]) {
518 ITDebugLog(@"Invalidating refresh timer.");
519 [refreshTimer invalidate];
520 [refreshTimer release];
524 if (![self songChanged]) {
527 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
528 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
529 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
531 [_lastTrackInfo release];
532 _lastTrackInfo = [[note userInfo] retain];
534 [self setLatestSongIdentifier:identifier];
535 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
536 if ([df boolForKey:@"runScripts"]) {
537 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
538 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
539 NSString *nextScript;
540 ITDebugLog(@"Running AppleScripts for song change.");
541 while ( (nextScript = [scriptsEnum nextObject]) ) {
543 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
544 ITDebugLog(@"Running script: %@", nextScript);
545 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
546 ITDebugLog(@"Error running script %@.", nextScript);
548 [currentScript release];
552 [statusItem setEnabled:NO];
555 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
557 if ([menuController rebuildSubmenus]) {
558 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
559 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
561 [self setLatestSongIdentifier:identifier];
562 //Create the tooltip for the status item
563 if ( [df boolForKey:@"showToolTip"] ) {
564 ITDebugLog(@"Creating status item tooltip.");
565 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
567 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
571 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
573 [statusItem setToolTip:_toolTip];
575 [statusItem setToolTip:nil];
579 [self networkError:localException];
582 [statusItem setEnabled:YES];
584 if ([networkController isConnectedToServer]) {
585 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
598 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
599 ITDebugLog(@"Play/Pause toggled");
600 if (state == ITMTRemotePlayerPlaying) {
601 [[self currentRemote] pause];
602 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
603 [[self currentRemote] pause];
604 [[self currentRemote] play];
606 [[self currentRemote] play];
609 [self networkError:localException];
619 ITDebugLog(@"Going to next song.");
621 [[self currentRemote] goToNextSong];
623 [self networkError:localException];
632 ITDebugLog(@"Going to previous song.");
634 [[self currentRemote] goToPreviousSong];
636 [self networkError:localException];
645 ITDebugLog(@"Fast forwarding.");
647 [[self currentRemote] forward];
649 [self networkError:localException];
658 ITDebugLog(@"Rewinding.");
660 [[self currentRemote] rewind];
662 [self networkError:localException];
669 - (void)selectPlaylistAtIndex:(int)index
671 ITDebugLog(@"Selecting playlist %i", index);
673 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
674 //[[self currentRemote] switchToPlaylistAtIndex:index];
676 [self networkError:localException];
683 - (void)selectSongAtIndex:(int)index
685 ITDebugLog(@"Selecting song %i", index);
687 [[self currentRemote] switchToSongAtIndex:index];
689 [self networkError:localException];
696 - (void)selectSongRating:(int)rating
698 ITDebugLog(@"Selecting song rating %i", rating);
700 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
702 [self networkError:localException];
709 - (void)selectEQPresetAtIndex:(int)index
711 ITDebugLog(@"Selecting EQ preset %i", index);
714 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
716 [[self currentRemote] switchToEQAtIndex:index];
719 [self networkError:localException];
726 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
728 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
730 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
732 [self networkError:localException];
734 ITDebugLog(@"Done making playlist");
739 ITDebugLog(@"Beginning show player.");
740 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
741 ITDebugLog(@"Showing player interface.");
743 [[self currentRemote] showPrimaryInterface];
745 [self networkError:localException];
748 ITDebugLog(@"Launching player.");
751 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
753 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
755 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
756 ITDebugLog(@"Error Launching Player");
759 [self networkError:localException];
762 ITDebugLog(@"Finished show player.");
765 - (void)showPreferences
767 ITDebugLog(@"Show preferences.");
768 [[PreferencesController sharedPrefs] showPrefsWindow:self];
771 - (void)showPreferencesAndClose
773 ITDebugLog(@"Show preferences.");
774 [[PreferencesController sharedPrefs] showPrefsWindow:self];
775 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
776 [[StatusWindow sharedWindow] vanish:self];
777 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
780 - (void)showTestWindow
782 [self showCurrentTrackInfo];
785 - (void)quitMenuTunes
787 ITDebugLog(@"Quitting MenuTunes.");
788 [NSApp terminate:self];
794 - (MenuController *)menuController
796 return menuController;
799 - (void)closePreferences
801 ITDebugLog(@"Preferences closed.");
802 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
807 - (ITMTRemote *)currentRemote
809 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
810 [self networkError:nil];
813 return currentRemote;
824 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
825 ITHotKey *nextHotKey;
826 ITDebugLog(@"Clearing hot keys.");
827 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
828 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
830 ITDebugLog(@"Done clearing hot keys.");
836 ITDebugLog(@"Setting up hot keys.");
838 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
842 if ([df objectForKey:@"PlayPause"] != nil) {
843 ITDebugLog(@"Setting up play pause hot key.");
844 hotKey = [[ITHotKey alloc] init];
845 [hotKey setName:@"PlayPause"];
846 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
847 [hotKey setTarget:self];
848 [hotKey setAction:@selector(playPause)];
849 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
852 if ([df objectForKey:@"NextTrack"] != nil) {
853 ITDebugLog(@"Setting up next track hot key.");
854 hotKey = [[ITHotKey alloc] init];
855 [hotKey setName:@"NextTrack"];
856 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
857 [hotKey setTarget:self];
858 [hotKey setAction:@selector(nextSong)];
859 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
862 if ([df objectForKey:@"PrevTrack"] != nil) {
863 ITDebugLog(@"Setting up previous track hot key.");
864 hotKey = [[ITHotKey alloc] init];
865 [hotKey setName:@"PrevTrack"];
866 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
867 [hotKey setTarget:self];
868 [hotKey setAction:@selector(prevSong)];
869 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
872 if ([df objectForKey:@"FastForward"] != nil) {
873 ITDebugLog(@"Setting up fast forward hot key.");
874 hotKey = [[ITHotKey alloc] init];
875 [hotKey setName:@"FastForward"];
876 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
877 [hotKey setTarget:self];
878 [hotKey setAction:@selector(fastForward)];
879 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
882 if ([df objectForKey:@"Rewind"] != nil) {
883 ITDebugLog(@"Setting up rewind hot key.");
884 hotKey = [[ITHotKey alloc] init];
885 [hotKey setName:@"Rewind"];
886 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
887 [hotKey setTarget:self];
888 [hotKey setAction:@selector(rewind)];
889 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
892 if ([df objectForKey:@"ShowPlayer"] != nil) {
893 ITDebugLog(@"Setting up show player hot key.");
894 hotKey = [[ITHotKey alloc] init];
895 [hotKey setName:@"ShowPlayer"];
896 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
897 [hotKey setTarget:self];
898 [hotKey setAction:@selector(showPlayer)];
899 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
902 if ([df objectForKey:@"TrackInfo"] != nil) {
903 ITDebugLog(@"Setting up track info hot key.");
904 hotKey = [[ITHotKey alloc] init];
905 [hotKey setName:@"TrackInfo"];
906 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
907 [hotKey setTarget:self];
908 [hotKey setAction:@selector(showCurrentTrackInfo)];
909 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
912 if ([df objectForKey:@"UpcomingSongs"] != nil) {
913 ITDebugLog(@"Setting up upcoming songs hot key.");
914 hotKey = [[ITHotKey alloc] init];
915 [hotKey setName:@"UpcomingSongs"];
916 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
917 [hotKey setTarget:self];
918 [hotKey setAction:@selector(showUpcomingSongs)];
919 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
922 if ([df objectForKey:@"ToggleLoop"] != nil) {
923 ITDebugLog(@"Setting up toggle loop hot key.");
924 hotKey = [[ITHotKey alloc] init];
925 [hotKey setName:@"ToggleLoop"];
926 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
927 [hotKey setTarget:self];
928 [hotKey setAction:@selector(toggleLoop)];
929 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
932 if ([df objectForKey:@"ToggleShuffle"] != nil) {
933 ITDebugLog(@"Setting up toggle shuffle hot key.");
934 hotKey = [[ITHotKey alloc] init];
935 [hotKey setName:@"ToggleShuffle"];
936 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
937 [hotKey setTarget:self];
938 [hotKey setAction:@selector(toggleShuffle)];
939 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
942 if ([df objectForKey:@"IncrementVolume"] != nil) {
943 ITDebugLog(@"Setting up increment volume hot key.");
944 hotKey = [[ITHotKey alloc] init];
945 [hotKey setName:@"IncrementVolume"];
946 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
947 [hotKey setTarget:self];
948 [hotKey setAction:@selector(incrementVolume)];
949 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
952 if ([df objectForKey:@"DecrementVolume"] != nil) {
953 ITDebugLog(@"Setting up decrement volume hot key.");
954 hotKey = [[ITHotKey alloc] init];
955 [hotKey setName:@"DecrementVolume"];
956 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
957 [hotKey setTarget:self];
958 [hotKey setAction:@selector(decrementVolume)];
959 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
962 if ([df objectForKey:@"IncrementRating"] != nil) {
963 ITDebugLog(@"Setting up increment rating hot key.");
964 hotKey = [[ITHotKey alloc] init];
965 [hotKey setName:@"IncrementRating"];
966 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
967 [hotKey setTarget:self];
968 [hotKey setAction:@selector(incrementRating)];
969 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
972 if ([df objectForKey:@"DecrementRating"] != nil) {
973 ITDebugLog(@"Setting up decrement rating hot key.");
974 hotKey = [[ITHotKey alloc] init];
975 [hotKey setName:@"DecrementRating"];
976 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
977 [hotKey setTarget:self];
978 [hotKey setAction:@selector(decrementRating)];
979 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
982 if ([df objectForKey:@"ToggleShufflability"] != nil) {
983 ITDebugLog(@"Setting up toggle song shufflability hot key.");
984 hotKey = [[ITHotKey alloc] init];
985 [hotKey setName:@"ToggleShufflability"];
986 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
987 [hotKey setTarget:self];
988 [hotKey setAction:@selector(toggleSongShufflable)];
989 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
992 if ([df objectForKey:@"PopupMenu"] != nil) {
993 ITDebugLog(@"Setting up popup menu hot key.");
994 hotKey = [[ITHotKey alloc] init];
995 [hotKey setName:@"PopupMenu"];
996 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
997 [hotKey setTarget:self];
998 [hotKey setAction:@selector(popupMenu)];
999 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1003 for (i = 0; i <= 5; i++) {
1004 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1005 if ([df objectForKey:curName] != nil) {
1006 ITDebugLog(@"Setting up set rating %i hot key.", i);
1007 hotKey = [[ITHotKey alloc] init];
1008 [hotKey setName:curName];
1009 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1010 [hotKey setTarget:self];
1011 [hotKey setAction:@selector(setRating:)];
1012 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1015 ITDebugLog(@"Finished setting up hot keys.");
1018 - (void)showCurrentTrackInfo
1020 ITMTRemotePlayerSource source = 0;
1021 NSString *title = nil;
1022 NSString *album = nil;
1023 NSString *artist = nil;
1024 NSString *composer = nil;
1025 NSString *time = nil;
1026 NSString *track = nil;
1031 ITDebugLog(@"Showing track info status window.");
1034 source = [[self currentRemote] currentSource];
1035 title = [[self currentRemote] currentSongTitle];
1037 [self networkError:localException];
1041 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1042 NSSize oldSize, newSize;
1044 art = [[self currentRemote] currentSongAlbumArt];
1045 oldSize = [art size];
1046 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1047 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1048 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1050 [self networkError:localException];
1054 if ( [df boolForKey:@"showAlbum"] ) {
1056 album = [[self currentRemote] currentSongAlbum];
1058 [self networkError:localException];
1062 if ( [df boolForKey:@"showArtist"] ) {
1064 artist = [[self currentRemote] currentSongArtist];
1066 [self networkError:localException];
1070 if ( [df boolForKey:@"showComposer"] ) {
1072 composer = [[self currentRemote] currentSongComposer];
1074 [self networkError:localException];
1078 if ( [df boolForKey:@"showTime"] ) {
1080 time = [NSString stringWithFormat:@"%@: %@ / %@",
1081 NSLocalizedString(@"time", @"Time"),
1082 [[self currentRemote] currentSongElapsed],
1083 [[self currentRemote] currentSongLength]];
1085 [self networkError:localException];
1087 _timeUpdateCount = 0;
1088 [self invalidateStatusWindowUpdateTimer];
1089 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1092 if ( [df boolForKey:@"showTrackNumber"] ) {
1097 trackNo = [[self currentRemote] currentSongTrack];
1098 trackCount = [[self currentRemote] currentAlbumTrackCount];
1100 [self networkError:localException];
1103 if ( (trackNo > 0) || (trackCount > 0) ) {
1104 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1105 @"Track", trackNo, @"of", trackCount];
1109 if ( [df boolForKey:@"showTrackRating"] ) {
1110 float currentRating = 0;
1113 currentRating = [[self currentRemote] currentSongRating];
1115 [self networkError:localException];
1118 if (currentRating >= 0.0) {
1119 rating = ( currentRating * 5 );
1123 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1125 playCount = [[self currentRemote] currentSongPlayCount];
1127 [self networkError:localException];
1131 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1133 ITDebugLog(@"Showing current track info status window.");
1134 [statusWindowController showSongInfoWindowWithSource:source
1146 - (void)updateTime:(NSTimer *)timer
1148 StatusWindow *sw = [StatusWindow sharedWindow];
1150 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1151 NSString *time = nil, *length;
1153 length = [[self currentRemote] currentSongLength];
1155 time = [NSString stringWithFormat:@"%@: %@ / %@",
1156 NSLocalizedString(@"time", @"Time"),
1157 [[self currentRemote] currentSongElapsed],
1159 [[StatusWindowController sharedController] updateTime:time];
1162 [self networkError:localException];
1165 [self invalidateStatusWindowUpdateTimer];
1169 - (void)invalidateStatusWindowUpdateTimer
1171 if (_statusWindowUpdateTimer) {
1172 [_statusWindowUpdateTimer invalidate];
1173 _statusWindowUpdateTimer = nil;
1177 - (void)showUpcomingSongs
1181 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1183 [self networkError:localException];
1186 [self invalidateStatusWindowUpdateTimer];
1188 ITDebugLog(@"Showing upcoming songs status window.");
1191 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1192 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1193 int curTrack = [[self currentRemote] currentSongIndex];
1196 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1197 if ([[self currentRemote] songEnabledAtIndex:i]) {
1198 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1200 numSongsInAdvance++;
1204 if ([songList count] == 0) {
1205 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1208 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1210 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1213 [self networkError:localException];
1222 NSMenu *menu = [statusItem menu];
1223 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1228 - (void)incrementVolume
1231 float volume = [[self currentRemote] volume];
1232 float dispVol = volume;
1233 ITDebugLog(@"Incrementing volume.");
1242 ITDebugLog(@"Setting volume to %f", volume);
1243 [[self currentRemote] setVolume:volume];
1245 // Show volume status window
1246 [self invalidateStatusWindowUpdateTimer];
1247 [statusWindowController showVolumeWindowWithLevel:dispVol];
1249 [self networkError:localException];
1253 - (void)decrementVolume
1256 float volume = [[self currentRemote] volume];
1257 float dispVol = volume;
1258 ITDebugLog(@"Decrementing volume.");
1267 ITDebugLog(@"Setting volume to %f", volume);
1268 [[self currentRemote] setVolume:volume];
1270 //Show volume status window
1271 [self invalidateStatusWindowUpdateTimer];
1272 [statusWindowController showVolumeWindowWithLevel:dispVol];
1274 [self networkError:localException];
1278 - (void)incrementRating
1281 float rating = [[self currentRemote] currentSongRating];
1282 ITDebugLog(@"Incrementing rating.");
1284 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1285 ITDebugLog(@"No song playing, rating change aborted.");
1293 ITDebugLog(@"Setting rating to %f", rating);
1294 [[self currentRemote] setCurrentSongRating:rating];
1296 //Show rating status window
1297 [self invalidateStatusWindowUpdateTimer];
1298 [statusWindowController showRatingWindowWithRating:rating];
1300 [self networkError:localException];
1304 - (void)decrementRating
1307 float rating = [[self currentRemote] currentSongRating];
1308 ITDebugLog(@"Decrementing rating.");
1310 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1311 ITDebugLog(@"No song playing, rating change aborted.");
1319 ITDebugLog(@"Setting rating to %f", rating);
1320 [[self currentRemote] setCurrentSongRating:rating];
1322 //Show rating status window
1323 [self invalidateStatusWindowUpdateTimer];
1324 [statusWindowController showRatingWindowWithRating:rating];
1326 [self networkError:localException];
1330 - (void)setRating:(ITHotKey *)sender
1332 int stars = [[sender name] characterAtIndex:9] - 48;
1333 [self selectSongRating:stars * 20];
1334 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1340 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1341 ITDebugLog(@"Toggling repeat mode.");
1342 switch (repeatMode) {
1343 case ITMTRemotePlayerRepeatOff:
1344 repeatMode = ITMTRemotePlayerRepeatAll;
1346 case ITMTRemotePlayerRepeatAll:
1347 repeatMode = ITMTRemotePlayerRepeatOne;
1349 case ITMTRemotePlayerRepeatOne:
1350 repeatMode = ITMTRemotePlayerRepeatOff;
1353 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1354 [[self currentRemote] setRepeatMode:repeatMode];
1356 //Show loop status window
1357 [self invalidateStatusWindowUpdateTimer];
1358 [statusWindowController showRepeatWindowWithMode:repeatMode];
1360 [self networkError:localException];
1364 - (void)toggleShuffle
1367 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1368 ITDebugLog(@"Toggling shuffle mode.");
1369 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1370 //Show shuffle status window
1371 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1372 [self invalidateStatusWindowUpdateTimer];
1373 [statusWindowController showShuffleWindow:newShuffleEnabled];
1375 [self networkError:localException];
1379 - (void)toggleSongShufflable
1381 if ([self songIsPlaying]) {
1383 BOOL flag = ![[self currentRemote] currentSongShufflable];
1384 ITDebugLog(@"Toggling shufflability.");
1385 [[self currentRemote] setCurrentSongShufflable:flag];
1386 //Show song shufflability status window
1387 [self invalidateStatusWindowUpdateTimer];
1388 [statusWindowController showSongShufflabilityWindow:flag];
1390 [self networkError:localException];
1395 - (void)registerNowOK
1397 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1398 [[StatusWindow sharedWindow] vanish:self];
1399 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1404 - (void)registerNowCancel
1406 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1407 [[StatusWindow sharedWindow] vanish:self];
1408 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1410 [NSApp terminate:self];
1413 /*************************************************************************/
1415 #pragma mark NETWORK HANDLERS
1416 /*************************************************************************/
1418 - (void)setServerStatus:(BOOL)newStatus
1422 [networkController setServerStatus:YES];
1425 [networkController setServerStatus:NO];
1429 - (int)connectToServer
1432 ITDebugLog(@"Attempting to connect to shared remote.");
1433 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1436 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1437 currentRemote = [[[networkController networkObject] remote] retain];
1439 [self setupHotKeys];
1440 //playerRunningState = ITMTRemotePlayerRunning;
1441 playerRunningState = [[self currentRemote] playerRunningState];
1442 if (_needsPolling) {
1444 [refreshTimer invalidate];
1446 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1448 selector:@selector(timerUpdate)
1450 repeats:YES] retain];
1453 ITDebugLog(@"Connection successful.");
1455 } else if (result == 0) {
1456 ITDebugLog(@"Connection failed.");
1457 currentRemote = [remoteArray objectAtIndex:0];
1460 //Do something about the password being invalid
1461 ITDebugLog(@"Connection failed.");
1462 currentRemote = [remoteArray objectAtIndex:0];
1467 - (BOOL)disconnectFromServer
1469 ITDebugLog(@"Disconnecting from shared remote.");
1471 [currentRemote release];
1472 currentRemote = [remoteArray objectAtIndex:0];
1473 [networkController disconnect];
1475 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1476 [self applicationLaunched:nil];
1478 [self applicationTerminated:nil];
1486 - (void)checkForRemoteServer
1488 [self checkForRemoteServerAndConnectImmediately:NO];
1491 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1493 ITDebugLog(@"Checking for remote server.");
1494 if (!_checkingForServer) {
1495 if (!_serverCheckLock) {
1496 _serverCheckLock = [[NSLock alloc] init];
1498 [_serverCheckLock lock];
1499 _checkingForServer = YES;
1500 [_serverCheckLock unlock];
1501 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1505 - (void)runRemoteServerCheck:(id)sender
1507 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1508 ITDebugLog(@"Remote server check running.");
1509 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1510 ITDebugLog(@"Remote server found.");
1511 if ([sender boolValue]) {
1512 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1514 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1517 ITDebugLog(@"Remote server not found.");
1518 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1520 [_serverCheckLock lock];
1521 _checkingForServer = NO;
1522 [_serverCheckLock unlock];
1526 - (void)remoteServerFound:(id)sender
1528 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1529 [self invalidateStatusWindowUpdateTimer];
1530 [[StatusWindowController sharedController] showReconnectQueryWindow];
1534 - (void)remoteServerNotFound:(id)sender
1536 if (![[NetworkController sharedController] isConnectedToServer]) {
1537 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1541 - (void)networkError:(NSException *)exception
1543 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1544 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1545 //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);
1546 [self invalidateStatusWindowUpdateTimer];
1547 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1548 if ([self disconnectFromServer]) {
1549 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1550 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1552 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1559 /*if ([self connectToServer] == 0) {
1560 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1562 [self checkForRemoteServerAndConnectImmediately:YES];
1563 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1564 [[StatusWindow sharedWindow] vanish:self];
1565 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1568 - (void)cancelReconnect
1570 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1571 [[StatusWindow sharedWindow] vanish:self];
1572 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1575 /*************************************************************************/
1577 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1578 /*************************************************************************/
1580 - (void)applicationLaunched:(NSNotification *)note
1583 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1584 ITDebugLog(@"Remote application launched.");
1585 playerRunningState = ITMTRemotePlayerRunning;
1586 [[self currentRemote] begin];
1587 [self setLatestSongIdentifier:@""];
1589 if (_needsPolling) {
1590 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1592 selector:@selector(timerUpdate)
1594 repeats:YES] retain];
1596 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1597 if (![df boolForKey:@"UsePollingOnly"]) {
1598 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1600 [self setupHotKeys];
1603 [self networkError:localException];
1607 - (void)applicationTerminated:(NSNotification *)note
1610 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1611 ITDebugLog(@"Remote application terminated.");
1612 playerRunningState = ITMTRemotePlayerNotRunning;
1613 [[self currentRemote] halt];
1614 [refreshTimer invalidate];
1615 [refreshTimer release];
1617 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1618 [statusItem setEnabled:YES];
1619 [statusItem setToolTip:@"iTunes not running."];
1620 [self clearHotKeys];
1623 if ([df objectForKey:@"ShowPlayer"] != nil) {
1625 ITDebugLog(@"Setting up show player hot key.");
1626 hotKey = [[ITHotKey alloc] init];
1627 [hotKey setName:@"ShowPlayer"];
1628 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1629 [hotKey setTarget:self];
1630 [hotKey setAction:@selector(showPlayer)];
1631 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1635 [self networkError:localException];
1640 /*************************************************************************/
1642 #pragma mark NSApplication DELEGATE METHODS
1643 /*************************************************************************/
1645 - (void)applicationWillTerminate:(NSNotification *)note
1647 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1648 [networkController stopRemoteServerSearch];
1649 [self clearHotKeys];
1650 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1653 - (void)applicationDidBecomeActive:(NSNotification *)note
1655 //This appears to not work in 10.4
1656 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1657 [[MainController sharedController] showPreferences];
1661 /*************************************************************************/
1663 #pragma mark DEALLOCATION METHOD
1664 /*************************************************************************/
1668 [self applicationTerminated:nil];
1670 [statusItem release];
1671 [statusWindowController release];
1672 [menuController release];
1673 [networkController release];
1674 [_serverCheckLock release];