Added hotkeys for setting individual song ratings 0-5 stars.
[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"] ) {
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     NSMenu *menu = [menuController menu];
995     [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
996 }
997
998 - (void)incrementVolume
999 {
1000     NS_DURING
1001         float volume  = [[self currentRemote] volume];
1002         float dispVol = volume;
1003         ITDebugLog(@"Incrementing volume.");
1004         volume  += 0.110;
1005         dispVol += 0.100;
1006         
1007         if (volume > 1.0) {
1008             volume  = 1.0;
1009             dispVol = 1.0;
1010         }
1011     
1012         ITDebugLog(@"Setting volume to %f", volume);
1013         [[self currentRemote] setVolume:volume];
1014     
1015         // Show volume status window
1016         [statusWindowController showVolumeWindowWithLevel:dispVol];
1017     NS_HANDLER
1018         [self networkError:localException];
1019     NS_ENDHANDLER
1020 }
1021
1022 - (void)decrementVolume
1023 {
1024     NS_DURING
1025         float volume  = [[self currentRemote] volume];
1026         float dispVol = volume;
1027         ITDebugLog(@"Decrementing volume.");
1028         volume  -= 0.090;
1029         dispVol -= 0.100;
1030     
1031         if (volume < 0.0) {
1032             volume  = 0.0;
1033             dispVol = 0.0;
1034         }
1035         
1036         ITDebugLog(@"Setting volume to %f", volume);
1037         [[self currentRemote] setVolume:volume];
1038         
1039         //Show volume status window
1040         [statusWindowController showVolumeWindowWithLevel:dispVol];
1041     NS_HANDLER
1042         [self networkError:localException];
1043     NS_ENDHANDLER
1044 }
1045
1046 - (void)incrementRating
1047 {
1048     NS_DURING
1049         float rating = [[self currentRemote] currentSongRating];
1050         ITDebugLog(@"Incrementing rating.");
1051         
1052         if ([[self currentRemote] currentPlaylistIndex] == 0) {
1053             ITDebugLog(@"No song playing, rating change aborted.");
1054             return;
1055         }
1056         
1057         rating += 0.2;
1058         if (rating > 1.0) {
1059             rating = 1.0;
1060         }
1061         ITDebugLog(@"Setting rating to %f", rating);
1062         [[self currentRemote] setCurrentSongRating:rating];
1063         
1064         //Show rating status window
1065         [statusWindowController showRatingWindowWithRating:rating];
1066     NS_HANDLER
1067         [self networkError:localException];
1068     NS_ENDHANDLER
1069 }
1070
1071 - (void)decrementRating
1072 {
1073     NS_DURING
1074         float rating = [[self currentRemote] currentSongRating];
1075         ITDebugLog(@"Decrementing rating.");
1076         
1077         if ([[self currentRemote] currentPlaylistIndex] == 0) {
1078             ITDebugLog(@"No song playing, rating change aborted.");
1079             return;
1080         }
1081         
1082         rating -= 0.2;
1083         if (rating < 0.0) {
1084             rating = 0.0;
1085         }
1086         ITDebugLog(@"Setting rating to %f", rating);
1087         [[self currentRemote] setCurrentSongRating:rating];
1088         
1089         //Show rating status window
1090         [statusWindowController showRatingWindowWithRating:rating];
1091     NS_HANDLER
1092         [self networkError:localException];
1093     NS_ENDHANDLER
1094 }
1095
1096 - (void)setRating:(ITHotKey *)sender
1097 {
1098     float rating = ([[sender name] characterAtIndex:9] - 48) / 5.0;
1099     [self selectSongRating:rating];
1100     [statusWindowController showRatingWindowWithRating:rating];
1101 }
1102
1103 - (void)toggleLoop
1104 {
1105     NS_DURING
1106         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1107         ITDebugLog(@"Toggling repeat mode.");
1108         switch (repeatMode) {
1109             case ITMTRemotePlayerRepeatOff:
1110                 repeatMode = ITMTRemotePlayerRepeatAll;
1111             break;
1112             case ITMTRemotePlayerRepeatAll:
1113                 repeatMode = ITMTRemotePlayerRepeatOne;
1114             break;
1115             case ITMTRemotePlayerRepeatOne:
1116                 repeatMode = ITMTRemotePlayerRepeatOff;
1117             break;
1118         }
1119         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1120         [[self currentRemote] setRepeatMode:repeatMode];
1121         
1122         //Show loop status window
1123         [statusWindowController showRepeatWindowWithMode:repeatMode];
1124     NS_HANDLER
1125         [self networkError:localException];
1126     NS_ENDHANDLER
1127 }
1128
1129 - (void)toggleShuffle
1130 {
1131     NS_DURING
1132         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1133         ITDebugLog(@"Toggling shuffle mode.");
1134         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1135         //Show shuffle status window
1136         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1137         [statusWindowController showShuffleWindow:newShuffleEnabled];
1138     NS_HANDLER
1139         [self networkError:localException];
1140     NS_ENDHANDLER
1141 }
1142
1143 - (void)registerNowOK
1144 {
1145     [[StatusWindow sharedWindow] setLocked:NO];
1146     [[StatusWindow sharedWindow] vanish:self];
1147     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1148
1149     [self blingNow];
1150 }
1151
1152 - (void)registerNowCancel
1153 {
1154     [[StatusWindow sharedWindow] setLocked:NO];
1155     [[StatusWindow sharedWindow] vanish:self];
1156     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1157
1158     [NSApp terminate:self];
1159 }
1160
1161 /*************************************************************************/
1162 #pragma mark -
1163 #pragma mark NETWORK HANDLERS
1164 /*************************************************************************/
1165
1166 - (void)setServerStatus:(BOOL)newStatus
1167 {
1168     if (newStatus) {
1169         //Turn on
1170         [networkController setServerStatus:YES];
1171     } else {
1172         //Tear down
1173         [networkController setServerStatus:NO];
1174     }
1175 }
1176
1177 - (int)connectToServer
1178 {
1179     int result;
1180     ITDebugLog(@"Attempting to connect to shared remote.");
1181     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1182     //Connect
1183     if (result == 1) {
1184         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1185         currentRemote = [[[networkController networkObject] remote] retain];
1186         
1187         [self setupHotKeys];
1188         //playerRunningState = ITMTRemotePlayerRunning;
1189         playerRunningState = [[self currentRemote] playerRunningState];
1190         
1191         [refreshTimer invalidate];
1192         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1193                                 target:self
1194                                 selector:@selector(timerUpdate)
1195                                 userInfo:nil
1196                                 repeats:YES] retain];
1197         [self timerUpdate];
1198         ITDebugLog(@"Connection successful.");
1199         return 1;
1200     } else if (result == 0) {
1201         ITDebugLog(@"Connection failed.");
1202         currentRemote = [remoteArray objectAtIndex:0];
1203         return 0;
1204     } else {
1205         //Do something about the password being invalid
1206         ITDebugLog(@"Connection failed.");
1207         currentRemote = [remoteArray objectAtIndex:0];
1208         return -1;
1209     }
1210 }
1211
1212 - (BOOL)disconnectFromServer
1213 {
1214     ITDebugLog(@"Disconnecting from shared remote.");
1215     //Disconnect
1216     [currentRemote release];
1217     currentRemote = [remoteArray objectAtIndex:0];
1218     [networkController disconnect];
1219     
1220     if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1221         [self applicationLaunched:nil];
1222     } else {
1223         [self applicationTerminated:nil];
1224     }
1225     [self timerUpdate];
1226     return YES;
1227 }
1228
1229 - (void)checkForRemoteServer
1230 {
1231     [self checkForRemoteServerAndConnectImmediately:NO];
1232 }
1233
1234 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1235 {
1236     ITDebugLog(@"Checking for remote server.");
1237     if (!_checkingForServer) {
1238         if (!_serverCheckLock) {
1239             _serverCheckLock = [[NSLock alloc] init];
1240         }
1241         [_serverCheckLock lock];
1242         _checkingForServer = YES;
1243         [_serverCheckLock unlock];
1244         [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1245     }
1246 }
1247
1248 - (void)runRemoteServerCheck:(id)sender
1249 {
1250     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1251     ITDebugLog(@"Remote server check running.");
1252     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1253         ITDebugLog(@"Remote server found.");
1254         if ([sender boolValue]) {
1255             [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1256         } else {
1257             [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1258         }
1259     } else {
1260         ITDebugLog(@"Remote server not found.");
1261         [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1262     }
1263     [_serverCheckLock lock];
1264     _checkingForServer = NO;
1265     [_serverCheckLock unlock];
1266     [pool release];
1267 }
1268
1269 - (void)remoteServerFound:(id)sender
1270 {
1271     if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1272         [[StatusWindowController sharedController] showReconnectQueryWindow];
1273     }
1274 }
1275
1276 - (void)remoteServerNotFound:(id)sender
1277 {
1278     if (![[NetworkController sharedController] isConnectedToServer]) {
1279         [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1280     }
1281 }
1282
1283 - (void)networkError:(NSException *)exception
1284 {
1285     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1286     if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1287         //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);
1288         [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1289         if ([self disconnectFromServer]) {
1290             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1291             [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1292         } else {
1293             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1294         }
1295     }
1296 }
1297
1298 - (void)reconnect
1299 {
1300     /*if ([self connectToServer] == 0) {
1301         [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1302     }*/
1303     [self checkForRemoteServerAndConnectImmediately:YES];
1304     [[StatusWindow sharedWindow] setLocked:NO];
1305     [[StatusWindow sharedWindow] vanish:self];
1306     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1307 }
1308
1309 - (void)cancelReconnect
1310 {
1311     [[StatusWindow sharedWindow] setLocked:NO];
1312     [[StatusWindow sharedWindow] vanish:self];
1313     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1314 }
1315
1316 /*************************************************************************/
1317 #pragma mark -
1318 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1319 /*************************************************************************/
1320
1321 - (void)applicationLaunched:(NSNotification *)note
1322 {
1323     NS_DURING
1324         if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1325             ITDebugLog(@"Remote application launched.");
1326             playerRunningState = ITMTRemotePlayerRunning;
1327             [[self currentRemote] begin];
1328             [self setLatestSongIdentifier:@""];
1329             [self timerUpdate];
1330             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1331                                 target:self
1332                                 selector:@selector(timerUpdate)
1333                                 userInfo:nil
1334                                 repeats:YES] retain];
1335             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1336             [self setupHotKeys];
1337         }
1338     NS_HANDLER
1339         [self networkError:localException];
1340     NS_ENDHANDLER
1341 }
1342
1343  - (void)applicationTerminated:(NSNotification *)note
1344  {
1345     NS_DURING
1346         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1347             ITDebugLog(@"Remote application terminated.");
1348             playerRunningState = ITMTRemotePlayerNotRunning;
1349             [[self currentRemote] halt];
1350             [refreshTimer invalidate];
1351             [refreshTimer release];
1352             refreshTimer = nil;
1353             [self clearHotKeys];
1354             
1355             if ([df objectForKey:@"ShowPlayer"] != nil) {
1356                 ITHotKey *hotKey;
1357                 ITDebugLog(@"Setting up show player hot key.");
1358                 hotKey = [[ITHotKey alloc] init];
1359                 [hotKey setName:@"ShowPlayer"];
1360                 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1361                 [hotKey setTarget:self];
1362                 [hotKey setAction:@selector(showPlayer)];
1363                 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1364             }
1365         }
1366     NS_HANDLER
1367         [self networkError:localException];
1368     NS_ENDHANDLER
1369  }
1370
1371
1372 /*************************************************************************/
1373 #pragma mark -
1374 #pragma mark NSApplication DELEGATE METHODS
1375 /*************************************************************************/
1376
1377 - (void)applicationWillTerminate:(NSNotification *)note
1378 {
1379     [networkController stopRemoteServerSearch];
1380     [self clearHotKeys];
1381     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1382 }
1383
1384
1385 /*************************************************************************/
1386 #pragma mark -
1387 #pragma mark DEALLOCATION METHOD
1388 /*************************************************************************/
1389
1390 - (void)dealloc
1391 {
1392     [self applicationTerminated:nil];
1393     [bling release];
1394     [statusItem release];
1395     [statusWindowController release];
1396     [menuController release];
1397     [networkController release];
1398     [_serverCheckLock release];
1399     [super dealloc];
1400 }
1401
1402 @end