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