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