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];
483 _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
484 [_audioscrobblerTimer invalidate];
485 [_audioscrobblerTimer release];
486 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:nil target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
487 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
490 _audioscrobblerTimer = nil;
493 [self networkError:localException];
496 [statusItem setEnabled:YES];
499 if ([networkController isConnectedToServer]) {
500 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
506 ITDebugLog(@"Menu clicked.");
508 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
510 if ([statusItem isEnabled]) {
511 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
513 [statusItem setEnabled:NO];
515 NSMenu *menu = [[NSMenu alloc] init];
516 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
517 [statusItem setMenu:[menu autorelease]];
520 } else if (![statusItem isEnabled]) {
521 [statusItem setEnabled:YES];
522 [statusItem setToolTip:_toolTip];
526 if ([networkController isConnectedToServer]) {
527 //Used the cached version
532 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
533 [statusItem setMenu:[menuController menu]];
535 [statusItem setMenu:[menuController menuForNoPlayer]];
538 [self networkError:localException];
542 - (void)trackChanged:(NSNotification *)note
544 //If we're running the timer, shut it off since we don't need it!
545 /*if (refreshTimer && [refreshTimer isValid]) {
546 ITDebugLog(@"Invalidating refresh timer.");
547 [refreshTimer invalidate];
548 [refreshTimer release];
552 if (![self songChanged]) {
555 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
556 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
557 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
559 [_lastTrackInfo release];
560 _lastTrackInfo = [[note userInfo] retain];
562 [self setLatestSongIdentifier:identifier];
563 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
564 if ([df boolForKey:@"runScripts"]) {
565 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
566 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
567 NSString *nextScript;
568 ITDebugLog(@"Running AppleScripts for song change.");
569 while ( (nextScript = [scriptsEnum nextObject]) ) {
571 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
572 ITDebugLog(@"Running script: %@", nextScript);
573 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
574 ITDebugLog(@"Error running script %@.", nextScript);
576 [currentScript release];
580 [statusItem setEnabled:NO];
583 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
585 if ([menuController rebuildSubmenus]) {
586 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
587 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
589 [self setLatestSongIdentifier:identifier];
590 //Create the tooltip for the status item
591 if ( [df boolForKey:@"showToolTip"] ) {
592 ITDebugLog(@"Creating status item tooltip.");
593 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
595 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
599 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
601 [statusItem setToolTip:_toolTip];
603 [statusItem setToolTip:nil];
607 if ([df boolForKey:@"audioscrobblerEnabled"]) {
608 int length = [[self currentRemote] currentSongDuration];
610 _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
611 [_audioscrobblerTimer invalidate];
612 [_audioscrobblerTimer release];
613 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
614 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
617 _audioscrobblerTimer = nil;
620 [self networkError:localException];
623 [statusItem setEnabled:YES];
625 if ([networkController isConnectedToServer]) {
626 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
630 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
632 ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
634 if ([df boolForKey:@"audioscrobblerEnabled"]) {
636 int elapsed = [[self currentRemote] currentSongPlayed], length = [[self currentRemote] currentSongDuration], requiredInterval = ((length / 2 < 240) ? length / 2 : 240);
637 if ((abs(elapsed - requiredInterval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
638 NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
639 NSLog(@"Audioscrobbler: Submitting");
640 if (title && artist) {
641 ITDebugLog(@"Audioscrobbler: Submitting current track");
642 [[AudioscrobblerController sharedController] submitTrack:title
644 album:[[self currentRemote] currentSongAlbum]
645 length:[[self currentRemote] currentSongDuration]];
647 } else if (requiredInterval - elapsed > 0) {
648 _audioscrobblerInterval = requiredInterval - elapsed;
649 [_audioscrobblerTimer release];
650 NSLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", _audioscrobblerInterval);
651 ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", _audioscrobblerInterval);
652 _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
653 [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
655 NSLog(@"Audioscrobbler: Skipping submission. %i, %i", requiredInterval, elapsed);
658 [self networkError:localException];
672 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
673 ITDebugLog(@"Play/Pause toggled");
674 if (state == ITMTRemotePlayerPlaying) {
675 [[self currentRemote] pause];
676 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
677 [[self currentRemote] pause];
678 [[self currentRemote] play];
680 [[self currentRemote] play];
683 [self networkError:localException];
693 ITDebugLog(@"Going to next song.");
695 [[self currentRemote] goToNextSong];
697 [self networkError:localException];
706 ITDebugLog(@"Going to previous song.");
708 [[self currentRemote] goToPreviousSong];
710 [self networkError:localException];
719 ITDebugLog(@"Fast forwarding.");
721 [[self currentRemote] forward];
723 [self networkError:localException];
732 ITDebugLog(@"Rewinding.");
734 [[self currentRemote] rewind];
736 [self networkError:localException];
743 - (void)selectPlaylistAtIndex:(int)index
745 ITDebugLog(@"Selecting playlist %i", index);
747 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
748 //[[self currentRemote] switchToPlaylistAtIndex:index];
750 [self networkError:localException];
757 - (void)selectSongAtIndex:(int)index
759 ITDebugLog(@"Selecting song %i", index);
761 [[self currentRemote] switchToSongAtIndex:index];
763 [self networkError:localException];
770 - (void)selectSongRating:(int)rating
772 ITDebugLog(@"Selecting song rating %i", rating);
774 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
776 [self networkError:localException];
783 - (void)selectEQPresetAtIndex:(int)index
785 ITDebugLog(@"Selecting EQ preset %i", index);
788 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
790 [[self currentRemote] switchToEQAtIndex:index];
793 [self networkError:localException];
800 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
802 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
804 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
806 [self networkError:localException];
808 ITDebugLog(@"Done making playlist");
813 ITDebugLog(@"Beginning show player.");
814 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
815 ITDebugLog(@"Showing player interface.");
817 [[self currentRemote] showPrimaryInterface];
819 [self networkError:localException];
822 ITDebugLog(@"Launching player.");
825 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
827 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
829 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
830 ITDebugLog(@"Error Launching Player");
833 [self networkError:localException];
836 ITDebugLog(@"Finished show player.");
839 - (void)showPreferences
841 ITDebugLog(@"Show preferences.");
842 [[PreferencesController sharedPrefs] showPrefsWindow:self];
845 - (void)showPreferencesAndClose
847 ITDebugLog(@"Show preferences.");
848 [[PreferencesController sharedPrefs] showPrefsWindow:self];
849 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
850 [[StatusWindow sharedWindow] vanish:self];
851 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
854 - (void)showTestWindow
856 [self showCurrentTrackInfo];
859 - (void)quitMenuTunes
861 ITDebugLog(@"Quitting MenuTunes.");
862 [NSApp terminate:self];
868 - (MenuController *)menuController
870 return menuController;
873 - (void)closePreferences
875 ITDebugLog(@"Preferences closed.");
876 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
881 - (ITMTRemote *)currentRemote
883 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
884 [self networkError:nil];
887 return currentRemote;
898 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
899 ITHotKey *nextHotKey;
900 ITDebugLog(@"Clearing hot keys.");
901 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
902 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
904 ITDebugLog(@"Done clearing hot keys.");
910 ITDebugLog(@"Setting up hot keys.");
912 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
916 if ([df objectForKey:@"PlayPause"] != nil) {
917 ITDebugLog(@"Setting up play pause hot key.");
918 hotKey = [[ITHotKey alloc] init];
919 [hotKey setName:@"PlayPause"];
920 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
921 [hotKey setTarget:self];
922 [hotKey setAction:@selector(playPause)];
923 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
926 if ([df objectForKey:@"NextTrack"] != nil) {
927 ITDebugLog(@"Setting up next track hot key.");
928 hotKey = [[ITHotKey alloc] init];
929 [hotKey setName:@"NextTrack"];
930 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
931 [hotKey setTarget:self];
932 [hotKey setAction:@selector(nextSong)];
933 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
936 if ([df objectForKey:@"PrevTrack"] != nil) {
937 ITDebugLog(@"Setting up previous track hot key.");
938 hotKey = [[ITHotKey alloc] init];
939 [hotKey setName:@"PrevTrack"];
940 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
941 [hotKey setTarget:self];
942 [hotKey setAction:@selector(prevSong)];
943 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
946 if ([df objectForKey:@"FastForward"] != nil) {
947 ITDebugLog(@"Setting up fast forward hot key.");
948 hotKey = [[ITHotKey alloc] init];
949 [hotKey setName:@"FastForward"];
950 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
951 [hotKey setTarget:self];
952 [hotKey setAction:@selector(fastForward)];
953 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
956 if ([df objectForKey:@"Rewind"] != nil) {
957 ITDebugLog(@"Setting up rewind hot key.");
958 hotKey = [[ITHotKey alloc] init];
959 [hotKey setName:@"Rewind"];
960 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
961 [hotKey setTarget:self];
962 [hotKey setAction:@selector(rewind)];
963 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
966 if ([df objectForKey:@"ShowPlayer"] != nil) {
967 ITDebugLog(@"Setting up show player hot key.");
968 hotKey = [[ITHotKey alloc] init];
969 [hotKey setName:@"ShowPlayer"];
970 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
971 [hotKey setTarget:self];
972 [hotKey setAction:@selector(showPlayer)];
973 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
976 if ([df objectForKey:@"TrackInfo"] != nil) {
977 ITDebugLog(@"Setting up track info hot key.");
978 hotKey = [[ITHotKey alloc] init];
979 [hotKey setName:@"TrackInfo"];
980 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
981 [hotKey setTarget:self];
982 [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
983 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
986 if ([df objectForKey:@"UpcomingSongs"] != nil) {
987 ITDebugLog(@"Setting up upcoming songs hot key.");
988 hotKey = [[ITHotKey alloc] init];
989 [hotKey setName:@"UpcomingSongs"];
990 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
991 [hotKey setTarget:self];
992 [hotKey setAction:@selector(showUpcomingSongs)];
993 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
996 if ([df objectForKey:@"ToggleLoop"] != nil) {
997 ITDebugLog(@"Setting up toggle loop hot key.");
998 hotKey = [[ITHotKey alloc] init];
999 [hotKey setName:@"ToggleLoop"];
1000 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
1001 [hotKey setTarget:self];
1002 [hotKey setAction:@selector(toggleLoop)];
1003 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1006 if ([df objectForKey:@"ToggleShuffle"] != nil) {
1007 ITDebugLog(@"Setting up toggle shuffle hot key.");
1008 hotKey = [[ITHotKey alloc] init];
1009 [hotKey setName:@"ToggleShuffle"];
1010 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
1011 [hotKey setTarget:self];
1012 [hotKey setAction:@selector(toggleShuffle)];
1013 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1016 if ([df objectForKey:@"IncrementVolume"] != nil) {
1017 ITDebugLog(@"Setting up increment volume hot key.");
1018 hotKey = [[ITHotKey alloc] init];
1019 [hotKey setName:@"IncrementVolume"];
1020 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
1021 [hotKey setTarget:self];
1022 [hotKey setAction:@selector(incrementVolume)];
1023 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1026 if ([df objectForKey:@"DecrementVolume"] != nil) {
1027 ITDebugLog(@"Setting up decrement volume hot key.");
1028 hotKey = [[ITHotKey alloc] init];
1029 [hotKey setName:@"DecrementVolume"];
1030 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
1031 [hotKey setTarget:self];
1032 [hotKey setAction:@selector(decrementVolume)];
1033 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1036 if ([df objectForKey:@"IncrementRating"] != nil) {
1037 ITDebugLog(@"Setting up increment rating hot key.");
1038 hotKey = [[ITHotKey alloc] init];
1039 [hotKey setName:@"IncrementRating"];
1040 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
1041 [hotKey setTarget:self];
1042 [hotKey setAction:@selector(incrementRating)];
1043 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1046 if ([df objectForKey:@"DecrementRating"] != nil) {
1047 ITDebugLog(@"Setting up decrement rating hot key.");
1048 hotKey = [[ITHotKey alloc] init];
1049 [hotKey setName:@"DecrementRating"];
1050 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
1051 [hotKey setTarget:self];
1052 [hotKey setAction:@selector(decrementRating)];
1053 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1056 if ([df objectForKey:@"ToggleShufflability"] != nil) {
1057 ITDebugLog(@"Setting up toggle song shufflability hot key.");
1058 hotKey = [[ITHotKey alloc] init];
1059 [hotKey setName:@"ToggleShufflability"];
1060 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
1061 [hotKey setTarget:self];
1062 [hotKey setAction:@selector(toggleSongShufflable)];
1063 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1066 if ([df objectForKey:@"PopupMenu"] != nil) {
1067 ITDebugLog(@"Setting up popup menu hot key.");
1068 hotKey = [[ITHotKey alloc] init];
1069 [hotKey setName:@"PopupMenu"];
1070 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
1071 [hotKey setTarget:self];
1072 [hotKey setAction:@selector(popupMenu)];
1073 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1077 for (i = 0; i <= 5; i++) {
1078 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1079 if ([df objectForKey:curName] != nil) {
1080 ITDebugLog(@"Setting up set rating %i hot key.", i);
1081 hotKey = [[ITHotKey alloc] init];
1082 [hotKey setName:curName];
1083 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1084 [hotKey setTarget:self];
1085 [hotKey setAction:@selector(setRating:)];
1086 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1089 ITDebugLog(@"Finished setting up hot keys.");
1092 - (void)showCurrentTrackInfoHotKey
1094 //If we're already visible and the setting says so, vanish instead of displaying again.
1095 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1096 ITDebugLog(@"Track window is already visible, hiding track window.");
1097 [self invalidateStatusWindowUpdateTimer];
1098 [[StatusWindow sharedWindow] vanish:nil];
1101 [self showCurrentTrackInfo];
1104 - (void)showCurrentTrackInfo
1106 ITMTRemotePlayerSource source = 0;
1107 NSString *title = nil;
1108 NSString *album = nil;
1109 NSString *artist = nil;
1110 NSString *composer = nil;
1111 NSString *time = nil;
1112 NSString *track = nil;
1117 ITDebugLog(@"Showing track info status window.");
1120 source = [[self currentRemote] currentSource];
1121 title = [[self currentRemote] currentSongTitle];
1123 [self networkError:localException];
1127 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1128 NSSize oldSize, newSize;
1130 art = [[self currentRemote] currentSongAlbumArt];
1131 oldSize = [art size];
1132 if (oldSize.width > oldSize.height) {
1133 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1135 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1136 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1138 [self networkError:localException];
1142 if ( [df boolForKey:@"showAlbum"] ) {
1144 album = [[self currentRemote] currentSongAlbum];
1146 [self networkError:localException];
1150 if ( [df boolForKey:@"showArtist"] ) {
1152 artist = [[self currentRemote] currentSongArtist];
1154 [self networkError:localException];
1158 if ( [df boolForKey:@"showComposer"] ) {
1160 composer = [[self currentRemote] currentSongComposer];
1162 [self networkError:localException];
1166 if ( [df boolForKey:@"showTime"] ) {
1168 time = [NSString stringWithFormat:@"%@: %@ / %@",
1169 NSLocalizedString(@"time", @"Time"),
1170 [[self currentRemote] currentSongElapsed],
1171 [[self currentRemote] currentSongLength]];
1173 [self networkError:localException];
1175 _timeUpdateCount = 0;
1176 [self invalidateStatusWindowUpdateTimer];
1177 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1180 if ( [df boolForKey:@"showTrackNumber"] ) {
1185 trackNo = [[self currentRemote] currentSongTrack];
1186 trackCount = [[self currentRemote] currentAlbumTrackCount];
1188 [self networkError:localException];
1191 if ( (trackNo > 0) || (trackCount > 0) ) {
1192 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1193 @"Track", trackNo, @"of", trackCount];
1197 if ( [df boolForKey:@"showTrackRating"] ) {
1198 float currentRating = 0;
1201 currentRating = [[self currentRemote] currentSongRating];
1203 [self networkError:localException];
1206 if (currentRating >= 0.0) {
1207 rating = ( currentRating * 5 );
1211 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1213 playCount = [[self currentRemote] currentSongPlayCount];
1215 [self networkError:localException];
1219 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1221 ITDebugLog(@"Showing current track info status window.");
1222 [statusWindowController showSongInfoWindowWithSource:source
1234 - (void)updateTime:(NSTimer *)timer
1236 StatusWindow *sw = (StatusWindow *)[StatusWindow sharedWindow];
1238 if ([sw visibilityState] != ITWindowHiddenState) {
1239 NSString *time = nil, *length;
1241 length = [[self currentRemote] currentSongLength];
1243 time = [NSString stringWithFormat:@"%@: %@ / %@",
1244 NSLocalizedString(@"time", @"Time"),
1245 [[self currentRemote] currentSongElapsed],
1247 [[StatusWindowController sharedController] updateTime:time];
1250 [self networkError:localException];
1253 [self invalidateStatusWindowUpdateTimer];
1257 - (void)invalidateStatusWindowUpdateTimer
1259 if (_statusWindowUpdateTimer) {
1260 [_statusWindowUpdateTimer invalidate];
1261 _statusWindowUpdateTimer = nil;
1265 - (void)showUpcomingSongs
1269 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1271 [self networkError:localException];
1274 [self invalidateStatusWindowUpdateTimer];
1276 ITDebugLog(@"Showing upcoming songs status window.");
1279 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1280 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1281 int curTrack = [[self currentRemote] currentSongIndex];
1284 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1285 if ([[self currentRemote] songEnabledAtIndex:i]) {
1286 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1288 numSongsInAdvance++;
1292 if ([songList count] == 0) {
1293 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1296 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1298 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1301 [self networkError:localException];
1310 NSMenu *menu = [statusItem menu];
1311 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1316 - (void)incrementVolume
1319 float volume = [[self currentRemote] volume];
1320 float dispVol = volume;
1321 ITDebugLog(@"Incrementing volume.");
1330 ITDebugLog(@"Setting volume to %f", volume);
1331 [[self currentRemote] setVolume:volume];
1333 // Show volume status window
1334 [self invalidateStatusWindowUpdateTimer];
1335 [statusWindowController showVolumeWindowWithLevel:dispVol];
1337 [self networkError:localException];
1341 - (void)decrementVolume
1344 float volume = [[self currentRemote] volume];
1345 float dispVol = volume;
1346 ITDebugLog(@"Decrementing volume.");
1355 ITDebugLog(@"Setting volume to %f", volume);
1356 [[self currentRemote] setVolume:volume];
1358 //Show volume status window
1359 [self invalidateStatusWindowUpdateTimer];
1360 [statusWindowController showVolumeWindowWithLevel:dispVol];
1362 [self networkError:localException];
1366 - (void)incrementRating
1369 float rating = [[self currentRemote] currentSongRating];
1370 ITDebugLog(@"Incrementing rating.");
1372 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1373 ITDebugLog(@"No song playing, rating change aborted.");
1381 ITDebugLog(@"Setting rating to %f", rating);
1382 [[self currentRemote] setCurrentSongRating:rating];
1384 //Show rating status window
1385 [self invalidateStatusWindowUpdateTimer];
1386 [statusWindowController showRatingWindowWithRating:rating];
1388 [self networkError:localException];
1392 - (void)decrementRating
1395 float rating = [[self currentRemote] currentSongRating];
1396 ITDebugLog(@"Decrementing rating.");
1398 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1399 ITDebugLog(@"No song playing, rating change aborted.");
1407 ITDebugLog(@"Setting rating to %f", rating);
1408 [[self currentRemote] setCurrentSongRating:rating];
1410 //Show rating status window
1411 [self invalidateStatusWindowUpdateTimer];
1412 [statusWindowController showRatingWindowWithRating:rating];
1414 [self networkError:localException];
1418 - (void)setRating:(ITHotKey *)sender
1420 if ([self songIsPlaying]) {
1421 int stars = [[sender name] characterAtIndex:9] - 48;
1422 [self selectSongRating:stars * 20];
1423 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1430 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1431 ITDebugLog(@"Toggling repeat mode.");
1432 switch (repeatMode) {
1433 case ITMTRemotePlayerRepeatOff:
1434 repeatMode = ITMTRemotePlayerRepeatAll;
1436 case ITMTRemotePlayerRepeatAll:
1437 repeatMode = ITMTRemotePlayerRepeatOne;
1439 case ITMTRemotePlayerRepeatOne:
1440 repeatMode = ITMTRemotePlayerRepeatOff;
1443 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1444 [[self currentRemote] setRepeatMode:repeatMode];
1446 //Show loop status window
1447 [self invalidateStatusWindowUpdateTimer];
1448 [statusWindowController showRepeatWindowWithMode:repeatMode];
1450 [self networkError:localException];
1454 - (void)toggleShuffle
1457 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1458 ITDebugLog(@"Toggling shuffle mode.");
1459 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1460 //Show shuffle status window
1461 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1462 [self invalidateStatusWindowUpdateTimer];
1463 [statusWindowController showShuffleWindow:newShuffleEnabled];
1465 [self networkError:localException];
1469 - (void)toggleSongShufflable
1471 if ([self songIsPlaying]) {
1473 BOOL flag = ![[self currentRemote] currentSongShufflable];
1474 ITDebugLog(@"Toggling shufflability.");
1475 [[self currentRemote] setCurrentSongShufflable:flag];
1476 //Show song shufflability status window
1477 [self invalidateStatusWindowUpdateTimer];
1478 [statusWindowController showSongShufflabilityWindow:flag];
1480 [self networkError:localException];
1485 - (void)registerNowOK
1487 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1488 [[StatusWindow sharedWindow] vanish:self];
1489 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1494 - (void)registerNowCancel
1496 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1497 [[StatusWindow sharedWindow] vanish:self];
1498 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1500 [NSApp terminate:self];
1503 /*************************************************************************/
1505 #pragma mark NETWORK HANDLERS
1506 /*************************************************************************/
1508 - (void)setServerStatus:(BOOL)newStatus
1512 [networkController setServerStatus:YES];
1515 [networkController setServerStatus:NO];
1519 - (int)connectToServer
1522 ITDebugLog(@"Attempting to connect to shared remote.");
1523 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1526 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1527 currentRemote = [[[networkController networkObject] remote] retain];
1529 [self setupHotKeys];
1530 //playerRunningState = ITMTRemotePlayerRunning;
1531 playerRunningState = [[self currentRemote] playerRunningState];
1532 if (_needsPolling) {
1534 [refreshTimer invalidate];
1538 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1540 selector:@selector(timerUpdate)
1542 repeats:YES] retain];
1545 ITDebugLog(@"Connection successful.");
1547 } else if (result == 0) {
1548 ITDebugLog(@"Connection failed.");
1549 currentRemote = [remoteArray objectAtIndex:0];
1552 //Do something about the password being invalid
1553 ITDebugLog(@"Connection failed.");
1554 currentRemote = [remoteArray objectAtIndex:0];
1559 - (BOOL)disconnectFromServer
1561 ITDebugLog(@"Disconnecting from shared remote.");
1563 [currentRemote release];
1564 currentRemote = [remoteArray objectAtIndex:0];
1565 [networkController disconnect];
1567 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1569 [self applicationLaunched:nil];
1571 [self applicationTerminated:nil];
1580 - (void)checkForRemoteServer
1582 [self checkForRemoteServerAndConnectImmediately:NO];
1585 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1587 ITDebugLog(@"Checking for remote server.");
1588 if (!_checkingForServer) {
1589 if (!_serverCheckLock) {
1590 _serverCheckLock = [[NSLock alloc] init];
1592 [_serverCheckLock lock];
1593 _checkingForServer = YES;
1594 [_serverCheckLock unlock];
1595 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1599 - (void)runRemoteServerCheck:(id)sender
1601 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1602 ITDebugLog(@"Remote server check running.");
1603 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1604 ITDebugLog(@"Remote server found.");
1605 if ([sender boolValue]) {
1606 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1608 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1611 ITDebugLog(@"Remote server not found.");
1612 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1614 [_serverCheckLock lock];
1615 _checkingForServer = NO;
1616 [_serverCheckLock unlock];
1620 - (void)remoteServerFound:(id)sender
1622 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1623 [self invalidateStatusWindowUpdateTimer];
1624 [[StatusWindowController sharedController] showReconnectQueryWindow];
1628 - (void)remoteServerNotFound:(id)sender
1630 if (![[NetworkController sharedController] isConnectedToServer]) {
1631 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1635 - (void)networkError:(NSException *)exception
1637 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1638 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1639 //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);
1640 [self invalidateStatusWindowUpdateTimer];
1641 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1642 if ([self disconnectFromServer]) {
1643 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1644 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1646 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1653 /*if ([self connectToServer] == 0) {
1654 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1656 [self checkForRemoteServerAndConnectImmediately:YES];
1657 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1658 [[StatusWindow sharedWindow] vanish:self];
1659 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1662 - (void)cancelReconnect
1664 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1665 [[StatusWindow sharedWindow] vanish:self];
1666 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1669 /*************************************************************************/
1671 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1672 /*************************************************************************/
1674 - (void)applicationLaunched:(NSNotification *)note
1677 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1678 ITDebugLog(@"Remote application launched.");
1679 playerRunningState = ITMTRemotePlayerRunning;
1680 [[self currentRemote] begin];
1681 [self setLatestSongIdentifier:@""];
1683 if (_needsPolling) {
1684 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1686 selector:@selector(timerUpdate)
1688 repeats:YES] retain];
1690 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1691 if (![df boolForKey:@"UsePollingOnly"]) {
1692 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1694 [self setupHotKeys];
1697 [self networkError:localException];
1701 - (void)applicationTerminated:(NSNotification *)note
1704 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1705 ITDebugLog(@"Remote application terminated.");
1706 playerRunningState = ITMTRemotePlayerNotRunning;
1707 [[self currentRemote] halt];
1708 [refreshTimer invalidate];
1709 [refreshTimer release];
1711 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1712 [statusItem setEnabled:YES];
1713 [statusItem setToolTip:@"iTunes not running."];
1714 [self clearHotKeys];
1717 if ([df objectForKey:@"ShowPlayer"] != nil) {
1719 ITDebugLog(@"Setting up show player hot key.");
1720 hotKey = [[ITHotKey alloc] init];
1721 [hotKey setName:@"ShowPlayer"];
1722 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1723 [hotKey setTarget:self];
1724 [hotKey setAction:@selector(showPlayer)];
1725 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1729 [self networkError:localException];
1734 /*************************************************************************/
1736 #pragma mark NSApplication DELEGATE METHODS
1737 /*************************************************************************/
1739 - (void)applicationWillTerminate:(NSNotification *)note
1741 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1742 [networkController stopRemoteServerSearch];
1743 [self clearHotKeys];
1744 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1747 - (void)applicationDidBecomeActive:(NSNotification *)note
1749 //This appears to not work in 10.4
1750 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1751 [[MainController sharedController] showPreferences];
1755 /*************************************************************************/
1757 #pragma mark DEALLOCATION METHOD
1758 /*************************************************************************/
1762 [self applicationTerminated:nil];
1764 [statusItem release];
1765 [statusWindowController release];
1766 [menuController release];
1767 [networkController release];
1768 [_serverCheckLock release];