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