Individual song rating setting by hotkey actually works now. I'm an idiot.
[MenuTunes.git] / MainController.m
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"
13
14 @interface NSCarbonMenuImpl:NSObject
15 {
16     NSMenu *_menu;
17 }
18
19 + (void)initialize;
20 + (void)setupForNoMenuBar;
21 - (void)dealloc;
22 - (void)setMenu:fp8;
23 - menu;
24 - (void)itemChanged:fp8;
25 - (void)itemAdded:fp8;
26 - (void)itemRemoved:fp8;
27 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
28 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
29 - (void)setupCarbonMenuBar;
30 - (void)setAsMainCarbonMenuBar;
31 - (void)clearAsMainCarbonMenuBar;
32 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
33 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
34 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
35 - window;
36 @end
37
38 @implementation NSImage (SmoothAdditions)
39
40 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
41 {
42     NSImage *newImage;
43     NSImageRep *rep = [self bestRepresentationForDevice:nil];
44     
45     newImage = [[NSImage alloc] initWithSize:scaledSize];
46     [newImage lockFocus];
47     {
48         [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
49         [[NSGraphicsContext currentContext] setShouldAntialias:YES];
50         [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
51     }
52     [newImage unlockFocus];
53     return [newImage autorelease];
54 }
55
56 @end
57
58 @interface MainController(Private)
59 - (ITMTRemote *)loadRemote;
60 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
61 - (void)applicationLaunched:(NSNotification *)note;
62 - (void)applicationTerminated:(NSNotification *)note;
63 @end
64
65 static MainController *sharedController;
66
67 @implementation MainController
68
69 + (MainController *)sharedController
70 {
71     return sharedController;
72 }
73
74 /*************************************************************************/
75 #pragma mark -
76 #pragma mark INITIALIZATION/DEALLOCATION METHODS
77 /*************************************************************************/
78
79 - (id)init
80 {
81     if ( ( self = [super init] ) ) {
82         sharedController = self;
83         
84         remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
85         [[PreferencesController sharedPrefs] setController:self];
86         statusWindowController = [StatusWindowController sharedController];
87         menuController = [[MenuController alloc] init];
88         df = [[NSUserDefaults standardUserDefaults] retain];
89         timerUpdating = NO;
90         blinged = NO;
91     }
92     return self;
93 }
94
95 - (void)applicationDidFinishLaunching:(NSNotification *)note
96 {
97     //Turn on debug mode if needed
98     if ([df boolForKey:@"ITDebugMode"]) {
99         SetITDebugMode(YES);
100     }
101     
102     if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
103         [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
104         [df synchronize];
105         [[PreferencesController sharedPrefs] registerDefaults];
106         [[StatusWindowController sharedController] showPreferencesUpdateWindow];
107     }
108     
109     currentRemote = [self loadRemote];
110     [[self currentRemote] begin];
111     
112     //Turn on network stuff if needed
113     networkController = [[NetworkController alloc] init];
114     if ([df boolForKey:@"enableSharing"]) {
115         [self setServerStatus:YES];
116     } else if ([df boolForKey:@"useSharedPlayer"]) {
117         [self checkForRemoteServerAndConnectImmediately:YES];
118     }
119     
120     //Setup for notification of the remote player launching or quitting
121     [[[NSWorkspace sharedWorkspace] notificationCenter]
122             addObserver:self
123             selector:@selector(applicationTerminated:)
124             name:NSWorkspaceDidTerminateApplicationNotification
125             object:nil];
126     
127     [[[NSWorkspace sharedWorkspace] notificationCenter]
128             addObserver:self
129             selector:@selector(applicationLaunched:)
130             name:NSWorkspaceDidLaunchApplicationNotification
131             object:nil];
132     
133     if (![df objectForKey:@"menu"]) {  // If this is nil, defaults have never been registered.
134         [[PreferencesController sharedPrefs] registerDefaults];
135     }
136     
137     if ([df boolForKey:@"ITMTNoStatusItem"]) {
138         statusItem = nil;
139     } else {
140         [StatusItemHack install];
141         statusItem = [[ITStatusItem alloc]
142                 initWithStatusBar:[NSStatusBar systemStatusBar]
143                 withLength:NSSquareStatusItemLength];
144     }
145     
146     bling = [[MTBlingController alloc] init];
147     [self blingTime];
148     registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
149                              target:self
150                              selector:@selector(blingTime)
151                              userInfo:nil
152                              repeats:YES] retain];
153     
154     NS_DURING
155         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
156             [self applicationLaunched:nil];
157         } else {
158             if ([df boolForKey:@"LaunchPlayerWithMT"])
159                 [self showPlayer];
160             else
161                 [self applicationTerminated:nil];
162         }
163     NS_HANDLER
164         [self networkError:localException];
165     NS_ENDHANDLER
166     
167     [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
168     [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
169
170     [networkController startRemoteServerSearch];
171     [NSApp deactivate];
172 }
173
174 - (ITMTRemote *)loadRemote
175 {
176     NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
177     ITDebugLog(@"Gathering remotes.");
178     if (folderPath) {
179         NSArray      *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
180         NSEnumerator *enumerator     = [bundlePathList objectEnumerator];
181         NSString     *bundlePath;
182
183         while ( (bundlePath = [enumerator nextObject]) ) {
184             NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
185
186             if (remoteBundle) {
187                 Class remoteClass = [remoteBundle principalClass];
188
189                 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
190                     [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
191                     id remote = [remoteClass remote];
192                     ITDebugLog(@"Adding remote at path %@", bundlePath);
193                     [remoteArray addObject:remote];
194                 }
195             }
196         }
197
198 //      if ( [remoteArray count] > 0 ) {  // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
199 //          if ( [remoteArray count] > 1 ) {
200 //              [remoteArray sortUsingSelector:@selector(sortAlpha:)];
201 //          }
202 //          [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
203 //      }
204     }
205 //  NSLog(@"%@", [remoteArray objectAtIndex:0]);  //DEBUG
206     return [remoteArray objectAtIndex:0];
207 }
208
209 /*************************************************************************/
210 #pragma mark -
211 #pragma mark INSTANCE METHODS
212 /*************************************************************************/
213
214 /*- (void)startTimerInNewThread
215 {
216     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
217     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
218     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
219                              target:self
220                              selector:@selector(timerUpdate)
221                              userInfo:nil
222                              repeats:YES] retain];
223     [runLoop run];
224     ITDebugLog(@"Timer started.");
225     [pool release];
226 }*/
227
228 - (void)setBlingTime:(NSDate*)date
229 {
230     NSMutableDictionary *globalPrefs;
231     [df synchronize];
232     globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
233     if (date) {
234         [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
235         [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
236     } else {
237         [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
238         [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
239     }
240     [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
241     [df synchronize];
242     [globalPrefs release];
243 }
244
245 - (NSDate*)getBlingTime
246 {
247     [df synchronize];
248     return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
249 }
250
251 - (void)blingTime
252 {
253     NSDate *now = [NSDate date];
254     if (![self blingBling]) {
255         if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
256             [self setBlingTime:now];
257         } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
258             if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
259                 [self setBlingTime:[now addTimeInterval:-259200]];
260             } else {
261                 NSMutableDictionary *globalPrefs;
262                 [df synchronize];
263                 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
264                 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
265                 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
266                 [df synchronize];
267                 [globalPrefs release];
268             }
269         }
270         
271         if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
272             blinged = YES;
273             [statusItem setEnabled:NO];
274             [self clearHotKeys];
275             if ([refreshTimer isValid]) {
276                 [refreshTimer invalidate];
277             }
278             [statusWindowController showRegistrationQueryWindow];
279         }
280     } else {
281         if (blinged) {
282             [statusItem setEnabled:YES];
283             [self setupHotKeys];
284             if (![refreshTimer isValid]) {
285                 [refreshTimer release];
286                 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
287                              target:self
288                              selector:@selector(timerUpdate)
289                              userInfo:nil
290                              repeats:YES] retain];
291             }
292             blinged = NO;
293         }
294         [self setBlingTime:nil];
295     }
296 }
297
298 - (void)blingNow
299 {
300     [bling showPanel];
301 }
302
303 - (BOOL)blingBling
304 {
305     if ( ! ([bling checkDone] == 2475) ) {
306         return NO;
307     } else {
308         return YES;
309     }
310 }
311
312 - (BOOL)songIsPlaying
313 {
314     NSString *identifier = nil;
315     NS_DURING
316         identifier = [[self currentRemote] playerStateUniqueIdentifier];
317     NS_HANDLER
318         [self networkError:localException];
319     NS_ENDHANDLER
320     return ( ! ([identifier isEqualToString:@"0-0"]) );
321 }
322
323 - (BOOL)radioIsPlaying
324 {
325     ITMTRemotePlayerPlaylistClass class = nil;
326     NS_DURING
327         class = [[self currentRemote] currentPlaylistClass];
328     NS_HANDLER
329         [self networkError:localException];
330     NS_ENDHANDLER
331     return (class  == ITMTRemotePlayerRadioPlaylist );
332 }
333
334 - (BOOL)songChanged
335 {
336     NSString *identifier = nil;
337     NS_DURING
338         identifier = [[self currentRemote] playerStateUniqueIdentifier];
339     NS_HANDLER
340         [self networkError:localException];
341     NS_ENDHANDLER
342     return ( ! [identifier isEqualToString:_latestSongIdentifier] );
343 }
344
345 - (NSString *)latestSongIdentifier
346 {
347     return _latestSongIdentifier;
348 }
349
350 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
351 {
352     ITDebugLog(@"Setting latest song identifier:");
353     ITDebugLog(@"   - Identifier: %@", newIdentifier);
354     [_latestSongIdentifier autorelease];
355     _latestSongIdentifier = [newIdentifier retain];
356 }
357
358 - (void)timerUpdate
359 {
360     if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
361         ITDebugLog(@"The song changed.");
362         
363         if ([df boolForKey:@"runScripts"]) {
364             NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
365             NSEnumerator *scriptsEnum = [scripts objectEnumerator];
366             NSString *nextScript;
367             ITDebugLog(@"Running AppleScripts for song change.");
368             while ( (nextScript = [scriptsEnum nextObject]) ) {
369                 NSDictionary *error;
370                 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
371                 ITDebugLog(@"Running script: %@", nextScript);
372                 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
373                     ITDebugLog(@"Error running script %@.", nextScript);
374                 }
375                 [currentScript release];
376             }
377         }
378         
379         timerUpdating = YES;
380         [statusItem setEnabled:NO];
381         
382         NS_DURING
383             latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
384             [menuController rebuildSubmenus];
385     
386             if ( [df boolForKey:@"showSongInfoOnChange"] ) {
387                 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
388             }
389             
390             [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
391             
392             //Create the tooltip for the status item
393             if ( [df boolForKey:@"showToolTip"] ) {
394                 NSString *artist = [[self currentRemote] currentSongArtist];
395                 NSString *title = [[self currentRemote] currentSongTitle];
396                 NSString *toolTip;
397                 ITDebugLog(@"Creating status item tooltip.");
398                 if (artist) {
399                     toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
400                 } else if (title) {
401                     toolTip = title;
402                 } else {
403                     toolTip = @"No Song Playing";
404                 }
405                 [statusItem setToolTip:toolTip];
406             } else {
407                 [statusItem setToolTip:nil];
408             }
409         NS_HANDLER
410             [self networkError:localException];
411         NS_ENDHANDLER
412         
413         timerUpdating = NO;
414         [statusItem setEnabled:YES];
415     }
416     
417     if ([networkController isConnectedToServer]) {
418         [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
419     }
420 }
421
422 - (void)menuClicked
423 {
424     ITDebugLog(@"Menu clicked.");
425     if ([networkController isConnectedToServer]) {
426         //Used the cached version
427         return;
428     }
429     
430     NS_DURING
431         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
432             [statusItem setMenu:[menuController menu]];
433         } else {
434             [statusItem setMenu:[menuController menuForNoPlayer]];
435         }
436     NS_HANDLER
437         [self networkError:localException];
438     NS_ENDHANDLER
439 }
440
441 //
442 //
443 // Menu Selectors
444 //
445 //
446
447 - (void)playPause
448 {
449     NS_DURING
450         ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
451         ITDebugLog(@"Play/Pause toggled");
452         if (state == ITMTRemotePlayerPlaying) {
453             [[self currentRemote] pause];
454         } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
455             [[self currentRemote] pause];
456             [[self currentRemote] play];
457         } else {
458             [[self currentRemote] play];
459         }
460     NS_HANDLER
461         [self networkError:localException];
462     NS_ENDHANDLER
463     
464     [self timerUpdate];
465 }
466
467 - (void)nextSong
468 {
469     ITDebugLog(@"Going to next song.");
470     NS_DURING
471         [[self currentRemote] goToNextSong];
472     NS_HANDLER
473         [self networkError:localException];
474     NS_ENDHANDLER
475     [self timerUpdate];
476 }
477
478 - (void)prevSong
479 {
480     ITDebugLog(@"Going to previous song.");
481     NS_DURING
482         [[self currentRemote] goToPreviousSong];
483     NS_HANDLER
484         [self networkError:localException];
485     NS_ENDHANDLER
486     [self timerUpdate];
487 }
488
489 - (void)fastForward
490 {
491     ITDebugLog(@"Fast forwarding.");
492     NS_DURING
493         [[self currentRemote] forward];
494     NS_HANDLER
495         [self networkError:localException];
496     NS_ENDHANDLER
497     [self timerUpdate];
498 }
499
500 - (void)rewind
501 {
502     ITDebugLog(@"Rewinding.");
503     NS_DURING
504         [[self currentRemote] rewind];
505     NS_HANDLER
506         [self networkError:localException];
507     NS_ENDHANDLER
508     [self timerUpdate];
509 }
510
511 - (void)selectPlaylistAtIndex:(int)index
512 {
513     ITDebugLog(@"Selecting playlist %i", index);
514     NS_DURING
515         [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
516         //[[self currentRemote] switchToPlaylistAtIndex:index];
517     NS_HANDLER
518         [self networkError:localException];
519     NS_ENDHANDLER
520     [self timerUpdate];
521 }
522
523 - (void)selectSongAtIndex:(int)index
524 {
525     ITDebugLog(@"Selecting song %i", index);
526     NS_DURING
527         [[self currentRemote] switchToSongAtIndex:index];
528     NS_HANDLER
529         [self networkError:localException];
530     NS_ENDHANDLER
531     [self timerUpdate];
532 }
533
534 - (void)selectSongRating:(int)rating
535 {
536     ITDebugLog(@"Selecting song rating %i", rating);
537     NS_DURING
538         [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
539     NS_HANDLER
540         [self networkError:localException];
541     NS_ENDHANDLER
542     [self timerUpdate];
543 }
544
545 - (void)selectEQPresetAtIndex:(int)index
546 {
547     ITDebugLog(@"Selecting EQ preset %i", index);
548     NS_DURING
549         if (index == -1) {
550             [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
551         } else {
552             [[self currentRemote] switchToEQAtIndex:index];
553         }
554     NS_HANDLER
555         [self networkError:localException];
556     NS_ENDHANDLER
557     [self timerUpdate];
558 }
559
560 - (void)showPlayer
561 {
562     ITDebugLog(@"Beginning show player.");
563     //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
564         ITDebugLog(@"Showing player interface.");
565         NS_DURING
566             [[self currentRemote] showPrimaryInterface];
567         NS_HANDLER
568             [self networkError:localException];
569         NS_ENDHANDLER
570     /*} else {
571         ITDebugLog(@"Launching player.");
572         NS_DURING
573             NSString *path;
574             if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
575             } else {
576                 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
577             }
578             if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
579                 ITDebugLog(@"Error Launching Player");
580             }
581         NS_HANDLER
582             [self networkError:localException];
583         NS_ENDHANDLER
584     }*/
585     ITDebugLog(@"Finished show player.");
586 }
587
588 - (void)showPreferences
589 {
590     ITDebugLog(@"Show preferences.");
591     [[PreferencesController sharedPrefs] showPrefsWindow:self];
592 }
593
594 - (void)showPreferencesAndClose
595 {
596     ITDebugLog(@"Show preferences.");
597     [[PreferencesController sharedPrefs] showPrefsWindow:self];
598     [[StatusWindow sharedWindow] setLocked:NO];
599     [[StatusWindow sharedWindow] vanish:self];
600     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
601 }
602
603 - (void)showTestWindow
604 {
605     [self showCurrentTrackInfo];
606 }
607
608 - (void)quitMenuTunes
609 {
610     ITDebugLog(@"Quitting MenuTunes.");
611     [NSApp terminate:self];
612 }
613
614 //
615 //
616
617 - (MenuController *)menuController
618 {
619     return menuController;
620 }
621
622 - (void)closePreferences
623 {
624     ITDebugLog(@"Preferences closed.");
625     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
626         [self setupHotKeys];
627     }
628 }
629
630 - (ITMTRemote *)currentRemote
631 {
632     if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
633         [self networkError:nil];
634         return nil;
635     }
636     return currentRemote;
637 }
638
639 //
640 //
641 // Hot key setup
642 //
643 //
644
645 - (void)clearHotKeys
646 {
647     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
648     ITHotKey *nextHotKey;
649     ITDebugLog(@"Clearing hot keys.");
650     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
651         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
652     }
653     ITDebugLog(@"Done clearing hot keys.");
654 }
655
656 - (void)setupHotKeys
657 {
658     ITHotKey *hotKey;
659     ITDebugLog(@"Setting up hot keys.");
660     
661     if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
662         return;
663     }
664     
665     if ([df objectForKey:@"PlayPause"] != nil) {
666         ITDebugLog(@"Setting up play pause hot key.");
667         hotKey = [[ITHotKey alloc] init];
668         [hotKey setName:@"PlayPause"];
669         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
670         [hotKey setTarget:self];
671         [hotKey setAction:@selector(playPause)];
672         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
673     }
674     
675     if ([df objectForKey:@"NextTrack"] != nil) {
676         ITDebugLog(@"Setting up next track hot key.");
677         hotKey = [[ITHotKey alloc] init];
678         [hotKey setName:@"NextTrack"];
679         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
680         [hotKey setTarget:self];
681         [hotKey setAction:@selector(nextSong)];
682         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
683     }
684     
685     if ([df objectForKey:@"PrevTrack"] != nil) {
686         ITDebugLog(@"Setting up previous track hot key.");
687         hotKey = [[ITHotKey alloc] init];
688         [hotKey setName:@"PrevTrack"];
689         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
690         [hotKey setTarget:self];
691         [hotKey setAction:@selector(prevSong)];
692         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
693     }
694     
695     if ([df objectForKey:@"FastForward"] != nil) {
696         ITDebugLog(@"Setting up fast forward hot key.");
697         hotKey = [[ITHotKey alloc] init];
698         [hotKey setName:@"FastForward"];
699         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
700         [hotKey setTarget:self];
701         [hotKey setAction:@selector(fastForward)];
702         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
703     }
704     
705     if ([df objectForKey:@"Rewind"] != nil) {
706         ITDebugLog(@"Setting up rewind hot key.");
707         hotKey = [[ITHotKey alloc] init];
708         [hotKey setName:@"Rewind"];
709         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
710         [hotKey setTarget:self];
711         [hotKey setAction:@selector(rewind)];
712         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
713     }
714     
715     if ([df objectForKey:@"ShowPlayer"] != nil) {
716         ITDebugLog(@"Setting up show player hot key.");
717         hotKey = [[ITHotKey alloc] init];
718         [hotKey setName:@"ShowPlayer"];
719         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
720         [hotKey setTarget:self];
721         [hotKey setAction:@selector(showPlayer)];
722         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
723     }
724     
725     if ([df objectForKey:@"TrackInfo"] != nil) {
726         ITDebugLog(@"Setting up track info hot key.");
727         hotKey = [[ITHotKey alloc] init];
728         [hotKey setName:@"TrackInfo"];
729         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
730         [hotKey setTarget:self];
731         [hotKey setAction:@selector(showCurrentTrackInfo)];
732         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
733     }
734     
735     if ([df objectForKey:@"UpcomingSongs"] != nil) {
736         ITDebugLog(@"Setting up upcoming songs hot key.");
737         hotKey = [[ITHotKey alloc] init];
738         [hotKey setName:@"UpcomingSongs"];
739         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
740         [hotKey setTarget:self];
741         [hotKey setAction:@selector(showUpcomingSongs)];
742         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
743     }
744     
745     if ([df objectForKey:@"ToggleLoop"] != nil) {
746         ITDebugLog(@"Setting up toggle loop hot key.");
747         hotKey = [[ITHotKey alloc] init];
748         [hotKey setName:@"ToggleLoop"];
749         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
750         [hotKey setTarget:self];
751         [hotKey setAction:@selector(toggleLoop)];
752         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
753     }
754     
755     if ([df objectForKey:@"ToggleShuffle"] != nil) {
756         ITDebugLog(@"Setting up toggle shuffle hot key.");
757         hotKey = [[ITHotKey alloc] init];
758         [hotKey setName:@"ToggleShuffle"];
759         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
760         [hotKey setTarget:self];
761         [hotKey setAction:@selector(toggleShuffle)];
762         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
763     }
764     
765     if ([df objectForKey:@"IncrementVolume"] != nil) {
766         ITDebugLog(@"Setting up increment volume hot key.");
767         hotKey = [[ITHotKey alloc] init];
768         [hotKey setName:@"IncrementVolume"];
769         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
770         [hotKey setTarget:self];
771         [hotKey setAction:@selector(incrementVolume)];
772         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
773     }
774     
775     if ([df objectForKey:@"DecrementVolume"] != nil) {
776         ITDebugLog(@"Setting up decrement volume hot key.");
777         hotKey = [[ITHotKey alloc] init];
778         [hotKey setName:@"DecrementVolume"];
779         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
780         [hotKey setTarget:self];
781         [hotKey setAction:@selector(decrementVolume)];
782         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
783     }
784     
785     if ([df objectForKey:@"IncrementRating"] != nil) {
786         ITDebugLog(@"Setting up increment rating hot key.");
787         hotKey = [[ITHotKey alloc] init];
788         [hotKey setName:@"IncrementRating"];
789         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
790         [hotKey setTarget:self];
791         [hotKey setAction:@selector(incrementRating)];
792         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
793     }
794     
795     if ([df objectForKey:@"DecrementRating"] != nil) {
796         ITDebugLog(@"Setting up decrement rating hot key.");
797         hotKey = [[ITHotKey alloc] init];
798         [hotKey setName:@"DecrementRating"];
799         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
800         [hotKey setTarget:self];
801         [hotKey setAction:@selector(decrementRating)];
802         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
803     }
804     
805     if ([df objectForKey:@"PopupMenu"] != nil) {
806         ITDebugLog(@"Setting up popup menu hot key.");
807         hotKey = [[ITHotKey alloc] init];
808         [hotKey setName:@"PopupMenu"];
809         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
810         [hotKey setTarget:self];
811         [hotKey setAction:@selector(popupMenu)];
812         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
813     }
814     
815     int i;
816     for (i = 0; i <= 5; i++) {
817         NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
818         if ([df objectForKey:curName] != nil) {
819             ITDebugLog(@"Setting up set rating %i hot key.", i);
820             hotKey = [[ITHotKey alloc] init];
821             [hotKey setName:curName];
822             [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
823             [hotKey setTarget:self];
824             [hotKey setAction:@selector(setRating:)];
825             [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
826         }
827     }
828     ITDebugLog(@"Finished setting up hot keys.");
829 }
830
831 - (void)showCurrentTrackInfo
832 {
833     ITMTRemotePlayerSource  source      = 0;
834     NSString               *title       = nil;
835     NSString               *album       = nil;
836     NSString               *artist      = nil;
837     NSString               *composer    = nil;
838     NSString               *time        = nil;
839     NSString               *track       = nil;
840     NSImage                *art         = nil;
841     int                     rating      = -1;
842     int                     playCount   = -1;
843     
844     ITDebugLog(@"Showing track info status window.");
845     
846     NS_DURING
847         source      = [[self currentRemote] currentSource];
848         title       = [[self currentRemote] currentSongTitle];
849     NS_HANDLER
850         [self networkError:localException];
851     NS_ENDHANDLER
852     
853     if ( title ) {
854         if ( [df boolForKey:@"showAlbumArtwork"] ) {
855             NSSize oldSize, newSize;
856              NS_DURING
857                  art = [[self currentRemote] currentSongAlbumArt];
858                  oldSize = [art size];
859                  if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
860                  else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
861                 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
862             NS_HANDLER
863                 [self networkError:localException];
864             NS_ENDHANDLER
865         }
866         
867         if ( [df boolForKey:@"showAlbum"] ) {
868             NS_DURING
869                 album = [[self currentRemote] currentSongAlbum];
870             NS_HANDLER
871                 [self networkError:localException];
872             NS_ENDHANDLER
873         }
874
875         if ( [df boolForKey:@"showArtist"] ) {
876             NS_DURING
877                 artist = [[self currentRemote] currentSongArtist];
878             NS_HANDLER
879                 [self networkError:localException];
880             NS_ENDHANDLER
881         }
882
883         if ( [df boolForKey:@"showComposer"] ) {
884             NS_DURING
885                 composer = [[self currentRemote] currentSongComposer];
886             NS_HANDLER
887                 [self networkError:localException];
888             NS_ENDHANDLER
889         }
890
891         if ( [df boolForKey:@"showTime"] ) {
892             NS_DURING
893                 time = [NSString stringWithFormat:@"%@: %@ / %@",
894                 @"Time",
895                 [[self currentRemote] currentSongElapsed],
896                 [[self currentRemote] currentSongLength]];
897             NS_HANDLER
898                 [self networkError:localException];
899             NS_ENDHANDLER
900         }
901
902         if ( [df boolForKey:@"showTrackNumber"] ) {
903             int trackNo    = 0;
904             int trackCount = 0;
905             
906             NS_DURING
907                 trackNo    = [[self currentRemote] currentSongTrack];
908                 trackCount = [[self currentRemote] currentAlbumTrackCount];
909             NS_HANDLER
910                 [self networkError:localException];
911             NS_ENDHANDLER
912             
913             if ( (trackNo > 0) || (trackCount > 0) ) {
914                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
915                     @"Track", trackNo, @"of", trackCount];
916             }
917         }
918
919         if ( [df boolForKey:@"showTrackRating"] ) {
920             float currentRating = 0;
921             
922             NS_DURING
923                 currentRating = [[self currentRemote] currentSongRating];
924             NS_HANDLER
925                 [self networkError:localException];
926             NS_ENDHANDLER
927             
928             if (currentRating >= 0.0) {
929                 rating = ( currentRating * 5 );
930             }
931         }
932         
933         if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] ) {
934             NS_DURING
935                 playCount = [[self currentRemote] currentSongPlayCount];
936             NS_HANDLER
937                 [self networkError:localException];
938             NS_ENDHANDLER
939         }
940     } else {
941         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
942     }
943     ITDebugLog(@"Showing current track info status window.");
944     [statusWindowController showSongInfoWindowWithSource:source
945                                                    title:title
946                                                    album:album
947                                                   artist:artist
948                                                 composer:composer
949                                                     time:time
950                                                    track:track
951                                                   rating:rating
952                                                playCount:playCount
953                                                    image:art];
954 }
955
956 - (void)showUpcomingSongs
957 {
958     int numSongs = 0;
959     NS_DURING
960         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
961     NS_HANDLER
962         [self networkError:localException];
963     NS_ENDHANDLER
964     
965     ITDebugLog(@"Showing upcoming songs status window.");
966     NS_DURING
967         if (numSongs > 0) {
968             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
969             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
970             int curTrack = [[self currentRemote] currentSongIndex];
971             int i;
972     
973             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
974                 if (i <= numSongs) {
975                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
976                 }
977             }
978             
979             if ([songList count] == 0) {
980                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
981             }
982             
983             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
984         } else {
985             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
986         }
987     NS_HANDLER
988         [self networkError:localException];
989     NS_ENDHANDLER
990 }
991
992 - (void)popupMenu
993 {
994     if (!_popped) {
995         NSMenu *menu = [menuController menu];
996         _popped = YES;
997         [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
998         _popped = NO;
999     }
1000 }
1001
1002 - (void)incrementVolume
1003 {
1004     NS_DURING
1005         float volume  = [[self currentRemote] volume];
1006         float dispVol = volume;
1007         ITDebugLog(@"Incrementing volume.");
1008         volume  += 0.110;
1009         dispVol += 0.100;
1010         
1011         if (volume > 1.0) {
1012             volume  = 1.0;
1013             dispVol = 1.0;
1014         }
1015     
1016         ITDebugLog(@"Setting volume to %f", volume);
1017         [[self currentRemote] setVolume:volume];
1018     
1019         // Show volume status window
1020         [statusWindowController showVolumeWindowWithLevel:dispVol];
1021     NS_HANDLER
1022         [self networkError:localException];
1023     NS_ENDHANDLER
1024 }
1025
1026 - (void)decrementVolume
1027 {
1028     NS_DURING
1029         float volume  = [[self currentRemote] volume];
1030         float dispVol = volume;
1031         ITDebugLog(@"Decrementing volume.");
1032         volume  -= 0.090;
1033         dispVol -= 0.100;
1034     
1035         if (volume < 0.0) {
1036             volume  = 0.0;
1037             dispVol = 0.0;
1038         }
1039         
1040         ITDebugLog(@"Setting volume to %f", volume);
1041         [[self currentRemote] setVolume:volume];
1042         
1043         //Show volume status window
1044         [statusWindowController showVolumeWindowWithLevel:dispVol];
1045     NS_HANDLER
1046         [self networkError:localException];
1047     NS_ENDHANDLER
1048 }
1049
1050 - (void)incrementRating
1051 {
1052     NS_DURING
1053         float rating = [[self currentRemote] currentSongRating];
1054         ITDebugLog(@"Incrementing rating.");
1055         
1056         if ([[self currentRemote] currentPlaylistIndex] == 0) {
1057             ITDebugLog(@"No song playing, rating change aborted.");
1058             return;
1059         }
1060         
1061         rating += 0.2;
1062         if (rating > 1.0) {
1063             rating = 1.0;
1064         }
1065         ITDebugLog(@"Setting rating to %f", rating);
1066         [[self currentRemote] setCurrentSongRating:rating];
1067         
1068         //Show rating status window
1069         [statusWindowController showRatingWindowWithRating:rating];
1070     NS_HANDLER
1071         [self networkError:localException];
1072     NS_ENDHANDLER
1073 }
1074
1075 - (void)decrementRating
1076 {
1077     NS_DURING
1078         float rating = [[self currentRemote] currentSongRating];
1079         ITDebugLog(@"Decrementing rating.");
1080         
1081         if ([[self currentRemote] currentPlaylistIndex] == 0) {
1082             ITDebugLog(@"No song playing, rating change aborted.");
1083             return;
1084         }
1085         
1086         rating -= 0.2;
1087         if (rating < 0.0) {
1088             rating = 0.0;
1089         }
1090         ITDebugLog(@"Setting rating to %f", rating);
1091         [[self currentRemote] setCurrentSongRating:rating];
1092         
1093         //Show rating status window
1094         [statusWindowController showRatingWindowWithRating:rating];
1095     NS_HANDLER
1096         [self networkError:localException];
1097     NS_ENDHANDLER
1098 }
1099
1100 - (void)setRating:(ITHotKey *)sender
1101 {
1102     int stars = [[sender name] characterAtIndex:9] - 48;
1103     [self selectSongRating:stars * 20];
1104     [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1105 }
1106
1107 - (void)toggleLoop
1108 {
1109     NS_DURING
1110         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1111         ITDebugLog(@"Toggling repeat mode.");
1112         switch (repeatMode) {
1113             case ITMTRemotePlayerRepeatOff:
1114                 repeatMode = ITMTRemotePlayerRepeatAll;
1115             break;
1116             case ITMTRemotePlayerRepeatAll:
1117                 repeatMode = ITMTRemotePlayerRepeatOne;
1118             break;
1119             case ITMTRemotePlayerRepeatOne:
1120                 repeatMode = ITMTRemotePlayerRepeatOff;
1121             break;
1122         }
1123         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1124         [[self currentRemote] setRepeatMode:repeatMode];
1125         
1126         //Show loop status window
1127         [statusWindowController showRepeatWindowWithMode:repeatMode];
1128     NS_HANDLER
1129         [self networkError:localException];
1130     NS_ENDHANDLER
1131 }
1132
1133 - (void)toggleShuffle
1134 {
1135     NS_DURING
1136         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1137         ITDebugLog(@"Toggling shuffle mode.");
1138         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1139         //Show shuffle status window
1140         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1141         [statusWindowController showShuffleWindow:newShuffleEnabled];
1142     NS_HANDLER
1143         [self networkError:localException];
1144     NS_ENDHANDLER
1145 }
1146
1147 - (void)registerNowOK
1148 {
1149     [[StatusWindow sharedWindow] setLocked:NO];
1150     [[StatusWindow sharedWindow] vanish:self];
1151     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1152
1153     [self blingNow];
1154 }
1155
1156 - (void)registerNowCancel
1157 {
1158     [[StatusWindow sharedWindow] setLocked:NO];
1159     [[StatusWindow sharedWindow] vanish:self];
1160     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1161
1162     [NSApp terminate:self];
1163 }
1164
1165 /*************************************************************************/
1166 #pragma mark -
1167 #pragma mark NETWORK HANDLERS
1168 /*************************************************************************/
1169
1170 - (void)setServerStatus:(BOOL)newStatus
1171 {
1172     if (newStatus) {
1173         //Turn on
1174         [networkController setServerStatus:YES];
1175     } else {
1176         //Tear down
1177         [networkController setServerStatus:NO];
1178     }
1179 }
1180
1181 - (int)connectToServer
1182 {
1183     int result;
1184     ITDebugLog(@"Attempting to connect to shared remote.");
1185     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1186     //Connect
1187     if (result == 1) {
1188         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1189         currentRemote = [[[networkController networkObject] remote] retain];
1190         
1191         [self setupHotKeys];
1192         //playerRunningState = ITMTRemotePlayerRunning;
1193         playerRunningState = [[self currentRemote] playerRunningState];
1194         
1195         [refreshTimer invalidate];
1196         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1197                                 target:self
1198                                 selector:@selector(timerUpdate)
1199                                 userInfo:nil
1200                                 repeats:YES] retain];
1201         [self timerUpdate];
1202         ITDebugLog(@"Connection successful.");
1203         return 1;
1204     } else if (result == 0) {
1205         ITDebugLog(@"Connection failed.");
1206         currentRemote = [remoteArray objectAtIndex:0];
1207         return 0;
1208     } else {
1209         //Do something about the password being invalid
1210         ITDebugLog(@"Connection failed.");
1211         currentRemote = [remoteArray objectAtIndex:0];
1212         return -1;
1213     }
1214 }
1215
1216 - (BOOL)disconnectFromServer
1217 {
1218     ITDebugLog(@"Disconnecting from shared remote.");
1219     //Disconnect
1220     [currentRemote release];
1221     currentRemote = [remoteArray objectAtIndex:0];
1222     [networkController disconnect];
1223     
1224     if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1225         [self applicationLaunched:nil];
1226     } else {
1227         [self applicationTerminated:nil];
1228     }
1229     [self timerUpdate];
1230     return YES;
1231 }
1232
1233 - (void)checkForRemoteServer
1234 {
1235     [self checkForRemoteServerAndConnectImmediately:NO];
1236 }
1237
1238 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1239 {
1240     ITDebugLog(@"Checking for remote server.");
1241     if (!_checkingForServer) {
1242         if (!_serverCheckLock) {
1243             _serverCheckLock = [[NSLock alloc] init];
1244         }
1245         [_serverCheckLock lock];
1246         _checkingForServer = YES;
1247         [_serverCheckLock unlock];
1248         [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1249     }
1250 }
1251
1252 - (void)runRemoteServerCheck:(id)sender
1253 {
1254     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1255     ITDebugLog(@"Remote server check running.");
1256     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1257         ITDebugLog(@"Remote server found.");
1258         if ([sender boolValue]) {
1259             [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1260         } else {
1261             [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1262         }
1263     } else {
1264         ITDebugLog(@"Remote server not found.");
1265         [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1266     }
1267     [_serverCheckLock lock];
1268     _checkingForServer = NO;
1269     [_serverCheckLock unlock];
1270     [pool release];
1271 }
1272
1273 - (void)remoteServerFound:(id)sender
1274 {
1275     if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1276         [[StatusWindowController sharedController] showReconnectQueryWindow];
1277     }
1278 }
1279
1280 - (void)remoteServerNotFound:(id)sender
1281 {
1282     if (![[NetworkController sharedController] isConnectedToServer]) {
1283         [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1284     }
1285 }
1286
1287 - (void)networkError:(NSException *)exception
1288 {
1289     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1290     if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1291         //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);
1292         [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1293         if ([self disconnectFromServer]) {
1294             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1295             [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1296         } else {
1297             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1298         }
1299     }
1300 }
1301
1302 - (void)reconnect
1303 {
1304     /*if ([self connectToServer] == 0) {
1305         [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1306     }*/
1307     [self checkForRemoteServerAndConnectImmediately:YES];
1308     [[StatusWindow sharedWindow] setLocked:NO];
1309     [[StatusWindow sharedWindow] vanish:self];
1310     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1311 }
1312
1313 - (void)cancelReconnect
1314 {
1315     [[StatusWindow sharedWindow] setLocked:NO];
1316     [[StatusWindow sharedWindow] vanish:self];
1317     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1318 }
1319
1320 /*************************************************************************/
1321 #pragma mark -
1322 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1323 /*************************************************************************/
1324
1325 - (void)applicationLaunched:(NSNotification *)note
1326 {
1327     NS_DURING
1328         if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1329             ITDebugLog(@"Remote application launched.");
1330             playerRunningState = ITMTRemotePlayerRunning;
1331             [[self currentRemote] begin];
1332             [self setLatestSongIdentifier:@""];
1333             [self timerUpdate];
1334             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1335                                 target:self
1336                                 selector:@selector(timerUpdate)
1337                                 userInfo:nil
1338                                 repeats:YES] retain];
1339             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1340             [self setupHotKeys];
1341         }
1342     NS_HANDLER
1343         [self networkError:localException];
1344     NS_ENDHANDLER
1345 }
1346
1347  - (void)applicationTerminated:(NSNotification *)note
1348  {
1349     NS_DURING
1350         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1351             ITDebugLog(@"Remote application terminated.");
1352             playerRunningState = ITMTRemotePlayerNotRunning;
1353             [[self currentRemote] halt];
1354             [refreshTimer invalidate];
1355             [refreshTimer release];
1356             refreshTimer = nil;
1357             [self clearHotKeys];
1358             
1359             if ([df objectForKey:@"ShowPlayer"] != nil) {
1360                 ITHotKey *hotKey;
1361                 ITDebugLog(@"Setting up show player hot key.");
1362                 hotKey = [[ITHotKey alloc] init];
1363                 [hotKey setName:@"ShowPlayer"];
1364                 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1365                 [hotKey setTarget:self];
1366                 [hotKey setAction:@selector(showPlayer)];
1367                 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1368             }
1369         }
1370     NS_HANDLER
1371         [self networkError:localException];
1372     NS_ENDHANDLER
1373  }
1374
1375
1376 /*************************************************************************/
1377 #pragma mark -
1378 #pragma mark NSApplication DELEGATE METHODS
1379 /*************************************************************************/
1380
1381 - (void)applicationWillTerminate:(NSNotification *)note
1382 {
1383     [networkController stopRemoteServerSearch];
1384     [self clearHotKeys];
1385     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1386 }
1387
1388
1389 /*************************************************************************/
1390 #pragma mark -
1391 #pragma mark DEALLOCATION METHOD
1392 /*************************************************************************/
1393
1394 - (void)dealloc
1395 {
1396     [self applicationTerminated:nil];
1397     [bling release];
1398     [statusItem release];
1399     [statusWindowController release];
1400     [menuController release];
1401     [networkController release];
1402     [_serverCheckLock release];
1403     [super dealloc];
1404 }
1405
1406 @end