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 if ([df boolForKey:@"audioscrobblerEnabled"]) {
202 [[AudioscrobblerController sharedController] attemptHandshake:NO];
205 [networkController startRemoteServerSearch];
207 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
209 bling = [[MTBlingController alloc] init];
211 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
213 selector:@selector(blingTime)
215 repeats:YES] retain];
223 - (ITMTRemote *)loadRemote
225 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
226 ITDebugLog(@"Gathering remotes.");
228 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
229 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
230 NSString *bundlePath;
232 while ( (bundlePath = [enumerator nextObject]) ) {
233 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
236 Class remoteClass = [remoteBundle principalClass];
238 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
239 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
240 id remote = [remoteClass remote];
241 ITDebugLog(@"Adding remote at path %@", bundlePath);
242 [remoteArray addObject:remote];
247 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
248 // if ( [remoteArray count] > 1 ) {
249 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
251 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
254 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
255 return [remoteArray objectAtIndex:0];
258 /*************************************************************************/
260 #pragma mark INSTANCE METHODS
261 /*************************************************************************/
263 /*- (void)startTimerInNewThread
265 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
266 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
267 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
269 selector:@selector(timerUpdate)
271 repeats:YES] retain];
273 ITDebugLog(@"Timer started.");
277 - (void)setBlingTime:(NSDate*)date
279 NSMutableDictionary *globalPrefs;
281 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
283 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
284 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
286 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
287 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
289 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
291 [globalPrefs release];
294 - (NSDate*)getBlingTime
297 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
302 NSDate *now = [NSDate date];
303 if (![self blingBling]) {
304 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
305 [self setBlingTime:now];
306 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
307 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
308 [self setBlingTime:[now addTimeInterval:-259200]];
310 NSMutableDictionary *globalPrefs;
312 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
313 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
314 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
316 [globalPrefs release];
320 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
322 [statusItem setEnabled:NO];
323 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
324 if ([refreshTimer isValid]) {
325 [refreshTimer invalidate];
326 [refreshTimer release];
329 [statusWindowController showRegistrationQueryWindow];
333 [statusItem setEnabled:YES];
334 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
335 if (_needsPolling && ![refreshTimer isValid]) {
336 [refreshTimer release];
337 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
339 selector:@selector(timerUpdate)
341 repeats:YES] retain];
345 [self setBlingTime:nil];
356 if ( ! ([bling checkDone] == 2475) ) {
363 - (BOOL)songIsPlaying
365 NSString *identifier = nil;
367 identifier = [[self currentRemote] playerStateUniqueIdentifier];
369 [self networkError:localException];
371 return ( ! ([identifier isEqualToString:@"0-0"]) );
374 - (BOOL)radioIsPlaying
376 ITMTRemotePlayerPlaylistClass class = nil;
378 class = [[self currentRemote] currentPlaylistClass];
380 [self networkError:localException];
382 return (class == ITMTRemotePlayerRadioPlaylist );
387 NSString *identifier = nil;
389 identifier = [[self currentRemote] playerStateUniqueIdentifier];
391 [self networkError:localException];
393 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
396 - (NSString *)latestSongIdentifier
398 return _latestSongIdentifier;
401 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
403 ITDebugLog(@"Setting latest song identifier:");
404 ITDebugLog(@" - Identifier: %@", newIdentifier);
405 [_latestSongIdentifier autorelease];
406 _latestSongIdentifier = [newIdentifier retain];
411 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
412 if (refreshTimer && identifier == nil) {
413 if ([statusItem isEnabled]) {
414 [statusItem setToolTip:@"iTunes not responding."];
416 [statusItem setEnabled:NO];
418 } else if (![statusItem isEnabled]) {
419 [statusItem setEnabled:YES];
420 [statusItem setToolTip:_toolTip];
424 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
425 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
426 if ([df boolForKey:@"runScripts"]) {
427 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
428 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
429 NSString *nextScript;
430 ITDebugLog(@"Running AppleScripts for song change.");
431 while ( (nextScript = [scriptsEnum nextObject]) ) {
433 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
434 ITDebugLog(@"Running script: %@", nextScript);
435 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
436 ITDebugLog(@"Error running script %@.", nextScript);
438 [currentScript release];
443 [statusItem setEnabled:NO];
446 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
448 if ([menuController rebuildSubmenus]) {
449 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
450 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
452 [self setLatestSongIdentifier:identifier];
453 //Create the tooltip for the status item
454 if ( [df boolForKey:@"showToolTip"] ) {
455 NSString *artist = [[self currentRemote] currentSongArtist];
456 NSString *title = [[self currentRemote] currentSongTitle];
457 ITDebugLog(@"Creating status item tooltip.");
459 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
463 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
465 [statusItem setToolTip:_toolTip];
467 [statusItem setToolTip:nil];
471 if ([df boolForKey:@"audioscrobblerEnabled"]) {
472 int length = [[self currentRemote] currentSongDuration];
473 if (_audioscrobblerTimer) {
474 [_audioscrobblerTimer invalidate];
477 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
480 _audioscrobblerTimer = nil;
483 [self networkError:localException];
486 [statusItem setEnabled:YES];
489 if ([networkController isConnectedToServer]) {
490 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
496 ITDebugLog(@"Menu clicked.");
498 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
500 if ([statusItem isEnabled]) {
501 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
503 [statusItem setEnabled:NO];
505 NSMenu *menu = [[NSMenu alloc] init];
506 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
507 [statusItem setMenu:[menu autorelease]];
510 } else if (![statusItem isEnabled]) {
511 [statusItem setEnabled:YES];
512 [statusItem setToolTip:_toolTip];
516 if ([networkController isConnectedToServer]) {
517 //Used the cached version
522 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
523 [statusItem setMenu:[menuController menu]];
525 [statusItem setMenu:[menuController menuForNoPlayer]];
528 [self networkError:localException];
532 - (void)trackChanged:(NSNotification *)note
534 //If we're running the timer, shut it off since we don't need it!
535 /*if (refreshTimer && [refreshTimer isValid]) {
536 ITDebugLog(@"Invalidating refresh timer.");
537 [refreshTimer invalidate];
538 [refreshTimer release];
542 if (![self songChanged]) {
545 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
546 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
547 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
549 [_lastTrackInfo release];
550 _lastTrackInfo = [[note userInfo] retain];
552 [self setLatestSongIdentifier:identifier];
553 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
554 if ([df boolForKey:@"runScripts"]) {
555 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
556 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
557 NSString *nextScript;
558 ITDebugLog(@"Running AppleScripts for song change.");
559 while ( (nextScript = [scriptsEnum nextObject]) ) {
561 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
562 ITDebugLog(@"Running script: %@", nextScript);
563 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
564 ITDebugLog(@"Error running script %@.", nextScript);
566 [currentScript release];
570 [statusItem setEnabled:NO];
573 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
575 if ([menuController rebuildSubmenus]) {
576 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
577 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
579 [self setLatestSongIdentifier:identifier];
580 //Create the tooltip for the status item
581 if ( [df boolForKey:@"showToolTip"] ) {
582 ITDebugLog(@"Creating status item tooltip.");
583 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
585 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
589 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
591 [statusItem setToolTip:_toolTip];
593 [statusItem setToolTip:nil];
597 if ([df boolForKey:@"audioscrobblerEnabled"]) {
598 int length = [[self currentRemote] currentSongDuration];
599 if (_audioscrobblerTimer) {
600 [_audioscrobblerTimer invalidate];
603 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
606 _audioscrobblerTimer = nil;
609 [self networkError:localException];
612 [statusItem setEnabled:YES];
614 if ([networkController isConnectedToServer]) {
615 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
619 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
621 int interval = [timer timeInterval];
623 _audioscrobblerTimer = nil;
624 ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
625 if ([df boolForKey:@"audioscrobblerEnabled"]) {
627 int elapsed = [[self currentRemote] currentSongPlayed];
628 if ((abs(elapsed - interval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
629 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
630 if (title && artist) {
631 ITDebugLog(@"Audioscrobbler: Submitting current track");
632 [[AudioscrobblerController sharedController] submitTrack:title
634 album:[[self currentRemote] currentSongAlbum]
635 length:[[self currentRemote] currentSongDuration]];
637 } else if (interval - elapsed > 0) {
638 ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", interval - elapsed);
639 _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:(interval - elapsed) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:YES];
642 [self networkError:localException];
656 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
657 ITDebugLog(@"Play/Pause toggled");
658 if (state == ITMTRemotePlayerPlaying) {
659 [[self currentRemote] pause];
660 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
661 [[self currentRemote] pause];
662 [[self currentRemote] play];
664 [[self currentRemote] play];
667 [self networkError:localException];
677 ITDebugLog(@"Going to next song.");
679 [[self currentRemote] goToNextSong];
681 [self networkError:localException];
690 ITDebugLog(@"Going to previous song.");
692 [[self currentRemote] goToPreviousSong];
694 [self networkError:localException];
703 ITDebugLog(@"Fast forwarding.");
705 [[self currentRemote] forward];
707 [self networkError:localException];
716 ITDebugLog(@"Rewinding.");
718 [[self currentRemote] rewind];
720 [self networkError:localException];
727 - (void)selectPlaylistAtIndex:(int)index
729 ITDebugLog(@"Selecting playlist %i", index);
731 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
732 //[[self currentRemote] switchToPlaylistAtIndex:index];
734 [self networkError:localException];
741 - (void)selectSongAtIndex:(int)index
743 ITDebugLog(@"Selecting song %i", index);
745 [[self currentRemote] switchToSongAtIndex:index];
747 [self networkError:localException];
754 - (void)selectSongRating:(int)rating
756 ITDebugLog(@"Selecting song rating %i", rating);
758 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
760 [self networkError:localException];
767 - (void)selectEQPresetAtIndex:(int)index
769 ITDebugLog(@"Selecting EQ preset %i", index);
772 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
774 [[self currentRemote] switchToEQAtIndex:index];
777 [self networkError:localException];
784 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
786 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
788 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
790 [self networkError:localException];
792 ITDebugLog(@"Done making playlist");
797 ITDebugLog(@"Beginning show player.");
798 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
799 ITDebugLog(@"Showing player interface.");
801 [[self currentRemote] showPrimaryInterface];
803 [self networkError:localException];
806 ITDebugLog(@"Launching player.");
809 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
811 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
813 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
814 ITDebugLog(@"Error Launching Player");
817 [self networkError:localException];
820 ITDebugLog(@"Finished show player.");
823 - (void)showPreferences
825 ITDebugLog(@"Show preferences.");
826 [[PreferencesController sharedPrefs] showPrefsWindow:self];
829 - (void)showPreferencesAndClose
831 ITDebugLog(@"Show preferences.");
832 [[PreferencesController sharedPrefs] showPrefsWindow:self];
833 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
834 [[StatusWindow sharedWindow] vanish:self];
835 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
838 - (void)showTestWindow
840 [self showCurrentTrackInfo];
843 - (void)quitMenuTunes
845 ITDebugLog(@"Quitting MenuTunes.");
846 [NSApp terminate:self];
852 - (MenuController *)menuController
854 return menuController;
857 - (void)closePreferences
859 ITDebugLog(@"Preferences closed.");
860 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
865 - (ITMTRemote *)currentRemote
867 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
868 [self networkError:nil];
871 return currentRemote;
882 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
883 ITHotKey *nextHotKey;
884 ITDebugLog(@"Clearing hot keys.");
885 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
886 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
888 ITDebugLog(@"Done clearing hot keys.");
894 ITDebugLog(@"Setting up hot keys.");
896 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
900 if ([df objectForKey:@"PlayPause"] != nil) {
901 ITDebugLog(@"Setting up play pause hot key.");
902 hotKey = [[ITHotKey alloc] init];
903 [hotKey setName:@"PlayPause"];
904 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
905 [hotKey setTarget:self];
906 [hotKey setAction:@selector(playPause)];
907 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
910 if ([df objectForKey:@"NextTrack"] != nil) {
911 ITDebugLog(@"Setting up next track hot key.");
912 hotKey = [[ITHotKey alloc] init];
913 [hotKey setName:@"NextTrack"];
914 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
915 [hotKey setTarget:self];
916 [hotKey setAction:@selector(nextSong)];
917 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
920 if ([df objectForKey:@"PrevTrack"] != nil) {
921 ITDebugLog(@"Setting up previous track hot key.");
922 hotKey = [[ITHotKey alloc] init];
923 [hotKey setName:@"PrevTrack"];
924 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
925 [hotKey setTarget:self];
926 [hotKey setAction:@selector(prevSong)];
927 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
930 if ([df objectForKey:@"FastForward"] != nil) {
931 ITDebugLog(@"Setting up fast forward hot key.");
932 hotKey = [[ITHotKey alloc] init];
933 [hotKey setName:@"FastForward"];
934 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
935 [hotKey setTarget:self];
936 [hotKey setAction:@selector(fastForward)];
937 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
940 if ([df objectForKey:@"Rewind"] != nil) {
941 ITDebugLog(@"Setting up rewind hot key.");
942 hotKey = [[ITHotKey alloc] init];
943 [hotKey setName:@"Rewind"];
944 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
945 [hotKey setTarget:self];
946 [hotKey setAction:@selector(rewind)];
947 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
950 if ([df objectForKey:@"ShowPlayer"] != nil) {
951 ITDebugLog(@"Setting up show player hot key.");
952 hotKey = [[ITHotKey alloc] init];
953 [hotKey setName:@"ShowPlayer"];
954 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
955 [hotKey setTarget:self];
956 [hotKey setAction:@selector(showPlayer)];
957 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
960 if ([df objectForKey:@"TrackInfo"] != nil) {
961 ITDebugLog(@"Setting up track info hot key.");
962 hotKey = [[ITHotKey alloc] init];
963 [hotKey setName:@"TrackInfo"];
964 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
965 [hotKey setTarget:self];
966 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
967 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
970 if ([df objectForKey:@"UpcomingSongs"] != nil) {
971 ITDebugLog(@"Setting up upcoming songs hot key.");
972 hotKey = [[ITHotKey alloc] init];
973 [hotKey setName:@"UpcomingSongs"];
974 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
975 [hotKey setTarget:self];
976 [hotKey setAction:@selector(showUpcomingSongs)];
977 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
980 if ([df objectForKey:@"ToggleLoop"] != nil) {
981 ITDebugLog(@"Setting up toggle loop hot key.");
982 hotKey = [[ITHotKey alloc] init];
983 [hotKey setName:@"ToggleLoop"];
984 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
985 [hotKey setTarget:self];
986 [hotKey setAction:@selector(toggleLoop)];
987 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
990 if ([df objectForKey:@"ToggleShuffle"] != nil) {
991 ITDebugLog(@"Setting up toggle shuffle hot key.");
992 hotKey = [[ITHotKey alloc] init];
993 [hotKey setName:@"ToggleShuffle"];
994 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
995 [hotKey setTarget:self];
996 [hotKey setAction:@selector(toggleShuffle)];
997 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1000 if ([df objectForKey:@"IncrementVolume"] != nil) {
1001 ITDebugLog(@"Setting up increment volume hot key.");
1002 hotKey = [[ITHotKey alloc] init];
1003 [hotKey setName:@"IncrementVolume"];
1004 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
1005 [hotKey setTarget:self];
1006 [hotKey setAction:@selector(incrementVolume)];
1007 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1010 if ([df objectForKey:@"DecrementVolume"] != nil) {
1011 ITDebugLog(@"Setting up decrement volume hot key.");
1012 hotKey = [[ITHotKey alloc] init];
1013 [hotKey setName:@"DecrementVolume"];
1014 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
1015 [hotKey setTarget:self];
1016 [hotKey setAction:@selector(decrementVolume)];
1017 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1020 if ([df objectForKey:@"IncrementRating"] != nil) {
1021 ITDebugLog(@"Setting up increment rating hot key.");
1022 hotKey = [[ITHotKey alloc] init];
1023 [hotKey setName:@"IncrementRating"];
1024 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
1025 [hotKey setTarget:self];
1026 [hotKey setAction:@selector(incrementRating)];
1027 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1030 if ([df objectForKey:@"DecrementRating"] != nil) {
1031 ITDebugLog(@"Setting up decrement rating hot key.");
1032 hotKey = [[ITHotKey alloc] init];
1033 [hotKey setName:@"DecrementRating"];
1034 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
1035 [hotKey setTarget:self];
1036 [hotKey setAction:@selector(decrementRating)];
1037 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1040 if ([df objectForKey:@"ToggleShufflability"] != nil) {
1041 ITDebugLog(@"Setting up toggle song shufflability hot key.");
1042 hotKey = [[ITHotKey alloc] init];
1043 [hotKey setName:@"ToggleShufflability"];
1044 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
1045 [hotKey setTarget:self];
1046 [hotKey setAction:@selector(toggleSongShufflable)];
1047 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1050 if ([df objectForKey:@"PopupMenu"] != nil) {
1051 ITDebugLog(@"Setting up popup menu hot key.");
1052 hotKey = [[ITHotKey alloc] init];
1053 [hotKey setName:@"PopupMenu"];
1054 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
1055 [hotKey setTarget:self];
1056 [hotKey setAction:@selector(popupMenu)];
1057 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1061 for (i = 0; i <= 5; i++) {
1062 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1063 if ([df objectForKey:curName] != nil) {
1064 ITDebugLog(@"Setting up set rating %i hot key.", i);
1065 hotKey = [[ITHotKey alloc] init];
1066 [hotKey setName:curName];
1067 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1068 [hotKey setTarget:self];
1069 [hotKey setAction:@selector(setRating:)];
1070 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1073 ITDebugLog(@"Finished setting up hot keys.");
1076 - (void)showCurrentTrackInfoHotKey
1078 //If we're already visible and the setting says so, vanish instead of displaying again.
1079 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1080 ITDebugLog(@"Track window is already visible, hiding track window.");
1081 [self invalidateStatusWindowUpdateTimer];
1082 [[StatusWindow sharedWindow] vanish:nil];
1085 [self showCurrentTrackInfo];
1088 - (void)showCurrentTrackInfo
1090 ITMTRemotePlayerSource source = 0;
1091 NSString *title = nil;
1092 NSString *album = nil;
1093 NSString *artist = nil;
1094 NSString *composer = nil;
1095 NSString *time = nil;
1096 NSString *track = nil;
1101 ITDebugLog(@"Showing track info status window.");
1104 source = [[self currentRemote] currentSource];
1105 title = [[self currentRemote] currentSongTitle];
1107 [self networkError:localException];
1111 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1112 NSSize oldSize, newSize;
1114 art = [[self currentRemote] currentSongAlbumArt];
1115 oldSize = [art size];
1116 if (oldSize.width > oldSize.height) {
1117 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1119 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1120 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1122 [self networkError:localException];
1126 if ( [df boolForKey:@"showAlbum"] ) {
1128 album = [[self currentRemote] currentSongAlbum];
1130 [self networkError:localException];
1134 if ( [df boolForKey:@"showArtist"] ) {
1136 artist = [[self currentRemote] currentSongArtist];
1138 [self networkError:localException];
1142 if ( [df boolForKey:@"showComposer"] ) {
1144 composer = [[self currentRemote] currentSongComposer];
1146 [self networkError:localException];
1150 if ( [df boolForKey:@"showTime"] ) {
1152 time = [NSString stringWithFormat:@"%@: %@ / %@",
1153 NSLocalizedString(@"time", @"Time"),
1154 [[self currentRemote] currentSongElapsed],
1155 [[self currentRemote] currentSongLength]];
1157 [self networkError:localException];
1159 _timeUpdateCount = 0;
1160 [self invalidateStatusWindowUpdateTimer];
1161 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1164 if ( [df boolForKey:@"showTrackNumber"] ) {
1169 trackNo = [[self currentRemote] currentSongTrack];
1170 trackCount = [[self currentRemote] currentAlbumTrackCount];
1172 [self networkError:localException];
1175 if ( (trackNo > 0) || (trackCount > 0) ) {
1176 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1177 @"Track", trackNo, @"of", trackCount];
1181 if ( [df boolForKey:@"showTrackRating"] ) {
1182 float currentRating = 0;
1185 currentRating = [[self currentRemote] currentSongRating];
1187 [self networkError:localException];
1190 if (currentRating >= 0.0) {
1191 rating = ( currentRating * 5 );
1195 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1197 playCount = [[self currentRemote] currentSongPlayCount];
1199 [self networkError:localException];
1203 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1205 ITDebugLog(@"Showing current track info status window.");
1206 [statusWindowController showSongInfoWindowWithSource:source
1218 - (void)updateTime:(NSTimer *)timer
1220 StatusWindow *sw = [StatusWindow sharedWindow];
1222 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1223 NSString *time = nil, *length;
1225 length = [[self currentRemote] currentSongLength];
1227 time = [NSString stringWithFormat:@"%@: %@ / %@",
1228 NSLocalizedString(@"time", @"Time"),
1229 [[self currentRemote] currentSongElapsed],
1231 [[StatusWindowController sharedController] updateTime:time];
1234 [self networkError:localException];
1237 [self invalidateStatusWindowUpdateTimer];
1241 - (void)invalidateStatusWindowUpdateTimer
1243 if (_statusWindowUpdateTimer) {
1244 [_statusWindowUpdateTimer invalidate];
1245 _statusWindowUpdateTimer = nil;
1249 - (void)showUpcomingSongs
1253 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1255 [self networkError:localException];
1258 [self invalidateStatusWindowUpdateTimer];
1260 ITDebugLog(@"Showing upcoming songs status window.");
1263 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1264 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1265 int curTrack = [[self currentRemote] currentSongIndex];
1268 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1269 if ([[self currentRemote] songEnabledAtIndex:i]) {
1270 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1272 numSongsInAdvance++;
1276 if ([songList count] == 0) {
1277 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1280 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1282 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1285 [self networkError:localException];
1294 NSMenu *menu = [statusItem menu];
1295 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1300 - (void)incrementVolume
1303 float volume = [[self currentRemote] volume];
1304 float dispVol = volume;
1305 ITDebugLog(@"Incrementing volume.");
1314 ITDebugLog(@"Setting volume to %f", volume);
1315 [[self currentRemote] setVolume:volume];
1317 // Show volume status window
1318 [self invalidateStatusWindowUpdateTimer];
1319 [statusWindowController showVolumeWindowWithLevel:dispVol];
1321 [self networkError:localException];
1325 - (void)decrementVolume
1328 float volume = [[self currentRemote] volume];
1329 float dispVol = volume;
1330 ITDebugLog(@"Decrementing volume.");
1339 ITDebugLog(@"Setting volume to %f", volume);
1340 [[self currentRemote] setVolume:volume];
1342 //Show volume status window
1343 [self invalidateStatusWindowUpdateTimer];
1344 [statusWindowController showVolumeWindowWithLevel:dispVol];
1346 [self networkError:localException];
1350 - (void)incrementRating
1353 float rating = [[self currentRemote] currentSongRating];
1354 ITDebugLog(@"Incrementing rating.");
1356 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1357 ITDebugLog(@"No song playing, rating change aborted.");
1365 ITDebugLog(@"Setting rating to %f", rating);
1366 [[self currentRemote] setCurrentSongRating:rating];
1368 //Show rating status window
1369 [self invalidateStatusWindowUpdateTimer];
1370 [statusWindowController showRatingWindowWithRating:rating];
1372 [self networkError:localException];
1376 - (void)decrementRating
1379 float rating = [[self currentRemote] currentSongRating];
1380 ITDebugLog(@"Decrementing rating.");
1382 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1383 ITDebugLog(@"No song playing, rating change aborted.");
1391 ITDebugLog(@"Setting rating to %f", rating);
1392 [[self currentRemote] setCurrentSongRating:rating];
1394 //Show rating status window
1395 [self invalidateStatusWindowUpdateTimer];
1396 [statusWindowController showRatingWindowWithRating:rating];
1398 [self networkError:localException];
1402 - (void)setRating:(ITHotKey *)sender
1404 if ([self songIsPlaying]) {
1405 int stars = [[sender name] characterAtIndex:9] - 48;
1406 [self selectSongRating:stars * 20];
1407 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1414 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1415 ITDebugLog(@"Toggling repeat mode.");
1416 switch (repeatMode) {
1417 case ITMTRemotePlayerRepeatOff:
1418 repeatMode = ITMTRemotePlayerRepeatAll;
1420 case ITMTRemotePlayerRepeatAll:
1421 repeatMode = ITMTRemotePlayerRepeatOne;
1423 case ITMTRemotePlayerRepeatOne:
1424 repeatMode = ITMTRemotePlayerRepeatOff;
1427 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1428 [[self currentRemote] setRepeatMode:repeatMode];
1430 //Show loop status window
1431 [self invalidateStatusWindowUpdateTimer];
1432 [statusWindowController showRepeatWindowWithMode:repeatMode];
1434 [self networkError:localException];
1438 - (void)toggleShuffle
1441 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1442 ITDebugLog(@"Toggling shuffle mode.");
1443 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1444 //Show shuffle status window
1445 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1446 [self invalidateStatusWindowUpdateTimer];
1447 [statusWindowController showShuffleWindow:newShuffleEnabled];
1449 [self networkError:localException];
1453 - (void)toggleSongShufflable
1455 if ([self songIsPlaying]) {
1457 BOOL flag = ![[self currentRemote] currentSongShufflable];
1458 ITDebugLog(@"Toggling shufflability.");
1459 [[self currentRemote] setCurrentSongShufflable:flag];
1460 //Show song shufflability status window
1461 [self invalidateStatusWindowUpdateTimer];
1462 [statusWindowController showSongShufflabilityWindow:flag];
1464 [self networkError:localException];
1469 - (void)registerNowOK
1471 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1472 [[StatusWindow sharedWindow] vanish:self];
1473 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1478 - (void)registerNowCancel
1480 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1481 [[StatusWindow sharedWindow] vanish:self];
1482 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1484 [NSApp terminate:self];
1487 /*************************************************************************/
1489 #pragma mark NETWORK HANDLERS
1490 /*************************************************************************/
1492 - (void)setServerStatus:(BOOL)newStatus
1496 [networkController setServerStatus:YES];
1499 [networkController setServerStatus:NO];
1503 - (int)connectToServer
1506 ITDebugLog(@"Attempting to connect to shared remote.");
1507 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1510 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1511 currentRemote = [[[networkController networkObject] remote] retain];
1513 [self setupHotKeys];
1514 //playerRunningState = ITMTRemotePlayerRunning;
1515 playerRunningState = [[self currentRemote] playerRunningState];
1516 if (_needsPolling) {
1518 [refreshTimer invalidate];
1520 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1522 selector:@selector(timerUpdate)
1524 repeats:YES] retain];
1527 ITDebugLog(@"Connection successful.");
1529 } else if (result == 0) {
1530 ITDebugLog(@"Connection failed.");
1531 currentRemote = [remoteArray objectAtIndex:0];
1534 //Do something about the password being invalid
1535 ITDebugLog(@"Connection failed.");
1536 currentRemote = [remoteArray objectAtIndex:0];
1541 - (BOOL)disconnectFromServer
1543 ITDebugLog(@"Disconnecting from shared remote.");
1545 [currentRemote release];
1546 currentRemote = [remoteArray objectAtIndex:0];
1547 [networkController disconnect];
1549 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1550 [self applicationLaunched:nil];
1552 [self applicationTerminated:nil];
1560 - (void)checkForRemoteServer
1562 [self checkForRemoteServerAndConnectImmediately:NO];
1565 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1567 ITDebugLog(@"Checking for remote server.");
1568 if (!_checkingForServer) {
1569 if (!_serverCheckLock) {
1570 _serverCheckLock = [[NSLock alloc] init];
1572 [_serverCheckLock lock];
1573 _checkingForServer = YES;
1574 [_serverCheckLock unlock];
1575 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1579 - (void)runRemoteServerCheck:(id)sender
1581 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1582 ITDebugLog(@"Remote server check running.");
1583 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1584 ITDebugLog(@"Remote server found.");
1585 if ([sender boolValue]) {
1586 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1588 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1591 ITDebugLog(@"Remote server not found.");
1592 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1594 [_serverCheckLock lock];
1595 _checkingForServer = NO;
1596 [_serverCheckLock unlock];
1600 - (void)remoteServerFound:(id)sender
1602 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1603 [self invalidateStatusWindowUpdateTimer];
1604 [[StatusWindowController sharedController] showReconnectQueryWindow];
1608 - (void)remoteServerNotFound:(id)sender
1610 if (![[NetworkController sharedController] isConnectedToServer]) {
1611 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1615 - (void)networkError:(NSException *)exception
1617 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1618 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1619 //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);
1620 [self invalidateStatusWindowUpdateTimer];
1621 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1622 if ([self disconnectFromServer]) {
1623 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1624 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1626 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1633 /*if ([self connectToServer] == 0) {
1634 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1636 [self checkForRemoteServerAndConnectImmediately:YES];
1637 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1638 [[StatusWindow sharedWindow] vanish:self];
1639 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1642 - (void)cancelReconnect
1644 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1645 [[StatusWindow sharedWindow] vanish:self];
1646 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1649 /*************************************************************************/
1651 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1652 /*************************************************************************/
1654 - (void)applicationLaunched:(NSNotification *)note
1657 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1658 ITDebugLog(@"Remote application launched.");
1659 playerRunningState = ITMTRemotePlayerRunning;
1660 [[self currentRemote] begin];
1661 [self setLatestSongIdentifier:@""];
1663 if (_needsPolling) {
1664 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1666 selector:@selector(timerUpdate)
1668 repeats:YES] retain];
1670 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1671 if (![df boolForKey:@"UsePollingOnly"]) {
1672 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1674 [self setupHotKeys];
1677 [self networkError:localException];
1681 - (void)applicationTerminated:(NSNotification *)note
1684 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1685 ITDebugLog(@"Remote application terminated.");
1686 playerRunningState = ITMTRemotePlayerNotRunning;
1687 [[self currentRemote] halt];
1688 [refreshTimer invalidate];
1689 [refreshTimer release];
1691 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1692 [statusItem setEnabled:YES];
1693 [statusItem setToolTip:@"iTunes not running."];
1694 [self clearHotKeys];
1697 if ([df objectForKey:@"ShowPlayer"] != nil) {
1699 ITDebugLog(@"Setting up show player hot key.");
1700 hotKey = [[ITHotKey alloc] init];
1701 [hotKey setName:@"ShowPlayer"];
1702 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1703 [hotKey setTarget:self];
1704 [hotKey setAction:@selector(showPlayer)];
1705 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1709 [self networkError:localException];
1714 /*************************************************************************/
1716 #pragma mark NSApplication DELEGATE METHODS
1717 /*************************************************************************/
1719 - (void)applicationWillTerminate:(NSNotification *)note
1721 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1722 [networkController stopRemoteServerSearch];
1723 [self clearHotKeys];
1724 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1727 - (void)applicationDidBecomeActive:(NSNotification *)note
1729 //This appears to not work in 10.4
1730 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1731 [[MainController sharedController] showPreferences];
1735 /*************************************************************************/
1737 #pragma mark DEALLOCATION METHOD
1738 /*************************************************************************/
1742 [self applicationTerminated:nil];
1744 [statusItem release];
1745 [statusWindowController release];
1746 [menuController release];
1747 [networkController release];
1748 [_serverCheckLock release];