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];
105 - (void)applicationDidFinishLaunching:(NSNotification *)note
107 NSString *iTunesPath = [df stringForKey:@"CustomPlayerPath"];
108 NSDictionary *iTunesInfoPlist;
111 //Turn on debug mode if needed
112 /*if ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)
113 if ((GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0)
114 if ((GetCurrentKeyModifiers() & (shiftKey | rightShiftKey)) != 0)*/
115 if ([df boolForKey:@"ITDebugMode"] || ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)) {
117 [[StatusWindowController sharedController] showDebugModeEnabledWindow];
120 //Check if iTunes 4.7 or later is installed
122 iTunesPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"];
124 iTunesInfoPlist = [[NSBundle bundleWithPath:iTunesPath] infoDictionary];
125 iTunesVersion = [[iTunesInfoPlist objectForKey:@"CFBundleVersion"] floatValue];
126 ITDebugLog(@"iTunes version found: %f.", iTunesVersion);
127 if (iTunesVersion >= 4.7) {
133 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
134 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
136 [[PreferencesController sharedPrefs] registerDefaults];
137 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
140 currentRemote = [self loadRemote];
141 [[self currentRemote] begin];
143 //Turn on network stuff if needed
144 networkController = [[NetworkController alloc] init];
145 if ([df boolForKey:@"enableSharing"]) {
146 [self setServerStatus:YES];
147 } else if ([df boolForKey:@"useSharedPlayer"]) {
148 [self checkForRemoteServerAndConnectImmediately:YES];
151 //Setup for notification of the remote player launching or quitting
152 [[[NSWorkspace sharedWorkspace] notificationCenter]
154 selector:@selector(applicationTerminated:)
155 name:NSWorkspaceDidTerminateApplicationNotification
158 [[[NSWorkspace sharedWorkspace] notificationCenter]
160 selector:@selector(applicationLaunched:)
161 name:NSWorkspaceDidLaunchApplicationNotification
164 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
165 [[PreferencesController sharedPrefs] registerDefaults];
168 if ([df boolForKey:@"ITMTNoStatusItem"]) {
171 [StatusItemHack install];
172 statusItem = [[ITStatusItem alloc]
173 initWithStatusBar:[NSStatusBar systemStatusBar]
174 withLength:NSSquareStatusItemLength];
177 /*bling = [[MTBlingController alloc] init];
179 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
181 selector:@selector(blingTime)
183 repeats:YES] retain];*/
186 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
187 [self applicationLaunched:nil];
189 if ([df boolForKey:@"LaunchPlayerWithMT"])
192 [self applicationTerminated:nil];
195 [self networkError:localException];
198 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
199 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
201 [networkController startRemoteServerSearch];
203 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
205 bling = [[MTBlingController alloc] init];
207 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
209 selector:@selector(blingTime)
211 repeats:YES] retain];
219 - (ITMTRemote *)loadRemote
221 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
222 ITDebugLog(@"Gathering remotes.");
224 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
225 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
226 NSString *bundlePath;
228 while ( (bundlePath = [enumerator nextObject]) ) {
229 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
232 Class remoteClass = [remoteBundle principalClass];
234 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
235 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
236 id remote = [remoteClass remote];
237 ITDebugLog(@"Adding remote at path %@", bundlePath);
238 [remoteArray addObject:remote];
243 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
244 // if ( [remoteArray count] > 1 ) {
245 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
247 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
250 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
251 return [remoteArray objectAtIndex:0];
254 /*************************************************************************/
256 #pragma mark INSTANCE METHODS
257 /*************************************************************************/
259 /*- (void)startTimerInNewThread
261 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
262 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
263 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
265 selector:@selector(timerUpdate)
267 repeats:YES] retain];
269 ITDebugLog(@"Timer started.");
273 - (void)setBlingTime:(NSDate*)date
275 NSMutableDictionary *globalPrefs;
277 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
279 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
280 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
282 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
283 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
285 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
287 [globalPrefs release];
290 - (NSDate*)getBlingTime
293 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
298 NSDate *now = [NSDate date];
299 if (![self blingBling]) {
300 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
301 [self setBlingTime:now];
302 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
303 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
304 [self setBlingTime:[now addTimeInterval:-259200]];
306 NSMutableDictionary *globalPrefs;
308 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
309 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
310 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
312 [globalPrefs release];
316 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
318 [statusItem setEnabled:NO];
319 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
320 if ([refreshTimer isValid]) {
321 [refreshTimer invalidate];
322 [refreshTimer release];
325 [statusWindowController showRegistrationQueryWindow];
329 [statusItem setEnabled:YES];
330 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
331 if (_needsPolling && ![refreshTimer isValid]) {
332 [refreshTimer release];
333 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
335 selector:@selector(timerUpdate)
337 repeats:YES] retain];
341 [self setBlingTime:nil];
352 if ( ! ([bling checkDone] == 2475) ) {
359 - (BOOL)songIsPlaying
361 NSString *identifier = nil;
363 identifier = [[self currentRemote] playerStateUniqueIdentifier];
365 [self networkError:localException];
367 return ( ! ([identifier isEqualToString:@"0-0"]) );
370 - (BOOL)radioIsPlaying
372 ITMTRemotePlayerPlaylistClass class = nil;
374 class = [[self currentRemote] currentPlaylistClass];
376 [self networkError:localException];
378 return (class == ITMTRemotePlayerRadioPlaylist );
383 NSString *identifier = nil;
385 identifier = [[self currentRemote] playerStateUniqueIdentifier];
387 [self networkError:localException];
389 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
392 - (NSString *)latestSongIdentifier
394 return _latestSongIdentifier;
397 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
399 ITDebugLog(@"Setting latest song identifier:");
400 ITDebugLog(@" - Identifier: %@", newIdentifier);
401 [_latestSongIdentifier autorelease];
402 _latestSongIdentifier = [newIdentifier retain];
407 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
408 if (refreshTimer && identifier == nil) {
409 if ([statusItem isEnabled]) {
410 [statusItem setToolTip:@"iTunes not responding."];
412 [statusItem setEnabled:NO];
414 } else if (![statusItem isEnabled]) {
415 [statusItem setEnabled:YES];
416 [statusItem setToolTip:_toolTip];
420 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
421 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
422 if ([df boolForKey:@"runScripts"]) {
423 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
424 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
425 NSString *nextScript;
426 ITDebugLog(@"Running AppleScripts for song change.");
427 while ( (nextScript = [scriptsEnum nextObject]) ) {
429 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
430 ITDebugLog(@"Running script: %@", nextScript);
431 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
432 ITDebugLog(@"Error running script %@.", nextScript);
434 [currentScript release];
439 [statusItem setEnabled:NO];
442 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
444 if ([menuController rebuildSubmenus]) {
445 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
446 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
448 [self setLatestSongIdentifier:identifier];
449 //Create the tooltip for the status item
450 if ( [df boolForKey:@"showToolTip"] ) {
451 NSString *artist = [[self currentRemote] currentSongArtist];
452 NSString *title = [[self currentRemote] currentSongTitle];
453 ITDebugLog(@"Creating status item tooltip.");
455 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
459 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
461 [statusItem setToolTip:_toolTip];
463 [statusItem setToolTip:nil];
467 if ([df boolForKey:@"audioscrobblerEnabled"]) {
468 int length = [[self currentRemote] currentSongDuration];
469 if (_audioscrobblerTimer) {
470 [_audioscrobblerTimer invalidate];
473 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
476 _audioscrobblerTimer = nil;
479 [self networkError:localException];
482 [statusItem setEnabled:YES];
485 if ([networkController isConnectedToServer]) {
486 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
492 ITDebugLog(@"Menu clicked.");
494 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
496 if ([statusItem isEnabled]) {
497 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
499 [statusItem setEnabled:NO];
501 NSMenu *menu = [[NSMenu alloc] init];
502 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
503 [statusItem setMenu:[menu autorelease]];
506 } else if (![statusItem isEnabled]) {
507 [statusItem setEnabled:YES];
508 [statusItem setToolTip:_toolTip];
512 if ([networkController isConnectedToServer]) {
513 //Used the cached version
518 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
519 [statusItem setMenu:[menuController menu]];
521 [statusItem setMenu:[menuController menuForNoPlayer]];
524 [self networkError:localException];
528 - (void)trackChanged:(NSNotification *)note
530 //If we're running the timer, shut it off since we don't need it!
531 /*if (refreshTimer && [refreshTimer isValid]) {
532 ITDebugLog(@"Invalidating refresh timer.");
533 [refreshTimer invalidate];
534 [refreshTimer release];
538 if (![self songChanged]) {
541 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
542 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
543 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
545 [_lastTrackInfo release];
546 _lastTrackInfo = [[note userInfo] retain];
548 [self setLatestSongIdentifier:identifier];
549 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
550 if ([df boolForKey:@"runScripts"]) {
551 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
552 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
553 NSString *nextScript;
554 ITDebugLog(@"Running AppleScripts for song change.");
555 while ( (nextScript = [scriptsEnum nextObject]) ) {
557 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
558 ITDebugLog(@"Running script: %@", nextScript);
559 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
560 ITDebugLog(@"Error running script %@.", nextScript);
562 [currentScript release];
566 [statusItem setEnabled:NO];
569 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
571 if ([menuController rebuildSubmenus]) {
572 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
573 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
575 [self setLatestSongIdentifier:identifier];
576 //Create the tooltip for the status item
577 if ( [df boolForKey:@"showToolTip"] ) {
578 ITDebugLog(@"Creating status item tooltip.");
579 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
581 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
585 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
587 [statusItem setToolTip:_toolTip];
589 [statusItem setToolTip:nil];
593 if ([df boolForKey:@"audioscrobblerEnabled"]) {
594 int length = [[self currentRemote] currentSongDuration];
595 if (_audioscrobblerTimer) {
596 [_audioscrobblerTimer invalidate];
599 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
602 _audioscrobblerTimer = nil;
605 [self networkError:localException];
608 [statusItem setEnabled:YES];
610 if ([networkController isConnectedToServer]) {
611 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
615 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
617 if ([df boolForKey:@"audioscrobblerEnabled"]) {
619 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
620 if (title && artist) {
621 [[AudioscrobblerController sharedController] submitTrack:title
623 album:[[self currentRemote] currentSongAlbum]
624 length:[[self currentRemote] currentSongDuration]];
627 [self networkError:localException];
630 _audioscrobblerTimer = nil;
643 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
644 ITDebugLog(@"Play/Pause toggled");
645 if (state == ITMTRemotePlayerPlaying) {
646 [[self currentRemote] pause];
647 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
648 [[self currentRemote] pause];
649 [[self currentRemote] play];
651 [[self currentRemote] play];
654 [self networkError:localException];
664 ITDebugLog(@"Going to next song.");
666 [[self currentRemote] goToNextSong];
668 [self networkError:localException];
677 ITDebugLog(@"Going to previous song.");
679 [[self currentRemote] goToPreviousSong];
681 [self networkError:localException];
690 ITDebugLog(@"Fast forwarding.");
692 [[self currentRemote] forward];
694 [self networkError:localException];
703 ITDebugLog(@"Rewinding.");
705 [[self currentRemote] rewind];
707 [self networkError:localException];
714 - (void)selectPlaylistAtIndex:(int)index
716 ITDebugLog(@"Selecting playlist %i", index);
718 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
719 //[[self currentRemote] switchToPlaylistAtIndex:index];
721 [self networkError:localException];
728 - (void)selectSongAtIndex:(int)index
730 ITDebugLog(@"Selecting song %i", index);
732 [[self currentRemote] switchToSongAtIndex:index];
734 [self networkError:localException];
741 - (void)selectSongRating:(int)rating
743 ITDebugLog(@"Selecting song rating %i", rating);
745 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
747 [self networkError:localException];
754 - (void)selectEQPresetAtIndex:(int)index
756 ITDebugLog(@"Selecting EQ preset %i", index);
759 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
761 [[self currentRemote] switchToEQAtIndex:index];
764 [self networkError:localException];
771 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
773 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
775 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
777 [self networkError:localException];
779 ITDebugLog(@"Done making playlist");
784 ITDebugLog(@"Beginning show player.");
785 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
786 ITDebugLog(@"Showing player interface.");
788 [[self currentRemote] showPrimaryInterface];
790 [self networkError:localException];
793 ITDebugLog(@"Launching player.");
796 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
798 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
800 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
801 ITDebugLog(@"Error Launching Player");
804 [self networkError:localException];
807 ITDebugLog(@"Finished show player.");
810 - (void)showPreferences
812 ITDebugLog(@"Show preferences.");
813 [[PreferencesController sharedPrefs] showPrefsWindow:self];
816 - (void)showPreferencesAndClose
818 ITDebugLog(@"Show preferences.");
819 [[PreferencesController sharedPrefs] showPrefsWindow:self];
820 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
821 [[StatusWindow sharedWindow] vanish:self];
822 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
825 - (void)showTestWindow
827 [self showCurrentTrackInfo];
830 - (void)quitMenuTunes
832 ITDebugLog(@"Quitting MenuTunes.");
833 [NSApp terminate:self];
839 - (MenuController *)menuController
841 return menuController;
844 - (void)closePreferences
846 ITDebugLog(@"Preferences closed.");
847 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
852 - (ITMTRemote *)currentRemote
854 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
855 [self networkError:nil];
858 return currentRemote;
869 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
870 ITHotKey *nextHotKey;
871 ITDebugLog(@"Clearing hot keys.");
872 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
873 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
875 ITDebugLog(@"Done clearing hot keys.");
881 ITDebugLog(@"Setting up hot keys.");
883 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
887 if ([df objectForKey:@"PlayPause"] != nil) {
888 ITDebugLog(@"Setting up play pause hot key.");
889 hotKey = [[ITHotKey alloc] init];
890 [hotKey setName:@"PlayPause"];
891 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
892 [hotKey setTarget:self];
893 [hotKey setAction:@selector(playPause)];
894 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
897 if ([df objectForKey:@"NextTrack"] != nil) {
898 ITDebugLog(@"Setting up next track hot key.");
899 hotKey = [[ITHotKey alloc] init];
900 [hotKey setName:@"NextTrack"];
901 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
902 [hotKey setTarget:self];
903 [hotKey setAction:@selector(nextSong)];
904 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
907 if ([df objectForKey:@"PrevTrack"] != nil) {
908 ITDebugLog(@"Setting up previous track hot key.");
909 hotKey = [[ITHotKey alloc] init];
910 [hotKey setName:@"PrevTrack"];
911 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
912 [hotKey setTarget:self];
913 [hotKey setAction:@selector(prevSong)];
914 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
917 if ([df objectForKey:@"FastForward"] != nil) {
918 ITDebugLog(@"Setting up fast forward hot key.");
919 hotKey = [[ITHotKey alloc] init];
920 [hotKey setName:@"FastForward"];
921 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
922 [hotKey setTarget:self];
923 [hotKey setAction:@selector(fastForward)];
924 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
927 if ([df objectForKey:@"Rewind"] != nil) {
928 ITDebugLog(@"Setting up rewind hot key.");
929 hotKey = [[ITHotKey alloc] init];
930 [hotKey setName:@"Rewind"];
931 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
932 [hotKey setTarget:self];
933 [hotKey setAction:@selector(rewind)];
934 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
937 if ([df objectForKey:@"ShowPlayer"] != nil) {
938 ITDebugLog(@"Setting up show player hot key.");
939 hotKey = [[ITHotKey alloc] init];
940 [hotKey setName:@"ShowPlayer"];
941 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
942 [hotKey setTarget:self];
943 [hotKey setAction:@selector(showPlayer)];
944 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
947 if ([df objectForKey:@"TrackInfo"] != nil) {
948 ITDebugLog(@"Setting up track info hot key.");
949 hotKey = [[ITHotKey alloc] init];
950 [hotKey setName:@"TrackInfo"];
951 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
952 [hotKey setTarget:self];
953 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
954 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
957 if ([df objectForKey:@"UpcomingSongs"] != nil) {
958 ITDebugLog(@"Setting up upcoming songs hot key.");
959 hotKey = [[ITHotKey alloc] init];
960 [hotKey setName:@"UpcomingSongs"];
961 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
962 [hotKey setTarget:self];
963 [hotKey setAction:@selector(showUpcomingSongs)];
964 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
967 if ([df objectForKey:@"ToggleLoop"] != nil) {
968 ITDebugLog(@"Setting up toggle loop hot key.");
969 hotKey = [[ITHotKey alloc] init];
970 [hotKey setName:@"ToggleLoop"];
971 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
972 [hotKey setTarget:self];
973 [hotKey setAction:@selector(toggleLoop)];
974 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
977 if ([df objectForKey:@"ToggleShuffle"] != nil) {
978 ITDebugLog(@"Setting up toggle shuffle hot key.");
979 hotKey = [[ITHotKey alloc] init];
980 [hotKey setName:@"ToggleShuffle"];
981 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
982 [hotKey setTarget:self];
983 [hotKey setAction:@selector(toggleShuffle)];
984 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
987 if ([df objectForKey:@"IncrementVolume"] != nil) {
988 ITDebugLog(@"Setting up increment volume hot key.");
989 hotKey = [[ITHotKey alloc] init];
990 [hotKey setName:@"IncrementVolume"];
991 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
992 [hotKey setTarget:self];
993 [hotKey setAction:@selector(incrementVolume)];
994 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
997 if ([df objectForKey:@"DecrementVolume"] != nil) {
998 ITDebugLog(@"Setting up decrement volume hot key.");
999 hotKey = [[ITHotKey alloc] init];
1000 [hotKey setName:@"DecrementVolume"];
1001 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
1002 [hotKey setTarget:self];
1003 [hotKey setAction:@selector(decrementVolume)];
1004 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1007 if ([df objectForKey:@"IncrementRating"] != nil) {
1008 ITDebugLog(@"Setting up increment rating hot key.");
1009 hotKey = [[ITHotKey alloc] init];
1010 [hotKey setName:@"IncrementRating"];
1011 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
1012 [hotKey setTarget:self];
1013 [hotKey setAction:@selector(incrementRating)];
1014 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1017 if ([df objectForKey:@"DecrementRating"] != nil) {
1018 ITDebugLog(@"Setting up decrement rating hot key.");
1019 hotKey = [[ITHotKey alloc] init];
1020 [hotKey setName:@"DecrementRating"];
1021 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
1022 [hotKey setTarget:self];
1023 [hotKey setAction:@selector(decrementRating)];
1024 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1027 if ([df objectForKey:@"ToggleShufflability"] != nil) {
1028 ITDebugLog(@"Setting up toggle song shufflability hot key.");
1029 hotKey = [[ITHotKey alloc] init];
1030 [hotKey setName:@"ToggleShufflability"];
1031 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
1032 [hotKey setTarget:self];
1033 [hotKey setAction:@selector(toggleSongShufflable)];
1034 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1037 if ([df objectForKey:@"PopupMenu"] != nil) {
1038 ITDebugLog(@"Setting up popup menu hot key.");
1039 hotKey = [[ITHotKey alloc] init];
1040 [hotKey setName:@"PopupMenu"];
1041 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
1042 [hotKey setTarget:self];
1043 [hotKey setAction:@selector(popupMenu)];
1044 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1048 for (i = 0; i <= 5; i++) {
1049 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1050 if ([df objectForKey:curName] != nil) {
1051 ITDebugLog(@"Setting up set rating %i hot key.", i);
1052 hotKey = [[ITHotKey alloc] init];
1053 [hotKey setName:curName];
1054 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1055 [hotKey setTarget:self];
1056 [hotKey setAction:@selector(setRating:)];
1057 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1060 ITDebugLog(@"Finished setting up hot keys.");
1063 - (void)showCurrentTrackInfoHotKey
1065 //If we're already visible and the setting says so, vanish instead of displaying again.
1066 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1067 ITDebugLog(@"Track window is already visible, hiding track window.");
1068 [self invalidateStatusWindowUpdateTimer];
1069 [[StatusWindow sharedWindow] vanish:nil];
1072 [self showCurrentTrackInfo];
1075 - (void)showCurrentTrackInfo
1077 ITMTRemotePlayerSource source = 0;
1078 NSString *title = nil;
1079 NSString *album = nil;
1080 NSString *artist = nil;
1081 NSString *composer = nil;
1082 NSString *time = nil;
1083 NSString *track = nil;
1088 ITDebugLog(@"Showing track info status window.");
1091 source = [[self currentRemote] currentSource];
1092 title = [[self currentRemote] currentSongTitle];
1094 [self networkError:localException];
1098 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1099 NSSize oldSize, newSize;
1101 art = [[self currentRemote] currentSongAlbumArt];
1102 oldSize = [art size];
1103 if (oldSize.width > oldSize.height) {
1104 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1106 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1107 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1109 [self networkError:localException];
1113 if ( [df boolForKey:@"showAlbum"] ) {
1115 album = [[self currentRemote] currentSongAlbum];
1117 [self networkError:localException];
1121 if ( [df boolForKey:@"showArtist"] ) {
1123 artist = [[self currentRemote] currentSongArtist];
1125 [self networkError:localException];
1129 if ( [df boolForKey:@"showComposer"] ) {
1131 composer = [[self currentRemote] currentSongComposer];
1133 [self networkError:localException];
1137 if ( [df boolForKey:@"showTime"] ) {
1139 time = [NSString stringWithFormat:@"%@: %@ / %@",
1140 NSLocalizedString(@"time", @"Time"),
1141 [[self currentRemote] currentSongElapsed],
1142 [[self currentRemote] currentSongLength]];
1144 [self networkError:localException];
1146 _timeUpdateCount = 0;
1147 [self invalidateStatusWindowUpdateTimer];
1148 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1151 if ( [df boolForKey:@"showTrackNumber"] ) {
1156 trackNo = [[self currentRemote] currentSongTrack];
1157 trackCount = [[self currentRemote] currentAlbumTrackCount];
1159 [self networkError:localException];
1162 if ( (trackNo > 0) || (trackCount > 0) ) {
1163 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1164 @"Track", trackNo, @"of", trackCount];
1168 if ( [df boolForKey:@"showTrackRating"] ) {
1169 float currentRating = 0;
1172 currentRating = [[self currentRemote] currentSongRating];
1174 [self networkError:localException];
1177 if (currentRating >= 0.0) {
1178 rating = ( currentRating * 5 );
1182 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1184 playCount = [[self currentRemote] currentSongPlayCount];
1186 [self networkError:localException];
1190 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1192 ITDebugLog(@"Showing current track info status window.");
1193 [statusWindowController showSongInfoWindowWithSource:source
1205 - (void)updateTime:(NSTimer *)timer
1207 StatusWindow *sw = [StatusWindow sharedWindow];
1209 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1210 NSString *time = nil, *length;
1212 length = [[self currentRemote] currentSongLength];
1214 time = [NSString stringWithFormat:@"%@: %@ / %@",
1215 NSLocalizedString(@"time", @"Time"),
1216 [[self currentRemote] currentSongElapsed],
1218 [[StatusWindowController sharedController] updateTime:time];
1221 [self networkError:localException];
1224 [self invalidateStatusWindowUpdateTimer];
1228 - (void)invalidateStatusWindowUpdateTimer
1230 if (_statusWindowUpdateTimer) {
1231 [_statusWindowUpdateTimer invalidate];
1232 _statusWindowUpdateTimer = nil;
1236 - (void)showUpcomingSongs
1240 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1242 [self networkError:localException];
1245 [self invalidateStatusWindowUpdateTimer];
1247 ITDebugLog(@"Showing upcoming songs status window.");
1250 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1251 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1252 int curTrack = [[self currentRemote] currentSongIndex];
1255 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1256 if ([[self currentRemote] songEnabledAtIndex:i]) {
1257 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1259 numSongsInAdvance++;
1263 if ([songList count] == 0) {
1264 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1267 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1269 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1272 [self networkError:localException];
1281 NSMenu *menu = [statusItem menu];
1282 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1287 - (void)incrementVolume
1290 float volume = [[self currentRemote] volume];
1291 float dispVol = volume;
1292 ITDebugLog(@"Incrementing volume.");
1301 ITDebugLog(@"Setting volume to %f", volume);
1302 [[self currentRemote] setVolume:volume];
1304 // Show volume status window
1305 [self invalidateStatusWindowUpdateTimer];
1306 [statusWindowController showVolumeWindowWithLevel:dispVol];
1308 [self networkError:localException];
1312 - (void)decrementVolume
1315 float volume = [[self currentRemote] volume];
1316 float dispVol = volume;
1317 ITDebugLog(@"Decrementing volume.");
1326 ITDebugLog(@"Setting volume to %f", volume);
1327 [[self currentRemote] setVolume:volume];
1329 //Show volume status window
1330 [self invalidateStatusWindowUpdateTimer];
1331 [statusWindowController showVolumeWindowWithLevel:dispVol];
1333 [self networkError:localException];
1337 - (void)incrementRating
1340 float rating = [[self currentRemote] currentSongRating];
1341 ITDebugLog(@"Incrementing rating.");
1343 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1344 ITDebugLog(@"No song playing, rating change aborted.");
1352 ITDebugLog(@"Setting rating to %f", rating);
1353 [[self currentRemote] setCurrentSongRating:rating];
1355 //Show rating status window
1356 [self invalidateStatusWindowUpdateTimer];
1357 [statusWindowController showRatingWindowWithRating:rating];
1359 [self networkError:localException];
1363 - (void)decrementRating
1366 float rating = [[self currentRemote] currentSongRating];
1367 ITDebugLog(@"Decrementing rating.");
1369 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1370 ITDebugLog(@"No song playing, rating change aborted.");
1378 ITDebugLog(@"Setting rating to %f", rating);
1379 [[self currentRemote] setCurrentSongRating:rating];
1381 //Show rating status window
1382 [self invalidateStatusWindowUpdateTimer];
1383 [statusWindowController showRatingWindowWithRating:rating];
1385 [self networkError:localException];
1389 - (void)setRating:(ITHotKey *)sender
1391 if ([self songIsPlaying]) {
1392 int stars = [[sender name] characterAtIndex:9] - 48;
1393 [self selectSongRating:stars * 20];
1394 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1401 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1402 ITDebugLog(@"Toggling repeat mode.");
1403 switch (repeatMode) {
1404 case ITMTRemotePlayerRepeatOff:
1405 repeatMode = ITMTRemotePlayerRepeatAll;
1407 case ITMTRemotePlayerRepeatAll:
1408 repeatMode = ITMTRemotePlayerRepeatOne;
1410 case ITMTRemotePlayerRepeatOne:
1411 repeatMode = ITMTRemotePlayerRepeatOff;
1414 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1415 [[self currentRemote] setRepeatMode:repeatMode];
1417 //Show loop status window
1418 [self invalidateStatusWindowUpdateTimer];
1419 [statusWindowController showRepeatWindowWithMode:repeatMode];
1421 [self networkError:localException];
1425 - (void)toggleShuffle
1428 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1429 ITDebugLog(@"Toggling shuffle mode.");
1430 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1431 //Show shuffle status window
1432 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1433 [self invalidateStatusWindowUpdateTimer];
1434 [statusWindowController showShuffleWindow:newShuffleEnabled];
1436 [self networkError:localException];
1440 - (void)toggleSongShufflable
1442 if ([self songIsPlaying]) {
1444 BOOL flag = ![[self currentRemote] currentSongShufflable];
1445 ITDebugLog(@"Toggling shufflability.");
1446 [[self currentRemote] setCurrentSongShufflable:flag];
1447 //Show song shufflability status window
1448 [self invalidateStatusWindowUpdateTimer];
1449 [statusWindowController showSongShufflabilityWindow:flag];
1451 [self networkError:localException];
1456 - (void)registerNowOK
1458 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1459 [[StatusWindow sharedWindow] vanish:self];
1460 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1465 - (void)registerNowCancel
1467 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1468 [[StatusWindow sharedWindow] vanish:self];
1469 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1471 [NSApp terminate:self];
1474 /*************************************************************************/
1476 #pragma mark NETWORK HANDLERS
1477 /*************************************************************************/
1479 - (void)setServerStatus:(BOOL)newStatus
1483 [networkController setServerStatus:YES];
1486 [networkController setServerStatus:NO];
1490 - (int)connectToServer
1493 ITDebugLog(@"Attempting to connect to shared remote.");
1494 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1497 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1498 currentRemote = [[[networkController networkObject] remote] retain];
1500 [self setupHotKeys];
1501 //playerRunningState = ITMTRemotePlayerRunning;
1502 playerRunningState = [[self currentRemote] playerRunningState];
1503 if (_needsPolling) {
1505 [refreshTimer invalidate];
1507 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1509 selector:@selector(timerUpdate)
1511 repeats:YES] retain];
1514 ITDebugLog(@"Connection successful.");
1516 } else if (result == 0) {
1517 ITDebugLog(@"Connection failed.");
1518 currentRemote = [remoteArray objectAtIndex:0];
1521 //Do something about the password being invalid
1522 ITDebugLog(@"Connection failed.");
1523 currentRemote = [remoteArray objectAtIndex:0];
1528 - (BOOL)disconnectFromServer
1530 ITDebugLog(@"Disconnecting from shared remote.");
1532 [currentRemote release];
1533 currentRemote = [remoteArray objectAtIndex:0];
1534 [networkController disconnect];
1536 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1537 [self applicationLaunched:nil];
1539 [self applicationTerminated:nil];
1547 - (void)checkForRemoteServer
1549 [self checkForRemoteServerAndConnectImmediately:NO];
1552 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1554 ITDebugLog(@"Checking for remote server.");
1555 if (!_checkingForServer) {
1556 if (!_serverCheckLock) {
1557 _serverCheckLock = [[NSLock alloc] init];
1559 [_serverCheckLock lock];
1560 _checkingForServer = YES;
1561 [_serverCheckLock unlock];
1562 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1566 - (void)runRemoteServerCheck:(id)sender
1568 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1569 ITDebugLog(@"Remote server check running.");
1570 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1571 ITDebugLog(@"Remote server found.");
1572 if ([sender boolValue]) {
1573 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1575 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1578 ITDebugLog(@"Remote server not found.");
1579 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1581 [_serverCheckLock lock];
1582 _checkingForServer = NO;
1583 [_serverCheckLock unlock];
1587 - (void)remoteServerFound:(id)sender
1589 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1590 [self invalidateStatusWindowUpdateTimer];
1591 [[StatusWindowController sharedController] showReconnectQueryWindow];
1595 - (void)remoteServerNotFound:(id)sender
1597 if (![[NetworkController sharedController] isConnectedToServer]) {
1598 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1602 - (void)networkError:(NSException *)exception
1604 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1605 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1606 //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);
1607 [self invalidateStatusWindowUpdateTimer];
1608 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1609 if ([self disconnectFromServer]) {
1610 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1611 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1613 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1620 /*if ([self connectToServer] == 0) {
1621 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1623 [self checkForRemoteServerAndConnectImmediately:YES];
1624 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1625 [[StatusWindow sharedWindow] vanish:self];
1626 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1629 - (void)cancelReconnect
1631 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1632 [[StatusWindow sharedWindow] vanish:self];
1633 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1636 /*************************************************************************/
1638 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1639 /*************************************************************************/
1641 - (void)applicationLaunched:(NSNotification *)note
1644 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1645 ITDebugLog(@"Remote application launched.");
1646 playerRunningState = ITMTRemotePlayerRunning;
1647 [[self currentRemote] begin];
1648 [self setLatestSongIdentifier:@""];
1650 if (_needsPolling) {
1651 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1653 selector:@selector(timerUpdate)
1655 repeats:YES] retain];
1657 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1658 if (![df boolForKey:@"UsePollingOnly"]) {
1659 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1661 [self setupHotKeys];
1664 [self networkError:localException];
1668 - (void)applicationTerminated:(NSNotification *)note
1671 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1672 ITDebugLog(@"Remote application terminated.");
1673 playerRunningState = ITMTRemotePlayerNotRunning;
1674 [[self currentRemote] halt];
1675 [refreshTimer invalidate];
1676 [refreshTimer release];
1678 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1679 [statusItem setEnabled:YES];
1680 [statusItem setToolTip:@"iTunes not running."];
1681 [self clearHotKeys];
1684 if ([df objectForKey:@"ShowPlayer"] != nil) {
1686 ITDebugLog(@"Setting up show player hot key.");
1687 hotKey = [[ITHotKey alloc] init];
1688 [hotKey setName:@"ShowPlayer"];
1689 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1690 [hotKey setTarget:self];
1691 [hotKey setAction:@selector(showPlayer)];
1692 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1696 [self networkError:localException];
1701 /*************************************************************************/
1703 #pragma mark NSApplication DELEGATE METHODS
1704 /*************************************************************************/
1706 - (void)applicationWillTerminate:(NSNotification *)note
1708 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1709 [networkController stopRemoteServerSearch];
1710 [self clearHotKeys];
1711 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1714 - (void)applicationDidBecomeActive:(NSNotification *)note
1716 //This appears to not work in 10.4
1717 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1718 [[MainController sharedController] showPreferences];
1722 /*************************************************************************/
1724 #pragma mark DEALLOCATION METHOD
1725 /*************************************************************************/
1729 [self applicationTerminated:nil];
1731 [statusItem release];
1732 [statusWindowController release];
1733 [menuController release];
1734 [networkController release];
1735 [_serverCheckLock release];