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 [[self currentRemote] currentSongElapsed];
145 //Turn on network stuff if needed
146 networkController = [[NetworkController alloc] init];
147 if ([df boolForKey:@"enableSharing"]) {
148 [self setServerStatus:YES];
149 } else if ([df boolForKey:@"useSharedPlayer"]) {
150 [self checkForRemoteServerAndConnectImmediately:YES];
153 //Setup for notification of the remote player launching or quitting
154 [[[NSWorkspace sharedWorkspace] notificationCenter]
156 selector:@selector(applicationTerminated:)
157 name:NSWorkspaceDidTerminateApplicationNotification
160 [[[NSWorkspace sharedWorkspace] notificationCenter]
162 selector:@selector(applicationLaunched:)
163 name:NSWorkspaceDidLaunchApplicationNotification
166 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
167 [[PreferencesController sharedPrefs] registerDefaults];
170 if ([df boolForKey:@"ITMTNoStatusItem"]) {
173 [StatusItemHack install];
174 statusItem = [[ITStatusItem alloc]
175 initWithStatusBar:[NSStatusBar systemStatusBar]
176 withLength:NSSquareStatusItemLength];
179 /*bling = [[MTBlingController alloc] init];
181 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
183 selector:@selector(blingTime)
185 repeats:YES] retain];*/
188 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
189 [self applicationLaunched:nil];
191 if ([df boolForKey:@"LaunchPlayerWithMT"])
194 [self applicationTerminated:nil];
197 [self networkError:localException];
200 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
201 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
203 if ([df boolForKey:@"audioscrobblerEnabled"]) {
204 if ([PreferencesController getKeychainItemPasswordForUser:[df stringForKey:@"audioscrobblerUser"]] != nil) {
205 [[AudioscrobblerController sharedController] attemptHandshake:NO];
209 [networkController startRemoteServerSearch];
211 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
213 bling = [[MTBlingController alloc] init];
215 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
217 selector:@selector(blingTime)
219 repeats:YES] retain];
227 - (ITMTRemote *)loadRemote
229 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
230 ITDebugLog(@"Gathering remotes.");
232 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
233 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
234 NSString *bundlePath;
236 while ( (bundlePath = [enumerator nextObject]) ) {
237 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
240 Class remoteClass = [remoteBundle principalClass];
242 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
243 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
244 id remote = [remoteClass remote];
245 ITDebugLog(@"Adding remote at path %@", bundlePath);
246 [remoteArray addObject:remote];
251 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
252 // if ( [remoteArray count] > 1 ) {
253 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
255 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
258 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
259 return [remoteArray objectAtIndex:0];
262 /*************************************************************************/
264 #pragma mark INSTANCE METHODS
265 /*************************************************************************/
267 /*- (void)startTimerInNewThread
269 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
270 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
271 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
273 selector:@selector(timerUpdate)
275 repeats:YES] retain];
277 ITDebugLog(@"Timer started.");
281 - (void)setBlingTime:(NSDate*)date
283 NSMutableDictionary *globalPrefs;
285 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
287 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
288 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
290 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
291 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
293 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
295 [globalPrefs release];
298 - (NSDate*)getBlingTime
301 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
306 NSDate *now = [NSDate date];
307 if (![self blingBling]) {
308 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
309 [self setBlingTime:now];
310 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
311 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
312 [self setBlingTime:[now addTimeInterval:-259200]];
314 NSMutableDictionary *globalPrefs;
316 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
317 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
318 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
320 [globalPrefs release];
324 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
326 [statusItem setEnabled:NO];
327 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
328 if ([refreshTimer isValid]) {
329 [refreshTimer invalidate];
330 [refreshTimer release];
333 [statusWindowController showRegistrationQueryWindow];
337 [statusItem setEnabled:YES];
338 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
339 if (_needsPolling && ![refreshTimer isValid]) {
340 [refreshTimer release];
341 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
343 selector:@selector(timerUpdate)
345 repeats:YES] retain];
349 [self setBlingTime:nil];
360 if ( ! ([bling checkDone] == 2475) ) {
367 - (BOOL)songIsPlaying
369 NSString *identifier = nil;
371 identifier = [[self currentRemote] playerStateUniqueIdentifier];
373 [self networkError:localException];
375 return ( ! ([identifier isEqualToString:@"0-0"]) );
378 - (BOOL)radioIsPlaying
380 ITMTRemotePlayerPlaylistClass class = nil;
382 class = [[self currentRemote] currentPlaylistClass];
384 [self networkError:localException];
386 return (class == ITMTRemotePlayerRadioPlaylist );
391 NSString *identifier = nil;
393 identifier = [[self currentRemote] playerStateUniqueIdentifier];
395 [self networkError:localException];
397 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
400 - (NSString *)latestSongIdentifier
402 return _latestSongIdentifier;
405 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
407 ITDebugLog(@"Setting latest song identifier:");
408 ITDebugLog(@" - Identifier: %@", newIdentifier);
409 [_latestSongIdentifier autorelease];
410 _latestSongIdentifier = [newIdentifier retain];
415 NSString *identifier = nil;
417 identifier = [[self currentRemote] playerStateUniqueIdentifier];
419 [self networkError:localException];
421 if (refreshTimer && identifier == nil) {
422 if ([statusItem isEnabled]) {
423 [statusItem setToolTip:@"iTunes not responding."];
425 [statusItem setEnabled:NO];
427 } else if (![statusItem isEnabled]) {
428 [statusItem setEnabled:YES];
429 [statusItem setToolTip:_toolTip];
433 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
434 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
435 if ([df boolForKey:@"runScripts"]) {
436 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
437 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
438 NSString *nextScript;
439 ITDebugLog(@"Running AppleScripts for song change.");
440 while ( (nextScript = [scriptsEnum nextObject]) ) {
442 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
443 ITDebugLog(@"Running script: %@", nextScript);
444 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
445 ITDebugLog(@"Error running script %@.", nextScript);
447 [currentScript release];
452 [statusItem setEnabled:NO];
455 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
457 if ([menuController rebuildSubmenus]) {
458 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
459 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
461 [self setLatestSongIdentifier:identifier];
462 //Create the tooltip for the status item
463 if ( [df boolForKey:@"showToolTip"] ) {
464 NSString *artist = [[self currentRemote] currentSongArtist];
465 NSString *title = [[self currentRemote] currentSongTitle];
466 ITDebugLog(@"Creating status item tooltip.");
468 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
472 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
474 [statusItem setToolTip:_toolTip];
476 [statusItem setToolTip:nil];
480 if ([df boolForKey:@"audioscrobblerEnabled"]) {
481 int length = [[self currentRemote] currentSongDuration];
482 if (_audioscrobblerTimer) {
483 [_audioscrobblerTimer invalidate];
486 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
489 _audioscrobblerTimer = nil;
492 [self networkError:localException];
495 [statusItem setEnabled:YES];
498 if ([networkController isConnectedToServer]) {
499 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
505 ITDebugLog(@"Menu clicked.");
507 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
509 if ([statusItem isEnabled]) {
510 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
512 [statusItem setEnabled:NO];
514 NSMenu *menu = [[NSMenu alloc] init];
515 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
516 [statusItem setMenu:[menu autorelease]];
519 } else if (![statusItem isEnabled]) {
520 [statusItem setEnabled:YES];
521 [statusItem setToolTip:_toolTip];
525 if ([networkController isConnectedToServer]) {
526 //Used the cached version
531 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
532 [statusItem setMenu:[menuController menu]];
534 [statusItem setMenu:[menuController menuForNoPlayer]];
537 [self networkError:localException];
541 - (void)trackChanged:(NSNotification *)note
543 //If we're running the timer, shut it off since we don't need it!
544 /*if (refreshTimer && [refreshTimer isValid]) {
545 ITDebugLog(@"Invalidating refresh timer.");
546 [refreshTimer invalidate];
547 [refreshTimer release];
551 if (![self songChanged]) {
554 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
555 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
556 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
558 [_lastTrackInfo release];
559 _lastTrackInfo = [[note userInfo] retain];
561 [self setLatestSongIdentifier:identifier];
562 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
563 if ([df boolForKey:@"runScripts"]) {
564 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
565 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
566 NSString *nextScript;
567 ITDebugLog(@"Running AppleScripts for song change.");
568 while ( (nextScript = [scriptsEnum nextObject]) ) {
570 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
571 ITDebugLog(@"Running script: %@", nextScript);
572 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
573 ITDebugLog(@"Error running script %@.", nextScript);
575 [currentScript release];
579 [statusItem setEnabled:NO];
582 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
584 if ([menuController rebuildSubmenus]) {
585 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
586 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
588 [self setLatestSongIdentifier:identifier];
589 //Create the tooltip for the status item
590 if ( [df boolForKey:@"showToolTip"] ) {
591 ITDebugLog(@"Creating status item tooltip.");
592 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
594 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
598 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
600 [statusItem setToolTip:_toolTip];
602 [statusItem setToolTip:nil];
606 if ([df boolForKey:@"audioscrobblerEnabled"]) {
607 int length = [[self currentRemote] currentSongDuration];
608 if (_audioscrobblerTimer) {
609 [_audioscrobblerTimer invalidate];
612 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
615 _audioscrobblerTimer = nil;
618 [self networkError:localException];
621 [statusItem setEnabled:YES];
623 if ([networkController isConnectedToServer]) {
624 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
628 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
630 int interval = [timer timeInterval];
632 _audioscrobblerTimer = nil;
633 ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
634 if ([df boolForKey:@"audioscrobblerEnabled"]) {
636 int elapsed = [[self currentRemote] currentSongPlayed];
637 if ((abs(elapsed - interval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
638 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
639 if (title && artist) {
640 ITDebugLog(@"Audioscrobbler: Submitting current track");
641 [[AudioscrobblerController sharedController] submitTrack:title
643 album:[[self currentRemote] currentSongAlbum]
644 length:[[self currentRemote] currentSongDuration]];
646 } else if (interval - elapsed > 0) {
647 ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", interval - elapsed);
648 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:(interval - elapsed) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
651 [self networkError:localException];
665 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
666 ITDebugLog(@"Play/Pause toggled");
667 if (state == ITMTRemotePlayerPlaying) {
668 [[self currentRemote] pause];
669 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
670 [[self currentRemote] pause];
671 [[self currentRemote] play];
673 [[self currentRemote] play];
676 [self networkError:localException];
686 ITDebugLog(@"Going to next song.");
688 [[self currentRemote] goToNextSong];
690 [self networkError:localException];
699 ITDebugLog(@"Going to previous song.");
701 [[self currentRemote] goToPreviousSong];
703 [self networkError:localException];
712 ITDebugLog(@"Fast forwarding.");
714 [[self currentRemote] forward];
716 [self networkError:localException];
725 ITDebugLog(@"Rewinding.");
727 [[self currentRemote] rewind];
729 [self networkError:localException];
736 - (void)selectPlaylistAtIndex:(int)index
738 ITDebugLog(@"Selecting playlist %i", index);
740 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
741 //[[self currentRemote] switchToPlaylistAtIndex:index];
743 [self networkError:localException];
750 - (void)selectSongAtIndex:(int)index
752 ITDebugLog(@"Selecting song %i", index);
754 [[self currentRemote] switchToSongAtIndex:index];
756 [self networkError:localException];
763 - (void)selectSongRating:(int)rating
765 ITDebugLog(@"Selecting song rating %i", rating);
767 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
769 [self networkError:localException];
776 - (void)selectEQPresetAtIndex:(int)index
778 ITDebugLog(@"Selecting EQ preset %i", index);
781 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
783 [[self currentRemote] switchToEQAtIndex:index];
786 [self networkError:localException];
793 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
795 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
797 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
799 [self networkError:localException];
801 ITDebugLog(@"Done making playlist");
806 ITDebugLog(@"Beginning show player.");
807 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
808 ITDebugLog(@"Showing player interface.");
810 [[self currentRemote] showPrimaryInterface];
812 [self networkError:localException];
815 ITDebugLog(@"Launching player.");
818 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
820 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
822 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
823 ITDebugLog(@"Error Launching Player");
826 [self networkError:localException];
829 ITDebugLog(@"Finished show player.");
832 - (void)showPreferences
834 ITDebugLog(@"Show preferences.");
835 [[PreferencesController sharedPrefs] showPrefsWindow:self];
838 - (void)showPreferencesAndClose
840 ITDebugLog(@"Show preferences.");
841 [[PreferencesController sharedPrefs] showPrefsWindow:self];
842 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
843 [[StatusWindow sharedWindow] vanish:self];
844 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
847 - (void)showTestWindow
849 [self showCurrentTrackInfo];
852 - (void)quitMenuTunes
854 ITDebugLog(@"Quitting MenuTunes.");
855 [NSApp terminate:self];
861 - (MenuController *)menuController
863 return menuController;
866 - (void)closePreferences
868 ITDebugLog(@"Preferences closed.");
869 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
874 - (ITMTRemote *)currentRemote
876 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
877 [self networkError:nil];
880 return currentRemote;
891 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
892 ITHotKey *nextHotKey;
893 ITDebugLog(@"Clearing hot keys.");
894 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
895 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
897 ITDebugLog(@"Done clearing hot keys.");
903 ITDebugLog(@"Setting up hot keys.");
905 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
909 if ([df objectForKey:@"PlayPause"] != nil) {
910 ITDebugLog(@"Setting up play pause hot key.");
911 hotKey = [[ITHotKey alloc] init];
912 [hotKey setName:@"PlayPause"];
913 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
914 [hotKey setTarget:self];
915 [hotKey setAction:@selector(playPause)];
916 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
919 if ([df objectForKey:@"NextTrack"] != nil) {
920 ITDebugLog(@"Setting up next track hot key.");
921 hotKey = [[ITHotKey alloc] init];
922 [hotKey setName:@"NextTrack"];
923 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
924 [hotKey setTarget:self];
925 [hotKey setAction:@selector(nextSong)];
926 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
929 if ([df objectForKey:@"PrevTrack"] != nil) {
930 ITDebugLog(@"Setting up previous track hot key.");
931 hotKey = [[ITHotKey alloc] init];
932 [hotKey setName:@"PrevTrack"];
933 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
934 [hotKey setTarget:self];
935 [hotKey setAction:@selector(prevSong)];
936 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
939 if ([df objectForKey:@"FastForward"] != nil) {
940 ITDebugLog(@"Setting up fast forward hot key.");
941 hotKey = [[ITHotKey alloc] init];
942 [hotKey setName:@"FastForward"];
943 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
944 [hotKey setTarget:self];
945 [hotKey setAction:@selector(fastForward)];
946 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
949 if ([df objectForKey:@"Rewind"] != nil) {
950 ITDebugLog(@"Setting up rewind hot key.");
951 hotKey = [[ITHotKey alloc] init];
952 [hotKey setName:@"Rewind"];
953 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
954 [hotKey setTarget:self];
955 [hotKey setAction:@selector(rewind)];
956 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
959 if ([df objectForKey:@"ShowPlayer"] != nil) {
960 ITDebugLog(@"Setting up show player hot key.");
961 hotKey = [[ITHotKey alloc] init];
962 [hotKey setName:@"ShowPlayer"];
963 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
964 [hotKey setTarget:self];
965 [hotKey setAction:@selector(showPlayer)];
966 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
969 if ([df objectForKey:@"TrackInfo"] != nil) {
970 ITDebugLog(@"Setting up track info hot key.");
971 hotKey = [[ITHotKey alloc] init];
972 [hotKey setName:@"TrackInfo"];
973 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
974 [hotKey setTarget:self];
975 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
976 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
979 if ([df objectForKey:@"UpcomingSongs"] != nil) {
980 ITDebugLog(@"Setting up upcoming songs hot key.");
981 hotKey = [[ITHotKey alloc] init];
982 [hotKey setName:@"UpcomingSongs"];
983 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
984 [hotKey setTarget:self];
985 [hotKey setAction:@selector(showUpcomingSongs)];
986 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
989 if ([df objectForKey:@"ToggleLoop"] != nil) {
990 ITDebugLog(@"Setting up toggle loop hot key.");
991 hotKey = [[ITHotKey alloc] init];
992 [hotKey setName:@"ToggleLoop"];
993 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
994 [hotKey setTarget:self];
995 [hotKey setAction:@selector(toggleLoop)];
996 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
999 if ([df objectForKey:@"ToggleShuffle"] != nil) {
1000 ITDebugLog(@"Setting up toggle shuffle hot key.");
1001 hotKey = [[ITHotKey alloc] init];
1002 [hotKey setName:@"ToggleShuffle"];
1003 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
1004 [hotKey setTarget:self];
1005 [hotKey setAction:@selector(toggleShuffle)];
1006 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1009 if ([df objectForKey:@"IncrementVolume"] != nil) {
1010 ITDebugLog(@"Setting up increment volume hot key.");
1011 hotKey = [[ITHotKey alloc] init];
1012 [hotKey setName:@"IncrementVolume"];
1013 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
1014 [hotKey setTarget:self];
1015 [hotKey setAction:@selector(incrementVolume)];
1016 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1019 if ([df objectForKey:@"DecrementVolume"] != nil) {
1020 ITDebugLog(@"Setting up decrement volume hot key.");
1021 hotKey = [[ITHotKey alloc] init];
1022 [hotKey setName:@"DecrementVolume"];
1023 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
1024 [hotKey setTarget:self];
1025 [hotKey setAction:@selector(decrementVolume)];
1026 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1029 if ([df objectForKey:@"IncrementRating"] != nil) {
1030 ITDebugLog(@"Setting up increment rating hot key.");
1031 hotKey = [[ITHotKey alloc] init];
1032 [hotKey setName:@"IncrementRating"];
1033 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
1034 [hotKey setTarget:self];
1035 [hotKey setAction:@selector(incrementRating)];
1036 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1039 if ([df objectForKey:@"DecrementRating"] != nil) {
1040 ITDebugLog(@"Setting up decrement rating hot key.");
1041 hotKey = [[ITHotKey alloc] init];
1042 [hotKey setName:@"DecrementRating"];
1043 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
1044 [hotKey setTarget:self];
1045 [hotKey setAction:@selector(decrementRating)];
1046 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1049 if ([df objectForKey:@"ToggleShufflability"] != nil) {
1050 ITDebugLog(@"Setting up toggle song shufflability hot key.");
1051 hotKey = [[ITHotKey alloc] init];
1052 [hotKey setName:@"ToggleShufflability"];
1053 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
1054 [hotKey setTarget:self];
1055 [hotKey setAction:@selector(toggleSongShufflable)];
1056 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1059 if ([df objectForKey:@"PopupMenu"] != nil) {
1060 ITDebugLog(@"Setting up popup menu hot key.");
1061 hotKey = [[ITHotKey alloc] init];
1062 [hotKey setName:@"PopupMenu"];
1063 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
1064 [hotKey setTarget:self];
1065 [hotKey setAction:@selector(popupMenu)];
1066 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1070 for (i = 0; i <= 5; i++) {
1071 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1072 if ([df objectForKey:curName] != nil) {
1073 ITDebugLog(@"Setting up set rating %i hot key.", i);
1074 hotKey = [[ITHotKey alloc] init];
1075 [hotKey setName:curName];
1076 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1077 [hotKey setTarget:self];
1078 [hotKey setAction:@selector(setRating:)];
1079 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1082 ITDebugLog(@"Finished setting up hot keys.");
1085 - (void)showCurrentTrackInfoHotKey
1087 //If we're already visible and the setting says so, vanish instead of displaying again.
1088 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1089 ITDebugLog(@"Track window is already visible, hiding track window.");
1090 [self invalidateStatusWindowUpdateTimer];
1091 [[StatusWindow sharedWindow] vanish:nil];
1094 [self showCurrentTrackInfo];
1097 - (void)showCurrentTrackInfo
1099 ITMTRemotePlayerSource source = 0;
1100 NSString *title = nil;
1101 NSString *album = nil;
1102 NSString *artist = nil;
1103 NSString *composer = nil;
1104 NSString *time = nil;
1105 NSString *track = nil;
1110 ITDebugLog(@"Showing track info status window.");
1113 source = [[self currentRemote] currentSource];
1114 title = [[self currentRemote] currentSongTitle];
1116 [self networkError:localException];
1120 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1121 NSSize oldSize, newSize;
1123 art = [[self currentRemote] currentSongAlbumArt];
1124 oldSize = [art size];
1125 if (oldSize.width > oldSize.height) {
1126 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1128 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1129 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1131 [self networkError:localException];
1135 if ( [df boolForKey:@"showAlbum"] ) {
1137 album = [[self currentRemote] currentSongAlbum];
1139 [self networkError:localException];
1143 if ( [df boolForKey:@"showArtist"] ) {
1145 artist = [[self currentRemote] currentSongArtist];
1147 [self networkError:localException];
1151 if ( [df boolForKey:@"showComposer"] ) {
1153 composer = [[self currentRemote] currentSongComposer];
1155 [self networkError:localException];
1159 if ( [df boolForKey:@"showTime"] ) {
1161 time = [NSString stringWithFormat:@"%@: %@ / %@",
1162 NSLocalizedString(@"time", @"Time"),
1163 [[self currentRemote] currentSongElapsed],
1164 [[self currentRemote] currentSongLength]];
1166 [self networkError:localException];
1168 _timeUpdateCount = 0;
1169 [self invalidateStatusWindowUpdateTimer];
1170 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1173 if ( [df boolForKey:@"showTrackNumber"] ) {
1178 trackNo = [[self currentRemote] currentSongTrack];
1179 trackCount = [[self currentRemote] currentAlbumTrackCount];
1181 [self networkError:localException];
1184 if ( (trackNo > 0) || (trackCount > 0) ) {
1185 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1186 @"Track", trackNo, @"of", trackCount];
1190 if ( [df boolForKey:@"showTrackRating"] ) {
1191 float currentRating = 0;
1194 currentRating = [[self currentRemote] currentSongRating];
1196 [self networkError:localException];
1199 if (currentRating >= 0.0) {
1200 rating = ( currentRating * 5 );
1204 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1206 playCount = [[self currentRemote] currentSongPlayCount];
1208 [self networkError:localException];
1212 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1214 ITDebugLog(@"Showing current track info status window.");
1215 [statusWindowController showSongInfoWindowWithSource:source
1227 - (void)updateTime:(NSTimer *)timer
1229 StatusWindow *sw = (StatusWindow *)[StatusWindow sharedWindow];
1231 if ([sw visibilityState] != ITWindowHiddenState) {
1232 NSString *time = nil, *length;
1234 length = [[self currentRemote] currentSongLength];
1236 time = [NSString stringWithFormat:@"%@: %@ / %@",
1237 NSLocalizedString(@"time", @"Time"),
1238 [[self currentRemote] currentSongElapsed],
1240 [[StatusWindowController sharedController] updateTime:time];
1243 [self networkError:localException];
1246 [self invalidateStatusWindowUpdateTimer];
1250 - (void)invalidateStatusWindowUpdateTimer
1252 if (_statusWindowUpdateTimer) {
1253 [_statusWindowUpdateTimer invalidate];
1254 _statusWindowUpdateTimer = nil;
1258 - (void)showUpcomingSongs
1262 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1264 [self networkError:localException];
1267 [self invalidateStatusWindowUpdateTimer];
1269 ITDebugLog(@"Showing upcoming songs status window.");
1272 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1273 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1274 int curTrack = [[self currentRemote] currentSongIndex];
1277 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1278 if ([[self currentRemote] songEnabledAtIndex:i]) {
1279 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1281 numSongsInAdvance++;
1285 if ([songList count] == 0) {
1286 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1289 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1291 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1294 [self networkError:localException];
1303 NSMenu *menu = [statusItem menu];
1304 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1309 - (void)incrementVolume
1312 float volume = [[self currentRemote] volume];
1313 float dispVol = volume;
1314 ITDebugLog(@"Incrementing volume.");
1323 ITDebugLog(@"Setting volume to %f", volume);
1324 [[self currentRemote] setVolume:volume];
1326 // Show volume status window
1327 [self invalidateStatusWindowUpdateTimer];
1328 [statusWindowController showVolumeWindowWithLevel:dispVol];
1330 [self networkError:localException];
1334 - (void)decrementVolume
1337 float volume = [[self currentRemote] volume];
1338 float dispVol = volume;
1339 ITDebugLog(@"Decrementing volume.");
1348 ITDebugLog(@"Setting volume to %f", volume);
1349 [[self currentRemote] setVolume:volume];
1351 //Show volume status window
1352 [self invalidateStatusWindowUpdateTimer];
1353 [statusWindowController showVolumeWindowWithLevel:dispVol];
1355 [self networkError:localException];
1359 - (void)incrementRating
1362 float rating = [[self currentRemote] currentSongRating];
1363 ITDebugLog(@"Incrementing 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)decrementRating
1388 float rating = [[self currentRemote] currentSongRating];
1389 ITDebugLog(@"Decrementing rating.");
1391 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1392 ITDebugLog(@"No song playing, rating change aborted.");
1400 ITDebugLog(@"Setting rating to %f", rating);
1401 [[self currentRemote] setCurrentSongRating:rating];
1403 //Show rating status window
1404 [self invalidateStatusWindowUpdateTimer];
1405 [statusWindowController showRatingWindowWithRating:rating];
1407 [self networkError:localException];
1411 - (void)setRating:(ITHotKey *)sender
1413 if ([self songIsPlaying]) {
1414 int stars = [[sender name] characterAtIndex:9] - 48;
1415 [self selectSongRating:stars * 20];
1416 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1423 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1424 ITDebugLog(@"Toggling repeat mode.");
1425 switch (repeatMode) {
1426 case ITMTRemotePlayerRepeatOff:
1427 repeatMode = ITMTRemotePlayerRepeatAll;
1429 case ITMTRemotePlayerRepeatAll:
1430 repeatMode = ITMTRemotePlayerRepeatOne;
1432 case ITMTRemotePlayerRepeatOne:
1433 repeatMode = ITMTRemotePlayerRepeatOff;
1436 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1437 [[self currentRemote] setRepeatMode:repeatMode];
1439 //Show loop status window
1440 [self invalidateStatusWindowUpdateTimer];
1441 [statusWindowController showRepeatWindowWithMode:repeatMode];
1443 [self networkError:localException];
1447 - (void)toggleShuffle
1450 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1451 ITDebugLog(@"Toggling shuffle mode.");
1452 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1453 //Show shuffle status window
1454 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1455 [self invalidateStatusWindowUpdateTimer];
1456 [statusWindowController showShuffleWindow:newShuffleEnabled];
1458 [self networkError:localException];
1462 - (void)toggleSongShufflable
1464 if ([self songIsPlaying]) {
1466 BOOL flag = ![[self currentRemote] currentSongShufflable];
1467 ITDebugLog(@"Toggling shufflability.");
1468 [[self currentRemote] setCurrentSongShufflable:flag];
1469 //Show song shufflability status window
1470 [self invalidateStatusWindowUpdateTimer];
1471 [statusWindowController showSongShufflabilityWindow:flag];
1473 [self networkError:localException];
1478 - (void)registerNowOK
1480 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1481 [[StatusWindow sharedWindow] vanish:self];
1482 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1487 - (void)registerNowCancel
1489 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1490 [[StatusWindow sharedWindow] vanish:self];
1491 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1493 [NSApp terminate:self];
1496 /*************************************************************************/
1498 #pragma mark NETWORK HANDLERS
1499 /*************************************************************************/
1501 - (void)setServerStatus:(BOOL)newStatus
1505 [networkController setServerStatus:YES];
1508 [networkController setServerStatus:NO];
1512 - (int)connectToServer
1515 ITDebugLog(@"Attempting to connect to shared remote.");
1516 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1519 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1520 currentRemote = [[[networkController networkObject] remote] retain];
1522 [self setupHotKeys];
1523 //playerRunningState = ITMTRemotePlayerRunning;
1524 playerRunningState = [[self currentRemote] playerRunningState];
1525 if (_needsPolling) {
1527 [refreshTimer invalidate];
1531 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1533 selector:@selector(timerUpdate)
1535 repeats:YES] retain];
1538 ITDebugLog(@"Connection successful.");
1540 } else if (result == 0) {
1541 ITDebugLog(@"Connection failed.");
1542 currentRemote = [remoteArray objectAtIndex:0];
1545 //Do something about the password being invalid
1546 ITDebugLog(@"Connection failed.");
1547 currentRemote = [remoteArray objectAtIndex:0];
1552 - (BOOL)disconnectFromServer
1554 ITDebugLog(@"Disconnecting from shared remote.");
1556 [currentRemote release];
1557 currentRemote = [remoteArray objectAtIndex:0];
1558 [networkController disconnect];
1560 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1562 [self applicationLaunched:nil];
1564 [self applicationTerminated:nil];
1573 - (void)checkForRemoteServer
1575 [self checkForRemoteServerAndConnectImmediately:NO];
1578 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1580 ITDebugLog(@"Checking for remote server.");
1581 if (!_checkingForServer) {
1582 if (!_serverCheckLock) {
1583 _serverCheckLock = [[NSLock alloc] init];
1585 [_serverCheckLock lock];
1586 _checkingForServer = YES;
1587 [_serverCheckLock unlock];
1588 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1592 - (void)runRemoteServerCheck:(id)sender
1594 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1595 ITDebugLog(@"Remote server check running.");
1596 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1597 ITDebugLog(@"Remote server found.");
1598 if ([sender boolValue]) {
1599 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1601 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1604 ITDebugLog(@"Remote server not found.");
1605 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1607 [_serverCheckLock lock];
1608 _checkingForServer = NO;
1609 [_serverCheckLock unlock];
1613 - (void)remoteServerFound:(id)sender
1615 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1616 [self invalidateStatusWindowUpdateTimer];
1617 [[StatusWindowController sharedController] showReconnectQueryWindow];
1621 - (void)remoteServerNotFound:(id)sender
1623 if (![[NetworkController sharedController] isConnectedToServer]) {
1624 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1628 - (void)networkError:(NSException *)exception
1630 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1631 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1632 //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);
1633 [self invalidateStatusWindowUpdateTimer];
1634 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1635 if ([self disconnectFromServer]) {
1636 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1637 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1639 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1646 /*if ([self connectToServer] == 0) {
1647 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1649 [self checkForRemoteServerAndConnectImmediately:YES];
1650 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1651 [[StatusWindow sharedWindow] vanish:self];
1652 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1655 - (void)cancelReconnect
1657 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1658 [[StatusWindow sharedWindow] vanish:self];
1659 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1662 /*************************************************************************/
1664 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1665 /*************************************************************************/
1667 - (void)applicationLaunched:(NSNotification *)note
1670 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1671 ITDebugLog(@"Remote application launched.");
1672 playerRunningState = ITMTRemotePlayerRunning;
1673 [[self currentRemote] begin];
1674 [self setLatestSongIdentifier:@""];
1676 if (_needsPolling) {
1677 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1679 selector:@selector(timerUpdate)
1681 repeats:YES] retain];
1683 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1684 if (![df boolForKey:@"UsePollingOnly"]) {
1685 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1687 [self setupHotKeys];
1690 [self networkError:localException];
1694 - (void)applicationTerminated:(NSNotification *)note
1697 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1698 ITDebugLog(@"Remote application terminated.");
1699 playerRunningState = ITMTRemotePlayerNotRunning;
1700 [[self currentRemote] halt];
1701 [refreshTimer invalidate];
1702 [refreshTimer release];
1704 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1705 [statusItem setEnabled:YES];
1706 [statusItem setToolTip:@"iTunes not running."];
1707 [self clearHotKeys];
1710 if ([df objectForKey:@"ShowPlayer"] != nil) {
1712 ITDebugLog(@"Setting up show player hot key.");
1713 hotKey = [[ITHotKey alloc] init];
1714 [hotKey setName:@"ShowPlayer"];
1715 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1716 [hotKey setTarget:self];
1717 [hotKey setAction:@selector(showPlayer)];
1718 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1722 [self networkError:localException];
1727 /*************************************************************************/
1729 #pragma mark NSApplication DELEGATE METHODS
1730 /*************************************************************************/
1732 - (void)applicationWillTerminate:(NSNotification *)note
1734 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1735 [networkController stopRemoteServerSearch];
1736 [self clearHotKeys];
1737 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1740 - (void)applicationDidBecomeActive:(NSNotification *)note
1742 //This appears to not work in 10.4
1743 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1744 [[MainController sharedController] showPreferences];
1748 /*************************************************************************/
1750 #pragma mark DEALLOCATION METHOD
1751 /*************************************************************************/
1755 [self applicationTerminated:nil];
1757 [statusItem release];
1758 [statusWindowController release];
1759 [menuController release];
1760 [networkController release];
1761 [_serverCheckLock release];