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:YES];
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:YES];
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 int interval = [timer timeInterval];
619 _audioscrobblerTimer = nil;
620 ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
621 if ([df boolForKey:@"audioscrobblerEnabled"]) {
623 int elapsed = [[self currentRemote] currentSongPlayed];
624 if ((abs(elapsed - interval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
625 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
626 if (title && artist) {
627 ITDebugLog(@"Audioscrobbler: Submitting current track");
628 [[AudioscrobblerController sharedController] submitTrack:title
630 album:[[self currentRemote] currentSongAlbum]
631 length:[[self currentRemote] currentSongDuration]];
633 } else if (interval - elapsed > 0) {
634 ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", interval - elapsed);
635 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:(interval - elapsed) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
638 [self networkError:localException];
652 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
653 ITDebugLog(@"Play/Pause toggled");
654 if (state == ITMTRemotePlayerPlaying) {
655 [[self currentRemote] pause];
656 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
657 [[self currentRemote] pause];
658 [[self currentRemote] play];
660 [[self currentRemote] play];
663 [self networkError:localException];
673 ITDebugLog(@"Going to next song.");
675 [[self currentRemote] goToNextSong];
677 [self networkError:localException];
686 ITDebugLog(@"Going to previous song.");
688 [[self currentRemote] goToPreviousSong];
690 [self networkError:localException];
699 ITDebugLog(@"Fast forwarding.");
701 [[self currentRemote] forward];
703 [self networkError:localException];
712 ITDebugLog(@"Rewinding.");
714 [[self currentRemote] rewind];
716 [self networkError:localException];
723 - (void)selectPlaylistAtIndex:(int)index
725 ITDebugLog(@"Selecting playlist %i", index);
727 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
728 //[[self currentRemote] switchToPlaylistAtIndex:index];
730 [self networkError:localException];
737 - (void)selectSongAtIndex:(int)index
739 ITDebugLog(@"Selecting song %i", index);
741 [[self currentRemote] switchToSongAtIndex:index];
743 [self networkError:localException];
750 - (void)selectSongRating:(int)rating
752 ITDebugLog(@"Selecting song rating %i", rating);
754 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
756 [self networkError:localException];
763 - (void)selectEQPresetAtIndex:(int)index
765 ITDebugLog(@"Selecting EQ preset %i", index);
768 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
770 [[self currentRemote] switchToEQAtIndex:index];
773 [self networkError:localException];
780 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
782 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
784 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
786 [self networkError:localException];
788 ITDebugLog(@"Done making playlist");
793 ITDebugLog(@"Beginning show player.");
794 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
795 ITDebugLog(@"Showing player interface.");
797 [[self currentRemote] showPrimaryInterface];
799 [self networkError:localException];
802 ITDebugLog(@"Launching player.");
805 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
807 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
809 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
810 ITDebugLog(@"Error Launching Player");
813 [self networkError:localException];
816 ITDebugLog(@"Finished show player.");
819 - (void)showPreferences
821 ITDebugLog(@"Show preferences.");
822 [[PreferencesController sharedPrefs] showPrefsWindow:self];
825 - (void)showPreferencesAndClose
827 ITDebugLog(@"Show preferences.");
828 [[PreferencesController sharedPrefs] showPrefsWindow:self];
829 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
830 [[StatusWindow sharedWindow] vanish:self];
831 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
834 - (void)showTestWindow
836 [self showCurrentTrackInfo];
839 - (void)quitMenuTunes
841 ITDebugLog(@"Quitting MenuTunes.");
842 [NSApp terminate:self];
848 - (MenuController *)menuController
850 return menuController;
853 - (void)closePreferences
855 ITDebugLog(@"Preferences closed.");
856 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
861 - (ITMTRemote *)currentRemote
863 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
864 [self networkError:nil];
867 return currentRemote;
878 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
879 ITHotKey *nextHotKey;
880 ITDebugLog(@"Clearing hot keys.");
881 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
882 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
884 ITDebugLog(@"Done clearing hot keys.");
890 ITDebugLog(@"Setting up hot keys.");
892 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
896 if ([df objectForKey:@"PlayPause"] != nil) {
897 ITDebugLog(@"Setting up play pause hot key.");
898 hotKey = [[ITHotKey alloc] init];
899 [hotKey setName:@"PlayPause"];
900 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
901 [hotKey setTarget:self];
902 [hotKey setAction:@selector(playPause)];
903 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
906 if ([df objectForKey:@"NextTrack"] != nil) {
907 ITDebugLog(@"Setting up next track hot key.");
908 hotKey = [[ITHotKey alloc] init];
909 [hotKey setName:@"NextTrack"];
910 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
911 [hotKey setTarget:self];
912 [hotKey setAction:@selector(nextSong)];
913 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
916 if ([df objectForKey:@"PrevTrack"] != nil) {
917 ITDebugLog(@"Setting up previous track hot key.");
918 hotKey = [[ITHotKey alloc] init];
919 [hotKey setName:@"PrevTrack"];
920 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
921 [hotKey setTarget:self];
922 [hotKey setAction:@selector(prevSong)];
923 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
926 if ([df objectForKey:@"FastForward"] != nil) {
927 ITDebugLog(@"Setting up fast forward hot key.");
928 hotKey = [[ITHotKey alloc] init];
929 [hotKey setName:@"FastForward"];
930 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
931 [hotKey setTarget:self];
932 [hotKey setAction:@selector(fastForward)];
933 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
936 if ([df objectForKey:@"Rewind"] != nil) {
937 ITDebugLog(@"Setting up rewind hot key.");
938 hotKey = [[ITHotKey alloc] init];
939 [hotKey setName:@"Rewind"];
940 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
941 [hotKey setTarget:self];
942 [hotKey setAction:@selector(rewind)];
943 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
946 if ([df objectForKey:@"ShowPlayer"] != nil) {
947 ITDebugLog(@"Setting up show player hot key.");
948 hotKey = [[ITHotKey alloc] init];
949 [hotKey setName:@"ShowPlayer"];
950 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
951 [hotKey setTarget:self];
952 [hotKey setAction:@selector(showPlayer)];
953 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
956 if ([df objectForKey:@"TrackInfo"] != nil) {
957 ITDebugLog(@"Setting up track info hot key.");
958 hotKey = [[ITHotKey alloc] init];
959 [hotKey setName:@"TrackInfo"];
960 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
961 [hotKey setTarget:self];
962 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
963 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
966 if ([df objectForKey:@"UpcomingSongs"] != nil) {
967 ITDebugLog(@"Setting up upcoming songs hot key.");
968 hotKey = [[ITHotKey alloc] init];
969 [hotKey setName:@"UpcomingSongs"];
970 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
971 [hotKey setTarget:self];
972 [hotKey setAction:@selector(showUpcomingSongs)];
973 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
976 if ([df objectForKey:@"ToggleLoop"] != nil) {
977 ITDebugLog(@"Setting up toggle loop hot key.");
978 hotKey = [[ITHotKey alloc] init];
979 [hotKey setName:@"ToggleLoop"];
980 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
981 [hotKey setTarget:self];
982 [hotKey setAction:@selector(toggleLoop)];
983 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
986 if ([df objectForKey:@"ToggleShuffle"] != nil) {
987 ITDebugLog(@"Setting up toggle shuffle hot key.");
988 hotKey = [[ITHotKey alloc] init];
989 [hotKey setName:@"ToggleShuffle"];
990 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
991 [hotKey setTarget:self];
992 [hotKey setAction:@selector(toggleShuffle)];
993 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
996 if ([df objectForKey:@"IncrementVolume"] != nil) {
997 ITDebugLog(@"Setting up increment volume hot key.");
998 hotKey = [[ITHotKey alloc] init];
999 [hotKey setName:@"IncrementVolume"];
1000 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
1001 [hotKey setTarget:self];
1002 [hotKey setAction:@selector(incrementVolume)];
1003 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1006 if ([df objectForKey:@"DecrementVolume"] != nil) {
1007 ITDebugLog(@"Setting up decrement volume hot key.");
1008 hotKey = [[ITHotKey alloc] init];
1009 [hotKey setName:@"DecrementVolume"];
1010 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
1011 [hotKey setTarget:self];
1012 [hotKey setAction:@selector(decrementVolume)];
1013 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1016 if ([df objectForKey:@"IncrementRating"] != nil) {
1017 ITDebugLog(@"Setting up increment rating hot key.");
1018 hotKey = [[ITHotKey alloc] init];
1019 [hotKey setName:@"IncrementRating"];
1020 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
1021 [hotKey setTarget:self];
1022 [hotKey setAction:@selector(incrementRating)];
1023 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1026 if ([df objectForKey:@"DecrementRating"] != nil) {
1027 ITDebugLog(@"Setting up decrement rating hot key.");
1028 hotKey = [[ITHotKey alloc] init];
1029 [hotKey setName:@"DecrementRating"];
1030 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
1031 [hotKey setTarget:self];
1032 [hotKey setAction:@selector(decrementRating)];
1033 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1036 if ([df objectForKey:@"ToggleShufflability"] != nil) {
1037 ITDebugLog(@"Setting up toggle song shufflability hot key.");
1038 hotKey = [[ITHotKey alloc] init];
1039 [hotKey setName:@"ToggleShufflability"];
1040 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
1041 [hotKey setTarget:self];
1042 [hotKey setAction:@selector(toggleSongShufflable)];
1043 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1046 if ([df objectForKey:@"PopupMenu"] != nil) {
1047 ITDebugLog(@"Setting up popup menu hot key.");
1048 hotKey = [[ITHotKey alloc] init];
1049 [hotKey setName:@"PopupMenu"];
1050 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
1051 [hotKey setTarget:self];
1052 [hotKey setAction:@selector(popupMenu)];
1053 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1057 for (i = 0; i <= 5; i++) {
1058 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1059 if ([df objectForKey:curName] != nil) {
1060 ITDebugLog(@"Setting up set rating %i hot key.", i);
1061 hotKey = [[ITHotKey alloc] init];
1062 [hotKey setName:curName];
1063 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1064 [hotKey setTarget:self];
1065 [hotKey setAction:@selector(setRating:)];
1066 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1069 ITDebugLog(@"Finished setting up hot keys.");
1072 - (void)showCurrentTrackInfoHotKey
1074 //If we're already visible and the setting says so, vanish instead of displaying again.
1075 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1076 ITDebugLog(@"Track window is already visible, hiding track window.");
1077 [self invalidateStatusWindowUpdateTimer];
1078 [[StatusWindow sharedWindow] vanish:nil];
1081 [self showCurrentTrackInfo];
1084 - (void)showCurrentTrackInfo
1086 ITMTRemotePlayerSource source = 0;
1087 NSString *title = nil;
1088 NSString *album = nil;
1089 NSString *artist = nil;
1090 NSString *composer = nil;
1091 NSString *time = nil;
1092 NSString *track = nil;
1097 ITDebugLog(@"Showing track info status window.");
1100 source = [[self currentRemote] currentSource];
1101 title = [[self currentRemote] currentSongTitle];
1103 [self networkError:localException];
1107 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1108 NSSize oldSize, newSize;
1110 art = [[self currentRemote] currentSongAlbumArt];
1111 oldSize = [art size];
1112 if (oldSize.width > oldSize.height) {
1113 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1115 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1116 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1118 [self networkError:localException];
1122 if ( [df boolForKey:@"showAlbum"] ) {
1124 album = [[self currentRemote] currentSongAlbum];
1126 [self networkError:localException];
1130 if ( [df boolForKey:@"showArtist"] ) {
1132 artist = [[self currentRemote] currentSongArtist];
1134 [self networkError:localException];
1138 if ( [df boolForKey:@"showComposer"] ) {
1140 composer = [[self currentRemote] currentSongComposer];
1142 [self networkError:localException];
1146 if ( [df boolForKey:@"showTime"] ) {
1148 time = [NSString stringWithFormat:@"%@: %@ / %@",
1149 NSLocalizedString(@"time", @"Time"),
1150 [[self currentRemote] currentSongElapsed],
1151 [[self currentRemote] currentSongLength]];
1153 [self networkError:localException];
1155 _timeUpdateCount = 0;
1156 [self invalidateStatusWindowUpdateTimer];
1157 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1160 if ( [df boolForKey:@"showTrackNumber"] ) {
1165 trackNo = [[self currentRemote] currentSongTrack];
1166 trackCount = [[self currentRemote] currentAlbumTrackCount];
1168 [self networkError:localException];
1171 if ( (trackNo > 0) || (trackCount > 0) ) {
1172 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1173 @"Track", trackNo, @"of", trackCount];
1177 if ( [df boolForKey:@"showTrackRating"] ) {
1178 float currentRating = 0;
1181 currentRating = [[self currentRemote] currentSongRating];
1183 [self networkError:localException];
1186 if (currentRating >= 0.0) {
1187 rating = ( currentRating * 5 );
1191 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1193 playCount = [[self currentRemote] currentSongPlayCount];
1195 [self networkError:localException];
1199 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1201 ITDebugLog(@"Showing current track info status window.");
1202 [statusWindowController showSongInfoWindowWithSource:source
1214 - (void)updateTime:(NSTimer *)timer
1216 StatusWindow *sw = [StatusWindow sharedWindow];
1218 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1219 NSString *time = nil, *length;
1221 length = [[self currentRemote] currentSongLength];
1223 time = [NSString stringWithFormat:@"%@: %@ / %@",
1224 NSLocalizedString(@"time", @"Time"),
1225 [[self currentRemote] currentSongElapsed],
1227 [[StatusWindowController sharedController] updateTime:time];
1230 [self networkError:localException];
1233 [self invalidateStatusWindowUpdateTimer];
1237 - (void)invalidateStatusWindowUpdateTimer
1239 if (_statusWindowUpdateTimer) {
1240 [_statusWindowUpdateTimer invalidate];
1241 _statusWindowUpdateTimer = nil;
1245 - (void)showUpcomingSongs
1249 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1251 [self networkError:localException];
1254 [self invalidateStatusWindowUpdateTimer];
1256 ITDebugLog(@"Showing upcoming songs status window.");
1259 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1260 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1261 int curTrack = [[self currentRemote] currentSongIndex];
1264 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1265 if ([[self currentRemote] songEnabledAtIndex:i]) {
1266 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1268 numSongsInAdvance++;
1272 if ([songList count] == 0) {
1273 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1276 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1278 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1281 [self networkError:localException];
1290 NSMenu *menu = [statusItem menu];
1291 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1296 - (void)incrementVolume
1299 float volume = [[self currentRemote] volume];
1300 float dispVol = volume;
1301 ITDebugLog(@"Incrementing volume.");
1310 ITDebugLog(@"Setting volume to %f", volume);
1311 [[self currentRemote] setVolume:volume];
1313 // Show volume status window
1314 [self invalidateStatusWindowUpdateTimer];
1315 [statusWindowController showVolumeWindowWithLevel:dispVol];
1317 [self networkError:localException];
1321 - (void)decrementVolume
1324 float volume = [[self currentRemote] volume];
1325 float dispVol = volume;
1326 ITDebugLog(@"Decrementing volume.");
1335 ITDebugLog(@"Setting volume to %f", volume);
1336 [[self currentRemote] setVolume:volume];
1338 //Show volume status window
1339 [self invalidateStatusWindowUpdateTimer];
1340 [statusWindowController showVolumeWindowWithLevel:dispVol];
1342 [self networkError:localException];
1346 - (void)incrementRating
1349 float rating = [[self currentRemote] currentSongRating];
1350 ITDebugLog(@"Incrementing rating.");
1352 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1353 ITDebugLog(@"No song playing, rating change aborted.");
1361 ITDebugLog(@"Setting rating to %f", rating);
1362 [[self currentRemote] setCurrentSongRating:rating];
1364 //Show rating status window
1365 [self invalidateStatusWindowUpdateTimer];
1366 [statusWindowController showRatingWindowWithRating:rating];
1368 [self networkError:localException];
1372 - (void)decrementRating
1375 float rating = [[self currentRemote] currentSongRating];
1376 ITDebugLog(@"Decrementing rating.");
1378 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1379 ITDebugLog(@"No song playing, rating change aborted.");
1387 ITDebugLog(@"Setting rating to %f", rating);
1388 [[self currentRemote] setCurrentSongRating:rating];
1390 //Show rating status window
1391 [self invalidateStatusWindowUpdateTimer];
1392 [statusWindowController showRatingWindowWithRating:rating];
1394 [self networkError:localException];
1398 - (void)setRating:(ITHotKey *)sender
1400 if ([self songIsPlaying]) {
1401 int stars = [[sender name] characterAtIndex:9] - 48;
1402 [self selectSongRating:stars * 20];
1403 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1410 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1411 ITDebugLog(@"Toggling repeat mode.");
1412 switch (repeatMode) {
1413 case ITMTRemotePlayerRepeatOff:
1414 repeatMode = ITMTRemotePlayerRepeatAll;
1416 case ITMTRemotePlayerRepeatAll:
1417 repeatMode = ITMTRemotePlayerRepeatOne;
1419 case ITMTRemotePlayerRepeatOne:
1420 repeatMode = ITMTRemotePlayerRepeatOff;
1423 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1424 [[self currentRemote] setRepeatMode:repeatMode];
1426 //Show loop status window
1427 [self invalidateStatusWindowUpdateTimer];
1428 [statusWindowController showRepeatWindowWithMode:repeatMode];
1430 [self networkError:localException];
1434 - (void)toggleShuffle
1437 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1438 ITDebugLog(@"Toggling shuffle mode.");
1439 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1440 //Show shuffle status window
1441 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1442 [self invalidateStatusWindowUpdateTimer];
1443 [statusWindowController showShuffleWindow:newShuffleEnabled];
1445 [self networkError:localException];
1449 - (void)toggleSongShufflable
1451 if ([self songIsPlaying]) {
1453 BOOL flag = ![[self currentRemote] currentSongShufflable];
1454 ITDebugLog(@"Toggling shufflability.");
1455 [[self currentRemote] setCurrentSongShufflable:flag];
1456 //Show song shufflability status window
1457 [self invalidateStatusWindowUpdateTimer];
1458 [statusWindowController showSongShufflabilityWindow:flag];
1460 [self networkError:localException];
1465 - (void)registerNowOK
1467 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1468 [[StatusWindow sharedWindow] vanish:self];
1469 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1474 - (void)registerNowCancel
1476 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1477 [[StatusWindow sharedWindow] vanish:self];
1478 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1480 [NSApp terminate:self];
1483 /*************************************************************************/
1485 #pragma mark NETWORK HANDLERS
1486 /*************************************************************************/
1488 - (void)setServerStatus:(BOOL)newStatus
1492 [networkController setServerStatus:YES];
1495 [networkController setServerStatus:NO];
1499 - (int)connectToServer
1502 ITDebugLog(@"Attempting to connect to shared remote.");
1503 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1506 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1507 currentRemote = [[[networkController networkObject] remote] retain];
1509 [self setupHotKeys];
1510 //playerRunningState = ITMTRemotePlayerRunning;
1511 playerRunningState = [[self currentRemote] playerRunningState];
1512 if (_needsPolling) {
1514 [refreshTimer invalidate];
1516 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1518 selector:@selector(timerUpdate)
1520 repeats:YES] retain];
1523 ITDebugLog(@"Connection successful.");
1525 } else if (result == 0) {
1526 ITDebugLog(@"Connection failed.");
1527 currentRemote = [remoteArray objectAtIndex:0];
1530 //Do something about the password being invalid
1531 ITDebugLog(@"Connection failed.");
1532 currentRemote = [remoteArray objectAtIndex:0];
1537 - (BOOL)disconnectFromServer
1539 ITDebugLog(@"Disconnecting from shared remote.");
1541 [currentRemote release];
1542 currentRemote = [remoteArray objectAtIndex:0];
1543 [networkController disconnect];
1545 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1546 [self applicationLaunched:nil];
1548 [self applicationTerminated:nil];
1556 - (void)checkForRemoteServer
1558 [self checkForRemoteServerAndConnectImmediately:NO];
1561 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1563 ITDebugLog(@"Checking for remote server.");
1564 if (!_checkingForServer) {
1565 if (!_serverCheckLock) {
1566 _serverCheckLock = [[NSLock alloc] init];
1568 [_serverCheckLock lock];
1569 _checkingForServer = YES;
1570 [_serverCheckLock unlock];
1571 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1575 - (void)runRemoteServerCheck:(id)sender
1577 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1578 ITDebugLog(@"Remote server check running.");
1579 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1580 ITDebugLog(@"Remote server found.");
1581 if ([sender boolValue]) {
1582 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1584 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1587 ITDebugLog(@"Remote server not found.");
1588 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1590 [_serverCheckLock lock];
1591 _checkingForServer = NO;
1592 [_serverCheckLock unlock];
1596 - (void)remoteServerFound:(id)sender
1598 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1599 [self invalidateStatusWindowUpdateTimer];
1600 [[StatusWindowController sharedController] showReconnectQueryWindow];
1604 - (void)remoteServerNotFound:(id)sender
1606 if (![[NetworkController sharedController] isConnectedToServer]) {
1607 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1611 - (void)networkError:(NSException *)exception
1613 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1614 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1615 //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);
1616 [self invalidateStatusWindowUpdateTimer];
1617 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1618 if ([self disconnectFromServer]) {
1619 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1620 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1622 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1629 /*if ([self connectToServer] == 0) {
1630 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1632 [self checkForRemoteServerAndConnectImmediately:YES];
1633 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1634 [[StatusWindow sharedWindow] vanish:self];
1635 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1638 - (void)cancelReconnect
1640 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1641 [[StatusWindow sharedWindow] vanish:self];
1642 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1645 /*************************************************************************/
1647 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1648 /*************************************************************************/
1650 - (void)applicationLaunched:(NSNotification *)note
1653 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1654 ITDebugLog(@"Remote application launched.");
1655 playerRunningState = ITMTRemotePlayerRunning;
1656 [[self currentRemote] begin];
1657 [self setLatestSongIdentifier:@""];
1659 if (_needsPolling) {
1660 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1662 selector:@selector(timerUpdate)
1664 repeats:YES] retain];
1666 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1667 if (![df boolForKey:@"UsePollingOnly"]) {
1668 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1670 [self setupHotKeys];
1673 [self networkError:localException];
1677 - (void)applicationTerminated:(NSNotification *)note
1680 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1681 ITDebugLog(@"Remote application terminated.");
1682 playerRunningState = ITMTRemotePlayerNotRunning;
1683 [[self currentRemote] halt];
1684 [refreshTimer invalidate];
1685 [refreshTimer release];
1687 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1688 [statusItem setEnabled:YES];
1689 [statusItem setToolTip:@"iTunes not running."];
1690 [self clearHotKeys];
1693 if ([df objectForKey:@"ShowPlayer"] != nil) {
1695 ITDebugLog(@"Setting up show player hot key.");
1696 hotKey = [[ITHotKey alloc] init];
1697 [hotKey setName:@"ShowPlayer"];
1698 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1699 [hotKey setTarget:self];
1700 [hotKey setAction:@selector(showPlayer)];
1701 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1705 [self networkError:localException];
1710 /*************************************************************************/
1712 #pragma mark NSApplication DELEGATE METHODS
1713 /*************************************************************************/
1715 - (void)applicationWillTerminate:(NSNotification *)note
1717 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1718 [networkController stopRemoteServerSearch];
1719 [self clearHotKeys];
1720 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1723 - (void)applicationDidBecomeActive:(NSNotification *)note
1725 //This appears to not work in 10.4
1726 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1727 [[MainController sharedController] showPreferences];
1731 /*************************************************************************/
1733 #pragma mark DEALLOCATION METHOD
1734 /*************************************************************************/
1738 [self applicationTerminated:nil];
1740 [statusItem release];
1741 [statusWindowController release];
1742 [menuController release];
1743 [networkController release];
1744 [_serverCheckLock release];