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