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(showCurrentTrackInfo)];
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)showCurrentTrackInfo
1065 ITMTRemotePlayerSource source = 0;
1066 NSString *title = nil;
1067 NSString *album = nil;
1068 NSString *artist = nil;
1069 NSString *composer = nil;
1070 NSString *time = nil;
1071 NSString *track = nil;
1076 //If we're already visible and the setting says so, vanish instead of displaying again.
1077 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1078 ITDebugLog(@"Track window is already visible, hiding track window.");
1079 [self invalidateStatusWindowUpdateTimer];
1080 [[StatusWindow sharedWindow] vanish:nil];
1084 ITDebugLog(@"Showing track info status window.");
1087 source = [[self currentRemote] currentSource];
1088 title = [[self currentRemote] currentSongTitle];
1090 [self networkError:localException];
1094 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1095 NSSize oldSize, newSize;
1097 art = [[self currentRemote] currentSongAlbumArt];
1098 oldSize = [art size];
1099 if (oldSize.width > oldSize.height) {
1100 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1102 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1103 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1105 [self networkError:localException];
1109 if ( [df boolForKey:@"showAlbum"] ) {
1111 album = [[self currentRemote] currentSongAlbum];
1113 [self networkError:localException];
1117 if ( [df boolForKey:@"showArtist"] ) {
1119 artist = [[self currentRemote] currentSongArtist];
1121 [self networkError:localException];
1125 if ( [df boolForKey:@"showComposer"] ) {
1127 composer = [[self currentRemote] currentSongComposer];
1129 [self networkError:localException];
1133 if ( [df boolForKey:@"showTime"] ) {
1135 time = [NSString stringWithFormat:@"%@: %@ / %@",
1136 NSLocalizedString(@"time", @"Time"),
1137 [[self currentRemote] currentSongElapsed],
1138 [[self currentRemote] currentSongLength]];
1140 [self networkError:localException];
1142 _timeUpdateCount = 0;
1143 [self invalidateStatusWindowUpdateTimer];
1144 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1147 if ( [df boolForKey:@"showTrackNumber"] ) {
1152 trackNo = [[self currentRemote] currentSongTrack];
1153 trackCount = [[self currentRemote] currentAlbumTrackCount];
1155 [self networkError:localException];
1158 if ( (trackNo > 0) || (trackCount > 0) ) {
1159 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1160 @"Track", trackNo, @"of", trackCount];
1164 if ( [df boolForKey:@"showTrackRating"] ) {
1165 float currentRating = 0;
1168 currentRating = [[self currentRemote] currentSongRating];
1170 [self networkError:localException];
1173 if (currentRating >= 0.0) {
1174 rating = ( currentRating * 5 );
1178 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1180 playCount = [[self currentRemote] currentSongPlayCount];
1182 [self networkError:localException];
1186 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1188 ITDebugLog(@"Showing current track info status window.");
1189 [statusWindowController showSongInfoWindowWithSource:source
1201 - (void)updateTime:(NSTimer *)timer
1203 StatusWindow *sw = [StatusWindow sharedWindow];
1205 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1206 NSString *time = nil, *length;
1208 length = [[self currentRemote] currentSongLength];
1210 time = [NSString stringWithFormat:@"%@: %@ / %@",
1211 NSLocalizedString(@"time", @"Time"),
1212 [[self currentRemote] currentSongElapsed],
1214 [[StatusWindowController sharedController] updateTime:time];
1217 [self networkError:localException];
1220 [self invalidateStatusWindowUpdateTimer];
1224 - (void)invalidateStatusWindowUpdateTimer
1226 if (_statusWindowUpdateTimer) {
1227 [_statusWindowUpdateTimer invalidate];
1228 _statusWindowUpdateTimer = nil;
1232 - (void)showUpcomingSongs
1236 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1238 [self networkError:localException];
1241 [self invalidateStatusWindowUpdateTimer];
1243 ITDebugLog(@"Showing upcoming songs status window.");
1246 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1247 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1248 int curTrack = [[self currentRemote] currentSongIndex];
1251 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1252 if ([[self currentRemote] songEnabledAtIndex:i]) {
1253 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1255 numSongsInAdvance++;
1259 if ([songList count] == 0) {
1260 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1263 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1265 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1268 [self networkError:localException];
1277 NSMenu *menu = [statusItem menu];
1278 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1283 - (void)incrementVolume
1286 float volume = [[self currentRemote] volume];
1287 float dispVol = volume;
1288 ITDebugLog(@"Incrementing volume.");
1297 ITDebugLog(@"Setting volume to %f", volume);
1298 [[self currentRemote] setVolume:volume];
1300 // Show volume status window
1301 [self invalidateStatusWindowUpdateTimer];
1302 [statusWindowController showVolumeWindowWithLevel:dispVol];
1304 [self networkError:localException];
1308 - (void)decrementVolume
1311 float volume = [[self currentRemote] volume];
1312 float dispVol = volume;
1313 ITDebugLog(@"Decrementing volume.");
1322 ITDebugLog(@"Setting volume to %f", volume);
1323 [[self currentRemote] setVolume:volume];
1325 //Show volume status window
1326 [self invalidateStatusWindowUpdateTimer];
1327 [statusWindowController showVolumeWindowWithLevel:dispVol];
1329 [self networkError:localException];
1333 - (void)incrementRating
1336 float rating = [[self currentRemote] currentSongRating];
1337 ITDebugLog(@"Incrementing rating.");
1339 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1340 ITDebugLog(@"No song playing, rating change aborted.");
1348 ITDebugLog(@"Setting rating to %f", rating);
1349 [[self currentRemote] setCurrentSongRating:rating];
1351 //Show rating status window
1352 [self invalidateStatusWindowUpdateTimer];
1353 [statusWindowController showRatingWindowWithRating:rating];
1355 [self networkError:localException];
1359 - (void)decrementRating
1362 float rating = [[self currentRemote] currentSongRating];
1363 ITDebugLog(@"Decrementing rating.");
1365 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1366 ITDebugLog(@"No song playing, rating change aborted.");
1374 ITDebugLog(@"Setting rating to %f", rating);
1375 [[self currentRemote] setCurrentSongRating:rating];
1377 //Show rating status window
1378 [self invalidateStatusWindowUpdateTimer];
1379 [statusWindowController showRatingWindowWithRating:rating];
1381 [self networkError:localException];
1385 - (void)setRating:(ITHotKey *)sender
1387 if ([self songIsPlaying]) {
1388 int stars = [[sender name] characterAtIndex:9] - 48;
1389 [self selectSongRating:stars * 20];
1390 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1397 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1398 ITDebugLog(@"Toggling repeat mode.");
1399 switch (repeatMode) {
1400 case ITMTRemotePlayerRepeatOff:
1401 repeatMode = ITMTRemotePlayerRepeatAll;
1403 case ITMTRemotePlayerRepeatAll:
1404 repeatMode = ITMTRemotePlayerRepeatOne;
1406 case ITMTRemotePlayerRepeatOne:
1407 repeatMode = ITMTRemotePlayerRepeatOff;
1410 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1411 [[self currentRemote] setRepeatMode:repeatMode];
1413 //Show loop status window
1414 [self invalidateStatusWindowUpdateTimer];
1415 [statusWindowController showRepeatWindowWithMode:repeatMode];
1417 [self networkError:localException];
1421 - (void)toggleShuffle
1424 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1425 ITDebugLog(@"Toggling shuffle mode.");
1426 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1427 //Show shuffle status window
1428 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1429 [self invalidateStatusWindowUpdateTimer];
1430 [statusWindowController showShuffleWindow:newShuffleEnabled];
1432 [self networkError:localException];
1436 - (void)toggleSongShufflable
1438 if ([self songIsPlaying]) {
1440 BOOL flag = ![[self currentRemote] currentSongShufflable];
1441 ITDebugLog(@"Toggling shufflability.");
1442 [[self currentRemote] setCurrentSongShufflable:flag];
1443 //Show song shufflability status window
1444 [self invalidateStatusWindowUpdateTimer];
1445 [statusWindowController showSongShufflabilityWindow:flag];
1447 [self networkError:localException];
1452 - (void)registerNowOK
1454 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1455 [[StatusWindow sharedWindow] vanish:self];
1456 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1461 - (void)registerNowCancel
1463 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1464 [[StatusWindow sharedWindow] vanish:self];
1465 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1467 [NSApp terminate:self];
1470 /*************************************************************************/
1472 #pragma mark NETWORK HANDLERS
1473 /*************************************************************************/
1475 - (void)setServerStatus:(BOOL)newStatus
1479 [networkController setServerStatus:YES];
1482 [networkController setServerStatus:NO];
1486 - (int)connectToServer
1489 ITDebugLog(@"Attempting to connect to shared remote.");
1490 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1493 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1494 currentRemote = [[[networkController networkObject] remote] retain];
1496 [self setupHotKeys];
1497 //playerRunningState = ITMTRemotePlayerRunning;
1498 playerRunningState = [[self currentRemote] playerRunningState];
1499 if (_needsPolling) {
1501 [refreshTimer invalidate];
1503 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1505 selector:@selector(timerUpdate)
1507 repeats:YES] retain];
1510 ITDebugLog(@"Connection successful.");
1512 } else if (result == 0) {
1513 ITDebugLog(@"Connection failed.");
1514 currentRemote = [remoteArray objectAtIndex:0];
1517 //Do something about the password being invalid
1518 ITDebugLog(@"Connection failed.");
1519 currentRemote = [remoteArray objectAtIndex:0];
1524 - (BOOL)disconnectFromServer
1526 ITDebugLog(@"Disconnecting from shared remote.");
1528 [currentRemote release];
1529 currentRemote = [remoteArray objectAtIndex:0];
1530 [networkController disconnect];
1532 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1533 [self applicationLaunched:nil];
1535 [self applicationTerminated:nil];
1543 - (void)checkForRemoteServer
1545 [self checkForRemoteServerAndConnectImmediately:NO];
1548 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1550 ITDebugLog(@"Checking for remote server.");
1551 if (!_checkingForServer) {
1552 if (!_serverCheckLock) {
1553 _serverCheckLock = [[NSLock alloc] init];
1555 [_serverCheckLock lock];
1556 _checkingForServer = YES;
1557 [_serverCheckLock unlock];
1558 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1562 - (void)runRemoteServerCheck:(id)sender
1564 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1565 ITDebugLog(@"Remote server check running.");
1566 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1567 ITDebugLog(@"Remote server found.");
1568 if ([sender boolValue]) {
1569 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1571 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1574 ITDebugLog(@"Remote server not found.");
1575 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1577 [_serverCheckLock lock];
1578 _checkingForServer = NO;
1579 [_serverCheckLock unlock];
1583 - (void)remoteServerFound:(id)sender
1585 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1586 [self invalidateStatusWindowUpdateTimer];
1587 [[StatusWindowController sharedController] showReconnectQueryWindow];
1591 - (void)remoteServerNotFound:(id)sender
1593 if (![[NetworkController sharedController] isConnectedToServer]) {
1594 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1598 - (void)networkError:(NSException *)exception
1600 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1601 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1602 //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);
1603 [self invalidateStatusWindowUpdateTimer];
1604 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1605 if ([self disconnectFromServer]) {
1606 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1607 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1609 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1616 /*if ([self connectToServer] == 0) {
1617 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1619 [self checkForRemoteServerAndConnectImmediately:YES];
1620 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1621 [[StatusWindow sharedWindow] vanish:self];
1622 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1625 - (void)cancelReconnect
1627 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1628 [[StatusWindow sharedWindow] vanish:self];
1629 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1632 /*************************************************************************/
1634 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1635 /*************************************************************************/
1637 - (void)applicationLaunched:(NSNotification *)note
1640 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1641 ITDebugLog(@"Remote application launched.");
1642 playerRunningState = ITMTRemotePlayerRunning;
1643 [[self currentRemote] begin];
1644 [self setLatestSongIdentifier:@""];
1646 if (_needsPolling) {
1647 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1649 selector:@selector(timerUpdate)
1651 repeats:YES] retain];
1653 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1654 if (![df boolForKey:@"UsePollingOnly"]) {
1655 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1657 [self setupHotKeys];
1660 [self networkError:localException];
1664 - (void)applicationTerminated:(NSNotification *)note
1667 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1668 ITDebugLog(@"Remote application terminated.");
1669 playerRunningState = ITMTRemotePlayerNotRunning;
1670 [[self currentRemote] halt];
1671 [refreshTimer invalidate];
1672 [refreshTimer release];
1674 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1675 [statusItem setEnabled:YES];
1676 [statusItem setToolTip:@"iTunes not running."];
1677 [self clearHotKeys];
1680 if ([df objectForKey:@"ShowPlayer"] != nil) {
1682 ITDebugLog(@"Setting up show player hot key.");
1683 hotKey = [[ITHotKey alloc] init];
1684 [hotKey setName:@"ShowPlayer"];
1685 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1686 [hotKey setTarget:self];
1687 [hotKey setAction:@selector(showPlayer)];
1688 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1692 [self networkError:localException];
1697 /*************************************************************************/
1699 #pragma mark NSApplication DELEGATE METHODS
1700 /*************************************************************************/
1702 - (void)applicationWillTerminate:(NSNotification *)note
1704 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1705 [networkController stopRemoteServerSearch];
1706 [self clearHotKeys];
1707 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1710 - (void)applicationDidBecomeActive:(NSNotification *)note
1712 //This appears to not work in 10.4
1713 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1714 [[MainController sharedController] showPreferences];
1718 /*************************************************************************/
1720 #pragma mark DEALLOCATION METHOD
1721 /*************************************************************************/
1725 [self applicationTerminated:nil];
1727 [statusItem release];
1728 [statusWindowController release];
1729 [menuController release];
1730 [networkController release];
1731 [_serverCheckLock release];