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 "StatusItemHack.h"
14 @interface NSMenu (MenuImpl)
18 @interface NSCarbonMenuImpl:NSObject
24 + (void)setupForNoMenuBar;
28 - (void)itemChanged:fp8;
29 - (void)itemAdded:fp8;
30 - (void)itemRemoved:fp8;
31 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
32 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
33 - (void)setupCarbonMenuBar;
34 - (void)setAsMainCarbonMenuBar;
35 - (void)clearAsMainCarbonMenuBar;
36 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
37 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
38 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
42 @implementation NSImage (SmoothAdditions)
44 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
47 NSImageRep *rep = [self bestRepresentationForDevice:nil];
49 newImage = [[NSImage alloc] initWithSize:scaledSize];
52 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
53 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
54 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
56 [newImage unlockFocus];
57 return [newImage autorelease];
62 @interface MainController(Private)
63 - (ITMTRemote *)loadRemote;
64 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
65 - (void)applicationLaunched:(NSNotification *)note;
66 - (void)applicationTerminated:(NSNotification *)note;
68 - (void)invalidateStatusWindowUpdateTimer;
71 static MainController *sharedController;
73 @implementation MainController
75 + (MainController *)sharedController
77 return sharedController;
80 /*************************************************************************/
82 #pragma mark INITIALIZATION/DEALLOCATION METHODS
83 /*************************************************************************/
87 if ( ( self = [super init] ) ) {
88 sharedController = self;
90 _statusWindowUpdateTimer = nil;
92 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
93 [[PreferencesController sharedPrefs] setController:self];
94 statusWindowController = [StatusWindowController sharedController];
95 menuController = [[MenuController alloc] init];
96 df = [[NSUserDefaults standardUserDefaults] retain];
103 - (void)applicationDidFinishLaunching:(NSNotification *)note
105 NSString *iTunesPath = [df stringForKey:@"CustomPlayerPath"];
106 NSDictionary *iTunesInfoPlist;
109 //Turn on debug mode if needed
110 /*if ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)
111 if ((GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0)
112 if ((GetCurrentKeyModifiers() & (shiftKey | rightShiftKey)) != 0)*/
113 if ([df boolForKey:@"ITDebugMode"] || ((GetCurrentKeyModifiers() & (controlKey | rightControlKey)) != 0)) {
115 [[StatusWindowController sharedController] showDebugModeEnabledWindow];
118 //Check if iTunes 4.7 or later is installed
120 iTunesPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"];
122 iTunesInfoPlist = [[NSBundle bundleWithPath:iTunesPath] infoDictionary];
123 iTunesVersion = [[iTunesInfoPlist objectForKey:@"CFBundleVersion"] floatValue];
124 ITDebugLog(@"iTunes version found: %f.", iTunesVersion);
125 if (iTunesVersion >= 4.7) {
131 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
132 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
134 [[PreferencesController sharedPrefs] registerDefaults];
135 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
138 currentRemote = [self loadRemote];
139 [[self currentRemote] begin];
141 //Turn on network stuff if needed
142 networkController = [[NetworkController alloc] init];
143 if ([df boolForKey:@"enableSharing"]) {
144 [self setServerStatus:YES];
145 } else if ([df boolForKey:@"useSharedPlayer"]) {
146 [self checkForRemoteServerAndConnectImmediately:YES];
149 //Setup for notification of the remote player launching or quitting
150 [[[NSWorkspace sharedWorkspace] notificationCenter]
152 selector:@selector(applicationTerminated:)
153 name:NSWorkspaceDidTerminateApplicationNotification
156 [[[NSWorkspace sharedWorkspace] notificationCenter]
158 selector:@selector(applicationLaunched:)
159 name:NSWorkspaceDidLaunchApplicationNotification
162 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
163 [[PreferencesController sharedPrefs] registerDefaults];
166 if ([df boolForKey:@"ITMTNoStatusItem"]) {
169 [StatusItemHack install];
170 statusItem = [[ITStatusItem alloc]
171 initWithStatusBar:[NSStatusBar systemStatusBar]
172 withLength:NSSquareStatusItemLength];
175 /*bling = [[MTBlingController alloc] init];
177 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
179 selector:@selector(blingTime)
181 repeats:YES] retain];*/
184 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
185 [self applicationLaunched:nil];
187 if ([df boolForKey:@"LaunchPlayerWithMT"])
190 [self applicationTerminated:nil];
193 [self networkError:localException];
196 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
197 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
199 [networkController startRemoteServerSearch];
201 [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
203 bling = [[MTBlingController alloc] init];
205 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
207 selector:@selector(blingTime)
209 repeats:YES] retain];
217 - (ITMTRemote *)loadRemote
219 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
220 ITDebugLog(@"Gathering remotes.");
222 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
223 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
224 NSString *bundlePath;
226 while ( (bundlePath = [enumerator nextObject]) ) {
227 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
230 Class remoteClass = [remoteBundle principalClass];
232 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
233 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
234 id remote = [remoteClass remote];
235 ITDebugLog(@"Adding remote at path %@", bundlePath);
236 [remoteArray addObject:remote];
241 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
242 // if ( [remoteArray count] > 1 ) {
243 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
245 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
248 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
249 return [remoteArray objectAtIndex:0];
252 /*************************************************************************/
254 #pragma mark INSTANCE METHODS
255 /*************************************************************************/
257 /*- (void)startTimerInNewThread
259 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
260 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
261 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
263 selector:@selector(timerUpdate)
265 repeats:YES] retain];
267 ITDebugLog(@"Timer started.");
271 - (void)setBlingTime:(NSDate*)date
273 NSMutableDictionary *globalPrefs;
275 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
277 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
278 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
280 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
281 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
283 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
285 [globalPrefs release];
288 - (NSDate*)getBlingTime
291 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
296 NSDate *now = [NSDate date];
297 if (![self blingBling]) {
298 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
299 [self setBlingTime:now];
300 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
301 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
302 [self setBlingTime:[now addTimeInterval:-259200]];
304 NSMutableDictionary *globalPrefs;
306 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
307 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
308 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
310 [globalPrefs release];
314 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
316 [statusItem setEnabled:NO];
317 [[ITHotKeyCenter sharedCenter] setEnabled:NO];
318 if ([refreshTimer isValid]) {
319 [refreshTimer invalidate];
320 [refreshTimer release];
323 [statusWindowController showRegistrationQueryWindow];
327 [statusItem setEnabled:YES];
328 [[ITHotKeyCenter sharedCenter] setEnabled:YES];
329 if (_needsPolling && ![refreshTimer isValid]) {
330 [refreshTimer release];
331 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
333 selector:@selector(timerUpdate)
335 repeats:YES] retain];
339 [self setBlingTime:nil];
350 if ( ! ([bling checkDone] == 2475) ) {
357 - (BOOL)songIsPlaying
359 NSString *identifier = nil;
361 identifier = [[self currentRemote] playerStateUniqueIdentifier];
363 [self networkError:localException];
365 return ( ! ([identifier isEqualToString:@"0-0"]) );
368 - (BOOL)radioIsPlaying
370 ITMTRemotePlayerPlaylistClass class = nil;
372 class = [[self currentRemote] currentPlaylistClass];
374 [self networkError:localException];
376 return (class == ITMTRemotePlayerRadioPlaylist );
381 NSString *identifier = nil;
383 identifier = [[self currentRemote] playerStateUniqueIdentifier];
385 [self networkError:localException];
387 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
390 - (NSString *)latestSongIdentifier
392 return _latestSongIdentifier;
395 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
397 ITDebugLog(@"Setting latest song identifier:");
398 ITDebugLog(@" - Identifier: %@", newIdentifier);
399 [_latestSongIdentifier autorelease];
400 _latestSongIdentifier = [newIdentifier retain];
405 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
406 if (refreshTimer && identifier == nil) {
407 if ([statusItem isEnabled]) {
408 [statusItem setToolTip:@"iTunes not responding."];
410 [statusItem setEnabled:NO];
412 } else if (![statusItem isEnabled]) {
413 [statusItem setEnabled:YES];
414 [statusItem setToolTip:_toolTip];
418 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
419 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
420 if ([df boolForKey:@"runScripts"]) {
421 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
422 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
423 NSString *nextScript;
424 ITDebugLog(@"Running AppleScripts for song change.");
425 while ( (nextScript = [scriptsEnum nextObject]) ) {
427 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
428 ITDebugLog(@"Running script: %@", nextScript);
429 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
430 ITDebugLog(@"Error running script %@.", nextScript);
432 [currentScript release];
437 [statusItem setEnabled:NO];
440 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
442 if ([menuController rebuildSubmenus]) {
443 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
444 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
446 [self setLatestSongIdentifier:identifier];
447 //Create the tooltip for the status item
448 if ( [df boolForKey:@"showToolTip"] ) {
449 NSString *artist = [[self currentRemote] currentSongArtist];
450 NSString *title = [[self currentRemote] currentSongTitle];
451 ITDebugLog(@"Creating status item tooltip.");
453 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
457 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
459 [statusItem setToolTip:_toolTip];
461 [statusItem setToolTip:nil];
465 [self networkError:localException];
468 [statusItem setEnabled:YES];
471 if ([networkController isConnectedToServer]) {
472 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
478 ITDebugLog(@"Menu clicked.");
480 if (([[self currentRemote] playerStateUniqueIdentifier] == nil) && playerRunningState == ITMTRemotePlayerRunning) {
482 if ([statusItem isEnabled]) {
483 [statusItem setToolTip:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.")];
485 [statusItem setEnabled:NO];
487 NSMenu *menu = [[NSMenu alloc] init];
488 [menu addItemWithTitle:NSLocalizedString(@"iTunesNotResponding", @"iTunes is not responding.") action:nil keyEquivalent:@""];
489 [statusItem setMenu:[menu autorelease]];
492 } else if (![statusItem isEnabled]) {
493 [statusItem setEnabled:YES];
494 [statusItem setToolTip:_toolTip];
498 if ([networkController isConnectedToServer]) {
499 //Used the cached version
504 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
505 [statusItem setMenu:[menuController menu]];
507 [statusItem setMenu:[menuController menuForNoPlayer]];
510 [self networkError:localException];
514 - (void)trackChanged:(NSNotification *)note
516 //If we're running the timer, shut it off since we don't need it!
517 /*if (refreshTimer && [refreshTimer isValid]) {
518 ITDebugLog(@"Invalidating refresh timer.");
519 [refreshTimer invalidate];
520 [refreshTimer release];
524 if (![self songChanged]) {
527 NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
528 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
529 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
531 [_lastTrackInfo release];
532 _lastTrackInfo = [[note userInfo] retain];
534 [self setLatestSongIdentifier:identifier];
535 ITDebugLog(@"The song changed. '%@'", _latestSongIdentifier);
536 if ([df boolForKey:@"runScripts"]) {
537 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
538 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
539 NSString *nextScript;
540 ITDebugLog(@"Running AppleScripts for song change.");
541 while ( (nextScript = [scriptsEnum nextObject]) ) {
543 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
544 ITDebugLog(@"Running script: %@", nextScript);
545 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
546 ITDebugLog(@"Error running script %@.", nextScript);
548 [currentScript release];
552 [statusItem setEnabled:NO];
555 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
557 if ([menuController rebuildSubmenus]) {
558 /*if ( [df boolForKey:@"showSongInfoOnChange"] ) {
559 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
561 [self setLatestSongIdentifier:identifier];
562 //Create the tooltip for the status item
563 if ( [df boolForKey:@"showToolTip"] ) {
564 ITDebugLog(@"Creating status item tooltip.");
565 NSString *artist = [_lastTrackInfo objectForKey:@"Artist"], *title = [_lastTrackInfo objectForKey:@"Name"];
567 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
571 _toolTip = NSLocalizedString(@"noSongPlaying", @"No song is playing.");;
573 [statusItem setToolTip:_toolTip];
575 [statusItem setToolTip:nil];
579 [self networkError:localException];
582 [statusItem setEnabled:YES];
584 if ([networkController isConnectedToServer]) {
585 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
598 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
599 ITDebugLog(@"Play/Pause toggled");
600 if (state == ITMTRemotePlayerPlaying) {
601 [[self currentRemote] pause];
602 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
603 [[self currentRemote] pause];
604 [[self currentRemote] play];
606 [[self currentRemote] play];
609 [self networkError:localException];
619 ITDebugLog(@"Going to next song.");
621 [[self currentRemote] goToNextSong];
623 [self networkError:localException];
632 ITDebugLog(@"Going to previous song.");
634 [[self currentRemote] goToPreviousSong];
636 [self networkError:localException];
645 ITDebugLog(@"Fast forwarding.");
647 [[self currentRemote] forward];
649 [self networkError:localException];
658 ITDebugLog(@"Rewinding.");
660 [[self currentRemote] rewind];
662 [self networkError:localException];
669 - (void)selectPlaylistAtIndex:(int)index
671 ITDebugLog(@"Selecting playlist %i", index);
673 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
674 //[[self currentRemote] switchToPlaylistAtIndex:index];
676 [self networkError:localException];
683 - (void)selectSongAtIndex:(int)index
685 ITDebugLog(@"Selecting song %i", index);
687 [[self currentRemote] switchToSongAtIndex:index];
689 [self networkError:localException];
696 - (void)selectSongRating:(int)rating
698 ITDebugLog(@"Selecting song rating %i", rating);
700 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
702 [self networkError:localException];
709 - (void)selectEQPresetAtIndex:(int)index
711 ITDebugLog(@"Selecting EQ preset %i", index);
714 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
716 [[self currentRemote] switchToEQAtIndex:index];
719 [self networkError:localException];
726 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
728 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
730 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
732 [self networkError:localException];
734 ITDebugLog(@"Done making playlist");
739 ITDebugLog(@"Beginning show player.");
740 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
741 ITDebugLog(@"Showing player interface.");
743 [[self currentRemote] showPrimaryInterface];
745 [self networkError:localException];
748 ITDebugLog(@"Launching player.");
751 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
753 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
755 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
756 ITDebugLog(@"Error Launching Player");
759 [self networkError:localException];
762 ITDebugLog(@"Finished show player.");
765 - (void)showPreferences
767 ITDebugLog(@"Show preferences.");
768 [[PreferencesController sharedPrefs] showPrefsWindow:self];
771 - (void)showPreferencesAndClose
773 ITDebugLog(@"Show preferences.");
774 [[PreferencesController sharedPrefs] showPrefsWindow:self];
775 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
776 [[StatusWindow sharedWindow] vanish:self];
777 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
780 - (void)showTestWindow
782 [self showCurrentTrackInfo];
785 - (void)quitMenuTunes
787 ITDebugLog(@"Quitting MenuTunes.");
788 [NSApp terminate:self];
794 - (MenuController *)menuController
796 return menuController;
799 - (void)closePreferences
801 ITDebugLog(@"Preferences closed.");
802 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
807 - (ITMTRemote *)currentRemote
809 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
810 [self networkError:nil];
813 return currentRemote;
824 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
825 ITHotKey *nextHotKey;
826 ITDebugLog(@"Clearing hot keys.");
827 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
828 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
830 ITDebugLog(@"Done clearing hot keys.");
836 ITDebugLog(@"Setting up hot keys.");
838 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
842 if ([df objectForKey:@"PlayPause"] != nil) {
843 ITDebugLog(@"Setting up play pause hot key.");
844 hotKey = [[ITHotKey alloc] init];
845 [hotKey setName:@"PlayPause"];
846 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
847 [hotKey setTarget:self];
848 [hotKey setAction:@selector(playPause)];
849 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
852 if ([df objectForKey:@"NextTrack"] != nil) {
853 ITDebugLog(@"Setting up next track hot key.");
854 hotKey = [[ITHotKey alloc] init];
855 [hotKey setName:@"NextTrack"];
856 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
857 [hotKey setTarget:self];
858 [hotKey setAction:@selector(nextSong)];
859 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
862 if ([df objectForKey:@"PrevTrack"] != nil) {
863 ITDebugLog(@"Setting up previous track hot key.");
864 hotKey = [[ITHotKey alloc] init];
865 [hotKey setName:@"PrevTrack"];
866 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
867 [hotKey setTarget:self];
868 [hotKey setAction:@selector(prevSong)];
869 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
872 if ([df objectForKey:@"FastForward"] != nil) {
873 ITDebugLog(@"Setting up fast forward hot key.");
874 hotKey = [[ITHotKey alloc] init];
875 [hotKey setName:@"FastForward"];
876 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
877 [hotKey setTarget:self];
878 [hotKey setAction:@selector(fastForward)];
879 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
882 if ([df objectForKey:@"Rewind"] != nil) {
883 ITDebugLog(@"Setting up rewind hot key.");
884 hotKey = [[ITHotKey alloc] init];
885 [hotKey setName:@"Rewind"];
886 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
887 [hotKey setTarget:self];
888 [hotKey setAction:@selector(rewind)];
889 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
892 if ([df objectForKey:@"ShowPlayer"] != nil) {
893 ITDebugLog(@"Setting up show player hot key.");
894 hotKey = [[ITHotKey alloc] init];
895 [hotKey setName:@"ShowPlayer"];
896 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
897 [hotKey setTarget:self];
898 [hotKey setAction:@selector(showPlayer)];
899 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
902 if ([df objectForKey:@"TrackInfo"] != nil) {
903 ITDebugLog(@"Setting up track info hot key.");
904 hotKey = [[ITHotKey alloc] init];
905 [hotKey setName:@"TrackInfo"];
906 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
907 [hotKey setTarget:self];
908 [hotKey setAction:@selector(showCurrentTrackInfo)];
909 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
912 if ([df objectForKey:@"UpcomingSongs"] != nil) {
913 ITDebugLog(@"Setting up upcoming songs hot key.");
914 hotKey = [[ITHotKey alloc] init];
915 [hotKey setName:@"UpcomingSongs"];
916 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
917 [hotKey setTarget:self];
918 [hotKey setAction:@selector(showUpcomingSongs)];
919 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
922 if ([df objectForKey:@"ToggleLoop"] != nil) {
923 ITDebugLog(@"Setting up toggle loop hot key.");
924 hotKey = [[ITHotKey alloc] init];
925 [hotKey setName:@"ToggleLoop"];
926 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
927 [hotKey setTarget:self];
928 [hotKey setAction:@selector(toggleLoop)];
929 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
932 if ([df objectForKey:@"ToggleShuffle"] != nil) {
933 ITDebugLog(@"Setting up toggle shuffle hot key.");
934 hotKey = [[ITHotKey alloc] init];
935 [hotKey setName:@"ToggleShuffle"];
936 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
937 [hotKey setTarget:self];
938 [hotKey setAction:@selector(toggleShuffle)];
939 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
942 if ([df objectForKey:@"IncrementVolume"] != nil) {
943 ITDebugLog(@"Setting up increment volume hot key.");
944 hotKey = [[ITHotKey alloc] init];
945 [hotKey setName:@"IncrementVolume"];
946 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
947 [hotKey setTarget:self];
948 [hotKey setAction:@selector(incrementVolume)];
949 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
952 if ([df objectForKey:@"DecrementVolume"] != nil) {
953 ITDebugLog(@"Setting up decrement volume hot key.");
954 hotKey = [[ITHotKey alloc] init];
955 [hotKey setName:@"DecrementVolume"];
956 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
957 [hotKey setTarget:self];
958 [hotKey setAction:@selector(decrementVolume)];
959 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
962 if ([df objectForKey:@"IncrementRating"] != nil) {
963 ITDebugLog(@"Setting up increment rating hot key.");
964 hotKey = [[ITHotKey alloc] init];
965 [hotKey setName:@"IncrementRating"];
966 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
967 [hotKey setTarget:self];
968 [hotKey setAction:@selector(incrementRating)];
969 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
972 if ([df objectForKey:@"DecrementRating"] != nil) {
973 ITDebugLog(@"Setting up decrement rating hot key.");
974 hotKey = [[ITHotKey alloc] init];
975 [hotKey setName:@"DecrementRating"];
976 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
977 [hotKey setTarget:self];
978 [hotKey setAction:@selector(decrementRating)];
979 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
982 if ([df objectForKey:@"ToggleShufflability"] != nil) {
983 ITDebugLog(@"Setting up toggle song shufflability hot key.");
984 hotKey = [[ITHotKey alloc] init];
985 [hotKey setName:@"ToggleShufflability"];
986 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShufflability"]]];
987 [hotKey setTarget:self];
988 [hotKey setAction:@selector(toggleSongShufflable)];
989 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
992 if ([df objectForKey:@"PopupMenu"] != nil) {
993 ITDebugLog(@"Setting up popup menu hot key.");
994 hotKey = [[ITHotKey alloc] init];
995 [hotKey setName:@"PopupMenu"];
996 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
997 [hotKey setTarget:self];
998 [hotKey setAction:@selector(popupMenu)];
999 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1003 for (i = 0; i <= 5; i++) {
1004 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
1005 if ([df objectForKey:curName] != nil) {
1006 ITDebugLog(@"Setting up set rating %i hot key.", i);
1007 hotKey = [[ITHotKey alloc] init];
1008 [hotKey setName:curName];
1009 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
1010 [hotKey setTarget:self];
1011 [hotKey setAction:@selector(setRating:)];
1012 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1015 ITDebugLog(@"Finished setting up hot keys.");
1018 - (void)showCurrentTrackInfo
1020 ITMTRemotePlayerSource source = 0;
1021 NSString *title = nil;
1022 NSString *album = nil;
1023 NSString *artist = nil;
1024 NSString *composer = nil;
1025 NSString *time = nil;
1026 NSString *track = nil;
1031 //If we're already visible and the setting says so, vanish instead of displaying again.
1032 if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
1033 ITDebugLog(@"Track window is already visible, hiding track window.");
1034 [self invalidateStatusWindowUpdateTimer];
1035 [[StatusWindow sharedWindow] vanish:nil];
1039 ITDebugLog(@"Showing track info status window.");
1042 source = [[self currentRemote] currentSource];
1043 title = [[self currentRemote] currentSongTitle];
1045 [self networkError:localException];
1049 if ( [df boolForKey:@"showAlbumArtwork"] ) {
1050 NSSize oldSize, newSize;
1052 art = [[self currentRemote] currentSongAlbumArt];
1053 oldSize = [art size];
1054 if (oldSize.width > oldSize.height) {
1055 newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
1057 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
1058 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
1060 [self networkError:localException];
1064 if ( [df boolForKey:@"showAlbum"] ) {
1066 album = [[self currentRemote] currentSongAlbum];
1068 [self networkError:localException];
1072 if ( [df boolForKey:@"showArtist"] ) {
1074 artist = [[self currentRemote] currentSongArtist];
1076 [self networkError:localException];
1080 if ( [df boolForKey:@"showComposer"] ) {
1082 composer = [[self currentRemote] currentSongComposer];
1084 [self networkError:localException];
1088 if ( [df boolForKey:@"showTime"] ) {
1090 time = [NSString stringWithFormat:@"%@: %@ / %@",
1091 NSLocalizedString(@"time", @"Time"),
1092 [[self currentRemote] currentSongElapsed],
1093 [[self currentRemote] currentSongLength]];
1095 [self networkError:localException];
1097 _timeUpdateCount = 0;
1098 [self invalidateStatusWindowUpdateTimer];
1099 _statusWindowUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
1102 if ( [df boolForKey:@"showTrackNumber"] ) {
1107 trackNo = [[self currentRemote] currentSongTrack];
1108 trackCount = [[self currentRemote] currentAlbumTrackCount];
1110 [self networkError:localException];
1113 if ( (trackNo > 0) || (trackCount > 0) ) {
1114 track = [NSString stringWithFormat:@"%@: %i %@ %i",
1115 @"Track", trackNo, @"of", trackCount];
1119 if ( [df boolForKey:@"showTrackRating"] ) {
1120 float currentRating = 0;
1123 currentRating = [[self currentRemote] currentSongRating];
1125 [self networkError:localException];
1128 if (currentRating >= 0.0) {
1129 rating = ( currentRating * 5 );
1133 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
1135 playCount = [[self currentRemote] currentSongPlayCount];
1137 [self networkError:localException];
1141 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
1143 ITDebugLog(@"Showing current track info status window.");
1144 [statusWindowController showSongInfoWindowWithSource:source
1156 - (void)updateTime:(NSTimer *)timer
1158 StatusWindow *sw = [StatusWindow sharedWindow];
1160 if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
1161 NSString *time = nil, *length;
1163 length = [[self currentRemote] currentSongLength];
1165 time = [NSString stringWithFormat:@"%@: %@ / %@",
1166 NSLocalizedString(@"time", @"Time"),
1167 [[self currentRemote] currentSongElapsed],
1169 [[StatusWindowController sharedController] updateTime:time];
1172 [self networkError:localException];
1175 [self invalidateStatusWindowUpdateTimer];
1179 - (void)invalidateStatusWindowUpdateTimer
1181 if (_statusWindowUpdateTimer) {
1182 [_statusWindowUpdateTimer invalidate];
1183 _statusWindowUpdateTimer = nil;
1187 - (void)showUpcomingSongs
1191 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
1193 [self networkError:localException];
1196 [self invalidateStatusWindowUpdateTimer];
1198 ITDebugLog(@"Showing upcoming songs status window.");
1201 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
1202 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
1203 int curTrack = [[self currentRemote] currentSongIndex];
1206 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance && i <= numSongs; i++) {
1207 if ([[self currentRemote] songEnabledAtIndex:i]) {
1208 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1210 numSongsInAdvance++;
1214 if ([songList count] == 0) {
1215 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1218 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1220 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1223 [self networkError:localException];
1232 NSMenu *menu = [statusItem menu];
1233 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1238 - (void)incrementVolume
1241 float volume = [[self currentRemote] volume];
1242 float dispVol = volume;
1243 ITDebugLog(@"Incrementing volume.");
1252 ITDebugLog(@"Setting volume to %f", volume);
1253 [[self currentRemote] setVolume:volume];
1255 // Show volume status window
1256 [self invalidateStatusWindowUpdateTimer];
1257 [statusWindowController showVolumeWindowWithLevel:dispVol];
1259 [self networkError:localException];
1263 - (void)decrementVolume
1266 float volume = [[self currentRemote] volume];
1267 float dispVol = volume;
1268 ITDebugLog(@"Decrementing volume.");
1277 ITDebugLog(@"Setting volume to %f", volume);
1278 [[self currentRemote] setVolume:volume];
1280 //Show volume status window
1281 [self invalidateStatusWindowUpdateTimer];
1282 [statusWindowController showVolumeWindowWithLevel:dispVol];
1284 [self networkError:localException];
1288 - (void)incrementRating
1291 float rating = [[self currentRemote] currentSongRating];
1292 ITDebugLog(@"Incrementing rating.");
1294 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1295 ITDebugLog(@"No song playing, rating change aborted.");
1303 ITDebugLog(@"Setting rating to %f", rating);
1304 [[self currentRemote] setCurrentSongRating:rating];
1306 //Show rating status window
1307 [self invalidateStatusWindowUpdateTimer];
1308 [statusWindowController showRatingWindowWithRating:rating];
1310 [self networkError:localException];
1314 - (void)decrementRating
1317 float rating = [[self currentRemote] currentSongRating];
1318 ITDebugLog(@"Decrementing rating.");
1320 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1321 ITDebugLog(@"No song playing, rating change aborted.");
1329 ITDebugLog(@"Setting rating to %f", rating);
1330 [[self currentRemote] setCurrentSongRating:rating];
1332 //Show rating status window
1333 [self invalidateStatusWindowUpdateTimer];
1334 [statusWindowController showRatingWindowWithRating:rating];
1336 [self networkError:localException];
1340 - (void)setRating:(ITHotKey *)sender
1342 if ([self songIsPlaying]) {
1343 int stars = [[sender name] characterAtIndex:9] - 48;
1344 [self selectSongRating:stars * 20];
1345 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1352 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1353 ITDebugLog(@"Toggling repeat mode.");
1354 switch (repeatMode) {
1355 case ITMTRemotePlayerRepeatOff:
1356 repeatMode = ITMTRemotePlayerRepeatAll;
1358 case ITMTRemotePlayerRepeatAll:
1359 repeatMode = ITMTRemotePlayerRepeatOne;
1361 case ITMTRemotePlayerRepeatOne:
1362 repeatMode = ITMTRemotePlayerRepeatOff;
1365 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1366 [[self currentRemote] setRepeatMode:repeatMode];
1368 //Show loop status window
1369 [self invalidateStatusWindowUpdateTimer];
1370 [statusWindowController showRepeatWindowWithMode:repeatMode];
1372 [self networkError:localException];
1376 - (void)toggleShuffle
1379 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1380 ITDebugLog(@"Toggling shuffle mode.");
1381 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1382 //Show shuffle status window
1383 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1384 [self invalidateStatusWindowUpdateTimer];
1385 [statusWindowController showShuffleWindow:newShuffleEnabled];
1387 [self networkError:localException];
1391 - (void)toggleSongShufflable
1393 if ([self songIsPlaying]) {
1395 BOOL flag = ![[self currentRemote] currentSongShufflable];
1396 ITDebugLog(@"Toggling shufflability.");
1397 [[self currentRemote] setCurrentSongShufflable:flag];
1398 //Show song shufflability status window
1399 [self invalidateStatusWindowUpdateTimer];
1400 [statusWindowController showSongShufflabilityWindow:flag];
1402 [self networkError:localException];
1407 - (void)registerNowOK
1409 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1410 [[StatusWindow sharedWindow] vanish:self];
1411 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1416 - (void)registerNowCancel
1418 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1419 [[StatusWindow sharedWindow] vanish:self];
1420 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1422 [NSApp terminate:self];
1425 /*************************************************************************/
1427 #pragma mark NETWORK HANDLERS
1428 /*************************************************************************/
1430 - (void)setServerStatus:(BOOL)newStatus
1434 [networkController setServerStatus:YES];
1437 [networkController setServerStatus:NO];
1441 - (int)connectToServer
1444 ITDebugLog(@"Attempting to connect to shared remote.");
1445 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1448 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1449 currentRemote = [[[networkController networkObject] remote] retain];
1451 [self setupHotKeys];
1452 //playerRunningState = ITMTRemotePlayerRunning;
1453 playerRunningState = [[self currentRemote] playerRunningState];
1454 if (_needsPolling) {
1456 [refreshTimer invalidate];
1458 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1460 selector:@selector(timerUpdate)
1462 repeats:YES] retain];
1465 ITDebugLog(@"Connection successful.");
1467 } else if (result == 0) {
1468 ITDebugLog(@"Connection failed.");
1469 currentRemote = [remoteArray objectAtIndex:0];
1472 //Do something about the password being invalid
1473 ITDebugLog(@"Connection failed.");
1474 currentRemote = [remoteArray objectAtIndex:0];
1479 - (BOOL)disconnectFromServer
1481 ITDebugLog(@"Disconnecting from shared remote.");
1483 [currentRemote release];
1484 currentRemote = [remoteArray objectAtIndex:0];
1485 [networkController disconnect];
1487 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1488 [self applicationLaunched:nil];
1490 [self applicationTerminated:nil];
1498 - (void)checkForRemoteServer
1500 [self checkForRemoteServerAndConnectImmediately:NO];
1503 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1505 ITDebugLog(@"Checking for remote server.");
1506 if (!_checkingForServer) {
1507 if (!_serverCheckLock) {
1508 _serverCheckLock = [[NSLock alloc] init];
1510 [_serverCheckLock lock];
1511 _checkingForServer = YES;
1512 [_serverCheckLock unlock];
1513 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1517 - (void)runRemoteServerCheck:(id)sender
1519 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1520 ITDebugLog(@"Remote server check running.");
1521 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1522 ITDebugLog(@"Remote server found.");
1523 if ([sender boolValue]) {
1524 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1526 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1529 ITDebugLog(@"Remote server not found.");
1530 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1532 [_serverCheckLock lock];
1533 _checkingForServer = NO;
1534 [_serverCheckLock unlock];
1538 - (void)remoteServerFound:(id)sender
1540 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1541 [self invalidateStatusWindowUpdateTimer];
1542 [[StatusWindowController sharedController] showReconnectQueryWindow];
1546 - (void)remoteServerNotFound:(id)sender
1548 if (![[NetworkController sharedController] isConnectedToServer]) {
1549 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1553 - (void)networkError:(NSException *)exception
1555 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1556 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1557 //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);
1558 [self invalidateStatusWindowUpdateTimer];
1559 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1560 if ([self disconnectFromServer]) {
1561 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1562 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1564 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1571 /*if ([self connectToServer] == 0) {
1572 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1574 [self checkForRemoteServerAndConnectImmediately:YES];
1575 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1576 [[StatusWindow sharedWindow] vanish:self];
1577 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1580 - (void)cancelReconnect
1582 [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
1583 [[StatusWindow sharedWindow] vanish:self];
1584 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1587 /*************************************************************************/
1589 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1590 /*************************************************************************/
1592 - (void)applicationLaunched:(NSNotification *)note
1595 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1596 ITDebugLog(@"Remote application launched.");
1597 playerRunningState = ITMTRemotePlayerRunning;
1598 [[self currentRemote] begin];
1599 [self setLatestSongIdentifier:@""];
1601 if (_needsPolling) {
1602 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1604 selector:@selector(timerUpdate)
1606 repeats:YES] retain];
1608 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1609 if (![df boolForKey:@"UsePollingOnly"]) {
1610 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackChanged:) name:@"ITMTTrackChanged" object:nil];
1612 [self setupHotKeys];
1615 [self networkError:localException];
1619 - (void)applicationTerminated:(NSNotification *)note
1622 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1623 ITDebugLog(@"Remote application terminated.");
1624 playerRunningState = ITMTRemotePlayerNotRunning;
1625 [[self currentRemote] halt];
1626 [refreshTimer invalidate];
1627 [refreshTimer release];
1629 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ITMTTrackChanged" object:nil];
1630 [statusItem setEnabled:YES];
1631 [statusItem setToolTip:@"iTunes not running."];
1632 [self clearHotKeys];
1635 if ([df objectForKey:@"ShowPlayer"] != nil) {
1637 ITDebugLog(@"Setting up show player hot key.");
1638 hotKey = [[ITHotKey alloc] init];
1639 [hotKey setName:@"ShowPlayer"];
1640 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1641 [hotKey setTarget:self];
1642 [hotKey setAction:@selector(showPlayer)];
1643 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1647 [self networkError:localException];
1652 /*************************************************************************/
1654 #pragma mark NSApplication DELEGATE METHODS
1655 /*************************************************************************/
1657 - (void)applicationWillTerminate:(NSNotification *)note
1659 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1660 [networkController stopRemoteServerSearch];
1661 [self clearHotKeys];
1662 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1665 - (void)applicationDidBecomeActive:(NSNotification *)note
1667 //This appears to not work in 10.4
1668 if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
1669 [[MainController sharedController] showPreferences];
1673 /*************************************************************************/
1675 #pragma mark DEALLOCATION METHOD
1676 /*************************************************************************/
1680 [self applicationTerminated:nil];
1682 [statusItem release];
1683 [statusWindowController release];
1684 [menuController release];
1685 [networkController release];
1686 [_serverCheckLock release];